hank 0.4.0

In-memory, multi-tenant code-analysis engine — the structural signal for the Bobbin × Quipu stack
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
//! Tests for `pre_edit` — the fail-open contract, capability scoping, the rule
//! planes, and the audit record. Child module of `pre_edit` (`super::*` reaches
//! its private `guard_inner`/`Decision`); size-exempt (`_test.rs`).

//! Test names here shout the invariant they pin — `is_NEVER_observable`,
//! `daemon_EXPECTED_but_DOWN`, `is_DOWN_not_UP`. That capitalisation is the
//! same emphasis the prose uses throughout this repo, and it is load-bearing in
//! a test name: it says which word the assertion turns on. Allowed explicitly,
//! and scoped to tests, so the lint stays live everywhere else rather than
//! being switched off crate-wide (hank #83).
#![allow(non_snake_case)]
use super::*;

/// A repo where `leaf` is called from three other files.
fn wide_repo() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("leaf.rs"), "fn leaf() {}\n").unwrap();
    for (i, name) in ["one", "two", "three"].iter().enumerate() {
        std::fs::write(
            dir.path().join(format!("caller{i}.rs")),
            format!("fn {name}() {{ leaf(); }}\n"),
        )
        .unwrap();
    }
    dir
}

fn write_policy(dir: &Path, body: &str) {
    let bobbin = dir.join(".bobbin");
    std::fs::create_dir_all(&bobbin).unwrap();
    std::fs::write(bobbin.join("config.toml"), body).unwrap();
}

/// A session id unique to this call, so the once-per-session fail-open
/// marker (a file in the temp dir, which outlives the test process) cannot
/// leak state between tests or between `cargo test` runs.
fn unique_session() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    format!(
        "test-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    )
}

fn edit_payload(dir: &Path, file: &str, old: &str) -> String {
    serde_json::json!({
        "session_id": unique_session(),
        "cwd": dir.to_str().unwrap(),
        "tool_name": "Edit",
        "tool_input": {
            "file_path": dir.join(file).to_str().unwrap(),
            "old_string": old,
            "new_string": "fn leaf() { changed(); }",
        },
    })
    .to_string()
}

#[test]
fn allows_when_no_policy_is_configured() {
    let dir = wide_repo();
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn allows_when_mode_is_off_despite_a_scope() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"off\"\n[hank.policy.scopes.t]\nmax_impacted_symbols = 0\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn denies_an_out_of_scope_path() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.policy.scopes.t]\nallow_paths = [\"caller*.rs\"]\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    let Outcome::Deny(reason) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("expected a deny");
    };
    assert!(reason.contains("leaf.rs"));
    assert!(reason.contains("outside the writable capability scope"));
}

#[test]
fn denies_an_edit_that_exceeds_the_blast_radius() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 30000\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 1\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    let Outcome::Deny(reason) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("expected a deny");
    };
    // leaf is called from three files; the ceiling is one.
    assert!(reason.contains("3 files (ceiling 1)"), "got: {reason}");
}

#[test]
fn allows_an_edit_within_the_blast_radius() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 30000\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 10\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn advise_mode_never_denies() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"advise\"\ndeadline_ms = 30000\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 1\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    let Outcome::Notify(message) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("expected an advisory, not a block");
    };
    assert!(message.contains("not blocking"));
}

#[test]
fn an_untouched_tenant_is_unconstrained() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.policy.scopes.other]\nallow_paths = [\"nothing/**\"]\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
    // ...and so is an agent with no tenant at all.
    assert_eq!(guard(&payload, dir.path(), None, None), Outcome::Allow);
}

#[test]
fn a_blown_deadline_allows_the_edit_and_says_so() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 0\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 1\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    // The same edit is denied with a real budget (see the test above), so
    // this proves the deadline — not the policy — is what let it through.
    // CONTRACT CHANGE: it still ALLOWS (fail-open is deliberate), but it no
    // longer allows in SILENCE. This test previously asserted Outcome::Allow,
    // which is the same value a clean edit produces — so the suite could not
    // tell "we did not look" from "we looked and it was fine", and neither
    // could an operator.
    match guard(&payload, dir.path(), Some("t"), None) {
        Outcome::Notify(message) => {
            assert!(message.contains("NOT EVALUATED"), "{message}");
            assert!(message.contains("deadline_ms"), "{message}");
        }
        other => panic!("a blown deadline must be reported, got {other:?}"),
    }
}

#[test]
fn a_path_check_still_applies_under_a_zero_deadline() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 0\n\
         [hank.policy.scopes.t]\nallow_paths = [\"caller*.rs\"]\n",
    );
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert!(matches!(
        guard(&payload, dir.path(), Some("t"), None),
        Outcome::Deny(_)
    ));
}

#[test]
fn garbage_and_unknown_payloads_allow() {
    let dir = wide_repo();
    assert_eq!(
        guard("not json", dir.path(), Some("t"), None),
        Outcome::Allow
    );
    let no_file = serde_json::json!({ "tool_input": {} }).to_string();
    assert_eq!(guard(&no_file, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn a_malformed_glob_fails_open_loudly() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.policy.scopes.t]\nallow_paths = [\"src/[\"]\n",
    );
    let session = unique_session();
    let payload = serde_json::json!({
        "session_id": session,
        "cwd": dir.path().to_str().unwrap(),
        "tool_name": "Edit",
        "tool_input": {
            "file_path": dir.path().join("leaf.rs").to_str().unwrap(),
            "old_string": "fn leaf() {}",
        },
    })
    .to_string();

    let Outcome::Notify(message) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("expected a fail-open notice, not a block");
    };
    assert!(message.contains("UNGUARDED"));
    assert!(message.contains("malformed path globs"));

    // Second edit in the same session: still allowed, but no longer noisy.
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
    let _ =
        std::fs::remove_file(std::env::temp_dir().join(format!("hank-guard-failopen-{session}")));
}

#[test]
fn two_different_gaps_in_one_session_both_notify() {
    // Regression (aegis-nz2x): the once-per-session notice was keyed on the
    // session alone, so the FIRST fail-open of any kind consumed the marker and
    // every later, DIFFERENT gap in that session went silent. A config error in
    // one repo would mute a blown blast-radius deadline in another. Demonstrated
    // on the shipped binary before this fix: edit 1 (bad config) notified, edit 2
    // (blown deadline) emitted nothing at all.
    let session = unique_session();
    let mkpayload = |dir: &Path, file: &str| {
        serde_json::json!({
            "session_id": session,
            "cwd": dir.to_str().unwrap(),
            "tool_name": "Edit",
            "tool_input": {
                "file_path": dir.join(file).to_str().unwrap(),
                "old_string": "fn leaf() {}",
                "new_string": "fn leaf() { x(); }",
            },
        })
        .to_string()
    };

    // Gap 1: an unreadable config.
    let a = tempfile::tempdir().unwrap();
    std::fs::write(a.path().join("leaf.rs"), "fn leaf() {}\n").unwrap();
    write_policy(a.path(), "this is not [[[ valid toml");
    let Outcome::Notify(m1) = guard(&mkpayload(a.path(), "leaf.rs"), a.path(), Some("t"), None)
    else {
        panic!("gap 1 (config) must notify");
    };
    assert!(m1.contains("failed open"), "{m1}");

    // Gap 2: SAME session, a blown blast-radius deadline — a different kind.
    let b = wide_repo();
    write_policy(
        b.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 0\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 1\n",
    );
    match guard(&mkpayload(b.path(), "leaf.rs"), b.path(), Some("t"), None) {
        Outcome::Notify(m2) => assert!(m2.contains("NOT EVALUATED"), "{m2}"),
        other => {
            panic!("gap 2 (deadline) was SILENCED by gap 1's marker — the exact bug: {other:?}")
        }
    }

    for kind in ["config", "unmeasured-deadline-leaf.rs"] {
        let _ = std::fs::remove_file(
            std::env::temp_dir().join(format!("hank-guard-failopen-{session}-{kind}")),
        );
    }
}

#[test]
fn an_unparseable_language_is_reported_unmeasured_not_silently_allowed() {
    let dir = wide_repo();
    std::fs::write(dir.path().join("notes.md"), "# hi\n").unwrap();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 30000\n\
         [hank.policy.scopes.t]\nmax_impacted_files = 0\n",
    );
    let payload = edit_payload(dir.path(), "notes.md", "# hi");
    // A zero ceiling denies anything measurable, so an Allow here means the
    // rule did not apply. Declining to measure is still right — but the
    // decline must be VISIBLE, or a rule that cannot be evaluated is
    // indistinguishable from one that passed. That is the whole bug: a fleet
    // was days from turning blocking on over ceilings that silently did not
    // apply to .py/.ts/.go.
    match guard(&payload, dir.path(), Some("t"), None) {
        Outcome::Notify(message) => {
            assert!(message.contains("NOT EVALUATED"), "{message}");
            assert!(message.contains("no grammar for `.md`"), "{message}");
            assert!(message.contains("UNGUARDED"), "{message}");
        }
        other => panic!("an unparseable language must be reported, got {other:?}"),
    }
}

/// THE regression test, at the guard level: a ceiling that denies a Rust edit
/// must deny the identical edit in Python and TypeScript. Measured on the
/// shipped v0.2.0 binary, both ALLOWED with empty stdout.
#[cfg(feature = "langs-extra")]
#[test]
fn a_ceiling_that_denies_rust_denies_python_and_typescript_too() {
    let cases: &[(&str, &str, &str, &str)] = &[
        (
            "py",
            "def leaf():\n    return 1\n",
            "from leaf import leaf\ndef one():\n    return leaf()\n",
            "def leaf():",
        ),
        (
            "ts",
            "export function leaf(): number { return 1; }\n",
            "import { leaf } from \"./leaf\";\nexport function one() { return leaf(); }\n",
            "export function leaf(): number { return 1; }",
        ),
    ];
    for (ext, leaf_src, caller_src, anchor) in cases {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(format!("leaf.{ext}")), leaf_src).unwrap();
        std::fs::write(dir.path().join(format!("one.{ext}")), caller_src).unwrap();
        write_policy(
            dir.path(),
            "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 30000\n\
             [hank.policy.scopes.t]\nmax_impacted_files = 0\n",
        );
        let payload = edit_payload(dir.path(), &format!("leaf.{ext}"), anchor);
        match guard(&payload, dir.path(), Some("t"), None) {
            Outcome::Deny(message) => assert!(
                message.contains("reaches"),
                ".{ext}: denied, but not for reach: {message}"
            ),
            other => panic!(
                ".{ext}: a zero ceiling did NOT deny an edit reaching another \
                 file — got {other:?}. The rule silently does not apply."
            ),
        }
    }
}

/// The load-bearing test for aegis-ll3p: a scope supplied ONLY via
/// `--config` must actually govern the edit. The ambient config allows
/// (no policy), so a deny here can only come from the override being read.
#[test]
fn a_config_override_scopes_the_guard() {
    let dir = wide_repo(); // no `.bobbin/config.toml` — ambient allows everything
    let scope_file = dir.path().join("elsewhere").join("scope.toml");
    std::fs::create_dir_all(scope_file.parent().unwrap()).unwrap();
    std::fs::write(
        &scope_file,
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.policy.scopes.t]\nallow_paths = [\"src/**\"]\n",
    )
    .unwrap();
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");

    // Negative control: without the override, the ambient (absent) config
    // allows the edit.
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);

    // With the override, `leaf.rs` is outside `src/**` and is denied.
    let Outcome::Deny(reason) = guard(&payload, dir.path(), Some("t"), Some(&scope_file)) else {
        panic!("the --config scope must govern the edit");
    };
    assert!(reason.contains("leaf.rs"));
    assert!(reason.contains("outside the writable capability scope"));
}

/// A `--config` path that does not exist must fail OPEN loudly, never
/// silently revert to the ambient config — reverting is the disarm this
/// override exists to prevent. Fail-open (allow) is still correct for a
/// guard, but it must be the loud, once-per-session kind.
#[test]
fn a_missing_config_override_fails_open_loudly() {
    let dir = wide_repo();
    // An ambient policy that WOULD deny, to prove the fail-open is the
    // override erroring — not the ambient config quietly taking over.
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.policy.scopes.t]\nallow_paths = [\"src/**\"]\n",
    );
    let missing = dir.path().join("does-not-exist.toml");
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");

    let Outcome::Notify(message) = guard(&payload, dir.path(), Some("t"), Some(&missing)) else {
        panic!("a bad --config must fail open loudly, not deny and not silently revert");
    };
    assert!(message.contains("UNGUARDED"));
    assert!(message.contains("does not exist"));
}

// --- Structural rules (tree-sitter tier) at the guard level -----------------

/// A `[[hank.policy.rules]]` set banning ticket ids in comments. TOML literal
/// (single-quote) strings keep the regex and query free of escape doubling.
const NO_TICKET_RULE: &str = "[hank.policy]\nmode = \"enforce\"\n\n\
     [[hank.policy.rules]]\nname = \"no-ticket-in-comment\"\nlanguage = \"rust\"\n\
     query = '(line_comment) @c'\nmatch_type = \"must-not-match\"\n\
     pattern = '\\b[A-Z]+-[0-9]+\\b'\n";

fn rule_edit_payload(dir: &Path, new_string: &str) -> String {
    serde_json::json!({
        "session_id": unique_session(),
        "cwd": dir.to_str().unwrap(),
        "tool_name": "Edit",
        "tool_input": {
            "file_path": dir.join("leaf.rs").to_str().unwrap(),
            "old_string": "fn leaf() {}",
            "new_string": new_string,
        },
    })
    .to_string()
}

#[test]
fn a_rule_denies_an_edit_introducing_a_forbidden_comment() {
    let dir = wide_repo();
    write_policy(dir.path(), NO_TICKET_RULE);
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // see ABC-123");
    let Outcome::Deny(reason) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("a forbidden comment must be denied");
    };
    assert!(reason.contains("no-ticket-in-comment"), "{reason}");
    assert!(reason.contains("ABC-123"), "{reason}");
    // Honest about provenance AND freshness (FR-3): a local-config verdict is
    // computed against the exact proposed edit, so it declares itself fresh —
    // it never silently omits or fakes the tag.
    assert!(reason.contains("treesitter tier"), "{reason}");
    assert!(reason.contains("verdict freshness: fresh"), "{reason}");
}

#[test]
fn a_rule_allows_a_clean_edit() {
    let dir = wide_repo();
    write_policy(dir.path(), NO_TICKET_RULE);
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // no ticket here");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn a_rule_applies_even_without_a_tenant_scope() {
    // Rules are global: no scopes table and no tenant, still enforced. This is
    // the whole reason they run BEFORE the tenant-scope gate.
    let dir = wide_repo();
    write_policy(dir.path(), NO_TICKET_RULE);
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // ABC-123");
    assert!(matches!(
        guard(&payload, dir.path(), None, None),
        Outcome::Deny(_)
    ));
}

#[test]
fn advise_mode_reports_a_rule_without_blocking() {
    let dir = wide_repo();
    write_policy(dir.path(), &NO_TICKET_RULE.replace("enforce", "advise"));
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // ABC-123");
    let Outcome::Notify(msg) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("advise must not block");
    };
    assert!(msg.contains("not blocking"), "{msg}");
}

#[test]
fn a_pre_existing_comment_is_not_re_flagged_only_the_introduced_text_is() {
    // The edit introduces a CLEAN comment; a bad comment already on disk is not
    // the agent's doing this turn, so the rule (which reads only introduced
    // text) allows.
    let dir = wide_repo();
    std::fs::write(
        dir.path().join("leaf.rs"),
        "// legacy XYZ-999\nfn leaf() {}\n",
    )
    .unwrap();
    write_policy(dir.path(), NO_TICKET_RULE);
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // clean now");
    assert_eq!(guard(&payload, dir.path(), Some("t"), None), Outcome::Allow);
}

#[test]
fn a_malformed_rule_fails_open_loudly() {
    let dir = wide_repo();
    let bad = "[hank.policy]\nmode = \"enforce\"\n\n\
         [[hank.policy.rules]]\nname = \"broken\"\nlanguage = \"rust\"\n\
         query = '(nonexistent_node) @x'\nmatch_type = \"must-not-match\"\npattern = 'x'\n";
    write_policy(dir.path(), bad);
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // whatever");
    let Outcome::Notify(msg) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("a malformed rule must fail open loudly, not block and not pass silently");
    };
    assert!(msg.contains("UNGUARDED"), "{msg}");
    assert!(msg.contains("do not compile"), "{msg}");
}

/// Projection is opt-in and behind the `quipu` feature: when quipu cannot be
/// reached, governed policy that could not be projected must be VISIBLE — a
/// loud fail-open, never a silent pass. (An unreachable port stands in for a
/// down quipu without a live server.)
#[cfg(feature = "quipu")]
#[test]
fn an_unreachable_quipu_projection_fails_open_loudly() {
    let dir = wide_repo();
    write_policy(
        dir.path(),
        "[hank.policy]\nmode = \"enforce\"\n\
         [hank.quipu]\nenabled = true\nendpoint = \"http://127.0.0.1:1\"\n",
    );
    let payload = rule_edit_payload(dir.path(), "fn leaf() {} // whatever");
    let Outcome::Notify(msg) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("an unreachable quipu projection must fail open loudly, not pass silently");
    };
    assert!(msg.contains("UNGUARDED"), "{msg}");
    assert!(msg.contains("could not project governed policy"), "{msg}");
}

// --- FR-31 thin-client cutover: daemon expected vs. absent (aegis-1qze) ------
//
// Four quadrants of (daemon expected?) x (daemon reachable?). A closed port
// (mcp_http_port = 1, never listening) stands in for "down" without a tokio
// server. The "up and used" quadrant is covered at the client level by the
// fetch_measure test against a live daemon in `daemon::http`.

const ALLOWS: &str = "[hank.policy.scopes.t]\nmax_impacted_files = 50\n";
const FORBIDS: &str = "[hank.policy.scopes.t]\nmax_impacted_files = 0\n";

fn policy_with_daemon(scope: &str, use_daemon: bool) -> String {
    format!(
        "[hank.policy]\nmode = \"enforce\"\ndeadline_ms = 30000\n{scope}\n\
         [hank.serve]\nuse_daemon = {use_daemon}\nbind_address = \"127.0.0.1\"\n\
         mcp_http_port = 1\n"
    )
}

#[test]
fn no_daemon_expected_is_silent_transient_the_normal_case() {
    // use_daemon = false (the default, and every case today). The guard builds
    // transiently and says NOTHING about a daemon — absence is normal.
    let dir = wide_repo();
    write_policy(dir.path(), &policy_with_daemon(ALLOWS, false));
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert_eq!(
        guard(&payload, dir.path(), Some("t"), None),
        Outcome::Allow,
        "no daemon expected: transient build, allowed, silent"
    );
}

#[test]
fn daemon_EXPECTED_but_DOWN_falls_back_and_is_LOUD_when_allowed() {
    // The cheapest-bypass case. A daemon is expected (use_daemon = true) but the
    // port is closed. The guard must STILL run (fail-open, via transient) and,
    // because the edit is allowed, say LOUDLY that the resident guard is down.
    let dir = wide_repo();
    write_policy(dir.path(), &policy_with_daemon(ALLOWS, true));
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    let Outcome::Notify(msg) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("an allowed edit while the expected daemon is down must be LOUD, not silent");
    };
    assert!(msg.contains("daemon is DOWN"), "{msg}");
}

#[test]
fn daemon_EXPECTED_but_DOWN_still_DENIES_a_violation_block_wins() {
    // Fail-open does not mean fail-quiet on a real violation: a down daemon must
    // not turn a Deny into an allow. The transient fallback still enforces, and a
    // Deny wins over the daemon-absent notice.
    let dir = wide_repo(); // leaf is called from three files
    write_policy(dir.path(), &policy_with_daemon(FORBIDS, true));
    let payload = edit_payload(dir.path(), "leaf.rs", "fn leaf() {}");
    assert!(
        matches!(
            guard(&payload, dir.path(), Some("t"), None),
            Outcome::Deny(_)
        ),
        "a violation must still be denied even with the expected daemon down"
    );
}

#[test]
fn daemon_EXPECTED_but_DOWN_keeps_the_UNMEASURED_contract() {
    // An unparseable file is still UNMEASURED (not a silent zero), and that notice
    // takes precedence over the daemon-absent one — the transient fallback reports
    // it exactly as it would with no daemon configured.
    let dir = wide_repo();
    std::fs::write(dir.path().join("notes.md"), "# hi\n").unwrap();
    write_policy(dir.path(), &policy_with_daemon(ALLOWS, true));
    let payload = edit_payload(dir.path(), "notes.md", "# hi");
    let Outcome::Notify(msg) = guard(&payload, dir.path(), Some("t"), None) else {
        panic!("an unmeasurable file must stay UNMEASURED-loud");
    };
    assert!(msg.contains("NOT EVALUATED"), "{msg}");
}
// --- the governed TEXT plane's blocking matrix (aegis-m9ln / aegis-mqnl) ---
//
// The pure half of governed_check: which tier x exposure combinations
// BLOCK. This is the part of the circuit that must never be wrong in the
// blocking direction, so it is tested without a network. The projection
// and evaluation halves have their own suites (project.rs, textrules.rs).

#[cfg(feature = "quipu")]
fn text_violation(tier: crate::textrules::TextTier) -> crate::textrules::TextViolation {
    crate::textrules::TextViolation {
        rule: "pattern_internal-lan-host".into(),
        tier,
        message: "governed text rule `pattern_internal-lan-host`: the edit \
                  introduces `dolt.lan` (hostname) — internal .lan hostname."
            .into(),
    }
}

#[cfg(feature = "quipu")]
#[test]
fn a_block_tier_hit_in_a_public_repo_blocks() {
    use crate::project::RepoExposure;
    let (messages, blocks) = text_plane(
        &[text_violation(crate::textrules::TextTier::Block)],
        &RepoExposure::Public,
    );
    assert!(blocks, "this is the exact leak the rule exists to stop");
    assert!(messages.iter().any(|m| m.contains("PUBLIC remote")));
}

#[cfg(feature = "quipu")]
#[test]
fn a_block_tier_hit_in_an_internal_repo_downgrades_and_says_why() {
    use crate::project::RepoExposure;
    let (messages, blocks) = text_plane(
        &[text_violation(crate::textrules::TextTier::Block)],
        &RepoExposure::Internal,
    );
    assert!(!blocks, "internal-only exposure must not block");
    assert!(messages.iter().any(|m| m.contains("downgraded")));
    assert!(messages
        .iter()
        .any(|m| m.contains("would BLOCK in a public repo")));
}

#[cfg(feature = "quipu")]
#[test]
fn an_unknown_repo_never_blocks_and_says_it_is_unknown() {
    // mqnl's constraint verbatim: warn AND SAY SO — never block on a guess.
    use crate::project::RepoExposure;
    let (messages, blocks) = text_plane(
        &[text_violation(crate::textrules::TextTier::Block)],
        &RepoExposure::Unknown("repo `hank` is not in the graph".into()),
    );
    assert!(!blocks);
    assert!(messages
        .iter()
        .any(|m| m.contains("never blocks on a guess")));
    assert!(messages.iter().any(|m| m.contains("not in the graph")));
    // The remedy is named: exposure is DATA, so the fix is a graph write.
    assert!(messages.iter().any(|m| m.contains("repo_<name>")));
}

#[cfg(feature = "quipu")]
#[test]
fn a_warn_tier_hit_never_blocks_even_in_a_public_repo() {
    use crate::project::RepoExposure;
    let (_, blocks) = text_plane(
        &[text_violation(crate::textrules::TextTier::Warn)],
        &RepoExposure::Public,
    );
    assert!(
        !blocks,
        "warn tier is advisory everywhere — per-pattern tier is data"
    );
}