okf-core 0.2.5

A pure-Rust implementation of the Open Knowledge Format (OKF) v0.2 specification: 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
//! Tests for OKF refactoring operations: move/rename, remove, split, and merge.

mod common;

use common::TempDir;
use okf_core::Bundle;
use okf_core::concept_id::ConceptId;
use okf_core::refactor::{
    MergeOptions, MoveOptions, RefactorError, RemoveOptions, SplitOptions, merge_concepts,
    move_concept, remove_concept, split_concept,
};

#[test]
fn test_move_concept_rewrites_incoming_and_rebases_outgoing() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "auth/token.md",
        "---\ntype: Concept\ntitle: Auth Token\n---\n\n# Auth Token\n\nSee [User Profile](../users/profile.md) for user details.\n",
    );
    tmp.write(
        "users/profile.md",
        "---\ntype: Concept\ntitle: User Profile\n---\n\n# User Profile\n\nUses [Auth Token](../auth/token.md) for authentication.\n",
    );
    tmp.write(
        "overview.md",
        "---\ntype: Concept\ntitle: Overview\n---\n\n# Overview\n\nCheck [Auth Token](auth/token.md#expiration) and [/auth/token.md](/auth/token.md).\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let from = ConceptId::parse("auth/token").unwrap();
    let to = ConceptId::parse("security/jwt/token").unwrap();

    let opts = MoveOptions::default();
    let report = move_concept(&bundle, &from, &to, &opts).unwrap();

    assert_eq!(report.rewritten_incoming_links, 3);
    assert_eq!(report.rebased_outgoing_links, 1);
    assert!(!tmp.path().join("auth/token.md").exists());
    assert!(tmp.path().join("security/jwt/token.md").exists());

    // Check moved file outgoing link
    let moved_content = tmp.read("security/jwt/token.md");
    assert!(
        moved_content.contains("[User Profile](../../users/profile.md)"),
        "Moved content was: {moved_content}"
    );

    // Check users/profile incoming link
    let users_content = tmp.read("users/profile.md");
    assert!(
        users_content.contains("[Auth Token](../security/jwt/token.md)"),
        "Users content was: {users_content}"
    );

    // Check overview incoming links (both relative with anchor and absolute)
    let overview_content = tmp.read("overview.md");
    assert!(
        overview_content.contains("[Auth Token](security/jwt/token.md#expiration)"),
        "Overview content was: {overview_content}"
    );
    assert!(
        overview_content.contains("[/auth/token.md](/security/jwt/token.md)"),
        "Overview content was: {overview_content}"
    );

    // Check log.md update
    let log_content = tmp.read("log.md");
    assert!(log_content.contains("Renamed concept `auth/token` to `security/jwt/token`"));
}

#[test]
fn test_move_concept_rebases_frontmatter_resources() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "metrics/calc/revenue.md",
        "---\ntype: Attested Computation\ntitle: Revenue\nruntime: python\ncomputation: ../scripts/rev.py\nexecutor:\n  resource: ../skills/run.md\n  receipt: [result]\nattester:\n  resource: ../attesters/verify.py\nsources:\n  - id: ga4\n    resource: ../data/schema.json\n---\n\n# Revenue\n\nComputed via rev.py.\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let from = ConceptId::parse("metrics/calc/revenue").unwrap();
    let to = ConceptId::parse("finance/revenue").unwrap();

    let opts = MoveOptions::default();
    let report = move_concept(&bundle, &from, &to, &opts).unwrap();

    assert_eq!(report.rebased_frontmatter_paths, 4);

    let moved_content = tmp.read("finance/revenue.md");
    assert!(moved_content.contains("computation: ../metrics/scripts/rev.py"));
    assert!(moved_content.contains("resource: ../metrics/skills/run.md"));
    assert!(moved_content.contains("resource: ../metrics/attesters/verify.py"));
    assert!(moved_content.contains("resource: ../metrics/data/schema.json"));
}

#[test]
fn test_move_concept_dry_run() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write("auth.md", "---\ntype: Concept\n---\n\n# Auth\n");
    tmp.write(
        "user.md",
        "---\ntype: Concept\n---\n\n# User\n\n[Auth](auth.md)\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let from = ConceptId::parse("auth").unwrap();
    let to = ConceptId::parse("security/auth").unwrap();

    let opts = MoveOptions {
        dry_run: true,
        ..Default::default()
    };
    let report = move_concept(&bundle, &from, &to, &opts).unwrap();

    assert!(report.dry_run);
    assert_eq!(report.rewritten_incoming_links, 1);
    // Source file must still exist and target must not exist
    assert!(tmp.path().join("auth.md").exists());
    assert!(!tmp.path().join("security/auth.md").exists());
}

#[test]
fn test_remove_concept_protection_and_redirect() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "legacy.md",
        "---\ntype: Concept\ntitle: Legacy\n---\n\n# Legacy\n",
    );
    tmp.write(
        "modern.md",
        "---\ntype: Concept\ntitle: Modern\n---\n\n# Modern\n",
    );
    tmp.write(
        "user.md",
        "---\ntype: Concept\ntitle: User\n---\n\n# User\n\nSee [Legacy](legacy.md).\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let target = ConceptId::parse("legacy").unwrap();
    let redirect = ConceptId::parse("modern").unwrap();

    // 1. Without force, redirect, or unlink -> fails
    let err = remove_concept(&bundle, &target, &RemoveOptions::default()).unwrap_err();
    assert!(matches!(err, RefactorError::HasInboundLinks { .. }));

    // 2. With redirect_to
    let report = remove_concept(
        &bundle,
        &target,
        &RemoveOptions {
            redirect_to: Some(redirect),
            ..Default::default()
        },
    )
    .unwrap();

    assert_eq!(report.redirected_count, 1);
    assert!(!tmp.path().join("legacy.md").exists());

    let user_content = tmp.read("user.md");
    assert!(user_content.contains("[Legacy](modern.md)"));
}

#[test]
fn test_remove_concept_unlink() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write("old.md", "---\ntype: Concept\n---\n\n# Old\n");
    tmp.write(
        "user.md",
        "---\ntype: Concept\n---\n\n# User\n\nSee [Old Docs](old.md) for details.\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let target = ConceptId::parse("old").unwrap();

    let report = remove_concept(
        &bundle,
        &target,
        &RemoveOptions {
            unlink: true,
            ..Default::default()
        },
    )
    .unwrap();

    assert_eq!(report.unlinked_count, 1);
    assert!(!tmp.path().join("old.md").exists());

    let user_content = tmp.read("user.md");
    assert_eq!(
        user_content.trim(),
        "---\ntype: Concept\n---\n\n# User\n\nSee Old Docs for details."
    );
}

#[test]
fn test_split_concept_extracts_section_and_migrates_footnotes() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    let source_body = "\
---
type: Concept
title: Payments
sources:
  - id: pci-dss
    resource: https://pcisecuritystandards.org
    title: PCI-DSS Spec
  - id: stripe-docs
    resource: https://stripe.com/docs
    title: Stripe Documentation
---

# Payments

Payments are processed via Stripe.[^stripe-docs]

## Security Policy

All cardholder data must comply with PCI-DSS.[^pci-dss]
Retention is limited to tokenized cards.

## Reconciliation

Daily settlement reports are verified.
";
    tmp.write("billing/payments.md", source_body);

    let bundle = Bundle::load(tmp.path()).unwrap();
    let source = ConceptId::parse("billing/payments").unwrap();
    let target = ConceptId::parse("security/pci").unwrap();

    let report = split_concept(
        &bundle,
        &source,
        &target,
        &SplitOptions {
            section: "Security Policy".to_string(),
            title: Some("PCI Compliance".to_string()),
            ..Default::default()
        },
    )
    .unwrap();

    assert_eq!(report.target_title, "PCI Compliance");
    assert!(tmp.path().join("security/pci.md").exists());

    let target_content = tmp.read("security/pci.md");
    assert!(target_content.contains("title: PCI Compliance"));
    assert!(target_content.contains("resource: https://pcisecuritystandards.org"));
    assert!(target_content.contains("# PCI Compliance"));
    assert!(target_content.contains("All cardholder data must comply with PCI-DSS.[^pci-dss]"));

    let source_content = tmp.read("billing/payments.md");
    assert!(
        source_content
            .contains("## Security Policy\n\nSee [PCI Compliance](../security/pci.md).\n")
    );
    assert!(source_content.contains("## Reconciliation"));
}

#[test]
fn test_merge_concepts_consolidates_and_redirects() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "billing/invoices.md",
        "---\ntype: Concept\ntitle: Invoices\nsources:\n  - id: inv-spec\n    resource: https://example.com/inv\nverified:\n  - by: human:alice\n    at: 2026-06-01T00:00:00Z\n---\n\n# Invoices\n\nInvoice details.[^inv-spec]\n",
    );
    tmp.write(
        "finance/invoicing.md",
        "---\ntype: Concept\ntitle: Invoicing\nsources:\n  - id: fin-spec\n    resource: https://example.com/fin\n---\n\n# Invoicing\n\nFinance rules.[^fin-spec]\n",
    );
    tmp.write(
        "overview.md",
        "---\ntype: Concept\ntitle: Overview\n---\n\n# Overview\n\nRead [Invoices](billing/invoices.md).\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let source = ConceptId::parse("billing/invoices").unwrap();
    let target = ConceptId::parse("finance/invoicing").unwrap();

    let report = merge_concepts(&bundle, &source, &target, &MergeOptions::default()).unwrap();

    assert_eq!(report.rewritten_links_count, 1);
    assert_eq!(report.merged_sources_count, 1);
    assert!(!tmp.path().join("billing/invoices.md").exists());

    let target_content = tmp.read("finance/invoicing.md");
    assert!(target_content.contains("Finance rules.[^fin-spec]"));
    assert!(target_content.contains("## Invoices"));
    assert!(target_content.contains("Invoice details.[^inv-spec]"));
    assert!(target_content.contains("resource: https://example.com/inv"));
    assert!(target_content.contains("by: human:alice"));

    let overview_content = tmp.read("overview.md");
    assert!(overview_content.contains("[Invoices](finance/invoicing.md)"));
}

#[test]
fn test_compute_relative_path_and_rebase_edge_cases() {
    use okf_core::refactor::{compute_relative_path, rebase_relative_path};

    // Deep to deep with common prefix
    let a = ConceptId::parse("a/b/c/d").unwrap();
    let b = ConceptId::parse("a/b/e/f").unwrap();
    assert_eq!(compute_relative_path(&a, &b), "../e/f.md");

    // Parent to nested child
    let parent = ConceptId::parse("a").unwrap();
    let child = ConceptId::parse("a/b/c").unwrap();
    assert_eq!(compute_relative_path(&parent, &child), "a/b/c.md");

    // Nested child to parent
    assert_eq!(compute_relative_path(&child, &parent), "../../a.md");

    // Rebase relative path edge cases
    let old_dir = vec!["a".to_string(), "b".to_string(), "c".to_string()];
    let new_dir = vec!["x".to_string(), "y".to_string()];

    // In-document anchor should remain unchanged
    assert_eq!(
        rebase_relative_path(&old_dir, &new_dir, "#my-anchor"),
        "#my-anchor"
    );

    // External URI should remain unchanged
    assert_eq!(
        rebase_relative_path(&old_dir, &new_dir, "https://example.com/api#doc"),
        "https://example.com/api#doc"
    );

    // Absolute path should remain unchanged
    assert_eq!(
        rebase_relative_path(&old_dir, &new_dir, "/data/schema.json"),
        "/data/schema.json"
    );

    // Deep relative file path
    assert_eq!(
        rebase_relative_path(&old_dir, &new_dir, "../../data/schema.json"),
        "../../a/data/schema.json"
    );
}

#[test]
fn test_merge_concepts_with_colliding_sources_and_footnotes() {
    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "source_doc.md",
        "---\ntype: Concept\ntitle: Source Doc\nsources:\n  - id: spec\n    resource: https://source.example.com/spec\n---\n\n# Source Doc\n\nSource claim.[^spec]\n",
    );
    tmp.write(
        "target_doc.md",
        "---\ntype: Concept\ntitle: Target Doc\nsources:\n  - id: spec\n    resource: https://target.example.com/different_spec\n---\n\n# Target Doc\n\nTarget claim.[^spec]\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let source = ConceptId::parse("source_doc").unwrap();
    let target = ConceptId::parse("target_doc").unwrap();

    let report = merge_concepts(&bundle, &source, &target, &MergeOptions::default()).unwrap();

    assert_eq!(report.merged_sources_count, 1);

    let target_content = tmp.read("target_doc.md");
    // Original target source kept
    assert!(target_content.contains("resource: https://target.example.com/different_spec"));
    // Source source remapped to source_doc_spec
    assert!(target_content.contains("id: source_doc_spec"));
    assert!(target_content.contains("resource: https://source.example.com/spec"));
    // Source body footnote reference remapped
    assert!(target_content.contains("Source claim.[^source_doc_spec]"));
    // Target body footnote reference unchanged
    assert!(target_content.contains("Target claim.[^spec]"));
}

#[test]
fn test_rename_section_with_deep_heading_and_slug() {
    use okf_core::refactor::{RenameSectionOptions, rename_section};

    let tmp = TempDir::new();
    tmp.write("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n");
    tmp.write(
        "auth.md",
        "---\ntype: Concept\ntitle: Auth\n---\n\n# Auth\n\nSee [OAuth Info](#oauth-20--token-auth).\n\n### OAuth 2.0 & Token Auth!\n\nDetails.\n",
    );
    tmp.write(
        "users.md",
        "---\ntype: Concept\ntitle: Users\n---\n\n# Users\n\nRead [Auth Tokens](auth.md#oauth-20--token-auth).\n",
    );

    let bundle = Bundle::load(tmp.path()).unwrap();
    let concept = ConceptId::parse("auth").unwrap();

    let report = rename_section(
        &bundle,
        &concept,
        "OAuth 2.0 & Token Auth!",
        "Modern OAuth",
        &RenameSectionOptions::default(),
    )
    .unwrap();

    assert_eq!(report.internal_links_updated, 1);
    assert_eq!(report.external_links_updated, 1);

    let auth_content = tmp.read("auth.md");
    assert!(auth_content.contains("### Modern OAuth"));
    assert!(auth_content.contains("[OAuth Info](#modern-oauth)"));

    let users_content = tmp.read("users.md");
    assert!(users_content.contains("[Auth Tokens](auth.md#modern-oauth)"));
}