quarb-session 0.75.0

Backend-agnostic interactive Quarb session — the history of labelled fragments (&N/&N!/&N#) over a pluggable Executor and Store
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
//! The session: a fragment table where each accepted line becomes
//! `def &N: <line> ;`, evaluated through an [`Executor`] and persisted
//! through a [`Store`].
//!
//! History is the language's own reuse mechanism, not a bolted-on
//! cell store: line 3 is the fragment `&3`, continued through the pipe
//! (`&3 | /name::`, `&3 @| [pred]`, `&3 @| count`). Frozen recall
//! (`&N=`) replays a line's captured footprint; the live/version-
//! pinned variants sharpen once a re-materializing executor (the
//! daemon) is in play.

use crate::{Cell, Executor, SessionState, Store};
use anyhow::{Context, Result};
use std::collections::HashMap;

pub struct Session {
    executor: Box<dyn Executor>,
    store: Box<dyn Store>,
    /// The fragment table as definition text, re-parsed per query
    /// (`def &1: …;\n …`). Kept as text so it seeds from `--defs`,
    /// round-trips for display, and persists trivially.
    defs_text: String,
    /// Each line's rendered output, captured at commit — the frozen
    /// footprint a `&N=` recall replays. In memory only for now.
    snapshots: HashMap<usize, Vec<Cell>>,
    /// The lines that replayed a stored result, each with the line
    /// whose result it was: such a line has a result and no query, so
    /// `&N` of it names nothing to run ([`Session::read`] says so).
    replays: HashMap<usize, usize>,
    /// The next line's number — the `&N` a fresh line will claim.
    line_no: usize,
    /// A bound every line is held to before it runs: the executor
    /// plans the line and a plan past the bound is refused unrun.
    budget: Option<quarb::plan::Budget>,
}

impl Session {
    /// Build a session over an executor and a store, restoring any
    /// persisted fragment history from the store.
    pub fn new(executor: Box<dyn Executor>, store: Box<dyn Store>) -> Session {
        let state = store.load().unwrap_or_default();
        let line_no = state.line_no.max(1);
        Session {
            executor,
            store,
            defs_text: state.defs_text,
            snapshots: HashMap::new(),
            replays: HashMap::new(),
            line_no,
            budget: None,
        }
    }

    /// Hold every line to a budget (`None` lifts it): the executor
    /// plans the line first, and a line whose estimate passes the
    /// bound is refused before anything is read.
    pub fn set_budget(&mut self, budget: Option<quarb::plan::Budget>) {
        self.budget = budget;
    }

    /// The budget the session holds its lines to, if any.
    pub fn budget(&self) -> Option<&quarb::plan::Budget> {
        self.budget.as_ref()
    }

    /// The static plan of a line — history refs resolved as in
    /// [`eval`](Self::eval) — priced by the executor, under the
    /// session's budget when one is set.
    pub fn plan(&self, line: &str) -> Result<quarb::plan::Plan> {
        self.executor
            .plan(&self.combined(line), self.budget.as_ref())
    }

    /// The plan of a line as its kaiv payload, the line as its
    /// `query` value.
    pub fn plan_text(&self, line: &str) -> Result<String> {
        Ok(self.plan(line)?.to_kaiv(line))
    }

    /// The budget's check of a combined query: nothing to do without
    /// one; with one, the plan past the bound is the refusal.
    fn within_budget(&self, query: &str) -> Result<()> {
        if let Some(b) = &self.budget {
            let plan = self.executor.plan(query, Some(b))?;
            if let Some(why) = b.exceeded_by(&plan) {
                return Err(quarb::QuarbError::refused(why).into());
            }
        }
        Ok(())
    }

    /// Swap the executor under a running session — an in-session
    /// remount (`:mount`). History and the fragment table stay: `&N`
    /// re-runs against the new source set.
    pub fn set_executor(&mut self, executor: Box<dyn Executor>) {
        self.executor = executor;
    }

    /// Seed the fragment table from a `--defs` file (validated first).
    /// Stored stripped of `#` comment lines: the table is prepended
    /// to query text, and the query lexer has no comment syntax.
    ///
    /// The statements are added to what the table holds, a model's
    /// definitions and then a `--defs` file's: the table was assigned,
    /// so the second seeding dropped the first, and a persisted
    /// session lost its own definitions at every start. What the
    /// table holds already is not added again.
    ///
    /// The engine's error comes back as it is: the host names the
    /// file the definitions stand in, as `qua` does ("parsing
    /// definitions in FILE"). (It was laid under "parsing --defs"
    /// here, for a model's definitions too.)
    pub fn seed_defs(&mut self, text: &str) -> Result<()> {
        quarb::parse_defs(text)?;
        let stripped = quarb::strip_defs_comments(text);
        if !stripped.trim().is_empty() && self.defs_text.contains(stripped.trim()) {
            return Ok(());
        }
        let candidate = format!("{}{}\n", self.defs_text, stripped);
        quarb::parse_defs(&candidate)?;
        self.defs_text = candidate;
        self.persist();
        Ok(())
    }

    /// Whether a line closes with a session push, `| ,name`, asked of
    /// the parsed line with the session's definitions in scope.
    pub fn closes_with_session_push(&self, line: &str) -> bool {
        quarb::closes_with_session_push(&self.combined(line))
    }

    /// Add a `def`/`macro` line to the table (validated first). Unlike
    /// a query line, a definition is not run — but it is a cell of the
    /// session and takes its ordinal (spec: .quai, Numbering): the line
    /// number advances, with no result behind it, so `&N` of a
    /// definition is a reference to a cell with no result and `&N=`
    /// replays nothing.
    pub fn add_def(&mut self, line: &str) -> Result<()> {
        let candidate = format!("{}{}\n", self.defs_text, line);
        quarb::parse_defs(&candidate).context("parsing definition")?;
        self.defs_text = candidate;
        self.snapshots.insert(self.line_no, Vec::new());
        self.line_no += 1;
        self.persist();
        Ok(())
    }

    /// The line with the fragment table prepended, so history refs
    /// resolve inline.
    fn combined(&self, line: &str) -> String {
        if self.defs_text.is_empty() {
            line.to_string()
        } else {
            format!("{}\n{line}", self.defs_text)
        }
    }

    /// A line's result, an engine error's position told in the line
    /// as it was written: the table stands in front of the line that
    /// runs, and its length was counted in (one line was refused "at
    /// character 19" as a session's first and "at character 91" as
    /// its fourth).
    fn in_line<T>(&self, result: Result<T>) -> Result<T> {
        if self.defs_text.is_empty() {
            return result;
        }
        let before = self.defs_text.chars().count() + 1;
        result.map_err(|e| match e.downcast::<quarb::QuarbError>() {
            Ok(q) => q.in_text_after(before).into(),
            Err(e) => e,
        })
    }

    /// Evaluate a line against the standing arbor (`&N`). Pure —
    /// history is not touched (a failed line commits nothing).
    pub fn eval(&self, line: &str) -> Result<Vec<Cell>> {
        let q = self.combined(line);
        self.within_budget(&q)?;
        self.in_line(self.executor.run(&q))
    }

    /// Evaluate a line, and when its closing command is `@| pretty`,
    /// hand back the HTML grid beside the cells (the text table as
    /// one cell) — the browser hosts' path; see
    /// [`crate::Executor::run_table`].
    pub fn eval_table(&self, line: &str) -> Result<(Vec<Cell>, Option<String>)> {
        let q = self.combined(line);
        self.within_budget(&q)?;
        self.in_line(if quarb::closes_with_table(&q) {
            self.executor.run_table(&q)
        } else {
            self.executor.run(&q).map(|cells| (cells, None))
        })
    }

    /// Evaluate a line and hand back its rich form beside the cells
    /// (the rendering rule, 2026-11-09): the browser hosts' path for
    /// every line — see [`crate::Executor::run_rich`].
    pub fn eval_rich(&self, line: &str) -> Result<(Vec<Cell>, Option<String>)> {
        let q = self.combined(line);
        self.within_budget(&q)?;
        self.in_line(self.executor.run_rich(&q))
    }

    /// The rich form of values already in hand (a frozen `&N=`
    /// replay), under the session's setting.
    pub fn rich_of(&self, cells: &[Cell]) -> Option<String> {
        let mode = self.pretty_mode();
        let values: Vec<quarb::Value> = cells
            .iter()
            .filter_map(|c| match c {
                Cell::Value(v) => Some(v.clone()),
                Cell::Node(_) => None,
            })
            .collect();
        quarb::rich::html_of(&values, None, None, mode)
    }

    /// The session's `--pretty` setting (`off` when it keeps no
    /// memory).
    pub fn pretty_mode(&self) -> quarb::PrettyMode {
        self.session_memory()
            .map(|m| m.borrow().pretty)
            .unwrap_or(quarb::PrettyMode::Off)
    }

    /// Set the session's `--pretty` setting from the host (the
    /// extension opens at `structures`, the playground at `off`).
    pub fn set_pretty(&self, mode: quarb::PrettyMode) {
        if let Some(m) = self.session_memory() {
            m.borrow_mut().pretty = mode;
        }
    }

    /// A line's rich form as a document fragment for an export
    /// (the stylesheet, the form, the diagnostics down to the
    /// session's level), or the text lines in a `<pre>` where there
    /// is none.
    pub fn export_rich(&self, line: &str) -> Result<String> {
        let (cells, html) = self.eval_rich(line)?;
        let diagnostics = self.diagnostics();
        let level = self.diagnostics_level();
        Ok(match html {
            Some(h) => quarb::rich::document(&h, &diagnostics, level),
            None => {
                let text: Vec<String> = cells.iter().map(|c| c.display()).collect();
                quarb::rich::document(
                    &format!(
                        "<pre class=\"quarb-text\">{}</pre>",
                        quarb::table::escape(&text.join("\n"))
                    ),
                    &diagnostics,
                    level,
                )
            }
        })
    }

    /// The unresolved external references the last evaluation
    /// recorded — see [`crate::Executor::refs`]. The host closes
    /// the loop: acquire, remount, re-run.
    pub fn refs(&self) -> Vec<String> {
        self.executor.refs()
    }

    /// The warnings and infos the last evaluation raised beside its
    /// answer (spec: Diagnostics), in raising order.
    pub fn diagnostics(&self) -> Vec<quarb::Diagnostic> {
        self.executor.diagnostics()
    }

    /// The diagnostics level the session shows
    /// (`session(--diagnostics=…)`; warning when the session keeps
    /// no memory).
    pub fn diagnostics_level(&self) -> quarb::Severity {
        self.session_memory()
            .map(|m| m.borrow().diagnostics)
            .unwrap_or(quarb::Severity::Warning)
    }

    /// The session memory, when the executor keeps one.
    pub fn session_memory(&self) -> Option<quarb::SessionMemory> {
        self.executor.session_memory()
    }

    /// Evaluate a line against a freshly re-materialized source — the
    /// `&N!` live reading, which sees current data.
    pub fn eval_fresh(&self, line: &str) -> Result<Vec<Cell>> {
        let q = self.combined(line);
        self.within_budget(&q)?;
        self.in_line(self.executor.run_fresh(&q))
    }

    /// Run a line and render its results as exportable markup
    /// (`md`, `html`, `txt`) — the panel's rendered-export path.
    /// History refs resolve inline, exactly as in [`eval`](Self::eval);
    /// an empty line exports the whole document.
    pub fn export(&self, line: &str, kind: &str) -> Result<String> {
        let line = line.trim();
        if line.is_empty() {
            return self.executor.export("", kind);
        }
        self.executor.export(&self.combined(line), kind)
    }

    /// Register an accepted line as `&N` and capture its output as the
    /// frozen footprint for `&N=`. Returns whether the line's shape
    /// could be a fragment body (so `&N` will resolve); either way the
    /// line number advances so labels track what the user saw.
    pub fn commit(&mut self, line: &str, snapshot: Vec<Cell>) -> bool {
        self.snapshots.insert(self.line_no, snapshot);
        // A space before the `;` terminator: a line ending in a `::`
        // projection would otherwise lex `::;` as the metadata sigil.
        let candidate = format!("{}def &{}: {} ;\n", self.defs_text, self.line_no, line);
        let referenceable = quarb::parse_defs(&candidate).is_ok();
        if referenceable {
            self.defs_text = candidate;
        }
        self.line_no += 1;
        self.persist();
        referenceable
    }

    /// `&N= | …` — line N's frozen footprint as the head of a
    /// pipeline: the captured cells as literals, one cell the value
    /// itself, several a list spread into one thread each (a node
    /// cell its locator as text), then the tail. The query every
    /// host of a session runs for such a line.
    pub fn frozen_head_query(&self, n: usize, tail: &str) -> std::result::Result<String, String> {
        let cells = self
            .frozen(n)
            .ok_or_else(|| format!("&{n}= has no captured result (line {n} hasn't run)"))?;
        let lits: Vec<String> = cells
            .iter()
            .map(|c| match c {
                Cell::Value(v) => v.to_quarb(),
                Cell::Node(s) => quarb::Value::Str(s.clone()).to_quarb(),
            })
            .collect();
        let head = match lits.as_slice() {
            [one] => one.clone(),
            many => format!("@({}) | ...", many.join("; ")),
        };
        Ok(format!("= {head} {tail}"))
    }

    /// The frozen output of line `n`, if captured — what a `&N=`
    /// recall replays.
    pub fn frozen(&self, n: usize) -> Option<&Vec<Cell>> {
        self.snapshots.get(&n)
    }

    /// Record a line that replayed the stored result of line `of`: it
    /// takes the next number and keeps its own snapshot, but is not
    /// itself a referenceable fragment body.
    pub fn record_frozen(&mut self, of: usize, snapshot: Vec<Cell>) {
        self.replays.insert(self.line_no, of);
        self.snapshots.insert(self.line_no, snapshot);
        self.line_no += 1;
        self.persist();
    }

    /// Persist the durable state (best-effort; a store error does not
    /// abort the session).
    fn persist(&self) {
        let state = SessionState {
            defs_text: self.defs_text.clone(),
            line_no: self.line_no,
        };
        let _ = self.store.save(&state);
    }

    /// The `&N` a fresh line will claim.
    /// Tab-completion candidates for a line being edited.
    /// Session-aware by construction: the executor answers with
    /// its live arbor when it has one, the syntax tier otherwise.
    pub fn complete(&self, text: &str, cursor: usize) -> Vec<quarb::complete::Candidate> {
        self.executor.complete(text, cursor)
    }

    pub fn line_no(&self) -> usize {
        self.line_no
    }

    /// The fragment history text, for a `:history` command.
    pub fn history(&self) -> &str {
        &self.defs_text
    }

    /// Replace the fragment history and line counter — restoring a
    /// persisted session (e.g. from the browser's localStorage). Frozen
    /// snapshots are not restored; they regenerate on re-run.
    pub fn restore(&mut self, defs_text: String, line_no: usize) {
        self.defs_text = defs_text;
        self.line_no = line_no.max(1);
    }

    /// Clear the fragment history and restart line numbering.
    pub fn reset(&mut self) {
        self.defs_text.clear();
        self.snapshots.clear();
        self.replays.clear();
        self.line_no = 1;
        self.persist();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MemStore;

    struct NullExec;
    impl Executor for NullExec {
        fn run(&self, _query: &str) -> anyhow::Result<Vec<Cell>> {
            Ok(vec![])
        }
    }

    /// A commented defs file seeds a table the query lexer can take:
    /// the stored text is prepended to every line, and the lexer has
    /// no comment syntax, so `#` lines must not survive seeding.
    #[test]
    fn seed_defs_strips_comments() {
        let mut s = Session::new(Box::new(NullExec), Box::new(MemStore));
        s.seed_defs("# a library header\ndef &a: /x;\n# and a note\ndef &b: /y;")
            .unwrap();
        assert!(!s.history().contains('#'), "history: {}", s.history());
        assert!(s.history().contains("def &a"));
        assert!(s.history().contains("def &b"));
    }
}

/// `&N=` / `&N!` heading a line, alone or before a pipe tail
/// (`&4= | ,df`, `&4! | count`): N, the suffix, and the tail from its
/// pipe (empty when the reference stands alone). The session reads
/// the suffixes, not the engine, whose lexer refuses a glued `=` and
/// whose `!` marks a data-aware macro. One reading for every host:
/// the terminal's had it alone, and the browser's refused `&3# |
/// count` and handed `&3! | count` to the engine.
///
/// `=` is the stored result, as it was when the line ran, nothing
/// run; it was written `#` through 0.74 (the user's ruling of
/// 2026-11-25: the quarq's `#` ran its body and this one ran
/// nothing, so the two take different marks, `&$.f!!` and `&N=`).
/// `#` is still read here, so that a host can refuse it naming the
/// spelling ([`retired_suffix`]).
///
/// The rounded spellings keep the suffix inside the parentheses
/// (the user's ruling of 2026-11-25): `(=3=)` and `(=3!)`, as
/// `(=3)` is `&3`. (`(=3!)` was resolved from `(=_!)` and then read
/// by nothing: the engine refused it as a bang on a pure fragment.)
pub fn history_head(line: &str) -> Option<(usize, char, &str)> {
    let line = line.trim();
    let (rest, rounded) = match line.strip_prefix('&') {
        Some(rest) => (rest, false),
        None => (line.strip_prefix("(=")?, true),
    };
    let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
    if digits == 0 {
        return None;
    }
    let n: usize = rest[..digits].parse().ok()?;
    let rest = &rest[digits..];
    let suffix = rest
        .chars()
        .next()
        .filter(|c| matches!(c, '=' | '!' | '#'))?;
    let rest = if rounded {
        // (the retired `#` never had a rounded spelling)
        if suffix == '#' {
            return None;
        }
        rest[1..].strip_prefix(')')?
    } else {
        &rest[1..]
    };
    let tail = rest.trim_start();
    if !(tail.is_empty()
        || tail.starts_with('|')
        || tail.starts_with("@|")
        || tail.starts_with("*__"))
    {
        return None;
    }
    Some((n, suffix, tail))
}

/// What a host answers `&N#` with: the stored result's suffix of
/// 0.74, retired, and the spelling that replaced it.
pub fn retired_suffix(n: usize) -> String {
    format!("'&{n}#' is retired: the stored result of line {n} is '&{n}='")
}

/// What hands the session a text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reader {
    /// A line of a session, a terminal's or a page's: `&_` and `&-N`
    /// are its forms, and a line that opens with `def` or `macro` is
    /// a definition.
    Line,
    /// A cell of a notebook file: it names its cell (`&N`; the
    /// previous-line forms are refused), a cell of definitions alone
    /// extends the table and one that goes on to a query is the
    /// query, and a cell whose first word is a model's statement is
    /// the model's.
    Cell,
}

/// What a session's text is: read once, for every host (the review
/// of 2026-11-23, front ends R2 and T3). The terminal's loop, the
/// notebook runner, the browser's line and its cell each decided
/// this for themselves, and each new kind of line (`man`, `version`,
/// the mount line, `&_`, the stored result's suffix) was written
/// into three or four of them, differing: a notebook's `&1=` cell
/// replayed in the terminal's runner and went to the engine in the
/// browser's; the retired `&N#` was refused by name where it stood
/// in the browser alone. A host asks [`Session::read`] and prints.
#[derive(Debug, Clone, PartialEq)]
pub enum Read {
    /// `man WORD`, `version`: the page, or the manual's refusal of a
    /// word it does not have. No query: it takes no ordinal.
    Manual(std::result::Result<String, String>),
    /// `mount NAME: ?options`: the sources read again under options,
    /// as the statements of a model cell (`mount NAME: ?…;`, one a
    /// line). The host has the sources.
    Remount(String),
    /// A mount line that names a target. A line re-reads a mounted
    /// source and adds none; the host says how one is added.
    MountTarget,
    /// A model cell of a file: its text (the re-reads alone, as
    /// [`Read::Remount`] has them, where the cell holds nothing
    /// else).
    Model(String),
    /// Refused before anything runs, in the session's own sentence.
    Refused(String),
    /// Definitions and nothing else: the fragment table's.
    Definitions(String),
    /// A line's stored result, alone: replayed, nothing run.
    Stored(usize),
    /// A query to run and to commit under this text: the line
    /// itself, a stored result at its head written out as literals
    /// before the tail, a live reference as its `&N` and the tail.
    /// `fresh`: against the source read again.
    Query { text: String, fresh: bool },
}

/// A line or a cell that re-reads mounted sources under options, as
/// a model cell the parser reads: `mount NAME: ?options`, the name
/// left out where one source is mounted (`mount: ?null=NA`), a
/// closing `;` or none. `None` for any other text: a query, or a
/// model cell whose mounts name targets.
pub fn remount_cell(text: &str) -> Option<String> {
    let mut out = String::new();
    for stmt in text.split(';') {
        let stmt = stmt.trim();
        if stmt.is_empty() {
            continue;
        }
        let rest = stmt.strip_prefix("mount")?;
        if !rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
            return None;
        }
        let (name, target) = rest.split_once(':')?;
        if !target.trim().starts_with('?') {
            return None;
        }
        out.push_str(&format!("mount {}: {};\n", name.trim(), target.trim()));
    }
    (!out.is_empty()).then_some(out)
}

/// The line a history reference `&N` with `suffix` names where it
/// stands anywhere in a text, outside a quoted string: `&3= | count`,
/// `(&12#) | dim`. A `#` or an `=` of the query's own (`| #`, `#(…)`,
/// ` = `) is no suffix: the suffix touches the digits, and what
/// follows it is no word.
pub fn embedded_ref(text: &str, suffix: char) -> Option<usize> {
    let chars: Vec<char> = text.chars().collect();
    let mut quote: Option<char> = None;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        match quote {
            Some(q) => {
                if c == '\\' {
                    i += 1;
                } else if c == q {
                    quote = None;
                }
            }
            None if c == '"' || c == '\'' => quote = Some(c),
            None if c == '&' => {
                let mut j = i + 1;
                while chars.get(j).is_some_and(|d| d.is_ascii_digit()) {
                    j += 1;
                }
                if j > i + 1 && chars.get(j) == Some(&suffix) {
                    let before = i == 0 || !chars[i - 1].is_alphanumeric();
                    let after = !chars.get(j + 1).is_some_and(|d| d.is_alphanumeric());
                    if before && after {
                        return chars[i + 1..j].iter().collect::<String>().parse().ok();
                    }
                }
            }
            None => {}
        }
        i += 1;
    }
    None
}

impl Session {
    /// The replay line a text invokes as a fragment, `&N` or its
    /// rounded `(=N)`, with the line it replayed: outside a quoted
    /// text, and not where a suffix makes it the stored result
    /// (`&N=`), which such a line has.
    fn names_a_replay(&self, text: &str) -> Option<(usize, usize)> {
        if self.replays.is_empty() {
            return None;
        }
        let chars: Vec<char> = text.chars().collect();
        let mut quote: Option<char> = None;
        let mut i = 0;
        while i < chars.len() {
            let c = chars[i];
            match quote {
                Some(q) => {
                    if c == '\\' {
                        i += 1;
                    } else if c == q {
                        quote = None;
                    }
                }
                None if c == '"' || c == '\'' => quote = Some(c),
                None if c == '&' || (c == '(' && chars.get(i + 1) == Some(&'=')) => {
                    let from = if c == '&' { i + 1 } else { i + 2 };
                    let mut j = from;
                    while chars.get(j).is_some_and(|d| d.is_ascii_digit()) {
                        j += 1;
                    }
                    let before = i == 0 || !chars[i - 1].is_alphanumeric();
                    let goes_on = chars
                        .get(j)
                        .is_some_and(|d| d.is_alphanumeric() || matches!(d, '=' | '_'));
                    if j > from
                        && before
                        && !goes_on
                        && let Ok(n) = chars[from..j].iter().collect::<String>().parse::<usize>()
                        && let Some(of) = self.replays.get(&n)
                    {
                        return Some((n, *of));
                    }
                }
                None => {}
            }
            i += 1;
        }
        None
    }

    /// What `text` is to this session ([`Read`]). Nothing is run and
    /// nothing committed: the host acts on the answer, prints in its
    /// own way, and keeps its own rule for the ordinal of a text
    /// that is refused (a session's line takes none, a file's cell
    /// keeps its own).
    pub fn read(&self, text: &str, reader: Reader) -> Read {
        let text = text.trim();
        // the manual and the build: no query opens with a bare word
        if let Some(page) = quarb::man::line(text) {
            return Read::Manual(page);
        }
        let first = text.split_whitespace().next().unwrap_or_default();
        let defines = text.starts_with("def ")
            || text == "def"
            || text.starts_with("macro ")
            || text == "macro";
        let resolved;
        let text = match reader {
            Reader::Line => {
                // `mount NAME: ?options`, and a mount line that is
                // none
                if let Some(cell) = remount_cell(text) {
                    return Read::Remount(cell);
                }
                if text
                    .strip_prefix("mount")
                    .is_some_and(|rest| rest.starts_with(|c: char| c.is_whitespace() || c == ':'))
                {
                    return Read::MountTarget;
                }
                // `&_`, `&-N`: the label they name, before anything
                // else reads the line (a failed line takes no label,
                // so the latest label is the last line that ran)
                let last = self.line_no().saturating_sub(1);
                resolved = match quarb::resolve_previous_line(text, last) {
                    Ok(resolved) => resolved,
                    Err(e) => return Read::Refused(e),
                };
                let text = resolved.as_deref().unwrap_or(text);
                if text.starts_with("def ")
                    || text == "def"
                    || text.starts_with("macro ")
                    || text == "macro"
                {
                    return Read::Definitions(text.to_string());
                }
                text
            }
            Reader::Cell => {
                // a file names its cell
                if let Some(why) = quarb::previous_line_in_a_file(text) {
                    return Read::Refused(why);
                }
                // definitions alone go to the table; a cell that
                // holds a definition and its query is the query, run
                // whole as `qua` runs it
                // (read with the session's definitions before it, as
                // the definitions are filed: a `def` whose body names
                // an earlier cell's fragment, `def &big: &b[…];`, did
                // not parse alone, was taken for a query and refused
                // as one, "a query branch needs at least one step";
                // the review of 2026-11-26, A11)
                let defs_alone =
                    defines && quarb::parse_defs(&format!("{}{text}", self.defs_text)).is_ok();
                if defs_alone {
                    return Read::Definitions(text.to_string());
                }
                // a model cell, or the re-read of the one source
                // (the bare `mount:` is no keyword of the model's)
                let re_read = remount_cell(text);
                if (quarb_model::STATEMENTS.contains(&first) && !defines) || re_read.is_some() {
                    return Read::Model(re_read.unwrap_or_else(|| text.to_string()));
                }
                text
            }
        };
        // the stored result's suffix of 0.74, refused by name
        // wherever it stands
        if let Some(n) = embedded_ref(text, '#') {
            return Read::Refused(retired_suffix(n));
        }
        // `&N` of a line that replayed a stored result: the line has
        // a result and no query (the user's ruling of 2026-11-25: the
        // behaviour stays, and the line says why; it was "unknown
        // fragment '&2'", of a number the session had just given)
        if let Some((n, of)) = self.names_a_replay(text) {
            return Read::Refused(format!(
                "'&{n}' is no query: line {n} replayed the stored result of line {of}; \
                 '&{of}' runs that line's query again, '&{n}=' gives the result line {n} showed"
            ));
        }
        match history_head(text) {
            Some((n, '=', "")) => Read::Stored(n),
            Some((n, '=', tail)) => match self.frozen_head_query(n, tail) {
                Ok(headed) => Read::Query {
                    text: headed,
                    fresh: false,
                },
                Err(e) => Read::Refused(e),
            },
            Some((n, '!', tail)) => Read::Query {
                text: format!("&{n} {tail}").trim_end().to_string(),
                fresh: true,
            },
            // a stored result anywhere else in a line has no meaning
            _ if embedded_ref(text, '=').is_some() => Read::Refused(
                "'&N=' recalls a stored result: alone on a line, or at its head before a pipe \
                 ('&N= | count')"
                    .to_string(),
            ),
            _ => Read::Query {
                text: text.to_string(),
                fresh: false,
            },
        }
    }
}