nornir 0.1.0

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! `nornir-mcp` — exposes the nornir library over the Model Context Protocol.
//!
//! Same surface as `nornir-cli`, different presentation: an MCP server
//! that registers each nornir API as a tool. LLM agents (Claude Desktop,
//! Copilot CLI, etc.) connect over stdio and can drive
//! guard/bench/release/docs/introspect operations directly.

use std::path::PathBuf;
use std::sync::Arc;

use anyhow::{Context, Result};
use chrono::Utc;
use rmcp::{
    ErrorData as McpError,
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::*,
    tool, tool_handler, tool_router,
    ServerHandler, ServiceExt,
    transport::stdio,
};
use tokio::sync::Mutex;

use nornir::bench;
use nornir::config::{self, Loaded};
use nornir::funnel::{
    event::{Event as FunnelEvent, NodeStatus, PlanStatus},
    ids::{IdeaId, NodeId, PlanId},
    store::Store as FunnelStore,
    topo::topo_ready,
};
use nornir::guard;
use nornir::index;
use nornir::introspect;
use nornir::release;

#[derive(Clone)]
struct NornirServer {
    state: Arc<Mutex<State>>,
    #[allow(dead_code)] // populated by #[tool_router] macro; read via reflection only
    tool_router: ToolRouter<NornirServer>,
}

struct State {
    loaded: Loaded,
    funnel: FunnelStore,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct RepoArg {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct SearchArgs {
    /// BM25 query (Tantivy syntax: terms, "phrases", AND/OR/NOT, +required, -excluded).
    query: String,
    /// Optional corpus filter: docs | code | bench_history | changelog | config.
    #[serde(default)]
    corpus: Option<String>,
    /// Optional repo filter (top-level workspace dir, e.g. "holger").
    #[serde(default)]
    repo: Option<String>,
    /// Max hits to return (default 10).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct SymbolLookupArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Substring matched against demangled/mangled symbol names.
    pattern: String,
    /// Max hits to return (default 25).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DefinedInArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Source file path suffix, e.g. `nornir/src/bench/mod.rs` or `mod.rs`.
    file: String,
    /// Max hits to return (default 100).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct CallQueryArgs {
    /// Path (relative to workspace root or absolute) to a debug-info binary.
    binary: String,
    /// Demangled (generics-stripped) function name, e.g. `nornir::index::Index::build`.
    name: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct PathBetweenArgs {
    binary: String,
    from: String,
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct DocsHistoryArgs {
    /// Repo name as declared under `[repo.<name>]` in nornir.toml.
    repo: String,
    /// Restrict to one document, e.g. "README".
    #[serde(default)]
    doc: Option<String>,
    /// Restrict to one version, e.g. "0.1.0".
    #[serde(default)]
    version: Option<String>,
    /// Restrict to one format: pdf | html | md.
    #[serde(default)]
    format: Option<String>,
    /// Max rows to return (default 50).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelSubmitIdeaArgs {
    /// One-line description of the idea.
    text: String,
    /// Optional source/provenance tag (e.g. "agent:claude", "user").
    #[serde(default)]
    source: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelCreatePlanArgs {
    /// Idea id this plan refines, e.g. "i-002".
    idea_id: String,
    /// Short summary of the plan.
    summary: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelAddNodeArgs {
    /// Plan id, e.g. "p-002".
    plan_id: String,
    /// Verb/kind, e.g. "code:write", "test:run", "doc:update".
    kind: String,
    /// Optional human-readable title.
    #[serde(default)]
    title: Option<String>,
    /// Optional prompt/notes for the executor.
    #[serde(default)]
    prompt: Option<String>,
    /// Optional file/symbol targets the node will touch.
    #[serde(default)]
    targets: Vec<String>,
    /// Optional list of node-ids this node depends on (in same plan).
    #[serde(default)]
    needs: Vec<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelLinkArgs {
    /// Plan id both nodes belong to.
    plan_id: String,
    /// Predecessor node-id.
    from: String,
    /// Successor node-id (will gain `from` as a dependency).
    to: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct FunnelStatusArgs {
    /// Plan id, e.g. "p-002".
    plan_id: String,
    /// Node id, e.g. "n-013".
    node_id: String,
    /// One of: ready | active | blocked | done | abandoned.
    status: String,
    /// Optional reason (required when status=blocked or abandoned).
    #[serde(default)]
    why: Option<String>,
}

#[tool_router]
impl NornirServer {
    async fn new(loaded: Loaded) -> Result<Self> {
        let funnel_root = std::env::var_os("NORNIR_FUNNEL_ROOT")
            .map(PathBuf::from)
            .unwrap_or_else(|| FunnelStore::default_root(&loaded.workspace_root));
        let funnel = FunnelStore::open_async(&funnel_root)
            .await
            .with_context(|| format!("open funnel warehouse at {}", funnel_root.display()))?;
        eprintln!(
            "funnel: {} ideas, {} plans loaded from {}",
            funnel.funnel.ideas.len(),
            funnel.funnel.plans.len(),
            funnel_root.display(),
        );
        Ok(Self {
            state: Arc::new(Mutex::new(State { loaded, funnel })),
            tool_router: Self::tool_router(),
        })
    }

    #[tool(description = "List repos declared in nornir.toml.")]
    async fn repos_list(&self) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let names: Vec<String> = s.loaded.nornir.repo.keys().cloned().collect();
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&names).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Guard: report writable state of every [guard].forbidden path.")]
    async fn guard_status(&self) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let report = guard::status(&s.loaded.workspace_root, &s.loaded.nornir.guard.forbidden);
        Ok(CallToolResult::success(vec![Content::text(format_status(&report))]))
    }

    #[tool(description = "Guard: chmod -w every [guard].forbidden path that exists.")]
    async fn guard_apply(&self) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let report = guard::apply(&s.loaded.workspace_root, &s.loaded.nornir.guard.forbidden)
            .map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format_status(&report))]))
    }

    #[tool(description = "Guard: chmod +w every [guard].forbidden path (allow human edits).")]
    async fn guard_release(&self) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let report = guard::release(&s.loaded.workspace_root, &s.loaded.nornir.guard.forbidden)
            .map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format_status(&report))]))
    }

    #[tool(description = "Bench: read bench_history.jsonl for <repo> (one BenchRun per line).")]
    async fn bench_history(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let repo = s.loaded.nornir.repo.get(&args.repo).ok_or_else(|| {
            McpError::invalid_params(format!("no [repo.{}]", args.repo), None)
        })?;
        let history = config::Nornir::repo_dir(&s.loaded.workspace_root, &args.repo)
            .join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
        let runs = bench::history::read_all(&history).map_err(internal)?;
        let body = serde_json::to_string_pretty(&runs).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Release: run the no-path-patches gate against <repo>'s Cargo.toml.")]
    async fn release_gate_path_patches(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let repo_root = config::Nornir::repo_dir(&s.loaded.workspace_root, &args.repo);
        release::gate::no_path_patches(&repo_root).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: no [patch.crates-io] znippy entries in {}",
            repo_root.display()
        ))]))
    }

    #[tool(description = "Release: nexus_floor gate — holger_ops_sec ≥ nexus_ops_sec for the latest BenchRun of <repo>.")]
    async fn release_gate_nexus_floor(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        release::gate::nexus_floor(&run).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: nexus_floor on v{}", run.version
        ))]))
    }

    #[tool(description = "Release: no_regression gate — compare latest BenchRun to same-machine history; fails if any metric drops > max_regression_pct.")]
    async fn release_gate_no_regression(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        let pct = if repo.gates.max_regression_pct > 0.0 { repo.gates.max_regression_pct } else { 10.0 };
        let hp = root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
        release::gate::no_regression(&run, &hp, pct).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: no_regression ≤{:.1}% on v{}", pct, run.version
        ))]))
    }

    #[tool(description = "Docs: scaffold `.nornir/` for <repo> (migrate any existing README.md/CHANGELOG.md into it).")]
    async fn docs_init(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, _) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let srcs = nornir::docs::init_repo(&layout).map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "nornir_dir": layout.nornir_dir(),
            "sources": srcs,
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Docs: render every managed doc for <repo> from .nornir/ (full rewrite, chmod-aware).")]
    async fn docs_render(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let last = mcp_last_run(&root, repo).ok();
        let ctx = nornir::docs::Ctx {
            repo_root: &root,
            workspace_root: &s.loaded.workspace_root,
            run: last.as_ref(),
        };
        let reports = nornir::docs::render_all(&layout, &ctx).map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "reports": reports.iter().map(|r| serde_json::json!({
                "output": r.output,
                "bytes": r.bytes,
                "changed": r.changed,
                "sections": r.sections,
            })).collect::<Vec<_>>(),
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Docs: dry-run check that every artifact (README.md, CHANGELOG.md) matches its .nornir/ source.")]
    async fn docs_check(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let last = mcp_last_run(&root, repo).ok();
        let ctx = nornir::docs::Ctx {
            repo_root: &root,
            workspace_root: &s.loaded.workspace_root,
            run: last.as_ref(),
        };
        nornir::docs::render_check_all(&layout, &ctx).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: every doc in {} matches its source", args.repo
        ))]))
    }

    #[tool(description = "Docs: list historical exports recorded in .nornir/warehouse/docs/ (newest first). Optional filters: doc, version, format, limit.")]
    async fn docs_history(
        &self,
        Parameters(args): Parameters<DocsHistoryArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, _) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let wh = nornir::docs::DocsWarehouse::open(&layout).map_err(internal)?;
        let filter = nornir::docs::ExportFilter {
            doc_name: args.doc,
            version: args.version,
            format: args.format,
            limit: args.limit.or(Some(50)),
        };
        let rows = wh.list(&filter).map_err(internal)?;
        let body = serde_json::json!({
            "repo": args.repo,
            "root": wh.root(),
            "rows": rows,
        });
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&body).unwrap_or_default(),
        )]))
    }

    #[tool(description = "Release: docs_fresh gate — README.md generated sections must be in sync with latest BenchRun.")]
    async fn release_gate_docs_fresh(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let layout = nornir::docs::RepoLayout::new(&root);
        let run = mcp_last_run(&root, repo).map_err(internal)?;
        let ctx = nornir::docs::Ctx {
            repo_root: &root,
            workspace_root: &s.loaded.workspace_root,
            run: Some(&run),
        };
        nornir::docs::render_check_all(&layout, &ctx).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "ok: docs_fresh on {}", root.display()
        ))]))
    }

    #[tool(description = "Release: run every gate enabled in [repo.<name>.gates] for <repo>; returns JSON {passed:[...], failed:[{name,error}]}. Roundtrip invokes `cargo test --test roundtrip_<kind> --release` per configured kind.")]
    async fn release_gate_all(
        &self,
        Parameters(args): Parameters<RepoArg>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let (root, repo) = repo_ctx(&s, &args.repo).map_err(internal)?;
        let g = &repo.gates;
        let mut passed: Vec<String> = Vec::new();
        let mut failed: Vec<serde_json::Value> = Vec::new();
        macro_rules! push {
            ($n:expr, $r:expr) => {
                match $r {
                    Ok(()) => passed.push($n.into()),
                    Err(e) => failed.push(serde_json::json!({"name": $n, "error": format!("{e:#}")})),
                }
            };
        }
        if g.no_path_patches {
            push!("no_path_patches", release::gate::no_path_patches(&root));
        }
        let last = mcp_last_run(&root, repo);
        if g.nexus_floor {
            push!("nexus_floor", last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}")).and_then(|r| release::gate::nexus_floor(r)));
        }
        if g.no_regression {
            let pct = if g.max_regression_pct > 0.0 { g.max_regression_pct } else { 10.0 };
            let hp = root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
            push!("no_regression",
                last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}")).and_then(|r| release::gate::no_regression(r, &hp, pct)));
        }
        if !g.integration_roundtrip.is_empty() {
            let kinds: Vec<&str> = g.integration_roundtrip.iter().map(|s| s.as_str()).collect();
            push!("integration_roundtrip",
                nornir::release::gate::integration_roundtrip_via_cargo_test(&root, &kinds));
        }
        if g.docs_fresh {
            let r: anyhow::Result<()> = (|| {
                let run = last.as_ref().map_err(|e| anyhow::anyhow!("{e:#}"))?;
                let layout = nornir::docs::RepoLayout::new(&root);
                let ctx = nornir::docs::Ctx { repo_root: &root, workspace_root: &s.loaded.workspace_root, run: Some(run) };
                nornir::docs::render_check_all(&layout, &ctx)
            })();
            push!("docs_fresh", r);
        }
        let body = serde_json::json!({"repo": args.repo, "passed": passed, "failed": failed});
        Ok(CallToolResult::success(vec![Content::text(serde_json::to_string_pretty(&body).unwrap())]))
    }

    #[tool(description = "Full-text BM25 search over indexed corpora. \
        Run `nornir index build` first. Args: query (Tantivy syntax), \
        optional corpus (docs|code|bench_history|changelog|config), \
        optional repo (top-level workspace dir), optional limit.")]
    async fn search(
        &self,
        Parameters(args): Parameters<SearchArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let idx = index::Index::open(&s.loaded.workspace_root).map_err(internal)?;
        let corpus = match args.corpus.as_deref() {
            None => None,
            Some(name) => Some(
                index::Corpus::parse(name)
                    .ok_or_else(|| McpError::invalid_params(format!("unknown corpus: {name}"), None))?,
            ),
        };
        let hits = idx
            .search(&args.query, corpus, args.repo.as_deref(), args.limit.unwrap_or(10))
            .map_err(internal)?;
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF symbol lookup: extract every function symbol \
        from a built binary and filter by name substring. Returns JSON \
        array of {name, name_demangled, name_mangled, file, line, size_bytes, krate}. \
        `binary` may be relative to workspace root.")]
    async fn symbol_lookup(
        &self,
        Parameters(args): Parameters<SymbolLookupArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let syms = introspect::artifact::extract_symbols(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let hits: Vec<_> = introspect::artifact::lookup(&syms, &args.pattern)
            .into_iter()
            .take(args.limit.unwrap_or(25))
            .cloned()
            .collect();
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF defined-in lookup: list every function symbol \
        defined in source files whose path ends with `file`. \
        `binary` may be relative to workspace root.")]
    async fn defined_in(
        &self,
        Parameters(args): Parameters<DefinedInArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let syms = introspect::artifact::extract_symbols(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let hits: Vec<_> = introspect::artifact::defined_in(&syms, &args.file)
            .into_iter()
            .take(args.limit.unwrap_or(100))
            .cloned()
            .collect();
        let body = serde_json::to_string_pretty(&hits).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: functions that call `name`. \
        Only inlined edges are visible at this layer — indirect calls (trait \
        objects, fn pointers) and non-inlined direct calls are NOT included. \
        Use demangled names with generics stripped (e.g. `nornir::index::Index::build`).")]
    async fn callers_of(
        &self,
        Parameters(args): Parameters<CallQueryArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let body = serde_json::to_string_pretty(&cg.callers_of(&args.name)).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: functions called by `name`. \
        Inlined edges only (see `callers_of` for caveats).")]
    async fn callees_of(
        &self,
        Parameters(args): Parameters<CallQueryArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let body = serde_json::to_string_pretty(&cg.callees_of(&args.name)).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "DWARF inline-callgraph: shortest call chain from `from` to `to` \
        (BFS over inlined edges). Returns the list of function names along the path, \
        or `null` when no path exists.")]
    async fn path_between(
        &self,
        Parameters(args): Parameters<PathBetweenArgs>,
    ) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let bin = resolve_binary(&s.loaded.workspace_root, &args.binary);
        let edges = introspect::callgraph_dwarf::extract_callgraph(&bin, &s.loaded.workspace_root)
            .map_err(internal)?;
        let cg = introspect::callgraph_dwarf::Callgraph::from_edges(&edges);
        let path = cg.path_between(&args.from, &args.to);
        let body = serde_json::to_string_pretty(&path).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    // ---------------- funnel (idea -> plan -> node -> run) ----------------

    #[tool(description = "Submit a new idea into the intake funnel. Returns the assigned idea id (e.g. \"i-007\"). Use this when the user or agent surfaces something worth doing but the work hasn't been planned yet.")]
    async fn funnel_submit_idea(
        &self,
        Parameters(args): Parameters<FunnelSubmitIdeaArgs>,
    ) -> Result<CallToolResult, McpError> {
        let mut s = self.state.lock().await;
        let id = IdeaId::seq(s.funnel.funnel.next_idea);
        let ev = FunnelEvent::IdeaSubmitted {
            id: id.clone(),
            source: args.source.unwrap_or_else(|| "mcp".into()),
            text: args.text,
            refs: Vec::new(),
            ts: Utc::now(),
        };
        s.funnel.record_async(ev).await.map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(id.as_str().to_string())]))
    }

    #[tool(description = "Create a plan that refines an existing idea into executable nodes. Auto-activates the plan. Returns the new plan id (e.g. \"p-003\"). Add nodes with funnel_add_node + funnel_link.")]
    async fn funnel_create_plan(
        &self,
        Parameters(args): Parameters<FunnelCreatePlanArgs>,
    ) -> Result<CallToolResult, McpError> {
        let mut s = self.state.lock().await;
        let plan_id = PlanId::seq(s.funnel.funnel.next_plan);
        let now = Utc::now();
        s.funnel.record_async(FunnelEvent::PlanCreated {
                id: plan_id.clone(),
                idea_id: IdeaId::new(args.idea_id),
                summary: args.summary,
                planner: "mcp".into(),
                ts: now,
            }).await.map_err(internal)?;
        s.funnel.record_async(FunnelEvent::PlanStatusChanged {
                plan_id: plan_id.clone(),
                status: PlanStatus::Active,
                why: None,
                ts: Utc::now(),
            }).await.map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(plan_id.as_str().to_string())]))
    }

    #[tool(description = "Add a node to a plan. `kind` is a free verb like \"code:write\", \"test:run\", \"doc:update\". Optionally pass `needs` (other node-ids in the same plan) to wire up dependencies in a single call. Returns the new node id (e.g. \"n-042\").")]
    async fn funnel_add_node(
        &self,
        Parameters(args): Parameters<FunnelAddNodeArgs>,
    ) -> Result<CallToolResult, McpError> {
        let mut s = self.state.lock().await;
        let plan_id = PlanId::new(args.plan_id);
        let node_id = NodeId::seq(s.funnel.funnel.next_node);
        let now = Utc::now();
        let mut params = serde_json::Map::new();
        if let Some(t) = args.title {
            params.insert("title".into(), serde_json::Value::String(t));
        }
        s.funnel.record_async(FunnelEvent::NodeAdded {
                plan_id: plan_id.clone(),
                node_id: node_id.clone(),
                kind: args.kind,
                params,
                targets: args.targets,
                prompt_excerpt: args.prompt,
                ts: now,
            }).await.map_err(internal)?;
        for from in &args.needs {
            s.funnel.record_async(FunnelEvent::EdgeAdded {
                    plan_id: plan_id.clone(),
                    from_node: NodeId::new(from.clone()),
                    to_node: node_id.clone(),
                    ts: Utc::now(),
                }).await.map_err(internal)?;
        }
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text(node_id.as_str().to_string())]))
    }

    #[tool(description = "Add a dependency edge: node `to` will only become ready once node `from` is done. Both must belong to the same plan.")]
    async fn funnel_link(
        &self,
        Parameters(args): Parameters<FunnelLinkArgs>,
    ) -> Result<CallToolResult, McpError> {
        let mut s = self.state.lock().await;
        s.funnel.record_async(FunnelEvent::EdgeAdded {
                plan_id: PlanId::new(args.plan_id),
                from_node: NodeId::new(args.from),
                to_node: NodeId::new(args.to),
                ts: Utc::now(),
            }).await.map_err(internal)?;
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text("ok".to_string())]))
    }

    #[tool(description = "What should the agent work on next? Returns a JSON array of ready PlanNodes (all deps satisfied) across every active plan, in stable topo order. Empty array = nothing ready (either all done, all blocked, or no active plans). Call this whenever your context resets.")]
    async fn funnel_next(&self) -> Result<CallToolResult, McpError> {
        let mut s = self.state.lock().await;
        s.funnel.funnel.promote_ready();
        let next = topo_ready(&mut s.funnel.funnel);
        let body = serde_json::to_string_pretty(&next).map_err(internal)?;
        Ok(CallToolResult::success(vec![Content::text(body)]))
    }

    #[tool(description = "Flip a node's status. `status` is one of: ready, active, blocked, done, abandoned. Pass `why` when blocking or abandoning. Use `done` after the actual work lands; the funnel will unblock dependents automatically on the next funnel_next call.")]
    async fn funnel_status(
        &self,
        Parameters(args): Parameters<FunnelStatusArgs>,
    ) -> Result<CallToolResult, McpError> {
        let status = match args.status.as_str() {
            "ready" => NodeStatus::Ready,
            "active" | "in_progress" => NodeStatus::InProgress,
            "blocked" => NodeStatus::Blocked,
            "done" => NodeStatus::Done,
            "failed" => NodeStatus::Failed,
            "abandoned" => NodeStatus::Failed, // closest legal status
            other => {
                return Err(McpError::invalid_params(
                    format!("unknown status {other:?}; expected ready|active|blocked|done|failed"),
                    None,
                ));
            }
        };
        let mut s = self.state.lock().await;
        s.funnel.record_async(FunnelEvent::NodeStatusChanged {
                plan_id: PlanId::new(args.plan_id),
                node_id: NodeId::new(args.node_id),
                status,
                why: args.why,
                ts: Utc::now(),
            }).await.map_err(internal)?;
        s.funnel.funnel.promote_ready();
        Ok(CallToolResult::success(vec![Content::text("ok".to_string())]))
    }

    #[tool(description = "Dump the entire funnel: ideas with their plans, each plan's nodes with status, and the dependency edges. Useful for orienting after a context reset before calling funnel_next.")]
    async fn funnel_show(&self) -> Result<CallToolResult, McpError> {
        let s = self.state.lock().await;
        let f = &s.funnel.funnel;
        let mut out = String::new();
        use std::fmt::Write;
        let _ = writeln!(out, "ideas: {}, plans: {}", f.ideas.len(), f.plans.len());
        for (iid, idea) in &f.ideas {
            let _ = writeln!(out, "  {} [{}] {}", iid.as_str(), idea.source, idea.text);
        }
        for (pid, plan) in &f.plans {
            let _ = writeln!(
                out,
                "  {} (idea {}) [{:?}] {}{} nodes, {} edges",
                pid.as_str(),
                plan.idea_id.as_str(),
                plan.status,
                plan.summary,
                plan.nodes.len(),
                plan.edges.len(),
            );
            for (nid, n) in &plan.nodes {
                let title = n.params.get("title").and_then(|v| v.as_str()).unwrap_or("");
                let _ = writeln!(out, "    {} [{:?}] {} {}", nid.as_str(), n.status, n.kind, title);
            }
        }
        Ok(CallToolResult::success(vec![Content::text(out)]))
    }
}

#[tool_handler]
impl ServerHandler for NornirServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder().enable_tools().build(),
        )
        .with_server_info(Implementation::from_build_env())
        .with_instructions(
            "nornir — companion to cargo. Tools: repos_list, guard_{status,apply,release}, \
             bench_history, release_gate_{path_patches,nexus_floor,no_regression,docs_fresh,all}, \
             docs_{init,render,check,history}, \
             search, symbol_lookup, defined_in, callers_of, callees_of, path_between, \
             funnel_{submit_idea,create_plan,add_node,link,next,status,show}. \
             The funnel is a persistent DAG of ideas → plans → nodes that survives agent \
             context loss; call funnel_show then funnel_next after any restart to find out \
             what to work on. The server reads workspace_holger/release/nornir.toml at start; \
             restart to pick up edits."
                .to_string(),
        )
    }
}

fn format_status(report: &[guard::PathStatus]) -> String {
    let mut s = String::new();
    s.push_str(&format!("{:<8} {:<8} {:<8} path\n", "exists", "writable", "changed"));
    for p in report {
        s.push_str(&format!(
            "{:<8} {:<8} {:<8} {}\n",
            yn(p.exists), yn(p.writable), yn(p.changed), p.path.display()
        ));
    }
    s
}

fn resolve_binary(workspace_root: &std::path::Path, binary: &str) -> std::path::PathBuf {
    let p = std::path::PathBuf::from(binary);
    if p.is_absolute() { p } else { workspace_root.join(p) }
}

fn yn(b: bool) -> &'static str { if b { "yes" } else { "no" } }

fn internal<E: std::fmt::Display>(e: E) -> McpError {
    McpError::internal_error(e.to_string(), None)
}

fn repo_ctx<'a>(
    s: &'a tokio::sync::MutexGuard<'a, State>,
    repo_name: &str,
) -> anyhow::Result<(PathBuf, &'a config::Repo)> {
    let repo = s.loaded.nornir.repo.get(repo_name)
        .ok_or_else(|| anyhow::anyhow!("repo `{repo_name}` not in nornir.toml"))?;
    let root = config::Nornir::repo_dir(&s.loaded.workspace_root, repo_name);
    Ok((root, repo))
}

fn mcp_last_run(repo_root: &std::path::Path, repo: &config::Repo) -> anyhow::Result<bench::BenchRun> {
    let path = repo_root.join(if repo.history.is_empty() { "bench_history.jsonl" } else { &repo.history });
    let runs = bench::history::read_all(&path)?;
    runs.into_iter().last().ok_or_else(|| anyhow::anyhow!("no bench runs in {}", path.display()))
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "nornir_mcp=info".into()),
        )
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();

    let config_path = std::env::var_os("NORNIR_CONFIG").map(PathBuf::from);
    let loaded = match config_path {
        Some(p) => config::load_explicit(&p)?,
        None => config::discover(&std::env::current_dir()?)?,
    };

    eprintln!("starting nornir-mcp; config={}", loaded.config_path.display());
    let server = NornirServer::new(loaded).await?.serve(stdio()).await?;
    server.waiting().await?;
    Ok(())
}