okf 0.2.1

A pure-Rust, zero-dependency implementation of the Open Knowledge Format (OKF) v0.2: parser, model, validator, provenance/trust/attestation families, link graph, and index/log tooling.
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
//! Markdown link extraction, classification, and path-valued fields (§6).
//!
//! OKF relationships are expressed as ordinary markdown links, so this module
//! provides a small, dependency-free scanner for inline `[text](dest)` links
//! plus the link-classification rules from §6.1 (absolute bundle-relative vs.
//! relative vs. external). It ignores links inside fenced code blocks and
//! inline code spans, which are content rather than relationships.
//!
//! §6.2 extends the same path grammar to *frontmatter* fields (`resource`,
//! `sources[].resource`, `computation`, `executor.resource`, and
//! `attester.resource`), which are resolved by
//! [`field_path_candidates`] rather than by [`Link::resolve`].
//!
//! It also still parses the v0.1 body `# Citations` list
//! ([`extract_citations`]), which v0.2 supersedes with `sources` (§13.1) but
//! which consumers MAY keep reading for legacy documents.

use crate::concept_id::ConceptId;

/// How a link target is interpreted under §6.1.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkKind {
    /// Begins with `/`: resolved relative to the bundle root (recommended).
    Absolute,
    /// A relative path such as `./other.md`.
    Relative,
    /// An external URI (`https://…`, `mailto:…`, …).
    External,
    /// A pure in-document anchor (`#section`).
    Anchor,
    /// Anything else (e.g. an empty target).
    Other,
}

/// A markdown link found in a concept body.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Link {
    /// The link text (between `[` and `]`).
    pub text: String,
    /// The raw destination (between `(` and `)`), with any title removed.
    pub target: String,
    /// The classification of [`Link::target`].
    pub kind: LinkKind,
}

impl Link {
    /// Classifies a raw target string per §6.
    #[must_use]
    pub fn classify(target: &str) -> LinkKind {
        let t = target.trim();
        if t.is_empty() {
            LinkKind::Other
        } else if t.starts_with('#') {
            LinkKind::Anchor
        } else if is_external(t) {
            LinkKind::External
        } else if t.starts_with('/') {
            LinkKind::Absolute
        } else {
            LinkKind::Relative
        }
    }

    /// Resolves an internal link to the concept id it points at, given the id
    /// of the concept the link appears in.
    ///
    /// Returns `None` for external links, anchors, links to directories
    /// (targets ending in `/`), or targets that cannot form a valid concept id.
    /// The result is *not* guaranteed to exist in the bundle: broken links are
    /// permitted by the spec (§6.1).
    ///
    /// Where a target is percent-encoded this returns the literal reading; use
    /// [`Link::resolve_all`] to also consider the decoded one.
    #[must_use]
    pub fn resolve(&self, source: &ConceptId) -> Option<ConceptId> {
        self.resolve_all(source).into_iter().next()
    }

    /// Every concept id this link may denote, most likely first.
    ///
    /// A markdown destination is a URL, so a concept whose filename contains a
    /// space is normally linked as `/tables/my%20notes.md`. Decoding is offered
    /// as a second candidate rather than applied outright, so that a file
    /// genuinely named `my%20notes.md` still resolves by its literal spelling.
    /// Callers should prefer the first candidate that exists in the bundle.
    #[must_use]
    pub fn resolve_all(&self, source: &ConceptId) -> Vec<ConceptId> {
        let mut out = Vec::new();
        let mut push = |target: &str| {
            let id = match self.kind {
                LinkKind::Absolute => resolve_absolute(target),
                LinkKind::Relative => resolve_relative(target, source),
                _ => None,
            };
            if let Some(id) = id {
                if !out.contains(&id) {
                    out.push(id);
                }
            }
        };
        push(&self.target);
        if let Some(decoded) = percent_decode(&self.target) {
            push(&decoded);
        }
        out
    }
}

/// Percent-decodes a link destination, or `None` if there is nothing to decode
/// or the result is not valid UTF-8.
fn percent_decode(s: &str) -> Option<String> {
    if !s.contains('%') {
        return None;
    }
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut decoded_any = false;
    let mut i = 0;
    while i < bytes.len() {
        let escape = (bytes[i] == b'%' && i + 3 <= bytes.len())
            .then(|| &bytes[i + 1..i + 3])
            .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit));
        if let Some(hex) = escape {
            let hex = std::str::from_utf8(hex).ok()?;
            out.push(u8::from_str_radix(hex, 16).ok()?);
            decoded_any = true;
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    if !decoded_any {
        return None;
    }
    String::from_utf8(out).ok()
}

/// A numbered entry under a legacy v0.1 `# Citations` heading.
///
/// v0.2 supersedes the body citations list with the `sources` frontmatter field
/// and footnote attribution (§5.1); consumers MAY still parse this form for
/// v0.1 documents (§13.1).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Citation {
    /// The citation number (the `n` in `[n]`).
    pub number: u32,
    /// The link text, if the entry is a markdown link.
    pub text: Option<String>,
    /// The cited URL/target, if present.
    pub target: Option<String>,
    /// The full raw text of the entry after the `[n]` marker.
    pub raw: String,
}

/// Whether a target names something outside the bundle.
///
/// Any RFC-3986 scheme prefix counts, not just `http`. §4.1 calls `resource`
/// "a URI that uniquely identifies the underlying asset", and producers do use
/// non-http schemes for warehouse assets (`bigquery:project.dataset.table`);
/// treating those as relative paths would have a consumer looking for a file
/// that was never meant to exist.
fn is_external(t: &str) -> bool {
    t.starts_with("//") /* protocol-relative URL */ || has_uri_scheme(t)
}

/// Matches `scheme:` where scheme is `ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`.
fn has_uri_scheme(t: &str) -> bool {
    let Some((scheme, _)) = t.split_once(':') else {
        return false;
    };
    let mut chars = scheme.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}

fn strip_anchor(target: &str) -> &str {
    target.find('#').map_or(target, |i| &target[..i])
}

fn resolve_absolute(target: &str) -> Option<ConceptId> {
    let t = strip_anchor(target);
    if t.ends_with('/') {
        return None; // directory link
    }
    // Normalize `.`/`..` segments relative to the bundle root, consistent with
    // relative-link resolution.
    strip_md(normalize_segments(t, &[])).and_then(|segs| ConceptId::new(segs).ok())
}

fn resolve_relative(target: &str, source: &ConceptId) -> Option<ConceptId> {
    let t = strip_anchor(target);
    if t.is_empty() || t.ends_with('/') {
        return None;
    }
    // Start from the source concept's directory.
    let base = source
        .parent()
        .map(|p| p.segments().to_vec())
        .unwrap_or_default();
    strip_md(normalize_segments(t, &base)).and_then(|segs| ConceptId::new(segs).ok())
}

/// Resolves `.`/`..`/empty components in a `/`-separated path against `base`.
fn normalize_segments(path: &str, base: &[String]) -> Vec<String> {
    let mut segs = base.to_vec();
    for comp in path.split('/') {
        match comp {
            "" | "." => {}
            ".." => {
                segs.pop();
            }
            other => segs.push(other.to_string()),
        }
    }
    segs
}

/// Drops a trailing `.md` from the last segment, or `None` if there are none.
fn strip_md(mut segs: Vec<String>) -> Option<Vec<String>> {
    let last = segs.last_mut()?;
    if let Some(s) = last.strip_suffix(".md") {
        *last = s.to_string();
    }
    Some(segs)
}

/// Normalizes a **path-valued frontmatter field** (§6.2) into the
/// bundle-relative paths it might name, most likely first.
///
/// `resource`, `sources[].resource`, `computation`, `executor.resource`, and
/// `attester.resource` all accept an absolute URL, a bundle-relative path
/// beginning with `/`, or a relative path. URLs (and anchors) yield an empty
/// vector, since there is nothing in the bundle to resolve.
///
/// A relative path yields **two** candidates, because the spec uses both
/// readings: §6.2 calls `../computations/revenue.md` relative to the concept,
/// while §6.3's `references/` convention is written from the bundle root
/// (`executor.resource: references/skills/run-on-bq.md` on a concept that lives
/// in `computations/`). Callers should take the first candidate that exists.
///
/// Unlike [`Link::resolve`], the returned paths keep their file extension:
/// these fields routinely name non-markdown files such as
/// `references/attesters/revenue.py`.
#[must_use]
pub fn field_path_candidates(raw: &str, from: &ConceptId) -> Vec<String> {
    let target = raw.trim();
    match Link::classify(target) {
        LinkKind::Absolute => {
            vec![normalize_segments(strip_anchor(target), &[]).join("/")]
        }
        LinkKind::Relative => {
            let base = from
                .parent()
                .map(|p| p.segments().to_vec())
                .unwrap_or_default();
            let stripped = strip_anchor(target);
            let mut out = vec![normalize_segments(stripped, &base).join("/")];
            let from_root = normalize_segments(stripped, &[]).join("/");
            if !out.contains(&from_root) {
                out.push(from_root);
            }
            out.retain(|p| !p.is_empty());
            out
        }
        _ => Vec::new(),
    }
}

/// The concept id a bundle-relative markdown path denotes, or `None` if the
/// path is not a `.md` file or is not a valid id (§2).
#[must_use]
pub fn concept_id_for_path(path: &str) -> Option<ConceptId> {
    let stem = path.strip_suffix(".md")?;
    ConceptId::parse(stem).ok()
}

/// Extracts all inline markdown links from a body, skipping fenced code blocks
/// and inline code spans.
#[must_use]
pub fn extract_links(body: &str) -> Vec<Link> {
    let mut links = Vec::new();
    for (_, line) in code_free_lines(body) {
        scan_line_links(&line, &mut links);
    }
    links
}

/// Returns the body's lines, as `(1-based line number, text)`, with fenced
/// code blocks removed and inline code spans blanked out.
///
/// Shared with [`footnotes`](crate::footnotes), which needs the same
/// "prose only" view of the body to find attribution markers (§5.1).
pub(crate) fn code_free_lines(body: &str) -> Vec<(usize, String)> {
    let mut out = Vec::new();
    let mut fence: Option<char> = None;
    for (i, line) in body.lines().enumerate() {
        let trimmed = line.trim_start();
        if let Some(f) = fence {
            // Inside a fence; look for the closing marker.
            if trimmed.starts_with(&f.to_string().repeat(3)) {
                fence = None;
            }
            continue;
        }
        if trimmed.starts_with("```") {
            fence = Some('`');
            continue;
        }
        if trimmed.starts_with("~~~") {
            fence = Some('~');
            continue;
        }
        out.push((i + 1, blank_inline_code(line)));
    }
    out
}

/// Replaces inline code spans (backtick-delimited) with spaces so links inside
/// them are not extracted.
fn blank_inline_code(line: &str) -> String {
    let mut out = String::with_capacity(line.len());
    let mut in_code = false;
    for c in line.chars() {
        if c == '`' {
            in_code = !in_code;
            out.push(' ');
        } else if in_code {
            out.push(' ');
        } else {
            out.push(c);
        }
    }
    out
}

/// Scans a single (code-free) line for `[text](dest)` links.
fn scan_line_links(line: &str, out: &mut Vec<Link>) {
    let chars: Vec<char> = line.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '[' {
            if let Some((text, dest, next)) = parse_inline_link(&chars, i) {
                let target = clean_destination(&dest);
                out.push(Link {
                    text,
                    kind: Link::classify(&target),
                    target,
                });
                i = next;
                continue;
            }
        }
        i += 1;
    }
}

/// Attempts to parse `[text](dest)` starting at `start` (the `[`). Returns the
/// text, destination, and index just past the closing `)`.
fn parse_inline_link(chars: &[char], start: usize) -> Option<(String, String, usize)> {
    // Match the link text up to a balanced `]`.
    let mut i = start + 1;
    let mut depth = 1;
    let text_start = i;
    while i < chars.len() {
        match chars[i] {
            '\\' => i += 1, // skip escaped char
            '[' => depth += 1,
            ']' => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            _ => {}
        }
        i += 1;
    }
    if depth != 0 || i >= chars.len() {
        return None;
    }
    let text: String = chars[text_start..i].iter().collect();
    // Next non-space char must be '('.
    let mut j = i + 1;
    if j >= chars.len() || chars[j] != '(' {
        return None;
    }
    j += 1;
    let dest_start = j;
    let mut paren = 1;
    while j < chars.len() {
        match chars[j] {
            '\\' => j += 1,
            '(' => paren += 1,
            ')' => {
                paren -= 1;
                if paren == 0 {
                    break;
                }
            }
            _ => {}
        }
        j += 1;
    }
    if paren != 0 || j >= chars.len() {
        return None;
    }
    let dest: String = chars[dest_start..j].iter().collect();
    Some((text, dest, j + 1))
}

/// Normalizes a raw link destination.
///
/// Unwraps the `CommonMark` `<...>` form, which is how a destination is allowed
/// to contain spaces, and otherwise removes an optional title suffix. A
/// bracketed destination is taken literally, since a space inside it is part of
/// the path rather than a separator before a title.
fn clean_destination(dest: &str) -> String {
    let d = dest.trim();
    if let Some(rest) = d.strip_prefix('<') {
        if let Some(end) = rest.find('>') {
            return rest[..end].to_string();
        }
    }
    strip_title(d)
}

/// Removes an optional `"title"` (or `'title'`) suffix from a link destination.
fn strip_title(dest: &str) -> String {
    let d = dest.trim();
    if let Some(idx) = d.find([' ', '\t']) {
        let (url, rest) = d.split_at(idx);
        let rest = rest.trim_start();
        if rest.starts_with('"') || rest.starts_with('\'') {
            return url.to_string();
        }
    }
    d.to_string()
}

/// Extracts numbered citation entries from the `# Citations` section (§8).
#[must_use]
pub fn extract_citations(body: &str) -> Vec<Citation> {
    let mut out = Vec::new();
    let mut in_section = false;
    for line in body.lines() {
        let trimmed = line.trim();
        if let Some(heading) = trimmed.strip_prefix('#') {
            let title = heading.trim_start_matches('#').trim();
            if in_section {
                // A new heading ends the citations section.
                break;
            }
            in_section = title.eq_ignore_ascii_case("citations");
            continue;
        }
        if !in_section || trimmed.is_empty() {
            continue;
        }
        if let Some(cit) = parse_citation_line(trimmed) {
            out.push(cit);
        }
    }
    out
}

/// Parses a single `[n] …` citation line.
fn parse_citation_line(line: &str) -> Option<Citation> {
    let rest = line.strip_prefix('[')?;
    let close = rest.find(']')?;
    let number: u32 = rest[..close].trim().parse().ok()?;
    let after = rest[close + 1..].trim().to_string();

    // If the remainder is itself a markdown link, capture its text and target.
    let mut text = None;
    let mut target = None;
    let chars: Vec<char> = after.chars().collect();
    if let Some(open) = chars.iter().position(|&c| c == '[') {
        if let Some((t, dest, _)) = parse_inline_link(&chars, open) {
            text = Some(t);
            target = Some(clean_destination(&dest));
        }
    }
    Some(Citation {
        number,
        text,
        target,
        raw: after,
    })
}