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
//! Phase-4 projection: a hot, one-directional cache of quipu's structural
//! policies (`quipu` feature).
//!
//! **Evidence locality** (`docs/book/src/design/policy-edit-hooks.md`): a
//! `tree-sitter`-tier policy is *defined* in quipu but *evaluated* in Hank, where
//! the code structure is hot. Hank never originates a policy — it projects
//! quipu's canonical `boundary:"action"` structural policies into the same
//! [`Rule`](crate::rules::Rule) shape the local config uses, and evaluates them at
//! the pre-edit seam. The projection is strictly one-directional (quipu canonical
//! → hank cache); if it diverged, Hank could allow what quipu would deny, so a
//! projected verdict always declares the cache's [`Freshness`].
//!
//! Like promotion (`src/promote.rs`), this talks to quipu over HTTP — quipu's
//! `POST /query` with the W3C-standard `application/sparql-results+json` shape —
//! so it needs no `quipu` *crate* dependency, only a blocking client. The decode
//! ([`decode_policies`]) is pure and testable against a canned result; the fetch
//! ([`fetch_policies`]) is the thin network wrapper.

use crate::errors::{Error, Result};
use crate::rules::{MatchType, Rule};
use crate::textrules::{TextRule, TextTier};
use crate::types::Freshness;

/// A policy projected from quipu: the [`Rule`] Hank evaluates, plus the governed
/// `effect` that decides what a violation does (independent of the local
pub use crate::project_queries::{EXPOSURE_POLICY_IRI, POLICY_QUERY, TEXT_POLICY_QUERY};

/// `[hank.policy] mode`, so a quipu `deny` denies and a `warn` advises).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectedPolicy {
    /// The structural rule, decoded into the same shape local config uses.
    pub rule: Rule,
    /// The governed effect: `deny`, `warn`, `require-approval`, `escalate`,
    /// `record`, or `allow`.
    pub effect: String,
}

/// Decode the [`TEXT_POLICY_QUERY`] result into text rules. Same contract as
/// [`decode_policies`]: a row missing a required binding, or carrying a tier
/// this build does not recognise, is an [`Error::Projection`] — never a
/// silently dropped rule.
pub fn decode_text_rules(sparql_json: &str) -> Result<Vec<TextRule>> {
    let value: serde_json::Value = serde_json::from_str(sparql_json)
        .map_err(|e| Error::Projection(format!("results are not JSON: {e}")))?;
    let bindings = rows_of(&value)?;

    let mut out = Vec::with_capacity(bindings.len());
    for (i, binding) in bindings.iter().enumerate() {
        let get = |key: &str| -> Option<String> { binding_value(binding, key) };
        let required = |key: &str| -> Result<String> {
            get(key).ok_or_else(|| {
                Error::Projection(format!(
                    "text-rule row {i}: missing required binding `{key}`"
                ))
            })
        };
        let tier = match required("tier")?.as_str() {
            "block" => TextTier::Block,
            "warn" => TextTier::Warn,
            other => {
                // An unrecognised tier blocks nothing silently and allows
                // nothing silently — it is a projection error the guard
                // surfaces as a loud fail-open (the conservative reading of a
                // governed decision this build cannot interpret).
                return Err(Error::Projection(format!(
                    "text-rule row {i}: unknown enforcementTier `{other}`"
                )));
            }
        };
        // The IRI tail is the stable rule name; verdicts cite it.
        let iri = required("s")?;
        let name = iri.rsplit('/').next().unwrap_or(&iri).to_string();
        let rule = TextRule {
            name,
            label: get("label"),
            pattern: required("regex")?,
            tier,
            class: get("class"),
            exempt_path_regex: get("exempt"),
            rationale: get("rationale"),
        };

        // ONE ENTITY IS ONE RULE. The query carries four OPTIONALs, and SPARQL
        // returns the CROSS PRODUCT of their bindings — so an entity with two
        // `rdfs:comment` values comes back as two rows and became two identical
        // rules. Measured on the live catalogue: 7 pattern entities projected as
        // 11 rules, 4 of them duplicates, purely because somebody had added a
        // second rationale to four of them.
        //
        // The cost lands on the model, twice over: the same violation is
        // reported twice for one edit, and the two copies carry DIFFERENT
        // rationales — for one of them, the second comment explained an
        // exemption, so the advisory argued with itself. An agent reading a
        // guard that contradicts itself learns to discount the guard.
        //
        // Multi-valued rdfs:comment is perfectly legal RDF and the catalogue is
        // right to have it. Collapsing it belongs HERE, in the decoder, not in a
        // convention nobody can enforce on graph authors.
        match out.iter_mut().find(|r: &&mut TextRule| r.name == rule.name) {
            None => out.push(rule),
            Some(existing) => {
                // A REQUIRED field that disagrees is not a duplicate to merge —
                // it is two different rules wearing one name, and picking either
                // one silently is how a guard enforces something nobody wrote.
                // Refuse, loudly, the same as an unknown tier.
                if existing.pattern != rule.pattern || existing.tier != rule.tier {
                    return Err(Error::Projection(format!(
                        "text-rule `{}` has conflicting definitions in the graph \
                         (regex or enforcementTier differ across its rows) — \
                         refusing to guess which one governs",
                        rule.name
                    )));
                }
                // Optionals: keep every DISTINCT value rather than picking one.
                // Dropping a rationale would lose the author's reasoning, and
                // choosing between them by row order would be arbitrary and
                // unstable across graph writes.
                merge_optional(&mut existing.rationale, rule.rationale);
                merge_optional(&mut existing.label, rule.label);
                merge_optional(&mut existing.class, rule.class);
                merge_optional(&mut existing.exempt_path_regex, rule.exempt_path_regex);
            }
        }
    }
    Ok(out)
}

/// Fold an additional optional binding into one a previous row already supplied.
///
/// Distinct values are joined rather than replaced: these are explanatory
/// strings, and the whole reason a second one exists is that somebody had more
/// to say. Identical values collapse, so the common case stays clean.
fn merge_optional(existing: &mut Option<String>, incoming: Option<String>) {
    let Some(add) = incoming else { return };
    match existing {
        None => *existing = Some(add),
        Some(have) => {
            if !have.split(" — ").any(|part| part == add) {
                have.push_str(" — ");
                have.push_str(&add);
            }
        }
    }
}

/// The `results.bindings` array of a W3C SPARQL-results body, or a projection
/// error naming what was malformed.
fn rows_of(value: &serde_json::Value) -> Result<&Vec<serde_json::Value>> {
    value
        .get("results")
        .and_then(|r| r.get("bindings"))
        .and_then(|b| b.as_array())
        .ok_or_else(|| Error::Projection("results have no `results.bindings` array".to_string()))
}

/// One binding's `.value` string, if present.
fn binding_value(binding: &serde_json::Value, key: &str) -> Option<String> {
    binding
        .get(key)
        .and_then(|v| v.get("value"))
        .and_then(|v| v.as_str())
        .map(str::to_string)
}

/// Fetch and decode the governed text-rule catalogue over HTTP.
pub fn fetch_text_rules(endpoint: &str) -> Result<Vec<TextRule>> {
    decode_text_rules(&query(endpoint, TEXT_POLICY_QUERY)?)
}

/// The ceiling on ANY single projection HTTP call. This path runs inside the
/// PRE-EDIT hook, so an unbounded call does not fail — it HANGS EVERY EDIT
/// (measured: a transiently wedged quipu held the guard for the full two
/// minutes a caller was willing to wait; only the harness's own hook timeout
/// stood between that and a frozen fleet). Two seconds is generous for a LAN
/// round-trip and keeps the worst case (two queries + one exposure check)
/// inside the harness's kill window — past it, the projection fails OPEN,
/// loudly, like every other gap on this path.
const HTTP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// POST a SPARQL query to quipu's `/query`, returning the raw body.
fn query(endpoint: &str, sparql: &str) -> Result<String> {
    let url = format!("{}/query", endpoint.trim_end_matches('/'));
    let body = serde_json::json!({ "query": sparql }).to_string();
    let resp = ureq::post(&url)
        .timeout(HTTP_TIMEOUT)
        .set("Content-Type", "application/json")
        .set("Accept", "application/sparql-results+json")
        .send_string(&body)
        .map_err(|e| Error::Projection(format!("POST {url} failed: {e}")))?;
    resp.into_string()
        .map_err(|e| Error::Projection(format!("could not read /query response: {e}")))
}

/// Decode a W3C `application/sparql-results+json` body (the result of
/// [`POLICY_QUERY`]) into projected policies.
///
/// Pure and testable without a live quipu. A row missing a required binding
/// (`language`/`query`/`pattern`/`matchType`) is a malformed projection and is an
/// [`Error::Projection`] — never silently dropped, so a broken sync cannot look
/// like "quipu has no policies".
pub fn decode_policies(sparql_json: &str) -> Result<Vec<ProjectedPolicy>> {
    let value: serde_json::Value = serde_json::from_str(sparql_json)
        .map_err(|e| Error::Projection(format!("results are not JSON: {e}")))?;
    let bindings = value
        .get("results")
        .and_then(|r| r.get("bindings"))
        .and_then(|b| b.as_array())
        .ok_or_else(|| Error::Projection("results have no `results.bindings` array".to_string()))?;

    let mut out = Vec::with_capacity(bindings.len());
    for (i, binding) in bindings.iter().enumerate() {
        let required = |key: &str| -> Result<String> {
            binding
                .get(key)
                .and_then(|v| v.get("value"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .ok_or_else(|| {
                    Error::Projection(format!("row {i}: missing required binding `{key}`"))
                })
        };
        let optional = |key: &str| -> Option<String> {
            binding
                .get(key)
                .and_then(|v| v.get("value"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
        };

        let match_type = match required("matchType")?.as_str() {
            "must-match" => MatchType::MustMatch,
            "must-not-match" => MatchType::MustNotMatch,
            "must-exist" => MatchType::MustExist,
            other => {
                return Err(Error::Projection(format!(
                    "row {i}: unknown matchType `{other}`"
                )))
            }
        };
        let language = required("language")?;
        let query = required("query")?;
        let pattern = required("pattern")?;
        // A policy with no label still needs a stable name for its verdicts.
        let name = optional("name").unwrap_or_else(|| format!("quipu-policy-{i}"));
        let effect = optional("effect").unwrap_or_else(|| "warn".to_string());

        out.push(ProjectedPolicy {
            rule: Rule {
                name,
                language,
                query,
                gate: optional("gate"),
                match_type,
                pattern,
                applies_to: Vec::new(),
                message: None,
            },
            effect,
        });
    }
    Ok(out)
}

/// How exposed is the repo an edit lands in? Three-valued BY DESIGN (the
/// mqnl seam): collapsing "not in the graph" into either answer is the bug.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepoExposure {
    /// The graph says this repo has a public remote: block-tier rules block.
    Public,
    /// The graph knows this repo and it has no public remote: block-tier
    /// rules DOWNGRADE to warnings — the token is not leaking anywhere, but
    /// saying so keeps the habit honest.
    Internal,
    /// The graph does not know this repo (or could not be asked). Warn AND SAY
    /// SO — never block on a guess, never stay silent on ignorance. Carries
    /// the reason so the verdict can explain itself.
    Unknown(String),
}

/// Ask quipu whether `repo` (by label) is public, via the governed policy's
/// own `/policy/check` — the same signed-verdict seam every other consumer of
/// rule #1 uses, so hank and the pre-push gate can never disagree about what
/// "public" means. NEVER errors: any failure IS the `Unknown` answer, with the
/// reason carried.
///
/// `outcome` mapping (quipu's three-valued contract):
///   satisfied   -> the repo has a public remote        -> Public
///   unsatisfied -> known repo, no public remote        -> Internal
///   unknown     -> the evidence probe found no repo    -> Unknown
pub fn fetch_repo_exposure(endpoint: &str, repo: &str) -> RepoExposure {
    let url = format!("{}/policy/check", endpoint.trim_end_matches('/'));
    let target = format!("http://aegis.gastown.local/ontology/repo_{repo}");
    let body = serde_json::json!({ "policy": EXPOSURE_POLICY_IRI, "target": target }).to_string();
    let resp = match ureq::post(&url)
        .timeout(HTTP_TIMEOUT)
        .set("Content-Type", "application/json")
        .send_string(&body)
    {
        Ok(r) => r,
        Err(e) => return RepoExposure::Unknown(format!("POST {url} failed: {e}")),
    };
    let text = match resp.into_string() {
        Ok(t) => t,
        Err(e) => return RepoExposure::Unknown(format!("unreadable /policy/check reply: {e}")),
    };
    let value: serde_json::Value = match serde_json::from_str(&text) {
        Ok(v) => v,
        Err(e) => return RepoExposure::Unknown(format!("/policy/check reply is not JSON: {e}")),
    };
    match value.get("outcome").and_then(|o| o.as_str()) {
        Some("satisfied") => RepoExposure::Public,
        Some("unsatisfied") => RepoExposure::Internal,
        Some("unknown") | None => RepoExposure::Unknown(format!(
            "repo `{repo}` is not in the graph (no `repo_{repo}` entity with remote facts)"
        )),
        Some(other) => RepoExposure::Unknown(format!("unrecognised outcome `{other}`")),
    }
}

/// A violation of a projected policy: the model-facing message plus whether the
/// governed `effect` blocks the edit (as opposed to merely advising).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectedViolation {
    /// The rule's model-facing message.
    pub message: String,
    /// Whether the governed effect is a blocking one (`deny` / `require-approval`
    /// / `escalate`) rather than advisory (`warn` / `record` / `allow`).
    pub blocking: bool,
}

/// Whether a governed `effect` blocks an edit. Unknown effects are treated as
/// blocking — the conservative direction for a governed decision Hank does not
/// recognise.
#[must_use]
pub fn effect_blocks(effect: &str) -> bool {
    !matches!(effect, "warn" | "record" | "allow")
}

/// Evaluate every projected policy against the introduced text, tagging each
/// violation with whether its governed effect blocks. The rule engine is the same
/// one local config uses — congruence means a projected policy is just a [`Rule`].
#[must_use]
pub fn evaluate_projected(
    policies: &[ProjectedPolicy],
    source: &str,
    language: &str,
    rel: &str,
) -> Vec<ProjectedViolation> {
    let mut out = Vec::new();
    for policy in policies {
        let blocking = effect_blocks(&policy.effect);
        for violation in
            crate::rules::evaluate(std::slice::from_ref(&policy.rule), source, language, rel)
        {
            out.push(ProjectedViolation {
                message: violation.message,
                blocking,
            });
        }
    }
    out
}

/// A hot, one-directional cache of quipu's structural policies, with the sync
/// state every projected verdict must declare.
///
/// [`Freshness::Fresh`] after a successful refresh; [`Freshness::Stale`] when a
/// refresh failed (the last-known policies are retained, but a verdict computed
/// against them is honestly stale) or before the first refresh.
#[derive(Debug, Clone)]
pub struct ProjectionRegistry {
    /// The quipu base URL (e.g. `http://localhost:8080`); `/query` is appended.
    endpoint: String,
    /// Last-known projected policies.
    policies: Vec<ProjectedPolicy>,
    /// Last-known governed text rules (aegis-mqnl catalogue).
    text_rules: Vec<TextRule>,
    /// Whether the projected sets reflect a successful, current sync.
    freshness: Freshness,
}

impl ProjectionRegistry {
    /// A registry pointed at `endpoint`, not yet synced — so it starts
    /// [`Freshness::Stale`] with no policies, never a fresh-looking empty set.
    #[must_use]
    pub fn new(endpoint: &str) -> Self {
        Self {
            endpoint: endpoint.to_string(),
            policies: Vec::new(),
            text_rules: Vec::new(),
            freshness: Freshness::Stale,
        }
    }

    /// The governed text rules and how current they are — same freshness
    /// contract as [`Self::policies`].
    #[must_use]
    pub fn text_rules(&self) -> &[TextRule] {
        &self.text_rules
    }

    /// The current policies and how current they are. A caller threads
    /// [`Self::freshness`] into the verdict so a stale projection is never served
    /// as fresh.
    #[must_use]
    pub fn policies(&self) -> &[ProjectedPolicy] {
        &self.policies
    }

    /// The cache's sync state.
    #[must_use]
    pub fn freshness(&self) -> Freshness {
        self.freshness
    }

    /// Refresh from quipu. On success, replaces the policies and marks the cache
    /// [`Freshness::Fresh`]; on failure, KEEPS the last-known policies but marks
    /// them [`Freshness::Stale`] and returns the error, so a caller can both keep
    /// enforcing (fail-open on the network, not on the policy) and report the
    /// staleness.
    pub fn refresh(&mut self) -> Result<()> {
        // BOTH catalogues or neither: a refresh that replaced the structural
        // policies but silently kept stale text rules would let the two planes
        // disagree about which sync they reflect — one freshness, one sync.
        match (
            fetch_policies(&self.endpoint),
            fetch_text_rules(&self.endpoint),
        ) {
            (Ok(policies), Ok(text_rules)) => {
                self.policies = policies;
                self.text_rules = text_rules;
                self.freshness = Freshness::Fresh;
                Ok(())
            }
            (Err(e), _) | (_, Err(e)) => {
                self.freshness = Freshness::Stale;
                Err(e)
            }
        }
    }

    /// Install decoded policies directly (test/daemon seam), marking the cache
    /// fresh — refresh over HTTP is [`Self::refresh`].
    pub fn set_policies(&mut self, policies: Vec<ProjectedPolicy>) {
        self.policies = policies;
        self.freshness = Freshness::Fresh;
    }

    /// Install decoded text rules directly (test/daemon seam).
    pub fn set_text_rules(&mut self, text_rules: Vec<TextRule>) {
        self.text_rules = text_rules;
        self.freshness = Freshness::Fresh;
    }
}

/// Fetch and decode quipu's structural policies over HTTP.
///
/// Mirrors `promote::write_knot`: a blocking `POST` to quipu's `/query`, asking
/// for the W3C-standard `application/sparql-results+json` shape so the decode is
/// version-stable.
pub fn fetch_policies(endpoint: &str) -> Result<Vec<ProjectedPolicy>> {
    decode_policies(&query(endpoint, POLICY_QUERY)?)
}

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