eidetic-engine 0.18.0

Durable, local-first, explainable memory for coding agents.
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
//! Bind binary item projections to the hash-checked canonical response.
//!
//! The v1 frame hashes its JSON footer, not its separate item blob. Geometry
//! checks alone therefore cannot establish that zero-copy item reads agree
//! with the response being replayed. Stream the content projection and compare
//! each decoded string immediately, without retaining a second copy of the
//! pack. Unescaped strings borrow the input; escaped strings use the JSON
//! decoder's reusable scratch buffer. Unknown fields are parsed but discarded.
//! The owning view exposes no item before the whole document passes and caches
//! only the verdict for its immutable borrowed frame.

use serde::Deserialize;
use serde::de::{self, DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};

use super::{PackBinaryError, PackBinaryItemEntry, PackBinaryView};

const INVALID_PROJECTION: &str =
    "canonical JSON must contain data.pack.items with string content fields";
const COUNT_MISMATCH: &str = "binary item count differs from the canonical response";
const CONTENT_MISMATCH: &str = "binary item bytes differ from the canonical response";

// Deserialize field names without allocating a String for every map key.
// Escaped JSON keys are still compared after decoding, including duplicates.
#[derive(Clone, Copy, Deserialize, Eq, PartialEq)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
    Data,
    Pack,
    Items,
    Content,
    #[serde(other)]
    Other,
}

struct Check<'frame> {
    bytes: &'frame [u8],
    entries: &'frame [PackBinaryItemEntry],
    failure: Option<PackBinaryError>,
}

impl Check<'_> {
    fn reject<E: de::Error>(&mut self, index: Option<usize>, reason: &'static str) -> E {
        self.failure = Some(PackBinaryError::InvalidItemContent { index, reason });
        E::custom("invalid binary pack item projection")
    }
}

// Each object has exactly one required projection field. All other fields
// retain the previous derived-struct behavior: validate JSON, then ignore.
struct Object<'check, 'frame> {
    check: &'check mut Check<'frame>,
    field: Field,
    index: usize,
}

impl<'de> DeserializeSeed<'de> for Object<'_, '_> {
    type Value = ();

    fn deserialize<D: de::Deserializer<'de>>(self, decoder: D) -> Result<(), D::Error> {
        if self.field == Field::Content && self.index >= self.check.entries.len() {
            // The frame table is already geometry-checked. An extra canonical
            // item cannot be legitimate, regardless of the size of its payload.
            return Err(self.check.reject(None, COUNT_MISMATCH));
        }
        decoder.deserialize_struct(
            "CanonicalProjection",
            &["data", "pack", "items", "content"],
            self,
        )
    }
}

impl<'de> Visitor<'de> for Object<'_, '_> {
    type Value = ();

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("a canonical pack projection object")
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
        let mut seen = false;
        while let Some(field) = map.next_key::<Field>()? {
            if field == self.field {
                if seen {
                    return Err(de::Error::custom("duplicate canonical projection field"));
                }
                seen = true;
                map.next_value_seed(FieldValue(Object {
                    check: &mut *self.check,
                    field: self.field,
                    index: self.index,
                }))?;
            } else {
                map.next_value::<IgnoredAny>()?;
            }
        }
        if seen {
            Ok(())
        } else {
            Err(de::Error::custom("missing canonical projection field"))
        }
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<(), A::Error> {
        // Preserve the one-field positional representation accepted by the
        // former derived structs. The normal renderer still emits objects.
        if sequence
            .next_element_seed(FieldValue(Object {
                check: &mut *self.check,
                field: self.field,
                index: self.index,
            }))?
            .is_none()
            || sequence.next_element::<IgnoredAny>()?.is_some()
        {
            return Err(de::Error::custom(
                "invalid canonical projection field count",
            ));
        }
        Ok(())
    }
}

struct FieldValue<'check, 'frame>(Object<'check, 'frame>);

impl<'de> DeserializeSeed<'de> for FieldValue<'_, '_> {
    type Value = ();

    fn deserialize<D: de::Deserializer<'de>>(self, decoder: D) -> Result<(), D::Error> {
        match self.0.field {
            Field::Data => Object {
                field: Field::Pack,
                ..self.0
            }
            .deserialize(decoder),
            Field::Pack => Object {
                field: Field::Items,
                ..self.0
            }
            .deserialize(decoder),
            Field::Items => Items {
                check: self.0.check,
            }
            .deserialize(decoder),
            Field::Content => Content {
                check: self.0.check,
                index: self.0.index,
            }
            .deserialize(decoder),
            Field::Other => Err(de::Error::custom("unknown canonical projection field")),
        }
    }
}

struct Items<'check, 'frame> {
    check: &'check mut Check<'frame>,
}

impl<'de> DeserializeSeed<'de> for Items<'_, '_> {
    type Value = ();

    fn deserialize<D: de::Deserializer<'de>>(self, decoder: D) -> Result<(), D::Error> {
        decoder.deserialize_seq(self)
    }
}

impl<'de> Visitor<'de> for Items<'_, '_> {
    type Value = ();

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("the ordered canonical pack items")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<(), A::Error> {
        let mut index = 0;
        while sequence
            .next_element_seed(Object {
                check: &mut *self.check,
                field: Field::Content,
                index,
            })?
            .is_some()
        {
            index += 1;
        }
        if index != self.check.entries.len() {
            return Err(self.check.reject(None, COUNT_MISMATCH));
        }
        Ok(())
    }
}

struct Content<'check, 'frame> {
    check: &'check mut Check<'frame>,
    index: usize,
}

impl<'de> DeserializeSeed<'de> for Content<'_, '_> {
    type Value = ();

    fn deserialize<D: de::Deserializer<'de>>(self, decoder: D) -> Result<(), D::Error> {
        decoder.deserialize_str(self)
    }
}

impl<'de> Visitor<'de> for Content<'_, '_> {
    type Value = ();

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("byte-exact canonical item content")
    }

    fn visit_str<E: de::Error>(self, text: &str) -> Result<(), E> {
        // Bounds and contiguity were already checked by PackBinaryView::parse;
        // Object checked the item index before deserializing this payload.
        // Do not call item_slice here: it invokes this cached validation.
        let entry = &self.check.entries[self.index];
        if text.as_bytes() != &self.check.bytes[entry.offset..entry.offset + entry.len] {
            return Err(self.check.reject(Some(self.index), CONTENT_MISMATCH));
        }
        Ok(())
    }
}

pub(super) fn validate(view: &PackBinaryView<'_>) -> Result<(), PackBinaryError> {
    let json = view.canonical_json()?;
    let mut check = Check {
        bytes: view.bytes,
        entries: &view.entries,
        failure: None,
    };
    let mut decoder = serde_json::Deserializer::from_str(json);
    let result = Object {
        check: &mut check,
        field: Field::Data,
        index: 0,
    }
    .deserialize(&mut decoder)
    .and_then(|()| decoder.end());
    result.map_err(|_| {
        check
            .failure
            .unwrap_or(PackBinaryError::InvalidItemContent {
                index: None,
                reason: INVALID_PROJECTION,
            })
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pack::binary::{
        PACK_BINARY_HEADER_LEN, PACK_BINARY_ITEM_TABLE_ENTRY_LEN, serialize_pack_binary,
    };

    fn json(contents: &[&str]) -> String {
        serde_json::json!({
            "schema": "ee.response.v2",
            "data": {
                "pack": {
                    "items": contents.iter().enumerate().map(|(index, content)| {
                        serde_json::json!({
                            "entityKind": if index == 0 { "memory" } else { "evidence_span" },
                            "content": content,
                        })
                    }).collect::<Vec<_>>()
                }
            }
        })
        .to_string()
    }

    fn frame(contents: &[&str]) -> Vec<u8> {
        let slices = contents
            .iter()
            .map(|item| item.as_bytes())
            .collect::<Vec<_>>();
        serialize_pack_binary(&json(contents), &slices, 0)
    }

    #[test]
    fn verifies_mixed_items_including_escaped_unicode_and_empty_content() {
        let contents = ["release checks", "café\n\"quoted\" \\ evidence", ""];
        let bytes = frame(&contents);
        let view = PackBinaryView::parse_verified(&bytes).expect("verified mixed frame");
        for (index, content) in contents.iter().enumerate() {
            let slice = view.item_slice(index).expect("verified zero-copy item");
            assert_eq!(slice, content.as_bytes());
            assert_eq!(slice.as_ptr(), bytes[view.entries[index].offset..].as_ptr());
        }
    }

    #[test]
    fn rejects_item_tampering_without_changing_the_json_hash() {
        let mut bytes = frame(&["alpha", "bravo"]);
        let blob = PACK_BINARY_HEADER_LEN + 2 * PACK_BINARY_ITEM_TABLE_ENTRY_LEN;
        bytes[blob] ^= 1;
        let view = PackBinaryView::parse(&bytes).expect("unchanged canonical hash");
        assert!(matches!(
            view.item_slice(0),
            Err(PackBinaryError::InvalidItemContent { index: Some(0), .. })
        ));
        assert!(PackBinaryView::parse_verified(&bytes).is_err());
    }

    #[test]
    fn refuses_every_item_if_a_later_item_is_corrupt() {
        let mut bytes = frame(&["alpha", "bravo"]);
        let second = PACK_BINARY_HEADER_LEN + 2 * PACK_BINARY_ITEM_TABLE_ENTRY_LEN + 5;
        bytes[second] ^= 1;
        let view = PackBinaryView::parse(&bytes).expect("valid frame geometry");
        assert!(matches!(
            view.item_slice(0),
            Err(PackBinaryError::InvalidItemContent { index: Some(1), .. })
        ));
        assert!(view.item_slice(1).is_err());
    }

    #[test]
    fn rejects_missing_extra_and_reordered_item_projections() {
        let canonical = json(&["alpha", "bravo"]);
        for items in [
            vec![&b"alpha"[..]],
            vec![&b"alpha"[..], &b"bravo"[..], &b"extra"[..]],
            vec![&b"bravo"[..], &b"alpha"[..]],
        ] {
            let bytes = serialize_pack_binary(&canonical, &items, 0);
            let view = PackBinaryView::parse(&bytes).expect("valid frame geometry");
            assert!(view.validate_item_contents().is_err());
        }
    }

    #[test]
    fn rejects_invalid_or_ambiguous_canonical_content_shapes() {
        for canonical in [
            "not JSON",
            "{}",
            r#"{"data":{"pack":{"items":null}}}"#,
            r#"{"data":{"pack":{"items":[{}]}}}"#,
            r#"{"data":{"pack":{"items":[{"content":7}]}}}"#,
            r#"{"data":{"pack":{"items":[],"items":[]}}}"#,
            r#"{"data":{"pack":{"items":[{"content":"alpha","content":"bravo"}]}}}"#,
        ] {
            let bytes = serialize_pack_binary(canonical, &[], 0);
            let view = PackBinaryView::parse(&bytes).expect("hash and geometry only");
            assert!(matches!(
                view.validate_item_contents(),
                Err(PackBinaryError::InvalidItemContent { .. })
            ));
        }
    }

    #[test]
    fn valid_empty_pack_verifies_without_item_reads() {
        let bytes = frame(&[]);
        let view = PackBinaryView::parse_verified(&bytes).expect("empty context pack");
        assert_eq!(view.item_count(), 0);
        assert!(view.validate_item_contents().is_ok());
        assert!(matches!(
            view.item_slice(0),
            Err(PackBinaryError::InvalidOffset { .. })
        ));
    }

    #[test]
    fn caches_success_and_failure_without_retaining_decoded_item_copies() {
        let mut bytes = frame(&["alpha"]);
        let view = PackBinaryView::parse(&bytes).expect("frame");
        assert!(view.item_validation.get().is_none());
        assert!(view.item_slice(0).is_ok());
        assert_eq!(view.item_validation.get(), Some(&Ok(())));
        assert!(view.item_slice(0).is_ok());
        drop(view);

        bytes[PACK_BINARY_HEADER_LEN + PACK_BINARY_ITEM_TABLE_ENTRY_LEN] ^= 1;
        let view = PackBinaryView::parse(&bytes).expect("unchanged canonical hash");
        assert!(view.item_validation.get().is_none());
        let first_error = view.item_slice(0).expect_err("corrupt item");
        assert_eq!(view.item_validation.get(), Some(&Err(first_error.clone())));
        assert_eq!(view.item_slice(0).expect_err("cached verdict"), first_error);
    }

    #[test]
    fn reports_integrity_failures_without_disclosing_item_text() {
        let bytes = serialize_pack_binary(&json(&["private-original"]), &[b"private-tampered"], 0);
        let view = PackBinaryView::parse(&bytes).expect("valid frame geometry");
        let error = view.item_slice(0).expect_err("different content");
        assert_eq!(error.code(), "pack_bin_content_hash_mismatch");
        let message = error.to_string();
        assert!(!message.contains("private-original"));
        assert!(!message.contains("private-tampered"));
    }

    #[test]
    fn large_mixed_pack_keeps_borrowed_item_slices_and_one_cached_verdict() {
        let content = ["ordinary source text", "café\n\"quoted\" \\ evidence", ""];
        let contents = (0..2048)
            .map(|index| content[index % content.len()])
            .collect::<Vec<_>>();
        let bytes = frame(&contents);
        let view = PackBinaryView::parse_verified(&bytes).expect("large mixed pack");
        assert_eq!(view.item_count(), contents.len());
        for (index, expected) in contents.iter().enumerate() {
            let actual = view.item_slice(index).expect("verified item");
            assert_eq!(actual, expected.as_bytes());
            assert_eq!(
                actual.as_ptr(),
                bytes[view.entries[index].offset..].as_ptr()
            );
        }
        assert_eq!(view.item_validation.get(), Some(&Ok(())));
    }

    #[test]
    fn extra_item_is_refused_before_its_payload_is_deserialized() {
        let bytes = frame(&[]);
        let view = PackBinaryView::parse(&bytes).expect("empty frame");
        let mut check = Check {
            bytes: view.bytes,
            entries: &view.entries,
            failure: None,
        };
        let entries = std::iter::once_with(|| -> (&'static str, &'static str) {
            panic!("an excess item payload must never be visited")
        });
        let decoder = serde::de::value::MapDeserializer::<_, serde::de::value::Error>::new(entries);
        assert!(
            Object {
                check: &mut check,
                field: Field::Content,
                index: 0,
            }
            .deserialize(decoder)
            .is_err()
        );
        assert_eq!(
            check.failure,
            Some(PackBinaryError::InvalidItemContent {
                index: None,
                reason: COUNT_MISMATCH,
            })
        );
    }

    #[test]
    fn escaped_keys_unknown_metadata_and_positional_structs_remain_compatible() {
        for canonical in [
            r#"{"d\u0061ta":{"pack":{"it\u0065ms":[{"cont\u0065nt":"alpha"}]}}}"#,
            r#"{"metadata":{"nested":[null,true,7]},"data":{"ignored":"value","pack":{"items":[{"metadata":[1,2],"content":"alpha"}],"tail":false}}}"#,
            r#"[[[[["alpha"]]]]]"#,
        ] {
            let bytes = serialize_pack_binary(canonical, &[b"alpha"], 0);
            let view = PackBinaryView::parse_verified(&bytes).expect("compatible projection");
            assert_eq!(view.item_slice(0).expect("content"), b"alpha");
        }
    }

    #[test]
    fn valid_item_prefix_never_hides_late_syntax_duplicates_or_trailing_documents() {
        for canonical in [
            r#"{"data":{"pack":{"items":[{"content":"alpha"}]}},"tail":[}"#,
            r#"{"data":{"pack":{"items":[{"content":"alpha"}]}},"data":{}}"#,
            r#"{"data":{"pack":{"items":[{"content":"alpha"}]},"pack":{}}}"#,
            r#"{"data":{"pack":{"items":[{"content":"alpha","cont\u0065nt":"alpha"}]}}}"#,
            r#"{"data":{"pack":{"items":[{"content":"alpha"}]}}} {}"#,
            r#"[[[[["alpha","extra field"]]]]]"#,
        ] {
            let bytes = serialize_pack_binary(canonical, &[b"alpha"], 0);
            let view = PackBinaryView::parse(&bytes).expect("hash-checked frame");
            assert!(view.item_slice(0).is_err());
            assert!(PackBinaryView::parse_verified(&bytes).is_err());
        }
    }
}