scc-cli 0.2.11

System Context Compiler CLI, daemon, MCP server, and Claude Code plugin
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
//! Export validation against `docs/system-ir.schema.json` and MCP end-to-end
//! tests (docs/TEST_PLAN.md §14, docs/API_AND_INTEGRATIONS.md §1).

mod common;
use common::*;
use std::io::Write;
use std::process::{Command, Stdio};

// Daemon guard: kill the child when the test scope exits, even on
// assertion failure (a leaked `scc serve` would hold the port and poison
// sibling tests in this binary).
// trace:exempt reason=test-helper
struct DaemonGuard(std::process::Child);
// trace:exempt reason=test-helper
impl Drop for DaemonGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}
// trace:v1 id=test.scc.interfaces verifies=REQ-SCC-API exercises=impl.scc.mcp,impl.scc.http,impl.scc.cli

#[test]
// trace:v1 id=test.crates-scc-cli-tests-interfaces.export-validates-against-json-schema work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
fn export_validates_against_json_schema() {
    let repo = copy_fixture("monorepo-acceptance");
    std::fs::create_dir_all(workdir(repo.path()).join(".scc")).unwrap();
    std::fs::write(
        workdir(repo.path()).join(".scc/intent.yaml"),
        "components:\n  api:\n    owns: [transcript]\n",
    )
    .unwrap();
    run_ok(&workdir(repo.path()), &["index", "--quiet"]);
    let ir = run_ok(&workdir(repo.path()), &["export", "system-ir.json"]);
    let value: serde_json::Value = serde_json::from_str(&ir).unwrap();

    let schema_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("docs/system-ir.schema.json");
    let schema_text = std::fs::read_to_string(&schema_path).unwrap();
    let schema: serde_json::Value = serde_json::from_str(&schema_text).unwrap();
    let compiled = jsonschema::validator_for(&schema).expect("schema compiles");
    let result = compiled.validate(&value);
    assert!(
        result.is_ok(),
        "System IR export violates the documented schema: {:?}",
        result.err().map(|e| e.to_string())
    );
}

#[test]
// trace:exempt reason=unit-test
fn mcp_server_exposes_ten_semantic_tools() {
    let repo = copy_fixture("http-service-python");
    run_ok(&workdir(repo.path()), &["index", "--quiet"]);

    let mut child = Command::new(scc())
        .arg("mcp")
        .current_dir(workdir(repo.path()))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    let send = |stdin: &mut std::process::ChildStdin, msg: &str| {
        writeln!(stdin, "{msg}").unwrap();
        stdin.flush().unwrap();
    };

    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test"}}}"#,
    );
    send(&mut stdin, r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#);
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"system_overview","arguments":{}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"task_context","arguments":{"goal":"transcript normalization"}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"impact_context","arguments":{"files":["main.py"]}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"system_context","arguments":{}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"surface_map","arguments":{"goal":"transcript normalization"}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"structural_source","arguments":{"files":["main.py"]}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"surface_map","arguments":{}}}"#,
    );
    drop(stdin);

    let mut stdout = String::new();
    use std::io::Read;
    child.stdout.take().unwrap().read_to_string(&mut stdout).unwrap();
    let _ = child.wait();

    let mut by_id: std::collections::BTreeMap<i64, serde_json::Value> = Default::default();
    for line in stdout.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let v: serde_json::Value = serde_json::from_str(line).unwrap();
        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
            by_id.insert(id, v);
        }
    }
    assert_eq!(by_id.len(), 9, "all requests answered: {stdout}");

    let tools = &by_id[&2]["result"]["tools"];
    let names: Vec<&str> = tools
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|t| t["name"].as_str())
        .collect();
    assert_eq!(
        names,
        vec![
            "system_overview",
            "system_atlas",
            "task_context",
            "component_context",
            "flow_context",
            "impact_context",
            "verify_context",
            "system_context",
            "surface_map",
            "structural_source"
        ],
        "the ten semantic tools"
    );
    let overview_text = by_id[&3]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(overview_text.contains("IDENTITY"));
    let task_text = by_id[&4]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(task_text.contains("TASK"));
    assert!(task_text.contains("Normalizer"));
    let impact_text = by_id[&5]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(impact_text.contains("AFFECTED COMPONENTS"));
    // the three new tools: startup fusion renders atlas + surface; the
    // task-personalized map renders the surface map; structural source
    // renders the requested file's units.
    let startup_text = by_id[&6]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(startup_text.contains("## SYSTEM ATLAS"), "{startup_text}");
    assert!(startup_text.contains("## SYSTEM SURFACE MAP"), "{startup_text}");
    assert!(startup_text.contains("## OMISSIONS"), "{startup_text}");
    let surface_text = by_id[&7]["result"]["content"][0]["text"].as_str().unwrap();
    // Wave 15.1: `surface_map` with a goal routes to build_surface Task
    // mode — the response must actually differ from the global render on
    // this fixture (task PPR re-ranking is not a no-op).
    let global_surface = by_id[&9]["result"]["content"][0]["text"].as_str().unwrap();
    assert_ne!(surface_text, global_surface, "task surface must differ from global");
    assert!(
        surface_text.contains("transcript normalization"),
        "{surface_text}"
    );
    assert!(surface_text.contains("handle_transcripts"), "{surface_text}");
    let structural_text = by_id[&8]["result"]["content"][0]["text"].as_str().unwrap();
    assert!(structural_text.contains("source: main.py:L"), "{structural_text}");
}

#[test]
// trace:v1 id=test.scc.interfaces.mcp-stdio-2025-11-25-initialize-then-tools-list verifies=REQ-SCC-API,REQ-implement-p0-omp-integration-correctness-and-writable-benchmark-scient exercises=impl.scc.mcp
fn mcp_stdio_negotiates_2025_11_25_then_lists_tools() {
    // Real stdio subprocess E2E: initialize 2025-11-25 → notifications/initialized
    // → tools/list. The negotiate_protocol unit test is not this contract.
    let repo = copy_fixture("http-service-python");
    run_ok(&workdir(repo.path()), &["index", "--quiet"]);

    let mut child = Command::new(scc())
        .arg("mcp")
        .current_dir(workdir(repo.path()))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    let send = |stdin: &mut std::process::ChildStdin, msg: &str| {
        writeln!(stdin, "{msg}").unwrap();
        stdin.flush().unwrap();
    };

    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"omp-e2e"}}}"#,
    );
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
    );
    send(&mut stdin, r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#);
    drop(stdin);

    let mut stdout = String::new();
    use std::io::Read;
    child.stdout.take().unwrap().read_to_string(&mut stdout).unwrap();
    let _ = child.wait();

    let mut by_id: std::collections::BTreeMap<i64, serde_json::Value> = Default::default();
    for line in stdout.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let v: serde_json::Value = serde_json::from_str(line).unwrap();
        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
            by_id.insert(id, v);
        }
    }
    assert!(by_id.contains_key(&1), "initialize answered: {stdout}");
    assert_eq!(
        by_id[&1]["result"]["protocolVersion"].as_str(),
        Some("2025-11-25"),
        "server must echo 2025-11-25: {stdout}"
    );
    assert!(by_id.contains_key(&2), "tools/list answered after initialized: {stdout}");
    let tools = &by_id[&2]["result"]["tools"];
    let names: Vec<&str> = tools
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|t| t["name"].as_str())
        .collect();
    assert!(names.contains(&"system_context"), "{names:?}");
    assert!(names.contains(&"surface_map"), "{names:?}");
    assert!(names.contains(&"structural_source"), "{names:?}");
    let ctx_tool = tools
        .as_array()
        .unwrap()
        .iter()
        .find(|t| t["name"] == "system_context")
        .unwrap();
    let desc = ctx_tool["description"].as_str().unwrap_or("");
    let budget_desc = ctx_tool["inputSchema"]["properties"]["token_budget"]["description"]
        .as_str()
        .unwrap_or("");
    assert!(
        !budget_desc.contains("13:7") && !desc.contains("13:7"),
        "system_context must not advertise the retired 13:7 split: {budget_desc} / {desc}"
    );
    assert!(
        budget_desc.contains("adaptive") || budget_desc.contains("complexity"),
        "system_context budget description must name adaptive allocation: {budget_desc}"
    );
}

#[test]
// trace:v1 id=test.crates-scc-cli-tests-interfaces.mcp-unknown-tool-returns-error work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
fn mcp_unknown_tool_returns_error() {
    let repo = copy_fixture("http-service-python");
    run_ok(&workdir(repo.path()), &["index", "--quiet"]);
    let mut child = Command::new(scc())
        .arg("mcp")
        .current_dir(workdir(repo.path()))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    {
        let mut stdin = child.stdin.take().unwrap();
        writeln!(
            stdin,
            r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":"query_graph","arguments":{{}}}}}}"#
        )
        .unwrap();
        stdin.flush().unwrap();
    }
    let mut stdout = String::new();
    use std::io::Read;
    child.stdout.take().unwrap().read_to_string(&mut stdout).unwrap();
    let _ = child.wait();
    let v: serde_json::Value = serde_json::from_str(stdout.lines().next().unwrap()).unwrap();
    assert_eq!(v["result"]["isError"], true, "advanced tools are not exposed");
}

#[test]
// trace:v1 id=test.crates-scc-cli-tests-interfaces.context-parity-across-cli-http-mcp work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
fn context_parity_across_cli_http_mcp() {
    // P0 §10: transport must not change semantic quality — the same
    // task_context request yields the same pack content on CLI, HTTP, MCP,
    // WITH embeddings + beads + hindsight ALL enabled (the transports must
    // agree on the enriched pack, not just the default-config pack).
    let repo = copy_fixture("http-service-python");
    let dir = workdir(repo.path());
    // beads task state + hindsight lessons + inference path (loopback
    // endpoint that fails closed to lexical ranking — parity must hold
    // through the same ranker decision on every transport). The config is
    // written FIRST so every transport sees hindsight enabled.
    let addr = test_listen_addr();
    std::fs::create_dir_all(dir.join(".scc")).unwrap();
    std::fs::create_dir_all(dir.join(".beads")).unwrap();
    std::fs::write(
        dir.join(".scc/config.yaml"),
        format!(
            "schema: 1\nindex:\n  watch: false\ninference:\n  enabled: true\n  provider: local\n  base_url: http://127.0.0.1:1\nintegrations:\n  hindsight: true\nsecurity:\n  listen: {addr}\n"
        ),
    )
    .unwrap();
    std::fs::write(
        dir.join(".beads/issues.jsonl"),
        "{\"id\":\"b1\",\"title\":\"Fix normalization retry\",\"status\":\"in_progress\",\"dependencies\":[]}\n",
    )
    .unwrap();
    std::fs::write(
        dir.join(".scc/lessons.jsonl"),
        "{\"id\":\"l1\",\"text\":\"raw transcripts are immutable\",\"created_at\":\"2026-01-01T00:00:00Z\"}\n",
    )
    .unwrap();
    run_ok(
        &dir,
        &["import", "hindsight", ".scc/lessons.jsonl"],
    );
    run_ok(&dir, &["index", "--quiet"]);
    let goal = "change transcript normalization";

    // CLI (JSON pack)
    let cli_json = run_ok(&dir, &["context", "task", "--json", goal]);
    let cli: serde_json::Value = serde_json::from_str(&cli_json).unwrap();
    // The artifact is {pack, delta, delta_ids}; parity is about the PACK
    // half (the delta is ledger-dependent per transport session).
    let cli_content = cli["pack"]["content"].as_str().unwrap().to_string();
    assert!(
        cli_content.contains("ACTIVE TASK STATE"),
        "beads enrichment present on CLI: {cli_content}"
    );
    assert!(
        cli_content.contains("HINDSIGHT LESSONS"),
        "hindsight enrichment present on CLI: {cli_content}"
    );
    let _child = DaemonGuard(
        Command::new(scc())
            .arg("serve")
            .current_dir(&dir)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap(),
    );
    let mut ready = false;
    for _ in 0..40 {
        if std::net::TcpStream::connect(addr.as_str()).is_ok() {
            ready = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    assert!(ready, "daemon did not start");
    let post = |path: &str, body: &str| -> (u16, String) {
        let mut stream = std::net::TcpStream::connect(addr.as_str()).unwrap();
        write!(
            stream,
            "POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        )
        .unwrap();
        let mut buf = String::new();
        use std::io::Read;
        stream.read_to_string(&mut buf).unwrap();
        let status: u16 = buf.split_whitespace().nth(1).unwrap().parse().unwrap();
        let body = buf.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
        (status, body)
    };
    let (s, http_body) = post(
        "/v1/context/task",
        &format!(r#"{{"goal":"{goal}"}}"#),
    );
    assert_eq!(s, 200);
    let http: serde_json::Value = serde_json::from_str(&http_body).unwrap();
    let http_content = http["pack"]["content"].as_str().unwrap().to_string();
    assert!(
        http["delta"].as_str().is_some_and(|d| !d.is_empty()),
        "HTTP artifact must carry the surface delta"
    );
    drop(_child);

    // MCP server
    let mut child = Command::new(scc())
        .arg("mcp")
        .current_dir(&dir)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    let send = |stdin: &mut std::process::ChildStdin, msg: &str| {
        writeln!(stdin, "{msg}").unwrap();
        stdin.flush().unwrap();
    };
    send(
        &mut stdin,
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"parity"}}}"#,
    );
    send(
        &mut stdin,
        &format!(
            r#"{{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{{"name":"task_context","arguments":{{"goal":"{goal}"}}}}}}"#
        ),
    );
    drop(stdin);
    let mut stdout = String::new();
    use std::io::Read;
    child.stdout.take().unwrap().read_to_string(&mut stdout).unwrap();
    let _ = child.wait();
    let mut mcp_content = String::new();
    for line in stdout.lines() {
        let v: serde_json::Value = serde_json::from_str(line).unwrap();
        if v.get("id").and_then(|i| i.as_i64()) == Some(2) {
            mcp_content = v["result"]["content"][0]["text"].as_str().unwrap().to_string();
        }
    }
    assert!(!mcp_content.is_empty(), "MCP answered: {stdout}");

    // parity: identical PACK content on every transport; MCP delivers it
    // together with the delta (pack-only responses were a downgrade)
    assert_eq!(cli_content, http_content, "CLI and HTTP packs differ");
    assert!(
        mcp_content.starts_with(&cli_content),
        "CLI and MCP packs differ (MCP must lead with the same pack)"
    );

    // Spec 2: the registry is the single derivation — direct engine invoke
    // matches the CLI artifact pack exactly (same input, same engine).
    let engine_out = scc_engine::invoke(
        &dir,
        "context.task",
        serde_json::json!({"goal": goal, "files": [], "symbols": [], "budget": null, "hook": false}),
    )
    .unwrap();
    // NB: the ledger records each shown render, so the engine pack may
    // legitimately differ in delta-adjacent content after three transports
    // already rendered; assert structural equivalence of the pack instead.
    assert!(
        engine_out["pack"]["content"].as_str().is_some_and(|c| !c.is_empty()),
        "engine invoke must produce a pack"
    );
    assert!(
        engine_out["pack"]["content"].as_str().unwrap().contains("ACTIVE TASK STATE"),
        "engine pack carries the same enrichment"
    );
}

#[test]
// trace:exempt reason=unit-test
fn structural_source_cli_renders_file_units() {
    // Item 7: `scc context structural` is the product CLI for the
    // Structural Source representation. --files renders the requested
    // file's units; --task resolves matching files via the lexical
    // fallback. Both must be non-empty on an indexed fixture.
    let repo = copy_fixture("http-service-python");
    let dir = workdir(repo.path());
    run_ok(&dir, &["index", "--quiet"]);

    let out = run_ok(&dir, &["context", "structural", "--files", "main.py"]);
    assert!(out.contains("source: main.py:L"), "unit provenance: {out}");
    assert!(out.contains("revision:"), "revision header: {out}");
    assert!(out.contains("handle_transcripts"), "symbol rendered: {out}");

    let task = run_ok(
        &dir,
        &["context", "structural", "--task", "transcript normalization"],
    );
    assert!(task.contains("representation:"), "task-matched units: {task}");
    assert!(task.contains("transcripts.py"), "task matched the service file: {task}");

    // budget caps the unit count without breaking rendering
    let capped = run_ok(&dir, &["context", "structural", "--files", "main.py", "--budget", "1000"]);
    assert!(capped.contains("source: main.py:L"), "budgeted render: {capped}");
}

#[test]
// trace:v1 id=test.scc.cli.handle-refused verifies=REQ-implement-phase-12-of-scc-x-ripwire-lessons-java-unprefixed-field-as exercises=impl.scc.structural.resolve-handle
fn structural_stale_handle_is_refused_on_cli() {
    let repo = copy_fixture("http-service-python");
    let dir = workdir(repo.path());
    run_ok(&dir, &["index", "--quiet"]);
    let stale = "scc://repo/epoch/file/main.py@aaaaaaaaaaaaaaaa";
    let out = run_ok(&dir, &["context", "structural", "--files", stale]);
    assert!(
        out.contains("HANDLE REFUSED"),
        "CLI must refuse a stale handle: {out}"
    );
    assert!(out.contains("stale"), "refusal must name staleness: {out}");
    assert!(
        !out.contains("handle_transcripts"),
        "must not guess and serve the file: {out}"
    );
}

#[test]
// trace:v1 id=test.scc.cli.corrupt-db-refuses verifies=REQ-implement-phase-12-of-scc-x-ripwire-lessons-java-unprefixed-field-as exercises=impl.scc.store.refuse-corrupt
fn corrupt_index_cache_refuses_instead_of_empty_atlas() {
    let repo = copy_fixture("http-service-python");
    let dir = workdir(repo.path());
    run_ok(&dir, &["index", "--quiet"]);
    let db = dir.join(".scc/scc.db");
    let _ = std::fs::remove_file(dir.join(".scc/scc.db-wal"));
    let _ = std::fs::remove_file(dir.join(".scc/scc.db-shm"));
    std::fs::write(&db, b"not a sqlite database").unwrap();
    let out = run(&dir, &["status"]);
    assert!(
        !out.status.success(),
        "corrupt cache must fail, not print an empty index"
    );
    let err = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stderr),
        String::from_utf8_lossy(&out.stdout)
    );
    assert!(
        err.contains("corrupt") || err.contains("not a SQLite"),
        "must disclose corruption: {err}"
    );
    assert!(
        !err.contains("components: 0") && !err.to_lowercase().contains("not indexed yet"),
        "must not fabricate a fresh empty index: {err}"
    );
}

#[test]
// trace:v1 id=test.crates-scc-cli-tests-interfaces.http-daemon-endpoints work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
fn http_daemon_endpoints() {
    let repo = copy_fixture("http-service-python");
    run_ok(&workdir(repo.path()), &["index", "--quiet"]);
    // override the listen address via config for this repo; ephemeral so
    // this test cannot collide with context_parity in the same binary
    let addr = test_listen_addr();
    std::fs::write(
        workdir(repo.path()).join(".scc/config.yaml"),
        format!("schema: 1\nindex:\n  watch: false\nsecurity:\n  listen: {addr}\n"),
    )
    .unwrap();

    let _child = DaemonGuard(
        Command::new(scc())
            .arg("serve")
            .current_dir(workdir(repo.path()))
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap(),
    );

    // poll until the port accepts connections
    let mut ready = false;
    for _ in 0..40 {
        if std::net::TcpStream::connect(addr.as_str()).is_ok() {
            ready = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    assert!(ready, "daemon did not start");

    let get = |path: &str| -> (u16, String) {
        let mut stream = std::net::TcpStream::connect(addr.as_str()).unwrap();
        write!(stream, "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
        let mut buf = String::new();
        use std::io::Read;
        stream.read_to_string(&mut buf).unwrap();
        let status: u16 = buf
            .split_whitespace()
            .nth(1)
            .unwrap()
            .parse()
            .unwrap();
        let body = buf.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
        (status, body)
    };
    let post = |path: &str, body: &str| -> (u16, String) {
        let mut stream = std::net::TcpStream::connect(addr.as_str()).unwrap();
        write!(
            stream,
            "POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        )
        .unwrap();
        let mut buf = String::new();
        use std::io::Read;
        stream.read_to_string(&mut buf).unwrap();
        let status: u16 = buf.split_whitespace().nth(1).unwrap().parse().unwrap();
        let body = buf.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
        (status, body)
    };

    let (s, _) = get("/healthz");
    assert_eq!(s, 200);
    let (s, body) = get("/v1/index/status");
    assert_eq!(s, 200);
    assert!(body.contains("\"indexed\":true"), "{body}");
    let (s, body) = get("/v1/system");
    assert_eq!(s, 200);
    assert!(body.contains("IDENTITY"), "{body}");
    let (s, body) = post("/v1/context/task", r#"{"goal":"transcript normalization"}"#);
    assert_eq!(s, 200);
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
    // /v1/context/task returns THE complete artifact {pack, delta, delta_ids}
    assert_eq!(v["pack"]["kind"], "task");
    assert!(v["delta"].is_string(), "artifact carries the surface delta");
    let (s, _body) = post("/v1/runtime/traces", r#"[{"source":"a","target":"b","count":3}]"#);
    assert_eq!(s, 202);
    let (s, body) = post("/v1/impact", r#"{"files":["main.py"]}"#);
    assert_eq!(s, 200);
    assert!(body.contains("AFFECTED COMPONENTS"), "{body}");
    let (s, body) = post("/v1/verify", "{}");
    assert_eq!(s, 200);
    assert!(body.contains("FRESHNESS"), "{body}");
    let (s, body) = get("/v1/operations");
    assert_eq!(s, 200);
    // §82 discovery: every entry carries its stability class.
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
    let ops = v["operations"].as_array().unwrap();
    assert!(ops.len() >= 50, "{v}");
    assert!(ops.iter().all(|o| o.get("stability").and_then(|x| x.as_str()).is_some()), "{v}");
    let (s, body) = post("/v1/operations/ranking.seeds", r#"{"goal":"transcript"}"#);
    assert_eq!(s, 200);
    assert!(body.contains("\"seeds\""), "{body}");
    // Spec §10: per-operation GET describes one op + its input schema.
    let (s, body) = get("/v1/operations/ranking.symbols");
    assert_eq!(s, 200);
    assert!(body.contains("ranking.symbols"), "{body}");
    assert!(body.contains("limit") || body.contains("goal"), "{body}");
    let (s, _) = get("/v1/operations/nope.nope");
    assert_eq!(s, 404);
    let (s, _) = get("/v1/nope");
    assert_eq!(s, 404);
    drop(_child);
}

/// Bind an ephemeral port so two HTTP tests in this binary cannot share a
/// listen address. `20000 + pid` collided when cargo ran
/// `context_parity_across_cli_http_mcp` and `http_daemon_endpoints` in
/// parallel: the parity POST hit the other daemon (no beads/hindsight).
// trace:exempt reason=internal-helper
fn test_listen_addr() -> String {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral");
    listener.local_addr().expect("local_addr").to_string()
}

// DoD 45: transports implement nothing. `httpd.rs` and `mcp.rs` must not
// name engine implementation types or call store-write / ranking-math
// entrypoints directly — they parse, dispatch into the operation registry
// (`scc_engine::invoke`) or the typed engine namespaces via commands, and
// render. `commands.rs` is the sanctioned CLI-client layer (typed engine
// calls + invoke + terminal rendering), so it is out of scope here.
#[test]
// trace:v1 id=test.crates-scc-cli-tests-interfaces.transports-implement-nothing work=WORK-SI-MMMJA4G6 verifies=REQ-SI-503JSBGP
fn transports_implement_nothing() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    for file in ["src/httpd.rs", "src/mcp.rs"] {
        let text = std::fs::read_to_string(root.join(file)).unwrap();
        for banned in [
            "ContextCompiler",
            "SystemRanker",
            "insert_entity",
            "insert_relationship",
            "insert_evidence",
            "final_importance",
            "build_surface",
            "open_engine",
            "inference::rankers",
        ] {
            assert!(
                !text.contains(banned),
                "{file} must not reference engine internals ({banned}): transports dispatch via invoke"
            );
        }
    }
    // Every invoke target named in the CLI crate must be a registered op.
    let cli = std::fs::read_to_string(root.join("src/commands.rs")).unwrap()
        + &std::fs::read_to_string(root.join("src/httpd.rs")).unwrap()
        + &std::fs::read_to_string(root.join("src/mcp.rs")).unwrap();
    let mut targets: Vec<String> = Vec::new();
    let mut pos = 0;
    while let Some(i) = cli[pos..].find("invoke(") {
        let seg = &cli[pos + i..];
        if let Some(q1) = seg.find('"') {
            let rest = &seg[q1 + 1..];
            if let Some(q2) = rest.find('"') {
                let op: String = rest[..q2].to_string();
                if op.contains('.') {
                    targets.push(op);
                }
            }
        }
        pos += i + 7;
    }
    targets.sort();
    targets.dedup();
    assert!(!targets.is_empty(), "expected invoke targets in the CLI crate");
    for op in &targets {
        assert!(
            scc_engine::ops::OPERATIONS.iter().any(|d| d.id == op),
            "CLI invokes unregistered operation '{op}' (see `scc operations`)"
        );
    }
}

#[test]
// trace:v1 id=test.scc-cli-interfaces.operations-describe-shows-schema verifies=REQ-SI-503JSBGP exercises=impl.crates-scc-cli-src-commands.cmd-operations
fn operations_describe_shows_schema() {
    // `scc operations --describe <id>` prints descriptor + input schema
    // in one view (discovery: what it does + what to send it).
    let repo = copy_fixture("http-service-python");
    let out = run_ok(&workdir(repo.path()), &["operations", "--describe", "ranking.symbols"]);
    assert!(out.contains("ranking.symbols"), "{out}");
    assert!(out.contains("limit") || out.contains("goal"), "{out}");
    let out = run_ok(&workdir(repo.path()), &["operations", "--describe", "surface.compile"]);
    assert!(out.contains("surface.compile"), "{out}");
    let out = run_ok(&workdir(repo.path()), &["operations", "--describe", "nope.nope"]);
    assert!(out.contains("unknown operation"), "{out}");
}