From 7a26655173c259b83ff2b4a2757afa5f7617f827 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 06:24:01 +0500 Subject: [PATCH 1/5] =?UTF-8?q?test(cockpit):=20red=20=E2=80=94=20curation?= =?UTF-8?q?-store=20OPFS/native=20byte=20adapter=20(3C-A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser (and native) persistence adapter for the merged curation_store domain model, as failing tests against stub bodies: - a missing store location is StoreOnDisk::Missing, a typed absence; - present valid bytes decode to the same store; - present malformed bytes are a typed Decode refusal, never an empty store; - canonical bytes survive a decode->encode round trip; - native (std::fs) write-then-load round-trips and absence reads as Missing. The adapter reads/writes the SAME encode_store/decode_store canonical bytes as the CLI's native adapter (ADR-0027 §3, no browser-specific wire schema); only the byte transport is per-target. classify + the native arm are stubs, so the behavioral tests fail; the wasm OPFS arm and the real bodies land in green. thiserror added to cockpit for the typed CurationStoreError. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- cockpit/Cargo.toml | 3 + cockpit/src/curation_io.rs | 194 +++++++++++++++++++++++++++++++++++++ cockpit/src/lib.rs | 1 + 3 files changed, 198 insertions(+) create mode 100644 cockpit/src/curation_io.rs diff --git a/cockpit/Cargo.toml b/cockpit/Cargo.toml index 1e366b16..4ac0d5c3 100644 --- a/cockpit/Cargo.toml +++ b/cockpit/Cargo.toml @@ -31,6 +31,9 @@ griff-swang = { path = "../swang" } # sidecar a kept candidate is stamped with (S8). serde = { workspace = true } serde_json = { workspace = true } +# Typed errors for the curation-store persistence adapter (3C-A), mirroring +# core's curation_store and the CLI's native adapter. +thiserror = { workspace = true } # Native desktop keeps eframe's defaults (winit + glow), exactly as Slice 1 # shipped; the web target picks a leaner, glow-only eframe below. diff --git a/cockpit/src/curation_io.rs b/cockpit/src/curation_io.rs new file mode 100644 index 00000000..649cce74 --- /dev/null +++ b/cockpit/src/curation_io.rs @@ -0,0 +1,194 @@ +//! Curation-store persistence adapter for the cockpit (step 3C-A). +//! +//! The browser backend for [`griff_core::curation_store`]: it reads and writes +//! the store's **canonical bytes** — the same `encode_store`/`decode_store` the +//! CLI's native adapter uses (ADR-0027 §3: "no browser-specific wire schema") — +//! to a single OPFS file, `curation/store.json`. A native arm mirrors it over +//! `std::fs` for the desktop cockpit. +//! +//! Only the byte *transport* is per-target; the Missing-vs-malformed +//! classification and the format itself live in core. There is deliberately **no +//! trait abstracting this over the CLI's native adapter (3B2)**: the shared +//! contract is core's encode/decode, which both call directly. +//! +//! **Experimental, `#[doc(hidden)]`** via the crate — not a stable API. + +use griff_core::curation_store::{decode_store, CurationStoreV1, StoreDecodeError}; + +/// The outcome of loading the store. +/// +/// A *missing* file is a typed absence — the caller bootstraps a fresh empty +/// store — and is never conflated with a *malformed* file, which is a hard +/// [`CurationStoreError::Decode`]. +#[derive(Debug)] +pub enum StoreOnDisk { + /// No store file exists yet. + Missing, + /// A valid store was read and decoded. + Loaded(CurationStoreV1), +} + +/// A raw read of the store location, before decoding — the seam between the +/// per-target byte transport and the shared [`classify`] logic. +#[derive(Debug)] +pub enum StoreBytes { + /// The store location does not exist. + Missing, + /// The store location holds these bytes (which may or may not decode). + Present(Vec), +} + +/// Everything that can go wrong loading the store. +#[derive(Debug, thiserror::Error)] +pub enum CurationStoreError { + /// A storage operation failed. + #[error("curation store I/O failed: {0}")] + Io(String), + /// Bytes are present but are not a valid store (malformed or rule-violating). + #[error("curation store on disk is invalid: {0}")] + Decode(#[from] StoreDecodeError), +} + +/// Classifies a raw read: a missing location is a typed absence; present bytes +/// are decoded (a malformed store is a typed refusal, never an empty store). +/// +/// # Errors +/// [`CurationStoreError::Decode`] when bytes are present but do not decode. +pub fn classify(read: StoreBytes) -> Result { + // STUB (red): every read reads as absence, so the loaded/malformed tests fail. + let _ = ( + read, + decode_store as fn(&[u8]) -> Result, + ); + Ok(StoreOnDisk::Missing) +} + +/// Loads the store from `path` on the native desktop cockpit. +/// +/// # Errors +/// [`CurationStoreError::Decode`] if the file exists but is invalid; +/// [`CurationStoreError::Io`] for any read error other than "not found" (which +/// is [`StoreOnDisk::Missing`], not an error). +#[cfg(not(target_arch = "wasm32"))] +pub fn load_store(path: &std::path::Path) -> Result { + // STUB (red): reports absence regardless, so the round-trip test fails. + let _ = path; + Ok(StoreOnDisk::Missing) +} + +/// Writes the store's canonical `bytes` to `path` on the native desktop cockpit. +/// +/// # Errors +/// [`CurationStoreError::Io`] if the write fails. +#[cfg(not(target_arch = "wasm32"))] +pub fn write_store(path: &std::path::Path, bytes: &[u8]) -> Result<(), CurationStoreError> { + // STUB (red): writes nothing, so the read-back test fails. + let _ = (path, bytes); + Ok(()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used, clippy::unwrap_used)] + + use super::{classify, StoreBytes, StoreOnDisk}; + use griff_core::corpus::{ChunkId, ReviewerDecision}; + use griff_core::curation_store::{ + encode_store, ChunkFingerprint, CorpusFingerprint, CurationContext, CurationEvent, + CurationEventId, CurationStoreV1, ReviewerId, StoreDecodeError, CURATION_STORE_VERSION, + }; + + fn sample() -> CurationStoreV1 { + CurationStoreV1 { + version: CURATION_STORE_VERSION, + corpus_fingerprint: CorpusFingerprint("corpus".to_owned()), + events: vec![CurationEvent { + event_id: CurationEventId("e1".to_owned()), + chunk_id: ChunkId("c1".to_owned()), + chunk_fingerprint: ChunkFingerprint("fp1".to_owned()), + decision: ReviewerDecision::Accepted, + reviewer: ReviewerId("alice".to_owned()), + occurred_at: "2026-07-18T10:00:00Z".to_owned(), + corpus_fingerprint: CorpusFingerprint("corpus".to_owned()), + context: CurationContext { + cluster_representative: ChunkId("c1".to_owned()), + cluster_members: vec![ChunkId("c1".to_owned())], + }, + tags: Vec::new(), + note: None, + }], + } + } + + #[test] + fn a_missing_location_is_a_typed_absence() { + assert!(matches!( + classify(StoreBytes::Missing), + Ok(StoreOnDisk::Missing) + )); + } + + #[test] + fn present_valid_bytes_decode_to_the_same_store() { + let store = sample(); + let bytes = encode_store(&store).expect("encodes"); + match classify(StoreBytes::Present(bytes)).expect("classifies") { + StoreOnDisk::Loaded(loaded) => assert_eq!(loaded, store), + StoreOnDisk::Missing => panic!("present bytes must not read as missing"), + } + } + + #[test] + fn present_malformed_bytes_are_a_typed_refusal_not_absence() { + let err = classify(StoreBytes::Present(b"{ not a store".to_vec())).expect_err("must fail"); + assert!(matches!( + err, + super::CurationStoreError::Decode(StoreDecodeError::MalformedStore(_)) + )); + } + + #[test] + fn canonical_bytes_survive_a_decode_encode_round_trip() { + let store = sample(); + let bytes = encode_store(&store).expect("encodes"); + match classify(StoreBytes::Present(bytes.clone())).expect("classifies") { + StoreOnDisk::Loaded(loaded) => { + assert_eq!(encode_store(&loaded).expect("re-encodes"), bytes); + } + StoreOnDisk::Missing => panic!("present bytes must not read as missing"), + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_write_then_load_round_trips_and_absence_is_missing() { + use super::{load_store, write_store}; + use std::{env, fs, process}; + + let dir = env::temp_dir().join(format!("griff_curio_{}", process::id())); + fs::remove_dir_all(&dir).ok(); + fs::create_dir_all(&dir).expect("mkdir"); + let path = dir.join("store.json"); + + // Absent file → Missing. + assert!(matches!( + load_store(&path).expect("load absent"), + StoreOnDisk::Missing + )); + + let store = sample(); + let bytes = encode_store(&store).expect("encodes"); + write_store(&path, &bytes).expect("write"); + assert_eq!( + fs::read(&path).expect("reread"), + bytes, + "bytes land verbatim" + ); + match load_store(&path).expect("load present") { + StoreOnDisk::Loaded(loaded) => assert_eq!(loaded, store), + StoreOnDisk::Missing => panic!("written store must load"), + } + + fs::remove_dir_all(&dir).ok(); + } +} diff --git a/cockpit/src/lib.rs b/cockpit/src/lib.rs index 23a48519..9ff2bf10 100644 --- a/cockpit/src/lib.rs +++ b/cockpit/src/lib.rs @@ -60,6 +60,7 @@ use griff_ui_core::{ }; pub mod audio; +pub mod curation_io; pub mod generation; pub mod swang; From f914e8c0e304f94f37d8f2476909d103df8c11db Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 06:31:30 +0500 Subject: [PATCH 2/5] =?UTF-8?q?feat(cockpit):=20green=20=E2=80=94=20curati?= =?UTF-8?q?on-store=20OPFS/native=20byte=20adapter=20(3C-A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement the adapter so all five behavioral tests pass: - classify: a missing location is StoreOnDisk::Missing (typed absence); present bytes decode through core::decode_store, so a malformed store is a typed Decode refusal, never an empty store. - native (std::fs) load_store / write_store for the desktop cockpit: NotFound is Missing; any other read error is Io; a written store round-trips. - wasm OPFS arm: opfs_load_store / opfs_write_store read and write curation/store.json in the Origin Private File System, mirroring the existing opfs_save call pattern. An absent directory or file reads as StoreBytes::Missing (the Missing-vs-malformed split stays in classify). The write creates the dir and file and closes the writable stream. The store is the SAME encode_store/decode_store canonical bytes as the CLI's native adapter — one wire format, two transports. No trait over the two adapters. The wasm arm was compile-verified for wasm32-unknown-unknown (a nix clang build reaches the link stage; the residual zstd-on-wasm link is the guitarpro dep's, handled in CI, not this code). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- cockpit/src/curation_io.rs | 123 ++++++++++++++++++++++++++++++++----- 1 file changed, 108 insertions(+), 15 deletions(-) diff --git a/cockpit/src/curation_io.rs b/cockpit/src/curation_io.rs index 649cce74..998e4ecd 100644 --- a/cockpit/src/curation_io.rs +++ b/cockpit/src/curation_io.rs @@ -15,6 +15,9 @@ use griff_core::curation_store::{decode_store, CurationStoreV1, StoreDecodeError}; +#[cfg(not(target_arch = "wasm32"))] +use std::{fs, io::ErrorKind, path::Path}; + /// The outcome of loading the store. /// /// A *missing* file is a typed absence — the caller bootstraps a fresh empty @@ -55,12 +58,10 @@ pub enum CurationStoreError { /// # Errors /// [`CurationStoreError::Decode`] when bytes are present but do not decode. pub fn classify(read: StoreBytes) -> Result { - // STUB (red): every read reads as absence, so the loaded/malformed tests fail. - let _ = ( - read, - decode_store as fn(&[u8]) -> Result, - ); - Ok(StoreOnDisk::Missing) + match read { + StoreBytes::Missing => Ok(StoreOnDisk::Missing), + StoreBytes::Present(bytes) => Ok(StoreOnDisk::Loaded(decode_store(&bytes)?)), + } } /// Loads the store from `path` on the native desktop cockpit. @@ -70,10 +71,13 @@ pub fn classify(read: StoreBytes) -> Result { /// [`CurationStoreError::Io`] for any read error other than "not found" (which /// is [`StoreOnDisk::Missing`], not an error). #[cfg(not(target_arch = "wasm32"))] -pub fn load_store(path: &std::path::Path) -> Result { - // STUB (red): reports absence regardless, so the round-trip test fails. - let _ = path; - Ok(StoreOnDisk::Missing) +pub fn load_store(path: &Path) -> Result { + match fs::read(path) { + Ok(bytes) => classify(StoreBytes::Present(bytes)), + // A missing file is a typed absence the caller resolves, not a failure. + Err(e) if e.kind() == ErrorKind::NotFound => Ok(StoreOnDisk::Missing), + Err(e) => Err(CurationStoreError::Io(e.to_string())), + } } /// Writes the store's canonical `bytes` to `path` on the native desktop cockpit. @@ -81,15 +85,104 @@ pub fn load_store(path: &std::path::Path) -> Result Result<(), CurationStoreError> { - // STUB (red): writes nothing, so the read-back test fails. - let _ = (path, bytes); - Ok(()) +pub fn write_store(path: &Path, bytes: &[u8]) -> Result<(), CurationStoreError> { + fs::write(path, bytes).map_err(|e| CurationStoreError::Io(e.to_string())) +} + +/// The browser byte transport: read and write `curation/store.json` in the +/// Origin Private File System. A missing directory or file reads as +/// [`StoreBytes::Missing`], so the caller can bootstrap a fresh store; the +/// Missing-vs-malformed split then happens in [`classify`]. +#[cfg(target_arch = "wasm32")] +pub use wasm::{opfs_load_store, opfs_write_store}; + +#[cfg(target_arch = "wasm32")] +mod wasm { + use wasm_bindgen::prelude::*; + use wasm_bindgen_futures::JsFuture; + + use super::StoreBytes; + + /// The OPFS directory and file the store lives in — a sibling of the + /// `corpus/` tree, one canonical file. + const DIR: &str = "curation"; + const FILE: &str = "store.json"; + + /// The OPFS `curation/` directory handle. `create` controls whether a + /// missing directory is created (write) or reported as absent (read → `None`). + async fn curation_dir( + create: bool, + ) -> Result, JsValue> { + let storage = web_sys::window() + .ok_or_else(|| JsValue::from_str("no window"))? + .navigator() + .storage(); + let root = JsFuture::from(storage.get_directory()) + .await? + .dyn_into::()?; + let opts = web_sys::FileSystemGetDirectoryOptions::new(); + opts.set_create(create); + match JsFuture::from(root.get_directory_handle_with_options(DIR, &opts)).await { + Ok(handle) => Ok(Some( + handle.dyn_into::()?, + )), + // Absent directory (no store recorded yet) → a typed absence, not an error. + Err(_) if !create => Ok(None), + Err(err) => Err(err), + } + } + + /// Reads `curation/store.json`. An absent directory or file is + /// [`StoreBytes::Missing`]; present bytes are returned verbatim for + /// [`super::classify`] to decode. + // OPFS handles aren't `Send`, but wasm is single-threaded and the future is + // driven by `spawn_local`, which never requires `Send`. + #[allow(clippy::future_not_send)] + pub async fn opfs_load_store() -> Result { + let Some(dir) = curation_dir(false).await? else { + return Ok(StoreBytes::Missing); + }; + // `create` defaults to false: a missing file rejects, which we read as absence. + let opts = web_sys::FileSystemGetFileOptions::new(); + let handle = match JsFuture::from(dir.get_file_handle_with_options(FILE, &opts)).await { + Ok(handle) => handle.dyn_into::()?, + Err(_) => return Ok(StoreBytes::Missing), + }; + // A `File` is a `Blob`; `Blob::text()` yields its contents as a string. + let blob = JsFuture::from(handle.get_file()) + .await? + .dyn_into::()?; + let text = JsFuture::from(blob.text()) + .await? + .as_string() + .unwrap_or_default(); + Ok(StoreBytes::Present(text.into_bytes())) + } + + /// Writes `contents` to `curation/store.json`, creating the directory and + /// file as needed. Returns once the writable stream is closed. + #[allow(clippy::future_not_send)] + pub async fn opfs_write_store(contents: String) -> Result<(), JsValue> { + let dir = curation_dir(true) + .await? + .ok_or_else(|| JsValue::from_str("no curation directory"))?; + let opts = web_sys::FileSystemGetFileOptions::new(); + opts.set_create(true); + let file = JsFuture::from(dir.get_file_handle_with_options(FILE, &opts)) + .await? + .dyn_into::()?; + let writable = JsFuture::from(file.create_writable()) + .await? + .dyn_into::()?; + JsFuture::from(writable.write_with_str(&contents)?).await?; + JsFuture::from(writable.close()).await?; + Ok(()) + } } #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] + #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)] use super::{classify, StoreBytes, StoreOnDisk}; use griff_core::corpus::{ChunkId, ReviewerDecision}; From 39372796af51664d48d79e59b7fc8f2aea2003d0 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 06:46:30 +0500 Subject: [PATCH 3/5] =?UTF-8?q?test(cockpit):=20red=20=E2=80=94=20semantic?= =?UTF-8?q?=20validated=20write=20for=20the=20curation=20adapter=20(3C-A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Corrective for the PR #141 review, testable half: a `encode` seam that routes a store through core's canonical `encode_store`, so a write can never carry non-canonical or invalid bytes. The stub serializes directly instead, so: - encode_produces_the_canonical_bytes_not_a_second_serializer fails (a plain serializer keeps input order; the canonical encoder sorts/dedups); - encode_refuses_an_invalid_store passes as a regression guard. Also lands the scaffolding the green step needs: a typed Encode error variant, the `DomException` web-sys feature (to tell a NotFoundError absence from any other reject), and removal of the native production load_store/write_store — that std::fs arm wrote straight to the canonical file, silently dropping the crash/pre-commit guarantees the frozen 3B2 adapter provides; 3C-A is a browser persistence slice, so the pure seam and its native tests stay while the weaker native backend goes. The OPFS transport rewrite (NotFound-only absence, lossless array_buffer read, encode-in-write) lands in green. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- cockpit/Cargo.toml | 5 +- cockpit/src/curation_io.rs | 100 +++++++++++++++++-------------------- 2 files changed, 50 insertions(+), 55 deletions(-) diff --git a/cockpit/Cargo.toml b/cockpit/Cargo.toml index 4ac0d5c3..9070b70b 100644 --- a/cockpit/Cargo.toml +++ b/cockpit/Cargo.toml @@ -64,9 +64,12 @@ web-sys = { version = "0.3", features = [ "AudioContext", "BaseAudioContext", "AudioNode", "AudioDestinationNode", "AudioParam", "GainNode", "OscillatorNode", "OscillatorType", # OPFS corpus persistence (ADR-0027 §3); the writable stream needs - # `--cfg=web_sys_unstable_apis` (set in build-web.sh). + # `--cfg=web_sys_unstable_apis` (set in build-web.sh). `DomException` lets the + # curation-store adapter (3C-A) tell a genuine NotFoundError (absence) from + # any other reject (SecurityError, InvalidStateError, …) that must stay an error. "StorageManager", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemWritableFileStream", "FileSystemGetDirectoryOptions", "FileSystemGetFileOptions", + "DomException", ] } getrandom = { version = "0.4", features = ["wasm_js"] } diff --git a/cockpit/src/curation_io.rs b/cockpit/src/curation_io.rs index 998e4ecd..366fe2f1 100644 --- a/cockpit/src/curation_io.rs +++ b/cockpit/src/curation_io.rs @@ -13,10 +13,9 @@ //! //! **Experimental, `#[doc(hidden)]`** via the crate — not a stable API. -use griff_core::curation_store::{decode_store, CurationStoreV1, StoreDecodeError}; - -#[cfg(not(target_arch = "wasm32"))] -use std::{fs, io::ErrorKind, path::Path}; +use griff_core::curation_store::{ + decode_store, encode_store, CurationStoreV1, StoreDecodeError, StoreEncodeError, +}; /// The outcome of loading the store. /// @@ -41,15 +40,19 @@ pub enum StoreBytes { Present(Vec), } -/// Everything that can go wrong loading the store. +/// Everything that can go wrong loading or saving the store. #[derive(Debug, thiserror::Error)] pub enum CurationStoreError { - /// A storage operation failed. + /// A storage/transport operation failed (and is *not* a benign absence). #[error("curation store I/O failed: {0}")] Io(String), /// Bytes are present but are not a valid store (malformed or rule-violating). #[error("curation store on disk is invalid: {0}")] Decode(#[from] StoreDecodeError), + /// The store to save is itself invalid — refused before any bytes are + /// written, so a transport never carries non-canonical or invalid data. + #[error("curation store cannot be encoded: {0}")] + Encode(#[from] StoreEncodeError), } /// Classifies a raw read: a missing location is a typed absence; present bytes @@ -64,29 +67,20 @@ pub fn classify(read: StoreBytes) -> Result { } } -/// Loads the store from `path` on the native desktop cockpit. +/// Encodes a store to the canonical bytes a transport writes. /// -/// # Errors -/// [`CurationStoreError::Decode`] if the file exists but is invalid; -/// [`CurationStoreError::Io`] for any read error other than "not found" (which -/// is [`StoreOnDisk::Missing`], not an error). -#[cfg(not(target_arch = "wasm32"))] -pub fn load_store(path: &Path) -> Result { - match fs::read(path) { - Ok(bytes) => classify(StoreBytes::Present(bytes)), - // A missing file is a typed absence the caller resolves, not a failure. - Err(e) if e.kind() == ErrorKind::NotFound => Ok(StoreOnDisk::Missing), - Err(e) => Err(CurationStoreError::Io(e.to_string())), - } -} - -/// Writes the store's canonical `bytes` to `path` on the native desktop cockpit. +/// This is the fallible, *validated* step every write shares: an invalid store +/// is refused here — a typed [`CurationStoreError::Encode`] — before any I/O, so +/// a transport can never persist non-canonical or rule-violating bytes. Core's +/// [`encode_store`] is the only encoder; there is no cockpit-side serializer. /// /// # Errors -/// [`CurationStoreError::Io`] if the write fails. -#[cfg(not(target_arch = "wasm32"))] -pub fn write_store(path: &Path, bytes: &[u8]) -> Result<(), CurationStoreError> { - fs::write(path, bytes).map_err(|e| CurationStoreError::Io(e.to_string())) +/// [`CurationStoreError::Encode`] if the store violates a domain rule. +pub fn encode(store: &CurationStoreV1) -> Result, CurationStoreError> { + // STUB (red): serializes the store directly instead of through the canonical + // encoder, so the canonical-bytes test fails; invalid stores still refuse. + encode_store(store)?; + serde_json::to_vec(store).map_err(|e| CurationStoreError::Io(e.to_string())) } /// The browser byte transport: read and write `curation/store.json` in the @@ -184,7 +178,7 @@ mod wasm { mod tests { #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)] - use super::{classify, StoreBytes, StoreOnDisk}; + use super::{classify, encode, StoreBytes, StoreOnDisk}; use griff_core::corpus::{ChunkId, ReviewerDecision}; use griff_core::curation_store::{ encode_store, ChunkFingerprint, CorpusFingerprint, CurationContext, CurationEvent, @@ -252,36 +246,34 @@ mod tests { } } - #[cfg(not(target_arch = "wasm32"))] #[test] - fn native_write_then_load_round_trips_and_absence_is_missing() { - use super::{load_store, write_store}; - use std::{env, fs, process}; - - let dir = env::temp_dir().join(format!("griff_curio_{}", process::id())); - fs::remove_dir_all(&dir).ok(); - fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join("store.json"); - - // Absent file → Missing. - assert!(matches!( - load_store(&path).expect("load absent"), - StoreOnDisk::Missing - )); - - let store = sample(); - let bytes = encode_store(&store).expect("encodes"); - write_store(&path, &bytes).expect("write"); + fn encode_produces_the_canonical_bytes_not_a_second_serializer() { + // Events out of canonical order: the real encoder sorts and dedups + // (that is what "canonical" means); a plain serializer preserves input + // order, so `encode` must equal core's `encode_store`, byte for byte. + let mut store = sample(); + store.events.push(CurationEvent { + event_id: CurationEventId("e0".to_owned()), + occurred_at: "2026-07-18T09:00:00Z".to_owned(), + ..store.events[0].clone() + }); + // Now [e1@10:00, e0@09:00] — unsorted. assert_eq!( - fs::read(&path).expect("reread"), - bytes, - "bytes land verbatim" + encode(&store).expect("encodes"), + encode_store(&store).expect("canonical"), + "encode must route through the canonical encoder" ); - match load_store(&path).expect("load present") { - StoreOnDisk::Loaded(loaded) => assert_eq!(loaded, store), - StoreOnDisk::Missing => panic!("written store must load"), - } + } - fs::remove_dir_all(&dir).ok(); + #[test] + fn encode_refuses_an_invalid_store() { + // Two events share an id: the domain model rejects it, and that refusal + // must surface as a typed Encode error before any transport runs. + let mut store = sample(); + store.events.push(store.events[0].clone()); + assert!(matches!( + encode(&store), + Err(super::CurationStoreError::Encode(_)) + )); } } From 9fa673ab6c7bc3351c97fba388c1e49509802d90 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 06:50:11 +0500 Subject: [PATCH 4/5] =?UTF-8?q?fix(cockpit):=20green=20=E2=80=94=20fail-cl?= =?UTF-8?q?osed=20OPFS=20transport=20+=20validated=20write=20(3C-A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve the four PR #141 correctives. 1. OPFS lookups no longer swallow every reject as absence. is_not_found checks DomException.name == "NotFoundError"; only that is StoreBytes::Missing. A SecurityError, InvalidStateError, or any other reject becomes a typed CurationStoreError::Io (with the DOMException message), never a silent bootstrap of an empty store. 2. The read is a real byte transport: Blob::array_buffer -> Uint8Array -> Vec, not Blob::text(). A UTF-8 text decode could rewrite malformed bytes before decode_store sees them, and the old unwrap_or_default() could turn an unexpected value into an empty store; both are gone. 3. The public write is semantic and validated: opfs_write_store takes &CurationStoreV1 and routes it through `encode` -> core encode_store, so an invalid store is a typed Encode error before any I/O and the transport only ever carries canonical bytes (write_with_u8_array over the encoded bytes). 4. The weaker native fs::write backend is gone (removed in red): it wrote straight to the canonical file, silently dropping 3B2's crash/pre-commit guarantees. 3C-A is browser persistence; the pure `encode`/`classify` seam stays native-tested, the degraded native backend does not. The wasm arm was compile-verified for wasm32-unknown-unknown (nix/clang build reaches the linker with no rustc errors; the residual zstd-on-wasm link is the guitarpro C dep miscompiled to x86 by nix's clang-wrapper, unrelated, and links in CI). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- cockpit/src/curation_io.rs | 129 +++++++++++++++++++++++++------------ 1 file changed, 89 insertions(+), 40 deletions(-) diff --git a/cockpit/src/curation_io.rs b/cockpit/src/curation_io.rs index 366fe2f1..0c862e15 100644 --- a/cockpit/src/curation_io.rs +++ b/cockpit/src/curation_io.rs @@ -77,10 +77,7 @@ pub fn classify(read: StoreBytes) -> Result { /// # Errors /// [`CurationStoreError::Encode`] if the store violates a domain rule. pub fn encode(store: &CurationStoreV1) -> Result, CurationStoreError> { - // STUB (red): serializes the store directly instead of through the canonical - // encoder, so the canonical-bytes test fails; invalid stores still refuse. - encode_store(store)?; - serde_json::to_vec(store).map_err(|e| CurationStoreError::Io(e.to_string())) + Ok(encode_store(store)?) } /// The browser byte transport: read and write `curation/store.json` in the @@ -95,88 +92,140 @@ mod wasm { use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; - use super::StoreBytes; + use griff_core::curation_store::CurationStoreV1; + + use super::{encode, CurationStoreError, StoreBytes}; /// The OPFS directory and file the store lives in — a sibling of the /// `corpus/` tree, one canonical file. const DIR: &str = "curation"; const FILE: &str = "store.json"; - /// The OPFS `curation/` directory handle. `create` controls whether a - /// missing directory is created (write) or reported as absent (read → `None`). + /// Whether `err` is a genuine "does not exist" — the *only* reject that means + /// absence. A `SecurityError`, `InvalidStateError`, or anything else is a real + /// failure and must not masquerade as "no store yet". + fn is_not_found(err: &JsValue) -> bool { + err.dyn_ref::() + .is_some_and(|e| e.name() == "NotFoundError") + } + + /// Maps a transport reject to a typed [`CurationStoreError::Io`], preferring + /// the `DOMException` message. + fn transport(err: &JsValue) -> CurationStoreError { + let message = err + .dyn_ref::() + .map_or_else(|| format!("{err:?}"), web_sys::DomException::message); + CurationStoreError::Io(message) + } + + /// The OPFS `curation/` directory handle. `create` controls whether a missing + /// directory is created (write) or reported as absent (read → `None`). Only a + /// genuine `NotFoundError` is absence; every other reject is an error. async fn curation_dir( create: bool, - ) -> Result, JsValue> { + ) -> Result, CurationStoreError> { let storage = web_sys::window() - .ok_or_else(|| JsValue::from_str("no window"))? + .ok_or_else(|| CurationStoreError::Io("no window".to_owned()))? .navigator() .storage(); let root = JsFuture::from(storage.get_directory()) - .await? - .dyn_into::()?; + .await + .map_err(|e| transport(&e))? + .dyn_into::() + .map_err(|e| transport(&e))?; let opts = web_sys::FileSystemGetDirectoryOptions::new(); opts.set_create(create); match JsFuture::from(root.get_directory_handle_with_options(DIR, &opts)).await { Ok(handle) => Ok(Some( - handle.dyn_into::()?, + handle + .dyn_into::() + .map_err(|e| transport(&e))?, )), - // Absent directory (no store recorded yet) → a typed absence, not an error. - Err(_) if !create => Ok(None), - Err(err) => Err(err), + Err(err) if !create && is_not_found(&err) => Ok(None), + Err(err) => Err(transport(&err)), } } /// Reads `curation/store.json`. An absent directory or file is - /// [`StoreBytes::Missing`]; present bytes are returned verbatim for - /// [`super::classify`] to decode. + /// [`StoreBytes::Missing`]; a non-`NotFound` reject is a typed error. Present + /// bytes are read losslessly (`ArrayBuffer`, not a UTF-8 text decode) so the + /// Missing-vs-malformed split can happen faithfully in [`super::classify`]. // OPFS handles aren't `Send`, but wasm is single-threaded and the future is // driven by `spawn_local`, which never requires `Send`. #[allow(clippy::future_not_send)] - pub async fn opfs_load_store() -> Result { + pub async fn opfs_load_store() -> Result { let Some(dir) = curation_dir(false).await? else { return Ok(StoreBytes::Missing); }; - // `create` defaults to false: a missing file rejects, which we read as absence. + // `create` defaults to false: a missing file is a NotFound reject → absence. let opts = web_sys::FileSystemGetFileOptions::new(); let handle = match JsFuture::from(dir.get_file_handle_with_options(FILE, &opts)).await { - Ok(handle) => handle.dyn_into::()?, - Err(_) => return Ok(StoreBytes::Missing), + Ok(handle) => handle + .dyn_into::() + .map_err(|e| transport(&e))?, + Err(err) if is_not_found(&err) => return Ok(StoreBytes::Missing), + Err(err) => return Err(transport(&err)), }; - // A `File` is a `Blob`; `Blob::text()` yields its contents as a string. let blob = JsFuture::from(handle.get_file()) - .await? - .dyn_into::()?; - let text = JsFuture::from(blob.text()) - .await? - .as_string() - .unwrap_or_default(); - Ok(StoreBytes::Present(text.into_bytes())) + .await + .map_err(|e| transport(&e))? + .dyn_into::() + .map_err(|e| transport(&e))?; + // Raw bytes, not `Blob::text()`: a UTF-8 decode could rewrite malformed + // input before `decode_store` ever sees it. + let buffer = JsFuture::from(blob.array_buffer()) + .await + .map_err(|e| transport(&e))?; + let bytes = js_sys::Uint8Array::new(&buffer).to_vec(); + Ok(StoreBytes::Present(bytes)) } - /// Writes `contents` to `curation/store.json`, creating the directory and - /// file as needed. Returns once the writable stream is closed. + /// Encodes `store` to its canonical bytes and writes them to + /// `curation/store.json`, creating the directory and file as needed. + /// + /// An invalid store is refused by [`encode`] before any I/O (a typed + /// [`CurationStoreError::Encode`]), so the transport only ever carries + /// canonical bytes. Returns once the writable stream is closed. #[allow(clippy::future_not_send)] - pub async fn opfs_write_store(contents: String) -> Result<(), JsValue> { + pub async fn opfs_write_store(store: &CurationStoreV1) -> Result<(), CurationStoreError> { + let bytes = encode(store)?; let dir = curation_dir(true) .await? - .ok_or_else(|| JsValue::from_str("no curation directory"))?; + .ok_or_else(|| CurationStoreError::Io("no curation directory".to_owned()))?; let opts = web_sys::FileSystemGetFileOptions::new(); opts.set_create(true); let file = JsFuture::from(dir.get_file_handle_with_options(FILE, &opts)) - .await? - .dyn_into::()?; + .await + .map_err(|e| transport(&e))? + .dyn_into::() + .map_err(|e| transport(&e))?; let writable = JsFuture::from(file.create_writable()) - .await? - .dyn_into::()?; - JsFuture::from(writable.write_with_str(&contents)?).await?; - JsFuture::from(writable.close()).await?; + .await + .map_err(|e| transport(&e))? + .dyn_into::() + .map_err(|e| transport(&e))?; + JsFuture::from( + writable + .write_with_u8_array(&bytes) + .map_err(|e| transport(&e))?, + ) + .await + .map_err(|e| transport(&e))?; + JsFuture::from(writable.close()) + .await + .map_err(|e| transport(&e))?; Ok(()) } } #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)] + #![allow( + clippy::expect_used, + clippy::unwrap_used, + clippy::panic, + clippy::indexing_slicing + )] use super::{classify, encode, StoreBytes, StoreOnDisk}; use griff_core::corpus::{ChunkId, ReviewerDecision}; From b4f513beaaee70881f70c248518dd9879fc6bbd9 Mon Sep 17 00:00:00 2001 From: PhysShell Date: Sun, 19 Jul 2026 06:50:47 +0500 Subject: [PATCH 5/5] docs(cockpit): correct the curation adapter module doc after the native-arm removal The header still described a native std::fs arm that green removed. State what the module now is: a browser-only OPFS transport plus the pure encode/classify seam, with durable native persistence left to the CLI's frozen curation_fs (3B2). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01NkqJUU6d1sW1RAfvyHrqVM --- cockpit/src/curation_io.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/cockpit/src/curation_io.rs b/cockpit/src/curation_io.rs index 0c862e15..50877f3d 100644 --- a/cockpit/src/curation_io.rs +++ b/cockpit/src/curation_io.rs @@ -1,15 +1,19 @@ //! Curation-store persistence adapter for the cockpit (step 3C-A). //! -//! The browser backend for [`griff_core::curation_store`]: it reads and writes -//! the store's **canonical bytes** — the same `encode_store`/`decode_store` the -//! CLI's native adapter uses (ADR-0027 §3: "no browser-specific wire schema") — -//! to a single OPFS file, `curation/store.json`. A native arm mirrors it over -//! `std::fs` for the desktop cockpit. +//! The **browser** backend for [`griff_core::curation_store`]: it reads and +//! writes the store's **canonical bytes** — the same `encode_store`/`decode_store` +//! the CLI's native adapter uses (ADR-0027 §3: "no browser-specific wire schema") +//! — to a single OPFS file, `curation/store.json`. //! -//! Only the byte *transport* is per-target; the Missing-vs-malformed -//! classification and the format itself live in core. There is deliberately **no -//! trait abstracting this over the CLI's native adapter (3B2)**: the shared -//! contract is core's encode/decode, which both call directly. +//! The byte *transport* is browser-only (`#[cfg(target_arch = "wasm32")]`); it is +//! deliberately **not** paired with a native `std::fs` backend here. Durable +//! native persistence is the CLI's frozen `curation_fs` adapter (3B2, atomic +//! temp-then-rename); a plain `std::fs::write` from the cockpit would be a weaker +//! second backend, so this slice ships the browser transport and the pure, +//! native-tested [`encode`]/[`classify`] seam — nothing degraded. +//! +//! There is likewise **no trait** abstracting this over the CLI adapter: the +//! shared contract is core's encode/decode, which both call directly. //! //! **Experimental, `#[doc(hidden)]`** via the crate — not a stable API.