diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index 646d823..21693d5 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -1,7 +1,7 @@ //! The `weksa` command line: the same validator and store admission the library //! exposes, plus text projections (`dump`) that are for review and are not stores. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use clap::error::{ContextKind, ContextValue, ErrorKind}; @@ -20,7 +20,7 @@ use weksa::run::{ use weksa::score::ScoreInput; use weksa::{ Annotator, CorpusStore, EntityId, EntityStore, Family, InventoryStore, OllamaEmbedder, OntologyStore, OptionLabel, - PacketStore, PairRelation, Party, Scene, Slot, SpeakerStateStore, ValueKind, Scorer, Split, SplitScheme, StoreError, lower, pronounce, validate, + PacketStore, PairRelation, Party, Scene, Slot, SpeakerStateStore, ValueKind, Scorer, Split, SplitScheme, StoreError, StoreRefusal, lower, pronounce, validate, }; #[derive(Parser)] @@ -790,6 +790,38 @@ fn main() -> Result<()> { ); } let (new_entities, items) = draft.into_import(&marked, &annotator)?; + // Every document passes the real doors on scratch copies of the + // stores before the first write, so a refusal leaves them untouched. + let scratch = std::env::temp_dir().join(format!("weksa-import-{}", std::process::id())); + std::fs::create_dir_all(&scratch)?; + let dry = (|| -> Result<()> { + let copy = |from: &Path, name: &str| -> Result { + let to = scratch.join(name); + if from.exists() { + std::fs::copy(from, &to)?; + } + Ok(to) + }; + let mut entities = EntityStore::open(©(&cli.entities, "e.cc")?)?; + let mut store = CorpusStore::open(©(&cli.corpus, "c.cc")?)?; + for e in new_entities.clone() { + entities + .put(e) + .map_err(|e| anyhow::anyhow!("a cast entity: {e}"))?; + } + for item in items.clone() { + let key = item.id.clone(); + store.add(item, &entities).map_err(|e| match e { + StoreError::Refused(StoreRefusal::S6TextHeld { held_by, .. }) => { + anyhow::anyhow!("{key} repeats the text of {held_by}") + } + e => anyhow::anyhow!("{key}: {e}"), + })?; + } + Ok(()) + })(); + let _ = std::fs::remove_dir_all(&scratch); + dry?; let mut entities = EntityStore::open(&cli.entities)?; for e in new_entities { let id = e.id.clone(); diff --git a/crates/weksa/tests/cli.rs b/crates/weksa/tests/cli.rs index 8e3d66e..b451cee 100644 --- a/crates/weksa/tests/cli.rs +++ b/crates/weksa/tests/cli.rs @@ -2202,3 +2202,77 @@ fn corpus_import_labels_spans_and_is_idempotent() { let dump = out(&weksa(d.path(), &["corpus", "dump"])); assert!(dump.contains("by Some(Model"), "{dump}"); } + +const LANTERN_CAST: &str = r#""cast":[{"entity":"entity:orsa","forms":["Orsa"]},{"entity":"entity:tamsin","forms":["Tamsin","Tam"]}]"#; +const LANTERN_SOURCE: &str = r#""source":{"PublicDomain":{"work":"The Lantern Wager","author":"A. Invented","edition_url":"https://example.invalid/lantern","licence":"public domain","jurisdiction":"US","translator":"none","edition_year":1890}}"#; + +/// Writes a work of `lines` (text per line, all said by Orsa) and an answer of +/// `marked` per line, returns both paths. +fn lantern(dir: &std::path::Path, lines: &[&str], marked: &[&str]) -> (String, String) { + let ls: Vec = lines + .iter() + .map(|t| format!(r#"{{"group":"s1","speaker":"entity:orsa","text":"{t}"}}"#)) + .collect(); + let work = dir.join("w.json"); + std::fs::write( + &work, + format!( + r#"{{"slug":"lantern-wager","language":"en-US","admitted_on":"2026-11-13",{LANTERN_SOURCE},{LANTERN_CAST},"lines":[{}]}}"#, + ls.join(",") + ), + ) + .unwrap(); + let names = dir.join("n.jsonl"); + let rows: Vec = marked + .iter() + .enumerate() + .map(|(i, m)| format!(r#"{{"line":{},"marked":"{m}"}}"#, i + 1)) + .collect(); + std::fs::write(&names, rows.join("\n")).unwrap(); + (work.to_str().unwrap().into(), names.to_str().unwrap().into()) +} + +const MODEL: [&str; 4] = ["--model-family", "anthropic", "--generator", "a name annotator"]; + +#[test] +fn a_refused_import_writes_nothing_and_a_redraw_imports() { + let d = tempfile::tempdir().unwrap(); + let lines = ["Tamsin, bring the lantern.", "Tamsin's lantern, said Orsa."]; + let (w, n) = lantern(d.path(), &lines, &["[[entity:tamsin|Tamsin]], bring the lantern.", "[[entity:tamsin|Tamsin's]] lantern, said Orsa."]); + let import = |w: &str, n: &str| weksa(d.path(), &[&["corpus", "import", w, n][..], &MODEL].concat()); + let bad = import(&w, &n); + assert!(!bad.status.success()); + assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), ""); + assert!(!d.path().join("e.cc").exists() || EntityStore::open(&d.path().join("e.cc")).unwrap().all().unwrap().is_empty()); + // The redrawn answer, different on line 1 too, imports. + let (w, n) = lantern(d.path(), &lines, &["Tamsin, bring the lantern.", "[[entity:tamsin|Tamsin]]'s lantern, said Orsa."]); + let good = import(&w, &n); + assert!(good.status.success(), "{}", out(&good)); + assert!(out(&good).contains("Added item:lantern-wager:2")); +} + +#[test] +fn a_work_repeating_a_line_is_refused_naming_both_lines() { + let d = tempfile::tempdir().unwrap(); + let (w, n) = lantern(d.path(), &["No, my lord.", "No, my lord!", "Quiet, both of you."], &["No, my lord.", "No, my lord!", "Quiet, both of you."]); + let o = weksa(d.path(), &[&["corpus", "import", &w, &n][..], &MODEL].concat()); + assert!(!o.status.success()); + let err = String::from_utf8_lossy(&o.stderr).to_string(); + assert!(err.contains("item:lantern-wager:2") && err.contains("item:lantern-wager:1"), "{err}"); + assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), ""); +} + +#[test] +fn the_annotator_flags_decide_the_label() { + let d = tempfile::tempdir().unwrap(); + let (w, n) = lantern(d.path(), &["Quiet, both of you."], &["Quiet, both of you."]); + let none = weksa(d.path(), &["corpus", "import", &w, &n]); + assert!(!none.status.success()); + let blank = weksa(d.path(), &["corpus", "import", &w, &n, "--model-family", "anthropic", "--generator", " "]); + assert!(!blank.status.success()); + assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), ""); + let op = weksa(d.path(), &["corpus", "import", &w, &n, "--operator"]); + assert!(op.status.success(), "{}", out(&op)); + let dump = out(&weksa(d.path(), &["corpus", "dump"])); + assert!(dump.contains("by Some(Operator)"), "{dump}"); +} diff --git a/docs/name-span-annotation.md b/docs/name-span-annotation.md index 0305158..a91f646 100644 --- a/docs/name-span-annotation.md +++ b/docs/name-span-annotation.md @@ -30,7 +30,12 @@ You are given a work's cast: each member's entity id and the forms the work spel - Import with `--model-family` and `--generator ' (name-span rubric r1, docs/name-span-annotation.md)'`. An operator-written or operator-reviewed answer imports with `--operator`. -- A parse failure or a refused line is re-drawn once and logged. +- Import is all or nothing: every entity and item passes the real store doors on + scratch copies before the first write, so a refusal (a parse failure, a span + the store judges, a work that repeats a line under case or width folding) + leaves the stores untouched. Re-draw the whole answer once, log it, and import + again. A work file repeating a line's text is refused naming both lines; fix + the file (a repeated line cannot be two corpus items). - A line the answer does not cover is not imported by that run; a later run over other lines of the work does not collide (keys are `item::`). - A line whose own text holds `[[` or `]]` cannot be marked and is refused; it