lific 2.8.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
//! LIF-201: enumeration-derived authorization completeness checks — design
//! decision #15 in LIF-DOC-7. "Enumeration-derived" means the manifests
//! below are checked against the *actual* set of REST routes / MCP tools
//! shipped in the binary (parsed from `api/mod.rs` source for REST, read at
//! runtime from the live `ToolRouter` for MCP), not hand-maintained lists
//! that can silently drift. Add a new `.route(...)` or `#[tool]` and forget
//! to classify it here, and `every_rest_route_is_classified` /
//! `every_mcp_tool_is_classified` fail with the exact method+path (or tool
//! name) that needs a manifest entry — the enforcement equivalent of an
//! exhaustive `match`.
//!
//! This module does **not** re-verify the actual runtime behavior (allow vs.
//! deny for each role) — that's the job of `authz.rs`'s unit tests, the
//! `authz_gating_tests` modules in `api/mod.rs` / `mcp/tools.rs`, and
//! `api/members.rs`'s tests. This module's only job is "is every surface
//! accounted for at all," which is a different (and easy to silently miss)
//! failure mode than "is the gate correct."

use std::collections::HashMap;

/// The role level a `Gated` surface checks. Mirrors `crate::authz`'s public
/// gates so the manifest below reads as "which function guards this."
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Gate {
    /// `authz::require_role(.., Role::Viewer)` (read access).
    Viewer,
    /// `authz::require_role(.., Role::Maintainer)` (content mutation).
    Maintainer,
    /// `authz::require_role(.., Role::Lead)` (project settings).
    Lead,
    /// `authz::require_structure_role` (modules/labels/folders).
    StructureRole,
    /// `authz::require_project_delete_role` (`DELETE` project / `delete`
    /// MCP tool with `resource_type="project"`).
    ProjectDelete,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Classification {
    /// Denies below `Gate`; enforced identically flag-on, and (for the
    /// legacy branch) reproduces pre-LIF-194 behavior — see `authz.rs`.
    Gated(Gate),
    /// Cross-project read: never denies, filters via
    /// `authz::visible_project_ids` instead (LIF-DOC-7's "visibility
    /// primitive").
    Filtered,
    /// One handler/tool multiplexes several sub-operations (REST: none;
    /// MCP: `delete`, `list_resources`, `manage_resource` dispatch on an
    /// enum-ish string argument) with *different* classifications per
    /// branch. The `&str` documents each branch's own gate so a reviewer
    /// doesn't have to re-derive it from source — the branches themselves
    /// are exercised by `authz_gating_tests` in both transports.
    Mixed(&'static str),
    /// Deliberately outside `authz.rs`'s project-role model — global
    /// account/instance surfaces, ownership-based checks, health/public
    /// endpoints. `&str` is the reason, checked only for non-emptiness (so
    /// a lazy `Exempt("")` doesn't slip through unreviewed).
    Exempt(&'static str),
}

// ── REST: source-derived route extraction ───────────────────────────

/// Extract every `(METHOD, PATH)` pair registered via `.route(...)` in the
/// given axum router source. Deliberately a small hand-rolled parser rather
/// than pulling in `regex` as a new dependency (LIF-201 is test-only code;
/// AGENTS.md scopes this issue to `src/` — a `dev-dependencies` bump is
/// avoidable here). Works because we control the source formatting: method
/// calls always appear as a bare identifier immediately followed by `(`
/// (`get(`, `.post(`, etc.), which can't collide with a handler function
/// name like `get_issue(` because the character after `get` there is `_`,
/// not `(`.
fn extract_rest_routes(src: &str) -> Vec<(String, String)> {
    const METHODS: [&str; 5] = ["get", "post", "put", "patch", "delete"];
    let mut routes = Vec::new();
    let bytes = src.as_bytes();
    let mut idx = 0;

    while let Some(rel) = src[idx..].find(".route(") {
        let start = idx + rel + ".route(".len();
        let mut depth = 1usize;
        let mut in_string = false;
        let mut i = start;
        while i < bytes.len() && depth > 0 {
            match bytes[i] {
                b'"' => in_string = !in_string,
                b'(' if !in_string => depth += 1,
                b')' if !in_string => depth -= 1,
                _ => {}
            }
            i += 1;
        }
        let call_body = &src[start..i.saturating_sub(1)];
        idx = i;

        let Some(q1) = call_body.find('"') else {
            continue;
        };
        let Some(q2_rel) = call_body[q1 + 1..].find('"') else {
            continue;
        };
        let path = call_body[q1 + 1..q1 + 1 + q2_rel].to_string();

        for method in METHODS {
            let needle = format!("{method}(");
            let mut search_from = 0;
            while let Some(pos) = call_body[search_from..].find(needle.as_str()) {
                let abs = search_from + pos;
                let word_start = abs == 0
                    || !call_body[..abs]
                        .chars()
                        .next_back()
                        .is_some_and(|c| c.is_alphanumeric() || c == '_');
                if word_start {
                    routes.push((method.to_ascii_uppercase(), path.clone()));
                    break;
                }
                search_from = abs + needle.len();
            }
        }
    }
    routes
}

/// The classification manifest for every route `api::router` registers
/// (`src/api/mod.rs`). Hand-authored, checked for completeness (not
/// correctness — see module docs) by `every_rest_route_is_classified`.
fn rest_manifest() -> HashMap<(&'static str, &'static str), Classification> {
    use Classification::{Exempt, Filtered, Gated};
    use Gate::*;

    const NOT_PROJECT_SCOPED: &str = "global account/instance surface, not project-scoped — gated (or intentionally open) independent of authz.rs";
    const PUBLIC: &str = "unauthenticated by design (auth screen / health check)";

    HashMap::from([
        // ── Public / instance ──
        (("GET", "/api/instance"), Exempt(PUBLIC)),
        (
            ("GET", "/api/instance/settings"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (
            ("PATCH", "/api/instance/settings"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (("GET", "/api/health"), Exempt(PUBLIC)),
        (
            ("GET", "/api/events/ws"),
            Exempt("cookie-authenticated event stream, not project-scoped"),
        ),
        // ── Auth: self-service, own account, not project-scoped ──
        (("POST", "/api/auth/signup"), Exempt(PUBLIC)),
        (("POST", "/api/auth/login"), Exempt(PUBLIC)),
        (
            ("POST", "/api/auth/auto-login"),
            Exempt("public but instance-flag gated — LIF-215"),
        ),
        (("POST", "/api/auth/logout"), Exempt(NOT_PROJECT_SCOPED)),
        (("GET", "/api/auth/me"), Exempt(NOT_PROJECT_SCOPED)),
        (("PATCH", "/api/auth/me"), Exempt(NOT_PROJECT_SCOPED)),
        (
            ("POST", "/api/auth/me/password"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (
            ("DELETE", "/api/auth/me/sessions"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (("POST", "/api/auth/me/refresh"), Exempt(NOT_PROJECT_SCOPED)),
        (("GET", "/api/auth/keys"), Exempt(NOT_PROJECT_SCOPED)),
        (("POST", "/api/auth/keys"), Exempt(NOT_PROJECT_SCOPED)),
        (
            ("DELETE", "/api/auth/keys/{id}"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (("GET", "/api/auth/bots"), Exempt(NOT_PROJECT_SCOPED)),
        (("POST", "/api/auth/bots"), Exempt(NOT_PROJECT_SCOPED)),
        (
            ("POST", "/api/auth/bots/{id}/disconnect"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (
            ("DELETE", "/api/auth/bots/{id}"),
            Exempt(NOT_PROJECT_SCOPED),
        ),
        (
            ("GET", "/api/users"),
            Exempt(
                "global user directory for UI dropdowns; auth-required only, via the outer auth_middleware_wrapper plus a handler-level require_user backstop (PR #29 report)",
            ),
        ),
        // LIF-214: the instance-admin axis. Orthogonal to project roles:
        // `require_admin` in the handler, plus the last-admin and no-bots
        // guard rails in db::queries::users.
        (
            ("POST", "/api/users"),
            Exempt("instance-admin roster: create an account, require_admin"),
        ),
        (
            ("POST", "/api/users/{id}/promote"),
            Exempt("instance-admin roster: grant instance admin, require_admin"),
        ),
        (
            ("POST", "/api/users/{id}/demote"),
            Exempt("instance-admin roster: revoke instance admin, require_admin"),
        ),
        (
            ("POST", "/api/users/{id}/deactivate"),
            Exempt("instance-admin roster: switch an account off, require_admin"),
        ),
        (
            ("POST", "/api/users/{id}/reactivate"),
            Exempt("instance-admin roster: restore an account, require_admin"),
        ),
        // ── Comments: Viewer to read/create (project resolved from parent) ──
        (("GET", "/api/issues/{issue_id}/comments"), Gated(Viewer)),
        (("POST", "/api/issues/{issue_id}/comments"), Gated(Viewer)),
        (("GET", "/api/pages/{page_id}/comments"), Gated(Viewer)),
        (("POST", "/api/pages/{page_id}/comments"), Gated(Viewer)),
        // LIF-410: mutating a comment takes the same Viewer gate reading one
        // does, checked *before* the author-or-admin ownership test on top of
        // it — authorship alone used to be enough, so an ex-member could keep
        // editing and deleting comments in a project they'd been removed
        // from. Gated(Viewer) is the project-role floor; ownership is the
        // additional check the Gate enum has no vocabulary for (same shape as
        // the saved-views entries above).
        (("PUT", "/api/comments/{id}"), Gated(Viewer)),
        (("DELETE", "/api/comments/{id}"), Gated(Viewer)),
        // ── Attachments (LIF-262) ──
        // The list endpoint gates on the owning entity's project at Viewer.
        (("GET", "/api/attachments"), Gated(Viewer)),
        // Upload is open to any authenticated user (per-user rate-limited); the
        // blob only becomes project-visible once linked into an entity, so
        // there's no project to gate at upload time.
        (
            ("POST", "/api/attachments"),
            Exempt(
                "any authenticated user may upload the blob itself (per-user rate-limited; it stays invisible until linked) — but the optional entity_type/entity_id link is gated dynamically against the target's project: Maintainer for an issue/page, Viewer for a comment, workspace-admin for a project-less page. See api::attachments::authorize_link (LIF-262, LIF-405)",
            ),
        ),
        // Download/delete authorize dynamically against EVERY project the
        // attachment is linked into (Viewer to read, Maintainer/uploader/admin
        // to delete), which no single fixed gate level captures.
        (
            ("GET", "/api/attachments/{id}"),
            Exempt(
                "read gated at Viewer on any linked project, or uploader/admin when still unlinked — dynamic, see api::attachments::authorize_read (LIF-262)",
            ),
        ),
        (
            ("DELETE", "/api/attachments/{id}"),
            Exempt(
                "delete gated at uploader, Maintainer on any linked project, or admin — dynamic, see api::attachments::authorize_delete (LIF-262)",
            ),
        ),
        // LIF-418. Alt text is metadata on the file, so it reuses the delete
        // gate verbatim; the three derived reads reuse the download gate.
        (
            ("PATCH", "/api/attachments/{id}"),
            Exempt(
                "alt-text edit gated identically to delete (uploader, Maintainer on any linked project, or admin): dynamic, see api::attachments::authorize_delete (LIF-418)",
            ),
        ),
        (
            ("GET", "/api/attachments/{id}/thumbnail"),
            Exempt(
                "same dynamic read gate as the download it derives from. See api::attachments::authorize_read (LIF-418)",
            ),
        ),
        (
            ("GET", "/api/attachments/{id}/links"),
            Exempt(
                "read gate on the attachment, then each linked entity is filtered by Viewer on its own project so the where-used list never leaks titles from invisible projects. See api::attachments::visible_links (LIF-418)",
            ),
        ),
        (
            ("GET", "/api/attachments/{id}/preview"),
            Exempt(
                "same dynamic read gate as the download it derives from. See api::attachments::authorize_read (LIF-418)",
            ),
        ),
        // LIF-418: the project files manager reads one project's whole
        // attachment set, so unlike the endpoints above it has a single fixed
        // project to gate on. Viewer, checked before the project is touched at
        // all so a non-member cannot tell an existing project from a
        // nonexistent one.
        (("GET", "/api/projects/{id}/attachments"), Gated(Viewer)),
        (
            ("GET", "/api/projects/{id}/attachments/orphans"),
            Gated(Viewer),
        ),
        // ── Projects ──
        (("GET", "/api/projects"), Filtered),
        (
            ("POST", "/api/projects"),
            Exempt(
                "open to any authenticated user; creator auto-becomes lead — LIF-DOC-7 decision #13",
            ),
        ),
        (
            ("PUT", "/api/projects/reorder"),
            Exempt("require_user only; instance-wide sidebar chrome, not a project edit — LIF-233"),
        ),
        (("GET", "/api/projects/{id}"), Gated(Viewer)),
        (("PUT", "/api/projects/{id}"), Gated(Lead)),
        (("DELETE", "/api/projects/{id}"), Gated(ProjectDelete)),
        // ── Sidebar project groups (per-user) ──
        // CRUD is identity-scoped, not project-scoped: every query filters on
        // the caller's user_id and an id belonging to someone else 404s, so
        // there is no project role to gate on. `assign` is the exception —
        // its body names a project, so it takes the Viewer gate.
        (
            ("GET", "/api/project-groups"),
            Exempt("per-user groups; ownership enforced in the query layer by user_id"),
        ),
        (
            ("POST", "/api/project-groups"),
            Exempt("per-user groups; creates only for the caller"),
        ),
        (
            ("PATCH", "/api/project-groups/{id}"),
            Exempt("per-user groups; another user's id is NotFound, never Forbidden"),
        ),
        (
            ("DELETE", "/api/project-groups/{id}"),
            Exempt("per-user groups; another user's id is NotFound, never Forbidden"),
        ),
        (("PUT", "/api/project-groups/assign"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/board"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/issue-counts"), Gated(Viewer)),
        // Dependency graph edges (LIF-363).
        (("GET", "/api/projects/{id}/relations"), Gated(Viewer)),
        (("POST", "/api/projects/{id}/import/github"), Gated(Lead)),
        // ── Membership management (LIF-199, REST/web-only) ──
        (("GET", "/api/projects/{id}/members"), Gated(Viewer)),
        (("POST", "/api/projects/{id}/members"), Gated(Lead)),
        (
            ("PATCH", "/api/projects/{id}/members/{user_id}"),
            Gated(Lead),
        ),
        (
            ("DELETE", "/api/projects/{id}/members/{user_id}"),
            Gated(Lead),
        ),
        // LIF-234: caller's own effective role — Viewer-gated, drives
        // role-aware UI affordances.
        (("GET", "/api/projects/{id}/my-role"), Gated(Viewer)),
        // @mention autocomplete candidates (LIF-263) — Viewer-gated, and
        // member-scoped in the query layer when enforcement is on.
        (
            ("GET", "/api/projects/{id}/mention-candidates"),
            Gated(Viewer),
        ),
        // ── Saved views (LIF-242, REST/web-only) ──
        // Gated(Viewer) is the *project-role* floor only — every one of
        // these additionally enforces strict per-user ownership in the
        // query layer (db::queries::views::get_owned_view), which this
        // manifest's Gate enum has no vocabulary for since it isn't a
        // project-role check at all: a project's Viewer, Maintainer, and
        // Lead can each only ever see/modify their *own* saved views, never
        // a teammate's. See src/api/views.rs's module doc comment.
        (("GET", "/api/projects/{id}/views"), Gated(Viewer)),
        (("POST", "/api/projects/{id}/views"), Gated(Viewer)),
        (
            ("PATCH", "/api/projects/{id}/views/{view_id}"),
            Gated(Viewer),
        ),
        (
            ("DELETE", "/api/projects/{id}/views/{view_id}"),
            Gated(Viewer),
        ),
        // ── Issues ──
        (("GET", "/api/issues"), Filtered),
        (("POST", "/api/issues"), Gated(Maintainer)),
        (("GET", "/api/issues/{id}"), Gated(Viewer)),
        (("PUT", "/api/issues/{id}"), Gated(Maintainer)),
        (("DELETE", "/api/issues/{id}"), Gated(Maintainer)),
        // LIF-438: undoing a soft delete is the same authority as performing
        // one, on the same project (read past the tombstone filter to find it).
        (("POST", "/api/issues/{id}/restore"), Gated(Maintainer)),
        (("GET", "/api/issues/resolve/{identifier}"), Gated(Viewer)),
        (("POST", "/api/issues/link"), Gated(Maintainer)),
        (("POST", "/api/issues/unlink"), Gated(Maintainer)),
        (("POST", "/api/issues/reverse"), Gated(Maintainer)),
        // ── Activity / export (all read-side, Viewer) ──
        (("GET", "/api/issues/{id}/activity"), Gated(Viewer)),
        (("GET", "/api/pages/{id}/activity"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/activity"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/activity/actors"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/insights"), Gated(Viewer)),
        // ── Delta sync (LIF-439) — read-side, Viewer ──
        (("GET", "/api/projects/{id}/changes"), Gated(Viewer)),
        (("GET", "/api/projects/{id}/index"), Gated(Viewer)),
        (("GET", "/api/export/issues/{identifier}"), Gated(Viewer)),
        (("GET", "/api/export/pages/{identifier}"), Gated(Viewer)),
        (("GET", "/api/export/projects/{identifier}"), Gated(Viewer)),
        // ── Structure: modules / labels / folders ──
        (("GET", "/api/modules"), Gated(Viewer)),
        (("POST", "/api/modules"), Gated(StructureRole)),
        (("GET", "/api/modules/{id}"), Gated(Viewer)),
        (("PUT", "/api/modules/{id}"), Gated(StructureRole)),
        (("DELETE", "/api/modules/{id}"), Gated(StructureRole)),
        (("GET", "/api/labels"), Gated(Viewer)),
        (("POST", "/api/labels"), Gated(StructureRole)),
        (("PUT", "/api/labels/{id}"), Gated(StructureRole)),
        (("DELETE", "/api/labels/{id}"), Gated(StructureRole)),
        (("POST", "/api/labels/{id}/merge"), Gated(StructureRole)),
        (("GET", "/api/folders"), Gated(Viewer)),
        (("POST", "/api/folders"), Gated(StructureRole)),
        (("PUT", "/api/folders/{id}"), Gated(StructureRole)),
        (("DELETE", "/api/folders/{id}"), Gated(StructureRole)),
        // ── Pages ──
        (("GET", "/api/pages"), Filtered),
        (("POST", "/api/pages"), Gated(Maintainer)),
        (("GET", "/api/pages/resolve/{identifier}"), Gated(Viewer)),
        (("GET", "/api/pages/{id}"), Gated(Viewer)),
        (("PUT", "/api/pages/{id}"), Gated(Maintainer)),
        (("DELETE", "/api/pages/{id}"), Gated(Maintainer)),
        // LIF-438: same authority as the delete it undoes.
        (("POST", "/api/pages/{id}/restore"), Gated(Maintainer)),
        // ── Plans ──
        (("GET", "/api/plans"), Filtered),
        (("POST", "/api/plans"), Gated(Maintainer)),
        (("GET", "/api/plans/{id}"), Gated(Viewer)),
        (("PUT", "/api/plans/{id}"), Gated(Maintainer)),
        (("DELETE", "/api/plans/{id}"), Gated(Maintainer)),
        (("GET", "/api/plans/resolve/{identifier}"), Gated(Viewer)),
        (("GET", "/api/plans/{id}/activity"), Gated(Viewer)),
        (("POST", "/api/plans/{id}/steps"), Gated(Maintainer)),
        (
            ("PUT", "/api/plans/{plan_id}/steps/{step_id}"),
            Gated(Maintainer),
        ),
        (
            ("DELETE", "/api/plans/{plan_id}/steps/{step_id}"),
            Gated(Maintainer),
        ),
        // ── Search ──
        (("GET", "/api/search"), Filtered),
    ])
}

#[test]
fn every_rest_route_is_classified() {
    let src = include_str!("api/mod.rs");
    let routes = extract_rest_routes(src);
    assert!(
        routes.len() > 40,
        "sanity check: route extraction found suspiciously few routes ({}) — the parser in \
         extract_rest_routes() is probably out of sync with api/mod.rs's formatting",
        routes.len()
    );

    let manifest = rest_manifest();
    let mut unclassified: Vec<String> = routes
        .iter()
        .filter(|(m, p)| !manifest.contains_key(&(m.as_str(), p.as_str())))
        .map(|(m, p)| format!("{m} {p}"))
        .collect();
    unclassified.sort();
    unclassified.dedup();

    assert!(
        unclassified.is_empty(),
        "New REST route(s) registered in api/mod.rs are not classified in \
         `rest_manifest()` (src/authz_coverage_tests.rs). Every route must be \
         Gated(<level>), Filtered, or Exempt(<reason>) before it ships — \
         see LIF-DOC-7 decision #15. Unclassified:\n  {}",
        unclassified.join("\n  ")
    );
}

#[test]
fn rest_manifest_has_no_stale_entries() {
    // The inverse of the completeness check: a manifest entry for a route
    // that was renamed/removed would otherwise sit there un-exercised
    // forever, silently hiding the fact that the *real* new route name is
    // unclassified (extract_rest_routes finds it, but a human skimming the
    // manifest sees an entry and assumes it's covered).
    let src = include_str!("api/mod.rs");
    let routes: std::collections::HashSet<(String, String)> =
        extract_rest_routes(src).into_iter().collect();

    let mut stale: Vec<String> = rest_manifest()
        .keys()
        .filter(|(m, p)| !routes.contains(&(m.to_string(), p.to_string())))
        .map(|(m, p)| format!("{m} {p}"))
        .collect();
    stale.sort();

    assert!(
        stale.is_empty(),
        "rest_manifest() has entries that no longer match a real route in api/mod.rs \
         (renamed or removed) — remove them so the manifest can't mask an unclassified \
         replacement route:\n  {}",
        stale.join("\n  ")
    );
}

#[test]
fn rest_manifest_exempt_reasons_are_non_empty() {
    for ((method, path), classification) in rest_manifest() {
        if let Classification::Exempt(reason) = classification {
            assert!(
                !reason.trim().is_empty(),
                "{method} {path} is Exempt() with no reason — every Exempt needs a reason \
                 a reviewer can check, not a bare exemption"
            );
        }
    }
}

// ── MCP: runtime tool enumeration ────────────────────────────────────

/// The classification manifest for every MCP tool `LificMcp` registers
/// (`src/mcp/tools.rs`, `#[tool_router]` block). Checked against the tool
/// names the live `ToolRouter` reports at runtime (`list_tool_names`,
/// `src/mcp/mod.rs`) — not a hand-copied list of `#[tool]` fns, so a
/// rename that only touches one side still gets caught.
fn mcp_manifest() -> HashMap<&'static str, Classification> {
    use Classification::{Exempt, Filtered, Gated, Mixed};
    use Gate::*;

    HashMap::from([
        ("search", Filtered),
        ("get_activity", Gated(Viewer)),
        ("list_issues", Gated(Viewer)),
        ("get_issue", Gated(Viewer)),
        ("export", Gated(Viewer)),
        ("create_issue", Gated(Maintainer)),
        ("update_issue", Gated(Maintainer)),
        ("bulk_update", Gated(Maintainer)),
        ("edit_issue", Gated(Maintainer)),
        ("get_board", Gated(Viewer)),
        ("link_issues", Gated(Maintainer)),
        ("unlink_issues", Gated(Maintainer)),
        ("get_page", Gated(Viewer)),
        ("create_page", Gated(Maintainer)),
        ("update_page", Gated(Maintainer)),
        ("edit_page", Gated(Maintainer)),
        (
            "delete",
            Mixed(
                "dispatches on resource_type: issue/plan/page = Maintainer (page falls back to \
                 workspace-admin when project-less); project = ProjectDelete; \
                 module/label/folder = StructureRole",
            ),
        ),
        (
            "list_resources",
            Mixed(
                "dispatches on resource_type: project = Filtered (visible_project_ids); \
                 module/label/folder/issue/plan = Viewer; page = Viewer when project given, \
                 else Filtered",
            ),
        ),
        (
            "manage_resource",
            Mixed(
                "dispatches on (resource_type, action): project/create = open to any \
                 authenticated user (mirrors REST decision #13); project/update = Lead; \
                 module|label|folder (create/update) = StructureRole",
            ),
        ),
        ("add_comment", Gated(Viewer)),
        ("list_comments", Gated(Viewer)),
        // LIF-143: mirror REST PUT/DELETE /api/comments/{id} — author-or-admin
        // ownership check, not a project-role gate.
        (
            "edit_comment",
            Exempt("author-or-admin ownership check (ownership, not project role)"),
        ),
        (
            "delete_comment",
            Exempt("author-or-admin ownership check (ownership, not project role)"),
        ),
        // LIF-418: attachment tools. Their gates are REST's, called directly
        // (`api::attachments::authorize_link` / `authorize_read`), so the two
        // transports cannot drift apart.
        (
            "upload_attachment",
            Mixed(
                "dispatches on the link target: entity=issue/page = Maintainer (workspace page \
                 falls back to workspace-admin); comment_id = Viewer; no target = open to any \
                 authenticated user, mirroring REST POST /api/attachments",
            ),
        ),
        (
            "get_attachment",
            Mixed(
                "dispatches on link state: an attachment linked into any project = Viewer on any \
                 one of them; an unlinked attachment = uploader-or-admin ownership check. Mirrors \
                 REST GET /api/attachments/{id}",
            ),
        ),
        ("list_attachments", Gated(Viewer)),
        ("create_plan", Gated(Maintainer)),
        ("get_plan", Gated(Viewer)),
        ("edit_plan_step", Gated(Maintainer)),
        ("update_plan_step", Gated(Maintainer)),
    ])
}

#[test]
fn every_mcp_tool_is_classified() {
    let db = crate::db::open_memory().expect("test db");
    let mcp = crate::mcp::LificMcp::new(db);
    let tools = mcp.list_tool_names();
    assert!(
        tools.len() > 15,
        "sanity check: only found {} MCP tools at runtime — list_tool_names()/ToolRouter \
         wiring is probably broken",
        tools.len()
    );

    let manifest = mcp_manifest();
    let mut unclassified: Vec<&str> = tools
        .iter()
        .filter(|name| !manifest.contains_key(name.as_str()))
        .map(|s| s.as_str())
        .collect();
    unclassified.sort();
    unclassified.dedup();

    assert!(
        unclassified.is_empty(),
        "New MCP tool(s) registered in src/mcp/tools.rs are not classified in \
         `mcp_manifest()` (src/authz_coverage_tests.rs). Every tool must be \
         Gated(<level>), Filtered, or Mixed(<per-branch summary>) before it ships — \
         see LIF-DOC-7 decision #15. Unclassified:\n  {}",
        unclassified.join("\n  ")
    );
}

#[test]
fn mcp_manifest_has_no_stale_entries() {
    let db = crate::db::open_memory().expect("test db");
    let mcp = crate::mcp::LificMcp::new(db);
    let tools: std::collections::HashSet<String> = mcp.list_tool_names().into_iter().collect();

    let mut stale: Vec<&str> = mcp_manifest()
        .keys()
        .filter(|name| !tools.contains(**name))
        .copied()
        .collect();
    stale.sort();

    assert!(
        stale.is_empty(),
        "mcp_manifest() has entries that no longer match a real MCP tool (renamed or \
         removed) — remove them so the manifest can't mask an unclassified replacement \
         tool:\n  {}",
        stale.join("\n  ")
    );
}

#[test]
fn mcp_manifest_mixed_reasons_are_non_empty() {
    for (name, classification) in mcp_manifest() {
        if let Classification::Mixed(reason) = classification {
            assert!(
                !reason.trim().is_empty(),
                "MCP tool '{name}' is Mixed() with no per-branch summary"
            );
        }
    }
}