-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheadless.test.js
More file actions
628 lines (606 loc) · 21.4 KB
/
Copy pathheadless.test.js
File metadata and controls
628 lines (606 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
const { runCli } = require("./helpers/cli-harness");
const fs = require("fs");
const os = require("os");
const path = require("path");
describe("headless mode (bin/nex-code.js)", () => {
// ─── --version ──────────────────────────────────────────────
describe("--version", () => {
it("prints version and exits", () => {
const r = runCli(["--version"]);
expect(r.exitCode).toBe(0);
expect(r.stdoutStripped.trim()).toMatch(/^\d+\.\d+\.\d+$/);
});
it("short flag -v works", () => {
const r = runCli(["-v"]);
expect(r.exitCode).toBe(0);
expect(r.stdoutStripped.trim()).toMatch(/^\d+\.\d+\.\d+$/);
});
});
// ─── --help ─────────────────────────────────────────────────
describe("--help", () => {
it("prints usage text and exits", () => {
const r = runCli(["--help"]);
expect(r.exitCode).toBe(0);
expect(r.stdoutStripped).toContain("Usage:");
for (const flag of ["--task", "--auto", "--model", "--json"])
expect(r.stdoutStripped).toContain(flag);
});
it("short flag -h works", () => {
const r = runCli(["-h"]);
expect(r.exitCode).toBe(0);
expect(r.stdoutStripped).toContain("Usage:");
});
});
// ─── --daemon in --help ─────────────────────────────────────
describe("--daemon flag", () => {
it("--help output mentions --daemon", () => {
const r = runCli(["--help"]);
expect(r.stdoutStripped).toContain("--daemon");
});
});
// ─── --task validation ──────────────────────────────────────
describe("--task validation", () => {
it("exits with error when --task has no prompt", () => {
const r = runCli(["--task"], { expectError: true });
expect(r.exitCode).toBe(1);
expect(r.stderrStripped).toContain("requires a prompt");
});
it("exits with error when --task is followed by another flag", () => {
const r = runCli(["--task", "--json"], { expectError: true });
expect(r.exitCode).toBe(1);
});
});
describe("headless fail-closed behavior", () => {
it("exits non-zero when the run ends without a final assistant response", () => {
const r = runCli(
["--auto", "--json", "--task", "Trigger null provider response."],
{
expectError: true,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_NULL_RESPONSE: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const lines = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
expect(lines.length).toBeGreaterThan(0);
const last = JSON.parse(lines[lines.length - 1]);
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain("without a final assistant response");
});
it("exits non-zero when writes occur without a final summary", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-"));
const r = runCli(
["--auto", "--json", "--task", "Write a file and then stop."],
{
expectError: true,
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_WRITE_THEN_NULL: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
expect(fs.readFileSync(path.join(cwd, "write-null.txt"), "utf-8")).toBe(
"changed\n",
);
const lines = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
const last = JSON.parse(lines[lines.length - 1]);
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain("modified files");
});
it("finalizes when a kcal edit is read back before an empty provider response", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-kcal-"));
const r = runCli(
[
"--auto",
"--json",
"--task",
"Update the nutrition display so kcal appears in the one-line diff, then verify the file readback.",
],
{
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_WRITE_READ_THEN_NULL: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(0);
expect(
fs.readFileSync(path.join(cwd, "headless-recovered.txt"), "utf-8"),
).toBe("stable edit\n");
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("done");
expect(last.success).toBe(true);
expect(last.response).toContain("Completed the requested edit");
expect(last.response).toContain("post-edit readback");
});
it("finalizes a neutral file edit after readback when the provider returns empty", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-neutral-"));
const r = runCli(
[
"--auto",
"--json",
"--task",
"Update src/components/ProfileCard.jsx and verify the edited file readback before finishing.",
],
{
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_WRITE_READ_THEN_NULL: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(0);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("done");
expect(last.success).toBe(true);
expect(last.response).toContain("headless-recovered.txt");
expect(last.response).toContain(
"provider returned an empty response after successful post-edit verification",
);
});
it("finalizes from the CLI wrapper when a stream aborts after verified readback", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-abort-"));
const r = runCli(
[
"--auto",
"--json",
"--task",
"Update src/lib/request-handler.js and verify the edited file readback before finishing.",
],
{
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_WRITE_READ_THEN_NULL: "1",
NEX_MOCK_WRITE_READ_THEN_ABORT_STREAM: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(0);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("done");
expect(last.success).toBe(true);
expect(last.response).toContain("model stream ended");
expect(last.response).toContain("post-edit readback");
});
it("does not recover as success when the write failed before readback", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-failed-"));
fs.writeFileSync(path.join(cwd, "headless-failed.txt"), "unchanged\n");
const r = runCli(
[
"--auto",
"--json",
"--task",
"Attempt an edit, read the file back, and finish.",
],
{
cwd,
expectError: true,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_FAILED_WRITE_READ_ABORT_STREAM: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain("without a final assistant response");
expect(fs.readFileSync(path.join(cwd, "headless-failed.txt"), "utf-8")).toBe(
"unchanged\n",
);
});
it("replaces confused post-edit questions with a verified-work summary", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-question-"));
const r = runCli(
[
"--auto",
"--json",
"--task",
"Update src/lib/request-handler.js and verify the edited file readback before finishing.",
],
{
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_WRITE_READ_THEN_QUESTION: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(0);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("done");
expect(last.success).toBe(true);
expect(last.response).toContain("Completed the requested edit");
expect(last.response).toContain("confused follow-up question");
expect(last.response).not.toContain("What would you like me to do");
});
it("emits a terminal error event when the process exits after tool_start", () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "nex-headless-exit-"));
const r = runCli(
["--auto", "--json", "--task", "Refactor app.js to async / await."],
{
expectError: true,
cwd,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_EXIT_AFTER_TOOL_START: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
expect(events.some((event) => event.type === "tool_start")).toBe(true);
expect(events.some((event) => event.type === "tool_end")).toBe(false);
expect(events.some((event) => event.type === "done")).toBe(false);
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toMatch(/unfinished tool call|Headless JSON run ended/);
});
it("emits a terminal error when the process exits 0 without a terminal event", () => {
const r = runCli(
["--auto", "--json", "--task", "Exit before finishing."],
{
expectError: true,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_EXIT_ZERO_NO_TERMINAL: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain(
"Headless JSON run ended before emitting a final done/error event",
);
});
it("emits an error instead of done when the final response explicitly refuses success", () => {
const r = runCli(
["--auto", "--json", "--task", "Run npm run lint before finishing."],
{
expectError: true,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_INCOMPLETE_VERIFY_RESPONSE: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain("Verification incomplete");
});
it(
"emits a terminal error when thinking tokens flow but no content arrives for the abort threshold",
() => {
const r = runCli(
[
"--auto",
"--json",
"--task",
"Fix the ESLint failures. Run npm run lint before finishing.",
],
{
expectError: true,
timeout: 120000,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_THINKING_NO_CONTENT: "1",
NEX_STALE_ABORT_MS: "1000",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(1);
const lines = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
expect(lines.length).toBeGreaterThan(0);
const last = JSON.parse(lines[lines.length - 1]);
expect(last.type).toBe("error");
expect(last.success).toBe(false);
},
125000,
);
it("does not fail when thinking tokens arrive before visible content", () => {
const r = runCli(
["--auto", "--json", "--task", "Fix the ESLint failures."],
{
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_THINKING_BEFORE_CONTENT: "1",
NEX_STALE_ABORT_MS: "1000",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
},
},
);
expect(r.exitCode).toBe(0);
const lines = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
expect(lines.length).toBeGreaterThan(0);
const last = JSON.parse(lines[lines.length - 1]);
expect(last.type).toBe("done");
expect(last.success).toBe(true);
}, 30000);
it(
"watchdog emits terminal error when tools remain pending past threshold",
() => {
const r = runCli(
[
"--auto",
"--json",
"--task",
"Refactor app.js to async / await.",
],
{
expectError: true,
timeout: 30000,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
// The mock returns a tool call normally, and the agent loop
// proceeds. The watchdog fires only if the process stalls
// mid-tool-execution. To test the watchdog itself, use
// NEX_MOCK_EXIT_AFTER_TOOL_START to simulate an exit during
// tool execution, which historically caused a dangling
// tool_start before the watchdog was added.
NEX_MOCK_EXIT_AFTER_TOOL_START: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
// Fast watchdog for testing — fire at 2 seconds instead of 15
NEX_PENDING_TOOLS_WATCHDOG_MS: "2000",
},
},
);
// The NEX_MOCK_EXIT_AFTER_TOOL_START trigger fires before the
// watchdog has a chance (process.exit(0) runs immediately after
// onToolStart). Both paths should produce a terminal error.
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
expect(events.some((event) => event.type === "tool_start")).toBe(true);
// No tool_end because the process exited during execution
expect(events.some((event) => event.type === "tool_end")).toBe(false);
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
// Error message should mention the unfinished tool or the lifecycle failure
expect(last.error).toMatch(
/unfinished tool call|Headless JSON run ended/,
);
},
35000,
);
it(
"watchdog keeps the process alive and fails closed for unresolved tool promises",
() => {
const r = runCli(
[
"--auto",
"--json",
"--task",
"Refactor app.js to async / await.",
],
{
expectError: true,
timeout: 30000,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
NEX_MOCK_HANG_AFTER_TOOL_START: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
NEX_PENDING_TOOLS_WATCHDOG_MS: "2000",
},
},
);
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
expect(events.some((event) => event.type === "tool_start")).toBe(true);
expect(events.some((event) => event.type === "tool_end")).toBe(false);
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
expect(last.error).toContain("Pending tool call");
},
35000,
);
// ─── Patch 3 regression: exit 0 blocked after dangling tool_start ──
it(
"emits terminal error (exit 1) when last event is a dangling tool_start with empty pending tools",
() => {
const r = runCli(
[
"--auto",
"--json",
"--task",
"Refactor app.js to async / await.",
],
{
expectError: true,
timeout: 30000,
env: {
NEX_NO_DOTENV: "1",
NEX_MOCK_PROVIDER: "1",
// Exit immediately after tool_start — this simulates a
// lifecycle bug where the process exits 0 before the
// pending-tools watchdog fires and mismatched tool_end
// cleanup left pendingTools empty but lastJsonEventType
// stuck at "tool_start".
NEX_MOCK_EXIT_AFTER_TOOL_START: "1",
HEADLESS_MODEL: "mock:mock-model",
NEX_NO_FLATRATE: "1",
OLLAMA_API_KEY: "",
NEX_PHASE_ROUTING: "0",
// Fast watchdog (won't fire because process exits first)
NEX_PENDING_TOOLS_WATCHDOG_MS: "2000",
},
},
);
// The process.exit override must prevent exit 0 when the last
// JSON event is a dangling tool_start, even if pendingTools is
// empty (e.g. due to a race or bug).
expect(r.exitCode).toBe(1);
const events = r.stdoutStripped
.trim()
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
.map((line) => JSON.parse(line));
const last = events[events.length - 1];
expect(last.type).toBe("error");
expect(last.success).toBe(false);
// The error must mention either the unfinished tool or the
// dangling tool_start / missing terminal event.
expect(last.error).toMatch(
/unfinished tool call|dangling tool_start|Headless JSON run ended/,
);
},
35000,
);
});
});