oy-cli 0.12.0

OpenCode launcher and deterministic MCP helpers for repository audit and review workflows
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
//! Minimal stdio MCP server exposing deterministic oy primitives.

use anyhow::{Context, Result, anyhow, bail};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fs;
use std::hash::{Hash as _, Hasher as _};
use std::io::{BufRead as _, Write as _};
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::{LazyLock, Mutex};

use crate::audit::input;
use crate::{audit, config, tools, ui};

const DEFAULT_MODEL_FOR_COUNTING: &str = "cl100k_base";
pub(crate) const DEFAULT_TARGET_TOKENS: usize = 64_000;
const MAX_EXISTING_REPORT_BYTES: u64 = 1024 * 1024;
const LATEST_PROTOCOL_VERSION: &str = "2025-06-18";
const FALLBACK_PROTOCOL_VERSION: &str = "2024-11-05";
const HOST_TOOL_OUTPUT_MAX_BYTES: usize = 256 * 1024;
const HOST_TOOL_OUTPUT_MAX_LINES: usize = 20_000;
const EXISTING_REPORT_OUTPUT_BUDGET: usize = HOST_TOOL_OUTPUT_MAX_BYTES - 8 * 1024;
const MAX_TOOL_ERROR_CHARS: usize = 300;

static CLEAN_REPO_INPUT_CACHE: LazyLock<Mutex<HashMap<String, Vec<input::AuditFile>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));
static BOUND_WORKFLOW_STATE: LazyLock<Mutex<Option<BoundWorkflowState>>> =
    LazyLock::new(|| Mutex::new(None));

#[derive(Debug, Clone)]
struct BoundWorkflowState {
    run_id: String,
    input_digest: u64,
    chunk_count: usize,
    next_chunk: usize,
}

pub(crate) async fn serve_stdio() -> Result<i32> {
    ui::set_output_mode(ui::OutputMode::Quiet);
    let stdin = std::io::stdin();
    let mut stdout = std::io::stdout();
    for line in stdin.lock().lines() {
        let line = line.context("failed reading MCP stdin")?;
        if line.trim().is_empty() {
            continue;
        }
        let request = match serde_json::from_str::<Value>(&line) {
            Ok(request) => request,
            Err(err) => {
                write_response(
                    &mut stdout,
                    jsonrpc_error(Value::Null, -32700, err.to_string()),
                )?;
                continue;
            }
        };
        let Some(id) = request.get("id").cloned() else {
            continue;
        };
        let method = request
            .get("method")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let params = request.get("params").cloned().unwrap_or(Value::Null);
        let response = match handle_request(method, params).await {
            Ok(response) => response.into_json(id),
            Err(err) => jsonrpc_error(id, -32603, err.to_string()),
        };
        write_response(&mut stdout, response)?;
    }
    Ok(0)
}

async fn handle_request(method: &str, params: Value) -> Result<JsonRpcResponse> {
    match method {
        "initialize" => Ok(JsonRpcResponse::Result(json!({
            "protocolVersion": negotiated_protocol_version(&params),
            "capabilities": { "tools": {} },
            "serverInfo": { "name": "oy", "version": env!("CARGO_PKG_VERSION") }
        }))),
        "ping" => Ok(JsonRpcResponse::Result(json!({}))),
        "tools/list" => Ok(JsonRpcResponse::Result(
            json!({ "tools": tool_definitions() }),
        )),
        "tools/call" => Ok(JsonRpcResponse::Result(
            handle_tool_call(params)
                .await
                .unwrap_or_else(|err| tool_error_result(&err)),
        )),
        other => Ok(JsonRpcResponse::Error {
            code: -32601,
            message: format!("unknown MCP method: {other}"),
        }),
    }
}

fn negotiated_protocol_version(params: &Value) -> &'static str {
    if params.get("protocolVersion").and_then(Value::as_str) == Some(LATEST_PROTOCOL_VERSION) {
        LATEST_PROTOCOL_VERSION
    } else {
        FALLBACK_PROTOCOL_VERSION
    }
}

enum JsonRpcResponse {
    Result(Value),
    Error { code: i32, message: String },
}

impl JsonRpcResponse {
    fn into_json(self, id: Value) -> Value {
        match self {
            Self::Result(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
            Self::Error { code, message } => jsonrpc_error(id, code, message),
        }
    }
}

async fn handle_tool_call(params: Value) -> Result<Value> {
    let name = params
        .get("name")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("tools/call missing tool name"))?;
    let args = params
        .get("arguments")
        .cloned()
        .unwrap_or_else(|| json!({}));
    let _context = authorize_bound_call(&args)?;
    let requested_chunk = args
        .get("chunk")
        .and_then(Value::as_u64)
        .map(|value| value as usize);
    let result = match name {
        "workflow_status" => workflow_status()?,
        "repo_manifest" => repo_manifest(args)?,
        "repo_chunks" => repo_chunks(args)?,
        "git_diff_input" => git_diff_input(args)?,
        "existing_report" => existing_report(args)?,
        "outline" => builtin_tool("outline", args).await?,
        "sloc" => builtin_tool("sloc", args).await?,
        "sighthound" => builtin_tool("sighthound", args).await?,
        "render_audit_report" => render_audit_report(args)?,
        "render_review_report" => render_review_report(args)?,
        other => bail!("unknown oy MCP tool: {other}"),
    };
    let response = tool_success_result(result)?;
    if matches!(name, "repo_chunks" | "git_diff_input") {
        acknowledge_bound_chunk(requested_chunk)?;
    }
    Ok(response)
}

fn authorize_bound_call(args: &Value) -> Result<Option<crate::workflow::ActiveContextGuard>> {
    if let Some(run_id) = args.get("run_id").and_then(Value::as_str) {
        let context = crate::workflow::find_by_run_id(run_id)?
            .ok_or_else(|| anyhow!("workflow_context_missing: unknown or completed run_id"))?;
        return crate::workflow::activate(context).map(Some);
    }
    let root = config::oy_root()?;
    if crate::workflow::retained(&root)?.is_some() {
        bail!("workflow_auth_required: pass the bound run_id to every oy tool call");
    }
    Ok(None)
}

async fn builtin_tool(name: &str, args: Value) -> Result<Value> {
    tools::invoke_read_only_deterministic(workspace_root()?, name, args).await
}

fn tool_success_result(result: Value) -> Result<Value> {
    let text = primary_result_text(&result)?;
    let value = if result.get("text").is_some() {
        json!({
            "content": [{ "type": "text", "text": text }],
            "isError": false
        })
    } else {
        json!({
            "content": [{ "type": "text", "text": text }],
            "structuredContent": result,
            "isError": false
        })
    };
    let encoded = serde_json::to_vec(&value)?;
    if encoded.len() > HOST_TOOL_OUTPUT_MAX_BYTES {
        bail!(
            "tool_output_too_large: encoded result {} bytes exceeds {}",
            encoded.len(),
            HOST_TOOL_OUTPUT_MAX_BYTES
        );
    }
    Ok(value)
}

fn primary_result_text(value: &Value) -> Result<String> {
    if let Some(text) = value.get("text").and_then(Value::as_str) {
        return Ok(text.to_string());
    }
    if value.get("exists").and_then(Value::as_bool) == Some(true)
        && let Some(report) = value.get("report").and_then(Value::as_str)
    {
        return Ok(report.to_string());
    }
    result_text(value)
}

fn result_text(value: &Value) -> Result<String> {
    match value {
        Value::String(value) => Ok(value.clone()),
        other => serde_json::to_string_pretty(other).context("failed encoding tool result"),
    }
}

fn tool_error_result(err: &anyhow::Error) -> Value {
    let message = err
        .to_string()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let mut chars = message.chars();
    let mut message = chars
        .by_ref()
        .take(MAX_TOOL_ERROR_CHARS)
        .collect::<String>();
    if chars.next().is_some() {
        message.push_str("...");
    }
    json!({
        "content": [{ "type": "text", "text": message }],
        "isError": true
    })
}

fn write_response(stdout: &mut std::io::Stdout, response: Value) -> Result<()> {
    serde_json::to_writer(&mut *stdout, &response).context("failed writing MCP response")?;
    stdout
        .write_all(b"\n")
        .context("failed writing MCP newline")?;
    stdout.flush().context("failed flushing MCP response")
}

fn jsonrpc_error(id: Value, code: i32, message: impl Into<String>) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message.into() }
    })
}

fn tool_definitions() -> Vec<Value> {
    let mut tools = vec![tool_def(
        "workflow_status",
        "Return the immutable oy workflow scope, output, model, chunk limit, and recovery run ID bound by the launcher.",
        json!({ "type": "object", "properties": {}, "additionalProperties": false }),
    )];
    tools.extend([
        tool_def(
            "repo_manifest",
            "Build a deterministic, gitignore-aware repository manifest for audit/review planning.",
            json!({
                "type": "object",
                "properties": {
                    "path": { "type": "string", "description": "Workspace-relative file or directory to inspect", "default": "." },
                    "model": { "type": "string", "description": "Model label retained for workflow metadata; token estimates use oy's approximate byte heuristic" },
                    "security_index": { "type": "boolean", "default": true },
                    "security_index_limit": { "type": "integer", "default": 120 }
                }
            }),
        ),
        tool_def(
            "repo_chunks",
            "Prepare deterministic repository chunks for a workspace-relative file or directory. Omit chunk to list summaries; pass a 1-based chunk number to get that chunk's text.",
            json!({
                "type": "object",
                "properties": {
                    "path": { "type": "string", "default": "." },
                    "model": { "type": "string", "description": "Model label retained for workflow metadata; token estimates use oy's approximate byte heuristic" },
                    "target_tokens": { "type": "integer", "default": DEFAULT_TARGET_TOKENS, "description": "Best-effort token target for unbound interactive calls; bound oy workflows enforce a fixed transport-safe target" },
                    "chunk": { "type": "integer", "description": "1-based chunk number to return with full text" }
                }
            }),
        ),
        tool_def(
            "git_diff_input",
            "Prepare deterministic review input from git diff against a target branch/commit/ref.",
            json!({
                "type": "object",
                "required": ["target"],
                "properties": {
                    "target": { "type": "string" },
                    "model": { "type": "string", "description": "Model label retained for workflow metadata; token estimates use oy's approximate byte heuristic" },
                    "target_tokens": { "type": "integer", "default": DEFAULT_TARGET_TOKENS, "description": "Best-effort token target for unbound interactive calls; bound oy workflows enforce a fixed transport-safe target" },
                    "chunk": { "type": "integer", "description": "1-based chunk number to return with full diff text" }
                }
            }),
        ),
        tool_def(
            "existing_report",
            "Read an existing generated ISSUES.md or REVIEW.md report so a new audit/review can carry forward still-current findings and supersede stale ones.",
            json!({
                "type": "object",
                "required": ["kind"],
                "properties": {
                    "kind": { "type": "string", "enum": ["audit", "review"] },
                    "out": { "type": "string", "description": "Workspace report path to read; defaults to ISSUES.md for audit and REVIEW.md for review" }
                }
            }),
        ),
    ]);

    if let Some(definition) = sloc_tool_definition() {
        tools.push(definition);
    }
    if let Some(definition) = outline_tool_definition() {
        tools.push(definition);
    }
    if let Some(definition) = sighthound_tool_definition() {
        tools.push(definition);
    }

    tools.extend([
        tool_def(
            "render_audit_report",
            "Render and write a deterministic audit report from agent-produced markdown/structured findings.",
            render_report_schema("ISSUES.md", true),
        ),
        tool_def(
            "render_review_report",
            "Render and write a deterministic review report from agent-produced markdown/structured findings.",
            render_report_schema("REVIEW.md", false),
        ),
    ]);

    tools
}

fn workflow_status() -> Result<Value> {
    let root = workspace_root()?;
    let context = crate::workflow::current(&root)?.ok_or_else(|| {
        anyhow!("workflow_context_missing: launch through oy audit/review/enhance")
    })?;
    let state = BOUND_WORKFLOW_STATE
        .lock()
        .map_err(|_| anyhow!("workflow state lock poisoned"))?
        .clone()
        .filter(|state| state.run_id == context.run_id);
    Ok(json!({
        "run_id": context.run_id,
        "kind": context.kind,
        "scope": context.scope,
        "focus": context.focus,
        "output": context.output,
        "format": context.format,
        "max_chunks": context.max_chunks,
        "model": context.model,
        "session_id": context.session_id,
        "prepared": state.is_some(),
        "chunk_count": state.as_ref().map(|state| state.chunk_count),
        "next_chunk": state.as_ref().map(|state| state.next_chunk),
    }))
}

fn outline_tool_definition() -> Option<Value> {
    tools::has_external_outline_tool().then(|| {
        tool_def(
            "outline",
            "Extract structural definitions from a source file using Universal Ctags when it is installed on PATH.",
            json!({
                "type": "object",
                "required": ["path"],
                "properties": {
                    "path": { "type": "string" }
                }
            }),
        )
    })
}

fn sloc_tool_definition() -> Option<Value> {
    tools::has_external_sloc_counter().then(|| {
        tool_def(
            "sloc",
            "Count source lines by language using tokei when it is installed on PATH.",
            json!({
                "type": "object",
                "required": ["path"],
                "properties": {
                    "path": { "type": "string" },
                    "exclude": {
                        "oneOf": [
                            { "type": "string" },
                            { "type": "array", "items": { "type": "string" } }
                        ]
                    }
                }
            }),
        )
    })
}

fn sighthound_tool_definition() -> Option<Value> {
    tools::has_external_security_scanner().then(|| {
        tool_def(
            "sighthound",
            "Scan a workspace directory for source vulnerabilities with Sighthound's embedded rules. Uses independent gitignore-aware discovery that may include supported source excluded by oy's collector. Runs single-threaded with fixed arguments and bounded output.",
            json!({
                "type": "object",
                "properties": {
                    "path": { "type": "string", "default": ".", "description": "Workspace-relative directory to scan" },
                    "analysis": { "type": "string", "enum": ["all", "simple", "taint"], "default": "all" },
                    "language": {
                        "type": "string",
                        "enum": ["python", "javascript", "typescript", "tsx", "java", "php", "csharp", "go", "ruby", "html", "django"],
                        "description": "Optional explicit scan language; omit to auto-detect supported languages"
                    },
                    "include_test_fixtures": { "type": "boolean", "default": false },
                    "max_findings": { "type": "integer", "minimum": 1, "maximum": 200, "default": 100, "description": "Maximum findings returned after stable sorting; output also has a byte budget" }
                }
            }),
        )
    })
}

fn tool_def(name: &str, description: &str, input_schema: Value) -> Value {
    let mut input_schema = input_schema;
    if let Some(properties) = input_schema
        .get_mut("properties")
        .and_then(Value::as_object_mut)
    {
        properties.insert(
            "run_id".to_string(),
            json!({ "type": "string", "description": "Required correlation token during a bound oy CLI workflow" }),
        );
    }
    json!({
        "name": name,
        "description": description,
        "inputSchema": input_schema
    })
}

fn render_report_schema(default_out: &str, sarif: bool) -> Value {
    let format = if sarif {
        json!({ "type": "string", "enum": ["markdown", "sarif"], "default": "markdown" })
    } else {
        json!({ "type": "string", "enum": ["markdown"], "default": "markdown" })
    };
    json!({
        "type": "object",
        "properties": {
            "report": { "type": "string", "description": "Markdown report body; renderer owns transparency and oy-findings block" },
            "findings": { "description": "Structured findings array, [] for no findings, or object with findings/oy-findings" },
            "out": { "type": "string", "default": default_out },
            "format": format,
            "model": { "type": "string", "description": "Model used for the audit/review, included in the transparency line" },
            "target": { "type": "string", "description": "Review target branch/commit/ref, included in review transparency" },
            "focus": { "type": "string", "description": "Focus text included in the transparency line" },
            "max_chunks": { "type": "integer", "description": "Max chunk limit included in the transparency line" }
        }
    })
}

#[derive(Debug, Deserialize)]
struct RepoInputArgs {
    #[serde(default = "default_path")]
    path: String,
    #[serde(default = "default_model")]
    model: String,
    #[serde(default = "default_true")]
    security_index: bool,
    #[serde(default = "default_security_index_limit")]
    security_index_limit: usize,
}

#[derive(Debug, Deserialize)]
struct ChunkArgs {
    #[serde(default = "default_path")]
    path: String,
    #[serde(default = "default_model")]
    model: String,
    #[serde(default = "default_target_tokens")]
    target_tokens: usize,
    #[serde(default)]
    chunk: Option<usize>,
}

#[derive(Debug, Deserialize)]
struct DiffArgs {
    target: String,
    #[serde(default = "default_model")]
    model: String,
    #[serde(default = "default_target_tokens")]
    target_tokens: usize,
    #[serde(default)]
    chunk: Option<usize>,
}

#[derive(Debug, Deserialize)]
struct ExistingReportArgs {
    kind: String,
    #[serde(default)]
    out: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
struct RenderReportArgs {
    #[serde(default)]
    report: Option<String>,
    #[serde(default)]
    findings: Option<Value>,
    #[serde(default)]
    out: Option<PathBuf>,
    #[serde(default = "default_markdown")]
    format: String,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    target: Option<String>,
    #[serde(default)]
    focus: Option<String>,
    #[serde(default)]
    max_chunks: Option<usize>,
}

fn repo_manifest(args: Value) -> Result<Value> {
    let mut args: RepoInputArgs = parse_args(args)?;
    let root = workspace_root()?;
    if let Some(context) = crate::workflow::current(&root)? {
        match context.scope {
            crate::workflow::WorkflowScope::Workspace { path } => args.path = path,
            crate::workflow::WorkflowScope::GitDiff { .. } => {
                bail!("bound review workflow requires git_diff_input")
            }
        }
        if let Some(model) = context.model {
            args.model = model;
        }
    }
    let files = collect_workspace_input_files(&root, &args.path, &args.model)?;
    if files.is_empty() {
        bail!("no reviewable text files found");
    }
    let manifest = input::build_manifest(&files);
    let security_index = args
        .security_index
        .then(|| input::build_security_index(&files, args.security_index_limit));
    Ok(json!({
        "path": args.path,
        "manifest": manifest,
        "security_index": security_index,
        "files": file_summaries(&files),
    }))
}

fn repo_chunks(args: Value) -> Result<Value> {
    let mut args: ChunkArgs = parse_args(args)?;
    let root = workspace_root()?;
    let context = crate::workflow::current(&root)?;
    if let Some(context) = &context {
        match &context.scope {
            crate::workflow::WorkflowScope::Workspace { path } => args.path = path.clone(),
            crate::workflow::WorkflowScope::GitDiff { .. } => {
                bail!("bound review workflow requires git_diff_input")
            }
        }
        if let Some(model) = &context.model {
            args.model = model.clone();
        }
        args.target_tokens = DEFAULT_TARGET_TOKENS;
    }
    let files = collect_workspace_input_files(&root, &args.path, &args.model)?;
    if files.is_empty() {
        bail!("no reviewable text files found");
    }
    let manifest = input::build_manifest(&files);
    let chunks = input::chunk_files(files, args.target_tokens.max(1));
    input::ensure_chunks_fit_prompt(&chunks, args.target_tokens.max(1))?;
    if let Some(context) = &context
        && chunks.len() > context.max_chunks
    {
        bail!(
            "chunk_limit_exceeded: {} chunks exceeds bound max_chunks {}",
            chunks.len(),
            context.max_chunks
        );
    }
    enforce_bound_chunk_sequence(context.as_ref(), &chunks, args.chunk)?;
    chunks_response("workspace", manifest, chunks, args.chunk)
}

fn git_diff_input(args: Value) -> Result<Value> {
    let mut args: DiffArgs = parse_args(args)?;
    let root = workspace_root()?;
    let context = crate::workflow::current(&root)?;
    if let Some(context) = &context {
        match &context.scope {
            crate::workflow::WorkflowScope::GitDiff { oid, .. } => args.target = oid.clone(),
            crate::workflow::WorkflowScope::Workspace { .. } => {
                bail!("bound workspace workflow requires repo_chunks")
            }
        }
        if let Some(model) = &context.model {
            args.model = model.clone();
        }
        args.target_tokens = DEFAULT_TARGET_TOKENS;
    }
    validate_target_ref(&args.target)?;
    let _ = git_output(&root, &["rev-parse", "--show-toplevel"])
        .context("git_diff_input requires a git workspace")?;
    let diff = git_output(
        &root,
        &[
            "diff",
            "--no-ext-diff",
            "--find-renames",
            "--find-copies",
            "--unified=80",
            &args.target,
            "--",
        ],
    )
    .with_context(|| format!("failed to collect git diff against {}", args.target))?;
    if diff.trim().is_empty() {
        bail!("no git diff found against target {}", args.target);
    }
    let stats = input::parse_numstat(&git_output(
        &root,
        &["diff", "--numstat", &args.target, "--"],
    )?);
    let files = input::collect_diff_files(&diff, &args.model);
    if files.is_empty() {
        bail!(
            "no reviewable text diff found against target {}",
            args.target
        );
    }
    let manifest = input::build_diff_manifest(&args.target, &files, &stats);
    let chunks = input::chunk_files(files, args.target_tokens.max(1));
    input::ensure_chunks_fit_prompt(&chunks, args.target_tokens.max(1))?;
    if let Some(context) = &context
        && chunks.len() > context.max_chunks
    {
        bail!(
            "chunk_limit_exceeded: {} chunks exceeds bound max_chunks {}",
            chunks.len(),
            context.max_chunks
        );
    }
    enforce_bound_chunk_sequence(context.as_ref(), &chunks, args.chunk)?;
    chunks_response(
        &format!("git diff against {}", args.target),
        manifest,
        chunks,
        args.chunk,
    )
}

fn enforce_bound_chunk_sequence(
    context: Option<&crate::workflow::WorkflowContext>,
    chunks: &[input::AuditChunk],
    requested: Option<usize>,
) -> Result<()> {
    let Some(context) = context else {
        return Ok(());
    };
    let digest = input_digest(chunks);
    let mut state = BOUND_WORKFLOW_STATE
        .lock()
        .map_err(|_| anyhow!("workflow state lock poisoned"))?;
    match requested {
        None => {
            if let Some(current) = state.as_ref()
                && current.run_id == context.run_id
            {
                if current.input_digest != digest {
                    bail!("input_changed: workflow evidence changed after preparation");
                }
            } else {
                *state = Some(BoundWorkflowState {
                    run_id: context.run_id.clone(),
                    input_digest: digest,
                    chunk_count: chunks.len(),
                    next_chunk: 1,
                });
            }
        }
        Some(number) => {
            let current = state
                .as_mut()
                .ok_or_else(|| anyhow!("workflow_not_prepared: request the chunk summary first"))?;
            if current.run_id != context.run_id || current.input_digest != digest {
                bail!("input_changed: workflow evidence changed after preparation");
            }
            if number > current.chunk_count {
                bail!(
                    "chunk_not_found: requested {number}, available chunks {}",
                    current.chunk_count
                );
            }
            if number != current.next_chunk && number + 1 != current.next_chunk {
                bail!(
                    "chunk_out_of_order: expected chunk {}, received {number}",
                    current.next_chunk
                );
            }
        }
    }
    Ok(())
}

fn acknowledge_bound_chunk(number: Option<usize>) -> Result<()> {
    let Some(number) = number else {
        return Ok(());
    };
    let root = workspace_root()?;
    let Some(context) = crate::workflow::current(&root)? else {
        return Ok(());
    };
    let mut state = BOUND_WORKFLOW_STATE
        .lock()
        .map_err(|_| anyhow!("workflow state lock poisoned"))?;
    let current = state
        .as_mut()
        .ok_or_else(|| anyhow!("workflow_not_prepared: request the chunk summary first"))?;
    if current.run_id == context.run_id && number == current.next_chunk {
        current.next_chunk += 1;
    }
    Ok(())
}

fn input_digest(chunks: &[input::AuditChunk]) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for chunk in chunks {
        for file in &chunk.files {
            file.path.hash(&mut hasher);
            file.text.hash(&mut hasher);
        }
    }
    hasher.finish()
}

fn existing_report(args: Value) -> Result<Value> {
    let mut args: ExistingReportArgs = parse_args(args)?;
    let root = workspace_root()?;
    if let Some(context) = crate::workflow::current(&root)? {
        args.kind = match context.kind {
            crate::workflow::WorkflowKind::Audit => "audit",
            crate::workflow::WorkflowKind::Review | crate::workflow::WorkflowKind::Enhance => {
                "review"
            }
        }
        .to_string();
        args.out = Some(context.output);
    }
    existing_report_at(&root, args)
}

fn existing_report_at(root: &Path, args: ExistingReportArgs) -> Result<Value> {
    let (kind, default_out) = match args.kind.as_str() {
        "audit" => (
            "audit",
            audit::default_output_path(audit::AuditOutputFormat::Markdown),
        ),
        "review" => ("review", crate::review::default_output_path()),
        other => bail!("unsupported existing report kind: {other}"),
    };
    let out = args.out.unwrap_or(default_out);
    let output_path = config::resolve_workspace_output_path(root, &out)?;
    if !output_path.exists() {
        return Ok(json!({
            "kind": kind,
            "path": out,
            "exists": false,
            "report": "",
            "findings": 0,
        }));
    }
    let meta = fs::metadata(&output_path)
        .with_context(|| format!("failed to stat existing report: {}", output_path.display()))?;
    if meta.len() > MAX_EXISTING_REPORT_BYTES {
        bail!(
            "existing {kind} report is too large to include deterministically ({} bytes > {}): {}",
            meta.len(),
            MAX_EXISTING_REPORT_BYTES,
            output_path.display()
        );
    }
    let report = fs::read_to_string(&output_path)
        .with_context(|| format!("failed to read existing report: {}", output_path.display()))?;
    let report_lines = report.lines().count();
    if report_lines > HOST_TOOL_OUTPUT_MAX_LINES {
        bail!(
            "existing {kind} report has too many lines to include deterministically ({report_lines} > {HOST_TOOL_OUTPUT_MAX_LINES}): {}",
            output_path.display()
        );
    }
    let findings = audit::report::findings_from_report(&report).len();
    let result = json!({
        "kind": kind,
        "path": out,
        "exists": true,
        "report": report,
        "findings": findings,
    });
    let encoded_bytes = serde_json::to_vec(&tool_success_result(result.clone())?)
        .context("failed measuring existing report MCP output")?
        .len();
    if encoded_bytes > EXISTING_REPORT_OUTPUT_BUDGET {
        bail!(
            "existing {kind} report exceeds the host tool-output budget ({encoded_bytes} > {EXISTING_REPORT_OUTPUT_BUDGET} encoded bytes): {}",
            output_path.display()
        );
    }
    Ok(result)
}

fn chunks_response(
    source: &str,
    manifest: String,
    chunks: Vec<input::AuditChunk>,
    requested: Option<usize>,
) -> Result<Value> {
    if let Some(number) = requested {
        let idx = number
            .checked_sub(1)
            .ok_or_else(|| anyhow!("chunk numbers are 1-based"))?;
        let chunk = chunks.get(idx).ok_or_else(|| {
            anyhow!(
                "chunk {number} not found; available chunks: {}",
                chunks.len()
            )
        })?;
        return Ok(json!({
            "source": source,
            "chunk": number,
            "chunk_count": chunks.len(),
            "tokens": chunk.tokens,
            "text": input::chunk_text(chunk),
        }));
    }
    Ok(json!({
        "source": source,
        "manifest": manifest,
        "chunk_count": chunks.len(),
        "chunks": chunks.iter().enumerate().map(|(idx, chunk)| json!({
            "chunk": idx + 1,
            "tokens": chunk.tokens,
            "file_count": chunk.files.len(),
        })).collect::<Vec<_>>()
    }))
}

fn render_audit_report(args: Value) -> Result<Value> {
    let mut args: RenderReportArgs = parse_args(args)?;
    let root = workspace_root()?;
    bind_render_args(&root, &mut args, crate::workflow::WorkflowKind::Audit)?;
    let format = format_arg(&args.format)?;
    let out = args
        .out
        .unwrap_or_else(|| audit::default_output_path(format));
    let output_path = config::resolve_workspace_output_path(&root, &out)?;
    let findings_payload = findings_payload(args.findings.as_ref(), "audit")?;
    let report = report_body(args.report, "# Audit Issues", findings_payload.as_deref())?;
    let report = with_machine_readable_findings(report, findings_payload.as_deref(), "audit");
    let report = audit::report::with_audit_transparency_line(
        &report,
        &audit::report::audit_transparency_snippet(
            args.model.as_deref(),
            args.focus.as_deref(),
            &out,
            args.max_chunks,
            format,
        ),
    );
    let report = with_workflow_provenance(&root, report)?;
    let finding_count = audit::report::findings_from_report(&report).len();
    let output = match args.format.as_str() {
        "markdown" => audit::report::with_succinct_findings_summary(&report),
        "sarif" => audit::report::render_sarif(&report)?,
        other => bail!("unsupported audit report format: {other}"),
    };
    config::write_workspace_file(&output_path, output.as_bytes())?;
    Ok(json!({
        "output": output_path,
        "format": args.format,
        "findings": finding_count,
    }))
}

fn render_review_report(args: Value) -> Result<Value> {
    let mut args: RenderReportArgs = parse_args(args)?;
    let root = workspace_root()?;
    bind_render_args(&root, &mut args, crate::workflow::WorkflowKind::Review)?;
    render_review_report_at(&root, args)
}

fn bind_render_args(
    root: &Path,
    args: &mut RenderReportArgs,
    expected: crate::workflow::WorkflowKind,
) -> Result<()> {
    let Some(context) = crate::workflow::current(root)? else {
        return Ok(());
    };
    if context.kind != expected && context.kind != crate::workflow::WorkflowKind::Enhance {
        bail!("workflow context kind does not match renderer");
    }
    if expected != crate::workflow::WorkflowKind::Enhance {
        let state = BOUND_WORKFLOW_STATE
            .lock()
            .map_err(|_| anyhow!("workflow state lock poisoned"))?;
        let state = state
            .as_ref()
            .ok_or_else(|| anyhow!("workflow_not_prepared: collect chunks before rendering"))?;
        if state.run_id != context.run_id || state.next_chunk <= state.chunk_count {
            bail!(
                "chunks_incomplete: read all {} chunks before rendering",
                state.chunk_count
            );
        }
    }
    args.out = Some(context.output);
    args.format = context.format;
    args.model = context.model;
    args.focus = (!context.focus.is_empty()).then(|| context.focus.join(" "));
    args.max_chunks = Some(context.max_chunks);
    args.target = match context.scope {
        crate::workflow::WorkflowScope::GitDiff { target, .. } => Some(target),
        crate::workflow::WorkflowScope::Workspace { .. } => None,
    };
    Ok(())
}

fn render_review_report_at(root: &Path, mut args: RenderReportArgs) -> Result<Value> {
    if args.format != "markdown" {
        bail!("review reports support markdown only");
    }
    let out = args
        .out
        .take()
        .unwrap_or_else(crate::review::default_output_path);
    let output_path = config::resolve_workspace_output_path(root, &out)?;
    let findings_payload = findings_payload(args.findings.as_ref(), "review")?;
    let report = report_body(
        args.report,
        "# Code Quality Review",
        findings_payload.as_deref(),
    )?;
    let report = with_machine_readable_findings(report, findings_payload.as_deref(), "review");
    let report = audit::report::with_review_transparency_line(
        &report,
        &audit::report::review_transparency_snippet(
            args.model.as_deref(),
            args.target.as_deref(),
            args.focus.as_deref(),
            &out,
            args.max_chunks,
        ),
    );
    let output = with_workflow_provenance(root, report)?;
    config::write_workspace_file(&output_path, output.as_bytes())?;
    Ok(json!({
        "output": output_path,
        "format": "markdown",
        "findings": audit::report::findings_from_report(&output).len(),
    }))
}

fn with_workflow_provenance(root: &Path, report: String) -> Result<String> {
    let Some(context) = crate::workflow::current(root)? else {
        return Ok(report);
    };
    let session = context.session_id.as_deref().unwrap_or("unknown");
    let line = format!(
        "> oy workflow: run `{}` · session `{session}` · bound max_chunks `{}`",
        context.run_id, context.max_chunks
    );
    let mut lines = report.lines().map(ToOwned::to_owned).collect::<Vec<_>>();
    let index = lines
        .iter()
        .position(|existing| existing.starts_with("> Generated with"))
        .map_or(1.min(lines.len()), |index| index + 1);
    lines.insert(index, line);
    let mut out = lines.join("\n");
    out.push('\n');
    Ok(out)
}

fn report_body(
    report: Option<String>,
    title: &str,
    findings_payload: Option<&str>,
) -> Result<String> {
    if let Some(report) = report.filter(|report| !report.trim().is_empty()) {
        return Ok(report);
    }
    let payload = findings_payload.ok_or_else(|| anyhow!("report or findings is required"))?;
    Ok(format!(
        "{title}\n\n## Machine-readable findings\n\n```json oy-findings\n{payload}\n```\n"
    ))
}

fn findings_payload(findings: Option<&Value>, fallback_source: &str) -> Result<Option<String>> {
    findings
        .map(|findings| {
            audit::report::normalized_findings_payload(findings, fallback_source).ok_or_else(|| {
                anyhow!(
                    "findings must be a JSON array or an object with a findings/oy-findings array"
                )
            })
        })
        .transpose()
}

fn with_machine_readable_findings(
    report: String,
    findings_payload: Option<&str>,
    source: &str,
) -> String {
    if let Some(payload) = findings_payload {
        audit::report::with_structured_findings_payload(&report, payload)
    } else {
        audit::report::with_structured_findings_block(&report, source)
    }
}

fn file_summaries(files: &[input::AuditFile]) -> Vec<Value> {
    files
        .iter()
        .take(200)
        .map(|file| {
            let mut value = json!({
                "path": file.path,
                "language": file.language,
                "bytes": file.bytes,
                "tokens": file.tokens,
            });
            if let Some(slice) = &file.slice {
                value["slice"] = json!({
                    "index": slice.index,
                    "count": slice.count,
                    "start_byte": slice.start_byte,
                    "end_byte": slice.end_byte,
                    "start_line": slice.start_line,
                    "end_line": slice.end_line,
                });
            }
            value
        })
        .collect()
}

fn workspace_root() -> Result<PathBuf> {
    if let Some(root) = crate::workflow::active_workspace() {
        return Ok(root);
    }
    config::oy_root()
}

fn collect_workspace_input_files(
    root: &Path,
    path: &str,
    model: &str,
) -> Result<Vec<input::AuditFile>> {
    if let Some(key) = clean_repo_cache_key(root, path, model) {
        if let Some(files) = CLEAN_REPO_INPUT_CACHE.lock().unwrap().get(&key).cloned() {
            return Ok(files);
        }
        let files = collect_workspace_input_files_uncached(root, path, model)?;
        CLEAN_REPO_INPUT_CACHE
            .lock()
            .unwrap()
            .insert(key, files.clone());
        return Ok(files);
    }
    collect_workspace_input_files_uncached(root, path, model)
}

fn collect_workspace_input_files_uncached(
    root: &Path,
    path: &str,
    model: &str,
) -> Result<Vec<input::AuditFile>> {
    let resolved = resolve_workspace_path(root, path)?;
    if resolved.is_dir() {
        let prefix = resolved
            .strip_prefix(
                root.canonicalize()
                    .context("failed to resolve workspace root")?,
            )
            .context("path escapes workspace")?
            .to_string_lossy()
            .replace('\\', "/");
        let prefix = prefix.trim_matches('/').to_string();
        let prefix_with_sep = format!("{prefix}/");
        return Ok(input::collect_files(root, None, model)?
            .into_iter()
            .filter(|file| {
                prefix.is_empty()
                    || file.path == prefix
                    || file.path.starts_with(prefix_with_sep.as_str())
            })
            .collect());
    }
    if !resolved.is_file() {
        bail!("path is not a file or directory: {path}");
    }
    Ok(input::collect_file(root, &resolved, model)?
        .into_iter()
        .collect())
}

fn clean_repo_cache_key(root: &Path, path: &str, model: &str) -> Option<String> {
    let head = git_output(root, &["rev-parse", "HEAD"]).ok()?;
    let status = git_output(
        root,
        &["status", "--porcelain=v1", "--untracked-files=normal"],
    )
    .ok()?;
    if !status.trim().is_empty() {
        return None;
    }
    Some(format!(
        "{}\0{}\0{}\0{}",
        root.canonicalize().ok()?.display(),
        head.trim(),
        path,
        model
    ))
}

fn resolve_workspace_path(root: &Path, path: &str) -> Result<PathBuf> {
    let root = root
        .canonicalize()
        .context("failed to resolve workspace root")?;
    let raw = Path::new(path);
    if raw
        .components()
        .any(|component| matches!(component, Component::ParentDir))
    {
        bail!("path must stay inside workspace: {path}");
    }
    if !raw.is_absolute()
        && raw
            .components()
            .any(|component| matches!(component, Component::Prefix(_)))
    {
        bail!("path must stay inside workspace: {path}");
    }

    let candidate = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        root.join(raw)
    };
    let resolved = candidate
        .canonicalize()
        .with_context(|| format!("path does not exist: {path}"))?;
    if !resolved.starts_with(&root) {
        bail!("path escapes workspace: {path}");
    }
    Ok(resolved)
}

fn validate_target_ref(target: &str) -> Result<()> {
    if target.trim().is_empty() {
        bail!("target cannot be empty");
    }
    if target.starts_with('-') {
        bail!("target must be a branch/commit/ref, not an option-like value");
    }
    if target.contains('\0') || target.contains('\n') || target.contains('\r') {
        bail!("target contains invalid control characters");
    }
    Ok(())
}

fn git_output(root: &Path, args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(root)
        .output()
        .with_context(|| format!("failed to run git {}", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git {} failed: {}",
            args.join(" "),
            stderr.trim().lines().next().unwrap_or("unknown git error")
        );
    }
    String::from_utf8(output.stdout).context("git output was not UTF-8")
}

fn parse_args<T: for<'de> Deserialize<'de>>(value: Value) -> Result<T> {
    serde_json::from_value(value).context("invalid tool arguments")
}

fn format_arg(format: &str) -> Result<audit::AuditOutputFormat> {
    match format {
        "markdown" => Ok(audit::AuditOutputFormat::Markdown),
        "sarif" => Ok(audit::AuditOutputFormat::Sarif),
        other => bail!("unsupported report format: {other}"),
    }
}

fn default_path() -> String {
    ".".to_string()
}

fn default_model() -> String {
    DEFAULT_MODEL_FOR_COUNTING.to_string()
}

fn default_true() -> bool {
    true
}

fn default_security_index_limit() -> usize {
    120
}

fn default_target_tokens() -> usize {
    DEFAULT_TARGET_TOKENS
}

fn default_markdown() -> String {
    "markdown".to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    const DOCUMENTED_TOOL_NAMES: &[&str] = &[
        "workflow_status",
        "repo_manifest",
        "repo_chunks",
        "git_diff_input",
        "existing_report",
        "sloc",
        "outline",
        "sighthound",
        "render_audit_report",
        "render_review_report",
    ];

    #[tokio::test]
    async fn initialize_negotiates_latest_protocol_and_retains_fallback() {
        let response = handle_request(
            "initialize",
            json!({ "protocolVersion": LATEST_PROTOCOL_VERSION }),
        )
        .await
        .unwrap()
        .into_json(json!(1));

        assert_eq!(
            response["result"]["protocolVersion"],
            LATEST_PROTOCOL_VERSION
        );
        assert_eq!(response["result"]["serverInfo"]["name"], "oy");
        assert_eq!(
            response["result"]["serverInfo"]["version"],
            env!("CARGO_PKG_VERSION")
        );
        assert!(response["result"]["capabilities"]["tools"].is_object());

        let fallback = handle_request("initialize", Value::Null)
            .await
            .unwrap()
            .into_json(json!(2));
        assert_eq!(
            fallback["result"]["protocolVersion"],
            FALLBACK_PROTOCOL_VERSION
        );
    }

    #[tokio::test]
    async fn tool_call_failure_returns_normal_is_error_result() {
        let response = handle_request(
            "tools/call",
            json!({ "name": "missing_tool", "arguments": {} }),
        )
        .await
        .unwrap()
        .into_json(json!(3));

        assert!(response.get("error").is_none());
        assert_eq!(response["result"]["isError"], true);
        assert_eq!(response["result"]["content"].as_array().unwrap().len(), 1);
        assert_eq!(response["result"]["content"][0]["type"], "text");
        assert!(
            response["result"]["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("unknown oy MCP tool: missing_tool")
        );
    }

    #[test]
    fn successful_json_result_includes_matching_structured_content() {
        let value = json!({ "answer": 42 });
        let result = tool_success_result(value.clone()).unwrap();

        assert_eq!(result["structuredContent"], value);
        assert_eq!(result["isError"], false);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("42")
        );
    }

    #[test]
    fn requested_chunk_uses_full_chunk_as_primary_text() {
        let chunk = input::AuditChunk {
            files: vec![input::AuditFile {
                path: "src/lib.rs".to_string(),
                language: "Rust",
                bytes: 13,
                tokens: 4,
                text: "fn lib() {}\n".to_string(),
                slice: None,
            }],
            tokens: 4,
        };
        let value =
            chunks_response("workspace", "manifest".to_string(), vec![chunk], Some(1)).unwrap();
        let expected_text = value["text"].as_str().unwrap().to_string();
        let result = tool_success_result(value.clone()).unwrap();

        assert_eq!(result["content"][0]["text"], expected_text);
        assert!(result.get("structuredContent").is_none());
        assert!(expected_text.contains("## src/lib.rs"));
        assert!(expected_text.contains("fn lib() {}"));
    }

    #[tokio::test]
    async fn tools_list_matches_inventory_and_reference() {
        let response = handle_request("tools/list", Value::Null)
            .await
            .unwrap()
            .into_json(json!(2));
        let names = response["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|tool| tool["name"].as_str().unwrap())
            .collect::<Vec<_>>();
        let mut expected = vec![
            "workflow_status",
            "repo_manifest",
            "repo_chunks",
            "git_diff_input",
            "existing_report",
        ];
        if crate::tools::has_external_sloc_counter() {
            expected.push("sloc");
        }
        if crate::tools::has_external_outline_tool() {
            expected.push("outline");
        }
        if crate::tools::has_external_security_scanner() {
            expected.push("sighthound");
        }
        expected.extend(["render_audit_report", "render_review_report"]);

        assert_eq!(names, expected);
        let reference = include_str!("../docs/reference.md");
        for name in DOCUMENTED_TOOL_NAMES {
            assert!(
                reference.contains(&format!("`{name}`")),
                "docs/reference.md is missing the `{name}` MCP tool"
            );
        }
    }

    #[tokio::test]
    async fn unknown_method_returns_top_level_jsonrpc_error() {
        let response = handle_request("missing/method", Value::Null)
            .await
            .unwrap()
            .into_json(json!(7));

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], 7);
        assert!(response.get("result").is_none());
        assert_eq!(response["error"]["code"], -32601);
        assert!(
            response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("unknown MCP method: missing/method")
        );
    }

    #[test]
    fn sloc_tool_is_listed_only_when_tokei_is_available() {
        let tools = tool_definitions();
        let has_sloc = tools.iter().any(|tool| tool["name"] == "sloc");

        assert_eq!(has_sloc, crate::tools::has_external_sloc_counter());
    }

    #[test]
    fn outline_tool_is_listed_only_when_ctags_is_available() {
        let tools = tool_definitions();
        let has_outline = tools.iter().any(|tool| tool["name"] == "outline");

        assert_eq!(has_outline, crate::tools::has_external_outline_tool());
    }

    #[test]
    fn sighthound_tool_is_listed_only_when_scanner_is_available() {
        let tools = tool_definitions();
        let has_sighthound = tools.iter().any(|tool| tool["name"] == "sighthound");

        assert_eq!(
            has_sighthound,
            crate::tools::has_external_security_scanner()
        );
    }

    #[test]
    fn existing_report_tool_is_listed() {
        let tools = tool_definitions();

        assert!(tools.iter().any(|tool| tool["name"] == "existing_report"));
    }

    #[test]
    fn mcp_workspace_path_accepts_absolute_path_inside_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("src");
        std::fs::create_dir(&nested).unwrap();

        let resolved = resolve_workspace_path(dir.path(), nested.to_str().unwrap()).unwrap();

        assert_eq!(resolved, nested.canonicalize().unwrap());
    }

    #[test]
    fn mcp_workspace_path_rejects_absolute_path_outside_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();

        let err = resolve_workspace_path(dir.path(), outside.path().to_str().unwrap()).unwrap_err();

        assert!(err.to_string().contains("path escapes workspace"));
    }

    #[test]
    fn repo_input_accepts_file_path_and_preserves_workspace_relative_path() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("src");
        std::fs::create_dir(&nested).unwrap();
        std::fs::write(nested.join("lib.rs"), "fn main() {}\n").unwrap();

        let files = collect_workspace_input_files(dir.path(), "src/lib.rs", "cl100k_base").unwrap();

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/lib.rs");
    }

    #[test]
    fn repo_input_accepts_directory_path_and_preserves_workspace_relative_paths() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("src");
        std::fs::create_dir(&nested).unwrap();
        std::fs::write(nested.join("lib.rs"), "fn lib() {}\n").unwrap();
        std::fs::write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();

        let files = collect_workspace_input_files(dir.path(), "src", "cl100k_base").unwrap();

        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/lib.rs");
    }

    #[test]
    fn existing_report_reads_default_audit_report() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("ISSUES.md"),
            "# Audit Issues\n\n### High: stale but structured\n\nEvidence: src/lib.rs:1\n",
        )
        .unwrap();

        let report = existing_report_at(
            dir.path(),
            ExistingReportArgs {
                kind: "audit".to_string(),
                out: None,
            },
        )
        .unwrap();

        assert_eq!(report["exists"], true);
        assert_eq!(report["findings"], 1);
        assert!(
            report["report"]
                .as_str()
                .unwrap()
                .contains("stale but structured")
        );
    }

    #[test]
    fn existing_report_returns_absent_default_review_report() {
        let dir = tempfile::tempdir().unwrap();

        let report = existing_report_at(
            dir.path(),
            ExistingReportArgs {
                kind: "review".to_string(),
                out: None,
            },
        )
        .unwrap();

        assert_eq!(report["exists"], false);
        assert_eq!(report["path"], "REVIEW.md");
        assert_eq!(report["report"], "");
    }

    #[test]
    fn render_review_report_adds_empty_findings_block_for_no_findings() {
        let dir = tempfile::tempdir().unwrap();

        let args = parse_args(json!({
            "report": "# Code Quality Review\n\n## Verdict\n\nNo major structural concerns.\n",
            "out": "REVIEW.md",
            "model": "openai/gpt-5.5"
        }))
        .unwrap();
        let result = render_review_report_at(dir.path(), args).unwrap();

        let report = std::fs::read_to_string(dir.path().join("REVIEW.md")).unwrap();
        assert_eq!(result["findings"], 0);
        assert!(report.contains("OY_OPENCODE_MODEL=openai/gpt-5.5 oy review"));
        assert!(report.contains("```json oy-findings\n[]\n```"));
    }

    #[test]
    fn render_review_report_uses_supplied_findings_with_markdown_report() {
        let dir = tempfile::tempdir().unwrap();

        let args = parse_args(json!({
            "report": "# Code Quality Review\n\n## Verdict\n\nNeeds work.\n\n## Machine-readable findings\n\n```json oy-findings\nnot json\n```\n",
            "findings": [{
                "severity": "Medium",
                "title": "diff keeps duplicate source of truth",
                "locations": [{ "path": "src/lib.rs", "line": 7 }],
                "evidence": "src/lib.rs:7 duplicates the option list",
                "body": "Use one canonical option list."
            }],
            "out": "REVIEW.md"
        }))
        .unwrap();
        let result = render_review_report_at(dir.path(), args).unwrap();

        let report = std::fs::read_to_string(dir.path().join("REVIEW.md")).unwrap();
        assert_eq!(result["findings"], 1);
        assert_eq!(report.matches("```json oy-findings").count(), 1);
        assert!(!report.contains("not json"));
        assert!(report.contains("src/lib.rs:7 duplicates the option list"));
        assert!(report.contains("Use one canonical option list."));
    }
}