-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.test.ts
More file actions
2397 lines (2190 loc) · 76.6 KB
/
Copy pathserver.test.ts
File metadata and controls
2397 lines (2190 loc) · 76.6 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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, expect, it, vi } from "vitest";
import {
createFakePluginHost,
makeThreadResponse,
} from "@bb/plugin-sdk/testing";
import type { PluginAgentConfigurationContext } from "@bb/plugin-sdk";
import plugin, { parseRuntimeSettings } from "./server.js";
const primaryContext = {
thread: {
id: "thread-primary",
title: "Implement feature",
parentThreadId: null,
sourceThreadId: null,
},
project: {
id: "project-test",
kind: "standard",
name: "Test",
gitRemoteUrl: null,
},
environment: {
id: "environment-test",
name: null,
path: "/workspace",
workspaceProvisionType: "unmanaged",
branchName: null,
},
host: { id: "host-test", name: "Test host" },
provider: { id: "codex", model: "gpt-5.6" },
origin: { kind: null, pluginId: null },
} satisfies PluginAgentConfigurationContext;
function timeline(maxSeq: number) {
return {
rows: [{ kind: "conversation", role: "assistant", text: "Implemented it." }],
maxSeq,
};
}
async function loadAdvisor(
output: string,
storedSettings: Record<string, string | boolean> = {},
) {
let timelineSeq = 42;
let currentOutput = output;
const spawn = vi.fn(async (_args: { prompt?: string }) =>
makeThreadResponse({
id: "thread-advisor",
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
originPluginId: "advisor",
visibility: "hidden",
status: "active",
}),
);
const host = createFakePluginHost({
pluginId: "advisor",
settings: { autoReview: false, ...storedSettings },
sdk: {
threads: {
timeline: async () => timeline(timelineSeq),
get: async ({ threadId }: { threadId: string }) =>
makeThreadResponse({
id: threadId,
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
title: threadId === "thread-primary" ? "Implement feature" : "Advisor",
status: "idle",
}),
spawn,
wait: async () => ({ matched: true }),
output: async () => ({ output: currentOutput }),
send: async () => ({ ok: true }),
stop: async () => ({ ok: true }),
defaultExecutionOptions: async () => ({
model: "gpt-5.6",
serviceTier: "none",
reasoningLevel: "high",
permissionMode: "readonly",
source: "client/turn/start",
}),
},
},
});
await plugin(host.bb);
await host.harness.resolveAgentConfiguration(primaryContext);
return {
...host,
spawn,
setTimelineSeq(next: number) {
timelineSeq = next;
},
setAdvisorOutput(next: string) {
currentOutput = next;
},
};
}
async function loadAutoAdvisor(output: string) {
const host = await loadAdvisor(output);
await host.harness.setSettings({ autoReview: true });
return host;
}
describe("advisor agent configuration", () => {
it("requires the advisor gate for primary threads but not plugin-owned reviewers", async () => {
const { harness } = await loadAdvisor(`ADVISOR_RESULT
severity: pass
summary: Looks correct
details:
none
END_ADVISOR_RESULT`);
const primary = await harness.resolveAgentConfiguration(primaryContext);
expect(primary.tools.map((tool) => tool.name)).toEqual(["advisor_review"]);
expect(primary.instructions).toContain("MUST call advisor_review");
const reviewer = await harness.resolveAgentConfiguration({
...primaryContext,
thread: { ...primaryContext.thread, id: "thread-advisor" },
origin: { kind: null, pluginId: "advisor" },
});
expect(reviewer.tools).toEqual([]);
expect(reviewer.instructions).toBeNull();
});
});
describe("advisor storage migrations", () => {
it("preserves legacy selections and sessions while adding reasoning state", async () => {
const host = createFakePluginHost({ pluginId: "advisor" });
const db = host.bb.storage.database();
db.exec(`
CREATE TABLE advisor_sessions (
primary_thread_id TEXT PRIMARY KEY,
advisor_thread_id TEXT NOT NULL,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE advisor_host_models (
host_id TEXT PRIMARY KEY,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
INSERT INTO advisor_sessions VALUES (
'primary', 'reviewer', 'codex', 'gpt-old', 1, 1
);
INSERT INTO advisor_host_models VALUES (
'host-old', 'codex', 'gpt-old', 1
);
CREATE TABLE advisor_reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
primary_thread_id TEXT NOT NULL,
source_seq INTEGER NOT NULL,
severity TEXT NOT NULL,
summary TEXT NOT NULL,
details TEXT NOT NULL,
normalized TEXT NOT NULL,
created_at INTEGER NOT NULL,
delivered_at INTEGER
);
INSERT INTO advisor_reviews (
primary_thread_id, source_seq, severity, summary, details,
normalized, created_at, delivered_at
) VALUES (
'primary', 7, 'concern', 'Legacy finding', 'old details',
'legacy finding old details', 1, 1
);
`);
await plugin(host.bb);
expect(
db
.prepare(
`SELECT provider_id, model, reasoning_level
FROM advisor_host_models WHERE host_id = 'host-old'`,
)
.get(),
).toEqual({
provider_id: "codex",
model: "gpt-old",
reasoning_level: "default",
});
// A legacy session carries no environment, so it can never match a live
// one and is rebuilt against the primary thread's current environment.
expect(
db
.prepare(
`SELECT provider_id, model, reasoning_level, environment_id
FROM advisor_sessions WHERE primary_thread_id = 'primary'`,
)
.get(),
).toEqual({
provider_id: "codex",
model: "gpt-old",
reasoning_level: "legacy",
environment_id: "",
});
// A pre-existing review survives with defaults the surfaces can render:
// no repeat lineage, and empty provenance rather than a bogus model name.
expect(
db
.prepare(
`SELECT severity, repeat_of, provider_id, model, reasoning_level,
advisor_thread_id, resolved_at, resolved_reason
FROM advisor_reviews WHERE primary_thread_id = 'primary'`,
)
.get(),
).toEqual({
severity: "concern",
repeat_of: null,
provider_id: "",
model: "",
reasoning_level: "",
advisor_thread_id: "",
resolved_at: null,
resolved_reason: "",
});
});
});
describe("advisor settings compatibility", () => {
it("exposes auto-continue as an opt-in native settings control", async () => {
const { harness } = await loadAdvisor("severity: pass\nsummary: fine");
expect(harness.registrations.settingsDescriptors.autoContinue).toMatchObject(
{
type: "boolean",
label: "Auto-continue on late findings",
default: false,
},
);
});
it("maps a legacy stored timeout value to the new labeled setting", async () => {
const common = {
enabled: true,
autoReview: false,
autoContinue: false,
advisorReasoning: "inherit",
severityThreshold: "nit",
watchdogFile: "WATCHDOG.md",
};
expect(
parseRuntimeSettings({
...common,
timeoutSeconds: "30",
transcriptSize: "20000",
}),
).toMatchObject({ timeoutSeconds: 30, transcriptSize: 20_000 });
expect(
parseRuntimeSettings({
...common,
timeoutSeconds: "30 seconds",
transcriptSize: "20,000 characters",
}),
).toMatchObject({ timeoutSeconds: 30, transcriptSize: 20_000 });
expect(
parseRuntimeSettings({
...common,
timeoutSeconds: "obsolete",
transcriptSize: "obsolete",
}),
).toMatchObject({ timeoutSeconds: 120, transcriptSize: 60_000 });
});
// Parsing legacy values is not enough on its own: the host reads stored
// settings in apps/server/src/services/plugins/plugin-settings.ts and drops
// any select value missing from `options`, substituting the default before
// the plugin ever sees it. These strings are already on disk from earlier
// versions and are historical facts, so they must stay declared.
const LEGACY_PERSISTED_SELECT_VALUES = {
timeoutSeconds: ["30", "60", "120", "300", "600"],
transcriptSize: ["20000", "60000", "120000"],
} as const;
it("still declares every legacy value it claims to accept", async () => {
const { harness } = await loadAdvisor("severity: pass\nsummary: fine");
for (const [key, legacyValues] of Object.entries(
LEGACY_PERSISTED_SELECT_VALUES,
)) {
const descriptor = harness.registrations.settingsDescriptors[key];
expect(descriptor?.type).toBe("select");
const options = descriptor?.type === "select" ? descriptor.options : [];
for (const legacy of legacyValues) {
expect(options).toContain(legacy);
}
}
});
it("honours a legacy stored timeout through the host's select filter", async () => {
// End-to-end past the filter above — the unit test on parseRuntimeSettings
// cannot see a value the host already replaced with the default.
const { harness } = await loadAdvisor(
`ADVISOR_RESULT
severity: pass
summary: fine
details:
none
END_ADVISOR_RESULT`,
{ timeoutSeconds: "30" },
);
await harness.callAgentTool(
"advisor_review",
{ focus: "" },
{ threadId: "thread-primary", projectId: "project-test" },
);
expect(harness.sdk.callsTo("threads.wait")).toEqual([
[expect.objectContaining({ timeoutMs: 30_000 })],
]);
});
});
describe("advisor review gate", () => {
it("gives the reviewer a bounded deadline and requires a final-only response", async () => {
const { harness, spawn } = await loadAdvisor(
`ADVISOR_RESULT
severity: pass
key: none
summary: Looks correct
details:
- none
resolved: none
END_ADVISOR_RESULT`,
{ timeoutSeconds: "2 minutes" },
);
await harness.callAgentTool(
"advisor_review",
{ focus: "Check the focused change." },
{ threadId: "thread-primary", projectId: "project-test" },
);
const prompt = spawn.mock.lastCall?.[0].prompt;
expect(prompt).toBeDefined();
expect(prompt).toContain("stops this review after 120 seconds");
expect(prompt).toContain("reserve the final 30 seconds");
expect(prompt).toContain("Do not send progress updates");
expect(prompt).toContain("at most 6 read-only inspection or command actions");
expect(prompt).toContain("Do not rerun broad test suites or builds");
expect(prompt).toContain("has not written its final answer yet");
expect(prompt).toContain("must never be reported as a missing-answer finding");
});
it("scales a 30-second review budget and steers finalization before cutoff", async () => {
vi.useFakeTimers();
try {
const { harness, spawn } = await loadAdvisor(
`ADVISOR_RESULT
severity: pass
key: none
summary: Looks correct
details:
- none
resolved: none
END_ADVISOR_RESULT`,
{ timeoutSeconds: "30 seconds" },
);
const send = vi.fn(async () => ({ ok: true as const }));
harness.sdk.stub("threads.send", send);
harness.sdk.stub(
"threads.wait",
async () =>
await new Promise<{ matched: true }>((resolve) => {
setTimeout(() => resolve({ matched: true }), 22_500);
}),
);
const result = harness.callAgentTool(
"advisor_review",
{ focus: "Check the focused change." },
{ threadId: "thread-primary", projectId: "project-test" },
);
await vi.advanceTimersByTimeAsync(22_000);
const prompt = spawn.mock.lastCall?.[0].prompt;
expect(prompt).toContain("stops this review after 30 seconds");
expect(prompt).toContain("reserve the final 8 seconds");
expect(prompt).toContain("at most 1 read-only inspection or command actions");
expect(send).toHaveBeenCalledWith(
expect.objectContaining({
threadId: "thread-advisor",
mode: "steer-if-active",
}),
);
await vi.advanceTimersByTimeAsync(500);
await expect(result).resolves.toContain("Advisor pass");
} finally {
vi.useRealTimers();
}
});
it("spawns a hidden review-only reviewer in the same environment", async () => {
const { harness, spawn } = await loadAdvisor(`ADVISOR_RESULT
severity: concern
summary: Verification is incomplete
details:
- Run the focused integration test.
END_ADVISOR_RESULT`);
harness.sdk.stub("providers.models", async () => ({
providers: [
{
id: "codex",
displayName: "Codex",
available: true,
// Both acceptable modes on offer: the reviewer must take the
// narrower one.
capabilities: {
supportedPermissionModes: ["readonly", "accept-edits", "full"],
},
},
],
models: [],
modelLoadError: null,
}));
await expect(
harness.callAgentTool(
"advisor_review",
{ focus: "Implemented the route and ran typecheck." },
{ threadId: "thread-primary", projectId: "project-test" },
),
).resolves.toContain("Advisor concern: Verification is incomplete");
expect(spawn).toHaveBeenCalledWith(
expect.objectContaining({
projectId: "project-test",
providerId: "codex",
model: "gpt-5.6",
permissionMode: "readonly",
environment: { type: "reuse", environmentId: "environment-test" },
visibility: "hidden",
}),
);
expect(harness.sdk.callsTo("threads.wait")).toEqual([
[expect.objectContaining({ threadId: "thread-advisor", status: "idle" })],
]);
});
it("deduplicates a review of the same timeline sequence", async () => {
const { harness, spawn } = await loadAdvisor(`ADVISOR_RESULT
severity: nit
summary: Rename the helper
details:
- The current name is ambiguous.
END_ADVISOR_RESULT`);
const first = await harness.callAgentTool(
"advisor_review",
{ focus: "Review naming." },
{ threadId: "thread-primary" },
);
const second = await harness.callAgentTool(
"advisor_review",
{ focus: "Review naming again." },
{ threadId: "thread-primary" },
);
expect(second).toBe(first);
expect(spawn).toHaveBeenCalledTimes(1);
expect(harness.sdk.callsTo("threads.output")).toHaveLength(1);
});
});
describe("post-turn advisor", () => {
it("carries an actionable completed-turn review into the next primary turn", async () => {
const { harness } = await loadAutoAdvisor(`ADVISOR_RESULT
severity: blocker
summary: The claimed test did not run
details:
- Run the integration test and report its actual result.
END_ADVISOR_RESULT`);
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
visibility: "visible",
}),
lastAssistantText: "Everything passes.",
});
const nextTurn = await harness.resolveAgentConfiguration(primaryContext);
expect(nextTurn.instructions).toContain("late independent review");
expect(nextTurn.instructions).toContain("The claimed test did not run");
const followingTurn = await harness.resolveAgentConfiguration(primaryContext);
expect(followingTurn.instructions).not.toContain("late independent review");
});
it("does not review hidden worker threads", async () => {
const { harness, spawn } = await loadAutoAdvisor(`ADVISOR_RESULT
severity: pass
summary: Fine
details:
none
END_ADVISOR_RESULT`);
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "hidden-worker",
visibility: "hidden",
originPluginId: "workflows",
}),
lastAssistantText: "Worker finished.",
});
expect(spawn).not.toHaveBeenCalled();
});
});
const BLOCKER_OUTPUT = `ADVISOR_RESULT
severity: blocker
summary: The claimed test did not run
details:
- Run the integration test and report its actual result.
END_ADVISOR_RESULT`;
describe("manual advisor review", () => {
it("returns started:false while a review is already in flight", async () => {
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
let releaseWait: (() => void) | undefined;
const wait = vi.fn(
async () =>
await new Promise<{ matched: true }>((resolve) => {
releaseWait = () => resolve({ matched: true });
}),
);
harness.sdk.stub("threads.wait", wait);
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: true, waiting: false });
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: false, waiting: false });
const during = (await harness.callRpc("threadBadge", {
threadId: "thread-primary",
})) as { reviewing: boolean };
expect(during.reviewing).toBe(true);
await vi.waitFor(() => expect(wait).toHaveBeenCalledTimes(1));
releaseWait!();
await vi.waitFor(async () => {
const after = (await harness.callRpc("threadReviews", {
threadId: "thread-primary",
})) as { reviewing: boolean; reviews: unknown[] };
expect(after.reviewing).toBe(false);
expect(after.reviews).toHaveLength(1);
});
const pending = (await harness.callRpc("pendingAdvice", {
threadId: "thread-primary",
})) as { advice: { severity: string } | null };
expect(pending.advice?.severity).toBe("blocker");
});
it("waits for an active turn instead of reviewing an incomplete answer", async () => {
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
let primaryStatus: "active" | "idle" = "active";
harness.sdk.stub("threads.get", async ({ threadId }: { threadId: string }) =>
makeThreadResponse({
id: threadId,
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
visibility: threadId === "thread-primary" ? "visible" : "hidden",
status: threadId === "thread-primary" ? primaryStatus : "idle",
}),
);
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: false, waiting: true });
const waiting = (await harness.callRpc("threadBadge", {
threadId: "thread-primary",
})) as { lifecycle: string };
expect(waiting.lifecycle).toBe("waiting");
expect(harness.sdk.callsTo("threads.spawn")).toHaveLength(0);
primaryStatus = "idle";
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
status: "idle",
}),
lastAssistantText: "The completed public answer.",
});
const completed = (await harness.callRpc("threadBadge", {
threadId: "thread-primary",
})) as { lifecycle: string };
expect(completed.lifecycle).toBe("changes-requested");
});
it("does not mistake an older output for completion of a cancelled latest turn", async () => {
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub(
"threads.timeline",
async () =>
({
rows: [
{
kind: "conversation",
role: "assistant",
turnId: "turn-1",
text: "Older completed answer.",
},
{
kind: "conversation",
role: "user",
turnId: "turn-2",
text: "New request whose turn was cancelled.",
},
],
maxSeq: 43,
}) as never,
);
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: false, waiting: true });
expect(harness.sdk.callsTo("threads.spawn")).toHaveLength(0);
});
it("settles a waiting review when the primary turn fails", async () => {
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub("threads.get", async ({ threadId }: { threadId: string }) =>
makeThreadResponse({
id: threadId,
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
visibility: threadId === "thread-primary" ? "visible" : "hidden",
status: threadId === "thread-primary" ? "active" : "idle",
}),
);
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: false, waiting: true });
await harness.emitThreadEvent("thread.failed", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
status: "idle",
}),
error: "provider stopped",
});
const settled = (await harness.callRpc("threadBadge", {
threadId: "thread-primary",
})) as { lifecycle: string; latestUnavailableReason: string | null };
expect(settled.lifecycle).toBe("unavailable");
expect(settled.latestUnavailableReason).toContain("primary turn failed");
});
it("settles a waiting review when idle arrives without a public answer", async () => {
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub("threads.get", async ({ threadId }: { threadId: string }) =>
makeThreadResponse({
id: threadId,
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
visibility: threadId === "thread-primary" ? "visible" : "hidden",
status: threadId === "thread-primary" ? "active" : "idle",
}),
);
await expect(
harness.callRpc("requestReview", { threadId: "thread-primary" }),
).resolves.toEqual({ started: false, waiting: true });
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
status: "idle",
}),
lastAssistantText: null,
});
const settled = (await harness.callRpc("threadBadge", {
threadId: "thread-primary",
})) as { lifecycle: string; latestUnavailableReason: string | null };
expect(settled.lifecycle).toBe("unavailable");
expect(settled.latestUnavailableReason).toContain(
"without a completed public answer",
);
});
});
describe("late-finding continuation", () => {
it("starts one agent-only corrective turn and is idempotent per review round", async () => {
const { harness } = await loadAutoAdvisor(BLOCKER_OUTPUT);
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
}),
lastAssistantText: "Everything passes.",
});
const panel = (await harness.callRpc("threadReviews", {
threadId: "thread-primary",
})) as { reviews: { id: number }[] };
const reviewId = panel.reviews[0]!.id;
await expect(
harness.callRpc("continueFinding", {
threadId: "thread-primary",
reviewId,
}),
).resolves.toEqual({ started: true, reason: "started" });
await expect(
harness.callRpc("continueFinding", {
threadId: "thread-primary",
reviewId,
}),
).resolves.toEqual({ started: false, reason: "already-started" });
const primarySends = harness.sdk
.callsTo("threads.send")
.filter(
([call]) =>
(call as { threadId: string }).threadId === "thread-primary",
);
expect(primarySends).toHaveLength(1);
expect(primarySends[0]?.[0]).toMatchObject({
mode: "queue-if-active",
input: [
expect.objectContaining({
visibility: "agent-only",
text: expect.stringContaining("requested changes"),
}),
],
});
const pending = (await harness.callRpc("pendingAdvice", {
threadId: "thread-primary",
})) as { advice: unknown };
expect(pending.advice).toBeNull();
});
it("auto-continues at most once for a persistent finding chain", async () => {
const { harness, setTimelineSeq } = await loadAutoAdvisor(BLOCKER_OUTPUT);
await harness.setSettings({ autoContinue: true });
const idle = () =>
harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
}),
lastAssistantText: "Done.",
});
await idle();
setTimelineSeq(43);
await idle();
const primarySends = harness.sdk
.callsTo("threads.send")
.filter(
([call]) =>
(call as { threadId: string }).threadId === "thread-primary",
);
expect(primarySends).toHaveLength(1);
});
});
describe("pending finding queue", () => {
const finding = (
severity: "concern" | "blocker",
key: string,
summary: string,
) => `ADVISOR_RESULT
severity: ${severity}
key: ${key}
summary: ${summary}
details:
- Correct ${key}.
resolved: none
END_ADVISOR_RESULT`;
it("carries every queued finding into the next turn and marks each sent", async () => {
const { harness, setTimelineSeq, setAdvisorOutput } = await loadAutoAdvisor(
finding("blocker", "first-open", "First queued finding"),
);
const idle = (text: string) =>
harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
}),
lastAssistantText: text,
});
await idle("First turn.");
setTimelineSeq(43);
setAdvisorOutput(
finding("concern", "second-open", "Second queued finding"),
);
await idle("Second turn.");
const nextTurn = await harness.resolveAgentConfiguration(primaryContext);
expect(nextTurn.instructions).toContain("First queued finding");
expect(nextTurn.instructions).toContain("Second queued finding");
const panel = (await harness.callRpc("threadReviews", {
threadId: "thread-primary",
})) as { reviews: { summary: string; sentAt: number | null }[] };
expect(
panel.reviews
.filter((review) => review.summary.includes("queued finding"))
.map((review) => review.sentAt),
).toEqual([expect.any(Number), expect.any(Number)]);
const followingTurn = await harness.resolveAgentConfiguration(primaryContext);
expect(followingTurn.instructions).not.toContain("queued finding");
});
it("does not bulk-retire an older finding when a tool review returns another", async () => {
const { harness, setTimelineSeq, setAdvisorOutput } = await loadAutoAdvisor(
finding("blocker", "older-open", "Older queued finding"),
);
await harness.emitThreadEvent("thread.idle", {
thread: makeThreadResponse({
id: "thread-primary",
visibility: "visible",
}),
lastAssistantText: "First turn.",
});
setTimelineSeq(43);
setAdvisorOutput(
finding("concern", "current-tool", "Current tool finding"),
);
expect(
await harness.callAgentTool(
"advisor_review",
{ focus: "Review current work." },
{ threadId: "thread-primary" },
),
).toContain("Current tool finding");
const pending = (await harness.callRpc("pendingAdvice", {
threadId: "thread-primary",
})) as { advice: { summary: string } | null };
expect(pending.advice?.summary).toBe("Older queued finding");
const nextTurn = await harness.resolveAgentConfiguration(primaryContext);
expect(nextTurn.instructions).toContain("Older queued finding");
});
});
describe("repeated advice", () => {
it("keeps the severity of an unresolved repeat instead of passing it", async () => {
const { harness, setTimelineSeq } = await loadAdvisor(BLOCKER_OUTPUT);
const first = await harness.callAgentTool(
"advisor_review",
{ focus: "First review." },
{ threadId: "thread-primary" },
);
setTimelineSeq(43);
const second = await harness.callAgentTool(
"advisor_review",
{ focus: "Second review after ignoring the advice." },
{ threadId: "thread-primary" },
);
expect(first).toContain("Advisor blocker: The claimed test did not run");
expect(second).toContain("Advisor blocker: The claimed test did not run");
expect(second).not.toContain("Advisor pass");
expect(second).toContain("still unresolved");
});
});
describe("advisor session environment binding", () => {
it("falls back to accept-edits on a bb without a read-only mode", async () => {
// The mode is negotiated, not pinned: pinning read-only would report every
// review unavailable on a bb that predates it.
const { harness, spawn } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub("providers.models", async () => ({
providers: [
{
id: "codex",
displayName: "Codex",
available: true,
capabilities: {
supportedPermissionModes: ["accept-edits", "auto", "full"],
},
},
],
models: [],
modelLoadError: null,
}));
await harness.callAgentTool(
"advisor_review",
{ focus: "Review on a bb without read-only." },
{ threadId: "thread-primary" },
);
expect(spawn).toHaveBeenCalledWith(
expect.objectContaining({ permissionMode: "accept-edits" }),
);
});
it("respawns the reviewer once a narrower mode becomes available", async () => {
// Reusing the old session after a bb upgrade would quietly keep the
// reviewer's workspace write access.
let modes = ["accept-edits", "auto", "full"];
const { harness, spawn, setTimelineSeq } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub("providers.models", async () => ({
providers: [
{
id: "codex",
displayName: "Codex",
available: true,
capabilities: { supportedPermissionModes: modes },
},
],
models: [],
modelLoadError: null,
}));
await harness.callAgentTool(
"advisor_review",
{ focus: "Before the upgrade." },
{ threadId: "thread-primary" },
);
expect(spawn).toHaveBeenCalledTimes(1);
modes = ["readonly", "accept-edits", "auto", "full"];
setTimelineSeq(43);
await harness.callAgentTool(
"advisor_review",
{ focus: "After the upgrade." },
{ threadId: "thread-primary" },
);
expect(spawn).toHaveBeenCalledTimes(2);
expect(spawn).toHaveBeenLastCalledWith(
expect.objectContaining({ permissionMode: "readonly" }),
);
});
it("probes narrowest-first when the catalog cannot be read", async () => {
// A transient catalog outage must not disable reviews, and must not
// silently hand the reviewer a wider mode than the host would have.
const attempted: string[] = [];
const { harness } = await loadAdvisor(BLOCKER_OUTPUT);
harness.sdk.stub("providers.models", async () => {
throw new Error("catalog unavailable");
});
harness.sdk.stub("threads.spawn", async (args: { permissionMode: string }) => {
attempted.push(args.permissionMode);
if (args.permissionMode === "readonly") {
throw new Error("unsupported permission mode");
}
return makeThreadResponse({
id: "thread-advisor",
projectId: "project-test",
environmentId: "environment-test",
providerId: "codex",
originPluginId: "advisor",
visibility: "hidden",
status: "active",
});
});
await harness.callAgentTool(
"advisor_review",
{ focus: "Review during a catalog outage." },
{ threadId: "thread-primary" },
);
// Read-only was asked for first and only refused, never assumed away.
expect(attempted).toEqual(["readonly", "accept-edits"]);
});
it("respawns the reviewer when the primary thread changes environment", async () => {
const { harness, spawn, setTimelineSeq } = await loadAdvisor(BLOCKER_OUTPUT);
await harness.callAgentTool(
"advisor_review",
{ focus: "Review in the original environment." },
{ threadId: "thread-primary" },
);
expect(spawn).toHaveBeenCalledTimes(1);
await harness.resolveAgentConfiguration({
...primaryContext,
environment: { ...primaryContext.environment, id: "environment-moved" },