lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
// SPDX-License-Identifier: Apache-2.0

//! Byte-preserving migration from the pre-v3.6.14 `.lctxpkg` name to `.ctxpkg`.

use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::verify::verify_package_file;

pub(crate) const PACKAGE_MIGRATION_RECEIPT_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackageMigrationReceipt {
    pub receipt_version: u32,
    pub source_file: String,
    pub output_file: String,
    pub source_sha256: String,
    pub output_sha256: String,
    pub byte_preserving: bool,
    pub source_retained_for_rollback: bool,
}

pub fn rollback_legacy_package(receipt_path: &Path) -> Result<PathBuf, String> {
    let _lock = lock_package_migration(receipt_path)?;
    reject_symlink(receipt_path, "migration receipt")?;
    let receipt_bytes =
        std::fs::read(receipt_path).map_err(|error| format!("read migration receipt: {error}"))?;
    let receipt: PackageMigrationReceipt = serde_json::from_slice(&receipt_bytes)
        .map_err(|error| format!("parse migration receipt: {error}"))?;
    if receipt.receipt_version != PACKAGE_MIGRATION_RECEIPT_VERSION
        || !receipt.byte_preserving
        || !receipt.source_retained_for_rollback
        || receipt.source_sha256 != receipt.output_sha256
    {
        return Err("migration receipt is not rollback-compatible".to_string());
    }
    validate_plain_filename(&receipt.source_file, "source_file")?;
    validate_plain_filename(&receipt.output_file, "output_file")?;
    let parent = receipt_path
        .parent()
        .ok_or_else(|| "migration receipt has no parent directory".to_string())?;
    let source = parent.join(&receipt.source_file);
    let output = parent.join(&receipt.output_file);
    if source == output
        || source.extension().and_then(|value| value.to_str())
            != Some(crate::core::contracts::LEGACY_PACKAGE_EXTENSION)
        || output.extension().and_then(|value| value.to_str())
            != Some(crate::core::contracts::PACKAGE_EXTENSION)
        || source.with_extension(crate::core::contracts::PACKAGE_EXTENSION) != output
    {
        return Err("migration receipt source/output package binding is invalid".to_string());
    }
    if output.with_extension("ctxpkg.migration.json") != receipt_path {
        return Err("migration receipt path does not match output package".to_string());
    }
    reject_symlink(&source, "rollback source")?;
    reject_symlink(&output, "rollback output")?;
    validate_digest(&source, &receipt.source_sha256, "rollback source")?;
    if output.exists() {
        validate_digest(&output, &receipt.output_sha256, "rollback output")?;
        std::fs::remove_file(&output)
            .map_err(|error| format!("remove migrated package {}: {error}", output.display()))?;
        sync_parent(parent)?;
    }
    std::fs::remove_file(receipt_path)
        .map_err(|error| format!("remove migration receipt: {error}"))?;
    sync_parent(parent)?;
    Ok(source)
}

fn validate_plain_filename(value: &str, field: &str) -> Result<(), String> {
    let path = Path::new(value);
    if value.is_empty() || path.file_name().and_then(|name| name.to_str()) != Some(value) {
        return Err(format!("{field} must be one plain UTF-8 filename"));
    }
    Ok(())
}

fn validate_digest(path: &Path, expected: &str, label: &str) -> Result<(), String> {
    let bytes = std::fs::read(path).map_err(|error| format!("read {label}: {error}"))?;
    let actual = crate::core::agent_identity::hex_encode(&Sha256::digest(&bytes));
    if actual != expected {
        return Err(format!("{label} SHA-256 mismatch"));
    }
    Ok(())
}

fn reject_symlink(path: &Path, label: &str) -> Result<(), String> {
    if path
        .symlink_metadata()
        .is_ok_and(|metadata| metadata.file_type().is_symlink())
    {
        Err(format!("refusing symlink {label}: {}", path.display()))
    } else {
        Ok(())
    }
}

fn sync_parent(parent: &Path) -> Result<(), String> {
    crate::core::atomic_fs::sync_directory(parent)
        .map_err(|error| format!("sync rollback directory: {error}"))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageMigrationResult {
    pub output_path: PathBuf,
    pub receipt_path: PathBuf,
    pub already_migrated: bool,
    pub receipt: PackageMigrationReceipt,
}

pub fn migrate_legacy_package(path: &Path) -> Result<PackageMigrationResult, String> {
    if path
        .symlink_metadata()
        .is_ok_and(|metadata| metadata.file_type().is_symlink())
    {
        return Err(format!("refusing to migrate symlink: {}", path.display()));
    }
    if path.extension().and_then(|value| value.to_str())
        != Some(crate::core::contracts::LEGACY_PACKAGE_EXTENSION)
    {
        return Err(format!(
            "expected a .{} package",
            crate::core::contracts::LEGACY_PACKAGE_EXTENSION
        ));
    }

    let verification = verify_package_file(path)?;
    if !verification.valid() {
        return Err(format!(
            "legacy package verification failed: {}",
            verification.errors.join("; ")
        ));
    }

    let bytes = std::fs::read(path).map_err(|error| format!("read legacy package: {error}"))?;
    // The migration copies these bytes under a new name. They are copied
    // only if the package they hold passes the CURRENT admission as it is —
    // a package that would be refused today never becomes a fresh `.ctxpkg`.
    // Nothing has been written at this point; the legacy file is not touched
    // by a refusal (nor by a migration: it is retained for rollback).
    super::registry::admit_package_bytes(&bytes)?;
    let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(&bytes));
    let output_path = path.with_extension(crate::core::contracts::PACKAGE_EXTENSION);
    let receipt_path = output_path.with_extension("ctxpkg.migration.json");
    let _lock = lock_package_migration(&receipt_path)?;
    let receipt = PackageMigrationReceipt {
        receipt_version: PACKAGE_MIGRATION_RECEIPT_VERSION,
        source_file: file_name(path)?,
        output_file: file_name(&output_path)?,
        source_sha256: digest.clone(),
        output_sha256: digest,
        byte_preserving: true,
        source_retained_for_rollback: true,
    };
    let receipt_bytes = serde_json::to_vec_pretty(&receipt).map_err(|error| error.to_string())?;
    validate_existing_file(&receipt_path, &receipt_bytes, "migration receipt")?;

    let already_migrated = if output_path.exists() {
        validate_existing_file(&output_path, &bytes, "destination")?;
        true
    } else {
        create_without_overwrite(&output_path, &bytes)?;
        false
    };

    let output_verification = verify_package_file(&output_path)?;
    if !output_verification.valid() {
        if !already_migrated {
            let _ = std::fs::remove_file(&output_path);
        }
        return Err("migrated package failed post-write verification".to_string());
    }
    if !receipt_path.exists()
        && let Err(error) = create_without_overwrite(&receipt_path, &receipt_bytes)
    {
        if !already_migrated {
            let _ = std::fs::remove_file(&output_path);
        }
        return Err(error);
    }
    Ok(PackageMigrationResult {
        output_path,
        receipt_path,
        already_migrated,
        receipt,
    })
}

fn validate_existing_file(path: &Path, expected: &[u8], label: &str) -> Result<(), String> {
    if !path.exists() {
        return Ok(());
    }
    let existing =
        std::fs::read(path).map_err(|error| format!("read existing {label}: {error}"))?;
    if existing == expected {
        Ok(())
    } else {
        Err(format!(
            "refusing to overwrite non-identical {label}: {}",
            path.display()
        ))
    }
}

fn file_name(path: &Path) -> Result<String, String> {
    path.file_name()
        .and_then(|value| value.to_str())
        .map(str::to_string)
        .ok_or_else(|| format!("package filename is not UTF-8: {}", path.display()))
}

fn create_without_overwrite(path: &Path, bytes: &[u8]) -> Result<(), String> {
    let name = path
        .file_name()
        .and_then(|value| value.to_str())
        .ok_or_else(|| format!("invalid output filename: {}", path.display()))?;
    let staged = path.with_file_name(format!(".{name}.staged"));
    reject_symlink(&staged, "staged migration file")?;
    if staged.exists() {
        std::fs::remove_file(&staged)
            .map_err(|error| format!("remove stale staged migration file: {error}"))?;
    }
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&staged)
        .map_err(|error| format!("create {}: {error}", staged.display()))?;
    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
        let _ = std::fs::remove_file(&staged);
        return Err(format!("write {}: {error}", staged.display()));
    }
    std::fs::hard_link(&staged, path)
        .map_err(|error| format!("publish {} without overwrite: {error}", path.display()))?;
    std::fs::remove_file(&staged)
        .map_err(|error| format!("remove staged migration file: {error}"))?;
    if let Some(parent) = path.parent() {
        sync_parent(parent)?;
    }
    Ok(())
}

fn lock_package_migration(
    receipt_path: &Path,
) -> Result<crate::core::migration_lock::MigrationLock, String> {
    let lock_path = receipt_path.with_extension("json.lock");
    reject_symlink(&lock_path, "migration lock")?;
    crate::core::migration_lock::acquire(&lock_path)
}

#[cfg(test)]
mod tests {
    use chrono::{TimeZone, Utc};

    use super::*;
    use crate::core::context_package::content::PackageContent;
    use crate::core::context_package::manifest::{
        CompatibilitySpec, PackageIntegrity, PackageLayer, PackageManifest, PackageProvenance,
        PackageStats,
    };

    #[derive(Serialize)]
    struct Bundle {
        manifest: PackageManifest,
        content: PackageContent,
    }

    fn legacy_package(path: &Path, signed: bool) -> Vec<u8> {
        let content = PackageContent::default();
        let content_json = serde_json::to_string(&content).unwrap();
        let content_hash =
            crate::core::agent_identity::hex_encode(&Sha256::digest(content_json.as_bytes()));
        let composite = format!("legacy-fixture:1.0.0:{content_hash}");
        let mut manifest = PackageManifest {
            schema_version: crate::core::contracts::CONTEXT_PACKAGE_V1_SCHEMA_VERSION,
            conformance_level: None,
            kind: Default::default(),
            name: "legacy-fixture".to_string(),
            version: "1.0.0".to_string(),
            description: "v3 package migration fixture".to_string(),
            author: None,
            scope: None,
            created_at: Utc.timestamp_opt(1_700_000_000, 0).single().unwrap(),
            updated_at: None,
            layers: vec![PackageLayer::Knowledge],
            dependencies: vec![],
            tags: vec![],
            visibility: None,
            integrity: PackageIntegrity {
                sha256: crate::core::agent_identity::hex_encode(&Sha256::digest(
                    composite.as_bytes(),
                )),
                content_hash,
                byte_size: content_json.len() as u64,
            },
            provenance: PackageProvenance {
                tool: "lean-ctx".to_string(),
                tool_version: "3.10.1".to_string(),
                project_hash: None,
                source_session_id: None,
            },
            compatibility: CompatibilitySpec::default(),
            stats: PackageStats::default(),
            signature: None,
            graph_summary: None,
            marketplace: None,
            redistributable: None,
        };
        if signed {
            let key = ed25519_dalek::SigningKey::from_bytes(&[11; 32]);
            crate::core::context_package::signing::sign_package(&mut manifest, &content, &key);
        }
        let bytes = serde_json::to_vec_pretty(&Bundle { manifest, content }).unwrap();
        std::fs::write(path, &bytes).unwrap();
        bytes
    }

    #[test]
    fn signed_legacy_package_migrates_byte_for_byte_and_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        let original = legacy_package(&source, true);

        let first = migrate_legacy_package(&source).unwrap();
        assert!(!first.already_migrated);
        assert_eq!(std::fs::read(&first.output_path).unwrap(), original);
        assert_eq!(std::fs::read(&source).unwrap(), original);
        assert_eq!(first.receipt.source_sha256, first.receipt.output_sha256);

        let second = migrate_legacy_package(&source).unwrap();
        assert!(second.already_migrated);
        assert_eq!(first.receipt, second.receipt);
    }

    #[test]
    fn rollback_removes_only_verified_generated_files() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        let original = legacy_package(&source, true);
        let migrated = migrate_legacy_package(&source).unwrap();

        let restored = rollback_legacy_package(&migrated.receipt_path).unwrap();
        assert_eq!(restored, source);
        assert_eq!(std::fs::read(&source).unwrap(), original);
        assert!(!migrated.output_path.exists());
        assert!(!migrated.receipt_path.exists());
    }

    #[test]
    fn rollback_refuses_changed_output_without_mutation() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let migrated = migrate_legacy_package(&source).unwrap();
        std::fs::write(&migrated.output_path, b"changed").unwrap();

        assert!(rollback_legacy_package(&migrated.receipt_path).is_err());
        assert_eq!(std::fs::read(&migrated.output_path).unwrap(), b"changed");
        assert!(migrated.receipt_path.exists());
    }

    #[test]
    fn rollback_recovers_after_output_was_already_removed() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let migrated = migrate_legacy_package(&source).unwrap();
        std::fs::remove_file(&migrated.output_path).unwrap();

        assert_eq!(
            rollback_legacy_package(&migrated.receipt_path).unwrap(),
            source
        );
        assert!(!migrated.receipt_path.exists());
    }

    #[test]
    fn rollback_rejects_receipt_moved_away_from_bound_output() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let migrated = migrate_legacy_package(&source).unwrap();
        let moved = dir.path().join("unbound.migration.json");
        std::fs::rename(&migrated.receipt_path, &moved).unwrap();

        assert!(rollback_legacy_package(&moved).is_err());
        assert!(migrated.output_path.exists());
    }

    #[test]
    fn rollback_rejects_receipt_that_aliases_source_and_output() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let migrated = migrate_legacy_package(&source).unwrap();
        let mut receipt = migrated.receipt.clone();
        receipt.output_file = receipt.source_file.clone();
        std::fs::write(
            &migrated.receipt_path,
            serde_json::to_vec_pretty(&receipt).unwrap(),
        )
        .unwrap();

        assert!(rollback_legacy_package(&migrated.receipt_path).is_err());
        assert!(source.exists());
        assert!(migrated.output_path.exists());
        assert!(migrated.receipt_path.exists());
    }

    #[test]
    fn tampered_signed_package_is_rejected_without_output() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        let mut bytes = legacy_package(&source, true);
        let index = bytes.iter().position(|byte| *byte == b'v').unwrap();
        bytes[index] = b'x';
        std::fs::write(&source, bytes).unwrap();

        assert!(migrate_legacy_package(&source).is_err());
        assert!(!source.with_extension("ctxpkg").exists());
    }

    #[test]
    fn conflicting_destination_is_never_overwritten() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let output = source.with_extension("ctxpkg");
        std::fs::write(&output, b"owned").unwrap();

        assert!(migrate_legacy_package(&source).is_err());
        assert_eq!(std::fs::read(output).unwrap(), b"owned");
    }

    #[test]
    fn conflicting_receipt_does_not_create_destination() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("fixture.lctxpkg");
        legacy_package(&source, false);
        let output = source.with_extension("ctxpkg");
        let receipt = output.with_extension("ctxpkg.migration.json");
        std::fs::write(&receipt, b"owned").unwrap();

        assert!(migrate_legacy_package(&source).is_err());
        assert!(!output.exists());
        assert_eq!(std::fs::read(receipt).unwrap(), b"owned");
    }

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

        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("target.lctxpkg");
        legacy_package(&target, false);
        let source = dir.path().join("fixture.lctxpkg");
        symlink(&target, &source).unwrap();

        assert!(migrate_legacy_package(&source).is_err());
        assert!(!source.with_extension("ctxpkg").exists());
    }
}