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

journal.test.ts

866 lines32.4 KB

1import { describe, expect, it } from 'vitest'
2import {
3 DEFAULT_JOURNAL_DIR,
4 EXIT_SENTINEL_NONCE_KEY,
5 decodeJournalRunId,
6 exitSentinelLine,
7 parseExitSentinel,
8 journalCleanupCommand,
9 journalExistsCommand,
10 journalExitProbeCommand,
11 journalFollowCommand,
12 journalListCommand,
13 journalMtimeListCommand,
14 journalPaths,
15 journalReadCommand,
16 journalStderrReadCommand,
17 journaledCommand,
18 parseJournalExit,
19 parseJournalMtimeListing,
20} from '../src/journal'
21​
22describe('journalPaths', () => {
23 it('derives both files under the default directory from the runId alone', () => {
24 const paths = journalPaths('run-123')
25 expect(paths.dir).toBe(DEFAULT_JOURNAL_DIR)
26 expect(paths.journal).toBe('/tmp/tanstack-runs/run-123.ndjson')
27 expect(paths.stderr).toBe('/tmp/tanstack-runs/run-123.err')
28 })
29​
30 it('is a pure function of the runId, so a successor host derives the same paths', () => {
31 expect(journalPaths('run-123')).toEqual(journalPaths('run-123'))
32 })
33​
34 it('honors an explicit directory without a trailing slash', () => {
35 expect(journalPaths('r', '/var/journals/').journal).toBe(
36 '/var/journals/r.ndjson',
37 )
38 })
39​
40 it('encodes characters that are unsafe in a filename or a shell word', () => {
41 // A client-chosen runId can contain anything. Encoding, not rejecting,
42 // keeps the mapping total AND deterministic across hosts.
43 const paths = journalPaths('a/b c;d')
44 expect(paths.journal).toBe('/tmp/tanstack-runs/a_2fb_20c_3bd.ndjson')
45 })
46​
47 it('rejects an empty runId rather than writing to a bare extension', () => {
48 expect(() => journalPaths('')).toThrow(/runId/)
49 })
50})
51​
52describe('journalPaths — encoding is injective', () => {
53 it('collides two distinct runIds under the OLD scheme; the NEW scheme must not', () => {
54 // Old scheme: `_` was "safe" and passed through literally, while ALSO
55 // being the escape prefix for every unsafe byte. `@` is 0x40, so it
56 // escaped to `_40` — colliding with the literal string `_40`, which under
57 // the old scheme's safe-set (`[A-Za-z0-9._-]`) passed through unchanged.
58 // Both distinct runIds produced the journal `/tmp/tanstack-runs/_40.ndjson`.
59 const fromEscapedByte = journalPaths('@')
60 const fromLiteralUnderscore = journalPaths('_40')
61 expect(fromEscapedByte.journal).not.toBe(fromLiteralUnderscore.journal)
62 // Concretely: `_` is no longer safe, so the literal runId `_40` now
63 // encodes with its underscore escaped too.
64 expect(fromLiteralUnderscore.journal).toBe(
65 '/tmp/tanstack-runs/_5f40.ndjson',
66 )
67 expect(fromEscapedByte.journal).toBe('/tmp/tanstack-runs/_40.ndjson')
68 })
69​
70 it('is injective over a set of adversarial runIds', () => {
71 const adversarial = [
72 '_',
73 '_40',
74 '@',
75 '/',
76 '\\',
77 '..',
78 '.',
79 '.hidden',
80 ' leading-space',
81 'trailing-space ',
82 'a b',
83 'ünïcödé',
84 '日本語',
85 '',
86 'a'.repeat(10_000),
87 'CON',
88 'con',
89 'NUL',
90 'COM1',
91 'lpt9',
92 'CONtainer',
93 'a_2fb_20c_3bd',
94 'a/b c;d',
95 ].filter((id) => id.length > 0) // empty runId is rejected, not encoded
96​
97 const seen = new Map<string, string>()
98 for (const runId of adversarial) {
99 const { journal } = journalPaths(runId)
100 const prior = seen.get(journal)
101 expect(
102 prior,
103 `runId ${JSON.stringify(runId)} collided with ${JSON.stringify(
104 prior,
105 )} at ${journal}`,
106 ).toBeUndefined()
107 seen.set(journal, runId)
108 }
109 })
110​
111 it('escapes a literal runId that IS a Windows-reserved device name', () => {
112 // `CON.ndjson` still opens the CON device on Windows rather than
113 // creating a file, even though the encoded token has an extension.
114 const reservedName = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i
115 for (const reserved of [
116 'CON',
117 'con',
118 'PRN',
119 'AUX',
120 'NUL',
121 'COM1',
122 'LPT9',
123 ]) {
124 const { journal } = journalPaths(reserved)
125 const filename = journal.slice(journal.lastIndexOf('/') + 1)
126 const base = filename.slice(0, filename.lastIndexOf('.ndjson'))
127 expect(reservedName.test(base)).toBe(false)
128 }
129 })
130​
131 it('does not flag a runId that merely CONTAINS a reserved word as a substring', () => {
132 // Only an EXACT match is reserved; `CONtainer` is a normal filename on
133 // Windows and must be left alone (no gratuitous escaping).
134 expect(journalPaths('CONtainer').journal).toBe(
135 '/tmp/tanstack-runs/CONtainer.ndjson',
136 )
137 })
138​
139 it('bounds the length of a very long runId while staying injective', () => {
140 const long1 = 'x'.repeat(5000)
141 const long2 = `${'x'.repeat(4999)}y` // differs only in the last character
142 const p1 = journalPaths(long1)
143 const p2 = journalPaths(long2)
144 expect(p1.journal).not.toBe(p2.journal)
145 // The filename component (not the whole path) must stay well under
146 // typical filesystem limits (NTFS/most POSIX: 255).
147 const filename1 = p1.journal.slice(p1.journal.lastIndexOf('/') + 1)
148 expect(filename1.length).toBeLessThan(255)
149 })
150})
151​
152describe('journaledCommand', () => {
153 it('redirects stdout to the journal, stderr to its own file, and appends the exit sentinel', () => {
154 const paths = journalPaths('r1')
155 expect(
156 journaledCommand('claude -p --output-format stream-json', paths),
157 ).toBe(
158 `mkdir -p '/tmp/tanstack-runs' && ` +
159 `{ ( claude -p --output-format stream-json ); ` +
160 `printf '{"__exit":%d,"__nonce":"${paths.nonce}"}\\n' "$?"; } ` +
161 `>> '/tmp/tanstack-runs/r1.ndjson' 2>> '/tmp/tanstack-runs/r1.err'`,
162 )
163 })
164​
165 it('emits a sentinel byte-identical to exitSentinelLine, so a seeded journal matches', () => {
166 // The two producers of the sentinel — this `printf` format and the helper a
167 // fake host / test uses to write one by hand — must agree exactly, including
168 // key ORDER, or a hand-seeded journal reads as unterminated.
169 const paths = journalPaths('r1')
170 const command = journaledCommand('agent', paths)
171 for (const code of [0, 7]) {
172 expect(command).toContain(
173 exitSentinelLine(paths, code).replace(String(code), '%d'),
174 )
175 }
176 expect(exitSentinelLine(paths, 0)).toBe(
177 `{"__exit":0,"__nonce":"${paths.nonce}"}`,
178 )
179 })
180​
181 it('carries a per-run nonce the agent cannot guess from another run', () => {
182 // The forgery this defends against: the agent's stdout and the sentinel land
183 // in the SAME file with no framing, so without a nonce any agent line
184 // containing `__exit` is a valid sentinel.
185 const a = journalPaths('nonce-a')
186 const b = journalPaths('nonce-b')
187 expect(a.nonce).not.toBe(b.nonce)
188 expect(a.nonce).toMatch(/^[0-9a-f]{32}$/)
189 // Derived, not random: a successor host must recompute it from the runId
190 // alone (the reaper probes journals written by a process that is gone).
191 expect(journalPaths('nonce-a').nonce).toBe(a.nonce)
192 // Hex only, so interpolating it into a single-quoted `printf` FORMAT is safe
193 // — no quote to escape and no `%` for printf to interpret.
194 expect(journaledCommand('agent', a)).toContain(`"${a.nonce}"`)
195 })
196​
197 it('appends rather than truncates, so a re-spawn cannot destroy a prior prefix', () => {
198 expect(journaledCommand('x', journalPaths('r1'))).toContain(
199 `>> '/tmp/tanstack-runs/r1.ndjson'`,
200 )
201 expect(journaledCommand('x', journalPaths('r1'))).not.toContain(
202 `> '/tmp/tanstack-runs/r1.ndjson'\n`,
203 )
204 })
205​
206 it('does not pipe the agent into anything (no tee: SIGPIPE would kill it)', () => {
207 expect(journaledCommand('agent', journalPaths('r1'))).not.toContain('|')
208 })
209​
210 it('quotes an adversarial runId so it cannot inject shell metacharacters', () => {
211 const paths = journalPaths(`a'; rm -rf /; echo $(whoami) "b`)
212 const cmd = journaledCommand('agent', paths)
213 // Every interpolated path is single-quoted; embedded single quotes are
214 // escaped with the POSIX '\'' idiom rather than left to break out of quoting.
215 expect(cmd).toContain(`>> ${`'${paths.journal.replaceAll("'", `'\\''`)}'`}`)
216 expect(cmd).toContain(`2>> ${`'${paths.stderr.replaceAll("'", `'\\''`)}'`}`)
217 expect(cmd).not.toContain('rm -rf /')
218 expect(cmd).not.toContain('$(whoami)')
219 })
220})
221​
222describe('journalFollowCommand / journalReadCommand', () => {
223 it('translates a 0-based consumed-byte count into tail -c +N (1-based)', () => {
224 const paths = journalPaths('r1')
225 expect(journalFollowCommand(paths, 0)).toBe(
226 `mkdir -p '/tmp/tanstack-runs' 2>/dev/null; ` +
227 `: >> '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null; ` +
228 `tail -c +1 -f '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null`,
229 )
230 expect(journalFollowCommand(paths, 100)).toContain(
231 `tail -c +101 -f '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null`,
232 )
233 })
234​
235 it('creates the journal before following it, so tail cannot exit on a missing file', () => {
236 // The agent spawn and the reader spawn are unordered, so the reader
237 // routinely wins the race. `tail -f` on a nonexistent path exits instead of
238 // waiting, which would silently deliver zero lines for the whole run.
239 const cmd = journalFollowCommand(journalPaths('r1'), 0)
240 expect(cmd).toContain(`: >> '/tmp/tanstack-runs/r1.ndjson'`)
241 // Append, never truncate: a prefix a previous host delivered must survive.
242 expect(cmd).not.toContain(`: > '/tmp/tanstack-runs/r1.ndjson'`)
243 expect(cmd.indexOf(': >>')).toBeLessThan(cmd.indexOf('tail -c'))
244 })
245​
246 it('the bounded read drops -f and keeps the base64 frame, so a poll cannot hang', () => {
247 const paths = journalPaths('r1')
248 expect(journalReadCommand(paths, 100)).toBe(
249 `tail -c +101 '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null | base64`,
250 )
251 expect(journalReadCommand(paths, 100)).not.toContain('-f')
252 })
253​
254 it('silences stderr on both reads', () => {
255 const paths = journalPaths('r1')
256 for (const cmd of [
257 journalFollowCommand(paths, 0),
258 journalReadCommand(paths, 0),
259 ]) {
260 expect(cmd).toContain('2>/dev/null')
261 }
262 })
263​
264 it('never pipes the following read into a filter, which would buffer the stream', () => {
265 // `base64` (GNU coreutils and busybox alike) buffers its stdout when it is
266 // a pipe, so `tail -f … | base64` delivers nothing until the encoder's
267 // stdin closes — i.e. until the reader kills `tail`, after the consumer has
268 // given up. Any pipe at all on the follow path reintroduces some filter's
269 // stdio buffer between the agent and the host, so assert there is none.
270 expect(journalFollowCommand(journalPaths('r1'), 0)).not.toContain('|')
271 // The bounded read is safe to frame: `exec` closes the encoder's stdin.
272 expect(journalReadCommand(journalPaths('r1'), 0)).toContain('| base64')
273 })
274​
275 it('rejects a negative byte position instead of emitting tail -c +0', () => {
276 expect(() => journalReadCommand(journalPaths('r1'), -1)).toThrow(/fromByte/)
277 expect(() => journalFollowCommand(journalPaths('r1'), -1)).toThrow(
278 /fromByte/,
279 )
280 })
281})
282​
283describe('journalExistsCommand', () => {
284 it('probes through the shell, never through fs.*', () => {
285 expect(journalExistsCommand(journalPaths('r1'))).toBe(
286 `test -f '/tmp/tanstack-runs/r1.ndjson'`,
287 )
288 })
289})
290​
291describe('journalStderrReadCommand', () => {
292 it('reads a BOUNDED tail of the sidecar, base64-framed, stderr silenced', () => {
293 expect(journalStderrReadCommand(journalPaths('r1'))).toBe(
294 `tail -c -4096 '/tmp/tanstack-runs/r1.err' 2>/dev/null | base64`,
295 )
296 })
297​
298 it('reads the sidecar and never the journal', () => {
299 const cmd = journalStderrReadCommand(journalPaths('r1'))
300 expect(cmd).toContain(`'/tmp/tanstack-runs/r1.err'`)
301 expect(cmd).not.toContain('.ndjson')
302 })
303​
304 it('keeps the base64 frame and drops -f, because this is an exec read', () => {
305 // Same reasoning as `journalReadCommand`: `exec` closes the encoder's stdin
306 // so it flushes, and an unbounded following read would never terminate. The
307 // sidecar is NOT line-delimited JSON, so the frame is what makes a provider
308 // that folds stderr into stdout harmless here.
309 const cmd = journalStderrReadCommand(journalPaths('r1'))
310 expect(cmd).toContain('| base64')
311 expect(cmd).not.toContain('-f ')
312 })
313​
314 it('honors an explicit byte bound', () => {
315 expect(journalStderrReadCommand(journalPaths('r1'), 64)).toContain(
316 'tail -c -64',
317 )
318 })
319​
320 it('rejects a non-positive bound rather than emitting an unbounded read', () => {
321 expect(() => journalStderrReadCommand(journalPaths('r1'), 0)).toThrow(
322 /maxBytes/,
323 )
324 expect(() => journalStderrReadCommand(journalPaths('r1'), -5)).toThrow(
325 /maxBytes/,
326 )
327 expect(() => journalStderrReadCommand(journalPaths('r1'), 1.5)).toThrow(
328 /maxBytes/,
329 )
330 })
331​
332 it('quotes an adversarial runId so the sidecar read cannot inject shell', () => {
333 const paths = journalPaths(`a'; rm -rf /; echo $(whoami)`)
334 const cmd = journalStderrReadCommand(paths)
335 expect(cmd).toContain(`'${paths.stderr.replaceAll("'", `'\\''`)}'`)
336 expect(cmd).not.toContain('rm -rf /')
337 expect(cmd).not.toContain('$(whoami)')
338 })
339})
340​
341describe('journalCleanupCommand', () => {
342 it("removes BOTH of a run's files in one shell rm -f", () => {
343 expect(journalCleanupCommand(journalPaths('r1'))).toBe(
344 `rm -f '/tmp/tanstack-runs/r1.ndjson' '/tmp/tanstack-runs/r1.err'`,
345 )
346 })
347​
348 it('deletes through the shell, never through fs.* (rule 3)', () => {
349 // On local-process, `/tmp` resolves under the sandbox root through `fs.*`
350 // but to the host's real `/tmp` through the shell — an `fs.remove` would
351 // delete a different path than `journaledCommand` wrote, i.e. nothing.
352 // Asserting the exact string is how that stays true.
353 expect(journalCleanupCommand(journalPaths('r1'))).toMatch(/^rm -f /)
354 })
355​
356 it('uses -f so an already-deleted journal is a success, not an error', () => {
357 // A provider may have reaped `/tmp`, or a successor host may have cleaned up
358 // first. Neither is a failure of the run.
359 expect(journalCleanupCommand(journalPaths('r1'))).toContain('rm -f')
360 })
361​
362 it('quotes an adversarial runId so cleanup cannot rm anything else', () => {
363 const paths = journalPaths(`a'; rm -rf /; echo $(whoami) "b`)
364 const cmd = journalCleanupCommand(paths)
365 expect(cmd).toContain(`'${paths.journal.replaceAll("'", `'\\''`)}'`)
366 expect(cmd).toContain(`'${paths.stderr.replaceAll("'", `'\\''`)}'`)
367 expect(cmd).not.toContain('rm -rf /')
368 expect(cmd).not.toContain('$(whoami)')
369 })
370​
371 it('never touches the journal DIRECTORY, which other runs share', () => {
372 const cmd = journalCleanupCommand(journalPaths('r1'))
373 // `-f` and nothing else: no `-r`, which is the flag that would let a
374 // mis-derived path take the whole shared directory with it.
375 expect(cmd.split(' ').filter((word) => word.startsWith('-'))).toEqual([
376 '-f',
377 ])
378 expect(cmd).not.toContain(`'${DEFAULT_JOURNAL_DIR}'`)
379 })
380})
381​
382/** Filename component of a path, which is what a listing hands the decoder. */
383function filenameOf(path: string): string {
384 return path.slice(path.lastIndexOf('/') + 1)
386​
387describe('journalListCommand', () => {
388 it('lists one entry per line with stderr silenced', () => {
389 expect(journalListCommand()).toBe(`ls -1 '/tmp/tanstack-runs' 2>/dev/null`)
390 })
391​
392 it('silences stderr so a missing directory yields NO lines, not a diagnostic line', () => {
393 // Daytona's `exec` and the Sprites fast path fold stderr into stdout, so
394 // without `2>/dev/null` an `ls: cannot access …` sentence arrives as if it
395 // were a filename — and the sweep would try to decode and delete it.
396 // Asserting the exact string is the only way this stays true; a
397 // `toContain('ls -1')` assertion passes against almost any command.
398 const cmd = journalListCommand('/var/journals')
399 expect(cmd).toBe(`ls -1 '/var/journals' 2>/dev/null`)
400 expect(cmd).toContain('2>/dev/null')
401 })
402​
403 it('quotes an adversarial directory so listing cannot inject shell', () => {
404 expect(journalListCommand(`/t'; rm -rf /; echo $(whoami)`)).toBe(
405 `ls -1 '/t'\\''; rm -rf /; echo $(whoami)' 2>/dev/null`,
406 )
407 })
408​
409 it('normalizes a trailing slash, so the dir matches the one journalPaths used', () => {
410 expect(journalListCommand('/var/journals/')).toBe(
411 `ls -1 '/var/journals' 2>/dev/null`,
412 )
413 })
414})
415​
416describe('journalMtimeListCommand', () => {
417 it('uses stat -c with the directory as its own first operand', () => {
418 // `find -newermt` / `-printf` are GNU-only: unrecognized on BusyBox 1.37
419 // (the alpine:3 image the docker journal conformance test runs in) and on
420 // MINGW64. `stat -c "%Y %n"` is measured working on all three.
421 expect(journalMtimeListCommand()).toBe(
422 `stat -c '%Y %n' '/tmp/tanstack-runs' '/tmp/tanstack-runs'/* 2>/dev/null`,
423 )
424 })
425​
426 it('never reaches for a GNU-only find predicate', () => {
427 const cmd = journalMtimeListCommand()
428 expect(cmd).not.toContain('newermt')
429 expect(cmd).not.toContain('-newer')
430 expect(cmd).not.toContain('printf')
431 expect(cmd).not.toContain('find ')
432 })
433​
434 it('writes nothing: no reference file that ls -1 would report as an entry', () => {
435 // The `touch -d <ts> ref` + `find ! -newer ref` idiom also works on all
436 // three shells, but a reference file INSIDE the journal directory is an
437 // entry a sweep would try to decode and delete. This command has no
438 // redirection other than the stderr silencer, so it cannot create one.
439 const cmd = journalMtimeListCommand()
440 expect(cmd).not.toContain('touch')
441 expect(cmd.match(/>/g)).toEqual(['>'])
442 expect(cmd).toContain('2>/dev/null')
443 })
444​
445 it('normalizes a trailing slash on both operands', () => {
446 expect(journalMtimeListCommand('/var/journals/')).toBe(
447 `stat -c '%Y %n' '/var/journals' '/var/journals'/* 2>/dev/null`,
448 )
449 })
450})
451​
452describe('parseJournalMtimeListing', () => {
453 it('reads the witness line plus one entry per file', () => {
454 const stdout = [
455 '1700000000 /tmp/tanstack-runs',
456 '1700000001 /tmp/tanstack-runs/r1.ndjson',
457 '1700000002 /tmp/tanstack-runs/r1.err',
458 '',
459 ].join('\n')
460 expect(parseJournalMtimeListing(stdout)).toEqual({
461 kind: 'listed',
462 entries: [
463 { name: 'r1.ndjson', mtimeMs: 1_700_000_001_000 },
464 { name: 'r1.err', mtimeMs: 1_700_000_002_000 },
465 ],
466 })
467 })
468​
469 it('distinguishes "mechanism unavailable" from "no files"', () => {
470 // BusyBox exits 1 with EMPTY stdout on an unrecognized flag, and `stat` on
471 // an EMPTY directory also exits 1 — but prints the witness line for the
472 // directory operand. If those two collapsed into `[]`, a caller inferring
473 // "no journals matched, therefore nothing here is recent" would delete the
474 // whole directory. The witness line, not the exit status, is the evidence.
475 expect(parseJournalMtimeListing('')).toEqual({ kind: 'unavailable' })
476 expect(parseJournalMtimeListing('1700000000 /tmp/tanstack-runs\n')).toEqual(
477 {
478 kind: 'listed',
479 entries: [],
480 },
481 )
482 })
483​
484 it('reports unavailable when the witness names a DIFFERENT directory', () => {
485 // Output that did not come from the command we composed proves nothing
486 // about the directory we asked about.
487 expect(
488 parseJournalMtimeListing(
489 '1700000000 /var/journals\n1700000001 /var/journals/r1.ndjson',
490 ),
491 ).toEqual({ kind: 'unavailable' })
492 })
493​
494 it('drops lines that are not "<digits> <dir>/<name>" rather than guessing', () => {
495 const stdout = [
496 '1700000000 /tmp/tanstack-runs',
497 // A folded stderr diagnostic, if one ever gets past 2>/dev/null.
498 "stat: can't stat '/tmp/tanstack-runs/x': No such file or directory",
499 // A nested path the single-level glob cannot produce.
500 '1700000003 /tmp/tanstack-runs/nested/r2.ndjson',
501 // Some other directory entirely.
502 '1700000004 /etc/passwd',
503 '1700000005 /tmp/tanstack-runs/r1.ndjson',
504 ].join('\n')
505 expect(parseJournalMtimeListing(stdout)).toEqual({
506 kind: 'listed',
507 entries: [{ name: 'r1.ndjson', mtimeMs: 1_700_000_005_000 }],
508 })
509 })
510​
511 it('honors an explicit directory, trailing slash or not', () => {
512 const stdout =
513 '1700000000 /var/journals\n1700000001 /var/journals/r1.ndjson'
514 for (const dir of ['/var/journals', '/var/journals/']) {
515 expect(parseJournalMtimeListing(stdout, dir)).toEqual({
516 kind: 'listed',
517 entries: [{ name: 'r1.ndjson', mtimeMs: 1_700_000_001_000 }],
518 })
519 }
520 })
521})
522​
523describe('journalExitProbeCommand', () => {
524 it('is the byte-identical bounded-read idiom, pointed at the journal', () => {
525 expect(journalExitProbeCommand(journalPaths('r1'))).toBe(
526 `tail -c -4096 '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null | base64`,
527 )
528 })
529​
530 it('reads the journal and never the sidecar', () => {
531 const cmd = journalExitProbeCommand(journalPaths('r1'))
532 expect(cmd).toContain(`'/tmp/tanstack-runs/r1.ndjson'`)
533 expect(cmd).not.toContain('.err')
534 })
535​
536 it('is bounded and terminating: -f dropped, base64 frame kept', () => {
537 // Safe to frame precisely because it terminates — `exec` closes the
538 // encoder's stdin so it flushes. The FOLLOW path must never do this.
539 const cmd = journalExitProbeCommand(journalPaths('r1'))
540 expect(cmd).toContain('| base64')
541 expect(cmd).not.toContain('-f ')
542 })
543​
544 it('honors an explicit byte bound', () => {
545 expect(journalExitProbeCommand(journalPaths('r1'), 64)).toBe(
546 `tail -c -64 '/tmp/tanstack-runs/r1.ndjson' 2>/dev/null | base64`,
547 )
548 })
549​
550 it('rejects a non-positive bound rather than emitting an unbounded read', () => {
551 for (const bad of [0, -5, 1.5]) {
552 expect(() => journalExitProbeCommand(journalPaths('r1'), bad)).toThrow(
553 /maxBytes/,
554 )
555 }
556 })
557​
558 it('quotes an adversarial runId so the probe cannot inject shell', () => {
559 const paths = journalPaths(`a'; rm -rf /; echo $(whoami)`)
560 const cmd = journalExitProbeCommand(paths)
561 expect(cmd).toContain(`'${paths.journal.replaceAll("'", `'\\''`)}'`)
562 expect(cmd).not.toContain('rm -rf /')
563 expect(cmd).not.toContain('$(whoami)')
564 })
565})
566​
567describe('parseJournalExit', () => {
568 const paths = journalPaths('pje-1')
569 const sentinel = (code: number): string => exitSentinelLine(paths, code)
570​
571 it('returns the exit code from the sentinel', () => {
572 expect(parseJournalExit(`{"type":"x"}\n${sentinel(7)}\n`, paths)).toBe(7)
573 expect(parseJournalExit(`${sentinel(0)}\n`, paths)).toBe(0)
574 })
575​
576 it('returns null when the sentinel is absent, which is the mid-flight case', () => {
577 // This is the whole point of the probe: a healthy mid-flight run must be
578 // reported as "not finished" WITHOUT driving it, because driving it writes
579 // a terminal status and drops it out of listReclaimable forever.
580 expect(parseJournalExit('{"type":"x"}\n{"type":"y"}\n', paths)).toBeNull()
581 expect(parseJournalExit('', paths)).toBeNull()
582 })
583​
584 it('skips the partial first line a byte-bounded tail can start inside', () => {
585 expect(parseJournalExit(`pe":"assistant"}\n${sentinel(3)}\n`, paths)).toBe(
586 3,
587 )
588 })
589​
590 it('does not mistake the sentinel KEY appearing as text for the sentinel', () => {
591 expect(
592 parseJournalExit('{"text":"the __exit sentinel is written last"}', paths),
593 ).toBeNull()
594 })
595​
596 // ── The forgery. This is the load-bearing case. ───────────────────────────
597 it('REFUSES an unnonced {"__exit":0} the agent printed, so a live run is not reaped', () => {
598 // `journaledCommand` redirects the agent's stdout and the sentinel into the
599 // SAME file with no framing, so an agent that echoes a fixture, cats a file,
600 // or dumps diagnostics can emit this line mid-run. Reading it as the sentinel
601 // makes `probeRunExit` answer `finished` for a MID-FLIGHT run, and `reapOne`
602 // then destroys the sandbox out from under a live agent.
603 expect(parseJournalExit('{"__exit":0}\n', paths)).toBeNull()
604 expect(parseJournalExit('{"delta":"hi"}\n{"__exit":0}\n', paths)).toBeNull()
605 expect(parseJournalExit('{"__exit":7}\n', paths)).toBeNull()
606 })
607​
608 it("REFUSES another run's sentinel, nonce and all", () => {
609 const other = journalPaths('pje-other')
610 expect(
611 parseJournalExit(`${exitSentinelLine(other, 0)}\n`, paths),
612 ).toBeNull()
613 })
614​
615 it('takes the LAST sentinel in the window, because the shell writes it last', () => {
616 // An agent that echoes a full, correctly-nonced sentinel mid-run (it would
617 // have to know its runId and reimplement the derivation) still cannot decide
618 // the answer: the real one is appended after all agent output, so scanning
619 // from the end always reaches the truth.
620 const text = `${sentinel(0)}\n{"delta":"still going"}\n${sentinel(7)}\n`
621 expect(parseJournalExit(text, paths)).toBe(7)
622 })
623​
624 it('REFUSES a nonced sentinel whose code is not an integer, rather than reporting 0', () => {
625 // The old code coerced a non-number to `0` — i.e. turned a garbled sentinel
626 // into a reported SUCCESS. Nothing legitimate reaches here non-integer: the
627 // only writer is `printf '…%d…' "$?"`.
628 for (const code of ['"weird"', 'null', '1.5', 'true']) {
629 expect(
630 parseJournalExit(
631 `{"__exit":${code},"${EXIT_SENTINEL_NONCE_KEY}":"${paths.nonce}"}`,
632 paths,
633 ),
634 ).toBeNull()
635 }
636 })
637​
638 it('is the same test parseExitSentinel applies to a single streamed line', () => {
639 // One definition of "the run ended", shared by the reaper's bounded tail and
640 // the streaming reader, so the two cannot drift.
641 expect(parseExitSentinel(sentinel(7), paths)).toBe(7)
642 expect(parseExitSentinel('{"__exit":7}', paths)).toBeNull()
643 expect(parseExitSentinel('not json', paths)).toBeNull()
644 expect(parseExitSentinel('', paths)).toBeNull()
645 expect(parseExitSentinel('[1,2]', paths)).toBeNull()
646 })
647})
648​
649describe('decodeJournalRunId', () => {
650 it('round-trips every non-truncating runId the encoder accepts', () => {
651 // Bounded to non-truncating inputs ON PURPOSE: the truncating branch of
652 // encodeRunId replaces the tail with a hash, which is lossy, so a
653 // "round-trips every runId journalPaths accepts" property is unsatisfiable.
654 // The truncation case is asserted separately, as a refusal.
655 const runIds = [
656 'run-123',
657 '_',
658 '_40',
659 '@',
660 '/',
661 '\\',
662 '..',
663 '.',
664 '.hidden',
665 ' leading-space',
666 'trailing-space ',
667 'a b',
668 'ünïcödé',
669 '日本語',
670 'CON',
671 'con',
672 'NUL',
673 'COM1',
674 'lpt9',
675 'CONtainer',
676 'a_2fb_20c_3bd',
677 'a/b c;d',
678 `a'; rm -rf /; echo $(whoami) "b`,
679 ' ',
680 '\n',
681 'a'.repeat(200),
682 ]
683 for (const runId of runIds) {
684 const { journal, stderr } = journalPaths(runId)
685 expect(decodeJournalRunId(filenameOf(journal)), runId).toEqual({
686 kind: 'runId',
687 runId,
688 })
689 expect(decodeJournalRunId(filenameOf(stderr)), runId).toEqual({
690 kind: 'runId',
691 runId,
692 })
693 }
694 })
695​
696 it('decodes to the EXACT string, never a U+FFFD-substituted lookalike', () => {
697 // A test asserting only `!== null` would not notice TextDecoder replacing a
698 // bad byte with U+FFFD — which is a DIFFERENT runId than any encoder input.
699 const decoded = decodeJournalRunId('_e6_97_a5_e6_9c_ac_e8_aa_9e.ndjson')
700 expect(decoded).toEqual({ kind: 'runId', runId: '日本語' })
701 if (decoded.kind === 'runId') {
702 expect(decoded.runId).not.toContain('�')
703 expect([...decoded.runId]).toHaveLength(3)
704 }
705 })
706​
707 it('refuses a truncated name — the encoding is lossy there, so the caller must KEEP it', () => {
708 // encodeRunId caps its output at 200 chars as
709 // `prefix + '-' + sha256(runId).slice(0,16)`. `-` is a pass-through-safe
710 // character, so that form is syntactically indistinguishable from a
711 // legitimately encoded id: decoding it would yield a plausible but WRONG
712 // runId, the store would not recognise it, and a sweep would delete the
713 // journal of a possibly LIVE run.
714 const { journal } = journalPaths('a'.repeat(201))
715 const name = filenameOf(journal)
716 expect(name).toMatch(/^a{183}-[0-9a-f]{16}\.ndjson$/)
717 expect(decodeJournalRunId(name)).toEqual({ kind: 'truncated' })
718 })
719​
720 it('refuses a truncation-shaped name even when it is legitimately encodable', () => {
721 // A false positive here costs an unswept journal (a bounded leak); a false
722 // negative costs a live run's journal. The refusal is the safe direction.
723 const legit = `${'a'.repeat(183)}-0123456789abcdef`
724 expect(legit).toHaveLength(200)
725 expect(filenameOf(journalPaths(legit).journal)).toBe(`${legit}.ndjson`)
726 expect(decodeJournalRunId(`${legit}.ndjson`)).toEqual({ kind: 'truncated' })
727 })
728​
729 it('refuses a token LONGER than the cap, which the encoder cannot produce', () => {
730 expect(decodeJournalRunId(`${'a'.repeat(201)}.ndjson`)).toEqual({
731 kind: 'truncated',
732 })
733 })
734​
735 it('decodes a name exactly AT the truncation threshold', () => {
736 const atThreshold = 'a'.repeat(200)
737 expect(filenameOf(journalPaths(atThreshold).journal)).toBe(
738 `${atThreshold}.ndjson`,
739 )
740 expect(decodeJournalRunId(`${atThreshold}.ndjson`)).toEqual({
741 kind: 'runId',
742 runId: atThreshold,
743 })
744 })
745​
746 it('refuses a malformed escape: bare _, one hex digit, or a non-hex digit', () => {
747 for (const token of [
748 '_',
749 'a_',
750 '_4',
751 'a_4',
752 '_zz',
753 'a_2z',
754 '_4-',
755 'a_g0b',
756 ]) {
757 expect(decodeJournalRunId(`${token}.ndjson`), token).toEqual({
758 kind: 'malformed',
759 })
760 }
761 })
762​
763 it('accepts an upper-case escape as well as a lower-case one', () => {
764 expect(decodeJournalRunId('_2F.ndjson')).toEqual({
765 kind: 'runId',
766 runId: '/',
767 })
768 expect(decodeJournalRunId('_2f.ndjson')).toEqual({
769 kind: 'runId',
770 runId: '/',
771 })
772 })
773​
774 it('refuses invalid UTF-8 byte sequences instead of substituting U+FFFD', () => {
775 // `fatal: true` is what makes these refusals. Without it each would decode
776 // to a replacement-character string — a runId no encoder ever produced.
777 for (const token of [
778 '_ff',
779 '_fe_ff',
780 '_c3', // truncated 2-byte sequence
781 '_e6_97', // truncated 3-byte sequence
782 '_80', // lone continuation byte
783 '_ed_a0_80', // surrogate half: valid CESU-8, not valid UTF-8
784 ]) {
785 expect(decodeJournalRunId(`${token}.ndjson`), token).toEqual({
786 kind: 'malformed',
787 })
788 }
789 })
790​
791 it('refuses characters outside the encoder alphabet, including path separators', () => {
792 for (const token of [
793 'a/b',
794 'a\\b',
795 'a b',
796 'a;b',
797 'a$b',
798 "a'b",
799 'a\nb',
800 'ü',
801 ]) {
802 expect(decodeJournalRunId(`${token}.ndjson`), token).toEqual({
803 kind: 'malformed',
804 })
805 }
806 })
807​
808 it('refuses a name with no journal extension, or an unknown one', () => {
809 for (const name of [
810 '',
811 'r1',
812 'r1.json',
813 'r1.ndjson.bak',
814 '.ndjson',
815 '.err',
816 ]) {
817 expect(decodeJournalRunId(name), name).toEqual({ kind: 'malformed' })
818 }
819 })
820​
821 it('decodes a Windows reserved device name back to its literal runId', () => {
822 // encodeRunId hex-escapes EVERY byte of these so `CON.ndjson` cannot open
823 // the CON device; the decode has to survive that all-escaped form.
824 expect(decodeJournalRunId('_43_4f_4e.ndjson')).toEqual({
825 kind: 'runId',
826 runId: 'CON',
827 })
828 expect(filenameOf(journalPaths('CON').journal)).toBe('_43_4f_4e.ndjson')
829 })
830​
831 it('decodes a leading dot and a relative-path lookalike to a STORE KEY, not a path', () => {
832 // `.` and `-` pass through the encoder, so these are legitimate decodes.
833 // The result is a run-store key; a caller must never join it onto a path.
834 expect(decodeJournalRunId('..ndjson')).toEqual({
835 kind: 'runId',
836 runId: '.',
837 })
838 expect(decodeJournalRunId('...ndjson')).toEqual({
839 kind: 'runId',
840 runId: '..',
841 })
842 expect(decodeJournalRunId('.hidden.ndjson')).toEqual({
843 kind: 'runId',
844 runId: '.hidden',
845 })
846 })
847​
848 it('is injective in the other direction too: distinct names never decode alike', () => {
849 const names = [
850 'r1.ndjson',
851 '_5f40.ndjson',
852 '_40.ndjson',
853 '_2f.ndjson',
854 'CONtainer.ndjson',
855 '_43_4f_4e.ndjson',
856 ]
857 const seen = new Map<string, string>()
858 for (const name of names) {
859 const decoded = decodeJournalRunId(name)
860 expect(decoded.kind, name).toBe('runId')
861 if (decoded.kind !== 'runId') continue
862 expect(seen.get(decoded.runId), name).toBeUndefined()
863 seen.set(decoded.runId, name)
864 }
865 })
866})