relay-knowledge 1.1.17

Graph-database-based knowledge graph project.
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
491
492
493
494
495
496
497
498
499
500
501
502
use super::*;

pub(super) async fn history_file_contents(directory: &std::path::Path) -> Vec<(String, Vec<u8>)> {
    let mut entries = fs::read_dir(directory)
        .await
        .expect("history directory should read");
    let mut names = Vec::new();
    while let Some(entry) = entries
        .next_entry()
        .await
        .expect("history entry should read")
    {
        names.push((
            entry.file_name().to_string_lossy().into_owned(),
            fs::read(entry.path())
                .await
                .expect("history artifact should read"),
        ));
    }
    names.sort();
    names
}

#[tokio::test]
async fn history_cleanup_rejects_unknown_entries_before_deleting_generated_files() {
    let root = temp_root("history-cleanup-unknown");
    let directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("history directory should create");
    let generated = directory.join(format!("{:020}-{:020}-{}.yaml", 1, 1, "a".repeat(64)));
    fs::write(&generated, "legacy archive")
        .await
        .expect("generated artifact should write");
    fs::write(directory.join("operator-notes.txt"), "preserve")
        .await
        .expect("unknown file should write");

    let error = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
        .await
        .expect_err("unknown files must stop cleanup");
    assert!(matches!(error, KnowledgeMapServiceError::Integrity(_)));
    assert!(fs::try_exists(generated).await.unwrap());
    assert!(
        fs::try_exists(directory.join("operator-notes.txt"))
            .await
            .unwrap()
    );
    let _ = fs::remove_dir_all(root).await;
}

#[cfg(unix)]
#[tokio::test]
async fn history_cleanup_rejects_a_symlinked_directory_without_touching_its_target() {
    use std::os::unix::fs::symlink;

    let root = temp_root("history-cleanup-symlink");
    let outside = temp_root("history-cleanup-outside");
    fs::create_dir_all(root.join(AGENT_CONTRACT_DIR_NAME))
        .await
        .expect("contract directory should create");
    fs::create_dir_all(&outside)
        .await
        .expect("outside directory should create");
    fs::write(outside.join("preserve.txt"), "preserve")
        .await
        .expect("outside file should write");
    symlink(
        &outside,
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME),
    )
    .expect("history symlink should create");

    let error = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
        .await
        .expect_err("symlinked history directory must be rejected");
    assert!(matches!(error, KnowledgeMapServiceError::UnsafePath(_)));
    assert!(fs::try_exists(outside.join("preserve.txt")).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
    let _ = fs::remove_dir_all(outside).await;
}

#[tokio::test]
async fn history_cleanup_is_bounded_and_resumes_on_the_next_attempt() {
    let root = temp_root("history-cleanup-batches");
    let directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("history directory should create");
    for version in 1..=1_025_u64 {
        let path = directory.join(format!(
            "{version:020}-{version:020}-{}.yaml",
            "a".repeat(64)
        ));
        fs::write(path, "legacy archive")
            .await
            .expect("history artifact should write");
    }

    let progress = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
        .await
        .expect("the first cleanup attempt should stop without failing its caller");
    assert_eq!(
        progress,
        HistoryCleanupStatus::Pending {
            removed: HISTORY_CLEANUP_ENTRY_LIMIT
        }
    );
    assert_eq!(history_file_contents(&directory).await.len(), 2);
    let completed = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
        .await
        .expect("the next attempt should finish cleanup");
    assert_eq!(completed, HistoryCleanupStatus::Complete);
    assert!(!fs::try_exists(directory).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn history_cleanup_defers_removal_for_in_flight_legacy_readers() {
    let root = temp_root("history-cleanup-reader-grace");
    let directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("history directory should create");
    let artifact = directory.join(format!("{:020}-{:020}-{}.yaml", 1, 1, "a".repeat(64)));
    fs::write(&artifact, "legacy archive")
        .await
        .expect("history artifact should write");
    let grace = Duration::from_millis(50);

    let deferred = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, grace)
        .await
        .expect("the first cleanup attempt should establish reader grace");
    assert_eq!(deferred, HistoryCleanupStatus::Deferred);
    assert!(fs::try_exists(&artifact).await.unwrap());
    sleep(grace + Duration::from_millis(25)).await;
    let completed = cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, grace)
        .await
        .expect("cleanup should proceed after reader grace elapses");
    assert_eq!(completed, HistoryCleanupStatus::Complete);
    assert!(!fs::try_exists(directory).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn committed_map_mutation_defers_history_cleanup_for_legacy_readers() {
    let root = temp_root("history-cleanup-after-commit");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");
    let directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("history directory should create");
    for version in 1..=1_025_u64 {
        fs::write(
            directory.join(format!(
                "{version:020}-{version:020}-{}.yaml",
                "a".repeat(64)
            )),
            "legacy archive",
        )
        .await
        .expect("history artifact should write");
    }

    service
        .add_source(
            &context,
            KnowledgeMapSourceAddRequest {
                id: "post-cleanup-source".to_owned(),
                topic: "build".to_owned(),
                kind: KnowledgeMapSourceKind::Config,
                uri: "build/post-cleanup.toml".to_owned(),
                source_scope: Some("repo".to_owned()),
                description: None,
            },
        )
        .await
        .expect("a committed mutation must not fail because cleanup remains pending");
    assert_eq!(history_file_contents(&directory).await.len(), 1_026);
    assert!(
        service
            .show(&context, None)
            .await
            .expect("committed map should remain readable")
            .map
            .sources
            .iter()
            .any(|source| source.id == "post-cleanup-source")
    );
    assert_eq!(
        cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
            .await
            .expect("an expired cleanup batch should run"),
        HistoryCleanupStatus::Pending {
            removed: HISTORY_CLEANUP_ENTRY_LIMIT
        }
    );
    assert_eq!(
        cleanup_history_artifacts_in(&root, AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
            .await
            .expect("the final expired cleanup batch should run"),
        HistoryCleanupStatus::Complete
    );
    assert!(!fs::try_exists(directory).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn committed_map_mutation_succeeds_when_history_cleanup_rejects_an_entry() {
    let root = temp_root("history-cleanup-rejection-after-commit");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");
    let directory = root
        .join(AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("history directory should create");
    let generated = directory.join(format!("{:020}-{:020}-{}.yaml", 1, 1, "a".repeat(64)));
    fs::write(&generated, "legacy archive")
        .await
        .expect("generated artifact should write");
    let unknown = directory.join("operator-notes.txt");
    fs::write(&unknown, "preserve")
        .await
        .expect("unknown entry should write");

    let mutation = service
        .add_source(
            &context,
            KnowledgeMapSourceAddRequest {
                id: "post-cleanup-rejection-source".to_owned(),
                topic: "build".to_owned(),
                kind: KnowledgeMapSourceKind::Config,
                uri: "build/post-cleanup-rejection.toml".to_owned(),
                source_scope: Some("repo".to_owned()),
                description: None,
            },
        )
        .await
        .expect("cleanup rejection must not retroactively fail a committed mutation");
    let shown = service
        .show(&context, None)
        .await
        .expect("committed map should remain readable");
    assert_eq!(shown.map.map_version, mutation.map_version);
    assert!(
        shown
            .map
            .sources
            .iter()
            .any(|source| source.id == "post-cleanup-rejection-source")
    );
    assert!(fs::try_exists(&generated).await.unwrap());
    assert!(fs::try_exists(&unknown).await.unwrap());
    assert!(
        !service
            .validate(&context)
            .await
            .expect("validation should expose pending cleanup maintenance")
            .valid
    );
    assert!(
        service
            .init(&context)
            .await
            .expect_err("a maintenance-only init should still report the unsafe cleanup state")
            .to_string()
            .contains("refuses unrecognized entry")
    );
    let _ = fs::remove_dir_all(root).await;
}

#[cfg(unix)]
#[tokio::test]
async fn validation_rejects_a_dangling_history_symlink() {
    use std::os::unix::fs::symlink;

    let root = temp_root("history-validation-dangling-symlink");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");
    symlink(
        root.join("missing-history-target"),
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME),
    )
    .expect("dangling history symlink should create");

    let validation = service
        .validate(&context)
        .await
        .expect("validation should run");
    assert!(!validation.valid);
    assert!(
        validation
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.contains("unsafe knowledge map artifact path"))
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn current_init_defers_recognized_legacy_namespace_history_artifacts() {
    let root = temp_root("legacy-namespace-history-cleanup");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");
    let directory = root
        .join(LEGACY_AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&directory)
        .await
        .expect("legacy history directory should create");
    fs::write(
        directory.join(format!("{:020}-{:020}-{}.yaml", 1, 1, "a".repeat(64))),
        "obsolete archive",
    )
    .await
    .expect("legacy history artifact should write");

    service
        .init(&context)
        .await
        .expect("idempotent init should establish legacy-reader grace");
    assert!(fs::try_exists(&directory).await.unwrap());
    cleanup_history_artifacts_in(&root, LEGACY_AGENT_CONTRACT_DIR_NAME, Duration::ZERO)
        .await
        .expect("expired legacy-reader grace should permit cleanup");
    assert!(!fs::try_exists(directory).await.unwrap());
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn current_init_preserves_history_referenced_by_a_live_legacy_root() {
    let root = temp_root("live-legacy-root-history-cleanup");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("map should initialize");

    let legacy_topics = root
        .join(LEGACY_AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME);
    fs::create_dir_all(&legacy_topics)
        .await
        .expect("legacy topics directory should create");
    let mut topics = fs::read_dir(
        root.join(AGENT_CONTRACT_DIR_NAME)
            .join(KNOWLEDGE_MAP_TOPICS_DIR_NAME),
    )
    .await
    .expect("current topics directory should read");
    while let Some(entry) = topics.next_entry().await.expect("topic entry should read") {
        fs::copy(entry.path(), legacy_topics.join(entry.file_name()))
            .await
            .expect("topic shard should copy to the legacy namespace");
    }
    fs::copy(service.map_path(), service.legacy_map_path())
        .await
        .expect("current root should copy to the legacy namespace");
    super::migration::rewrite_contract_schema_for_test(
        &root,
        LEGACY_AGENT_CONTRACT_DIR_NAME,
        &service.legacy_map_path(),
        DIRECTORY_ARTIFACT_SCHEMA_VERSION,
        None,
    )
    .await
    .expect("legacy root and shards should downgrade together");
    let mut legacy_manifest = parse_manifest(
        &fs::read_to_string(service.legacy_map_path())
            .await
            .expect("legacy manifest should read"),
    )
    .expect("current manifest should parse");
    let archived_entry = legacy_manifest
        .history
        .recent
        .first()
        .cloned()
        .expect("initial history entry should exist");
    let archive = KnowledgeMapHistoryArchive {
        schema_version: DIRECTORY_ARTIFACT_SCHEMA_VERSION,
        from_version: 1,
        through_version: 1,
        previous: None,
        entries: vec![archived_entry],
    };
    let archive_yaml = serialize_yaml(&archive).expect("legacy archive should serialize");
    let archive_digest = content_digest(archive_yaml.as_bytes());
    let archive_ref = KnowledgeMapArchiveRef {
        r#ref: format!(
            "{KNOWLEDGE_MAP_HISTORY_DIR_NAME}/{:020}-{:020}-{archive_digest}.yaml",
            1, 1
        ),
        digest: archive_digest,
    };
    legacy_manifest.map_version = 2;
    legacy_manifest.updated_at = "unix:2".to_owned();
    legacy_manifest.history.archived_through = 1;
    legacy_manifest.history.omitted_through = 0;
    legacy_manifest.history.archive = Some(archive_ref.clone());
    legacy_manifest.history.index = None;
    legacy_manifest.history.recent = vec![crate::domain::KnowledgeMapHistoryEntry {
        version: 2,
        action: "fixture".to_owned(),
        actor: "test".to_owned(),
        summary: "Retain live legacy history".to_owned(),
    }];

    let legacy_history = root
        .join(LEGACY_AGENT_CONTRACT_DIR_NAME)
        .join(KNOWLEDGE_MAP_HISTORY_DIR_NAME);
    fs::create_dir_all(&legacy_history)
        .await
        .expect("legacy history directory should create");
    fs::write(
        root.join(LEGACY_AGENT_CONTRACT_DIR_NAME)
            .join(&archive_ref.r#ref),
        archive_yaml,
    )
    .await
    .expect("legacy archive should write");
    fs::write(
        service.legacy_map_path(),
        serialize_yaml(&legacy_manifest).expect("legacy manifest should serialize"),
    )
    .await
    .expect("live legacy root should write");
    assert!(!fs::try_exists(service.legacy_backup_path()).await.unwrap());

    service
        .init(&context)
        .await
        .expect("idempotent init should preserve a live legacy root");

    assert!(fs::try_exists(&legacy_history).await.unwrap());
    assert!(
        fs::try_exists(
            root.join(LEGACY_AGENT_CONTRACT_DIR_NAME)
                .join(&archive_ref.r#ref)
        )
        .await
        .unwrap()
    );
    assert!(
        !fs::read_to_string(service.legacy_map_path())
            .await
            .expect("live legacy root should remain")
            .contains("artifact_kind: redirect")
    );
    let _ = fs::remove_dir_all(root).await;
}

#[tokio::test]
async fn show_rejects_explicit_empty_archive_fields_in_a_recent_only_manifest() {
    let root = temp_root("invalid-show-empty-archive-fields");
    fs::create_dir_all(&root).await.expect("root should create");
    let service = KnowledgeMapService::new(root.clone());
    let context = RequestContext::for_interface(crate::api::InterfaceKind::Cli);
    service.init(&context).await.expect("init should work");
    let content = fs::read_to_string(service.map_path())
        .await
        .expect("manifest should read");
    let content = content.replacen(
        "history:\n",
        "history:\n  archived_through: 0\n  archive: null\n  index: null\n",
        1,
    );
    fs::write(service.map_path(), content)
        .await
        .expect("manifest should write");

    let error = service
        .show(&context, None)
        .await
        .expect_err("show must reject even empty archive fields in schema v4");
    assert!(
        error
            .to_string()
            .contains("must not reference archive artifacts")
    );
    let _ = fs::remove_dir_all(root).await;
}