scc-engine 0.2.9

SCC engine facade: one orchestration seam for CLI, HTTP, MCP, SDKs, RPC, FFI
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
//! Dynamic operation dispatch: `invoke(id, input_json) -> output_json`.
//!
//! The SAME fns the typed namespaces call — one implementation, two
//! interfaces (spec §4). Transports (RPC/HTTP/SDK/FFI) go through here;
//! the CLI keeps its typed calls. Outputs are the canonical types
//! serialized — never re-modelled strings.

use serde_json::Value;

// trace:exempt reason=internal-detail
pub fn invoke(
    root: &std::path::Path,
    operation: &str,
    input: Value,
) -> crate::Result<Value> {
    let store = crate::workspace::open_store(root)?;
    let config = crate::workspace::load_config(root)?;
    let stale = crate::workspace::stale_paths(&store)?;
    let engine = crate::workspace::open_engine(&store, &config, stale)?;
    let ctx = engine.context();
    let out = match operation {
        "workspace.status" => {
            let s = status_value(&store)?;
            serde_json::to_value(&s)?
        }
        "workspace.languages" => Value::String(scc_core::support_matrix_markdown()),
        "context.overview" => serde_json::to_value(ctx.overview()?)?,
        "context.atlas" => {
            let budget: Option<usize> = input.get("budget").and_then(|v| v.as_u64()).map(|v| v as usize);
            let full: bool = input.get("full").and_then(|v| v.as_bool()).unwrap_or(false);
            let unbounded: bool = input.get("unbounded").and_then(|v| v.as_bool()).unwrap_or(false);
            serde_json::to_value(ctx.atlas(budget, full, unbounded)?)?
        }
        "context.startup" => {
            let req: scc_api::StartupRequest = serde_json::from_value(input).unwrap_or(scc_api::StartupRequest { budget: None });
            // Structured triple: text + budget + artifact. Transports that
            // need a bare string take `.text`; nothing re-derives startup.
            let (startup, text) = ctx.startup(&req)?;
            let budget = scc_context::startup::allocate_startup_budget(&ctx.engine.ctx(), req.budget);
            serde_json::json!({"text": text, "budget": budget, "artifact": startup.artifact})
        }
        "context.task" => {
            let req: scc_api::TaskContextRequest = serde_json::from_value(input)?;
            let (scorer, reranker) = crate::inference::rankers(&store, &config, &req.goal);
            let scorer_trait: Option<&dyn scc_context::rank::SemanticScorer> =
                scorer.as_ref().map(|s| s as &dyn scc_context::rank::SemanticScorer);
            let reranker_trait: Option<&dyn scc_context::rank::Reranker> =
                reranker.as_ref().map(|r| r as &dyn scc_context::rank::Reranker);
            serde_json::to_value(crate::task::build_task_context(&engine, &config, root, &req, scorer_trait, reranker_trait)?)?
        }
        "context.task_pack" => {
            let req: scc_api::TaskContextRequest = serde_json::from_value(input)?;
            let (scorer, reranker) = crate::inference::rankers(&store, &config, &req.goal);
            let scorer_trait: Option<&dyn scc_context::rank::SemanticScorer> =
                scorer.as_ref().map(|s| s as &dyn scc_context::rank::SemanticScorer);
            let reranker_trait: Option<&dyn scc_context::rank::Reranker> =
                reranker.as_ref().map(|r| r as &dyn scc_context::rank::Reranker);
            serde_json::to_value(crate::task::build_enriched_task_pack(&engine, &config, root, &req, scorer_trait, reranker_trait)?)?
        }
        "context.subagent" => {
            let goal = input.get("goal").and_then(|v| v.as_str()).unwrap_or("");
            let files: Vec<String> = input.get("files").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_string())).collect()).unwrap_or_default();
            let symbols: Vec<String> = input.get("symbols").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_string())).collect()).unwrap_or_default();
            let budget = input.get("budget").and_then(|v| v.as_u64()).map(|b| b as usize);
            serde_json::to_value(ctx.subagent(goal, &files, &symbols, budget)?)?
        }
        "context.compress" => {
            // Pack-only compression ladder, no external summarizer, no delta,
            // no ledger: same derivation the CLI uses with --cmd omitted.
            let goal = input.get("goal").and_then(|v| v.as_str()).unwrap_or("");
            let budget = input.get("budget").and_then(|v| v.as_u64()).map(|b| b as usize);
            let (scorer, reranker) = crate::inference::rankers(&store, &config, goal);
            let scorer_trait: Option<&dyn scc_context::rank::SemanticScorer> =
                scorer.as_ref().map(|s| s as &dyn scc_context::rank::SemanticScorer);
            let reranker_trait: Option<&dyn scc_context::rank::Reranker> =
                reranker.as_ref().map(|r| r as &dyn scc_context::rank::Reranker);
            let pack = crate::task::build_enriched_task_pack(&engine, &config, root, &scc_api::TaskContextRequest { goal: goal.into(), files: vec![], symbols: vec![], budget, hook: false }, scorer_trait, reranker_trait)?;
            serde_json::to_value(pack)?
        }
        "context.component" | "context.flow" | "context.impact" | "context.verify" | "context.structural" | "source.structural" | "surface.build" => {
            invoke_context(&ctx, &store, &config, operation, input)?
        }
        "graph.query" => {
            let req: scc_api::QueryRequest = serde_json::from_value(input)?;
            let hit = crate::graph::query(&store, &req)?;
            serde_json::json!({
                "entities": hit.entities,
                "symbols": hit.symbols.iter().map(|(n, s, k, f, l)| serde_json::json!({"name": n, "signature": s, "kind": k, "file": f, "line": l})).collect::<Vec<_>>(),
            })
        }
        "graph.entities" | "architecture.components" => serde_json::to_value(crate::graph::components(&store)?)?,
        "graph.flows" | "architecture.flows" => serde_json::to_value(crate::graph::flows(&store)?)?,
        "graph.relationships" => {
            let subject = input.get("subject").and_then(|v| v.as_str());
            let predicate = input.get("predicate").and_then(|v| v.as_str());
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(100) as usize;
            serde_json::to_value(crate::graph::relationships(&store, subject, predicate, limit)?)?
        }
        "graph.search" => {
            let q = input.get("query").and_then(|v| v.as_str()).unwrap_or("");
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(100) as usize;
            let mut entities = store.search_entities(q, limit)?;
            if entities.is_empty() { entities = store.search_entities_like(q, limit)?; }
            serde_json::to_value(entities)?
        }
        "graph.search_symbols" => {
            let q = input.get("query").and_then(|v| v.as_str()).unwrap_or("");
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(100) as usize;
            let mut symbols = store.search_symbols(q, limit)?;
            if symbols.is_empty() { symbols = store.search_symbols_like(q, limit)?; }
            serde_json::json!({"symbols": symbols.iter().map(|(n, s, k, f, l)| serde_json::json!({"name": n, "signature": s, "kind": k, "file": f, "line": l})).collect::<Vec<_>>()})
        }
        "evidence.get" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            serde_json::to_value(store.get_evidence(id)?)?
        }
        "evidence.list" => {
            let path = input.get("path").and_then(|v| v.as_str());
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(200) as usize;
            let mut out = match path {
                Some(p) => store.evidence_for_path(p)?,
                None => store.all_evidence()?,
            };
            out.truncate(limit.max(1));
            serde_json::to_value(out)?
        }
        "runtime.signatures" => {
            let rows = store.trace_signatures()?;
            serde_json::json!({"signatures": rows.iter().map(|(sig, count, lat, err, last)| serde_json::json!({"signature": sig, "count": count, "latency_ms": lat, "errors": err, "last_observed": last})).collect::<Vec<_>>()})
        }
        "integrations.describe" => {
            let name = input.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let all = crate::integrations::list(root)?;
            match all.into_iter().find(|(n, _)| n == name) {
                Some((n, scope)) => serde_json::json!({"name": n, "scope": scope}),
                None => serde_json::json!({"error": format!("unknown integration '{name}'")}),
            }
        }
        "index.full" => serde_json::to_value(crate::index::full(root, &config)?)?,
        "index.refresh" => {
            let req: scc_api::IndexPathsRequest = serde_json::from_value(input)?;
            serde_json::to_value(crate::index::refresh_paths(root, &config, &req.paths)?)?
        }
        "history.revisions" => serde_json::to_value(crate::history::revisions(&store)?)?,
        "history.diff" => {
            let req: scc_api::DiffRequest = serde_json::from_value(input)?;
            serde_json::to_value(crate::history::diff(&store, req.from, req.to)?)?
        }
        "model.get" => serde_json::to_value(crate::exports::model_get(&store)?)?,
        "context.external_docs" => {
            let dep = input.get("dependency").and_then(|v| v.as_str()).unwrap_or("");
            Value::String(crate::state::external_docs(root, dep)?)
        }
        "embeddings.build" => crate::state::embeddings_build(root)?,
        "embeddings.get" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            crate::state::embeddings_get(&store, id)?
        }
        "embeddings.status" => crate::state::embeddings_status(&store)?,
        "export.system_ir" => {
            let req: scc_api::ExportRequest = serde_json::from_value(input).unwrap_or(scc_api::ExportRequest { format: "system-ir.json".into() });
            export_value(&store, root, &req.format)?
        }
        "export.system_ir_jsonl" => export_value(&store, root, "system-ir.jsonl")?,
        "export.ccg" => export_value(&store, root, "ccg")?,
        "export.flow_graphs" => export_value(&store, root, "flow-graphs.json")?,
        "export.snap" => export_value(&store, root, "capsule.md")?,
        "workspace.init" => {
            let dir = crate::workspace::scc_dir(root);
            std::fs::create_dir_all(&dir)?;
            let cfg_path = crate::workspace::config_path(root);
            if !cfg_path.exists() {
                std::fs::write(&cfg_path, scc_indexer::Config::default_yaml())?;
            }
            crate::workspace::ensure_scc_ignored(root);
            serde_json::json!({"initialized": dir.to_string_lossy(), "config": cfg_path.to_string_lossy()})
        }
        "workspace.state_path" => Value::String(crate::workspace::state_dir(root).to_string_lossy().into()),
        "workspace.session" => serde_json::to_value(crate::workspace::open_session(&store, &config)?)?,
        "workspace.session_check" => {
            let session: crate::workspace::Session = serde_json::from_value(input.get("session").cloned().unwrap_or(serde_json::Value::Null))?;
            serde_json::json!({"current": crate::workspace::session_is_current(&store, &config, &session)?})
        }
        "index.status" => {
            let s = status_value(&store)?;
            serde_json::to_value(&s)?
        }
        "resolution.run" => serde_json::to_value(crate::index::resolve_and_recompile(root)?)?,
        "graph.recompile" => {
            let r = crate::index::recompile(&store)?;
            serde_json::json!({
                "components": r.components,
                "flows": r.flows,
                "invariants": r.invariants,
                "drift": r.drift,
                "boundaries": r.boundaries,
            })
        },
        "graph.entity.get" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            let all = store.all_entities()?;
            serde_json::to_value(all.into_iter().find(|e| e.id == id))?
        }
        "architecture.drift" => serde_json::to_value(crate::misc::drift(&store)?)?,
        "architecture.cochange" => {
            let min = input.get("min_commits").and_then(|v| v.as_u64()).unwrap_or(2) as u32;
            let (pairs, enriched) = crate::misc::cochange(root, min)?;
            serde_json::json!({"pairs": pairs, "enriched": enriched})
        }
        "integrity.invariants" | "architecture.invariants" => serde_json::to_value(crate::misc::check_invariants(&store)?)?,
        "integrity.ci" => {
            let max = input.get("max_severity").and_then(|v| v.as_str()).unwrap_or("medium");
            let violations = crate::misc::check_invariants(&store)?;
            let (ok, lines) = crate::misc::ci_check(&store, &violations, max)?;
            serde_json::json!({"ok": ok, "lines": lines})
        }
        "integrations.list" => serde_json::to_value(crate::integrations::list(root)?)?,
        "integrations.doctor" => {
            let deep = input.get("deep").and_then(|v| v.as_bool()).unwrap_or(false);
            let network = input.get("network").and_then(|v| v.as_bool()).unwrap_or(false);
            serde_json::to_value(crate::integrations::doctor_report(&store, &config, root, deep, network)?)?
        }
        "lessons.add" => {
            let text = input.get("text").and_then(|v| v.as_str()).unwrap_or("");
            let (id, path) = crate::state::lessons_add(root, text)?;
            serde_json::json!({"id": id, "path": path.to_string_lossy()})
        }
        "lessons.list" => {
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize;
            serde_json::to_value(crate::state::lessons_list(root, limit)?)?
        }
        "beads.list" => serde_json::to_value(crate::state::beads(root, 20)?)?,
        "setup.claude" | "setup.detected" | "setup.codex" | "setup.opencode" | "setup.hermes" | "setup.omp" | "setup.pi" => {
            return Err(crate::EngineError::Other("setup operations are CLI-local file installation (harness dirs, home directory); not engine operations".into()));
        }
        "snapshot.save" => {
            let req: scc_api::SnapshotSaveRequest = serde_json::from_value(input)?;
            serde_json::to_value(crate::misc::snapshot_save(root, &req.task, req.budget)?)?
        }
        "snapshot.get" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            serde_json::to_value(crate::snapshots::get(&store, id)?)?
        }
        "snapshot.diff" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            serde_json::to_value(crate::snapshots::diff(&store, id)?)?
        }
        "checkpoint.save" => serde_json::to_value(crate::checkpoint::capture(root)?)?,
        "checkpoint.load" => serde_json::to_value(crate::checkpoint::load(root)?)?,
        "system.stitch" => {
            let members: Vec<std::path::PathBuf> = input.get("members")
                .and_then(|v| v.as_array())
                .map(|a| a.iter().filter_map(|s| s.as_str().map(std::path::PathBuf::from)).collect())
                .unwrap_or_default();
            let (members, stitches) = crate::systems::stitch(&members)?;
            serde_json::json!({"members": members.iter().map(|m| &m.repo_id).collect::<Vec<_>>(), "stitches": stitches})
        }
        "import.scip" | "import.ccg" | "import.gitnexus" | "import.tracelayer" | "import.beads" | "import.hindsight" | "import.cbm" => {
            let format = operation.trim_start_matches("import.");
            let file = input.get("file").and_then(|v| v.as_str()).unwrap_or("");
            let r = crate::state::import_evidence(root, format, file)?;
            serde_json::json!({
                "symbols": r.symbols,
                "calls": r.calls,
                "imports": r.imports,
                "errors": r.errors,
            })
        }
        "export.diagram" => {
            let format = input.get("format").and_then(|v| v.as_str()).unwrap_or("mermaid");
            crate::exports::diagram(&store, format)?
        }
        "index.watch" => {
            return Err(crate::EngineError::Other("index.watch is a streaming filesystem watch, not a request/response operation; run `scc watch`".into()));
        }
        "runtime.ingest" => {
            let body = input.get("body").and_then(|v| v.as_str()).unwrap_or("");
            crate::state::ingest_runtime(root, body)?;
            serde_json::json!({"status": "accepted"})
        }
        "runtime.status" => serde_json::to_value(crate::state::runtime_edges(root)?)?,
        "runtime.reconcile" => serde_json::to_value(crate::state::reconcile(root)?)?,
        "ranking.important" => {
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
            let task = input.get("task").and_then(|v| v.as_str()).map(|s| s.to_string());
            let component = input.get("component").and_then(|v| v.as_str()).map(|s| s.to_string());
            let (entries, tasked) = ctx.important(limit, component.as_deref(), task.as_deref())?;
            serde_json::json!({"entries": entries, "tasked": tasked})
        }
        "ranking.symbols" => {
            let req: scc_api::RankRequest = serde_json::from_value(input)?;
            let ranker = engine.ranking();
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::order_extensions(&crate::plugins::collect_extensions(&ap))?;
            let hooks = ranking_hooks_from_plugins(&mut ap, req.goal.as_deref().unwrap_or(""));
            let out = ranker.symbols_with_hooks(&req, &hooks)?;
            let mut v = serde_json::to_value(&out)?;
            if !ap.diagnostics.is_empty() {
                v["plugin_diagnostics"] = serde_json::to_value(&ap.diagnostics)?;
            }
            v
        }
        "ranking.candidates" => {
            let goal = input.get("goal").and_then(|v| v.as_str()).unwrap_or("");
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as usize;
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::order_extensions(&crate::plugins::collect_extensions(&ap))?;
            let hooks = ranking_hooks_from_plugins(&mut ap, goal);
            let cands = engine.ranking().candidates_with(goal, limit, &hooks)?;
            serde_json::json!({"candidates": cands.iter().map(|c| serde_json::json!({"id": c.id, "kind": c.kind, "name": c.name, "score": c.score, "reason": c.reason})).collect::<Vec<_>>()})
        }
        "ranking.pagerank.global" => {
            // Raw stage introspection: no plugin hooks by contract.
            let v = engine.ranking().pagerank_global()?;
            serde_json::json!({"vector": v.iter().map(|(id, s)| serde_json::json!({"id": id, "score": s})).collect::<Vec<_>>()})
        }
        "ranking.pagerank.task" => {
            // Raw stage introspection: no plugin hooks by contract.
            let goal = input.get("goal").and_then(|v| v.as_str()).unwrap_or("");
            let v = engine.ranking().pagerank_task(goal)?;
            serde_json::json!({"vector": v.iter().map(|(id, s)| serde_json::json!({"id": id, "score": s})).collect::<Vec<_>>()})
        }
        "ranking.final_importance" => {
            let f = |k: &str| input.get(k).and_then(|v| v.as_f64()).unwrap_or(0.0);
            let has_task = input.get("has_task").and_then(|v| v.as_bool()).unwrap_or(true);
            let s = scc_context::pagerank::final_importance(f("task_ppr"), f("global_ppr"), f("lexical"), f("semantic"), f("confidence"), f("criticality"), f("change_risk"), f("novelty"), has_task);
            serde_json::json!({"score": s})
        }
        "ranking.edge_weight" => {
            let predicate = input.get("predicate").and_then(|v| v.as_str()).unwrap_or("calls");
            let confidence = input.get("confidence").and_then(|v| v.as_f64()).unwrap_or(1.0);
            let total = input.get("total_symbols").and_then(|v| v.as_u64()).unwrap_or(1) as usize;
            let indeg = input.get("target_in_degree").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
            serde_json::json!({"weight": scc_context::pagerank::edge_weight(predicate, scc_core::Provenance::Extracted, confidence, total, indeg)})
        }
        "ranking.architectural_specificity" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            let exported = input.get("exported").and_then(|v| v.as_bool()).unwrap_or(false);
            serde_json::json!({"specificity": if exported { 1.15 } else { 1.0 }, "id": id})
        }
        "ranking.explain" => {
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            let goal = input.get("goal").and_then(|v| v.as_str()).unwrap_or("");
            let req = scc_api::RankRequest { profile: None, goal: Some(goal.into()), limit: 1000, explain: true, include_features: true, include_intermediate: true };
            let ranker = engine.ranking();
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::order_extensions(&crate::plugins::collect_extensions(&ap))?;
            let hooks = ranking_hooks_from_plugins(&mut ap, goal);
            let out = ranker.symbols_with_hooks(&req, &hooks)?;
            match out.items.into_iter().find(|i| i.id == id) {
                Some(item) => serde_json::to_value(&item)?,
                None => serde_json::json!({"error": format!("symbol {id} not in ranking")}),
            }
        }
        "ranking.global" | "ranking.task" | "ranking.entities" => {
            let goal = input.get("goal").and_then(|v| v.as_str()).map(|s| s.to_string());
            let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as usize;
            let req = scc_api::RankRequest { profile: None, goal, limit, explain: false, include_features: true, include_intermediate: false };
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::order_extensions(&crate::plugins::collect_extensions(&ap))?;
            let hooks = ranking_hooks_from_plugins(&mut ap, req.goal.as_deref().unwrap_or(""));
            serde_json::to_value(engine.ranking().symbols_with_hooks(&req, &hooks)?)?
        }
        "selection.mmr" => {
            let req: scc_api::SelectionRequest = serde_json::from_value(input)?;
            let ranked: Vec<(String, f64)> = req.ranked.iter().map(|e| (e.id.clone(), e.value)).collect();
            let groups: Vec<Option<String>> = req.ranked.iter().map(|e| e.group.clone()).collect();
            // Similarity hook chain (DoD 27): `similarity` extensions fire
            // first; the same-group default runs last. Groups ride the
            // request's `group` field (component/path supplied by caller).
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::order_extensions(&crate::plugins::collect_extensions(&ap))?;
            let hooks = ranking_hooks_from_plugins(&mut ap, "");
            let sims = std::sync::Arc::new(hooks.similarities);
            let out = scc_context::selector::mmr_diversify(
                &ranked,
                |a: &str, b: &str| {
                    let (ga, gb) = (group_of(&ranked, &groups, a), group_of(&ranked, &groups, b));
                    crate::ranking::fold_similarity(&sims, a, b, ga, gb)
                },
                req.lambda.unwrap_or(0.5),
                ranked.len(),
            );
            serde_json::json!({"selected": out})
        }
        "selection.quotas" => {
            let req: scc_api::SelectionRequest = serde_json::from_value(input)?;
            let rows: Vec<(String, String, f64, usize)> = req.ranked.iter().map(|e| (e.id.clone(), e.kind.clone(), e.value, e.token_cost)).collect();
            let quotas: Vec<(String, f64)> = req.quotas.unwrap_or_default().iter().map(|q| (q.kind.clone(), q.fraction)).collect();
            let budget: usize = req.ranked.iter().map(|e| e.token_cost).sum();
            serde_json::json!({"selected": crate::ranking::apply_quotas(&rows, &quotas, budget)})
        }
        "selection.budget" => {
            let req: scc_api::SelectionRequest = serde_json::from_value(input)?;
            let items: Vec<scc_core::ContextItem> = req.ranked.iter().map(|e| scc_core::ContextItem { id: e.id.clone(), value: e.value, token_cost: e.token_cost, required: false, group: e.group.clone() }).collect();
            let budget: usize = items.iter().map(|i| i.token_cost).sum();
            serde_json::json!({"selected": crate::ranking::select_with_budget(&items, budget, budget)})
        }
        "plugins.list" => {
            let ap = crate::plugins::active(root, &config);
            serde_json::json!({"plugins": scc_plugin_host::discover(root).iter().map(|p| &p.manifest.id).collect::<Vec<_>>(), "lock": crate::plugins::lock_entries(&ap)})
        }
        "plugins.describe" => {
            let ap = crate::plugins::active(root, &config);
            let id = input.get("id").and_then(|v| v.as_str()).unwrap_or("");
            match ap.plugins.iter().find(|p| p.manifest.id == id) {
                Some(p) => serde_json::json!({"manifest": {"id": p.manifest.id, "name": p.manifest.name, "version": p.manifest.version, "api": p.manifest.api, "operations": p.manifest.operations, "timeout_ms": p.manifest.timeout_ms, "failure_policy": p.manifest.failure_policy, "deterministic": p.manifest.deterministic, "runtime": format!("{:?}", p.manifest.runtime).to_lowercase(), "extensions": p.manifest.extensions}, "lock": scc_plugin_host::lock_entry(p)}),
                None => serde_json::json!({"error": format!("unknown plugin '{id}'")}),
            }
        }
        "plugins.doctor" => {
            let ap = crate::plugins::active(root, &config);
            serde_json::json!({"plugins": ap.plugins.iter().map(|p| serde_json::json!({"id": p.manifest.id, "operations": p.manifest.operations})).collect::<Vec<_>>(), "diagnostics": ap.diagnostics})
        }
        "plugins.contribute" => {
            let plugin = input.get("plugin").and_then(|v| v.as_str()).unwrap_or("");
            let batch = input.get("batch").cloned().unwrap_or(serde_json::json!({}));
            if plugin.is_empty() {
                return Err(crate::EngineError::Other("plugins.contribute requires a `plugin` id".into()));
            }
            crate::plugins::commit_contribution(&store, plugin, &batch)?
        }
        "plugins.lock" => {
            let ap = crate::plugins::active(root, &config);
            let path = scc_plugin_host::write_lockfile(root, &ap.plugins).map_err(crate::EngineError::Other)?;
            serde_json::json!({"ok": true, "path": path.to_string_lossy(), "plugins": crate::plugins::lock_entries(&ap)})
        }
        "plugins.check" => {
            let ap = crate::plugins::active(root, &config);
            match scc_plugin_host::check_lockfile(root, &ap.plugins) {
                Ok(()) => serde_json::json!({"ok": true}),
                Err(drift) => serde_json::json!({"ok": false, "drift": drift}),
            }
        }
        "plugin_state.get" | "plugin_state.put" | "plugin_state.delete" | "plugin_state.scan" => {
            let pid = input.get("plugin").and_then(|v| v.as_str()).unwrap_or("");
            let ap = crate::plugins::active(root, &config);
            let plug = ap.plugins.iter().find(|p| p.manifest.id == pid).ok_or_else(|| {
                crate::EngineError::Other(format!("unknown plugin '{pid}' (not active)"))
            })?;
            match operation {
                "plugin_state.get" => {
                    let key = input.get("key").and_then(|v| v.as_str()).unwrap_or("");
                    crate::state::plugin_state_get(&store, pid, &plug.grants, key)?
                }
                "plugin_state.put" => {
                    let key = input.get("key").and_then(|v| v.as_str()).unwrap_or("");
                    let value = input.get("value").map(|v| v.to_string()).unwrap_or_default();
                    crate::state::plugin_state_put(&store, pid, &plug.grants, key, &value)?
                }
                "plugin_state.delete" => {
                    let key = input.get("key").and_then(|v| v.as_str()).unwrap_or("");
                    crate::state::plugin_state_delete(&store, pid, &plug.grants, key)?
                }
                _ => {
                    let prefix = input.get("prefix").and_then(|v| v.as_str()).unwrap_or("");
                    let limit = input.get("limit").and_then(|v| v.as_u64()).unwrap_or(100) as usize;
                    crate::state::plugin_state_scan(&store, pid, &plug.grants, prefix, limit)?
                }
            }
        }
        "plugins.invoke" => {
            let op = input.get("operation").and_then(|v| v.as_str()).unwrap_or(operation);
            let inner = input.get("input").cloned().unwrap_or(serde_json::json!({}));
            let mut ap = crate::plugins::active(root, &config);
            crate::plugins::call_operation(&mut ap, op, inner)?
        }
        _ => {
            // Custom plugin operations: no per-transport code needed (spec 31).
            let mut ap = crate::plugins::active(root, &config);
            match scc_plugin_host::provider_for(&ap.plugins, operation) {
                Ok(_) => crate::plugins::call_operation(&mut ap, operation, input)?,
                Err(_) => return Err(crate::EngineError::Other(format!("unknown operation '{operation}' (see operations.list)"))),
            }
        }
    };
    Ok(out)
}

// trace:exempt reason=internal-detail
fn group_of<'a>(ranked: &[(String, f64)], groups: &'a [Option<String>], id: &str) -> Option<&'a str> {
    ranked.iter().position(|(rid, _)| rid == id).and_then(|i| groups.get(i).and_then(|g| g.as_deref()))
}

// trace:exempt reason=internal-detail
fn ranking_hooks_from_plugins(
    ap: &mut crate::plugins::ActivePlugins,
    goal: &str,
) -> crate::ranking::RankHooks {
    use std::sync::Arc;
    let mut hooks = crate::ranking::RankHooks::default();
    // Snapshot what each plugin provides (borrow ends before mutation).
    // Extension registrations (§17) select hook wiring; legacy bare
    // operation names (ranking.seed/feature/rerank) keep working.
    // trace:exempt reason=internal-detail
    struct PlugSpec { id: String, ops: Vec<String>, exts: Vec<(String, String)> }
    let specs: Vec<PlugSpec> = ap.plugins.iter()
        .map(|p| PlugSpec { id: p.manifest.id.clone(), ops: p.manifest.operations.clone(),
            exts: p.manifest.extensions.iter().map(|e| (e.extension_type.clone(), e.id.clone())).collect() })
        .collect();
    for spec in specs {
        let plug = match ap.plugins.iter().find(|p| p.manifest.id == spec.id).cloned() {
            Some(p) => Arc::new(p),
            None => continue,
        };
        let pid = spec.id.clone();
        let wants = |t: &str, op: &str| {
            spec.exts.iter().any(|(ty, _)| ty == t) || spec.ops.iter().any(|o| o == op)
        };
        if wants("candidate-provider", "ranking.candidates") {
            let plug = Arc::clone(&plug);
            let pid2 = pid.clone();
            hooks.candidates.push(Box::new(move |goal: &str| {
                let input = serde_json::json!({"goal": goal});
                match scc_plugin_host::call(&plug, "ranking.candidates", input, None) {
                    Ok(v) => v.get("candidates").and_then(|s| s.as_array()).map(|a| {
                        a.iter().filter_map(|e| {
                            let id = e.get("id").and_then(|x| x.as_str()).unwrap_or("").to_string();
                            if id.is_empty() { return None; }
                            Some(scc_context::rank::ScoredEntity {
                                id,
                                kind: e.get("kind").and_then(|x| x.as_str()).unwrap_or("symbol").into(),
                                name: e.get("name").and_then(|x| x.as_str()).unwrap_or("").into(),
                                score: e.get("score").and_then(|x| x.as_f64()).unwrap_or(0.0),
                                reason: format!("plugin:{}", pid2),
                            })
                        }).collect()
                    }).unwrap_or_default(),
                    Err(_) => Vec::new(),
                }
            }));
        }
        if wants("seed-provider", "ranking.seed") {
            let plug = Arc::clone(&plug);
            let g = goal.to_string();
            hooks.seed_providers.push(Box::new(move |_goal| {
                let input = serde_json::json!({"goal": g});
                match scc_plugin_host::call(&plug, "ranking.seed", input, None) {
                    Ok(v) => v.get("seeds").and_then(|s| s.as_array()).map(|a| {
                        a.iter().map(|e| scc_core::TaskSeed {
                            kind: e.get("kind").and_then(|x| x.as_str()).unwrap_or("symbol").into(),
                            id: e.get("id").and_then(|x| x.as_str()).unwrap_or("").into(),
                            weight: e.get("weight").and_then(|x| x.as_f64()).unwrap_or(0.0),
                        }).filter(|s| !s.id.is_empty()).collect()
                    }).unwrap_or_default(),
                    Err(_) => Vec::new(),
                }
            }));
        }
        if wants("rank-feature", "ranking.feature") {
            let plug = Arc::clone(&plug);
            hooks.features.push(Box::new(move |sym, goal| {
                let input = serde_json::json!({"symbol": sym, "goal": goal});
                match scc_plugin_host::call(&plug, "ranking.feature", input, None) {
                    Ok(v) => crate::ranking::RankFeatureValue {
                        name: format!("{pid}.feature"),
                        score: v.get("score").and_then(|x| x.as_f64()).unwrap_or(0.0),
                        weight: v.get("weight").and_then(|x| x.as_f64()).unwrap_or(0.0),
                        reason: v.get("reason").and_then(|x| x.as_str()).unwrap_or("").into(),
                    },
                    Err(_) => crate::ranking::RankFeatureValue { name: format!("{pid}.feature"), score: 0.0, weight: 0.0, reason: String::new() },
                }
            }));
        }
        if wants("edge-weight", "ranking.edge_weight") {
            let plug = Arc::clone(&plug);
            hooks.edge_weights.push(std::sync::Arc::new(move |subject, predicate, object, base| {
                let input = serde_json::json!({
                    "subject": subject, "predicate": predicate,
                    "object": object, "base": base,
                });
                match scc_plugin_host::call(&plug, "ranking.edge_weight", input, None) {
                    Ok(v) => {
                        let mode = v.get("mode").and_then(|x| x.as_str()).unwrap_or("").to_string();
                        let value = v.get("value").and_then(|x| x.as_f64()).unwrap_or(0.0);
                        match mode.as_str() {
                            "add" | "multiply" | "replace" | "veto" => Some((mode, value)),
                            _ => None,
                        }
                    }
                    Err(_) => None,
                }
            }));
        }
        // Named blend profiles (spec 12 + DoD 25): a
        // `blend-profile:<name>` extension registers profile `<name>` via
        // the plugin's `ranking.profile` op returning weight overrides.
        for eid in spec.exts.iter().filter(|(ty, _)| ty == "blend-profile").map(|(_, id)| id) {
            let name = eid.strip_prefix("blend-profile:").unwrap_or(eid).to_string();
            let plug = Arc::clone(&plug);
            if let Ok(v) = scc_plugin_host::call(&plug, "ranking.profile", serde_json::json!({"profile": name}), None) {
                let w = v.get("weights").cloned().unwrap_or(serde_json::Value::Null);
                let mut bw = crate::ranking::BlendWeights::default();
                let mut bad: Vec<String> = Vec::new();
                if let Some(obj) = w.as_object() {
                    for (k, val) in obj {
                        let num = val.as_f64();
                        match (k.as_str(), num) {
                            ("task_ppr", Some(x)) => bw.task_ppr = Some(x),
                            ("global_ppr", Some(x)) => bw.global_ppr = Some(x),
                            ("lexical", Some(x)) => bw.lexical = Some(x),
                            ("semantic", Some(x)) => bw.semantic = Some(x),
                            ("confidence", Some(x)) => bw.confidence = Some(x),
                            ("criticality", Some(x)) => bw.criticality = Some(x),
                            ("change_risk", Some(x)) => bw.change_risk = Some(x),
                            ("novelty", Some(x)) => bw.novelty = Some(x),
                            _ => bad.push(k.clone()),
                        }
                    }
                }
                // Unknown feature keys fail loudly at registration, not
                // silently ignored (would lie about the blend).
                if !bad.is_empty() {
                    ap.diagnostics.push(scc_plugin_host::PluginDiagnostic {
                        plugin: spec.id.clone(), operation: "ranking.profile".into(),
                        error: format!("unknown blend features for profile '{name}': {}", bad.join(", ")),
                        action: "skipped".into(),
                    });
                    continue;
                }
                hooks.profiles.insert(name, bw);
            }
        }
        if wants("similarity", "ranking.similarity") {
            let plug = Arc::clone(&plug);
            hooks.similarities.push(std::sync::Arc::new(move |a, b, ga, gb| {
                let input = serde_json::json!({"a": a, "b": b, "group_a": ga, "group_b": gb});
                match scc_plugin_host::call(&plug, "ranking.similarity", input, None) {
                    Ok(v) => v.get("similarity").and_then(|x| x.as_f64()).unwrap_or(0.0),
                    Err(_) => 0.0,
                }
            }));
        }
        if wants("reranker", "ranking.rerank") {
            let plug = Arc::clone(&plug);
            hooks.rerankers.push(Box::new(move |items, goal| {
                let input = serde_json::json!({"goal": goal, "items": items.iter().map(|i: &scc_api::RankItem| i.id.clone()).collect::<Vec<_>>()});
                if let Ok(v) = scc_plugin_host::call(&plug, "ranking.rerank", input, None) {
                    if let Some(order) = v.get("order").and_then(|o| o.as_array()) {
                        let pos: std::collections::HashMap<&str, usize> =
                            order.iter().enumerate().filter_map(|(i, x)| x.as_str().map(|s| (s, i))).collect();
                        items.sort_by_key(|i| (pos.get(i.id.as_str()).copied().unwrap_or(usize::MAX), i.id.clone()));
                        for (k, it) in items.iter_mut().enumerate() { it.position = k + 1; }
                    }
                }
            }));
        }
    }
    hooks
}

// trace:exempt reason=internal-detail
fn invoke_context(
    ctx: &crate::SccContext,
    store: &scc_store::Store,
    config: &scc_indexer::Config,
    operation: &str,
    input: Value,
) -> crate::Result<Value> {
    Ok(match operation {
        "context.component" => {
            let req: scc_api::DetailRequest = serde_json::from_value(input)?;
            serde_json::to_value(ctx.component(&req)?)?
        }
        "context.flow" => {
            let req: scc_api::DetailRequest = serde_json::from_value(input)?;
            serde_json::to_value(ctx.flow(&req)?)?
        }
        "context.impact" => {
            let req: scc_api::ImpactRequest = serde_json::from_value(input)?;
            serde_json::to_value(ctx.impact(&req)?)?
        }
        "context.verify" => {
            let unbounded = input.get("unbounded").and_then(|v| v.as_bool()).unwrap_or(false);
            serde_json::to_value(ctx.verify(unbounded)?)?
        }
        "context.structural" | "source.structural" => {
            let req: scc_api::StructuralRequest = serde_json::from_value(input)?;
            let goal = req.task.clone().unwrap_or_default();
            let (scorer, _) = crate::inference::rankers(store, config, &goal);
            let semantic: Option<&dyn scc_context::rank::SemanticScorer> =
                scorer.as_ref().map(|s| s as &dyn scc_context::rank::SemanticScorer);
            serde_json::json!({"text": ctx.structural(&req, &store.root, semantic)?})
        }
        "surface.build" | "ranking.important" => {
            let req: scc_api::SurfaceRequest = serde_json::from_value(input)?;
            let goal = req.task.clone().unwrap_or_default();
            let (scorer, _) = crate::inference::rankers(store, config, &goal);
            let semantic: Option<&dyn scc_context::rank::SemanticScorer> =
                scorer.as_ref().map(|s| s as &dyn scc_context::rank::SemanticScorer);
            let (result, text) = ctx.surface(&req, semantic)?;
            serde_json::json!({ "result": result, "text": text })
        }
        _ => unreachable!("invoke routes only context ops here"),
    })
}

// trace:exempt reason=internal-detail
fn status_value(store: &scc_store::Store) -> crate::Result<Value> {
    let repo = store.repository();
    let stale = crate::workspace::stale_paths(store)?;
    let (revision, indexed_at, branch) = match store.snapshot_status()? {
        Some((snap, _)) => (snap.revision, Some(snap.indexed_at), snap.branch),
        None => ("not-indexed".to_string(), None, None),
    };
    Ok(serde_json::json!({
        "repository": repo.name,
        "repository_id": repo.id,
        "remote": repo.url,
        "revision": revision,
        "branch": branch,
        "indexed_at": indexed_at,
        "stats": store.stats()?,
        "freshness": if stale.is_empty() { "CURRENT" } else { "STALE" },
        "stale_files": stale.iter().take(10).collect::<Vec<_>>(),
        "stale_count": stale.len(),
    }))
}

// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
fn export_value(store: &scc_store::Store, root: &std::path::Path, format: &str) -> crate::Result<Value> {
    let ir = crate::exports::system_ir(store)?;
    match format {
        "system-ir.json" | "system-ir.jsonl" | "ccg" | "flow-graphs.json" => {
            Ok(match format {
                "system-ir.jsonl" => Value::Array(crate::exports::jsonl(&ir)?.into_iter().map(Value::String).collect()),
                "ccg" => crate::exports::ccg(&ir)?,
                "flow-graphs.json" => serde_json::to_value(store.flow_graphs()?)?,
                _ => serde_json::to_value(&ir)?,
            })
        }
        "capsule.md" => Ok(Value::String(crate::exports::capsule(root)?)),
        other => Err(crate::EngineError::Other(format!(
            "unknown export format '{other}' (use system-ir.json, system-ir.jsonl, ccg, flow-graphs.json, capsule.md)"
        ))),
    }
}