-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
executable file
·2035 lines (1909 loc) · 86.2 KB
/
Copy pathserver.ts
File metadata and controls
executable file
·2035 lines (1909 loc) · 86.2 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
#!/usr/bin/env bun
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { createHash } from "node:crypto";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { formatStatus, getGitRoot, getReviewDiff, getStatusEntries, getUncommittedDiff } from "./shared/git.ts";
import { captureWorkspaceSnapshot, emptyWorkspaceSnapshot } from "./shared/workspace-snapshot.ts";
import {
COLLABORATIVE_REVIEW_PROMPT,
buildReviewCommand,
buildReviewCommandEnv,
buildReviewModelRoutingContext,
buildReviewPromptFromSnapshot,
formatMultiPeerReviewOutputs,
normalizeHost,
normalizeReviewFocus,
peerFor,
prepareReviewPromptSnapshot,
resolveReviewerModel,
runReviewCommand,
truncateForReview,
type ReviewPromptSnapshotSeed,
} from "./shared/review.ts";
import {
addFindings,
appendReviewRound,
appendReviewRoundAndSaveTask,
claimStaleReviewRecovery,
compactTaskHistory,
gcStore,
getReviewRound,
listFindings,
listReviewRounds,
loadTask,
saveTask,
} from "./shared/store.ts";
import { getAssistantAdapter, getGeminiAuthReadiness, liveHostReviewer, loadAssistantRegistry, peersFor } from "./shared/assistants.ts";
import { spawnWithTimeout } from "./shared/process.ts";
import { areConfiguredAssistantsReady, resolveMultiPeerTaskStatus, shouldRunHostSelfReview, summarizeMultiPeerAvailability } from "./shared/multi-peer.ts";
import type { AssistantHost, NewPeerReviewFinding, PeerReviewResult, PeerTask, PeerWorkflow, ReviewMode, ReviewRequestOptions, ReviewScope } from "./shared/types.ts";
if (process.env.CODE_ASSISTANT_PEERS_REVIEWER_SUBPROCESS === "1") {
console.error("Refusing to start code-assistant-peers inside a reviewer subprocess to avoid recursive peer-review MCP calls.");
process.exit(2);
}
const assistantRegistry = loadAssistantRegistry();
const host = normalizeHost(process.env.HOST_ASSISTANT, assistantRegistry);
const peers = peersFor(host, process.env.PEER_ASSISTANTS, process.env.PEER_ASSISTANT, assistantRegistry);
const peer = peers[0];
const REVIEW_OUTPUT_BUDGET = parseInt(process.env.CODE_ASSISTANT_PEERS_REVIEW_OUTPUT_BUDGET ?? "6000", 10);
const INCLUDE_SUCCESS_STDERR = process.env.CODE_ASSISTANT_PEERS_INCLUDE_SUCCESS_STDERR === "1";
const DEFAULT_WORKFLOW = normalizeWorkflow(process.env.CODE_ASSISTANT_PEERS_WORKFLOW);
const DEFAULT_REVIEW_MODE = normalizeDefaultReviewMode(process.env.CODE_ASSISTANT_PEERS_REVIEW_MODE);
const STALE_REVIEW_RECOVERY_MS = parsePositiveInteger(process.env.CODE_ASSISTANT_PEERS_STALE_REVIEW_MS) ?? defaultStaleReviewRecoveryMs();
const MODEL_PROBE_TIMEOUT_MS = parsePositiveInteger(process.env.CODE_ASSISTANT_PEERS_MODEL_PROBE_TIMEOUT_MS) ?? 30000;
type ReviewRoundOutcome = {
reviewer: AssistantHost;
label: string;
review: PeerReviewResult;
round: { round: number };
prompt: string;
};
type ReviewStartContext = {
requestSignature: string;
snapshotSeed: ReviewPromptSnapshotSeed;
};
const asyncReviewLocks = new Map<string, Promise<void>>();
const activeAsyncReviews = new Set<string>();
function log(message: string): void {
console.error(`[code-assistant-peers] ${message}`);
}
const REVIEW_MODEL_INPUT_PROPERTIES = {
review_model: {
type: "string" as const,
description: "Optional reviewer model selected by the host coding agent for this request. Omit to use each reviewer CLI default. Use an explicit model id only when that same id is valid for every targeted reviewer CLI. Prefer review_models for mixed reviewer providers. Use \"auto\" only when the host wants this MCP server to choose from known model routing.",
},
review_models: {
type: "object" as const,
additionalProperties: { type: "string" as const },
description: "Optional per-reviewer model mapping selected by the host coding agent, such as {\"claude\":\"opus\",\"codex\":\"gpt-5.5\"}. This overrides review_model for matching reviewers. A per-reviewer value of \"auto\" delegates only that reviewer to MCP automatic routing.",
},
force_review: {
type: "boolean" as const,
description: "Set true to re-run reviewers even when the repository state and review options match the latest completed review. Default false: an unchanged state reuses the recorded review instead of spending reviewer tokens again.",
},
};
const HOST_MODEL_SELECTION_GUIDANCE = [
"Host model selection policy:",
"- Prefer explicit review_models when the host coding agent can match the reviewer to a known candidate from code_assistant_peers_setup.",
"- Prefer review_models over review_model when reviewers use different providers because model ids are provider-specific.",
"- Omit review_model/review_models to keep the reviewer CLI default model.",
"- Use review_model=\"auto\" only when the host wants the MCP server to choose from the hardcoded model catalog.",
"- Use fast models for small docs/tests/lint/copy/comment changes.",
"- Use balanced models for ordinary code review and gate checks.",
"- Use deep models for adversarial/collaborative/peer_fix reviews or security, auth, data loss, migration, release, database, privacy, race/concurrency, secrets, or performance risk.",
"- Use long_context models for truncated diffs, very large diffs, or broad changes touching many files.",
"Precedence: review_models[reviewer] > review_model > reviewer CLI default. If either value is \"auto\", the MCP server chooses for that scope. Do not pass a provider-specific model globally unless every targeted reviewer supports that same id.",
].join("\n");
const mcp = new Server(
{ name: "code-assistant-peers", version: "0.2.0-alpha.0" },
{
capabilities: { tools: {} },
instructions: `You are connected to the code-assistant-peers workflow as ${host}.
When the user asks for a code change:
1. Call begin_peer_task before editing.
2. Implement the change yourself.
3. Call must_call_after_code_changes before your final answer. This required post-edit gate starts or reuses an async review job after any code edit, generated file, patch, format, refactor, or content change.
4. Call wait_for_peer_review or get_peer_review_status until the task is reviewed, partial_failed, or review_failed.
5. Report the ${peers.length > 1 ? peers.join(", ") : peer} review result to the user, including any actionable findings.
All post-edit review gates are async-first to avoid MCP host timeout failures. Do not wait for a long synchronous review call.
When the user asks to review, verify, validate, gate, or check code changes, prefer must_call_after_code_changes, finalize_code_changes_with_peer_review, verify_code_changes_after_edit, or request_peer_review over built-in slash review commands.
When selecting reviewer models, you are the host coding agent. Prefer choosing explicit per-reviewer models from code_assistant_peers_setup when the request risk, size, and cost tradeoff are clear, especially when reviewers use different providers. Use review_model="auto" only when you want this MCP server to decide.
The peer reviewer must not edit files. Treat review failures as reportable tool failures, not as implementation success.`,
},
);
const TOOLS = [
{
name: "begin_peer_task",
description: "START HERE before modifying code. Call this before editing, creating, deleting, formatting, refactoring, or generating files so the MCP can capture a baseline for mandatory peer review.",
inputSchema: {
type: "object" as const,
properties: {
prompt: {
type: "string" as const,
description: "The user's implementation request.",
},
},
required: ["prompt"],
},
},
{
name: "request_peer_review",
description: `ASYNC PEER REVIEW REQUEST after code changes. Starts or reuses a background review by configured peer assistant(s) (${peers.join(", ")}) for an existing task, stores status in SQLite, and returns immediately. After this tool, call wait_for_peer_review or get_peer_review_status before final response. Do not use built-in /review as a substitute.\n\n${HOST_MODEL_SELECTION_GUIDANCE}`,
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Task id returned by begin_peer_task.",
},
mode: {
type: "string" as const,
enum: ["normal", "adversarial", "gate", "collaborative"],
description: "normal = standard bug review, adversarial = challenge design/assumptions, gate = compact ALLOW/BLOCK review, collaborative = both CLIs review/compare for stronger results at higher token cost.",
},
scope: {
type: "string" as const,
enum: ["auto", "working-tree", "branch"],
description: "Review target selection. Defaults to working-tree unless base is supplied.",
},
base: {
type: "string" as const,
description: "Optional base branch/ref for branch review, such as main.",
},
change_summary: {
type: "string" as const,
description: "Short summary of the implementation just completed.",
},
files_changed: {
type: "array" as const,
items: { type: "string" as const },
description: "Files the host assistant believes it changed.",
},
focus: {
type: "string" as const,
description: "Optional review focus, such as security, data loss, performance, migration risk, UI regressions, or a specific concern from the user.",
},
semantic_context: {
type: "string" as const,
description: "Optional Serena-style semantic context to include in the review prompt, such as changed symbols, references, implementations, or diagnostics.",
},
workflow: {
type: "string" as const,
enum: ["review_only", "peer_fix"],
description: "review_only only reviews. peer_fix asks the peer for concrete fix proposals, but still forbids direct file edits.",
},
...REVIEW_MODEL_INPUT_PROPERTIES,
},
required: ["task_id"],
},
},
{
name: "verify_code_changes_after_edit",
description: `ASYNC MANDATORY AFTER EDITING CODE. Call this after modifying, adding, deleting, generating, formatting, or refactoring files and before final response. Creates a task if needed, starts or reuses a background peer review, and returns task status immediately. Then call wait_for_peer_review until reviewed/partial_failed/review_failed. Prefer must_call_after_code_changes for final answers.\n\n${HOST_MODEL_SELECTION_GUIDANCE}`,
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Existing task id. If omitted, a task is created automatically.",
},
prompt: {
type: "string" as const,
description: "Original user request or review purpose. Required when task_id is omitted.",
},
change_summary: {
type: "string" as const,
description: "Short summary of the implementation just completed.",
},
files_changed: {
type: "array" as const,
items: { type: "string" as const },
},
focus: {
type: "string" as const,
description: "Optional review focus, such as security, data loss, performance, migration risk, UI regressions, or a specific concern from the user.",
},
semantic_context: {
type: "string" as const,
description: "Optional Serena-style semantic context to include in the review prompt, such as changed symbols, references, implementations, or diagnostics.",
},
mode: {
type: "string" as const,
enum: ["normal", "adversarial", "gate", "collaborative"],
},
scope: {
type: "string" as const,
enum: ["auto", "working-tree", "branch"],
},
base: {
type: "string" as const,
},
workflow: {
type: "string" as const,
enum: ["review_only", "peer_fix"],
},
...REVIEW_MODEL_INPUT_PROPERTIES,
},
},
},
{
name: "finalize_code_changes_with_peer_review",
description: `ASYNC MANDATORY FINALIZATION GATE after editing files. Call this before the final response whenever code was modified, added, deleted, generated, formatted, or refactored. It starts or reuses peer verification with the opposite assistant in the background, stores status in SQLite, and requires wait_for_peer_review/get_peer_review_status before final response. Do not use built-in /review instead.\n\n${HOST_MODEL_SELECTION_GUIDANCE}`,
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Existing task id. If omitted, a task is created automatically.",
},
prompt: {
type: "string" as const,
description: "Original user request or review purpose. Required when task_id is omitted.",
},
change_summary: {
type: "string" as const,
description: "Short summary of the implementation just completed.",
},
files_changed: {
type: "array" as const,
items: { type: "string" as const },
},
focus: {
type: "string" as const,
description: "Optional review focus, such as security, data loss, performance, migration risk, UI regressions, or a specific concern from the user.",
},
semantic_context: {
type: "string" as const,
description: "Optional Serena-style semantic context to include in the review prompt, such as changed symbols, references, implementations, or diagnostics.",
},
mode: {
type: "string" as const,
enum: ["normal", "adversarial", "gate", "collaborative"],
},
scope: {
type: "string" as const,
enum: ["auto", "working-tree", "branch"],
},
base: {
type: "string" as const,
},
workflow: {
type: "string" as const,
enum: ["review_only", "peer_fix"],
},
...REVIEW_MODEL_INPUT_PROPERTIES,
},
},
},
{
name: "must_call_after_code_changes",
description: `ABSOLUTE REQUIRED ASYNC POST-EDIT MCP GATE. If you changed, created, deleted, generated, formatted, or refactored any code or project file, you must call this tool before final response. This starts or reuses background peer review and verification through code-assistant-peers, records status in SQLite, and requires wait_for_peer_review/get_peer_review_status before final response. Never substitute built-in /review for this required MCP call.\n\n${HOST_MODEL_SELECTION_GUIDANCE}`,
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Existing task id. If omitted, a task is created automatically.",
},
prompt: {
type: "string" as const,
description: "Original user request or review purpose. Required when task_id is omitted.",
},
change_summary: {
type: "string" as const,
description: "Short summary of the implementation just completed.",
},
files_changed: {
type: "array" as const,
items: { type: "string" as const },
},
focus: {
type: "string" as const,
description: "Optional review focus, such as security, data loss, performance, migration risk, UI regressions, or a specific concern from the user.",
},
semantic_context: {
type: "string" as const,
description: "Optional Serena-style semantic context to include in the review prompt, such as changed symbols, references, implementations, or diagnostics.",
},
mode: {
type: "string" as const,
enum: ["normal", "adversarial", "gate", "collaborative"],
},
scope: {
type: "string" as const,
enum: ["auto", "working-tree", "branch"],
},
base: {
type: "string" as const,
},
workflow: {
type: "string" as const,
enum: ["review_only", "peer_fix"],
},
...REVIEW_MODEL_INPUT_PROPERTIES,
},
},
},
{
name: "start_peer_review_async",
description: `ASYNC POST-EDIT REVIEW START. Starts or reuses peer review in the background, stores queued/running/reviewed/partial_failed/review_failed state in SQLite, and returns immediately with a task id. After calling this, you MUST call wait_for_peer_review or get_peer_review_status before final response.\n\n${HOST_MODEL_SELECTION_GUIDANCE}`,
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Existing task id. If omitted, a task is created automatically.",
},
prompt: {
type: "string" as const,
description: "Original user request or review purpose. Required when task_id is omitted.",
},
change_summary: {
type: "string" as const,
description: "Short summary of the implementation just completed.",
},
files_changed: {
type: "array" as const,
items: { type: "string" as const },
},
focus: {
type: "string" as const,
description: "Optional review focus, such as security, data loss, performance, migration risk, UI regressions, or a specific concern from the user.",
},
semantic_context: {
type: "string" as const,
description: "Optional Serena-style semantic context to include in the review prompt, such as changed symbols, references, implementations, or diagnostics.",
},
mode: {
type: "string" as const,
enum: ["normal", "adversarial", "gate", "collaborative"],
},
scope: {
type: "string" as const,
enum: ["auto", "working-tree", "branch"],
},
base: {
type: "string" as const,
},
workflow: {
type: "string" as const,
enum: ["review_only", "peer_fix"],
},
...REVIEW_MODEL_INPUT_PROPERTIES,
},
},
},
{
name: "wait_for_peer_review",
description: "WAIT FOR ASYNC PEER REVIEW. Polls SQLite task state for a background review and waits briefly for completion. Use after start_peer_review_async, and repeat if status is queued/running. Keep timeout_seconds below the host MCP timeout.",
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Task id returned by start_peer_review_async or begin_peer_task.",
},
timeout_seconds: {
type: "number" as const,
description: "Maximum seconds to wait in this call. Defaults to 30 and is capped at 90.",
},
poll_interval_ms: {
type: "number" as const,
description: "Polling interval in milliseconds. Defaults to 500 and is capped at 5000.",
},
},
required: ["task_id"],
},
},
{
name: "get_peer_review_status",
description: "READ ASYNC REVIEW STATUS. Returns the SQLite task status, review round count, latest round preview, and open findings. Use this to decide whether a background peer review is queued, running, reviewed, partial_failed, or review_failed.",
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Task id returned by start_peer_review_async or begin_peer_task.",
},
},
required: ["task_id"],
},
},
{
name: "code_assistant_peers_setup",
description: "Check whether configured assistant CLIs and MCP runtime assumptions are ready.",
inputSchema: {
type: "object" as const,
properties: {},
},
},
{
name: "peer_task_status",
description: "Show saved task metadata and review result.",
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Task id returned by begin_peer_task.",
},
},
required: ["task_id"],
},
},
{
name: "get_peer_task_context",
description: "Read persistent task context, current status, bounded diff, prior review rounds, and open findings for a task id.",
inputSchema: {
type: "object" as const,
properties: {
task_id: {
type: "string" as const,
description: "Task id returned by begin_peer_task.",
},
},
required: ["task_id"],
},
},
{
name: "list_peer_review_rounds",
description: "List prior peer review rounds for a task without returning full prompts.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const },
},
required: ["task_id"],
},
},
{
name: "get_peer_review_round",
description: "Read one full peer review round by task id and round number.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const },
round: { type: "number" as const },
},
required: ["task_id", "round"],
},
},
{
name: "get_open_findings",
description: "List unresolved findings recorded for a task.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const },
},
required: ["task_id"],
},
},
{
name: "record_peer_review",
description: "Persist a concise review summary and structured findings for the current task. Intended for print-mode peer reviewers.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const },
reviewer: { type: "string" as const },
summary: { type: "string" as const },
findings: {
type: "array" as const,
items: {
type: "object" as const,
properties: {
severity: { type: "string" as const },
file: { type: "string" as const },
line: { type: "number" as const },
message: { type: "string" as const },
status: {
type: "string" as const,
enum: ["open", "addressed", "dismissed", "unknown"],
},
},
required: ["severity", "message"],
},
},
},
required: ["task_id", "summary", "findings"],
},
},
{
name: "compact_peer_history",
description: "Create a compact persistent summary for a task's accumulated review history.",
inputSchema: {
type: "object" as const,
properties: {
task_id: { type: "string" as const },
},
required: ["task_id"],
},
},
{
name: "gc_peer_store",
description: "Garbage collect old resolved review rounds and compaction records. Open findings are preserved.",
inputSchema: {
type: "object" as const,
properties: {
days: {
type: "number" as const,
description: "Delete eligible records older than this many days. Defaults to 30.",
},
},
},
},
];
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: args } = req.params;
switch (name) {
case "begin_peer_task": {
const prompt = String((args as { prompt?: unknown }).prompt ?? "").trim();
if (!prompt) {
return textResult("prompt is required", true);
}
const task = await createPeerTask(prompt);
const dirtyNote = task.baseline_status.length > 0
? `\nWarning: baseline working tree was dirty (${task.baseline_status.length} path(s)).`
: "";
return textResult(`Started peer task ${task.id}. Implement the change, then call must_call_after_code_changes.${dirtyNote}`);
}
case "request_peer_review": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const task = await loadTask(taskId);
if (!task) return textResult(`Task not found: ${taskId}`, true);
return await startOrReuseAsyncPeerReview(task, parseReviewOptions(args), "Requested async peer review");
}
case "verify_code_changes_after_edit": {
return await runAsyncReviewGateTool(args, "Code changes require peer review");
}
case "finalize_code_changes_with_peer_review": {
return await runAsyncReviewGateTool(args, "Code changes require final peer review");
}
case "must_call_after_code_changes": {
return await runAsyncReviewGateTool(args, "Code changes require mandatory peer review");
}
case "start_peer_review_async": {
return await startAsyncReviewTool(args, "Code changes require async peer review");
}
case "wait_for_peer_review": {
return await waitForPeerReviewTool(args);
}
case "get_peer_review_status": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const task = await loadTask(taskId);
if (!task) return textResult(`Task not found: ${taskId}`, true);
return textResult(await buildReviewStatusJson(task), task.status === "review_failed");
}
case "code_assistant_peers_setup": {
return textResult(JSON.stringify(await buildSetupStatus(), null, 2));
}
case "peer_task_status": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const task = await loadTask(taskId);
if (!task) return textResult(`Task not found: ${taskId}`, true);
const rounds = await listReviewRounds(taskId);
const findings = await listFindings(taskId);
return textResult(JSON.stringify({ task: redactTaskForToolResult(task), rounds, findings }, null, 2));
}
case "get_peer_task_context": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const task = await loadTask(taskId);
if (!task) return textResult(`Task not found: ${taskId}`, true);
const [currentStatus, currentReviewContext, rounds, openFindings] = await Promise.all([
getStatusEntries(task.cwd),
getReviewDiff(task.cwd, {
baselineWorkspaceSnapshot: task.baseline_workspace_snapshot
?? (task.git_root === null
? emptyWorkspaceSnapshot("No pre-edit baseline snapshot was captured; current non-git files are reported as added for review.")
: null),
}),
listReviewRounds(taskId),
listFindings(taskId, "open"),
]);
return textResult(JSON.stringify({
task: redactTaskForToolResult(task),
baseline_status: formatStatus(task.baseline_status),
current_status: formatStatus(currentStatus),
current_diff: truncateForReview(currentReviewContext.diff, 30_000),
prior_rounds: rounds.map((round) => ({
id: round.id,
round: round.round,
reviewer: round.reviewer,
exit_code: round.exit_code,
completed_at: round.completed_at,
output_preview: truncateForReview(round.stdout || round.stderr, 2000),
})),
open_findings: openFindings,
}, null, 2));
}
case "list_peer_review_rounds": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const rounds = await listReviewRounds(taskId);
return textResult(JSON.stringify(rounds.map((round) => ({
id: round.id,
task_id: round.task_id,
round: round.round,
reviewer: round.reviewer,
exit_code: round.exit_code,
warning: round.warning,
started_at: round.started_at,
completed_at: round.completed_at,
stdout_preview: truncateForReview(round.stdout, 2000),
stderr_preview: truncateForReview(round.stderr, 1000),
})), null, 2));
}
case "get_peer_review_round": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
const roundNumber = Number((args as { round?: unknown }).round);
if (!Number.isFinite(roundNumber)) return textResult("round must be a number", true);
const round = await getReviewRound(taskId, roundNumber);
if (!round) return textResult(`Review round not found: ${taskId} round ${roundNumber}`, true);
return textResult(JSON.stringify(round, null, 2));
}
case "get_open_findings": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
return textResult(JSON.stringify(await listFindings(taskId, "open"), null, 2));
}
case "record_peer_review": {
const parsed = args as {
task_id?: unknown;
reviewer?: unknown;
summary?: unknown;
findings?: unknown;
};
const taskId = String(parsed.task_id ?? "").trim();
const reviewer = String(parsed.reviewer ?? peer).trim();
const summary = String(parsed.summary ?? "").trim();
const task = await loadTask(taskId);
if (!task) return textResult(`Task not found: ${taskId}`, true);
const allowedReviewers = new Set([task.peer, ...(task.peers ?? [])]);
if (!allowedReviewers.has(reviewer)) return textResult(`reviewer must be one of: ${[...allowedReviewers].join(", ")}`, true);
if (!summary) return textResult("summary is required", true);
if (!Array.isArray(parsed.findings)) return textResult("findings must be an array", true);
const findings = parsed.findings.map(normalizeFinding);
const now = new Date().toISOString();
const round = await appendReviewRound(task, {
reviewer,
command: ["mcp", "record_peer_review"],
exit_code: 0,
stdout: summary,
stderr: "",
started_at: now,
completed_at: now,
}, summary);
const inserted = await addFindings(taskId, round.id, findings);
return textResult(`Recorded review round ${round.round} with ${inserted.length} finding(s).`);
}
case "compact_peer_history": {
const taskId = String((args as { task_id?: unknown }).task_id ?? "").trim();
return textResult(await compactTaskHistory(taskId));
}
case "gc_peer_store": {
const days = Number((args as { days?: unknown }).days ?? 30);
if (!Number.isFinite(days) || days < 1) return textResult("days must be a positive number", true);
return textResult(JSON.stringify(await gcStore(days), null, 2));
}
default:
throw new Error(`Unknown tool: ${name}`);
}
});
function textResult(text: string, isError = false) {
return {
content: [{ type: "text" as const, text }],
isError,
};
}
function buildFailureReviewResult(reviewer: AssistantHost, failureMessage: string): PeerReviewResult {
const now = new Date().toISOString();
return {
reviewer,
command: ["async-peer-review-preflight"],
exit_code: 1,
stdout: "",
stderr: failureMessage,
started_at: now,
completed_at: now,
warning: failureMessage,
};
}
async function withAsyncReviewLock<T>(taskId: string, action: () => Promise<T>): Promise<T> {
const previousLock = asyncReviewLocks.get(taskId) ?? Promise.resolve();
let releaseLock: (() => void) | undefined;
const currentLock = new Promise<void>((resolve) => {
releaseLock = resolve;
});
const chainedLock = previousLock.then(() => currentLock);
asyncReviewLocks.set(taskId, chainedLock);
await previousLock.catch(() => undefined);
try {
return await action();
} finally {
releaseLock?.();
if (asyncReviewLocks.get(taskId) === chainedLock) {
asyncReviewLocks.delete(taskId);
}
}
}
function buildReviewRequestSignatureFromState(
task: PeerTask,
options: ReviewRequestOptions,
reviewState: { statusEntries: PeerTask["baseline_status"]; diff: string },
): string {
// NOTE: change_summary / files_changed are deliberately EXCLUDED. They are host-written free
// text that hosts reword on every call, so including them made the signature differ while the
// actual repository state (git_status + git_diff below) was identical — defeating the
// same-state dedup and superseding in-flight reviews for no reason. They still flow into the
// review prompt; they just don't define "did anything reviewable change". Use force_review to
// re-run a review for an unchanged state.
const payload = {
cwd: task.cwd,
host: task.host,
peer: task.peer,
peers: task.peers ?? [task.peer],
prompt: task.prompt,
mode: options.mode ?? "normal",
scope: options.scope ?? "auto",
base: options.base ?? null,
workflow: options.workflow ?? "review_only",
focus: normalizeReviewFocus(options.focus ?? process.env.CODE_ASSISTANT_PEERS_REVIEW_FOCUS),
semantic_context: options.semantic_context ?? null,
self_review: options.self_review ?? false,
review_model: options.review_model ?? null,
review_models: options.review_models ?? {},
git_status: reviewState.statusEntries,
git_diff: reviewState.diff,
};
return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
}
async function captureReviewStartContext(task: PeerTask, options: ReviewRequestOptions): Promise<ReviewStartContext> {
const [statusEntries, reviewContext] = await Promise.all([
getStatusEntries(task.cwd),
getReviewDiff(task.cwd, {
scope: options.scope,
base: options.base,
baselineWorkspaceSnapshot: task.baseline_workspace_snapshot
?? (task.git_root === null
? emptyWorkspaceSnapshot("No pre-edit baseline snapshot was captured; current non-git files are reported as added for review.")
: null),
}),
]);
return {
requestSignature: buildReviewRequestSignatureFromState(task, options, {
statusEntries,
diff: reviewContext.diff,
}),
snapshotSeed: {
currentStatus: statusEntries,
reviewContext,
},
};
}
function buildLegacyReviewRequestSignature(task: PeerTask, options: ReviewRequestOptions): string {
return buildReviewRequestSignatureFromState(task, options, {
statusEntries: task.baseline_status,
diff: task.baseline_diff,
});
}
async function recordReviewFailure(task: PeerTask, reviewer: AssistantHost, failureMessage: string): Promise<void> {
task.review = buildFailureReviewResult(reviewer, failureMessage);
task.status = "review_failed";
task.updated_at = task.review.completed_at;
try {
await appendReviewRoundAndSaveTask(task, task.review, failureMessage);
} catch (error) {
const message = error instanceof Error ? error.stack || error.message : String(error);
log(`Could not append synthetic failure round for task ${task.id}: ${message}`);
}
}
async function canFinalizeReview(taskId: string, expectedSignature?: string): Promise<boolean> {
if (!expectedSignature) return true;
const current = await loadTask(taskId);
return Boolean(current && current.status === "running" && current.review_signature === expectedSignature);
}
async function withReviewCommitLock<T>(
taskId: string,
expectedSignature: string | undefined,
action: (current: PeerTask) => Promise<T>,
): Promise<T | null> {
return await withAsyncReviewLock(taskId, async () => {
const current = await loadTask(taskId);
if (!current || !(expectedSignature ? current.review_signature === expectedSignature && current.status === "running" : true)) {
return null;
}
return await action(current);
});
}
async function withReviewFailureCommitLock<T>(
taskId: string,
expectedSignature: string | undefined,
action: (current: PeerTask) => Promise<T>,
): Promise<T | null> {
return await withAsyncReviewLock(taskId, async () => {
if (!expectedSignature) {
const current = await loadTask(taskId);
if (!current) return null;
return await action(current);
}
const current = await loadTask(taskId);
if (!current || current.review_signature !== expectedSignature || (current.status !== "queued" && current.status !== "running")) {
return null;
}
return await action(current);
});
}
async function createPeerTask(
prompt: string,
seed?: ReviewPromptSnapshotSeed,
options: { persist?: boolean; nonGitBaseline?: "snapshot" | "empty" } = {},
): Promise<PeerTask> {
const cwd = process.cwd();
const gitRoot = await getGitRoot(cwd);
const baselineStatus = seed?.currentStatus ?? await getStatusEntries(cwd);
const baselineDiff = seed?.reviewContext.diff ?? await getUncommittedDiff(cwd);
const baselineWorkspaceSnapshot = gitRoot
? null
: options.nonGitBaseline === "empty"
? emptyWorkspaceSnapshot("No pre-edit baseline snapshot was captured; current non-git files are reported as added for review.")
: await captureWorkspaceSnapshot(cwd);
const now = new Date().toISOString();
const task: PeerTask = {
id: crypto.randomUUID(),
host,
peer,
peers,
prompt,
cwd,
git_root: gitRoot,
baseline_status: baselineStatus,
baseline_diff: baselineDiff,
baseline_workspace_snapshot: baselineWorkspaceSnapshot,
created_at: now,
updated_at: now,
status: "open",
};
if (options.persist !== false) {
await saveTask(task);
}
return task;
}
async function runAsyncReviewGateTool(args: unknown, defaultPrompt: string) {
const parsed = args as { task_id?: unknown; prompt?: unknown };
const taskId = String(parsed.task_id ?? "").trim();
const task = taskId
? await loadTask(taskId)
: await createPeerTask(String(parsed.prompt ?? defaultPrompt).trim(), undefined, { nonGitBaseline: "empty" });
if (!task) return textResult(`Task not found: ${taskId}`, true);
return await startOrReuseAsyncPeerReview(task, parseReviewOptions(args), "Mandatory async peer review gate");
}
async function startAsyncReviewTool(args: unknown, defaultPrompt: string) {
const parsed = args as { task_id?: unknown; prompt?: unknown };
const taskId = String(parsed.task_id ?? "").trim();
const task = taskId
? await loadTask(taskId)
: await createPeerTask(String(parsed.prompt ?? defaultPrompt).trim(), undefined, { nonGitBaseline: "empty" });
if (!task) return textResult(`Task not found: ${taskId}`, true);
return await startOrReuseAsyncPeerReview(task, parseReviewOptions(args), "Started async peer review");
}
function redactTaskForToolResult(task: PeerTask): PeerTask {
const redacted = structuredClone(task);
const snapshot = redacted.baseline_workspace_snapshot;
if (!snapshot) return redacted;
for (const entry of Object.values(snapshot.files)) {
if (!entry.sensitive) continue;
entry.fingerprint = "[redacted sensitive fingerprint]";
if (entry.sha256) entry.sha256 = "[redacted sensitive fingerprint]";
}
return redacted;
}
function startBackgroundAsyncReview(
task: PeerTask,
options: ReviewRequestOptions,
expectedSignature?: string,
promptSnapshotSeed?: ReviewPromptSnapshotSeed,
): void {
activeAsyncReviews.add(task.id);
void runAsyncPeerReview(task, options, expectedSignature, promptSnapshotSeed);
}
async function startOrReuseAsyncPeerReview(task: PeerTask, options: ReviewRequestOptions, label: string) {
return await withAsyncReviewLock(task.id, async () => {
const current = await loadTask(task.id) ?? task;
const startContext = await captureReviewStartContext(current, options);
const requestSignature = startContext.requestSignature;
const currentSignature = current.review_signature ?? buildLegacyReviewRequestSignature(current, options);
const hasSensitivePossibleChange = startContext.snapshotSeed.reviewContext.diff.includes("sensitive path");
const hasNoNonGitBaseline = current.git_root === null && !current.baseline_workspace_snapshot;
if (currentSignature === requestSignature && isTerminalReviewStatus(current.status) && !hasSensitivePossibleChange && !hasNoNonGitBaseline && options.force_review !== true) {
return textResult([
`Peer review already completed for task ${current.id}.`,
"The repository state and review options match the latest recorded review, so no reviewer was re-run (no extra tokens spent). Pass force_review=true to re-run anyway.",
"Call wait_for_peer_review with this task_id before your final response.",
await buildReviewStatusJson(current),
].join("\n\n"));
}
if (current.status === "queued" || current.status === "running") {
if (currentSignature === requestSignature) {
if (!activeAsyncReviews.has(current.id) && isStaleReviewState(current)) {
const staleStatus = current.status;
const claimed = await claimStaleReviewRecovery(
current.id,
requestSignature,
new Date(Date.now() - STALE_REVIEW_RECOVERY_MS).toISOString(),
);
if (!claimed) {
const refreshed = await loadTask(current.id) ?? current;
return textResult([
`Peer review is already ${refreshed.status} for task ${refreshed.id}.`,
"Another MCP server process appears to have claimed or refreshed this review state.",
"No duplicate reviewer process was started.",
"Call wait_for_peer_review with this task_id before your final response.",
await buildReviewStatusJson(refreshed),
].join("\n\n"));
}