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
//! The `PreToolUse` policy guard — a blocking, capability-scoped edit check.
//!
//! This is where the §5.8 trust boundary becomes concrete: an agent's edit tool
//! call is intercepted *before* it lands, sized against the tenant's capability
//! scope (FR-25), and denied with a readable reason when it exceeds it.
//!
//! Everything here is arranged around one invariant: **fail open**. The harness
//! launches every crew agent through this hook, so a guard that fails closed
//! bricks the fleet the moment Hank is unavailable. Only a policy decision
//! blocks an edit; every error, timeout, and unknown degrades to "allow". See
//! `docs/book/src/reference/policy-guard.md` for the pinned contract.

use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use super::measure::{measure_within, relative};
use super::{deny_envelope, first_notice_for_session, system_message, HookInput};
use crate::config::HankConfig;
use crate::extract::language_for_extension;
use crate::policy::{BlastRadius, Mode};
use crate::types::Freshness;

/// What the guard decided — the value the CLI turns into stdout.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// Allow the edit, silently. Exit 0, empty stdout.
    Allow,
    /// Block the edit with this model-facing reason.
    Deny(String),
    /// Allow the edit but tell the user something (advise mode, or fail-open).
    Notify(String),
}

/// Run the `pre-edit` guard: read the harness payload from stdin, decide, and
/// print at most one JSON object. Always returns `Ok` — the process must exit 0
/// so the harness never treats the guard as a fail-closed block.
pub fn run_pre_edit(tenant: Option<&str>, config_override: Option<&Path>) -> anyhow::Result<()> {
    let mut buf = String::new();
    std::io::stdin().lock().read_to_string(&mut buf).ok();
    let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    match guard(&buf, &root, tenant, config_override) {
        Outcome::Allow => {}
        Outcome::Deny(reason) => println!("{}", deny_envelope(&reason)),
        Outcome::Notify(message) => println!("{}", system_message(&message)),
    }
    Ok(())
}

/// A guard outcome plus the identity of what produced it.
///
/// [`Outcome`] is what the harness sees; this is what the AUDIT record sees.
/// They are separate because the model-facing text and the operator-facing
/// record answer different questions: the model needs to know what to do
/// instead, the operator needs to know which rule fired so a false positive can
/// be told from a correct deny (hank #77).
#[derive(Debug, Clone)]
struct Decision {
    outcome: Outcome,
    /// Stable id of the deciding rule, when one rule decided. `None` for a plain
    /// allow, where nothing fired and there is nothing to name.
    rule: Option<String>,
}

impl From<Outcome> for Decision {
    fn from(outcome: Outcome) -> Self {
        Self {
            outcome,
            rule: None,
        }
    }
}

impl Decision {
    /// A decision attributed to `rule`.
    fn ruled(outcome: Outcome, rule: impl Into<String>) -> Self {
        Self {
            outcome,
            rule: Some(rule.into()),
        }
    }
}

/// Decide an edit, and SPOOL the decision (aegis-0nng): one `guard` metrics
/// line per invocation — result, duration, extension, and (hank #77) the target
/// path and the rule that fired — through the fail-silent spool, after the
/// outcome is already fixed. Measurement rides behind the decision; it can
/// never lean on it.
#[must_use]
pub fn guard(
    input_json: &str,
    default_root: &Path,
    tenant: Option<&str>,
    config_override: Option<&Path>,
) -> Outcome {
    let started = Instant::now();
    let decision = guard_inner(input_json, default_root, tenant, config_override);
    let result = match &decision.outcome {
        Outcome::Allow => "allow",
        Outcome::Deny(_) => "deny",
        Outcome::Notify(_) => "notify",
    };
    let input = HookInput::parse(input_json);
    let file_path = input.as_ref().and_then(|i| i.tool_input.file_path.clone());
    let ext = file_path
        .as_ref()
        .and_then(|f| {
            Path::new(f)
                .extension()
                .and_then(OsStr::to_str)
                .map(str::to_string)
        })
        .unwrap_or_default();
    // Resolve the config against the PAYLOAD's root, the way `guard_inner` does
    // — not against the process CWD. The record must describe the decision that
    // was actually made: config resolved from a different root can report a
    // `mode` the deciding code never saw, which is worst precisely where the
    // mode matters (an agent invoking the hook from outside the repo it edits
    // spooled `mode: off` for a decision made under `enforce`). One root, one
    // config, one record.
    let root = input
        .as_ref()
        .map_or_else(|| default_root.to_path_buf(), |i| i.root(default_root));
    let config = HankConfig::resolve(config_override, &root).ok();
    // The MODE rides every guard line (soak hygiene): the enforce-flip gate is
    // "zero false positives measured over ambient ADVISE traffic", and the
    // first live window was unusable because operator test bursts under an
    // enforce config were indistinguishable from fleet lines. The mode is the
    // filter that makes the soak evidence clean.
    let mode = config.as_ref().map_or("?", |c| c.policy.mode.as_str());

    let mut fields: Vec<(&str, serde_json::Value)> = vec![
        ("result", result.into()),
        ("mode", mode.into()),
        (
            "duration_ms",
            u64::try_from(started.elapsed().as_millis())
                .unwrap_or(u64::MAX)
                .into(),
        ),
        ("ext", ext.into()),
    ];

    // The SUBJECT of the decision (hank #77). Recorded for allow as well as
    // deny, deliberately and under the same knob: scope that can only be
    // inferred from the absence of denies cannot be verified at all, and an
    // operator confirming a rule is scoped correctly needs to see what it let
    // through as much as what it stopped.
    //
    // Both fields are omitted rather than blanked when they have nothing to say,
    // so a reader never has to distinguish "recorded as empty" from "not
    // recorded" — the same reason the spool never writes a placeholder tier.
    if let (Some(config), Some(file_path)) = (config.as_ref(), file_path.as_ref()) {
        let file = PathBuf::from(file_path);
        let rel = relative(&file, &root);
        if let Some(recorded) = crate::audit::record_path(config.metrics.record_paths, &rel, &file)
        {
            fields.push(("path", recorded.into()));
        }
    }
    if let Some(rule) = decision.rule {
        fields.push(("rule", rule.into()));
    }

    crate::metrics::emit("guard", &fields);
    decision.outcome
}

/// The decision itself. Pure apart from reading the repo, so it is directly
/// testable without a spool in the way.
#[must_use]
fn guard_inner(
    input_json: &str,
    default_root: &Path,
    tenant: Option<&str>,
    config_override: Option<&Path>,
) -> Decision {
    let started = Instant::now();

    // An unparseable payload is an ALLOW: the guard only speaks up about edits
    // it genuinely understands.
    let Some(input) = HookInput::parse(input_json) else {
        return Outcome::Allow.into();
    };
    let Some(file_path) = input.tool_input.file_path.clone() else {
        return Outcome::Allow.into();
    };
    let root = input.root(default_root);

    // Honour `--config` if the operator scoped the guard at a specific file. A
    // bad override path errors here and lands in `fail_open` — a loud allow,
    // never a silent revert to the ambient config the operator meant to bypass.
    let config = match HankConfig::resolve(config_override, &root) {
        Ok(config) => config,
        Err(e) => return fail_open(&input, "config", &format!("unreadable config ({e})")).into(),
    };

    let file = PathBuf::from(&file_path);
    let rel = relative(&file, &root);

    // Structural rules (tree-sitter tier) govern the TEXT an edit introduces and
    // are NOT per-tenant: a "no ticket id in a comment" rule holds for everyone.
    // Evaluate them before the tenant-scope gate so they apply even to an
    // unconstrained tenant. A rule Deny/Notify short-circuits the scope checks —
    // one guard decision per edit.
    if let Some(decision) = rule_check(&config, &input, &rel) {
        return decision;
    }

    // Governed policies projected from quipu (Phase 4), evaluated where the
    // evidence is hot — BOTH planes, one registry refresh, one verdict:
    // language-independent text rules (aegis-mqnl's catalogue: the plane the
    // measured leaks needed, since they were in .md/.yml files no grammar
    // covers) and language-gated structural rules. Opt-in (quipu.enabled +
    // endpoint), and behind the `quipu` feature so a default build carries
    // none of it.
    #[cfg(feature = "quipu")]
    if let Some(decision) = governed_check(&config, &input, &root, &rel) {
        return decision;
    }

    // No scope for this tenant — mode is off, or the tenant is unconstrained.
    let (Some(tenant), Some(scope)) = (tenant, config.policy.scope_for(tenant)) else {
        return Outcome::Allow.into();
    };

    // A scope whose globs do not compile is misconfigured; say so rather than
    // quietly under-enforcing it.
    let glob_errors = scope.glob_errors();
    if !glob_errors.is_empty() {
        let detail: Vec<String> = glob_errors
            .iter()
            .map(|(pattern, why)| format!("`{pattern}` ({why})"))
            .collect();
        return fail_open(
            &input,
            "globs",
            &format!(
                "scope for tenant `{tenant}` has malformed path globs: {}",
                detail.join(", ")
            ),
        )
        .into();
    }

    // 1. Path scope — cheap, no graph needed, so it runs even under a blown
    //    deadline. This is the check that must never be skipped.
    if let Some(violation) = scope.check_path(&rel, tenant) {
        return Decision::ruled(
            decide(config.policy.mode, violation.message),
            violation.rule,
        );
    }

    // 2. Blast radius — expensive. Bounded by whatever remains of the budget.
    let budget = Duration::from_millis(config.policy.deadline_ms)
        .checked_sub(started.elapsed())
        .unwrap_or_default();
    if scope.max_impacted_symbols.is_none() && scope.max_impacted_files.is_none() {
        return Outcome::Allow.into(); // Nothing to measure against.
    }

    // Size the edit against the RESIDENT daemon when one is expected and usable,
    // else the transient build (FR-31 thin-client cutover). Both paths yield the
    // same `MeasureReply`; `daemon_absent` is set when a daemon was EXPECTED but
    // could not be used, so we can be LOUD about it below.
    let (reply, daemon_absent) = blast_reply(&config, &root, &file, &rel, &input, budget);

    let radius = if reply.measured {
        BlastRadius {
            symbols: reply.symbols,
            files: reply.files,
        }
    } else {
        // NOT MEASURED. Allowing is still the contract — the guard is fail-open by
        // design and a language we cannot parse must not brick an agent's edits.
        // But allowing SILENTLY is the defect: an unparseable file and a
        // genuinely-clean edit produced identical empty stdout, so a rule that
        // could not be evaluated looked exactly like a rule that passed. Say it
        // instead. Rate-limited to once per session by the same gate the
        // fail-open notice uses, because a per-edit message would be scrolled
        // past and then ignored.
        let reason = reply
            .reason
            .clone()
            .unwrap_or_else(|| "unmeasured".to_string());
        eprintln!("hank: blast radius UNMEASURED for `{rel}`: {reason}");
        let kind = format!("unmeasured-{}-{rel}", reply.kind);
        if first_notice_for_session(input.session_id.as_deref(), &kind) {
            return Decision::ruled(
                Outcome::Notify(format!(
                    "hank: blast-radius rules were NOT EVALUATED for `{rel}` — \
                     {reason}. The edit is allowed (the guard fails open), but \
                     tenant `{tenant}`'s ceilings did not apply to it. Treat this \
                     file as UNGUARDED by blast radius, not as within limits."
                )),
                "unmeasured",
            );
        }
        return Outcome::Allow.into();
    };

    let verdict = match scope.check_blast(radius, &rel, tenant) {
        Some(violation) => Decision::ruled(
            decide(config.policy.mode, violation.message),
            violation.rule,
        ),
        None => Outcome::Allow.into(),
    };

    // DAEMON EXPECTED BUT DOWN — the cheapest-bypass scenario the daemon exists to
    // prevent. Always log it; and when the edit is otherwise ALLOWED, surface it to
    // the model once per session, because an allowed edit while the resident guard
    // is down is exactly the silent bypass we must not let pass quietly. A Deny wins
    // (blocking the edit is the priority; the daemon-down stays on stderr); an
    // UNMEASURED Notify already returned above. The fail-open is intact: the edit was
    // still guarded, by the transient rebuild.
    if let Some(reason) = daemon_absent {
        eprintln!("hank: resident guard daemon EXPECTED but unusable: {reason}");
        if matches!(verdict.outcome, Outcome::Allow)
            && first_notice_for_session(input.session_id.as_deref(), "daemon-absent")
        {
            return Outcome::Notify(format!(
                "hank: the resident guard daemon is DOWN ({reason}). This edit was guarded by a \
                 transient rebuild and ALLOWED — but the daemon a caller could kill to bypass \
                 the guard on every edit is not running. Restart it."
            ))
            .into();
        }
    }
    verdict
}

/// Size an edit into a [`MeasureReply`], from the resident daemon when one is
/// EXPECTED and usable, else the transient build. Returns `(reply, daemon_absent)`;
/// `daemon_absent` is `Some(reason)` only when a daemon was expected but could not
/// be used — so the caller can be loud about it without ever treating "daemon down"
/// as "allow".
///
/// This is the whole cutover, and its shape is the safety contract:
/// - No daemon expected (`use_daemon = false`, the default and every case today):
///   transient build, `None`. Absence is normal and stays silent.
/// - Daemon expected and it answered: use its reply, `None`.
/// - Daemon expected and it could NOT answer (down, or serving a different repo so
///   `/measure` 400s): FALL BACK to the transient build, and return the reason so
///   the caller warns. The guard still runs — fail-open is preserved.
fn blast_reply(
    config: &HankConfig,
    root: &Path,
    file: &Path,
    rel: &str,
    input: &HookInput,
    budget: Duration,
) -> (crate::daemon::MeasureReply, Option<String>) {
    let transient = || {
        crate::daemon::MeasureReply::from_sizing(&measure_within(
            root,
            file,
            rel,
            input,
            config.policy.max_hops,
            budget,
        ))
    };

    if !config.serve.use_daemon {
        return (transient(), None);
    }

    let anchors: Vec<String> = input
        .replaced_texts()
        .into_iter()
        .map(str::to_string)
        .collect();
    match crate::daemon::client::fetch_measure(
        &config.serve.bind_address,
        config.serve.mcp_http_port,
        &file.to_string_lossy(),
        rel,
        &anchors,
        config.policy.max_hops,
        budget,
    ) {
        Ok(reply) => (reply, None),
        Err(reason) => (transient(), Some(reason)),
    }
}

#[path = "rule_planes.rs"]
mod rule_planes;
#[cfg(feature = "quipu")]
use rule_planes::governed_check;
use rule_planes::rule_check;
// The text plane's pure core is exercised directly by `pre_edit_test`, which
// sits beside this module rather than beside the plane it tests.
#[cfg(all(test, feature = "quipu"))]
use rule_planes::text_plane;

/// The text an edit INTRODUCES: the full `Write` content, else the `new_string`s
/// of an `Edit`/`MultiEdit` joined by newlines. `None` when the payload adds no
/// text (e.g. a pure deletion), in which case there is nothing for a rule to see.
fn introduced_text(input: &HookInput) -> Option<String> {
    if let Some(content) = &input.tool_input.content {
        return Some(content.clone());
    }
    let mut parts: Vec<&str> = Vec::new();
    if let Some(new) = input.tool_input.new_string.as_deref() {
        parts.push(new);
    }
    for edit in &input.tool_input.edits {
        if let Some(new) = edit.new_string.as_deref() {
            parts.push(new);
        }
    }
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("\n"))
    }
}

/// Turn a violation into an outcome according to the enforcement mode.
fn decide(mode: Mode, message: String) -> Outcome {
    match mode {
        Mode::Enforce => Outcome::Deny(message),
        // Advise: report what would have been denied, but never block.
        Mode::Advise => Outcome::Notify(format!("hank (advise, not blocking): {message}")),
        Mode::Off => Outcome::Allow,
    }
}

/// Degrade to "allow", loudly. Writes the stderr line the contract requires and,
/// once per session, a user-visible notice — because a hook's stderr is
/// surfaced only on exit `2`, so stderr alone would be silent in practice.
fn fail_open(input: &HookInput, kind: &str, reason: &str) -> Outcome {
    eprintln!("hank: policy guard failed open: {reason}");
    // The metric that separates "allowed clean" from "allowed because the
    // check could not run" — the two must never share a label (aegis-0nng).
    crate::metrics::emit("fail_open", &[("fail_kind", kind.into())]);
    if first_notice_for_session(input.session_id.as_deref(), kind) {
        return Outcome::Notify(format!(
            "hank: policy guard failed open ({reason}) — edits are UNGUARDED this session."
        ));
    }
    Outcome::Allow
}

#[cfg(test)]
#[path = "pre_edit_test.rs"]
mod pre_edit_test;