1
+import assert from 'node:assert/strict';
2
+import { execFileSync, spawn, spawnSync } from 'node:child_process';
3
+import {
4
+ copyFileSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ mkdtempSync,
8
+ readFileSync,
9
+ readdirSync,
10
+ rmSync,
11
+ symlinkSync,
12
+ writeFileSync,
13
+} from 'node:fs';
14
+import os from 'node:os';
15
+import path from 'node:path';
16
+import { afterEach, test } from 'bun:test';
17
+import { setTimeout as delay } from 'node:timers/promises';
18
+
19
+interface TaskStatus {
20
+ task: {
21
+ id: string;
22
+ goal: string;
23
+ nextStep: string | null;
24
+ blocker: string | null;
25
+ authority: string;
26
+ };
27
+ status: string;
28
+ receipt: string;
29
+}
30
+type Fixture = ReturnType<typeof fixture>;
31
+
32
+const script = new URL('../scripts/agent-task.ts', import.meta.url);
33
+const cleanups: Array<() => void> = [];
34
+afterEach(() => {
35
+ for (const cleanup of cleanups.splice(0).reverse()) cleanup();
36
+});
37
+
38
+const lingeringWorker =
39
+ 'process.on("SIGTERM",()=>{});require("fs").writeFileSync(".artifacts/child.pid",String(process.pid));setInterval(()=>{},1000)';
40
+
41
+const fixture = () => {
42
+ const root = mkdtempSync(path.join(os.tmpdir(), 'composio-agent-task-'));
43
+ cleanups.push(() => rmSync(root, { recursive: true, force: true }));
44
+ mkdirSync(path.join(root, 'scripts'));
45
+ copyFileSync(script, path.join(root, 'scripts/agent-task.ts'));
46
+ symlinkSync(new URL('../node_modules', import.meta.url), path.join(root, 'node_modules'), 'dir');
47
+ writeFileSync(path.join(root, '.gitignore'), '.artifacts/\nnode_modules\n');
48
+ writeFileSync(path.join(root, 'source.txt'), 'original');
49
+ mkdirSync(path.join(root, '.claude'));
50
+ writeFileSync(path.join(root, '.claude/scheduled_tasks.lock'), 'session one');
51
+ const profiles = {
52
+ offline: {
53
+ boundary: 'offline',
54
+ commands: [{ cwd: '.', argv: [process.execPath, '-e', 'console.log("verified")'] }],
55
+ },
56
+ failure: {
57
+ boundary: 'offline',
58
+ commands: [
59
+ {
60
+ cwd: '.',
61
+ argv: [
62
+ process.execPath,
63
+ '-e',
64
+ 'process.exit(require("fs").existsSync(".artifacts/succeed") ? 0 : 7)',
65
+ ],
66
+ },
67
+ { cwd: '.', argv: [process.execPath, '-e', 'console.log("second")'] },
68
+ ],
69
+ },
70
+ missing: {
71
+ boundary: 'offline',
72
+ commands: [{ cwd: '.', argv: ['composio-test-missing-executable'] }],
73
+ },
74
+ mutating: {
75
+ boundary: 'offline',
76
+ commands: [
77
+ {
78
+ cwd: '.',
79
+ argv: [
80
+ process.execPath,
81
+ '-e',
82
+ 'require("fs").writeFileSync("source.txt", "changed during verification")',
83
+ ],
84
+ },
85
+ ],
86
+ },
87
+ noisy: {
88
+ boundary: 'offline',
89
+ commands: [
90
+ {
91
+ cwd: '.',
92
+ argv: [
93
+ process.execPath,
94
+ '-e',
95
+ 'console.log("first line");console.log("x".repeat(200000));console.error("final type error");process.exitCode=2',
96
+ ],
97
+ },
98
+ ],
99
+ },
100
+ interrupt: {
101
+ boundary: 'offline',
102
+ commands: [
103
+ {
104
+ cwd: '.',
105
+ argv: [
106
+ process.execPath,
107
+ '-e',
108
+ 'const child=require("child_process").spawn(process.execPath,["-e","setInterval(()=>{},1000)"],{stdio:"inherit"});require("fs").writeFileSync(".artifacts/child.pid",String(child.pid));setInterval(()=>{},1000)',
109
+ ],
110
+ },
111
+ ],
112
+ },
113
+ lingering: {
114
+ boundary: 'offline',
115
+ commands: [
116
+ {
117
+ cwd: '.',
118
+ argv: [
119
+ process.execPath,
120
+ '-e',
121
+ `require("child_process").spawn(process.execPath,["-e",${JSON.stringify(lingeringWorker)}],{stdio:"ignore"});setInterval(()=>{if(require("fs").existsSync(".artifacts/child.pid"))process.exit(0)},10)`,
122
+ ],
123
+ },
124
+ ],
125
+ },
126
+ };
127
+ writeFileSync(path.join(root, 'scripts/agent-profiles.json'), JSON.stringify(profiles));
128
+ for (const args of [
129
+ ['init', '-q'],
130
+ ['add', '.'],
131
+ ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'baseline'],
132
+ ]) {
133
+ execFileSync('git', args, { cwd: root });
134
+ }
135
+ const run = (...args: string[]) =>
136
+ spawnSync(process.execPath, ['scripts/agent-task.ts', ...args], {
137
+ cwd: root,
138
+ encoding: 'utf8',
139
+ });
140
+ const state = (id: string): TaskStatus => JSON.parse(run('status', id).stdout);
141
+ const init = (id = 'case', profile = 'offline') =>
142
+ run(
143
+ 'init',
144
+ id,
145
+ '--goal',
146
+ 'Verify the changed behavior',
147
+ '--profile',
148
+ profile,
149
+ '--authority',
150
+ 'local verification only'
151
+ );
152
+ return { root, run, state, init };
153
+};
154
+
155
+async function runningFixture(f: Fixture) {
156
+ assert.equal(f.init('case', 'interrupt').status, 0);
157
+ const runner = spawn(process.execPath, ['scripts/agent-task.ts', 'verify', 'case'], {
158
+ cwd: f.root,
159
+ stdio: 'ignore',
160
+ });
161
+ const exit = new Promise(resolve =>
162
+ runner.on('exit', (code, signal) => resolve({ code, signal }))
163
+ );
164
+ cleanups.push(() => runner.kill('SIGKILL'));
165
+ const file = path.join(f.root, '.artifacts/child.pid');
166
+ for (let i = 0; i < 250 && !existsSync(file); i++) await delay(20);
167
+ const childPid = Number(readFileSync(file, 'utf8'));
168
+ const receipt = JSON.parse(readFileSync(path.join(f.root, f.state('case').receipt), 'utf8'));
169
+ const group = receipt.commands[0].pid;
170
+ cleanups.push(() => {
171
+ try {
172
+ process.kill(-group, 'SIGKILL');
173
+ } catch {}
174
+ });
175
+ return { runner, exit, childPid, group };
176
+}
177
+
178
+async function waitGone(pid: number) {
179
+ for (let i = 0; i < 250; i++) {
180
+ try {
181
+ process.kill(pid, 0);
182
+ } catch (error) {
183
+ const code = error instanceof Error && 'code' in error ? error.code : undefined;
184
+ if (code === 'ESRCH') return;
185
+ assert.equal(code, 'EPERM');
186
+ }
187
+ await delay(20);
188
+ }
189
+ assert.fail(`Process ${pid} did not stop`);
190
+}
191
+
192
+function useOfflineProfile(f: Fixture) {
193
+ const file = path.join(f.root, 'scripts/agent-profiles.json');
194
+ const profiles = JSON.parse(readFileSync(file, 'utf8'));
195
+ profiles.interrupt.commands = profiles.offline.commands;
196
+ writeFileSync(file, JSON.stringify(profiles));
197
+}
198
+
199
+test('CLI help describes commands and required initialization inputs without creating a task', () => {
200
+ const f = fixture();
201
+ const rootHelp = f.run('--help');
202
+ assert.equal(rootHelp.status, 0, rootHelp.stderr);
203
+ assert.match(rootHelp.stdout, /init/);
204
+ assert.match(rootHelp.stdout, /verify/);
205
+ const initHelp = f.run('init', '--help');
206
+ assert.equal(initHelp.status, 0, initHelp.stderr);
207
+ assert.match(initHelp.stdout, /--goal/);
208
+ assert.match(initHelp.stdout, /--profile/);
209
+ assert.equal(existsSync(path.join(f.root, '.artifacts/agent-tasks')), false);
210
+});
211
+
212
+test('invalid CLI inputs fail before creating task state', () => {
213
+ const f = fixture();
214
+ const missing = f.run('init', 'case', '--profile', 'offline');
215
+ assert.equal(missing.status, 1);
216
+ assert.match(missing.stderr, /goal/i);
217
+ const unknown = f.run(
218
+ 'init',
219
+ 'case',
220
+ '--goal',
221
+ 'Check behavior',
222
+ '--profile',
223
+ 'offline',
224
+ '--bogus'
225
+ );
226
+ assert.equal(unknown.status, 1);
227
+ assert.match(unknown.stderr, /bogus/i);
228
+ const completions = f.run('--completions', 'nope');
229
+ assert.equal(completions.status, 1);
230
+ assert.match(completions.stderr, /nope/);
231
+ const duplicate = f.run(
232
+ 'init',
233
+ 'case',
234
+ '--goal',
235
+ 'A goal',
236
+ '--profile',
237
+ 'offline',
238
+ '--profile',
239
+ 'failure'
240
+ );
241
+ assert.equal(duplicate.status, 1);
242
+ assert.match(duplicate.stderr, /profile/);
243
+ const authority = f.run(
244
+ 'init',
245
+ 'case',
246
+ '--goal',
247
+ 'A goal',
248
+ '--profile',
249
+ 'offline',
250
+ '--authority',
251
+ 'First scope',
252
+ '--authority',
253
+ 'Other scope'
254
+ );
255
+ assert.equal(authority.status, 1);
256
+ assert.match(authority.stderr, /authority/);
257
+ assert.equal(existsSync(path.join(f.root, '.artifacts/agent-tasks')), false);
258
+});
259
+
260
+test('dash-leading task text is saved literally instead of activating built-in flags', () => {
261
+ const f = fixture();
262
+ assert.equal(
263
+ f.run(
264
+ 'init',
265
+ 'case',
266
+ '--goal',
267
+ '- Fix the CLI',
268
+ '--profile',
269
+ 'offline',
270
+ '--authority',
271
+ '- No merge'
272
+ ).status,
273
+ 0
274
+ );
275
+ assert.equal(existsSync(path.join(f.root, '.artifacts/agent-tasks/case/task.json')), true);
276
+ assert.equal(f.state('case').task.goal, '- Fix the CLI');
277
+ assert.equal(f.state('case').task.authority, '- No merge');
278
+});
279
+
280
+test('task context survives a fresh invocation and duplicate init preserves it', () => {
281
+ const f = fixture();
282
+ assert.equal(f.init().status, 0);
283
+ const task = f.state('case').task;
284
+ assert.equal(task.goal, 'Verify the changed behavior');
285
+ assert.equal(task.authority, 'local verification only');
286
+ assert.equal(f.init().status, 1);
287
+ assert.deepEqual(f.state('case').task, task);
288
+ assert.equal(f.state('case').status, 'pending');
289
+ assert.equal(JSON.parse(f.run('list').stdout)[0].task.id, 'case');
290
+});
291
+
292
+test('list reports an unreadable task folder without hiding the others', () => {
293
+ const f = fixture();
294
+ assert.equal(f.init().status, 0);
295
+ mkdirSync(path.join(f.root, '.artifacts/agent-tasks/broken'));
296
+ writeFileSync(path.join(f.root, '.artifacts/agent-tasks/broken/task.json'), '{');
297
+ const result = f.run('list');
298
+ assert.equal(result.status, 0, result.stderr);
299
+ const [broken, valid] = JSON.parse(result.stdout);
300
+ assert.equal(broken.id, 'broken');
301
+ assert.equal(broken.status, 'unreadable');
302
+ assert.equal(valid.task.id, 'case');
303
+ assert.equal(valid.status, 'pending');
304
+});
305
+
306
+test('successful profile evidence expires after dirty edits, untracked sources, or task changes', () => {
307
+ const f = fixture();
308
+ assert.equal(f.init().status, 0);
309
+ assert.equal(f.run('verify', 'case').status, 0);
310
+ assert.equal(f.state('case').status, 'passed');
311
+ writeFileSync(path.join(f.root, 'source.txt'), 'changed without a commit');
312
+ assert.equal(f.state('case').status, 'stale');
313
+ assert.equal(f.run('verify', 'case').status, 0);
314
+ assert.equal(f.state('case').status, 'passed');
315
+ writeFileSync(path.join(f.root, 'new-source.txt'), 'new input');
316
+ assert.equal(f.state('case').status, 'stale');
317
+ assert.equal(f.run('verify', 'case').status, 0);
318
+ const taskPath = path.join(f.root, '.artifacts/agent-tasks/case/task.json');
319
+ const task = JSON.parse(readFileSync(taskPath, 'utf8'));
320
+ task.goal = 'A different acceptance outcome';
321
+ writeFileSync(taskPath, JSON.stringify(task));
322
+ assert.equal(f.state('case').status, 'stale');
323
+});
324
+
325
+test('the Claude Code scheduler lock does not invalidate evidence', () => {
326
+ const f = fixture();
327
+ assert.equal(f.init().status, 0);
328
+ assert.equal(f.run('verify', 'case').status, 0);
329
+ writeFileSync(path.join(f.root, '.claude/scheduled_tasks.lock'), 'session two');
330
+ assert.equal(f.state('case').status, 'passed');
331
+ writeFileSync(path.join(f.root, 'source.txt'), 'changed without a commit');
332
+ assert.equal(f.state('case').status, 'stale');
333
+});
334
+
335
+test('changed profiles invalidate receipts and failed attempts survive later success', () => {
336
+ const f = fixture();
337
+ assert.equal(f.init('case', 'failure').status, 0);
338
+ assert.equal(f.run('verify', 'case').status, 1);
339
+ assert.equal(f.state('case').status, 'failed');
340
+ const attempts = path.join(f.root, '.artifacts/agent-tasks/case/attempts');
341
+ const first = readdirSync(attempts)[0];
342
+ const failed = readFileSync(path.join(attempts, first, 'receipt.json'), 'utf8');
343
+ writeFileSync(path.join(f.root, '.artifacts/succeed'), 'ready');
344
+ assert.equal(f.run('verify', 'case').status, 0);
345
+ assert.equal(f.state('case').status, 'passed');
346
+ assert.equal(readdirSync(attempts).length, 2);
347
+ assert.equal(readFileSync(path.join(attempts, first, 'receipt.json'), 'utf8'), failed);
348
+ const profilesPath = path.join(f.root, 'scripts/agent-profiles.json');
349
+ const profiles = JSON.parse(readFileSync(profilesPath, 'utf8'));
350
+ profiles.failure.boundary = 'packaged';
351
+ writeFileSync(profilesPath, JSON.stringify(profiles));
352
+ assert.equal(f.state('case').status, 'stale');
353
+});
354
+
355
+test('handoff progress notes preserve proof without changing its acceptance contract', () => {
356
+ const f = fixture();
357
+ assert.equal(f.init().status, 0);
358
+ assert.equal(f.run('verify', 'case').status, 0);
359
+ const taskPath = path.join(f.root, '.artifacts/agent-tasks/case/task.json');
360
+ const task = JSON.parse(readFileSync(taskPath, 'utf8'));
361
+ task.nextStep = 'Review the verified diff';
362
+ task.blocker = 'Waiting for an owner decision';
363
+ writeFileSync(taskPath, JSON.stringify(task));
364
+ assert.equal(f.state('case').status, 'passed');
365
+ assert.equal(f.state('case').task.nextStep, task.nextStep);
366
+});
367
+
368
+test('an unfinished newer attempt cannot expose an older passing receipt', () => {
369
+ const f = fixture();
370
+ assert.equal(f.init().status, 0);
371
+ assert.equal(f.run('verify', 'case').status, 0);
372
+ mkdirSync(path.join(f.root, '.artifacts/agent-tasks/case/attempts/9999999999999-incomplete'));
373
+ assert.equal(f.state('case').status, 'interrupted');
374
+});
375
+
376
+test('a killed runner exposes interrupted evidence and a recoverable lock', async () => {
377
+ const f = fixture();
378
+ const { runner, exit, group } = await runningFixture(f);
379
+ runner.kill('SIGKILL');
380
+ assert.deepEqual(await Promise.race([exit, delay(5000, 'timed out', { ref: false })]), {
381
+ code: null,
382
+ signal: 'SIGKILL',
383
+ });
384
+ assert.equal(f.state('case').status, 'interrupted');
385
+ const blocked = f.run('verify', 'case');
386
+ assert.equal(blocked.status, 1);
387
+ assert.match(blocked.stderr, /Inspect and stop that group/);
388
+ process.kill(-group, 'SIGKILL');
389
+ await waitGone(-group);
390
+ useOfflineProfile(f);
391
+ assert.equal(f.run('verify', 'case').status, 0);
392
+ assert.equal(f.state('case').status, 'passed');
393
+});
394
+
395
+test('missing tools fail and preserve an attempted command receipt', () => {
396
+ const f = fixture();
397
+ assert.equal(f.init('case', 'missing').status, 0);
398
+ assert.equal(f.run('verify', 'case').status, 1);
399
+ assert.equal(f.state('case').status, 'failed');
400
+ const attempts = path.join(f.root, '.artifacts/agent-tasks/case/attempts');
401
+ const receipt = JSON.parse(
402
+ readFileSync(path.join(attempts, readdirSync(attempts)[0], 'receipt.json'), 'utf8')
403
+ );
404
+ assert.equal(receipt.commands.length, 1);
405
+ assert.notEqual(receipt.commands[0].exitCode, 0);
406
+});
407
+
408
+test('long output keeps its start and end in the capped log', () => {
409
+ const f = fixture();
410
+ assert.equal(f.init('case', 'noisy').status, 0);
411
+ assert.equal(f.run('verify', 'case').status, 1);
412
+ const receiptPath = path.join(f.root, f.state('case').receipt);
413
+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
414
+ assert.equal(receipt.logTruncated, true);
415
+ const log = readFileSync(path.join(path.dirname(receiptPath), 'output.log'), 'utf8');
416
+ assert.ok(log.length <= 64 * 1024 + 100, `log has ${log.length} bytes`);
417
+ assert.match(log, /^first line\n/);
418
+ assert.match(log, /bytes of output omitted/);
419
+ assert.match(log, /final type error\n$/);
420
+});
421
+
422
+test('a successful command that edits its verification subject cannot establish fresh proof', () => {
423
+ const f = fixture();
424
+ assert.equal(f.init('case', 'mutating').status, 0);
425
+ assert.equal(f.run('verify', 'case').status, 1);
426
+ assert.equal(f.state('case').status, 'stale');
427
+});
428
+
429
+for (const signal of ['SIGTERM', 'SIGHUP'] as const) {
430
+ test(`${signal} terminates the command group, preserves evidence and releases the task for retry`, async () => {
431
+ const f = fixture();
432
+ const { runner, exit, childPid } = await runningFixture(f);
433
+ runner.kill(signal);
434
+ assert.deepEqual(await Promise.race([exit, delay(5000, 'timed out', { ref: false })]), {
435
+ code: 1,
436
+ signal: null,
437
+ });
438
+ assert.equal(f.state('case').status, 'interrupted');
439
+ await waitGone(childPid);
440
+ useOfflineProfile(f);
441
+ assert.equal(f.run('verify', 'case').status, 0);
442
+ assert.equal(f.state('case').status, 'passed');
443
+ });
444
+}
445
+
446
+test('verification remains locked until independent-stdio descendants stop', async () => {
447
+ const f = fixture();
448
+ const file = path.join(f.root, 'scripts/agent-profiles.json');
449
+ const profiles = JSON.parse(readFileSync(file, 'utf8'));
450
+ const descendant = 'process.on("SIGTERM",()=>{});console.log("ready");setInterval(()=>{},1000)';
451
+ profiles.interrupt.commands[0].argv[2] = `
452
+ const child = require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(descendant)}], { stdio: ['ignore', 'pipe', 'ignore'] });
453
+ child.stdout.once('data', () => require('fs').writeFileSync('.artifacts/child.pid', String(child.pid)));
454
+ process.on('SIGTERM', () => process.exit(0));
455
+ setInterval(() => {}, 1000);
456
+ `;
457
+ writeFileSync(file, JSON.stringify(profiles));
458
+ const { runner, exit, childPid, group } = await runningFixture(f);
459
+ assert.equal(f.init('other').status, 0);
460
+ runner.kill('SIGTERM');
461
+ await waitGone(group);
462
+ process.kill(childPid, 0);
463
+ assert.equal(existsSync(path.join(f.root, '.artifacts/agent-locks/verify.lock')), true);
464
+ const overlap = f.run('verify', 'other');
465
+ assert.equal(
466
+ overlap.status,
467
+ 1,
468
+ 'the lock must outlive the direct command until its descendants stop'
469
+ );
470
+ assert.match(overlap.stderr, /case/);
471
+ assert.deepEqual(await Promise.race([exit, delay(5000, 'timed out', { ref: false })]), {
472
+ code: 1,
473
+ signal: null,
474
+ });
475
+ await waitGone(childPid);
476
+ assert.equal(f.state('case').status, 'interrupted');
477
+});
478
+
479
+test('different task profiles serialize shared worktree verification', async () => {
480
+ const f = fixture();
481
+ const { runner, exit } = await runningFixture(f);
482
+ assert.equal(f.init('other').status, 0);
483
+ try {
484
+ const overlap = f.run('verify', 'other');
485
+ assert.equal(overlap.status, 1, 'a different task must not overlap worktree verification');
486
+ assert.match(overlap.stderr, /case/);
487
+ } finally {
488
+ runner.kill('SIGTERM');
489
+ await exit;
490
+ }
491
+ assert.equal(f.run('verify', 'other').status, 0);
492
+});
493
+
494
+test('an unreadable lock is replaced once no attempt is running', () => {
495
+ const f = fixture();
496
+ assert.equal(f.init().status, 0);
497
+ mkdirSync(path.join(f.root, '.artifacts/agent-locks'), { recursive: true });
498
+ writeFileSync(path.join(f.root, '.artifacts/agent-locks/verify.lock'), '');
499
+ const result = f.run('verify', 'case');
500
+ assert.equal(result.status, 0, result.stderr);
501
+ assert.match(result.stderr, /Replacing unreadable lock/);
502
+ assert.equal(f.state('case').status, 'passed');
503
+});
504
+
505
+test('an unreadable lock still blocks verification while another attempt runs', async () => {
506
+ const f = fixture();
507
+ const { runner, exit } = await runningFixture(f);
508
+ assert.equal(f.init('other').status, 0);
509
+ try {
510
+ mkdirSync(path.join(f.root, '.artifacts/agent-locks'), { recursive: true });
511
+ writeFileSync(path.join(f.root, '.artifacts/agent-locks/verify.lock'), '{');
512
+ const overlap = f.run('verify', 'other');
513
+ assert.equal(overlap.status, 1);
514
+ assert.match(overlap.stderr, /unreadable and task case still has a running attempt/);
515
+ } finally {
516
+ runner.kill('SIGTERM');
517
+ await exit;
518
+ }
519
+});
520
+
521
+test('a revision-only change invalidates otherwise identical source evidence', () => {
522
+ const f = fixture();
523
+ assert.equal(f.init().status, 0);
524
+ assert.equal(f.run('verify', 'case').status, 0);
525
+ execFileSync(
526
+ 'git',
527
+ [
528
+ '-c',
529
+ 'user.name=Test',
530
+ '-c',
531
+ 'user.email=test@example.invalid',
532
+ 'commit',
533
+ '--allow-empty',
534
+ '-qm',
535
+ 'new revision',
536
+ ],
537
+ { cwd: f.root }
538
+ );
539
+ assert.equal(f.state('case').status, 'stale');
540
+});
541
+
542
+test('task ids cannot collide with worktree lock files', () => {
543
+ const f = fixture();
544
+ assert.equal(f.init('verify.lock').status, 0);
545
+ assert.equal(f.init('acquire.lock').status, 0);
546
+ assert.equal(f.init().status, 0);
547
+ const result = f.run('verify', 'case');
548
+ assert.equal(result.status, 0, result.stderr);
549
+ assert.equal(f.run('verify', 'verify.lock').status, 0);
550
+ assert.equal(f.state('verify.lock').status, 'passed');
551
+});
552
+
553
+test('a command that exits 0 cannot leave workers running after verification', () => {
554
+ const f = fixture();
555
+ assert.equal(f.init('case', 'lingering').status, 0);
556
+ const result = f.run('verify', 'case');
557
+ const childPid = Number(readFileSync(path.join(f.root, '.artifacts/child.pid'), 'utf8'));
558
+ cleanups.push(() => {
559
+ try {
560
+ process.kill(childPid, 'SIGKILL');
561
+ } catch {}
562
+ });
563
+ assert.equal(result.status, 0, result.stderr);
564
+ assert.throws(() => process.kill(childPid, 0), { code: 'ESRCH' });
565
+ assert.equal(f.state('case').status, 'passed');
566
+});
567
+
568
+test('a runner killed before saving its command pid keeps the lock', () => {
569
+ const f = fixture();
570
+ assert.equal(f.init().status, 0);
571
+ const deadRunner = spawnSync(process.execPath, ['-e', '']).pid;
572
+ const attempt = path.join(f.root, '.artifacts/agent-tasks/case/attempts/1-unsaved-pid');
573
+ mkdirSync(attempt, { recursive: true });
574
+ writeFileSync(
575
+ path.join(attempt, 'receipt.json'),
576
+ JSON.stringify({
577
+ version: 1,
578
+ id: '1-unsaved-pid',
579
+ runnerPid: deadRunner,
580
+ status: 'running',
581
+ commands: [
582
+ {
583
+ cwd: '.',
584
+ argv: ['long-check'],
585
+ startedAt: new Date().toISOString(),
586
+ finishedAt: null,
587
+ exitCode: null,
588
+ signal: null,
589
+ },
590
+ ],
591
+ })
592
+ );
593
+ const lock = path.join(f.root, '.artifacts/agent-locks/verify.lock');
594
+ mkdirSync(path.dirname(lock), { recursive: true });
595
+ writeFileSync(lock, JSON.stringify({ pid: deadRunner, task: 'case' }));
596
+ const blocked = f.run('verify', 'case');
597
+ assert.equal(blocked.status, 1);
598
+ assert.match(blocked.stderr, /no recorded process group/);
599
+ assert.equal(existsSync(lock), true);
600
+});
601
+
602
+test('an interrupted init can be retried and staging folders stay out of the list', () => {
603
+ const f = fixture();
604
+ mkdirSync(path.join(f.root, '.artifacts/agent-tasks/case'), { recursive: true });
605
+ mkdirSync(path.join(f.root, '.artifacts/agent-tasks/.init-leftover'));
606
+ const result = f.init();
607
+ assert.equal(result.status, 0, result.stderr);
608
+ assert.equal(f.state('case').task.goal, 'Verify the changed behavior');
609
+ assert.deepEqual(
610
+ JSON.parse(f.run('list').stdout).map((entry: TaskStatus) => entry.task.id),
611
+ ['case']
612
+ );
613
+});
614
+
615
+test('a newer attempt stays latest when the clock moves backwards', () => {
616
+ const f = fixture();
617
+ assert.equal(f.init('case', 'failure').status, 0);
618
+ writeFileSync(path.join(f.root, '.artifacts/succeed'), 'ready');
619
+ assert.equal(f.run('verify', 'case').status, 0);
620
+ rmSync(path.join(f.root, '.artifacts/succeed'));
621
+ const clock = path.join(f.root, '.artifacts/clock.ts');
622
+ writeFileSync(clock, 'Date.now = () => 1;');
623
+ const earlier = spawnSync(
624
+ process.execPath,
625
+ ['--preload', clock, 'scripts/agent-task.ts', 'verify', 'case'],
626
+ { cwd: f.root, encoding: 'utf8' }
627
+ );
628
+ assert.equal(earlier.status, 1, earlier.stderr);
629
+ assert.equal(f.state('case').status, 'failed');
630
+});
631
+
632
+test('output written before a runner is killed survives in the log', async () => {
633
+ const f = fixture();
634
+ const file = path.join(f.root, 'scripts/agent-profiles.json');
635
+ const profiles = JSON.parse(readFileSync(file, 'utf8'));
636
+ profiles.interrupt.commands[0].argv[2] =
637
+ 'process.stdout.write("x".repeat(20000)+"\\nlate diagnostic\\n",()=>{require("fs").writeFileSync(".artifacts/child.pid",String(process.pid))});setInterval(()=>{},1000)';
638
+ writeFileSync(file, JSON.stringify(profiles));
639
+ const { runner, exit } = await runningFixture(f);
640
+ const log = path.join(f.root, path.dirname(f.state('case').receipt), 'output.log');
641
+ for (let i = 0; i < 250 && !readFileSync(log, 'utf8').includes('late diagnostic'); i++)
642
+ await delay(20);
643
+ runner.kill('SIGKILL');
644
+ await exit;
645
+ const saved = readFileSync(log, 'utf8');
646
+ assert.match(saved, /^x{100}/);
647
+ assert.match(saved, /late diagnostic\n$/);
648
+});