with_scene reads the item's speaker and group scene from the store; V17 addressee names a referent

The view keeps its corpus item's speaker and group (LoweringInput::of takes
the item; admissible is gone), and with_scene takes the SpeakerStateStore, so
neither speaker nor scene comes from the caller and only admitted scenes
reach a view. An addressee that names a predication is refused as V17.
Pins scene numbering per group and the no-fallback case for a named
addressee outside the participants; tests/scene.rs fixture now speaks as the
item's speaker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Weksa 2026-11-10 02:51:35 +00:00
commit 71e6058b64
8 changed files with 350 additions and 254 deletions

View file

@ -21,7 +21,7 @@ use crate::inventory::{
};
use crate::packet::{EntityId, Packet};
use crate::speaker::{Annotator, MAX_PARTICIPANTS, Party, Scene, Speaker, scene_key, speaker_key};
use crate::validate::{LoweringInput, Refusal, admissible, feature_refusals};
use crate::validate::{LoweringInput, Refusal, feature_refusals, validate};
/// A broken store rule, named.
#[derive(Clone, Debug, PartialEq, Eq)]
@ -959,7 +959,7 @@ impl PacketStore {
corpus: &CorpusStore,
entities: &EntityStore,
) -> Result<LoweringInput, StoreError> {
let view = admissible(&packet, &inventory.inventory()?).map_err(StoreError::Invalid)?;
validate(&packet, &inventory.inventory()?).map_err(StoreError::Invalid)?;
let item = corpus.resolve(&packet.provenance.corpus_item)?;
if item.withdrawn {
return Err(StoreRefusal::WithdrawnCorpusItem {
@ -983,6 +983,7 @@ impl PacketStore {
.into());
}
}
let view = LoweringInput::of(&packet, &item);
let key = packet.id.to_string();
if let Some(existing) = self.get(&key)? {
if existing == packet {

View file

@ -1,13 +1,14 @@
//! The validator owns the inventory and form rules a packet must meet. Every
//! path that admits a packet applies them, but `validate` only judges: it
//! returns `Ok(())` or the refusals. [`LoweringInput`], the only thing a
//! lowerer sees, comes from `PacketStore::admit` alone, which builds it through
//! the crate-private `admissible`. The stance is checked like every feature
//! list, in slot `Stance`. The rules are V1..V8, V10..V12 and V14..V16: the
//! lowerer sees, comes from `PacketStore::admit` alone, which builds it from
//! the admitted packet and its corpus item through the crate-private
//! `LoweringInput::of`. The stance is checked like every feature
//! list, in slot `Stance`. The rules are V1..V8, V10..V12 and V14..V17: the
//! shape of an id or a grade is its type's parse, not a rule, so V9 is retired
//! and not renumbered; V13 is retired too. [`LoweringInput::with_scene`] takes
//! a [`Scene`](crate::speaker::Scene) document, and `feature_refusals` is the
//! one feature check it and the speaker-state store share.
//! and not renumbered; V13 is retired too. [`LoweringInput::with_scene`] reads the
//! scene of the view's own item group from the speaker-state store, and
//! `feature_refusals` is the one feature check it and that store share.
//!
//! `validate` owns form and capacity and makes no leak decision. A packet's one
//! free text is its trace (`notes` and `rejected_readings`): `validate` does not
@ -27,12 +28,13 @@
use std::collections::BTreeSet;
use std::fmt;
use crate::corpus::CorpusItem;
use crate::inventory::{Family, InvId, Inventory, InventoryEntry, Slot, ValueKind};
use crate::packet::{
Constraints, Context, Discourse, EntityId, Extension, FeatValue, FeatureValue, NodeId, Packet,
PacketKind, Predication, ProvenanceSource, Referent, Relation, SCHEMA_VERSION, Stance,
};
use crate::speaker::Scene;
use crate::store::{SpeakerStateStore, StoreError};
/// A broken rule, named.
#[derive(Clone, Debug, PartialEq, Eq)]
@ -110,8 +112,13 @@ pub enum Refusal {
V15ConsentSource {
source: ProvenanceSource,
},
/// V16: `with_scene` was given a speaker the scene does not list.
/// V16: `with_scene` found the item's speaker absent from its group's scene.
V16SpeakerNotInScene,
/// V17: an addressee that names a predication. An act is not someone
/// spoken to, so the addressee names a referent.
V17AddresseeNotAReferent {
id: NodeId,
},
}
impl Refusal {
@ -135,6 +142,7 @@ impl Refusal {
}
Refusal::V15ConsentSource { .. } => "V15",
Refusal::V16SpeakerNotInScene => "V16",
Refusal::V17AddresseeNotAReferent { .. } => "V17",
}
}
}
@ -161,6 +169,7 @@ impl fmt::Display for Refusal {
Refusal::V14ConsentNotAPredication { .. } => "consent names no predication",
Refusal::V15ConsentSource { .. } => "consent set by a source that only read wording",
Refusal::V16SpeakerNotInScene => "the speaker is not a participant of the scene",
Refusal::V17AddresseeNotAReferent { .. } => "the addressee names no referent",
};
write!(f, "{}: {what}", self.rule())
}
@ -180,28 +189,6 @@ impl fmt::Display for Refusal {
/// fn lower(p: &Packet, i: &Inventory) -> Result<LoweringInput, Vec<Refusal>> { weksa::validate(p, i) }
/// ```
pub fn validate(packet: &Packet, inventory: &Inventory) -> Result<(), Vec<Refusal>> {
admissible(packet, inventory).map(|_| ())
}
/// The one implementation of the rules. Crate-private: `PacketStore::admit` is
/// the only caller that keeps the view.
///
/// The first block is the same call through the public name, so the second
/// fails for the private path and nothing else.
///
/// ```
/// use weksa::{Inventory, packet::Packet};
/// fn judge(p: &Packet, i: &Inventory) { let _ = weksa::validate::validate(p, i); }
/// ```
///
/// ```compile_fail
/// use weksa::{Inventory, packet::Packet};
/// fn lower(p: &Packet, i: &Inventory) { let _ = weksa::validate::admissible(p, i); }
/// ```
pub(crate) fn admissible(
packet: &Packet,
inventory: &Inventory,
) -> Result<LoweringInput, Vec<Refusal>> {
let mut out = Vec::new();
if packet.schema_version != SCHEMA_VERSION {
out.push(Refusal::V1SchemaVersion {
@ -221,6 +208,7 @@ pub(crate) fn admissible(
}
let nodes = check_nodes(packet, &mut out);
check_refs(packet, &nodes, &mut out);
check_addressee(packet, &nodes, &mut out);
check_repeats(packet, &mut out);
check_consent(packet, &nodes, &mut out);
if inventory.has_revision(packet.inventory_rev) {
@ -235,11 +223,7 @@ pub(crate) fn admissible(
rev: packet.inventory_rev,
});
}
if out.is_empty() {
Ok(LoweringInput::of(packet))
} else {
Err(out)
}
if out.is_empty() { Ok(()) } else { Err(out) }
}
fn check_nodes(packet: &Packet, out: &mut Vec<Refusal>) -> BTreeSet<NodeId> {
@ -285,6 +269,17 @@ fn check_refs(packet: &Packet, nodes: &BTreeSet<NodeId>, out: &mut Vec<Refusal>)
}
}
/// V17: the addressee, when it names a node, names a referent. A dangling id
/// is V4's.
fn check_addressee(packet: &Packet, nodes: &BTreeSet<NodeId>, out: &mut Vec<Refusal>) {
if let Some(a) = &packet.discourse.addressee
&& nodes.contains(a)
&& !packet.referents.iter().any(|r| &r.id == a)
{
out.push(Refusal::V17AddresseeNotAReferent { id: a.clone() });
}
}
/// V14 and V15: the addressee's consent is a typed fact with one origin. A
/// dangling id is V4's, so V14 judges only a node that exists.
fn check_consent(packet: &Packet, nodes: &BTreeSet<NodeId>, out: &mut Vec<Refusal>) {
@ -560,11 +555,17 @@ fn fits(kind: Option<&ValueKind>, value: &FeatValue) -> bool {
/// fn read(l: weksa::LoweringInput) { let _ = l.scene; }
/// ```
///
/// Scene values come only from a `weksa.scene` document: the raw-values door
/// is gone. The first block is the same call with a document; the second hands
/// it feature values and fails for that alone.
/// Scene values come only from the store: the call names neither speaker nor
/// scene. The first block is the call with the store; the second hands it a
/// scene value and a speaker and fails for that alone.
///
/// ```
/// fn pick(l: weksa::LoweringInput, i: &weksa::Inventory, s: &weksa::SpeakerStateStore) {
/// let _ = l.with_scene(i, s);
/// }
/// ```
///
/// ```compile_fail
/// fn pick(
/// l: weksa::LoweringInput,
/// i: &weksa::Inventory,
@ -618,11 +619,16 @@ pub struct LoweringInput {
constraints: Constraints,
extensions: Vec<Extension>,
stance: Stance,
/// The item's speaker and group, as the corpus store holds them: the
/// only source of whose relation `with_scene` selects, and from which scene.
speaker: EntityId,
group: String,
scene: Vec<FeatureValue>,
}
impl LoweringInput {
fn of(p: &Packet) -> Self {
/// The view of an admitted packet and the corpus item it was minted for.
pub(crate) fn of(p: &Packet, item: &CorpusItem) -> Self {
Self {
inventory_rev: p.inventory_rev,
kind: p.kind,
@ -634,38 +640,44 @@ impl LoweringInput {
constraints: p.constraints.clone(),
extensions: p.extensions.clone(),
stance: p.stance.clone(),
speaker: item.speaker.clone(),
group: item.group.clone(),
scene: Vec::new(),
}
}
/// Adds the speaker's relation to the addressee, the only path for scene
/// values into a view; they come only from a `weksa.scene` document. The
/// speaker must be a participant of `scene` (V16). With no addressee, or
/// one that names no referent, nothing is selected; otherwise the relation
/// from the speaker to the addressee referent's entity (to `Unnamed` when
/// the referent has none) is checked like every feature list, in slot
/// `Scene` at this view's inventory revision, and replaces any earlier
/// scene. The English lowerer ignores it.
/// values into a view. The speaker is the item's speaker and the scene is
/// the latest the store holds for the item's group; the caller names
/// neither. No scene for the group selects nothing; a scene that does not
/// list the item's speaker is V16. With no addressee nothing is selected;
/// otherwise the relation from the speaker to the addressee referent's
/// entity (to `Unnamed` when the referent has none) is checked like every
/// feature list, in slot `Scene` at this view's inventory revision, and
/// replaces any earlier scene. The English lowerer ignores it.
pub fn with_scene(
mut self,
inventory: &Inventory,
scene: &Scene,
speaker: &EntityId,
) -> Result<Self, Vec<Refusal>> {
if !scene.participants.contains(speaker) {
return Err(vec![Refusal::V16SpeakerNotInScene]);
state: &SpeakerStateStore,
) -> Result<Self, StoreError> {
self.scene = Vec::new();
let Some(scene) = state.scene(&self.group)? else {
return Ok(self);
};
if !scene.participants.contains(&self.speaker) {
return Err(StoreError::Invalid(vec![Refusal::V16SpeakerNotInScene]));
}
let addressee = self
let selected = self
.discourse
.addressee
.as_ref()
.and_then(|id| self.referents.iter().find(|r| &r.id == id));
let selected = addressee
.map(|r| scene.relation(speaker, r.entity.as_ref()))
.unwrap_or_default();
.and_then(|a| self.referents.iter().find(|r| &r.id == a))
.map_or(&[][..], |r| {
scene.relation(&self.speaker, r.entity.as_ref())
});
let out = feature_refusals(inventory, self.inventory_rev, selected, Slot::Scene);
if !out.is_empty() {
return Err(out);
return Err(StoreError::Invalid(out));
}
self.scene = selected.to_vec();
Ok(self)

View file

@ -122,6 +122,8 @@ fn refusal_display_names_the_rule_and_no_identifier() {
Refusal::V15ConsentSource {
source: ProvenanceSource::ImportedCorpus,
},
Refusal::V16SpeakerNotInScene,
Refusal::V17AddresseeNotAReferent { id: node() },
];
for r in &all {
assert!(r.to_string().starts_with(r.rule()), "{r:?}");

View file

@ -1,244 +1,274 @@
//! The speaker's relation to the addressee as a lowering input: the relation of
//! a `weksa.scene` document from the speaker to the addressee referent's
//! entity, typed feature values of slot `Scene` checked against the inventory
//! at the view's revision, never wording.
//! The speaker's relation to the addressee as a lowering input. `with_scene`
//! names neither speaker nor scene: the view knows its corpus item, so the
//! speaker is the item's speaker and the scene is the store's latest for the
//! item's group. The relation is the one from that speaker to the addressee
//! referent's entity. Typed feature values only, never wording.
mod common;
use std::path::Path;
use common::{eid, grade, iv, lab, nd};
use common::{cast, eid, entities_in, grade, item_in, lab, nd};
use weksa::inventory::{proof_revision, seed, speaker_scene_revision};
use weksa::packet::{FeatValue, FeatureValue, Packet, proof_packet};
use weksa::speaker::{Annotator, PairRelation, Party, Scene};
use weksa::{
CorpusStore, EntityId, EntityStore, Inventory, InventoryStore, LoweringInput, PacketStore,
Refusal, lower,
CorpusStore, EntityStore, Inventory, InventoryStore, LoweringInput, NameSpan, PacketStore,
Refusal, SpeakerStateStore, StoreError, lower,
};
fn store() -> (InventoryStore, Inventory, tempfile::TempDir) {
struct W {
dir: tempfile::TempDir,
inventory: InventoryStore,
corpus: CorpusStore,
entities: EntityStore,
state: SpeakerStateStore,
}
/// Group `g` holds `item:nibu:1`: Nibu says "Brokkr, come here." Group `h`
/// holds `item:nibu:2`, also spoken by Nibu.
fn world() -> W {
let dir = tempfile::tempdir().unwrap();
let mut store = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
let mut inventory = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision()] {
store.admit_revision(rev, entries).unwrap();
inventory.admit_revision(rev, entries).unwrap();
}
let entities = entities_in(dir.path());
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
let mut first = item_in("item:nibu:1", "Brokkr, come here.", "g", cast());
first.names = vec![NameSpan {
entity: eid("brokkr"),
start: 0,
end: 6,
}];
corpus.add(first, &entities).unwrap();
corpus
.add(item_in("item:nibu:2", "Go away.", "h", cast()), &entities)
.unwrap();
let state = SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
W {
dir,
inventory,
corpus,
entities,
state,
}
let inv = store.inventory().unwrap();
(store, inv, dir)
}
fn admitted(packet: &Packet, inventory: &InventoryStore) -> LoweringInput {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let corpus = CorpusStore::open(&root.join("data/corpus/corpus.cc")).unwrap();
let entities = EntityStore::open(&root.join("data/entity/entity.cc")).unwrap();
let dir = tempfile::tempdir().unwrap();
PacketStore::open(&dir.path().join("p.cc"))
.unwrap()
.admit(packet.clone(), inventory, &corpus, &entities)
.unwrap()
fn inv(w: &W) -> Inventory {
w.inventory.inventory().unwrap()
}
/// The proof packet at `rev`. Its referent `n1` has no entity and `n3` is
/// `entity:nibu`; `addressee` names which one is spoken to, or none.
fn packet(rev: u32, addressee: Option<&str>) -> Packet {
let mut p = proof_packet();
p.inventory_rev = rev;
p.discourse.addressee = addressee.map(nd);
p
}
fn feat(inv: &Inventory, gloss: &str, value: FeatValue) -> FeatureValue {
let id = inv
.entries()
fn feat(gloss: &str, value: FeatValue) -> FeatureValue {
let feature = seed()
.1
.into_iter()
.chain(speaker_scene_revision().1)
.find(|e| e.gloss == gloss)
.unwrap_or_else(|| panic!("no feature {gloss}"))
.id;
FeatureValue { feature: id, value }
FeatureValue { feature, value }
}
fn rules(r: Result<LoweringInput, Vec<Refusal>>) -> Vec<&'static str> {
r.unwrap_err().iter().map(Refusal::rule).collect()
fn intimacy(v: u16) -> Vec<FeatureValue> {
vec![feat("intimacy", FeatValue::Grade(grade(v)))]
}
fn speaker() -> EntityId {
eid("brokkr")
fn status() -> Vec<FeatureValue> {
vec![
feat("relative_status", FeatValue::Option(lab("above"))),
feat("intimacy", FeatValue::Grade(grade(200))),
feat("in_group", FeatValue::Flag(false)),
]
}
/// Brokkr speaks; the scene holds a relation to Nibu and one to an unnamed
/// party, with different values.
fn scene(inv: &Inventory) -> Scene {
scene_with(vec![
PairRelation {
from: speaker(),
to: Party::Named(eid("nibu")),
features: vec![
feat(inv, "relative_status", FeatValue::Option(lab("above"))),
feat(inv, "intimacy", FeatValue::Grade(grade(200))),
feat(inv, "in_group", FeatValue::Flag(false)),
],
},
PairRelation {
from: speaker(),
to: Party::Unnamed,
features: vec![feat(inv, "intimacy", FeatValue::Grade(grade(7)))],
},
])
fn relation(from: &str, to: Party, features: Vec<FeatureValue>) -> PairRelation {
PairRelation {
from: eid(from),
to,
features,
}
}
fn scene_with(relations: Vec<PairRelation>) -> Scene {
/// Nibu's relations to Brokkr and to an unnamed party, and Brokkr's to Nibu.
fn scene(group: &str, n: u32, participants: &[&str], relations: Vec<PairRelation>) -> Scene {
Scene {
group: "g".into(),
n: 1,
group: group.into(),
n,
inventory_rev: 3,
participants: vec![speaker(), eid("nibu")],
participants: participants.iter().map(|p| eid(p)).collect(),
relations,
annotator: Annotator::Operator,
}
}
fn selected(view: LoweringInput, inv: &Inventory, s: &Scene) -> Vec<FeatureValue> {
view.with_scene(inv, s, &speaker())
fn standard(group: &str, n: u32) -> Scene {
scene(
group,
n,
&["nibu", "brokkr"],
vec![
relation("nibu", Party::Named(eid("brokkr")), status()),
relation("nibu", Party::Unnamed, intimacy(7)),
relation("brokkr", Party::Named(eid("nibu")), intimacy(99)),
],
)
}
fn put(w: &mut W, s: Scene) {
w.state
.put_scene(s, &w.inventory, &w.corpus, &w.entities)
.unwrap();
}
/// The line of `item:nibu:1` at `rev`, its addressee node `addressee` (`n1`
/// has no entity, `n3` is Brokkr), through the packet door.
fn view_of(w: &W, rev: u32, addressee: Option<&str>) -> LoweringInput {
let mut p: Packet = proof_packet();
p.inventory_rev = rev;
p.referents[2].entity = Some(eid("brokkr"));
p.discourse.addressee = addressee.map(nd);
// A packet key holds its packet for good, so each view gets a fresh store.
let scratch = tempfile::tempdir().unwrap();
PacketStore::open(&scratch.path().join("p.cc"))
.unwrap()
.scene()
.to_vec()
.admit(p, &w.inventory, &w.corpus, &w.entities)
.unwrap()
}
fn rules(r: Result<LoweringInput, StoreError>) -> Vec<&'static str> {
match r.map(|_| ()).unwrap_err() {
StoreError::Invalid(rs) => rs.iter().map(Refusal::rule).collect(),
other => panic!("not a rule refusal: {other}"),
}
}
#[test]
fn a_scene_relation_reaches_the_lowering_view_and_changes_no_english() {
let (store, inv, _dir) = store();
let plain = admitted(&packet(3, Some("n3")), &store);
let mut w = world();
put(&mut w, standard("g", 1));
let plain = view_of(&w, 3, Some("n3"));
assert!(plain.scene().is_empty());
let s = scene(&inv);
let with = plain.clone().with_scene(&inv, &s, &speaker()).unwrap();
assert_eq!(with.scene(), s.relations[0].features.as_slice());
assert!(!with.scene().is_empty());
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let entities = EntityStore::open(&root.join("data/entity/entity.cc")).unwrap();
let with = plain.clone().with_scene(&inv(&w), &w.state).unwrap();
assert_eq!(with.scene(), status().as_slice());
assert_eq!(
lower(&with, &inv, &entities).unwrap(),
lower(&plain, &inv, &entities).unwrap()
lower(&with, &inv(&w), &w.entities).unwrap(),
lower(&plain, &inv(&w), &w.entities).unwrap()
);
}
#[test]
fn with_scene_selects_by_addressee() {
let (store, inv, _dir) = store();
let s = scene(&inv);
// A referent with an entity selects the relation to that entity.
let named = selected(admitted(&packet(3, Some("n3")), &store), &inv, &s);
assert_eq!(named, s.relations[0].features);
// A referent without one selects the relation to an unnamed party.
let unnamed = selected(admitted(&packet(3, Some("n1")), &store), &inv, &s);
assert_eq!(unnamed, s.relations[1].features);
// No addressee selects nothing.
assert!(selected(admitted(&packet(3, None), &store), &inv, &s).is_empty());
// A named addressee the scene lacks selects nothing, though an unnamed
// relation exists.
let only_unnamed = scene_with(vec![s.relations[1].clone()]);
assert!(
selected(
admitted(&packet(3, Some("n3")), &store),
&inv,
&only_unnamed
)
.is_empty()
);
// Another speaker's relations are not selected.
let view = admitted(&packet(3, Some("n3")), &store);
let theirs = Scene {
participants: vec![speaker(), eid("nibu"), eid("hero")],
..s.clone()
let mut w = world();
put(&mut w, standard("g", 1));
let take = |w: &W, addressee| {
view_of(w, 3, addressee)
.with_scene(&inv(w), &w.state)
.unwrap()
.scene()
.to_vec()
};
assert!(
view.with_scene(&inv, &theirs, &eid("hero"))
.unwrap()
.scene()
.is_empty()
// A referent with an entity selects the relation to that entity; a
// referent without one, the relation to an unnamed party; and the
// speaker's relation, never Brokkr's to Nibu.
assert_eq!(take(&w, Some("n3")), status());
assert_eq!(take(&w, Some("n1")), intimacy(7));
// No addressee selects nothing.
assert!(take(&w, None).is_empty());
}
#[test]
fn a_named_addressee_the_scene_lacks_never_falls_back_to_unnamed() {
let mut w = world();
// Brokkr is not a participant and Nibu has only an unnamed relation.
put(
&mut w,
scene(
"g",
1,
&["nibu", "player"],
vec![relation("nibu", Party::Unnamed, intimacy(7))],
),
);
// A replacement replaces: an empty selection clears the earlier one.
let first = admitted(&packet(3, Some("n3")), &store)
.with_scene(&inv, &s, &speaker())
let got = view_of(&w, 3, Some("n3"))
.with_scene(&inv(&w), &w.state)
.unwrap();
assert!(
first
.with_scene(&inv, &only_unnamed, &speaker())
.unwrap()
.scene()
.is_empty()
assert!(got.scene().is_empty());
// A participant without a relation behaves the same.
put(
&mut w,
scene(
"g",
2,
&["nibu", "brokkr"],
vec![relation("nibu", Party::Unnamed, intimacy(7))],
),
);
let got = view_of(&w, 3, Some("n3"))
.with_scene(&inv(&w), &w.state)
.unwrap();
assert!(got.scene().is_empty());
}
#[test]
fn the_scene_is_the_items_group_and_its_latest_revision() {
let mut w = world();
// Group h holds a different relation for the same pair.
put(
&mut w,
scene(
"h",
1,
&["nibu", "brokkr"],
vec![relation("nibu", Party::Named(eid("brokkr")), intimacy(1))],
),
);
// No scene for the item's group selects nothing, whatever other groups hold.
let got = view_of(&w, 3, Some("n3"))
.with_scene(&inv(&w), &w.state)
.unwrap();
assert!(got.scene().is_empty());
// Revisions: the highest n is read.
put(&mut w, standard("g", 1));
let mut second = standard("g", 2);
second.relations[0].features = intimacy(5);
put(&mut w, second);
let got = view_of(&w, 3, Some("n3"))
.with_scene(&inv(&w), &w.state)
.unwrap();
assert_eq!(got.scene(), intimacy(5).as_slice());
// A replacement replaces: a store without the scene clears the selection.
let empty = SpeakerStateStore::open(&w.dir.path().join("empty.cc")).unwrap();
let cleared = got.with_scene(&inv(&w), &empty).unwrap();
assert!(cleared.scene().is_empty());
}
#[test]
fn with_scene_refusals() {
let (store, inv, _dir) = store();
let view = admitted(&packet(3, Some("n3")), &store);
let to_nibu = |features| {
scene_with(vec![PairRelation {
from: speaker(),
to: Party::Named(eid("nibu")),
features,
}])
};
let take = |s: &Scene| view.clone().with_scene(&inv, s, &speaker());
// A speaker the scene does not list.
let mut w = world();
put(&mut w, standard("g", 1));
// The scene was admitted at revision 3; a view of revision 2 predates the
// Scene features, so the selected relation's ids do not resolve there.
assert_eq!(
view.clone()
.with_scene(&inv, &scene(&inv), &eid("hero"))
.map(|_| ())
.unwrap_err(),
[Refusal::V16SpeakerNotInScene]
);
// A label the feature does not declare.
let lordly = feat(&inv, "relative_status", FeatValue::Option(lab("lordly")));
assert_eq!(rules(take(&to_nibu(vec![lordly]))), ["V7"]);
// A value of the wrong kind.
let flag = feat(&inv, "intimacy", FeatValue::Flag(true));
assert_eq!(rules(take(&to_nibu(vec![flag]))), ["V7"]);
// A stance feature in a relation.
let anger = feat(&inv, "anger", FeatValue::Grade(grade(1)));
assert_eq!(rules(take(&to_nibu(vec![anger]))), ["V8"]);
// A speaker feature in a relation.
let age = feat(&inv, "education", FeatValue::Grade(grade(1)));
assert_eq!(rules(take(&to_nibu(vec![age]))), ["V8"]);
// Twice in one list.
let twice = vec![
feat(&inv, "intimacy", FeatValue::Grade(grade(1))),
feat(&inv, "intimacy", FeatValue::Grade(grade(2))),
];
assert_eq!(rules(take(&to_nibu(twice))), ["V11"]);
// Revision 2 predates the Scene features, so their ids do not resolve there.
let old = admitted(&packet(2, Some("n3")), &store);
assert_eq!(
rules(old.with_scene(&inv, &scene(&inv), &speaker())),
rules(view_of(&w, 2, Some("n3")).with_scene(&inv(&w), &w.state)),
["V5", "V5", "V5"]
);
// An unselected relation is not checked: only the selected one is.
let bad_elsewhere = scene_with(vec![
PairRelation {
from: speaker(),
to: Party::Unnamed,
features: vec![feat(&inv, "anger", FeatValue::Grade(grade(1)))],
},
PairRelation {
from: speaker(),
to: Party::Named(eid("nibu")),
features: vec![],
},
]);
assert!(take(&bad_elsewhere).unwrap().scene().is_empty());
}
#[test]
fn feature_ids_are_stable() {
let (_store, inv, _dir) = store();
let ids: Vec<_> = [
"relative_status",
"intimacy",
"in_group",
"socioeconomic_standing",
"education",
"age_cohort",
]
.map(|g| feat(&inv, g, FeatValue::Flag(true)).feature)
.into();
let want: Vec<_> = (19..=24).map(|n| iv(&format!("feature:{n}"))).collect();
assert_eq!(ids, want);
// A scene that does not list the item's speaker: group k admitted while
// Brokkr was its only speaker, then an item of Nibu's joins it.
let mut item = item_in("item:brokkr:1", "Hello.", "k", cast());
item.speaker = eid("brokkr");
w.corpus.add(item, &w.entities).unwrap();
put(&mut w, scene("k", 1, &["brokkr"], vec![]));
w.corpus
.add(
item_in("item:nibu:3", "Hello there.", "k", cast()),
&w.entities,
)
.unwrap();
let mut p = proof_packet();
p.inventory_rev = 3;
p.provenance.corpus_item = weksa::CorpusItemId::parse("item:nibu:3").unwrap();
p.referents[2].entity = Some(eid("nibu"));
let view = PacketStore::open(&w.dir.path().join("p3.cc"))
.unwrap()
.admit(p, &w.inventory, &w.corpus, &w.entities)
.unwrap();
assert_eq!(rules(view.with_scene(&inv(&w), &w.state)), ["V16"]);
}

View file

@ -22,7 +22,7 @@ struct W {
}
/// Group `g` holds two live items (speakers nibu and brokkr) and one withdrawn
/// item (speaker hero).
/// item (speaker hero); group `g2` holds one live item of nibu's.
fn world() -> W {
let dir = tempfile::tempdir().unwrap();
let mut inventory = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
@ -35,9 +35,14 @@ fn world() -> W {
("item:nibu:1", "Come here.", "nibu"),
("item:nibu:2", "Go there.", "brokkr"),
("item:nibu:3", "Stay away.", "hero"),
("item:nibu:4", "Elsewhere.", "g2"),
] {
let mut item = item_in(key, text, "g", cast());
item.speaker = eid(speaker);
if key == "item:nibu:4" {
item.group = "g2".into();
item.speaker = eid("nibu");
}
corpus.add(item, &entities).unwrap();
}
corpus.withdraw("item:nibu:3").unwrap();
@ -219,6 +224,26 @@ fn scene_revisions_append() {
assert_eq!(w.state.scene("g").unwrap().unwrap().n, 10);
let listed: Vec<u32> = w.state.all_scenes().unwrap().iter().map(|s| s.n).collect();
assert_eq!(listed, (1..=10).collect::<Vec<_>>());
// Numbering is per group: the first scene of another group is revision 1
// whatever g holds, and its second is 2.
let other = |n| Scene {
group: "g2".into(),
participants: vec![eid("nibu")],
relations: vec![],
..scene(n, 1)
};
assert_eq!(
refused(put_scene(&mut w, other(2))),
not_next(&scene_key("g2", 2), 1, 2)
);
assert_eq!(put_scene(&mut w, other(1)).unwrap(), AddOutcome::Added);
assert_eq!(
refused(put_scene(&mut w, other(3))),
not_next(&scene_key("g2", 3), 2, 3)
);
assert_eq!(put_scene(&mut w, other(2)).unwrap(), AddOutcome::Added);
assert_eq!(w.state.scene("g2").unwrap().unwrap().n, 2);
assert_eq!(w.state.scene("g").unwrap().unwrap().n, 10);
}
#[test]

View file

@ -739,3 +739,26 @@ fn a_source_that_only_read_wording_cannot_set_consent() {
assert_eq!(refusals(&p), vec![Refusal::V15ConsentSource { source }]);
}
}
// V17: the addressee is someone spoken to, a referent.
#[test]
fn the_addressee_names_a_referent_not_a_predication() {
let mut p = good();
p.discourse.addressee = Some(nd("n2"));
assert_eq!(
refusals(&p),
vec![Refusal::V17AddresseeNotAReferent { id: nd("n2") }]
);
// A referent passes, and a dangling id is V4's alone.
p.discourse.addressee = Some(nd("n1"));
assert_eq!(refusals(&p), vec![]);
p.discourse.addressee = Some(nd("n99"));
assert_eq!(
refusals(&p),
vec![Refusal::V4DanglingRef {
id: nd("n99"),
at: "addressee"
}]
);
}

View file

@ -163,6 +163,7 @@ names the rule.
- V15: an `addressee_consent` is set only by provenance `Authored` or
`GameTelemetry`; a decomposition of text or imported corpus text cannot mint
it.
- V17: an `addressee` names a referent, not a predication.
V9 is retired and not renumbered: the form of a key or a grade is its type, and
an extension key's family is V6. `PacketStore::admit` returns the lowering view of a
@ -190,7 +191,7 @@ ids.
### `discourse`
Why the packet is said: `speech_act` is a speech-act id, `addressee` a node id,
Why the packet is said: `speech_act` is a speech-act id, `addressee` a referent's node id (V17),
and `features` carry source-side nuance on content (hedge, certainty, irony and
whatever the inventory grows). This is source-side communicative pressure, not
target-language register. `addressee_consent` is no feature: it names the
@ -226,11 +227,13 @@ latest plus one, and the latest revision is the highest `n`. Each carries an
`Annotator`, `Operator` or `Model` with an attestation string for its generator.
Both hold typed feature values only, never text. A feature of slot `Stance`,
`Speaker` or `Scene` sits in that slot alone (each layer has one writer and one
lifetime), which `admit_revision` enforces. `LoweringInput::with_scene` takes a
scene document and the speaker; the speaker must be a participant (V16), and
the relation selected is the speaker's to the entity of the addressee referent
(to `Unnamed` when that referent has no entity, to nothing when the packet has
no addressee). V13 is retired.
lifetime), which `admit_revision` enforces. `LoweringInput::with_scene` takes the
store and names neither speaker nor scene: the view knows its corpus item, so
the speaker is the item's speaker and the scene is the store's latest for the
item's group. The speaker must be a participant (V16), and the relation
selected is the speaker's to the entity of the addressee referent (to
`Unnamed` when that referent has no entity, to nothing when the packet has no
addressee or the scene holds no such relation). V13 is retired.
### `referents`

View file

@ -399,8 +399,8 @@ One line per cut; specs exist for the cuts about to run (2d and 4, siblings on `
2d. `entity-door-lows`: invisible format characters refused in entity forms (ZWJ, ZWNJ, CGJ and variation selectors kept); the form length bound per question `form-word-bound` (recommended: bytes only); attested origins (`Cast { persona, fixture }`, `Live { persona }`) and `CastAuthored.author`; empty provenance strings refused at the store; S6 under NFKC plus case fold and no-alphanumeric texts refused; `next_key` refuses at `u32::MAX`; CLI flags that do not apply refuse and no error echoes a value. Owns follow-ups `entity-door-lows` and `s6-unicode-normal-form`. (spec r1)
3b. `lowerer-first-cut` (follow-up `golf-loop-lowerer-cut`): the section above. `lower`, `weksa lower`, `weksa score`, `weksa packet proof`, inventory rev 2 for `nibu-proof-001`.
4. `speaker-state`: packet `stance` (felt affect and restraint, slot `Stance`, packet schema v4); formality, warmth and intensity out of the seed and the standard; only `PacketStore::admit` yields a `LoweringInput`, and it refuses packets for withdrawn items (follow-up `lowering-input-from-packet-store`). (spec r1)
4a. `speaker-relation-input`: slot `Scene` and its first seed features (`relative_status`, `intimacy`, `in_group`; inventory revision 3, now `speaker_scene_revision`); `LoweringInput::with_scene` carries the speaker's relation to the addressee as typed `Scene` feature values. Since 4b it takes a `weksa.scene` document and selects the relation by the addressee referent's entity (V16 when the speaker is not a participant; V13 is retired). The English lowerer does not render it. (PR for follow-up `chat-s3352-3352`)
4b. `speaker-scene` (spec r1; `speaker-scene-seeds` is its cut 4c: CLI, inventory revision 3, cast speakers and scenes; `Party::Unnamed` covers an addressee with no entity; Speaker and Scene share one `SpeakerStateStore`): slots `Speaker` and `Scene` with their seed features; `weksa.speaker` (`speaker:<entity-slug>@<n>`) and `weksa.scene` (`scene:<group>@<n>`, participants and ordered-pair relations) documents with `Annotator` `Operator` and `Model { family, generator }`, validated by the packet's shared feature check, append-only per key; their stores, `weksa speaker` and `weksa scene` commands, published schemas; Model-annotated cast speakers and scenes for the committed items. Waits on 2d and 4; `pd-speaker-annotation` blocks only the public-domain annotator. Part 1 landed (branch `weksa-lowering/speaker-scene`): `speaker.rs`, `SpeakerStateStore`, slots `Speaker` and `Scene` exclusive to their own feature lists, `speaker_scene_revision()` (Speaker features 22-24), `with_scene` on a Scene document, schemas. The CLI, the committed inventory revision 3 and the seeds stay with 4c.
4a. `speaker-relation-input`: slot `Scene` and its first seed features (`relative_status`, `intimacy`, `in_group`; inventory revision 3, now `speaker_scene_revision`); `LoweringInput::with_scene` carries the speaker's relation to the addressee as typed `Scene` feature values. Since 4b it takes the `SpeakerStateStore`, reads the scene of the view's own item group for the item's speaker, and selects the relation by the addressee referent's entity (V16 when the item's speaker is not a participant; V17 refuses an addressee that names a predication; V13 is retired). The English lowerer does not render it. (PR for follow-up `chat-s3352-3352`)
4b. `speaker-scene` (spec r1; `speaker-scene-seeds` is its cut 4c: CLI, inventory revision 3, cast speakers and scenes; `Party::Unnamed` covers an addressee with no entity; Speaker and Scene share one `SpeakerStateStore`): slots `Speaker` and `Scene` with their seed features; `weksa.speaker` (`speaker:<entity-slug>@<n>`) and `weksa.scene` (`scene:<group>@<n>`, participants and ordered-pair relations) documents with `Annotator` `Operator` and `Model { family, generator }`, validated by the packet's shared feature check, append-only per key; their stores, `weksa speaker` and `weksa scene` commands, published schemas; Model-annotated cast speakers and scenes for the committed items. Waits on 2d and 4; `pd-speaker-annotation` blocks only the public-domain annotator. Part 1 landed (branch `weksa-lowering/speaker-scene`): `speaker.rs`, `SpeakerStateStore`, slots `Speaker` and `Scene` exclusive to their own feature lists, `speaker_scene_revision()` (Speaker features 22-24), `with_scene` on the store, schemas. The CLI, the committed inventory revision 3 and the seeds stay with 4c.
5. `language-ontology`: `weksa.community` from `data/cultural-ontology/` (owns follow-up `edda-referent-yaml-parse`), `weksa.ontology_entry` for en-US and ja-JP from `data/target-language-ontology/` (YAML deleted), speaker communities, deterministic `select`, the lowering view (packet without trace, speaker, scene, selected entries). Waits on 4.
6. `pd-importer`: public-domain play and fiction dialogue into the corpus with speaker, scene group, edition provenance, and Speaker and Scene annotations by the ruled annotator. Waits on 4, follow-up `gutenberg-terms` and question `pd-speaker-annotation`.
7a. `loop-context-builder`: `context.rs` (`TrainItems`, `EncoderOffer`, `Prompt`: corpus text reaches a model call only through `Prompt::mint` over live Train items or `Prompt::encode` over one offered item; instructions are `&'static str`), `SplitScheme::live`, `CorpusItem::cited_entities` (one owner of the id set `PacketStore::admit` and the offer share), and checkpoint-only Test readings (`Checkpoint`, `TestReadings`; `Aggregate` and `leak_diagnostic` carry no Test). Library only. Merges follow-ups `loop-context-builder-2` and `scorer-test-readings-type`. (spec r1)