Skip to main content

qualia_client_core/
studio_workspace_wal.rs

1//! Quin-backed audit trail for studio workspace deploys.
2//!
3//! Each manifest save appends a deploy checkpoint Quin plus one placement Quin per
4//! pane. History is recoverable from `{storage}/studio-workspace.wal`.
5
6use qualia_core_db::{q_hash, wal::WriteAheadLog, NQuin};
7
8const OBJECT_HASH_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
9const LAMPORT_SHIFT: u32 = 32;
10const LAMPORT_MASK: u64 = 0x1FFF_FFFF;
11
12pub const STUDIO_WAL_FILE: &str = "studio-workspace.wal";
13pub const REVISION_SNAPSHOT_PREFIX: &str = "studio-workspace-rev-";
14const WORKSPACE_SUBJECT: &str = "studio:workspace";
15const PREDICATE_DEPLOY: &str = "q42:studioDeploy";
16const PREDICATE_PANE: &str = "q42:studioPanePlacement";
17const PREDICATE_UNDO_FRAME: &str = "q42:studioUndoFrame";
18
19pub const UNDO_FRAME_SNAPSHOT_PREFIX: &str = "studio-undo-frame-";
20pub const MAX_UNDO_FRAMES: usize = 32;
21
22#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
23pub struct StudioUndoFrameRecord {
24    pub frame_seq: u64,
25    pub stack_index: u16,
26    pub manifest_hash: u64,
27    pub unix_ts: u32,
28}
29
30#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
31pub struct StudioDeployRecord {
32    pub revision: u64,
33    pub unix_ts: u32,
34    pub pane_count: u16,
35    pub manifest_hash: u64,
36}
37
38#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
39struct WalManifestPage {
40    url_path: String,
41    panes: Vec<WalManifestPane>,
42}
43
44#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
45struct WalManifestPane {
46    component_id: String,
47    x: u16,
48    y: u16,
49    w: u16,
50    h: u16,
51}
52
53#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
54struct WalManifest {
55    pages: Vec<WalManifestPage>,
56}
57
58/// Studio WAL path.
59pub fn studio_wal_path(storage_path: &str) -> std::path::PathBuf {
60    std::path::PathBuf::from(storage_path).join(STUDIO_WAL_FILE)
61}
62
63fn workspace_subject() -> u64 {
64    q_hash(WORKSPACE_SUBJECT)
65}
66
67fn author_context_hash() -> u64 {
68    let profile = crate::user_profile::load_profile();
69    q_hash(&profile.public_did)
70}
71
72fn manifest_content_hash(manifest_json: &str) -> u64 {
73    q_hash(manifest_json) & OBJECT_HASH_MASK
74}
75
76/// Undo-frame snapshot path.
77pub fn undo_frame_snapshot_path(storage_path: &str, frame_seq: u64) -> std::path::PathBuf {
78    std::path::PathBuf::from(storage_path)
79        .join(format!("{UNDO_FRAME_SNAPSHOT_PREFIX}{frame_seq}.json"))
80}
81
82/// Revision snapshot path.
83pub fn revision_snapshot_path(storage_path: &str, revision: u64) -> std::path::PathBuf {
84    std::path::PathBuf::from(storage_path)
85        .join(format!("{REVISION_SNAPSHOT_PREFIX}{revision}.json"))
86}
87
88/// Persists a revision snapshot.
89pub fn persist_revision_snapshot(
90    storage_path: &str,
91    revision: u64,
92    manifest_json: &str,
93) -> Result<(), String> {
94    let path = revision_snapshot_path(storage_path, revision);
95    if let Some(parent) = path.parent() {
96        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
97    }
98    let tmp = path.with_extension("json.tmp");
99    std::fs::write(&tmp, manifest_json.as_bytes()).map_err(|e| e.to_string())?;
100    std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
101    Ok(())
102}
103
104/// Unpacks a placement.
105pub fn unpack_placement(object: u64) -> (u16, u16, u16, u16) {
106    let o = object & OBJECT_HASH_MASK;
107    (
108        (o & 0xFFFF) as u16,
109        ((o >> 16) & 0xFFFF) as u16,
110        ((o >> 32) & 0xFFFF) as u16,
111        ((o >> 48) & 0xFFFF) as u16,
112    )
113}
114
115fn pack_placement(x: u16, y: u16, w: u16, h: u16) -> u64 {
116    ((w as u64) << 48) | ((h as u64) << 32) | ((y as u64) << 16) | (x as u64)
117}
118
119fn count_existing_undo_frames(wal_path: &std::path::Path) -> u64 {
120    let Ok(mut wal) = WriteAheadLog::open(wal_path) else {
121        return 0;
122    };
123    let Ok(quins) = wal.recover() else {
124        return 0;
125    };
126    let undo_pred = q_hash(PREDICATE_UNDO_FRAME);
127    quins.iter().filter(|q| q.predicate == undo_pred).count() as u64
128}
129
130fn build_undo_frame_quin(frame_seq: u64, stack_index: u16, manifest_json: &str) -> NQuin {
131    let subject = workspace_subject();
132    let predicate = q_hash(PREDICATE_UNDO_FRAME);
133    let object = manifest_content_hash(manifest_json);
134    let context = author_context_hash();
135    let metadata = ((frame_seq & LAMPORT_MASK) << LAMPORT_SHIFT) | ((stack_index as u64) & 0xFFFF);
136    let parity = subject ^ predicate ^ object ^ context ^ metadata;
137    NQuin {
138        subject,
139        predicate,
140        object,
141        context,
142        metadata,
143        parity,
144    }
145}
146
147fn build_deploy_quin(revision: u64, manifest_json: &str) -> NQuin {
148    let subject = workspace_subject();
149    let predicate = q_hash(PREDICATE_DEPLOY);
150    let object = manifest_content_hash(manifest_json);
151    let context = author_context_hash();
152    let unix_ts = std::time::SystemTime::now()
153        .duration_since(std::time::UNIX_EPOCH)
154        .unwrap_or_default()
155        .as_secs() as u32;
156    let metadata = ((revision & LAMPORT_MASK) << LAMPORT_SHIFT) | (unix_ts as u64);
157    let parity = subject ^ predicate ^ object ^ context ^ metadata;
158    NQuin {
159        subject,
160        predicate,
161        object,
162        context,
163        metadata,
164        parity,
165    }
166}
167
168fn build_pane_quin(
169    page_path: &str,
170    component_id: &str,
171    x: u16,
172    y: u16,
173    w: u16,
174    h: u16,
175    revision: u64,
176) -> NQuin {
177    let subject = q_hash(component_id);
178    let predicate = q_hash(PREDICATE_PANE);
179    let object = pack_placement(x, y, w, h) & OBJECT_HASH_MASK;
180    let context = q_hash(page_path);
181    let metadata = (revision & LAMPORT_MASK) << LAMPORT_SHIFT;
182    let parity = subject ^ predicate ^ object ^ context ^ metadata;
183    NQuin {
184        subject,
185        predicate,
186        object,
187        context,
188        metadata,
189        parity,
190    }
191}
192
193fn count_existing_deploys(wal_path: &std::path::Path) -> u64 {
194    let Ok(mut wal) = WriteAheadLog::open(wal_path) else {
195        return 0;
196    };
197    let Ok(quins) = wal.recover() else {
198        return 0;
199    };
200    let deploy_pred = q_hash(PREDICATE_DEPLOY);
201    quins.iter().filter(|q| q.predicate == deploy_pred).count() as u64
202}
203
204/// Append deploy + pane placement Quins for a saved workspace manifest.
205pub fn append_workspace_deploy(storage_path: &str, manifest_json: &str) -> Result<u64, String> {
206    let manifest: WalManifest =
207        serde_json::from_str(manifest_json).map_err(|e| format!("manifest parse: {e}"))?;
208    let wal_path = studio_wal_path(storage_path);
209    let revision = count_existing_deploys(&wal_path) + 1;
210
211    let mut wal = WriteAheadLog::open(&wal_path).map_err(|e| format!("wal open: {e}"))?;
212    wal.append_mutation(&build_deploy_quin(revision, manifest_json))
213        .map_err(|e| format!("wal deploy append: {e}"))?;
214
215    for page in &manifest.pages {
216        for pane in &page.panes {
217            let quin = build_pane_quin(
218                &page.url_path,
219                &pane.component_id,
220                pane.x,
221                pane.y,
222                pane.w,
223                pane.h,
224                revision,
225            );
226            wal.append_mutation(&quin)
227                .map_err(|e| format!("wal pane append: {e}"))?;
228        }
229    }
230
231    Ok(revision)
232}
233
234/// Append an undo-stack frame Quin plus on-disk snapshot (bounded to [`MAX_UNDO_FRAMES`]).
235pub fn append_undo_frame(
236    storage_path: &str,
237    stack_index: u16,
238    manifest_json: &str,
239) -> Result<u64, String> {
240    if manifest_json.trim().is_empty() {
241        return Err("empty undo manifest".to_string());
242    }
243    let wal_path = studio_wal_path(storage_path);
244    let frame_seq = count_existing_undo_frames(&wal_path) + 1;
245    let snap_path = undo_frame_snapshot_path(storage_path, frame_seq);
246    if let Some(parent) = snap_path.parent() {
247        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
248    }
249    let tmp = snap_path.with_extension("json.tmp");
250    std::fs::write(&tmp, manifest_json.as_bytes()).map_err(|e| e.to_string())?;
251    std::fs::rename(&tmp, &snap_path).map_err(|e| e.to_string())?;
252
253    let mut wal = WriteAheadLog::open(&wal_path).map_err(|e| format!("wal open: {e}"))?;
254    wal.append_mutation(&build_undo_frame_quin(
255        frame_seq,
256        stack_index,
257        manifest_json,
258    ))
259    .map_err(|e| format!("wal undo append: {e}"))?;
260
261    prune_old_undo_snapshots(storage_path, frame_seq)?;
262    Ok(frame_seq)
263}
264
265fn prune_old_undo_snapshots(storage_path: &str, latest_seq: u64) -> Result<(), String> {
266    if latest_seq <= MAX_UNDO_FRAMES as u64 {
267        return Ok(());
268    }
269    let remove_before = latest_seq - MAX_UNDO_FRAMES as u64;
270    for seq in 1..=remove_before {
271        let path = undo_frame_snapshot_path(storage_path, seq);
272        if path.is_file() {
273            let _ = std::fs::remove_file(path);
274        }
275    }
276    Ok(())
277}
278
279/// List undo-frame checkpoints from the studio WAL (oldest first).
280pub fn list_undo_frames(storage_path: &str) -> Result<Vec<StudioUndoFrameRecord>, String> {
281    let wal_path = studio_wal_path(storage_path);
282    if !wal_path.is_file() {
283        return Ok(Vec::new());
284    }
285    let mut wal = WriteAheadLog::open(&wal_path).map_err(|e| format!("wal open: {e}"))?;
286    let quins = wal.recover().map_err(|e| format!("wal recover: {e}"))?;
287    let undo_pred = q_hash(PREDICATE_UNDO_FRAME);
288    let mut records = Vec::new();
289    for quin in quins {
290        if quin.predicate != undo_pred {
291            continue;
292        }
293        let frame_seq = (quin.metadata >> LAMPORT_SHIFT) & LAMPORT_MASK;
294        let stack_index = (quin.metadata & 0xFFFF) as u16;
295        records.push(StudioUndoFrameRecord {
296            frame_seq,
297            stack_index,
298            manifest_hash: quin.object,
299            unix_ts: 0,
300        });
301    }
302    Ok(records)
303}
304
305/// Load a single undo-frame manifest snapshot by sequence id.
306pub fn load_undo_frame_manifest(storage_path: &str, frame_seq: u64) -> Result<String, String> {
307    let path = undo_frame_snapshot_path(storage_path, frame_seq);
308    if !path.is_file() {
309        return Err(format!("undo frame {frame_seq} snapshot missing"));
310    }
311    std::fs::read_to_string(&path).map_err(|e| e.to_string())
312}
313
314/// Recover the last N undo manifests in chronological order for history hydration.
315pub fn recover_undo_chain_manifests(storage_path: &str) -> Result<Vec<String>, String> {
316    let frames = list_undo_frames(storage_path)?;
317    if frames.is_empty() {
318        return Ok(Vec::new());
319    }
320    let start = frames.len().saturating_sub(MAX_UNDO_FRAMES);
321    let mut manifests = Vec::new();
322    for frame in &frames[start..] {
323        match load_undo_frame_manifest(storage_path, frame.frame_seq) {
324            Ok(body) => manifests.push(body),
325            Err(err) => eprintln!("undo frame {} skip: {err}", frame.frame_seq),
326        }
327    }
328    Ok(manifests)
329}
330
331/// Recover deploy checkpoints from the studio WAL (most recent last).
332pub fn list_deploy_history(storage_path: &str) -> Result<Vec<StudioDeployRecord>, String> {
333    let wal_path = studio_wal_path(storage_path);
334    if !wal_path.is_file() {
335        return Ok(Vec::new());
336    }
337    let mut wal = WriteAheadLog::open(&wal_path).map_err(|e| format!("wal open: {e}"))?;
338    let quins = wal.recover().map_err(|e| format!("wal recover: {e}"))?;
339    let deploy_pred = q_hash(PREDICATE_DEPLOY);
340    let pane_pred = q_hash(PREDICATE_PANE);
341    let mut pane_counts: std::collections::HashMap<u64, u16> = std::collections::HashMap::new();
342    for quin in &quins {
343        if quin.predicate != pane_pred {
344            continue;
345        }
346        let revision = (quin.metadata >> LAMPORT_SHIFT) & LAMPORT_MASK;
347        let entry = pane_counts.entry(revision).or_insert(0);
348        *entry = entry.saturating_add(1);
349    }
350
351    let mut records = Vec::new();
352    for quin in quins {
353        if quin.predicate != deploy_pred {
354            continue;
355        }
356        let revision = (quin.metadata >> LAMPORT_SHIFT) & LAMPORT_MASK;
357        let unix_ts = (quin.metadata & 0xFFFF_FFFF) as u32;
358        let pane_count = pane_counts.get(&revision).copied().unwrap_or(0);
359        records.push(StudioDeployRecord {
360            revision,
361            unix_ts,
362            pane_count,
363            manifest_hash: quin.object,
364        });
365    }
366    Ok(records)
367}
368
369/// Reconstruct a minimal workspace manifest from pane placement Quins at `revision`.
370pub fn reconstruct_manifest_from_pane_quins(
371    storage_path: &str,
372    revision: u64,
373) -> Result<String, String> {
374    let wal_path = studio_wal_path(storage_path);
375    let mut wal = WriteAheadLog::open(&wal_path).map_err(|e| format!("wal open: {e}"))?;
376    let quins = wal.recover().map_err(|e| format!("wal recover: {e}"))?;
377    let pane_pred = q_hash(PREDICATE_PANE);
378
379    let mut pages: std::collections::HashMap<String, Vec<WalManifestPane>> =
380        std::collections::HashMap::new();
381
382    for quin in &quins {
383        if quin.predicate != pane_pred {
384            continue;
385        }
386        let rev = (quin.metadata >> LAMPORT_SHIFT) & LAMPORT_MASK;
387        if rev != revision {
388            continue;
389        }
390        let page_path = format!("wal-page-{}", quin.context);
391        let (x, y, w, h) = unpack_placement(quin.object);
392        let component_id = format!("wal-pane-{}", quin.subject);
393        pages.entry(page_path).or_default().push(WalManifestPane {
394            component_id,
395            x,
396            y,
397            w,
398            h,
399        });
400    }
401
402    if pages.is_empty() {
403        return Err(format!("no pane quins for revision {revision}"));
404    }
405
406    let manifest = WalManifest {
407        pages: pages
408            .into_iter()
409            .map(|(url_path, panes)| WalManifestPage { url_path, panes })
410            .collect(),
411    };
412    serde_json::to_string(&manifest).map_err(|e| format!("manifest encode: {e}"))
413}
414
415/// Load a saved revision snapshot, falling back to pane-quin reconstruction.
416pub fn replay_workspace_manifest(storage_path: &str, revision: u64) -> Result<String, String> {
417    let snap = revision_snapshot_path(storage_path, revision);
418    if snap.is_file() {
419        return std::fs::read_to_string(&snap).map_err(|e| e.to_string());
420    }
421    reconstruct_manifest_from_pane_quins(storage_path, revision)
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use std::fs;
428
429    #[test]
430    fn append_and_recover_deploy_history() {
431        let dir = std::env::temp_dir().join(format!(
432            "qualia-studio-wal-{}",
433            std::time::SystemTime::now()
434                .duration_since(std::time::UNIX_EPOCH)
435                .unwrap()
436                .as_nanos()
437        ));
438        fs::create_dir_all(&dir).unwrap();
439        let storage = dir.to_string_lossy().to_string();
440        let manifest = r#"{"pages":[{"url_path":"/","panes":[{"component_id":"n3-logic-studio","x":0,"y":0,"w":40,"h":30}]}]}"#;
441
442        let rev = append_workspace_deploy(&storage, manifest).unwrap();
443        assert_eq!(rev, 1);
444
445        let history = list_deploy_history(&storage).unwrap();
446        assert_eq!(history.len(), 1);
447        assert_eq!(history[0].revision, 1);
448        assert_eq!(history[0].pane_count, 1);
449        assert_eq!(history[0].manifest_hash, manifest_content_hash(manifest));
450
451        let rev2 = append_workspace_deploy(&storage, manifest).unwrap();
452        assert_eq!(rev2, 2);
453        let history2 = list_deploy_history(&storage).unwrap();
454        assert_eq!(history2.len(), 2);
455
456        let _ = fs::remove_dir_all(dir);
457    }
458
459    #[test]
460    fn revision_snapshot_roundtrip() {
461        let dir = std::env::temp_dir().join(format!(
462            "qualia-studio-snap-{}",
463            std::time::SystemTime::now()
464                .duration_since(std::time::UNIX_EPOCH)
465                .unwrap()
466                .as_nanos()
467        ));
468        std::fs::create_dir_all(&dir).unwrap();
469        let storage = dir.to_string_lossy().to_string();
470        let body = r#"{"pages":[{"url_path":"/","panes":[]}]}"#;
471        persist_revision_snapshot(&storage, 3, body).unwrap();
472        let loaded = replay_workspace_manifest(&storage, 3).unwrap();
473        assert_eq!(loaded, body);
474        let _ = std::fs::remove_dir_all(dir);
475    }
476
477    #[test]
478    fn undo_frame_append_and_recover() {
479        let dir = std::env::temp_dir().join(format!(
480            "qualia-studio-undo-{}",
481            std::time::SystemTime::now()
482                .duration_since(std::time::UNIX_EPOCH)
483                .unwrap()
484                .as_nanos()
485        ));
486        fs::create_dir_all(&dir).unwrap();
487        let storage = dir.to_string_lossy().to_string();
488        let m1 = r#"{"pages":[{"url_path":"/","panes":[{"component_id":"a","x":0,"y":0,"w":10,"h":10}]}]}"#;
489        let m2 = r#"{"pages":[{"url_path":"/","panes":[{"component_id":"b","x":1,"y":1,"w":20,"h":20}]}]}"#;
490        let s1 = append_undo_frame(&storage, 0, m1).unwrap();
491        let s2 = append_undo_frame(&storage, 1, m2).unwrap();
492        assert_eq!(s1, 1);
493        assert_eq!(s2, 2);
494        let chain = recover_undo_chain_manifests(&storage).unwrap();
495        assert_eq!(chain.len(), 2);
496        assert_eq!(chain[0], m1);
497        assert_eq!(chain[1], m2);
498        let _ = fs::remove_dir_all(dir);
499    }
500
501    #[test]
502    fn pack_placement_roundtrip_bits() {
503        let packed = pack_placement(4, 8, 32, 16);
504        assert_eq!(packed & 0xFFFF, 4);
505        assert_eq!((packed >> 16) & 0xFFFF, 8);
506        assert_eq!((packed >> 32) & 0xFFFF, 16);
507        assert_eq!((packed >> 48) & 0xFFFF, 32);
508    }
509}