Skip to main content

webizen_studio/
keep_volume.rs

1//! Keep volume browse โ€” sayable reopen, held-gate, real commit only.
2//!
3//! Live ALL_BOUND binds: `GraphDatabase.volume_open` ยท `GraphDatabase.volume_commit`.
4//! No Host invent. Missing volume โ†’ held / not yet. Never "unavailable".
5//! Celebrate only when `volume_commit` returns `written > 0`.
6
7use serde::{Deserialize, Serialize};
8
9/// Live ALL_BOUND id. Do not invent a Host method.
10pub const OPEN_ID: &str = "GraphDatabase.volume_open";
11/// Live ALL_BOUND id. Do not invent a Host method.
12pub const COMMIT_ID: &str = "GraphDatabase.volume_commit";
13
14/// Soft why-text for missing / unknown / E300. Never "broken". Never "unavailable".
15pub const HELD_WHY: &str = "held / not yet โ€” keep a volume";
16
17pub const RECENT_STORAGE_KEY: &str = "qualia-ui:keep-recent-volumes";
18pub const MAX_RECENTS: usize = 8;
19pub const MAX_BROWSE: usize = 12;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum VolumeLook {
23    Closed,
24    Open,
25    Committed,
26    Held,
27    Fault,
28}
29
30impl VolumeLook {
31    /// `&str` form.
32    pub fn as_str(self) -> &'static str {
33        match self {
34            Self::Closed => "closed",
35            Self::Open => "open",
36            Self::Committed => "committed",
37            Self::Held => "held",
38            Self::Fault => "fault",
39        }
40    }
41
42    /// Label.
43    pub fn label(self) -> &'static str {
44        match self {
45            Self::Closed => "closed",
46            Self::Open => "open",
47            Self::Committed => "committed",
48            Self::Held | Self::Fault => "held / not yet",
49        }
50    }
51
52    /// Named beat.
53    pub fn named_beat(self) -> &'static str {
54        match self {
55            Self::Open => "dwell",
56            Self::Committed => "exit",
57            Self::Closed | Self::Held | Self::Fault => "entrance",
58        }
59    }
60}
61
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63pub struct RecentVolume {
64    pub path: String,
65    pub sayable: String,
66}
67
68#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
69pub struct VaultVolume {
70    #[serde(default)]
71    pub path: String,
72    #[serde(default)]
73    pub display_name: String,
74    #[serde(default)]
75    pub relative: String,
76    #[serde(default)]
77    pub open_error: Option<String>,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub enum KeepOutcome {
82    Held {
83        why: String,
84    },
85    Open {
86        path: String,
87        sayable: String,
88    },
89    Committed {
90        path: String,
91        sayable: String,
92        written: u64,
93    },
94}
95
96impl KeepOutcome {
97    /// Volume look.
98    pub fn look(&self) -> VolumeLook {
99        match self {
100            Self::Held { .. } => VolumeLook::Held,
101            Self::Open { .. } => VolumeLook::Open,
102            Self::Committed { .. } => VolumeLook::Committed,
103        }
104    }
105
106    /// `true` when the volume celebrates.
107    pub fn celebrates(&self) -> bool {
108        matches!(self, Self::Committed { written, .. } if *written > 0)
109    }
110}
111
112/// Human-sayable name for a path.
113pub fn sayable_name(path: &str) -> String {
114    let file = path.rsplit(['/', '\\']).next().unwrap_or(path).trim();
115    let stem = file
116        .strip_suffix(".q42")
117        .or_else(|| file.strip_suffix(".Q42"))
118        .unwrap_or(file);
119    let pretty = stem.replace(['-', '_'], " ");
120    let trimmed = pretty.trim();
121    if trimmed.is_empty() {
122        "keep".to_string()
123    } else {
124        trimmed.to_string()
125    }
126}
127
128/// Held outcome.
129pub fn held_outcome(why: &str) -> KeepOutcome {
130    KeepOutcome::Held {
131        why: sanitize_held_why(why),
132    }
133}
134
135/// Sanitizes a held reason.
136pub fn sanitize_held_why(raw: &str) -> String {
137    let folded = raw.to_ascii_lowercase();
138    if raw.trim().is_empty()
139        || folded.contains("unavailable")
140        || folded.contains("broken")
141        || folded.contains("e300")
142    {
143        HELD_WHY.to_string()
144    } else if folded.contains("held / not yet") {
145        raw.trim().to_string()
146    } else {
147        HELD_WHY.to_string()
148    }
149}
150
151/// `true` when copy avoids "unavailable".
152pub fn copy_avoids_unavailable(text: &str) -> bool {
153    !text.to_ascii_lowercase().contains("unavailable")
154}
155
156/// `true` when copy avoids broken terms.
157pub fn copy_avoids_broken(text: &str) -> bool {
158    !text.to_ascii_lowercase().contains("broken")
159}
160
161/// Celebrate only on a real durable write. Local checkpoint / deny / empty written never.
162pub fn celebrate_commit(ok: bool, written: u64) -> bool {
163    ok && written > 0
164}
165
166/// Parses u64-field.
167pub fn parse_u64_field(src: &str, key: &str) -> u64 {
168    let patterns = [
169        format!("{key}: "),
170        format!("{key}:"),
171        format!("\"{key}\": "),
172        format!("\"{key}\":"),
173    ];
174    for pat in patterns {
175        if let Some(start) = src.find(&pat) {
176            let rest = src[start + pat.len()..].trim_start();
177            let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
178            if let Ok(n) = digits.parse::<u64>() {
179                return n;
180            }
181        }
182    }
183    0
184}
185
186/// Interprets an open action.
187pub fn interpret_open(ok: bool, value: &str, diagnostic: Option<&str>, path: &str) -> KeepOutcome {
188    if ok {
189        return KeepOutcome::Open {
190            path: path.to_string(),
191            sayable: sayable_name(path),
192        };
193    }
194    let _ = (value, diagnostic);
195    held_outcome(HELD_WHY)
196}
197
198/// Interprets a commit action.
199pub fn interpret_commit(
200    ok: bool,
201    value: &str,
202    diagnostic: Option<&str>,
203    path: &str,
204) -> KeepOutcome {
205    let written = parse_u64_field(value, "written");
206    if celebrate_commit(ok, written) {
207        return KeepOutcome::Committed {
208            path: path.to_string(),
209            sayable: sayable_name(path),
210            written,
211        };
212    }
213    let _ = diagnostic;
214    held_outcome(HELD_WHY)
215}
216
217/// Remembers a recent item.
218pub fn remember_recent(recents: &[RecentVolume], path: &str) -> Vec<RecentVolume> {
219    let path = path.trim();
220    if path.is_empty() {
221        return recents.to_vec();
222    }
223    let mut out = vec![RecentVolume {
224        path: path.to_string(),
225        sayable: sayable_name(path),
226    }];
227    for item in recents {
228        if item.path != path {
229            out.push(item.clone());
230        }
231        if out.len() >= MAX_RECENTS {
232            break;
233        }
234    }
235    out
236}
237
238/// Parses recents-json.
239pub fn parse_recents_json(raw: &str) -> Vec<RecentVolume> {
240    serde_json::from_str::<Vec<RecentVolume>>(raw)
241        .unwrap_or_default()
242        .into_iter()
243        .filter(|item| !item.path.trim().is_empty())
244        .take(MAX_RECENTS)
245        .map(|mut item| {
246            if item.sayable.trim().is_empty() {
247                item.sayable = sayable_name(&item.path);
248            }
249            item
250        })
251        .collect()
252}
253
254/// Recents as JSON.
255pub fn recents_json(recents: &[RecentVolume]) -> String {
256    serde_json::to_string(recents).unwrap_or_else(|_| "[]".into())
257}
258
259/// Merges a browse list.
260pub fn merge_browse_list(recents: &[RecentVolume], vault: &[VaultVolume]) -> Vec<RecentVolume> {
261    let mut out = Vec::new();
262    let mut seen = Vec::new();
263    for item in recents {
264        if seen.iter().any(|p| p == &item.path) {
265            continue;
266        }
267        seen.push(item.path.clone());
268        out.push(item.clone());
269        if out.len() >= MAX_BROWSE {
270            return out;
271        }
272    }
273    for item in vault {
274        if item.path.trim().is_empty() || seen.iter().any(|p| p == &item.path) {
275            continue;
276        }
277        if item.open_error.is_some() {
278            continue;
279        }
280        seen.push(item.path.clone());
281        out.push(RecentVolume {
282            path: item.path.clone(),
283            sayable: if item.display_name.trim().is_empty() {
284                sayable_name(&item.path)
285            } else {
286                sayable_name(&item.display_name)
287            },
288        });
289        if out.len() >= MAX_BROWSE {
290            break;
291        }
292    }
293    out
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[test]
301    fn binds_are_live_graph_volume_ids() {
302        assert_eq!(OPEN_ID, "GraphDatabase.volume_open");
303        assert_eq!(COMMIT_ID, "GraphDatabase.volume_commit");
304        assert!(!OPEN_ID.contains("qualia."));
305        assert!(!COMMIT_ID.contains("qualia."));
306    }
307
308    #[test]
309    fn sayable_strips_absolute_path_soup() {
310        assert_eq!(
311            sayable_name("/workspace/qualia-data/uat-sanctuary.q42"),
312            "uat sanctuary"
313        );
314        assert_eq!(sayable_name("C:\\\\Vault\\\\session.q42"), "session");
315        assert_eq!(sayable_name("keep.q42"), "keep");
316        assert!(!sayable_name("/workspace/qualia-data/uat-sanctuary.q42").contains('/'));
317    }
318
319    #[test]
320    fn celebrate_only_on_real_written() {
321        assert!(celebrate_commit(true, 1));
322        assert!(!celebrate_commit(true, 0));
323        assert!(!celebrate_commit(false, 1));
324        assert!(!celebrate_commit(false, 0));
325        match interpret_commit(
326            true,
327            r#"{path: "/tmp/keep.q42", written: 1, sanctuary: true}"#,
328            None,
329            "/tmp/keep.q42",
330        ) {
331            KeepOutcome::Committed { written, .. } => {
332                assert_eq!(written, 1);
333                assert!(KeepOutcome::Committed {
334                    path: "/tmp/keep.q42".into(),
335                    sayable: "keep".into(),
336                    written: 1,
337                }
338                .celebrates());
339            }
340            other => panic!("{other:?}"),
341        }
342        match interpret_commit(
343            true,
344            r#"{path: "/tmp/keep.q42", written: 0}"#,
345            None,
346            "/tmp/x.q42",
347        ) {
348            KeepOutcome::Held { why } => {
349                assert_eq!(why, HELD_WHY);
350                assert!(copy_avoids_unavailable(&why));
351            }
352            other => panic!("{other:?}"),
353        }
354        match interpret_commit(false, "", Some("E300 denied"), "/tmp/x.q42") {
355            KeepOutcome::Held { why } => assert!(copy_avoids_unavailable(&why)),
356            other => panic!("{other:?}"),
357        }
358    }
359
360    #[test]
361    fn missing_volume_is_held_never_unavailable() {
362        match interpret_open(false, "", Some("Unavailable: no daemon"), "/missing.q42") {
363            KeepOutcome::Held { why } => {
364                assert_eq!(why, HELD_WHY);
365                assert!(copy_avoids_unavailable(&why));
366                assert!(copy_avoids_broken(&why));
367            }
368            other => panic!("{other:?}"),
369        }
370        assert_eq!(sanitize_held_why("Unavailable: start daemon"), HELD_WHY);
371        assert!(copy_avoids_unavailable(VolumeLook::Held.label()));
372        assert!(copy_avoids_unavailable(HELD_WHY));
373    }
374
375    #[test]
376    fn recent_and_vault_merge_prefers_sayable_reopen() {
377        let recents = remember_recent(&[], "/workspace/qualia-data/uat-sanctuary.q42");
378        assert_eq!(recents[0].sayable, "uat sanctuary");
379        let vault = [VaultVolume {
380            path: "/vault/session.q42".into(),
381            display_name: "session.q42".into(),
382            relative: "session.q42".into(),
383            open_error: None,
384        }];
385        let merged = merge_browse_list(&recents, &vault);
386        assert_eq!(merged.len(), 2);
387        assert_eq!(merged[0].sayable, "uat sanctuary");
388        assert_eq!(merged[1].sayable, "session");
389        assert!(!merged.iter().any(|v| v.sayable.contains('/')));
390    }
391
392    #[test]
393    fn recents_json_round_trip() {
394        let raw = recents_json(&[RecentVolume {
395            path: "/tmp/keep.q42".into(),
396            sayable: "keep".into(),
397        }]);
398        let parsed = parse_recents_json(&raw);
399        assert_eq!(parsed[0].path, "/tmp/keep.q42");
400        assert_eq!(RECENT_STORAGE_KEY, "qualia-ui:keep-recent-volumes");
401    }
402
403    #[test]
404    fn keep_hub_chrome_is_browse_not_unavailable() {
405        let src = include_str!("components/keep_hub.rs");
406        let ui: String = src
407            .lines()
408            .filter(|line| !line.trim_start().starts_with("//"))
409            .collect();
410        assert!(src.contains("data-keep-volume-browse"));
411        assert!(src.contains("Browse"));
412        assert!(src.contains("celebrate"));
413        assert!(!ui.to_ascii_lowercase().contains("unavailable"));
414        assert!(src.contains("OPEN_ID"));
415        assert!(src.contains("COMMIT_ID"));
416    }
417}