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
use super::*;

fn prompt_store() -> (tempfile::TempDir, newt_core::ConversationStore, String) {
    let tmp = tempfile::TempDir::new().unwrap();
    let workspace = tmp.path().join("workspace");
    std::fs::create_dir_all(&workspace).unwrap();
    let store =
        newt_core::ConversationStore::new(tmp.path().join("state"), &workspace, 100).unwrap();
    (tmp, store, newt_core::new_conversation_id())
}

#[test]
fn session_artifact_store_exists_only_for_ephemeral_mode() {
    let conversation_id = newt_core::new_conversation_id();

    assert!(session_artifact_store(false, &conversation_id)
        .unwrap()
        .is_none());
    let ephemeral = session_artifact_store(true, &conversation_id)
        .unwrap()
        .expect("ephemeral ledger");
    assert_eq!(ephemeral.conversation_id(), conversation_id);
}

#[test]
fn session_artifact_store_rebinds_when_conversation_rotates() {
    let first_id = newt_core::new_conversation_id();
    let second_id = newt_core::new_conversation_id();
    let mut ledger = session_artifact_store(true, &first_id)
        .unwrap()
        .expect("first ledger");
    assert_eq!(ledger.conversation_id(), first_id);

    ledger = session_artifact_store(true, &second_id)
        .unwrap()
        .expect("replacement ledger");
    assert_eq!(ledger.conversation_id(), second_id);
    assert_ne!(ledger.conversation_id(), first_id);
}

/// Real repository reads ground the workspace formatter's distinction between
/// an unavailable optional snapshot and the native tool's bounded authority.
#[test]
fn git_head_snapshot_requires_effective_workspace_read_authority() {
    let tmp = tempfile::TempDir::new().unwrap();
    std::fs::create_dir_all(tmp.path().join(".git/objects")).unwrap();
    std::fs::create_dir_all(tmp.path().join(".git/refs/heads")).unwrap();
    std::fs::write(tmp.path().join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
    let tool = newt_git::LocalGitTool {
        root: tmp.path().to_path_buf(),
        author: newt_git::Author {
            name: "test".into(),
            email: "test@example.com".into(),
        },
        attribution: None,
        commit_succeeded: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        contributors_consumed: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        signer: None,
    };
    let mut denied = newt_core::Caveats::top();
    denied.fs_read = newt_core::Scope::none();
    assert!(git_head_snapshot(Some(&tool), &denied).is_none());
    assert!(git_head_snapshot(None, &newt_core::Caveats::top()).is_none());
    // A real repository grounds the optional-metadata policy: passing the
    // workspace path check is not authority for legacy discovery/config reads.
    assert!(git_head_snapshot(Some(&tool), &newt_core::Caveats::top()).is_some());
    let workspace = tmp.path().to_str().unwrap();
    let mut read_only = read_only_caveats(workspace);
    newt_core::caveats::lock_fs_to_workspace(&mut read_only, workspace, &[], &[]);
    assert_eq!(read_only.fs_write, newt_core::Scope::none());
    assert_eq!(read_only.exec, newt_core::Scope::none());
    assert_eq!(read_only.net, newt_core::Scope::none());
    assert!(git_head_snapshot(Some(&tool), &read_only).is_none());
    assert_eq!(
        newt_core::git_hardening::metadata_git(
            tmp.path(),
            &["status", "--porcelain=v1"],
            &read_only.fs_read,
        )
        .unwrap_err()
        .kind(),
        std::io::ErrorKind::PermissionDenied,
        "optional metadata must not bypass bounded reads"
    );
    let branches = newt_core::agentic::GitTool::dispatch(
        &tool,
        "branch-list",
        &serde_json::json!({"scope": "all"}),
        &newt_core::git_caveats::GitCaveats::from_session(&read_only),
        &read_only,
    )
    .expect("native branch-list works with the same bounded read-only capability");
    assert!(branches.contains("local branches: 0"), "{branches}");
    assert!(
        branches.contains("cached remote-tracking branches: 0"),
        "{branches}"
    );
    let unavailable = workspace_state_block(workspace, &read_only.fs_read);
    assert!(
        unavailable.contains("automatic git metadata: unavailable"),
        "{unavailable}"
    );
    assert!(!unavailable.contains("git: unavailable"), "{unavailable}");
    assert!(!unavailable.contains("local changes: clean"));
    assert!(!unavailable.contains("Recent commits:"));
    assert_eq!(
        lightweight_git_meta(workspace, &read_only.fs_read),
        (None, None)
    );
    let control = workspace_state_block(workspace, &newt_core::Scope::All);
    assert!(control.contains("local changes: clean"), "{control}");
}

#[test]
fn persistent_ingress_keeps_exact_raw_and_model_bytes_in_prompt_only_conversation() {
    let (_tmp, store, conversation_id) = prompt_store();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let raw = b"  inspect src \\\nthen test  ";
    let model = b"inspect src \nthen test";

    let context = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "inspect src",
        Some("coder"),
        raw,
        model,
        &ModelInputOrigin::Operator,
    )
    .unwrap();

    let submitted = context.submitted_prompt().receipt();
    assert_eq!(submitted.raw_text(), raw);
    assert_eq!(submitted.model_text(), model);
    assert_eq!(submitted.origin(), newt_core::PromptOrigin::Operator);
    assert_eq!(submitted.root_prompt_id(), submitted.id());
    submitted.verify_integrity().unwrap();

    let record = store.load(&conversation_id).unwrap();
    assert!(record.turns.is_empty(), "ingress precedes turn completion");
    assert_eq!(record.title, "inspect src");
    assert_eq!(record.persona.as_deref(), Some("coder"));
}

/// A3/W6 end-to-end at the seam level: a prompt enqueued via the attach
/// API is dequeued and minted by the running session (D2), its durable
/// receipt stays `origin=operator` (so no prompt_receipts CHECK migration),
/// the inbox row is linked to that receipt, and — crucially — a web-injected
/// line is NOT operator input to the TUI (its `/exit`/`!rm` can never reach
/// the host-shell/slash/history gates).
#[test]
fn web_injected_prompt_mints_operator_receipt_and_is_inert_tui_input() {
    // Containment: the load-bearing safety property.
    let origin = ModelInputOrigin::WebInjected {
        inbox_id: "ib-1".into(),
    };
    assert!(
        !origin.is_operator(),
        "a web-injected line must be inert model text, never TUI operator input"
    );

    let (_tmp, store, conversation_id) = prompt_store();
    store
        .create_with_id(&conversation_id, "attached session", None)
        .unwrap();
    // The attach surface enqueues; it never mints the turn.
    store
        .inject_prompt(&conversation_id, "fix the flaky test", Some("req-1"))
        .unwrap();
    let injected = store
        .take_injected_prompt(&conversation_id)
        .unwrap()
        .expect("one queued prompt");
    assert_eq!(injected.body, "fix the flaky test");

    // The RUNNING session mints the turn (D2), durable origin = operator.
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let context = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "attached session",
        None,
        injected.body.as_bytes(),
        injected.body.as_bytes(),
        &ModelInputOrigin::WebInjected {
            inbox_id: injected.id.clone(),
        },
    )
    .unwrap();
    let submitted = context.submitted_prompt().receipt();
    assert_eq!(
        submitted.origin(),
        newt_core::PromptOrigin::Operator,
        "durable origin stays operator — no prompt_receipts CHECK migration"
    );
    submitted.verify_integrity().unwrap();

    // Additive provenance + exactly-once drain.
    store
        .link_inbox_delivery(&injected.id, &submitted.id().to_string())
        .unwrap();
    assert_eq!(
        store.take_injected_prompt(&conversation_id).unwrap(),
        None,
        "the inbox drained exactly once"
    );
}

#[test]
fn persistent_ingress_error_is_returned_before_a_prompt_can_run() {
    let (_tmp, store, _conversation_id) = prompt_store();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let err = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        "../outside",
        "unsafe id",
        None,
        b"do work",
        b"do work",
        &ModelInputOrigin::Operator,
    )
    .unwrap_err();

    assert!(err.to_string().contains("invalid"), "got: {err}");
    assert!(store.list().unwrap().is_empty());
}

#[test]
fn ephemeral_ingress_has_equivalent_context_without_a_store() {
    let conversation_id = newt_core::new_conversation_id();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let context = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "unused",
        None,
        b" raw ",
        b"raw",
        &ModelInputOrigin::Operator,
    )
    .unwrap();

    assert_eq!(context.submitted_prompt().receipt().raw_text(), b" raw ");
    assert_eq!(context.active_operator_prompt().model_text(), b"raw");
    assert_eq!(
        context.submitted_prompt().receipt().origin(),
        newt_core::PromptOrigin::Operator
    );
}

#[test]
fn ephemeral_ingress_chains_attempts_and_fences_a_new_conversation() {
    use newt_core::agentic::PromptSource as _;

    let prompts = newt_core::agentic::SessionPromptStore::default();
    let first_conversation = newt_core::new_conversation_id();
    let first = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &prompts,
        },
        &first_conversation,
        "unused",
        None,
        b"first raw",
        b"FIRST",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    let second = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &prompts,
        },
        &first_conversation,
        "unused",
        None,
        b"second raw",
        b"SECOND",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    assert_eq!(
        second.submitted().receipt().previous_prompt_id(),
        Some(first.submitted().id())
    );

    let retry_one = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &prompts,
        },
        &first_conversation,
        "unused",
        None,
        b"retry one raw",
        b"RETRY ONE",
        &ModelInputOrigin::HarnessRetry {
            parent: Box::new(second.clone()),
        },
    )
    .unwrap();
    let retry_two = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &prompts,
        },
        &first_conversation,
        "unused",
        None,
        b"retry two raw",
        b"RETRY TWO",
        &ModelInputOrigin::HarnessRetry {
            parent: Box::new(retry_one.clone()),
        },
    )
    .unwrap();
    assert_eq!(
        retry_two.submitted().receipt().previous_prompt_id(),
        Some(retry_one.submitted().id())
    );
    assert_eq!(
        retry_two.submitted().receipt().parent_prompt_id(),
        Some(retry_one.submitted().id())
    );
    assert_eq!(
        prompts
            .source(&first_conversation)
            .fetch_prompt(retry_one.submitted().id())
            .unwrap()
            .unwrap()
            .model_text(),
        b"RETRY ONE"
    );

    // `/new` changes this binding. Even though the process-local store
    // retains the old receipts until exit, the new view cannot address
    // them and therefore cannot leak the previous task.
    let new_conversation = newt_core::new_conversation_id();
    let fresh = begin_model_prompt(
        PromptIngress {
            durable: None,
            ephemeral: &prompts,
        },
        &new_conversation,
        "unused",
        None,
        b"fresh raw",
        b"FRESH",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    let fresh_source = prompts.source(&new_conversation);
    assert!(fresh_source
        .fetch_prompt(retry_one.submitted().id())
        .unwrap()
        .is_none());
    assert!(fresh_source
        .fetch_prompt(fresh.submitted().id())
        .unwrap()
        .is_some());
}

#[test]
fn harness_retry_is_derived_and_keeps_operator_root_active() {
    let (_tmp, store, conversation_id) = prompt_store();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let operator = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "fix the parser",
        None,
        b"fix the parser",
        b"fix the parser",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    let derived = ModelInputOrigin::HarnessRetry {
        parent: Box::new(operator.clone()),
    };
    let retry = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "fix the parser",
        None,
        b"/exit",
        b"/exit",
        &derived,
    )
    .unwrap();

    assert!(
        !derived.is_operator(),
        "retry must bypass human interceptors"
    );
    assert_eq!(
        retry.submitted_prompt().receipt().origin(),
        newt_core::PromptOrigin::HarnessRetry
    );
    assert_ne!(
        retry.submitted_prompt().id(),
        operator.submitted_prompt().id()
    );
    assert_eq!(
        retry.submitted_prompt().receipt().parent_prompt_id(),
        Some(operator.submitted_prompt().id())
    );
    assert_eq!(
        retry.active_operator_prompt().id(),
        operator.active_operator_prompt().id()
    );
    assert_eq!(
        retry.active_operator_prompt().model_text(),
        b"fix the parser"
    );

    let retry_again = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "fix the parser",
        None,
        b"ground it again",
        b"ground it again",
        &ModelInputOrigin::HarnessRetry {
            parent: Box::new(retry.clone()),
        },
    )
    .unwrap();
    assert_eq!(
        retry_again.submitted_prompt().receipt().parent_prompt_id(),
        Some(retry.submitted_prompt().id()),
        "attempt ancestry must not be flattened to the operator root"
    );
    assert_eq!(
        retry_again.active_operator_prompt().id(),
        operator.active_operator_prompt().id()
    );
    assert_eq!(
        active_operator_task(Some(&retry_again), "ground it again"),
        "fix the parser",
        "derived memory must never relabel retry prose as the active task"
    );
}

#[test]
fn clarification_answer_is_an_operator_continuation_of_the_pending_objective() {
    let (_tmp, store, conversation_id) = prompt_store();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let original = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "implement the selected storage backend",
        None,
        b"implement either SQLite or Postgres",
        b"implement either SQLite or Postgres",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    let answer_origin = ModelInputOrigin::OperatorContinuation {
        parent: Box::new(original.clone()),
    };
    let answer = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "implement the selected storage backend",
        None,
        b"1: SQLite",
        b"1: SQLite",
        &answer_origin,
    )
    .unwrap();

    assert!(answer_origin.is_operator());
    assert_eq!(
        answer.submitted_prompt().receipt().parent_prompt_id(),
        Some(original.submitted_prompt().id())
    );
    assert_eq!(
        answer.submitted_prompt().receipt().root_prompt_id(),
        original.submitted_prompt().receipt().root_prompt_id(),
        "a clarification answer must retain the original objective root"
    );
    // bug/steering-regressions (#1443): a clarification/decision CONTINUATION
    // refines the parent objective — it must NOT become the active operator
    // authority. Otherwise the protected prompt card carries the ceremony
    // reply ("1: SQLite") for the whole turn and mid-turn compaction can
    // evict the real task.
    assert_eq!(
        answer.active_operator_prompt().id(),
        original.submitted_prompt().id(),
        "a clarification answer must keep the original objective as active authority"
    );
    assert_ne!(
        answer.active_operator_prompt().id(),
        answer.submitted_prompt().id(),
        "the ceremony reply itself is not the active operator prompt"
    );
}

#[test]
fn durable_pending_clarification_rehydrates_its_lineage_after_resume() {
    let (_tmp, store, conversation_id) = prompt_store();
    let ephemeral_prompts = newt_core::agentic::SessionPromptStore::default();
    let original = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "select storage",
        None,
        b"Implement either SQLite or Postgres.",
        b"Implement either SQLite or Postgres.",
        &ModelInputOrigin::Operator,
    )
    .unwrap();
    let unclear_answer = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "select storage",
        None,
        b"continue",
        b"continue",
        &ModelInputOrigin::OperatorContinuation {
            parent: Box::new(original.clone()),
        },
    )
    .unwrap();

    let restored = store
        .turn_prompt_context(&conversation_id, unclear_answer.submitted_prompt().id())
        .unwrap()
        .expect("durable prompt context");
    let pending = rehydrate_pending_clarification(&store, &conversation_id, &restored)
        .unwrap()
        .expect("unclear answer must remain an outstanding clarification");
    assert_eq!(
        pending.parent.submitted_prompt().id(),
        unclear_answer.submitted_prompt().id(),
        "the next answer must descend from the durable latest clarification receipt"
    );
    assert_eq!(
        pending.intake.disposition(),
        newt_core::agentic::PromptDisposition::Ask
    );

    let resolved = begin_model_prompt(
        PromptIngress {
            durable: Some(&store),
            ephemeral: &ephemeral_prompts,
        },
        &conversation_id,
        "select storage",
        None,
        b"1: SQLite",
        b"1: SQLite",
        &ModelInputOrigin::OperatorContinuation {
            parent: pending.parent.clone(),
        },
    )
    .unwrap();
    assert_eq!(
        resolved.submitted_prompt().receipt().root_prompt_id(),
        original.submitted_prompt().receipt().root_prompt_id(),
        "the resumed answer remains in the original objective"
    );
    let resolved_context = store
        .turn_prompt_context(&conversation_id, resolved.submitted_prompt().id())
        .unwrap()
        .expect("durable resolved context");
    assert!(
        rehydrate_pending_clarification(&store, &conversation_id, &resolved_context)
            .unwrap()
            .is_none(),
        "a fully explicit answer must clear the recovered pending state"
    );
}

/// #2515: `/discuss` (the clarification batch's own advertised escape
/// hatch) must reach the pending clarification, not the slash registry —
/// and only while something is actually pending. This is the input-routing
/// decision that was wrong before the fix: it lived as an inline
/// `task.starts_with('/')` check with no way to exercise it without driving
/// the whole REPL loop.
#[test]
fn discuss_routes_to_pending_clarification_only_when_something_is_pending() {
    assert!(line_answers_pending_clarification(
        "/discuss why does this need a decision at all?",
        true
    ));
    assert!(!line_answers_pending_clarification(
        "/discuss why does this need a decision at all?",
        false
    ));
}

/// The `/chat` alias behaves identically to `/discuss`.
#[test]
fn chat_alias_routes_to_pending_clarification() {
    assert!(line_answers_pending_clarification("/chat go on", true));
    assert!(!line_answers_pending_clarification("/chat go on", false));
}

/// A bare `/discuss` (no trailing text) still counts — the operator may just
/// want the batch re-explained.
#[test]
fn bare_discuss_routes_to_pending_clarification() {
    assert!(line_answers_pending_clarification("/discuss", true));
}

/// Every other `/word` keeps going to the slash registry even with a batch
/// pending — the batch text promises `/new` keeps working, and nothing here
/// should quietly swallow `/help` or `/exit` too.
#[test]
fn other_slash_commands_never_divert_to_pending_clarification() {
    for line in ["/help", "/new", "/exit"] {
        assert!(
            !line_answers_pending_clarification(line, true),
            "{line} must still reach the slash registry with a batch pending"
        );
    }
}

/// `/discussion-of-x` is not the command — the prefix must be followed by
/// whitespace or end of input, matching `discussion_request`'s own rule.
#[test]
fn discuss_prefix_must_not_be_glued_to_more_text() {
    assert!(!line_answers_pending_clarification(
        "/discussion-of-x",
        true
    ));
}