-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
2534 lines (2407 loc) · 88.8 KB
/
Copy pathserver.ts
File metadata and controls
2534 lines (2407 loc) · 88.8 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 { z } from "zod";
import { defineRpcContract } from "@bb/plugin-sdk";
import type {
BbPluginApi,
PluginAgentConfigurationContext,
} from "@bb/plugin-sdk";
import {
formatReview,
formatTimelineRows,
meetsThreshold,
normalizeAdvice,
parseAdvisorOutput,
strongerSeverity,
type AdvisorFinding,
type AdvisorSeverity,
} from "./src/review.js";
const PLUGIN_ID = "advisor";
const ADVISOR_TOOL = "advisor_review";
const ADVISOR_TITLE_PREFIX = "Advisor · ";
/**
* Permission modes the reviewer will accept, least privileged first. The mode
* is negotiated against what the provider actually advertises rather than
* hardcoded, because bb only gained a real `readonly` mode recently: pinning
* it would make every review report unavailable on a bb that predates it,
* while pinning `accept-edits` would keep handing the reviewer workspace write
* access forever on a bb that has something narrower. Picking the value out of
* the provider's own `supportedPermissionModes` also keeps this typed on both
* versions without a cast.
*/
const ADVISOR_PERMISSION_MODE_PREFERENCE = ["readonly", "accept-edits"];
const ADVISOR_PERMISSION_MODE_LABEL = "read-only (or accept-edits) mode";
/** The host's own permission-mode union, whichever bb version is running. */
type AdvisorPermissionMode = NonNullable<
Parameters<BbPluginApi["sdk"]["threads"]["spawn"]>[0]["permissionMode"]
>;
/** Advice about a turn this old is stale; it is retired instead of injected. */
const PENDING_ADVICE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const CANCELLED_REASON =
"the primary turn was cancelled before the review finished";
/**
* Advice must carry this much normalized text before it can join a repeat
* chain. Chaining is text equality, so a terse generic line ("rename the
* helper") could otherwise collide with an unrelated later finding — and, since
* a repeat inherits the chain's strongest severity, hand it a blocker it never
* earned. Long identical text is the same advice; short identical text is not.
*/
const MIN_CHAINABLE_ADVICE_LENGTH = 40;
/** Keeps the closable-findings list in the prompt bounded on a long thread. */
const MAX_PROMPTED_OPEN_FINDINGS = 20;
/** Bound one turn's carried advice without dropping later queued findings. */
const MAX_PENDING_ADVICE_PER_TURN = 20;
/** Per-thread cap so a persistently failing advisor cannot grow the table forever. */
const MAX_INCIDENTS_PER_THREAD = 50;
const reasoningLevelSchema = z.enum([
"none",
"low",
"medium",
"high",
"xhigh",
"ultracode",
"max",
"ultra",
]);
const savedReasoningLevelSchema = z.union([
z.literal("default"),
reasoningLevelSchema,
]);
type ReasoningLevel = z.infer<typeof reasoningLevelSchema>;
const modelIdentitySchema = z
.object({
providerId: z.string().min(1),
model: z.string().min(1),
})
.strict();
const modelSelectionSchema = modelIdentitySchema.extend({
reasoningLevel: savedReasoningLevelSchema,
});
const modelOptionSchema = modelIdentitySchema.extend({
providerName: z.string(),
modelName: z.string(),
isDefault: z.boolean(),
supportedReasoningLevels: z.array(reasoningLevelSchema),
defaultReasoningLevel: reasoningLevelSchema,
});
const hostModelConfigurationSchema = z.object({
hostId: z.string(),
hostName: z.string(),
connected: z.boolean(),
selection: modelSelectionSchema.nullable(),
options: z.array(modelOptionSchema),
error: z.string().nullable(),
});
const modelConfigurationOutputSchema = z.object({
hosts: z.array(hostModelConfigurationSchema),
});
export type ModelConfiguration = z.infer<
typeof modelConfigurationOutputSchema
>;
const severitySchema = z.enum(["pass", "nit", "concern", "blocker"]);
/** '' is a finding resolved before decisions were recorded. */
const decisionSchema = z.enum(["", "fixed", "not-an-issue", "wont-fix"]);
// `fixed` remains readable for legacy rows, but new user actions cannot write
// it. A fix becomes fact only when a later Advisor round closes the chain.
const userDecisionSchema = z.enum(["not-an-issue", "wont-fix"]);
const SEVERITY_RANK: Record<AdvisorSeverity, number> = {
pass: 0,
nit: 1,
concern: 2,
blocker: 3,
};
const threadTargetSchema = z.object({ threadId: z.string().min(1) }).strict();
/**
* One repeat chain collapsed to its latest round. `repeatCount` > 1 means the
* same advice was given again and is still unresolved.
*/
const panelReviewSchema = z.object({
id: z.number().int(),
/**
* Stable across repeat rounds. The row `id` moves to the newest round, so
* keying UI state on it collapses whatever the user had open the moment the
* advisor re-flags the finding they were reading.
*/
chainId: z.number().int(),
severity: severitySchema,
summary: z.string(),
details: z.string(),
sourceSeq: z.number().int(),
createdAt: z.number(),
providerId: z.string(),
model: z.string(),
reasoningLevel: z.string(),
repeatCount: z.number().int(),
firstSourceSeq: z.number().int(),
/** When the finding was first raised, for a human-readable "first flagged". */
firstCreatedAt: z.number(),
advisorThreadId: z.string().nullable(),
resolvedAt: z.number().nullable(),
resolvedReason: z.string(),
/** When the finding's text actually reached the primary agent. */
sentAt: z.number().nullable(),
decision: decisionSchema,
/** Set when the advisor itself re-checked the finding and closed it. */
closedAt: z.number().nullable(),
closedSeq: z.number().int().nullable(),
/** This exact review round already started a corrective follow-up turn. */
continuedAt: z.number().nullable(),
});
/** A review that never happened. Kept apart from verdicts on purpose. */
const incidentSchema = z.object({
id: z.number().int(),
reason: z.string(),
sourceSeq: z.number().int(),
createdAt: z.number(),
});
const pendingAdviceSchema = z.object({
id: z.number().int(),
severity: severitySchema,
summary: z.string(),
details: z.string(),
repeatCount: z.number().int(),
});
const reviewLifecycleSchema = z.enum([
"unreviewed",
"waiting",
"pending",
"approved",
"changes-requested",
"decided",
"unavailable",
]);
export const rpcContract = defineRpcContract({
modelConfiguration: {
input: z.null(),
output: modelConfigurationOutputSchema,
},
threadReviews: {
input: threadTargetSchema,
output: z.object({
reviews: z.array(panelReviewSchema),
incidents: z.array(incidentSchema),
advisorThreadId: z.string().nullable(),
reviewing: z.boolean(),
lifecycle: reviewLifecycleSchema,
}),
},
threadBadge: {
input: threadTargetSchema,
output: z.object({
open: z
.object({
chainId: z.number().int(),
severity: severitySchema,
summary: z.string(),
repeatCount: z.number().int(),
})
.nullable(),
latest: z
.object({
severity: severitySchema,
summary: z.string(),
repeatCount: z.number().int(),
})
.nullable(),
unavailableCount: z.number().int(),
/** The most recent thing that happened was a failed review, not a verdict. */
latestIsUnavailable: z.boolean(),
latestUnavailableReason: z.string().nullable(),
reviewing: z.boolean(),
lifecycle: reviewLifecycleSchema,
}),
},
pendingAdvice: {
input: threadTargetSchema,
output: z.object({ advice: pendingAdviceSchema.nullable() }),
},
/**
* Checked on demand rather than for every listed review: a reviewer thread
* can be deleted, and embedding a chat for a thread that is gone shows the
* host's raw failure inside the panel.
*/
reviewerThreadAvailable: {
input: z
.object({
// Scoped: without the owning thread this would probe the existence of
// any thread id the caller cares to guess.
threadId: z.string().min(1),
advisorThreadId: z.string().min(1),
})
.strict(),
output: z.object({ available: z.boolean() }),
},
dismissAdvice: {
input: z
.object({
threadId: z.string().min(1),
// Required: dismissing by thread alone would retire a newer finding
// that arrived after the banner rendered and was never seen.
adviceId: z.number().int(),
})
.strict(),
output: z.object({ ok: z.literal(true), dismissed: z.boolean() }),
},
resolveFinding: {
input: z
.object({
threadId: z.string().min(1),
chainId: z.number().int(),
resolved: z.boolean(),
reason: z.string().max(500).default(""),
decision: userDecisionSchema.default("not-an-issue"),
})
.strict(),
output: z.object({
ok: z.literal(true),
resolved: z.boolean(),
}),
},
requestReview: {
input: threadTargetSchema,
output: z.object({ started: z.boolean(), waiting: z.boolean() }),
},
continueFinding: {
input: z
.object({
threadId: z.string().min(1),
reviewId: z.number().int(),
})
.strict(),
output: z.object({
started: z.boolean(),
reason: z.enum(["started", "already-started", "not-open"]),
}),
},
setHostModel: {
input: z
.object({
hostId: z.string().min(1),
selection: modelSelectionSchema.nullable(),
})
.strict(),
output: z.object({ ok: z.literal(true) }),
},
});
const reviewRowSchema = z.object({
id: z.number().int(),
primary_thread_id: z.string(),
source_seq: z.number().int().nonnegative(),
severity: z.enum(["pass", "nit", "concern", "blocker"]),
summary: z.string(),
details: z.string(),
normalized: z.string(),
created_at: z.number(),
delivered_at: z.number().nullable(),
repeat_of: z.number().int().nullable(),
provider_id: z.string(),
model: z.string(),
reasoning_level: z.string(),
advisor_thread_id: z.string(),
finding_key: z.string(),
resolved_at: z.number().nullable(),
resolved_reason: z.string(),
sent_at: z.number().nullable(),
closed_at: z.number().nullable(),
closed_seq: z.number().int().nullable(),
decision: decisionSchema,
continued_at: z.number().nullable(),
auto_continued_at: z.number().nullable(),
});
const incidentRowSchema = z.object({
id: z.number().int(),
source_seq: z.number().int(),
reason: z.string(),
created_at: z.number(),
});
type ReviewRow = z.infer<typeof reviewRowSchema>;
const chainRootRowSchema = z.object({
id: z.number().int(),
severity: z.enum(["pass", "nit", "concern", "blocker"]),
resolved_at: z.number().nullable(),
resolved_reason: z.string(),
closed_at: z.number().nullable(),
closed_seq: z.number().int().nullable(),
decision: decisionSchema,
auto_continued_at: z.number().nullable(),
});
const sessionRowSchema = z.object({
advisor_thread_id: z.string(),
provider_id: z.string(),
model: z.string(),
reasoning_level: z.string(),
environment_id: z.string(),
permission_mode: z.string(),
});
const hostModelRowSchema = z.object({
host_id: z.string(),
provider_id: z.string(),
model: z.string(),
reasoning_level: savedReasoningLevelSchema,
});
interface PrimaryContext {
projectId: string;
providerId: string;
model: string;
environmentId: string;
hostId: string;
}
interface RuntimeSettings {
enabled: boolean;
autoReview: boolean;
autoContinue: boolean;
advisorReasoning: "inherit" | "low" | "medium" | "high" | "xhigh";
severityThreshold: AdvisorSeverity;
watchdogFile: string;
timeoutSeconds: number;
transcriptSize: number;
}
const TIMEOUT_OPTIONS = [
["30 seconds", "30", 30],
["1 minute", "60", 60],
["2 minutes", "120", 120],
["5 minutes", "300", 300],
["10 minutes", "600", 600],
] as const;
const TRANSCRIPT_OPTIONS = [
["20,000 characters", "20000", 20_000],
["60,000 characters", "60000", 60_000],
["120,000 characters", "120000", 120_000],
] as const;
/**
* Every string the host may hand back for a numeric select: the readable
* labels first, then the legacy numeric values this plugin used to persist.
*
* The legacy entries are load-bearing, not clutter. The host reads stored
* settings in apps/server/src/services/plugins/plugin-settings.ts and discards
* any select value missing from `options`, substituting `descriptor.default`
* before `settings.get()` ever returns it. Dropping "30" from this list would
* therefore not fall through to `numericSetting`'s legacy mapping — it would
* silently reset an existing 30-second timeout to two minutes.
*/
function selectOptions(
options: readonly (readonly [label: string, legacy: string, value: number])[],
): string[] {
return [
...options.map(([label]) => label),
...options.map(([, legacy]) => legacy),
];
}
function numericSetting(
options: readonly (readonly [label: string, legacy: string, value: number])[],
fallback: number,
) {
const values = new Map(
options.flatMap(([label, legacy, value]) => [
[label, value] as const,
[legacy, value] as const,
]),
);
return z.unknown().transform((value) =>
typeof value === "string" ? (values.get(value) ?? fallback) : fallback,
);
}
const runtimeSettingsSchema: z.ZodType<RuntimeSettings> = z.object({
enabled: z.boolean(),
autoReview: z.boolean(),
autoContinue: z.boolean(),
advisorReasoning: z.enum(["inherit", "low", "medium", "high", "xhigh"]),
severityThreshold: z.enum(["pass", "nit", "concern", "blocker"]),
watchdogFile: z.string(),
timeoutSeconds: numericSetting(TIMEOUT_OPTIONS, 120),
transcriptSize: numericSetting(TRANSCRIPT_OPTIONS, 60_000),
});
export function parseRuntimeSettings(value: unknown) {
return runtimeSettingsSchema.parse(value);
}
const REVIEW_COLUMNS = `id, primary_thread_id, source_seq, severity, summary,
details, normalized, created_at, delivered_at, repeat_of,
provider_id, model, reasoning_level, advisor_thread_id,
finding_key, resolved_at, resolved_reason, sent_at, closed_at,
closed_seq, decision, continued_at, auto_continued_at`;
/**
* Newest first by the turn reviewed, not by insertion order: a review of an
* earlier turn can be written after a later one, and it is not "the latest
* verdict".
*/
function byTurnDescending(
left: { source_seq: number; id: number },
right: { source_seq: number; id: number },
): number {
return right.source_seq - left.source_seq || right.id - left.id;
}
/**
* All rounds of one finding share a chain key: the first row's id. `repeat_of`
* always points at that first row, so a chain never forms a longer path.
*/
function chainKeyOf(row: { id: number; repeat_of: number | null }): number {
return row.repeat_of ?? row.id;
}
/**
* The result of asking for a review. An advisor that could not run is
* explicitly `unavailable` rather than a `pass`, so a failure can never read
* as approval.
*/
type AdvisorOutcome =
| { kind: "reviewed"; row: ReviewRow }
| { kind: "unavailable"; reason: string };
/**
* The narrowest mode in {@link ADVISOR_PERMISSION_MODE_PREFERENCE} this
* provider supports, or null when it supports none of them. The value is taken
* from `supported` rather than from the preference list so it stays typed as
* the host's own permission-mode union on whichever bb version is running.
*/
function narrowestReviewMode<Mode extends string>(
supported: readonly Mode[],
): Mode | null {
for (const preferred of ADVISOR_PERMISSION_MODE_PREFERENCE) {
const match = supported.find((mode) => mode === preferred);
if (match !== undefined) return match;
}
return null;
}
/** A model the reviewer can actually be spawned with, or why it cannot be. */
type AdvisorModelResolution =
| {
kind: "ready";
providerId: string;
model: string;
reasoningLevel: ReasoningLevel | null;
/**
* Ordered narrowest-first. Exactly one entry when the catalog answered;
* the whole preference list when it could not be read, in which case the
* spawn itself is the check and each is tried in turn. Never widened
* without evidence that the narrower one was refused.
*/
permissionModeCandidates: readonly string[];
}
| { kind: "unavailable"; reason: string };
function rowToReview(row: ReviewRow): AdvisorFinding {
return {
severity: row.severity,
key: row.finding_key,
summary: row.summary,
details: row.details,
repeatOf: row.repeat_of,
};
}
function formatOutcome(outcome: AdvisorOutcome): string {
if (outcome.kind === "reviewed") return formatReview(rowToReview(outcome.row));
return `Advisor unavailable: ${outcome.reason}. No review was performed, so this is NOT an approval — say plainly that the advisor did not run instead of claiming the work was reviewed.`;
}
function describeError(error: unknown): string {
if (!(error instanceof Error)) return String(error);
if (!("body" in error)) return String(error);
try {
return `${String(error)}; body=${JSON.stringify(error.body)}`;
} catch {
return String(error);
}
}
function reviewBudget(timeoutSeconds: number): {
reserveSeconds: number;
maxInspectionActions: number;
finalizeAfterMs: number;
} {
const reserveSeconds = Math.min(
30,
Math.max(5, Math.ceil(timeoutSeconds / 4)),
);
const inspectionSeconds = Math.max(1, timeoutSeconds - reserveSeconds);
return {
reserveSeconds,
maxInspectionActions: Math.max(
1,
Math.min(6, Math.floor(inspectionSeconds / 15)),
),
finalizeAfterMs: inspectionSeconds * 1000,
};
}
function buildAdvisorPrompt(args: {
primaryThreadId: string;
sourceSeq: number;
transcript: string;
focus: string;
watchdogFile: string;
timeoutSeconds: number;
openFindings: readonly { key: string; summary: string }[];
openFindingsTruncated: boolean;
}): string {
const budget = reviewBudget(args.timeoutSeconds);
return `You are the independent advisor for bb coding thread ${args.primaryThreadId}.
Review the primary agent's work, reasoning summaries, tool activity, and current workspace state. You are a reviewer, not the primary executor. Inspect files with read-only tools when the transcript alone is insufficient.
Before reviewing, try to read ${args.watchdogFile} from the workspace root. If it exists, treat it as project-specific review policy. If it does not exist, continue normally.
Review priorities:
- factual or API mistakes
- missed user requirements
- unsafe, destructive, or overly broad actions
- correctness gaps and untested behavior
- architecture or contract violations
- claims that are not supported by verification
Review budget:
- The host stops this review after ${args.timeoutSeconds} seconds. Finish and emit the structured result before then; reserve the final ${budget.reserveSeconds} seconds for it.
- Do not send progress updates. Your only assistant message must be the final ADVISOR_RESULT block.
- Use the supplied timeline and focus first. Inspect only files needed to verify a concrete risk; do not broadly inventory the workspace.
- Perform at most ${budget.maxInspectionActions} read-only inspection or command actions. Do not rerun broad test suites or builds—the primary agent already owns verification.
- If exhaustive verification would exceed the budget, report the strongest concrete issue you can support, or pass when you found none. Never omit the result format.
Findings you raised earlier on this thread that are still open:
${
args.openFindings.length === 0
? "None."
: args.openFindings
.map((finding) => `- ${finding.key}: ${finding.summary}`)
.join("\n") +
(args.openFindingsTruncated
? "\n- (older open findings omitted)"
: "")
}
If you have re-checked one of those and it is genuinely addressed now, list its key on the "resolved:" line. Only close a key you actually verified in this round: not mentioning a finding never closes it, and you must not close one you did not check. Closing a key that is not listed above does nothing.
Focus supplied by the primary agent:
${args.focus || "No additional focus was supplied."}
Primary timeline through sequence ${args.sourceSeq} (JSONL, oldest selected row first):
${args.transcript}
Return exactly one result in this format. Use pass and silence-equivalent details when there is no actionable issue. Do not repeat old advice merely to have something to say.
ADVISOR_RESULT
severity: pass|nit|concern|blocker
key: a short stable slug naming the defect itself, anchored to where it lives, e.g. server-ts-runreview-timeout-untested. Use the SAME key whenever you raise the same underlying defect again, even if you reword it or rate it differently. Use "none" for a pass.
summary: one concise line
details:
- concrete evidence and a specific correction, or "none"
resolved: comma-separated keys from the open list above that you verified are now fixed, or "none"
END_ADVISOR_RESULT`;
}
export default async function plugin(bb: BbPluginApi) {
const settings = bb.settings.define({
enabled: {
type: "boolean",
label: "Enable advisor",
description: "Require an independent review before an agent completes substantial work.",
default: true,
},
autoReview: {
type: "boolean",
label: "Review completed turns",
description: "Review every completed primary turn and carry late findings into its next turn.",
default: true,
},
autoContinue: {
type: "boolean",
label: "Auto-continue on late findings",
description:
"Start one follow-up turn when a completed-turn review requests changes. Disabled by default to avoid unexpected agent runs.",
default: false,
},
advisorReasoning: {
type: "select",
label: "Fallback advisor reasoning",
description:
"Used only when a machine follows the primary model instead of selecting its own model and reasoning level.",
options: ["inherit", "low", "medium", "high", "xhigh"],
default: "inherit",
},
severityThreshold: {
type: "select",
label: "Minimum severity",
options: ["nit", "concern", "blocker"],
default: "nit",
},
watchdogFile: {
type: "string",
label: "Watchdog file",
description: "Workspace-relative advisor policy file.",
default: "WATCHDOG.md",
},
timeoutSeconds: {
type: "select",
label: "Review timeout",
description:
"Seconds to wait for a review. Exceeding it reports the advisor as unavailable, never as a pass.",
options: selectOptions(TIMEOUT_OPTIONS),
default: "2 minutes",
},
transcriptSize: {
type: "select",
label: "Transcript budget",
options: selectOptions(TRANSCRIPT_OPTIONS),
default: "60,000 characters",
},
});
let currentSettings = parseRuntimeSettings(await settings.get());
settings.onChange((next) => {
currentSettings = parseRuntimeSettings(next);
});
const db = bb.storage.database();
bb.storage.migrate(db, [
`CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS advisor_reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
primary_thread_id TEXT NOT NULL,
source_seq INTEGER NOT NULL,
severity TEXT NOT NULL CHECK (severity IN ('pass', 'nit', 'concern', 'blocker')),
summary TEXT NOT NULL,
details TEXT NOT NULL,
normalized TEXT NOT NULL,
created_at INTEGER NOT NULL,
delivered_at INTEGER,
UNIQUE(primary_thread_id, source_seq)
)`,
`CREATE INDEX IF NOT EXISTS advisor_reviews_pending_idx
ON advisor_reviews(primary_thread_id, delivered_at, id)`,
`CREATE TABLE IF NOT EXISTS advisor_host_models (
host_id TEXT PRIMARY KEY,
provider_id TEXT NOT NULL,
model TEXT NOT NULL,
updated_at INTEGER NOT NULL
)`,
`ALTER TABLE advisor_host_models
ADD COLUMN reasoning_level TEXT NOT NULL DEFAULT 'default'`,
`ALTER TABLE advisor_sessions
ADD COLUMN reasoning_level TEXT NOT NULL DEFAULT 'legacy'`,
`ALTER TABLE advisor_reviews ADD COLUMN repeat_of INTEGER`,
// Legacy sessions carry no environment, so they never match a live one and
// are rebuilt against the primary thread's current environment on first use.
`ALTER TABLE advisor_sessions
ADD COLUMN environment_id TEXT NOT NULL DEFAULT ''`,
// Provenance per review, not per session: "who reviewed this" must survive
// the machine's model selection changing afterwards.
`ALTER TABLE advisor_reviews ADD COLUMN provider_id TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE advisor_reviews ADD COLUMN model TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE advisor_reviews
ADD COLUMN reasoning_level TEXT NOT NULL DEFAULT ''`,
// Reviews that never ran. Deliberately a separate table: an incident must
// never be reachable by any query that treats rows as verdicts.
`CREATE TABLE IF NOT EXISTS advisor_incidents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
primary_thread_id TEXT NOT NULL,
source_seq INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at INTEGER NOT NULL
)`,
`CREATE INDEX IF NOT EXISTS advisor_incidents_thread_idx
ON advisor_incidents(primary_thread_id, id)`,
// Which reviewer thread actually produced this row. The session pointer
// moves when the reviewer is respawned, so it cannot answer that for history.
`ALTER TABLE advisor_reviews
ADD COLUMN advisor_thread_id TEXT NOT NULL DEFAULT ''`,
// The advisor's own identifier for the defect, so a chain survives
// rewording and a changed severity.
`ALTER TABLE advisor_reviews
ADD COLUMN finding_key TEXT NOT NULL DEFAULT ''`,
`CREATE INDEX IF NOT EXISTS advisor_reviews_chain_idx
ON advisor_reviews(primary_thread_id, finding_key)`,
`ALTER TABLE advisor_reviews ADD COLUMN resolved_at INTEGER`,
`ALTER TABLE advisor_reviews ADD COLUMN resolved_reason TEXT NOT NULL DEFAULT ''`,
// The mode is negotiated per review, so a bb upgrade that adds a narrower
// one must retire the wider session instead of reusing it. Legacy rows
// carry '', which matches no negotiated mode and so respawns once.
`ALTER TABLE advisor_sessions
ADD COLUMN permission_mode TEXT NOT NULL DEFAULT ''`,
// When the finding's text actually reached the primary agent. Distinct
// from delivered_at, which only tracks the pending-advice queue and is set
// in bulk, so it cannot back a "sent to the agent" claim.
`ALTER TABLE advisor_reviews ADD COLUMN sent_at INTEGER`,
// Advisor-verified closure, on the chain root. Provisional by design: a
// later round of the same key reopens it, because a finding that comes
// back was a regression, not a closure.
`ALTER TABLE advisor_reviews ADD COLUMN closed_at INTEGER`,
`ALTER TABLE advisor_reviews ADD COLUMN closed_seq INTEGER`,
// What the user decided, so a finding they fixed is distinguishable from
// one they overruled. Rows resolved before this column carry '' and stay
// a plain dismissal rather than being backfilled with a guess.
`ALTER TABLE advisor_reviews ADD COLUMN decision TEXT NOT NULL DEFAULT ''`,
// Manual continuation is idempotent per review round. Automatic
// continuation is capped once per finding chain so a persistent finding
// cannot create an unattended agent/reviewer loop.
`ALTER TABLE advisor_reviews ADD COLUMN continued_at INTEGER`,
`ALTER TABLE advisor_reviews ADD COLUMN auto_continued_at INTEGER`,
]);
const primaryContexts = new Map<string, PrimaryContext>();
const inFlight = new Map<string, Promise<AdvisorOutcome>>();
const reviewingThreads = new Map<string, number>();
/** Manual reviews requested while the primary turn is still active. */
const waitingForCompletion = new Set<string>();
/**
* Primary threads whose current turn already ran a tool review, so the
* post-turn pass would only re-review the same work at a higher sequence.
*/
const toolReviewedThreads = new Set<string>();
// Retire advice that can no longer be delivered: rows older than the window,
// including any left undeliverable by the pre-fix post-turn handler, which
// reviewed other plugins' threads that never consume pending advice.
db.prepare(
`UPDATE advisor_reviews SET delivered_at = ?
WHERE delivered_at IS NULL AND created_at < ?`,
).run(Date.now(), Date.now() - PENDING_ADVICE_MAX_AGE_MS);
// Versions before the persisted queue fix could bulk-mark older findings
// delivered when only a newer tool result reached the agent. A shared
// millisecond with a genuinely sent row identifies that bulk sweep without
// resurrecting individually dismissed advice.
db.prepare(
`UPDATE advisor_reviews AS stale
SET delivered_at = NULL
WHERE stale.sent_at IS NULL
AND stale.severity != 'pass'
AND stale.delivered_at IS NOT NULL
AND EXISTS (
SELECT 1 FROM advisor_reviews AS sent
WHERE sent.primary_thread_id = stale.primary_thread_id
AND sent.delivered_at = stale.delivered_at
AND sent.sent_at IS NOT NULL
)`,
).run();
/**
* Tell every open client that this thread's advisor state moved. The payload
* is only an invalidation hint — surfaces refetch over rpc rather than trust
* an ephemeral broadcast that a reconnecting client may have missed.
*/
function publishThreadChanged(primaryThreadId: string): void {
bb.realtime.publish("thread-changed", { threadId: primaryThreadId });
}
function readChainRoot(
primaryThreadId: string,
chainId: number,
): z.infer<typeof chainRootRowSchema> | null {
const parsed = chainRootRowSchema.safeParse(
db
.prepare(
`SELECT id, severity, resolved_at, resolved_reason, closed_at,
closed_seq, decision, auto_continued_at
FROM advisor_reviews
WHERE primary_thread_id = ? AND id = ? AND repeat_of IS NULL`,
)
.get(primaryThreadId, chainId),
);
return parsed.success ? parsed.data : null;
}
/**
* Settled from either direction: the user decided it, or the advisor
* re-checked and closed it. Both keep a finding out of the badge and out of
* the next turn's instructions.
*/
function chainIsResolved(row: ReviewRow): boolean {
const root = readChainRoot(row.primary_thread_id, chainKeyOf(row));
if (!root) return false;
return root.resolved_at !== null || root.closed_at !== null;
}
function isReviewing(primaryThreadId: string): boolean {
return (reviewingThreads.get(primaryThreadId) ?? 0) > 0;
}
function beginReview(primaryThreadId: string): void {
const current = reviewingThreads.get(primaryThreadId) ?? 0;
reviewingThreads.set(primaryThreadId, current + 1);
if (current === 0) publishThreadChanged(primaryThreadId);
}
function endReview(primaryThreadId: string): void {
const current = reviewingThreads.get(primaryThreadId) ?? 0;
if (current <= 1) {
reviewingThreads.delete(primaryThreadId);
publishThreadChanged(primaryThreadId);
return;
}
reviewingThreads.set(primaryThreadId, current - 1);
}
function recordIncident(
primaryThreadId: string,
sourceSeq: number,
reason: string,
): void {
db.prepare(
`INSERT INTO advisor_incidents (
primary_thread_id, source_seq, reason, created_at
) VALUES (?, ?, ?, ?)`,
).run(primaryThreadId, sourceSeq, reason, Date.now());
// An advisor that fails every turn would otherwise grow this table without
// bound; only the most recent failures are diagnostically useful.
db.prepare(
`DELETE FROM advisor_incidents
WHERE primary_thread_id = ? AND id NOT IN (
SELECT id FROM advisor_incidents
WHERE primary_thread_id = ? ORDER BY id DESC LIMIT ?
)`,
).run(primaryThreadId, primaryThreadId, MAX_INCIDENTS_PER_THREAD);
publishThreadChanged(primaryThreadId);
}
function readReview(primaryThreadId: string, sourceSeq: number): ReviewRow | null {
const parsed = reviewRowSchema.safeParse(
db
.prepare(
`SELECT ${REVIEW_COLUMNS}
FROM advisor_reviews
WHERE primary_thread_id = ? AND source_seq = ?`,
)
.get(primaryThreadId, sourceSeq),
);
return parsed.success ? parsed.data : null;
}
/**
* Record that this finding's text actually reached the primary agent. Only
* the two moments that genuinely hand it over call this — the tool result
* and the injected instruction — so "sent to the agent" stays a fact rather
* than an artefact of the pending-advice sweep.
*/
function markSent(rowId: number): void {
db.prepare(
`UPDATE advisor_reviews SET sent_at = ? WHERE id = ? AND sent_at IS NULL`,
).run(Date.now(), rowId);
}
function readPendingAdvice(primaryThreadId: string): ReviewRow[] {
return db
.prepare(
`SELECT ${REVIEW_COLUMNS}
FROM advisor_reviews
WHERE primary_thread_id = ?
AND delivered_at IS NULL
AND severity != 'pass'
ORDER BY CASE severity
WHEN 'blocker' THEN 3
WHEN 'concern' THEN 2
WHEN 'nit' THEN 1
ELSE 0 END DESC,
source_seq ASC, id ASC`,
)
.all(primaryThreadId)
.flatMap((candidate) => {
const parsed = reviewRowSchema.safeParse(candidate);
return parsed.success && !chainIsResolved(parsed.data)
? [parsed.data]
: [];
});
}
function markReviewDelivered(rowId: number, sent: boolean): void {
db.prepare(
`UPDATE advisor_reviews SET delivered_at = ?
WHERE id = ? AND delivered_at IS NULL`,
).run(Date.now(), rowId);
if (sent) markSent(rowId);
}
function consumePending(primaryThreadId: string): ReviewRow[] {
const rows = readPendingAdvice(primaryThreadId).slice(
0,
MAX_PENDING_ADVICE_PER_TURN,
);
if (rows.length === 0) return [];
db.transaction(() => {
for (const row of rows) markReviewDelivered(row.id, true);
})();
publishThreadChanged(primaryThreadId);
return rows;
}
function rememberContext(context: PluginAgentConfigurationContext): void {
primaryContexts.set(context.thread.id, {
projectId: context.project.id,
providerId: context.provider.id,
model: context.provider.model,
environmentId: context.environment.id,
hostId: context.host.id,
});
}
function readHostModel(hostId: string) {
const parsed = hostModelRowSchema.safeParse(
db
.prepare(
`SELECT host_id, provider_id, model, reasoning_level
FROM advisor_host_models WHERE host_id = ?`,
)
.get(hostId),
);
return parsed.success
? {
providerId: parsed.data.provider_id,
model: parsed.data.model,
reasoningLevel: parsed.data.reasoning_level,
}
: null;
}
async function listHostModelOptions(hostId: string) {
const providers = (await bb.sdk.providers.list({ hostId })).filter(
(provider) =>
provider.available &&
narrowestReviewMode(provider.capabilities.supportedPermissionModes) !==
null,
);
const optionGroups = await Promise.all(
providers.map(async (provider) => {
const catalog = await bb.sdk.providers.models({
hostId,