eidetic-engine 0.15.2

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
//! bd-1n0np.21.3 — `ee sandbox remember|import|curate|diff` What-If Sandbox CLI.
//!
//! A read-only overlay session over the live memory store: `remember`/`import`/
//! `curate` accumulate proposed, NON-DURABLE changes into a scratch session file
//! (`<workspace>/.ee/sandbox/<name>.json`, never the truth DB), and `diff` shows
//! the baseline-vs-overlay change set keyed by the deterministic overlay hash
//! (reusing the bd-1n0np.21.1 overlay evaluator). No durable memory mutation
//! happens here; the diff is explicitly marked `sandboxApproximation`
//! (bd-1n0np.21.2) so an agent never mistakes the change set for faithful
//! retrieval. Promotion to durable memory is the separate `ee remember`/`ee
//! curate`/`ee import` audited path.

use std::path::Path;

use clap::{Args, Subcommand};

use crate::core::memory::{RememberMemoryOptions, remember_memory};
use crate::core::sandbox::{
    SandboxDiffSurface, SandboxProposal, SandboxSession, assemble_sandbox_diff, content_hash,
    synthetic_memory_id,
};
use crate::db::DbConnection;
use crate::models::{DomainError, RESPONSE_SCHEMA_V2};

/// Subcommands for `ee sandbox` (no durable mutation).
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum SandboxCommand {
    /// Propose a new synthetic memory in the overlay (no durable write).
    Remember(SandboxRememberArgs),
    /// Propose importing a memory into the overlay (no durable write).
    Import(SandboxImportArgs),
    /// Propose hypothetically retiring existing memories (no durable write).
    Curate(SandboxCurateArgs),
    /// Show the baseline-vs-overlay diff for the session (no durable write).
    Diff(SandboxDiffArgs),
    /// Promote the session's additive proposals to durable memory through the
    /// normal audited remember path (the only durable-write subcommand).
    Apply(SandboxApplyArgs),
}

/// Shared `--session` selector (defaults to `default`).
fn session_name(explicit: &Option<String>) -> Result<String, DomainError> {
    let name = explicit
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .unwrap_or("default")
        .to_owned();
    if is_safe_session_name(&name) {
        Ok(name)
    } else {
        Err(DomainError::Usage {
            message: "Invalid sandbox session name: session names must be plain file-safe names."
                .to_owned(),
            repair: Some(
                "Use only ASCII letters, digits, '.', '_' or '-' and do not pass path separators."
                    .to_owned(),
            ),
        })
    }
}

fn is_safe_session_name(name: &str) -> bool {
    !matches!(name, "." | "..")
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}

#[derive(Clone, Debug, Eq, PartialEq, Args)]
pub struct SandboxRememberArgs {
    /// Proposed memory content.
    #[arg(value_name = "CONTENT")]
    pub content: String,
    /// Memory level (accepted for `ee remember` parity; the overlay is
    /// content-keyed, so it does not change the diff).
    #[arg(long, short = 'l', value_name = "LEVEL")]
    pub level: Option<String>,
    /// Memory kind (accepted for `ee remember` parity).
    #[arg(long, short = 'k', value_name = "KIND")]
    pub kind: Option<String>,
    /// Overlay session name.
    #[arg(long, value_name = "NAME")]
    pub session: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Args)]
pub struct SandboxImportArgs {
    /// Proposed imported memory content.
    #[arg(value_name = "CONTENT")]
    pub content: String,
    /// Memory level (accepted for `ee remember` parity).
    #[arg(long, short = 'l', value_name = "LEVEL")]
    pub level: Option<String>,
    /// Memory kind (accepted for `ee remember` parity).
    #[arg(long, short = 'k', value_name = "KIND")]
    pub kind: Option<String>,
    /// Overlay session name.
    #[arg(long, value_name = "NAME")]
    pub session: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Args)]
pub struct SandboxCurateArgs {
    /// Memory id(s) to hypothetically retire (repeatable).
    #[arg(long = "retire", value_name = "MEMORY_ID")]
    pub retire: Vec<String>,
    /// Overlay session name.
    #[arg(long, value_name = "NAME")]
    pub session: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Args)]
pub struct SandboxDiffArgs {
    /// Optional task/query context for the diff. Recorded for the agent; the
    /// change set is content-keyed, so retrieval impact stays a
    /// `sandboxApproximation` (bd-1n0np.21.2) rather than a live re-ranking.
    #[arg(value_name = "QUERY")]
    pub query: Option<String>,
    /// Overlay session name.
    #[arg(long, value_name = "NAME")]
    pub session: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Args)]
pub struct SandboxApplyArgs {
    /// Overlay session name.
    #[arg(long, value_name = "NAME")]
    pub session: Option<String>,
}

/// Outcome of a proposal command: the updated session + which session it is.
pub struct ProposeOutcome {
    pub session_name: String,
    pub session: SandboxSession,
    /// Non-fatal notes (e.g. the import injection-guard caveat).
    pub notes: Vec<String>,
}

fn load_session(workspace: &Path, name: &str) -> SandboxSession {
    SandboxSession::load(&SandboxSession::session_path(workspace, name))
}

fn save_session(workspace: &Path, name: &str, session: &SandboxSession) -> Result<(), DomainError> {
    session
        .save(&SandboxSession::session_path(workspace, name))
        .map_err(|error| DomainError::Storage {
            message: format!("Failed to persist sandbox session `{name}`: {error}"),
            repair: Some("Check that <workspace>/.ee/sandbox is writable.".to_owned()),
        })
}

/// `ee sandbox remember` — append a synthetic-memory proposal (no durable write).
pub fn propose_remember(
    workspace: &Path,
    args: &SandboxRememberArgs,
) -> Result<ProposeOutcome, DomainError> {
    let name = session_name(&args.session)?;
    let mut session = load_session(workspace, &name);
    session.proposals.push(SandboxProposal::Remember {
        memory_id: synthetic_memory_id(&args.content),
        content: args.content.clone(),
        content_hash: content_hash(&args.content),
        level: args.level.clone().unwrap_or_else(default_level),
        kind: args.kind.clone().unwrap_or_else(default_kind),
    });
    save_session(workspace, &name, &session)?;
    Ok(ProposeOutcome {
        session_name: name,
        session,
        notes: Vec::new(),
    })
}

fn default_level() -> String {
    "episodic".to_owned()
}

fn default_kind() -> String {
    "fact".to_owned()
}

/// `ee sandbox import` — append an import proposal (no durable write).
pub fn propose_import(
    workspace: &Path,
    args: &SandboxImportArgs,
) -> Result<ProposeOutcome, DomainError> {
    let name = session_name(&args.session)?;
    let mut session = load_session(workspace, &name);
    session.proposals.push(SandboxProposal::Import {
        memory_id: synthetic_memory_id(&args.content),
        content: args.content.clone(),
        content_hash: content_hash(&args.content),
        level: args.level.clone().unwrap_or_else(default_level),
        kind: args.kind.clone().unwrap_or_else(default_kind),
    });
    save_session(workspace, &name, &session)?;
    // bd-1n0np.21.3: imports must pass the injection guard (bd-1n0np.23.3) before
    // entering the overlay. That guard is not yet wired into the sandbox path, so
    // the proposal is recorded with a visible caveat rather than a silent pass.
    Ok(ProposeOutcome {
        session_name: name,
        session,
        notes: vec![
            "import injection guard (bd-1n0np.23.3) is not yet wired into the sandbox path; review imported content before promotion".to_owned(),
        ],
    })
}

/// `ee sandbox curate --retire` — append retire proposals (no durable write).
pub fn propose_curate(
    workspace: &Path,
    args: &SandboxCurateArgs,
) -> Result<ProposeOutcome, DomainError> {
    if args.retire.is_empty() {
        return Err(DomainError::Usage {
            message: "ee sandbox curate requires at least one --retire <MEMORY_ID>.".to_owned(),
            repair: Some("Pass --retire <id> (repeatable) to propose retirements.".to_owned()),
        });
    }
    let name = session_name(&args.session)?;
    let mut session = load_session(workspace, &name);
    let mut added_retire_proposals = 0_usize;
    for memory_id in &args.retire {
        let trimmed = memory_id.trim();
        if !trimmed.is_empty() {
            session.proposals.push(SandboxProposal::Retire {
                memory_id: trimmed.to_owned(),
            });
            added_retire_proposals += 1;
        }
    }
    if added_retire_proposals == 0 {
        return Err(DomainError::Usage {
            message: "ee sandbox curate requires at least one non-empty --retire <MEMORY_ID>."
                .to_owned(),
            repair: Some("Pass --retire <id> (repeatable) to propose retirements.".to_owned()),
        });
    }
    save_session(workspace, &name, &session)?;
    Ok(ProposeOutcome {
        session_name: name,
        session,
        notes: Vec::new(),
    })
}

/// `ee sandbox diff` — assemble the baseline-vs-overlay diff surface (read-only).
pub fn build_diff(
    workspace: &Path,
    args: &SandboxDiffArgs,
) -> Result<(String, SandboxDiffSurface), DomainError> {
    let name = session_name(&args.session)?;
    let session = load_session(workspace, &name);
    let baseline = baseline_memories(workspace)?;
    Ok((name, assemble_sandbox_diff(&baseline, &session)))
}

/// Read the baseline `(memory_id, content)` pairs from the workspace, read-only.
fn baseline_memories(workspace: &Path) -> Result<Vec<(String, String)>, DomainError> {
    let database_path = workspace.join(".ee").join("ee.db");
    if !database_path.exists() {
        return Ok(Vec::new());
    }
    let connection =
        DbConnection::open_file(&database_path).map_err(|error| DomainError::Storage {
            message: format!("Failed to open workspace database: {error}"),
            repair: Some("Run `ee doctor --workspace . --json`.".to_owned()),
        })?;
    let canonical = workspace
        .canonicalize()
        .unwrap_or_else(|_| workspace.to_path_buf());
    let workspace_id = crate::core::workspace::bound_workspace_id_or_hash(
        &connection,
        &crate::core::workspace::stable_workspace_id(&canonical),
        &[workspace, canonical.as_path()],
    )?;
    let memories = connection
        .list_memories(&workspace_id, None, false)
        .map_err(|error| DomainError::Storage {
            message: format!("Failed to list workspace memories: {error}"),
            repair: Some("Run `ee doctor --workspace . --json`.".to_owned()),
        })?;
    Ok(memories
        .into_iter()
        .map(|memory| (memory.id, memory.content))
        .collect())
}

/// Outcome of `ee sandbox apply`: which proposals were persisted vs deferred.
pub struct ApplyOutcome {
    pub session_name: String,
    /// Memory ids persisted through the normal audited remember path.
    pub persisted: Vec<String>,
    /// Retire proposals that require explicit `ee curate` promotion (apply does
    /// not auto-tombstone existing memories).
    pub retire_pending: Vec<String>,
    pub notes: Vec<String>,
}

/// `ee sandbox apply` — promote the session's additive proposals to durable
/// memory through the NORMAL audited remember path (bd-1n0np.21.3). Retire
/// proposals are reported for explicit `ee curate` promotion, never silently
/// auto-applied. Applied additive proposals are cleared from the session.
pub fn apply_session(
    workspace: &Path,
    args: &SandboxApplyArgs,
) -> Result<ApplyOutcome, DomainError> {
    let name = session_name(&args.session)?;
    let session = load_session(workspace, &name);

    let mut persisted = Vec::new();
    let mut retire_pending = Vec::new();
    let mut applied_additive_count = 0_usize;
    for proposal in &session.proposals {
        match proposal {
            SandboxProposal::Remember {
                content,
                level,
                kind,
                ..
            }
            | SandboxProposal::Import {
                content,
                level,
                kind,
                ..
            } => {
                let options = RememberMemoryOptions {
                    workspace_path: workspace,
                    database_path: None,
                    content,
                    workflow_id: None,
                    level,
                    kind,
                    tags: None,
                    confidence: 0.8,
                    source: None,
                    allow_secret_mention: false,
                    valid_from: None,
                    valid_to: None,
                    dry_run: false,
                    auto_link: false,
                    propose_candidates: false,
                };
                let report = match remember_memory(&options) {
                    Ok(report) => report,
                    Err(error) => {
                        return Err(record_partial_apply_failure(
                            workspace,
                            &name,
                            &session,
                            applied_additive_count,
                            error,
                        ));
                    }
                };
                persisted.push(report.memory_id.to_string());
                applied_additive_count += 1;
            }
            SandboxProposal::Retire { memory_id } => retire_pending.push(memory_id.clone()),
        }
    }

    let mut notes = Vec::new();
    if !retire_pending.is_empty() {
        notes.push(format!(
            "{} retire proposal(s) require explicit `ee curate` promotion; sandbox apply persists additive proposals through the audited remember path and never auto-tombstones existing memories",
            retire_pending.len()
        ));
    }

    // Clear the applied additive proposals; keep un-promoted retires.
    let remaining = remaining_after_applied_additives(&session, applied_additive_count);
    save_session(workspace, &name, &remaining)?;

    Ok(ApplyOutcome {
        session_name: name,
        persisted,
        retire_pending,
        notes,
    })
}

fn record_partial_apply_failure(
    workspace: &Path,
    name: &str,
    session: &SandboxSession,
    applied_additive_count: usize,
    apply_error: DomainError,
) -> DomainError {
    if applied_additive_count == 0 {
        return apply_error;
    }

    let remaining = remaining_after_applied_additives(session, applied_additive_count);
    match save_session(workspace, name, &remaining) {
        Ok(()) => DomainError::Storage {
            message: format!(
                "Sandbox apply persisted {applied_additive_count} additive proposal(s), then stopped before completing: {apply_error}. The scratch session was updated to keep only unapplied proposals."
            ),
            repair: Some(format!(
                "Review `ee sandbox diff --session {name}` and rerun after fixing the remaining proposal."
            )),
        },
        Err(cleanup_error) => DomainError::Storage {
            message: format!(
                "Sandbox apply failed after {applied_additive_count} additive proposal(s) persisted; also failed to update the scratch session: {cleanup_error}. Original apply error: {apply_error}"
            ),
            repair: Some(
                "Inspect <workspace>/.ee/sandbox and avoid retrying the same session until the persisted proposals are reconciled."
                    .to_owned(),
            ),
        },
    }
}

fn remaining_after_applied_additives(
    session: &SandboxSession,
    applied_additive_count: usize,
) -> SandboxSession {
    let mut remaining = SandboxSession::default();
    let mut seen_additives = 0_usize;
    for proposal in &session.proposals {
        match proposal {
            SandboxProposal::Remember { .. } | SandboxProposal::Import { .. } => {
                if seen_additives >= applied_additive_count {
                    remaining.proposals.push(proposal.clone());
                }
                seen_additives += 1;
            }
            SandboxProposal::Retire { .. } => remaining.proposals.push(proposal.clone()),
        }
    }
    remaining
}

/// Render an `ee.response.v2` envelope for an apply outcome.
#[must_use]
pub fn render_apply_json(outcome: &ApplyOutcome) -> String {
    serde_json::json!({
        "schema": RESPONSE_SCHEMA_V2,
        "success": true,
        "data": {
            "command": "sandbox apply",
            "sessionName": outcome.session_name,
            "persistedMemoryIds": outcome.persisted,
            "persistedCount": outcome.persisted.len(),
            "retireProposalsPending": outcome.retire_pending,
            "notes": outcome.notes,
        },
        "degraded": [],
    })
    .to_string()
}

/// Compact human summary for an apply outcome.
#[must_use]
pub fn render_apply_human(outcome: &ApplyOutcome) -> String {
    let mut out = format!(
        "sandbox apply (session `{}`): persisted {} memory(ies) via the audited remember path\n",
        outcome.session_name,
        outcome.persisted.len(),
    );
    for id in &outcome.persisted {
        out.push_str(&format!("  + {id}\n"));
    }
    for note in &outcome.notes {
        out.push_str(&format!("  note: {note}\n"));
    }
    out
}

/// Render an `ee.response.v2` envelope for a proposal outcome.
#[must_use]
pub fn render_propose_json(command: &str, outcome: &ProposeOutcome) -> String {
    serde_json::json!({
        "schema": RESPONSE_SCHEMA_V2,
        "success": true,
        "data": {
            "command": command,
            "sessionName": outcome.session_name,
            "overlayHash": outcome.session.overlay().overlay_hash(),
            "proposalCount": outcome.session.proposals.len(),
            "durableMutation": false,
            "notes": outcome.notes,
        },
        "degraded": [],
    })
    .to_string()
}

/// Render an `ee.response.v2` envelope wrapping the `ee.sandbox.diff.v1` surface.
#[must_use]
pub fn render_diff_json(session_name: &str, surface: &SandboxDiffSurface) -> String {
    serde_json::json!({
        "schema": RESPONSE_SCHEMA_V2,
        "success": true,
        "data": {
            "sessionName": session_name,
            "diff": surface,
        },
        "degraded": [],
    })
    .to_string()
}

/// Compact human summary for a proposal outcome.
#[must_use]
pub fn render_propose_human(command: &str, outcome: &ProposeOutcome) -> String {
    let mut out = format!(
        "sandbox {command}: session `{}` now has {} proposal(s) (no durable write)\n  overlay hash: {}\n",
        outcome.session_name,
        outcome.session.proposals.len(),
        outcome.session.overlay().overlay_hash(),
    );
    for note in &outcome.notes {
        out.push_str(&format!("  note: {note}\n"));
    }
    out
}

/// Compact human summary for the diff surface.
#[must_use]
pub fn render_diff_human(session_name: &str, surface: &SandboxDiffSurface) -> String {
    let mut out = format!(
        "sandbox diff (session `{session_name}`, no durable write)\n  overlay hash: {}\n  added: {}  modified: {}  removed: {}  unchanged: {}\n",
        surface.overlay_hash,
        surface.added.len(),
        surface.modified.len(),
        surface.removed.len(),
        surface.unchanged,
    );
    if surface.sandbox_approximation {
        out.push_str(&format!(
            "  approximation: {}\n",
            surface.approximation_reason
        ));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{
        ApplyOutcome, ProposeOutcome, SandboxCurateArgs, SandboxProposal, SandboxSession,
        load_session, propose_curate, remaining_after_applied_additives, render_apply_json,
        render_diff_json, render_propose_json, session_name,
    };
    use crate::core::sandbox::{SANDBOX_DIFF_SCHEMA_V1, SandboxDiffSurface};

    #[test]
    fn session_name_defaults_and_trims() {
        assert_eq!(session_name(&None).expect("default"), "default");
        assert_eq!(
            session_name(&Some("  ".to_owned())).expect("blank defaults"),
            "default"
        );
        assert_eq!(
            session_name(&Some(" feature-x ".to_owned())).expect("trimmed"),
            "feature-x"
        );
    }

    #[test]
    fn session_name_rejects_path_traversal() {
        for raw in [
            ".",
            "..",
            "../escape",
            "nested/name",
            "/absolute",
            r"nested\name",
            "feature name",
            "feature:name",
            "feature\nname",
            "feature-\u{2603}",
        ] {
            let error = session_name(&Some(raw.to_owned())).expect_err(raw);
            assert!(
                error.to_string().contains("Invalid sandbox session name"),
                "unexpected error for {raw:?}: {error}"
            );
        }
    }

    #[test]
    fn session_name_accepts_file_safe_names() {
        for raw in [
            "default",
            "feature-x",
            "feature_x",
            "feature.2026",
            "A1-b_2.c",
        ] {
            assert_eq!(session_name(&Some(raw.to_owned())).expect(raw), raw);
        }
    }

    #[test]
    fn sandbox_curate_rejects_blank_retire_values() {
        let workspace = tempfile::tempdir().expect("tempdir");
        let args = SandboxCurateArgs {
            retire: vec![" ".to_owned(), "\t".to_owned()],
            session: Some("blank-retire".to_owned()),
        };

        let error = match propose_curate(workspace.path(), &args) {
            Ok(_) => panic!("blank retires must fail"),
            Err(error) => error,
        };
        assert!(
            error
                .to_string()
                .contains("at least one non-empty --retire"),
            "unexpected error: {error}"
        );

        let session_path =
            crate::core::sandbox::SandboxSession::session_path(workspace.path(), "blank-retire");
        assert!(
            !session_path.exists(),
            "invalid curate invocation must not create a scratch session"
        );
    }

    #[test]
    fn sandbox_curate_trims_and_records_non_empty_retire_values() {
        let workspace = tempfile::tempdir().expect("tempdir");
        let args = SandboxCurateArgs {
            retire: vec!["  mem_a  ".to_owned(), "".to_owned(), "mem_b".to_owned()],
            session: Some("trim-retire".to_owned()),
        };

        let outcome = propose_curate(workspace.path(), &args).expect("valid retires");
        assert_eq!(outcome.session.proposals.len(), 2);
        assert_eq!(
            outcome.session.proposals,
            vec![
                SandboxProposal::Retire {
                    memory_id: "mem_a".to_owned()
                },
                SandboxProposal::Retire {
                    memory_id: "mem_b".to_owned()
                },
            ]
        );

        let stored = load_session(workspace.path(), "trim-retire");
        assert_eq!(stored.proposals, outcome.session.proposals);
    }

    #[test]
    fn sandbox_apply_remaining_session_drops_only_confirmed_additives() {
        let first = SandboxProposal::Remember {
            memory_id: "sandbox_mem_first".to_owned(),
            content: "first".to_owned(),
            content_hash: "blake3:first".to_owned(),
            level: "episodic".to_owned(),
            kind: "fact".to_owned(),
        };
        let retire = SandboxProposal::Retire {
            memory_id: "mem_existing".to_owned(),
        };
        let second = SandboxProposal::Import {
            memory_id: "sandbox_mem_second".to_owned(),
            content: "second".to_owned(),
            content_hash: "blake3:second".to_owned(),
            level: "episodic".to_owned(),
            kind: "fact".to_owned(),
        };
        let third = SandboxProposal::Remember {
            memory_id: "sandbox_mem_third".to_owned(),
            content: "third".to_owned(),
            content_hash: "blake3:third".to_owned(),
            level: "episodic".to_owned(),
            kind: "fact".to_owned(),
        };
        let session = SandboxSession {
            proposals: vec![first.clone(), retire.clone(), second.clone(), third.clone()],
        };

        assert_eq!(
            remaining_after_applied_additives(&session, 0).proposals,
            session.proposals
        );
        assert_eq!(
            remaining_after_applied_additives(&session, 2).proposals,
            vec![retire.clone(), third.clone()]
        );
        assert_eq!(
            remaining_after_applied_additives(&session, usize::MAX).proposals,
            vec![retire]
        );
    }

    #[test]
    fn sandbox_success_json_envelopes_include_clean_degraded_array() {
        let session = SandboxSession {
            proposals: vec![SandboxProposal::Remember {
                memory_id: "sandbox_mem_first".to_owned(),
                content: "first".to_owned(),
                content_hash: "blake3:first".to_owned(),
                level: "episodic".to_owned(),
                kind: "fact".to_owned(),
            }],
        };
        let propose = ProposeOutcome {
            session_name: "default".to_owned(),
            session,
            notes: Vec::new(),
        };
        let apply = ApplyOutcome {
            session_name: "default".to_owned(),
            persisted: vec!["mem_a".to_owned()],
            retire_pending: Vec::new(),
            notes: Vec::new(),
        };
        let diff = SandboxDiffSurface {
            schema: SANDBOX_DIFF_SCHEMA_V1,
            overlay_hash: "blake3:overlay".to_owned(),
            added: vec!["sandbox_mem_first".to_owned()],
            modified: Vec::new(),
            removed: Vec::new(),
            unchanged: 0,
            proposal_count: 1,
            durable_mutation: false,
            sandbox_approximation: true,
            approximation_reason: "test approximation",
        };

        for raw in [
            render_propose_json("sandbox remember", &propose),
            render_apply_json(&apply),
            render_diff_json("default", &diff),
        ] {
            let envelope: serde_json::Value =
                serde_json::from_str(&raw).expect("sandbox success envelope");
            assert_eq!(envelope["schema"], crate::models::RESPONSE_SCHEMA_V2);
            assert_eq!(envelope["success"], true);
            assert_eq!(envelope["degraded"], serde_json::json!([]));
        }
    }
}