quarb-session 0.74.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
//! 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 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(),
            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.
    pub fn seed_defs(&mut self, text: &str) -> Result<()> {
        quarb::parse_defs(text).context("parsing --defs")?;
        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).context("parsing --defs")?;
        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 frozen-recall line: it takes the next number and keeps
    /// its own snapshot, but is not itself a referenceable fragment body.
    pub fn record_frozen(&mut self, snapshot: Vec<Cell>) {
        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.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 two suffixes, not the engine, whose lexer has no `#` 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.
pub fn history_head(line: &str) -> Option<(usize, char, &str)> {
    let rest = line.trim().strip_prefix('&')?;
    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 tail = rest[1..].trim_start();
    if !(tail.is_empty()
        || tail.starts_with('|')
        || tail.starts_with("@|")
        || tail.starts_with("*__"))
    {
        return None;
    }
    Some((n, suffix, tail))
}