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
//! Phase-4 promotion: validate a Turtle projection in-process, then write it to
//! Quipu (#14 FR-20, #15 FR-19/21/22). Gated behind the `quipu` feature.
//!
//! THE ORDER IS THE CONTRACT. `export::to_turtle` produces the facts; this module
//! SHACL-validates them against the shipped shapes BEFORE any write, and refuses
//! the whole promotion on a single violation (all-or-nothing per commit, §6.3).
//! Validation is always whole-graph. The WRITE is chunked when the payload would
//! exceed Quipu's request-body limit (axum defaults to 2 MiB and the deployed
//! server sets no override — a 2.28 MB projection of the quipu repo itself came
//! back 413, aegis-hbiw): entity blocks are split across multiple `/knot` posts,
//! each under the limit, prefixes replicated. A chunked write is NOT atomic
//! across chunks — if chunk k fails, chunks 0..k are landed — but every IRI is
//! deterministic and `/knot` supersedes, so a re-run converges to the same graph
//! rather than duplicating. The failure message names exactly what landed.
//!
//! WHY IN-PROCESS VALIDATION, NOT QUIPU'S. Quipu exposes `/validate`, and it works.
//! But validating against the same server you are about to write to proves only
//! that the server agrees with itself. FR-20 wants hank to hold its own copy of the
//! shapes and check independently, so a shape drift between hank and Quipu is caught
//! at hank rather than discovered as bad data already in the graph. rudof_lib is
//! that independent checker; `scripts/check-code-shapes.sh` is the cross-check that
//! the two engines still agree.
//!
//! WHY `/knot` OVER HTTP, NOT THE `quipu` CRATE. FR-21 names three promotion
//! surfaces — `quipu_knot` (MCP) / `POST /knot` (REST) / `Store::transact`
//! (in-process). The REST surface needs no `quipu` crate dependency (still
//! rev-unpinned, Cargo.toml), and hank explicitly does NOT stand up its own triple
//! store (§14.4). So promotion is an HTTP POST of validated Turtle. `/knot` is
//! bitemporal: a re-promotion of the same facts supersedes rather than duplicating,
//! which is why re-running is idempotent BY TRIPLE COUNT, not by write count.

use std::io::Write;

use crate::errors::{Error, Result};

/// The code-edge SHACL shapes hank ships and validates against. Compiled in so a
/// promotion can never run against shapes that drift from the binary — the file on
/// disk is for humans and `check-code-shapes.sh`; THIS is what actually gates a
/// write.
pub const CODE_EDGE_SHAPES: &str = include_str!("../shapes/code-edges.ttl");

/// The outcome of validating a Turtle projection against the code shapes.
#[derive(Debug, Clone)]
pub struct Validation {
    /// Did the projection satisfy every shape?
    pub conforms: bool,
    /// Human-readable violation messages, empty iff `conforms`.
    pub violations: Vec<String>,
}

/// SHACL-validate `data_ttl` against `shapes_ttl`, in-process, via `rudof_lib`.
///
/// Returns the conformance verdict and, when it does not conform, the specific
/// violations. A parse failure of either input is itself a non-conformance we can
/// name, never a silent pass — an unparseable projection must not reach Quipu.
pub fn validate(data_ttl: &str, shapes_ttl: &str) -> Result<Validation> {
    use rudof_lib::formats::{DataFormat, InputSpec, ResultShaclValidationFormat, ShaclFormat};
    use rudof_lib::{Rudof, RudofConfig};

    let mut rudof = Rudof::new(RudofConfig::default());

    rudof
        .load_data()
        .with_data(&[InputSpec::str(data_ttl)])
        .with_data_format(&DataFormat::Turtle)
        .execute()
        .map_err(|e| Error::Promote(format!("promotion data is not valid Turtle: {e}")))?;

    rudof
        .load_shacl_shapes()
        .with_shacl_schema(&InputSpec::str(shapes_ttl))
        .with_shacl_schema_format(&ShaclFormat::Turtle)
        .execute()
        .map_err(|e| Error::Promote(format!("SHACL shapes did not load: {e}")))?;

    rudof
        .validate_shacl()
        .execute()
        .map_err(|e| Error::Promote(format!("SHACL validation failed to run: {e}")))?;

    // The report lives in rudof's private state; serialize it to Turtle and read
    // `sh:conforms` / `sh:resultMessage` out. This is the only exposed path to the
    // verdict — there is no public `conforms()` accessor on Rudof.
    let mut buf: Vec<u8> = Vec::new();
    rudof
        .serialize_shacl_validation_results(&mut buf)
        .with_result_shacl_validation_format(&ResultShaclValidationFormat::Turtle)
        .execute()
        .map_err(|e| Error::Promote(format!("could not read validation report: {e}")))?;
    let report = String::from_utf8_lossy(&buf);

    Ok(parse_report(&report))
}

/// Read `sh:conforms` and any `sh:resultMessage`s out of a SHACL report in Turtle.
fn parse_report(report: &str) -> Validation {
    let conforms = report.contains("sh:conforms true") || report.contains("sh:conforms  true");
    let mut violations = Vec::new();
    for line in report.lines() {
        let l = line.trim();
        if let Some(rest) = l.strip_prefix("sh:resultMessage") {
            // sh:resultMessage "MinCount(1) not satisfied" ;
            let msg = rest.trim().trim_end_matches(';').trim().trim_matches('"');
            if !msg.is_empty() {
                violations.push(msg.to_string());
            }
        }
    }
    // Belt and braces: a report that does not conform but whose messages we failed
    // to parse must still be non-empty, or a caller could read "conforms=false,
    // violations=[]" as "nothing wrong". A refusal must always carry a reason.
    if !conforms && violations.is_empty() {
        violations.push("SHACL validation reported non-conformance (see report)".to_string());
    }
    Validation {
        conforms,
        violations,
    }
}

/// The bearer token for Quipu write endpoints, if the environment carries one.
///
/// Quipu gates writes behind `Authorization: Bearer <token>` once its
/// `[quipu.server] auth_token` is set; reads stay open. `QUIPU_AUTH_TOKEN` is
/// the client-side half: set it and every promotion sends the bearer, leave it
/// unset against an open server and nothing changes. An empty value counts as
/// unset — `Bearer ` (no token) would be sent as a real-but-wrong credential
/// and turn a misconfigured env into a confusing 401.
fn quipu_auth_token() -> Option<String> {
    normalize_token(std::env::var("QUIPU_AUTH_TOKEN").ok()).or_else(token_from_file)
}

/// The token file — the half of distribution that reaches processes launched
/// BEFORE the token existed (an env var is captured at spawn; a file is read
/// per request). Env wins above as the per-invocation override. Path:
/// `QUIPU_AUTH_TOKEN_FILE`, else `~/.config/quipu/token`. Absent/unreadable
/// is `None`: no auth configured, the open-server default.
fn token_from_file() -> Option<String> {
    let path = std::env::var("QUIPU_AUTH_TOKEN_FILE")
        .ok()
        .filter(|p| !p.is_empty())
        .or_else(|| {
            std::env::var("HOME")
                .ok()
                .map(|h| format!("{h}/.config/quipu/token"))
        })?;
    normalize_token(
        std::fs::read_to_string(path)
            .ok()
            .map(|s| s.trim().to_string()),
    )
}

/// The pure half of [`quipu_auth_token`]: empty-or-absent collapses to `None`.
fn normalize_token(raw: Option<String>) -> Option<String> {
    raw.filter(|t| !t.is_empty())
}

/// Post validated Turtle to Quipu's `/knot`. Returns the number of triples the
/// transaction reports as present for these facts — the count that makes
/// idempotence checkable (a re-promotion returns the same count, not a larger one).
///
/// `endpoint` is the Quipu base URL (e.g. from `--to` / config); this appends
/// `/knot`. NEVER defaulted to a hardcoded host — a promotion that silently picks a
/// graph is how facts land in the wrong one.
pub fn write_knot(endpoint: &str, turtle: &str, source: &str) -> Result<KnotResult> {
    let url = format!("{}/knot", endpoint.trim_end_matches('/'));
    let auth = quipu_auth_token();
    // Provenance on every write (promotion tail item 4): quipu records actor +
    // source per transaction; an anonymous writer is unauditable, and hank was
    // the only anonymous one left.
    let body =
        serde_json::json!({ "turtle": turtle, "actor": "hank", "source": source }).to_string();

    // Quipu is known to flap (transient 503 "no available server", recovering in
    // seconds). Ride through TRANSIENT failures — 5xx and transport errors — with
    // a short backoff; a 4xx is a real answer and fails immediately. The
    // all-or-nothing guarantee is unaffected: every attempt is the same full
    // idempotent write, and exhausting retries still fails loud, never partial.
    const ATTEMPTS: u32 = 3;
    let mut resp = None;
    let mut last_err = String::new();
    for attempt in 1..=ATTEMPTS {
        let mut req = ureq::post(&url).set("Content-Type", "application/json");
        if let Some(token) = &auth {
            req = req.set("Authorization", &format!("Bearer {token}"));
        }
        match req.send_string(&body) {
            Ok(r) => {
                resp = Some(r);
                break;
            }
            Err(ureq::Error::Status(code, _)) if code < 500 => {
                return Err(Error::Promote(format!("POST {url} failed: status {code}")));
            }
            Err(e) => {
                last_err = e.to_string();
                if attempt < ATTEMPTS {
                    std::thread::sleep(std::time::Duration::from_secs(2 * u64::from(attempt)));
                }
            }
        }
    }
    let resp = resp.ok_or_else(|| {
        Error::Promote(format!(
            "POST {url} failed after {ATTEMPTS} attempts (transient errors retried): {last_err}"
        ))
    })?;

    let text = resp
        .into_string()
        .map_err(|e| Error::Promote(format!("could not read /knot response: {e}")))?;
    // Quipu can REFUSE the write server-side: its persistent shape registry,
    // when loaded, validates independently of hank's in-process gate, and a
    // shape the server holds that hank's copy lacks surfaces HERE as HTTP 200
    // with conforms:false (seen live: a stored symbolKind maxCount(1) refused
    // a projection hank's shapes accepted). That is a real refusal and must
    // read as one — not as a JSON parse error on a missing `count` field.
    if let Ok(refusal) = serde_json::from_str::<KnotRefusal>(&text) {
        if !refusal.conforms {
            let issues = refusal
                .issues
                .iter()
                .map(|i| format!("{} {} on {}", i.component, i.message, i.focus_node))
                .collect::<Vec<_>>()
                .join("; ");
            return Err(Error::Promote(format!(
                "quipu refused the write (server-side SHACL, {} violation(s)): {issues}. \
                 hank's own shapes ACCEPTED this projection — the two shape sets have \
                 drifted; reconcile shapes/code-edges.ttl with quipu's stored registry.",
                refusal.violations
            )));
        }
    }
    let parsed: KnotResult = serde_json::from_str(&text)
        .map_err(|e| Error::Promote(format!("unexpected /knot response {text:?}: {e}")))?;
    Ok(parsed)
}

/// Quipu's `/knot` refusal shape (HTTP 200, `conforms:false`).
#[derive(Debug, serde::Deserialize)]
struct KnotRefusal {
    conforms: bool,
    #[serde(default)]
    violations: u64,
    #[serde(default)]
    issues: Vec<KnotIssue>,
}

#[derive(Debug, serde::Deserialize)]
struct KnotIssue {
    #[serde(default)]
    component: String,
    #[serde(default)]
    message: String,
    #[serde(default)]
    focus_node: String,
}

/// Quipu `/knot` response. `conforms` here is Quipu's OWN field and is NOT the
/// validation gate — Quipu's persistent shape registry may be empty, in which case
/// it reports `conforms:true` for anything. hank's gate is [`validate`] above,
/// which ran before this. `count` is the load-bearing field for idempotence.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct KnotResult {
    /// Triples present for these facts after the write — the idempotence signal.
    pub count: u64,
    /// Quipu's monotonic transaction id, when returned.
    #[serde(default)]
    pub tx_id: Option<u64>,
}

/// Stay safely under axum's 2 MiB default body limit: the Turtle is JSON-string
/// encoded (quotes/newlines escape to two bytes) before it travels, so leave
/// headroom for that inflation plus the JSON envelope.
const CHUNK_LIMIT: usize = 1_500_000;

/// Split a Turtle document into chunks of whole statements, each chunk carrying
/// the prefix header. `to_turtle` separates entity blocks with blank lines and
/// never emits blank nodes, so a blank line is always a safe split point — but
/// the call/reference EDGE sections are contiguous single-line statements with
/// no blank lines between them (bobbin's edge section alone is ~6.9 MB), so an
/// oversized block is split further at statement boundaries: a line ending in
/// `.` completes a Turtle statement in this exporter's output.
///
/// Errors only if a single STATEMENT exceeds `limit` — that genuinely cannot be
/// split, and silently posting it would just 413 downstream.
fn chunk_turtle(turtle: &str, limit: usize) -> Result<Vec<String>> {
    if turtle.len() <= limit {
        return Ok(vec![turtle.to_string()]);
    }
    let mut blocks = turtle.split("\n\n");
    // The first "block" is the @prefix header `to_turtle` puts at the top.
    let header = blocks.next().unwrap_or_default();
    let mut chunks = Vec::new();
    let mut cur = String::from(header);

    // Append one statement-complete piece, starting a new chunk when full.
    let push_piece = |cur: &mut String, chunks: &mut Vec<String>, piece: &str| -> Result<()> {
        if header.len() + 2 + piece.len() > limit {
            return Err(Error::Promote(format!(
                "a single Turtle statement is {} bytes, over the {limit} byte chunk limit — cannot split below statement granularity",
                piece.len()
            )));
        }
        if cur.len() + 2 + piece.len() > limit {
            chunks.push(std::mem::replace(cur, String::from(header)));
        }
        cur.push_str("\n\n");
        cur.push_str(piece);
        Ok(())
    };

    for block in blocks {
        if block.trim().is_empty() {
            continue;
        }
        if header.len() + 2 + block.len() <= limit {
            push_piece(&mut cur, &mut chunks, block)?;
            continue;
        }
        // Oversized block: regroup its lines into statement-complete pieces
        // (a line ending in `.` closes a statement in to_turtle's output).
        let mut piece = String::new();
        for line in block.lines() {
            if !piece.is_empty() {
                piece.push('\n');
            }
            piece.push_str(line);
            if line.trim_end().ends_with('.') && header.len() + 2 + piece.len() > limit / 2 {
                push_piece(&mut cur, &mut chunks, &piece)?;
                piece.clear();
            }
        }
        if !piece.trim().is_empty() {
            push_piece(&mut cur, &mut chunks, &piece)?;
        }
    }
    if cur.len() > header.len() {
        chunks.push(cur);
    }
    Ok(chunks)
}

/// The aggregated result of a (possibly chunked) promotion write.
#[derive(Debug, Clone)]
pub struct WriteSummary {
    /// Sum of the per-chunk `count` fields — the idempotence signal (a re-run
    /// returns the same total, not a larger one).
    pub count: u64,
    /// Every transaction id Quipu returned, in write order.
    pub tx_ids: Vec<u64>,
    /// How many `/knot` posts the write took (1 = the classic single-post path).
    pub chunks: usize,
}

/// The full promotion: validate the WHOLE graph, then write iff it conforms —
/// in one `/knot` post when it fits, in idempotent chunks when it would 413.
/// On non-conformance it writes NOTHING and returns the violations.
pub fn promote(endpoint: &str, turtle: &str, source: &str) -> Result<Promotion> {
    let v = validate(turtle, CODE_EDGE_SHAPES)?;
    if !v.conforms {
        return Ok(Promotion::Refused(v.violations));
    }
    let chunks = chunk_turtle(turtle, CHUNK_LIMIT)?;
    let total = chunks.len();
    let mut summary = WriteSummary {
        count: 0,
        tx_ids: Vec::new(),
        chunks: total,
    };
    for (i, chunk) in chunks.iter().enumerate() {
        let knot = write_knot(endpoint, chunk, source).map_err(|e| {
            Error::Promote(format!(
                "chunk {}/{total} failed after {} chunk(s) landed — re-running is safe (deterministic IRIs supersede): {e}",
                i + 1,
                i
            ))
        })?;
        summary.count += knot.count;
        if let Some(t) = knot.tx_id {
            summary.tx_ids.push(t);
        }
    }
    Ok(Promotion::Wrote(summary))
}

/// The result of a full promotion: it either wrote, or refused whole.
#[derive(Debug)]
pub enum Promotion {
    /// Validated and written; carries the aggregated write result.
    Wrote(WriteSummary),
    /// Did not pass SHACL; carries the violations and wrote nothing.
    Refused(Vec<String>),
}

impl Promotion {
    /// Render for a human, and set the process exit intent: a refusal is exit-2
    /// (could-not-promote), never a silent success.
    pub fn report(&self, w: &mut impl Write) -> std::io::Result<bool> {
        match self {
            Promotion::Wrote(k) => {
                let txs = match k.tx_ids.as_slice() {
                    [] => String::new(),
                    [one] => format!(" (tx {one})"),
                    [first, .., last] => format!(" (tx {first}..{last})"),
                };
                let chunked = if k.chunks > 1 {
                    format!(" in {} chunks", k.chunks)
                } else {
                    String::new()
                };
                writeln!(w, "  promoted: {} triples present{txs}{chunked}", k.count)?;
                Ok(true)
            }
            Promotion::Refused(vs) => {
                writeln!(
                    w,
                    "  REFUSED — promotion did not pass SHACL, wrote nothing:"
                )?;
                for v in vs {
                    writeln!(w, "    - {v}")?;
                }
                Ok(false)
            }
        }
    }
}

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