sprawling-kernel 0.0.9

Every decision of a sprawling city - addresses, events, gates, plans and errors - with nothing that touches a disk.
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright (c) 2026 2youg1 and the sprawling contributors

//! Locator: the one grammar for referring to content across events and
//! sessions. The part `crates/kernel/spec/Locator.lean` specifies this
//! module. Two schemes only:
//!
//! `cas:b3-<hex64>[#(L|B)<a>-<b>]` | `file:<address>@<hex40>[#(L|B)<a>-<b>]`
//!
//! Invariants owned here:
//! - fail-closed: whatever is not exactly the grammar is `E_LOCATOR_INVALID`;
//!   unknown schemes and unknown algorithm tags are errors, never fallbacks.
//! - canonical echo: `parse` additionally requires `Display(parsed) == raw`,
//!   which closes every non-canonical spelling (uppercase hex, leading
//!   zeros, `+` signs) with one rule.
//! - `secret:` never parses here: SecretRef has a separate parser by
//!   design, so a read path can never redeem a credential.
//! - range semantics: `L` is 1-based closed (editor precedent), `B` is
//!   0-based closed (HTTP Range precedent); `from <= to` always.
//!
//! [`B3Hash`] lives here because `b3-` is part of this grammar; the event
//! chain and CAS reuse the same type (one hash function library-wide).

use serde::{Deserialize, Serialize};

use crate::address::Address;
use crate::error::{AxCode, AxError};

/// BLAKE3 digest, 32 bytes; displayed as 64 lowercase hex digits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct B3Hash([u8; 32]);

impl B3Hash {
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        B3Hash(bytes)
    }

    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// The library-wide content-hash producer. Every non-chain hash (prefix
    /// segment hashes, stall fingerprints) comes through here so blake3 has
    /// exactly one home outside `chain_hash`.
    pub fn digest(bytes: &[u8]) -> Self {
        B3Hash(*blake3::hash(bytes).as_bytes())
    }
}

impl std::fmt::Display for B3Hash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write_hex(f, &self.0)
    }
}

impl Serialize for B3Hash {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        write_digest(self, &self.0, serializer)
    }
}

impl<'de> Deserialize<'de> for B3Hash {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        read_digest(deserializer).map(B3Hash)
    }
}

/// Git object id, 40 lowercase hex digits (SHA-1 repositories; other
/// lengths are rejected; SHA-256 repositories are not accepted).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GitOid([u8; 20]);

impl GitOid {
    pub fn from_bytes(bytes: [u8; 20]) -> Self {
        GitOid(bytes)
    }

    /// The hex spelling, read back.
    ///
    /// Public because a checkpoint identity travels as a string in more
    /// than one direction: the wire deserialises one, and a client that
    /// was shown a checkpoint in a sentence has to turn it back into an
    /// oid to act on it. Without this the caller decodes its own hex,
    /// which is a second definition of what an oid looks like - the exact
    /// thing the note on `Deserialize` below says stays here.
    ///
    /// `None` on anything that is not exactly forty lowercase hex digits:
    /// a wrong length is a refusal, never a padded guess.
    #[must_use]
    pub fn parse(raw: &str) -> Option<Self> {
        decode_hex_fixed::<20>(raw).map(GitOid)
    }
}

impl std::fmt::Display for GitOid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write_hex(f, &self.0)
    }
}

impl Serialize for GitOid {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        write_digest(self, &self.0, serializer)
    }
}

impl<'de> Deserialize<'de> for GitOid {
    /// The shape authority stays here, so the wire (`wire::frames`) has no
    /// second definition of what an oid looks like.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        read_digest(deserializer).map(GitOid)
    }
}

/// A digest as its format wants it (`crates/kernel/spec/Locator.lean` §8-84): the hex spelling
/// wherever a person or a frame reads it, the bytes themselves in a
/// binary format, which only this binary reads back (a snapshot).
fn write_digest<const N: usize, S: serde::Serializer>(
    spelled: &impl std::fmt::Display,
    bytes: &[u8; N],
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    [u8; N]: Serialize,
{
    if serializer.is_human_readable() {
        serializer.collect_str(spelled)
    } else {
        bytes.serialize(serializer)
    }
}

/// What [`write_digest`] wrote. A human-readable format is read through
/// the one hex spelling, and a wrong length is a refusal rather than a
/// padded guess.
fn read_digest<'de, const N: usize, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<[u8; N], D::Error>
where
    [u8; N]: Deserialize<'de>,
{
    if !deserializer.is_human_readable() {
        return <[u8; N]>::deserialize(deserializer);
    }
    let raw = String::deserialize(deserializer)?;
    decode_hex_fixed::<N>(&raw).ok_or_else(|| {
        serde::de::Error::custom(format_args!(
            "expected exactly {} lowercase hex digits",
            N.saturating_mul(2)
        ))
    })
}

/// Sub-content range. `Lines` is 1-based closed; `Bytes` is 0-based closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Range {
    Lines { from: u64, to: u64 },
    Bytes { from: u64, to: u64 },
}

impl Range {
    /// 1-based closed line range; rejects `from == 0` and `from > to`.
    pub fn lines(from: u64, to: u64) -> Result<Self, AxError> {
        if from == 0 || from > to {
            return Err(range_error("lines", from, to));
        }
        Ok(Range::Lines { from, to })
    }

    /// 0-based closed byte range; rejects `from > to`.
    pub fn bytes(from: u64, to: u64) -> Result<Self, AxError> {
        if from > to {
            return Err(range_error("bytes", from, to));
        }
        Ok(Range::Bytes { from, to })
    }
}

fn range_error(unit: &str, from: u64, to: u64) -> AxError {
    AxError::failure(
        AxCode::InvalidArgs,
        "construct range",
        format!("{unit} {from}-{to}"),
    )
    .with_recovery("require from <= to; line ranges start at 1, byte ranges at 0")
}

impl std::fmt::Display for Range {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Range::Lines { from, to } => write!(f, "L{from}-{to}"),
            Range::Bytes { from, to } => write!(f, "B{from}-{to}"),
        }
    }
}

/// The two-scheme reference grammar.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Locator {
    Cas {
        hash: B3Hash,
        range: Option<Range>,
    },
    File {
        address: Address,
        oid: GitOid,
        range: Option<Range>,
    },
}

impl Locator {
    /// The whole stored object behind `hash`. Infallible because a
    /// `B3Hash` is already a digest the grammar accepts, so a caller that
    /// holds one never spells the locator as text and parses it back.
    #[must_use]
    pub const fn cas(hash: B3Hash) -> Self {
        Locator::Cas { hash, range: None }
    }

    /// Fail-closed parser: exact grammar or `E_LOCATOR_INVALID`.
    pub fn parse(raw: &str) -> Result<Self, AxError> {
        let parsed = Locator::parse_inner(raw)?;
        // Canonical echo: one rule closes every non-canonical spelling.
        let echo = parsed.to_string();
        if echo != raw {
            return Err(invalid(
                raw,
                format!("non-canonical spelling; use `{echo}`"),
            ));
        }
        Ok(parsed)
    }

    fn parse_inner(raw: &str) -> Result<Self, AxError> {
        if let Some(rest) = raw.strip_prefix("cas:") {
            let (body, range) = split_range(raw, rest)?;
            let hex = body.strip_prefix("b3-").ok_or_else(|| {
                invalid(
                    raw,
                    "unknown or missing algorithm tag; the only tag is `b3-`",
                )
            })?;
            let hash = decode_hex_fixed::<32>(hex)
                .map(B3Hash)
                .ok_or_else(|| invalid(raw, "hash must be exactly 64 lowercase hex digits"))?;
            return Ok(Locator::Cas { hash, range });
        }
        if let Some(rest) = raw.strip_prefix("file:") {
            let (body, range) = split_range(raw, rest)?;
            let (addr_raw, oid_raw) = body
                .rsplit_once('@')
                .ok_or_else(|| invalid(raw, "file locator needs `<address>@<git-oid>`"))?;
            let address = Address::parse(addr_raw)
                .map_err(|_| invalid(raw, "address part violates the address grammar"))?;
            let oid = GitOid::parse(oid_raw)
                .ok_or_else(|| invalid(raw, "git oid must be exactly 40 lowercase hex digits"))?;
            return Ok(Locator::File {
                address,
                oid,
                range,
            });
        }
        if raw.starts_with("secret:") {
            return Err(invalid(
                raw,
                "SecretRef never enters the locator grammar (separate parser by design)",
            ));
        }
        Err(invalid(
            raw,
            "unknown scheme; only `cas:` and `file:` exist",
        ))
    }
}

impl std::fmt::Display for Locator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Locator::Cas { hash, range } => {
                write!(f, "cas:b3-{hash}")?;
                write_range(f, range)
            }
            Locator::File {
                address,
                oid,
                range,
            } => {
                write!(f, "file:{address}@{oid}")?;
                write_range(f, range)
            }
        }
    }
}

impl Serialize for Locator {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Locator {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = String::deserialize(deserializer)?;
        Locator::parse(&raw).map_err(serde::de::Error::custom)
    }
}

fn invalid(raw: &str, violation: impl Into<String>) -> AxError {
    AxError::failure(AxCode::LocatorInvalid, "parse locator", raw).with_recovery(violation.into())
}

/// Splits an optional `#(L|B)<a>-<b>` suffix off `rest`; `raw` only feeds
/// error context.
fn split_range(raw: &str, rest: &str) -> Result<(String, Option<Range>), AxError> {
    match rest.split_once('#') {
        None => Ok((rest.to_owned(), None)),
        Some((body, fragment)) => {
            let range = parse_range(raw, fragment)?;
            Ok((body.to_owned(), Some(range)))
        }
    }
}

fn parse_range(raw: &str, fragment: &str) -> Result<Range, AxError> {
    let mut chars = fragment.chars();
    let unit = chars
        .next()
        .ok_or_else(|| invalid(raw, "empty range fragment"))?;
    let body: &str = chars.as_str();
    let (from_raw, to_raw) = body
        .split_once('-')
        .ok_or_else(|| invalid(raw, "range needs `<from>-<to>`"))?;
    let from = parse_canonical_u64(raw, from_raw)?;
    let to = parse_canonical_u64(raw, to_raw)?;
    let range = match unit {
        'L' => Range::lines(from, to),
        'B' => Range::bytes(from, to),
        _ => {
            return Err(invalid(
                raw,
                "range unit must be `L` (lines) or `B` (bytes)",
            ));
        }
    };
    range.map_err(|_| invalid(raw, "range bounds are out of order or out of base"))
}

/// Digits only, no leading zeros (except "0" itself), no signs.
fn parse_canonical_u64(raw: &str, digits: &str) -> Result<u64, AxError> {
    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
        return Err(invalid(raw, "range bound must be decimal digits"));
    }
    if digits.len() > 1 && digits.starts_with('0') {
        return Err(invalid(raw, "range bound must not carry leading zeros"));
    }
    digits
        .parse::<u64>()
        .map_err(|_| invalid(raw, "range bound exceeds u64"))
}

pub(crate) fn write_hex(f: &mut std::fmt::Formatter<'_>, bytes: &[u8]) -> std::fmt::Result {
    for b in bytes {
        write!(f, "{b:02x}")?;
    }
    Ok(())
}

fn write_range(f: &mut std::fmt::Formatter<'_>, range: &Option<Range>) -> std::fmt::Result {
    match range {
        Some(r) => write!(f, "#{r}"),
        None => Ok(()),
    }
}

/// Strict lowercase hex into a fixed-width array; `None` on any deviation.
pub(crate) fn decode_hex_fixed<const N: usize>(raw: &str) -> Option<[u8; N]> {
    if raw.len() != N.checked_mul(2)? {
        return None;
    }
    let mut out = Vec::with_capacity(N);
    let mut bytes = raw.bytes();
    while let Some(hi) = bytes.next() {
        let lo = bytes.next()?;
        let value = nibble(hi)?.checked_mul(16)?.checked_add(nibble(lo)?)?;
        out.push(value);
    }
    <[u8; N]>::try_from(out.as_slice()).ok()
}

/// Lowercase-only nibble; uppercase is non-canonical and refused.
fn nibble(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => c.checked_sub(b'0'),
        b'a'..=b'f' => c.checked_sub(b'a')?.checked_add(10),
        _ => None,
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::wildcard_enum_match_arm,
    clippy::let_underscore_must_use,
    clippy::let_underscore_untyped,
    reason = "test code"
)]
mod tests;