newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
use super::*;
use newt_core::agentic::{PlanEntry, PromptDisposition};

/// #2424: an Act-disposition turn means the model called `enter_plan_mode`
/// mid-turn — the clamp is a LOCAL restriction layered on a turn already
/// validated for Act, so approval only needs to lift it, never re-validate
/// authority. This must hold regardless of the human-selected operating
/// mode, since the mode only decided what disposition INTAKE would have
/// picked absent a model override — the model's own mid-turn entry wins.
#[test]
fn act_disposition_is_always_model_during_act() {
    for mode in [
        OperatingMode::Chat,
        OperatingMode::Dev,
        OperatingMode::Admin,
        OperatingMode::Plan,
        OperatingMode::Diagnose,
        OperatingMode::Auto,
        OperatingMode::FullAuto,
    ] {
        assert_eq!(
            plan_entry_for_turn(PromptDisposition::Act, mode),
            PlanEntry::ModelDuringAct,
            "an Act-disposition turn is always ModelDuringAct, regardless of {mode:?}"
        );
    }
}

/// A Plan-disposition turn while the operator has `/mode plan` selected is
/// the OperatorSelected case — the operator explicitly asked for this, as
/// opposed to intake inferring it on its own.
#[test]
fn plan_disposition_under_mode_plan_is_operator_selected() {
    assert_eq!(
        plan_entry_for_turn(PromptDisposition::Plan, OperatingMode::Plan),
        PlanEntry::OperatorSelected
    );
}

/// The originally observed bug case: a Plan-disposition turn the operator
/// never asked for (their selected mode is something else entirely) means
/// intake inferred Plan on its own.
#[test]
fn plan_disposition_under_any_other_mode_is_intake_inferred() {
    for mode in [
        OperatingMode::Chat,
        OperatingMode::Dev,
        OperatingMode::Admin,
        OperatingMode::Diagnose,
        OperatingMode::Auto,
        OperatingMode::FullAuto,
    ] {
        assert_eq!(
            plan_entry_for_turn(PromptDisposition::Plan, mode),
            PlanEntry::IntakeInferred,
            "Plan disposition under {mode:?} (not /mode plan) is intake-inferred"
        );
    }
}

/// Every non-Act, non-Plan disposition (Ask/Explain/Research) is not
/// expected to reach the approval hook at all in practice — the local
/// mid-turn promotion only fires from Act, and intake only narrows to Plan
/// itself, never to these. But the classifier is total, so an unexpected
/// disposition must still fail SAFE: it is treated as needing the full
/// seeded-turn approval path (IntakeInferred), never as a same-turn resume
/// (which would be the wrong direction to fail toward, since it would let a
/// misclassified turn keep going instead of stopping for a fresh look).
#[test]
fn unexpected_dispositions_fail_safe_to_intake_inferred() {
    for disposition in [
        PromptDisposition::Ask,
        PromptDisposition::Explain,
        PromptDisposition::Research,
    ] {
        assert_eq!(
            plan_entry_for_turn(disposition, OperatingMode::Chat),
            PlanEntry::IntakeInferred,
            "{disposition:?} must fail safe, never ModelDuringAct"
        );
    }
}

/// #2424 regression: the guard must fire on the turn's own disposition, not
/// only the model-entered flag — an intake-inferred Plan turn (the original
/// bug report) never sets that flag, so keying on it alone silently skipped
/// the exact case the design exists for.
#[test]
fn a_plan_turn_that_presented_a_draft_is_asked_even_without_the_model_flag() {
    assert!(plan_approval_due(
        PromptDisposition::Plan,
        /* model_entered_plan */ false,
        /* exit_requested */ false,
        /* presented_draft */ true,
        false
    ));
}

/// A Plan turn that drafted nothing (it answered a question, say) has no
/// plan to approve and is not asked.
#[test]
fn a_plan_turn_with_no_draft_is_not_asked() {
    assert!(!plan_approval_due(
        PromptDisposition::Plan,
        false,
        false,
        /* presented_draft */ false,
        false
    ));
}

/// The model-entered case: an Act turn where the model called
/// `enter_plan_mode` and drafted is asked; an ordinary Act turn that never
/// touched Plan mode is never interrupted.
#[test]
fn model_entered_plan_with_a_draft_is_asked_and_a_plain_act_turn_is_not() {
    assert!(plan_approval_due(
        PromptDisposition::Act,
        /* model_entered_plan */ true,
        false,
        /* presented_draft */ true,
        false
    ));
    assert!(!plan_approval_due(
        PromptDisposition::Act,
        false,
        false,
        false,
        false
    ));
}

/// An explicit `exit_plan_mode` request always reaches the operator — the
/// clamp lift itself is what needs a human, draft or no draft.
#[test]
fn an_exit_request_is_always_asked() {
    assert!(plan_approval_due(
        PromptDisposition::Act,
        false,
        /* exit_requested */ true,
        /* presented_draft */ false,
        false
    ));
    assert!(plan_approval_due(
        PromptDisposition::Plan,
        false,
        true,
        false,
        false
    ));
}

/// A non-plan disposition is never a plan turn, whatever else is set —
/// `render_report` only stores a draft under Plan, so this state is not
/// reachable, but the predicate must still say no rather than assume.
#[test]
fn a_non_plan_disposition_is_not_asked_without_an_exit_request() {
    for disposition in [
        PromptDisposition::Ask,
        PromptDisposition::Explain,
        PromptDisposition::Research,
    ] {
        assert!(
            !plan_approval_due(disposition, false, false, true, false),
            "{disposition:?} is not a plan turn"
        );
    }
}

/// A Plan turn that set a multi-step plan in the harness ledger drafted a
/// plan the operator can read, so it is asked even with no `render_report`
/// draft; an Act turn's first plan reaches the hook as an exit request
/// instead, never through this flag alone.
#[test]
fn a_plan_turn_that_set_a_ledger_plan_is_asked_without_a_draft() {
    assert!(plan_approval_due(
        PromptDisposition::Plan,
        false,
        false,
        /* presented_draft */ false,
        /* set_plan_this_turn */ true,
    ));
    assert!(!plan_approval_due(
        PromptDisposition::Act,
        false,
        false,
        false,
        /* set_plan_this_turn */ true,
    ));
}

/// With no presented draft, approval seeds implementation from the ledger's
/// own `<plan>` block — the plan the operator just read.
#[test]
fn selected_target_approval_seeds_the_ledger_plan_when_no_draft_was_presented() {
    let states = ConversationModeStates::default();
    let a = objective("refactor the parser");
    states.plan.set_plan_mode(true).unwrap();
    let mut gate = ScriptedGate::new([answer("y")]);
    let block = "<plan>\nSelected source (agent data): \"packages/parser/nested/root.py\"\n✓ 1. inspect packages/parser/nested/root.py\n→ 2. repair packages/parser/nested/root.py\n</plan>";
    let effects = run_plan_approval(
        Some(&mut gate),
        PlanEntry::ModelDuringAct,
        &states.plan,
        &states.plan_draft,
        Some(&a),
        PlanApprovalSeed {
            exit_guidance: "GUIDANCE",
            ledger_plan: Some(block),
        },
        false,
    );
    assert!(!states.plan.is_plan_mode(), "clamp lifted");
    let (input, _) = effects.queued.expect("one continuation").into_input();
    let ReadOutcome::Line(text) = input else {
        panic!("a line of input")
    };
    assert!(text.contains("approved the plan below"), "{text}");
    assert!(text.contains(block), "{text}");
}

/// `/mode full-auto` answers the question for the operator: nothing is
/// asked, the clamp lifts, the seed runs, and the notice says why.
#[test]
fn full_auto_approves_without_asking() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([]);
    let effects = run_plan_approval(
        Some(&mut gate),
        PlanEntry::ModelDuringAct,
        &states.plan,
        &states.plan_draft,
        Some(&a),
        PlanApprovalSeed {
            exit_guidance: "GUIDANCE",
            ledger_plan: None,
        },
        true,
    );
    assert!(gate.asked.is_empty(), "no question under full-auto");
    assert!(!states.plan.is_plan_mode(), "clamp lifted");
    assert!(effects.queued.is_some());
    assert!(
        effects.notice.contains("auto-approved"),
        "{}",
        effects.notice
    );
}

/// #2424: the seeded implementation turn carries the approved draft when
/// there is one, and ALWAYS carries the initiative exit guidance — that
/// guidance used to be `exit_plan_mode`'s own ack; this is the turn it now
/// belongs to.
#[test]
fn approval_seed_text_carries_the_plan_when_present_and_the_guidance_always() {
    let with_plan = plan_approval_seed_text(Some("# Refactor\n1. step"), "GUIDANCE");
    // The coordinate: every seeded turn starts with the registered prefix,
    // so the compaction boundary classifier recognizes it as harness-owned.
    assert!(
        with_plan.starts_with(newt_core::agentic::PLAN_APPROVAL_PREFIX),
        "{with_plan}"
    );
    assert!(with_plan.contains("Implement it now"), "{with_plan}");
    assert!(with_plan.contains("# Refactor\n1. step"), "{with_plan}");
    assert!(with_plan.contains("GUIDANCE"), "{with_plan}");

    let without = plan_approval_seed_text(None, "GUIDANCE");
    assert!(without.contains("Continue the task"), "{without}");
    assert!(!without.contains("Implement it now"), "{without}");
    assert!(without.contains("GUIDANCE"), "{without}");
}

/// The seeded turn resumes as Act by the operator's decision — even though
/// its text quotes a plan, which a fresh intake analysis could read as Plan
/// and re-clamp the very turn that was just approved.
#[test]
fn approval_intake_resumes_as_act_even_when_the_text_quotes_a_plan() {
    let lexicon = newt_core::agentic::DispositionLexicon::default();
    let text = plan_approval_seed_text(
        Some("# Plan\n1. Plan the refactor of the parser\n2. Outline the steps"),
        "guidance",
    );
    assert_eq!(
        plan_approval_intake(&text, &lexicon).disposition(),
        PromptDisposition::Act
    );
}

/// The same decision holds when the seeded text itself opens collaboratively
/// (the one wording intake reads as Plan on its own): approval is the
/// operator's decision, so `resume_with` keeps Act rather than re-clamping
/// the turn.
#[test]
fn approval_intake_resumes_as_act_even_when_the_text_opens_collaboratively() {
    let lexicon = newt_core::agentic::DispositionLexicon::default();
    let text = "let's refactor the parser";
    assert_eq!(
        newt_core::agentic::PromptIntake::analyze_with(text, &lexicon).disposition(),
        PromptDisposition::Plan,
        "control: on its own this wording reads as Plan"
    );
    assert_eq!(
        plan_approval_intake(text, &lexicon).disposition(),
        PromptDisposition::Act
    );
}

// ---------------------------------------------------------------------------
// Composed approval-to-dispatch: a scripted gate drives `run_plan_approval`
// against real `PlanModeState` / `PlanDraftState`, and the queued turn is
// consumed through `PendingPlanTurn::into_input` exactly as the loop head
// does. Acceptance question: does exactly the human-authorized work proceed
// once, with the correct objective, draft, lineage, and authority?
// ---------------------------------------------------------------------------

use newt_core::agentic::{
    HumanQuestionOutcome, PermissionDecision, PermissionGate, PermissionRequest,
    PlanDraftSink as _, PlanModeControl as _,
};
use newt_core::Caveats;

/// Answers each question with the next scripted outcome; records the
/// questions asked. `ask`/`refresh_caveats` must never be reached by the
/// approval path — approval is a question, not a permission grant.
struct ScriptedGate {
    outcomes: Vec<HumanQuestionOutcome>,
    asked: Vec<String>,
}

impl ScriptedGate {
    fn new(outcomes: impl IntoIterator<Item = HumanQuestionOutcome>) -> Self {
        let mut outcomes: Vec<_> = outcomes.into_iter().collect();
        outcomes.reverse();
        Self {
            outcomes,
            asked: Vec::new(),
        }
    }
}

impl PermissionGate for ScriptedGate {
    fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
        panic!("plan approval must never request a permission grant");
    }
    fn refresh_caveats(&mut self, _: &Caveats) -> PermissionDecision {
        panic!("plan approval must never re-mint caveats");
    }
    fn ask_question(&mut self, question: &str) -> HumanQuestionOutcome {
        self.asked.push(question.to_string());
        self.outcomes
            .pop()
            .expect("a scripted outcome per question")
    }
    fn ask_choice(
        &mut self,
        question: &str,
        options: &[newt_core::agentic::ChoiceSpec],
    ) -> HumanQuestionOutcome {
        assert_eq!(
            options.iter().map(|o| o.id).collect::<Vec<_>>(),
            vec!["yes", "no", "discuss"],
            "the plan question offers exactly its three answers, yes first"
        );
        self.ask_question(question)
    }
}

/// `discuss` is a selection that opens one free-text follow-up; the words
/// typed there are the feedback the model receives, under the clamp.
#[test]
fn discuss_opens_one_follow_up_and_feeds_its_text_back() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([answer("discuss"), answer("split transport first")]);
    let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));
    assert_eq!(gate.asked.len(), 2, "{:?}", gate.asked);
    assert!(
        gate.asked[1].starts_with("What should change"),
        "{:?}",
        gate.asked
    );
    assert!(states.plan.is_plan_mode(), "the clamp stays");
    let (input, origin) = effects.queued.expect("the feedback runs next").into_input();
    let ReadOutcome::Line(text) = input else {
        panic!("a line of input")
    };
    assert_eq!(text, "split transport first");
    assert!(matches!(
        origin,
        ModelInputOrigin::OperatorContinuation { .. }
    ));
}

fn answer(text: &str) -> HumanQuestionOutcome {
    HumanQuestionOutcome::Answer(text.to_string())
}

fn objective(text: &str) -> newt_core::TurnPromptContext {
    newt_core::TurnPromptContext::ephemeral_operator("conv-1", text, text)
}

/// A model-entered plan turn under `objective` that saved and presented
/// `markdown`: the state the turn-end hook sees right before asking.
fn presented_plan(
    states: &ConversationModeStates,
    objective: &newt_core::TurnPromptContext,
    markdown: &str,
) -> newt_core::agentic::PresentedPlan {
    states.plan.set_plan_mode(true).unwrap();
    let noop = |_: &std::path::Path, _: &str| Ok(());
    states
        .plan_draft
        .bind("conv-1", plan_objective(Some(objective)), &noop)
        .save_draft(markdown.to_string())
        .unwrap();
    states
        .plan_draft
        .take_for_presentation(plan_objective(Some(objective)).unwrap())
        .expect("presented")
}

fn approve(
    gate: &mut ScriptedGate,
    states: &ConversationModeStates,
    entry: PlanEntry,
    parent: Option<&newt_core::TurnPromptContext>,
) -> PlanApprovalEffects {
    run_plan_approval(
        Some(gate),
        entry,
        &states.plan,
        &states.plan_draft,
        parent,
        PlanApprovalSeed {
            exit_guidance: "GUIDANCE",
            ledger_plan: None,
        },
        false,
    )
}

/// "y" → exactly one harness-origin continuation, carrying the presented
/// draft, parented to the objective it was drafted under; the clamp lifts.
#[test]
fn approval_queues_exactly_one_harness_turn_with_the_presented_plan() {
    let states = ConversationModeStates::default();
    let a = objective("refactor the parser");
    let shown = presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([answer("y")]);

    let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));

    assert_eq!(gate.asked, vec!["Approve this plan? [Y/n/discuss] "]);
    assert!(!states.plan.is_plan_mode(), "clamp lifted");
    assert!(!effects.switch_to_dev);
    let (input, origin) = effects.queued.expect("one continuation").into_input();
    let ReadOutcome::Line(text) = input else {
        panic!("a line of input")
    };
    assert!(text.starts_with(newt_core::agentic::PLAN_APPROVAL_PREFIX));
    assert!(text.contains(&shown.draft.markdown), "{text}");
    assert!(text.contains("GUIDANCE"));
    match origin {
        ModelInputOrigin::HarnessPlanApproval { parent } => {
            assert_eq!(
                parent.active().root_prompt_id(),
                a.active().root_prompt_id()
            );
        }
        other => panic!("harness origin expected, got {other:?}"),
    }
    assert!(
        states
            .plan_draft
            .take_approved(a.active().root_prompt_id())
            .is_none(),
        "the snapshot is consumed by the one approval"
    );
}

/// Reject, cancel, exit, closed/failed input, no operator, no gate:
/// none of these queue anything, and the clamp stays. No gate outcome other
/// than a submitted answer widens what the model may do.
#[test]
fn every_non_approval_outcome_queues_nothing_and_keeps_the_clamp() {
    let outcomes = [
        answer("n"),
        HumanQuestionOutcome::InputFailed,
        HumanQuestionOutcome::Cancelled,
        HumanQuestionOutcome::ExitRequested,
        HumanQuestionOutcome::InputClosed,
        HumanQuestionOutcome::Unavailable,
    ];
    for outcome in outcomes {
        let states = ConversationModeStates::default();
        let a = objective("A");
        presented_plan(&states, &a, "# plan A");
        let mut gate = ScriptedGate::new([outcome.clone()]);
        let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));
        assert!(effects.queued.is_none(), "{outcome:?} queued a turn");
        assert!(states.plan.is_plan_mode(), "{outcome:?} lifted the clamp");
        assert!(!effects.switch_to_dev);
        assert!(
            states
                .plan_draft
                .take_approved(a.active().root_prompt_id())
                .is_some(),
            "{outcome:?} must leave the snapshot for a later approval"
        );
    }
    // No gate at all.
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    let effects = run_plan_approval(
        None,
        PlanEntry::ModelDuringAct,
        &states.plan,
        &states.plan_draft,
        Some(&a),
        PlanApprovalSeed {
            exit_guidance: "GUIDANCE",
            ledger_plan: None,
        },
        false,
    );
    assert!(effects.queued.is_none());
    assert!(states.plan.is_plan_mode());
}

/// "discuss" text → one OPERATOR-origin continuation of the same lineage,
/// the clamp stays, and the presented snapshot survives so the eventual
/// "y" (with no new draft) seeds exactly what the operator saw.
#[test]
fn discussion_preserves_lineage_clamp_and_snapshot_then_approval_seeds_it() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    let shown = presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([answer("why step 2?"), answer("yes")]);

    let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));
    assert!(states.plan.is_plan_mode(), "discussion keeps the clamp");
    let (input, origin) = effects.queued.expect("the discussion turn").into_input();
    assert!(matches!(input, ReadOutcome::Line(ref t) if t == "why step 2?"));
    let ModelInputOrigin::OperatorContinuation { parent } = origin else {
        panic!("operator-authored text keeps an operator origin")
    };
    assert_eq!(
        parent.active().root_prompt_id(),
        a.active().root_prompt_id()
    );

    // The discussion turn ran as a continuation (same root) and saved no
    // new draft; the operator now says yes.
    let discuss =
        newt_core::TurnPromptContext::ephemeral_operator_continuation("conv-1", "d", "d", &a)
            .unwrap();
    assert!(states
        .plan_draft
        .take_for_presentation(discuss.active().root_prompt_id())
        .is_none());
    let effects = approve(
        &mut gate,
        &states,
        PlanEntry::ModelDuringAct,
        Some(&discuss),
    );
    let (input, _) = effects
        .queued
        .expect("the implementation turn")
        .into_input();
    let ReadOutcome::Line(text) = input else {
        panic!()
    };
    assert!(text.contains(&shown.draft.markdown), "{text}");
    assert!(!states.plan.is_plan_mode());
}

/// The steer's binding case end to end: plan A presented; unrelated
/// objective B ends with `exit_plan_mode` and no B draft; the operator
/// approves. The seeded turn carries NO plan (A's must not become B's
/// input) and is parented to B, and A's snapshot remains A's.
#[test]
fn approval_under_objective_b_never_seeds_objective_a_plan() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");

    let b = objective("B");
    states.plan.set_plan_mode(true).unwrap();
    states.plan.request_exit().unwrap();
    assert!(states
        .plan_draft
        .take_for_presentation(b.active().root_prompt_id())
        .is_none());
    let mut gate = ScriptedGate::new([answer("y")]);
    let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&b));

    let (input, origin) = effects.queued.expect("B's continuation").into_input();
    let ReadOutcome::Line(text) = input else {
        panic!()
    };
    assert!(!text.contains("# plan A"), "A leaked into B: {text}");
    assert!(text.contains("Continue the task"), "{text}");
    let ModelInputOrigin::HarnessPlanApproval { parent } = origin else {
        panic!()
    };
    assert_eq!(
        parent.active().root_prompt_id(),
        b.active().root_prompt_id()
    );
    assert!(
        states
            .plan_draft
            .take_approved(a.active().root_prompt_id())
            .is_some(),
        "A's snapshot is untouched by B's approval"
    );
}

/// A second `exit_plan_mode` + "y" after an approval cannot re-seed the
/// same plan: the snapshot was consumed, so the second seed carries none.
#[test]
fn a_repeated_exit_cannot_consume_the_approval_twice() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([answer("y"), answer("y")]);

    let first = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));
    let (ReadOutcome::Line(first_text), _) = first.queued.unwrap().into_input() else {
        panic!()
    };
    assert!(first_text.contains("# plan A"));

    states.plan.set_plan_mode(true).unwrap();
    states.plan.request_exit().unwrap();
    let second = approve(&mut gate, &states, PlanEntry::ModelDuringAct, Some(&a));
    let (ReadOutcome::Line(second_text), _) = second.queued.unwrap().into_input() else {
        panic!()
    };
    assert!(
        !second_text.contains("# plan A"),
        "the approved snapshot must not be replayed: {second_text}"
    );
}

/// `/mode plan` (OperatorSelected): the question names the mode switch and
/// approval reports it; the loop applies the process-global write.
#[test]
fn operator_selected_approval_asks_about_the_mode_switch_and_requests_it() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    let mut gate = ScriptedGate::new([answer("y")]);
    let effects = approve(&mut gate, &states, PlanEntry::OperatorSelected, Some(&a));
    assert_eq!(
        gate.asked,
        vec!["Approve this plan and switch to /mode dev? [Y/n/discuss] "]
    );
    assert!(effects.switch_to_dev);
    assert!(effects.queued.is_some());
}

/// No receipt for the turn (fails safe): approval lifts the clamp but
/// queues nothing — the operator's own next message starts implementation,
/// so no harness turn runs without a lineage to attach to.
#[test]
fn approval_without_a_receipt_queues_nothing() {
    let states = ConversationModeStates::default();
    states.plan.set_plan_mode(true).unwrap();
    let mut gate = ScriptedGate::new([answer("y")]);
    let effects = approve(&mut gate, &states, PlanEntry::ModelDuringAct, None);
    assert!(effects.queued.is_none());
    assert!(!states.plan.is_plan_mode());
    assert!(effects.notice.contains("Send a message"));
}

/// `exit_plan_mode` only REQUESTS: the flag is set, the clamp is untouched,
/// and the request is consumed by exactly one turn-end read.
#[test]
fn exit_plan_mode_only_requests_and_the_request_is_read_once() {
    let states = ConversationModeStates::default();
    assert!(!states.plan.exit_requested());
    states.plan.set_plan_mode(true).unwrap();
    states.plan.request_exit().unwrap();
    assert!(
        states.plan.is_plan_mode(),
        "request does not lift the clamp"
    );
    assert!(states.plan.exit_requested());
    assert!(
        states.plan.exit_requested(),
        "the loop only observes the request"
    );
    assert!(states.plan.take_exit_requested());
    assert!(!states.plan.exit_requested());
    assert!(!states.plan.take_exit_requested(), "consumed once");
    assert!(states.plan.is_plan_mode());
}

/// A queued continuation from before a boundary clear is stale: the queue
/// is a single slot the loop head drains on the very next iteration, and
/// `ConversationModeStates::clear()` (new/restore/persona) drops the draft
/// and snapshot, so nothing survives for a later objective to run.
#[test]
fn boundary_clear_leaves_no_snapshot_for_a_later_approval() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    presented_plan(&states, &a, "# plan A");
    states.clear();
    assert!(!states.plan.is_plan_mode());
    assert!(states
        .plan_draft
        .take_approved(a.active().root_prompt_id())
        .is_none());
    let noop = |_: &std::path::Path, _: &str| Ok(());
    assert!(states
        .plan_draft
        .bind("conv-1", plan_objective(Some(&a)), &noop)
        .latest_draft()
        .is_none());
}

/// Recording presenter: the pane-facing render the loop performs and the
/// snapshot it prints are the same bytes — `ToolDisplay::document` is a
/// `writeln!`+flush, so rendering the snapshot's markdown directly is
/// contract-equivalent; this pins that the presented text is the draft.
#[test]
fn the_presented_snapshot_is_the_saved_markdown_byte_for_byte() {
    let states = ConversationModeStates::default();
    let a = objective("A");
    let shown = presented_plan(&states, &a, "# Title\n\n1. step one\n");
    assert_eq!(shown.draft.markdown, "# Title\n\n1. step one\n");
    assert_eq!(shown.draft.revision, 1);
}

/// PR #2799 review: choosing discuss binds the follow-up to feedback, even
/// when its verbatim text would approve or reject the separate decision prompt.
#[test]
fn discussion_2799_cannot_be_reinterpreted_as_approval_or_rejection() {
    for entry in [
        PlanEntry::ModelDuringAct,
        PlanEntry::OperatorSelected,
        PlanEntry::IntakeInferred,
    ] {
        for feedback in ["yes", "continue", "go", "no", "  yes\n"] {
            let states = ConversationModeStates::default();
            let parent = objective("A");
            presented_plan(&states, &parent, "# plan A");
            let mut gate = ScriptedGate::new([answer("discuss"), answer(feedback)]);
            let effects = approve(&mut gate, &states, entry, Some(&parent));
            assert!(
                states.plan.is_plan_mode(),
                "{entry:?}/{feedback:?}: clamp lifted"
            );
            assert!(!effects.switch_to_dev, "discussion cannot switch mode");
            let (input, origin) = effects.queued.expect("verbatim feedback turn").into_input();
            let ReadOutcome::Line(text) = input else {
                panic!("feedback line")
            };
            assert_eq!(text, feedback);
            assert!(matches!(
                origin,
                ModelInputOrigin::OperatorContinuation { .. }
            ));
            assert!(
                states
                    .plan_draft
                    .take_approved(parent.active().root_prompt_id())
                    .is_some(),
                "discussion consumed approval snapshot"
            );
            assert_eq!(gate.asked.len(), 2);
        }
    }
}

/// PR #2799 review: cancelling the discussion (or losing input) cannot approve
/// the plan, discard its snapshot, or seed an implementing turn.
#[test]
fn discussion_2799_unanswered_follow_up_retains_clamp_and_snapshot() {
    for outcome in [
        HumanQuestionOutcome::Cancelled,
        HumanQuestionOutcome::Unavailable,
        HumanQuestionOutcome::InputClosed,
        HumanQuestionOutcome::ExitRequested,
        answer(""),
    ] {
        let states = ConversationModeStates::default();
        let parent = objective("A");
        presented_plan(&states, &parent, "# plan A");
        let mut gate = ScriptedGate::new([answer("discuss"), outcome.clone()]);
        let effects = approve(
            &mut gate,
            &states,
            PlanEntry::OperatorSelected,
            Some(&parent),
        );
        assert!(states.plan.is_plan_mode(), "{outcome:?}");
        assert!(!effects.switch_to_dev);
        assert!(effects.queued.is_none());
        assert!(states
            .plan_draft
            .take_approved(parent.active().root_prompt_id())
            .is_some());
        assert_eq!(gate.asked.len(), 2);
    }
}

/// Submitting a blank accepts the displayed default, including an explicit
/// /mode plan exit, and seeds one continuation from the presented snapshot.
#[test]
fn plan_default_yes_blank_approval_seeds_implementation() {
    for entry in [
        PlanEntry::IntakeInferred,
        PlanEntry::ModelDuringAct,
        PlanEntry::OperatorSelected,
    ] {
        for text in ["", "  "] {
            let states = ConversationModeStates::default();
            let parent = objective("A");
            let shown = presented_plan(&states, &parent, "# approved default");
            let mut gate = ScriptedGate::new([answer(text)]);
            let effects = approve(&mut gate, &states, entry, Some(&parent));
            assert!(!states.plan.is_plan_mode());
            assert_eq!(effects.switch_to_dev, entry == PlanEntry::OperatorSelected);
            assert!(gate.asked[0].contains("[Y/n/discuss]"));
            let (input, origin) = effects.queued.expect("one implementing turn").into_input();
            let ReadOutcome::Line(line) = input else {
                panic!("implementation line")
            };
            assert!(line.contains(&shown.draft.markdown));
            assert!(matches!(
                origin,
                ModelInputOrigin::HarnessPlanApproval { .. }
            ));
            assert!(states
                .plan_draft
                .take_approved(parent.active().root_prompt_id())
                .is_none());
        }
    }
}