eidetic-engine 0.15.1

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
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! Structured test logging harness (bead bd-17c65.10.1 / J1).
//!
//! Emits JSON-line events to the path in `EE_TEST_LOG_PATH` so every test —
//! Rust unit, Rust integration, and bash e2e — produces a uniform, agent-
//! parseable record of what happened. Companion bash harness lives at
//! `scripts/lib/e2e_logger.sh`; both follow `docs/schemas/test_event_v1.json`.
//!
//! Design notes (see bead description for full context):
//!
//! - JSON-line so consumers can `jq` over the stream.
//! - BLAKE3 hashes of stdin/stdout so we never log secret bytes.
//! - `EE_TEST_LOG_PATH` unset → all calls no-op (opt-in by design).
//! - `EE_TEST_LOG_LEVEL` (`quiet|normal|verbose`) controls filtering.
//! - Events are appended atomically (one full line per `write` call) so
//!   multiple processes can share a log file without partial-line interleave.
//! - The crate forbids `unsafe`, so unit tests use `log_event_to`
//!   (explicit-path entry point) instead of mutating `EE_TEST_LOG_PATH`. The
//!   integration smoke test (`tests/support_logging_smoke.rs`) spawns
//!   subprocesses for env-based validation.

use chrono::{DateTime, Utc};
use serde::Serialize;
use serde_json::{Map, Value};
use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use std::time::Instant;

use crate::config::{EnvVar, read_env_var, read_env_var_os};
use crate::policy::redact_secret_like_content;

pub use crate::models::TEST_EVENT_SCHEMA_V1;

/// Env var naming the JSON-line log file. Unset → harness no-ops.
pub const ENV_TEST_LOG_PATH: &str = EnvVar::TestLogPath.name();

/// Env var controlling verbosity (`quiet|normal|verbose`).
pub const ENV_TEST_LOG_LEVEL: &str = EnvVar::TestLogLevel.name();
/// Env var naming the current test scenario.
pub const ENV_TEST_LOG_TEST_ID: &str = EnvVar::TestLogTestId.name();
/// S7 benchmark gate degraded code for measurements beyond tolerance.
pub const SWARM_SCALE_BUDGET_EXCEEDED_CODE: &str = "swarm_scale_budget_exceeded";
/// S7 benchmark gate degraded code for non-identical normalized outputs.
pub const SWARM_SCALE_NONDETERMINISM_CODE: &str = "swarm_scale_nondeterminism";

/// Event kinds emitted by the harness. `timer_lap` is suppressed at the
/// `normal` level; everything else is always emitted when a log path is
/// configured (modulo level-specific drops in `quiet` mode).
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EventKind {
    /// A command is about to run.
    CommandStart,
    /// A command finished, with exit code + duration + I/O hashes.
    CommandEnd,
    /// An assertion succeeded.
    AssertOk,
    /// An assertion failed (with a free-form `expected`/`actual` payload).
    AssertFail,
    /// A golden comparison was performed (`matched` lives in `fields`).
    GoldenCompare,
    /// An intermediate timer reading (suppressed at level=normal).
    TimerLap,
    /// A free-form note (e.g. test setup phase markers).
    Note,
    /// Pack-hash subcomponent hashes for determinism debugging.
    PackHashComponents,
    /// Observed DB/index generations for staleness debugging.
    DbGenerationObserved,
    /// Volatile fields stripped before determinism hashing.
    VolatileStrip,
    /// Test-event schema gate summary.
    SchemaGate,
    /// Output field selector application summary.
    FieldSelector,
    /// Performance benchmark iteration summary emitted by scripts/bench.sh.
    BenchIteration,
    /// Verification artifact manifest emitted by the J1 bash harness.
    ArtifactManifest,
    /// Determinism-lint gate summary emitted by the N4.4 e2e driver.
    LintDeterminism,
    /// Determinism proptest summary emitted by the N4.5 e2e driver.
    ProptestRun,
    /// Redaction application summary emitted by redaction matrix drivers.
    RedactionApply,
}

impl EventKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CommandStart => "command_start",
            Self::CommandEnd => "command_end",
            Self::AssertOk => "assert_ok",
            Self::AssertFail => "assert_fail",
            Self::GoldenCompare => "golden_compare",
            Self::TimerLap => "timer_lap",
            Self::Note => "note",
            Self::PackHashComponents => "pack_hash_components",
            Self::DbGenerationObserved => "db_generation_observed",
            Self::VolatileStrip => "volatile_strip",
            Self::SchemaGate => "schema_gate",
            Self::FieldSelector => "field_selector",
            Self::BenchIteration => "bench_iteration",
            Self::ArtifactManifest => "artifact_manifest",
            Self::LintDeterminism => "lint_determinism",
            Self::ProptestRun => "proptest_run",
            Self::RedactionApply => "redaction_apply",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 17] {
        [
            Self::CommandStart,
            Self::CommandEnd,
            Self::AssertOk,
            Self::AssertFail,
            Self::GoldenCompare,
            Self::TimerLap,
            Self::Note,
            Self::PackHashComponents,
            Self::DbGenerationObserved,
            Self::VolatileStrip,
            Self::SchemaGate,
            Self::FieldSelector,
            Self::BenchIteration,
            Self::ArtifactManifest,
            Self::LintDeterminism,
            Self::ProptestRun,
            Self::RedactionApply,
        ]
    }
}

/// Verbosity filter parsed from `EE_TEST_LOG_LEVEL`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    Quiet,
    Normal,
    Verbose,
}

impl LogLevel {
    fn parse(raw: Option<OsString>) -> Self {
        match raw.as_deref().and_then(|s| s.to_str()) {
            Some("quiet") => Self::Quiet,
            Some("verbose") => Self::Verbose,
            _ => Self::Normal,
        }
    }

    /// Predicate: does this level emit `kind`?
    #[must_use]
    pub const fn allows(self, kind: EventKind) -> bool {
        match self {
            Self::Quiet => matches!(
                kind,
                EventKind::CommandEnd
                    | EventKind::AssertFail
                    | EventKind::GoldenCompare
                    | EventKind::LintDeterminism
                    | EventKind::ProptestRun
                    | EventKind::RedactionApply
            ),
            Self::Normal => !matches!(kind, EventKind::TimerLap),
            Self::Verbose => true,
        }
    }
}

/// A single test event. Matches `docs/schemas/test_event_v1.json` exactly.
///
/// `fields` is a free-form map for per-test metadata that doesn't fit the
/// fixed columns (e.g. `bytes_per_token`, `arm_lexical_hits`).
#[derive(Debug, Serialize)]
pub struct TestEvent {
    pub schema: &'static str,
    pub ts: DateTime<Utc>,
    pub test_id: String,
    pub kind: EventKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdin_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdout_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr_excerpt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elapsed_ms: Option<f64>,
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub fields: Map<String, Value>,
}

impl TestEvent {
    /// Construct an event with the schema + timestamp filled in.
    #[must_use]
    pub fn new(test_id: impl Into<String>, kind: EventKind) -> Self {
        Self {
            schema: TEST_EVENT_SCHEMA_V1,
            ts: Utc::now(),
            test_id: test_id.into(),
            kind,
            command: None,
            args: Vec::new(),
            stdin_hash: None,
            stdout_hash: None,
            stderr_excerpt: None,
            exit_code: None,
            elapsed_ms: None,
            fields: Map::new(),
        }
    }

    /// Attach a free-form field.
    #[must_use]
    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.fields.insert(key.into(), value.into());
        self
    }
}

/// Resolve the configured log path (env-based). `None` when unset.
#[must_use]
pub fn log_path() -> Option<PathBuf> {
    read_env_var_os(EnvVar::TestLogPath).map(PathBuf::from)
}

/// Current log level (env-based). Cheap; called per-emit so tests can flip
/// the env mid-run via subprocess `Command::env` (NOT in-process mutation
/// because this crate forbids `unsafe`).
#[must_use]
pub fn log_level() -> LogLevel {
    LogLevel::parse(read_env_var_os(EnvVar::TestLogLevel))
}

/// Resolve the current test id, falling back to a stable caller-supplied id.
#[must_use]
pub fn test_id_or(default: impl Into<String>) -> String {
    read_env_var(EnvVar::TestLogTestId).unwrap_or_else(|| default.into())
}

// Lock keeps appends atomic in-process; cross-process appends rely on the
// OS-level file append semantics (single `write` syscall per line on POSIX).
static WRITE_LOCK: Mutex<()> = Mutex::new(());

/// Append a single event to an explicit path with an explicit level. The
/// testable core — wrappers below add env-based discovery.
///
/// Returns `true` when the event was written, `false` when filtered or
/// suppressed by an I/O error. Best-effort — never panics in tests.
pub fn log_event_to(path: &Path, level: LogLevel, event: &TestEvent) -> bool {
    if !level.allows(event.kind) {
        return false;
    }
    let Ok(serialized) = serde_json::to_string(event) else {
        return false;
    };
    let _guard = WRITE_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if test_log_path_has_symlink_component(path).unwrap_or(true) {
        return false;
    }
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if test_log_path_has_symlink_component(path).unwrap_or(true) {
        return false;
    }
    if !test_log_final_path_is_regular_or_missing(path) {
        return false;
    }
    let Ok(mut file) = open_test_log_for_append(path) else {
        return false;
    };
    write_serialized_event_line(&mut file, &serialized).is_ok()
}

fn write_serialized_event_line<W: Write>(writer: &mut W, serialized: &str) -> io::Result<()> {
    let mut line = String::with_capacity(serialized.len().saturating_add(1));
    line.push_str(serialized);
    line.push('\n');
    writer.write_all(line.as_bytes())
}

fn open_test_log_for_append(path: &Path) -> io::Result<fs::File> {
    let mut options = OpenOptions::new();
    options.create(true).append(true);
    configure_test_log_append_options(&mut options);
    options.open(path)
}

#[cfg(all(unix, not(any(target_os = "espidf", target_os = "horizon"))))]
fn configure_test_log_append_options(options: &mut OpenOptions) {
    use std::os::unix::fs::OpenOptionsExt;

    options.custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32);
}

#[cfg(not(all(unix, not(any(target_os = "espidf", target_os = "horizon")))))]
fn configure_test_log_append_options(_options: &mut OpenOptions) {}

fn test_log_final_path_is_regular_or_missing(path: &Path) -> bool {
    match fs::symlink_metadata(path) {
        Ok(metadata) => metadata.file_type().is_file(),
        Err(error) if error.kind() == io::ErrorKind::NotFound => true,
        Err(_) => false,
    }
}

fn test_log_path_has_symlink_component(path: &Path) -> io::Result<bool> {
    let mut current = PathBuf::new();
    for component in path.components() {
        current.push(component.as_os_str());
        #[cfg(windows)]
        if matches!(
            component,
            std::path::Component::Prefix(_) | std::path::Component::RootDir
        ) {
            continue;
        }
        #[cfg(not(windows))]
        if matches!(component, std::path::Component::RootDir) {
            continue;
        }
        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => return Ok(true),
            Ok(_) => {}
            Err(error)
                if matches!(
                    error.kind(),
                    io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
                ) =>
            {
                return Ok(false);
            }
            Err(error) => return Err(error),
        }
    }
    Ok(false)
}

/// Append a single event to the configured log file. No-op when unconfigured.
pub fn log_event(event: TestEvent) {
    let Some(path) = log_path() else { return };
    let _ = log_event_to(&path, log_level(), &event);
}

/// Compute BLAKE3 of a byte slice as `blake3:<64-hex>`. Used for stdin/stdout
/// so logs stay small and never carry content bytes.
#[must_use]
pub fn hash_bytes(bytes: &[u8]) -> String {
    format!("blake3:{}", blake3::hash(bytes).to_hex())
}

/// Redact and truncate stderr to at most `cap` bytes (default cap is the
/// spec's 4096). Stderr often carries diagnostics plus copied command output,
/// so redaction runs before truncation to avoid leaking partially capped secret
/// values into structured logs.
#[must_use]
pub fn excerpt_stderr(stderr: &[u8], cap: usize) -> String {
    let text = String::from_utf8_lossy(stderr);
    let redacted = redact_secret_like_content(&text).content;
    truncate_utf8_bytes(&redacted, cap)
}

fn truncate_utf8_bytes(value: &str, cap: usize) -> String {
    if value.len() <= cap {
        return value.to_string();
    }
    let mut end = cap;
    while !value.is_char_boundary(end) {
        end = end.saturating_sub(1);
    }
    value[..end].to_string()
}

/// Wraps `std::process::Command` so command-start/end events are emitted
/// automatically. Use this in tests instead of raw `Command::new(...)`.
pub struct CommandRecorder<'a> {
    inner: &'a mut Command,
    test_id: String,
    command_label: String,
    args: Vec<String>,
    stdin_bytes: Option<Vec<u8>>,
    stderr_cap: usize,
}

impl<'a> CommandRecorder<'a> {
    /// Wrap a command for recording. The label is the human/agent name (e.g.
    /// `"ee remember"`), distinct from the command's argv\[0\].
    pub fn new(
        test_id: impl Into<String>,
        command_label: impl Into<String>,
        command: &'a mut Command,
    ) -> Self {
        Self {
            inner: command,
            test_id: test_id.into(),
            command_label: command_label.into(),
            args: Vec::new(),
            stdin_bytes: None,
            stderr_cap: 4096,
        }
    }

    /// Record the arg list for the event; mirrors what was passed to the
    /// underlying `Command`.
    #[must_use]
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for arg in args {
            self.args.push(arg.as_ref().to_string());
        }
        self
    }

    /// Attach stdin bytes; the recorder hashes them for the event.
    #[must_use]
    pub fn stdin(mut self, bytes: impl Into<Vec<u8>>) -> Self {
        self.stdin_bytes = Some(bytes.into());
        self
    }

    /// Override the stderr excerpt cap.
    #[must_use]
    pub const fn stderr_cap(mut self, cap: usize) -> Self {
        self.stderr_cap = cap;
        self
    }

    /// Run the command, emit start/end events, return the `Output`.
    ///
    /// # Errors
    ///
    /// Returns the error from `Command::output()` (or the spawn/IO equivalent
    /// when stdin is piped) when the process cannot be spawned.
    pub fn run(self) -> std::io::Result<std::process::Output> {
        let mut start_event = TestEvent::new(self.test_id.clone(), EventKind::CommandStart)
            .with_field("command_label", Value::String(self.command_label.clone()))
            .with_field(
                "args",
                Value::Array(self.args.iter().cloned().map(Value::String).collect()),
            );
        if let Some(ref stdin) = self.stdin_bytes {
            start_event = start_event.with_field("stdin_hash", Value::String(hash_bytes(stdin)));
        }
        log_event(start_event);

        let started = Instant::now();
        let output = if let Some(stdin) = self.stdin_bytes {
            use std::process::Stdio;
            self.inner
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());
            let mut child = self.inner.spawn()?;
            if let Some(mut writer) = child.stdin.take() {
                writer.write_all(&stdin)?;
            }
            child.wait_with_output()?
        } else {
            self.inner.output()?
        };
        let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;

        let mut end_event = TestEvent::new(self.test_id, EventKind::CommandEnd)
            .with_field("command_label", Value::String(self.command_label))
            .with_field(
                "args",
                Value::Array(self.args.into_iter().map(Value::String).collect()),
            )
            .with_field("stdout_hash", Value::String(hash_bytes(&output.stdout)))
            .with_field(
                "stderr_excerpt",
                Value::String(excerpt_stderr(&output.stderr, self.stderr_cap)),
            );
        if let Some(code) = output.status.code() {
            end_event.exit_code = Some(code);
        }
        end_event.elapsed_ms = Some(elapsed_ms);
        log_event(end_event);

        Ok(output)
    }
}

/// Emit an `AssertOk` event with a label.
pub fn assert_ok(test_id: impl Into<String>, label: impl Into<String>) {
    log_event(
        TestEvent::new(test_id, EventKind::AssertOk)
            .with_field("label", Value::String(label.into())),
    );
}

/// Emit an `AssertFail` event with label + expected + actual.
pub fn assert_fail(
    test_id: impl Into<String>,
    label: impl Into<String>,
    expected: impl Into<Value>,
    actual: impl Into<Value>,
) {
    log_event(
        TestEvent::new(test_id, EventKind::AssertFail)
            .with_field("label", Value::String(label.into()))
            .with_field("expected", expected)
            .with_field("actual", actual),
    );
}

/// Emit a golden-comparison event with `matched` in `fields`.
pub fn golden_compare(
    test_id: impl Into<String>,
    name: impl Into<String>,
    generated_path: &Path,
    expected_path: &Path,
    matched: bool,
) {
    log_event(
        TestEvent::new(test_id, EventKind::GoldenCompare)
            .with_field("name", Value::String(name.into()))
            .with_field(
                "generated_path",
                Value::String(generated_path.display().to_string()),
            )
            .with_field(
                "expected_path",
                Value::String(expected_path.display().to_string()),
            )
            .with_field("matched", Value::Bool(matched)),
    );
}

/// Emit a free-form note.
pub fn note(test_id: impl Into<String>, message: impl Into<String>) {
    log_event(
        TestEvent::new(test_id, EventKind::Note)
            .with_field("message", Value::String(message.into())),
    );
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::Value;

    fn read_lines(path: &Path) -> Vec<Value> {
        std::fs::read_to_string(path)
            .expect("read log")
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| serde_json::from_str::<Value>(l).expect("valid json"))
            .collect()
    }

    struct CountingWriter {
        write_calls: usize,
        bytes: Vec<u8>,
    }

    impl Write for CountingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.write_calls = self.write_calls.saturating_add(1);
            self.bytes.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn log_event_to_writes_jsonl() {
        let tmp = tempfile::NamedTempFile::new().expect("tempfile");
        log_event_to(
            tmp.path(),
            LogLevel::Normal,
            &TestEvent::new("smoke", EventKind::Note)
                .with_field("message", Value::String("hello".into())),
        );
        log_event_to(
            tmp.path(),
            LogLevel::Normal,
            &TestEvent::new("smoke", EventKind::AssertOk)
                .with_field("label", Value::String("pass".into())),
        );
        let lines = read_lines(tmp.path());
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0]["schema"], TEST_EVENT_SCHEMA_V1);
        assert_eq!(lines[0]["kind"], "note");
        assert_eq!(lines[0]["fields"]["message"], "hello");
        assert_eq!(lines[1]["kind"], "assert_ok");
    }

    #[test]
    fn serialized_event_line_is_written_as_one_buffer() {
        let mut writer = CountingWriter {
            write_calls: 0,
            bytes: Vec::new(),
        };

        write_serialized_event_line(&mut writer, r#"{"kind":"note"}"#)
            .expect("write serialized event line");

        assert_eq!(writer.write_calls, 1);
        assert_eq!(writer.bytes, b"{\"kind\":\"note\"}\n");
    }

    #[test]
    fn test_log_symlink_scan_accepts_absolute_roots() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let canonical =
            std::fs::canonicalize(tmp.path()).unwrap_or_else(|_| tmp.path().to_path_buf());
        let log_path = canonical.join("events.jsonl");

        assert!(
            !test_log_path_has_symlink_component(&log_path)
                .expect("absolute test-log path should be inspectable"),
            "absolute test-log paths should not fail during prefix/root preflight"
        );
    }

    #[cfg(unix)]
    #[test]
    fn log_event_to_rejects_symlinked_parent_path() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let workspace = tmp.path().join("workspace");
        let real_logs = tmp.path().join("real-logs");
        std::fs::create_dir_all(&workspace).expect("workspace");
        std::fs::create_dir_all(&real_logs).expect("real logs");
        std::os::unix::fs::symlink(&real_logs, workspace.join("logs")).expect("symlink logs");
        let log_path = workspace.join("logs").join("events.jsonl");

        assert!(
            !log_event_to(
                &log_path,
                LogLevel::Normal,
                &TestEvent::new("smoke", EventKind::Note)
            ),
            "test-event logging should reject symlinked parents"
        );
        assert!(
            !real_logs.join("events.jsonl").exists(),
            "test-event logging must not write through symlinked parent"
        );
    }

    #[cfg(unix)]
    #[test]
    fn log_event_to_rejects_symlinked_log_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let log_dir = tmp.path().join("logs");
        std::fs::create_dir_all(&log_dir).expect("log dir");
        let outside_log = tmp.path().join("outside.jsonl");
        std::fs::write(&outside_log, "outside\n").expect("outside log");
        let linked_log = log_dir.join("events.jsonl");
        std::os::unix::fs::symlink(&outside_log, &linked_log).expect("symlink log");

        assert!(
            !log_event_to(
                &linked_log,
                LogLevel::Normal,
                &TestEvent::new("smoke", EventKind::Note)
            ),
            "test-event logging should reject symlinked log files"
        );
        assert_eq!(
            std::fs::read_to_string(&outside_log).expect("outside content"),
            "outside\n",
            "test-event logging must not append through symlinked file"
        );
    }

    #[cfg(all(unix, not(any(target_os = "espidf", target_os = "horizon"))))]
    #[test]
    fn open_test_log_for_append_rejects_symlinked_final_path() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let outside_log = tmp.path().join("outside.jsonl");
        std::fs::write(&outside_log, "outside\n").expect("outside log");
        let linked_log = tmp.path().join("events.jsonl");
        std::os::unix::fs::symlink(&outside_log, &linked_log).expect("symlink log");

        assert!(
            open_test_log_for_append(&linked_log).is_err(),
            "test-event log append open should not follow final symlinks"
        );
        assert_eq!(
            std::fs::read_to_string(&outside_log).expect("outside content"),
            "outside\n",
            "test-event log append open must not mutate the linked target"
        );
    }

    #[cfg(unix)]
    #[test]
    fn log_event_to_rejects_non_regular_log_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let log_path = tmp.path().join("events.jsonl");
        std::fs::create_dir(&log_path).expect("directory at log path");

        assert!(
            !log_event_to(
                &log_path,
                LogLevel::Normal,
                &TestEvent::new("smoke", EventKind::Note)
            ),
            "test-event logging should reject non-regular final log paths"
        );
        assert!(
            log_path.is_dir(),
            "test-event logging must leave a non-regular final path untouched"
        );
    }

    #[test]
    fn timer_lap_suppressed_at_normal_level() {
        let tmp = tempfile::NamedTempFile::new().expect("tempfile");
        log_event_to(
            tmp.path(),
            LogLevel::Normal,
            &TestEvent::new("smoke", EventKind::TimerLap),
        );
        log_event_to(
            tmp.path(),
            LogLevel::Normal,
            &TestEvent::new("smoke", EventKind::Note),
        );
        let lines = read_lines(tmp.path());
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0]["kind"], "note");
    }

    #[test]
    fn quiet_level_keeps_only_failure_events() {
        let tmp = tempfile::NamedTempFile::new().expect("tempfile");
        for kind in [
            EventKind::Note,
            EventKind::AssertOk,
            EventKind::AssertFail,
            EventKind::CommandEnd,
            EventKind::ProptestRun,
            EventKind::RedactionApply,
        ] {
            log_event_to(tmp.path(), LogLevel::Quiet, &TestEvent::new("smoke", kind));
        }
        let kinds: Vec<String> = read_lines(tmp.path())
            .iter()
            .map(|l| l["kind"].as_str().unwrap().to_string())
            .collect();
        assert_eq!(
            kinds,
            vec![
                "assert_fail",
                "command_end",
                "proptest_run",
                "redaction_apply"
            ]
        );
    }

    #[test]
    fn verbose_level_keeps_everything() {
        let tmp = tempfile::NamedTempFile::new().expect("tempfile");
        for kind in [EventKind::Note, EventKind::TimerLap, EventKind::AssertOk] {
            log_event_to(
                tmp.path(),
                LogLevel::Verbose,
                &TestEvent::new("smoke", kind),
            );
        }
        assert_eq!(read_lines(tmp.path()).len(), 3);
    }

    #[test]
    fn level_parse_recognizes_variants() {
        assert_eq!(LogLevel::parse(Some("quiet".into())), LogLevel::Quiet);
        assert_eq!(LogLevel::parse(Some("verbose".into())), LogLevel::Verbose);
        assert_eq!(LogLevel::parse(Some("normal".into())), LogLevel::Normal);
        assert_eq!(LogLevel::parse(Some("garbage".into())), LogLevel::Normal);
        assert_eq!(LogLevel::parse(None), LogLevel::Normal);
    }

    #[test]
    fn level_allows_table_is_correct() {
        // Quiet
        assert!(!LogLevel::Quiet.allows(EventKind::Note));
        assert!(!LogLevel::Quiet.allows(EventKind::AssertOk));
        assert!(LogLevel::Quiet.allows(EventKind::AssertFail));
        assert!(LogLevel::Quiet.allows(EventKind::CommandEnd));
        assert!(LogLevel::Quiet.allows(EventKind::GoldenCompare));
        // Normal
        assert!(LogLevel::Normal.allows(EventKind::Note));
        assert!(!LogLevel::Normal.allows(EventKind::TimerLap));
        // Verbose
        assert!(LogLevel::Verbose.allows(EventKind::TimerLap));
        assert!(LogLevel::Verbose.allows(EventKind::Note));
    }

    #[test]
    fn hash_bytes_is_blake3_prefixed_and_deterministic() {
        let h1 = hash_bytes(b"abc");
        let h2 = hash_bytes(b"abc");
        assert_eq!(h1, h2);
        assert!(h1.starts_with("blake3:"));
        assert_eq!(h1.len(), "blake3:".len() + 64);
        assert_ne!(hash_bytes(b"abc"), hash_bytes(b"def"));
    }

    #[test]
    fn excerpt_stderr_caps_to_size() {
        let huge = vec![b'x'; 10_000];
        assert_eq!(excerpt_stderr(&huge, 4096).len(), 4096);
        let small = b"short stderr";
        assert_eq!(excerpt_stderr(small, 4096), "short stderr");
    }

    #[test]
    fn excerpt_stderr_redacts_secret_like_values_before_capping() {
        let raw = b"failed: api_key=api-fixture-alpha password=password-fixture-beta bearer fake-curl-auth-header-token-0041";
        let excerpt = excerpt_stderr(raw, 4096);
        for forbidden in [
            "api-fixture-alpha",
            "password-fixture-beta",
            "fake-curl-auth-header-token-0041",
        ] {
            assert!(
                !excerpt.contains(forbidden),
                "stderr excerpt leaked {forbidden}: {excerpt}"
            );
        }
        for placeholder in [
            "[REDACTED:api_key]",
            "[REDACTED:password]",
            "[REDACTED:bearer_token]",
        ] {
            assert!(
                excerpt.contains(placeholder),
                "stderr excerpt missing {placeholder}: {excerpt}"
            );
        }

        let capped = excerpt_stderr(raw, 24);
        assert!(capped.len() <= 24);
        assert!(!capped.contains("api-fixture-alpha"));
    }

    #[test]
    fn empty_log_path_function_returns_none_when_unset() {
        // Read-only env access is safe even without unsafe.
        if read_env_var_os(EnvVar::TestLogPath).is_none() {
            assert!(log_path().is_none());
        } else {
            // Test runner has the var set externally — skip rather than fail.
        }
    }

    #[test]
    fn event_omits_empty_optional_fields_in_json() {
        let event = TestEvent::new("smoke", EventKind::Note);
        let json = serde_json::to_value(&event).unwrap();
        let obj = json.as_object().unwrap();
        assert!(!obj.contains_key("stdin_hash"));
        assert!(!obj.contains_key("stdout_hash"));
        assert!(!obj.contains_key("exit_code"));
        assert!(!obj.contains_key("elapsed_ms"));
        assert!(!obj.contains_key("fields"));
        assert!(obj.contains_key("schema"));
        assert!(obj.contains_key("ts"));
        assert!(obj.contains_key("test_id"));
        assert!(obj.contains_key("kind"));
    }
}