Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

test(storage): cover encoded corruption and cross-platform generations

Seraph-x0a7e65530b44
diff --git a/crates/host-core/src/transcripts/binary_integrity_tests.rs b/crates/host-core/src/transcripts/binary_integrity_tests.rs
index 7a3899f0e..5aa05f85c 100644
--- a/crates/host-core/src/transcripts/binary_integrity_tests.rs
+++ b/crates/host-core/src/transcripts/binary_integrity_tests.rs
@@ -72,7 +72,9 @@ fn replacement_file_cannot_reuse_a_verified_generation() {
let replacement = path.with_extension("replacement");
fs::copy(&path, &replacement).unwrap();
replace_message_line(&replacement, "reference");
- File::open(&replacement)
+ File::options()
+ .write(true)
+ .open(&replacement)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(metadata.modified().unwrap()))
.unwrap();
@@ -84,7 +86,6 @@ fn replacement_file_cannot_reuse_a_verified_generation() {
assert_eq!(fs::read(path).unwrap(), before);
}
-#[cfg(unix)]
#[test]
fn same_size_rewrite_restoring_mtime_cannot_reuse_a_verified_generation() {
let dir = tempfile::tempdir().unwrap();
@@ -96,7 +97,9 @@ fn same_size_rewrite_restoring_mtime_cannot_reuse_a_verified_generation() {
let corrupt = raw.replacen("\"image\":0", "\"image\":9", 1);
assert_ne!(raw, corrupt);
fs::write(&path, &corrupt).unwrap();
- File::open(&path)
+ File::options()
+ .write(true)
+ .open(&path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(metadata.modified().unwrap()))
.unwrap();
diff --git a/crates/host-core/src/transcripts/binary_migration.rs b/crates/host-core/src/transcripts/binary_migration.rs
index a8a0e8102..2da0212c9 100644
--- a/crates/host-core/src/transcripts/binary_migration.rs
+++ b/crates/host-core/src/transcripts/binary_migration.rs
@@ -81,23 +81,20 @@ pub(super) fn prepare(path: &Path, header: Option<&str>) -> Result<bool> {
value["schema"] = Value::from(TRANSCRIPT_SCHEMA);
replacement = Some(value);
}
- Some("message" | "compaction" | "revision") => {
- // Readers historically skip malformed plain records. Do
- // not turn one into an encoded row whose typed read must
- // fail explicitly. Existing encoded rows were validated
- // before opening the conversion temporary.
+ // Keep malformed historical plain records skippable. Existing
+ // encoded rows were validated before opening the temporary.
+ Some("message" | "compaction" | "revision")
if value.get("binaryStorage").is_some()
- || binary_storage::validate_record(value.clone()).is_ok()
- {
- let decoded = binary_storage::decode(value.clone())?;
- let encoded = binary_storage::encode(decoded.clone())?;
- anyhow::ensure!(
- binary_storage::decode(encoded.clone())? == decoded,
- "lossless transcript conversion verification failed"
- );
- if encoded != value {
- replacement = Some(encoded);
- }
+ || binary_storage::validate_record(value.clone()).is_ok() =>
+ {
+ let decoded = binary_storage::decode(value.clone())?;
+ let encoded = binary_storage::encode(decoded.clone())?;
+ anyhow::ensure!(
+ binary_storage::decode(encoded.clone())? == decoded,
+ "lossless transcript conversion verification failed"
+ );
+ if encoded != value {
+ replacement = Some(encoded);
}
}
_ => {}
diff --git a/crates/host-core/src/transcripts/binary_storage_tests.rs b/crates/host-core/src/transcripts/binary_storage_tests.rs
index 298af7b73..d9ab02ded 100644
--- a/crates/host-core/src/transcripts/binary_storage_tests.rs
+++ b/crates/host-core/src/transcripts/binary_storage_tests.rs
@@ -357,3 +357,59 @@ fn headerless_and_empty_legacy_files_receive_a_current_header_once() {
);
}
}
+
+#[test]
+fn current_format_corruption_blocks_appends_and_updates_without_changing_files() {
+ for fault in ["image", "version"] {
+ for update in [false, true] {
+ let dir = tempfile::tempdir().unwrap();
+ let path = transcript_path(dir.path(), "s").unwrap();
+ let record = screenshot();
+ append_message(dir.path(), "s", "old", &record).unwrap();
+ let raw = fs::read_to_string(&path).unwrap();
+ let mut lines: Vec<Value> = raw
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ if fault == "image" {
+ lines[1]["binaryStorage"]["refs"][0]["image"] = json!(999);
+ } else {
+ lines[1]["binaryStorage"]["version"] = json!(999);
+ }
+ let corrupt = lines
+ .iter()
+ .map(Value::to_string)
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n";
+ fs::write(&path, &corrupt).unwrap();
+ let mut next = record.clone();
+ next.id = "next".into();
+ let result = if update {
+ update_message(dir.path(), "s", &record).map(|_| ())
+ } else {
+ append_message(dir.path(), "s", "old", &next)
+ };
+ assert!(
+ result.is_err(),
+ "{fault}, update={update} must refuse corrupted existing storage"
+ );
+ assert_eq!(fs::read_to_string(&path).unwrap(), corrupt);
+ }
+ }
+}
+
+#[test]
+fn rust_rejects_unknown_nested_mirror_part_fields_like_typescript() {
+ let mut encoded = binary_storage::encode(nested_mirror(1)).unwrap();
+ let part = encoded["binaryStorage"]["texts"]
+ .as_array_mut()
+ .unwrap()
+ .iter_mut()
+ .flat_map(|text| text["parts"].as_array_mut().unwrap())
+ .find(|part| part.get("text").is_some())
+ .unwrap();
+ part["unknown"] = json!(true);
+ let error = binary_storage::decode(encoded).unwrap_err();
+ assert!(binary_storage::is_error(&error), "{error}");
+}
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index e2d5dfe20..6232f6b1b 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -609,7 +609,7 @@ Refresh (spec 13 §6/§9) upserts `discovered` rows and **never overwrites
`source='user'`** rows. Recent-model MRU stays in `kv(cache)` — it is a
bounded display list, not relational data.
-Schema v26 adds nullable `discovery_state`, distinct from metadata deprecation.
+Schema v25 adds nullable `discovery_state`, distinct from metadata deprecation.
The v24 upgrade backs up first, adds the field transactionally, and marks
existing discovered rows as past publication evidence. User-owned rows remain
unknown. No provider configuration, credentials, sessions, or turns are changed.
diff --git a/packages/host-runtime/src/binary-storage.test.ts b/packages/host-runtime/src/binary-storage.test.ts
index a44f180c5..604c2c3d8 100644
--- a/packages/host-runtime/src/binary-storage.test.ts
+++ b/packages/host-runtime/src/binary-storage.test.ts
@@ -288,3 +288,15 @@ describe("nested proven JSON mirrors", () => {
expect(() => decodeBinaryStorage(encoded)).toThrow(/binary storage.*text.*token/i);
});
});
+
+describe("nested mirror corruption parity", () => {
+ it("rejects unknown fields in a text-reference part", () => {
+ const encoded = structuredClone(nestedGolden.encoded) as StoredMirror;
+ const part = encoded.binaryStorage.texts
+ .flatMap((text) => text.parts)
+ .find((part) => typeof part !== "string" && "text" in part);
+ if (!part || typeof part === "string") throw new Error("Missing mirror part fixture");
+ Object.assign(part, { unknown: true });
+ expect(() => decodeBinaryStorage(encoded)).toThrow(/unexpected envelope fields/i);
+ });
+});