From 966a3678a70df3ff410fd371216c47585f5d781d Mon Sep 17 00:00:00 2001 From: Weksa Date: Thu, 12 Nov 2026 16:31:55 +0000 Subject: [PATCH] language-ontology-scene s3-6: inventory rev 4 in both beds, empty speaker-state stores committed, scene tests, original corpus checks, lowering map Co-Authored-By: Claude Sonnet 5.5 --- crates/weksa/src/main.rs | 2 +- crates/weksa/src/run.rs | 4 +- crates/weksa/tests/cli.rs | 65 ++++++- crates/weksa/tests/common/mod.rs | 15 ++ crates/weksa/tests/golf_loop.rs | 217 ++++++++++++++++++++++- crates/weksa/tests/original_corpus.rs | 38 +++- crates/weksa/tests/scene.rs | 57 ++++++ crates/weksa/tests/stores.rs | 41 ++++- data/corpus/speaker-state.cc | 1 + data/daodejing/inventory.cc | Bin 10559 -> 11369 bytes data/daodejing/speaker-state.cc | 1 + data/original/inventory.cc | Bin 10559 -> 11369 bytes data/original/speaker-state.cc | 1 + docs/targets/interlingua-lowering-map.md | 8 +- 14 files changed, 429 insertions(+), 21 deletions(-) create mode 100644 data/corpus/speaker-state.cc create mode 100644 data/daodejing/speaker-state.cc create mode 100644 data/original/speaker-state.cc diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index efae4ff..c4d7be6 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -844,7 +844,7 @@ fn main() -> Result<()> { } ValueKind::Flag => FeatValue::Flag(value.parse().map_err(|_| bad())?), }; - features.push(FeatureValue { feature: entry.id.clone(), value }); + features.push(FeatureValue { feature: entry.id, value }); } let mut participants = vec![from.clone()]; if let Party::Named(a) = &to diff --git a/crates/weksa/src/run.rs b/crates/weksa/src/run.rs index 6d598d9..8b49f8e 100644 --- a/crates/weksa/src/run.rs +++ b/crates/weksa/src/run.rs @@ -2953,7 +2953,7 @@ mod tests { } /// Answers the Dao encode prompts from `answers` by item, the candidate - /// inventory's (rev 4) from the good drafts, and the editor with one concept. + /// inventory's (rev 5) from the good drafts, and the editor with one concept. struct Fake { degraded: HashMap, good: HashMap, @@ -2980,7 +2980,7 @@ mod tests { }; return Ok(format!(r#"{{"text":"{text}"}}"#)); } - let answers = if prompt.text().contains("\n\ninventory rev:4\n") { + let answers = if prompt.text().contains("\n\ninventory rev:5\n") { &self.good } else { &self.degraded diff --git a/crates/weksa/tests/cli.rs b/crates/weksa/tests/cli.rs index e90297b..65563ea 100644 --- a/crates/weksa/tests/cli.rs +++ b/crates/weksa/tests/cli.rs @@ -1416,7 +1416,7 @@ fn loop_open_and_unanswered_round() { assert!(second.status.success(), "{}", out(&second)); assert_eq!( out(&second), - "round 1 rev 3 en-US train n=1 scored=0 chrf=0.00 meaning=0.0000 refused=1 validation n=2 scored=0 chrf=0.00 meaning=0.0000 refused parse=2 admit=0 lower=0 parse-reasons=syntaxx3 lowering=tool-less-relay\n" + "round 1 rev 4 en-US train n=1 scored=0 chrf=0.00 meaning=0.0000 refused=1 validation n=2 scored=0 chrf=0.00 meaning=0.0000 refused parse=2 admit=0 lower=0 parse-reasons=syntaxx3 lowering=tool-less-relay\n" ); // The global store flags are not read by loop round: a drifted store is refused. @@ -1549,7 +1549,7 @@ fn loop_cycle_asks_then_decides() { assert!(done.status.success(), "{}", out(&done)); assert_eq!( out(&done), - "cycle 1 rev 3->none en-US base=0.0000 candidate=none floor=0.0000 threshold=0.0050 rejected edit-parse lowering=tool-less-relay\n" + "cycle 1 rev 4->none en-US base=0.0000 candidate=none floor=0.0000 threshold=0.0050 rejected edit-parse lowering=tool-less-relay\n" ); // The next cycle asks afresh in its own directory. @@ -1814,3 +1814,64 @@ fn ontology_admit_and_dump() { assert!(!out(&o).contains("LEAKYCHOICE"), "{}", out(&o)); assert_eq!(out(&weksa(d.path(), &["ontology", "dump"])), before); } + +#[test] +fn scene_put_and_dump() { + let d = tempfile::tempdir().unwrap(); + cast_entities(d.path(), &["nibu", "brokkr"]); + for step in ["seed", "proof", "speaker-scene"] { + let o = weksa(d.path(), &["inventory", step]); + assert!(o.status.success(), "{}", out(&o)); + } + let mut add = ADD.to_vec(); + add.extend(["--persona", "nibu", "--fixture", "f.yaml", "--author", "Ada Writer"]); + let o = weksa(d.path(), &add); + assert!(o.status.success(), "{}", out(&o)); + let put = |group: &str, to: &str, sets: &[&str]| { + let mut args = vec![ + "scene", "put", "--group", group, "--to", to, "--inventory-rev", "3", + "--model-family", "anthropic", "--generator", "a scene annotator", + ]; + for s in sets { + args.extend(["--set", s]); + } + weksa(d.path(), &args) + }; + let sets = ["relative_status=above", "intimacy=200", "in_group=false"]; + let o = put("scene-1", "unnamed", &sets); + assert!(o.status.success(), "{}", out(&o)); + let dump = out(&weksa(d.path(), &["scene", "dump"])); + for want in ["scene:scene-1@1", "rev:3", "Anthropic", "a scene annotator", "entity:nibu->unnamed", "relative_status=above", "intimacy=200", "in_group=false"] { + assert!(dump.contains(want), "{want}: {dump}"); + } + // A repeat is unchanged and writes nothing. + let o = put("scene-1", "unnamed", &sets); + assert!(out(&o).contains("unchanged"), "{}", out(&o)); + assert_eq!(out(&weksa(d.path(), &["scene", "dump"])), dump); + // A changed value is the next revision. + let o = put("scene-1", "unnamed", &["relative_status=level", "intimacy=200", "in_group=false"]); + assert!(o.status.success(), "{}", out(&o)); + assert!(out(&weksa(d.path(), &["scene", "dump"])).contains("scene:scene-1@2")); + // An unknown gloss and an unknown group are refused and not echoed. + for (group, set) in [("scene-1", "canarygloss=1"), ("canarygroup", "intimacy=1")] { + let before = out(&weksa(d.path(), &["scene", "dump"])); + let o = put(group, "unnamed", &[set]); + assert!(!o.status.success()); + assert!(!out(&o).contains("canary"), "{}", out(&o)); + assert_eq!(out(&weksa(d.path(), &["scene", "dump"])), before); + } + // A group with two live speakers is refused: multi-party scenes wait. + let mut two = add.clone(); + let at = two.iter().position(|a| *a == "entity:nibu").unwrap(); + two[at] = "entity:brokkr"; + let at = two.iter().position(|a| *a == "nibu").unwrap(); + two[at] = "brokkr"; + two.retain(|a| *a != "Mind the hatch."); + let at = two.iter().position(|a| *a == "--text").unwrap() + 1; + two.insert(at, "Brokkr speaks."); + let o = weksa(d.path(), &two); + assert!(o.status.success(), "{}", out(&o)); + let o = put("scene-1", "unnamed", &sets); + assert!(!o.status.success()); + assert!(!out(&o).contains("scene-1"), "{}", out(&o)); +} diff --git a/crates/weksa/tests/common/mod.rs b/crates/weksa/tests/common/mod.rs index 723a371..fa2deb9 100644 --- a/crates/weksa/tests/common/mod.rs +++ b/crates/weksa/tests/common/mod.rs @@ -123,6 +123,21 @@ pub fn ontology_in(dir: &std::path::Path) -> std::path::PathBuf { path } +/// A new inventory store at `path` holding the Dao inventory as it stood at +/// rev 3 (seed, proof, the Dao revision): the loop tests' fixed head, whose +/// round and candidate revisions they pin. The committed +/// `data/daodejing/inventory.cc` is rev 4 and is read by the corpus tests. +pub fn dao_rev3_at(path: &std::path::Path) { + let mut store = weksa::InventoryStore::open(path).unwrap(); + for (rev, entries) in [ + weksa::inventory::seed(), + weksa::inventory::proof_revision(), + weksa::daodejing::revision(), + ] { + store.admit_revision(rev, entries).unwrap(); + } +} + /// An empty speaker-state store beside `ontology` (same directory), made if absent. pub fn speaker_state_beside(ontology: &std::path::Path) -> std::path::PathBuf { let path = ontology.with_file_name("speaker-state.cc"); diff --git a/crates/weksa/tests/golf_loop.rs b/crates/weksa/tests/golf_loop.rs index 3c36f33..d2bf719 100644 --- a/crates/weksa/tests/golf_loop.rs +++ b/crates/weksa/tests/golf_loop.rs @@ -896,9 +896,11 @@ fn dao_build( std::fs::copy(src.join(from), dir.path().join(to)).unwrap(); dir.path().join(to) }; + // The Dao inventory at rev 3: the pins below are written against it. + common::dao_rev3_at(&dir.path().join("i.cc")); let (corpus, inventory, entities) = ( copy("corpus.cc", "c.cc"), - copy("inventory.cc", "i.cc"), + dir.path().join("i.cc"), copy("entity.cc", "e.cc"), ); edit(&corpus, &entities); @@ -4778,7 +4780,7 @@ fn create_refuses_an_entry_its_inventory_cannot_read() { inventory: &dir.join("i.cc"), entities: &dir.join("e.cc"), ontology, - speaker_state: &common::speaker_state_beside(&ontology), + speaker_state: &common::speaker_state_beside(ontology), }, "fake-model", "bag", @@ -4834,3 +4836,214 @@ fn round_lowering_prompts_carry_selected_entries() { } assert_eq!(seen.len(), 6, "three items in each language"); } + +/// Admits the speaker-state revision (rev 4) onto the rev-3 Dao inventory at +/// `inventory`, and the scene for the group of `item:daodejing:3`: Laozi's +/// relation to an unnamed party, above, intimacy 200. +fn put_dao_scene(speaker_state: &Path, inventory: &Path, corpus: &Path, entities: &Path) { + use weksa::packet::{FeatValue, FeatureValue}; + let mut inv_store = InventoryStore::open(inventory).unwrap(); + let (rev, entries) = weksa::inventory::speaker_scene_revision(4); + inv_store.admit_revision(rev, entries).unwrap(); + let inv = inv_store.inventory().unwrap(); + let id = |gloss: &str| inv.entries().find(|e| e.gloss == gloss).unwrap().id; + let corpus = CorpusStore::open(corpus).unwrap(); + let item = corpus.get("item:daodejing:3").unwrap().unwrap(); + let scene = weksa::Scene { + group: item.group.clone(), + n: 1, + inventory_rev: 4, + participants: vec![item.speaker.clone()], + relations: vec![weksa::PairRelation { + from: item.speaker.clone(), + to: weksa::Party::Unnamed, + features: vec![ + FeatureValue { + feature: id("relative_status"), + value: FeatValue::Option(common::lab("above")), + }, + FeatureValue { + feature: id("intimacy"), + value: FeatValue::Grade(common::grade(200)), + }, + ], + }], + annotator: weksa::Annotator::Operator, + }; + weksa::SpeakerStateStore::open(speaker_state) + .unwrap() + .put_scene(scene, &inv_store, &corpus, &weksa::EntityStore::open(entities).unwrap()) + .unwrap(); +} + +/// A Dao run whose store holds a scene for item 3's group and whose ontology +/// holds en-US:1, selected when the speaker is above the addressee. +fn scene_dao(extra: impl FnOnce(&Path, &Path)) -> Dao { + dao_build( + |_, _| {}, + &["en-US"], + |ontology, inventory| { + use weksa::{Condition, Layer, OntologyEntry, OntologyStore, Slot, Test}; + let dir = ontology.parent().unwrap(); + put_dao_scene( + &common::speaker_state_beside(ontology), + inventory, + &dir.join("c.cc"), + &dir.join("e.cc"), + ); + let inv_store = InventoryStore::open(inventory).unwrap(); + let status = inv_store + .inventory() + .unwrap() + .entries() + .find(|e| e.gloss == "relative_status") + .unwrap() + .id; + OntologyStore::open(ontology) + .unwrap() + .admit( + vec![OntologyEntry { + language: "en-US".into(), + n: 1, + inventory_rev: 4, + layer: Layer::Discourse, + when: vec![Condition { + slot: Slot::Scene, + feature: status, + test: Test::Is(weksa::packet::FeatValue::Option(common::lab("above"))), + }], + choice: "ENABOVE".into(), + examples: vec![], + annotator: weksa::Annotator::Operator, + }], + &inv_store, + ) + .unwrap(); + extra(&dir.join("c.cc"), &dir.join("e.cc")); + }, + ) +} + +/// Answers for items 1 to 3 where item 3 names referent n2 (no entity) as its +/// addressee, or nobody. +fn addressing(addressee: Option<&str>) -> Vec<(usize, String)> { + (1..=3) + .map(|n| { + let mut v = serde_json::to_value(draft_of(n)).unwrap(); + if n == 3 { + v["discourse"]["addressee"] = serde_json::json!(addressee); + } + (n, v.to_string()) + }) + .collect() +} + +fn lowering_of(model: &FakeModel, marker: &str) -> Vec { + lowering_texts(model) + .into_iter() + .filter(|t| t.contains(marker)) + .map(String::from) + .collect() +} + +#[test] +fn round_prompts_carry_scene_selected_entries() { + // Above an unnamed addressee: item 3's prompt holds the entry, the other + // two (no scene for their groups) read NoScene and print without it. + let mut dao = scene_dao(|_, _| {}); + let mut model = fake(&addressing(Some("n2"))); + recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap()); + assert_eq!(lowering_texts(&model).len(), 3); + let with = lowering_of(&model, "\nonto:en-US:1 [discourse] ENABOVE"); + assert_eq!(with.len(), 1, "only item 3 has a scene and an addressee"); + assert_eq!( + lowering_texts(&model).iter().filter(|t| t.contains("ontology: none")).count(), + 2 + ); + // The same item with no addressee selects no Scene entry. + let mut dao = scene_dao(|_, _| {}); + let mut model = fake(&addressing(None)); + recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap()); + assert!(lowering_of(&model, "ENABOVE").is_empty()); + assert_eq!(lowering_texts(&model).len(), 3); +} + +#[test] +fn a_scene_read_failure_is_a_lower_refusal() { + // A live item of item 3's group, in a language outside the panel, spoken by + // someone the scene does not cover: V16 for that group. + let mut dao = scene_dao(|corpus, entities| { + let mut entity_store = weksa::EntityStore::open(entities).unwrap(); + entity_store.put(ent("stranger", "en-US", &["Stranger"])).unwrap(); + let mut store = CorpusStore::open(corpus).unwrap(); + let mut twin = store.get("item:daodejing:3").unwrap().unwrap(); + twin.id = "item:daodejing:93".into(); + twin.language = "pt-BR".into(); + twin.text = "PORTUGUESEMARK 93 o sabio".into(); + twin.speaker = common::eid("stranger"); + twin.names = vec![]; + twin.prior_turns = vec![]; + store.add(twin, &entity_store).unwrap(); + }); + let mut model = fake(&addressing(Some("n2"))); + let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap()); + // Item 3 never reached the model; items 1 and 2 did, and the round recorded. + assert_eq!(lowering_texts(&model).len(), 2); + assert_eq!(r.n(), 1); +} + +#[test] +fn a_run_pins_its_speaker_state_and_refuses_drift() { + let dao = scene_dao(|_, _| {}); + let r = dao.run.record(); + let path = dao.ontology.with_file_name("speaker-state.cc"); + assert_eq!(r.speaker_state, std::fs::canonicalize(&path).unwrap().to_str().unwrap()); + assert_eq!(r.speaker_state_digest, hex(&path)); + let root = dao.root.clone(); + assert_eq!(RunStores::open(&root).unwrap().record(), dao.run.record()); + let mut bytes = std::fs::read(&path).unwrap(); + bytes.push(0xc0); + std::fs::write(&path, bytes).unwrap(); + assert_eq!( + RunStores::open(&root).err(), + Some(RunError::Drift(DriftOf::SpeakerState)) + ); +} + +#[test] +fn create_refuses_a_scene_its_inventory_cannot_read() { + // The scene is admitted against a copy that gained rev 4; the run's head + // inventory stops at rev 3. + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing"); + let dir = tempfile::tempdir().unwrap(); + for (from, to) in [("corpus.cc", "c.cc"), ("entity.cc", "e.cc")] { + std::fs::copy(src.join(from), dir.path().join(to)).unwrap(); + } + common::dao_rev3_at(&dir.path().join("i.cc")); + common::dao_rev3_at(&dir.path().join("rich.cc")); + let state = common::speaker_state_in(dir.path()); + put_dao_scene(&state, &dir.path().join("rich.cc"), &dir.path().join("c.cc"), &dir.path().join("e.cc")); + let ontology = common::ontology_in(dir.path()); + let root = dir.path().join("run"); + let create = || { + RunStores::create( + &root, + "x", + RunPaths { + corpus: &dir.path().join("c.cc"), + inventory: &dir.path().join("i.cc"), + entities: &dir.path().join("e.cc"), + ontology: &ontology, + speaker_state: &state, + }, + "fake-model", + "bag", + weksa::run::LowererReach::ToolLessRelay, + ModelFamily::Unrecorded, + &["en-US".to_string()], + ) + }; + assert_eq!(create().err(), Some(RunError::SpeakerState)); + assert!(!root.join("run.cc").exists()); + assert!(!root.join("inventory.cc").exists()); +} diff --git a/crates/weksa/tests/original_corpus.rs b/crates/weksa/tests/original_corpus.rs index 8b06da7..8838554 100644 --- a/crates/weksa/tests/original_corpus.rs +++ b/crates/weksa/tests/original_corpus.rs @@ -18,7 +18,7 @@ use weksa::{CorpusStore, EntityStore, InventoryStore}; fn stores() -> (CorpusStore, EntityStore) { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/original"); let tmp = tempfile::tempdir().unwrap(); - for f in ["corpus.cc", "entity.cc", "inventory.cc"] { + for f in ["corpus.cc", "entity.cc", "inventory.cc", "speaker-state.cc"] { std::fs::copy(dir.join(f), tmp.path().join(f)).unwrap(); } let keep = tmp.keep(); @@ -241,14 +241,22 @@ fn the_first_six_original_items_are_unchanged() { } #[test] -fn the_original_inventory_is_the_dao_revision_three() { +fn the_original_inventory_is_the_dao_inventory() { let dao = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing/inventory.cc"); let own = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/original/inventory.cc"); assert_eq!(std::fs::read(dao).unwrap(), std::fs::read(&own).unwrap()); let tmp = tempfile::tempdir().unwrap(); let copy = tmp.path().join("inventory.cc"); std::fs::copy(&own, ©).unwrap(); - assert!(InventoryStore::open(©).is_ok()); + let inventory = InventoryStore::open(©).unwrap().inventory().unwrap(); + // Revision 4 is the speaker-state vocabulary: the same six features the + // generator admits, ids and all. + assert_eq!(inventory.latest().unwrap().n, 4); + let (rev, entries) = weksa::inventory::speaker_scene_revision(4); + assert_eq!(inventory.latest().unwrap().changes, rev.changes); + for e in &entries { + assert_eq!(inventory.entry(&e.id), Some(e), "{}", e.gloss); + } } /// The committed seed ontology: every entry model-drafted, exactly the two @@ -270,8 +278,12 @@ fn committed_ontology_is_model_drafted_and_reads_every_inventory() { match &e.annotator { Annotator::Model { family, generator } => { assert_eq!(*family, ModelFamily::Anthropic, "{}", e.key()); - assert_eq!( - generator, "claude-sonnet-5-5 (Weksa Hands, model-drafted seed ontology)", + assert!( + [ + "claude-sonnet-5-5 (Weksa Hands, model-drafted seed ontology)", + "claude-sonnet-5-5 (Weksa Hands, model-drafted scene ontology)", + ] + .contains(&generator.as_str()), "{}", e.key() ); @@ -283,6 +295,15 @@ fn committed_ontology_is_model_drafted_and_reads_every_inventory() { langs.sort(); langs.dedup(); assert_eq!(langs, PANEL); + // Every entry from number 10 on is conditioned on the scene relation, and + // only an entry with a Scene condition may name a politeness level. + for e in entries.iter().filter(|e| e.n >= 10) { + assert!( + e.when.iter().any(|c| c.slot == weksa::inventory::Slot::Scene), + "{} has no Scene condition", + e.key() + ); + } for lang in PANEL { let stance = |c: &Condition| c.slot == weksa::inventory::Slot::Stance; assert!( @@ -299,6 +320,7 @@ fn committed_ontology_is_model_drafted_and_reads_every_inventory() { tmp.path().join(format!("{corpus}-{f}")) }; let (c, i, e) = (copy("corpus.cc"), copy("inventory.cc"), copy("entity.cc")); + let s = copy("speaker-state.cc"); RunStores::create( &tmp.path().join(format!("run-{corpus}")), corpus, @@ -307,7 +329,7 @@ fn committed_ontology_is_model_drafted_and_reads_every_inventory() { inventory: &i, entities: &e, ontology: &onto, - speaker_state: &common::speaker_state_beside(&onto), + speaker_state: &s, }, "m", "bag", @@ -419,7 +441,7 @@ fn original_round(family: ModelFamily) -> (weksa::run::RunStores, weksa::run::Ro use weksa::run::{LowererReach, RoundOutcome, RunPaths, RunStores, round}; let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/original"); let tmp = tempfile::tempdir().unwrap().keep(); - for f in ["corpus.cc", "entity.cc", "inventory.cc"] { + for f in ["corpus.cc", "entity.cc", "inventory.cc", "speaker-state.cc"] { std::fs::copy(src.join(f), tmp.join(f)).unwrap(); } std::fs::write(tmp.join("ontology.cc"), [0x90]).unwrap(); @@ -578,7 +600,7 @@ fn no_test_item_is_offered_to_a_round_or_recall_or_recorded() { use weksa::run::{LowererReach, RoundOutcome, RunPaths, RunStores, round}; let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/original"); let tmp = tempfile::tempdir().unwrap(); - for f in ["corpus.cc", "entity.cc", "inventory.cc"] { + for f in ["corpus.cc", "entity.cc", "inventory.cc", "speaker-state.cc"] { std::fs::copy(src.join(f), tmp.path().join(f)).unwrap(); } std::fs::write(tmp.path().join("ontology.cc"), [0x90]).unwrap(); diff --git a/crates/weksa/tests/scene.rs b/crates/weksa/tests/scene.rs index 66f3cb7..5974883 100644 --- a/crates/weksa/tests/scene.rs +++ b/crates/weksa/tests/scene.rs @@ -408,3 +408,60 @@ fn only_live_speakers_of_the_views_group_and_the_views_own_speaker_must_be_cover ["V16"] ); } + +mod select { + use super::*; + use weksa::speaker::Annotator; + use weksa::{Condition, Layer, OntologyEntry, OntologyStore, Slot, Test, select}; + + fn scene_feature(gloss: &str) -> weksa::InvId { + speaker_scene_revision(3).1.into_iter().find(|e| e.gloss == gloss).unwrap().id + } + + fn entry(n: u32, slot: Slot, gloss: &str, test: Test) -> OntologyEntry { + OntologyEntry { + language: "ja-JP".into(), + n, + inventory_rev: 3, + layer: Layer::Grammar, + when: vec![Condition { slot, feature: scene_feature(gloss), test }], + choice: "a choice".into(), + examples: vec![], + annotator: Annotator::Operator, + } + } + + #[test] + fn select_reads_the_scene_relation() { + let mut w = world(); + put(&mut w, standard("g", 1)); + let mut store = OntologyStore::open(&w.dir.path().join("o.cc")).unwrap(); + store + .admit( + vec![ + entry(1, Slot::Scene, "relative_status", Test::Is(FeatValue::Option(lab("above")))), + entry(2, Slot::Scene, "intimacy", Test::AtLeast(grade(150))), + ], + &w.inventory, + ) + .unwrap(); + let ontology = store.ontology().unwrap(); + let keys = |read: SceneRead, w: &W| { + let view = view_of(w, 3, Some("n3")).with_scene(&inv(w), &w.state, &w.corpus).unwrap(); + assert_eq!(view.scene_read(), &read); + select(&ontology, "ja-JP", &view).iter().map(|e| e.n).collect::>() + }; + // Brokkr is above-status at intimacy 200: both Scene entries select. + assert_eq!(keys(selected(1, status()), &w), [1, 2]); + // No scene for the group: neither selects. + let empty = world(); + assert_eq!(keys(SceneRead::NoScene, &empty), Vec::::new()); + // No addressee, and no relation to the addressee: neither selects. + let view = view_of(&w, 3, None).with_scene(&inv(&w), &w.state, &w.corpus).unwrap(); + assert_eq!(view.scene_read(), &SceneRead::NoAddressee { rev: 1 }); + assert!(select(&ontology, "ja-JP", &view).is_empty()); + let mut lone = world(); + put(&mut lone, scene("g", 1, &["nibu", "brokkr"], vec![relation("brokkr", Party::Named(eid("nibu")), intimacy(99))])); + assert_eq!(keys(SceneRead::NoRelation { rev: 1 }, &lone), Vec::::new()); + } +} diff --git a/crates/weksa/tests/stores.rs b/crates/weksa/tests/stores.rs index f027611..5b26e85 100644 --- a/crates/weksa/tests/stores.rs +++ b/crates/weksa/tests/stores.rs @@ -1740,9 +1740,9 @@ mod ontology { "five conditions", vec![OntologyEntry { when: (0..5).map(|_| restraint()).collect(), ..entry("ja-JP", 1) }], )); - for slot in [Slot::Speaker, Slot::Scene, Slot::Predication] { + for slot in [Slot::Speaker, Slot::Predication] { cases.push(( - "slot not Stance or Discourse", + "slot not Stance, Discourse or Scene", vec![OntologyEntry { when: vec![when(slot, "restraint", Test::AtLeast(Grade::new(1).unwrap()))], ..entry("ja-JP", 1) @@ -1818,6 +1818,43 @@ mod ontology { assert_eq!(s.all().unwrap().len(), 64); } + #[test] + fn ontology_admit_takes_scene_refuses_speaker() { + use weksa::inventory::{proof_revision, speaker_scene_revision}; + let d = dir(); + let mut inventory = InventoryStore::open(&d.path().join("i.cc")).unwrap(); + for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision(3)] { + inventory.admit_revision(rev, entries).unwrap(); + } + let scene_feature = |gloss: &str| { + speaker_scene_revision(3).1.into_iter().find(|e| e.gloss == gloss).unwrap().id + }; + let at = |slot, feature, test| OntologyEntry { + inventory_rev: 3, + when: vec![Condition { slot, feature, test }], + ..entry("ja-JP", 1) + }; + let above = Test::Is(FeatValue::Option(lab("above"))); + let mut s = store(&d); + // A Scene condition on a Scene feature admits. + assert_eq!( + s.admit(vec![at(Slot::Scene, scene_feature("relative_status"), above.clone())], &inventory) + .unwrap(), + AddOutcome::Added + ); + // Speaker and Predication slots refuse, and a Scene condition naming a + // Stance feature refuses. + for bad in [ + at(Slot::Speaker, scene_feature("education"), Test::AtLeast(Grade::new(1).unwrap())), + at(Slot::Predication, feature("modality"), Test::Is(FeatValue::Option(lab("actual")))), + at(Slot::Scene, feature("restraint"), Test::AtLeast(Grade::new(1).unwrap())), + ] { + let bad = OntologyEntry { n: 2, ..bad }; + assert!(s.admit(vec![bad], &inventory).is_err()); + } + assert_eq!(s.all().unwrap().len(), 1); + } + #[test] fn ontology_admit_is_all_or_nothing() { let d = dir(); diff --git a/data/corpus/speaker-state.cc b/data/corpus/speaker-state.cc new file mode 100644 index 0000000..9e99dd5 --- /dev/null +++ b/data/corpus/speaker-state.cc @@ -0,0 +1 @@ +� \ No newline at end of file diff --git a/data/daodejing/inventory.cc b/data/daodejing/inventory.cc index 373eb3cf259663321fdf94128b4f11a984998f01..3904b809b75c3558a065b8043c36df0a79b8aeaf 100644 GIT binary patch delta 653 zcmaLT!Ab%_7zc1Pp%C!_f>0{*(!p7`z$F4Nb*dl>qC?9#^R;e`JF+{w;n61uS@Q*I zFzt{abP9^-5qg1+y+te4y6d6Kz<&LFIDN15hUb8VYlDW$k2WwYOb>KN1brw;W&AfblEI zzyl_6jeF3MRRR{Ie3WgcLqqY4$^3R~!s>K_QoJ`UVKy*n$z2=M5P9uRg~`sjtr)Qq zAy7c*hRxmP-44UX-x^WD|6I!N#Q-$|C{GS2CWoLS-Z07JREwIH@w-vK+5~(Fb}A;~ zg?uF@79wJ40MsQxaoqY3Q74DhV#;wuQHR(7o$xxhMOgfeBz2R~A*P&x6BI5UTHLh^ z9aEPH`SSv!V0XgB$D{1^;(S-y;AyJ=yteGbW0{*(!p7`z$F4Nb*dl>qC?9#^R;e`JF+{w;n61uS@Q*I zFzt{abP9^-5qg1+y+te4y6d6Kz<&LFIDN15hUb8VYlDW$k2WwYOb>KN1brw;W&AfblEI zzyl_6jeF3MRRR{Ie3WgcLqqY4$^3R~!s>K_QoJ`UVKy*n$z2=M5P9uRg~`sjtr)Qq zAy7c*hRxmP-44UX-x^WD|6I!N#Q-$|C{GS2CWoLS-Z07JREwIH@w-vK+5~(Fb}A;~ zg?uF@79wJ40MsQxaoqY3Q74DhV#;wuQHR(7o$xxhMOgfeBz2R~A*P&x6BI5UTHLh^ z9aEPH`SSv!V0XgB$D{1^;(S-y;AyJ=yteGbW` constant in `crates/weksa`; published JSON Schema at `schemas/cultnet/` | Bumped by a commit that changes the Rust types; the published schema is regenerated in the same commit and a test fails on drift | A cut (Hands, under a spec); never the loop | | Inventory entry | Key `:`, `n` canonical decimal >= 1 (families: concept, frame, role, relation, speech_act, feature, referent_kind, extension); type `weksa.inventory_entry`, with a bounded gloss, value kind (option labels bounded), the slots a feature may sit in (`Discourse`, `Referent`, `Predication`, `Relation`; `Stance` from cut `speaker-state`, `Speaker` and `Scene` from cut `speaker-scene`), `introduced_rev` and optional `retired_rev`. Speaker axes, scene relations and affects are features of those slots, so the loop grows them like any closed-class family and convergence covers them | Added or retired by an inventory revision; never edited in place (a changed meaning is a retire plus an add); a retired id still resolves for packets of earlier revisions | The loop's accepted rounds, whose minting call the context builder assembles from Train items only; Self on merge to main. Admission checks form, not text | | Inventory revision | Key `rev:`, type `weksa.inventory_revision`, with parent, change list and `frozen` | Appended per accepted round; exactly one revision is ever marked frozen, by the convergence test | The loop's accept rule appends; the convergence test freezes; Self records the freeze as a ruling | -| Target profile | Locale or language-project id (`en-US`, `ja-JP`, a conlang's slug). Until entries grow in rounds there is no profile revision document: a run names the profile it lowered with by the ontology store's path and digest in its `RunRecord` (cut `language-ontology`); `profile::` revision documents arrive with follow-up `language-ontology-growth` | The ontology store is revised by commit; a run pins it and refuses drift | Profile authors and accepted rounds; never the lowerer's defaults (`persona-drives-register`) | -| Language ontology entry (cut `language-ontology`) | Key `onto::`, `n` from 1 per language; type `weksa.ontology_entry` in `data/ontology/ontology.cc`: the language, the inventory revision its conditions are read at, a layer (lexicon, grammar, discourse, phonology, orthography), at most four conditions (a feature id of slot `Stance` or `Discourse` with `AtLeast`/`AtMost` a grade or `Is` an option or flag; slots `Speaker` and `Scene` and community ids join with follow-up `language-ontology-view-assembly`), a choice of 1 to 200 bytes, at most three examples of 1 to 120 bytes, and an `Annotator` | Admitted in all-or-nothing batches through `OntologyStore::admit`, immutable, never edited; retire arrives with `language-ontology-growth`. The run pins the store like the entity store (path and digest, `Drift(Ontology)`), never copies it, because no loop step writes it yet. Cut `language-ontology-seed` converts by drafting, not by parse: a fresh model drafts each language's seed from that language's YAML and the inventory's feature lines with no corpus text, then deletes `data/target-language-ontology/` and `.weksa/cultural-ontology/` in the same cut | Seed: a labelled model (`Annotator::Model`), no operator gate, never Test evidence (`ja-ontology-owner-answer`); attestation (operator, native reader) appends later. Accepted rounds later, through a mint call from Train items only. Selection is `ontology::select(ontology, language, view)`, called only inside `Prompt::lower`, so no caller picks entries; the prompt prints each selected entry's id, layer, choice and examples. Its text is minted text for the leak diagnostic, which today has no runtime caller (follow-up `leak-diagnostic-in-round`) | +| Target profile | Locale or language-project id (`en-US`, `ja-JP`, a conlang's slug). Until entries grow in rounds there is no profile revision document: a run names the profile it lowered with by the ontology store's path and digest in its `RunRecord` (cut `language-ontology`); `profile::` revision documents arrive with follow-up `language-ontology-growth` | The ontology store is revised by commit; a run pins it and refuses drift; it likewise pins the speaker-state store (`RunRecord` keys 17 and 18, `Drift(SpeakerState)`, cut `language-ontology-scene`) | Profile authors and accepted rounds; never the lowerer's defaults (`persona-drives-register`) | +| Language ontology entry (cut `language-ontology`) | Key `onto::`, `n` from 1 per language; type `weksa.ontology_entry` in `data/ontology/ontology.cc`: the language, the inventory revision its conditions are read at, a layer (lexicon, grammar, discourse, phonology, orthography), at most four conditions (a feature id of slot `Stance`, `Discourse` or `Scene` with `AtLeast`/`AtMost` a grade or `Is` an option or flag; a `Scene` condition reads the relation of the item's speaker to its addressee that `with_scene` selected; slot `Speaker` and community ids wait on follow-up `language-ontology-communities`), a choice of 1 to 200 bytes, at most three examples of 1 to 120 bytes, and an `Annotator` | Admitted in all-or-nothing batches through `OntologyStore::admit`, immutable, never edited; retire arrives with `language-ontology-growth`. The run pins the store like the entity store (path and digest, `Drift(Ontology)`), never copies it, because no loop step writes it yet. Cut `language-ontology-seed` converts by drafting, not by parse: a fresh model drafts each language's seed from that language's YAML and the inventory's feature lines with no corpus text, then deletes `data/target-language-ontology/` and `.weksa/cultural-ontology/` in the same cut | Seed: a labelled model (`Annotator::Model`), no operator gate, never Test evidence (`ja-ontology-owner-answer`); attestation (operator, native reader) appends later. Accepted rounds later, through a mint call from Train items only. Selection is `ontology::select(ontology, language, view)`, called only inside `Prompt::lower`, so no caller picks entries; the prompt prints each selected entry's id, layer, choice and examples. Its text is minted text for the leak diagnostic, which today has no runtime caller (follow-up `leak-diagnostic-in-round`) | | Community (cut `language-ontology`, follow-up `language-ontology-communities`) | Key `community:`; type `weksa.community`, converted from `data/cultural-ontology/cultures/` and `referents/` (YAML deleted in the same cut) | Revised by commit; a speaker names the communities it belongs to by id | The cultural ontology's author (owner-attested evidence only; Discord-only content stays deleted, `discord-only-content-deleted`) | | Speaker (cut `speaker-scene`) | Key `speaker:@`; type `weksa.speaker`: stable axes as feature values of slot `Speaker` (origin, socioeconomic standing, age cohort, education and whatever the loop adds), at an inventory revision, and an `Annotator` | A new revision appends, never edits; a corpus item and every prior turn name a speaker slug, and a round records the speaker revisions it read | The annotator it names: `PersonaSnapshot` (a projection of a `gamecult.persona_state.v0` document, naming its source document and `updatedAt`), `Operator`, `WorkMetadata` (a public-domain work's own cast list and narration), or `Model { family, generator }` (the 2b `ModelFamily`) | -| Scene (cut `speaker-scene`) | Key `scene:@`, the item's split group; type `weksa.scene`: participants (speaker slugs) and, per ordered pair, relation features of slot `Scene` (relative status, intimacy, in-group, audience and whatever the loop adds), at an inventory revision, and an `Annotator` | As Speaker. Keyed by the group, so a scene never straddles the split | As Speaker | +| Scene (cut `speaker-scene`) | Key `scene:@`, the item's split group; type `weksa.scene`: participants (speaker slugs) and, per ordered pair, relation features of slot `Scene` (relative status, intimacy, in-group, audience and whatever the loop adds), at an inventory revision, and an `Annotator` | As Speaker. Keyed by the group, so a scene never straddles the split. `data/original/speaker-state.cc` holds Model-annotated keeper scenes, one per Train or Validation group of both languages (`weksa scene put|dump`); a Test group has none and reads `NoScene` | As Speaker; a model-annotated scene is never Test evidence | | Corpus item | Key `item::`, `n` canonical decimal >= 1 (no sign, no leading zero, from cut 2b); type `weksa.corpus_item` with text, language, speaker, split group, prior turns, source. Source `ModelWritten` carries a `ModelFamily` enum, the generator string as the fixture wrote it, and a prompt digest (cut 2b). The item carries no speaker state of its own: its speaker slug and group name the Speaker and Scene documents | Admitted once; the whole item is immutable (re-adding an identical item is a no-op, any difference is refused; a correction is a new item that `supersedes` the old); text already held under another key is refused unless the new item supersedes that key (cut 2b); withdrawn, never deleted, so old scores stay explainable | Importers and `weksa corpus add`, under `corpus-cast-plus-public-domain`; the source enum has no variant for Discord or any training-forbidden source (`corpus-clean`) | | Split assignment | Derived: `split(scheme, item.group)` | Fixed for a scheme; a new scheme is a new constant, never a reassignment. A model-written item whose group derives test is in no split; a superseding item keeps its predecessor's group | The hash function. Nobody assigns by hand, so there is no writer to forbid | | Loop round | Key `run: