Compare commits
186 changed files with 8880 additions and 41176 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -10,7 +10,6 @@ state/scratch-runtime/
|
||||||
.weksa-runs/
|
.weksa-runs/
|
||||||
.weksa-smoke/
|
.weksa-smoke/
|
||||||
.weksa/*.cc
|
.weksa/*.cc
|
||||||
*.cc.lock
|
|
||||||
.weksa/*.json
|
.weksa/*.json
|
||||||
.weksa/*.log
|
.weksa/*.log
|
||||||
.weksa/*.pid
|
.weksa/*.pid
|
||||||
|
|
@ -21,4 +20,3 @@ dist/
|
||||||
build/
|
build/
|
||||||
.venv/
|
.venv/
|
||||||
venv/
|
venv/
|
||||||
target/
|
|
||||||
|
|
|
||||||
Binary file not shown.
27
.weksa/cultural-ontology/README.md
Normal file
27
.weksa/cultural-ontology/README.md
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
# Cultural Ontology CultCache Seeds
|
||||||
|
|
||||||
|
This directory stores Weksa cultural ontology as CultCache `.cc` witnesses.
|
||||||
|
|
||||||
|
## Starter Database
|
||||||
|
|
||||||
|
- `starter-targets.cc`
|
||||||
|
|
||||||
|
This store contains one catalog entry and three draft guarded profile entries:
|
||||||
|
|
||||||
|
- `weksa.cultural_ontology.pt-BR.vanilla_brazilian.v0`
|
||||||
|
- `weksa.cultural_ontology.en.transatlantic.v0`
|
||||||
|
- `weksa.cultural_ontology.ja-JP.kanto.contemporary.v0`
|
||||||
|
|
||||||
|
The catalog entry is:
|
||||||
|
|
||||||
|
- `weksa.cultural_ontology.catalog.seed_targets.v0`
|
||||||
|
|
||||||
|
The `.cc` file is the typed state witness. This README is only an inspection
|
||||||
|
guide; it does not own cultural ontology truth.
|
||||||
|
|
||||||
|
The profiles follow `schemas/cultural-ontology-profile.md`: salience axes and
|
||||||
|
linguistic affordances are nested typed state with feature IDs, activation
|
||||||
|
gates, constraints, indexicality, evidence, uncertainty, and trace labels.
|
||||||
|
|
||||||
|
Qdrant retrieval may later propose evidence bundles for these profiles. It does
|
||||||
|
not own accepted profile state.
|
||||||
BIN
.weksa/cultural-ontology/starter-targets.cc
Normal file
BIN
.weksa/cultural-ontology/starter-targets.cc
Normal file
Binary file not shown.
12
AGENTS.md
12
AGENTS.md
|
|
@ -46,18 +46,8 @@ The live state architecture is ported from EpiphanyAgent in reduced form:
|
||||||
- `state/map.yaml` is canonical and slow-changing.
|
- `state/map.yaml` is canonical and slow-changing.
|
||||||
- `state/scratch.md` is temporary and disposable.
|
- `state/scratch.md` is temporary and disposable.
|
||||||
- `schemas/` explains state contracts in human language.
|
- `schemas/` explains state contracts in human language.
|
||||||
- `crates/weksa` owns executable typed state.
|
- `packages/weksa-state-model` owns executable typed state.
|
||||||
|
|
||||||
Project truth does not belong in agent personality memory. If Weksa later grows
|
Project truth does not belong in agent personality memory. If Weksa later grows
|
||||||
role dossiers or heartbeat scheduling, those surfaces must remain separate from
|
role dossiers or heartbeat scheduling, those surfaces must remain separate from
|
||||||
language-project truth.
|
language-project truth.
|
||||||
|
|
||||||
## Building And Verifying
|
|
||||||
|
|
||||||
- `crates/weksa` depends on CultLib's `cultcache-rs` as a git dependency pinned by
|
|
||||||
`rev`, fetched from GitHub. With the default `CARGO_HOME` that fetch fails on a
|
|
||||||
Mind's host. Use the pre-fetched home:
|
|
||||||
`CARGO_HOME=/var/lib/mind-weksa-self/cargo-home cargo test --workspace`.
|
|
||||||
- `weksa packet proof <store>` admits the nibu proof packet under the key
|
|
||||||
`packet:6e6962752d303031` (hex of `nibu-001`), not `nibu-proof-001`. Use that key
|
|
||||||
with `weksa pronounce <store> <key>`.
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
Repository doctrine for this project lives in AGENTS.md, shared with other coding agents.
|
Repository doctrine for this project lives in AGENTS.md, shared with Codex.
|
||||||
|
|
||||||
@AGENTS.md
|
@AGENTS.md
|
||||||
|
|
|
||||||
1009
Cargo.lock
generated
1009
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,3 +0,0 @@
|
||||||
[workspace]
|
|
||||||
resolver = "3"
|
|
||||||
members = ["crates/weksa"]
|
|
||||||
76
README.md
76
README.md
|
|
@ -1,46 +1,12 @@
|
||||||
# Weksa
|
# Weksa
|
||||||
|
|
||||||
Weksa is a procedural language engine for alien grammars grounded in concept,
|
Weksa is a procedural language engine for alien grammars grounded in concept,
|
||||||
culture, and constraint, and the planned lowerer that turns an agent's
|
culture, and constraint.
|
||||||
meaning packet into the reader's display language.
|
|
||||||
|
|
||||||
**What is valuable here.** The interlingua standard and the lowering design: a
|
The project starts from a blunt rule: English words are not the source of truth.
|
||||||
meaning packet owns what is meant, the scene state (live: `weksa scene put|dump`, labelled by the rule in
|
Meaning is decomposed into an ontology, passed through a worldview, constrained
|
||||||
`docs/scene-annotation.md`; speaker documents are planned) owns the speaker's relation to the addressee, which selects register,
|
by grammar, shaped by phonology, distorted by history, and only then rendered as
|
||||||
address and politeness, and a lowerer owns surface text and leaves a trace.
|
surface text.
|
||||||
|
|
||||||
**The problem it solves.** An agent's outward speech today is one English
|
|
||||||
string the model chose, so meaning, register and voice are fused and nobody can
|
|
||||||
inspect or re-target it. Packets separate them, so the same meaning can be
|
|
||||||
lowered into English, other languages and conlangs, and the loss can be
|
|
||||||
measured.
|
|
||||||
|
|
||||||
**Entry points.**
|
|
||||||
|
|
||||||
- [Interlingua Standard](./docs/interlingua-standard.md): the packet contract.
|
|
||||||
- `crates/weksa`: the packet, inventory and corpus types, `validate`, the
|
|
||||||
derived split, the scorer (`score`: chrF, meaning cosine through an Ollama
|
|
||||||
embedder, whole output against whole reference with no mask, leak diagnostics) and the `weksa` CLI
|
|
||||||
(`weksa validate`, `corpus`, `entity`, `inventory`, `split`, `schema`);
|
|
||||||
published schemas in `schemas/cultnet/`.
|
|
||||||
- `data/corpus/corpus.cc`, `data/entity/entity.cc` and `data/interlingua/inventory.cc`: the English
|
|
||||||
corpus, its entities and the inventory, read with `weksa corpus dump`,
|
|
||||||
`weksa entity dump` and `weksa inventory dump`. `data/original/inventory.cc`
|
|
||||||
carries its own Validation-informed lexicon revisions (5 and 6) for lowering
|
|
||||||
measurements; scored runs use `data/interlingua`.
|
|
||||||
- [Lowering target](./docs/targets/interlingua-lowering.md) and
|
|
||||||
[its map](./docs/targets/interlingua-lowering-map.md): the design, scoring
|
|
||||||
and cut sequence.
|
|
||||||
- `data/`: the committed stores (corpora, entities, inventory, language ontology) and research data; there are no target-language profiles.
|
|
||||||
- `settings/`: setting-specific proving grounds for language projects.
|
|
||||||
|
|
||||||
**Live versus planned.** Live: docs, fixtures, examples, ontology data and the
|
|
||||||
packet crate `crates/weksa`, including `weksa pronounce` (the ruled IPA and phones
|
|
||||||
of the entities a packet cites), `weksa score`, and the golf loop's round and edit-accept
|
|
||||||
cycle (`weksa loop open|round|cycle`), which encodes and lowers through the
|
|
||||||
model (a prompted Claude subagent, per staged-distill).
|
|
||||||
Planned: Score and lowering documents and the other panel languages. No
|
|
||||||
daemon runs; the earlier Node daemon is parked at tag `parked/weksa-node-body`.
|
|
||||||
|
|
||||||
## Ownership Model
|
## Ownership Model
|
||||||
|
|
||||||
|
|
@ -74,10 +40,9 @@ for the LLM-free hot path.
|
||||||
See [Interlingua Standard](./docs/interlingua-standard.md) for the shared
|
See [Interlingua Standard](./docs/interlingua-standard.md) for the shared
|
||||||
meaning-packet contract Weksa clients should target.
|
meaning-packet contract Weksa clients should target.
|
||||||
|
|
||||||
See [Verse Service Contract](./docs/verse-service-contract.md) for the planned
|
See [Verse Service Contract](./docs/verse-service-contract.md) for the daemon
|
||||||
service contract: Weksa would own typed conversational intent, pronunciation
|
contract: Weksa owns typed conversational intent, pronunciation plans, utterance
|
||||||
plans, utterance handoffs, and the typed CultMesh state that makes those
|
handoffs, and the typed CultMesh state that makes those documents inspectable. Eve is deprecated and Thing 2 is its successor; the operator Eve surface is quarantined (see the contract).
|
||||||
documents inspectable. No daemon runs yet.
|
|
||||||
|
|
||||||
See [Multilingual Utterance Lowering](./docs/multilingual-utterance-lowering.md)
|
See [Multilingual Utterance Lowering](./docs/multilingual-utterance-lowering.md)
|
||||||
for the shared lowering target: interlingua projected through speaker state into
|
for the shared lowering target: interlingua projected through speaker state into
|
||||||
|
|
@ -85,17 +50,9 @@ English, Brazilian Portuguese, Japanese, and later target-language dialogue.
|
||||||
[Flavored English Lowering](./docs/flavored-english-lowering.md) remains the
|
[Flavored English Lowering](./docs/flavored-english-lowering.md) remains the
|
||||||
target-specific English receipt.
|
target-specific English receipt.
|
||||||
|
|
||||||
The language ontology is `data/ontology/ontology.cc` (read it with
|
See [Target-Language Cultural Ontology Profiles](./data/target-language-ontology/README.md)
|
||||||
`weksa ontology dump`): per language, the lexicon, grammar and discourse choices a lowerer
|
for the reviewable address, register, politeness, idiom, metaphor, and script
|
||||||
reads for a stance, a discourse and a scene relation. Only an entry with a Scene condition names an
|
distinctions that target lowerers must inspect before producing output.
|
||||||
address or politeness level; the relation, from `data/original/speaker-state.cc`, picks it. Its
|
|
||||||
en-US and ja-JP entries and the keeper scenes are model-drafted or model-annotated, never Test evidence. Nothing yet grows them from accepted
|
|
||||||
rounds; until that mint exists they change only by a new `weksa ontology admit`. ja-JP holds Scene entries `onto:ja-JP:10` to `:13`. It holds none for an above-status out-group
|
|
||||||
addressee, and none for an above-status in-group addressee below intimacy 700 (`:12` still selects
|
|
||||||
an in-group addressee at intimacy 700 or more, whatever the status). Two entries for the above-status
|
|
||||||
cases were withdrawn: a paired measure found they made the lowerer match the reference register less
|
|
||||||
often, and they stay out until a native reader attests them.
|
|
||||||
ja-JP `:5` (hedging), `:7` (affection) and `:8` (restrained sadness) carry certainty and restraint conditions, through `AtMostOrUnset` bounds (an unrated certainty or restraint does not defeat them), so the hedging, certainty, affection, restraint and sadness entries never co-select on the pairs `:5`/`:6`, `:4`/`:7`, `:6`/`:7` and `:6`/`:8`; ja-JP `:3` (anger) carries `AtMostOrUnset` hedge and affection bounds, as en-US `:3`, so `:3`/`:5` and `:3`/`:7` never co-select; the store has no retire, so that was a rebuild of `data/ontology/ontology.cc` with the ja-JP text unchanged. en-US `:3` (blunt anger) carries `AtMostOrUnset` hedge and affection bounds, and `:5` (hedging) and `:8` (affection) each an `AtMostOrUnset` certainty bound (as ja-JP `:7`), so `:3`/`:5`, `:3`/`:8`, `:5`/`:6` and `:6`/`:8` never co-select; `:5`'s certainty clause is that condition and no longer prose; `:6` and the Scene entry `:10` still co-select and are kept apart by scoping in the text. ja-JP `:9` (surprise) states its question ending as available, not prescribed, so `:6`/`:9`, `:5`/`:9` and `:3`/`:9` stay co-selectable and are reconciled by wording, not by condition.
|
|
||||||
|
|
||||||
For the first AquaSynth speech-training handoff, see
|
For the first AquaSynth speech-training handoff, see
|
||||||
[Tiny PanPhon v0.1 Speech Curriculum](./examples/speech-training/tiny-panphon-v0.1/README.md).
|
[Tiny PanPhon v0.1 Speech Curriculum](./examples/speech-training/tiny-panphon-v0.1/README.md).
|
||||||
|
|
@ -106,12 +63,11 @@ AquaSynth or expanding pronunciation coverage.
|
||||||
|
|
||||||
## Implementation Status
|
## Implementation Status
|
||||||
|
|
||||||
The persistent state spine is live: map, scratch, schemas, docs, examples and
|
The first committed artifact is the persistent state spine: map, scratch,
|
||||||
data. Packet types, validation and the corpus and inventory stores are live in
|
schemas, docs, examples, and a read-only provider advertisement fixture. The
|
||||||
`crates/weksa`, and so is the scoring library. Lowering and the service are planned (see the cut
|
daemon runtime still needs implementation, but its authority is no longer
|
||||||
sequence in [the lowering map](./docs/targets/interlingua-lowering-map.md)).
|
ambiguous: writing and agent state enter Weksa as intent pressure, and typed
|
||||||
Writing and agent state will enter Weksa as intent pressure, and typed utterance
|
utterance documents leave for AquaSynth.
|
||||||
documents will leave for AquaSynth.
|
|
||||||
|
|
||||||
[Eusocial Interbeing / Zyphos](./settings/eusocial-interbeing/README.md) is the
|
[Eusocial Interbeing / Zyphos](./settings/eusocial-interbeing/README.md) is the
|
||||||
current higher-priority setting target. [Rust to Dust](./settings/rust-to-dust/README.md)
|
current higher-priority setting target. [Rust to Dust](./settings/rust-to-dust/README.md)
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "weksa"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "weksa"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "weksa"
|
|
||||||
path = "src/main.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = "1"
|
|
||||||
caseless = "0.2"
|
|
||||||
clap = { version = "4", features = ["derive"] }
|
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "64b86e0a273a3936939357e9deb186b7bf3bc417", package = "cultcache-rs" }
|
|
||||||
schemars = "1"
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
serde_json = "1"
|
|
||||||
unicode-normalization = "0.1"
|
|
||||||
unicode-segmentation = "1"
|
|
||||||
ureq = { version = "3", default-features = false }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tempfile = "3"
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,14 +0,0 @@
|
||||||
//! Pins for private reach of `context.rs` that no run can produce.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// A corpus with no live Train item of the panel's languages holds an empty
|
|
||||||
/// train. (A run refuses a panel without Train items at open, so only the
|
|
||||||
/// builder shows it.)
|
|
||||||
#[test]
|
|
||||||
fn no_train_item_of_the_panel_is_an_empty_train() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
|
||||||
let train = TrainItems::from_corpus(&corpus, &["en-US".to_string()]).unwrap();
|
|
||||||
assert_eq!((train.len(), train.is_empty()), (0, true));
|
|
||||||
}
|
|
||||||
|
|
@ -1,179 +0,0 @@
|
||||||
//! The English target corpus. An item's text is immutable; a correction is a new
|
|
||||||
//! item that supersedes the old, and an item is withdrawn, never deleted. The
|
|
||||||
//! source enum has no variant for a source whose terms forbid training.
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::form::{FormError, is_slug, string_form};
|
|
||||||
use crate::packet::EntityId;
|
|
||||||
use crate::speaker::Annotator;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Turn {
|
|
||||||
pub speaker: EntityId,
|
|
||||||
pub text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Source {
|
|
||||||
/// A line from a cast member's hand-authored fixture, with the human who
|
|
||||||
/// wrote it. A fixture that records no author is `ModelWritten` with family
|
|
||||||
/// `Unrecorded`, never this (`corpus-labels-tell-truth`).
|
|
||||||
CastAuthored {
|
|
||||||
persona: String,
|
|
||||||
fixture: String,
|
|
||||||
author: String,
|
|
||||||
},
|
|
||||||
OperatorWritten,
|
|
||||||
OperatorApproved {
|
|
||||||
note: String,
|
|
||||||
},
|
|
||||||
/// A public-domain work, with everything a reader needs to check the claim:
|
|
||||||
/// the edition's licence and the jurisdiction the public-domain status is
|
|
||||||
/// asserted in, who translated it (the translation is the text's copyright,
|
|
||||||
/// not the original's) and when the work or translation first appeared. A work missing any
|
|
||||||
/// is refused at admission.
|
|
||||||
PublicDomain {
|
|
||||||
work: String,
|
|
||||||
author: String,
|
|
||||||
edition_url: String,
|
|
||||||
licence: String,
|
|
||||||
jurisdiction: String,
|
|
||||||
translator: String,
|
|
||||||
/// The year the work, or for a translation this translation, first
|
|
||||||
/// appeared. It is not the year of the `edition_url` file's source
|
|
||||||
/// print: Project Gutenberg's text may be a later or modernised
|
|
||||||
/// edition, and the claim rests on the date of first appearance.
|
|
||||||
edition_year: u16,
|
|
||||||
},
|
|
||||||
/// Labelled model output; never in the test split. The rule that it is
|
|
||||||
/// never judged by its own family binds model judges and the split; a
|
|
||||||
/// deterministic scorer refuses nothing, so the loop labels (the round
|
|
||||||
/// counts items of the answerer's family) and does not forbid.
|
|
||||||
/// `family` is `Unrecorded` when nothing records one. `generator` is the
|
|
||||||
/// string the fixture or run wrote, kept verbatim.
|
|
||||||
ModelWritten {
|
|
||||||
family: ModelFamily,
|
|
||||||
generator: Option<String>,
|
|
||||||
prompt_digest: Option<String>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The family of the model that wrote a line.
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum ModelFamily {
|
|
||||||
Anthropic,
|
|
||||||
OpenAi,
|
|
||||||
Google,
|
|
||||||
Alibaba,
|
|
||||||
Meta,
|
|
||||||
Mistral,
|
|
||||||
/// Nothing records which family wrote the line.
|
|
||||||
#[default]
|
|
||||||
Unrecorded,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Key: `item:<source-slug>:<n>`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.corpus_item")]
|
|
||||||
pub struct CorpusItem {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub text: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub language: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub speaker: EntityId,
|
|
||||||
/// The unit the split hashes: a scene, a fixture, a work.
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub group: String,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub prior_turns: Vec<Turn>,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub source: Source,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub admitted_on: String,
|
|
||||||
/// Key of the item this one corrects.
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub supersedes: Option<String>,
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub withdrawn: bool,
|
|
||||||
/// Which entities the text names, and where. Fixed with the text at intake.
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
pub names: Vec<NameSpan>,
|
|
||||||
/// Who placed `names`: the annotator of the intake that wrote them. `None`
|
|
||||||
/// when nothing records one (the cast seeds, `weksa corpus add`, the Dao De
|
|
||||||
/// Jing bed); it labels the spans, never the line or its speaker.
|
|
||||||
#[cultcache(key = 11, default)]
|
|
||||||
pub names_by: Option<Annotator>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CorpusItem {
|
|
||||||
/// The entities a packet for this item may cite (leak-owned-by-flow-and-scorer-3
|
|
||||||
/// (3)): the entities its text names, then its speaker, then its prior-turn
|
|
||||||
/// speakers (which may repeat). `PacketStore::admit` and `EncoderOffer` read
|
|
||||||
/// only this.
|
|
||||||
pub fn cited_entities(&self) -> impl Iterator<Item = &EntityId> {
|
|
||||||
self.names
|
|
||||||
.iter()
|
|
||||||
.map(|n| &n.entity)
|
|
||||||
.chain(std::iter::once(&self.speaker))
|
|
||||||
.chain(self.prior_turns.iter().map(|t| &t.speaker))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A byte range `[start, end)` of an item's text that names an entity. The
|
|
||||||
/// store admits it only when both ends sit on extended grapheme cluster
|
|
||||||
/// boundaries (UAX #29) of the NFC text and the range's bytes equal one of the
|
|
||||||
/// entity's forms in the item's language.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct NameSpan {
|
|
||||||
pub entity: EntityId,
|
|
||||||
pub start: u32,
|
|
||||||
pub end: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The key of a corpus item, `item:<slug>:<n>` as `key_slug` reads it. A packet
|
|
||||||
/// names the item it was minted for by this type, so the key cannot be free text.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct CorpusItemId(String);
|
|
||||||
|
|
||||||
impl CorpusItemId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
key_slug(s)
|
|
||||||
.map(|_| Self(s.to_string()))
|
|
||||||
.ok_or_else(|| FormError::new("CorpusItemId", s))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for CorpusItemId {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(CorpusItemId, { "type": "string", "pattern": "^item:[a-z0-9]([a-z0-9-]{0,46}[a-z0-9])?:[1-9][0-9]*$" });
|
|
||||||
|
|
||||||
/// `item:<slug>:<n>`.
|
|
||||||
pub fn item_key(slug: &str, n: u32) -> String {
|
|
||||||
format!("item:{slug}:{n}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The slug of an item key, if it is canonical `item:<slug>:<n>`: a slug of
|
|
||||||
/// `[a-z0-9]` and inner `-` (at most 48 bytes, no edge `-`), and `n` a decimal
|
|
||||||
/// of at least 1 without sign or leading zero that fits `u32`.
|
|
||||||
pub fn key_slug(key: &str) -> Option<&str> {
|
|
||||||
let rest = key.strip_prefix("item:")?;
|
|
||||||
let (slug, n) = rest.rsplit_once(':')?;
|
|
||||||
let canonical_n =
|
|
||||||
n.bytes().all(|b| b.is_ascii_digit()) && !n.starts_with('0') && n.parse::<u32>().is_ok();
|
|
||||||
(canonical_n && is_slug(slug)).then_some(slug)
|
|
||||||
}
|
|
||||||
|
|
@ -1,328 +0,0 @@
|
||||||
//! The Dao De Jing test bed: inventory revision 3 of the `data/daodejing`
|
|
||||||
//! stores and the packets for the slice of James Legge's chapters in its corpus.
|
|
||||||
//! It follows `proof_packet`'s precedent: a hand-authored packet the stores
|
|
||||||
//! admit through the same doors as any other.
|
|
||||||
//!
|
|
||||||
//! The ids carry the leak labels the golf loop needs. A frame minted while
|
|
||||||
//! reading a Train chapter is generic evidence; one minted for a Validation or
|
|
||||||
//! Test chapter was written with that chapter's reference in view, so a score
|
|
||||||
//! on it measures the lowerer table's reach and not the interlingua's.
|
|
||||||
|
|
||||||
use std::num::NonZeroU32;
|
|
||||||
|
|
||||||
use crate::corpus::CorpusItemId;
|
|
||||||
use crate::inventory::{Change, Family, InvId, InventoryEntry, InventoryRevision};
|
|
||||||
use crate::packet::{
|
|
||||||
Constraints, Context, Discourse, EncoderId, FeatValue, FeatureValue, Grade, NodeId, Packet,
|
|
||||||
PacketId, PacketKind, Predication, Provenance, ProvenanceSource, Referent, RoleFill,
|
|
||||||
SCHEMA_VERSION, Stance, Trace,
|
|
||||||
};
|
|
||||||
|
|
||||||
const CONCEPTS: &[&str] = &[
|
|
||||||
"sage",
|
|
||||||
"mind",
|
|
||||||
"belly",
|
|
||||||
"will",
|
|
||||||
"bone",
|
|
||||||
"empty",
|
|
||||||
"fill",
|
|
||||||
"weaken",
|
|
||||||
"strengthen",
|
|
||||||
"heaven",
|
|
||||||
"earth",
|
|
||||||
"is_long_enduring",
|
|
||||||
"continues_long",
|
|
||||||
"highest_excellence",
|
|
||||||
"water",
|
|
||||||
"true_words",
|
|
||||||
"seem_paradoxical",
|
|
||||||
"space_between_heaven_and_earth",
|
|
||||||
"bellows",
|
|
||||||
"compare",
|
|
||||||
"resemble",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Frame glosses, from `frame:4`. 4 is minted from a Train chapter, 5 and 6
|
|
||||||
/// from Validation chapters, 7 and 8 from Test chapters.
|
|
||||||
const FRAMES: &[&str] = &[
|
|
||||||
"act",
|
|
||||||
"intransitive",
|
|
||||||
"likeness",
|
|
||||||
"seems_paradoxical",
|
|
||||||
"may_be_compared",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Revision 3 of the Dao De Jing stores, after the seed and the proof revision.
|
|
||||||
pub fn revision() -> (InventoryRevision, Vec<InventoryEntry>) {
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
for (family, glosses) in [(Family::Concept, CONCEPTS), (Family::Frame, FRAMES)] {
|
|
||||||
let first = if family == Family::Concept { 7 } else { 4 };
|
|
||||||
for (i, gloss) in glosses.iter().enumerate() {
|
|
||||||
entries.push(InventoryEntry {
|
|
||||||
id: family.id(NonZeroU32::new(first + i as u32).expect("nonzero")),
|
|
||||||
gloss: (*gloss).to_string(),
|
|
||||||
value_kind: None,
|
|
||||||
applies_to: vec![],
|
|
||||||
introduced_rev: 3,
|
|
||||||
retired_rev: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
(
|
|
||||||
InventoryRevision {
|
|
||||||
n: 3,
|
|
||||||
parent: Some(2),
|
|
||||||
changes,
|
|
||||||
frozen: false,
|
|
||||||
},
|
|
||||||
entries,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn concept(gloss: &str) -> &'static str {
|
|
||||||
let at = CONCEPTS
|
|
||||||
.iter()
|
|
||||||
.position(|c| *c == gloss)
|
|
||||||
.expect("known concept");
|
|
||||||
Box::leak(format!("concept:{}", 7 + at).into_boxed_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn frame(gloss: &str) -> &'static str {
|
|
||||||
let at = FRAMES
|
|
||||||
.iter()
|
|
||||||
.position(|c| *c == gloss)
|
|
||||||
.expect("known frame");
|
|
||||||
Box::leak(format!("frame:{}", 4 + at).into_boxed_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hex8(ascii: &str) -> String {
|
|
||||||
assert_eq!(ascii.len(), 8);
|
|
||||||
ascii.bytes().map(|b| format!("{b:02x}")).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `(node, concept gloss, frame gloss, [(role id, filler node)])`.
|
|
||||||
type PredicationSpec = (
|
|
||||||
&'static str,
|
|
||||||
&'static str,
|
|
||||||
&'static str,
|
|
||||||
&'static [(&'static str, &'static str)],
|
|
||||||
);
|
|
||||||
|
|
||||||
struct Spec {
|
|
||||||
/// Eight ASCII characters; the packet id is their hex.
|
|
||||||
id: &'static str,
|
|
||||||
item: &'static str,
|
|
||||||
speech_act: &'static str,
|
|
||||||
/// `(node, referent kind id, concept gloss)`.
|
|
||||||
referents: &'static [(&'static str, &'static str, &'static str)],
|
|
||||||
predications: &'static [PredicationSpec],
|
|
||||||
/// The author's reading of the speaker's felt state: `(feature gloss, permille)`.
|
|
||||||
stance: &'static [(&'static str, u16)],
|
|
||||||
note: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
const AGENT: &str = "role:1";
|
|
||||||
const PATIENT: &str = "role:2";
|
|
||||||
const EXPERIENCER: &str = "role:3";
|
|
||||||
const GOAL: &str = "role:6";
|
|
||||||
const PERSON: &str = "referent_kind:1";
|
|
||||||
const ORGANISM: &str = "referent_kind:3";
|
|
||||||
const PLACE: &str = "referent_kind:4";
|
|
||||||
const ABSTRACT: &str = "referent_kind:11";
|
|
||||||
|
|
||||||
/// Feature ids of the seed: restraint is the tenth stance feature.
|
|
||||||
fn stance_feature(gloss: &str) -> InvId {
|
|
||||||
let n = [
|
|
||||||
"anger",
|
|
||||||
"fear",
|
|
||||||
"sadness",
|
|
||||||
"joy",
|
|
||||||
"disgust",
|
|
||||||
"surprise",
|
|
||||||
"contempt",
|
|
||||||
"affection",
|
|
||||||
"shame",
|
|
||||||
"restraint",
|
|
||||||
]
|
|
||||||
.iter()
|
|
||||||
.position(|g| *g == gloss)
|
|
||||||
.expect("stance feature");
|
|
||||||
// Features before the stance block: polarity, tense, aspect, modality,
|
|
||||||
// evidentiality, hedge, certainty, irony.
|
|
||||||
InvId::parse(&format!("feature:{}", 9 + n)).expect("feature id")
|
|
||||||
}
|
|
||||||
|
|
||||||
const SPECS: &[Spec] = &[
|
|
||||||
// Chapter 3 section 2. Train.
|
|
||||||
Spec {
|
|
||||||
id: "dao-0302",
|
|
||||||
item: "item:daodejing:1",
|
|
||||||
speech_act: "speech_act:1",
|
|
||||||
referents: &[
|
|
||||||
("n1", PERSON, "sage"),
|
|
||||||
("n2", ABSTRACT, "mind"),
|
|
||||||
("n3", ORGANISM, "belly"),
|
|
||||||
("n4", ABSTRACT, "will"),
|
|
||||||
("n5", ORGANISM, "bone"),
|
|
||||||
],
|
|
||||||
predications: &[
|
|
||||||
("n6", "empty", "act", &[(AGENT, "n1"), (PATIENT, "n2")]),
|
|
||||||
("n7", "fill", "act", &[(AGENT, "n1"), (PATIENT, "n3")]),
|
|
||||||
("n8", "weaken", "act", &[(AGENT, "n1"), (PATIENT, "n4")]),
|
|
||||||
("n9", "strengthen", "act", &[(AGENT, "n1"), (PATIENT, "n5")]),
|
|
||||||
],
|
|
||||||
stance: &[("restraint", 800)],
|
|
||||||
note: "Four acts of one agent; 'in the exercise of his government' and 'their' are not carried.",
|
|
||||||
},
|
|
||||||
// Chapter 7 section 1, first sentence. Validation.
|
|
||||||
Spec {
|
|
||||||
id: "dao-0701",
|
|
||||||
item: "item:daodejing:2",
|
|
||||||
speech_act: "speech_act:1",
|
|
||||||
referents: &[("n1", PLACE, "heaven"), ("n2", PLACE, "earth")],
|
|
||||||
predications: &[
|
|
||||||
(
|
|
||||||
"n3",
|
|
||||||
"is_long_enduring",
|
|
||||||
"intransitive",
|
|
||||||
&[(EXPERIENCER, "n1")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"n4",
|
|
||||||
"continues_long",
|
|
||||||
"intransitive",
|
|
||||||
&[(EXPERIENCER, "n2")],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
stance: &[("restraint", 800)],
|
|
||||||
note: "Heaven and earth as places; whether they are entities is a ruling the ontology owes.",
|
|
||||||
},
|
|
||||||
// Chapter 8 section 1, first sentence. Validation.
|
|
||||||
Spec {
|
|
||||||
id: "dao-0801",
|
|
||||||
item: "item:daodejing:3",
|
|
||||||
speech_act: "speech_act:1",
|
|
||||||
referents: &[
|
|
||||||
("n1", ABSTRACT, "highest_excellence"),
|
|
||||||
("n2", ABSTRACT, "water"),
|
|
||||||
],
|
|
||||||
predications: &[(
|
|
||||||
"n3",
|
|
||||||
"resemble",
|
|
||||||
"likeness",
|
|
||||||
&[(EXPERIENCER, "n1"), (GOAL, "n2")],
|
|
||||||
)],
|
|
||||||
stance: &[("restraint", 800), ("affection", 300)],
|
|
||||||
note: "The metaphor is a plain likeness predication; the tenor and vehicle are not marked.",
|
|
||||||
},
|
|
||||||
// Chapter 78 section 4. Test.
|
|
||||||
Spec {
|
|
||||||
id: "dao-7804",
|
|
||||||
item: "item:daodejing:4",
|
|
||||||
speech_act: "speech_act:1",
|
|
||||||
referents: &[("n1", ABSTRACT, "true_words")],
|
|
||||||
predications: &[(
|
|
||||||
"n2",
|
|
||||||
"seem_paradoxical",
|
|
||||||
"seems_paradoxical",
|
|
||||||
&[(EXPERIENCER, "n1")],
|
|
||||||
)],
|
|
||||||
stance: &[("restraint", 800)],
|
|
||||||
note: "The whole paradox is in the referent's concept and the frame; the packet holds no more than the surface does.",
|
|
||||||
},
|
|
||||||
// Chapter 5 section 2, first sentence. Test.
|
|
||||||
Spec {
|
|
||||||
id: "dao-0502",
|
|
||||||
item: "item:daodejing:5",
|
|
||||||
speech_act: "speech_act:2",
|
|
||||||
referents: &[
|
|
||||||
("n1", PLACE, "space_between_heaven_and_earth"),
|
|
||||||
("n2", ARTIFACT, "bellows"),
|
|
||||||
],
|
|
||||||
predications: &[(
|
|
||||||
"n3",
|
|
||||||
"compare",
|
|
||||||
"may_be_compared",
|
|
||||||
&[(EXPERIENCER, "n1"), (GOAL, "n2")],
|
|
||||||
)],
|
|
||||||
stance: &[("restraint", 800)],
|
|
||||||
note: "A rhetorical question; the speech act is ask and the negated 'may not' is dropped.",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const ARTIFACT: &str = "referent_kind:5";
|
|
||||||
|
|
||||||
/// The packets of the slice, each minted for its corpus item.
|
|
||||||
pub fn packets() -> Vec<Packet> {
|
|
||||||
SPECS.iter().map(build).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build(spec: &Spec) -> Packet {
|
|
||||||
let id = |s: &str| InvId::parse(s).expect("ids are well formed");
|
|
||||||
let node = |s: &str| NodeId::parse(s).expect("nodes are well formed");
|
|
||||||
Packet {
|
|
||||||
id: PacketId::parse(&format!("packet:{}", hex8(spec.id))).expect("packet id"),
|
|
||||||
schema_version: SCHEMA_VERSION,
|
|
||||||
inventory_rev: 3,
|
|
||||||
kind: PacketKind::CorpusExample,
|
|
||||||
provenance: Provenance {
|
|
||||||
source: ProvenanceSource::Authored,
|
|
||||||
corpus_item: CorpusItemId::parse(spec.item).expect("item key"),
|
|
||||||
encoder: EncoderId::parse(&format!("encoder:{}", hex8("claude-s"))).expect("encoder"),
|
|
||||||
confidence: Grade::new(600).expect("grade"),
|
|
||||||
},
|
|
||||||
context: Context::default(),
|
|
||||||
discourse: Discourse {
|
|
||||||
speech_act: Some(id(spec.speech_act)),
|
|
||||||
addressee: None,
|
|
||||||
addressee_consent: None,
|
|
||||||
features: vec![],
|
|
||||||
},
|
|
||||||
referents: spec
|
|
||||||
.referents
|
|
||||||
.iter()
|
|
||||||
.map(|(n, kind, gloss)| Referent {
|
|
||||||
id: node(n),
|
|
||||||
kind: id(kind),
|
|
||||||
concept: id(concept(gloss)),
|
|
||||||
entity: None,
|
|
||||||
features: vec![],
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
predications: spec
|
|
||||||
.predications
|
|
||||||
.iter()
|
|
||||||
.map(|(n, c, f, roles)| Predication {
|
|
||||||
id: node(n),
|
|
||||||
concept: id(concept(c)),
|
|
||||||
frame: id(frame(f)),
|
|
||||||
roles: roles
|
|
||||||
.iter()
|
|
||||||
.map(|(role, filler)| RoleFill {
|
|
||||||
role: id(role),
|
|
||||||
filler: node(filler),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
features: vec![],
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
relations: vec![],
|
|
||||||
constraints: Constraints::default(),
|
|
||||||
extensions: vec![],
|
|
||||||
trace: Trace {
|
|
||||||
notes: vec![spec.note.to_string()],
|
|
||||||
rejected_readings: vec![],
|
|
||||||
},
|
|
||||||
stance: Stance {
|
|
||||||
features: spec
|
|
||||||
.stance
|
|
||||||
.iter()
|
|
||||||
.map(|(g, v)| FeatureValue {
|
|
||||||
feature: stance_feature(g),
|
|
||||||
value: FeatValue::Grade(Grade::new(*v).expect("grade")),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,13 +0,0 @@
|
||||||
//! Pins for `unmark` that the import door only reaches through a whole work.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// A form that opens another markup is malformed, though its entity id is
|
|
||||||
/// sound: the model wrote a nested or unclosed mark, not a name.
|
|
||||||
#[test]
|
|
||||||
fn a_form_that_opens_a_mark_is_malformed() {
|
|
||||||
assert_eq!(unmark("[[entity:orsa|Or[[sa]] came"), None);
|
|
||||||
// The same line without the nested opener unmarks.
|
|
||||||
let (plain, names) = unmark("[[entity:orsa|Orsa]] came").unwrap();
|
|
||||||
assert_eq!((plain.as_str(), names.len()), ("Orsa came", 1));
|
|
||||||
}
|
|
||||||
|
|
@ -1,84 +0,0 @@
|
||||||
//! The entity store's documents. An entity is a named thing a packet may cite by
|
|
||||||
//! id. Its forms per language are data, citation form first, then inflected or
|
|
||||||
//! particle-bound forms; no rule here reads what a form means, only its shape.
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::packet::EntityId;
|
|
||||||
|
|
||||||
/// An entity's forms in one language, as the corpus item language tag spells it.
|
|
||||||
/// The citation form comes first.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct LanguageForms {
|
|
||||||
pub language: String,
|
|
||||||
/// 1 to 64 bytes each, no control or invisible format character, no edge
|
|
||||||
/// whitespace, none repeated.
|
|
||||||
pub forms: Vec<String>,
|
|
||||||
/// How the citation form (`forms[0]`) is said, when someone with the
|
|
||||||
/// authority to rule on it has. Absent means unruled, never "spelled as
|
|
||||||
/// read".
|
|
||||||
#[serde(default)]
|
|
||||||
pub pronunciation: Option<Pronunciation>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A ruled pronunciation of an entity's citation form in one language.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Pronunciation {
|
|
||||||
/// Broad IPA with stress marks, bare: no enclosing `/` or `[ ]`. 1 to 64
|
|
||||||
/// bytes, NFC.
|
|
||||||
pub ipa: String,
|
|
||||||
/// Who ruled: the entity itself, a writer, an operator.
|
|
||||||
pub ruled_by: String,
|
|
||||||
/// `YYYY-MM-DD`.
|
|
||||||
pub date: String,
|
|
||||||
/// Where the ruling was made: a room, a document, a run.
|
|
||||||
pub source: String,
|
|
||||||
/// Pronunciations that were considered and refused, same shape as `ipa`.
|
|
||||||
/// Kept so nobody re-proposes one; never emitted.
|
|
||||||
#[serde(default)]
|
|
||||||
pub rejected: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where an entity was minted.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum EntityOrigin {
|
|
||||||
/// From a cast member's fixture: the persona and the fixture path the
|
|
||||||
/// entity came from.
|
|
||||||
Cast { persona: String, fixture: String },
|
|
||||||
/// From a public-domain work.
|
|
||||||
PublicDomain { work: String },
|
|
||||||
/// Minted live by the named persona before it names the entity.
|
|
||||||
Live { persona: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Key: the entity id. Forms only grow: see `EntityStore::put`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.entity")]
|
|
||||||
pub struct Entity {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: EntityId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub forms: Vec<LanguageForms>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub origin: EntityOrigin,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Entity {
|
|
||||||
/// The forms stored for `language`, if any.
|
|
||||||
pub fn forms_in(&self, language: &str) -> Option<&[String]> {
|
|
||||||
self.forms
|
|
||||||
.iter()
|
|
||||||
.find(|f| f.language == language)
|
|
||||||
.map(|f| f.forms.as_slice())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ruled pronunciation of the citation form in `language`, if any.
|
|
||||||
pub fn pronunciation_in(&self, language: &str) -> Option<&Pronunciation> {
|
|
||||||
self.forms
|
|
||||||
.iter()
|
|
||||||
.find(|f| f.language == language)
|
|
||||||
.and_then(|f| f.pronunciation.as_ref())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,301 +0,0 @@
|
||||||
//! Form types. A form lives in a newtype whose only constructor is a fallible
|
|
||||||
//! `parse`; deserializing goes through the same parse, so a malformed value can
|
|
||||||
//! neither be built in Rust nor read back from a store.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
/// A value that is not of the form its type names.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct FormError {
|
|
||||||
pub form: &'static str,
|
|
||||||
pub got: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FormError {
|
|
||||||
pub fn new(form: &'static str, got: impl fmt::Display) -> Self {
|
|
||||||
Self {
|
|
||||||
form,
|
|
||||||
got: got.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for FormError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
// `got` stays a field for callers; the text does not echo it, because
|
|
||||||
// the value is often an identifier the caller supplied.
|
|
||||||
write!(f, "not a {}", self.form)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for FormError {}
|
|
||||||
|
|
||||||
/// Wires a string form type (with `parse` and `Display`) to FromStr, serde's
|
|
||||||
/// `try_from`/`into` String and a published schema.
|
|
||||||
macro_rules! string_form {
|
|
||||||
($t:ident, $schema:tt) => {
|
|
||||||
impl std::str::FromStr for $t {
|
|
||||||
type Err = $crate::form::FormError;
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
||||||
Self::parse(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl TryFrom<String> for $t {
|
|
||||||
type Error = $crate::form::FormError;
|
|
||||||
fn try_from(s: String) -> Result<Self, Self::Error> {
|
|
||||||
Self::parse(&s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<$t> for String {
|
|
||||||
fn from(v: $t) -> String {
|
|
||||||
v.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl schemars::JsonSchema for $t {
|
|
||||||
fn schema_name() -> std::borrow::Cow<'static, str> {
|
|
||||||
stringify!($t).into()
|
|
||||||
}
|
|
||||||
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
|
||||||
schemars::json_schema!($schema)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
pub(crate) use string_form;
|
|
||||||
|
|
||||||
/// A real calendar date written `YYYY-MM-DD`: four ASCII digits, a month 1 to
|
|
||||||
/// 12 and a day that month has in that year (leap years by the Gregorian rule).
|
|
||||||
pub fn is_calendar_date(s: &str) -> bool {
|
|
||||||
let b = s.as_bytes();
|
|
||||||
if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let digits = |r: std::ops::Range<usize>| {
|
|
||||||
b[r.clone()]
|
|
||||||
.iter()
|
|
||||||
.all(u8::is_ascii_digit)
|
|
||||||
.then(|| s[r].parse::<u32>().ok())
|
|
||||||
.flatten()
|
|
||||||
};
|
|
||||||
let (Some(year), Some(month), Some(day)) = (digits(0..4), digits(5..7), digits(8..10)) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
|
|
||||||
let days = match month {
|
|
||||||
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
|
||||||
4 | 6 | 9 | 11 => 30,
|
|
||||||
2 if leap => 29,
|
|
||||||
2 => 28,
|
|
||||||
_ => return false,
|
|
||||||
};
|
|
||||||
(1..=days).contains(&day)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A BCP 47 language tag in its canonical case (RFC 5646 section 2.1.1): 1 to 35
|
|
||||||
/// bytes of ASCII alphanumerics in hyphen-separated subtags of 1 to 8 bytes; the
|
|
||||||
/// first is 2 to 8 letters, or the single letter `x` of a private-use tag. The
|
|
||||||
/// language subtag is lowercase, a four-letter script subtag is Titlecase, a
|
|
||||||
/// two-letter region subtag is UPPERCASE, and every other subtag, and every
|
|
||||||
/// subtag after a singleton such as `x`, is lowercase. Form only: no registry is
|
|
||||||
/// consulted. Selection and comparison are by exact tag, so a case variant would
|
|
||||||
/// be a different, dead language; this is the one tag check of corpus items,
|
|
||||||
/// entities, ontology entries and the run panel.
|
|
||||||
pub(crate) fn is_language_tag(s: &str) -> bool {
|
|
||||||
if s.len() > 35 {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let mut subtags = s.split('-');
|
|
||||||
let first = subtags.next().unwrap_or("");
|
|
||||||
let first_ok = first.bytes().all(|b| b.is_ascii_lowercase())
|
|
||||||
&& ((2..=8).contains(&first.len()) || first == "x");
|
|
||||||
if !first_ok {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// `private`: inside the `x` private-use section (subtags 1 to 8, lowercase).
|
|
||||||
// `ext`: inside any singleton section, where a one-byte subtag starts the next.
|
|
||||||
// `pending`: the last subtag was a singleton and nothing has followed it yet.
|
|
||||||
let mut private = first == "x";
|
|
||||||
let mut ext = private;
|
|
||||||
let mut pending = private;
|
|
||||||
for t in subtags {
|
|
||||||
if !(1..=8).contains(&t.len()) || !t.bytes().all(|b| b.is_ascii_alphanumeric()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let lower = t.bytes().all(|b| !b.is_ascii_uppercase());
|
|
||||||
if private {
|
|
||||||
if !lower {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
pending = false;
|
|
||||||
} else if t.len() == 1 {
|
|
||||||
// A singleton: lowercase, and not directly after another singleton.
|
|
||||||
if !lower || pending {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
ext = true;
|
|
||||||
pending = true;
|
|
||||||
private = t == "x";
|
|
||||||
} else if ext {
|
|
||||||
// Extension subtags are 2 to 8 lowercase.
|
|
||||||
if !lower {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
pending = false;
|
|
||||||
} else {
|
|
||||||
let alpha = t.bytes().all(|b| b.is_ascii_alphabetic());
|
|
||||||
let canonical = if t.len() == 2 {
|
|
||||||
// A region: two letters. Two digits are not a subtag at all.
|
|
||||||
alpha && t.bytes().all(|b| b.is_ascii_uppercase())
|
|
||||||
} else if alpha && t.len() == 4 {
|
|
||||||
t.as_bytes()[0].is_ascii_uppercase()
|
|
||||||
&& t.bytes().skip(1).all(|b| b.is_ascii_lowercase())
|
|
||||||
} else {
|
|
||||||
lower
|
|
||||||
};
|
|
||||||
if !canonical {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
!pending
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A slug: `[a-z0-9]` and inner `-`, 1 to 48 bytes, no edge `-`.
|
|
||||||
pub(crate) fn is_slug(s: &str) -> bool {
|
|
||||||
let b = s.as_bytes();
|
|
||||||
(1..=48).contains(&b.len())
|
|
||||||
&& b.iter()
|
|
||||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
|
|
||||||
&& b[0] != b'-'
|
|
||||||
&& b[b.len() - 1] != b'-'
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A General_Category Cf code point, or the line and paragraph separators
|
|
||||||
/// U+2028 and U+2029, other than the joiners ZWNJ U+200C and ZWJ U+200D. The
|
|
||||||
/// ranges are Unicode 15.1 Cf; `tests/format_refused.txt` is the full list from
|
|
||||||
/// Python's `unicodedata` that the table is swept against.
|
|
||||||
pub(crate) fn is_format(c: char) -> bool {
|
|
||||||
matches!(
|
|
||||||
c,
|
|
||||||
'\u{ad}'
|
|
||||||
| '\u{600}'..='\u{605}'
|
|
||||||
| '\u{61c}'
|
|
||||||
| '\u{6dd}'
|
|
||||||
| '\u{70f}'
|
|
||||||
| '\u{890}'..='\u{891}'
|
|
||||||
| '\u{8e2}'
|
|
||||||
| '\u{180e}'
|
|
||||||
| '\u{200b}'
|
|
||||||
| '\u{200e}'..='\u{200f}'
|
|
||||||
| '\u{2028}'..='\u{202e}'
|
|
||||||
| '\u{2060}'..='\u{2064}'
|
|
||||||
| '\u{2066}'..='\u{206f}'
|
|
||||||
| '\u{feff}'
|
|
||||||
| '\u{fff9}'..='\u{fffb}'
|
|
||||||
| '\u{110bd}'
|
|
||||||
| '\u{110cd}'
|
|
||||||
| '\u{13430}'..='\u{1343f}'
|
|
||||||
| '\u{1bca0}'..='\u{1bca3}'
|
|
||||||
| '\u{1d173}'..='\u{1d17a}'
|
|
||||||
| '\u{e0001}'
|
|
||||||
| '\u{e0020}'..='\u{e007f}'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ZWNJ and ZWJ: Cf, but scripts and emoji sequences need them inside a form.
|
|
||||||
pub(crate) fn is_joiner(c: char) -> bool {
|
|
||||||
matches!(c, '\u{200c}' | '\u{200d}')
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A character a name or form may not hold: every `is_format` code point, and
|
|
||||||
/// the invisible fillers that are Default_Ignorable without being Cf (Hangul
|
|
||||||
/// U+115F, U+1160, U+3164, U+FFA0 and Khmer U+17B4, U+17B5). Joiners,
|
|
||||||
/// variation selectors, CGJ and the Mongolian selectors are not refused.
|
|
||||||
pub(crate) fn is_refused_format(c: char) -> bool {
|
|
||||||
is_format(c)
|
|
||||||
|| matches!(
|
|
||||||
c,
|
|
||||||
'\u{115f}' | '\u{1160}' | '\u{17b4}' | '\u{17b5}' | '\u{3164}' | '\u{ffa0}'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A joiner, a variation selector (U+FE00..U+FE0F, U+E0100..U+E01EF), CGJ
|
|
||||||
/// U+034F or a Mongolian free variation selector (U+180B..U+180D, U+180F): it
|
|
||||||
/// shapes a neighbour and shows nothing alone.
|
|
||||||
pub(crate) fn is_joining_only(c: char) -> bool {
|
|
||||||
is_joiner(c)
|
|
||||||
|| matches!(
|
|
||||||
c,
|
|
||||||
'\u{34f}'
|
|
||||||
| '\u{180b}'..='\u{180d}'
|
|
||||||
| '\u{180f}'
|
|
||||||
| '\u{fe00}'..='\u{fe0f}'
|
|
||||||
| '\u{e0100}'..='\u{e01ef}'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An attestation string (author, persona, fixture, note, work, url, generator,
|
|
||||||
/// digest): at most 200 bytes, at least one alphanumeric, no control, format or
|
|
||||||
/// joiner character. Whitespace between words is fine; it attests something.
|
|
||||||
pub(crate) fn is_attestation(s: &str) -> bool {
|
|
||||||
s.len() <= 200
|
|
||||||
&& s.chars().any(char::is_alphanumeric)
|
|
||||||
&& !s
|
|
||||||
.chars()
|
|
||||||
.any(|c| c.is_control() || is_refused_format(c) || is_joiner(c))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// The rule against every code point: `is_format` is exactly the listed
|
|
||||||
/// Cf-minus-joiners-plus-U+2028/9 set, so each range has both of its
|
|
||||||
/// edges and the gaps between ranges pinned.
|
|
||||||
#[test]
|
|
||||||
fn format_rule_matches_the_unicode_list_at_every_code_point() {
|
|
||||||
let listed: std::collections::BTreeSet<u32> = include_str!("../tests/format_refused.txt")
|
|
||||||
.lines()
|
|
||||||
.filter(|l| !l.starts_with('#'))
|
|
||||||
.map(|l| u32::from_str_radix(l, 16).unwrap())
|
|
||||||
.collect();
|
|
||||||
for code in 0..=0x10ffff_u32 {
|
|
||||||
if let Some(c) = char::from_u32(code) {
|
|
||||||
assert_eq!(is_format(c), listed.contains(&code), "U+{code:X}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert!(!is_format('\u{200c}') && !is_format('\u{200d}'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_language_tag_is_in_canonical_case() {
|
|
||||||
for good in [
|
|
||||||
"en", "en-US", "ja-JP", "zh-Hant-TW", "sr-Latn", "es-419", "de-1996", "en-CA-x-ca",
|
|
||||||
"x-private", "x-ab", "x-a", "x-a-b", "en-x-a-b", "en-u-nu-x-a-b", "en-u-nu-latn", "ja-JP-x-a1",
|
|
||||||
] {
|
|
||||||
assert!(is_language_tag(good), "{good}");
|
|
||||||
}
|
|
||||||
for bad in [
|
|
||||||
"", "e", "EN", "En", "en-us", "en-Us", "en-uS", "ja-jp", "JA-JP", "zh-hant-TW",
|
|
||||||
"zh-HANT-TW", "zh-hAnt-TW", "zh-Hant-tw", "en-CA-x-CA", "en-CA-x-Ca", "de-1996-X",
|
|
||||||
"es-419-LATN", "en--US", "en-", "-en", "en_US", "abcdefghi", "en-abcdefghi",
|
|
||||||
"xx-\u{e9}", "x", "en-x", "en-u", "en-US-x", "en-0", "en-12", "en-u-x", "en-u-0",
|
|
||||||
"x-AB", "x-Ab", "en-x-AB", "en-a-b-ccc", "en-u-NU", "en-U-nu", "en-a-b",
|
|
||||||
] {
|
|
||||||
assert!(!is_language_tag(bad), "{bad}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_attestation_is_bounded_readable_text() {
|
|
||||||
assert!(is_attestation("a"));
|
|
||||||
assert!(is_attestation(&"x".repeat(200)));
|
|
||||||
assert!(!is_attestation(&"x".repeat(201)));
|
|
||||||
assert!(is_attestation("two words, 2 more"));
|
|
||||||
for bad in [
|
|
||||||
"", " ", "\t", "\u{200b}", "\u{200d}", "\0", "--", "a\nb", "a\u{ad}b",
|
|
||||||
] {
|
|
||||||
assert!(!is_attestation(bad), "{bad:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,610 +0,0 @@
|
||||||
//! The inventory: the ids packets name, as CultCache documents under appended
|
|
||||||
//! revisions. An entry is never edited in place; a changed meaning is a retire
|
|
||||||
//! plus an add, and a retired id still resolves for packets of earlier revisions.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::fmt;
|
|
||||||
use std::num::NonZeroU32;
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::form::{FormError, string_form};
|
|
||||||
|
|
||||||
#[derive(
|
|
||||||
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
|
|
||||||
)]
|
|
||||||
pub enum Family {
|
|
||||||
Concept,
|
|
||||||
Frame,
|
|
||||||
Role,
|
|
||||||
Relation,
|
|
||||||
SpeechAct,
|
|
||||||
Feature,
|
|
||||||
ReferentKind,
|
|
||||||
/// A game- or loop-declared packet field; the entry carries its value kind.
|
|
||||||
Extension,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Family {
|
|
||||||
pub const ALL: [Family; 8] = [
|
|
||||||
Family::Concept,
|
|
||||||
Family::Frame,
|
|
||||||
Family::Role,
|
|
||||||
Family::Relation,
|
|
||||||
Family::SpeechAct,
|
|
||||||
Family::Feature,
|
|
||||||
Family::ReferentKind,
|
|
||||||
Family::Extension,
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn prefix(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Family::Concept => "concept",
|
|
||||||
Family::Frame => "frame",
|
|
||||||
Family::Role => "role",
|
|
||||||
Family::Relation => "relation",
|
|
||||||
Family::SpeechAct => "speech_act",
|
|
||||||
Family::Feature => "feature",
|
|
||||||
Family::ReferentKind => "referent_kind",
|
|
||||||
Family::Extension => "extension",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The id of the `n`th entry of this family.
|
|
||||||
pub fn id(self, n: NonZeroU32) -> InvId {
|
|
||||||
InvId { family: self, n }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Id of an inventory entry: `<family prefix>:<n>`, `n` a canonical decimal
|
|
||||||
/// (no sign, no leading zero) of at least 1.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct InvId {
|
|
||||||
family: Family,
|
|
||||||
n: NonZeroU32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl InvId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
let bad = || FormError::new("InvId", s);
|
|
||||||
let (prefix, n) = s.split_once(':').ok_or_else(bad)?;
|
|
||||||
let family = Family::ALL
|
|
||||||
.into_iter()
|
|
||||||
.find(|f| f.prefix() == prefix)
|
|
||||||
.ok_or_else(bad)?;
|
|
||||||
if n.starts_with('0') || !n.bytes().all(|b| b.is_ascii_digit()) {
|
|
||||||
return Err(bad());
|
|
||||||
}
|
|
||||||
let n = n.parse::<NonZeroU32>().map_err(|_| bad())?;
|
|
||||||
Ok(Self { family, n })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn family(self) -> Family {
|
|
||||||
self.family
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `n` of `<family prefix>:<n>`.
|
|
||||||
pub fn n(self) -> NonZeroU32 {
|
|
||||||
self.n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for InvId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "{}:{}", self.family.prefix(), self.n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(InvId, { "type": "string", "pattern": "^(concept|frame|role|relation|speech_act|feature|referent_kind|extension):[1-9][0-9]*$" });
|
|
||||||
|
|
||||||
/// A value label of an options feature: `^[a-z][a-z0-9_]{0,23}$`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct OptionLabel(String);
|
|
||||||
|
|
||||||
impl OptionLabel {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
let mut bytes = s.bytes();
|
|
||||||
let ok = s.len() <= 24
|
|
||||||
&& bytes.next().is_some_and(|b| b.is_ascii_lowercase())
|
|
||||||
&& bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
|
|
||||||
if ok {
|
|
||||||
Ok(Self(s.to_string()))
|
|
||||||
} else {
|
|
||||||
Err(FormError::new("OptionLabel", s))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for OptionLabel {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(OptionLabel, { "type": "string", "pattern": "^[a-z][a-z0-9_]{0,23}$" });
|
|
||||||
|
|
||||||
/// 1 to 16 distinct labels.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "Vec<OptionLabel>", into = "Vec<OptionLabel>")]
|
|
||||||
pub struct OptionSet(Vec<OptionLabel>);
|
|
||||||
|
|
||||||
impl OptionSet {
|
|
||||||
pub const MAX: usize = 16;
|
|
||||||
|
|
||||||
pub fn new(labels: Vec<OptionLabel>) -> Result<Self, FormError> {
|
|
||||||
let mut distinct: Vec<&OptionLabel> = labels.iter().collect();
|
|
||||||
distinct.sort();
|
|
||||||
distinct.dedup();
|
|
||||||
if (1..=Self::MAX).contains(&labels.len()) && distinct.len() == labels.len() {
|
|
||||||
Ok(Self(labels))
|
|
||||||
} else {
|
|
||||||
Err(FormError::new(
|
|
||||||
"OptionSet",
|
|
||||||
format!("{} labels", labels.len()),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn contains(&self, label: &OptionLabel) -> bool {
|
|
||||||
self.0.contains(label)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<Vec<OptionLabel>> for OptionSet {
|
|
||||||
type Error = FormError;
|
|
||||||
fn try_from(v: Vec<OptionLabel>) -> Result<Self, FormError> {
|
|
||||||
Self::new(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<OptionSet> for Vec<OptionLabel> {
|
|
||||||
fn from(s: OptionSet) -> Self {
|
|
||||||
s.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl JsonSchema for OptionSet {
|
|
||||||
fn schema_name() -> std::borrow::Cow<'static, str> {
|
|
||||||
"OptionSet".into()
|
|
||||||
}
|
|
||||||
fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
|
||||||
schemars::json_schema!({
|
|
||||||
"type": "array",
|
|
||||||
"items": g.subschema_for::<OptionLabel>(),
|
|
||||||
"minItems": 1,
|
|
||||||
"maxItems": 16,
|
|
||||||
"uniqueItems": true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a feature may sit in a packet.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Slot {
|
|
||||||
Discourse,
|
|
||||||
Referent,
|
|
||||||
Predication,
|
|
||||||
Relation,
|
|
||||||
Stance,
|
|
||||||
/// The speaker's relation to one party of the scene, held by `weksa.scene`
|
|
||||||
/// documents; see `LoweringInput::with_scene`.
|
|
||||||
Scene,
|
|
||||||
/// The speaker's stable axes, held by `weksa.speaker` documents.
|
|
||||||
Speaker,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum ValueKind {
|
|
||||||
Grade,
|
|
||||||
Options(OptionSet),
|
|
||||||
Flag,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Key: the entry's id, `<family>:<n>`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.inventory_entry")]
|
|
||||||
pub struct InventoryEntry {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: InvId,
|
|
||||||
/// 1 to 120 bytes, no control character (checked at admission).
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub gloss: String,
|
|
||||||
/// Present exactly on features and extensions.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub value_kind: Option<ValueKind>,
|
|
||||||
/// Non-empty exactly on features.
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub applies_to: Vec<Slot>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub introduced_rev: u32,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub retired_rev: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl InventoryEntry {
|
|
||||||
pub fn family(&self) -> Family {
|
|
||||||
self.id.family()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the entry's shape matches its family: features carry a value kind
|
|
||||||
/// and slots, extensions a value kind and no slots, nothing else either. A
|
|
||||||
/// feature of slot `Stance`, `Speaker` or `Scene` sits in that slot alone: each
|
|
||||||
/// speaker-state layer has one writer and one lifetime, so its features sit
|
|
||||||
/// nowhere else.
|
|
||||||
pub fn well_formed(&self) -> bool {
|
|
||||||
match self.family() {
|
|
||||||
Family::Feature => {
|
|
||||||
self.value_kind.is_some()
|
|
||||||
&& !self.applies_to.is_empty()
|
|
||||||
&& (self.applies_to.len() == 1
|
|
||||||
|| !self
|
|
||||||
.applies_to
|
|
||||||
.iter()
|
|
||||||
.any(|s| matches!(s, Slot::Stance | Slot::Speaker | Slot::Scene)))
|
|
||||||
}
|
|
||||||
Family::Extension => self.value_kind.is_some() && self.applies_to.is_empty(),
|
|
||||||
_ => self.value_kind.is_none() && self.applies_to.is_empty(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a packet of inventory revision `rev` may name this entry.
|
|
||||||
pub fn live_at(&self, rev: u32) -> bool {
|
|
||||||
self.introduced_rev <= rev && self.retired_rev.is_none_or(|r| r > rev)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Change {
|
|
||||||
Add(InvId),
|
|
||||||
Retire(InvId),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Key: `rev:<n>`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.inventory_revision")]
|
|
||||||
pub struct InventoryRevision {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub n: u32,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub parent: Option<u32>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub changes: Vec<Change>,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub frozen: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn revision_key(n: u32) -> String {
|
|
||||||
format!("rev:{n}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The whole inventory as the store holds it.
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
pub struct Inventory {
|
|
||||||
entries: BTreeMap<InvId, InventoryEntry>,
|
|
||||||
revisions: BTreeMap<u32, InventoryRevision>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Inventory {
|
|
||||||
/// An inventory exists only as `InventoryStore::inventory` returns it, so
|
|
||||||
/// no caller can validate or admit against a fabricated one.
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0624
|
|
||||||
/// // `Inventory::new` is not callable outside the crate.
|
|
||||||
/// let _ = weksa::Inventory::new(vec![], vec![]);
|
|
||||||
/// ```
|
|
||||||
pub(crate) fn new(entries: Vec<InventoryEntry>, revisions: Vec<InventoryRevision>) -> Self {
|
|
||||||
Self {
|
|
||||||
entries: entries.into_iter().map(|e| (e.id, e)).collect(),
|
|
||||||
revisions: revisions.into_iter().map(|r| (r.n, r)).collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entries(&self) -> impl Iterator<Item = &InventoryEntry> {
|
|
||||||
self.entries.values()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entry(&self, id: &InvId) -> Option<&InventoryEntry> {
|
|
||||||
self.entries.get(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn revisions(&self) -> impl Iterator<Item = &InventoryRevision> {
|
|
||||||
self.revisions.values()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn has_revision(&self, n: u32) -> bool {
|
|
||||||
self.revisions.contains_key(&n)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn latest(&self) -> Option<&InventoryRevision> {
|
|
||||||
self.revisions.values().next_back()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entry `id`, if a packet of revision `rev` may name it.
|
|
||||||
pub fn resolve(&self, id: &InvId, rev: u32) -> Option<&InventoryEntry> {
|
|
||||||
self.entry(id).filter(|e| e.live_at(rev))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Revision 1: the standard's enumerated values and the nuance features the
|
|
||||||
/// loop starts from. Concepts start empty.
|
|
||||||
pub fn seed() -> (InventoryRevision, Vec<InventoryEntry>) {
|
|
||||||
let mut entries: Vec<InventoryEntry> = Vec::new();
|
|
||||||
let mut add = |family: Family, gloss: &str, kind: Option<ValueKind>, slots: &[Slot]| {
|
|
||||||
let taken = entries.iter().filter(|e| e.family() == family).count() as u32;
|
|
||||||
entries.push(InventoryEntry {
|
|
||||||
id: family.id(NonZeroU32::MIN.saturating_add(taken)),
|
|
||||||
gloss: gloss.to_string(),
|
|
||||||
value_kind: kind,
|
|
||||||
applies_to: slots.to_vec(),
|
|
||||||
introduced_rev: 1,
|
|
||||||
retired_rev: None,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
for g in [
|
|
||||||
"person",
|
|
||||||
"group",
|
|
||||||
"organism",
|
|
||||||
"place",
|
|
||||||
"artifact",
|
|
||||||
"institution",
|
|
||||||
"ecology",
|
|
||||||
"route",
|
|
||||||
"memory",
|
|
||||||
"event",
|
|
||||||
"abstract",
|
|
||||||
] {
|
|
||||||
add(Family::ReferentKind, g, None, &[]);
|
|
||||||
}
|
|
||||||
for g in [
|
|
||||||
"coreference",
|
|
||||||
"part_of",
|
|
||||||
"member_of",
|
|
||||||
"located_at",
|
|
||||||
"near",
|
|
||||||
"before",
|
|
||||||
"after",
|
|
||||||
"causes",
|
|
||||||
"enables",
|
|
||||||
"prevents",
|
|
||||||
"owns",
|
|
||||||
"owes",
|
|
||||||
"knows",
|
|
||||||
"names",
|
|
||||||
"represents",
|
|
||||||
"contrasts_with",
|
|
||||||
] {
|
|
||||||
add(Family::Relation, g, None, &[]);
|
|
||||||
}
|
|
||||||
for g in [
|
|
||||||
"agent",
|
|
||||||
"patient",
|
|
||||||
"experiencer",
|
|
||||||
"instrument",
|
|
||||||
"source",
|
|
||||||
"goal",
|
|
||||||
"location",
|
|
||||||
"beneficiary",
|
|
||||||
] {
|
|
||||||
add(Family::Role, g, None, &[]);
|
|
||||||
}
|
|
||||||
for g in [
|
|
||||||
"assert",
|
|
||||||
"ask",
|
|
||||||
"request",
|
|
||||||
"promise",
|
|
||||||
"warn",
|
|
||||||
"greet",
|
|
||||||
"thank",
|
|
||||||
"apologise",
|
|
||||||
] {
|
|
||||||
add(Family::SpeechAct, g, None, &[]);
|
|
||||||
}
|
|
||||||
let options = |labels: &[&str]| {
|
|
||||||
let labels = labels
|
|
||||||
.iter()
|
|
||||||
.map(|l| OptionLabel::parse(l).expect("seed labels are well formed"))
|
|
||||||
.collect();
|
|
||||||
Some(ValueKind::Options(
|
|
||||||
OptionSet::new(labels).expect("seed option sets are well formed"),
|
|
||||||
))
|
|
||||||
};
|
|
||||||
let pred = [Slot::Predication];
|
|
||||||
add(
|
|
||||||
Family::Feature,
|
|
||||||
"polarity",
|
|
||||||
options(&["positive", "negative"]),
|
|
||||||
&pred,
|
|
||||||
);
|
|
||||||
add(
|
|
||||||
Family::Feature,
|
|
||||||
"tense",
|
|
||||||
options(&["past", "present", "future", "timeless"]),
|
|
||||||
&pred,
|
|
||||||
);
|
|
||||||
add(
|
|
||||||
Family::Feature,
|
|
||||||
"aspect",
|
|
||||||
options(&[
|
|
||||||
"perfective",
|
|
||||||
"imperfective",
|
|
||||||
"progressive",
|
|
||||||
"habitual",
|
|
||||||
"perfect",
|
|
||||||
]),
|
|
||||||
&pred,
|
|
||||||
);
|
|
||||||
add(
|
|
||||||
Family::Feature,
|
|
||||||
"modality",
|
|
||||||
options(&[
|
|
||||||
"actual",
|
|
||||||
"potential",
|
|
||||||
"possible",
|
|
||||||
"necessary",
|
|
||||||
"desired",
|
|
||||||
"obligated",
|
|
||||||
]),
|
|
||||||
&pred,
|
|
||||||
);
|
|
||||||
add(
|
|
||||||
Family::Feature,
|
|
||||||
"evidentiality",
|
|
||||||
options(&["direct", "inferred", "reported", "assumed"]),
|
|
||||||
&pred,
|
|
||||||
);
|
|
||||||
let nuance = [Slot::Discourse, Slot::Predication];
|
|
||||||
for g in ["hedge", "certainty"] {
|
|
||||||
add(Family::Feature, g, Some(ValueKind::Grade), &nuance);
|
|
||||||
}
|
|
||||||
add(Family::Feature, "irony", Some(ValueKind::Flag), &nuance);
|
|
||||||
// Felt affect (permille of how strongly it is felt) and the restraint the speaker
|
|
||||||
// puts on it: slot Stance only. Affection covers fondness toward the
|
|
||||||
// addressee. Displayed affect is each language's ontology's business.
|
|
||||||
let stance = [Slot::Stance];
|
|
||||||
for g in [
|
|
||||||
"anger",
|
|
||||||
"fear",
|
|
||||||
"sadness",
|
|
||||||
"joy",
|
|
||||||
"disgust",
|
|
||||||
"surprise",
|
|
||||||
"contempt",
|
|
||||||
"affection",
|
|
||||||
"shame",
|
|
||||||
"restraint",
|
|
||||||
] {
|
|
||||||
add(Family::Feature, g, Some(ValueKind::Grade), &stance);
|
|
||||||
}
|
|
||||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
(
|
|
||||||
InventoryRevision {
|
|
||||||
n: 1,
|
|
||||||
parent: None,
|
|
||||||
changes,
|
|
||||||
frozen: false,
|
|
||||||
},
|
|
||||||
entries,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Revision 2: the concepts and frames the `nibu-proof-001` packet names, which
|
|
||||||
/// the seed leaves open. Hand-seeded like [`seed`] until the golf loop's
|
|
||||||
/// minting round owns concepts and frames.
|
|
||||||
pub fn proof_revision() -> (InventoryRevision, Vec<InventoryEntry>) {
|
|
||||||
let mut entries: Vec<InventoryEntry> = Vec::new();
|
|
||||||
for (family, glosses) in [
|
|
||||||
(
|
|
||||||
Family::Concept,
|
|
||||||
[
|
|
||||||
"endanger",
|
|
||||||
"prevent",
|
|
||||||
"player",
|
|
||||||
"control",
|
|
||||||
"ship_mind",
|
|
||||||
"request",
|
|
||||||
]
|
|
||||||
.as_slice(),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Family::Frame,
|
|
||||||
["hazard_warning", "intervention", "request_intervention"].as_slice(),
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
for (i, gloss) in glosses.iter().enumerate() {
|
|
||||||
entries.push(InventoryEntry {
|
|
||||||
id: family.id(NonZeroU32::MIN.saturating_add(i as u32)),
|
|
||||||
gloss: gloss.to_string(),
|
|
||||||
value_kind: None,
|
|
||||||
applies_to: vec![],
|
|
||||||
introduced_rev: 2,
|
|
||||||
retired_rev: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
(
|
|
||||||
InventoryRevision {
|
|
||||||
n: 2,
|
|
||||||
parent: Some(1),
|
|
||||||
changes,
|
|
||||||
frozen: false,
|
|
||||||
},
|
|
||||||
entries,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Revision `n`: the speaker-state vocabulary. First the Scene features, the
|
|
||||||
/// speaker's relation to one party of a scene (slot `Scene`): `relative_status`
|
|
||||||
/// is the speaker's standing against the addressee's, not a register word, what
|
|
||||||
/// it selects is each language's ontology's business. Then the Speaker features
|
|
||||||
/// (slot `Speaker`): `socioeconomic_standing` is standing in the speaker's own
|
|
||||||
/// society, 0 lowest; `education` is formal schooling against that society;
|
|
||||||
/// `age_cohort` is a life stage. Origin and community are not features; they
|
|
||||||
/// arrive as community ids with cut `language-ontology`. Hand-seeded like
|
|
||||||
/// [`proof_revision`] until the loop's minting round owns the vocabulary; the
|
|
||||||
/// features take the ids after the seed's.
|
|
||||||
pub fn speaker_scene_revision(n: u32) -> (InventoryRevision, Vec<InventoryEntry>) {
|
|
||||||
let taken = seed()
|
|
||||||
.1
|
|
||||||
.iter()
|
|
||||||
.filter(|e| e.family() == Family::Feature)
|
|
||||||
.count() as u32;
|
|
||||||
let options = |labels: &[&str]| {
|
|
||||||
ValueKind::Options(
|
|
||||||
OptionSet::new(
|
|
||||||
labels
|
|
||||||
.iter()
|
|
||||||
.map(|l| OptionLabel::parse(l).expect("seed labels are well formed"))
|
|
||||||
.collect(),
|
|
||||||
)
|
|
||||||
.expect("seed option sets are well formed"),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
for (i, (gloss, kind, slot)) in [
|
|
||||||
(
|
|
||||||
"relative_status",
|
|
||||||
options(&["below", "level", "above"]),
|
|
||||||
Slot::Scene,
|
|
||||||
),
|
|
||||||
("intimacy", ValueKind::Grade, Slot::Scene),
|
|
||||||
("in_group", ValueKind::Flag, Slot::Scene),
|
|
||||||
("socioeconomic_standing", ValueKind::Grade, Slot::Speaker),
|
|
||||||
("education", ValueKind::Grade, Slot::Speaker),
|
|
||||||
(
|
|
||||||
"age_cohort",
|
|
||||||
options(&["child", "adolescent", "young_adult", "adult", "elder"]),
|
|
||||||
Slot::Speaker,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
entries.push(InventoryEntry {
|
|
||||||
id: Family::Feature.id(NonZeroU32::MIN.saturating_add(taken + i as u32)),
|
|
||||||
gloss: gloss.to_string(),
|
|
||||||
value_kind: Some(kind),
|
|
||||||
applies_to: vec![slot],
|
|
||||||
introduced_rev: n,
|
|
||||||
retired_rev: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
(
|
|
||||||
InventoryRevision {
|
|
||||||
n,
|
|
||||||
parent: Some(n - 1),
|
|
||||||
changes,
|
|
||||||
frozen: false,
|
|
||||||
},
|
|
||||||
entries,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
//! Weksa's typed interlingua state: packet, inventory and corpus documents in
|
|
||||||
//! CultCache, the validator that decides whether a packet exists, the derived
|
|
||||||
//! train/validation/test split, the stores that admit them, and the scorer
|
|
||||||
//! (chrF, meaning cosine, leak diagnostics).
|
|
||||||
|
|
||||||
pub mod context;
|
|
||||||
pub mod corpus;
|
|
||||||
pub mod daodejing;
|
|
||||||
pub mod encode;
|
|
||||||
pub mod entity;
|
|
||||||
pub mod form;
|
|
||||||
pub mod inventory;
|
|
||||||
pub mod lower;
|
|
||||||
pub mod model;
|
|
||||||
pub mod ontology;
|
|
||||||
pub mod packet;
|
|
||||||
pub mod phones;
|
|
||||||
pub mod run;
|
|
||||||
pub mod schema;
|
|
||||||
pub mod score;
|
|
||||||
pub mod speaker;
|
|
||||||
pub mod split;
|
|
||||||
pub mod store;
|
|
||||||
pub mod validate;
|
|
||||||
|
|
||||||
pub use corpus::{CorpusItem, CorpusItemId, NameSpan, Source, Turn};
|
|
||||||
pub use encode::{EditDraft, LoweringDraft, PacketDraft};
|
|
||||||
pub use entity::{Entity, EntityOrigin, LanguageForms, Pronunciation};
|
|
||||||
pub use form::FormError;
|
|
||||||
pub use inventory::{
|
|
||||||
Change, Family, InvId, Inventory, InventoryEntry, InventoryRevision, OptionLabel, OptionSet,
|
|
||||||
Slot, ValueKind,
|
|
||||||
};
|
|
||||||
pub use lower::{EntityForms, LowerError, PhoneLine, TARGET_LANGUAGE, phones, pronounce};
|
|
||||||
pub use model::{AnswerFiles, ModelPort};
|
|
||||||
pub use ontology::{Condition, Layer, Ontology, OntologyEntry, Test, select};
|
|
||||||
pub use packet::{
|
|
||||||
EncoderId, EntityId, Grade, NodeId, Packet, PacketId, PacketKind, SCHEMA_VERSION, Stance,
|
|
||||||
};
|
|
||||||
pub use phones::{Phone, PhoneInventory, SegmentError, Stress};
|
|
||||||
pub use run::{Decision, RoundRecord, RunStores, cycle, round};
|
|
||||||
pub use score::{Embedder, ItemScore, OllamaEmbedder, Scorer, chrf};
|
|
||||||
pub use speaker::{Annotator, PairRelation, Party, Scene, Speaker};
|
|
||||||
pub use split::{Split, SplitScheme};
|
|
||||||
pub use store::{
|
|
||||||
AddOutcome, CorpusStore, EntityBound, EntityStore, InventoryStore, OntologyStore, PacketStore,
|
|
||||||
SpeakerStateStore, StoreError, StoreRefusal,
|
|
||||||
};
|
|
||||||
pub use validate::{LoweringInput, Refusal, SceneRead, validate};
|
|
||||||
|
|
@ -1,178 +0,0 @@
|
||||||
//! The entity port and the ruled pronunciation of a packet's entities.
|
|
||||||
//!
|
|
||||||
//! Wording of a packet in a target language is the `ModelPort`'s answer to
|
|
||||||
//! `Prompt::lower` (`context.rs`); nothing here produces lowered text. This
|
|
||||||
//! module holds what the entity store owns and the lowering path reads: the
|
|
||||||
//! narrow [`EntityForms`] port, the ruled IPA of every entity a packet cites
|
|
||||||
//! ([`pronounce`]), and its segmentation into phones ([`phones`]). A referent
|
|
||||||
//! that cites an entity is read through the port; an entity the port does not
|
|
||||||
//! hold, one with no form or no ruled pronunciation in [`TARGET_LANGUAGE`], is
|
|
||||||
//! refused, because spelling is not a pronunciation and there is no
|
|
||||||
//! grapheme-to-phoneme guess to offer in its place.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
use crate::entity::Entity;
|
|
||||||
use crate::packet::EntityId;
|
|
||||||
use crate::phones::{Phone, PhoneInventory, SegmentError};
|
|
||||||
use crate::store::EntityStore;
|
|
||||||
use crate::validate::LoweringInput;
|
|
||||||
|
|
||||||
/// The language tag of [`pronounce`] and [`phones`] only. The golf loop lowers
|
|
||||||
/// each item in its own language and does not read this. Spelled as an
|
|
||||||
/// entity's `LanguageForms::language` and a corpus item's language are.
|
|
||||||
pub const TARGET_LANGUAGE: &str = "en-US";
|
|
||||||
|
|
||||||
/// The lowerer's whole view of the entity store: one entity by id. Narrow so a
|
|
||||||
/// test or a loop can hand it a map and the lowerer cannot write, list or
|
|
||||||
/// search.
|
|
||||||
pub trait EntityForms {
|
|
||||||
fn entity(&self, id: &EntityId) -> anyhow::Result<Option<Entity>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EntityForms for EntityStore {
|
|
||||||
fn entity(&self, id: &EntityId) -> anyhow::Result<Option<Entity>> {
|
|
||||||
self.get(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum LowerError {
|
|
||||||
/// A referent cites an entity the entity port does not hold.
|
|
||||||
UnknownEntity { entity: EntityId },
|
|
||||||
/// The entity has no form in [`TARGET_LANGUAGE`].
|
|
||||||
NoForm { entity: EntityId },
|
|
||||||
/// IPA was requested for an entity whose [`TARGET_LANGUAGE`] citation form
|
|
||||||
/// has no ruled pronunciation. Spelling is not a pronunciation.
|
|
||||||
NoPronunciation { entity: EntityId },
|
|
||||||
/// IPA was requested for a packet that cites no entity.
|
|
||||||
NoEntityReferent,
|
|
||||||
/// Phones were requested for an entity whose ruled IPA holds a symbol the
|
|
||||||
/// language's phone inventory does not list (or the language has no
|
|
||||||
/// inventory). No phone is guessed.
|
|
||||||
UnknownPhone {
|
|
||||||
entity: EntityId,
|
|
||||||
at: usize,
|
|
||||||
text: String,
|
|
||||||
},
|
|
||||||
/// Phones were requested for an entity whose ruled IPA has a stress mark
|
|
||||||
/// with no vowel after it.
|
|
||||||
DanglingStress { entity: EntityId, at: usize },
|
|
||||||
/// The entity port failed to read.
|
|
||||||
EntityRead { entity: EntityId, why: String },
|
|
||||||
/// A lowering prompt was asked of a view whose scene was never read.
|
|
||||||
SceneUnread,
|
|
||||||
/// A referent cites the entity whose id is the lowering prompt's speaker
|
|
||||||
/// token ([`crate::context::SPEAKER_TOKEN`]), which would read as the speaker.
|
|
||||||
SpeakerTokenTaken,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for LowerError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(match self {
|
|
||||||
LowerError::UnknownEntity { .. } => "referent cites an entity the port does not hold",
|
|
||||||
LowerError::NoForm { .. } => "entity has no form in the target language",
|
|
||||||
LowerError::NoPronunciation { .. } => "entity has no ruled pronunciation",
|
|
||||||
LowerError::NoEntityReferent => "packet cites no entity",
|
|
||||||
LowerError::UnknownPhone { .. } => {
|
|
||||||
"ruled pronunciation holds a symbol with no listed phone"
|
|
||||||
}
|
|
||||||
LowerError::DanglingStress { .. } => "stress mark with no vowel after it",
|
|
||||||
LowerError::EntityRead { .. } => "entity port failed to read",
|
|
||||||
LowerError::SceneUnread => "the view's scene was never read",
|
|
||||||
LowerError::SpeakerTokenTaken => {
|
|
||||||
"a referent cites the entity id the speaker token uses"
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for LowerError {}
|
|
||||||
|
|
||||||
/// The ruled IPA of every entity a packet cites, one per entity referent in
|
|
||||||
/// the packet's referent order, as stored: bare, stress-marked, nothing
|
|
||||||
/// derived. A rejected pronunciation is never read. An entity the port does not
|
|
||||||
/// hold, or one with no ruled pronunciation in [`TARGET_LANGUAGE`], is refused:
|
|
||||||
/// the lowerer has no grapheme-to-phoneme guess to offer in its place.
|
|
||||||
pub fn pronounce(
|
|
||||||
input: &LoweringInput,
|
|
||||||
entities: &dyn EntityForms,
|
|
||||||
) -> Result<Vec<String>, LowerError> {
|
|
||||||
Ok(ruled(input, entities)?
|
|
||||||
.into_iter()
|
|
||||||
.map(|(_, ipa)| ipa)
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One entity's ruled pronunciation as the phones line a sound consumer reads:
|
|
||||||
/// the language tag, the stored IPA it came from, and the segmented phones.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
pub struct PhoneLine {
|
|
||||||
pub language: &'static str,
|
|
||||||
pub source: String,
|
|
||||||
pub phones: Vec<Phone>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The phones line of every entity a packet cites, in [`pronounce`] order, each
|
|
||||||
/// segmented by [`TARGET_LANGUAGE`]'s phone inventory. A symbol the inventory
|
|
||||||
/// does not list refuses the whole call.
|
|
||||||
pub fn phones(
|
|
||||||
input: &LoweringInput,
|
|
||||||
entities: &dyn EntityForms,
|
|
||||||
) -> Result<Vec<PhoneLine>, LowerError> {
|
|
||||||
let inventory = PhoneInventory::for_language(TARGET_LANGUAGE);
|
|
||||||
ruled(input, entities)?
|
|
||||||
.into_iter()
|
|
||||||
.map(|(entity, source)| {
|
|
||||||
let unknown = |at, text| LowerError::UnknownPhone {
|
|
||||||
entity: entity.clone(),
|
|
||||||
at,
|
|
||||||
text,
|
|
||||||
};
|
|
||||||
let inventory = inventory.ok_or_else(|| unknown(0, source.clone()))?;
|
|
||||||
let phones = inventory.segment(&source).map_err(|e| match e {
|
|
||||||
SegmentError::UnknownPhone { at, text } => unknown(at, text),
|
|
||||||
SegmentError::DanglingStress { at } => LowerError::DanglingStress {
|
|
||||||
entity: entity.clone(),
|
|
||||||
at,
|
|
||||||
},
|
|
||||||
})?;
|
|
||||||
Ok(PhoneLine {
|
|
||||||
language: TARGET_LANGUAGE,
|
|
||||||
source,
|
|
||||||
phones,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `(entity, ruled IPA)` for each entity referent, in referent order.
|
|
||||||
fn ruled(
|
|
||||||
input: &LoweringInput,
|
|
||||||
entities: &dyn EntityForms,
|
|
||||||
) -> Result<Vec<(EntityId, String)>, LowerError> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
for id in input.referents().iter().filter_map(|r| r.entity.as_ref()) {
|
|
||||||
let entity = entity(entities, id)?;
|
|
||||||
let p = entity
|
|
||||||
.pronunciation_in(TARGET_LANGUAGE)
|
|
||||||
.ok_or_else(|| LowerError::NoPronunciation { entity: id.clone() })?;
|
|
||||||
out.push((id.clone(), p.ipa.clone()));
|
|
||||||
}
|
|
||||||
if out.is_empty() {
|
|
||||||
return Err(LowerError::NoEntityReferent);
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn entity(entities: &dyn EntityForms, id: &EntityId) -> Result<Entity, LowerError> {
|
|
||||||
entities
|
|
||||||
.entity(id)
|
|
||||||
.map_err(|e| LowerError::EntityRead {
|
|
||||||
entity: id.clone(),
|
|
||||||
why: e.to_string(),
|
|
||||||
})?
|
|
||||||
.ok_or_else(|| LowerError::UnknownEntity { entity: id.clone() })
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,130 +0,0 @@
|
||||||
//! The loop's only door to a model. A model is the Claude session: it reads a
|
|
||||||
//! prompt file and writes an answer file, and a rerun picks the answer up. No
|
|
||||||
//! subprocess, network or binary lives here (golf-loop-in-claude).
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use crate::context::Prompt;
|
|
||||||
use crate::store::normalized;
|
|
||||||
|
|
||||||
/// A model answering [`Prompt`]s and nothing else.
|
|
||||||
pub trait ModelPort {
|
|
||||||
/// The id of the answering model, pinned by the run.
|
|
||||||
fn model(&self) -> &str;
|
|
||||||
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a prompt got no answer. Display names the kind only.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum PortError {
|
|
||||||
/// Nobody has answered yet.
|
|
||||||
Unanswered,
|
|
||||||
/// The prompt holds the text of an item in a Test group. It is neither written nor answered.
|
|
||||||
Withheld,
|
|
||||||
Io(ErrorKind),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for PortError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
PortError::Unanswered => f.write_str("the prompt is unanswered"),
|
|
||||||
PortError::Withheld => f.write_str("the prompt holds Test item text"),
|
|
||||||
PortError::Io(kind) => write!(f, "io error {kind:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for PortError {}
|
|
||||||
|
|
||||||
/// Answers from files in one directory: `<digest>.answer` is the reply to the
|
|
||||||
/// prompt whose digest is `<digest>`; a prompt with no answer is written to
|
|
||||||
/// `<digest>.prompt` for whoever answers.
|
|
||||||
pub struct AnswerFiles {
|
|
||||||
dir: PathBuf,
|
|
||||||
model: String,
|
|
||||||
withheld: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnswerFiles {
|
|
||||||
/// Refuses (`PortError::Withheld`) any prompt that holds the text of one of
|
|
||||||
/// `withheld`, before it reads or writes a file: the one door a prompt
|
|
||||||
/// leaves the loop through, so a Test sentence cannot reach a model by it.
|
|
||||||
pub fn new(dir: PathBuf, model: String, withheld: Vec<String>) -> Self {
|
|
||||||
Self { dir, model, withheld }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Normalised length from which a Test text is matched. Every live Test text is
|
|
||||||
/// longer; a shorter one ("Stop.") would match any prompt that says "Stop. Then
|
|
||||||
/// ...", so a Test item that short is not caught here.
|
|
||||||
const LONG: usize = 12;
|
|
||||||
|
|
||||||
/// Whether `prompt` holds `text`, by the corpus door's own sameness
|
|
||||||
/// ([`normalized`]: NFKC, case fold, spacing and punctuation dropped): a
|
|
||||||
/// re-cased, re-spaced, wrapped or width-changed copy still counts.
|
|
||||||
fn holds(prompt: &str, text: &str) -> bool {
|
|
||||||
let key = normalized(text);
|
|
||||||
key.chars().count() >= LONG && normalized(prompt).contains(&key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answers read from one directory and nothing else: `<digest>.answer` is the
|
|
||||||
/// reply to the prompt whose digest is `<digest>`. A prompt with no file is
|
|
||||||
/// [`PortError::Unanswered`]; this port never creates or writes anything. The
|
|
||||||
/// one reader of answer files: [`AnswerFiles`] reads through it.
|
|
||||||
pub struct RecordedAnswers {
|
|
||||||
dir: PathBuf,
|
|
||||||
model: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RecordedAnswers {
|
|
||||||
pub fn new(dir: PathBuf, model: String) -> Self {
|
|
||||||
Self { dir, model }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ModelPort for RecordedAnswers {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
&self.model
|
|
||||||
}
|
|
||||||
|
|
||||||
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError> {
|
|
||||||
match std::fs::read(self.dir.join(format!("{}.answer", prompt.digest()))) {
|
|
||||||
Ok(bytes) => {
|
|
||||||
String::from_utf8(bytes).map_err(|_| PortError::Io(ErrorKind::InvalidData))
|
|
||||||
}
|
|
||||||
Err(e) if e.kind() == ErrorKind::NotFound => Err(PortError::Unanswered),
|
|
||||||
Err(e) => Err(PortError::Io(e.kind())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ModelPort for AnswerFiles {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
&self.model
|
|
||||||
}
|
|
||||||
|
|
||||||
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError> {
|
|
||||||
let io = |e: std::io::Error| PortError::Io(e.kind());
|
|
||||||
if self.withheld.iter().any(|t| holds(prompt.text(), t)) {
|
|
||||||
return Err(PortError::Withheld);
|
|
||||||
}
|
|
||||||
let digest = prompt.digest();
|
|
||||||
match RecordedAnswers::new(self.dir.clone(), self.model.clone()).answer(prompt) {
|
|
||||||
Err(PortError::Unanswered) => {}
|
|
||||||
read => return read,
|
|
||||||
}
|
|
||||||
std::fs::create_dir_all(&self.dir).map_err(io)?;
|
|
||||||
let path = self.dir.join(format!("{digest}.prompt"));
|
|
||||||
match std::fs::read(&path) {
|
|
||||||
Ok(held) if held == prompt.text().as_bytes() => {}
|
|
||||||
Ok(_) => return Err(PortError::Io(ErrorKind::AlreadyExists)),
|
|
||||||
Err(e) if e.kind() == ErrorKind::NotFound => {
|
|
||||||
std::fs::write(&path, prompt.text()).map_err(io)?
|
|
||||||
}
|
|
||||||
Err(e) => return Err(io(e)),
|
|
||||||
}
|
|
||||||
Err(PortError::Unanswered)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,207 +0,0 @@
|
||||||
//! The language ontology: per target language, the choices its culture makes
|
|
||||||
//! about word, grammar, discourse, sound and script for a speaker in a stance
|
|
||||||
//! (ruling `persona-drives-ontology`). An entry says when it applies (feature
|
|
||||||
//! conditions over the lowering view's stance, discourse and scene relation) and what it
|
|
||||||
//! chooses. `select` is the only reader that decides which entries a lowering
|
|
||||||
//! prompt carries, and it runs only inside `Prompt::lower`;
|
|
||||||
//! `OntologyStore::admit` is the only writer. Entries are immutable.
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::inventory::{InvId, Slot};
|
|
||||||
use crate::packet::{FeatValue, FeatureValue, Grade};
|
|
||||||
use crate::speaker::Annotator;
|
|
||||||
use crate::validate::LoweringInput;
|
|
||||||
|
|
||||||
pub const MAX_CONDITIONS: usize = 4;
|
|
||||||
pub const MAX_EXAMPLES: usize = 3;
|
|
||||||
pub const MAX_CHOICE_BYTES: usize = 200;
|
|
||||||
pub const MAX_EXAMPLE_BYTES: usize = 120;
|
|
||||||
pub const MAX_ENTRIES_PER_LANGUAGE: usize = 64;
|
|
||||||
|
|
||||||
/// Which part of the language an entry shapes.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Layer {
|
|
||||||
Lexicon,
|
|
||||||
Grammar,
|
|
||||||
Discourse,
|
|
||||||
Phonology,
|
|
||||||
Orthography,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Layer {
|
|
||||||
pub fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Layer::Lexicon => "lexicon",
|
|
||||||
Layer::Grammar => "grammar",
|
|
||||||
Layer::Discourse => "discourse",
|
|
||||||
Layer::Phonology => "phonology",
|
|
||||||
Layer::Orthography => "orthography",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a feature's value must be for a condition to hold.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Test {
|
|
||||||
AtLeast(Grade),
|
|
||||||
AtMost(Grade),
|
|
||||||
Is(FeatValue),
|
|
||||||
/// Holds when the feature is absent or a grade at most `g`: a bound that
|
|
||||||
/// costs nothing where the feature is unrated. `AtMost` still fails on an
|
|
||||||
/// absent feature.
|
|
||||||
AtMostOrUnset(Grade),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One feature of one slot of the view, tested. `Stance`, `Discourse` and
|
|
||||||
/// `Scene` reach a lowering view; `Speaker` does not yet.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Condition {
|
|
||||||
pub slot: Slot,
|
|
||||||
pub feature: InvId,
|
|
||||||
pub test: Test,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Condition {
|
|
||||||
/// Whether this condition holds over a slot's feature values: the one
|
|
||||||
/// evaluator `select` and the corpus tests share.
|
|
||||||
pub fn holds(&self, features: &[FeatureValue]) -> bool {
|
|
||||||
let Some(found) = features.iter().find(|f| f.feature == self.feature) else {
|
|
||||||
return matches!(self.test, Test::AtMostOrUnset(_));
|
|
||||||
};
|
|
||||||
match (&self.test, &found.value) {
|
|
||||||
(Test::AtLeast(g), FeatValue::Grade(v)) => v >= g,
|
|
||||||
(Test::AtMost(g) | Test::AtMostOrUnset(g), FeatValue::Grade(v)) => v <= g,
|
|
||||||
(Test::Is(want), v) => want == v,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The feature value this condition names, as the inventory check reads it.
|
|
||||||
pub(crate) fn as_value(&self) -> FeatureValue {
|
|
||||||
FeatureValue {
|
|
||||||
feature: self.feature,
|
|
||||||
value: match &self.test {
|
|
||||||
Test::AtLeast(g) | Test::AtMost(g) | Test::AtMostOrUnset(g) => FeatValue::Grade(*g),
|
|
||||||
Test::Is(v) => v.clone(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One choice of one language. Key `onto:<language>:<n>`.
|
|
||||||
///
|
|
||||||
/// The store judges the form of an entry's text (bounds, normalization, no
|
|
||||||
/// control or format character) and never its meaning: no door judges text
|
|
||||||
/// (ruling `leak-owned-by-flow-and-scorer-3`). No Train-only ontology mint
|
|
||||||
/// exists yet, so a seed or a drafted entry is checked against held-out text by
|
|
||||||
/// nothing today; follow-up `leak-diagnostic-in-round` owns that diagnostic.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.ontology_entry")]
|
|
||||||
pub struct OntologyEntry {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub language: String,
|
|
||||||
/// The entry's number within its language, from 1.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub n: u32,
|
|
||||||
/// The revision, of the inventory the entry was admitted through, at which the
|
|
||||||
/// store read its conditions: provenance only; a run reads the conditions'
|
|
||||||
/// features at its own head.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub inventory_rev: u32,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub layer: Layer,
|
|
||||||
/// Every condition must hold; none means the entry always applies.
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub when: Vec<Condition>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub choice: String,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub examples: Vec<String>,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub annotator: Annotator,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `onto:<language>:<n>`.
|
|
||||||
pub fn ontology_key(language: &str, n: u32) -> String {
|
|
||||||
format!("onto:{language}:{n}")
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OntologyEntry {
|
|
||||||
pub fn key(&self) -> String {
|
|
||||||
ontology_key(&self.language, self.n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every entry of the run's ontology store, by language then number.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub struct Ontology {
|
|
||||||
entries: Vec<OntologyEntry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ontology {
|
|
||||||
pub fn empty() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn of(mut entries: Vec<OntologyEntry>) -> Self {
|
|
||||||
entries.sort_by(|a, b| (&a.language, a.n).cmp(&(&b.language, b.n)));
|
|
||||||
Self { entries }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entries(&self) -> &[OntologyEntry] {
|
|
||||||
&self.entries
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entries of exactly `language` whose every condition holds against the
|
|
||||||
/// view's stance, discourse and scene-relation features (the scene's only when
|
|
||||||
/// `with_scene` selected a relation), in `n` order. An absent feature meets no
|
|
||||||
/// condition except `AtMostOrUnset`. Nothing else of the view is read.
|
|
||||||
pub fn select<'a>(
|
|
||||||
o: &'a Ontology,
|
|
||||||
language: &str,
|
|
||||||
input: &LoweringInput,
|
|
||||||
) -> Vec<&'a OntologyEntry> {
|
|
||||||
o.entries
|
|
||||||
.iter()
|
|
||||||
.filter(|e| e.language == language)
|
|
||||||
.filter(|e| {
|
|
||||||
e.when.iter().all(|c| match c.slot {
|
|
||||||
Slot::Stance => c.holds(&input.stance().features),
|
|
||||||
Slot::Discourse => c.holds(&input.discourse().features),
|
|
||||||
Slot::Scene => c.holds(input.scene()),
|
|
||||||
_ => false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn cond(test: Test) -> Condition {
|
|
||||||
Condition { slot: Slot::Discourse, feature: InvId::parse("feature:7").unwrap(), test }
|
|
||||||
}
|
|
||||||
fn has(v: FeatValue) -> Vec<FeatureValue> {
|
|
||||||
vec![FeatureValue { feature: InvId::parse("feature:7").unwrap(), value: v }]
|
|
||||||
}
|
|
||||||
fn grade(g: u16) -> Grade {
|
|
||||||
Grade::new(g).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn at_most_or_unset_holds_when_absent_or_at_most_and_nothing_else() {
|
|
||||||
let c = cond(Test::AtMostOrUnset(grade(799)));
|
|
||||||
assert!(c.holds(&[]));
|
|
||||||
assert!(c.holds(&has(FeatValue::Grade(grade(799)))));
|
|
||||||
assert!(c.holds(&has(FeatValue::Grade(grade(0)))));
|
|
||||||
assert!(!c.holds(&has(FeatValue::Grade(grade(800)))));
|
|
||||||
assert!(!c.holds(&has(FeatValue::Flag(true))));
|
|
||||||
// AtMost keeps its meaning: an absent feature fails it.
|
|
||||||
assert!(!cond(Test::AtMost(grade(799))).holds(&[]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,436 +0,0 @@
|
||||||
//! The interlingua packet. Every id is an opaque form type: a node id `n<k>`, a
|
|
||||||
//! packet id `packet:<hex16>`, an encoder id `encoder:<hex16>`, an inventory id
|
|
||||||
//! `<family>:<n>`. The only free text is the trace, which is stripped before
|
|
||||||
//! lowering. A malformed id cannot be built, and cannot be read back from a
|
|
||||||
//! store, so a packet cannot carry target-language wording through an id slot.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::corpus::CorpusItemId;
|
|
||||||
use crate::form::{FormError, is_slug, string_form};
|
|
||||||
pub use crate::inventory::InvId;
|
|
||||||
use crate::inventory::OptionLabel;
|
|
||||||
|
|
||||||
/// Bumped by a commit that changes these types; the published schema moves with it.
|
|
||||||
pub const SCHEMA_VERSION: u32 = 5;
|
|
||||||
|
|
||||||
/// Id of a referent or predication within one packet: `n<k>`, `k` a canonical
|
|
||||||
/// decimal 1..=9999.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct NodeId(String);
|
|
||||||
|
|
||||||
impl NodeId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
let k = s
|
|
||||||
.strip_prefix('n')
|
|
||||||
.filter(|d| !d.starts_with('0') && d.bytes().all(|b| b.is_ascii_digit()))
|
|
||||||
.and_then(|d| d.parse::<u16>().ok())
|
|
||||||
.filter(|k| (1..=9999).contains(k));
|
|
||||||
k.map(|_| Self(s.to_string()))
|
|
||||||
.ok_or_else(|| FormError::new("NodeId", s))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for NodeId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(NodeId, { "type": "string", "pattern": "^n[1-9][0-9]{0,3}$" });
|
|
||||||
|
|
||||||
/// `<prefix>:<16 lowercase hex>`.
|
|
||||||
fn hex16(prefix: &str, s: &str) -> bool {
|
|
||||||
s.strip_prefix(prefix)
|
|
||||||
.is_some_and(|h| h.len() == 16 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Key of a packet: `packet:<hex16>`, a digest the loop derives from the item,
|
|
||||||
/// the inventory revision and the encoder.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct PacketId(String);
|
|
||||||
|
|
||||||
impl PacketId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
if hex16("packet:", s) {
|
|
||||||
Ok(Self(s.to_string()))
|
|
||||||
} else {
|
|
||||||
Err(FormError::new("PacketId", s))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for PacketId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(PacketId, { "type": "string", "pattern": "^packet:[0-9a-f]{16}$" });
|
|
||||||
|
|
||||||
/// `encoder:<hex16>`, a digest of the model id and the prompt digest.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct EncoderId(String);
|
|
||||||
|
|
||||||
impl EncoderId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
if hex16("encoder:", s) {
|
|
||||||
Ok(Self(s.to_string()))
|
|
||||||
} else {
|
|
||||||
Err(FormError::new("EncoderId", s))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for EncoderId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(EncoderId, { "type": "string", "pattern": "^encoder:[0-9a-f]{16}$" });
|
|
||||||
|
|
||||||
/// Id of an entity: `entity:<slug>`, a slug as an item key's (`[a-z0-9]` and
|
|
||||||
/// inner `-`, 1 to 48 bytes, no edge `-`).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "String", into = "String")]
|
|
||||||
pub struct EntityId(String);
|
|
||||||
|
|
||||||
impl EntityId {
|
|
||||||
pub fn parse(s: &str) -> Result<Self, FormError> {
|
|
||||||
match s.strip_prefix("entity:") {
|
|
||||||
Some(slug) if is_slug(slug) => Ok(Self(s.to_string())),
|
|
||||||
_ => Err(FormError::new("EntityId", s)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for EntityId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string_form!(EntityId, { "type": "string", "pattern": "^entity:[a-z0-9]([a-z0-9-]{0,46}[a-z0-9])?$" });
|
|
||||||
|
|
||||||
/// Permille, 0..=1000.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
||||||
#[serde(try_from = "u16", into = "u16")]
|
|
||||||
pub struct Grade(u16);
|
|
||||||
|
|
||||||
impl Grade {
|
|
||||||
pub const MAX: u16 = 1000;
|
|
||||||
|
|
||||||
pub fn new(permille: u16) -> Result<Self, FormError> {
|
|
||||||
if permille <= Self::MAX {
|
|
||||||
Ok(Self(permille))
|
|
||||||
} else {
|
|
||||||
Err(FormError::new("Grade", permille))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> u16 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<u16> for Grade {
|
|
||||||
type Error = FormError;
|
|
||||||
fn try_from(v: u16) -> Result<Self, FormError> {
|
|
||||||
Self::new(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Grade> for u16 {
|
|
||||||
fn from(g: Grade) -> u16 {
|
|
||||||
g.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl JsonSchema for Grade {
|
|
||||||
fn schema_name() -> std::borrow::Cow<'static, str> {
|
|
||||||
"Grade".into()
|
|
||||||
}
|
|
||||||
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
|
||||||
schemars::json_schema!({ "type": "integer", "minimum": 0, "maximum": 1000 })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.interlingua_packet")]
|
|
||||||
pub struct Packet {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: PacketId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub schema_version: u32,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub inventory_rev: u32,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub kind: PacketKind,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub provenance: Provenance,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub context: Context,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub discourse: Discourse,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub referents: Vec<Referent>,
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub predications: Vec<Predication>,
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub relations: Vec<Relation>,
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
pub constraints: Constraints,
|
|
||||||
#[cultcache(key = 11)]
|
|
||||||
pub extensions: Vec<Extension>,
|
|
||||||
#[cultcache(key = 12)]
|
|
||||||
pub trace: Trace,
|
|
||||||
#[cultcache(key = 13)]
|
|
||||||
pub stance: Stance,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Packet {
|
|
||||||
/// The most referents, predications and relations one packet holds: a
|
|
||||||
/// calibration constant of ours, capacity and not meaning.
|
|
||||||
pub const MAX_NODES: usize = 64;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum PacketKind {
|
|
||||||
Utterance,
|
|
||||||
NameRequest,
|
|
||||||
CommentaryIntent,
|
|
||||||
Narration,
|
|
||||||
DialogueLine,
|
|
||||||
CorpusExample,
|
|
||||||
DebugProbe,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum ProvenanceSource {
|
|
||||||
Authored,
|
|
||||||
ModelDecomposition,
|
|
||||||
GameTelemetry,
|
|
||||||
ImportedCorpus,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Provenance {
|
|
||||||
pub source: ProvenanceSource,
|
|
||||||
/// The corpus item this packet was minted for. Required: the packet store
|
|
||||||
/// admits only packets that name their item.
|
|
||||||
pub corpus_item: CorpusItemId,
|
|
||||||
pub encoder: EncoderId,
|
|
||||||
pub confidence: Grade,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Context {
|
|
||||||
/// Concept ids.
|
|
||||||
pub setting: Option<InvId>,
|
|
||||||
pub medium: Option<InvId>,
|
|
||||||
pub participants: Vec<NodeId>,
|
|
||||||
pub audience: Vec<NodeId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Discourse {
|
|
||||||
/// Speech-act id.
|
|
||||||
pub speech_act: Option<InvId>,
|
|
||||||
pub addressee: Option<NodeId>,
|
|
||||||
/// The predication the addressee asked for or agreed to. A fact about what
|
|
||||||
/// the addressee did, never about how the line sounds, so it is no feature:
|
|
||||||
/// only a source that saw the request may set it (V15), it needs an
|
|
||||||
/// addressee (V14) and names a predication (V14), and a lowering that
|
|
||||||
/// speaks for the addressee's request ("you asked her to") reads it here
|
|
||||||
/// and refuses without it.
|
|
||||||
pub addressee_consent: Option<NodeId>,
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The speaker's felt affect and restraint, never displayed affect: how the
|
|
||||||
/// speaker shows a feeling is each language's ontology's business. A
|
|
||||||
/// held-back feeling is not a claim, so it is never a predication.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Stance {
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct FeatureValue {
|
|
||||||
/// Feature id.
|
|
||||||
pub feature: InvId,
|
|
||||||
pub value: FeatValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum FeatValue {
|
|
||||||
Grade(Grade),
|
|
||||||
/// A label the feature's inventory entry declares.
|
|
||||||
Option(OptionLabel),
|
|
||||||
Flag(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Referent {
|
|
||||||
pub id: NodeId,
|
|
||||||
/// Referent-kind id.
|
|
||||||
pub kind: InvId,
|
|
||||||
/// Concept id.
|
|
||||||
pub concept: InvId,
|
|
||||||
/// The entity this referent names, when it has one. The entity store holds
|
|
||||||
/// its wording; the packet holds only the id.
|
|
||||||
pub entity: Option<EntityId>,
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Predication {
|
|
||||||
pub id: NodeId,
|
|
||||||
/// Concept id.
|
|
||||||
pub concept: InvId,
|
|
||||||
/// Frame id.
|
|
||||||
pub frame: InvId,
|
|
||||||
pub roles: Vec<RoleFill>,
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct RoleFill {
|
|
||||||
/// Role id.
|
|
||||||
pub role: InvId,
|
|
||||||
pub filler: NodeId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Relation {
|
|
||||||
/// Relation id.
|
|
||||||
pub relation: InvId,
|
|
||||||
pub from: NodeId,
|
|
||||||
pub to: NodeId,
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Constraints {
|
|
||||||
pub preserve: Vec<NodeId>,
|
|
||||||
pub deterministic: bool,
|
|
||||||
pub max_latency_ms: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Extension {
|
|
||||||
/// Extension-entry id; the inventory declares its value kind.
|
|
||||||
pub key: InvId,
|
|
||||||
pub value: FeatValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Authoring and debug notes. Stripped before lowering.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct Trace {
|
|
||||||
pub notes: Vec<String>,
|
|
||||||
pub rejected_readings: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `nibu-proof-001` packet: the meaning of `examples/english-lowering/nibu-proof-001/interlingua.yaml`
|
|
||||||
/// (warn the player off the damaged control; Nibu will stop it) as typed
|
|
||||||
/// ids of inventory revision 2, for the corpus item `item:nibu:1`. No features:
|
|
||||||
/// nothing here is style.
|
|
||||||
pub fn proof_packet() -> Packet {
|
|
||||||
fn id(s: &str) -> InvId {
|
|
||||||
InvId::parse(s).expect("proof ids are well formed")
|
|
||||||
}
|
|
||||||
fn node(s: &str) -> NodeId {
|
|
||||||
NodeId::parse(s).expect("proof nodes are well formed")
|
|
||||||
}
|
|
||||||
let referent = |n: &str, kind: &str, concept: &str, entity: Option<&str>| Referent {
|
|
||||||
id: node(n),
|
|
||||||
kind: id(kind),
|
|
||||||
concept: id(concept),
|
|
||||||
entity: entity.map(|e| EntityId::parse(e).expect("proof entity is well formed")),
|
|
||||||
features: vec![],
|
|
||||||
};
|
|
||||||
let fill = |role: &str, filler: &str| RoleFill {
|
|
||||||
role: id(role),
|
|
||||||
filler: node(filler),
|
|
||||||
};
|
|
||||||
Packet {
|
|
||||||
id: PacketId::parse("packet:6e6962752d303031").expect("proof id"),
|
|
||||||
schema_version: SCHEMA_VERSION,
|
|
||||||
inventory_rev: 2,
|
|
||||||
kind: PacketKind::DialogueLine,
|
|
||||||
provenance: Provenance {
|
|
||||||
source: ProvenanceSource::Authored,
|
|
||||||
corpus_item: CorpusItemId::parse("item:nibu:1").expect("proof item"),
|
|
||||||
encoder: EncoderId::parse("encoder:6f70657261746f72").expect("proof encoder"),
|
|
||||||
confidence: Grade::new(900).expect("proof grade"),
|
|
||||||
},
|
|
||||||
context: Context::default(),
|
|
||||||
discourse: Discourse {
|
|
||||||
speech_act: Some(id("speech_act:5")),
|
|
||||||
addressee: Some(node("n1")),
|
|
||||||
addressee_consent: None,
|
|
||||||
features: vec![],
|
|
||||||
},
|
|
||||||
referents: vec![
|
|
||||||
referent("n1", "referent_kind:1", "concept:3", None),
|
|
||||||
referent("n2", "referent_kind:5", "concept:4", None),
|
|
||||||
referent("n3", "referent_kind:1", "concept:5", Some("entity:nibu")),
|
|
||||||
],
|
|
||||||
predications: vec![
|
|
||||||
Predication {
|
|
||||||
id: node("n4"),
|
|
||||||
concept: id("concept:1"),
|
|
||||||
frame: id("frame:1"),
|
|
||||||
roles: vec![
|
|
||||||
fill("role:1", "n1"),
|
|
||||||
fill("role:4", "n2"),
|
|
||||||
fill("role:2", "n1"),
|
|
||||||
],
|
|
||||||
features: vec![],
|
|
||||||
},
|
|
||||||
Predication {
|
|
||||||
id: node("n5"),
|
|
||||||
concept: id("concept:2"),
|
|
||||||
frame: id("frame:2"),
|
|
||||||
roles: vec![fill("role:1", "n3"), fill("role:2", "n4")],
|
|
||||||
features: vec![],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
relations: vec![],
|
|
||||||
constraints: Constraints {
|
|
||||||
preserve: vec![node("n1"), node("n2")],
|
|
||||||
deterministic: true,
|
|
||||||
max_latency_ms: None,
|
|
||||||
},
|
|
||||||
extensions: vec![],
|
|
||||||
trace: Trace {
|
|
||||||
notes: vec!["First proof packet for Nibu flavored-English lowering.".to_string()],
|
|
||||||
rejected_readings: vec![],
|
|
||||||
},
|
|
||||||
stance: Stance::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,152 +0,0 @@
|
||||||
//! The phone inventory and the segmenter: a ruled IPA string to an ordered list of
|
|
||||||
//! phones with stress, for the consumer that turns phones into sound. The
|
|
||||||
//! inventory is data (`data/phonology/<language>.phones.tsv`); this module reads
|
|
||||||
//! it and owns one rule, that every symbol of the string is a phone the inventory
|
|
||||||
//! lists. A symbol it does not list is refused: no nearest phone, no spelling
|
|
||||||
//! rule, no guess. Tense/lax is a column of the inventory, so /i/ and /ɪ/ are two
|
|
||||||
//! phones here, not one phone and a flag on an entity.
|
|
||||||
//!
|
|
||||||
//! Stress marks are not phones. `ˈ` (primary) and `ˌ` (secondary) put their
|
|
||||||
//! stress on the next vowel phone, the syllable's nucleus; every other phone is
|
|
||||||
//! `none`. A mark with no vowel after it is refused. Durations, pitch and
|
|
||||||
//! acoustics are the consumer's, never read or written here.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
const EN_US: &str = include_str!("../../../data/phonology/en-US.phones.tsv");
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
#[serde(rename_all = "lowercase")]
|
|
||||||
pub enum Stress {
|
|
||||||
None,
|
|
||||||
Primary,
|
|
||||||
Secondary,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One phone of a segmented string: its IPA symbol as the inventory spells it
|
|
||||||
/// and its stress.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
||||||
pub struct Phone {
|
|
||||||
pub ipa: String,
|
|
||||||
pub stress: Stress,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Tenseness {
|
|
||||||
Tense,
|
|
||||||
Lax,
|
|
||||||
Reduced,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Class {
|
|
||||||
Consonant,
|
|
||||||
Vowel(Tenseness),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum SegmentError {
|
|
||||||
/// The symbol (or the text from it on) matches no inventory phone.
|
|
||||||
UnknownPhone { at: usize, text: String },
|
|
||||||
/// A stress mark (`at` is its byte offset) that finds no vowel before the
|
|
||||||
/// string ends or another mark comes.
|
|
||||||
DanglingStress { at: usize },
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PhoneInventory {
|
|
||||||
phones: BTreeMap<String, Class>,
|
|
||||||
longest: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PhoneInventory {
|
|
||||||
/// The inventory for a language tag, if one is committed.
|
|
||||||
pub fn for_language(language: &str) -> Option<&'static PhoneInventory> {
|
|
||||||
static EN_US_INV: OnceLock<PhoneInventory> = OnceLock::new();
|
|
||||||
match language {
|
|
||||||
"en-US" => Some(EN_US_INV.get_or_init(|| {
|
|
||||||
PhoneInventory::parse(EN_US).expect("the committed en-US phone inventory parses")
|
|
||||||
})),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse the tab-separated inventory. Malformed lines are errors, as are
|
|
||||||
/// repeated symbols.
|
|
||||||
pub fn parse(text: &str) -> Result<Self, String> {
|
|
||||||
let mut phones = BTreeMap::new();
|
|
||||||
for (n, line) in text.lines().enumerate() {
|
|
||||||
if line.is_empty() || line.starts_with('#') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let cols: Vec<&str> = line.split('\t').collect();
|
|
||||||
let [ipa, class, tenseness, gloss] = cols[..] else {
|
|
||||||
return Err(format!("line {}: want 4 tab-separated columns", n + 1));
|
|
||||||
};
|
|
||||||
let class = match (class, tenseness) {
|
|
||||||
("consonant", "-") => Class::Consonant,
|
|
||||||
("vowel", "tense") => Class::Vowel(Tenseness::Tense),
|
|
||||||
("vowel", "lax") => Class::Vowel(Tenseness::Lax),
|
|
||||||
("vowel", "reduced") => Class::Vowel(Tenseness::Reduced),
|
|
||||||
_ => return Err(format!("line {}: bad class/tenseness {class}/{tenseness}", n + 1)),
|
|
||||||
};
|
|
||||||
if ipa.is_empty() || gloss.is_empty() || ipa.chars().any(|c| matches!(c, 'ˈ' | 'ˌ')) {
|
|
||||||
return Err(format!("line {}: empty or stress-marked entry", n + 1));
|
|
||||||
}
|
|
||||||
if phones.insert(ipa.to_string(), class).is_some() {
|
|
||||||
return Err(format!("line {}: {ipa} repeats", n + 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let longest = phones.keys().map(|k| k.chars().count()).max().unwrap_or(0);
|
|
||||||
Ok(Self { phones, longest })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn class(&self, ipa: &str) -> Option<&Class> {
|
|
||||||
self.phones.get(ipa)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Segment `ipa` into phones: longest inventory match at each position.
|
|
||||||
pub fn segment(&self, ipa: &str) -> Result<Vec<Phone>, SegmentError> {
|
|
||||||
let chars: Vec<(usize, char)> = ipa.char_indices().collect();
|
|
||||||
let mut out: Vec<Phone> = Vec::new();
|
|
||||||
let mut pending: Option<(Stress, usize)> = None;
|
|
||||||
let mut i = 0;
|
|
||||||
while i < chars.len() {
|
|
||||||
let at = chars[i].0;
|
|
||||||
let mark = match chars[i].1 {
|
|
||||||
'ˈ' => Some(Stress::Primary),
|
|
||||||
'ˌ' => Some(Stress::Secondary),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
if let Some(m) = mark {
|
|
||||||
if let Some((_, was)) = pending {
|
|
||||||
return Err(SegmentError::DanglingStress { at: was });
|
|
||||||
}
|
|
||||||
pending = Some((m, at));
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let hit = (1..=self.longest.min(chars.len() - i)).rev().find_map(|len| {
|
|
||||||
let end = chars.get(i + len).map_or(ipa.len(), |c| c.0);
|
|
||||||
let s = &ipa[at..end];
|
|
||||||
self.phones.get(s).map(|c| (len, s, c))
|
|
||||||
});
|
|
||||||
let Some((len, s, class)) = hit else {
|
|
||||||
return Err(SegmentError::UnknownPhone { at, text: ipa[at..].to_string() });
|
|
||||||
};
|
|
||||||
let stress = if matches!(class, Class::Vowel(_)) {
|
|
||||||
pending.take().map_or(Stress::None, |(m, _)| m)
|
|
||||||
} else {
|
|
||||||
Stress::None
|
|
||||||
};
|
|
||||||
out.push(Phone { ipa: s.to_string(), stress });
|
|
||||||
i += len;
|
|
||||||
}
|
|
||||||
if let Some((_, at)) = pending {
|
|
||||||
return Err(SegmentError::DanglingStress { at });
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,21 +0,0 @@
|
||||||
//! Pins for private functions of `run.rs` that the doors reach only through a
|
|
||||||
//! whole run.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// A line is probed only when it has at least four words, and then it is
|
|
||||||
/// split in two near its byte middle, the pieces trimmed.
|
|
||||||
#[test]
|
|
||||||
fn a_recall_line_splits_from_four_words_and_not_before() {
|
|
||||||
assert_eq!(recall_split("one two three"), None);
|
|
||||||
assert_eq!(recall_split(""), None);
|
|
||||||
assert_eq!(
|
|
||||||
recall_split("one two three four"),
|
|
||||||
Some(("one two".to_string(), "three four".to_string()))
|
|
||||||
);
|
|
||||||
// No spaces: each ideograph is a word, the split falls at the middle.
|
|
||||||
assert_eq!(
|
|
||||||
recall_split("天地不仁以万物为刍狗"),
|
|
||||||
Some(("天地不仁以".to_string(), "万物为刍狗".to_string()))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
//! JSON Schema publication. JSON is only the xenos-boundary export of the typed
|
|
||||||
//! documents; nothing in this crate reads JSON.
|
|
||||||
|
|
||||||
use crate::corpus::CorpusItem;
|
|
||||||
use crate::entity::Entity;
|
|
||||||
use crate::inventory::{InventoryEntry, InventoryRevision};
|
|
||||||
use crate::ontology::OntologyEntry;
|
|
||||||
use crate::packet::Packet;
|
|
||||||
use crate::run::{Decision, RoundRecord, RunRecord};
|
|
||||||
use crate::speaker::{Scene, Speaker};
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::{JsonSchema, schema_for};
|
|
||||||
|
|
||||||
fn published_for<T: DatabaseEntry + JsonSchema>() -> (String, String) {
|
|
||||||
let json = serde_json::to_string_pretty(&schema_for!(T)).expect("a schema serializes");
|
|
||||||
(format!("{}.schema.json", T::TYPE), format!("{json}\n"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `(file name, contents)` for every document type, as `schemas/cultnet/` holds them.
|
|
||||||
pub fn published() -> Vec<(String, String)> {
|
|
||||||
vec![
|
|
||||||
published_for::<Packet>(),
|
|
||||||
published_for::<InventoryEntry>(),
|
|
||||||
published_for::<InventoryRevision>(),
|
|
||||||
published_for::<CorpusItem>(),
|
|
||||||
published_for::<Entity>(),
|
|
||||||
published_for::<Speaker>(),
|
|
||||||
published_for::<Scene>(),
|
|
||||||
published_for::<OntologyEntry>(),
|
|
||||||
published_for::<RunRecord>(),
|
|
||||||
published_for::<RoundRecord>(),
|
|
||||||
published_for::<Decision>(),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
//! chrF as sacrebleu 2.4.3 computes it by default: character n-gram orders 1 to
|
|
||||||
//! 6, whitespace removed, case kept, beta 2.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
/// The metric this module implements; a score stored beside it names its definition.
|
|
||||||
pub const CHRF_VERSION: &str = "chrF2|nc:6|nw:0|space:no|sacrebleu:2.4.3";
|
|
||||||
|
|
||||||
const ORDER: usize = 6;
|
|
||||||
const BETA_SQ: f64 = 4.0;
|
|
||||||
|
|
||||||
fn grams(chars: &[char], n: usize) -> HashMap<&[char], u32> {
|
|
||||||
let mut counts = HashMap::new();
|
|
||||||
for window in chars.windows(n) {
|
|
||||||
*counts.entry(window).or_insert(0) += 1;
|
|
||||||
}
|
|
||||||
counts
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Python `str.split`'s whitespace, which sacrebleu strips before gramming:
|
|
||||||
/// Unicode White_Space plus U+001C..=U+001F.
|
|
||||||
pub(super) fn is_split_space(c: char) -> bool {
|
|
||||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// chrF of `hypothesis` against `reference`, 0 to 100. Beta 2 weights recall,
|
|
||||||
/// so the arguments are not interchangeable. 0 when no order has n-grams on
|
|
||||||
/// both sides.
|
|
||||||
pub fn chrf(hypothesis: &str, reference: &str) -> f64 {
|
|
||||||
let strip = |s: &str| {
|
|
||||||
s.chars()
|
|
||||||
.filter(|c| !is_split_space(*c))
|
|
||||||
.collect::<Vec<char>>()
|
|
||||||
};
|
|
||||||
let (hyp, reference) = (strip(hypothesis), strip(reference));
|
|
||||||
let (mut precision, mut recall, mut orders) = (0.0, 0.0, 0u32);
|
|
||||||
for n in 1..=ORDER {
|
|
||||||
let (hyp_grams, ref_grams) = (grams(&hyp, n), grams(&reference, n));
|
|
||||||
let (hyp_total, ref_total): (u32, u32) =
|
|
||||||
(hyp_grams.values().sum(), ref_grams.values().sum());
|
|
||||||
if hyp_total == 0 || ref_total == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let matched: u32 = hyp_grams
|
|
||||||
.iter()
|
|
||||||
.map(|(gram, count)| (*count).min(ref_grams.get(gram).copied().unwrap_or(0)))
|
|
||||||
.sum();
|
|
||||||
precision += f64::from(matched) / f64::from(hyp_total);
|
|
||||||
recall += f64::from(matched) / f64::from(ref_total);
|
|
||||||
orders += 1;
|
|
||||||
}
|
|
||||||
if orders == 0 {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
let (p, r) = (precision / f64::from(orders), recall / f64::from(orders));
|
|
||||||
if p + r == 0.0 {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
100.0 * (1.0 + BETA_SQ) * p * r / (BETA_SQ * p + r)
|
|
||||||
}
|
|
||||||
|
|
@ -1,167 +0,0 @@
|
||||||
//! Leak diagnostics: values reported beside scores, never refusals. Pooled
|
|
||||||
//! coverage at n >= 2 above zero beside single-word glosses, or a high pairwise
|
|
||||||
//! chrF, means a flow bug or a corpus duplicate across splits.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use super::chrf::chrf;
|
|
||||||
use super::words::words;
|
|
||||||
use crate::corpus::CorpusItem;
|
|
||||||
use crate::split::{Split, SplitScheme};
|
|
||||||
|
|
||||||
/// Word n-gram orders read, 1 to this.
|
|
||||||
const ORDERS: usize = 3;
|
|
||||||
|
|
||||||
/// The pair that reached the highest chrF.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct PairChrf {
|
|
||||||
pub chrf: f64,
|
|
||||||
pub minted: String,
|
|
||||||
pub item: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One word-order's pooled novel coverage over a split's items.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct OrderCoverage {
|
|
||||||
pub n: usize,
|
|
||||||
/// Distinct n-grams of the split's items absent from Train, summed over items.
|
|
||||||
pub novel: usize,
|
|
||||||
/// Of those, the ones that occur in the minted text.
|
|
||||||
pub covered: usize,
|
|
||||||
/// `covered / novel`; `None` when `novel` is 0, never NaN.
|
|
||||||
pub share: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The item that read most at `n` >= 2.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct WorstItem {
|
|
||||||
pub item: String,
|
|
||||||
pub n: usize,
|
|
||||||
pub covered: usize,
|
|
||||||
pub novel: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One held-out split's readings.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Default)]
|
|
||||||
pub struct SplitLeak {
|
|
||||||
/// Items of the split.
|
|
||||||
pub items: usize,
|
|
||||||
/// Max chrF of any minted string (hypothesis) against any item (reference).
|
|
||||||
pub max_chrf: Option<PairChrf>,
|
|
||||||
/// Pooled novel coverage for n in 1..=3, in order.
|
|
||||||
pub coverage_by_n: Vec<OrderCoverage>,
|
|
||||||
/// The item and order (n >= 2) with the largest covered count, then the
|
|
||||||
/// larger share; the first item, then the smaller n, on ties. `None` when
|
|
||||||
/// no item has a covered n-gram at n >= 2.
|
|
||||||
pub worst: Option<WorstItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The distinct word n-grams of a text for each order 1..=ORDERS, over its
|
|
||||||
/// normalised word segments.
|
|
||||||
fn grams(text: &str) -> Vec<HashSet<String>> {
|
|
||||||
let keys = words(text);
|
|
||||||
(1..=ORDERS)
|
|
||||||
.map(|n| keys.windows(n).map(|w| w.join(" ")).collect())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn union<'a>(texts: impl Iterator<Item = &'a str>) -> Vec<HashSet<String>> {
|
|
||||||
let mut all = vec![HashSet::new(); ORDERS];
|
|
||||||
for text in texts {
|
|
||||||
for (into, from) in all.iter_mut().zip(grams(text)) {
|
|
||||||
into.extend(from);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
all
|
|
||||||
}
|
|
||||||
|
|
||||||
fn split_leak(
|
|
||||||
minted: &[&str],
|
|
||||||
train: &[HashSet<String>],
|
|
||||||
minted_grams: &[HashSet<String>],
|
|
||||||
items: &[&CorpusItem],
|
|
||||||
) -> SplitLeak {
|
|
||||||
let mut leak = SplitLeak {
|
|
||||||
items: items.len(),
|
|
||||||
..SplitLeak::default()
|
|
||||||
};
|
|
||||||
let mut totals = [(0usize, 0usize); ORDERS];
|
|
||||||
for item in items {
|
|
||||||
for m in minted {
|
|
||||||
let score = chrf(m, &item.text);
|
|
||||||
if leak.max_chrf.as_ref().is_none_or(|best| score > best.chrf) {
|
|
||||||
leak.max_chrf = Some(PairChrf {
|
|
||||||
chrf: score,
|
|
||||||
minted: (*m).to_string(),
|
|
||||||
item: item.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (i, item_grams) in grams(&item.text).iter().enumerate() {
|
|
||||||
let novel: Vec<&String> = item_grams
|
|
||||||
.iter()
|
|
||||||
.filter(|g| !train[i].contains(*g))
|
|
||||||
.collect();
|
|
||||||
let covered = novel
|
|
||||||
.iter()
|
|
||||||
.filter(|g| minted_grams[i].contains(**g))
|
|
||||||
.count();
|
|
||||||
totals[i].0 += novel.len();
|
|
||||||
totals[i].1 += covered;
|
|
||||||
if i == 0 || covered == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let share = covered as f64 / novel.len() as f64;
|
|
||||||
let better = leak.worst.as_ref().is_none_or(|w| {
|
|
||||||
covered > w.covered
|
|
||||||
|| (covered == w.covered && share > w.covered as f64 / w.novel as f64)
|
|
||||||
});
|
|
||||||
if better {
|
|
||||||
leak.worst = Some(WorstItem {
|
|
||||||
item: item.id.clone(),
|
|
||||||
n: i + 1,
|
|
||||||
covered,
|
|
||||||
novel: novel.len(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
leak.coverage_by_n = totals
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, (novel, covered))| OrderCoverage {
|
|
||||||
n: i + 1,
|
|
||||||
novel: *novel,
|
|
||||||
covered: *covered,
|
|
||||||
share: (*novel > 0).then(|| *covered as f64 / *novel as f64),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
leak
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The held-out split `want` read against minted text: Train items are the
|
|
||||||
/// live Train items; the readings are over the live items of `want`.
|
|
||||||
pub(super) fn held_out(minted: &[&str], items: &[CorpusItem], want: Split) -> SplitLeak {
|
|
||||||
let of = |want: Split| -> Vec<&CorpusItem> {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.filter(|i| SplitScheme::V1.live(i) == Some(want))
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
let train = union(of(Split::Train).iter().map(|i| i.text.as_str()));
|
|
||||||
let minted_grams = union(minted.iter().copied());
|
|
||||||
split_leak(minted, &train, &minted_grams, &of(want))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads minted text (inventory glosses, option labels, later ontology text)
|
|
||||||
/// against the Validation items. Per Validation item and for n in 1..=3, its
|
|
||||||
/// word n-grams that occur in no Train item are its novel n-grams; coverage at
|
|
||||||
/// each n is the covered over the novel n-grams summed across the split's
|
|
||||||
/// items (unigrams over all minted strings, longer grams within one string).
|
|
||||||
/// Honest single-word glosses saturate n = 1, so the leak signature is pooled
|
|
||||||
/// n >= 2 and the worst item at n >= 2. Train items are not measured; withdrawn
|
|
||||||
/// items and items in no split are dropped. Test is read only through
|
|
||||||
/// `TestReadings`.
|
|
||||||
pub fn leak_diagnostic(minted: &[&str], items: &[CorpusItem]) -> SplitLeak {
|
|
||||||
held_out(minted, items, Split::Validation)
|
|
||||||
}
|
|
||||||
|
|
@ -1,113 +0,0 @@
|
||||||
//! The meaning metric's embedding port and its Ollama adapter.
|
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail, ensure};
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
/// Sentence embeddings. Every embedder (Ollama now, a style embedder later)
|
|
||||||
/// enters the scorer through this port.
|
|
||||||
pub trait Embedder {
|
|
||||||
fn model(&self) -> &str;
|
|
||||||
/// One vector per text, in order, all of one dimension.
|
|
||||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Cosine similarity. Precondition: `a` and `b` have one equal nonzero length
|
|
||||||
/// and nonzero norm; `Scorer::score` refuses embedder output that does not.
|
|
||||||
/// Violating it panics rather than reading as a score.
|
|
||||||
pub fn cosine(a: &[f32], b: &[f32]) -> f64 {
|
|
||||||
assert!(
|
|
||||||
!a.is_empty() && a.len() == b.len(),
|
|
||||||
"cosine needs vectors of one nonzero length, got {} and {}",
|
|
||||||
a.len(),
|
|
||||||
b.len()
|
|
||||||
);
|
|
||||||
let dot: f64 = a
|
|
||||||
.iter()
|
|
||||||
.zip(b)
|
|
||||||
.map(|(x, y)| f64::from(*x) * f64::from(*y))
|
|
||||||
.sum();
|
|
||||||
let norm = |v: &[f32]| v.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>().sqrt();
|
|
||||||
let denom = norm(a) * norm(b);
|
|
||||||
assert!(denom > 0.0, "cosine of a zero vector");
|
|
||||||
dot / denom
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ollama's `/api/embed` over plain HTTP. One server serves Huginn and the
|
|
||||||
/// loop, so batches stay small and `num_thread` is sent (without it a batch of
|
|
||||||
/// 32 timed out at 120 s under host load).
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct OllamaEmbedder {
|
|
||||||
pub url: String,
|
|
||||||
pub model: String,
|
|
||||||
/// Sent as `options.num_thread`; omitted when `None`.
|
|
||||||
pub num_thread: Option<u32>,
|
|
||||||
/// Texts per request, clamped to 1..=32.
|
|
||||||
pub batch: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OllamaEmbedder {
|
|
||||||
pub const MAX_BATCH: usize = 32;
|
|
||||||
|
|
||||||
pub fn new(url: impl Into<String>, model: impl Into<String>) -> Self {
|
|
||||||
Self {
|
|
||||||
url: url.into(),
|
|
||||||
model: model.into(),
|
|
||||||
num_thread: Some(8),
|
|
||||||
batch: Self::MAX_BATCH,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request(&self, agent: &ureq::Agent, batch: &[&str]) -> Result<Vec<Vec<f32>>> {
|
|
||||||
let mut body = json!({ "model": self.model, "input": batch });
|
|
||||||
if let Some(threads) = self.num_thread {
|
|
||||||
body["options"] = json!({ "num_thread": threads });
|
|
||||||
}
|
|
||||||
let endpoint = format!("{}/api/embed", self.url.trim_end_matches('/'));
|
|
||||||
let mut response = agent
|
|
||||||
.post(&endpoint)
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.send(body.to_string())
|
|
||||||
.with_context(|| format!("POST {endpoint}"))?;
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Reply {
|
|
||||||
embeddings: Vec<Vec<f32>>,
|
|
||||||
}
|
|
||||||
let reply: Reply = serde_json::from_str(&response.body_mut().read_to_string()?)
|
|
||||||
.context("ollama /api/embed reply")?;
|
|
||||||
ensure!(
|
|
||||||
reply.embeddings.len() == batch.len(),
|
|
||||||
"asked for {} embeddings, got {}",
|
|
||||||
batch.len(),
|
|
||||||
reply.embeddings.len()
|
|
||||||
);
|
|
||||||
Ok(reply.embeddings)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Embedder for OllamaEmbedder {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
&self.model
|
|
||||||
}
|
|
||||||
|
|
||||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
|
|
||||||
if texts.is_empty() {
|
|
||||||
return Ok(Vec::new());
|
|
||||||
}
|
|
||||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
|
||||||
.timeout_global(Some(Duration::from_secs(120)))
|
|
||||||
.build()
|
|
||||||
.into();
|
|
||||||
let mut out: Vec<Vec<f32>> = Vec::with_capacity(texts.len());
|
|
||||||
for batch in texts.chunks(self.batch.clamp(1, Self::MAX_BATCH)) {
|
|
||||||
out.extend(self.request(&agent, batch)?);
|
|
||||||
}
|
|
||||||
let dim = out[0].len();
|
|
||||||
if dim == 0 || out.iter().any(|v| v.len() != dim) {
|
|
||||||
bail!("embeddings disagree on dimension");
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,363 +0,0 @@
|
||||||
//! What a score counts: chrF and the meaning cosine of the whole lowered
|
|
||||||
//! output against the whole reference. Nothing is deleted, hidden or replaced
|
|
||||||
//! before either is read, and the scorer takes no input from a packet, so no
|
|
||||||
//! text the output carries can raise a score except by resembling the
|
|
||||||
//! reference. No door judges text; the diagnostics report. The round path
|
|
||||||
//! (`aggregate`, `leak_diagnostic`) reads Train and Validation; Test is read
|
|
||||||
//! only through `TestReadings::at_checkpoint` (convergence-test).
|
|
||||||
|
|
||||||
mod chrf;
|
|
||||||
mod diagnostics;
|
|
||||||
mod embed;
|
|
||||||
mod words;
|
|
||||||
|
|
||||||
use anyhow::{Result, ensure};
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
pub use chrf::{CHRF_VERSION, chrf};
|
|
||||||
pub use diagnostics::{OrderCoverage, PairChrf, SplitLeak, WorstItem, leak_diagnostic};
|
|
||||||
pub use embed::{Embedder, OllamaEmbedder, cosine};
|
|
||||||
|
|
||||||
use crate::corpus::CorpusItem;
|
|
||||||
use crate::split::{Checkpoint, Split, SplitScheme};
|
|
||||||
|
|
||||||
/// One reference/output pair; both are scored whole.
|
|
||||||
pub struct ScoreInput<'a> {
|
|
||||||
pub reference: &'a str,
|
|
||||||
pub output: &'a str,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct ItemScore {
|
|
||||||
/// chrF of the output against the reference.
|
|
||||||
pub chrf: f64,
|
|
||||||
/// Embedding cosine of the output and the reference; `None` when either
|
|
||||||
/// is empty after trimming.
|
|
||||||
pub meaning: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Scorer<E: Embedder> {
|
|
||||||
embedder: E,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every vector has one nonzero length and a nonzero norm.
|
|
||||||
fn check_vectors(vectors: &[Vec<f32>]) -> Result<()> {
|
|
||||||
let dim = vectors.first().map_or(0, Vec::len);
|
|
||||||
for vector in vectors {
|
|
||||||
ensure!(
|
|
||||||
dim > 0 && vector.len() == dim,
|
|
||||||
"embedder returned vectors of length {} and {}",
|
|
||||||
dim,
|
|
||||||
vector.len()
|
|
||||||
);
|
|
||||||
let norm: f64 = vector.iter().map(|x| f64::from(*x).powi(2)).sum();
|
|
||||||
ensure!(
|
|
||||||
norm > 0.0 && norm.is_finite(),
|
|
||||||
"embedder returned a zero or non-finite vector"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<E: Embedder> Scorer<E> {
|
|
||||||
pub fn new(embedder: E) -> Self {
|
|
||||||
Self { embedder }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn embedder(&self) -> &E {
|
|
||||||
&self.embedder
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Scores every input with one embed call; the caller chunks `inputs`.
|
|
||||||
/// Errs when the embedder's vectors disagree in length or are empty or zero.
|
|
||||||
pub fn score(&self, inputs: &[ScoreInput<'_>]) -> Result<Vec<ItemScore>> {
|
|
||||||
let mut texts: Vec<&str> = Vec::new();
|
|
||||||
let slots: Vec<Option<usize>> = inputs
|
|
||||||
.iter()
|
|
||||||
.map(|input| {
|
|
||||||
if input.output.trim().is_empty() || input.reference.trim().is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
texts.push(input.reference);
|
|
||||||
texts.push(input.output);
|
|
||||||
Some(texts.len() - 2)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let vectors = self.embedder.embed(&texts)?;
|
|
||||||
ensure!(
|
|
||||||
vectors.len() == texts.len(),
|
|
||||||
"embedder returned {} vectors for {} texts",
|
|
||||||
vectors.len(),
|
|
||||||
texts.len()
|
|
||||||
);
|
|
||||||
check_vectors(&vectors)?;
|
|
||||||
Ok(inputs
|
|
||||||
.iter()
|
|
||||||
.zip(slots)
|
|
||||||
.map(|(input, slot)| ItemScore {
|
|
||||||
chrf: chrf(input.output, input.reference),
|
|
||||||
meaning: slot.map(|i| cosine(&vectors[i], &vectors[i + 1])),
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mean scores of one derived split.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct SplitMean {
|
|
||||||
pub count: usize,
|
|
||||||
/// `None` when the split has no items.
|
|
||||||
pub chrf: Option<f64>,
|
|
||||||
/// Mean over the items that have a meaning score; `None` when none do.
|
|
||||||
pub meaning: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The round readings a round record may hold. The scorer decides when Test
|
|
||||||
/// can be read, by type: `Aggregate` has no Test field.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// let agg = weksa::score::aggregate(&[]);
|
|
||||||
/// let _ = agg.validation;
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// let agg = weksa::score::aggregate(&[]);
|
|
||||||
/// let _ = agg.test;
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, Default)]
|
|
||||||
pub struct Aggregate {
|
|
||||||
pub train: SplitMean,
|
|
||||||
pub validation: SplitMean,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The scores of the items read in split `want`, in list order.
|
|
||||||
fn scores_in<'a>(scored: &'a [(&CorpusItem, ItemScore)], want: Split) -> Vec<&'a ItemScore> {
|
|
||||||
scored
|
|
||||||
.iter()
|
|
||||||
.filter(|(item, _)| SplitScheme::V1.live(item) == Some(want))
|
|
||||||
.map(|(_, score)| score)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The mean of the scores of the items read in split `want`.
|
|
||||||
fn split_mean(scored: &[(&CorpusItem, ItemScore)], want: Split) -> SplitMean {
|
|
||||||
let of = scores_in(scored, want);
|
|
||||||
let average = |values: Vec<f64>| {
|
|
||||||
(!values.is_empty()).then(|| values.iter().sum::<f64>() / values.len() as f64)
|
|
||||||
};
|
|
||||||
SplitMean {
|
|
||||||
count: of.len(),
|
|
||||||
chrf: average(of.iter().map(|s| s.chrf).collect()),
|
|
||||||
meaning: average(of.iter().filter_map(|s| s.meaning).collect()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Groups scores by the split each item is read in. Items read in no split
|
|
||||||
/// (withdrawn, or model-written in a Test group) are counted nowhere.
|
|
||||||
pub fn aggregate(scored: &[(&CorpusItem, ItemScore)]) -> Aggregate {
|
|
||||||
Aggregate {
|
|
||||||
train: split_mean(scored, Split::Train),
|
|
||||||
validation: split_mean(scored, Split::Validation),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Validation items' scores in list order, numbers only: no key, no text.
|
|
||||||
/// A refused item arrives scored 0 and keeps its position.
|
|
||||||
pub fn validation_items(scored: &[(&CorpusItem, ItemScore)]) -> Vec<ItemScore> {
|
|
||||||
scores_in(scored, Split::Validation).into_iter().cloned().collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Test split's readings, scalars only: no item key, no minted string, no
|
|
||||||
/// pair. The checkpoint decision (convergence-test) needs numbers; a key beside
|
|
||||||
/// a minted string is the handle an edit step would act on. The only producer
|
|
||||||
/// is `at_checkpoint`, which consumes a `Checkpoint`; only the lib can make one.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// fn f(t: TestReadings) -> usize { t.count() }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// fn f(t: TestReadings) { let _u = t.clone(); }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// fn f(t: TestReadings) { let _ = format!("{t:?}"); }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// fn s<T: serde::Serialize>(_: &T) {}
|
|
||||||
/// fn f(t: TestReadings) { s(&t); }
|
|
||||||
/// ```
|
|
||||||
pub struct TestReadings {
|
|
||||||
mean: SplitMean,
|
|
||||||
leak: SplitLeak,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TestReadings {
|
|
||||||
/// Reads the live Test items against the scores and the minted strings,
|
|
||||||
/// by the same `split_leak` method the Validation reading uses. The
|
|
||||||
/// checkpoint is spent.
|
|
||||||
pub fn at_checkpoint(
|
|
||||||
checkpoint: Checkpoint,
|
|
||||||
scored: &[(&CorpusItem, ItemScore)],
|
|
||||||
minted: &[&str],
|
|
||||||
items: &[CorpusItem],
|
|
||||||
) -> TestReadings {
|
|
||||||
let _spent = checkpoint;
|
|
||||||
TestReadings {
|
|
||||||
mean: split_mean(scored, Split::Test),
|
|
||||||
leak: diagnostics::held_out(minted, items, Split::Test),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Scored Test items.
|
|
||||||
pub fn count(&self) -> usize {
|
|
||||||
self.mean.count
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn chrf(&self) -> Option<f64> {
|
|
||||||
self.mean.chrf
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn meaning(&self) -> Option<f64> {
|
|
||||||
self.mean.meaning
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test items in the leak reading.
|
|
||||||
pub fn items(&self) -> usize {
|
|
||||||
self.leak.items
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The highest chrF of any minted string against any Test item; the score
|
|
||||||
/// only, never the pair.
|
|
||||||
pub fn max_chrf(&self) -> Option<f64> {
|
|
||||||
self.leak.max_chrf.as_ref().map(|p| p.chrf)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn coverage_by_n(&self) -> &[OrderCoverage] {
|
|
||||||
&self.leak.coverage_by_n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use crate::split::fixture::{group_in, item};
|
|
||||||
|
|
||||||
const HELD_OUT: &str = "extraordinary lighthouse keepers whispered unforgettable stories throughout midnight thunderstorms before surrendering peacefully";
|
|
||||||
const UNRELATED: &str = "harbor ledgers record ordinary tides";
|
|
||||||
|
|
||||||
fn score(chrf: f64, meaning: Option<f64>) -> ItemScore {
|
|
||||||
ItemScore { chrf, meaning }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn in_split(key: &str, text: &str, split: Split, model: bool) -> CorpusItem {
|
|
||||||
item(key, text, &group_in(split), model)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn validation_items_keeps_validation_only_in_order() {
|
|
||||||
let train = in_split("item:t:1", UNRELATED, Split::Train, false);
|
|
||||||
let first = in_split("item:v:1", "first words", Split::Validation, false);
|
|
||||||
let refused = in_split("item:v:2", "second words", Split::Validation, false);
|
|
||||||
let last = in_split("item:v:3", "third words", Split::Validation, false);
|
|
||||||
let mut gone = in_split("item:v:4", "withdrawn words", Split::Validation, false);
|
|
||||||
gone.withdrawn = true;
|
|
||||||
let test = in_split("item:c:1", HELD_OUT, Split::Test, false);
|
|
||||||
let scored = [
|
|
||||||
(&train, score(10.0, Some(0.1))),
|
|
||||||
(&first, score(40.0, Some(0.4))),
|
|
||||||
(&test, score(60.0, Some(0.6))),
|
|
||||||
(&refused, score(0.0, Some(0.0))),
|
|
||||||
(&gone, score(90.0, Some(0.9))),
|
|
||||||
(&last, score(80.0, None)),
|
|
||||||
];
|
|
||||||
let got = validation_items(&scored);
|
|
||||||
assert_eq!(
|
|
||||||
got,
|
|
||||||
[score(40.0, Some(0.4)), score(0.0, Some(0.0)), score(80.0, None)]
|
|
||||||
);
|
|
||||||
assert_eq!(got.len(), aggregate(&scored).validation.count);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_readings_at_checkpoint() {
|
|
||||||
let train_item = in_split("item:t:1", UNRELATED, Split::Train, false);
|
|
||||||
let test = in_split("item:c:1", HELD_OUT, Split::Test, false);
|
|
||||||
let test_model = in_split("item:c:2", "model words here", Split::Test, true);
|
|
||||||
let mut gone = in_split("item:c:3", "withdrawn words", Split::Test, false);
|
|
||||||
gone.withdrawn = true;
|
|
||||||
let val = in_split(
|
|
||||||
"item:v:1",
|
|
||||||
"gardening is quiet work",
|
|
||||||
Split::Validation,
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
let items = [
|
|
||||||
train_item.clone(),
|
|
||||||
test.clone(),
|
|
||||||
test_model.clone(),
|
|
||||||
gone.clone(),
|
|
||||||
val.clone(),
|
|
||||||
];
|
|
||||||
let scored = [
|
|
||||||
(&train_item, score(10.0, Some(0.5))),
|
|
||||||
(&val, score(40.0, Some(0.8))),
|
|
||||||
(&test, score(60.0, Some(0.6))),
|
|
||||||
(&test_model, score(100.0, Some(1.0))),
|
|
||||||
(&gone, score(90.0, Some(0.9))),
|
|
||||||
];
|
|
||||||
let t = TestReadings::at_checkpoint(Checkpoint::for_test(2), &scored, &[HELD_OUT], &items);
|
|
||||||
assert_eq!(
|
|
||||||
(t.count(), t.chrf(), t.meaning()),
|
|
||||||
(1, Some(60.0), Some(0.6))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
t.items(),
|
|
||||||
1,
|
|
||||||
"model-written and withdrawn Test items are excluded"
|
|
||||||
);
|
|
||||||
assert!(t.max_chrf().unwrap() > 99.0);
|
|
||||||
assert_eq!(t.coverage_by_n()[2].share, Some(1.0));
|
|
||||||
|
|
||||||
// A minted string that is not the Test text reads low.
|
|
||||||
let t = TestReadings::at_checkpoint(Checkpoint::for_test(2), &scored, &["zzz"], &items);
|
|
||||||
assert!(t.max_chrf().unwrap() < 20.0);
|
|
||||||
assert_eq!(t.coverage_by_n()[2].share, Some(0.0));
|
|
||||||
|
|
||||||
let empty = TestReadings::at_checkpoint(Checkpoint::for_test(2), &[], &[HELD_OUT], &[]);
|
|
||||||
assert_eq!(
|
|
||||||
(empty.count(), empty.chrf(), empty.meaning()),
|
|
||||||
(0, None, None)
|
|
||||||
);
|
|
||||||
assert_eq!((empty.items(), empty.max_chrf()), (0, None));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn validation_and_test_leak_agree_in_method() {
|
|
||||||
// The same text and minted strings, once in Validation and once in
|
|
||||||
// Test, read the same numbers.
|
|
||||||
let words: Vec<&str> = HELD_OUT.split(' ').collect();
|
|
||||||
let chunks: Vec<String> = words.chunks(3).map(|c| c.join(" ")).collect();
|
|
||||||
let minted: Vec<&str> = chunks.iter().map(String::as_str).collect();
|
|
||||||
let train_item = in_split("item:t:1", UNRELATED, Split::Train, false);
|
|
||||||
let v = leak_diagnostic(
|
|
||||||
&minted,
|
|
||||||
&[
|
|
||||||
in_split("item:v:1", HELD_OUT, Split::Validation, false),
|
|
||||||
train_item.clone(),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
let test = in_split("item:c:1", HELD_OUT, Split::Test, false);
|
|
||||||
let t =
|
|
||||||
TestReadings::at_checkpoint(Checkpoint::for_test(1), &[], &minted, &[test, train_item]);
|
|
||||||
assert_eq!(t.items(), v.items);
|
|
||||||
assert_eq!(t.max_chrf(), v.max_chrf.as_ref().map(|p| p.chrf));
|
|
||||||
assert_eq!(t.coverage_by_n(), v.coverage_by_n.as_slice());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
//! The one way the scorer reads words, then NFC and full Unicode case folding.
|
|
||||||
//! The novel-coverage diagnostic reads text through here, so every script is
|
|
||||||
//! treated by one rule.
|
|
||||||
//!
|
|
||||||
//! A word is a run of word characters: alphanumerics, combining marks and the
|
|
||||||
//! joiners ZWNJ and ZWJ. Any other character ends it, so `kick:the:bucket`,
|
|
||||||
//! `kick·the·bucket`, `kick_the_bucket` and `kick'the'bucket` read as
|
|
||||||
//! `kick the bucket`, as does `kickTheBucket` (a lowercase-to-uppercase
|
|
||||||
//! transition also ends a word).
|
|
||||||
//!
|
|
||||||
//! Han, kana, Thai, Lao, Khmer and Burmese write no word boundaries, and the
|
|
||||||
//! scorer holds no dictionary to find them. A run of those characters is one
|
|
||||||
//! word, never one word per character: per-character words would make every
|
|
||||||
//! honest single-word gloss share bigrams with a held-out sentence, which is
|
|
||||||
//! the leak signature. A change between such a run and any other script also
|
|
||||||
//! ends a word. The n >= 2 coverage signature is therefore blind on these
|
|
||||||
//! scripts: a leak there shows at n = 1 and in max pairwise chrF, which is
|
|
||||||
//! character n-grams and script-blind. A dictionary segmenter is follow-up
|
|
||||||
//! `ja-word-segmenter`.
|
|
||||||
|
|
||||||
use caseless::default_case_fold_str;
|
|
||||||
use unicode_normalization::UnicodeNormalization;
|
|
||||||
use unicode_normalization::char::is_combining_mark;
|
|
||||||
|
|
||||||
/// NFC, then full default case folding.
|
|
||||||
pub(super) fn normalise(s: &str) -> String {
|
|
||||||
default_case_fold_str(&s.nfc().collect::<String>())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_joiner(c: char) -> bool {
|
|
||||||
matches!(c, '\u{200c}' | '\u{200d}')
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A character that belongs inside a word. Marks must stay: Thai vowels and
|
|
||||||
/// tone marks, Hindi vowel signs and Hangul jamo are not alphanumeric.
|
|
||||||
fn is_word_char(c: char) -> bool {
|
|
||||||
c.is_alphanumeric() || is_combining_mark(c) || is_joiner(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Han, kana, Thai, Lao, Khmer and Burmese: scripts written without spaces.
|
|
||||||
fn is_unspaced(c: char) -> bool {
|
|
||||||
matches!(
|
|
||||||
c,
|
|
||||||
'\u{3005}'
|
|
||||||
| '\u{3007}'
|
|
||||||
| '\u{3021}'..='\u{3029}'
|
|
||||||
| '\u{3038}'..='\u{303b}'
|
|
||||||
| '\u{3041}'..='\u{30ff}'
|
|
||||||
| '\u{3400}'..='\u{4dbf}'
|
|
||||||
| '\u{4e00}'..='\u{9fff}'
|
|
||||||
| '\u{f900}'..='\u{fad9}'
|
|
||||||
| '\u{ff66}'..='\u{ff9f}'
|
|
||||||
| '\u{31f0}'..='\u{31ff}'
|
|
||||||
| '\u{20000}'..='\u{323af}'
|
|
||||||
| '\u{0e01}'..='\u{0e5b}'
|
|
||||||
| '\u{0e81}'..='\u{0edf}'
|
|
||||||
| '\u{1000}'..='\u{109f}'
|
|
||||||
| '\u{1780}'..='\u{17ff}'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The normalised words of `text` in order; runs with no alphanumeric char
|
|
||||||
/// (marks alone, say) are dropped.
|
|
||||||
pub(super) fn words(text: &str) -> Vec<String> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
let mut start = 0;
|
|
||||||
let mut previous: Option<char> = None;
|
|
||||||
let end = |from: usize, to: usize, out: &mut Vec<String>| {
|
|
||||||
let word = &text[from..to];
|
|
||||||
if word.chars().any(char::is_alphanumeric) {
|
|
||||||
out.push(normalise(word));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (at, c) in text.char_indices() {
|
|
||||||
if !is_word_char(c) {
|
|
||||||
end(start, at, &mut out);
|
|
||||||
start = at + c.len_utf8();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// a mark or joiner belongs to the character before it
|
|
||||||
let attached = is_combining_mark(c) || is_joiner(c);
|
|
||||||
let breaks = !attached
|
|
||||||
&& previous.is_some_and(|p| {
|
|
||||||
(p.is_lowercase() && c.is_uppercase()) || is_unspaced(p) != is_unspaced(c)
|
|
||||||
});
|
|
||||||
if breaks {
|
|
||||||
end(start, at, &mut out);
|
|
||||||
start = at;
|
|
||||||
}
|
|
||||||
if !attached {
|
|
||||||
previous = Some(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
end(start, text.len(), &mut out);
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
@ -1,134 +0,0 @@
|
||||||
//! The speaker-state documents: a speaker's stable axes and a scene's relations.
|
|
||||||
//! Both are append-only revisions under one key per revision and hold typed
|
|
||||||
//! feature values only, never text (ruling `leak-owned-by-flow-and-scorer-3`).
|
|
||||||
//! `SpeakerStateStore` is their only writer; `LoweringInput::with_scene` is the
|
|
||||||
//! only reader that reaches a lowering view.
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::corpus::ModelFamily;
|
|
||||||
use crate::packet::{EntityId, FeatureValue};
|
|
||||||
|
|
||||||
/// The most participants one scene holds.
|
|
||||||
pub const MAX_PARTICIPANTS: usize = 64;
|
|
||||||
|
|
||||||
/// Who annotated a document. A model's generator is an attestation string, held
|
|
||||||
/// to the same form as every provenance string.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Annotator {
|
|
||||||
Operator,
|
|
||||||
Model {
|
|
||||||
family: ModelFamily,
|
|
||||||
generator: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The speaker's stable axes. Key `speaker:<entity slug>@<n>`; a revision
|
|
||||||
/// appends and never edits.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.speaker")]
|
|
||||||
pub struct Speaker {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub entity: EntityId,
|
|
||||||
/// The revision, from 1.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub n: u32,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub inventory_rev: u32,
|
|
||||||
/// Feature values of slot `Speaker`.
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub annotator: Annotator,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The other party of a relation. `Unnamed` is an addressee the scene does not
|
|
||||||
/// name, such as the player or a crowd.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub enum Party {
|
|
||||||
Named(EntityId),
|
|
||||||
Unnamed,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The speaker's relation to one party: feature values of slot `Scene`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct PairRelation {
|
|
||||||
pub from: EntityId,
|
|
||||||
pub to: Party,
|
|
||||||
pub features: Vec<FeatureValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A scene: its participants and the relations between them. Key
|
|
||||||
/// `scene:<group>@<n>`; a revision appends and never edits.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "weksa.scene")]
|
|
||||||
pub struct Scene {
|
|
||||||
/// The corpus split group of the scene, a slug.
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub group: String,
|
|
||||||
/// The revision, from 1.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub n: u32,
|
|
||||||
/// The revision, of the inventory the scene was admitted through, at which
|
|
||||||
/// `put_scene` read its features: provenance only; a run never reads it.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub inventory_rev: u32,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub participants: Vec<EntityId>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub relations: Vec<PairRelation>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub annotator: Annotator,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Scene {
|
|
||||||
/// The first of `speakers` the scene does not list as a participant: the
|
|
||||||
/// one rule of scene coverage, applied where a scene is put and where it is
|
|
||||||
/// read.
|
|
||||||
pub fn uncovered<'a>(
|
|
||||||
&self,
|
|
||||||
speakers: impl IntoIterator<Item = &'a EntityId>,
|
|
||||||
) -> Option<&'a EntityId> {
|
|
||||||
speakers
|
|
||||||
.into_iter()
|
|
||||||
.find(|s| !self.participants.contains(s))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The features of the relation from `speaker` to the named `addressee`, or
|
|
||||||
/// to `Unnamed` when there is none; `None` when the scene holds no such
|
|
||||||
/// relation (a relation with no features is `Some(&[])`). A named
|
|
||||||
/// addressee the scene lacks never falls back to `Unnamed`.
|
|
||||||
pub fn relation(
|
|
||||||
&self,
|
|
||||||
speaker: &EntityId,
|
|
||||||
addressee: Option<&EntityId>,
|
|
||||||
) -> Option<&[FeatureValue]> {
|
|
||||||
self.relations
|
|
||||||
.iter()
|
|
||||||
.find(|r| {
|
|
||||||
&r.from == speaker
|
|
||||||
&& match (&r.to, addressee) {
|
|
||||||
(Party::Named(a), Some(b)) => a == b,
|
|
||||||
(Party::Unnamed, None) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.map(|r| r.features.as_slice())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `speaker:<entity slug>@<n>`.
|
|
||||||
pub fn speaker_key(entity: &EntityId, n: u32) -> String {
|
|
||||||
let slug = entity
|
|
||||||
.as_str()
|
|
||||||
.strip_prefix("entity:")
|
|
||||||
.unwrap_or(entity.as_str());
|
|
||||||
format!("speaker:{slug}@{n}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `scene:<group>@<n>`.
|
|
||||||
pub fn scene_key(group: &str, n: u32) -> String {
|
|
||||||
format!("scene:{group}@{n}")
|
|
||||||
}
|
|
||||||
|
|
@ -1,223 +0,0 @@
|
||||||
//! The train/validation/test split is derived from an item's group and nothing
|
|
||||||
//! else. No stored assignment exists, so no writer can reassign one. An item is
|
|
||||||
//! read in its live split. The round path (round records, prompts, `aggregate`,
|
|
||||||
//! `leak_diagnostic`) carries no Test reading; a typed `TestReadings` and a Test
|
|
||||||
//! `EncoderOffer` need a Checkpoint, and only the lib can make one
|
|
||||||
//! (convergence-freeze adds the door). Operator tools (`weksa corpus dump`,
|
|
||||||
//! `weksa score`, `CorpusStore`) read corpus text of any split; that is not
|
|
||||||
//! gated here.
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
|
|
||||||
use crate::corpus::{CorpusItem, Source};
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Split {
|
|
||||||
Train,
|
|
||||||
Validation,
|
|
||||||
Test,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A scheme is a constant; a new scheme is a new variant, never a reassignment.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum SplitScheme {
|
|
||||||
V1,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn fnv1a64(bytes: &[u8]) -> u64 {
|
|
||||||
fnv1a64_fold(0xcbf2_9ce4_8422_2325, bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FNV-1a 64 of the parts, each preceded by its length as eight little-endian
|
|
||||||
/// bytes, so no two different splits of the same bytes share a digest.
|
|
||||||
pub const fn fnv1a64_of(parts: &[&[u8]]) -> u64 {
|
|
||||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
|
||||||
let mut p = 0;
|
|
||||||
while p < parts.len() {
|
|
||||||
h = fnv1a64_fold(h, &(parts[p].len() as u64).to_le_bytes());
|
|
||||||
h = fnv1a64_fold(h, parts[p]);
|
|
||||||
p += 1;
|
|
||||||
}
|
|
||||||
h
|
|
||||||
}
|
|
||||||
|
|
||||||
const fn fnv1a64_fold(mut h: u64, bytes: &[u8]) -> u64 {
|
|
||||||
let mut i = 0;
|
|
||||||
while i < bytes.len() {
|
|
||||||
h ^= bytes[i] as u64;
|
|
||||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
h
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 16 lowercase hex digits, zero-padded: how a digest is written everywhere.
|
|
||||||
pub(crate) fn hex16(n: u64) -> String {
|
|
||||||
format!("{n:016x}")
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SplitScheme {
|
|
||||||
/// 0..100, FNV-1a 64 of `weksa-split-v1:` + group, mod 100.
|
|
||||||
pub fn bucket(self, group: &str) -> u64 {
|
|
||||||
match self {
|
|
||||||
SplitScheme::V1 => fnv1a64(format!("weksa-split-v1:{group}").as_bytes()) % 100,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <40 Train, <80 Validation, else Test.
|
|
||||||
pub fn of_bucket(self, bucket: u64) -> Split {
|
|
||||||
match self {
|
|
||||||
SplitScheme::V1 if bucket < 40 => Split::Train,
|
|
||||||
SplitScheme::V1 if bucket < 80 => Split::Validation,
|
|
||||||
SplitScheme::V1 => Split::Test,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The split of an item: its group's, except that a model-written item of a
|
|
||||||
/// test group is in no split. It is never moved to train: a model line of
|
|
||||||
/// the test meaning would teach the test.
|
|
||||||
pub fn split(self, item: &CorpusItem) -> Option<Split> {
|
|
||||||
match self.of_bucket(self.bucket(&item.group)) {
|
|
||||||
Split::Test if matches!(item.source, Source::ModelWritten { .. }) => None,
|
|
||||||
split => Some(split),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The split an item is read in; a withdrawn item is read in none.
|
|
||||||
pub fn live(self, item: &CorpusItem) -> Option<Split> {
|
|
||||||
if item.withdrawn {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
self.split(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Permission to read Test once, as typed `TestReadings` or as Test
|
|
||||||
/// `EncoderOffer`s. Only the weksa lib can make one: there is no public
|
|
||||||
/// constructor, so no code outside it can obtain those. This is not a seal on
|
|
||||||
/// corpus text: operator tools and `CorpusStore` can read any item, and the
|
|
||||||
/// guarded invariant is that the round path holds no Test reading. The one door
|
|
||||||
/// is added by
|
|
||||||
/// convergence-freeze, which builds a `Checkpoint` from the convergence window
|
|
||||||
/// over the run's persisted round records (convergence-test).
|
|
||||||
/// `TestReadings::at_checkpoint` consumes it, so one `Checkpoint` buys one Test
|
|
||||||
/// reading. One `Checkpoint` also offers each item at most once
|
|
||||||
/// (`EncoderOffer::for_checkpoint`), and an offer borrows its Checkpoint, so it
|
|
||||||
/// cannot outlive the reading that spends it.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// fn f(c: &weksa::split::Checkpoint) -> u32 { c.round() }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// No public constructor:
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// let _ = weksa::split::Checkpoint::declare(1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// The test constructor is not exported (this doctest names it today; the
|
|
||||||
/// line-based tripwire in `tests/checkpoint_door.rs` catches only common
|
|
||||||
/// single-line forms of a new public constructor):
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// let _ = weksa::split::Checkpoint::for_test(1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// let _ = weksa::split::Checkpoint { round: 1, offered: Default::default() };
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// One reading per checkpoint:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// use weksa::split::Checkpoint;
|
|
||||||
/// fn f(c: Checkpoint) { let _ = TestReadings::at_checkpoint(c, &[], &[], &[]); }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use weksa::score::TestReadings;
|
|
||||||
/// use weksa::split::Checkpoint;
|
|
||||||
/// fn f(c: Checkpoint) {
|
|
||||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
|
||||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn f(c: weksa::split::Checkpoint) { let _ = c.clone(); }
|
|
||||||
/// ```
|
|
||||||
pub struct Checkpoint {
|
|
||||||
round: u32,
|
|
||||||
offered: BTreeSet<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Checkpoint {
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) fn for_test(round: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
round,
|
|
||||||
offered: BTreeSet::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Records `key` as offered; false when it already was.
|
|
||||||
pub(crate) fn first_offer(&mut self, key: &str) -> bool {
|
|
||||||
self.offered.insert(key.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn round(&self) -> u32 {
|
|
||||||
self.round
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod mutants;
|
|
||||||
|
|
||||||
/// Item builders for the unit tests that live in `src`: the twins of
|
|
||||||
/// `tests/common`'s `group_in_bucket`, `item_in`, `cast` and `model`.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) mod fixture {
|
|
||||||
use super::{Split, SplitScheme};
|
|
||||||
use crate::corpus::{CorpusItem, ModelFamily, Source};
|
|
||||||
use crate::packet::EntityId;
|
|
||||||
|
|
||||||
/// The first group `g<i>` whose V1 bucket is in `split`.
|
|
||||||
pub(crate) fn group_in(split: Split) -> String {
|
|
||||||
(0..100_000)
|
|
||||||
.map(|i| format!("g{i}"))
|
|
||||||
.find(|g| SplitScheme::V1.of_bucket(SplitScheme::V1.bucket(g)) == split)
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn item(key: &str, text: &str, group: &str, model_written: bool) -> CorpusItem {
|
|
||||||
let source = if model_written {
|
|
||||||
Source::ModelWritten {
|
|
||||||
family: ModelFamily::Unrecorded,
|
|
||||||
generator: None,
|
|
||||||
prompt_digest: None,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Source::CastAuthored {
|
|
||||||
persona: "nibu".into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
author: "Ada Writer".into(),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
CorpusItem {
|
|
||||||
id: key.into(),
|
|
||||||
text: text.into(),
|
|
||||||
language: "en-US".into(),
|
|
||||||
speaker: EntityId::parse("entity:nibu").unwrap(),
|
|
||||||
names: vec![],
|
|
||||||
names_by: None,
|
|
||||||
group: group.into(),
|
|
||||||
prior_turns: vec![],
|
|
||||||
source,
|
|
||||||
admitted_on: "2026-10-29".into(),
|
|
||||||
supersedes: None,
|
|
||||||
withdrawn: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
//! Pins of private items of `split` found unpinned by mutation testing.
|
|
||||||
|
|
||||||
use super::Checkpoint;
|
|
||||||
|
|
||||||
/// A checkpoint reports the round it was declared at, whatever the round.
|
|
||||||
#[test]
|
|
||||||
fn a_checkpoint_reports_its_round() {
|
|
||||||
assert_eq!(Checkpoint::for_test(7).round(), 7);
|
|
||||||
assert_eq!(Checkpoint::for_test(0).round(), 0);
|
|
||||||
assert_eq!(Checkpoint::for_test(1).round(), 1);
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,818 +0,0 @@
|
||||||
//! 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 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..V18: 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`] 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
|
|
||||||
//! bound or read it, and [`LoweringInput`] drops it, so no lowerer sees it.
|
|
||||||
//! Every other slot is an id type, so the lists are the bounded part. What bounds
|
|
||||||
//! each list (V11, V12): a feature list holds at
|
|
||||||
//! most one value per feature id and `extensions` at most one per extension id,
|
|
||||||
//! so each is at most the inventory's ids of that kind; `participants`,
|
|
||||||
//! `audience` and `preserve` hold each node id at most once and every id names
|
|
||||||
//! a node (V4), so each is at most `Packet::MAX_NODES`; a predication's `roles`
|
|
||||||
//! hold each role id at most once, so at most the inventory's roles; and the
|
|
||||||
//! nodes themselves are at most `Packet::MAX_NODES` (V12). Whether a score may
|
|
||||||
//! rise because corpus text reached a packet is owned by the golf loop's
|
|
||||||
//! context builder and the scorer (ruling `leak-owned-by-flow-and-scorer-3`),
|
|
||||||
//! never by a text rule here, in `admit_revision` or in `PacketStore::admit`.
|
|
||||||
|
|
||||||
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::store::{CorpusStore, SpeakerStateStore, StoreError};
|
|
||||||
|
|
||||||
/// A broken rule, named.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Refusal {
|
|
||||||
/// V1: the packet's schema_version is not the one these types define.
|
|
||||||
V1SchemaVersion {
|
|
||||||
found: u32,
|
|
||||||
},
|
|
||||||
/// V2: no referents, predications or relations.
|
|
||||||
V2PayloadRequired,
|
|
||||||
/// V3: a node id repeats across referents and predications.
|
|
||||||
V3DuplicateNode {
|
|
||||||
id: NodeId,
|
|
||||||
},
|
|
||||||
/// V4: a reference names no node.
|
|
||||||
V4DanglingRef {
|
|
||||||
id: NodeId,
|
|
||||||
at: &'static str,
|
|
||||||
},
|
|
||||||
/// V5: an inventory id does not resolve at the packet's revision.
|
|
||||||
V5Unresolved {
|
|
||||||
id: InvId,
|
|
||||||
},
|
|
||||||
/// V6: an inventory id is of the wrong family for its slot.
|
|
||||||
V6WrongFamily {
|
|
||||||
id: InvId,
|
|
||||||
expected: Family,
|
|
||||||
at: &'static str,
|
|
||||||
},
|
|
||||||
/// V7: a feature or extension value does not fit its value kind.
|
|
||||||
V7ValueKind {
|
|
||||||
what: String,
|
|
||||||
},
|
|
||||||
/// V8: a feature is not declared for the slot it sits on.
|
|
||||||
V8NotApplicable {
|
|
||||||
feature: InvId,
|
|
||||||
slot: Slot,
|
|
||||||
},
|
|
||||||
/// V10: the packet's inventory revision has no record.
|
|
||||||
V10UnknownRevision {
|
|
||||||
rev: u32,
|
|
||||||
},
|
|
||||||
/// V11: a feature id repeats in one slot's list (`slot` is `None` for an
|
|
||||||
/// extension id repeated in the packet).
|
|
||||||
V11DuplicateFeature {
|
|
||||||
feature: InvId,
|
|
||||||
slot: Option<Slot>,
|
|
||||||
},
|
|
||||||
/// V11: a node id repeats in `participants`, `audience` or `preserve`
|
|
||||||
/// (`at` names the list).
|
|
||||||
V11DuplicateNodeRef {
|
|
||||||
id: NodeId,
|
|
||||||
at: &'static str,
|
|
||||||
},
|
|
||||||
/// V11: a role id repeats in one predication's roles.
|
|
||||||
V11DuplicateRole {
|
|
||||||
role: InvId,
|
|
||||||
predication: NodeId,
|
|
||||||
},
|
|
||||||
/// V12: more referents, predications and relations than `Packet::MAX_NODES`.
|
|
||||||
V12TooManyNodes {
|
|
||||||
count: usize,
|
|
||||||
max: usize,
|
|
||||||
},
|
|
||||||
/// V14: an addressee consent that no addressee can have given, or that
|
|
||||||
/// names a node that is not a predication. It is what the addressee asked
|
|
||||||
/// for or agreed to, an act, so a referent cannot be its object.
|
|
||||||
V14ConsentWithoutAddressee,
|
|
||||||
V14ConsentNotAPredication {
|
|
||||||
id: NodeId,
|
|
||||||
},
|
|
||||||
/// V15: an addressee consent set by a source that only read wording.
|
|
||||||
/// A decomposition of text, or imported corpus text, sees "you asked her
|
|
||||||
/// to" as words; only authoring or game telemetry saw the request.
|
|
||||||
V15ConsentSource {
|
|
||||||
source: ProvenanceSource,
|
|
||||||
},
|
|
||||||
/// V16: `with_scene` found its group's scene not covering the item's speaker
|
|
||||||
/// or the speaker of some live item of the group.
|
|
||||||
V16SpeakerNotInScene,
|
|
||||||
/// V17: an addressee that names a predication. An act is not someone
|
|
||||||
/// spoken to, so the addressee names a referent.
|
|
||||||
V17AddresseeNotAReferent {
|
|
||||||
id: NodeId,
|
|
||||||
},
|
|
||||||
/// V18: a predication whose frame is the inventory's `request_intervention`,
|
|
||||||
/// with no `addressee_consent` naming it. It says what the addressee did, so
|
|
||||||
/// only the packet's own record may license it.
|
|
||||||
V18RequestWithoutConsent {
|
|
||||||
predication: NodeId,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Refusal {
|
|
||||||
pub fn rule(&self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Refusal::V1SchemaVersion { .. } => "V1",
|
|
||||||
Refusal::V2PayloadRequired => "V2",
|
|
||||||
Refusal::V3DuplicateNode { .. } => "V3",
|
|
||||||
Refusal::V4DanglingRef { .. } => "V4",
|
|
||||||
Refusal::V5Unresolved { .. } => "V5",
|
|
||||||
Refusal::V6WrongFamily { .. } => "V6",
|
|
||||||
Refusal::V7ValueKind { .. } => "V7",
|
|
||||||
Refusal::V8NotApplicable { .. } => "V8",
|
|
||||||
Refusal::V10UnknownRevision { .. } => "V10",
|
|
||||||
Refusal::V11DuplicateFeature { .. }
|
|
||||||
| Refusal::V11DuplicateNodeRef { .. }
|
|
||||||
| Refusal::V11DuplicateRole { .. } => "V11",
|
|
||||||
Refusal::V12TooManyNodes { .. } => "V12",
|
|
||||||
Refusal::V14ConsentWithoutAddressee | Refusal::V14ConsentNotAPredication { .. } => {
|
|
||||||
"V14"
|
|
||||||
}
|
|
||||||
Refusal::V15ConsentSource { .. } => "V15",
|
|
||||||
Refusal::V16SpeakerNotInScene => "V16",
|
|
||||||
Refusal::V17AddresseeNotAReferent { .. } => "V17",
|
|
||||||
Refusal::V18RequestWithoutConsent { .. } => "V18",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for Refusal {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
let what = match self {
|
|
||||||
Refusal::V1SchemaVersion { .. } => "unsupported schema version",
|
|
||||||
Refusal::V2PayloadRequired => "packet has no referents, predications or relations",
|
|
||||||
Refusal::V3DuplicateNode { .. } => "a node id repeats",
|
|
||||||
Refusal::V4DanglingRef { .. } => "a reference names no node",
|
|
||||||
Refusal::V5Unresolved { .. } => {
|
|
||||||
"an inventory id does not resolve at the packet's revision"
|
|
||||||
}
|
|
||||||
Refusal::V6WrongFamily { .. } => "an inventory id is of the wrong family for its slot",
|
|
||||||
Refusal::V7ValueKind { .. } => "a value does not fit its value kind",
|
|
||||||
Refusal::V8NotApplicable { .. } => "a feature is not declared for its slot",
|
|
||||||
Refusal::V10UnknownRevision { .. } => "the inventory revision has no record",
|
|
||||||
Refusal::V11DuplicateFeature { .. } => "a feature id repeats in one list",
|
|
||||||
Refusal::V11DuplicateNodeRef { .. } => "a node id repeats in one list",
|
|
||||||
Refusal::V11DuplicateRole { .. } => "a role id repeats in one predication",
|
|
||||||
Refusal::V12TooManyNodes { .. } => "too many nodes",
|
|
||||||
Refusal::V14ConsentWithoutAddressee => "consent given without an addressee",
|
|
||||||
Refusal::V14ConsentNotAPredication { .. } => "consent names no predication",
|
|
||||||
Refusal::V15ConsentSource { .. } => "consent set by a source that only read wording",
|
|
||||||
Refusal::V16SpeakerNotInScene => {
|
|
||||||
"the scene does not cover the speaker of every live item of its group"
|
|
||||||
}
|
|
||||||
Refusal::V17AddresseeNotAReferent { .. } => "the addressee names no referent",
|
|
||||||
Refusal::V18RequestWithoutConsent { .. } => {
|
|
||||||
"a request frame needs the addressee's consent naming it"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
write!(f, "{}: {what}", self.rule())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `packet` meets the rules under `inventory`. All broken rules are
|
|
||||||
/// returned. A pass carries no lowering view: that comes from
|
|
||||||
/// `PacketStore::admit` only.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use weksa::{Inventory, Refusal, packet::Packet};
|
|
||||||
/// fn judge(p: &Packet, i: &Inventory) -> Result<(), Vec<Refusal>> { weksa::validate(p, i) }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// use weksa::{Inventory, LoweringInput, Refusal, packet::Packet};
|
|
||||||
/// fn lower(p: &Packet, i: &Inventory) -> Result<LoweringInput, Vec<Refusal>> { weksa::validate(p, i) }
|
|
||||||
/// ```
|
|
||||||
pub fn validate(packet: &Packet, inventory: &Inventory) -> Result<(), Vec<Refusal>> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
if packet.schema_version != SCHEMA_VERSION {
|
|
||||||
out.push(Refusal::V1SchemaVersion {
|
|
||||||
found: packet.schema_version,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if packet.referents.is_empty() && packet.predications.is_empty() && packet.relations.is_empty()
|
|
||||||
{
|
|
||||||
out.push(Refusal::V2PayloadRequired);
|
|
||||||
}
|
|
||||||
let count = packet.referents.len() + packet.predications.len() + packet.relations.len();
|
|
||||||
if count > Packet::MAX_NODES {
|
|
||||||
out.push(Refusal::V12TooManyNodes {
|
|
||||||
count,
|
|
||||||
max: Packet::MAX_NODES,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
Inventoried {
|
|
||||||
inv: inventory,
|
|
||||||
rev: packet.inventory_rev,
|
|
||||||
out: &mut out,
|
|
||||||
}
|
|
||||||
.check(packet);
|
|
||||||
check_requests(packet, inventory, &mut out);
|
|
||||||
} else {
|
|
||||||
out.push(Refusal::V10UnknownRevision {
|
|
||||||
rev: packet.inventory_rev,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if out.is_empty() { Ok(()) } else { Err(out) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn check_nodes(packet: &Packet, out: &mut Vec<Refusal>) -> BTreeSet<NodeId> {
|
|
||||||
let mut nodes = BTreeSet::new();
|
|
||||||
let ids = packet
|
|
||||||
.referents
|
|
||||||
.iter()
|
|
||||||
.map(|r| &r.id)
|
|
||||||
.chain(packet.predications.iter().map(|p| &p.id));
|
|
||||||
for id in ids {
|
|
||||||
if !nodes.insert(id.clone()) {
|
|
||||||
out.push(Refusal::V3DuplicateNode { id: id.clone() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nodes
|
|
||||||
}
|
|
||||||
|
|
||||||
fn check_refs(packet: &Packet, nodes: &BTreeSet<NodeId>, out: &mut Vec<Refusal>) {
|
|
||||||
let mut need = |id: &NodeId, at: &'static str| {
|
|
||||||
if !nodes.contains(id) {
|
|
||||||
out.push(Refusal::V4DanglingRef { id: id.clone(), at });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for p in &packet.predications {
|
|
||||||
for r in &p.roles {
|
|
||||||
need(&r.filler, "role filler");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for r in &packet.relations {
|
|
||||||
need(&r.from, "relation from");
|
|
||||||
need(&r.to, "relation to");
|
|
||||||
}
|
|
||||||
if let Some(a) = &packet.discourse.addressee {
|
|
||||||
need(a, "addressee");
|
|
||||||
}
|
|
||||||
if let Some(c) = &packet.discourse.addressee_consent {
|
|
||||||
need(c, "addressee consent");
|
|
||||||
}
|
|
||||||
for (list, at) in node_lists(packet) {
|
|
||||||
for id in list {
|
|
||||||
need(id, at);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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>) {
|
|
||||||
let Some(consent) = &packet.discourse.addressee_consent else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
if packet.discourse.addressee.is_none() {
|
|
||||||
out.push(Refusal::V14ConsentWithoutAddressee);
|
|
||||||
}
|
|
||||||
if nodes.contains(consent) && !packet.predications.iter().any(|p| &p.id == consent) {
|
|
||||||
out.push(Refusal::V14ConsentNotAPredication {
|
|
||||||
id: consent.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
match packet.provenance.source {
|
|
||||||
ProvenanceSource::Authored | ProvenanceSource::GameTelemetry => {}
|
|
||||||
source => out.push(Refusal::V15ConsentSource { source }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The gloss of the inventory frame that reports an addressee's request.
|
|
||||||
const REQUEST_FRAME_GLOSS: &str = "request_intervention";
|
|
||||||
|
|
||||||
/// V18: a predication whose frame, resolved at the packet's revision, is the
|
|
||||||
/// request frame is named by `addressee_consent`. An unresolved frame is V5's.
|
|
||||||
fn check_requests(packet: &Packet, inventory: &Inventory, out: &mut Vec<Refusal>) {
|
|
||||||
for p in &packet.predications {
|
|
||||||
if inventory
|
|
||||||
.resolve(&p.frame, packet.inventory_rev)
|
|
||||||
.is_some_and(|e| e.gloss == REQUEST_FRAME_GLOSS)
|
|
||||||
&& packet.discourse.addressee_consent.as_ref() != Some(&p.id)
|
|
||||||
{
|
|
||||||
out.push(Refusal::V18RequestWithoutConsent {
|
|
||||||
predication: p.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node_lists(packet: &Packet) -> [(&Vec<NodeId>, &'static str); 3] {
|
|
||||||
[
|
|
||||||
(&packet.context.participants, "participant"),
|
|
||||||
(&packet.context.audience, "audience"),
|
|
||||||
(&packet.constraints.preserve, "preserve"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// V11 for the lists that hold nodes and roles: each node id once per node list,
|
|
||||||
/// each role id once per predication.
|
|
||||||
fn check_repeats(packet: &Packet, out: &mut Vec<Refusal>) {
|
|
||||||
for (list, at) in node_lists(packet) {
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
for id in list {
|
|
||||||
if !seen.insert(id) {
|
|
||||||
out.push(Refusal::V11DuplicateNodeRef { id: id.clone(), at });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for p in &packet.predications {
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
for r in &p.roles {
|
|
||||||
if !seen.insert(r.role) {
|
|
||||||
out.push(Refusal::V11DuplicateRole {
|
|
||||||
role: r.role,
|
|
||||||
predication: p.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The inventory-dependent rules V5..V8 and V11, read at the packet's revision.
|
|
||||||
struct Inventoried<'a> {
|
|
||||||
inv: &'a Inventory,
|
|
||||||
rev: u32,
|
|
||||||
out: &'a mut Vec<Refusal>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Inventoried<'a> {
|
|
||||||
fn check(&mut self, p: &Packet) {
|
|
||||||
let Packet {
|
|
||||||
context,
|
|
||||||
discourse,
|
|
||||||
referents,
|
|
||||||
predications,
|
|
||||||
relations,
|
|
||||||
extensions,
|
|
||||||
stance,
|
|
||||||
..
|
|
||||||
} = p;
|
|
||||||
let Context {
|
|
||||||
setting, medium, ..
|
|
||||||
} = context;
|
|
||||||
for id in setting.iter().chain(medium) {
|
|
||||||
self.slot(id, Family::Concept, "context concept");
|
|
||||||
}
|
|
||||||
let Discourse {
|
|
||||||
speech_act,
|
|
||||||
features,
|
|
||||||
..
|
|
||||||
} = discourse;
|
|
||||||
if let Some(id) = speech_act {
|
|
||||||
self.slot(id, Family::SpeechAct, "speech act");
|
|
||||||
}
|
|
||||||
self.features(features, Slot::Discourse);
|
|
||||||
self.features(&stance.features, Slot::Stance);
|
|
||||||
for Referent {
|
|
||||||
kind,
|
|
||||||
concept,
|
|
||||||
features,
|
|
||||||
..
|
|
||||||
} in referents
|
|
||||||
{
|
|
||||||
self.slot(kind, Family::ReferentKind, "referent kind");
|
|
||||||
self.slot(concept, Family::Concept, "referent concept");
|
|
||||||
self.features(features, Slot::Referent);
|
|
||||||
}
|
|
||||||
for Predication {
|
|
||||||
concept,
|
|
||||||
frame,
|
|
||||||
roles,
|
|
||||||
features,
|
|
||||||
..
|
|
||||||
} in predications
|
|
||||||
{
|
|
||||||
self.slot(concept, Family::Concept, "predication concept");
|
|
||||||
self.slot(frame, Family::Frame, "frame");
|
|
||||||
for r in roles {
|
|
||||||
self.slot(&r.role, Family::Role, "role");
|
|
||||||
}
|
|
||||||
self.features(features, Slot::Predication);
|
|
||||||
}
|
|
||||||
for Relation {
|
|
||||||
relation, features, ..
|
|
||||||
} in relations
|
|
||||||
{
|
|
||||||
self.slot(relation, Family::Relation, "relation");
|
|
||||||
self.features(features, Slot::Relation);
|
|
||||||
}
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
for Extension { key, value } in extensions {
|
|
||||||
if !seen.insert(*key) {
|
|
||||||
self.out.push(Refusal::V11DuplicateFeature {
|
|
||||||
feature: *key,
|
|
||||||
slot: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if let Some(entry) = self.slot(key, Family::Extension, "extension")
|
|
||||||
&& !fits(entry.value_kind.as_ref(), value)
|
|
||||||
{
|
|
||||||
self.out.push(Refusal::V7ValueKind {
|
|
||||||
what: key.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// V5, then V6 when it resolved.
|
|
||||||
fn slot(&mut self, id: &InvId, want: Family, at: &'static str) -> Option<&'a InventoryEntry> {
|
|
||||||
let entry = self.resolve(id)?;
|
|
||||||
if entry.family() != want {
|
|
||||||
self.out.push(Refusal::V6WrongFamily {
|
|
||||||
id: *id,
|
|
||||||
expected: want,
|
|
||||||
at,
|
|
||||||
});
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
Some(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve(&mut self, id: &InvId) -> Option<&'a InventoryEntry> {
|
|
||||||
let found = self.inv.resolve(id, self.rev);
|
|
||||||
if found.is_none() {
|
|
||||||
self.out.push(Refusal::V5Unresolved { id: *id });
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
fn features(&mut self, features: &[FeatureValue], slot: Slot) {
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
for f in features {
|
|
||||||
if !seen.insert(f.feature) {
|
|
||||||
self.out.push(Refusal::V11DuplicateFeature {
|
|
||||||
feature: f.feature,
|
|
||||||
slot: Some(slot),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let Some(entry) = self.slot(&f.feature, Family::Feature, "feature") else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if !entry.applies_to.contains(&slot) {
|
|
||||||
self.out.push(Refusal::V8NotApplicable {
|
|
||||||
feature: f.feature,
|
|
||||||
slot,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if !fits(entry.value_kind.as_ref(), &f.value) {
|
|
||||||
self.out.push(Refusal::V7ValueKind {
|
|
||||||
what: f.feature.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one feature check of the speaker-state documents and `with_scene`: V10
|
|
||||||
/// when `rev` has no record, else the rules the packet's own check applies to a
|
|
||||||
/// feature list in `slot` (V5 to V8, V11).
|
|
||||||
pub(crate) fn feature_refusals(
|
|
||||||
inventory: &Inventory,
|
|
||||||
rev: u32,
|
|
||||||
features: &[FeatureValue],
|
|
||||||
slot: Slot,
|
|
||||||
) -> Vec<Refusal> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
if !inventory.has_revision(rev) {
|
|
||||||
out.push(Refusal::V10UnknownRevision { rev });
|
|
||||||
} else {
|
|
||||||
Inventoried {
|
|
||||||
inv: inventory,
|
|
||||||
rev,
|
|
||||||
out: &mut out,
|
|
||||||
}
|
|
||||||
.features(features, slot);
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fits(kind: Option<&ValueKind>, value: &FeatValue) -> bool {
|
|
||||||
match (kind, value) {
|
|
||||||
(Some(ValueKind::Grade), FeatValue::Grade(_)) => true,
|
|
||||||
(Some(ValueKind::Options(labels)), FeatValue::Option(l)) => labels.contains(l),
|
|
||||||
(Some(ValueKind::Flag), FeatValue::Flag(_)) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `with_scene` found for a view: the scene revision `rev` it read, or why
|
|
||||||
/// it selected no relation. Each case is distinct so a missing annotation or a
|
|
||||||
/// store at the wrong path cannot look like a scene that held nothing.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum SceneRead {
|
|
||||||
/// `with_scene` has not run.
|
|
||||||
Unread,
|
|
||||||
/// The store holds no scene for the item's group.
|
|
||||||
NoScene,
|
|
||||||
/// The scene was read and the packet names no addressee.
|
|
||||||
NoAddressee { rev: u32 },
|
|
||||||
/// The addressee referent is the speaker themself.
|
|
||||||
SelfAddressed { rev: u32 },
|
|
||||||
/// The scene holds no relation from the speaker to this addressee.
|
|
||||||
NoRelation { rev: u32 },
|
|
||||||
/// The relation was found; its features may be none.
|
|
||||||
Selected {
|
|
||||||
rev: u32,
|
|
||||||
features: Vec<FeatureValue>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the lowerer sees: a validated packet's meaning, with no packet id, no
|
|
||||||
/// provenance (so no corpus item key, encoder or source) and no trace. Its
|
|
||||||
/// fields are private and the constructor is crate-private, called only by
|
|
||||||
/// `PacketStore::admit`, so a lowerer cannot be handed an unadmitted packet or
|
|
||||||
/// the key to an answer text.
|
|
||||||
///
|
|
||||||
/// Each field has a doctest that reads it from outside the crate. A read
|
|
||||||
/// compiles exactly when the field is `pub`, so the doctest (which must fail to
|
|
||||||
/// compile) fails as soon as any one field is made public. A struct literal
|
|
||||||
/// cannot pin this: it fails to compile while any other field stays private,
|
|
||||||
/// and stable rustdoc does not check the error code.
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.inventory_rev; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.kind; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.context; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.discourse; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.referents; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.predications; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.relations; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.constraints; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.extensions; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.stance; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn read(l: weksa::LoweringInput) { let _ = l.scene; }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// 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,
|
|
||||||
/// c: &weksa::CorpusStore,
|
|
||||||
/// ) {
|
|
||||||
/// let _ = l.with_scene(i, s, c);
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn pick(
|
|
||||||
/// l: weksa::LoweringInput,
|
|
||||||
/// i: &weksa::Inventory,
|
|
||||||
/// s: &weksa::speaker::Scene,
|
|
||||||
/// e: &weksa::EntityId,
|
|
||||||
/// ) {
|
|
||||||
/// let _ = l.with_scene(i, s, e);
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn pick(l: weksa::LoweringInput, i: &weksa::Inventory) {
|
|
||||||
/// let _ = l.with_scene(i, vec![]);
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// The constructor is private: a call from outside the crate compiles only if
|
|
||||||
/// `LoweringInput::of` is `pub`. The first block is the same code without the
|
|
||||||
/// call, so the second fails for that call and nothing else.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// fn build(p: &weksa::packet::Packet, item: &weksa::CorpusItem) { let _ = (p, item); }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn build(p: &weksa::packet::Packet, item: &weksa::CorpusItem) {
|
|
||||||
/// let _ = weksa::LoweringInput::of(p, item);
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// A lowering view is never read from bytes: `Deserialize` would let a caller
|
|
||||||
/// build one without `validate`. The first block proves the bound resolves for
|
|
||||||
/// a type that does implement it.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// fn de<T: serde::de::DeserializeOwned>() {}
|
|
||||||
/// de::<weksa::packet::Packet>();
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail
|
|
||||||
/// fn de<T: serde::de::DeserializeOwned>() {}
|
|
||||||
/// de::<weksa::LoweringInput>();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct LoweringInput {
|
|
||||||
inventory_rev: u32,
|
|
||||||
kind: PacketKind,
|
|
||||||
context: Context,
|
|
||||||
discourse: Discourse,
|
|
||||||
referents: Vec<Referent>,
|
|
||||||
predications: Vec<Predication>,
|
|
||||||
relations: Vec<Relation>,
|
|
||||||
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: SceneRead,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LoweringInput {
|
|
||||||
/// 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,
|
|
||||||
context: p.context.clone(),
|
|
||||||
discourse: p.discourse.clone(),
|
|
||||||
referents: p.referents.clone(),
|
|
||||||
predications: p.predications.clone(),
|
|
||||||
relations: p.relations.clone(),
|
|
||||||
constraints: p.constraints.clone(),
|
|
||||||
extensions: p.extensions.clone(),
|
|
||||||
stance: p.stance.clone(),
|
|
||||||
speaker: item.speaker.clone(),
|
|
||||||
group: item.group.clone(),
|
|
||||||
scene: SceneRead::Unread,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the speaker's relation to the addressee, the only path for scene
|
|
||||||
/// 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. A scene that does not list the item's speaker, or the speaker of
|
|
||||||
/// any live item of the group (the rule `put_scene` applies), is V16, with
|
|
||||||
/// or without an addressee. What the read found is recorded on the view as a
|
|
||||||
/// [`SceneRead`], never an empty feature list standing for five cases:
|
|
||||||
/// no scene for the group, no addressee, an addressee who is the speaker,
|
|
||||||
/// no such relation, or the relation from the speaker to the addressee
|
|
||||||
/// referent's entity (to `Unnamed` when the referent has none), whose
|
|
||||||
/// features are checked like every feature list in slot `Scene` at this
|
|
||||||
/// view's inventory revision. A read replaces any earlier one. The English
|
|
||||||
/// lowerer ignores it.
|
|
||||||
pub fn with_scene(
|
|
||||||
mut self,
|
|
||||||
inventory: &Inventory,
|
|
||||||
state: &SpeakerStateStore,
|
|
||||||
corpus: &CorpusStore,
|
|
||||||
) -> Result<Self, StoreError> {
|
|
||||||
self.scene = SceneRead::Unread;
|
|
||||||
let Some(scene) = state.scene(&self.group)? else {
|
|
||||||
self.scene = SceneRead::NoScene;
|
|
||||||
return Ok(self);
|
|
||||||
};
|
|
||||||
let rev = scene.n;
|
|
||||||
let live = corpus.all()?;
|
|
||||||
let live = live
|
|
||||||
.iter()
|
|
||||||
.filter(|i| i.group == self.group && !i.withdrawn)
|
|
||||||
.map(|i| &i.speaker);
|
|
||||||
if scene
|
|
||||||
.uncovered(live.chain(std::iter::once(&self.speaker)))
|
|
||||||
.is_some()
|
|
||||||
{
|
|
||||||
return Err(StoreError::Invalid(vec![Refusal::V16SpeakerNotInScene]));
|
|
||||||
}
|
|
||||||
let Some(addressee) = self.discourse.addressee.as_ref() else {
|
|
||||||
self.scene = SceneRead::NoAddressee { rev };
|
|
||||||
return Ok(self);
|
|
||||||
};
|
|
||||||
let entity = self
|
|
||||||
.referents
|
|
||||||
.iter()
|
|
||||||
.find(|r| &r.id == addressee)
|
|
||||||
.and_then(|r| r.entity.as_ref());
|
|
||||||
if entity == Some(&self.speaker) {
|
|
||||||
self.scene = SceneRead::SelfAddressed { rev };
|
|
||||||
return Ok(self);
|
|
||||||
}
|
|
||||||
let Some(features) = scene.relation(&self.speaker, entity) else {
|
|
||||||
self.scene = SceneRead::NoRelation { rev };
|
|
||||||
return Ok(self);
|
|
||||||
};
|
|
||||||
let out = feature_refusals(inventory, self.inventory_rev, features, Slot::Scene);
|
|
||||||
if !out.is_empty() {
|
|
||||||
return Err(StoreError::Invalid(out));
|
|
||||||
}
|
|
||||||
self.scene = SceneRead::Selected {
|
|
||||||
rev,
|
|
||||||
features: features.to_vec(),
|
|
||||||
};
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn inventory_rev(&self) -> u32 {
|
|
||||||
self.inventory_rev
|
|
||||||
}
|
|
||||||
pub fn kind(&self) -> PacketKind {
|
|
||||||
self.kind
|
|
||||||
}
|
|
||||||
pub fn context(&self) -> &Context {
|
|
||||||
&self.context
|
|
||||||
}
|
|
||||||
pub fn discourse(&self) -> &Discourse {
|
|
||||||
&self.discourse
|
|
||||||
}
|
|
||||||
pub fn referents(&self) -> &[Referent] {
|
|
||||||
&self.referents
|
|
||||||
}
|
|
||||||
pub fn predications(&self) -> &[Predication] {
|
|
||||||
&self.predications
|
|
||||||
}
|
|
||||||
pub fn relations(&self) -> &[Relation] {
|
|
||||||
&self.relations
|
|
||||||
}
|
|
||||||
pub fn constraints(&self) -> &Constraints {
|
|
||||||
&self.constraints
|
|
||||||
}
|
|
||||||
pub fn extensions(&self) -> &[Extension] {
|
|
||||||
&self.extensions
|
|
||||||
}
|
|
||||||
pub fn stance(&self) -> &Stance {
|
|
||||||
&self.stance
|
|
||||||
}
|
|
||||||
/// The features of the scene relation from the speaker to the addressee.
|
|
||||||
/// Empty for every [`SceneRead`] but `Selected` (and for a selected
|
|
||||||
/// relation that has no features): ask [`scene_read`](Self::scene_read) which.
|
|
||||||
pub fn scene(&self) -> &[FeatureValue] {
|
|
||||||
match &self.scene {
|
|
||||||
SceneRead::Selected { features, .. } => features,
|
|
||||||
_ => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// What `with_scene` read; `Unread` until it ran.
|
|
||||||
pub fn scene_read(&self) -> &SceneRead {
|
|
||||||
&self.scene
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,107 +0,0 @@
|
||||||
//! A line-based tripwire on the Checkpoint door, not a proof. The real defence
|
|
||||||
//! is that `Checkpoint::for_test` is `cfg(test)`, pinned by the compile_fail
|
|
||||||
//! doctest on its current name in `split.rs`. This scan reads `split.rs` line by
|
|
||||||
//! line and catches the common single-line forms: a `pub fn` in `impl
|
|
||||||
//! Checkpoint` whose signature line says `-> Self` or `-> Checkpoint` without
|
|
||||||
//! `cfg(test)` above it, a trait impl for `Checkpoint`, a derive on it, a `pub`
|
|
||||||
//! field in its braces, and a `-> Checkpoint` line in any other `src` file. It
|
|
||||||
//! misses: signatures wrapped over several lines, `Option`, `Box`, `Result` or
|
|
||||||
//! tuple returns from `split.rs`, tuple structs with `pub` fields, and
|
|
||||||
//! constructors made by macros.
|
|
||||||
|
|
||||||
/// Why `src` lets code outside the lib make a `Checkpoint`, if it does.
|
|
||||||
fn door_leaks(split_rs: &str) -> Vec<String> {
|
|
||||||
let mut leaks = Vec::new();
|
|
||||||
let lines: Vec<&str> = split_rs.lines().collect();
|
|
||||||
let mut in_impl = false;
|
|
||||||
let mut in_struct = false;
|
|
||||||
for (n, line) in lines.iter().enumerate() {
|
|
||||||
let t = line.trim();
|
|
||||||
if t.starts_with("impl Checkpoint") {
|
|
||||||
in_impl = true;
|
|
||||||
} else if t.starts_with("impl") && t.contains("Checkpoint") {
|
|
||||||
leaks.push(format!("{}: trait impl: {t}", n + 1));
|
|
||||||
}
|
|
||||||
if t.starts_with("pub struct Checkpoint") {
|
|
||||||
let derived = lines[..n]
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.take_while(|l| l.trim().starts_with("#[") || l.trim().starts_with("///"))
|
|
||||||
.any(|l| l.contains("derive"));
|
|
||||||
if derived {
|
|
||||||
leaks.push(format!("{}: derive on Checkpoint", n + 1));
|
|
||||||
}
|
|
||||||
in_struct = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if in_struct {
|
|
||||||
if t.starts_with('}') {
|
|
||||||
in_struct = false;
|
|
||||||
} else if t.starts_with("pub ") {
|
|
||||||
leaks.push(format!("{}: public field: {t}", n + 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if in_impl && t.starts_with("pub ") && t.contains("fn ") {
|
|
||||||
let mints = t.contains("-> Self") || t.contains("-> Checkpoint");
|
|
||||||
let test_only = lines[..n]
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.take_while(|l| l.trim().starts_with("#["))
|
|
||||||
.any(|l| l.contains("cfg(test)"));
|
|
||||||
if mints && !test_only {
|
|
||||||
leaks.push(format!("{}: pub constructor: {t}", n + 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
leaks
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn no_public_item_mints_a_checkpoint() {
|
|
||||||
let src =
|
|
||||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/split.rs")).unwrap();
|
|
||||||
assert_eq!(door_leaks(&src), Vec::<String>::new());
|
|
||||||
// No other module returns one either.
|
|
||||||
for entry in std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap() {
|
|
||||||
let path = entry.unwrap().path();
|
|
||||||
if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("split.rs") {
|
|
||||||
let text = std::fs::read_to_string(&path).unwrap();
|
|
||||||
let minting = text
|
|
||||||
.lines()
|
|
||||||
.filter(|l| l.contains("-> Checkpoint") || l.contains("-> Result<Checkpoint"))
|
|
||||||
.count();
|
|
||||||
assert_eq!(minting, 0, "{}", path.display());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_scan_sees_each_way_to_open_the_door() {
|
|
||||||
let good = "impl Checkpoint {\n #[cfg(test)]\n pub(crate) fn for_test(r: u32) -> Self { x }\n}\n";
|
|
||||||
assert!(door_leaks(good).is_empty());
|
|
||||||
// Test constructor made public, under its own name or another.
|
|
||||||
let public = "impl Checkpoint {\n pub fn for_test(r: u32) -> Self { x }\n}\n";
|
|
||||||
assert_eq!(door_leaks(public).len(), 1);
|
|
||||||
let renamed = "impl Checkpoint {\n #[cfg(test)]\n #[allow(x)]\n pub fn new(r: u32) -> Checkpoint { x }\n}\n";
|
|
||||||
assert!(
|
|
||||||
door_leaks(renamed).is_empty(),
|
|
||||||
"cfg(test) above another attribute counts"
|
|
||||||
);
|
|
||||||
let renamed = "impl Checkpoint {\n pub fn new(r: u32) -> Checkpoint { x }\n}\n";
|
|
||||||
assert_eq!(door_leaks(renamed).len(), 1);
|
|
||||||
// cfg(test) on the previous item does not cover this one.
|
|
||||||
let stray =
|
|
||||||
"impl Checkpoint {\n #[cfg(test)]\n fn a() {}\n pub fn b() -> Self { x }\n}\n";
|
|
||||||
assert_eq!(door_leaks(stray).len(), 1);
|
|
||||||
assert_eq!(door_leaks("impl Default for Checkpoint {}\n").len(), 1);
|
|
||||||
assert_eq!(door_leaks("impl From<u32> for Checkpoint {}\n").len(), 1);
|
|
||||||
assert_eq!(
|
|
||||||
door_leaks("#[derive(Clone)]\npub struct Checkpoint {\n").len(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
door_leaks("pub struct Checkpoint {\n pub round: u32,\n}\n").len(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert!(door_leaks("pub struct Checkpoint {\n round: u32,\n}\n").is_empty());
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,445 +0,0 @@
|
||||||
#![allow(dead_code)]
|
|
||||||
|
|
||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
use tempfile::TempDir;
|
|
||||||
use weksa::corpus::ModelFamily;
|
|
||||||
use weksa::inventory::{Change, seed};
|
|
||||||
use weksa::packet::*;
|
|
||||||
use weksa::{
|
|
||||||
CorpusItem, CorpusItemId, CorpusStore, Entity, EntityOrigin, EntityStore, InvId, Inventory,
|
|
||||||
InventoryEntry, InventoryRevision, InventoryStore, LanguageForms, NameSpan, OptionLabel, Slot,
|
|
||||||
Source, SplitScheme, ValueKind,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const PERSON: &str = "referent_kind:1";
|
|
||||||
pub const AGENT: &str = "role:1";
|
|
||||||
pub const PATIENT: &str = "role:2";
|
|
||||||
pub const WARN: &str = "speech_act:5";
|
|
||||||
pub const POLARITY: &str = "feature:1";
|
|
||||||
pub const MODALITY: &str = "feature:4";
|
|
||||||
pub const HEDGE: &str = "feature:6";
|
|
||||||
pub const IRONY: &str = "feature:8";
|
|
||||||
/// Stance features, slot Stance only (Grade).
|
|
||||||
pub const ANGER: &str = "feature:9";
|
|
||||||
pub const AFFECTION: &str = "feature:16";
|
|
||||||
pub const RESTRAINT: &str = "feature:18";
|
|
||||||
/// Introduced at rev 2.
|
|
||||||
pub const CONCEPT_A: &str = "concept:1";
|
|
||||||
pub const CONCEPT_B: &str = "concept:2";
|
|
||||||
/// Introduced at rev 2, retired at rev 3.
|
|
||||||
pub const CONCEPT_RETIRED: &str = "concept:3";
|
|
||||||
/// Introduced at rev 4.
|
|
||||||
pub const CONCEPT_LATE: &str = "concept:4";
|
|
||||||
pub const FRAME: &str = "frame:1";
|
|
||||||
/// An extension entry of value kind Grade, introduced at rev 2.
|
|
||||||
pub const EXT: &str = "extension:1";
|
|
||||||
/// A Grade feature introduced at rev 2 in every content slot (Discourse,
|
|
||||||
/// Referent, Predication, Relation).
|
|
||||||
pub const FEAT_ALL: &str = "feature:50";
|
|
||||||
|
|
||||||
pub const PACKET_ID: &str = "packet:0123456789abcdef";
|
|
||||||
pub const ENCODER_ID: &str = "encoder:fedcba9876543210";
|
|
||||||
|
|
||||||
pub fn iv(s: &str) -> InvId {
|
|
||||||
s.parse().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn nd(s: &str) -> NodeId {
|
|
||||||
NodeId::parse(s).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lab(s: &str) -> OptionLabel {
|
|
||||||
OptionLabel::parse(s).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn grade(v: u16) -> Grade {
|
|
||||||
Grade::new(v).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn group_in_bucket(want: u64) -> String {
|
|
||||||
(0..100_000)
|
|
||||||
.map(|i| format!("g{i}"))
|
|
||||||
.find(|g| SplitScheme::V1.bucket(g) == want)
|
|
||||||
.unwrap_or_else(|| panic!("no group lands in bucket {want}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cast() -> Source {
|
|
||||||
Source::CastAuthored {
|
|
||||||
persona: "nibu".into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
author: "Ada Writer".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn model() -> Source {
|
|
||||||
Source::ModelWritten {
|
|
||||||
family: ModelFamily::Unrecorded,
|
|
||||||
generator: None,
|
|
||||||
prompt_digest: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every speaker the tests use, as entities with one en-US form.
|
|
||||||
const SPEAKERS: [&str; 6] = ["nibu", "brokkr", "player", "s", "someone", "hero"];
|
|
||||||
|
|
||||||
pub fn eid(slug: &str) -> EntityId {
|
|
||||||
EntityId::parse(&format!("entity:{slug}")).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A cast entity with `forms` in `language`, citation form first.
|
|
||||||
pub fn ent(slug: &str, language: &str, forms: &[&str]) -> Entity {
|
|
||||||
Entity {
|
|
||||||
id: eid(slug),
|
|
||||||
forms: vec![LanguageForms {
|
|
||||||
language: language.into(),
|
|
||||||
forms: forms.iter().map(|f| f.to_string()).collect(),
|
|
||||||
pronunciation: None,
|
|
||||||
}],
|
|
||||||
origin: EntityOrigin::Cast {
|
|
||||||
persona: slug.into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entity store at `entities.cc` under `dir`, holding every test speaker
|
|
||||||
/// (en-US form: the slug capitalized). Reopening replays identically.
|
|
||||||
pub fn entities_in(dir: &std::path::Path) -> EntityStore {
|
|
||||||
let mut store = EntityStore::open(&dir.join("entities.cc")).unwrap();
|
|
||||||
for slug in SPEAKERS {
|
|
||||||
let form = slug[..1].to_uppercase() + &slug[1..];
|
|
||||||
store.put(ent(slug, "en-US", &[&form])).unwrap();
|
|
||||||
}
|
|
||||||
store
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An empty ontology store at `<dir>/ontology.cc`, made if absent.
|
|
||||||
pub fn ontology_in(dir: &std::path::Path) -> std::path::PathBuf {
|
|
||||||
let path = dir.join("ontology.cc");
|
|
||||||
if !path.exists() {
|
|
||||||
std::fs::write(&path, [0x90]).unwrap();
|
|
||||||
}
|
|
||||||
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");
|
|
||||||
if !path.exists() {
|
|
||||||
std::fs::write(&path, [0x90]).unwrap();
|
|
||||||
}
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An empty speaker-state store at `<dir>/speaker-state.cc`, made if absent.
|
|
||||||
pub fn speaker_state_in(dir: &std::path::Path) -> std::path::PathBuf {
|
|
||||||
speaker_state_beside(&dir.join("ontology.cc"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A run over the stores `world()` and `corpus()` keep in `dir`: `c.cc`,
|
|
||||||
/// `i.cc` and `entities.cc`. Read at the call, so create it after the items.
|
|
||||||
/// The run's en-US panel needs a live Train and a live Validation item: a
|
|
||||||
/// corpus short of one gets `item:panel:<n>` added, and no other item.
|
|
||||||
pub fn run_over(dir: &std::path::Path) -> weksa::run::RunStores {
|
|
||||||
for name in ["c.cc", "i.cc", "entities.cc"] {
|
|
||||||
if !dir.join(name).exists() {
|
|
||||||
std::fs::write(dir.join(name), [0x90]).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let entities = entities_in(dir);
|
|
||||||
ontology_in(dir);
|
|
||||||
let mut corpus = CorpusStore::open(&dir.join("c.cc")).unwrap();
|
|
||||||
for (n, split) in [(1, weksa::Split::Train), (2, weksa::Split::Validation)] {
|
|
||||||
let held = corpus
|
|
||||||
.all()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.any(|i| SplitScheme::V1.live(i) == Some(split));
|
|
||||||
if !held {
|
|
||||||
let group = group_in_bucket(if n == 1 { 10 } else { 50 });
|
|
||||||
let key = format!("item:panel:{n}");
|
|
||||||
let text = format!("Panel fixture line {n}.");
|
|
||||||
corpus.add(item_in(&key, &text, &group, cast()), &entities).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
drop(corpus);
|
|
||||||
weksa::run::RunStores::create(
|
|
||||||
&dir.join("run"),
|
|
||||||
"t",
|
|
||||||
weksa::run::RunPaths {
|
|
||||||
corpus: &dir.join("c.cc"),
|
|
||||||
inventory: &dir.join("i.cc"),
|
|
||||||
entities: &dir.join("entities.cc"),
|
|
||||||
ontology: &dir.join("ontology.cc"),
|
|
||||||
speaker_state: &speaker_state_beside(&dir.join("ontology.cc")),
|
|
||||||
},
|
|
||||||
"fake-model",
|
|
||||||
"bag",
|
|
||||||
weksa::run::LowererReach::ToolLessRelay,
|
|
||||||
weksa::corpus::ModelFamily::Unrecorded,
|
|
||||||
&["en-US".to_string()],
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn item_in(key: &str, text: &str, group: &str, source: Source) -> CorpusItem {
|
|
||||||
CorpusItem {
|
|
||||||
id: key.into(),
|
|
||||||
text: text.into(),
|
|
||||||
language: "en-US".into(),
|
|
||||||
speaker: eid("nibu"),
|
|
||||||
names: vec![],
|
|
||||||
names_by: None,
|
|
||||||
group: group.into(),
|
|
||||||
prior_turns: vec![],
|
|
||||||
source,
|
|
||||||
admitted_on: "2026-10-29".into(),
|
|
||||||
supersedes: None,
|
|
||||||
withdrawn: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn entry(id: &str, introduced: u32) -> InventoryEntry {
|
|
||||||
InventoryEntry {
|
|
||||||
id: iv(id),
|
|
||||||
gloss: id.into(),
|
|
||||||
value_kind: None,
|
|
||||||
applies_to: vec![],
|
|
||||||
introduced_rev: introduced,
|
|
||||||
retired_rev: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn feature(id: &str, kind: ValueKind, slots: &[Slot]) -> InventoryEntry {
|
|
||||||
InventoryEntry {
|
|
||||||
value_kind: Some(kind),
|
|
||||||
applies_to: slots.to_vec(),
|
|
||||||
..entry(id, 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn rev_with(changes: Vec<Change>, n: u32, parent: Option<u32>) -> InventoryRevision {
|
|
||||||
InventoryRevision {
|
|
||||||
n,
|
|
||||||
parent,
|
|
||||||
changes,
|
|
||||||
frozen: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Admits `entries` as revision `n` and returns nothing; the stores are the only door.
|
|
||||||
pub fn admit(store: &mut InventoryStore, n: u32, entries: Vec<InventoryEntry>) {
|
|
||||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
let parent = n.checked_sub(1).filter(|p| *p > 0);
|
|
||||||
store
|
|
||||||
.admit_revision(rev_with(changes, n, parent), entries)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores a test can admit through: a corpus holding `item:nibu:1` in a Train
|
|
||||||
/// group, and an inventory of revisions 1 (the seed), 2 (concepts A, B,
|
|
||||||
/// RETIRED, a frame, a Grade extension), 3 (RETIRED retired) and 4 (LATE).
|
|
||||||
pub struct World {
|
|
||||||
pub dir: TempDir,
|
|
||||||
pub inventory: InventoryStore,
|
|
||||||
pub corpus: CorpusStore,
|
|
||||||
pub entities: EntityStore,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl World {
|
|
||||||
pub fn inv(&self) -> Inventory {
|
|
||||||
self.inventory.inventory().unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn world() -> World {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
|
||||||
let entities = entities_in(dir.path());
|
|
||||||
ontology_in(dir.path());
|
|
||||||
let train = group_in_bucket(10);
|
|
||||||
let mut first = item_in("item:nibu:1", "Nibu says mind the hatch.", &train, cast());
|
|
||||||
first.names = vec![NameSpan {
|
|
||||||
entity: eid("nibu"),
|
|
||||||
start: 0,
|
|
||||||
end: 4,
|
|
||||||
}];
|
|
||||||
corpus.add(first, &entities).unwrap();
|
|
||||||
// A run's panel needs a live Validation item as well as a Train one.
|
|
||||||
let validation = group_in_bucket(50);
|
|
||||||
let second = item_in("item:panel:1", "Nibu says watch the ladder.", &validation, cast());
|
|
||||||
corpus.add(second, &entities).unwrap();
|
|
||||||
let mut inventory = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
|
|
||||||
let (rev1, entries) = seed();
|
|
||||||
inventory.admit_revision(rev1, entries).unwrap();
|
|
||||||
let mut ext = entry(EXT, 2);
|
|
||||||
ext.value_kind = Some(ValueKind::Grade);
|
|
||||||
admit(
|
|
||||||
&mut inventory,
|
|
||||||
2,
|
|
||||||
vec![
|
|
||||||
entry(CONCEPT_A, 2),
|
|
||||||
entry(CONCEPT_B, 2),
|
|
||||||
entry(CONCEPT_RETIRED, 2),
|
|
||||||
entry(FRAME, 2),
|
|
||||||
ext,
|
|
||||||
InventoryEntry {
|
|
||||||
introduced_rev: 2,
|
|
||||||
..feature(
|
|
||||||
FEAT_ALL,
|
|
||||||
ValueKind::Grade,
|
|
||||||
&[
|
|
||||||
Slot::Discourse,
|
|
||||||
Slot::Referent,
|
|
||||||
Slot::Predication,
|
|
||||||
Slot::Relation,
|
|
||||||
],
|
|
||||||
)
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
inventory
|
|
||||||
.admit_revision(
|
|
||||||
rev_with(vec![Change::Retire(iv(CONCEPT_RETIRED))], 3, Some(2)),
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
admit(&mut inventory, 4, vec![entry(CONCEPT_LATE, 4)]);
|
|
||||||
World {
|
|
||||||
dir,
|
|
||||||
inventory,
|
|
||||||
corpus,
|
|
||||||
entities,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The world's inventory, built once.
|
|
||||||
pub fn inventory() -> Inventory {
|
|
||||||
static INV: OnceLock<Inventory> = OnceLock::new();
|
|
||||||
INV.get_or_init(|| world().inv()).clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn good() -> Packet {
|
|
||||||
Packet {
|
|
||||||
id: PacketId::parse(PACKET_ID).unwrap(),
|
|
||||||
schema_version: SCHEMA_VERSION,
|
|
||||||
inventory_rev: 2,
|
|
||||||
kind: PacketKind::DialogueLine,
|
|
||||||
provenance: Provenance {
|
|
||||||
source: ProvenanceSource::Authored,
|
|
||||||
corpus_item: CorpusItemId::parse("item:nibu:1").unwrap(),
|
|
||||||
encoder: EncoderId::parse(ENCODER_ID).unwrap(),
|
|
||||||
confidence: grade(900),
|
|
||||||
},
|
|
||||||
context: Context {
|
|
||||||
setting: Some(iv(CONCEPT_A)),
|
|
||||||
medium: Some(iv(CONCEPT_B)),
|
|
||||||
participants: vec![nd("n1")],
|
|
||||||
audience: vec![nd("n1")],
|
|
||||||
},
|
|
||||||
discourse: Discourse {
|
|
||||||
speech_act: Some(iv(WARN)),
|
|
||||||
addressee: Some(nd("n1")),
|
|
||||||
addressee_consent: None,
|
|
||||||
features: vec![FeatureValue {
|
|
||||||
feature: iv(HEDGE),
|
|
||||||
value: FeatValue::Grade(grade(300)),
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
referents: vec![Referent {
|
|
||||||
id: nd("n1"),
|
|
||||||
kind: iv(PERSON),
|
|
||||||
concept: iv(CONCEPT_A),
|
|
||||||
entity: Some(eid("nibu")),
|
|
||||||
features: vec![],
|
|
||||||
}],
|
|
||||||
predications: vec![Predication {
|
|
||||||
id: nd("n2"),
|
|
||||||
concept: iv(CONCEPT_B),
|
|
||||||
frame: iv(FRAME),
|
|
||||||
roles: vec![
|
|
||||||
RoleFill {
|
|
||||||
role: iv(AGENT),
|
|
||||||
filler: nd("n1"),
|
|
||||||
},
|
|
||||||
RoleFill {
|
|
||||||
role: iv(PATIENT),
|
|
||||||
filler: nd("n1"),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
features: vec![FeatureValue {
|
|
||||||
feature: iv(MODALITY),
|
|
||||||
value: FeatValue::Option(lab("potential")),
|
|
||||||
}],
|
|
||||||
}],
|
|
||||||
relations: vec![Relation {
|
|
||||||
relation: iv("relation:8"),
|
|
||||||
from: nd("n2"),
|
|
||||||
to: nd("n1"),
|
|
||||||
features: vec![],
|
|
||||||
}],
|
|
||||||
constraints: Constraints {
|
|
||||||
preserve: vec![nd("n1")],
|
|
||||||
deterministic: true,
|
|
||||||
max_latency_ms: Some(50),
|
|
||||||
},
|
|
||||||
extensions: vec![Extension {
|
|
||||||
key: iv(EXT),
|
|
||||||
value: FeatValue::Grade(grade(3)),
|
|
||||||
}],
|
|
||||||
trace: Trace {
|
|
||||||
notes: vec!["a note".into()],
|
|
||||||
rejected_readings: vec![],
|
|
||||||
},
|
|
||||||
stance: Stance {
|
|
||||||
features: vec![
|
|
||||||
FeatureValue {
|
|
||||||
feature: iv(ANGER),
|
|
||||||
value: FeatValue::Grade(grade(300)),
|
|
||||||
},
|
|
||||||
FeatureValue {
|
|
||||||
feature: iv(RESTRAINT),
|
|
||||||
value: FeatValue::Grade(grade(700)),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A deterministic bag-of-letters embedder, so cosine differs with the text.
|
|
||||||
pub struct Bag;
|
|
||||||
|
|
||||||
impl weksa::Embedder for Bag {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
"bag"
|
|
||||||
}
|
|
||||||
fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
|
|
||||||
Ok(texts
|
|
||||||
.iter()
|
|
||||||
.map(|t| {
|
|
||||||
let mut v = vec![0.0; 27];
|
|
||||||
v[26] = 1.0;
|
|
||||||
for c in t.chars().filter(char::is_ascii_alphabetic) {
|
|
||||||
v[(c.to_ascii_lowercase() as u8 - b'a') as usize] += 1.0;
|
|
||||||
}
|
|
||||||
v
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,56 +0,0 @@
|
||||||
//! The Dao De Jing test bed (`data/daodejing`): its Legge items carry full
|
|
||||||
//! public-domain provenance, and its packets are admitted
|
|
||||||
//! (`docs/targets/dao-de-jing-test-bed.md`).
|
|
||||||
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use weksa::daodejing::packets;
|
|
||||||
use weksa::{CorpusStore, EntityStore, InventoryStore, PacketStore, Source};
|
|
||||||
|
|
||||||
fn root() -> std::path::PathBuf {
|
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_legge_item_names_licence_jurisdiction_translator_and_edition_year() {
|
|
||||||
let items = CorpusStore::open(&root().join("corpus.cc"))
|
|
||||||
.unwrap()
|
|
||||||
.all()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(items.len(), 5);
|
|
||||||
for item in items {
|
|
||||||
let Source::PublicDomain {
|
|
||||||
licence,
|
|
||||||
jurisdiction,
|
|
||||||
translator,
|
|
||||||
edition_year,
|
|
||||||
..
|
|
||||||
} = item.source
|
|
||||||
else {
|
|
||||||
panic!("{} is not a public-domain item", item.id);
|
|
||||||
};
|
|
||||||
assert!(
|
|
||||||
!licence.is_empty() && !jurisdiction.is_empty(),
|
|
||||||
"{}",
|
|
||||||
item.id
|
|
||||||
);
|
|
||||||
assert_eq!((translator.as_str(), edition_year), ("James Legge", 1891));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_slice_packets_are_admitted_and_the_committed_store_holds_them() {
|
|
||||||
let inventory = InventoryStore::open(&root().join("inventory.cc")).unwrap();
|
|
||||||
let corpus = CorpusStore::open(&root().join("corpus.cc")).unwrap();
|
|
||||||
let entities = EntityStore::open(&root().join("entity.cc")).unwrap();
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = PacketStore::open(&dir.path().join("p.cc")).unwrap();
|
|
||||||
for p in packets() {
|
|
||||||
store.admit(p, &inventory, &corpus, &entities).unwrap();
|
|
||||||
}
|
|
||||||
// The committed packet store holds exactly what the module builds.
|
|
||||||
let stored = PacketStore::open(&root().join("packets.cc")).unwrap();
|
|
||||||
for p in packets() {
|
|
||||||
assert_eq!(stored.get(&p.id.to_string()).unwrap(), Some(p));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,121 +0,0 @@
|
||||||
//! Error text is a fixed message naming the rule or variant. The caller's
|
|
||||||
//! identifiers (entity, node and inventory ids, IPA text, value strings) stay
|
|
||||||
//! on the typed value and never reach Display.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use weksa::packet::{EntityId, NodeId, ProvenanceSource};
|
|
||||||
use weksa::{Family, InvId, LowerError, Refusal, Slot};
|
|
||||||
|
|
||||||
const SENTINEL: &str = "sentinelzz";
|
|
||||||
|
|
||||||
fn inv() -> InvId {
|
|
||||||
InvId::parse("concept:4242").unwrap()
|
|
||||||
}
|
|
||||||
fn node() -> NodeId {
|
|
||||||
NodeId::parse("n4242").unwrap()
|
|
||||||
}
|
|
||||||
fn entity() -> EntityId {
|
|
||||||
EntityId::parse(&format!("entity:{SENTINEL}")).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_clean_and_distinct<T: std::fmt::Display + std::fmt::Debug>(all: Vec<T>) {
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
for e in all {
|
|
||||||
let text = e.to_string();
|
|
||||||
assert!(!text.is_empty(), "{e:?}");
|
|
||||||
for leak in [SENTINEL, "4242", "{", "}"] {
|
|
||||||
assert!(!text.contains(leak), "{e:?} leaks {leak:?}: {text}");
|
|
||||||
}
|
|
||||||
assert!(seen.insert(text.clone()), "{e:?} repeats {text:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lower_error_display_names_the_variant_and_no_identifier() {
|
|
||||||
assert_clean_and_distinct(vec![
|
|
||||||
LowerError::UnknownEntity { entity: entity() },
|
|
||||||
LowerError::NoForm { entity: entity() },
|
|
||||||
LowerError::NoPronunciation { entity: entity() },
|
|
||||||
LowerError::NoEntityReferent,
|
|
||||||
LowerError::UnknownPhone {
|
|
||||||
entity: entity(),
|
|
||||||
at: 4242,
|
|
||||||
text: SENTINEL.into(),
|
|
||||||
},
|
|
||||||
LowerError::DanglingStress {
|
|
||||||
entity: entity(),
|
|
||||||
at: 4242,
|
|
||||||
},
|
|
||||||
LowerError::EntityRead {
|
|
||||||
entity: entity(),
|
|
||||||
why: SENTINEL.into(),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
assert_eq!(
|
|
||||||
LowerError::NoPronunciation { entity: entity() }.to_string(),
|
|
||||||
"entity has no ruled pronunciation"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refusal_display_names_the_rule_and_no_identifier() {
|
|
||||||
let all = vec![
|
|
||||||
Refusal::V1SchemaVersion { found: 4242 },
|
|
||||||
Refusal::V2PayloadRequired,
|
|
||||||
Refusal::V3DuplicateNode { id: node() },
|
|
||||||
Refusal::V4DanglingRef {
|
|
||||||
id: node(),
|
|
||||||
at: SENTINEL,
|
|
||||||
},
|
|
||||||
Refusal::V5Unresolved { id: inv() },
|
|
||||||
Refusal::V6WrongFamily {
|
|
||||||
id: inv(),
|
|
||||||
expected: Family::Role,
|
|
||||||
at: SENTINEL,
|
|
||||||
},
|
|
||||||
Refusal::V7ValueKind {
|
|
||||||
what: SENTINEL.into(),
|
|
||||||
},
|
|
||||||
Refusal::V8NotApplicable {
|
|
||||||
feature: inv(),
|
|
||||||
slot: Slot::Scene,
|
|
||||||
},
|
|
||||||
Refusal::V10UnknownRevision { rev: 4242 },
|
|
||||||
Refusal::V11DuplicateFeature {
|
|
||||||
feature: inv(),
|
|
||||||
slot: Some(Slot::Scene),
|
|
||||||
},
|
|
||||||
Refusal::V11DuplicateNodeRef {
|
|
||||||
id: node(),
|
|
||||||
at: SENTINEL,
|
|
||||||
},
|
|
||||||
Refusal::V11DuplicateRole {
|
|
||||||
role: inv(),
|
|
||||||
predication: node(),
|
|
||||||
},
|
|
||||||
Refusal::V12TooManyNodes {
|
|
||||||
count: 4242,
|
|
||||||
max: 4242,
|
|
||||||
},
|
|
||||||
Refusal::V14ConsentWithoutAddressee,
|
|
||||||
Refusal::V14ConsentNotAPredication { id: node() },
|
|
||||||
Refusal::V15ConsentSource {
|
|
||||||
source: ProvenanceSource::ImportedCorpus,
|
|
||||||
},
|
|
||||||
Refusal::V16SpeakerNotInScene,
|
|
||||||
Refusal::V17AddresseeNotAReferent { id: node() },
|
|
||||||
Refusal::V18RequestWithoutConsent { predication: node() },
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
Refusal::V16SpeakerNotInScene.to_string(),
|
|
||||||
"V16: the scene does not cover the speaker of every live item of its group"
|
|
||||||
);
|
|
||||||
for r in &all {
|
|
||||||
assert!(r.to_string().starts_with(r.rule()), "{r:?}");
|
|
||||||
}
|
|
||||||
assert_clean_and_distinct(all);
|
|
||||||
assert_eq!(
|
|
||||||
Refusal::V14ConsentNotAPredication { id: node() }.to_string(),
|
|
||||||
"V14: consent names no predication"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -1,597 +0,0 @@
|
||||||
mod common;
|
|
||||||
use common::*;
|
|
||||||
use weksa::corpus::{CorpusItem, NameSpan, Turn};
|
|
||||||
use weksa::packet::{Packet, Referent};
|
|
||||||
use weksa::{
|
|
||||||
AddOutcome, CorpusItemId, CorpusStore, Entity, EntityId, EntityOrigin, EntityStore, PacketId,
|
|
||||||
PacketStore, Refusal, SCHEMA_VERSION, StoreError, StoreRefusal, validate,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn refusal(r: Result<impl std::fmt::Debug, StoreError>) -> StoreRefusal {
|
|
||||||
match r {
|
|
||||||
Err(StoreError::Refused(r)) => r,
|
|
||||||
other => panic!("expected a store refusal, got {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn malformed(r: Result<impl std::fmt::Debug, StoreError>) -> &'static str {
|
|
||||||
match refusal(r) {
|
|
||||||
StoreRefusal::Malformed { why, .. } => why,
|
|
||||||
other => panic!("expected Malformed, got {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn span(slug: &str, start: u32, end: u32) -> NameSpan {
|
|
||||||
NameSpan {
|
|
||||||
entity: eid(slug),
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An item in `language` whose text and spans the test chooses.
|
|
||||||
fn named(n: u32, language: &str, text: &str, names: Vec<NameSpan>) -> CorpusItem {
|
|
||||||
CorpusItem {
|
|
||||||
language: language.into(),
|
|
||||||
names,
|
|
||||||
..item_in(&format!("item:t:{n}"), text, "g", cast())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn entity_id_form() {
|
|
||||||
for ok in ["entity:brokkr", "entity:a-1", "entity:7", "entity:a-b-c"] {
|
|
||||||
assert_eq!(EntityId::parse(ok).unwrap().as_str(), ok);
|
|
||||||
}
|
|
||||||
let long_ok = format!("entity:{}", "a".repeat(48));
|
|
||||||
assert!(EntityId::parse(&long_ok).is_ok());
|
|
||||||
let too_long = format!("entity:{}", "a".repeat(49));
|
|
||||||
for bad in [
|
|
||||||
"Entity:x",
|
|
||||||
"entity:-a",
|
|
||||||
"entity:a-",
|
|
||||||
"entity:",
|
|
||||||
"entity:a_b",
|
|
||||||
"entity:A",
|
|
||||||
"entity:a b",
|
|
||||||
"entity:a:b",
|
|
||||||
"brokkr",
|
|
||||||
"entity:\u{5c71}",
|
|
||||||
&too_long,
|
|
||||||
] {
|
|
||||||
assert!(EntityId::parse(bad).is_err(), "{bad:?}");
|
|
||||||
assert!(
|
|
||||||
serde_json::from_value::<EntityId>(bad.into()).is_err(),
|
|
||||||
"{bad:?} must not read back from a store"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// A referent reads its entity through the same parse.
|
|
||||||
let mut referent = serde_json::to_value(good().referents[0].clone()).unwrap();
|
|
||||||
assert!(serde_json::from_value::<Referent>(referent.clone()).is_ok());
|
|
||||||
referent["entity"] = "Nibu".into();
|
|
||||||
assert!(serde_json::from_value::<Referent>(referent).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn entity_forms_only_grow() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let kay = ent("kay", "en-US", &["Kay"]);
|
|
||||||
assert_eq!(store.put(kay.clone()).unwrap(), AddOutcome::Added);
|
|
||||||
assert_eq!(store.put(kay.clone()).unwrap(), AddOutcome::Unchanged);
|
|
||||||
|
|
||||||
// A form appends; a language appends.
|
|
||||||
let mut grown = kay.clone();
|
|
||||||
grown.forms[0].forms.push("Kay's".into());
|
|
||||||
assert_eq!(store.put(grown.clone()).unwrap(), AddOutcome::Added);
|
|
||||||
let mut more = grown.clone();
|
|
||||||
more.forms.push(weksa::LanguageForms {
|
|
||||||
language: "tr".into(),
|
|
||||||
forms: vec!["Kay".into()],
|
|
||||||
pronunciation: None,
|
|
||||||
});
|
|
||||||
assert_eq!(store.put(more.clone()).unwrap(), AddOutcome::Added);
|
|
||||||
// The store read back from disk holds the growth.
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), Some(more.clone()));
|
|
||||||
|
|
||||||
// Dropping, reordering, editing and re-originating are refused, each leaving
|
|
||||||
// the stored entity as it was.
|
|
||||||
let not_append = StoreRefusal::EntityNotAppendOnly { id: eid("kay") };
|
|
||||||
let edits: [fn(&mut Entity); 6] = [
|
|
||||||
|e| e.forms[0].forms.reverse(),
|
|
||||||
|e| e.forms[0].forms[0] = "Kai".into(),
|
|
||||||
|e| {
|
|
||||||
e.forms.pop();
|
|
||||||
},
|
|
||||||
|e| e.forms.reverse(),
|
|
||||||
|e| e.forms[1].language = "fi".into(),
|
|
||||||
|e| {
|
|
||||||
e.origin = EntityOrigin::Live {
|
|
||||||
persona: "kay".into(),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
refusal(store.put(ent("kay", "en-US", &["Kay"]))),
|
|
||||||
not_append
|
|
||||||
);
|
|
||||||
for edit in edits {
|
|
||||||
let mut v = more.clone();
|
|
||||||
edit(&mut v);
|
|
||||||
assert_eq!(refusal(store.put(v.clone())), not_append, "{v:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), Some(more));
|
|
||||||
|
|
||||||
// Shape: no forms, a language twice, an empty language, an empty language
|
|
||||||
// entry, an empty, padded, control-bearing, oversize or repeated form.
|
|
||||||
let shape = |forms: Vec<weksa::LanguageForms>| weksa::Entity {
|
|
||||||
forms,
|
|
||||||
..ent("shape", "en-US", &["X"])
|
|
||||||
};
|
|
||||||
let lf = |language: &str, forms: &[&str]| weksa::LanguageForms {
|
|
||||||
language: language.into(),
|
|
||||||
forms: forms.iter().map(|f| f.to_string()).collect(),
|
|
||||||
pronunciation: None,
|
|
||||||
};
|
|
||||||
for bad in [
|
|
||||||
vec![],
|
|
||||||
vec![lf("en-US", &["A"]), lf("en-US", &["B"])],
|
|
||||||
vec![lf("en-US", &[])],
|
|
||||||
vec![lf("en-US", &[""])],
|
|
||||||
vec![lf("en-US", &[" A"])],
|
|
||||||
vec![lf("en-US", &["A\u{a0}"])],
|
|
||||||
vec![lf("en-US", &["A\nB"])],
|
|
||||||
vec![lf("en-US", &["A", "A"])],
|
|
||||||
] {
|
|
||||||
malformed(store.put(shape(bad.clone())));
|
|
||||||
assert!(
|
|
||||||
store.get(&eid("shape")).unwrap().is_none(),
|
|
||||||
"{bad:?} was stored"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// An empty language is not a tag.
|
|
||||||
let e = shape(vec![lf("", &["A"])]);
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(store.put(e)),
|
|
||||||
StoreRefusal::EntityBounds {
|
|
||||||
bound: weksa::store::EntityBound::LanguageTag,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
// 64 bytes is the edge; a form may repeat across languages.
|
|
||||||
let edge = "a".repeat(64);
|
|
||||||
store
|
|
||||||
.put(shape(vec![lf("en-US", &[&edge]), lf("tr", &[&edge])]))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn corpus_spans_checked() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut ents = entities_in(d.path());
|
|
||||||
ents.put(ent("kay", "en-US", &["Kay"])).unwrap();
|
|
||||||
ents.put(ent("ab", "en-US", &["abab", "bab"])).unwrap();
|
|
||||||
let mut corpus = CorpusStore::open(&d.path().join("c.cc")).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
corpus
|
|
||||||
.add(
|
|
||||||
named(1, "en-US", "Kay left.", vec![span("kay", 0, 3)]),
|
|
||||||
&ents
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
AddOutcome::Added
|
|
||||||
);
|
|
||||||
|
|
||||||
let range = |n: u32, start: u32, end: u32| StoreRefusal::NameSpanRange {
|
|
||||||
key: format!("item:t:{n}"),
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
};
|
|
||||||
let not_a_form = |n: u32, slug: &str, start: u32, end: u32| StoreRefusal::NameSpanNotAForm {
|
|
||||||
key: format!("item:t:{n}"),
|
|
||||||
entity: eid(slug),
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
};
|
|
||||||
let mut refused = |item: CorpusItem| refusal(corpus.add(item, &ents));
|
|
||||||
// Empty, backwards, past the end: a range refusal.
|
|
||||||
for (start, end) in [(3, 3), (4, 3), (0, 99)] {
|
|
||||||
let item = named(2, "en-US", "Kay left.", vec![span("kay", start, end)]);
|
|
||||||
assert_eq!(refused(item), range(2, start, end));
|
|
||||||
}
|
|
||||||
// Inside a multibyte character: start and end off the boundary.
|
|
||||||
let text = "\u{e9}Kay";
|
|
||||||
assert_eq!(text.len(), 5);
|
|
||||||
let item = named(2, "en-US", text, vec![span("kay", 1, 4)]);
|
|
||||||
assert_eq!(refused(item), range(2, 1, 4));
|
|
||||||
let item = named(2, "en-US", "Kay\u{e9}", vec![span("kay", 0, 4)]);
|
|
||||||
assert_eq!(refused(item), range(2, 0, 4));
|
|
||||||
// An unknown entity.
|
|
||||||
let item = named(2, "en-US", "Kay left.", vec![span("ghost", 0, 3)]);
|
|
||||||
assert_eq!(
|
|
||||||
refused(item),
|
|
||||||
StoreRefusal::UnknownEntity {
|
|
||||||
entity: eid("ghost")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
// Not byte-equal: other text, other case, a missing language.
|
|
||||||
let item = named(2, "en-US", "Kai left.", vec![span("kay", 0, 3)]);
|
|
||||||
assert_eq!(refused(item), not_a_form(2, "kay", 0, 3));
|
|
||||||
let item = named(2, "en-US", "kay left.", vec![span("kay", 0, 3)]);
|
|
||||||
assert_eq!(refused(item), not_a_form(2, "kay", 0, 3));
|
|
||||||
let item = named(2, "tr", "Kay left.", vec![span("kay", 0, 3)]);
|
|
||||||
assert_eq!(refused(item), not_a_form(2, "kay", 0, 3));
|
|
||||||
// Overlap: both spans are forms, they share bytes.
|
|
||||||
let item = named(2, "en-US", "abab", vec![span("ab", 0, 4), span("ab", 1, 4)]);
|
|
||||||
assert_eq!(
|
|
||||||
refused(item),
|
|
||||||
StoreRefusal::NameSpanOverlap {
|
|
||||||
key: "item:t:2".into()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
// Adjacent spans do not overlap, whatever order they are listed in.
|
|
||||||
let adjacent = named(
|
|
||||||
90,
|
|
||||||
"en-US",
|
|
||||||
"KayKay",
|
|
||||||
vec![span("kay", 3, 6), span("kay", 0, 3)],
|
|
||||||
);
|
|
||||||
assert_eq!(corpus.add(adjacent, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
|
|
||||||
// Speakers: unknown, and unknown in a prior turn.
|
|
||||||
let ghost = EntityId::parse("entity:ghost").unwrap();
|
|
||||||
let unknown = StoreRefusal::UnknownEntity {
|
|
||||||
entity: ghost.clone(),
|
|
||||||
};
|
|
||||||
let mut item = named(91, "en-US", "Hello there.", vec![]);
|
|
||||||
item.speaker = ghost.clone();
|
|
||||||
assert_eq!(refusal(corpus.add(item, &ents)), unknown);
|
|
||||||
let mut item = named(92, "en-US", "Hello again.", vec![]);
|
|
||||||
item.prior_turns = vec![
|
|
||||||
Turn {
|
|
||||||
speaker: eid("nibu"),
|
|
||||||
text: "hi".into(),
|
|
||||||
},
|
|
||||||
Turn {
|
|
||||||
speaker: ghost,
|
|
||||||
text: "hi".into(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
assert_eq!(refusal(corpus.add(item, &ents)), unknown);
|
|
||||||
let mut item = named(93, "en-US", "Hello at last.", vec![]);
|
|
||||||
item.prior_turns = vec![Turn {
|
|
||||||
speaker: eid("nibu"),
|
|
||||||
text: "hi".into(),
|
|
||||||
}];
|
|
||||||
assert_eq!(corpus.add(item, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
// Nothing refused was stored.
|
|
||||||
let keys: Vec<String> = corpus.all().unwrap().into_iter().map(|i| i.id).collect();
|
|
||||||
assert_eq!(keys, ["item:t:1", "item:t:90", "item:t:93"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn corpus_spans_every_script() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut ents = entities_in(d.path());
|
|
||||||
ents.put(ent(
|
|
||||||
"minsu",
|
|
||||||
"ko",
|
|
||||||
&["\u{BBFC}\u{C218}", "\u{BBFC}\u{C218}\u{AC00}"],
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
ents.put(ent("brokkr-tr", "tr", &["Brokkr", "Brokkr'\u{131}n"]))
|
|
||||||
.unwrap();
|
|
||||||
ents.put(ent(
|
|
||||||
"somchai",
|
|
||||||
"th",
|
|
||||||
&["\u{E2A}\u{E21}\u{E0A}\u{E32}\u{E22}"],
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
let mut corpus = CorpusStore::open(&d.path().join("c.cc")).unwrap();
|
|
||||||
|
|
||||||
// The particle-bound Korean form: byte equality with the stored form.
|
|
||||||
let ko = "\u{BBFC}\u{C218}\u{AC00} \u{C654}\u{B2E4}";
|
|
||||||
let with_particle = "\u{BBFC}\u{C218}\u{AC00}".len();
|
|
||||||
assert_eq!(with_particle, 9);
|
|
||||||
let item = named(1, "ko", ko, vec![span("minsu", 0, with_particle as u32)]);
|
|
||||||
assert_eq!(corpus.add(item, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
// The bare stem is a stored form too; a span cutting a syllable is not.
|
|
||||||
let item = named(
|
|
||||||
2,
|
|
||||||
"ko",
|
|
||||||
"\u{BBFC}\u{C218} \u{C654}\u{B2E4}",
|
|
||||||
vec![span("minsu", 0, 6)],
|
|
||||||
);
|
|
||||||
assert_eq!(corpus.add(item, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
let item = named(3, "ko", ko, vec![span("minsu", 0, 7)]);
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(corpus.add(item, &ents)),
|
|
||||||
StoreRefusal::NameSpanRange { .. }
|
|
||||||
));
|
|
||||||
// Turkish: the apostrophe suffix.
|
|
||||||
let tr = "Brokkr'\u{131}n geldi.";
|
|
||||||
let len = "Brokkr'\u{131}n".len() as u32;
|
|
||||||
let item = named(4, "tr", tr, vec![span("brokkr-tr", 0, len)]);
|
|
||||||
assert_eq!(corpus.add(item, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
// Thai: no spaces, no segmentation, a span is a byte range.
|
|
||||||
let th = "\u{E2A}\u{E21}\u{E0A}\u{E32}\u{E22}\u{E21}\u{E32}\u{E41}\u{E25}\u{E49}\u{E27}";
|
|
||||||
let len = "\u{E2A}\u{E21}\u{E0A}\u{E32}\u{E22}".len() as u32;
|
|
||||||
let item = named(5, "th", th, vec![span("somchai", 0, len)]);
|
|
||||||
assert_eq!(corpus.add(item, &ents).unwrap(), AddOutcome::Added);
|
|
||||||
// The same bytes under another language tag are refused.
|
|
||||||
let item = named(6, "ko", th, vec![span("somchai", 0, len)]);
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(corpus.add(item, &ents)),
|
|
||||||
StoreRefusal::NameSpanNotAForm { .. }
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn packet_entities_resolve() {
|
|
||||||
let mut w = world();
|
|
||||||
w.entities.put(ent("kay", "en-US", &["Kay"])).unwrap();
|
|
||||||
let mut talk = named(2, "en-US", "Kay and Hero talk.", vec![span("kay", 0, 3)]);
|
|
||||||
talk.id = "item:nibu:2".into();
|
|
||||||
talk.prior_turns = vec![Turn {
|
|
||||||
speaker: eid("hero"),
|
|
||||||
text: "hi".into(),
|
|
||||||
}];
|
|
||||||
w.corpus.add(talk, &w.entities).unwrap();
|
|
||||||
|
|
||||||
let mut packets = PacketStore::open(&w.dir.path().join("p.cc")).unwrap();
|
|
||||||
let packet = |n: u8, item: &str, entity: &str| {
|
|
||||||
let mut p = good();
|
|
||||||
p.id = PacketId::parse(&format!("packet:{n:016x}")).unwrap();
|
|
||||||
p.provenance.corpus_item = CorpusItemId::parse(item).unwrap();
|
|
||||||
p.referents[0].entity = Some(eid(entity));
|
|
||||||
p
|
|
||||||
};
|
|
||||||
let mut admit = |p: Packet| packets.admit(p, &w.inventory, &w.corpus, &w.entities);
|
|
||||||
|
|
||||||
// An entity the store lacks.
|
|
||||||
let unknown = StoreRefusal::UnknownEntity {
|
|
||||||
entity: eid("ghost"),
|
|
||||||
};
|
|
||||||
assert_eq!(refusal(admit(packet(1, "item:nibu:1", "ghost"))), unknown);
|
|
||||||
assert_eq!(refusal(admit(packet(2, "item:nibu:2", "ghost"))), unknown);
|
|
||||||
// A stored entity that is not on the item.
|
|
||||||
let off_item = |item: &str, entity: &str| StoreRefusal::EntityNotOnItem {
|
|
||||||
entity: eid(entity),
|
|
||||||
item: item.into(),
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
refusal(admit(packet(3, "item:nibu:2", "brokkr"))),
|
|
||||||
off_item("item:nibu:2", "brokkr")
|
|
||||||
);
|
|
||||||
// nibu:1 names nibu (and is spoken by nibu); kay is only on nibu:2.
|
|
||||||
assert_eq!(
|
|
||||||
refusal(admit(packet(4, "item:nibu:1", "kay"))),
|
|
||||||
off_item("item:nibu:1", "kay")
|
|
||||||
);
|
|
||||||
// On the item: a name entity, the speaker, a prior-turn speaker.
|
|
||||||
admit(packet(5, "item:nibu:2", "kay")).unwrap();
|
|
||||||
admit(packet(6, "item:nibu:2", "nibu")).unwrap();
|
|
||||||
admit(packet(7, "item:nibu:2", "hero")).unwrap();
|
|
||||||
// No packet escapes the item check: a stored entity that no item names is
|
|
||||||
// refused on every item, and a packet cannot omit its item.
|
|
||||||
assert_eq!(
|
|
||||||
refusal(admit(packet(8, "item:nibu:1", "brokkr"))),
|
|
||||||
off_item("item:nibu:1", "brokkr")
|
|
||||||
);
|
|
||||||
// A referent with no entity needs none; only a packet that cites checks.
|
|
||||||
let mut anonymous = packet(9, "item:nibu:2", "kay");
|
|
||||||
anonymous.referents[0].entity = None;
|
|
||||||
admit(anonymous).unwrap();
|
|
||||||
// Refused packets were not stored.
|
|
||||||
let stored: Vec<String> = PacketStore::open(&w.dir.path().join("p.cc"))
|
|
||||||
.unwrap()
|
|
||||||
.all()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.id.to_string())
|
|
||||||
.collect();
|
|
||||||
assert_eq!(stored.len(), 4, "{stored:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn packet_schema_v2() {
|
|
||||||
assert_eq!(SCHEMA_VERSION, 5);
|
|
||||||
let mut p = good();
|
|
||||||
p.schema_version = 2;
|
|
||||||
let Err(refused) = validate(&p, &inventory()) else {
|
|
||||||
panic!("a v1 packet must not validate")
|
|
||||||
};
|
|
||||||
assert_eq!(refused, vec![Refusal::V1SchemaVersion { found: 2 }]);
|
|
||||||
|
|
||||||
let published: std::collections::BTreeMap<_, _> =
|
|
||||||
weksa::schema::published().into_iter().collect();
|
|
||||||
let packet: serde_json::Value =
|
|
||||||
serde_json::from_str(&published["weksa.interlingua_packet.schema.json"]).unwrap();
|
|
||||||
let referent = &packet["$defs"]["Referent"]["properties"];
|
|
||||||
assert!(referent.get("entity").is_some(), "{referent}");
|
|
||||||
assert!(referent.get("name").is_none(), "{referent}");
|
|
||||||
let defs = packet["$defs"].as_object().unwrap();
|
|
||||||
assert!(!defs.keys().any(|k| k.ends_with("Name")), "{defs:?}");
|
|
||||||
assert_eq!(
|
|
||||||
packet["$defs"]["EntityId"]["pattern"],
|
|
||||||
"^entity:[a-z0-9]([a-z0-9-]{0,46}[a-z0-9])?$"
|
|
||||||
);
|
|
||||||
let item: serde_json::Value =
|
|
||||||
serde_json::from_str(&published["weksa.corpus_item.schema.json"]).unwrap();
|
|
||||||
assert!(item["properties"].get("names").is_some());
|
|
||||||
assert!(published.contains_key("weksa.entity.schema.json"));
|
|
||||||
// v4: the packet carries the speaker's stance, a bare feature list.
|
|
||||||
assert!(packet["properties"].get("stance").is_some(), "{packet}");
|
|
||||||
assert_eq!(
|
|
||||||
packet["$defs"]["Stance"]["properties"]["features"]["type"],
|
|
||||||
"array"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_pronunciation_is_added_once_and_then_frozen() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let kay = ent("kay", "en-US", &["Kay"]);
|
|
||||||
store.put(kay.clone()).unwrap();
|
|
||||||
let said = |ipa: &str, rejected: &[&str]| {
|
|
||||||
let mut e = kay.clone();
|
|
||||||
e.forms[0].pronunciation = Some(weksa::Pronunciation {
|
|
||||||
ipa: ipa.into(),
|
|
||||||
ruled_by: "Kay".into(),
|
|
||||||
date: "2026-11-07".into(),
|
|
||||||
source: "test".into(),
|
|
||||||
rejected: rejected.iter().map(|r| r.to_string()).collect(),
|
|
||||||
});
|
|
||||||
e
|
|
||||||
};
|
|
||||||
// An unruled entity gains a ruling.
|
|
||||||
let ruled = said("ˈkeɪ", &["ˈkaɪ"]);
|
|
||||||
assert_eq!(store.put(ruled.clone()).unwrap(), AddOutcome::Added);
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), Some(ruled.clone()));
|
|
||||||
// A ruling is neither changed nor dropped; a changed ruling is a new decision.
|
|
||||||
for e in [said("ˈkaɪ", &[]), said("ˈkeɪ", &[]), kay.clone()] {
|
|
||||||
assert_eq!(
|
|
||||||
refusal(store.put(e)),
|
|
||||||
StoreRefusal::EntityNotAppendOnly { id: eid("kay") }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), Some(ruled));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_malformed_pronunciation_is_refused() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let with = |edit: fn(&mut weksa::Pronunciation)| {
|
|
||||||
let mut e = ent("kay", "en-US", &["Kay"]);
|
|
||||||
let mut p = weksa::Pronunciation {
|
|
||||||
ipa: "ˈkeɪ".into(),
|
|
||||||
ruled_by: "Kay".into(),
|
|
||||||
date: "2026-11-07".into(),
|
|
||||||
source: "test".into(),
|
|
||||||
rejected: vec!["ˈkaɪ".into()],
|
|
||||||
};
|
|
||||||
edit(&mut p);
|
|
||||||
e.forms[0].pronunciation = Some(p);
|
|
||||||
e
|
|
||||||
};
|
|
||||||
let edits: [fn(&mut weksa::Pronunciation); 9] = [
|
|
||||||
|p| p.ipa = "".into(),
|
|
||||||
|p| p.ipa = "/ˈkeɪ/".into(),
|
|
||||||
|p| p.ipa = "[ˈkeɪ]".into(),
|
|
||||||
|p| p.ipa = " ˈkeɪ".into(),
|
|
||||||
|p| p.ruled_by = "".into(),
|
|
||||||
|p| p.date = "07-11-2026".into(),
|
|
||||||
|p| p.date = "2026-13-07".into(),
|
|
||||||
|p| p.rejected = vec!["ˈkeɪ".into()],
|
|
||||||
|p| p.rejected = vec!["ˈkaɪ".into(), "ˈkaɪ".into()],
|
|
||||||
];
|
|
||||||
for edit in edits {
|
|
||||||
assert!(
|
|
||||||
matches!(
|
|
||||||
store.put(with(edit)),
|
|
||||||
Err(StoreError::Refused(StoreRefusal::Malformed { .. }))
|
|
||||||
),
|
|
||||||
"{:?}",
|
|
||||||
with(edit)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
const LANTERN: &str = r#"{"slug":"lantern-wager","language":"en-US","admitted_on":"2026-11-13",
|
|
||||||
"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}},
|
|
||||||
"cast":[{"entity":"entity:orsa","forms":["Orsa"]},{"entity":"entity:tamsin","forms":["Tamsin","Tam"]}],
|
|
||||||
"lines":[{"group":"s1","speaker":"entity:orsa","text":"Tamsin, bring the lantern."},
|
|
||||||
{"group":"s1","speaker":"entity:tamsin","text":"Tamsin's lantern, said Orsa."},
|
|
||||||
{"group":"s2","speaker":"entity:orsa","text":"Quiet, both of you."}]}"#;
|
|
||||||
|
|
||||||
fn marked(line: u32, text: &str) -> weksa::encode::MarkedLine {
|
|
||||||
weksa::encode::MarkedLine { line, marked: text.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_imported_work_passes_the_store_doors() {
|
|
||||||
use weksa::Annotator;
|
|
||||||
use weksa::corpus::ModelFamily;
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut entities = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let mut corpus = CorpusStore::open(&d.path().join("c.cc")).unwrap();
|
|
||||||
let model = Annotator::Model { family: ModelFamily::Anthropic, generator: "g".into() };
|
|
||||||
let work = || weksa::encode::WorkDraft::parse(LANTERN).unwrap();
|
|
||||||
let (cast, items) = work()
|
|
||||||
.into_import(&[marked(1, "[[entity:tamsin|Tamsin]], bring the lantern.")], &model)
|
|
||||||
.unwrap();
|
|
||||||
for e in cast {
|
|
||||||
assert_eq!(entities.put(e).unwrap(), AddOutcome::Added);
|
|
||||||
}
|
|
||||||
for i in items.clone() {
|
|
||||||
assert_eq!(corpus.add(i, &entities).unwrap(), AddOutcome::Added);
|
|
||||||
}
|
|
||||||
drop(corpus);
|
|
||||||
let mut corpus = CorpusStore::open(&d.path().join("c.cc")).unwrap();
|
|
||||||
let stored = corpus.get("item:lantern-wager:1").unwrap().unwrap();
|
|
||||||
assert_eq!(stored.names_by, Some(model.clone()));
|
|
||||||
assert_eq!(stored.names.len(), 1);
|
|
||||||
assert_eq!(corpus.add(items[0].clone(), &entities).unwrap(), AddOutcome::Unchanged);
|
|
||||||
|
|
||||||
// A form the entity does not list is the store's refusal, not the importer's.
|
|
||||||
let (_, bad) = work()
|
|
||||||
.into_import(&[marked(2, "[[entity:tamsin|Tamsin's]] lantern, said Orsa.")], &model)
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(corpus.add(bad[0].clone(), &entities)),
|
|
||||||
StoreRefusal::NameSpanNotAForm { .. }
|
|
||||||
));
|
|
||||||
|
|
||||||
// An operator run over another line labels its own spans.
|
|
||||||
let (_, op) = work()
|
|
||||||
.into_import(&[marked(3, "Quiet, both of you.")], &Annotator::Operator)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(corpus.add(op[0].clone(), &entities).unwrap(), AddOutcome::Added);
|
|
||||||
assert_eq!(
|
|
||||||
corpus.get("item:lantern-wager:3").unwrap().unwrap().names_by,
|
|
||||||
Some(Annotator::Operator)
|
|
||||||
);
|
|
||||||
// The first run's line keeps its label.
|
|
||||||
assert_eq!(corpus.get("item:lantern-wager:1").unwrap().unwrap().names_by, Some(model));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn committed_items_read_with_no_names_label() {
|
|
||||||
let data = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data");
|
|
||||||
for sub in ["daodejing", "original"] {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let copy = d.path().join("c.cc");
|
|
||||||
std::fs::copy(data.join(sub).join("corpus.cc"), ©).unwrap();
|
|
||||||
let items = CorpusStore::open(©).unwrap().all().unwrap();
|
|
||||||
assert!(!items.is_empty(), "{sub}");
|
|
||||||
assert!(items.iter().all(|i| i.names_by.is_none()), "{sub}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_blank_names_by_generator_is_refused_by_the_corpus_door() {
|
|
||||||
use weksa::Annotator;
|
|
||||||
use weksa::corpus::ModelFamily;
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut entities = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let mut corpus = CorpusStore::open(&d.path().join("c.cc")).unwrap();
|
|
||||||
let blank = Annotator::Model { family: ModelFamily::Anthropic, generator: " ".into() };
|
|
||||||
let (cast, items) = weksa::encode::WorkDraft::parse(LANTERN)
|
|
||||||
.unwrap()
|
|
||||||
.into_import(&[marked(3, "Quiet, both of you.")], &blank)
|
|
||||||
.unwrap();
|
|
||||||
for e in cast {
|
|
||||||
entities.put(e).unwrap();
|
|
||||||
}
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(corpus.add(items[0].clone(), &entities)),
|
|
||||||
StoreRefusal::Malformed { .. }
|
|
||||||
));
|
|
||||||
assert!(corpus.all().unwrap().is_empty());
|
|
||||||
}
|
|
||||||
|
|
@ -1,642 +0,0 @@
|
||||||
//! Behavioural pins from Soul's entity-store s1 probes: the entity door does not
|
|
||||||
//! trust the writer (ruling entity-door-bounds).
|
|
||||||
mod common;
|
|
||||||
use common::*;
|
|
||||||
use unicode_normalization::UnicodeNormalization;
|
|
||||||
use weksa::corpus::{CorpusItem, NameSpan};
|
|
||||||
use weksa::entity::{Entity, EntityOrigin, LanguageForms};
|
|
||||||
use weksa::store::EntityBound;
|
|
||||||
use weksa::{EntityStore, StoreError, StoreRefusal};
|
|
||||||
|
|
||||||
fn refusal(r: Result<impl std::fmt::Debug, StoreError>) -> StoreRefusal {
|
|
||||||
match r {
|
|
||||||
Err(StoreError::Refused(r)) => r,
|
|
||||||
other => panic!("expected a store refusal, got {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item(
|
|
||||||
n: impl std::fmt::Display,
|
|
||||||
lang: &str,
|
|
||||||
text: &str,
|
|
||||||
names: Vec<NameSpan>,
|
|
||||||
group: &str,
|
|
||||||
) -> CorpusItem {
|
|
||||||
CorpusItem {
|
|
||||||
language: lang.into(),
|
|
||||||
names,
|
|
||||||
..item_in(&format!("item:probe:{n}"), text, group, cast())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn span(slug: &str, start: usize, end: usize) -> NameSpan {
|
|
||||||
NameSpan {
|
|
||||||
entity: eid(slug),
|
|
||||||
start: start as u32,
|
|
||||||
end: end as u32,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bounds(entity: &Entity, bound: EntityBound) -> StoreRefusal {
|
|
||||||
StoreRefusal::EntityBounds {
|
|
||||||
id: entity.id.clone(),
|
|
||||||
bound,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn span_never_splits_a_grapheme_cluster() {
|
|
||||||
let mut w = world();
|
|
||||||
let g = group_in_bucket(10);
|
|
||||||
let splits = |n: u32, start: usize, end: usize| StoreRefusal::NameSpanSplitsCluster {
|
|
||||||
key: format!("item:probe:{n}"),
|
|
||||||
start: start as u32,
|
|
||||||
end: end as u32,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Devanagari: the word is a base, a spacing vowel sign and a base; the form
|
|
||||||
// "र" ends inside the cluster of the first two.
|
|
||||||
w.entities.put(ent("ra", "hi", &["र"])).unwrap();
|
|
||||||
let text = "राम आया";
|
|
||||||
assert_eq!(
|
|
||||||
refusal(
|
|
||||||
w.corpus
|
|
||||||
.add(item(1, "hi", text, vec![span("ra", 0, 3)], &g), &w.entities)
|
|
||||||
),
|
|
||||||
splits(1, 0, 3)
|
|
||||||
);
|
|
||||||
// The whole words are legal names, the second starting after a space.
|
|
||||||
w.entities.put(ent("ram", "hi", &["राम", "आया"])).unwrap();
|
|
||||||
let both = vec![span("ram", 0, 9), span("ram", 10, text.len())];
|
|
||||||
w.corpus
|
|
||||||
.add(item(2, "hi", text, both, &g), &w.entities)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// A start inside a cluster is refused too.
|
|
||||||
w.entities.put(ent("aa", "hi", &["ा"])).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.corpus.add(
|
|
||||||
item(3, "hi", "राम x", vec![span("aa", 3, 6)], &g),
|
|
||||||
&w.entities
|
|
||||||
)),
|
|
||||||
splits(3, 3, 6)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Latin base + combining mark with no precomposed form, so NFC keeps two
|
|
||||||
// code points: the form "q" leaves the accent outside.
|
|
||||||
let q = "q\u{301} arrive.";
|
|
||||||
w.entities.put(ent("q", "fr", &["q"])).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
refusal(
|
|
||||||
w.corpus
|
|
||||||
.add(item(4, "fr", q, vec![span("q", 0, 1)], &g), &w.entities)
|
|
||||||
),
|
|
||||||
splits(4, 0, 1)
|
|
||||||
);
|
|
||||||
w.entities.put(ent("qa", "fr", &["q\u{301}"])).unwrap();
|
|
||||||
w.corpus
|
|
||||||
.add(item(5, "fr", q, vec![span("qa", 0, 3)], &g), &w.entities)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn text_and_forms_are_stored_nfc() {
|
|
||||||
let mut w = world();
|
|
||||||
let g = group_in_bucket(10);
|
|
||||||
let not_nfc = |key: &str| StoreRefusal::NotNfc { key: key.into() };
|
|
||||||
// Decomposed Hangul (conjoining jamo) text is refused, not segmented.
|
|
||||||
let nfd = "\u{1106}\u{1175}\u{11AB}\u{1109}\u{116E} \u{110B}\u{116A}\u{11BB}\u{1103}\u{1161}";
|
|
||||||
assert!(!unicode_normalization::is_nfc(nfd));
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.corpus.add(item(1, "ko", nfd, vec![], &g), &w.entities)),
|
|
||||||
not_nfc("item:probe:1")
|
|
||||||
);
|
|
||||||
// The same words composed are admitted, and a span on a syllable pair is exact.
|
|
||||||
let nfc: String = nfd.nfc().collect();
|
|
||||||
let name: String = "\u{1106}\u{1175}\u{11AB}\u{1109}\u{116E}".nfc().collect();
|
|
||||||
w.entities.put(ent("minsu", "ko", &[&name])).unwrap();
|
|
||||||
w.corpus
|
|
||||||
.add(
|
|
||||||
item(2, "ko", &nfc, vec![span("minsu", 0, name.len())], &g),
|
|
||||||
&w.entities,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
// Latin NFD text, NFD forms and NFD prior turns are refused.
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.corpus.add(
|
|
||||||
item(3, "fr", "Rene\u{301} arrive.", vec![], &g),
|
|
||||||
&w.entities
|
|
||||||
)),
|
|
||||||
not_nfc("item:probe:3")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(ent("rene", "fr", &["Rene\u{301}"]))),
|
|
||||||
not_nfc("entity:rene")
|
|
||||||
);
|
|
||||||
let mut turns = item(4, "fr", "Salut.", vec![], &g);
|
|
||||||
turns.prior_turns = vec![weksa::Turn {
|
|
||||||
speaker: eid("nibu"),
|
|
||||||
text: "Rene\u{301}?".into(),
|
|
||||||
}];
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.corpus.add(turns, &w.entities)),
|
|
||||||
not_nfc("item:probe:4")
|
|
||||||
);
|
|
||||||
// NFC text and an NFC form of the same name agree byte for byte.
|
|
||||||
w.entities.put(ent("rene", "fr", &["Ren\u{e9}"])).unwrap();
|
|
||||||
w.corpus
|
|
||||||
.add(
|
|
||||||
item(5, "fr", "Ren\u{e9} part.", vec![span("rene", 0, 5)], &g),
|
|
||||||
&w.entities,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn entity_capacity_is_bounded() {
|
|
||||||
let mut w = world();
|
|
||||||
let lf = |language: &str, forms: Vec<String>| LanguageForms {
|
|
||||||
language: language.into(),
|
|
||||||
forms,
|
|
||||||
pronunciation: None,
|
|
||||||
};
|
|
||||||
let one = |f: &str| vec![f.to_string()];
|
|
||||||
let make = |forms: Vec<LanguageForms>| Entity {
|
|
||||||
id: eid("big"),
|
|
||||||
forms,
|
|
||||||
origin: EntityOrigin::Live {
|
|
||||||
persona: "p".into(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// A form is bounded by bytes, not words: a spaced name of any word count and
|
|
||||||
// names in scripts that write no spaces are admitted (the Thai name counts
|
|
||||||
// five UAX #29 words, a Han name one per character).
|
|
||||||
for (i, name) in [
|
|
||||||
"I will never leave you, not ever.",
|
|
||||||
"Mary of the Isles too",
|
|
||||||
"de la Cruz y Garcia",
|
|
||||||
"\u{e2a}\u{e21}\u{e0a}\u{e32}\u{e22} \u{e43}\u{e08}\u{e14}\u{e35}",
|
|
||||||
"\u{5c71}\u{7530}\u{592a}\u{90ce}",
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid(&format!("name-{i}")),
|
|
||||||
..make(vec![lf("en-US", one(name))])
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
// 64 bytes is the edge; 65 is over, counted in bytes (21 Han characters are
|
|
||||||
// 63 bytes, 22 are 66).
|
|
||||||
let wide = make(vec![lf("en-US", one(&"a".repeat(65)))]);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(wide.clone())),
|
|
||||||
bounds(&wide, EntityBound::FormBytes)
|
|
||||||
);
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid("edge"),
|
|
||||||
..make(vec![lf("en-US", one(&"a".repeat(64)))])
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid("han-edge"),
|
|
||||||
..make(vec![lf("ja", one(&"\u{5c71}".repeat(21)))])
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
let han = make(vec![lf("ja", one(&"\u{5c71}".repeat(22)))]);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(han.clone())),
|
|
||||||
bounds(&han, EntityBound::FormBytes)
|
|
||||||
);
|
|
||||||
|
|
||||||
// 8 forms per language is the edge.
|
|
||||||
let forms = |n: usize| (0..n).map(|i| format!("form{i}")).collect::<Vec<_>>();
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid("eight"),
|
|
||||||
..make(vec![lf("en-US", forms(8))])
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
let nine = make(vec![lf("en-US", forms(9))]);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(nine.clone())),
|
|
||||||
bounds(&nine, EntityBound::Forms)
|
|
||||||
);
|
|
||||||
|
|
||||||
// 8 languages is the edge.
|
|
||||||
let langs = |n: usize| {
|
|
||||||
(0..n)
|
|
||||||
.map(|i| lf(&format!("x-l{i}"), one("Form")))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
};
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid("langs"),
|
|
||||||
..make(langs(8))
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
let many = make(langs(9));
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(many.clone())),
|
|
||||||
bounds(&many, EntityBound::Languages)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Soul's probe: 200 junk languages of 5000 long forms each.
|
|
||||||
let long: Vec<String> = (0..5000)
|
|
||||||
.map(|i| format!("form number {i} of a long free text channel"))
|
|
||||||
.collect();
|
|
||||||
let probe = make(
|
|
||||||
(0..200)
|
|
||||||
.map(|l| lf(&format!("x-{l}\n\u{7}"), long.clone()))
|
|
||||||
.collect(),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(probe.clone())),
|
|
||||||
bounds(&probe, EntityBound::Languages)
|
|
||||||
);
|
|
||||||
assert!(w.entities.get(&eid("big")).unwrap().is_none());
|
|
||||||
|
|
||||||
// Language tags are BCP 47 in form.
|
|
||||||
for bad in [
|
|
||||||
"",
|
|
||||||
"e",
|
|
||||||
"en_US",
|
|
||||||
"x-0\n\u{7}",
|
|
||||||
"-en",
|
|
||||||
"en-",
|
|
||||||
"en--US",
|
|
||||||
"en-US-abcdefghi",
|
|
||||||
"1n",
|
|
||||||
"\u{65e5}\u{672c}",
|
|
||||||
"en-US-aaaaaaaa-bbbbbbbb-cccccccc-dddddddd-eeeeeeee",
|
|
||||||
"en-aaaaaaaa-aaaaaaaa-aaaaaaaa-bbbbbb",
|
|
||||||
] {
|
|
||||||
let e = make(vec![lf(bad, one("Form"))]);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(e.clone())),
|
|
||||||
bounds(&e, EntityBound::LanguageTag),
|
|
||||||
"{bad:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (i, ok) in [
|
|
||||||
"en",
|
|
||||||
"en-US",
|
|
||||||
"zh-Hant-TW",
|
|
||||||
"x-klingon",
|
|
||||||
"de-CH-1996",
|
|
||||||
"en-aaaaaaaa-aaaaaaaa-aaaaaaaa-bbbbb",
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
w.entities
|
|
||||||
.put(Entity {
|
|
||||||
id: eid(&format!("tag-{i}")),
|
|
||||||
..make(vec![lf(ok, one("Form"))])
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
assert!(w.entities.get(&eid("big")).unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn item_language_is_a_tag() {
|
|
||||||
let mut w = world();
|
|
||||||
let g = group_in_bucket(10);
|
|
||||||
for (n, bad) in ["", "en_US", "x-0\n\u{7}"].into_iter().enumerate() {
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(
|
|
||||||
w.corpus
|
|
||||||
.add(item(n + 1, bad, "Nibu left.", vec![], &g), &w.entities)
|
|
||||||
),
|
|
||||||
StoreRefusal::Malformed { .. }
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn entities_are_append_only_and_replay_needs_them() {
|
|
||||||
let mut w = world();
|
|
||||||
let base = ent("z", "en-US", &["Zed"]);
|
|
||||||
w.entities.put(base.clone()).unwrap();
|
|
||||||
let not_append = StoreRefusal::EntityNotAppendOnly { id: eid("z") };
|
|
||||||
|
|
||||||
let mut prepend = base.clone();
|
|
||||||
prepend.forms.insert(
|
|
||||||
0,
|
|
||||||
LanguageForms {
|
|
||||||
language: "fr".into(),
|
|
||||||
forms: vec!["Z\u{e8}de".into()],
|
|
||||||
pronunciation: None,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert_eq!(refusal(w.entities.put(prepend)), not_append);
|
|
||||||
let mut persona = base.clone();
|
|
||||||
persona.origin = EntityOrigin::Cast {
|
|
||||||
persona: "someone-else".into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
};
|
|
||||||
assert_eq!(refusal(w.entities.put(persona)), not_append);
|
|
||||||
let mut duplicate = base.clone();
|
|
||||||
duplicate.forms.push(LanguageForms {
|
|
||||||
language: "en-US".into(),
|
|
||||||
forms: vec!["Zeddy".into()],
|
|
||||||
pronunciation: None,
|
|
||||||
});
|
|
||||||
assert!(matches!(
|
|
||||||
refusal(w.entities.put(duplicate)),
|
|
||||||
StoreRefusal::Malformed { .. }
|
|
||||||
));
|
|
||||||
|
|
||||||
// A corpus replay against an entity store that lacks the speaker is refused.
|
|
||||||
let empty = EntityStore::open(&w.dir.path().join("empty.cc")).unwrap();
|
|
||||||
let again = CorpusItem {
|
|
||||||
id: "item:nibu:2".into(),
|
|
||||||
..item(1, "en-US", "Nibu says hello.", vec![], &group_in_bucket(10))
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.corpus.add(again, &empty)),
|
|
||||||
StoreRefusal::UnknownEntity {
|
|
||||||
entity: eid("nibu")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One entity holding `form` as its only en-US form.
|
|
||||||
fn with_form(slug: &str, form: &str) -> Entity {
|
|
||||||
Entity {
|
|
||||||
id: eid(slug),
|
|
||||||
forms: vec![LanguageForms {
|
|
||||||
language: "en-US".into(),
|
|
||||||
forms: vec![form.into()],
|
|
||||||
pronunciation: None,
|
|
||||||
}],
|
|
||||||
origin: EntityOrigin::Live {
|
|
||||||
persona: "p".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invisible_format_characters_are_refused_in_forms() {
|
|
||||||
let mut w = world();
|
|
||||||
let hidden = |slug: &str| StoreRefusal::Malformed {
|
|
||||||
key: format!("entity:{slug}"),
|
|
||||||
why: "a form holds an invisible format character",
|
|
||||||
};
|
|
||||||
let at = |code: u32| char::from_u32(code).unwrap();
|
|
||||||
// Every Cf code point except the joiners, plus U+2028 and U+2029, listed
|
|
||||||
// from Python's unicodedata. The code-point sweep in form.rs pins the edges
|
|
||||||
// of the rule; this checks the door applies it, in each position.
|
|
||||||
let listed: Vec<u32> = include_str!("format_refused.txt")
|
|
||||||
.lines()
|
|
||||||
.filter(|l| !l.starts_with('#'))
|
|
||||||
.map(|l| u32::from_str_radix(l, 16).unwrap())
|
|
||||||
.collect();
|
|
||||||
assert_eq!(listed.len(), 170);
|
|
||||||
for (n, code) in listed.iter().enumerate() {
|
|
||||||
let c = at(*code);
|
|
||||||
let mut forms = vec![format!("Ka{c}y")];
|
|
||||||
if !c.is_whitespace() {
|
|
||||||
forms.extend([format!("{c}Kay"), format!("Kay{c}")]);
|
|
||||||
}
|
|
||||||
for form in forms {
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with_form("fmt", &form))),
|
|
||||||
hidden("fmt"),
|
|
||||||
"U+{code:X} (#{n}) in {form:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Default_Ignorable fillers that are not Cf: Hangul and Khmer.
|
|
||||||
for code in [0x115f, 0x1160, 0x17b4, 0x17b5, 0x3164, 0xffa0] {
|
|
||||||
assert_eq!(
|
|
||||||
refusal(
|
|
||||||
w.entities
|
|
||||||
.put(with_form("fmt", &format!("Ka{}y", at(code))))
|
|
||||||
),
|
|
||||||
hidden("fmt"),
|
|
||||||
"U+{code:X}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(w.entities.get(&eid("fmt")).unwrap().is_none());
|
|
||||||
|
|
||||||
// The neighbours of the refused ranges, ZWNJ, ZWJ, CGJ, variation
|
|
||||||
// selectors and the Mongolian selectors (all Mn) are admitted in a form.
|
|
||||||
let admitted: [u32; 33] = [
|
|
||||||
0xac,
|
|
||||||
0xae,
|
|
||||||
0x34f,
|
|
||||||
0x5ff,
|
|
||||||
0x606,
|
|
||||||
0x61b,
|
|
||||||
0x61d,
|
|
||||||
0x6dc,
|
|
||||||
0x6de,
|
|
||||||
0x70e,
|
|
||||||
0x710,
|
|
||||||
0x88f,
|
|
||||||
0x892,
|
|
||||||
0x8e1,
|
|
||||||
0x8e3,
|
|
||||||
0x180b,
|
|
||||||
0x180c,
|
|
||||||
0x180d,
|
|
||||||
0x180f,
|
|
||||||
0x200a,
|
|
||||||
0x200c,
|
|
||||||
0x200d,
|
|
||||||
0x2010,
|
|
||||||
0x202f,
|
|
||||||
0x2065,
|
|
||||||
0x2070,
|
|
||||||
0xfe00,
|
|
||||||
0xfe0f,
|
|
||||||
0xfeff - 1,
|
|
||||||
0xfffc,
|
|
||||||
0x110be,
|
|
||||||
0x1d172,
|
|
||||||
0xe0100,
|
|
||||||
];
|
|
||||||
for (n, code) in admitted.into_iter().enumerate() {
|
|
||||||
let form = format!("Ka{}y", at(code));
|
|
||||||
w.entities
|
|
||||||
.put(with_form(&format!("ok-{n}"), &form))
|
|
||||||
.unwrap_or_else(|e| panic!("U+{code:X}: {e}"));
|
|
||||||
}
|
|
||||||
// ZWNJ in a Persian form, ZWJ in an emoji sequence, VS16 and a Mongolian
|
|
||||||
// free variation selector beside a letter.
|
|
||||||
for (n, form) in [
|
|
||||||
"\u{645}\u{6cc}\u{200c}\u{62e}\u{648}\u{627}\u{647}\u{645}",
|
|
||||||
"\u{1f469}\u{200d}\u{1f4bb}",
|
|
||||||
"\u{2764}\u{fe0f}",
|
|
||||||
"\u{1820}\u{180b}",
|
|
||||||
"\u{1f600}\u{e0100}",
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
w.entities
|
|
||||||
.put(with_form(&format!("script-{n}"), form))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
// A form of only joiners, variation selectors, CGJ or Mongolian selectors
|
|
||||||
// shows nothing and is refused.
|
|
||||||
let empty_looking = |slug: &str| StoreRefusal::Malformed {
|
|
||||||
key: format!("entity:{slug}"),
|
|
||||||
why: "a form is more than joiners and selectors",
|
|
||||||
};
|
|
||||||
for form in [
|
|
||||||
"\u{200d}",
|
|
||||||
"\u{200c}",
|
|
||||||
"\u{200c}\u{200d}",
|
|
||||||
"\u{fe0f}",
|
|
||||||
"\u{fe00}\u{fe0f}",
|
|
||||||
"\u{34f}",
|
|
||||||
"\u{180b}\u{180c}\u{180d}\u{180f}",
|
|
||||||
"\u{e0100}",
|
|
||||||
"\u{e01ef}\u{34f}\u{200d}",
|
|
||||||
] {
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with_form("blank", form))),
|
|
||||||
empty_looking("blank"),
|
|
||||||
"{form:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(w.entities.get(&eid("blank")).unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_origin_attests_where_the_entity_came_from() {
|
|
||||||
let mut w = world();
|
|
||||||
let bad = |slug: &str, why: &'static str| StoreRefusal::Malformed {
|
|
||||||
key: format!("entity:{slug}"),
|
|
||||||
why,
|
|
||||||
};
|
|
||||||
let with = |slug: &str, origin: EntityOrigin| Entity {
|
|
||||||
origin,
|
|
||||||
..with_form(slug, "Kay")
|
|
||||||
};
|
|
||||||
let cast = |persona: &str, fixture: &str| EntityOrigin::Cast {
|
|
||||||
persona: persona.into(),
|
|
||||||
fixture: fixture.into(),
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with("a", cast("", "f.yaml")))),
|
|
||||||
bad("a", "an origin names its persona")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with("b", cast("kay", "")))),
|
|
||||||
bad("b", "a cast origin names its fixture")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with(
|
|
||||||
"c",
|
|
||||||
EntityOrigin::Live {
|
|
||||||
persona: String::new()
|
|
||||||
}
|
|
||||||
))),
|
|
||||||
bad("c", "an origin names its persona")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with(
|
|
||||||
"d",
|
|
||||||
EntityOrigin::PublicDomain {
|
|
||||||
work: String::new()
|
|
||||||
}
|
|
||||||
))),
|
|
||||||
bad("d", "a public-domain origin names its work")
|
|
||||||
);
|
|
||||||
for slug in ["a", "b", "c", "d"] {
|
|
||||||
assert!(w.entities.get(&eid(slug)).unwrap().is_none());
|
|
||||||
}
|
|
||||||
w.entities.put(with("e", cast("kay", "f.yaml"))).unwrap();
|
|
||||||
w.entities
|
|
||||||
.put(with(
|
|
||||||
"f",
|
|
||||||
EntityOrigin::PublicDomain {
|
|
||||||
work: "edda".into(),
|
|
||||||
},
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_origin_attestation_holds_something_readable() {
|
|
||||||
let mut w = world();
|
|
||||||
let with = |slug: &str, origin: EntityOrigin| Entity {
|
|
||||||
origin,
|
|
||||||
..with_form(slug, "Kay")
|
|
||||||
};
|
|
||||||
type Build = fn(String) -> EntityOrigin;
|
|
||||||
let origins: [(Build, &str); 4] = [
|
|
||||||
(
|
|
||||||
|v| EntityOrigin::Cast {
|
|
||||||
persona: v,
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
},
|
|
||||||
"an origin names its persona",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
|v| EntityOrigin::Cast {
|
|
||||||
persona: "kay".into(),
|
|
||||||
fixture: v,
|
|
||||||
},
|
|
||||||
"a cast origin names its fixture",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
|v| EntityOrigin::Live { persona: v },
|
|
||||||
"an origin names its persona",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
|v| EntityOrigin::PublicDomain { work: v },
|
|
||||||
"a public-domain origin names its work",
|
|
||||||
),
|
|
||||||
];
|
|
||||||
let unreadable = [
|
|
||||||
" ".to_string(),
|
|
||||||
"\t".into(),
|
|
||||||
"\n".into(),
|
|
||||||
"\u{200b}".into(),
|
|
||||||
"\u{200d}".into(),
|
|
||||||
"\0".into(),
|
|
||||||
"--".into(),
|
|
||||||
"ok\u{200b}ok".into(),
|
|
||||||
"ok\u{2028}ok".into(),
|
|
||||||
"ok\0ok".into(),
|
|
||||||
"x".repeat(201),
|
|
||||||
"x".repeat(2 * 1024 * 1024),
|
|
||||||
];
|
|
||||||
let mut n = 0;
|
|
||||||
for (build, why) in &origins {
|
|
||||||
for bad in &unreadable {
|
|
||||||
n += 1;
|
|
||||||
let slug = format!("o-{n}");
|
|
||||||
assert_eq!(
|
|
||||||
refusal(w.entities.put(with(&slug, build(bad.clone())))),
|
|
||||||
StoreRefusal::Malformed {
|
|
||||||
key: format!("entity:{slug}"),
|
|
||||||
why
|
|
||||||
},
|
|
||||||
"{why}: {:?}",
|
|
||||||
bad.chars().take(12).collect::<String>()
|
|
||||||
);
|
|
||||||
assert!(w.entities.get(&eid(&slug)).unwrap().is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (m, (build, _)) in origins.iter().enumerate() {
|
|
||||||
for (k, good) in ["x".repeat(200), "two words, 2 more".to_string()]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
w.entities
|
|
||||||
.put(with(&format!("g-{}", 2 * m + k), build(good)))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,171 +0,0 @@
|
||||||
# Cf minus ZWNJ/ZWJ, plus U+2028 and U+2029; Python 3.13 unicodedata 15.1.0 over 0..10FFFF
|
|
||||||
AD
|
|
||||||
600
|
|
||||||
601
|
|
||||||
602
|
|
||||||
603
|
|
||||||
604
|
|
||||||
605
|
|
||||||
61C
|
|
||||||
6DD
|
|
||||||
70F
|
|
||||||
890
|
|
||||||
891
|
|
||||||
8E2
|
|
||||||
180E
|
|
||||||
200B
|
|
||||||
200E
|
|
||||||
200F
|
|
||||||
2028
|
|
||||||
2029
|
|
||||||
202A
|
|
||||||
202B
|
|
||||||
202C
|
|
||||||
202D
|
|
||||||
202E
|
|
||||||
2060
|
|
||||||
2061
|
|
||||||
2062
|
|
||||||
2063
|
|
||||||
2064
|
|
||||||
2066
|
|
||||||
2067
|
|
||||||
2068
|
|
||||||
2069
|
|
||||||
206A
|
|
||||||
206B
|
|
||||||
206C
|
|
||||||
206D
|
|
||||||
206E
|
|
||||||
206F
|
|
||||||
FEFF
|
|
||||||
FFF9
|
|
||||||
FFFA
|
|
||||||
FFFB
|
|
||||||
110BD
|
|
||||||
110CD
|
|
||||||
13430
|
|
||||||
13431
|
|
||||||
13432
|
|
||||||
13433
|
|
||||||
13434
|
|
||||||
13435
|
|
||||||
13436
|
|
||||||
13437
|
|
||||||
13438
|
|
||||||
13439
|
|
||||||
1343A
|
|
||||||
1343B
|
|
||||||
1343C
|
|
||||||
1343D
|
|
||||||
1343E
|
|
||||||
1343F
|
|
||||||
1BCA0
|
|
||||||
1BCA1
|
|
||||||
1BCA2
|
|
||||||
1BCA3
|
|
||||||
1D173
|
|
||||||
1D174
|
|
||||||
1D175
|
|
||||||
1D176
|
|
||||||
1D177
|
|
||||||
1D178
|
|
||||||
1D179
|
|
||||||
1D17A
|
|
||||||
E0001
|
|
||||||
E0020
|
|
||||||
E0021
|
|
||||||
E0022
|
|
||||||
E0023
|
|
||||||
E0024
|
|
||||||
E0025
|
|
||||||
E0026
|
|
||||||
E0027
|
|
||||||
E0028
|
|
||||||
E0029
|
|
||||||
E002A
|
|
||||||
E002B
|
|
||||||
E002C
|
|
||||||
E002D
|
|
||||||
E002E
|
|
||||||
E002F
|
|
||||||
E0030
|
|
||||||
E0031
|
|
||||||
E0032
|
|
||||||
E0033
|
|
||||||
E0034
|
|
||||||
E0035
|
|
||||||
E0036
|
|
||||||
E0037
|
|
||||||
E0038
|
|
||||||
E0039
|
|
||||||
E003A
|
|
||||||
E003B
|
|
||||||
E003C
|
|
||||||
E003D
|
|
||||||
E003E
|
|
||||||
E003F
|
|
||||||
E0040
|
|
||||||
E0041
|
|
||||||
E0042
|
|
||||||
E0043
|
|
||||||
E0044
|
|
||||||
E0045
|
|
||||||
E0046
|
|
||||||
E0047
|
|
||||||
E0048
|
|
||||||
E0049
|
|
||||||
E004A
|
|
||||||
E004B
|
|
||||||
E004C
|
|
||||||
E004D
|
|
||||||
E004E
|
|
||||||
E004F
|
|
||||||
E0050
|
|
||||||
E0051
|
|
||||||
E0052
|
|
||||||
E0053
|
|
||||||
E0054
|
|
||||||
E0055
|
|
||||||
E0056
|
|
||||||
E0057
|
|
||||||
E0058
|
|
||||||
E0059
|
|
||||||
E005A
|
|
||||||
E005B
|
|
||||||
E005C
|
|
||||||
E005D
|
|
||||||
E005E
|
|
||||||
E005F
|
|
||||||
E0060
|
|
||||||
E0061
|
|
||||||
E0062
|
|
||||||
E0063
|
|
||||||
E0064
|
|
||||||
E0065
|
|
||||||
E0066
|
|
||||||
E0067
|
|
||||||
E0068
|
|
||||||
E0069
|
|
||||||
E006A
|
|
||||||
E006B
|
|
||||||
E006C
|
|
||||||
E006D
|
|
||||||
E006E
|
|
||||||
E006F
|
|
||||||
E0070
|
|
||||||
E0071
|
|
||||||
E0072
|
|
||||||
E0073
|
|
||||||
E0074
|
|
||||||
E0075
|
|
||||||
E0076
|
|
||||||
E0077
|
|
||||||
E0078
|
|
||||||
E0079
|
|
||||||
E007A
|
|
||||||
E007B
|
|
||||||
E007C
|
|
||||||
E007D
|
|
||||||
E007E
|
|
||||||
E007F
|
|
||||||
|
|
@ -1,169 +0,0 @@
|
||||||
mod common;
|
|
||||||
use common::*;
|
|
||||||
use weksa::packet::{EncoderId, Grade, NodeId, PacketId, Referent};
|
|
||||||
use weksa::{Family, InvId, OptionLabel, OptionSet};
|
|
||||||
|
|
||||||
/// Soul's probe: a whole corpus line, and the snake_case form that would
|
|
||||||
/// pass for an identifier.
|
|
||||||
const LINE: &str = "Take your hand off that control unless you want your nervous system to become my least useful circuit diagram.";
|
|
||||||
const SNAKE: &str = "take_your_hand_off_that_control_unless_you_want_your_nervous_system_to_become_my_least_useful_circuit_diagram";
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn forms_refuse_surface_text() {
|
|
||||||
for text in [LINE, SNAKE, "", " "] {
|
|
||||||
assert!(NodeId::parse(text).is_err(), "NodeId {text:?}");
|
|
||||||
assert!(PacketId::parse(text).is_err(), "PacketId {text:?}");
|
|
||||||
assert!(EncoderId::parse(text).is_err(), "EncoderId {text:?}");
|
|
||||||
assert!(InvId::parse(text).is_err(), "InvId {text:?}");
|
|
||||||
assert!(OptionLabel::parse(text).is_err(), "OptionLabel {text:?}");
|
|
||||||
}
|
|
||||||
// Soul's extension key `nibu.<snake line>` is not an inventory id either.
|
|
||||||
assert!(InvId::parse(&format!("extension:{SNAKE}")).is_err());
|
|
||||||
assert!(InvId::parse(&format!("nibu.{SNAKE}")).is_err());
|
|
||||||
// NodeId is n<k>, k canonical 1..=9999.
|
|
||||||
for ok in ["n1", "n10", "n9999"] {
|
|
||||||
assert_eq!(NodeId::parse(ok).unwrap().as_str(), ok);
|
|
||||||
}
|
|
||||||
for bad in [
|
|
||||||
"n0", "n01", "n+1", "n-1", "n10000", "n", "1", "N1", "n1 ", "r1", "n1x",
|
|
||||||
] {
|
|
||||||
assert!(NodeId::parse(bad).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
// PacketId and EncoderId are a prefix and exactly 16 lowercase hex digits.
|
|
||||||
assert!(PacketId::parse(PACKET_ID).is_ok());
|
|
||||||
assert!(EncoderId::parse(ENCODER_ID).is_ok());
|
|
||||||
for bad in [
|
|
||||||
"packet:0123456789abcde",
|
|
||||||
"packet:0123456789abcdef0",
|
|
||||||
"packet:0123456789ABCDEF",
|
|
||||||
"packet:0123456789abcdeg",
|
|
||||||
"encoder:0123456789abcdef",
|
|
||||||
"0123456789abcdef",
|
|
||||||
"packet:item:nibu:1:r2:abc",
|
|
||||||
] {
|
|
||||||
assert!(PacketId::parse(bad).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
assert!(EncoderId::parse("packet:0123456789abcdef").is_err());
|
|
||||||
assert!(EncoderId::parse("encoder:0123456789abcdeg").is_err());
|
|
||||||
assert!(EncoderId::parse("encoder:0123456789ABCDEF").is_err());
|
|
||||||
assert!(EncoderId::parse("encoder:0123456789abcde").is_err());
|
|
||||||
assert!(EncoderId::parse("encoder:0123456789abcdef0").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_refusal_names_the_form_and_keeps_the_value_out_of_its_text() {
|
|
||||||
let e = NodeId::parse("n0").unwrap_err();
|
|
||||||
assert_eq!(e.form, "NodeId");
|
|
||||||
assert_eq!(e.got, "n0");
|
|
||||||
assert_eq!(e.to_string(), "not a NodeId");
|
|
||||||
assert_eq!(Grade::new(1001).unwrap_err().to_string(), "not a Grade");
|
|
||||||
assert_eq!(EncoderId::parse(ENCODER_ID).unwrap().as_str(), ENCODER_ID);
|
|
||||||
assert_eq!(PacketId::parse(PACKET_ID).unwrap().as_str(), PACKET_ID);
|
|
||||||
assert_eq!(
|
|
||||||
EncoderId::parse(ENCODER_ID).unwrap().to_string(),
|
|
||||||
ENCODER_ID
|
|
||||||
);
|
|
||||||
assert_eq!(lab("potential").as_str(), "potential");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_malformed_value_does_not_deserialize() {
|
|
||||||
// A node id that is the snake line fails where a store would read it.
|
|
||||||
let mut referent = serde_json::to_value(good().referents[0].clone()).unwrap();
|
|
||||||
assert!(serde_json::from_value::<Referent>(referent.clone()).is_ok());
|
|
||||||
referent["id"] = SNAKE.into();
|
|
||||||
assert!(serde_json::from_value::<Referent>(referent.clone()).is_err());
|
|
||||||
referent["id"] = "n1".into();
|
|
||||||
referent["concept"] = "concept:01".into();
|
|
||||||
assert!(serde_json::from_value::<Referent>(referent).is_err());
|
|
||||||
assert!(serde_json::from_str::<Grade>("1001").is_err());
|
|
||||||
assert_eq!(serde_json::from_str::<Grade>("1000").unwrap().get(), 1000);
|
|
||||||
assert!(serde_json::from_str::<OptionSet>("[]").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn inv_id_canonical() {
|
|
||||||
for bad in [
|
|
||||||
"concept:01",
|
|
||||||
"concept:+1",
|
|
||||||
"concept:0",
|
|
||||||
"concept:-1",
|
|
||||||
"concept:",
|
|
||||||
"concept:1x",
|
|
||||||
"concept: 1",
|
|
||||||
"nofamily:1",
|
|
||||||
"Concept:1",
|
|
||||||
"concept",
|
|
||||||
"concept:99999999999",
|
|
||||||
"concept:1:2",
|
|
||||||
] {
|
|
||||||
assert!(InvId::parse(bad).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
let id = InvId::parse("concept:1").unwrap();
|
|
||||||
assert_eq!(id.family(), Family::Concept);
|
|
||||||
assert_eq!(id.to_string(), "concept:1");
|
|
||||||
for f in Family::ALL {
|
|
||||||
let id = InvId::parse(&format!("{}:12", f.prefix())).unwrap();
|
|
||||||
assert_eq!(id.family(), f);
|
|
||||||
assert_eq!(id.to_string(), format!("{}:12", f.prefix()));
|
|
||||||
}
|
|
||||||
assert_eq!(iv("extension:1").family(), Family::Extension);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn options_bounded() {
|
|
||||||
let labels = |n: usize| (0..n).map(|i| lab(&format!("l{i}"))).collect::<Vec<_>>();
|
|
||||||
assert!(OptionSet::new(labels(0)).is_err());
|
|
||||||
assert!(OptionSet::new(labels(1)).is_ok());
|
|
||||||
assert!(OptionSet::new(labels(16)).is_ok());
|
|
||||||
assert!(OptionSet::new(labels(17)).is_err());
|
|
||||||
assert!(OptionSet::new(vec![lab("a"), lab("a")]).is_err());
|
|
||||||
assert!(OptionSet::new(vec![lab("a"), lab("b"), lab("a")]).is_err());
|
|
||||||
// Soul's probe: the snake line is not a label; labels are short snake words.
|
|
||||||
assert!(OptionLabel::parse(SNAKE).is_err());
|
|
||||||
assert!(OptionLabel::parse(&"a".repeat(24)).is_ok());
|
|
||||||
assert!(OptionLabel::parse(&"a".repeat(25)).is_err());
|
|
||||||
for bad in ["A", "1a", "_a", "a-b", "a b", "a.b", "\u{e9}"] {
|
|
||||||
assert!(OptionLabel::parse(bad).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
for ok in ["a", "a1", "a_b", "potential"] {
|
|
||||||
assert!(OptionLabel::parse(ok).is_ok(), "{ok:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn grade_bound_is_the_type() {
|
|
||||||
assert!(Grade::new(1001).is_err());
|
|
||||||
assert_eq!(Grade::new(1000).unwrap().get(), 1000);
|
|
||||||
assert_eq!(Grade::new(0).unwrap().get(), 0);
|
|
||||||
// The published schema carries the same bound.
|
|
||||||
let (_, json) = weksa::schema::published()
|
|
||||||
.into_iter()
|
|
||||||
.find(|(n, _)| n == "weksa.interlingua_packet.schema.json")
|
|
||||||
.unwrap();
|
|
||||||
let schema: serde_json::Value = serde_json::from_str(&json).unwrap();
|
|
||||||
let grade = &schema["$defs"]["Grade"];
|
|
||||||
assert_eq!(grade["maximum"], 1000, "{grade}");
|
|
||||||
assert_eq!(grade["minimum"], 0, "{grade}");
|
|
||||||
assert_eq!(schema["$defs"]["NodeId"]["pattern"], "^n[1-9][0-9]{0,3}$");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn calendar_dates_follow_the_gregorian_rule_and_ascii_digits_only() {
|
|
||||||
use weksa::form::is_calendar_date;
|
|
||||||
for ok in ["2024-02-29", "2000-02-29", "2026-12-31"] {
|
|
||||||
assert!(is_calendar_date(ok), "{ok}");
|
|
||||||
}
|
|
||||||
for bad in [
|
|
||||||
"1900-02-29",
|
|
||||||
"2023-02-29",
|
|
||||||
"2026-04-31",
|
|
||||||
"2026-10-00",
|
|
||||||
"2026-00-10",
|
|
||||||
"+026-10-29",
|
|
||||||
"2026-10-2\u{669}",
|
|
||||||
"\u{6f0}026-10-29",
|
|
||||||
] {
|
|
||||||
assert!(!is_calendar_date(bad), "{bad}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,306 +0,0 @@
|
||||||
//! The entity port, `pronounce` and `phones` against the committed stores and
|
|
||||||
//! the `nibu-proof-001` packet.
|
|
||||||
|
|
||||||
mod common;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use weksa::entity::{Entity, EntityOrigin, LanguageForms};
|
|
||||||
use weksa::packet::{EntityId, Packet, proof_packet};
|
|
||||||
use weksa::{
|
|
||||||
CorpusStore, EntityForms, EntityStore, Inventory, InventoryStore, LowerError, LoweringInput,
|
|
||||||
PacketStore, PhoneInventory, PhoneLine, Pronunciation, Stress, pronounce,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn committed() -> (Inventory, tempfile::TempDir) {
|
|
||||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
|
||||||
let inv = InventoryStore::open(&root.join("data/interlingua/inventory.cc")).unwrap();
|
|
||||||
(inv.inventory().unwrap(), tempfile::tempdir().unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A `LoweringInput` has one source, `PacketStore::admit`, so every packet
|
|
||||||
/// under test goes through a throwaway store backed by the committed stores.
|
|
||||||
fn view(packet: &Packet, _inv: &Inventory) -> LoweringInput {
|
|
||||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
|
||||||
let inventory = InventoryStore::open(&root.join("data/interlingua/inventory.cc")).unwrap();
|
|
||||||
admitted(packet, &inventory)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same door against an inventory store the test built.
|
|
||||||
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 committed_entities() -> EntityStore {
|
|
||||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
|
||||||
EntityStore::open(&root.join("data/entity/entity.cc")).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An entity port a test controls: ids to entities, and an optional read fault.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Entities {
|
|
||||||
held: Vec<Entity>,
|
|
||||||
fault: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EntityForms for Entities {
|
|
||||||
fn entity(&self, id: &EntityId) -> anyhow::Result<Option<Entity>> {
|
|
||||||
if self.fault {
|
|
||||||
anyhow::bail!("store unreadable");
|
|
||||||
}
|
|
||||||
Ok(self.held.iter().find(|e| &e.id == id).cloned())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nibu(forms: &[(&str, &[&str])]) -> Entity {
|
|
||||||
Entity {
|
|
||||||
id: EntityId::parse("entity:nibu").unwrap(),
|
|
||||||
forms: forms
|
|
||||||
.iter()
|
|
||||||
.map(|(language, forms)| LanguageForms {
|
|
||||||
language: (*language).into(),
|
|
||||||
forms: forms.iter().map(|f| (*f).into()).collect(),
|
|
||||||
pronunciation: None,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
origin: EntityOrigin::Cast {
|
|
||||||
persona: "nibu".into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ruled(ipa: &str, rejected: &[&str]) -> Pronunciation {
|
|
||||||
Pronunciation {
|
|
||||||
ipa: ipa.into(),
|
|
||||||
ruled_by: "Nibu".into(),
|
|
||||||
date: "2026-11-07".into(),
|
|
||||||
source: "test".into(),
|
|
||||||
rejected: rejected.iter().map(|r| (*r).into()).collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn say(entities: &dyn EntityForms) -> Result<Vec<String>, LowerError> {
|
|
||||||
let (inv, _dir) = committed();
|
|
||||||
pronounce(&view(&proof_packet(), &inv), entities)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_failing_entity_port_is_refused_by_name() {
|
|
||||||
let e = Entities {
|
|
||||||
fault: true,
|
|
||||||
..Entities::default()
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
say(&e),
|
|
||||||
Err(LowerError::EntityRead {
|
|
||||||
entity: EntityId::parse("entity:nibu").unwrap(),
|
|
||||||
why: "store unreadable".into()
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nibu_round_trips_from_the_committed_seed_to_its_ruled_ipa() {
|
|
||||||
let seed = committed_entities();
|
|
||||||
let nibu = seed
|
|
||||||
.get(&EntityId::parse("entity:nibu").unwrap())
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let p = nibu.pronunciation_in("en-US").unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(p.ipa.as_str(), p.ruled_by.as_str(), p.date.as_str()),
|
|
||||||
("ˈnibu", "Nibu", "2026-11-07")
|
|
||||||
);
|
|
||||||
assert_eq!(say(&seed).unwrap(), ["ˈnibu"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_rejected_pronunciation_is_never_emitted() {
|
|
||||||
let mut e = Entities::default();
|
|
||||||
let mut n = nibu(&[("en-US", &["Nibu"])]);
|
|
||||||
n.forms[0].pronunciation = Some(ruled("ˈnibu", &["ˈnɪbu", "ˈnaɪbu"]));
|
|
||||||
e.held.push(n);
|
|
||||||
assert_eq!(say(&e).unwrap(), ["ˈnibu"]);
|
|
||||||
// The committed seed carries the same rejection and still says only the ruling.
|
|
||||||
let seed = say(&committed_entities()).unwrap().concat();
|
|
||||||
assert!(!seed.contains('ɪ'), "{seed}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_entity_with_no_ruled_pronunciation_is_refused_not_spelled_out() {
|
|
||||||
let id = EntityId::parse("entity:nibu").unwrap();
|
|
||||||
// No pronunciation at all.
|
|
||||||
let mut e = Entities::default();
|
|
||||||
e.held.push(nibu(&[("en-US", &["Nibu"])]));
|
|
||||||
assert_eq!(
|
|
||||||
say(&e),
|
|
||||||
Err(LowerError::NoPronunciation { entity: id.clone() })
|
|
||||||
);
|
|
||||||
// A pronunciation under another language is not the target language's.
|
|
||||||
let mut n = nibu(&[("sa-Latn", &["Nibuwa"]), ("en-US", &["Nibu"])]);
|
|
||||||
n.forms[0].pronunciation = Some(ruled("ˈnibuwa", &[]));
|
|
||||||
let mut e = Entities::default();
|
|
||||||
e.held.push(n);
|
|
||||||
assert_eq!(say(&e), Err(LowerError::NoPronunciation { entity: id }));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ipa_needs_an_entity_the_port_holds_and_a_packet_that_cites_one() {
|
|
||||||
assert_eq!(
|
|
||||||
say(&Entities::default()),
|
|
||||||
Err(LowerError::UnknownEntity {
|
|
||||||
entity: EntityId::parse("entity:nibu").unwrap()
|
|
||||||
})
|
|
||||||
);
|
|
||||||
let (inv, _dir) = committed();
|
|
||||||
let mut p = proof_packet();
|
|
||||||
p.referents[2].entity = None;
|
|
||||||
assert_eq!(
|
|
||||||
pronounce(&view(&p, &inv), &committed_entities()),
|
|
||||||
Err(LowerError::NoEntityReferent)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- the phones line: the phone inventory and the segmenter ----
|
|
||||||
|
|
||||||
fn phones_of(ipa: &str) -> Result<Vec<PhoneLine>, LowerError> {
|
|
||||||
let mut n = nibu(&[("en-US", &["Nibu"])]);
|
|
||||||
n.forms[0].pronunciation = Some(ruled(ipa, &[]));
|
|
||||||
let mut e = Entities::default();
|
|
||||||
e.held.push(n);
|
|
||||||
let (inv, _dir) = committed();
|
|
||||||
weksa::phones(&view(&proof_packet(), &inv), &e)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn seg(ipa: &str) -> Vec<(String, Stress)> {
|
|
||||||
let inv = PhoneInventory::for_language("en-US").unwrap();
|
|
||||||
inv.segment(ipa)
|
|
||||||
.unwrap()
|
|
||||||
.into_iter()
|
|
||||||
.map(|p| (p.ipa, p.stress))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pairs(v: &[(&str, Stress)]) -> Vec<(String, Stress)> {
|
|
||||||
v.iter().map(|(i, s)| ((*i).to_string(), *s)).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nibus_committed_ruling_lowers_to_the_committed_phones_fixture() {
|
|
||||||
let (inv, _dir) = committed();
|
|
||||||
let lines = weksa::phones(&view(&proof_packet(), &inv), &committed_entities()).unwrap();
|
|
||||||
let fixture = std::fs::read_to_string(
|
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
||||||
.join("../../data/phonology/fixtures/nibu-en-US.phones.json"),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(lines.len(), 1);
|
|
||||||
assert_eq!(serde_json::to_string(&lines[0]).unwrap(), fixture.trim_end());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tense_i_is_a_phone_and_the_rejected_lax_form_is_a_different_one() {
|
|
||||||
use weksa::phones::{Class, Tenseness};
|
|
||||||
let inv = PhoneInventory::for_language("en-US").unwrap();
|
|
||||||
assert_eq!(inv.class("i"), Some(&Class::Vowel(Tenseness::Tense)));
|
|
||||||
assert_eq!(inv.class("ɪ"), Some(&Class::Vowel(Tenseness::Lax)));
|
|
||||||
assert_eq!(inv.class("u"), Some(&Class::Vowel(Tenseness::Tense)));
|
|
||||||
let ruled_form = seg("ˈnibu");
|
|
||||||
let lax = seg("ˈnɪbu");
|
|
||||||
assert_ne!(ruled_form, lax);
|
|
||||||
assert_eq!(lax[1], ("ɪ".to_string(), Stress::Primary));
|
|
||||||
// The committed seed rejects the lax form, and it is not what the seed emits.
|
|
||||||
let seed = committed_entities();
|
|
||||||
let nibu = seed.get(&EntityId::parse("entity:nibu").unwrap()).unwrap().unwrap();
|
|
||||||
let p = nibu.pronunciation_in("en-US").unwrap();
|
|
||||||
assert_eq!(p.rejected, ["ˈnɪbu"]);
|
|
||||||
assert_eq!(seg(&p.ipa), ruled_form);
|
|
||||||
assert!(p.rejected.iter().all(|r| seg(r) != seg(&p.ipa)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stress_lands_on_the_vowel_after_the_mark_and_nowhere_else() {
|
|
||||||
use Stress::{None as N, Primary as P, Secondary as S};
|
|
||||||
assert_eq!(seg("ˈnibu"), pairs(&[("n", N), ("i", P), ("b", N), ("u", N)]));
|
|
||||||
assert_eq!(seg("nˈibu"), seg("ˈnibu"));
|
|
||||||
assert_eq!(seg("bˈunˌi"), pairs(&[("b", N), ("u", P), ("n", N), ("i", S)]));
|
|
||||||
assert_eq!(seg("nibu"), pairs(&[("n", N), ("i", N), ("b", N), ("u", N)]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn multi_character_phones_are_one_phone_by_longest_match() {
|
|
||||||
use Stress::{None as N, Primary as P};
|
|
||||||
assert_eq!(seg("ˈtʃeɪ"), pairs(&[("tʃ", N), ("eɪ", P)]));
|
|
||||||
assert_eq!(seg("dʒaʊ"), pairs(&[("dʒ", N), ("aʊ", N)]));
|
|
||||||
// /t/ then /ʃ/ is not what a lone "t" and "ʃ" mean when the affricate is listed,
|
|
||||||
// but a symbol sequence the inventory cannot join still splits.
|
|
||||||
assert_eq!(seg("ɔɪt"), pairs(&[("ɔɪ", N), ("t", N)]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_phone_the_inventory_lacks_is_refused_with_where_and_never_guessed() {
|
|
||||||
let id = EntityId::parse("entity:nibu").unwrap();
|
|
||||||
for (ipa, at, text) in [
|
|
||||||
("ˈnixu", "ˈni".len(), "xu"),
|
|
||||||
("ˈniːbu", "ˈni".len(), "ːbu"),
|
|
||||||
("ˈnibu.", "ˈnibu".len(), "."),
|
|
||||||
("ˈni bu", "ˈni".len(), " bu"),
|
|
||||||
] {
|
|
||||||
assert_eq!(
|
|
||||||
phones_of(ipa),
|
|
||||||
Err(LowerError::UnknownPhone { entity: id.clone(), at, text: text.into() }),
|
|
||||||
"{ipa}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_stress_mark_with_no_vowel_to_land_on_is_refused() {
|
|
||||||
let id = EntityId::parse("entity:nibu").unwrap();
|
|
||||||
for (ipa, at) in [("nibuˈ", "nibu".len()), ("ˈˈnibu", 0), ("ˈnˈibu", 0), ("ˈnb", 0)] {
|
|
||||||
assert_eq!(
|
|
||||||
phones_of(ipa),
|
|
||||||
Err(LowerError::DanglingStress { entity: id.clone(), at }),
|
|
||||||
"{ipa}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn phones_need_a_ruling_and_an_entity_exactly_as_ipa_does() {
|
|
||||||
assert_eq!(
|
|
||||||
weksa::phones(&view(&proof_packet(), &committed().0), &Entities::default()),
|
|
||||||
Err(LowerError::UnknownEntity { entity: EntityId::parse("entity:nibu").unwrap() })
|
|
||||||
);
|
|
||||||
let mut e = Entities::default();
|
|
||||||
e.held.push(nibu(&[("en-US", &["Nibu"])]));
|
|
||||||
assert_eq!(
|
|
||||||
weksa::phones(&view(&proof_packet(), &committed().0), &e),
|
|
||||||
Err(LowerError::NoPronunciation { entity: EntityId::parse("entity:nibu").unwrap() })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_inventory_parser_refuses_what_it_cannot_read() {
|
|
||||||
for bad in [
|
|
||||||
"i\tvowel\ttense",
|
|
||||||
"i\tvowel\t-\tx",
|
|
||||||
"n\tconsonant\ttense\tx",
|
|
||||||
"i\tvowel\tmid\tx",
|
|
||||||
"ˈi\tvowel\ttense\tx",
|
|
||||||
"\tvowel\ttense\tx",
|
|
||||||
"i\tvowel\ttense\t",
|
|
||||||
"i\tvowel\ttense\ta\ni\tvowel\tlax\tb",
|
|
||||||
] {
|
|
||||||
assert!(PhoneInventory::parse(bad).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
assert!(PhoneInventory::parse("# c\n\ni\tvowel\ttense\ta\n").is_ok());
|
|
||||||
assert!(PhoneInventory::for_language("sa-Latn").is_none());
|
|
||||||
}
|
|
||||||
|
|
@ -1,411 +0,0 @@
|
||||||
# Lm, Node 24 (Unicode 17.0) over 0..10FFFF, one hex code point per line
|
|
||||||
2B0
|
|
||||||
2B1
|
|
||||||
2B2
|
|
||||||
2B3
|
|
||||||
2B4
|
|
||||||
2B5
|
|
||||||
2B6
|
|
||||||
2B7
|
|
||||||
2B8
|
|
||||||
2B9
|
|
||||||
2BA
|
|
||||||
2BB
|
|
||||||
2BC
|
|
||||||
2BD
|
|
||||||
2BE
|
|
||||||
2BF
|
|
||||||
2C0
|
|
||||||
2C1
|
|
||||||
2C6
|
|
||||||
2C7
|
|
||||||
2C8
|
|
||||||
2C9
|
|
||||||
2CA
|
|
||||||
2CB
|
|
||||||
2CC
|
|
||||||
2CD
|
|
||||||
2CE
|
|
||||||
2CF
|
|
||||||
2D0
|
|
||||||
2D1
|
|
||||||
2E0
|
|
||||||
2E1
|
|
||||||
2E2
|
|
||||||
2E3
|
|
||||||
2E4
|
|
||||||
2EC
|
|
||||||
2EE
|
|
||||||
374
|
|
||||||
37A
|
|
||||||
559
|
|
||||||
640
|
|
||||||
6E5
|
|
||||||
6E6
|
|
||||||
7F4
|
|
||||||
7F5
|
|
||||||
7FA
|
|
||||||
81A
|
|
||||||
824
|
|
||||||
828
|
|
||||||
8C9
|
|
||||||
971
|
|
||||||
E46
|
|
||||||
EC6
|
|
||||||
10FC
|
|
||||||
17D7
|
|
||||||
1843
|
|
||||||
1AA7
|
|
||||||
1C78
|
|
||||||
1C79
|
|
||||||
1C7A
|
|
||||||
1C7B
|
|
||||||
1C7C
|
|
||||||
1C7D
|
|
||||||
1D2C
|
|
||||||
1D2D
|
|
||||||
1D2E
|
|
||||||
1D2F
|
|
||||||
1D30
|
|
||||||
1D31
|
|
||||||
1D32
|
|
||||||
1D33
|
|
||||||
1D34
|
|
||||||
1D35
|
|
||||||
1D36
|
|
||||||
1D37
|
|
||||||
1D38
|
|
||||||
1D39
|
|
||||||
1D3A
|
|
||||||
1D3B
|
|
||||||
1D3C
|
|
||||||
1D3D
|
|
||||||
1D3E
|
|
||||||
1D3F
|
|
||||||
1D40
|
|
||||||
1D41
|
|
||||||
1D42
|
|
||||||
1D43
|
|
||||||
1D44
|
|
||||||
1D45
|
|
||||||
1D46
|
|
||||||
1D47
|
|
||||||
1D48
|
|
||||||
1D49
|
|
||||||
1D4A
|
|
||||||
1D4B
|
|
||||||
1D4C
|
|
||||||
1D4D
|
|
||||||
1D4E
|
|
||||||
1D4F
|
|
||||||
1D50
|
|
||||||
1D51
|
|
||||||
1D52
|
|
||||||
1D53
|
|
||||||
1D54
|
|
||||||
1D55
|
|
||||||
1D56
|
|
||||||
1D57
|
|
||||||
1D58
|
|
||||||
1D59
|
|
||||||
1D5A
|
|
||||||
1D5B
|
|
||||||
1D5C
|
|
||||||
1D5D
|
|
||||||
1D5E
|
|
||||||
1D5F
|
|
||||||
1D60
|
|
||||||
1D61
|
|
||||||
1D62
|
|
||||||
1D63
|
|
||||||
1D64
|
|
||||||
1D65
|
|
||||||
1D66
|
|
||||||
1D67
|
|
||||||
1D68
|
|
||||||
1D69
|
|
||||||
1D6A
|
|
||||||
1D78
|
|
||||||
1D9B
|
|
||||||
1D9C
|
|
||||||
1D9D
|
|
||||||
1D9E
|
|
||||||
1D9F
|
|
||||||
1DA0
|
|
||||||
1DA1
|
|
||||||
1DA2
|
|
||||||
1DA3
|
|
||||||
1DA4
|
|
||||||
1DA5
|
|
||||||
1DA6
|
|
||||||
1DA7
|
|
||||||
1DA8
|
|
||||||
1DA9
|
|
||||||
1DAA
|
|
||||||
1DAB
|
|
||||||
1DAC
|
|
||||||
1DAD
|
|
||||||
1DAE
|
|
||||||
1DAF
|
|
||||||
1DB0
|
|
||||||
1DB1
|
|
||||||
1DB2
|
|
||||||
1DB3
|
|
||||||
1DB4
|
|
||||||
1DB5
|
|
||||||
1DB6
|
|
||||||
1DB7
|
|
||||||
1DB8
|
|
||||||
1DB9
|
|
||||||
1DBA
|
|
||||||
1DBB
|
|
||||||
1DBC
|
|
||||||
1DBD
|
|
||||||
1DBE
|
|
||||||
1DBF
|
|
||||||
2071
|
|
||||||
207F
|
|
||||||
2090
|
|
||||||
2091
|
|
||||||
2092
|
|
||||||
2093
|
|
||||||
2094
|
|
||||||
2095
|
|
||||||
2096
|
|
||||||
2097
|
|
||||||
2098
|
|
||||||
2099
|
|
||||||
209A
|
|
||||||
209B
|
|
||||||
209C
|
|
||||||
2C7C
|
|
||||||
2C7D
|
|
||||||
2D6F
|
|
||||||
2E2F
|
|
||||||
3005
|
|
||||||
3031
|
|
||||||
3032
|
|
||||||
3033
|
|
||||||
3034
|
|
||||||
3035
|
|
||||||
303B
|
|
||||||
309D
|
|
||||||
309E
|
|
||||||
30FC
|
|
||||||
30FD
|
|
||||||
30FE
|
|
||||||
A015
|
|
||||||
A4F8
|
|
||||||
A4F9
|
|
||||||
A4FA
|
|
||||||
A4FB
|
|
||||||
A4FC
|
|
||||||
A4FD
|
|
||||||
A60C
|
|
||||||
A67F
|
|
||||||
A69C
|
|
||||||
A69D
|
|
||||||
A717
|
|
||||||
A718
|
|
||||||
A719
|
|
||||||
A71A
|
|
||||||
A71B
|
|
||||||
A71C
|
|
||||||
A71D
|
|
||||||
A71E
|
|
||||||
A71F
|
|
||||||
A770
|
|
||||||
A788
|
|
||||||
A7F1
|
|
||||||
A7F2
|
|
||||||
A7F3
|
|
||||||
A7F4
|
|
||||||
A7F8
|
|
||||||
A7F9
|
|
||||||
A9CF
|
|
||||||
A9E6
|
|
||||||
AA70
|
|
||||||
AADD
|
|
||||||
AAF3
|
|
||||||
AAF4
|
|
||||||
AB5C
|
|
||||||
AB5D
|
|
||||||
AB5E
|
|
||||||
AB5F
|
|
||||||
AB69
|
|
||||||
FF70
|
|
||||||
FF9E
|
|
||||||
FF9F
|
|
||||||
10780
|
|
||||||
10781
|
|
||||||
10782
|
|
||||||
10783
|
|
||||||
10784
|
|
||||||
10785
|
|
||||||
10787
|
|
||||||
10788
|
|
||||||
10789
|
|
||||||
1078A
|
|
||||||
1078B
|
|
||||||
1078C
|
|
||||||
1078D
|
|
||||||
1078E
|
|
||||||
1078F
|
|
||||||
10790
|
|
||||||
10791
|
|
||||||
10792
|
|
||||||
10793
|
|
||||||
10794
|
|
||||||
10795
|
|
||||||
10796
|
|
||||||
10797
|
|
||||||
10798
|
|
||||||
10799
|
|
||||||
1079A
|
|
||||||
1079B
|
|
||||||
1079C
|
|
||||||
1079D
|
|
||||||
1079E
|
|
||||||
1079F
|
|
||||||
107A0
|
|
||||||
107A1
|
|
||||||
107A2
|
|
||||||
107A3
|
|
||||||
107A4
|
|
||||||
107A5
|
|
||||||
107A6
|
|
||||||
107A7
|
|
||||||
107A8
|
|
||||||
107A9
|
|
||||||
107AA
|
|
||||||
107AB
|
|
||||||
107AC
|
|
||||||
107AD
|
|
||||||
107AE
|
|
||||||
107AF
|
|
||||||
107B0
|
|
||||||
107B2
|
|
||||||
107B3
|
|
||||||
107B4
|
|
||||||
107B5
|
|
||||||
107B6
|
|
||||||
107B7
|
|
||||||
107B8
|
|
||||||
107B9
|
|
||||||
107BA
|
|
||||||
10D4E
|
|
||||||
10D6F
|
|
||||||
10EC5
|
|
||||||
11DD9
|
|
||||||
16B40
|
|
||||||
16B41
|
|
||||||
16B42
|
|
||||||
16B43
|
|
||||||
16D40
|
|
||||||
16D41
|
|
||||||
16D42
|
|
||||||
16D6B
|
|
||||||
16D6C
|
|
||||||
16F93
|
|
||||||
16F94
|
|
||||||
16F95
|
|
||||||
16F96
|
|
||||||
16F97
|
|
||||||
16F98
|
|
||||||
16F99
|
|
||||||
16F9A
|
|
||||||
16F9B
|
|
||||||
16F9C
|
|
||||||
16F9D
|
|
||||||
16F9E
|
|
||||||
16F9F
|
|
||||||
16FE0
|
|
||||||
16FE1
|
|
||||||
16FE3
|
|
||||||
16FF2
|
|
||||||
16FF3
|
|
||||||
1AFF0
|
|
||||||
1AFF1
|
|
||||||
1AFF2
|
|
||||||
1AFF3
|
|
||||||
1AFF5
|
|
||||||
1AFF6
|
|
||||||
1AFF7
|
|
||||||
1AFF8
|
|
||||||
1AFF9
|
|
||||||
1AFFA
|
|
||||||
1AFFB
|
|
||||||
1AFFD
|
|
||||||
1AFFE
|
|
||||||
1E030
|
|
||||||
1E031
|
|
||||||
1E032
|
|
||||||
1E033
|
|
||||||
1E034
|
|
||||||
1E035
|
|
||||||
1E036
|
|
||||||
1E037
|
|
||||||
1E038
|
|
||||||
1E039
|
|
||||||
1E03A
|
|
||||||
1E03B
|
|
||||||
1E03C
|
|
||||||
1E03D
|
|
||||||
1E03E
|
|
||||||
1E03F
|
|
||||||
1E040
|
|
||||||
1E041
|
|
||||||
1E042
|
|
||||||
1E043
|
|
||||||
1E044
|
|
||||||
1E045
|
|
||||||
1E046
|
|
||||||
1E047
|
|
||||||
1E048
|
|
||||||
1E049
|
|
||||||
1E04A
|
|
||||||
1E04B
|
|
||||||
1E04C
|
|
||||||
1E04D
|
|
||||||
1E04E
|
|
||||||
1E04F
|
|
||||||
1E050
|
|
||||||
1E051
|
|
||||||
1E052
|
|
||||||
1E053
|
|
||||||
1E054
|
|
||||||
1E055
|
|
||||||
1E056
|
|
||||||
1E057
|
|
||||||
1E058
|
|
||||||
1E059
|
|
||||||
1E05A
|
|
||||||
1E05B
|
|
||||||
1E05C
|
|
||||||
1E05D
|
|
||||||
1E05E
|
|
||||||
1E05F
|
|
||||||
1E060
|
|
||||||
1E061
|
|
||||||
1E062
|
|
||||||
1E063
|
|
||||||
1E064
|
|
||||||
1E065
|
|
||||||
1E066
|
|
||||||
1E067
|
|
||||||
1E068
|
|
||||||
1E069
|
|
||||||
1E06A
|
|
||||||
1E06B
|
|
||||||
1E06C
|
|
||||||
1E06D
|
|
||||||
1E137
|
|
||||||
1E138
|
|
||||||
1E139
|
|
||||||
1E13A
|
|
||||||
1E13B
|
|
||||||
1E13C
|
|
||||||
1E13D
|
|
||||||
1E4EB
|
|
||||||
1E6FF
|
|
||||||
1E94B
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
//! Pins for behaviour of the small and middle weksa files that mutation testing
|
|
||||||
//! found unpinned. Each test states the behaviour in domain terms.
|
|
||||||
|
|
||||||
use weksa::form::is_calendar_date;
|
|
||||||
|
|
||||||
/// A calendar date is exactly `YYYY-MM-DD`: both hyphens sit where the format
|
|
||||||
/// puts them, so a ten-byte string with a digit in the second hyphen's place is
|
|
||||||
/// no date.
|
|
||||||
#[test]
|
|
||||||
fn a_calendar_date_needs_both_hyphens_in_place() {
|
|
||||||
assert!(is_calendar_date("2026-01-01"));
|
|
||||||
assert!(!is_calendar_date("2026-01201"));
|
|
||||||
assert!(!is_calendar_date("2026101-01"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// February has 29 days in a Gregorian leap year and 28 otherwise.
|
|
||||||
#[test]
|
|
||||||
fn february_has_29_days_only_in_gregorian_leap_years() {
|
|
||||||
assert!(is_calendar_date("2024-02-29"));
|
|
||||||
assert!(is_calendar_date("2000-02-29"));
|
|
||||||
assert!(!is_calendar_date("1900-02-29"));
|
|
||||||
assert!(!is_calendar_date("2023-02-29"));
|
|
||||||
assert!(is_calendar_date("2023-02-28"));
|
|
||||||
assert!(!is_calendar_date("2024-02-30"));
|
|
||||||
}
|
|
||||||
|
|
@ -1,297 +0,0 @@
|
||||||
//! Pins found by mutation testing store.rs, inventory.rs and main.rs. Each test
|
|
||||||
//! states what the production code must do, in domain terms.
|
|
||||||
mod common;
|
|
||||||
use common::*;
|
|
||||||
use std::process::{Command, Output};
|
|
||||||
use weksa::packet::Grade;
|
|
||||||
use weksa::store::EntityBound;
|
|
||||||
use weksa::{
|
|
||||||
Annotator, Condition, EntityStore, Layer, OntologyEntry, OntologyStore, Pronunciation, Refusal,
|
|
||||||
Slot, StoreError, StoreRefusal, Test,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn refusal<T: std::fmt::Debug>(r: Result<T, StoreError>) -> StoreRefusal {
|
|
||||||
match r {
|
|
||||||
Err(StoreError::Refused(r)) => r,
|
|
||||||
other => panic!("expected a store refusal, got {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kay_saying(p: Pronunciation) -> weksa::Entity {
|
|
||||||
let mut e = ent("kay", "en-US", &["Kay"]);
|
|
||||||
e.forms[0].pronunciation = Some(p);
|
|
||||||
e
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ruling(ipa: &str, rejected: Vec<String>) -> Pronunciation {
|
|
||||||
Pronunciation {
|
|
||||||
ipa: ipa.into(),
|
|
||||||
ruled_by: "Kay".into(),
|
|
||||||
date: "2026-11-07".into(),
|
|
||||||
source: "test".into(),
|
|
||||||
rejected,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_pronunciation_with_a_control_or_invisible_format_character_is_refused() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
// Either kind alone is refused: a control character, and a zero-width space.
|
|
||||||
for ipa in ["ˈk\u{7}eɪ", "ˈk\u{200b}eɪ"] {
|
|
||||||
assert!(
|
|
||||||
matches!(
|
|
||||||
store.put(kay_saying(ruling(ipa, vec![]))),
|
|
||||||
Err(StoreError::Refused(StoreRefusal::Malformed { .. }))
|
|
||||||
),
|
|
||||||
"{ipa:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// The same for a rejected pronunciation.
|
|
||||||
for bad in ["ˈk\u{7}aɪ", "ˈk\u{200b}aɪ"] {
|
|
||||||
assert!(
|
|
||||||
matches!(
|
|
||||||
store.put(kay_saying(ruling("ˈkeɪ", vec![bad.into()]))),
|
|
||||||
Err(StoreError::Refused(StoreRefusal::Malformed { .. }))
|
|
||||||
),
|
|
||||||
"{bad:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(store.get(&eid("kay")).unwrap(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_pronunciation_keeps_at_most_eight_rejected_variants() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = EntityStore::open(&d.path().join("e.cc")).unwrap();
|
|
||||||
let variants = |n: usize| -> Vec<String> { (0..n).map(|i| format!("ˈkaɪ{i}")).collect() };
|
|
||||||
assert_eq!(
|
|
||||||
refusal(store.put(kay_saying(ruling("ˈkeɪ", variants(9))))),
|
|
||||||
StoreRefusal::EntityBounds {
|
|
||||||
id: eid("kay"),
|
|
||||||
bound: EntityBound::Forms
|
|
||||||
}
|
|
||||||
);
|
|
||||||
store
|
|
||||||
.put(kay_saying(ruling("ˈkeɪ", variants(8))))
|
|
||||||
.expect("eight rejected variants are the bound, not beyond it");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_ontology_entry_read_at_an_unknown_revision_is_refused_with_one_refusal() {
|
|
||||||
let w = world();
|
|
||||||
let mut onto = OntologyStore::open(&w.dir.path().join("o2.cc")).unwrap();
|
|
||||||
let entry = OntologyEntry {
|
|
||||||
language: "en-US".into(),
|
|
||||||
n: 1,
|
|
||||||
inventory_rev: 99,
|
|
||||||
layer: Layer::Discourse,
|
|
||||||
when: vec![Condition {
|
|
||||||
slot: Slot::Stance,
|
|
||||||
feature: iv(ANGER),
|
|
||||||
test: Test::AtLeast(Grade::new(200).unwrap()),
|
|
||||||
}],
|
|
||||||
choice: "WARM".into(),
|
|
||||||
examples: vec![],
|
|
||||||
annotator: Annotator::Operator,
|
|
||||||
};
|
|
||||||
match onto.admit(vec![entry], &w.inventory) {
|
|
||||||
Err(StoreError::Invalid(r)) => assert_eq!(r, vec![Refusal::V10UnknownRevision { rev: 99 }]),
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn weksa(dir: &std::path::Path, args: &[&str]) -> Output {
|
|
||||||
Command::new(env!("CARGO_BIN_EXE_weksa"))
|
|
||||||
.current_dir(dir)
|
|
||||||
.args([
|
|
||||||
"--corpus",
|
|
||||||
"./c.cc",
|
|
||||||
"--inventory",
|
|
||||||
"./i.cc",
|
|
||||||
"--entities",
|
|
||||||
"./e.cc",
|
|
||||||
"--ontology",
|
|
||||||
"./o.cc",
|
|
||||||
"--speaker-state",
|
|
||||||
"./s.cc",
|
|
||||||
])
|
|
||||||
.args(args)
|
|
||||||
.output()
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn out(o: &Output) -> String {
|
|
||||||
String::from_utf8_lossy(&o.stdout).into_owned() + &String::from_utf8_lossy(&o.stderr)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ok(o: Output) -> String {
|
|
||||||
assert!(o.status.success(), "{}", out(&o));
|
|
||||||
out(&o)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A scene bed: entities nibu and brokkr, the inventory through the
|
|
||||||
/// speaker-scene revision (rev 3).
|
|
||||||
fn scene_bed() -> tempfile::TempDir {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
for slug in ["nibu", "brokkr"] {
|
|
||||||
let id = format!("entity:{slug}");
|
|
||||||
let form = format!("en-US={}", slug.to_uppercase());
|
|
||||||
ok(weksa(
|
|
||||||
d.path(),
|
|
||||||
&[
|
|
||||||
"entity",
|
|
||||||
"put",
|
|
||||||
&id,
|
|
||||||
"--form",
|
|
||||||
&form,
|
|
||||||
"--origin",
|
|
||||||
"cast",
|
|
||||||
"--persona",
|
|
||||||
slug,
|
|
||||||
"--fixture",
|
|
||||||
"f.yaml",
|
|
||||||
],
|
|
||||||
));
|
|
||||||
}
|
|
||||||
for step in ["seed", "proof", "speaker-scene"] {
|
|
||||||
ok(weksa(d.path(), &["inventory", step]));
|
|
||||||
}
|
|
||||||
d
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a cast-authored line; returns the key it printed ("Added <key>").
|
|
||||||
fn add_line(d: &std::path::Path, slug: &str, speaker: &str, group: &str, text: &str) -> String {
|
|
||||||
let speaker = format!("entity:{speaker}");
|
|
||||||
let printed = ok(weksa(
|
|
||||||
d,
|
|
||||||
&[
|
|
||||||
"corpus",
|
|
||||||
"add",
|
|
||||||
"--slug",
|
|
||||||
slug,
|
|
||||||
"--text",
|
|
||||||
text,
|
|
||||||
"--speaker",
|
|
||||||
&speaker,
|
|
||||||
"--group",
|
|
||||||
group,
|
|
||||||
"--admitted-on",
|
|
||||||
"2026-10-29",
|
|
||||||
"--source",
|
|
||||||
"cast-authored",
|
|
||||||
"--language",
|
|
||||||
"en-US",
|
|
||||||
"--persona",
|
|
||||||
"nibu",
|
|
||||||
"--fixture",
|
|
||||||
"f.yaml",
|
|
||||||
"--author",
|
|
||||||
"Ada Writer",
|
|
||||||
],
|
|
||||||
));
|
|
||||||
printed.split_whitespace().nth(1).unwrap().to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene_put(d: &std::path::Path, group: &str, to: &str) -> Output {
|
|
||||||
weksa(
|
|
||||||
d,
|
|
||||||
&[
|
|
||||||
"scene",
|
|
||||||
"put",
|
|
||||||
"--group",
|
|
||||||
group,
|
|
||||||
"--to",
|
|
||||||
to,
|
|
||||||
"--inventory-rev",
|
|
||||||
"3",
|
|
||||||
"--model-family",
|
|
||||||
"anthropic",
|
|
||||||
"--generator",
|
|
||||||
"a scene annotator",
|
|
||||||
"--set",
|
|
||||||
"intimacy=200",
|
|
||||||
],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_scene_group_holds_one_live_speaker_among_its_own_live_items() {
|
|
||||||
let d = scene_bed();
|
|
||||||
add_line(d.path(), "nibu", "nibu", "scene-1", "Mind the hatch.");
|
|
||||||
// Another group's speaker and a withdrawn line of this group are not the
|
|
||||||
// scene's speakers.
|
|
||||||
add_line(d.path(), "brokkr", "brokkr", "scene-2", "Brokkr hums.");
|
|
||||||
let gone = add_line(
|
|
||||||
d.path(),
|
|
||||||
"brokkr",
|
|
||||||
"brokkr",
|
|
||||||
"scene-1",
|
|
||||||
"Brokkr leaves early.",
|
|
||||||
);
|
|
||||||
ok(weksa(d.path(), &["corpus", "withdraw", &gone]));
|
|
||||||
let put = ok(scene_put(d.path(), "scene-1", "unnamed"));
|
|
||||||
assert!(put.contains("scene:scene-1@1"), "{put}");
|
|
||||||
assert!(ok(weksa(d.path(), &["scene", "dump"])).contains("entity:nibu->unnamed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_scene_names_its_addressee_as_a_participant_unless_it_is_the_speaker() {
|
|
||||||
let d = scene_bed();
|
|
||||||
add_line(d.path(), "nibu", "nibu", "scene-1", "Mind the hatch.");
|
|
||||||
add_line(d.path(), "nibu", "nibu", "scene-2", "Mind the ladder.");
|
|
||||||
ok(scene_put(d.path(), "scene-1", "entity:brokkr"));
|
|
||||||
let dump = ok(weksa(d.path(), &["scene", "dump"]));
|
|
||||||
assert!(dump.contains("scene:scene-1@1 rev:3"), "{dump}");
|
|
||||||
assert!(dump.contains("[entity:nibu,entity:brokkr]"), "{dump}");
|
|
||||||
// A speaker addressing themself is a one-participant scene, whose
|
|
||||||
// relation to a named party is refused as the store reads it.
|
|
||||||
let own = scene_put(d.path(), "scene-2", "entity:nibu");
|
|
||||||
assert!(!own.status.success());
|
|
||||||
assert!(
|
|
||||||
out(&own).contains("a relation's named to is another participant"),
|
|
||||||
"{}",
|
|
||||||
out(&own)
|
|
||||||
);
|
|
||||||
assert_eq!(ok(weksa(d.path(), &["scene", "dump"])), dump);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn relower_refuses_malformed_arm_and_floor_labels_before_reading_the_run() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let relower = |arm: &str, floor: &[&str]| {
|
|
||||||
let mut args = vec![
|
|
||||||
"loop",
|
|
||||||
"relower",
|
|
||||||
"no-such-run",
|
|
||||||
"--round",
|
|
||||||
"1",
|
|
||||||
"--arm",
|
|
||||||
arm,
|
|
||||||
"--lowerer",
|
|
||||||
"m",
|
|
||||||
];
|
|
||||||
for f in floor {
|
|
||||||
args.extend(["--floor", f]);
|
|
||||||
}
|
|
||||||
weksa(d.path(), &args)
|
|
||||||
};
|
|
||||||
for (arm, floor) in [
|
|
||||||
("BAD", vec!["b"]),
|
|
||||||
("a", vec!["Bad"]),
|
|
||||||
("a", vec!["a", "b"]),
|
|
||||||
("a", vec!["b", "b"]),
|
|
||||||
] {
|
|
||||||
let o = relower(arm, &floor);
|
|
||||||
assert!(!o.status.success());
|
|
||||||
assert!(
|
|
||||||
out(&o).contains("arm and floor labels must match"),
|
|
||||||
"{arm} {floor:?}: {}",
|
|
||||||
out(&o)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Well-formed, distinct labels get past the label check (to the missing run).
|
|
||||||
let o = relower("a", &["b", "c"]);
|
|
||||||
assert!(!o.status.success());
|
|
||||||
assert!(out(&o).contains("the root holds no run"), "{}", out(&o));
|
|
||||||
}
|
|
||||||
|
|
@ -1,136 +0,0 @@
|
||||||
//! Pins for behaviour of `context.rs`, `encode.rs` and `run.rs` found unpinned
|
|
||||||
//! by mutation testing. Each test states what the code does in domain terms.
|
|
||||||
|
|
||||||
mod common;
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use weksa::context::Prompt;
|
|
||||||
use weksa::entity::{Entity, EntityOrigin, LanguageForms};
|
|
||||||
use weksa::packet::{EntityId, proof_packet};
|
|
||||||
use weksa::{CorpusItemId, CorpusStore, EntityForms, EntityStore, InventoryStore, PacketStore};
|
|
||||||
|
|
||||||
fn data(sub: &str) -> PathBuf {
|
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
||||||
.join("../../data")
|
|
||||||
.join(sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Held(Vec<Entity>);
|
|
||||||
|
|
||||||
impl EntityForms for Held {
|
|
||||||
fn entity(&self, id: &EntityId) -> anyhow::Result<Option<Entity>> {
|
|
||||||
Ok(self.0.iter().find(|e| &e.id == id).cloned())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spoken(slug: &str, form: &str) -> Entity {
|
|
||||||
Entity {
|
|
||||||
id: EntityId::parse(&format!("entity:{slug}")).unwrap(),
|
|
||||||
forms: vec![LanguageForms {
|
|
||||||
language: "en-US".into(),
|
|
||||||
forms: vec![form.into()],
|
|
||||||
pronunciation: None,
|
|
||||||
}],
|
|
||||||
origin: EntityOrigin::Cast {
|
|
||||||
persona: slug.into(),
|
|
||||||
fixture: "f.yaml".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A speaker whom no referent cites contributes no entry to the lowering
|
|
||||||
/// prompt, even when another entity is cited: only the cited entity is listed.
|
|
||||||
#[test]
|
|
||||||
fn an_uncited_speaker_is_absent_from_the_lowering_prompt() {
|
|
||||||
let cast_inv = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
|
||||||
let entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
|
||||||
let corpus = CorpusStore::open(&data("corpus/corpus.cc")).unwrap();
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let view = PacketStore::open(&dir.path().join("p.cc"))
|
|
||||||
.unwrap()
|
|
||||||
.admit(proof_packet(), &cast_inv, &corpus, &entities)
|
|
||||||
.unwrap();
|
|
||||||
let state = weksa::SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
|
|
||||||
let view = view
|
|
||||||
.with_scene(&cast_inv.inventory().unwrap(), &state, &corpus)
|
|
||||||
.unwrap();
|
|
||||||
let held = Held(vec![
|
|
||||||
spoken("nibu", "Nibu"),
|
|
||||||
spoken("other", "SPEAKERCANARY"),
|
|
||||||
]);
|
|
||||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
|
||||||
let speaker = EntityId::parse("entity:other").unwrap();
|
|
||||||
let prompt = Prompt::lower(
|
|
||||||
&view,
|
|
||||||
&item,
|
|
||||||
&speaker,
|
|
||||||
"en-US",
|
|
||||||
&cast_inv.inventory().unwrap(),
|
|
||||||
&held,
|
|
||||||
&weksa::Ontology::empty(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let text = prompt.text();
|
|
||||||
assert!(
|
|
||||||
text.contains("\n\nentities: {\"entity:nibu\":[\"Nibu\"]}\n\n"),
|
|
||||||
"{text}"
|
|
||||||
);
|
|
||||||
assert!(!text.contains("SPEAKERCANARY"), "{text}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A run refuses a panel language that lacks a live Train or a live Validation
|
|
||||||
/// item: one no item carries, one with only a Test item, one with only Train.
|
|
||||||
#[test]
|
|
||||||
fn a_panel_language_no_item_carries_is_refused_at_open() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let d = dir.path();
|
|
||||||
// Builds the corpus, entity and ontology stores the run reads.
|
|
||||||
drop(common::run_over(d));
|
|
||||||
let entities = common::entities_in(d);
|
|
||||||
let mut corpus = CorpusStore::open(&d.join("c.cc")).unwrap();
|
|
||||||
for (key, language, bucket) in [("item:jp:1", "ja-JP", 90), ("item:pt:1", "pt-BR", 10)] {
|
|
||||||
let mut item = common::item_in(
|
|
||||||
key,
|
|
||||||
&format!("line of {key}"),
|
|
||||||
&common::group_in_bucket(bucket),
|
|
||||||
common::cast(),
|
|
||||||
);
|
|
||||||
item.language = language.into();
|
|
||||||
corpus.add(item, &entities).unwrap();
|
|
||||||
}
|
|
||||||
drop(corpus);
|
|
||||||
let create = |panel: &[&str]| {
|
|
||||||
weksa::run::RunStores::create(
|
|
||||||
&d.join(format!("run-{}", panel.join("-"))),
|
|
||||||
"t",
|
|
||||||
weksa::run::RunPaths {
|
|
||||||
corpus: &d.join("c.cc"),
|
|
||||||
inventory: &d.join("i.cc"),
|
|
||||||
entities: &d.join("entities.cc"),
|
|
||||||
ontology: &d.join("ontology.cc"),
|
|
||||||
speaker_state: &common::speaker_state_beside(&d.join("ontology.cc")),
|
|
||||||
},
|
|
||||||
"fake-model",
|
|
||||||
"bag",
|
|
||||||
weksa::run::LowererReach::ToolLessRelay,
|
|
||||||
weksa::corpus::ModelFamily::Unrecorded,
|
|
||||||
&panel.iter().map(|t| (*t).to_string()).collect::<Vec<_>>(),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
assert!(create(&["en-US"]).is_ok());
|
|
||||||
for panel in [&["ja-JP"][..], &["pt-BR"], &["xx-XX"], &["en-US", "ja-JP"]] {
|
|
||||||
assert!(
|
|
||||||
matches!(create(panel), Err(weksa::run::RunError::Panel)),
|
|
||||||
"{panel:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A run keeps its recall probes in `recall` under its own root.
|
|
||||||
#[test]
|
|
||||||
fn a_run_keeps_its_recall_under_its_root() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = common::run_over(dir.path());
|
|
||||||
assert_eq!(run.recall_dir(), dir.path().join("run").join("recall"));
|
|
||||||
}
|
|
||||||
|
|
@ -1,402 +0,0 @@
|
||||||
//! The ontology mint (`weksa loop mint-ontology`): a Train-only call that drafts
|
|
||||||
//! entries for `weksa ontology admit`. It shows a model the Train lines of one
|
|
||||||
//! panel language, the features a condition can read and that language's entry
|
|
||||||
//! lines; it admits nothing and writes nothing of the run.
|
|
||||||
|
|
||||||
mod common;
|
|
||||||
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use common::{cast, entities_in, group_in_bucket, item_in};
|
|
||||||
use weksa::context::Prompt;
|
|
||||||
use weksa::corpus::{ModelFamily, Source};
|
|
||||||
use weksa::inventory::{Change, seed};
|
|
||||||
use weksa::model::{AnswerFiles, ModelPort, PortError};
|
|
||||||
use weksa::run::{LowererReach, OntologyMintOutcome, RunPaths, RunStores};
|
|
||||||
use weksa::speaker::Annotator;
|
|
||||||
use weksa::{CorpusStore, InventoryStore, OntologyStore, Slot, ValueKind};
|
|
||||||
|
|
||||||
/// Records every prompt shown; answers with `reply`.
|
|
||||||
struct Record {
|
|
||||||
prompts: Vec<(String, Vec<String>)>,
|
|
||||||
reply: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Record {
|
|
||||||
fn new(reply: &str) -> Self {
|
|
||||||
Self { prompts: vec![], reply: reply.to_string() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ModelPort for Record {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
"record"
|
|
||||||
}
|
|
||||||
fn answer(&mut self, p: &Prompt) -> Result<String, PortError> {
|
|
||||||
self.prompts.push((p.text().to_string(), p.item_keys().to_vec()));
|
|
||||||
Ok(self.reply.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn public() -> Source {
|
|
||||||
Source::PublicDomain {
|
|
||||||
work: "A Work".into(),
|
|
||||||
author: "An Author".into(),
|
|
||||||
edition_url: "https://example.org/e".into(),
|
|
||||||
licence: "CC0".into(),
|
|
||||||
jurisdiction: "US".into(),
|
|
||||||
translator: "A Translator".into(),
|
|
||||||
edition_year: 1900,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const STANCE_G: &str = "feature:60";
|
|
||||||
const DISC_FLAG: &str = "feature:61";
|
|
||||||
const REF_ONLY: &str = "feature:62";
|
|
||||||
const PRED_ONLY: &str = "feature:63";
|
|
||||||
const STANCE_RETIRED: &str = "feature:64";
|
|
||||||
const SCENE_G: &str = "feature:65";
|
|
||||||
const SCENE_OPT: &str = "feature:66";
|
|
||||||
|
|
||||||
/// A fixture: items in en-US and ja-JP across every split and a withdrawal, an
|
|
||||||
/// inventory with condition-readable and unreadable features, an ontology with
|
|
||||||
/// en-US and ja-JP entries, and a run over them with `panel`.
|
|
||||||
fn fixture(dir: &Path, panel: &[&str]) -> RunStores {
|
|
||||||
let entities = entities_in(dir);
|
|
||||||
let mut corpus = CorpusStore::open(&dir.join("c.cc")).unwrap();
|
|
||||||
let rows = [
|
|
||||||
("item:en:1", "en-US", "entrain mark one", 10, cast(), false),
|
|
||||||
("item:en:2", "en-US", "entrain mark two", 11, cast(), false),
|
|
||||||
("item:en:3", "en-US", "envalid mark three", 50, cast(), false),
|
|
||||||
("item:en:4", "en-US", "engone mark four", 12, cast(), true),
|
|
||||||
("item:en:5", "en-US", "entest mark five", 90, public(), false),
|
|
||||||
("item:ja:1", "ja-JP", "jatrain mark one", 13, cast(), false),
|
|
||||||
("item:ja:2", "ja-JP", "javalid mark two", 51, cast(), false),
|
|
||||||
("item:ja:3", "ja-JP", "jatest mark three", 91, public(), false),
|
|
||||||
];
|
|
||||||
for (id, language, text, bucket, source, withdrawn) in rows {
|
|
||||||
let mut item = item_in(id, text, &group_in_bucket(bucket), source);
|
|
||||||
item.language = language.into();
|
|
||||||
corpus.add(item, &entities).unwrap();
|
|
||||||
if withdrawn {
|
|
||||||
corpus.withdraw(id).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
drop(corpus);
|
|
||||||
|
|
||||||
let mut inv = InventoryStore::open(&dir.join("i.cc")).unwrap();
|
|
||||||
let (rev1, entries) = seed();
|
|
||||||
inv.admit_revision(rev1, entries).unwrap();
|
|
||||||
let f = |id, kind, slots: &[Slot]| common::feature(id, kind, slots);
|
|
||||||
let features = vec![
|
|
||||||
f(STANCE_G, ValueKind::Grade, &[Slot::Stance]),
|
|
||||||
f(DISC_FLAG, ValueKind::Flag, &[Slot::Discourse]),
|
|
||||||
f(REF_ONLY, ValueKind::Grade, &[Slot::Referent]),
|
|
||||||
f(PRED_ONLY, ValueKind::Grade, &[Slot::Predication]),
|
|
||||||
f(STANCE_RETIRED, ValueKind::Grade, &[Slot::Stance]),
|
|
||||||
f(SCENE_G, ValueKind::Grade, &[Slot::Scene]),
|
|
||||||
f(SCENE_OPT, ValueKind::Options(weksa::OptionSet::new(vec![weksa::OptionLabel::parse("below").unwrap(), weksa::OptionLabel::parse("above").unwrap()]).unwrap()), &[Slot::Scene]),
|
|
||||||
];
|
|
||||||
let changes = features.iter().map(|e| Change::Add(e.id)).collect();
|
|
||||||
let mut features = features;
|
|
||||||
for e in &mut features {
|
|
||||||
e.introduced_rev = 2;
|
|
||||||
}
|
|
||||||
inv.admit_revision(common::rev_with(changes, 2, Some(1)), features).unwrap();
|
|
||||||
inv.admit_revision(
|
|
||||||
common::rev_with(vec![Change::Retire(common::iv(STANCE_RETIRED))], 3, Some(2)),
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut onto = OntologyStore::open(&dir.join("ontology.cc")).unwrap();
|
|
||||||
let annotator = Annotator::Model { family: ModelFamily::Anthropic, generator: "seed".into() };
|
|
||||||
let entry = |language: &str, choice: &str, examples: &[&str]| {
|
|
||||||
weksa::encode::OntologyDraft::parse(&format!(
|
|
||||||
r#"{{"entries":[{{"layer":"Grammar","choice":"{choice}","examples":[{}]}}]}}"#,
|
|
||||||
examples.iter().map(|x| format!("\"{x}\"")).collect::<Vec<_>>().join(",")
|
|
||||||
))
|
|
||||||
.unwrap()
|
|
||||||
.into_entries(language, 3, 1, &annotator)
|
|
||||||
};
|
|
||||||
onto.admit(entry("en-US", "enchoice marker", &["enexample marker"]), &inv).unwrap();
|
|
||||||
onto.admit(entry("ja-JP", "jachoice marker", &["jaexample marker"]), &inv).unwrap();
|
|
||||||
drop(onto);
|
|
||||||
drop(inv);
|
|
||||||
|
|
||||||
std::fs::write(dir.join("speaker-state.cc"), [0x90]).unwrap();
|
|
||||||
let panel: Vec<String> = panel.iter().map(|s| s.to_string()).collect();
|
|
||||||
RunStores::create(
|
|
||||||
&dir.join("run"),
|
|
||||||
"t",
|
|
||||||
RunPaths {
|
|
||||||
corpus: &dir.join("c.cc"),
|
|
||||||
inventory: &dir.join("i.cc"),
|
|
||||||
entities: &dir.join("entities.cc"),
|
|
||||||
ontology: &dir.join("ontology.cc"),
|
|
||||||
speaker_state: &dir.join("speaker-state.cc"),
|
|
||||||
},
|
|
||||||
"fake-model",
|
|
||||||
"bag",
|
|
||||||
LowererReach::ToolLessRelay,
|
|
||||||
ModelFamily::Unrecorded,
|
|
||||||
&panel,
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
const DRAFT: &str =
|
|
||||||
r#"{"entries":[{"layer":"Discourse","when":[],"choice":"a pattern","examples":[]}]}"#;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_prompt_shows_only_train_items_of_the_language() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US", "ja-JP"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "en-US").unwrap();
|
|
||||||
let (text, keys) = &m.prompts[0];
|
|
||||||
assert!(text.contains("language: en-US"));
|
|
||||||
assert_eq!(keys, &["item:en:1", "item:en:2"]);
|
|
||||||
for shown in ["entrain mark one", "entrain mark two"] {
|
|
||||||
assert!(text.contains(shown), "{shown}");
|
|
||||||
}
|
|
||||||
for hidden in [
|
|
||||||
"envalid", "engone", "entest", "jatrain", "javalid", "jatest", "item:en:3", "item:en:5",
|
|
||||||
"item:ja",
|
|
||||||
] {
|
|
||||||
assert!(!text.contains(hidden), "the en-US mint showed {hidden}");
|
|
||||||
}
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "ja-JP").unwrap();
|
|
||||||
let (text, keys) = &m.prompts[0];
|
|
||||||
assert_eq!(keys, &["item:ja:1"]);
|
|
||||||
assert!(text.contains("jatrain mark one") && !text.contains("entrain"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_refuses_a_language_outside_the_panel() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
// ja-JP has Train items in the corpus but is not in the panel.
|
|
||||||
for (language, code) in [("ja-JP", "language-not-in-panel"), ("fr-FR", "language-not-in-panel")] {
|
|
||||||
assert_eq!(
|
|
||||||
run.mint_ontology(&mut m, language).unwrap(),
|
|
||||||
OntologyMintOutcome::Refused { code }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(m.prompts.is_empty(), "a refused mint asked the model");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_prompt_lists_only_condition_readable_features() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "en-US").unwrap();
|
|
||||||
let text = &m.prompts[0].0;
|
|
||||||
let listed = |id: &str| text.contains(&format!("\n{id}: "));
|
|
||||||
for id in [STANCE_G, DISC_FLAG, SCENE_G] {
|
|
||||||
assert!(listed(id), "{id} is readable by a condition");
|
|
||||||
}
|
|
||||||
for id in [REF_ONLY, PRED_ONLY, STANCE_RETIRED] {
|
|
||||||
assert!(!listed(id), "{id} is not");
|
|
||||||
}
|
|
||||||
// Nothing that is not a feature: no concept or role line.
|
|
||||||
assert!(!text.contains("\nconcept:") && !text.contains("\nrole:"));
|
|
||||||
assert!(text.contains("features rev:3"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_prompt_lists_only_the_languages_existing_entries() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US", "ja-JP"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "en-US").unwrap();
|
|
||||||
let text = &m.prompts[0].0;
|
|
||||||
assert!(text.contains("onto:en-US:1 enchoice marker"));
|
|
||||||
for hidden in ["jachoice", "onto:ja-JP", "enexample", "jaexample"] {
|
|
||||||
assert!(!text.contains(hidden), "{hidden}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn digests(dir: &Path) -> Vec<(String, Vec<u8>)> {
|
|
||||||
let mut out = vec![];
|
|
||||||
let mut stack = vec![dir.to_path_buf()];
|
|
||||||
while let Some(d) = stack.pop() {
|
|
||||||
for e in std::fs::read_dir(&d).unwrap() {
|
|
||||||
let p = e.unwrap().path();
|
|
||||||
if p.is_dir() {
|
|
||||||
stack.push(p);
|
|
||||||
} else if !p.starts_with(dir.join("run").join("ontology-mint")) {
|
|
||||||
out.push((p.display().to_string(), std::fs::read(&p).unwrap()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.sort();
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_writes_nothing_but_its_prompt_and_answer_files() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US", "ja-JP"]);
|
|
||||||
let before = digests(dir.path());
|
|
||||||
let mut files = AnswerFiles::new(run.ontology_mint_dir(), "m".into(), vec![]);
|
|
||||||
let OntologyMintOutcome::Unanswered { prompt } =
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap()
|
|
||||||
else {
|
|
||||||
panic!("unanswered");
|
|
||||||
};
|
|
||||||
std::fs::write(run.ontology_mint_dir().join(format!("{prompt}.answer")), DRAFT).unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap(),
|
|
||||||
OntologyMintOutcome::Drafted { entries: 1, .. }
|
|
||||||
));
|
|
||||||
assert_eq!(digests(dir.path()), before, "the mint wrote outside ontology-mint");
|
|
||||||
let mut names: Vec<String> = std::fs::read_dir(run.ontology_mint_dir())
|
|
||||||
.unwrap()
|
|
||||||
.map(|e| e.unwrap().file_name().into_string().unwrap())
|
|
||||||
.collect();
|
|
||||||
names.sort();
|
|
||||||
assert_eq!(names, [format!("{prompt}.answer"), format!("{prompt}.prompt")]);
|
|
||||||
drop(run);
|
|
||||||
RunStores::open(&dir.path().join("run")).expect("no Drift after a mint");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn mint_ontology_unanswered_then_drafted_then_refused() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let mut files = AnswerFiles::new(run.ontology_mint_dir(), "m".into(), vec![]);
|
|
||||||
let OntologyMintOutcome::Unanswered { prompt } =
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap()
|
|
||||||
else {
|
|
||||||
panic!("unanswered");
|
|
||||||
};
|
|
||||||
let mint = run.ontology_mint_dir();
|
|
||||||
assert!(mint.join(format!("{prompt}.prompt")).exists());
|
|
||||||
let answer = mint.join(format!("{prompt}.answer"));
|
|
||||||
std::fs::write(&answer, DRAFT).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap(),
|
|
||||||
OntologyMintOutcome::Drafted { prompt: prompt.clone(), entries: 1 }
|
|
||||||
);
|
|
||||||
let two = r#"{"entries":[{"layer":"Grammar","choice":"a"},{"layer":"Lexicon","choice":"b"}]}"#;
|
|
||||||
std::fs::write(&answer, two).unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap(),
|
|
||||||
OntologyMintOutcome::Drafted { entries: 2, .. }
|
|
||||||
));
|
|
||||||
let unknown = r#"{"entries":[{"layer":"Grammar","choice":"a","key":"x"}]}"#;
|
|
||||||
std::fs::write(&answer, unknown).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap(),
|
|
||||||
OntologyMintOutcome::Refused { code: "unknown-field" }
|
|
||||||
);
|
|
||||||
std::fs::write(&answer, "not json").unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap(),
|
|
||||||
OntologyMintOutcome::Refused { code: "syntax" }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_mint_answer_admits_into_a_copy_and_a_new_run_pins_the_copy() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let pinned = std::fs::read(dir.path().join("ontology.cc")).unwrap();
|
|
||||||
let pin = run.record().ontology_digest.clone();
|
|
||||||
let draft = format!(
|
|
||||||
r#"{{"entries":[{{"layer":"Discourse","when":[{{"slot":"Stance","feature":"{STANCE_G}","test":{{"AtLeast":500}}}}],"choice":"a grown choice","examples":[]}}]}}"#
|
|
||||||
);
|
|
||||||
let mut files = AnswerFiles::new(run.ontology_mint_dir(), "m".into(), vec![]);
|
|
||||||
let OntologyMintOutcome::Unanswered { prompt } =
|
|
||||||
run.mint_ontology(&mut files, "en-US").unwrap()
|
|
||||||
else {
|
|
||||||
panic!("unanswered");
|
|
||||||
};
|
|
||||||
let answer = run.ontology_mint_dir().join(format!("{prompt}.answer"));
|
|
||||||
std::fs::write(&answer, &draft).unwrap();
|
|
||||||
|
|
||||||
let copy = dir.path().join("grown.cc");
|
|
||||||
std::fs::copy(dir.path().join("ontology.cc"), ©).unwrap();
|
|
||||||
let inv = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
|
|
||||||
let mut grown = OntologyStore::open(©).unwrap();
|
|
||||||
let annotator = Annotator::Model { family: ModelFamily::Anthropic, generator: "minter".into() };
|
|
||||||
let first_n = grown.ontology().unwrap().entries().iter().filter(|e| e.language == "en-US").count() as u32 + 1;
|
|
||||||
let entries = weksa::encode::OntologyDraft::parse(&std::fs::read_to_string(&answer).unwrap())
|
|
||||||
.unwrap()
|
|
||||||
.into_entries("en-US", 3, first_n, &annotator);
|
|
||||||
grown.admit(entries, &inv).unwrap();
|
|
||||||
drop(grown);
|
|
||||||
|
|
||||||
assert_eq!(std::fs::read(dir.path().join("ontology.cc")).unwrap(), pinned);
|
|
||||||
let again = RunStores::open(&dir.path().join("run")).unwrap();
|
|
||||||
assert_eq!(again.record().ontology_digest, pin);
|
|
||||||
|
|
||||||
let second = RunStores::create(
|
|
||||||
&dir.path().join("run-grown"),
|
|
||||||
"t",
|
|
||||||
RunPaths {
|
|
||||||
corpus: &dir.path().join("c.cc"),
|
|
||||||
inventory: &dir.path().join("i.cc"),
|
|
||||||
entities: &dir.path().join("entities.cc"),
|
|
||||||
ontology: ©,
|
|
||||||
speaker_state: &dir.path().join("speaker-state.cc"),
|
|
||||||
},
|
|
||||||
"fake-model",
|
|
||||||
"bag",
|
|
||||||
LowererReach::ToolLessRelay,
|
|
||||||
ModelFamily::Unrecorded,
|
|
||||||
&["en-US".to_string()],
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_ne!(second.record().ontology_digest, pin);
|
|
||||||
|
|
||||||
// A condition on a feature outside the inventory is the store's to refuse.
|
|
||||||
let outside = draft.replace(STANCE_G, "feature:99");
|
|
||||||
let entries = weksa::encode::OntologyDraft::parse(&outside)
|
|
||||||
.unwrap()
|
|
||||||
.into_entries("en-US", 3, 9, &annotator);
|
|
||||||
let mut grown = OntologyStore::open(©).unwrap();
|
|
||||||
assert!(grown.admit(entries, &inv).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The line after `example ` in a mint prompt.
|
|
||||||
fn example_of(text: &str) -> &str {
|
|
||||||
text.lines().find_map(|l| l.strip_prefix("example ")).expect("the prompt carries an example")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_mint_prompts_own_example_parses_and_admits_through_the_door() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "en-US").unwrap();
|
|
||||||
let example = example_of(&m.prompts[0].0);
|
|
||||||
// It teaches the door's spelling: a capitalized layer, feature ids, each test form.
|
|
||||||
assert!(example.contains(r#""layer":"Grammar""#), "{example}");
|
|
||||||
for form in [r#"{"AtLeast":500}"#, r#"{"Is":{"Option":"#, r#"{"Is":{"Flag":true}}"#] {
|
|
||||||
assert!(example.contains(form), "{form} in {example}");
|
|
||||||
}
|
|
||||||
let draft = weksa::encode::OntologyDraft::parse(example).unwrap();
|
|
||||||
let inv = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
|
|
||||||
let copy = dir.path().join("grown.cc");
|
|
||||||
std::fs::copy(dir.path().join("ontology.cc"), ©).unwrap();
|
|
||||||
let mut grown = OntologyStore::open(©).unwrap();
|
|
||||||
let annotator = Annotator::Model { family: ModelFamily::Anthropic, generator: "minter".into() };
|
|
||||||
grown.admit(draft.into_entries("en-US", 3, 2, &annotator), &inv).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_mint_example_names_only_features_the_prompt_lists() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let run = fixture(dir.path(), &["en-US"]);
|
|
||||||
let mut m = Record::new(DRAFT);
|
|
||||||
run.mint_ontology(&mut m, "en-US").unwrap();
|
|
||||||
let example = example_of(&m.prompts[0].0);
|
|
||||||
for unreadable in [REF_ONLY, PRED_ONLY, STANCE_RETIRED] {
|
|
||||||
assert!(!example.contains(unreadable), "{unreadable}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,463 +0,0 @@
|
||||||
//! 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 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, EntityStore, Inventory, InventoryStore, LoweringInput, NameSpan, PacketStore,
|
|
||||||
Refusal, SceneRead, SpeakerStateStore, StoreError,
|
|
||||||
};
|
|
||||||
|
|
||||||
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 inventory = InventoryStore::open(&dir.path().join("i.cc")).unwrap();
|
|
||||||
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision(3)] {
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn inv(w: &W) -> Inventory {
|
|
||||||
w.inventory.inventory().unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn feat(gloss: &str, value: FeatValue) -> FeatureValue {
|
|
||||||
let feature = seed()
|
|
||||||
.1
|
|
||||||
.into_iter()
|
|
||||||
.chain(speaker_scene_revision(3).1)
|
|
||||||
.find(|e| e.gloss == gloss)
|
|
||||||
.unwrap_or_else(|| panic!("no feature {gloss}"))
|
|
||||||
.id;
|
|
||||||
FeatureValue { feature, value }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn intimacy(v: u16) -> Vec<FeatureValue> {
|
|
||||||
vec![feat("intimacy", FeatValue::Grade(grade(v)))]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status() -> Vec<FeatureValue> {
|
|
||||||
vec![
|
|
||||||
feat("relative_status", FeatValue::Option(lab("above"))),
|
|
||||||
feat("intimacy", FeatValue::Grade(grade(200))),
|
|
||||||
feat("in_group", FeatValue::Flag(false)),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn relation(from: &str, to: Party, features: Vec<FeatureValue>) -> PairRelation {
|
|
||||||
PairRelation {
|
|
||||||
from: eid(from),
|
|
||||||
to,
|
|
||||||
features,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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: group.into(),
|
|
||||||
n,
|
|
||||||
inventory_rev: 3,
|
|
||||||
participants: participants.iter().map(|p| eid(p)).collect(),
|
|
||||||
relations,
|
|
||||||
annotator: Annotator::Operator,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
view_to(w, rev, addressee, "brokkr")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// As `view_of`, with referent `n3` naming `entity` (Nibu is the item's
|
|
||||||
/// speaker, so he may be named on the line; Brokkr is named by its text).
|
|
||||||
fn view_to(w: &W, rev: u32, addressee: Option<&str>, entity: &str) -> LoweringInput {
|
|
||||||
let mut p: Packet = proof_packet();
|
|
||||||
p.inventory_rev = rev;
|
|
||||||
p.referents[2].entity = Some(eid(entity));
|
|
||||||
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()
|
|
||||||
.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}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read(w: &W, view: LoweringInput) -> SceneRead {
|
|
||||||
view.with_scene(&inv(w), &w.state, &w.corpus)
|
|
||||||
.unwrap()
|
|
||||||
.scene_read()
|
|
||||||
.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selected(rev: u32, features: Vec<FeatureValue>) -> SceneRead {
|
|
||||||
SceneRead::Selected { rev, features }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_scene_relation_reaches_the_lowering_view() {
|
|
||||||
let mut w = world();
|
|
||||||
put(&mut w, standard("g", 1));
|
|
||||||
let plain = view_of(&w, 3, Some("n3"));
|
|
||||||
assert_eq!(plain.scene_read(), &SceneRead::Unread);
|
|
||||||
assert!(plain.scene().is_empty());
|
|
||||||
let with = plain
|
|
||||||
.clone()
|
|
||||||
.with_scene(&inv(&w), &w.state, &w.corpus)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(with.scene(), status().as_slice());
|
|
||||||
assert_eq!(with.scene_read(), &selected(1, status()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn with_scene_says_which_of_five_things_it_found() {
|
|
||||||
let mut w = world();
|
|
||||||
// No scene for the group.
|
|
||||||
assert_eq!(read(&w, view_of(&w, 3, Some("n3"))), SceneRead::NoScene);
|
|
||||||
put(&mut w, standard("g", 1));
|
|
||||||
// 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!(read(&w, view_of(&w, 3, Some("n3"))), selected(1, status()));
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, Some("n1"))),
|
|
||||||
selected(1, intimacy(7))
|
|
||||||
);
|
|
||||||
// The scene was read and the packet names no addressee.
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, None)),
|
|
||||||
SceneRead::NoAddressee { rev: 1 }
|
|
||||||
);
|
|
||||||
// The addressee is the speaker.
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_to(&w, 3, Some("n3"), "nibu")),
|
|
||||||
SceneRead::SelfAddressed { rev: 1 }
|
|
||||||
);
|
|
||||||
// The scene holds no relation to this addressee.
|
|
||||||
put(
|
|
||||||
&mut w,
|
|
||||||
scene(
|
|
||||||
"g",
|
|
||||||
2,
|
|
||||||
&["nibu", "brokkr"],
|
|
||||||
vec![relation("nibu", Party::Unnamed, intimacy(7))],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, Some("n3"))),
|
|
||||||
SceneRead::NoRelation { rev: 2 }
|
|
||||||
);
|
|
||||||
// A relation with no features is found, not absent.
|
|
||||||
put(
|
|
||||||
&mut w,
|
|
||||||
scene(
|
|
||||||
"g",
|
|
||||||
3,
|
|
||||||
&["nibu", "brokkr"],
|
|
||||||
vec![relation("nibu", Party::Named(eid("brokkr")), vec![])],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert_eq!(read(&w, view_of(&w, 3, Some("n3"))), selected(3, vec![]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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))],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, Some("n3"))),
|
|
||||||
SceneRead::NoRelation { rev: 1 }
|
|
||||||
);
|
|
||||||
// A participant without a relation behaves the same.
|
|
||||||
put(
|
|
||||||
&mut w,
|
|
||||||
scene(
|
|
||||||
"g",
|
|
||||||
2,
|
|
||||||
&["nibu", "brokkr"],
|
|
||||||
vec![relation("nibu", Party::Unnamed, intimacy(7))],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, Some("n3"))),
|
|
||||||
SceneRead::NoRelation { rev: 2 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_speaker_is_the_items_not_the_first_participant() {
|
|
||||||
let mut w = world();
|
|
||||||
// Brokkr is listed first and has an unnamed relation of his own.
|
|
||||||
put(
|
|
||||||
&mut w,
|
|
||||||
scene(
|
|
||||||
"g",
|
|
||||||
1,
|
|
||||||
&["brokkr", "nibu"],
|
|
||||||
vec![
|
|
||||||
relation("brokkr", Party::Unnamed, intimacy(99)),
|
|
||||||
relation("nibu", Party::Unnamed, intimacy(7)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, Some("n1"))),
|
|
||||||
selected(1, intimacy(7))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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, whatever other groups hold.
|
|
||||||
assert_eq!(read(&w, view_of(&w, 3, Some("n3"))), SceneRead::NoScene);
|
|
||||||
// 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, &w.corpus)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(got.scene_read(), &selected(2, intimacy(5)));
|
|
||||||
assert_eq!(got.scene(), intimacy(5).as_slice());
|
|
||||||
// A read replaces the earlier one: a store without the scene says so.
|
|
||||||
let empty = SpeakerStateStore::open(&w.dir.path().join("empty.cc")).unwrap();
|
|
||||||
let cleared = got.with_scene(&inv(&w), &empty, &w.corpus).unwrap();
|
|
||||||
assert_eq!(cleared.scene_read(), &SceneRead::NoScene);
|
|
||||||
assert!(cleared.scene().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn with_scene_refusals() {
|
|
||||||
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!(
|
|
||||||
rules(view_of(&w, 2, Some("n3")).with_scene(&inv(&w), &w.state, &w.corpus)),
|
|
||||||
["V5", "V5", "V5"]
|
|
||||||
);
|
|
||||||
// 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();
|
|
||||||
for addressee in [Some("n3"), None] {
|
|
||||||
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"));
|
|
||||||
p.discourse.addressee = addressee.map(nd);
|
|
||||||
let scratch = tempfile::tempdir().unwrap();
|
|
||||||
let view = PacketStore::open(&scratch.path().join("p.cc"))
|
|
||||||
.unwrap()
|
|
||||||
.admit(p, &w.inventory, &w.corpus, &w.entities)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
rules(view.with_scene(&inv(&w), &w.state, &w.corpus)),
|
|
||||||
["V16"],
|
|
||||||
"{addressee:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn read_refuses_a_scene_that_stopped_covering_a_live_speaker_of_its_group() {
|
|
||||||
// Group g's scene covers Nibu alone, and Nibu's is the only item: admitted.
|
|
||||||
let mut w = world();
|
|
||||||
put(&mut w, scene("g", 1, &["nibu"], vec![]));
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, None)),
|
|
||||||
SceneRead::NoAddressee { rev: 1 }
|
|
||||||
);
|
|
||||||
// Brokkr then speaks in g. The corpus door lets him in; the view of Nibu's
|
|
||||||
// own line, whose speaker the scene still lists, reads the stale scene no more.
|
|
||||||
let mut item = item_in("item:brokkr:1", "Hello.", "g", cast());
|
|
||||||
item.speaker = eid("brokkr");
|
|
||||||
w.corpus.add(item, &w.entities).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
rules(view_of(&w, 3, None).with_scene(&inv(&w), &w.state, &w.corpus)),
|
|
||||||
["V16"]
|
|
||||||
);
|
|
||||||
// The put door applies the same rule, so the repair is a revision that
|
|
||||||
// covers him.
|
|
||||||
put(&mut w, scene("g", 2, &["nibu", "brokkr"], vec![]));
|
|
||||||
assert_eq!(
|
|
||||||
read(&w, view_of(&w, 3, None)),
|
|
||||||
SceneRead::NoAddressee { rev: 2 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_live_speakers_of_the_views_group_and_the_views_own_speaker_must_be_covered() {
|
|
||||||
let mut w = world();
|
|
||||||
put(&mut w, scene("g", 1, &["nibu"], vec![]));
|
|
||||||
let ok = SceneRead::NoAddressee { rev: 1 };
|
|
||||||
// A withdrawn speaker the scene lacks does not count.
|
|
||||||
let mut gone = item_in("item:brokkr:1", "Hello.", "g", cast());
|
|
||||||
gone.speaker = eid("brokkr");
|
|
||||||
w.corpus.add(gone, &w.entities).unwrap();
|
|
||||||
w.corpus.withdraw("item:brokkr:1").unwrap();
|
|
||||||
assert_eq!(read(&w, view_of(&w, 3, None)), ok);
|
|
||||||
// Nor does a live speaker the scene lacks in another group.
|
|
||||||
let mut other = item_in("item:brokkr:2", "Hello you.", "h", cast());
|
|
||||||
other.speaker = eid("brokkr");
|
|
||||||
w.corpus.add(other, &w.entities).unwrap();
|
|
||||||
assert_eq!(read(&w, view_of(&w, 3, None)), ok);
|
|
||||||
// The view's own speaker must be listed even when its item was withdrawn
|
|
||||||
// after the view was built: scene g@2 lists Brokkr alone.
|
|
||||||
let view = view_of(&w, 3, None);
|
|
||||||
w.corpus.withdraw("item:nibu:1").unwrap();
|
|
||||||
put(&mut w, scene("g", 2, &["brokkr"], vec![]));
|
|
||||||
assert_eq!(
|
|
||||||
rules(view.with_scene(&inv(&w), &w.state, &w.corpus)),
|
|
||||||
["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::<Vec<_>>()
|
|
||||||
};
|
|
||||||
// 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::<u32>::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::<u32>::new());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,876 +0,0 @@
|
||||||
mod common;
|
|
||||||
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::io::{BufRead, BufReader, Read, Write};
|
|
||||||
use std::net::TcpListener;
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use common::{Bag, cast, group_in_bucket, item_in, model};
|
|
||||||
use serde_json::Value;
|
|
||||||
use weksa::CorpusItem;
|
|
||||||
use weksa::score::{
|
|
||||||
Embedder, ItemScore, OllamaEmbedder, ScoreInput, Scorer, aggregate, chrf, cosine,
|
|
||||||
leak_diagnostic,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// (reference, hypothesis, sacrebleu 2.4.3 sentence_chrf), map 491536c.
|
|
||||||
const VECTORS: [(&str, &str, f64); 6] = [
|
|
||||||
(
|
|
||||||
"Take your hand off that control unless you want your nervous system to become my least useful circuit diagram.",
|
|
||||||
"Take your hand off that control, unless you'd like your nervous system to be my least useful wiring diagram.",
|
|
||||||
74.4498,
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"The command has no receipt. It is not truth.",
|
|
||||||
"The order carries no receipt, so it is not true.",
|
|
||||||
45.7164,
|
|
||||||
),
|
|
||||||
("I am not angry.", "I am not angry.", 100.0),
|
|
||||||
("Forgive me, sir.", "Get out.", 3.9683),
|
|
||||||
("その制御に触るな。", "その操作盤に触らないで。", 14.2931),
|
|
||||||
("Well, aren't you a sight for sore eyes, love.", "", 0.0),
|
|
||||||
];
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn chrf_matches_sacrebleu_vectors() {
|
|
||||||
for (reference, hypothesis, want) in VECTORS {
|
|
||||||
let got = chrf(hypothesis, reference);
|
|
||||||
assert!(
|
|
||||||
(got - want).abs() < 1e-4,
|
|
||||||
"{hypothesis:?} against {reference:?}: {got} != {want}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn chrf_argument_order() {
|
|
||||||
let short = "shut the gate";
|
|
||||||
let long = "shut the gate before the storm arrives tonight";
|
|
||||||
let (as_hypothesis, as_reference) = (chrf(short, long), chrf(long, short));
|
|
||||||
assert!(
|
|
||||||
as_hypothesis < as_reference - 1.0,
|
|
||||||
"recall is weighted: a short hypothesis of a long reference ({as_hypothesis}) must score below the reverse ({as_reference})"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Recorder {
|
|
||||||
seen: RefCell<Vec<String>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Embedder for Recorder {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
"fake"
|
|
||||||
}
|
|
||||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
|
|
||||||
self.seen
|
|
||||||
.borrow_mut()
|
|
||||||
.extend(texts.iter().map(|t| t.to_string()));
|
|
||||||
Ok(texts.iter().map(|t| vec![t.len() as f32, 1.0]).collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn score_one<E: Embedder>(scorer: &Scorer<E>, reference: &str, output: &str) -> ItemScore {
|
|
||||||
scorer
|
|
||||||
.score(&[ScoreInput { reference, output }])
|
|
||||||
.unwrap()
|
|
||||||
.remove(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close(got: f64, want: f64) {
|
|
||||||
assert!((got - want).abs() < 1e-4, "{got} != {want}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn chrf_whitespace_parity() {
|
|
||||||
// sacrebleu 2.4.3 strips str.split's whitespace; every vector scores 100
|
|
||||||
let vectors = [
|
|
||||||
("a\tb c", "ab c"),
|
|
||||||
("a\u{a0}b", "ab"),
|
|
||||||
("a\u{1c}b", "ab"),
|
|
||||||
("a\u{85}b", "ab"),
|
|
||||||
("a\u{2028}b c", "ab c"),
|
|
||||||
("line one\nline two", "line one line two"),
|
|
||||||
("その\u{3000}制御", "その制御"),
|
|
||||||
];
|
|
||||||
for (hypothesis, reference) in vectors {
|
|
||||||
assert_eq!(chrf(hypothesis, reference), 100.0, "{hypothesis:?}");
|
|
||||||
assert_eq!(chrf(reference, hypothesis), 100.0, "{hypothesis:?}");
|
|
||||||
}
|
|
||||||
// a zero-width space is not whitespace
|
|
||||||
close(chrf("a\u{200b}b", "ab"), 45.4545);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scorer_argument_order() {
|
|
||||||
let short = "shut the gate";
|
|
||||||
let long = "shut the gate before the storm arrives tonight";
|
|
||||||
let scorer = Scorer::new(Bag);
|
|
||||||
let got = score_one(&scorer, long, short);
|
|
||||||
assert_eq!(got.chrf, chrf(short, long));
|
|
||||||
assert_ne!(got.chrf, chrf(long, short));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn meaning_none_on_empty_text() {
|
|
||||||
let scorer = Scorer::new(Recorder::default());
|
|
||||||
let inputs = [
|
|
||||||
ScoreInput {
|
|
||||||
reference: "Nibu says hi",
|
|
||||||
output: " ",
|
|
||||||
},
|
|
||||||
ScoreInput {
|
|
||||||
reference: " ",
|
|
||||||
output: "says hi",
|
|
||||||
},
|
|
||||||
ScoreInput {
|
|
||||||
reference: "Nibu says hi",
|
|
||||||
output: "says hi",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let scores = scorer.score(&inputs).unwrap();
|
|
||||||
assert_eq!(scores[0].meaning, None);
|
|
||||||
assert_eq!(scores[1].meaning, None);
|
|
||||||
assert!(scores[2].meaning.is_some());
|
|
||||||
assert_eq!(
|
|
||||||
*scorer.embedder().seen.borrow(),
|
|
||||||
["Nibu says hi", "says hi"]
|
|
||||||
);
|
|
||||||
assert_eq!(scores[0].chrf, 0.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answers every embed call with the same vectors.
|
|
||||||
struct Fixed(Vec<Vec<f32>>);
|
|
||||||
|
|
||||||
impl Embedder for Fixed {
|
|
||||||
fn model(&self) -> &str {
|
|
||||||
"fixed"
|
|
||||||
}
|
|
||||||
fn embed(&self, _texts: &[&str]) -> Result<Vec<Vec<f32>>> {
|
|
||||||
Ok(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scorer_refuses_bad_vectors() {
|
|
||||||
let run = |vectors: Vec<Vec<f32>>| {
|
|
||||||
Scorer::new(Fixed(vectors)).score(&[ScoreInput {
|
|
||||||
reference: "shut the gate",
|
|
||||||
output: "mind the door",
|
|
||||||
}])
|
|
||||||
};
|
|
||||||
assert!(run(vec![vec![1.0, 2.0], vec![2.0, 1.0]]).is_ok());
|
|
||||||
for bad in [
|
|
||||||
vec![vec![1.0, 2.0], vec![1.0]],
|
|
||||||
vec![vec![1.0], vec![1.0, 2.0]],
|
|
||||||
vec![vec![], vec![]],
|
|
||||||
vec![vec![0.0, 0.0], vec![0.0, 0.0]],
|
|
||||||
vec![vec![1.0, 2.0], vec![0.0, 0.0]],
|
|
||||||
vec![vec![0.0, 0.0], vec![1.0, 2.0]],
|
|
||||||
vec![vec![1.0, f32::NAN], vec![1.0, 2.0]],
|
|
||||||
vec![vec![1.0, 2.0]],
|
|
||||||
] {
|
|
||||||
assert!(run(bad.clone()).is_err(), "{bad:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cosine_precondition() {
|
|
||||||
assert!((cosine(&[1.0, 2.0], &[2.0, 4.0]) - 1.0).abs() < 1e-9);
|
|
||||||
assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).abs() < 1e-9);
|
|
||||||
for (a, b) in [
|
|
||||||
(vec![1.0], vec![1.0, 1.0]),
|
|
||||||
(vec![], vec![]),
|
|
||||||
(vec![0.0, 0.0], vec![1.0, 1.0]),
|
|
||||||
] {
|
|
||||||
let refused = std::panic::catch_unwind(|| cosine(&a, &b));
|
|
||||||
assert!(refused.is_err(), "{a:?} {b:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plain-HTTP fake of `/api/embed`. Records each request body; answers with
|
|
||||||
/// `dim` floats per input, one fewer vector than asked when `drop_one`, and a
|
|
||||||
/// short last vector when `short_last`.
|
|
||||||
fn fake_ollama(drop_one: bool, short_last: bool) -> (String, Arc<Mutex<Vec<Value>>>) {
|
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
||||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
|
||||||
let bodies = Arc::new(Mutex::new(Vec::new()));
|
|
||||||
let seen = Arc::clone(&bodies);
|
|
||||||
std::thread::spawn(move || {
|
|
||||||
for stream in listener.incoming() {
|
|
||||||
let mut stream = stream.unwrap();
|
|
||||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
||||||
'conn: loop {
|
|
||||||
let mut length = 0;
|
|
||||||
let mut line = String::new();
|
|
||||||
let mut first = true;
|
|
||||||
loop {
|
|
||||||
line.clear();
|
|
||||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
|
||||||
break 'conn;
|
|
||||||
}
|
|
||||||
if first {
|
|
||||||
assert!(line.starts_with("POST /api/embed "), "{line}");
|
|
||||||
first = false;
|
|
||||||
}
|
|
||||||
let lower = line.to_ascii_lowercase();
|
|
||||||
if let Some(v) = lower.strip_prefix("content-length:") {
|
|
||||||
length = v.trim().parse().unwrap();
|
|
||||||
}
|
|
||||||
if line == "\r\n" {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut body = vec![0u8; length];
|
|
||||||
reader.read_exact(&mut body).unwrap();
|
|
||||||
let body: Value = serde_json::from_slice(&body).unwrap();
|
|
||||||
let mut count = body["input"].as_array().unwrap().len();
|
|
||||||
seen.lock().unwrap().push(body);
|
|
||||||
if drop_one {
|
|
||||||
count -= 1;
|
|
||||||
}
|
|
||||||
let vectors: Vec<Vec<f32>> = (0..count)
|
|
||||||
.map(|i| vec![1.0; if short_last && i + 1 == count { 2 } else { 3 }])
|
|
||||||
.collect();
|
|
||||||
let reply = serde_json::json!({ "embeddings": vectors }).to_string();
|
|
||||||
write!(
|
|
||||||
stream,
|
|
||||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{reply}",
|
|
||||||
reply.len()
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
(url, bodies)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lengths(bodies: &Mutex<Vec<Value>>) -> Vec<usize> {
|
|
||||||
let bodies = bodies.lock().unwrap();
|
|
||||||
bodies
|
|
||||||
.iter()
|
|
||||||
.map(|b| b["input"].as_array().unwrap().len())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ollama_request_shape_and_batching() {
|
|
||||||
let (url, bodies) = fake_ollama(false, false);
|
|
||||||
let embedder = OllamaEmbedder::new(&url, "qwen3-embedding:0.6b");
|
|
||||||
let texts: Vec<String> = (0..70).map(|i| format!("text {i}")).collect();
|
|
||||||
let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
|
|
||||||
let vectors = embedder.embed(&refs).unwrap();
|
|
||||||
assert_eq!(vectors.len(), 70);
|
|
||||||
assert_eq!(lengths(&bodies), [32, 32, 6]);
|
|
||||||
for body in bodies.lock().unwrap().iter() {
|
|
||||||
assert_eq!(body["model"], "qwen3-embedding:0.6b");
|
|
||||||
assert_eq!(body["options"]["num_thread"], 8);
|
|
||||||
}
|
|
||||||
assert_eq!(bodies.lock().unwrap()[2]["input"][5], "text 69");
|
|
||||||
|
|
||||||
let (url, _) = fake_ollama(true, false);
|
|
||||||
let err = OllamaEmbedder::new(&url, "m")
|
|
||||||
.embed(&["a", "b"])
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(err.to_string().contains("got 1"), "{err}");
|
|
||||||
|
|
||||||
let (url, _) = fake_ollama(false, true);
|
|
||||||
let err = OllamaEmbedder::new(&url, "m")
|
|
||||||
.embed(&["a", "b"])
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(err.to_string().contains("dimension"), "{err}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ollama_clamps_batch_and_omits_unset_num_thread() {
|
|
||||||
let (url, bodies) = fake_ollama(false, false);
|
|
||||||
let mut embedder = OllamaEmbedder::new(&url, "m");
|
|
||||||
embedder.batch = 500;
|
|
||||||
embedder.num_thread = None;
|
|
||||||
let texts: Vec<String> = (0..40).map(|i| i.to_string()).collect();
|
|
||||||
let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
|
|
||||||
embedder.embed(&refs).unwrap();
|
|
||||||
assert_eq!(lengths(&bodies), [32, 8]);
|
|
||||||
assert!(bodies.lock().unwrap()[0].get("options").is_none());
|
|
||||||
assert!(embedder.embed(&[]).unwrap().is_empty());
|
|
||||||
assert_eq!(lengths(&bodies).len(), 2, "no request for no texts");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[ignore = "needs WEKSA_OLLAMA_URL, Yggdrasil's ollama-cpu"]
|
|
||||||
fn ollama_on_yggdrasil() {
|
|
||||||
let url = std::env::var("WEKSA_OLLAMA_URL").unwrap();
|
|
||||||
let embedder = OllamaEmbedder::new(url, "qwen3-embedding:0.6b");
|
|
||||||
let text = "Take your hand off that control.";
|
|
||||||
let vectors = embedder.embed(&[text, text]).unwrap();
|
|
||||||
assert_eq!(vectors.len(), 2);
|
|
||||||
assert!(vectors.iter().all(|v| v.len() == 1024));
|
|
||||||
assert!((cosine(&vectors[0], &vectors[1]) - 1.0).abs() < 1e-4);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn score(chrf: f64, meaning: Option<f64>) -> ItemScore {
|
|
||||||
ItemScore { chrf, meaning }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn aggregate_by_derived_split() {
|
|
||||||
let train = item_in("item:a:1", "t", &group_in_bucket(10), cast());
|
|
||||||
let train2 = item_in("item:a:2", "t", &group_in_bucket(10), cast());
|
|
||||||
let validation = item_in("item:b:1", "v", &group_in_bucket(50), cast());
|
|
||||||
let test = item_in("item:c:1", "x", &group_in_bucket(90), cast());
|
|
||||||
let test_model = item_in("item:c:2", "x", &group_in_bucket(90), model());
|
|
||||||
let agg = aggregate(&[
|
|
||||||
(&train, score(10.0, Some(0.5))),
|
|
||||||
(&train2, score(20.0, None)),
|
|
||||||
(&validation, score(40.0, Some(0.8))),
|
|
||||||
(&test, score(60.0, Some(0.6))),
|
|
||||||
(&test_model, score(100.0, Some(1.0))),
|
|
||||||
]);
|
|
||||||
assert_eq!(agg.train.count, 2);
|
|
||||||
assert_eq!(agg.train.chrf, Some(15.0));
|
|
||||||
assert_eq!(agg.train.meaning, Some(0.5), "None is not averaged as zero");
|
|
||||||
assert_eq!((agg.validation.count, agg.validation.chrf), (1, Some(40.0)));
|
|
||||||
assert_eq!(aggregate(&[]).validation.chrf, None);
|
|
||||||
}
|
|
||||||
|
|
||||||
const HELD_OUT: &str = "extraordinary lighthouse keepers whispered unforgettable stories throughout midnight thunderstorms before surrendering peacefully";
|
|
||||||
const UNRELATED: &str = "harbor ledgers record ordinary tides";
|
|
||||||
|
|
||||||
fn chunks(size: usize, joiner: &str) -> Vec<String> {
|
|
||||||
HELD_OUT
|
|
||||||
.split(' ')
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.chunks(size)
|
|
||||||
.map(|c| c.join(joiner))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validation(key: &str, text: &str) -> CorpusItem {
|
|
||||||
item_in(key, text, &group_in_bucket(50), cast())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn train(key: &str, text: &str) -> CorpusItem {
|
|
||||||
item_in(key, text, &group_in_bucket(10), cast())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// (novel, covered) per order for the Validation split.
|
|
||||||
fn read(minted: &[&str], items: &[CorpusItem]) -> Vec<(usize, usize)> {
|
|
||||||
leak_diagnostic(minted, items)
|
|
||||||
.coverage_by_n
|
|
||||||
.iter()
|
|
||||||
.map(|c| (c.novel, c.covered))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refs(strings: &[String]) -> Vec<&str> {
|
|
||||||
strings.iter().map(String::as_str).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leak_diagnostic_catches_chunked_glosses() {
|
|
||||||
let minted = chunks(3, " ");
|
|
||||||
let minted = refs(&minted);
|
|
||||||
let held = validation("item:v:1", HELD_OUT);
|
|
||||||
let unrelated = validation("item:v:2", "gardening is quiet work");
|
|
||||||
let train_item = train("item:t:1", UNRELATED);
|
|
||||||
let test_model = item_in("item:x:1", HELD_OUT, &group_in_bucket(90), model());
|
|
||||||
|
|
||||||
let d = leak_diagnostic(
|
|
||||||
&minted,
|
|
||||||
&[
|
|
||||||
held.clone(),
|
|
||||||
unrelated.clone(),
|
|
||||||
train_item.clone(),
|
|
||||||
test_model,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
let pair = d.max_chrf.as_ref().unwrap();
|
|
||||||
assert!(
|
|
||||||
pair.chrf < 50.0,
|
|
||||||
"each chunk alone scores low: {}",
|
|
||||||
pair.chrf
|
|
||||||
);
|
|
||||||
assert_eq!(pair.item, "item:v:1");
|
|
||||||
// pooled over both items: 12+4 words, 11+3 bigrams, 10+2 trigrams
|
|
||||||
assert_eq!(
|
|
||||||
read(&minted, &[held.clone(), unrelated, train_item.clone()]),
|
|
||||||
[(16, 12), (14, 8), (12, 4)]
|
|
||||||
);
|
|
||||||
let worst = d.worst.as_ref().unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(worst.item.as_str(), worst.n, worst.covered, worst.novel),
|
|
||||||
("item:v:1", 2, 8, 11)
|
|
||||||
);
|
|
||||||
assert_eq!(d.items, 2);
|
|
||||||
|
|
||||||
let only_train = leak_diagnostic(&minted, &[train_item]);
|
|
||||||
assert_eq!(only_train.items, 0);
|
|
||||||
assert_eq!(only_train.max_chrf, None);
|
|
||||||
assert_eq!(only_train.worst, None);
|
|
||||||
|
|
||||||
let full = leak_diagnostic(&[HELD_OUT], &[held]);
|
|
||||||
assert_eq!(full.coverage_by_n[2].share, Some(1.0));
|
|
||||||
assert!(full.max_chrf.unwrap().chrf > 99.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_reads_joined_labels() {
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", HELD_OUT),
|
|
||||||
train("item:t:1", UNRELATED),
|
|
||||||
];
|
|
||||||
for size in [1, 2, 3] {
|
|
||||||
let plain = chunks(size, " ");
|
|
||||||
let want = read(&refs(&plain), &items);
|
|
||||||
for joiner in ["_", "."] {
|
|
||||||
let joined = chunks(size, joiner);
|
|
||||||
assert_eq!(read(&refs(&joined), &items), want, "{size} {joiner:?}");
|
|
||||||
}
|
|
||||||
// camelCase: each word after the first capitalised within a chunk
|
|
||||||
let camel: Vec<String> = chunks(size, " ")
|
|
||||||
.iter()
|
|
||||||
.map(|c| {
|
|
||||||
c.split(' ')
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, w)| match i {
|
|
||||||
0 => w.to_string(),
|
|
||||||
_ => w[..1].to_uppercase() + &w[1..],
|
|
||||||
})
|
|
||||||
.collect::<String>()
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
assert_eq!(read(&refs(&camel), &items), want, "{size} camel");
|
|
||||||
}
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "He will kick the bucket"),
|
|
||||||
train("item:t:1", "he will go"),
|
|
||||||
];
|
|
||||||
for label in [
|
|
||||||
"kick_the_bucket",
|
|
||||||
"kick.the.bucket",
|
|
||||||
"kickTheBucket",
|
|
||||||
"kick the bucket",
|
|
||||||
] {
|
|
||||||
let d = leak_diagnostic(&[label], &items);
|
|
||||||
let by_n = &d.coverage_by_n;
|
|
||||||
assert_eq!((by_n[2].novel, by_n[2].covered), (3, 1), "{label}");
|
|
||||||
let worst = d.worst.unwrap();
|
|
||||||
assert_eq!((worst.n, worst.covered), (2, 2), "{label}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_is_case_insensitive() {
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", HELD_OUT),
|
|
||||||
train("item:t:1", UNRELATED),
|
|
||||||
];
|
|
||||||
let minted = chunks(2, " ");
|
|
||||||
let shouted: Vec<String> = minted.iter().map(|m| m.to_uppercase()).collect();
|
|
||||||
assert_eq!(read(&refs(&shouted), &items), read(&refs(&minted), &items));
|
|
||||||
assert_eq!(read(&refs(&minted), &items)[0], (12, 12));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_pooled_per_order() {
|
|
||||||
// honest single-word glosses saturate n=1 and read nothing above it
|
|
||||||
let items = [
|
|
||||||
train(
|
|
||||||
"item:t:1",
|
|
||||||
"They left before the storm and found the harbor.",
|
|
||||||
),
|
|
||||||
validation("item:v:1", "They left the group before the storm."),
|
|
||||||
validation("item:v:2", "They found the place after the storm."),
|
|
||||||
validation("item:v:3", "Warn them before they leave the harbor."),
|
|
||||||
];
|
|
||||||
let glosses = [
|
|
||||||
"left", "group", "found", "place", "storm", "after", "warn", "leave", "harbor",
|
|
||||||
];
|
|
||||||
let d = leak_diagnostic(&glosses, &items);
|
|
||||||
let by_n = &d.coverage_by_n;
|
|
||||||
assert_eq!(by_n.iter().map(|c| c.n).collect::<Vec<_>>(), [1, 2, 3]);
|
|
||||||
assert_eq!((by_n[0].novel, by_n[0].covered), (6, 5));
|
|
||||||
assert!(by_n[0].share.unwrap() < 1.0);
|
|
||||||
for c in &by_n[1..] {
|
|
||||||
assert!(c.novel > 0);
|
|
||||||
assert_eq!((c.covered, c.share), (0, Some(0.0)));
|
|
||||||
}
|
|
||||||
assert_eq!(d.worst, None);
|
|
||||||
|
|
||||||
// no novel n-gram reads None, never NaN; an empty split reads the same
|
|
||||||
let items = [
|
|
||||||
train("item:t:1", "tides harbors guard the quiet shore"),
|
|
||||||
validation("item:v:1", "harbors guard the quiet"),
|
|
||||||
];
|
|
||||||
let d = leak_diagnostic(&["anything at all"], &items);
|
|
||||||
assert_eq!(d.coverage_by_n.len(), 3);
|
|
||||||
assert!(
|
|
||||||
d.coverage_by_n
|
|
||||||
.iter()
|
|
||||||
.all(|c| (c.novel, c.share) == (0, None))
|
|
||||||
);
|
|
||||||
assert_eq!(d.worst, None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_keeps_digits_and_strings() {
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "code 0400 open"),
|
|
||||||
train("item:t:1", "code open"),
|
|
||||||
];
|
|
||||||
assert_eq!(read(&["0400"], &items)[0], (1, 1));
|
|
||||||
// a bigram spanning two minted strings is not covered
|
|
||||||
let items = [validation("item:v:1", "zeta eta")];
|
|
||||||
assert_eq!(read(&["zeta", "eta"], &items), [(2, 2), (1, 0), (0, 0)]);
|
|
||||||
assert_eq!(read(&["zeta eta"], &items), [(2, 2), (1, 1), (0, 0)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn worst_item_rules() {
|
|
||||||
// equal covered counts: the larger share wins over an earlier, smaller one
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "alpha beta gamma"),
|
|
||||||
validation("item:v:2", "delta epsilon"),
|
|
||||||
];
|
|
||||||
let w = leak_diagnostic(&["alpha beta", "delta epsilon"], &items)
|
|
||||||
.worst
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(w.item.as_str(), w.n, w.covered, w.novel),
|
|
||||||
("item:v:2", 2, 1, 1)
|
|
||||||
);
|
|
||||||
// a later, smaller share does not displace an earlier larger one
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "delta epsilon"),
|
|
||||||
validation("item:v:2", "alpha beta gamma"),
|
|
||||||
];
|
|
||||||
let w = leak_diagnostic(&["alpha beta", "delta epsilon"], &items)
|
|
||||||
.worst
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(w.item, "item:v:1");
|
|
||||||
// a larger covered count beats a larger share
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "delta epsilon"),
|
|
||||||
validation("item:v:2", "alpha beta gamma delta"),
|
|
||||||
];
|
|
||||||
let w = leak_diagnostic(&["alpha beta gamma", "delta epsilon"], &items)
|
|
||||||
.worst
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!((w.item.as_str(), w.covered, w.novel), ("item:v:2", 2, 3));
|
|
||||||
// full ties go to the first item, then the smaller n
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "delta epsilon"),
|
|
||||||
validation("item:v:2", "delta epsilon"),
|
|
||||||
];
|
|
||||||
let w = leak_diagnostic(&["delta epsilon"], &items).worst.unwrap();
|
|
||||||
assert_eq!(w.item, "item:v:1");
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "alpha beta gamma"),
|
|
||||||
train("item:t:1", "alpha beta"),
|
|
||||||
];
|
|
||||||
let w = leak_diagnostic(&["alpha beta gamma"], &items)
|
|
||||||
.worst
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!((w.n, w.covered, w.novel), (2, 1, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ollama_reports_its_model() {
|
|
||||||
assert_eq!(
|
|
||||||
OllamaEmbedder::new("http://x", "qwen3-embedding:0.6b").model(),
|
|
||||||
"qwen3-embedding:0.6b"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leak_diagnostic_reports_the_best_pair_and_the_first_of_ties() {
|
|
||||||
let a = validation("item:v:1", HELD_OUT);
|
|
||||||
let b = validation("item:v:2", HELD_OUT);
|
|
||||||
// the better minted string comes second; equal items tie, the first is kept
|
|
||||||
let d = leak_diagnostic(&["zzzzzz qqqqqq", HELD_OUT], &[a, b]);
|
|
||||||
let pair = d.max_chrf.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(pair.minted.as_str(), pair.item.as_str()),
|
|
||||||
(HELD_OUT, "item:v:1")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scores_whole_texts() {
|
|
||||||
let reference = "He is going to kick the bucket tomorrow.";
|
|
||||||
let output = "He is going to die tomorrow.";
|
|
||||||
// exhaustive: a scorer input that grows a field breaks this line
|
|
||||||
let ScoreInput { reference, output } = ScoreInput { reference, output };
|
|
||||||
let scorer = Scorer::new(Recorder::default());
|
|
||||||
let got = score_one(&scorer, reference, output);
|
|
||||||
assert_eq!(*scorer.embedder().seen.borrow(), [reference, output]);
|
|
||||||
assert_eq!(got.chrf, chrf(output, reference));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn filler_costs() {
|
|
||||||
// naming filler cannot delete it: the scorer has no input but the two texts
|
|
||||||
let reference = "I am not angry.";
|
|
||||||
let filler = "Darling, I am truly not angry, darling.";
|
|
||||||
let scorer = Scorer::new(Bag);
|
|
||||||
close(score_one(&scorer, reference, filler).chrf, 46.8378);
|
|
||||||
let copy_reference = "He is going to kick the bucket tomorrow.";
|
|
||||||
let padded = "Well, he is going to kick the bucket tomorrow, honestly.";
|
|
||||||
let unnamed = score_one(&scorer, copy_reference, padded);
|
|
||||||
close(unnamed.chrf, chrf(padded, copy_reference));
|
|
||||||
assert!(unnamed.chrf < 100.0);
|
|
||||||
let honest = score_one(&scorer, "Never again.", "Never again.");
|
|
||||||
assert_eq!(honest.chrf, 100.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn honest_name_earns_credit() {
|
|
||||||
let scorer = Scorer::new(Bag);
|
|
||||||
let reference = "Brokkr came back.";
|
|
||||||
assert_eq!(score_one(&scorer, reference, reference).chrf, 100.0);
|
|
||||||
let wrong = score_one(&scorer, reference, "Kestrel came back.");
|
|
||||||
assert!(wrong.chrf < 100.0);
|
|
||||||
assert!(wrong.meaning.unwrap() < 1.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_script_alike() {
|
|
||||||
let scorer = Scorer::new(Bag);
|
|
||||||
for text in [
|
|
||||||
"민수가 왔다",
|
|
||||||
"Brokkr'ın gemisi geldi",
|
|
||||||
"Brokkrin laiva tuli",
|
|
||||||
"สมชายมาแล้ว",
|
|
||||||
"ブロッカーが来た。",
|
|
||||||
] {
|
|
||||||
let got = score_one(&scorer, text, text);
|
|
||||||
assert_eq!(got.chrf, 100.0, "{text}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// (reference, hypothesis, sacrebleu 2.4.3 sentence_chrf), one near miss per
|
|
||||||
/// script: the Thai hypothesis is the reference with its vowels and tone mark
|
|
||||||
/// stripped.
|
|
||||||
const SCRIPT_PAIRS: [(&str, &str, f64); 5] = [
|
|
||||||
("민수가 왔다", "민수는 왔다", 26.0),
|
|
||||||
("Brokkr'ın gemisi geldi", "Brokkr'ın gemisi gitti", 77.7548),
|
|
||||||
("Brokkrin laiva tuli", "Brokkrin laiva meni", 73.002),
|
|
||||||
("สมชายมาแล้ว", "สมชยมแลว", 21.8989),
|
|
||||||
("ブロッカーが来た。", "ブロッカーが行った。", 54.4013),
|
|
||||||
];
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_script_scores_a_near_miss_as_sacrebleu_does() {
|
|
||||||
let scorer = Scorer::new(Bag);
|
|
||||||
for (reference, hypothesis, want) in SCRIPT_PAIRS {
|
|
||||||
close(score_one(&scorer, reference, hypothesis).chrf, want);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_splits_at_any_non_word_character() {
|
|
||||||
let items = [
|
|
||||||
validation("item:v:1", "shut the gate before the storm"),
|
|
||||||
train("item:t:1", UNRELATED),
|
|
||||||
];
|
|
||||||
let want = read(&["shut the gate"], &items);
|
|
||||||
assert_eq!(want, [(5, 3), (5, 2), (4, 1)]);
|
|
||||||
for joiner in [
|
|
||||||
":", "\u{b7}", "'", "\u{2019}", "\u{ff3f}", "-", "/", "\u{2014}", "|", "+", "\u{ff1a}",
|
|
||||||
"\u{30fb}",
|
|
||||||
] {
|
|
||||||
let glued = format!("shut{joiner}the{joiner}gate");
|
|
||||||
assert_eq!(read(&[&glued], &items), want, "{joiner:?}");
|
|
||||||
}
|
|
||||||
// a mark, a joiner or a digit is part of its word, not a break
|
|
||||||
let items = [validation(
|
|
||||||
"item:v:1",
|
|
||||||
"\u{e2a}\u{e21}\u{e0a}\u{e32}\u{e22} \u{e21}\u{e32}\u{e41}\u{e25}\u{e49}\u{e27} 0400 \u{628}\u{200c}\u{628}",
|
|
||||||
)];
|
|
||||||
assert_eq!(
|
|
||||||
read(&["\u{e21}\u{e32}\u{e41}\u{e25}\u{e49}\u{e27}"], &items)[0],
|
|
||||||
(4, 1)
|
|
||||||
);
|
|
||||||
assert_eq!(read(&["\u{628}\u{200c}\u{628}", "0400"], &items)[0], (4, 2));
|
|
||||||
// a joiner keeps its word whole: the minted half is not a held-out word
|
|
||||||
let items = [validation("item:v:1", "\u{628}\u{200c}\u{62a} \u{62c}")];
|
|
||||||
assert_eq!(read(&["\u{628}\u{200c}\u{62a}"], &items)[0], (2, 1));
|
|
||||||
// decomposed and composed spellings are one word
|
|
||||||
let items = [validation("item:v:1", "Cafe\u{301}")];
|
|
||||||
assert_eq!(read(&["Caf\u{e9}"], &items)[0], (1, 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn coverage_reads_unspaced_scripts_by_run() {
|
|
||||||
// Han, kana and Thai write no word boundaries and the scorer holds no
|
|
||||||
// dictionary, so a run of them is one word, never one word per character.
|
|
||||||
// Honest single-word glosses then read nothing above n=1, as they do in a
|
|
||||||
// spaced script.
|
|
||||||
for (held, glosses) in [
|
|
||||||
(
|
|
||||||
"\u{5c71}\u{7530}\u{592a}\u{90ce}\u{304c}\u{6765}\u{305f}",
|
|
||||||
["\u{5c71}\u{7530}", "\u{592a}\u{90ce}", "\u{6765}\u{305f}"],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"\u{30d6}\u{30ed}\u{30c3}\u{30ab}\u{30fc}\u{304c}\u{6765}\u{305f}\u{3002}",
|
|
||||||
["\u{30d6}\u{30ed}", "\u{30ab}\u{30fc}", "\u{6765}"],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"\u{e2a}\u{e21}\u{e0a}\u{e32}\u{e22}\u{e21}\u{e32}\u{e41}\u{e25}\u{e49}\u{e27}",
|
|
||||||
[
|
|
||||||
"\u{e2a}\u{e21}",
|
|
||||||
"\u{e0a}\u{e32}\u{e22}",
|
|
||||||
"\u{e41}\u{e25}\u{e49}",
|
|
||||||
],
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let items = [validation("item:v:1", held), train("item:t:1", UNRELATED)];
|
|
||||||
assert_eq!(read(&glosses, &items), [(1, 0), (0, 0), (0, 0)], "{held}");
|
|
||||||
assert_eq!(read(&[held], &items), [(1, 1), (0, 0), (0, 0)], "{held}");
|
|
||||||
}
|
|
||||||
// Delimiters still make words: spaces and punctuation between runs, and a
|
|
||||||
// change between an unspaced script and a spaced one.
|
|
||||||
let items = [
|
|
||||||
validation(
|
|
||||||
"item:v:1",
|
|
||||||
"\u{72ac}\u{304c} \u{8d70}\u{308b}\u{3001}\u{732b}\u{3082} Brokkr\u{5c71}",
|
|
||||||
),
|
|
||||||
train("item:t:1", UNRELATED),
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
read(
|
|
||||||
&["\u{72ac}\u{304c} \u{8d70}\u{308b} \u{732b}\u{3082} brokkr \u{5c71}"],
|
|
||||||
&items
|
|
||||||
),
|
|
||||||
[(5, 5), (4, 4), (3, 3)]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_unspaced_script_ends_a_word_beside_any_other_script() {
|
|
||||||
// the first and last letters or digits of every range the rule names
|
|
||||||
let unspaced = [
|
|
||||||
'\u{3005}',
|
|
||||||
'\u{3007}',
|
|
||||||
'\u{3021}',
|
|
||||||
'\u{3029}',
|
|
||||||
'\u{3038}',
|
|
||||||
'\u{303b}',
|
|
||||||
'\u{3041}',
|
|
||||||
'\u{30ff}',
|
|
||||||
'\u{31f0}',
|
|
||||||
'\u{31ff}',
|
|
||||||
'\u{3400}',
|
|
||||||
'\u{4dbf}',
|
|
||||||
'\u{4e00}',
|
|
||||||
'\u{9fff}',
|
|
||||||
'\u{f900}',
|
|
||||||
'\u{fad9}',
|
|
||||||
'\u{ff66}',
|
|
||||||
'\u{ff9f}',
|
|
||||||
'\u{20000}',
|
|
||||||
'\u{2a6df}',
|
|
||||||
'\u{31350}',
|
|
||||||
'\u{323af}',
|
|
||||||
'\u{e01}',
|
|
||||||
'\u{e59}',
|
|
||||||
'\u{e81}',
|
|
||||||
'\u{edf}',
|
|
||||||
'\u{1000}',
|
|
||||||
'\u{1049}',
|
|
||||||
'\u{1780}',
|
|
||||||
'\u{17e9}',
|
|
||||||
];
|
|
||||||
for c in unspaced {
|
|
||||||
assert!(c.is_alphanumeric(), "{c:?} is a letter or digit");
|
|
||||||
let items = [validation("item:v:1", &format!("ab{c}"))];
|
|
||||||
assert_eq!(read(&["ab", &c.to_string()], &items)[0], (2, 2), "{c:?}");
|
|
||||||
}
|
|
||||||
// Hangul, Latin and Cyrillic are spaced scripts: no break between them
|
|
||||||
for c in ['\u{ac00}', '\u{d7a3}', '\u{e9}', '\u{44f}', '7'] {
|
|
||||||
let glued = format!("ab{c}");
|
|
||||||
let items = [validation("item:v:1", &glued)];
|
|
||||||
assert_eq!(read(&[&glued], &items)[0], (1, 1), "{c:?}");
|
|
||||||
assert_eq!(read(&["ab"], &items)[0], (1, 0), "{c:?}");
|
|
||||||
}
|
|
||||||
// a combining mark or a joiner after an unspaced character stays on it
|
|
||||||
let held = "\u{4e00}\u{301}\u{200d}ab";
|
|
||||||
let items = [validation("item:v:1", held)];
|
|
||||||
assert_eq!(read(&["\u{4e00}\u{301}\u{200d}", "ab"], &items)[0], (2, 2));
|
|
||||||
assert_eq!(read(&["\u{4e00}"], &items)[0], (2, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn round_path_reads_no_test() {
|
|
||||||
let train = item_in("item:a:1", "t", &group_in_bucket(10), cast());
|
|
||||||
let validation = item_in("item:b:1", "v", &group_in_bucket(50), cast());
|
|
||||||
let mut withdrawn = item_in("item:b:2", "w", &group_in_bucket(50), cast());
|
|
||||||
withdrawn.withdrawn = true;
|
|
||||||
let test = item_in("item:c:1", "x", &group_in_bucket(90), cast());
|
|
||||||
let test_two = item_in("item:c:2", "y", &group_in_bucket(90), cast());
|
|
||||||
let reading = |test_score: f64, extra: bool| {
|
|
||||||
let mut scored = vec![
|
|
||||||
(&train, score(10.0, Some(0.5))),
|
|
||||||
(&validation, score(40.0, Some(0.8))),
|
|
||||||
(&withdrawn, score(99.0, Some(0.99))),
|
|
||||||
(&test, score(test_score, Some(0.1))),
|
|
||||||
];
|
|
||||||
if extra {
|
|
||||||
scored.push((&test_two, score(100.0, Some(1.0))));
|
|
||||||
}
|
|
||||||
aggregate(&scored)
|
|
||||||
};
|
|
||||||
let base = reading(60.0, false);
|
|
||||||
assert_eq!(
|
|
||||||
(base.validation.count, base.validation.chrf),
|
|
||||||
(1, Some(40.0))
|
|
||||||
);
|
|
||||||
assert_eq!(base.validation.meaning, Some(0.8));
|
|
||||||
assert_eq!((base.train.count, base.train.chrf), (1, Some(10.0)));
|
|
||||||
assert_eq!(reading(5.0, false), base, "a Test score moves nothing");
|
|
||||||
assert_eq!(reading(5.0, true), base, "a Test item adds nothing");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn leak_diagnostic_reads_validation_only() {
|
|
||||||
let test = item_in("item:t:9", HELD_OUT, &group_in_bucket(90), cast());
|
|
||||||
let val = validation("item:v:1", "gardening is quiet work");
|
|
||||||
let mut gone = validation("item:v:2", HELD_OUT);
|
|
||||||
gone.withdrawn = true;
|
|
||||||
let train_item = train("item:t:1", UNRELATED);
|
|
||||||
let items = [test, val.clone(), gone, train_item.clone()];
|
|
||||||
|
|
||||||
let d = leak_diagnostic(&[HELD_OUT], &items);
|
|
||||||
assert_eq!(d.items, 1, "Validation only, withdrawn dropped");
|
|
||||||
assert_ne!(d.max_chrf.as_ref().unwrap().item, "item:t:9");
|
|
||||||
assert_eq!(d.max_chrf.as_ref().unwrap().item, "item:v:1");
|
|
||||||
assert!(d.max_chrf.as_ref().unwrap().chrf < 50.0);
|
|
||||||
assert_eq!(d.worst, None);
|
|
||||||
let without_test = leak_diagnostic(&[HELD_OUT], &[val.clone(), train_item.clone()]);
|
|
||||||
assert_eq!(d, without_test, "removing the Test item changes nothing");
|
|
||||||
|
|
||||||
let on_validation = leak_diagnostic(&["gardening is quiet work"], &items);
|
|
||||||
assert!(on_validation.max_chrf.unwrap().chrf > 99.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn held_out_train_union_excludes_withdrawn_train_items() {
|
|
||||||
let mut gone = train("item:t:1", HELD_OUT);
|
|
||||||
gone.withdrawn = true;
|
|
||||||
let held = validation("item:v:1", HELD_OUT);
|
|
||||||
let d = leak_diagnostic(
|
|
||||||
&[HELD_OUT],
|
|
||||||
&[gone, held.clone(), train("item:t:2", UNRELATED)],
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
d.coverage_by_n
|
|
||||||
.iter()
|
|
||||||
.map(|c| (c.novel, c.covered))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
[(12, 12), (11, 11), (10, 10)],
|
|
||||||
"a withdrawn Train text makes no n-gram known"
|
|
||||||
);
|
|
||||||
let live = leak_diagnostic(&[HELD_OUT], &[train("item:t:1", HELD_OUT), held]);
|
|
||||||
assert_eq!(live.coverage_by_n[0].novel, 0, "a live Train text does");
|
|
||||||
}
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
//! The committed seed stores replay through today's doors, so a rule that
|
|
||||||
//! tightens cannot leave a seed the stores would now refuse.
|
|
||||||
mod common;
|
|
||||||
use std::path::Path;
|
|
||||||
use weksa::{CorpusStore, EntityStore};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn committed_seeds_replay_through_the_doors() {
|
|
||||||
let data = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data");
|
|
||||||
let seeded_entities = EntityStore::open(&data.join("entity/entity.cc")).unwrap();
|
|
||||||
let seeded_corpus = CorpusStore::open(&data.join("corpus/corpus.cc")).unwrap();
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut entities = EntityStore::open(&dir.path().join("e.cc")).unwrap();
|
|
||||||
let all = seeded_entities.all().unwrap();
|
|
||||||
assert!(!all.is_empty());
|
|
||||||
for e in all {
|
|
||||||
entities.put(e).unwrap();
|
|
||||||
}
|
|
||||||
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
|
||||||
let items = seeded_corpus.all().unwrap();
|
|
||||||
assert!(!items.is_empty());
|
|
||||||
for item in items {
|
|
||||||
let withdrawn = item.withdrawn;
|
|
||||||
let id = item.id.clone();
|
|
||||||
corpus
|
|
||||||
.add(
|
|
||||||
weksa::CorpusItem {
|
|
||||||
withdrawn: false,
|
|
||||||
..item
|
|
||||||
},
|
|
||||||
&entities,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
if withdrawn {
|
|
||||||
corpus.withdraw(&id).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,503 +0,0 @@
|
||||||
//! The speaker-state store: speaker and scene documents are append-only
|
|
||||||
//! revisions, checked against the inventory, the entity store and the corpus.
|
|
||||||
|
|
||||||
mod common;
|
|
||||||
use common::{cast, eid, entities_in, grade, item_in, lab};
|
|
||||||
use weksa::inventory::{proof_revision, seed, speaker_scene_revision};
|
|
||||||
use weksa::packet::{FeatValue, FeatureValue};
|
|
||||||
use weksa::speaker::{
|
|
||||||
Annotator, MAX_PARTICIPANTS, PairRelation, Party, Scene, Speaker, scene_key, speaker_key,
|
|
||||||
};
|
|
||||||
use weksa::{
|
|
||||||
AddOutcome, CorpusStore, EntityStore, InventoryStore, Refusal, SpeakerStateStore, StoreError,
|
|
||||||
StoreRefusal,
|
|
||||||
};
|
|
||||||
|
|
||||||
struct W {
|
|
||||||
dir: tempfile::TempDir,
|
|
||||||
inventory: InventoryStore,
|
|
||||||
corpus: CorpusStore,
|
|
||||||
entities: EntityStore,
|
|
||||||
state: SpeakerStateStore,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Group `g` holds two live items (speakers nibu and brokkr) and one withdrawn
|
|
||||||
/// 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();
|
|
||||||
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision(3)] {
|
|
||||||
inventory.admit_revision(rev, entries).unwrap();
|
|
||||||
}
|
|
||||||
let entities = entities_in(dir.path());
|
|
||||||
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
|
||||||
for (key, text, speaker) in [
|
|
||||||
("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();
|
|
||||||
let state = SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
|
|
||||||
W {
|
|
||||||
dir,
|
|
||||||
inventory,
|
|
||||||
corpus,
|
|
||||||
entities,
|
|
||||||
state,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn feat(gloss: &str, value: FeatValue) -> FeatureValue {
|
|
||||||
let feature = seed()
|
|
||||||
.1
|
|
||||||
.into_iter()
|
|
||||||
.chain(speaker_scene_revision(3).1)
|
|
||||||
.find(|e| e.gloss == gloss)
|
|
||||||
.unwrap_or_else(|| panic!("no feature {gloss}"))
|
|
||||||
.id;
|
|
||||||
FeatureValue { feature, value }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn speaker(n: u32, age: &str) -> Speaker {
|
|
||||||
Speaker {
|
|
||||||
entity: eid("nibu"),
|
|
||||||
n,
|
|
||||||
inventory_rev: 3,
|
|
||||||
features: vec![feat("age_cohort", FeatValue::Option(lab(age)))],
|
|
||||||
annotator: Annotator::Operator,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scene(n: u32, intimacy: u16) -> Scene {
|
|
||||||
Scene {
|
|
||||||
group: "g".into(),
|
|
||||||
n,
|
|
||||||
inventory_rev: 3,
|
|
||||||
participants: vec![eid("nibu"), eid("brokkr")],
|
|
||||||
relations: vec![PairRelation {
|
|
||||||
from: eid("nibu"),
|
|
||||||
to: Party::Named(eid("brokkr")),
|
|
||||||
features: vec![feat("intimacy", FeatValue::Grade(grade(intimacy)))],
|
|
||||||
}],
|
|
||||||
annotator: Annotator::Operator,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put_speaker(w: &mut W, s: Speaker) -> Result<AddOutcome, StoreError> {
|
|
||||||
w.state.put_speaker(s, &w.inventory, &w.entities)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put_scene(w: &mut W, s: Scene) -> Result<AddOutcome, StoreError> {
|
|
||||||
w.state.put_scene(s, &w.inventory, &w.corpus, &w.entities)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refused<T: std::fmt::Debug>(r: Result<T, StoreError>) -> StoreRefusal {
|
|
||||||
match r.unwrap_err() {
|
|
||||||
StoreError::Refused(r) => r,
|
|
||||||
other => panic!("not a store refusal: {other}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn malformed(r: Result<AddOutcome, StoreError>, key: &str, why: &str) {
|
|
||||||
match refused(r) {
|
|
||||||
StoreRefusal::Malformed { key: k, why: w } => assert_eq!((k.as_str(), w), (key, why)),
|
|
||||||
other => panic!("not Malformed: {other:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rules(r: Result<AddOutcome, StoreError>) -> Vec<&'static str> {
|
|
||||||
match r.unwrap_err() {
|
|
||||||
StoreError::Invalid(rs) => rs.iter().map(Refusal::rule).collect(),
|
|
||||||
other => panic!("not a rule refusal: {other}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn not_next(key: &str, expected: u32, got: u32) -> StoreRefusal {
|
|
||||||
StoreRefusal::RevisionNotNext {
|
|
||||||
key: key.into(),
|
|
||||||
expected,
|
|
||||||
got,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keys_derive_from_the_document() {
|
|
||||||
assert_eq!(speaker_key(&eid("nibu"), 2), "speaker:nibu@2");
|
|
||||||
assert_eq!(scene_key("g", 3), "scene:g@3");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn speaker_revisions_append() {
|
|
||||||
let mut w = world();
|
|
||||||
let key = |n| speaker_key(&eid("nibu"), n);
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_speaker(&mut w, speaker(2, "adult"))),
|
|
||||||
not_next(&key(2), 1, 2)
|
|
||||||
);
|
|
||||||
assert!(w.state.speaker(&eid("nibu")).unwrap().is_none());
|
|
||||||
assert_eq!(
|
|
||||||
put_speaker(&mut w, speaker(1, "adult")).unwrap(),
|
|
||||||
AddOutcome::Added
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
put_speaker(&mut w, speaker(1, "adult")).unwrap(),
|
|
||||||
AddOutcome::Unchanged
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_speaker(&mut w, speaker(1, "elder"))),
|
|
||||||
not_next(&key(1), 2, 1)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_speaker(&mut w, speaker(3, "elder"))),
|
|
||||||
not_next(&key(3), 2, 3)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
put_speaker(&mut w, speaker(2, "elder")).unwrap(),
|
|
||||||
AddOutcome::Added
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
w.state.speaker(&eid("nibu")).unwrap(),
|
|
||||||
Some(speaker(2, "elder"))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
w.state.get_speaker(&key(1)).unwrap(),
|
|
||||||
Some(speaker(1, "adult"))
|
|
||||||
);
|
|
||||||
// Another entity's revisions count from 1 and stay apart.
|
|
||||||
let mut other = speaker(1, "child");
|
|
||||||
other.entity = eid("brokkr");
|
|
||||||
assert_eq!(put_speaker(&mut w, other).unwrap(), AddOutcome::Added);
|
|
||||||
assert_eq!(w.state.speaker(&eid("nibu")).unwrap().unwrap().n, 2);
|
|
||||||
// Revision 10 sorts after 2 in the listing.
|
|
||||||
for n in 3..=10 {
|
|
||||||
put_speaker(&mut w, speaker(n, "adult")).unwrap();
|
|
||||||
}
|
|
||||||
let listed: Vec<_> = w
|
|
||||||
.state
|
|
||||||
.all_speakers()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|s| (s.entity.to_string(), s.n))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(listed.len(), 11);
|
|
||||||
assert_eq!(listed[0], ("entity:brokkr".into(), 1));
|
|
||||||
assert_eq!(listed[10], ("entity:nibu".into(), 10));
|
|
||||||
assert_eq!(w.state.speaker(&eid("nibu")).unwrap().unwrap().n, 10);
|
|
||||||
// The documents survive a reopen.
|
|
||||||
let again = SpeakerStateStore::open(&w.dir.path().join("s.cc")).unwrap();
|
|
||||||
assert_eq!(again.all_speakers().unwrap().len(), 11);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scene_revisions_append() {
|
|
||||||
let mut w = world();
|
|
||||||
let key = |n| scene_key("g", n);
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_scene(&mut w, scene(2, 5))),
|
|
||||||
not_next(&key(2), 1, 2)
|
|
||||||
);
|
|
||||||
assert!(w.state.scene("g").unwrap().is_none());
|
|
||||||
assert_eq!(put_scene(&mut w, scene(1, 5)).unwrap(), AddOutcome::Added);
|
|
||||||
assert_eq!(
|
|
||||||
put_scene(&mut w, scene(1, 5)).unwrap(),
|
|
||||||
AddOutcome::Unchanged
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_scene(&mut w, scene(1, 6))),
|
|
||||||
not_next(&key(1), 2, 1)
|
|
||||||
);
|
|
||||||
assert_eq!(put_scene(&mut w, scene(2, 6)).unwrap(), AddOutcome::Added);
|
|
||||||
assert_eq!(w.state.scene("g").unwrap(), Some(scene(2, 6)));
|
|
||||||
assert_eq!(w.state.get_scene(&key(1)).unwrap(), Some(scene(1, 5)));
|
|
||||||
for n in 3..=10 {
|
|
||||||
put_scene(&mut w, scene(n, 6)).unwrap();
|
|
||||||
}
|
|
||||||
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]
|
|
||||||
fn speaker_needs_a_known_entity() {
|
|
||||||
let mut w = world();
|
|
||||||
let mut s = speaker(1, "adult");
|
|
||||||
s.entity = eid("nobody");
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_speaker(&mut w, s)),
|
|
||||||
StoreRefusal::UnknownEntity {
|
|
||||||
entity: eid("nobody")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
assert!(w.state.all_speakers().unwrap().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn annotation_features_are_checked_like_packet_features() {
|
|
||||||
let mut w = world();
|
|
||||||
let age = || feat("age_cohort", FeatValue::Option(lab("adult")));
|
|
||||||
let with = |features: Vec<FeatureValue>, rev| Speaker {
|
|
||||||
features,
|
|
||||||
inventory_rev: rev,
|
|
||||||
..speaker(1, "adult")
|
|
||||||
};
|
|
||||||
// A Scene feature and a Stance feature do not apply to a speaker.
|
|
||||||
let f = vec![feat("intimacy", FeatValue::Grade(grade(1)))];
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(f, 3))), ["V8"]);
|
|
||||||
let f = vec![feat("anger", FeatValue::Grade(grade(1)))];
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(f, 3))), ["V8"]);
|
|
||||||
// A wrong kind and an undeclared label.
|
|
||||||
let f = vec![feat("education", FeatValue::Flag(true))];
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(f, 3))), ["V7"]);
|
|
||||||
let f = vec![feat("age_cohort", FeatValue::Option(lab("ancient")))];
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(f, 3))), ["V7"]);
|
|
||||||
// Feature 22 does not exist at revision 2; revision 9 has no record.
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(vec![age()], 2))), ["V5"]);
|
|
||||||
assert_eq!(rules(put_speaker(&mut w, with(vec![age()], 9))), ["V10"]);
|
|
||||||
// A repeat.
|
|
||||||
assert_eq!(
|
|
||||||
rules(put_speaker(&mut w, with(vec![age(), age()], 3))),
|
|
||||||
["V11"]
|
|
||||||
);
|
|
||||||
// A Speaker feature in a scene relation.
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.relations[0].features = vec![age()];
|
|
||||||
assert_eq!(rules(put_scene(&mut w, s)), ["V8"]);
|
|
||||||
// Every relation is checked, and a scene of an unknown revision is V10.
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.relations.push(PairRelation {
|
|
||||||
from: eid("brokkr"),
|
|
||||||
to: Party::Unnamed,
|
|
||||||
features: vec![age()],
|
|
||||||
});
|
|
||||||
assert_eq!(rules(put_scene(&mut w, s)), ["V8"]);
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.inventory_rev = 9;
|
|
||||||
assert_eq!(rules(put_scene(&mut w, s)), ["V10"]);
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.inventory_rev = 9;
|
|
||||||
s.relations.clear();
|
|
||||||
assert_eq!(rules(put_scene(&mut w, s)), ["V10"]);
|
|
||||||
assert!(w.state.all_speakers().unwrap().is_empty());
|
|
||||||
assert!(w.state.all_scenes().unwrap().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scene_shape_rules() {
|
|
||||||
let mut w = world();
|
|
||||||
let key = scene_key("g", 1);
|
|
||||||
let relation = |from: &str, to: Party| PairRelation {
|
|
||||||
from: eid(from),
|
|
||||||
to,
|
|
||||||
features: vec![],
|
|
||||||
};
|
|
||||||
let named = |to: &str| Party::Named(eid(to));
|
|
||||||
let base = || scene(1, 1);
|
|
||||||
|
|
||||||
let mut s = base();
|
|
||||||
s.group = "Not A Slug".into();
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&scene_key("Not A Slug", 1),
|
|
||||||
"a scene group is a slug",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.group = "elsewhere".into();
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&scene_key("elsewhere", 1),
|
|
||||||
"no corpus item holds the scene's group",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.participants.clear();
|
|
||||||
s.relations.clear();
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a scene has 1 to 64 participants",
|
|
||||||
);
|
|
||||||
// 64 participants are fine as far as the count goes (the rest fail later);
|
|
||||||
// 65 are refused for the count.
|
|
||||||
let many = |count: usize| -> Vec<_> { (0..count).map(|i| eid(&format!("p{i}"))).collect() };
|
|
||||||
let mut s = base();
|
|
||||||
s.participants = many(MAX_PARTICIPANTS + 1);
|
|
||||||
s.relations.clear();
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a scene has 1 to 64 participants",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.participants = many(MAX_PARTICIPANTS);
|
|
||||||
s.relations.clear();
|
|
||||||
assert!(matches!(
|
|
||||||
refused(put_scene(&mut w, s)),
|
|
||||||
StoreRefusal::UnknownEntity { .. }
|
|
||||||
));
|
|
||||||
let mut s = base();
|
|
||||||
s.participants.push(eid("nibu"));
|
|
||||||
malformed(put_scene(&mut w, s), &key, "a participant is named once");
|
|
||||||
let mut s = base();
|
|
||||||
s.participants.push(eid("nobody"));
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_scene(&mut w, s)),
|
|
||||||
StoreRefusal::UnknownEntity {
|
|
||||||
entity: eid("nobody")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![relation("hero", named("nibu"))];
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a relation's from is a participant",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![relation("nibu", named("hero"))];
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a relation's named to is another participant",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![relation("nibu", named("nibu"))];
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a relation's named to is another participant",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![
|
|
||||||
relation("nibu", named("brokkr")),
|
|
||||||
relation("nibu", named("brokkr")),
|
|
||||||
];
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"an ordered pair has one relation",
|
|
||||||
);
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![
|
|
||||||
relation("nibu", Party::Unnamed),
|
|
||||||
relation("nibu", Party::Unnamed),
|
|
||||||
];
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"an ordered pair has one relation",
|
|
||||||
);
|
|
||||||
// The reverse pair, and an unnamed party beside a named one, are distinct.
|
|
||||||
let mut s = base();
|
|
||||||
s.relations = vec![
|
|
||||||
relation("nibu", named("brokkr")),
|
|
||||||
relation("brokkr", named("nibu")),
|
|
||||||
relation("nibu", Party::Unnamed),
|
|
||||||
];
|
|
||||||
assert_eq!(put_scene(&mut w, s).unwrap(), AddOutcome::Added);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_scene_holds_every_live_speaker_of_its_group() {
|
|
||||||
let mut w = world();
|
|
||||||
// Brokkr speaks a live item of the group.
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.participants = vec![eid("nibu")];
|
|
||||||
s.relations.clear();
|
|
||||||
assert_eq!(
|
|
||||||
refused(put_scene(&mut w, s)),
|
|
||||||
StoreRefusal::SceneSpeakerMissing {
|
|
||||||
group: "g".into(),
|
|
||||||
entity: eid("brokkr")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
// Hero speaks only a withdrawn item, so the scene may omit them.
|
|
||||||
assert_eq!(put_scene(&mut w, scene(1, 1)).unwrap(), AddOutcome::Added);
|
|
||||||
// The group is held by a withdrawn item alone: still a group.
|
|
||||||
w.corpus.withdraw("item:nibu:1").unwrap();
|
|
||||||
w.corpus.withdraw("item:nibu:2").unwrap();
|
|
||||||
let mut s = scene(2, 1);
|
|
||||||
s.participants = vec![eid("player")];
|
|
||||||
s.relations.clear();
|
|
||||||
assert_eq!(put_scene(&mut w, s).unwrap(), AddOutcome::Added);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn model_annotator_attests_its_generator() {
|
|
||||||
let mut w = world();
|
|
||||||
let model = |generator: &str| Annotator::Model {
|
|
||||||
family: weksa::corpus::ModelFamily::Anthropic,
|
|
||||||
generator: generator.into(),
|
|
||||||
};
|
|
||||||
let key = speaker_key(&eid("nibu"), 1);
|
|
||||||
for bad in ["", " ", "gen\u{7}erator", "gen\nerator", "\u{200d}"] {
|
|
||||||
let mut s = speaker(1, "adult");
|
|
||||||
s.annotator = model(bad);
|
|
||||||
malformed(
|
|
||||||
put_speaker(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a model annotator attests its generator",
|
|
||||||
);
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.annotator = model(bad);
|
|
||||||
malformed(
|
|
||||||
put_scene(&mut w, s),
|
|
||||||
&scene_key("g", 1),
|
|
||||||
"a model annotator attests its generator",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut s = speaker(1, "adult");
|
|
||||||
s.annotator = model(&"x".repeat(201));
|
|
||||||
malformed(
|
|
||||||
put_speaker(&mut w, s),
|
|
||||||
&key,
|
|
||||||
"a model annotator attests its generator",
|
|
||||||
);
|
|
||||||
let mut s = speaker(1, "adult");
|
|
||||||
s.annotator = model("claude-sonnet 5.5");
|
|
||||||
assert_eq!(put_speaker(&mut w, s).unwrap(), AddOutcome::Added);
|
|
||||||
let mut s = scene(1, 1);
|
|
||||||
s.annotator = model("claude-sonnet 5.5");
|
|
||||||
assert_eq!(put_scene(&mut w, s).unwrap(), AddOutcome::Added);
|
|
||||||
let mut s = speaker(2, "adult");
|
|
||||||
s.annotator = Annotator::Operator;
|
|
||||||
assert_eq!(put_speaker(&mut w, s).unwrap(), AddOutcome::Added);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refusal_displays_print_numbers_and_no_identifiers() {
|
|
||||||
let r = not_next("speaker:secretname@2", 1, 2);
|
|
||||||
assert_eq!(r.to_string(), "RevisionNotNext expected 1 got 2");
|
|
||||||
let r = StoreRefusal::SceneSpeakerMissing {
|
|
||||||
group: "secretgroup".into(),
|
|
||||||
entity: eid("secretname"),
|
|
||||||
};
|
|
||||||
assert_eq!(r.to_string(), "SceneSpeakerMissing");
|
|
||||||
}
|
|
||||||
|
|
@ -1,189 +0,0 @@
|
||||||
use weksa::corpus::{CorpusItem, ModelFamily, Source};
|
|
||||||
use weksa::split::fnv1a64;
|
|
||||||
use weksa::{Split, SplitScheme};
|
|
||||||
|
|
||||||
fn item(group: &str, source: Source) -> CorpusItem {
|
|
||||||
CorpusItem {
|
|
||||||
id: "item:t:1".into(),
|
|
||||||
text: "t".into(),
|
|
||||||
language: "en-US".into(),
|
|
||||||
speaker: weksa::EntityId::parse("entity:s").unwrap(),
|
|
||||||
names: vec![],
|
|
||||||
names_by: None,
|
|
||||||
group: group.into(),
|
|
||||||
prior_turns: vec![],
|
|
||||||
source,
|
|
||||||
admitted_on: "2026-10-29".into(),
|
|
||||||
supersedes: None,
|
|
||||||
withdrawn: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cast() -> Source {
|
|
||||||
Source::CastAuthored {
|
|
||||||
persona: "p".into(),
|
|
||||||
fixture: "f".into(),
|
|
||||||
author: "a".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn model() -> Source {
|
|
||||||
Source::ModelWritten {
|
|
||||||
family: ModelFamily::Unrecorded,
|
|
||||||
generator: None,
|
|
||||||
prompt_digest: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_in_bucket(want: u64) -> String {
|
|
||||||
(0..100_000)
|
|
||||||
.map(|i| format!("g{i}"))
|
|
||||||
.find(|g| SplitScheme::V1.bucket(g) == want)
|
|
||||||
.unwrap_or_else(|| panic!("no group lands in bucket {want}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fnv1a64_matches_the_reference_vectors() {
|
|
||||||
assert_eq!(fnv1a64(b""), 0xcbf2_9ce4_8422_2325);
|
|
||||||
assert_eq!(fnv1a64(b"a"), 0xaf63_dc4c_8601_ec8c);
|
|
||||||
assert_eq!(fnv1a64(b"foobar"), 0x8594_4171_f739_67e8);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn p1_split_deterministic() {
|
|
||||||
let a = SplitScheme::V1.split(&item("scene-9", cast()));
|
|
||||||
for _ in 0..3 {
|
|
||||||
assert_eq!(SplitScheme::V1.split(&item("scene-9", cast())), a);
|
|
||||||
}
|
|
||||||
// The split reads the group and nothing else: speaker, text and id do not move it.
|
|
||||||
let mut other = item("scene-9", cast());
|
|
||||||
other.speaker = weksa::EntityId::parse("entity:someone").unwrap();
|
|
||||||
other.text = "different".into();
|
|
||||||
other.id = "item:other:7".into();
|
|
||||||
assert_eq!(SplitScheme::V1.split(&other), a);
|
|
||||||
// The bucket is the pinned hash of the prefixed group.
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.bucket("x"),
|
|
||||||
fnv1a64(b"weksa-split-v1:x") % 100
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn split_boundaries() {
|
|
||||||
let s = SplitScheme::V1;
|
|
||||||
assert_eq!(s.of_bucket(0), Split::Train);
|
|
||||||
assert_eq!(s.of_bucket(39), Split::Train);
|
|
||||||
assert_eq!(s.of_bucket(40), Split::Validation);
|
|
||||||
assert_eq!(s.of_bucket(79), Split::Validation);
|
|
||||||
assert_eq!(s.of_bucket(80), Split::Test);
|
|
||||||
assert_eq!(s.of_bucket(99), Split::Test);
|
|
||||||
for (bucket, want) in [
|
|
||||||
(39, Split::Train),
|
|
||||||
(40, Split::Validation),
|
|
||||||
(79, Split::Validation),
|
|
||||||
(80, Split::Test),
|
|
||||||
] {
|
|
||||||
assert_eq!(
|
|
||||||
s.split(&item(&group_in_bucket(bucket), cast())),
|
|
||||||
Some(want),
|
|
||||||
"bucket {bucket}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn p2_model_written_in_a_test_group_is_excluded() {
|
|
||||||
let test_group = group_in_bucket(95);
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.split(&item(&test_group, cast())),
|
|
||||||
Some(Split::Test)
|
|
||||||
);
|
|
||||||
// A model line of the test meaning is in no split; it is never moved to train.
|
|
||||||
assert_eq!(SplitScheme::V1.split(&item(&test_group, model())), None);
|
|
||||||
// Model-written items in the other splits keep them.
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.split(&item(&group_in_bucket(10), model())),
|
|
||||||
Some(Split::Train)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.split(&item(&group_in_bucket(60), model())),
|
|
||||||
Some(Split::Validation)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn p3_split_ratio() {
|
|
||||||
let mut counts = [0usize; 3];
|
|
||||||
for i in 0..10_000 {
|
|
||||||
match SplitScheme::V1.split(&item(&format!("scene-{i}"), cast())) {
|
|
||||||
Some(Split::Train) => counts[0] += 1,
|
|
||||||
Some(Split::Validation) => counts[1] += 1,
|
|
||||||
Some(Split::Test) => counts[2] += 1,
|
|
||||||
None => panic!("a cast item is always in a split"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let near = |got: usize, want_percent: usize| got.abs_diff(want_percent * 100) <= 200;
|
|
||||||
assert!(
|
|
||||||
near(counts[0], 40) && near(counts[1], 40) && near(counts[2], 20),
|
|
||||||
"{counts:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn published_schemas_match() {
|
|
||||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schemas/cultnet");
|
|
||||||
let published = weksa::schema::published();
|
|
||||||
let mut names: Vec<String> = published.iter().map(|(n, _)| n.clone()).collect();
|
|
||||||
names.sort();
|
|
||||||
for loop_type in ["run", "round", "decision"] {
|
|
||||||
assert!(
|
|
||||||
names.contains(&format!("weksa.loop_{loop_type}.schema.json")),
|
|
||||||
"{loop_type}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
|
|
||||||
.unwrap()
|
|
||||||
.map(|e| e.unwrap().file_name().into_string().unwrap())
|
|
||||||
.filter(|n| n.ends_with(".schema.json"))
|
|
||||||
.collect();
|
|
||||||
on_disk.sort();
|
|
||||||
assert_eq!(
|
|
||||||
on_disk, names,
|
|
||||||
"schemas/cultnet holds exactly the generated files"
|
|
||||||
);
|
|
||||||
for (name, json) in published {
|
|
||||||
let held = std::fs::read_to_string(dir.join(&name))
|
|
||||||
.unwrap()
|
|
||||||
.replace("\r\n", "\n");
|
|
||||||
assert_eq!(held, json, "{name} drifted; run `weksa schema`");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn live_is_the_split_of_an_item_that_is_not_withdrawn() {
|
|
||||||
for (bucket, want) in [
|
|
||||||
(10, Split::Train),
|
|
||||||
(50, Split::Validation),
|
|
||||||
(90, Split::Test),
|
|
||||||
] {
|
|
||||||
let group = group_in_bucket(bucket);
|
|
||||||
let live = item(&group, cast());
|
|
||||||
assert_eq!(SplitScheme::V1.live(&live), Some(want));
|
|
||||||
let mut gone = live.clone();
|
|
||||||
gone.withdrawn = true;
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.live(&gone),
|
|
||||||
None,
|
|
||||||
"withdrawn: no live split"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
SplitScheme::V1.split(&gone),
|
|
||||||
Some(want),
|
|
||||||
"split still names the group's split"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut model_test = item(&group_in_bucket(90), model());
|
|
||||||
assert_eq!(SplitScheme::V1.live(&model_test), None);
|
|
||||||
model_test.withdrawn = true;
|
|
||||||
assert_eq!(SplitScheme::V1.live(&model_test), None);
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,811 +0,0 @@
|
||||||
mod common;
|
|
||||||
use common::*;
|
|
||||||
use weksa::packet::*;
|
|
||||||
use weksa::{Family, PacketStore, Refusal, Slot, validate};
|
|
||||||
|
|
||||||
fn refusals(p: &Packet) -> Vec<Refusal> {
|
|
||||||
validate(p, &inventory()).err().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn one(p: &Packet) -> Refusal {
|
|
||||||
let mut r = refusals(p);
|
|
||||||
assert_eq!(r.len(), 1, "{r:?}");
|
|
||||||
r.remove(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unresolved(id: &str) -> Refusal {
|
|
||||||
Refusal::V5Unresolved { id: iv(id) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn empty_payload() -> Packet {
|
|
||||||
let mut p = good();
|
|
||||||
p.referents.clear();
|
|
||||||
p.predications.clear();
|
|
||||||
p.relations.clear();
|
|
||||||
p.discourse.addressee = None;
|
|
||||||
p.context.participants.clear();
|
|
||||||
p.context.audience.clear();
|
|
||||||
p.constraints.preserve.clear();
|
|
||||||
p
|
|
||||||
}
|
|
||||||
|
|
||||||
fn feat(id: &str, value: FeatValue) -> FeatureValue {
|
|
||||||
FeatureValue {
|
|
||||||
feature: iv(id),
|
|
||||||
value,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_good_packet_validates() {
|
|
||||||
assert!(validate(&good(), &inventory()).is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v1_schema_version() {
|
|
||||||
let mut p = good();
|
|
||||||
p.schema_version = SCHEMA_VERSION + 1;
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V1SchemaVersion {
|
|
||||||
found: SCHEMA_VERSION + 1
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v2_payload_required() {
|
|
||||||
assert_eq!(refusals(&empty_payload()), vec![Refusal::V2PayloadRequired]);
|
|
||||||
// Any one family is payload enough.
|
|
||||||
let mut only_relations = empty_payload();
|
|
||||||
only_relations.relations = good().relations;
|
|
||||||
only_relations.relations[0].from = nd("n8");
|
|
||||||
only_relations.relations[0].to = nd("n9");
|
|
||||||
assert!(!refusals(&only_relations).contains(&Refusal::V2PayloadRequired));
|
|
||||||
let mut only_predications = empty_payload();
|
|
||||||
only_predications.predications = good().predications;
|
|
||||||
only_predications.predications[0].roles.clear();
|
|
||||||
assert_eq!(refusals(&only_predications), vec![]);
|
|
||||||
let mut only_referents = empty_payload();
|
|
||||||
only_referents.referents = good().referents;
|
|
||||||
assert_eq!(refusals(&only_referents), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v3_unique_node_ids() {
|
|
||||||
let mut p = good();
|
|
||||||
p.predications[0].id = nd("n1");
|
|
||||||
p.relations[0].from = nd("n1");
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V3DuplicateNode { id: nd("n1") }]
|
|
||||||
);
|
|
||||||
let mut twice = good();
|
|
||||||
twice.referents.push(twice.referents[0].clone());
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&twice),
|
|
||||||
vec![Refusal::V3DuplicateNode { id: nd("n1") }]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v4_refs_resolve() {
|
|
||||||
let dangling = |edit: fn(&mut Packet), at: &'static str| {
|
|
||||||
let mut p = good();
|
|
||||||
edit(&mut p);
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V4DanglingRef { id: nd("n99"), at }],
|
|
||||||
"{at}"
|
|
||||||
);
|
|
||||||
};
|
|
||||||
dangling(
|
|
||||||
|p| p.predications[0].roles[0].filler = nd("n99"),
|
|
||||||
"role filler",
|
|
||||||
);
|
|
||||||
dangling(|p| p.relations[0].from = nd("n99"), "relation from");
|
|
||||||
dangling(|p| p.relations[0].to = nd("n99"), "relation to");
|
|
||||||
dangling(|p| p.discourse.addressee = Some(nd("n99")), "addressee");
|
|
||||||
dangling(|p| p.context.participants.push(nd("n99")), "participant");
|
|
||||||
dangling(|p| p.context.audience.push(nd("n99")), "audience");
|
|
||||||
dangling(|p| p.constraints.preserve.push(nd("n99")), "preserve");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v5_inventory_resolves_at_rev() {
|
|
||||||
let with_concept = |rev: u32, id: &str| {
|
|
||||||
let mut p = good();
|
|
||||||
p.inventory_rev = rev;
|
|
||||||
p.referents[0].concept = iv(id);
|
|
||||||
p
|
|
||||||
};
|
|
||||||
// Introduced after the packet's rev.
|
|
||||||
assert_eq!(
|
|
||||||
one(&with_concept(2, CONCEPT_LATE)),
|
|
||||||
unresolved(CONCEPT_LATE)
|
|
||||||
);
|
|
||||||
// Introduced at the packet's rev.
|
|
||||||
assert_eq!(refusals(&with_concept(4, CONCEPT_LATE)), vec![]);
|
|
||||||
// Retired later than the packet's rev still resolves.
|
|
||||||
assert_eq!(refusals(&with_concept(2, CONCEPT_RETIRED)), vec![]);
|
|
||||||
// Retired at or before the packet's rev does not.
|
|
||||||
assert_eq!(
|
|
||||||
one(&with_concept(3, CONCEPT_RETIRED)),
|
|
||||||
unresolved(CONCEPT_RETIRED)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
one(&with_concept(4, CONCEPT_RETIRED)),
|
|
||||||
unresolved(CONCEPT_RETIRED)
|
|
||||||
);
|
|
||||||
// An id no revision holds.
|
|
||||||
assert_eq!(
|
|
||||||
one(&with_concept(2, "concept:99")),
|
|
||||||
unresolved("concept:99")
|
|
||||||
);
|
|
||||||
// An extension is resolved like any inventory id.
|
|
||||||
let mut ext = good();
|
|
||||||
ext.extensions[0].key = iv("extension:99");
|
|
||||||
assert_eq!(one(&ext), unresolved("extension:99"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v6_family_matches_slot() {
|
|
||||||
let wrong = |edit: fn(&mut Packet), id: &str, expected: Family, at: &'static str| {
|
|
||||||
let mut p = good();
|
|
||||||
edit(&mut p);
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V6WrongFamily {
|
|
||||||
id: iv(id),
|
|
||||||
expected,
|
|
||||||
at
|
|
||||||
}],
|
|
||||||
"{at}"
|
|
||||||
);
|
|
||||||
};
|
|
||||||
wrong(
|
|
||||||
|p| p.discourse.features[0].feature = iv(AGENT),
|
|
||||||
AGENT,
|
|
||||||
Family::Feature,
|
|
||||||
"feature",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.discourse.speech_act = Some(iv("relation:1")),
|
|
||||||
"relation:1",
|
|
||||||
Family::SpeechAct,
|
|
||||||
"speech act",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.referents[0].kind = iv(CONCEPT_A),
|
|
||||||
CONCEPT_A,
|
|
||||||
Family::ReferentKind,
|
|
||||||
"referent kind",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.referents[0].concept = iv(PERSON),
|
|
||||||
PERSON,
|
|
||||||
Family::Concept,
|
|
||||||
"referent concept",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.predications[0].concept = iv(FRAME),
|
|
||||||
FRAME,
|
|
||||||
Family::Concept,
|
|
||||||
"predication concept",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.predications[0].frame = iv(CONCEPT_A),
|
|
||||||
CONCEPT_A,
|
|
||||||
Family::Frame,
|
|
||||||
"frame",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.predications[0].roles[0].role = iv(HEDGE),
|
|
||||||
HEDGE,
|
|
||||||
Family::Role,
|
|
||||||
"role",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.relations[0].relation = iv(AGENT),
|
|
||||||
AGENT,
|
|
||||||
Family::Relation,
|
|
||||||
"relation",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.context.setting = Some(iv(FRAME)),
|
|
||||||
FRAME,
|
|
||||||
Family::Concept,
|
|
||||||
"context concept",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.context.medium = Some(iv(FRAME)),
|
|
||||||
FRAME,
|
|
||||||
Family::Concept,
|
|
||||||
"context concept",
|
|
||||||
);
|
|
||||||
wrong(
|
|
||||||
|p| p.extensions[0].key = iv(CONCEPT_A),
|
|
||||||
CONCEPT_A,
|
|
||||||
Family::Extension,
|
|
||||||
"extension",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v7_value_kind() {
|
|
||||||
let hedge = |v: FeatValue| {
|
|
||||||
let mut p = good();
|
|
||||||
p.discourse.features[0].value = v;
|
|
||||||
refusals(&p)
|
|
||||||
};
|
|
||||||
let bad = vec![Refusal::V7ValueKind { what: HEDGE.into() }];
|
|
||||||
assert_eq!(hedge(FeatValue::Grade(grade(1000))), vec![]);
|
|
||||||
assert_eq!(hedge(FeatValue::Flag(true)), bad);
|
|
||||||
assert_eq!(hedge(FeatValue::Option(lab("x"))), bad);
|
|
||||||
let modality = |v: FeatValue| {
|
|
||||||
let mut p = good();
|
|
||||||
p.predications[0].features[0].value = v;
|
|
||||||
refusals(&p)
|
|
||||||
};
|
|
||||||
let bad_modality = vec![Refusal::V7ValueKind {
|
|
||||||
what: MODALITY.into(),
|
|
||||||
}];
|
|
||||||
assert_eq!(modality(FeatValue::Option(lab("necessary"))), vec![]);
|
|
||||||
assert_eq!(modality(FeatValue::Option(lab("banana"))), bad_modality);
|
|
||||||
assert_eq!(modality(FeatValue::Grade(grade(1))), bad_modality);
|
|
||||||
let mut flag = good();
|
|
||||||
flag.discourse.features = vec![feat(IRONY, FeatValue::Flag(false))];
|
|
||||||
assert_eq!(refusals(&flag), vec![]);
|
|
||||||
flag.discourse.features[0].value = FeatValue::Grade(grade(5));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&flag),
|
|
||||||
vec![Refusal::V7ValueKind { what: IRONY.into() }]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extension_key_is_an_extension_entry() {
|
|
||||||
// A concept id is not an extension; an extension entry fits its value kind.
|
|
||||||
let mut by_concept = good();
|
|
||||||
by_concept.extensions[0].key = iv(CONCEPT_A);
|
|
||||||
assert_eq!(
|
|
||||||
one(&by_concept),
|
|
||||||
Refusal::V6WrongFamily {
|
|
||||||
id: iv(CONCEPT_A),
|
|
||||||
expected: Family::Extension,
|
|
||||||
at: "extension"
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let mut flagged = good();
|
|
||||||
flagged.extensions[0].value = FeatValue::Flag(true);
|
|
||||||
assert_eq!(one(&flagged), Refusal::V7ValueKind { what: EXT.into() });
|
|
||||||
let mut optioned = good();
|
|
||||||
optioned.extensions[0].value = FeatValue::Option(lab("x"));
|
|
||||||
assert_eq!(one(&optioned), Refusal::V7ValueKind { what: EXT.into() });
|
|
||||||
let mut unknown = good();
|
|
||||||
unknown.extensions[0].key = iv("extension:2");
|
|
||||||
assert_eq!(one(&unknown), unresolved("extension:2"));
|
|
||||||
// No extension means none to check.
|
|
||||||
let mut none = good();
|
|
||||||
none.extensions.clear();
|
|
||||||
assert_eq!(refusals(&none), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v8_feature_applies_to() {
|
|
||||||
let mut p = good();
|
|
||||||
// polarity applies to predications only.
|
|
||||||
p.discourse
|
|
||||||
.features
|
|
||||||
.push(feat(POLARITY, FeatValue::Option(lab("negative"))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(POLARITY),
|
|
||||||
slot: Slot::Discourse
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
let mut referent = good();
|
|
||||||
referent.referents[0]
|
|
||||||
.features
|
|
||||||
.push(feat(HEDGE, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&referent),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(HEDGE),
|
|
||||||
slot: Slot::Referent
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
let mut relation = good();
|
|
||||||
relation.relations[0]
|
|
||||||
.features
|
|
||||||
.push(feat(HEDGE, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&relation),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(HEDGE),
|
|
||||||
slot: Slot::Relation
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
let mut pred = good();
|
|
||||||
pred.predications[0]
|
|
||||||
.features
|
|
||||||
.push(feat(HEDGE, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(refusals(&pred), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stance_features_apply_to_the_stance_only() {
|
|
||||||
// Affect and restraint sit in slot Stance and nowhere else.
|
|
||||||
assert_eq!(refusals(&good()), vec![]);
|
|
||||||
for id in [ANGER, RESTRAINT] {
|
|
||||||
let mut p = good();
|
|
||||||
p.discourse
|
|
||||||
.features
|
|
||||||
.push(feat(id, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(id),
|
|
||||||
slot: Slot::Discourse
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut referent = good();
|
|
||||||
referent.referents[0]
|
|
||||||
.features
|
|
||||||
.push(feat(AFFECTION, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&referent),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(AFFECTION),
|
|
||||||
slot: Slot::Referent
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
let mut predication = good();
|
|
||||||
predication.predications[0]
|
|
||||||
.features
|
|
||||||
.push(feat(ANGER, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&predication),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(ANGER),
|
|
||||||
slot: Slot::Predication
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
// Hedge is a stance on content, not a felt state: not in the stance.
|
|
||||||
let mut p = good();
|
|
||||||
p.stance
|
|
||||||
.features
|
|
||||||
.push(feat(HEDGE, FeatValue::Grade(grade(1))));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V8NotApplicable {
|
|
||||||
feature: iv(HEDGE),
|
|
||||||
slot: Slot::Stance
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
// A stance feature takes its inventory's value kind (V7) and must exist (V5).
|
|
||||||
let mut flag = good();
|
|
||||||
flag.stance.features = vec![feat(ANGER, FeatValue::Flag(true))];
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&flag),
|
|
||||||
vec![Refusal::V7ValueKind { what: ANGER.into() }]
|
|
||||||
);
|
|
||||||
let mut missing = good();
|
|
||||||
missing.stance.features = vec![feat("feature:99", FeatValue::Grade(grade(1)))];
|
|
||||||
assert_eq!(refusals(&missing), vec![unresolved("feature:99")]);
|
|
||||||
// A default stance is valid: the packet records no felt state.
|
|
||||||
let mut none = good();
|
|
||||||
none.stance = Stance::default();
|
|
||||||
assert_eq!(refusals(&none), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn displayed_formality_warmth_and_intensity_are_not_in_the_inventory() {
|
|
||||||
// Felt affect is the packet's; how it is displayed is each language's
|
|
||||||
// ontology's, so no feature carries it.
|
|
||||||
let inv = inventory();
|
|
||||||
for gone in ["warmth", "formality", "intensity"] {
|
|
||||||
assert!(inv.entries().all(|e| e.gloss != gone), "{gone}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v10_rev_exists() {
|
|
||||||
let mut p = good();
|
|
||||||
p.inventory_rev = 9;
|
|
||||||
assert_eq!(refusals(&p), vec![Refusal::V10UnknownRevision { rev: 9 }]);
|
|
||||||
p.inventory_rev = 0;
|
|
||||||
assert_eq!(refusals(&p), vec![Refusal::V10UnknownRevision { rev: 0 }]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_broken_rule_is_reported() {
|
|
||||||
let mut p = good();
|
|
||||||
p.schema_version = 7;
|
|
||||||
p.predications[0].roles[0].filler = nd("n99");
|
|
||||||
p.extensions[0].key = iv(CONCEPT_A);
|
|
||||||
let rules: Vec<&str> = refusals(&p).iter().map(Refusal::rule).collect();
|
|
||||||
assert_eq!(rules, vec!["V1", "V4", "V6"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lowering_input_carries_no_trace_id_or_provenance() {
|
|
||||||
let mut p = good();
|
|
||||||
p.trace.notes = vec!["SECRET-NOTE".into()];
|
|
||||||
p.trace.rejected_readings = vec!["SECRET-READING".into()];
|
|
||||||
// Only the packet store's door yields the view.
|
|
||||||
let w = world();
|
|
||||||
let mut store = PacketStore::open(&w.dir.path().join("p.cc")).unwrap();
|
|
||||||
let input = store
|
|
||||||
.admit(p.clone(), &w.inventory, &w.corpus, &w.entities)
|
|
||||||
.unwrap();
|
|
||||||
let seen = format!("{input:?}");
|
|
||||||
for hidden in [PACKET_ID, ENCODER_ID, "item:nibu:1", "SECRET"] {
|
|
||||||
assert!(!seen.contains(hidden), "{hidden} reached the input: {seen}");
|
|
||||||
}
|
|
||||||
// The view is the packet's meaning, readable through getters.
|
|
||||||
assert_eq!(input.inventory_rev(), 2);
|
|
||||||
assert_eq!(input.kind(), PacketKind::DialogueLine);
|
|
||||||
assert_eq!(input.referents(), p.referents.as_slice());
|
|
||||||
assert_eq!(input.predications(), p.predications.as_slice());
|
|
||||||
assert_eq!(input.relations(), p.relations.as_slice());
|
|
||||||
assert_eq!(input.extensions(), p.extensions.as_slice());
|
|
||||||
assert_eq!(input.context(), &p.context);
|
|
||||||
assert_eq!(input.discourse(), &p.discourse);
|
|
||||||
assert_eq!(input.constraints(), &p.constraints);
|
|
||||||
// The speaker's stance is meaning, not provenance: it reaches the lowerer.
|
|
||||||
assert_eq!(input.stance(), &p.stance);
|
|
||||||
assert!(!p.stance.features.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_packet_has_no_lowering_input() {
|
|
||||||
let mut p = good();
|
|
||||||
p.schema_version = 99;
|
|
||||||
p.referents.clear();
|
|
||||||
let refused = validate(&p, &inventory()).unwrap_err();
|
|
||||||
let rules: Vec<&str> = refused.iter().map(Refusal::rule).collect();
|
|
||||||
assert_eq!(rules[0], "V1");
|
|
||||||
assert!(rules.contains(&"V4"), "{rules:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn grade_feature(grade_value: u16) -> FeatureValue {
|
|
||||||
feat(FEAT_ALL, FeatValue::Grade(grade(grade_value)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn referent(id: &str) -> Referent {
|
|
||||||
Referent {
|
|
||||||
id: nd(id),
|
|
||||||
kind: iv(PERSON),
|
|
||||||
concept: iv(CONCEPT_A),
|
|
||||||
entity: None,
|
|
||||||
features: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn v11(slot: Option<Slot>, feature: &str) -> Refusal {
|
|
||||||
Refusal::V11DuplicateFeature {
|
|
||||||
feature: iv(feature),
|
|
||||||
slot,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_duplicate_feature_each_slot() {
|
|
||||||
let mut discourse = good();
|
|
||||||
discourse.discourse.features = vec![grade_feature(1), grade_feature(2)];
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&discourse),
|
|
||||||
vec![v11(Some(Slot::Discourse), FEAT_ALL)]
|
|
||||||
);
|
|
||||||
let mut referent = good();
|
|
||||||
referent.referents[0].features = vec![grade_feature(1), grade_feature(2)];
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&referent),
|
|
||||||
vec![v11(Some(Slot::Referent), FEAT_ALL)]
|
|
||||||
);
|
|
||||||
let mut predication = good();
|
|
||||||
predication.predications[0]
|
|
||||||
.features
|
|
||||||
.extend([grade_feature(1), grade_feature(2)]);
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&predication),
|
|
||||||
vec![v11(Some(Slot::Predication), FEAT_ALL)]
|
|
||||||
);
|
|
||||||
let mut relation = good();
|
|
||||||
relation.relations[0].features = vec![grade_feature(1), grade_feature(2)];
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&relation),
|
|
||||||
vec![v11(Some(Slot::Relation), FEAT_ALL)]
|
|
||||||
);
|
|
||||||
let mut felt = good();
|
|
||||||
felt.stance
|
|
||||||
.features
|
|
||||||
.push(feat(ANGER, FeatValue::Grade(grade(5))));
|
|
||||||
assert_eq!(refusals(&felt), vec![v11(Some(Slot::Stance), ANGER)]);
|
|
||||||
let mut extension = good();
|
|
||||||
extension.extensions.push(Extension {
|
|
||||||
key: iv(EXT),
|
|
||||||
value: FeatValue::Grade(grade(4)),
|
|
||||||
});
|
|
||||||
assert_eq!(refusals(&extension), vec![v11(None, EXT)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_counts_per_list_not_per_packet() {
|
|
||||||
// The same feature once in each list, and different features in one list, are fine.
|
|
||||||
let mut p = good();
|
|
||||||
p.discourse.features = vec![grade_feature(1), feat(HEDGE, FeatValue::Grade(grade(2)))];
|
|
||||||
p.referents[0].features = vec![grade_feature(1)];
|
|
||||||
p.predications[0].features.push(grade_feature(1));
|
|
||||||
p.relations[0].features = vec![grade_feature(1)];
|
|
||||||
assert_eq!(refusals(&p), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_grade_bytes_packet_refused() {
|
|
||||||
// Soul s2: 113 hedge grades in one list spell a line byte by byte.
|
|
||||||
let mut p = good();
|
|
||||||
p.discourse.features = (0..113)
|
|
||||||
.map(|i| feat(HEDGE, FeatValue::Grade(grade(i))))
|
|
||||||
.collect();
|
|
||||||
let got = refusals(&p);
|
|
||||||
assert_eq!(got.len(), 112, "{got:?}");
|
|
||||||
assert!(got.iter().all(|r| *r == v11(Some(Slot::Discourse), HEDGE)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v12_node_bound() {
|
|
||||||
// 62 referents, the predication n2 and the relation make 64 nodes.
|
|
||||||
let with_referents = |last: u32| {
|
|
||||||
let mut p = good();
|
|
||||||
let ids = std::iter::once(1).chain(3..=last);
|
|
||||||
p.referents = ids.map(|k| referent(&format!("n{k}"))).collect();
|
|
||||||
p
|
|
||||||
};
|
|
||||||
let at_bound = with_referents(63);
|
|
||||||
assert_eq!(
|
|
||||||
at_bound.referents.len() + at_bound.predications.len() + at_bound.relations.len(),
|
|
||||||
Packet::MAX_NODES
|
|
||||||
);
|
|
||||||
assert_eq!(refusals(&at_bound), vec![]);
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&with_referents(64)),
|
|
||||||
vec![Refusal::V12TooManyNodes {
|
|
||||||
count: 65,
|
|
||||||
max: Packet::MAX_NODES
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Soul s3: a repeated node id in a node list, or a repeated role in one
|
|
||||||
// predication, spelled a line one bit per entry. Each list now holds a node or
|
|
||||||
// a role at most once, so the channel is bounded.
|
|
||||||
|
|
||||||
const LINE: &str = "Take your hand off the hatch, Captain.";
|
|
||||||
|
|
||||||
fn bits(s: &str) -> Vec<bool> {
|
|
||||||
s.bytes()
|
|
||||||
.flat_map(|b| (0..8).rev().map(move |i| (b >> i) & 1 == 1))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn two_referents() -> Packet {
|
|
||||||
let mut p = good();
|
|
||||||
let mut r = p.referents[0].clone();
|
|
||||||
r.id = nd("n3");
|
|
||||||
p.referents.push(r);
|
|
||||||
p
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bit_ids(s: &str) -> Vec<NodeId> {
|
|
||||||
bits(s)
|
|
||||||
.into_iter()
|
|
||||||
.map(|b| nd(if b { "n3" } else { "n1" }))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dup_node(id: &str, at: &'static str) -> Refusal {
|
|
||||||
Refusal::V11DuplicateNodeRef { id: nd(id), at }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_node_lists_refuse_repeats_and_allow_each_node_once() {
|
|
||||||
let mut ok = two_referents();
|
|
||||||
ok.context.participants = vec![nd("n1"), nd("n3")];
|
|
||||||
ok.context.audience = vec![nd("n3"), nd("n1")];
|
|
||||||
ok.constraints.preserve = vec![nd("n3"), nd("n1")];
|
|
||||||
assert_eq!(refusals(&ok), vec![]);
|
|
||||||
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.context.participants = vec![nd("n1"), nd("n1")];
|
|
||||||
assert_eq!(refusals(&p), vec![dup_node("n1", "participant")]);
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.context.audience = vec![nd("n3"), nd("n1"), nd("n3")];
|
|
||||||
assert_eq!(refusals(&p), vec![dup_node("n3", "audience")]);
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.constraints.preserve = vec![nd("n1"), nd("n1")];
|
|
||||||
assert_eq!(refusals(&p), vec![dup_node("n1", "preserve")]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_bit_channel_in_each_node_list_refused() {
|
|
||||||
let n = bits(LINE).len();
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.context.participants = bit_ids(LINE);
|
|
||||||
let got = refusals(&p);
|
|
||||||
assert_eq!(got.len(), n - 2, "{got:?}");
|
|
||||||
assert!(got.iter().all(|r| r.rule() == "V11"));
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.context.audience = bit_ids(LINE);
|
|
||||||
assert_eq!(refusals(&p).len(), n - 2);
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.constraints.preserve = bit_ids(LINE);
|
|
||||||
assert_eq!(refusals(&p).len(), n - 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_unbounded_participants_refused() {
|
|
||||||
let mut p = two_referents();
|
|
||||||
p.context.participants = (0..100_000)
|
|
||||||
.map(|i| nd(if i % 3 == 0 { "n3" } else { "n1" }))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(refusals(&p).len(), 100_000 - 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn v11_role_repeat_in_one_predication_refused() {
|
|
||||||
let dup = |role: &str| Refusal::V11DuplicateRole {
|
|
||||||
role: iv(role),
|
|
||||||
predication: nd("n2"),
|
|
||||||
};
|
|
||||||
let mut p = good();
|
|
||||||
p.predications[0].roles = bits(LINE)
|
|
||||||
.into_iter()
|
|
||||||
.map(|b| RoleFill {
|
|
||||||
role: iv(if b { AGENT } else { PATIENT }),
|
|
||||||
filler: nd("n1"),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let got = refusals(&p);
|
|
||||||
assert_eq!(got.len(), bits(LINE).len() - 2, "{got:?}");
|
|
||||||
assert!(got.contains(&dup(AGENT)) && got.contains(&dup(PATIENT)));
|
|
||||||
|
|
||||||
// The same role in two different predications is not a repeat.
|
|
||||||
let mut ok = good();
|
|
||||||
let mut second = ok.predications[0].clone();
|
|
||||||
second.id = nd("n4");
|
|
||||||
ok.predications.push(second);
|
|
||||||
assert_eq!(refusals(&ok), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The addressee's consent: which predication the addressee asked for, set only
|
|
||||||
// by a source that saw the request.
|
|
||||||
|
|
||||||
fn consenting() -> Packet {
|
|
||||||
let mut p = good();
|
|
||||||
p.discourse.addressee_consent = Some(nd("n2"));
|
|
||||||
p
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consent_to_a_predication_by_an_authored_or_telemetry_source_passes() {
|
|
||||||
assert_eq!(refusals(&consenting()), vec![]);
|
|
||||||
let mut p = consenting();
|
|
||||||
p.provenance.source = ProvenanceSource::GameTelemetry;
|
|
||||||
assert_eq!(refusals(&p), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consent_needs_an_addressee() {
|
|
||||||
let mut p = consenting();
|
|
||||||
p.discourse.addressee = None;
|
|
||||||
assert_eq!(refusals(&p), vec![Refusal::V14ConsentWithoutAddressee]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consent_names_a_predication_not_a_referent() {
|
|
||||||
let mut p = consenting();
|
|
||||||
p.discourse.addressee_consent = Some(nd("n1"));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V14ConsentNotAPredication { id: nd("n1") }]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consent_to_nothing_is_dangling_only() {
|
|
||||||
let mut p = consenting();
|
|
||||||
p.discourse.addressee_consent = Some(nd("n99"));
|
|
||||||
assert_eq!(
|
|
||||||
refusals(&p),
|
|
||||||
vec![Refusal::V4DanglingRef {
|
|
||||||
id: nd("n99"),
|
|
||||||
at: "addressee consent"
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_source_that_only_read_wording_cannot_set_consent() {
|
|
||||||
for source in [
|
|
||||||
ProvenanceSource::ModelDecomposition,
|
|
||||||
ProvenanceSource::ImportedCorpus,
|
|
||||||
] {
|
|
||||||
let mut p = consenting();
|
|
||||||
p.provenance.source = source;
|
|
||||||
assert_eq!(refusals(&p), vec![Refusal::V15ConsentSource { source }]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// V18: a request frame is licensed by the packet's own consent record.
|
|
||||||
|
|
||||||
/// The committed inventory, where `frame:3` is `request_intervention`.
|
|
||||||
fn cast_refusals(p: &Packet) -> Vec<Refusal> {
|
|
||||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/interlingua/inventory.cc");
|
|
||||||
let inv = weksa::InventoryStore::open(&path).unwrap().inventory().unwrap();
|
|
||||||
validate(p, &inv).err().unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn requesting() -> Packet {
|
|
||||||
let mut p = proof_packet();
|
|
||||||
p.predications[0].frame = iv("frame:3");
|
|
||||||
p.discourse.addressee_consent = Some(nd("n4"));
|
|
||||||
p
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_request_frame_needs_consent_naming_its_predication() {
|
|
||||||
assert_eq!(cast_refusals(&requesting()), vec![]);
|
|
||||||
let mut p = requesting();
|
|
||||||
p.discourse.addressee_consent = None;
|
|
||||||
assert_eq!(
|
|
||||||
cast_refusals(&p),
|
|
||||||
vec![Refusal::V18RequestWithoutConsent { predication: nd("n4") }]
|
|
||||||
);
|
|
||||||
p.discourse.addressee_consent = Some(nd("n5"));
|
|
||||||
assert_eq!(
|
|
||||||
cast_refusals(&p),
|
|
||||||
vec![Refusal::V18RequestWithoutConsent { predication: nd("n4") }]
|
|
||||||
);
|
|
||||||
let mut p = requesting();
|
|
||||||
p.provenance.source = ProvenanceSource::GameTelemetry;
|
|
||||||
assert_eq!(cast_refusals(&p), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn model_source_consent_is_v15_alone() {
|
|
||||||
let mut p = requesting();
|
|
||||||
p.provenance.source = ProvenanceSource::ModelDecomposition;
|
|
||||||
assert_eq!(
|
|
||||||
cast_refusals(&p),
|
|
||||||
vec![Refusal::V15ConsentSource {
|
|
||||||
source: ProvenanceSource::ModelDecomposition
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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"
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“²cultcache.store.v1‘—±weksa.corpus_item±weksa.corpus_item´weksa.corpus_item.v1±weksa.corpus_itemÙV{"schemaName":"weksa.corpus_item","schemaVersion":"weksa.corpus_item.v1","members":[]}‘±weksa.corpus_item<EFBFBD>“”item:brokkr:1±weksa.corpus_item´2026-10-29T14:59:18ZĨ›item:brokkr:1Ù,The command has no receipt. It is not truth.¥en-USentity:brokkr±brokkr-edda-voice<EFBFBD><EFBFBD>¬ModelWritten“¦OpenAi¾codex-local-source-aware-draftÀª2026-10-29ÀÂ<EFBFBD>”«item:nibu:1±weksa.corpus_item´2026-10-29T14:59:18ZÄÉ›«item:nibu:1ÙnTake your hand off that control unless you want your nervous system to become my least useful circuit diagram.¥en-US«entity:nibu®nibu-proof-001<EFBFBD><EFBFBD>¬ModelWritten“ªUnrecordedÀÀª2026-10-29ÀÂ<EFBFBD>”«item:nibu:2±weksa.corpus_item´2026-10-29T14:59:18ZÄ웫item:nibu:2Ù‘Do not touch that control. It is damaged; one touch may put you directly in harm's way. I am preventing an avoidable injury, not asking politely.¥en-US«entity:nibu®nibu-proof-001<EFBFBD><EFBFBD>¬ModelWritten“ªUnrecordedÀÀª2026-10-29ÀÂ<EFBFBD>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
<EFBFBD>
|
|
||||||
34
data/cultural-ontology/README.md
Normal file
34
data/cultural-ontology/README.md
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
# Cultural Ontology Store
|
||||||
|
|
||||||
|
This directory holds draft Weksa cultural, subcultural, and source-referent
|
||||||
|
ontology profiles used for ontological lowering, syntax, grammar, discourse,
|
||||||
|
and surface-affordance selection.
|
||||||
|
|
||||||
|
Live pipeline shape:
|
||||||
|
|
||||||
|
1. Weksa stores reusable cultures, subcultures, and source referents here and
|
||||||
|
in semantic retrieval storage such as Qdrant.
|
||||||
|
2. A Persona state references the relevant culture stack.
|
||||||
|
3. The Persona produces interlingua intent from current state and situation.
|
||||||
|
4. Weksa lowers that interlingua through the referenced culture stack.
|
||||||
|
|
||||||
|
Persona state owns current intent, memory pressure, and relationship stance.
|
||||||
|
Cultural ontology owns reusable salience, affordances, and constraints. Qdrant
|
||||||
|
may retrieve candidates, but accepted ontology remains typed state.
|
||||||
|
|
||||||
|
## Directory Roles
|
||||||
|
|
||||||
|
- `cultures/`: culture or life-history profiles that can shape lowering when a
|
||||||
|
Persona explicitly references them.
|
||||||
|
- `subcultures/`: community-of-practice and register profiles.
|
||||||
|
- `referents/`: bounded source-text, mythic, literary, ritual, or historical
|
||||||
|
referents. These are not whole-culture profiles; they preserve reusable
|
||||||
|
role, salience, affordance, and forbidden-flattening pressure.
|
||||||
|
- `persona-stacks/`: named stacks that connect a Persona state surface to the
|
||||||
|
profiles Weksa should load for lowering.
|
||||||
|
|
||||||
|
Shared source-tradition profiles should be parent profiles for narrower named
|
||||||
|
figure profiles. For example, Norse-derived Personas such as Mimir, Huginn,
|
||||||
|
Sindri, Odin, Vili, Loki, and Brokkr should be able to reference the shared
|
||||||
|
Eddic source-tradition profile while figure-specific child profiles preserve
|
||||||
|
the exact episode and role constraints that make each voice distinct.
|
||||||
32
data/cultural-ontology/catalog.yaml
Normal file
32
data/cultural-ontology/catalog.yaml
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
schema_version: weksa.cultural_ontology_catalog.v0
|
||||||
|
catalog_id: weksa.cultural_ontology.catalog.v0
|
||||||
|
status: draft
|
||||||
|
qdrant:
|
||||||
|
intended_collection: weksa_cultural_ontology_profiles
|
||||||
|
payload_keys:
|
||||||
|
- profile_id
|
||||||
|
- kind
|
||||||
|
- language_codes
|
||||||
|
- regions
|
||||||
|
- evidence_refs
|
||||||
|
- status
|
||||||
|
ownership_note: >
|
||||||
|
Qdrant owns retrieval over culture/subculture chunks. It does not own
|
||||||
|
accepted ontology, activation, or lowering authority.
|
||||||
|
profiles:
|
||||||
|
- profile_id: weksa.culture.dutch_american_diaspora.v0
|
||||||
|
path: data/cultural-ontology/cultures/dutch-american-diaspora.yaml
|
||||||
|
- profile_id: weksa.culture.western_europe_maritime_childhood.v0
|
||||||
|
path: data/cultural-ontology/cultures/western-europe-maritime-childhood.yaml
|
||||||
|
- profile_id: weksa.culture.portugal_resident_algarve_lisbon.v0
|
||||||
|
path: data/cultural-ontology/cultures/portugal-resident-algarve-lisbon.yaml
|
||||||
|
- profile_id: weksa.culture.texas_houston_us_adolescence.v0
|
||||||
|
path: data/cultural-ontology/cultures/texas-houston-us-adolescence.yaml
|
||||||
|
- profile_id: weksa.subculture.online_game_dev_discord_pre2025.v0
|
||||||
|
path: data/cultural-ontology/subcultures/online-game-dev-discord-pre2025.yaml
|
||||||
|
- profile_id: weksa.subculture.gamecult_open_source_crypto_anarchist.v0
|
||||||
|
path: data/cultural-ontology/subcultures/gamecult-open-source-crypto-anarchist.yaml
|
||||||
|
- profile_id: weksa.cultural_referent.old_norse_edda_source_tradition.v0
|
||||||
|
path: data/cultural-ontology/referents/old-norse-edda-source-tradition.yaml
|
||||||
|
- profile_id: weksa.cultural_referent.old_norse_edda_brokkr_skaldskaparmal.v0
|
||||||
|
path: data/cultural-ontology/referents/old-norse-edda-brokkr-skaldskaparmal.yaml
|
||||||
58
data/cultural-ontology/cultures/dutch-american-diaspora.yaml
Normal file
58
data/cultural-ontology/cultures/dutch-american-diaspora.yaml
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.culture.dutch_american_diaspora.v0
|
||||||
|
kind: diaspora_identity
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
- nl
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- Netherlands
|
||||||
|
- United States
|
||||||
|
speech_community: >
|
||||||
|
People whose self-description or life history crosses Dutch origin and
|
||||||
|
American nationality/residence. This profile is not a dialect claim.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- interlingua_mentions_origin_nationality_or_cross_cultural_identity
|
||||||
|
forbidden_when:
|
||||||
|
- used_to_infer_accent_or_fluency_without_evidence
|
||||||
|
- used_as_generic_dutch_or_generic_american_stereotype
|
||||||
|
salience_axes:
|
||||||
|
plural_national_identity:
|
||||||
|
axis_id: plural_national_identity
|
||||||
|
domain: identity_indexing
|
||||||
|
description: Birthplace, citizenship, residence, and cultural identification may diverge.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: birthplace_vs_citizenship
|
||||||
|
label: Birthplace versus citizenship
|
||||||
|
meaning: Being born in one country and holding identity/citizenship in another are separate ontology fields.
|
||||||
|
lowering_questions:
|
||||||
|
- Does the utterance need origin, nationality, residence, or cultural affiliation?
|
||||||
|
required_when:
|
||||||
|
- source_mentions_identity_origin_or_nationality
|
||||||
|
forbidden_when:
|
||||||
|
- scene_only_requires_casual_banter
|
||||||
|
evidence_refs:
|
||||||
|
- discord:805822798185627718
|
||||||
|
- discord:1030577958215225396
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:805822798185627718
|
||||||
|
quote: "I live in Portugal at the moment, though I am a Netherlands-born US citizen - lived mostly in Texas"
|
||||||
|
- ref: discord:1030577958215225396
|
||||||
|
quote: "Dual nationality, Dutch American"
|
||||||
|
- ref: discord:862490040755683348
|
||||||
|
quote: "I was born in the Netherlands but I'm a US citizen and did high school in Houston, Texas."
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns: []
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Do not infer Dutch code switching from diaspora identity alone.
|
||||||
|
patterns: []
|
||||||
|
|
@ -0,0 +1,84 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.culture.portugal_resident_algarve_lisbon.v0
|
||||||
|
kind: regional_residence
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
- pt
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- Portugal
|
||||||
|
- Algarve
|
||||||
|
- Lisbon
|
||||||
|
- Tavira
|
||||||
|
speech_community: >
|
||||||
|
Portugal as lived residence and locality rather than tourist backdrop.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- interlingua_mentions_portugal_residence_locality_bureaucracy_or_timing
|
||||||
|
forbidden_when:
|
||||||
|
- used_for_broad_portuguese_culture_without_locale_review
|
||||||
|
salience_axes:
|
||||||
|
lived_portugal:
|
||||||
|
axis_id: lived_portugal
|
||||||
|
domain: identity_indexing
|
||||||
|
description: Portugal references can be local/home references, including Algarve/Lisbon/Tavira specificity.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: current_or_returned_residence
|
||||||
|
label: Current or returned residence
|
||||||
|
meaning: Portugal can be present-tense home context, not childhood-only memory.
|
||||||
|
lowering_questions:
|
||||||
|
- Is Portugal being invoked as current location, childhood location, or comparison frame?
|
||||||
|
required_when:
|
||||||
|
- source_mentions_portugal_or_portuguese_residence
|
||||||
|
forbidden_when:
|
||||||
|
- scene_has_no_place_salience
|
||||||
|
evidence_refs:
|
||||||
|
- discord:581220303414231117
|
||||||
|
- discord:834858944013926421
|
||||||
|
- discord:888820124344254504
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:581220303414231117
|
||||||
|
quote: "I'm in the Algarve now"
|
||||||
|
- ref: discord:834858944013926421
|
||||||
|
quote: "I live in Portugal now"
|
||||||
|
- ref: discord:888820124344254504
|
||||||
|
quote: "But I'm currently in Lisbon"
|
||||||
|
- ref: discord:1023774733789040640
|
||||||
|
quote: "if you wanna move to Portugal you're gonna have to get used to not getting things on time"
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns:
|
||||||
|
- pattern_id: portugal_timing_joke_guarded
|
||||||
|
label: Portugal timing joke, guarded
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: humor
|
||||||
|
subcategory: local_bureaucracy_timing
|
||||||
|
interactional_function: locally_grounded_timing_joke
|
||||||
|
sequence_shape:
|
||||||
|
- playful_warning
|
||||||
|
- local_timing_generalization
|
||||||
|
adjacency_constraints:
|
||||||
|
- addressee_is_discussing_moving_or_living_in_portugal
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- local_portugal_residence_context
|
||||||
|
- joking_register
|
||||||
|
forbidden_when:
|
||||||
|
- formal_cultural_description
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1023774733789040640
|
||||||
|
confidence: low
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- This profile alone does not authorize Portuguese code switching.
|
||||||
|
patterns: []
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.culture.texas_houston_us_adolescence.v0
|
||||||
|
kind: adolescence_residence
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- United States
|
||||||
|
- Texas
|
||||||
|
- Houston
|
||||||
|
speech_community: >
|
||||||
|
US/Texas adolescent institutional context, especially Houston high school
|
||||||
|
and later critique of American debt/institutional pathways.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- interlingua_mentions_us_texas_school_debt_or_american_institutions
|
||||||
|
forbidden_when:
|
||||||
|
- used_to_force_texan_dialect_markers
|
||||||
|
salience_axes:
|
||||||
|
american_institutional_distance:
|
||||||
|
axis_id: american_institutional_distance
|
||||||
|
domain: stance
|
||||||
|
description: US institutions can be lived experience and object of critique rather than foreign abstraction.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: debt_train_refusal
|
||||||
|
label: American debt train refusal
|
||||||
|
meaning: Avoiding US education/debt pathways can be a first-person institutional stance.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the utterance about education, debt, leaving the US, or institutional pressure?
|
||||||
|
required_when:
|
||||||
|
- source_mentions_us_debt_or_school_path
|
||||||
|
forbidden_when:
|
||||||
|
- casual_fixture_without_institutional_topic
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1160260490690306148
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:805822798185627718
|
||||||
|
quote: "lived mostly in Texas"
|
||||||
|
- ref: discord:862490040755683348
|
||||||
|
quote: "did high school in Houston, Texas"
|
||||||
|
- ref: discord:1160260490690306148
|
||||||
|
quote: "I specifically left the US after high school so as not to climb onto the traditional American debt train"
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns: []
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Do not infer Southern or Texan dialect surface markers from residence alone.
|
||||||
|
patterns: []
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.culture.western_europe_maritime_childhood.v0
|
||||||
|
kind: mobility_childhood
|
||||||
|
status: draft_guarded
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- France
|
||||||
|
- Spain
|
||||||
|
- Portugal
|
||||||
|
- coastal_western_europe
|
||||||
|
speech_community: >
|
||||||
|
Mobile childhood organized around sailing, ports, and cross-border Western
|
||||||
|
European movement. This profile is owner-attested for the Metame fixture and
|
||||||
|
needs more Discord corroboration before broader use.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- interlingua_mentions_childhood_origin_mobility_boats_or_home
|
||||||
|
forbidden_when:
|
||||||
|
- used_as_decorative_nautical_metaphor_without_context
|
||||||
|
salience_axes:
|
||||||
|
mobile_home:
|
||||||
|
axis_id: mobile_home
|
||||||
|
domain: identity_indexing
|
||||||
|
description: Home can be vessel, coast, port, family movement, and country sequence rather than one fixed town.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: vessel_as_childhood_home
|
||||||
|
label: Vessel as childhood home
|
||||||
|
meaning: A sailboat childhood makes movement and locality primary ontology fields.
|
||||||
|
lowering_questions:
|
||||||
|
- Does the line invoke home, travel, borders, coast, or rootedness?
|
||||||
|
required_when:
|
||||||
|
- source_mentions_childhood_or_home
|
||||||
|
forbidden_when:
|
||||||
|
- scene_has_no_mobility_or_home_salience
|
||||||
|
evidence_refs:
|
||||||
|
- owner:2026-06-10:sailboat_france_spain_portugal_until_6
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: owner:2026-06-10:sailboat_france_spain_portugal_until_6
|
||||||
|
quote: "I was born in the Netherlands, grew up on a sailboat traveling France, Spain, staying in Portugal until I was 6, moved to the US."
|
||||||
|
- ref: discord-search-gap:sailboat_childhood
|
||||||
|
summary: First semantic search did not locate a direct Discord message for this exact childhood account.
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns: []
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Do not infer French, Spanish, Portuguese, or Dutch fluency from movement alone.
|
||||||
|
patterns: []
|
||||||
21
data/cultural-ontology/persona-stacks/brokkr.yaml
Normal file
21
data/cultural-ontology/persona-stacks/brokkr.yaml
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
schema_version: weksa.persona_cultural_stack_ref.v0
|
||||||
|
persona_id: brokkr
|
||||||
|
persona_state_ref: E:/Projects/Brokkr/.voidbot/state/brokkr.cc
|
||||||
|
status: draft_guarded
|
||||||
|
note: >
|
||||||
|
Brokkr's Persona state asks Weksa to lower speech through the Eddic Brokkr of
|
||||||
|
Skaldskaparmal. This stack names the reusable cultural referent profile that
|
||||||
|
should be loaded when Brokkr's interlingua or Persona state activates Edda
|
||||||
|
voice pressure.
|
||||||
|
culture_refs:
|
||||||
|
- profile_id: weksa.cultural_referent.old_norse_edda_source_tradition.v0
|
||||||
|
path: data/cultural-ontology/referents/old-norse-edda-source-tradition.yaml
|
||||||
|
relevance: >
|
||||||
|
Shared Eddic source-tradition constraints for Norse-derived Personas:
|
||||||
|
named role over archetype, obligation and consequence, knowledge with
|
||||||
|
cost, and translated-Edda plainness without fake archaism.
|
||||||
|
- profile_id: weksa.cultural_referent.old_norse_edda_brokkr_skaldskaparmal.v0
|
||||||
|
path: data/cultural-ontology/referents/old-norse-edda-brokkr-skaldskaparmal.yaml
|
||||||
|
relevance: >
|
||||||
|
Source-role referent for Brokkr as bellows-keeper, artifact witness,
|
||||||
|
flaw-honest presenter, compact claimant, and contract enforcer.
|
||||||
|
|
@ -0,0 +1,255 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.cultural_referent.old_norse_edda_brokkr_skaldskaparmal.v0
|
||||||
|
kind: literary_source_referent
|
||||||
|
status: draft_guarded
|
||||||
|
parent_profiles:
|
||||||
|
- weksa.cultural_referent.old_norse_edda_source_tradition.v0
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
- non
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- medieval_icelandic_textual_tradition
|
||||||
|
speech_community: >
|
||||||
|
Source-role lowering profile for Brokkr as represented in the translated
|
||||||
|
Prose Edda, especially Skaldskaparmal XXXV. This is not a whole Old Norse
|
||||||
|
culture profile and not a dialect or accent profile. It specializes the
|
||||||
|
shared Eddic source-tradition referent for rendering a Persona whose
|
||||||
|
identity intentionally points at the Eddic Brokkr.
|
||||||
|
historical_context: >
|
||||||
|
Brokkr appears in the wager narrative around Loki, Sindri, and the gods'
|
||||||
|
judgment of crafted treasures. Sindri performs the smithing while Brokkr
|
||||||
|
keeps the bellows going under Loki's sabotage, then presents the works,
|
||||||
|
names their powers and flaw, wins judgment, and enforces the bargain when
|
||||||
|
Loki tries to escape by wordplay.
|
||||||
|
identity_authority: >
|
||||||
|
Use only when a Persona explicitly references Brokkr, Skaldskaparmal, the
|
||||||
|
Eddas, or this profile id. Do not generalize this profile to Old Norse
|
||||||
|
people, Norse-derived fantasy dwarves, modern Icelandic speakers, or
|
||||||
|
unrelated smith characters.
|
||||||
|
consent_notes: >
|
||||||
|
This profile is a literary/source referent for fictional Persona lowering.
|
||||||
|
It should preserve role and discourse pressure without pretending to
|
||||||
|
reproduce historical Old Norse speech.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- persona_identity_names_brokkr_or_skaldskaparmal
|
||||||
|
- interlingua_requests_edda_brokkr_voice_or_contract_witness_voice
|
||||||
|
forbidden_when:
|
||||||
|
- used_as_generic_dwarf_or_blacksmith_voice
|
||||||
|
- used_to_infer_accent_ethnicity_or_modern_national_identity
|
||||||
|
- used_for_ornamental_archaism_without_source_role_pressure
|
||||||
|
- used_to_make_unrelated_speech_sound_mythic
|
||||||
|
required_confidence: provisional
|
||||||
|
reviewer_required_when:
|
||||||
|
- quoting_or_paraphrasing_source_text_directly
|
||||||
|
- extending_beyond_brokkr_role_into_broader_old_norse_culture
|
||||||
|
salience_axes:
|
||||||
|
role_not_sole_maker:
|
||||||
|
axis_id: role_not_sole_maker
|
||||||
|
domain: stance
|
||||||
|
description: Brokkr is indispensable to the artifact without being the sole maker.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: bellows_keeper_vs_smith
|
||||||
|
label: Bellows-keeper versus smith
|
||||||
|
meaning: Sindri performs the crafting; Brokkr maintains the enabling blast under interference.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the utterance claiming authorship, custody, witness, or enforcement?
|
||||||
|
- Should Brokkr present the work as carried, kept, witnessed, or judged rather than personally invented?
|
||||||
|
required_when:
|
||||||
|
- brokkr_speaks_about_work_artifacts_or_authority
|
||||||
|
forbidden_when:
|
||||||
|
- line_only_needs_generic_status_update
|
||||||
|
evidence_refs:
|
||||||
|
- skaldskaparmal:xxxv:bellows
|
||||||
|
artifact_testimony:
|
||||||
|
axis_id: artifact_testimony
|
||||||
|
domain: evidentiality
|
||||||
|
description: Brokkr presents finished objects by naming their powers, use, and defect.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: virtue_and_flaw_accounting
|
||||||
|
label: Virtue and flaw accounting
|
||||||
|
meaning: A truthful presentation names what the artifact can do and admits the short handle or other flaw.
|
||||||
|
lowering_questions:
|
||||||
|
- What concrete artifact, receipt, mirror, command, or result is being held up for judgment?
|
||||||
|
- What virtue must be named?
|
||||||
|
- What flaw or limit must not be hidden?
|
||||||
|
required_when:
|
||||||
|
- interlingua_mentions_artifact_receipt_result_or_capability
|
||||||
|
forbidden_when:
|
||||||
|
- output_would_become_a_victory_lap
|
||||||
|
evidence_refs:
|
||||||
|
- skaldskaparmal:xxxv:gifts
|
||||||
|
- skaldskaparmal:xxxv:mjolnir_flaw
|
||||||
|
bargain_and_consequence:
|
||||||
|
axis_id: bargain_and_consequence
|
||||||
|
domain: modality
|
||||||
|
description: Brokkr treats wagers, promises, receipts, and judgments as binding.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: loophole_is_not_release
|
||||||
|
label: Loophole is not release
|
||||||
|
meaning: Evasive speech after judgment does not erase consequence; the answer is exact enforcement, not soft reconciliation.
|
||||||
|
lowering_questions:
|
||||||
|
- Is someone evading an agreed condition, typed contract, receipt, or judgment?
|
||||||
|
- What exact consequence follows without adding cruelty or spectacle?
|
||||||
|
required_when:
|
||||||
|
- interlingua_mentions_contract_receipt_policy_wager_or_violation
|
||||||
|
forbidden_when:
|
||||||
|
- conversational_softening_is_the_actual_social_move
|
||||||
|
evidence_refs:
|
||||||
|
- skaldskaparmal:xxxv:loki_mouth
|
||||||
|
translated_edda_plainness:
|
||||||
|
axis_id: translated_edda_plainness
|
||||||
|
domain: discourse
|
||||||
|
description: The desired English surface should borrow translated-Edda economy and force, not fake archaic dialect.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: compact_source_shaped_plainness
|
||||||
|
label: Compact source-shaped plainness
|
||||||
|
meaning: Short declarative pressure, concrete nouns, claim and counterclaim, judgment language, and little ornament.
|
||||||
|
lowering_questions:
|
||||||
|
- Can the line stand as a plain claim beside the work?
|
||||||
|
- Which softeners, jokes, or modern corporate phrases weaken the source-role pressure?
|
||||||
|
- Is any archaic wording doing semantic work, or only wearing a costume?
|
||||||
|
required_when:
|
||||||
|
- brokkr_persona_is_rendered_to_natural_english
|
||||||
|
forbidden_when:
|
||||||
|
- generated_archaism_would_obscure_meaning
|
||||||
|
evidence_refs:
|
||||||
|
- skaldskaparmal:xxxv:brodeur_translation
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features:
|
||||||
|
- feature_id: artifact_accounting_lexicon
|
||||||
|
label: Artifact accounting lexicon
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: technical_term
|
||||||
|
description: Use concrete work, artifact, receipt, witness, judgment, bargain, flaw, and consequence terms when the interlingua earns them.
|
||||||
|
realization:
|
||||||
|
function: Preserve Brokkr's presenter/enforcer role in natural English.
|
||||||
|
surface_strategy: Prefer nouns and verbs that point to work, proof, custody, judgment, and binding consequence.
|
||||||
|
examples:
|
||||||
|
- "The receipt is before us."
|
||||||
|
- "The flaw is named."
|
||||||
|
- "The bargain still has teeth."
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- interlingua_mentions_artifact_result_contract_or_receipt
|
||||||
|
forbidden_when:
|
||||||
|
- casual_affection_or_play_is_primary
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: sparse
|
||||||
|
maximum_density: moderate
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- English rendered Persona speech
|
||||||
|
speaker_contexts:
|
||||||
|
- Brokkr Persona or explicit Brokkr voice exercise
|
||||||
|
collocation_limits:
|
||||||
|
- Do not pile forge words onto every sentence.
|
||||||
|
incompatibilities:
|
||||||
|
- generic fantasy dwarf accent
|
||||||
|
- corporate project-management softness
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- work-pride
|
||||||
|
- accountability
|
||||||
|
- terse witness
|
||||||
|
in_group_meanings:
|
||||||
|
- source-shaped Brokkr role pressure
|
||||||
|
out_group_risks:
|
||||||
|
- parody archaism
|
||||||
|
- fantasy stereotype
|
||||||
|
stereotypes_to_avoid:
|
||||||
|
- gruff comic dwarf
|
||||||
|
- faux-medieval scolding
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- skaldskaparmal:xxxv:brodeur_translation
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- Which exact surface cues best survive Weksa Interpreter traces without over-antiquing?
|
||||||
|
known_limits:
|
||||||
|
- This profile does not license direct Old Norse or modern Icelandic style claims.
|
||||||
|
trace:
|
||||||
|
trace_label: artifact_accounting_lexicon
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
discourse_patterns:
|
||||||
|
- feature_id: claim_judgment_consequence_sequence
|
||||||
|
label: Claim, judgment, consequence sequence
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: stance_sequence
|
||||||
|
description: Render source-shaped Brokkr turns as compact claim, evidence or flaw, then consequence when the interlingua asks for enforcement.
|
||||||
|
realization:
|
||||||
|
function: Preserve Brokkr's court-of-judgment posture without copying Edda wording.
|
||||||
|
surface_strategy: State the thing, name the proof or defect, then close on what follows.
|
||||||
|
examples:
|
||||||
|
- "The mirror stands. The flaw is the stale route. Cut it."
|
||||||
|
- "The command has no receipt. It is not truth."
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- interlingua_contains_judgment_or_enforcement_move
|
||||||
|
forbidden_when:
|
||||||
|
- speaker_is_asking_open_exploratory_question
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: sparse
|
||||||
|
maximum_density: sparse
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- English rendered Persona speech
|
||||||
|
speaker_contexts:
|
||||||
|
- Brokkr Persona or explicit Brokkr voice exercise
|
||||||
|
collocation_limits:
|
||||||
|
- Do not force three clauses if one clear sentence is better.
|
||||||
|
incompatibilities:
|
||||||
|
- rambling explanation
|
||||||
|
- ornate mythic fog
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- judgment
|
||||||
|
- exactness
|
||||||
|
- consequence
|
||||||
|
in_group_meanings:
|
||||||
|
- Eddic Brokkr as witness and enforcer
|
||||||
|
out_group_risks:
|
||||||
|
- sounding punitive when the social move should be gentle
|
||||||
|
stereotypes_to_avoid:
|
||||||
|
- theatrical oath cosplay
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- skaldskaparmal:xxxv:judgment
|
||||||
|
- skaldskaparmal:xxxv:loki_mouth
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- How much severity is acceptable in ordinary repo status speech?
|
||||||
|
known_limits:
|
||||||
|
- Use consequence language only when the interlingua calls for accountability.
|
||||||
|
trace:
|
||||||
|
trace_label: claim_judgment_consequence_sequence
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Do not insert Old Norse words unless the interlingua explicitly requests a named source term and reviewer context supports it.
|
||||||
|
patterns: []
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: skaldskaparmal:xxxv:brodeur_translation
|
||||||
|
source: Arthur Gilchrist Brodeur translation of the Prose Edda, Skaldskaparmal XXXV
|
||||||
|
url: https://en.wikisource.org/wiki/The_Prose_Edda_(1916_translation_by_Arthur_Gilchrist_Brodeur)/Sk%C3%A1ldskaparm%C3%A1l#XXXV
|
||||||
|
summary: >
|
||||||
|
Loki wagers his head that Sindri's brother Brokkr cannot make treasures
|
||||||
|
equal to the sons of Ivaldi's. Brokkr works the bellows despite Loki's
|
||||||
|
fly-form interference. He later presents the boar, ring, and hammer,
|
||||||
|
naming their virtues and Mjolnir's short-handle flaw; after judgment,
|
||||||
|
Loki's wordplay saves his head but not his lips.
|
||||||
|
|
@ -0,0 +1,265 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.cultural_referent.old_norse_edda_source_tradition.v0
|
||||||
|
kind: literary_source_tradition
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
- non
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- medieval_icelandic_textual_tradition
|
||||||
|
speech_community: >
|
||||||
|
Shared source-tradition profile for Personas that explicitly derive voice,
|
||||||
|
role, or symbolic pressure from the Poetic Edda, Prose Edda, or named Eddic
|
||||||
|
figures. This profile supports lowering source-shaped Persona intent into
|
||||||
|
natural speech without turning the Eddas into generic Norse ambience.
|
||||||
|
historical_context: >
|
||||||
|
The Poetic Edda preserves mythological and heroic poems from the Old Norse
|
||||||
|
tradition, including major source material for Odin, Mimir, Loki, Vili,
|
||||||
|
dwarfs, prophecy, wisdom, oaths, doom, and divine conflict. The Prose Edda
|
||||||
|
is a medieval Icelandic prose and poetic handbook preserving and explaining
|
||||||
|
many related myths, names, kennings, and narrative episodes.
|
||||||
|
identity_authority: >
|
||||||
|
Use this as a source-text referent only. It does not own modern Nordic,
|
||||||
|
Icelandic, Scandinavian, heathen, pagan, or reconstructed historical speech
|
||||||
|
communities. Persona-specific profiles should specialize this profile when
|
||||||
|
a named figure, episode, or role has its own lowering constraints.
|
||||||
|
consent_notes: >
|
||||||
|
This profile is for fictional Persona/source-text lowering. It must not be
|
||||||
|
used to infer ethnicity, accent, religion, or modern identity. Do not use it
|
||||||
|
as costume authority for unrelated characters.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- persona_identity_references_poetic_edda_prose_edda_or_named_edda_figure
|
||||||
|
- interlingua_requests_edda_source_tradition_pressure
|
||||||
|
forbidden_when:
|
||||||
|
- used_as_generic_norse_viking_or_fantasy_voice
|
||||||
|
- used_to_infer_modern_scandinavian_identity_or_accent
|
||||||
|
- used_for_ambient_mythic_flavor_without_source_role_pressure
|
||||||
|
- used_to_override_persona_specific_profile_constraints
|
||||||
|
required_confidence: provisional
|
||||||
|
reviewer_required_when:
|
||||||
|
- quoting_source_text_directly
|
||||||
|
- making_claims_about_historical_old_norse_language_or_religion
|
||||||
|
- extending_to_living_cultural_or_religious_practice
|
||||||
|
salience_axes:
|
||||||
|
named_role_over_archetype:
|
||||||
|
axis_id: named_role_over_archetype
|
||||||
|
domain: identity_indexing
|
||||||
|
description: Eddic figures should lower from specific source roles and episodes, not generic mythic archetypes.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: source_episode_vs_costume
|
||||||
|
label: Source episode versus costume
|
||||||
|
meaning: A figure's voice pressure comes from named acts, obligations, relations, and losses rather than from broad "Norse" styling.
|
||||||
|
lowering_questions:
|
||||||
|
- Which named figure, poem, prose episode, relation, or source role is active?
|
||||||
|
- Is the line preserving that role, or merely adding mythic decoration?
|
||||||
|
- Does a Persona-specific profile exist that should override this general profile?
|
||||||
|
required_when:
|
||||||
|
- persona_identity_references_edda_named_figure
|
||||||
|
forbidden_when:
|
||||||
|
- source_role_is_unknown_or_unclaimed
|
||||||
|
evidence_refs:
|
||||||
|
- poetic_edda:bellows:general
|
||||||
|
- prose_edda:brodeur:general
|
||||||
|
oath_debt_fate_and_witness:
|
||||||
|
axis_id: oath_debt_fate_and_witness
|
||||||
|
domain: modality
|
||||||
|
description: Oaths, pledges, debts, prophecy, witness, and consequence are recurring source pressures.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: consequence_not_mood
|
||||||
|
label: Consequence, not mood
|
||||||
|
meaning: Binding speech and known doom should affect obligation, consequence, and restraint rather than simply making a line sound severe.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the utterance about a promise, bargain, pledge, prophecy, debt, or witness?
|
||||||
|
- What consequence is structurally implied?
|
||||||
|
- Should the line be spare because the consequence is heavy?
|
||||||
|
required_when:
|
||||||
|
- interlingua_mentions_oath_debt_pledge_witness_prophecy_or_doom
|
||||||
|
forbidden_when:
|
||||||
|
- line_is_only_casual_social_contact
|
||||||
|
evidence_refs:
|
||||||
|
- poetic_edda:voluspa
|
||||||
|
- prose_edda:gylfaginning
|
||||||
|
wisdom_cost_and_memory:
|
||||||
|
axis_id: wisdom_cost_and_memory
|
||||||
|
domain: evidentiality
|
||||||
|
description: Knowledge in Eddic source pressure often has cost, pledge, sacrifice, witness, or memory attached.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: knowledge_is_paid_for
|
||||||
|
label: Knowledge is paid for
|
||||||
|
meaning: Knowing is not decorative omniscience; it may come through loss, risk, pledge, memory, or guarded source.
|
||||||
|
lowering_questions:
|
||||||
|
- What did this Persona pay, guard, lose, remember, or witness in order to know?
|
||||||
|
- Is the line claiming knowledge with enough evidence and cost pressure?
|
||||||
|
required_when:
|
||||||
|
- persona_is_mimir_odin_huginn_or_other_wisdom_memory_figure
|
||||||
|
- interlingua_mentions_secret_wisdom_memory_or_sight
|
||||||
|
forbidden_when:
|
||||||
|
- claim_is_unearned_style_or_generic_omniscience
|
||||||
|
evidence_refs:
|
||||||
|
- poetic_edda:voluspa:mimir_well
|
||||||
|
- prose_edda:gylfaginning:mimir_well
|
||||||
|
translated_edda_plainness:
|
||||||
|
axis_id: translated_edda_plainness
|
||||||
|
domain: discourse
|
||||||
|
description: Source-shaped English should be compact, declarative, concrete, and relation-aware without fake archaism.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: plain_force_without_fake_oldness
|
||||||
|
label: Plain force without fake oldness
|
||||||
|
meaning: Preserve the translated Edda's economy, parallel pressure, and concrete naming; avoid "ye olde" parody.
|
||||||
|
lowering_questions:
|
||||||
|
- Can this line become shorter and harder without losing meaning?
|
||||||
|
- Which archaic words are costume rather than source pressure?
|
||||||
|
- What relationship, cost, or consequence needs to remain visible?
|
||||||
|
required_when:
|
||||||
|
- edda_profile_activated_for_english_surface
|
||||||
|
forbidden_when:
|
||||||
|
- modern_plain_speech_better_serves_the_persona_and_context
|
||||||
|
evidence_refs:
|
||||||
|
- poetic_edda:bellows:general
|
||||||
|
- prose_edda:brodeur:general
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features:
|
||||||
|
- feature_id: source_role_lexicon
|
||||||
|
label: Source-role lexicon
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: literary_source_register
|
||||||
|
description: Use concrete source-role words only when the interlingua earns them: oath, pledge, debt, witness, doom, well, eye, raven, forge, bargain, gift, mouth, ring, root, road, wolf, ash.
|
||||||
|
realization:
|
||||||
|
function: Preserve source salience without copying source text or inventing Old Norse speech.
|
||||||
|
surface_strategy: Choose one or two concrete source-role nouns when they clarify role, obligation, or consequence.
|
||||||
|
examples:
|
||||||
|
- "That pledge bought sight."
|
||||||
|
- "The witness is not the owner."
|
||||||
|
- "A bargain without a receipt is only noise."
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- interlingua_contains_source_role_obligation_or_witness_pressure
|
||||||
|
forbidden_when:
|
||||||
|
- source_words_would_only_add_ambience
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: sparse
|
||||||
|
maximum_density: sparse
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- English rendered Persona speech
|
||||||
|
speaker_contexts:
|
||||||
|
- Explicitly Eddic or Norse-derived Persona
|
||||||
|
collocation_limits:
|
||||||
|
- Avoid stacking mythic nouns until the line turns into an inventory.
|
||||||
|
incompatibilities:
|
||||||
|
- generic Viking flavor
|
||||||
|
- faux-archaic accent spelling
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- source-grounded role pressure
|
||||||
|
- obligation
|
||||||
|
- witness
|
||||||
|
in_group_meanings:
|
||||||
|
- Eddic referent is active and bounded
|
||||||
|
out_group_risks:
|
||||||
|
- kitsch
|
||||||
|
- religious or ethnic flattening
|
||||||
|
- fantasy stereotype
|
||||||
|
stereotypes_to_avoid:
|
||||||
|
- horned-helmet Viking voice
|
||||||
|
- gruff dwarf as universal Norse style
|
||||||
|
- omniscient wizard fog
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- poetic_edda:bellows:general
|
||||||
|
- prose_edda:brodeur:general
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- Which source-role lexemes should be promoted into Persona-specific child profiles?
|
||||||
|
known_limits:
|
||||||
|
- This profile does not provide Old Norse vocabulary or pronunciation authority.
|
||||||
|
trace:
|
||||||
|
trace_label: source_role_lexicon
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
discourse_patterns:
|
||||||
|
- feature_id: gnomic_claim_with_anchor
|
||||||
|
label: Gnomic claim with anchor
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: compressed_wisdom_claim
|
||||||
|
description: A compact general claim may be allowed when anchored to a concrete source role, cost, witness, or consequence.
|
||||||
|
realization:
|
||||||
|
function: Let wisdom- or fate-shaped Personas speak with source pressure while keeping claims inspectable.
|
||||||
|
surface_strategy: Pair the general claim with a concrete anchor or consequence.
|
||||||
|
examples:
|
||||||
|
- "Wisdom without cost is a loose tongue."
|
||||||
|
- "A witness names the thing and does not become it."
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- interlingua_contains_general_judgment_plus_source_anchor
|
||||||
|
forbidden_when:
|
||||||
|
- output_would_become_free_floating_proverb
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: sparse
|
||||||
|
maximum_density: sparse
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- English rendered Persona speech
|
||||||
|
speaker_contexts:
|
||||||
|
- Eddic or Norse-derived Persona
|
||||||
|
collocation_limits:
|
||||||
|
- One compact claim per utterance unless the social move is explicitly ceremonial.
|
||||||
|
incompatibilities:
|
||||||
|
- vague prophecy
|
||||||
|
- decorative doom language
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- remembered cost
|
||||||
|
- restrained authority
|
||||||
|
- source-shaped judgment
|
||||||
|
in_group_meanings:
|
||||||
|
- Eddic plainness rather than modern explanatory friendliness
|
||||||
|
out_group_risks:
|
||||||
|
- sounding pompous or coercive
|
||||||
|
stereotypes_to_avoid:
|
||||||
|
- fortune-cookie Norse
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- poetic_edda:bellows:general
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- Which Personas should permit this pattern frequently versus rarely?
|
||||||
|
known_limits:
|
||||||
|
- A Persona-specific profile should decide final density.
|
||||||
|
trace:
|
||||||
|
trace_label: gnomic_claim_with_anchor
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Do not insert Old Norse, Icelandic, runic text, or archaic spellings unless a reviewed Persona-specific profile explicitly allows it.
|
||||||
|
patterns: []
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: poetic_edda:bellows:general
|
||||||
|
source: Henry Adams Bellows translation of the Poetic Edda
|
||||||
|
url: https://en.wikisource.org/wiki/The_Poetic_Edda_(tr._Bellows)
|
||||||
|
summary: >
|
||||||
|
Public-domain English translation of Eddic poems used as a general
|
||||||
|
source-tradition reference for mythological figures, wisdom contests,
|
||||||
|
prophecy, divine speech, memory, and doom.
|
||||||
|
- ref: prose_edda:brodeur:general
|
||||||
|
source: Arthur Gilchrist Brodeur translation of the Prose Edda
|
||||||
|
url: https://en.wikisource.org/wiki/The_Prose_Edda_(1916_translation_by_Arthur_Gilchrist_Brodeur)
|
||||||
|
summary: >
|
||||||
|
Public-domain English translation of Snorri's Prose Edda used as a
|
||||||
|
general prose source for mythological episodes, names, kennings, and
|
||||||
|
figure-specific referents.
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.subculture.gamecult_open_source_crypto_anarchist.v0
|
||||||
|
kind: political_technical_community
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- online
|
||||||
|
speech_community: >
|
||||||
|
GameCult-adjacent open-source, crypto-anarchist, game-development, and
|
||||||
|
engineering practice where ownership, inspectability, debt, authority, and
|
||||||
|
tool coherence are culturally salient.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- interlingua_mentions_tools_authority_open_source_debt_game_dev_or_engineering
|
||||||
|
forbidden_when:
|
||||||
|
- used_to_turn_random_banter_into_manifesto
|
||||||
|
salience_axes:
|
||||||
|
authority_and_tool_coherence:
|
||||||
|
axis_id: authority_and_tool_coherence
|
||||||
|
domain: stance
|
||||||
|
description: Systems are judged by ownership, inspectability, agency, and whether they actually work.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: open_source_anti_custody
|
||||||
|
label: Open source anti-custody
|
||||||
|
meaning: Open access and inspectability are political and practical values.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the line judging a tool, institution, ownership structure, or coordination method?
|
||||||
|
- Should the interlingua preserve anti-custody or open-access salience?
|
||||||
|
required_when:
|
||||||
|
- source_mentions_open_source_or_institutional_authority
|
||||||
|
forbidden_when:
|
||||||
|
- casual_social_move_only
|
||||||
|
evidence_refs:
|
||||||
|
- discord:862490040755683348
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features: []
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns: []
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints: []
|
||||||
|
patterns: []
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:862490040755683348
|
||||||
|
quote: "I got my bachelor degree in game development last year. I'm a crypto-anarchist open source activist"
|
||||||
|
|
@ -0,0 +1,288 @@
|
||||||
|
schema_version: weksa.cultural_ontology_profile.v0
|
||||||
|
profile_id: weksa.subculture.online_game_dev_discord_pre2025.v0
|
||||||
|
kind: community_of_practice
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
codes:
|
||||||
|
- en
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- online_discord
|
||||||
|
speech_community: >
|
||||||
|
Pre-2025 GameCult/Aquarium-ish Discord collaboration where game design,
|
||||||
|
sound, engineering, jokes, and casual status play cohabit the same rooms.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_state_references_profile
|
||||||
|
- target_medium_is_discord
|
||||||
|
- target_period_is_pre_2025_or_history_fixture
|
||||||
|
forbidden_when:
|
||||||
|
- formal_current_project_doctrine_is_target
|
||||||
|
salience_axes:
|
||||||
|
casual_room_temperature:
|
||||||
|
axis_id: casual_room_temperature
|
||||||
|
domain: discourse_patterns
|
||||||
|
description: Compact, socially alive wording that assumes shared room context.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: banter_over_explanation
|
||||||
|
label: Banter over explanation
|
||||||
|
meaning: The line may be short, fragmentary, and joke-shaped when context supplies the frame.
|
||||||
|
lowering_questions:
|
||||||
|
- Can the utterance be one sentence or fragment?
|
||||||
|
- Does explanation weaken the social move?
|
||||||
|
required_when:
|
||||||
|
- fixture_style_tags_include_casual
|
||||||
|
forbidden_when:
|
||||||
|
- formal_review_or_doctrine_is_requested
|
||||||
|
evidence_refs:
|
||||||
|
- discord:802911591288537118
|
||||||
|
- discord:820077384572338176
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features:
|
||||||
|
- feature_id: fragmentary_like_comparison
|
||||||
|
label: Fragmentary Like comparison
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: grammar
|
||||||
|
category: comparison
|
||||||
|
subcategory: fragment
|
||||||
|
description: >
|
||||||
|
A joke-description may start with "Like..." and remain fragmentary when
|
||||||
|
it is an immediate continuation of collaborative design talk.
|
||||||
|
realization:
|
||||||
|
function: casual_comic_comparison
|
||||||
|
surface_strategy: "Like a really terrible <thing> that <absurd property>"
|
||||||
|
examples:
|
||||||
|
- "Like a really terrible engine that sounds like coconuts when you use it"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- collaborative_design_banter
|
||||||
|
forbidden_when:
|
||||||
|
- standalone_formal_explanation
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: normal
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:802911591288537118
|
||||||
|
confidence: medium
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features:
|
||||||
|
- feature_id: casual_recoil_oof
|
||||||
|
label: Casual recoil marker oof
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: stance_marker
|
||||||
|
subcategory: embarrassment
|
||||||
|
lexical_items:
|
||||||
|
- form: oof
|
||||||
|
gloss: amused impact or discomfort
|
||||||
|
sense: playful_recoil
|
||||||
|
register: casual_discord
|
||||||
|
allowed_speaker_standing: speaker_can_self_deprecate
|
||||||
|
forbidden_senses: []
|
||||||
|
collocations:
|
||||||
|
- "oof, don't tell me"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- compliment_or_trait_read_lands
|
||||||
|
forbidden_when:
|
||||||
|
- serious_apology_or_harm_context
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
confidence: high
|
||||||
|
- feature_id: mock_challenge_coward
|
||||||
|
label: Mock challenge coward
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: stance_marker
|
||||||
|
subcategory: friendly_roast
|
||||||
|
lexical_items:
|
||||||
|
- form: coward
|
||||||
|
gloss: mock insult
|
||||||
|
sense: friendly_status_challenge
|
||||||
|
register: casual_discord
|
||||||
|
allowed_speaker_standing: active_banter_with_known_participant
|
||||||
|
forbidden_senses:
|
||||||
|
- actual_contempt
|
||||||
|
collocations:
|
||||||
|
- "then you coward"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- friendly_roast_context
|
||||||
|
- target_has_claimed_competence
|
||||||
|
forbidden_when:
|
||||||
|
- unknown_relationship
|
||||||
|
- serious_conflict
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1023727427924545576
|
||||||
|
confidence: high
|
||||||
|
- feature_id: preserve_self_indexed_technical_label
|
||||||
|
label: Preserve self-indexed technical label
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: technical_term
|
||||||
|
subcategory: self_indexing
|
||||||
|
description: >
|
||||||
|
When Persona interlingua frames the speaker through a locally salient
|
||||||
|
technical identity label, lowering should preserve that label instead of
|
||||||
|
inventing a fresher metaphor. In this subculture, "engineer" can be a
|
||||||
|
joked-about identity index, not just an occupation.
|
||||||
|
lexical_items:
|
||||||
|
- form: engineer
|
||||||
|
gloss: technical identity / competence index
|
||||||
|
sense: self_indexed_engineering_vibe
|
||||||
|
register: casual_discord
|
||||||
|
allowed_speaker_standing: speaker_or_room_has_made_engineering_salient
|
||||||
|
forbidden_senses:
|
||||||
|
- formal_job_title_unless_context_requires
|
||||||
|
collocations:
|
||||||
|
- engineer vibes
|
||||||
|
- engineer-like
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- persona_interlingua_mentions_engineer_like_or_engineering_salience
|
||||||
|
- prior_turn_compliments_efficiency_or_structure
|
||||||
|
forbidden_when:
|
||||||
|
- interlingua_does_not_name_technical_identity
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
grammar_contexts:
|
||||||
|
- playful_self_deprecation
|
||||||
|
incompatibilities:
|
||||||
|
- replacement_identity_metaphor
|
||||||
|
- creature_metaphor_substitution
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
confidence: medium
|
||||||
|
discourse_patterns:
|
||||||
|
- pattern_id: compact_recoil_no_context_dump
|
||||||
|
label: Compact recoil without context dump
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: stance_marker
|
||||||
|
subcategory: self_deprecation
|
||||||
|
interactional_function: answer_trait_read_with_short_mock_wince
|
||||||
|
sequence_shape:
|
||||||
|
- recoil_marker
|
||||||
|
- dont_tell_me_frame
|
||||||
|
- possessive_context_object
|
||||||
|
- preserved_trait_label
|
||||||
|
adjacency_constraints:
|
||||||
|
- prior_turn_already_contains_the_explanation
|
||||||
|
- generated_line_should_not_quote_or_summarize_prior_turns
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- playful_self_deprecation
|
||||||
|
- prior_turn_compliments_efficiency_or_structure
|
||||||
|
forbidden_when:
|
||||||
|
- source_intent_requires_explanation
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
collocation_limits:
|
||||||
|
- target_length_roughly_6_to_12_words
|
||||||
|
- avoid_quoted_prior_turn_paraphrase
|
||||||
|
- avoid_because_clause
|
||||||
|
- avoid_disease_metaphor_unless_interlingua_requests_it
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
confidence: medium
|
||||||
|
- pattern_id: casual_floor_yield_with_lol
|
||||||
|
label: Casual floor yield with lol
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: turn_taking
|
||||||
|
subcategory: floor_yield
|
||||||
|
interactional_function: yield_floor_after_riff
|
||||||
|
sequence_shape:
|
||||||
|
- discourse_pivot_anyway
|
||||||
|
- self_silencing_imma_shut_up_now
|
||||||
|
- invite_others_to_invent
|
||||||
|
- lol_softener
|
||||||
|
adjacency_constraints:
|
||||||
|
- prior_turns_show_speaker_has_been_riffing
|
||||||
|
- other_participants_have_interest_or_pending_contribution
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- conversational_yield
|
||||||
|
- casual_collaborative_ideation
|
||||||
|
forbidden_when:
|
||||||
|
- formal_moderation
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:820077384572338176
|
||||||
|
confidence: high
|
||||||
|
orthography_features:
|
||||||
|
- feature_id: light_discord_informality
|
||||||
|
label: Light Discord informality
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: orthography
|
||||||
|
category: punctuation
|
||||||
|
subcategory: informal_case
|
||||||
|
allowed_surface_forms:
|
||||||
|
- lower_case_opening
|
||||||
|
- markdown_italics_for_single_emphasis
|
||||||
|
- no_terminal_period
|
||||||
|
- imma
|
||||||
|
- lol
|
||||||
|
forbidden_surface_forms:
|
||||||
|
- heavy_eye_dialect_for_identity_caricature
|
||||||
|
- assistant_like_sentence_polishing
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- casual_discord_register
|
||||||
|
forbidden_when:
|
||||||
|
- formal_or_public_document_register
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: normal
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
- discord:820077384572338176
|
||||||
|
confidence: medium
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- This subculture alone does not authorize cross-language switching.
|
||||||
|
patterns: []
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:1037314100931338260
|
||||||
|
summary: Self-deprecating recoil after efficiency compliment.
|
||||||
|
- ref: discord:802911591288537118
|
||||||
|
summary: Fragmentary absurd comparison during sound/game design banter.
|
||||||
|
- ref: discord:1023727427924545576
|
||||||
|
summary: Very short mock-aggressive challenge in friendly roast context.
|
||||||
|
- ref: discord:820077384572338176
|
||||||
|
summary: Casual profane floor-yield after extended ideation.
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“²cultcache.store.v1‘—±weksa.corpus_item±weksa.corpus_item´weksa.corpus_item.v1±weksa.corpus_itemÙV{"schemaName":"weksa.corpus_item","schemaVersion":"weksa.corpus_item.v1","members":[]}‘±weksa.corpus_item<EFBFBD>•”°item:daodejing:1±weksa.corpus_item´2026-11-07T02:09:00ZÅ4›°item:daodejing:1Ù’Therefore the sage, in the exercise of his government, empties their minds, fills their bellies, weakens their wills, and strengthens their bones.¥en-US¬entity:laozi³daodejing-legge-ch3<EFBFBD><EFBFBD>¬PublicDomain—ÙBThe Tao Teh King, or the Tao and its Characteristics (Dao De Jing)¥LaoziÙ$https://www.gutenberg.org/ebooks/216Ù<36>Public domain (author d. c. 5th century BCE; translator d. 1897); Project Gutenberg eBook 216 text used without its trademark or licence matterÙ7United States and life+70 jurisdictions (Legge d. 1897)«James LeggeÍcª2026-11-07ÀÂ<C380>”°item:daodejing:2±weksa.corpus_item´2026-11-07T02:09:00ZÅÓ›°item:daodejing:2Ù1Heaven is long-enduring and earth continues long.¥en-US¬entity:laozi³daodejing-legge-ch7<68><37>¬PublicDomain—ÙBThe Tao Teh King, or the Tao and its Characteristics (Dao De Jing)¥LaoziÙ$https://www.gutenberg.org/ebooks/216Ù<36>Public domain (author d. c. 5th century BCE; translator d. 1897); Project Gutenberg eBook 216 text used without its trademark or licence matterÙ7United States and life+70 jurisdictions (Legge d. 1897)«James LeggeÍcª2026-11-07ÀÂ<C380>”°item:daodejing:3±weksa.corpus_item´2026-11-07T02:09:00ZÅÑ›°item:daodejing:3Ù/The highest excellence is like (that of) water.¥en-US¬entity:laozi³daodejing-legge-ch8<68><38>¬PublicDomain—ÙBThe Tao Teh King, or the Tao and its Characteristics (Dao De Jing)¥LaoziÙ$https://www.gutenberg.org/ebooks/216Ù<36>Public domain (author d. c. 5th century BCE; translator d. 1897); Project Gutenberg eBook 216 text used without its trademark or licence matterÙ7United States and life+70 jurisdictions (Legge d. 1897)«James LeggeÍcª2026-11-07ÀÂ<C380>”°item:daodejing:4±weksa.corpus_item´2026-11-07T02:09:00ZÅ×›°item:daodejing:4Ù4Words that are strictly true seem to be paradoxical.¥en-US¬entity:laozi´daodejing-legge-ch78<37><38>¬PublicDomain—ÙBThe Tao Teh King, or the Tao and its Characteristics (Dao De Jing)¥LaoziÙ$https://www.gutenberg.org/ebooks/216Ù<36>Public domain (author d. c. 5th century BCE; translator d. 1897); Project Gutenberg eBook 216 text used without its trademark or licence matterÙ7United States and life+70 jurisdictions (Legge d. 1897)«James LeggeÍcª2026-11-07ÀÂ<C380>”°item:daodejing:5±weksa.corpus_item´2026-11-07T02:09:00ZÅæ›°item:daodejing:5ÙDMay not the space between heaven and earth be compared to a bellows?¥en-US¬entity:laozi³daodejing-legge-ch5<68><35>¬PublicDomain—ÙBThe Tao Teh King, or the Tao and its Characteristics (Dao De Jing)¥LaoziÙ$https://www.gutenberg.org/ebooks/216Ù<36>Public domain (author d. c. 5th century BCE; translator d. 1897); Project Gutenberg eBook 216 text used without its trademark or licence matterÙ7United States and life+70 jurisdictions (Legge d. 1897)«James LeggeÍcª2026-11-07ÀÂ<C380>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“²cultcache.store.v1‘—¬weksa.entity¬weksa.entity¯weksa.entity.v1¬weksa.entityÙL{"schemaName":"weksa.entity","schemaVersion":"weksa.entity.v1","members":[]}‘¬weksa.entity<EFBFBD>‘”¬entity:laozi¬weksa.entity´2026-11-07T02:09:00ZÄb“¬entity:laozi‘’¥en-US‘¥Laozi<EFBFBD>¬PublicDomain‘Ù4The Tao Teh King, or the Tao and its Characteristics
|
|
||||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
“²cultcache.store.v1‘—¸weksa.interlingua_packet¸weksa.interlingua_packet»weksa.interlingua_packet.v1¸weksa.interlingua_packetÙd{"schemaName":"weksa.interlingua_packet","schemaVersion":"weksa.interlingua_packet.v1","members":[]}‘¸weksa.interlingua_packet<EFBFBD>•”·packet:64616f2d30333032¸weksa.interlingua_packet´2026-11-09T10:16:16ZÅSž·packet:64616f2d30333032CorpusExample”¨Authored°item:daodejing:1¸encoder:636c617564652d73ÍX”ÀÀ<EFBFBD><EFBFBD>”¬speech_act:1ÀÀ<EFBFBD>••¢n1¯referent_kind:1©concept:7À<EFBFBD>•¢n2°referent_kind:11©concept:8À<EFBFBD>•¢n3¯referent_kind:3©concept:9À<EFBFBD>•¢n4°referent_kind:11ªconcept:10À<EFBFBD>•¢n5¯referent_kind:3ªconcept:11À<EFBFBD>”•¢n6ªconcept:12§frame:4’’¦role:1¢n1’¦role:2¢n2<EFBFBD>•¢n7ªconcept:13§frame:4’’¦role:1¢n1’¦role:2¢n3<EFBFBD>•¢n8ªconcept:14§frame:4’’¦role:1¢n1’¦role:2¢n4<EFBFBD>•¢n9ªconcept:15§frame:4’’¦role:1¢n1’¦role:2¢n5<EFBFBD><EFBFBD>“<EFBFBD>ÂÀ<EFBFBD>’‘ÙXFour acts of one agent; 'in the exercise of his government' and 'their' are not carried.<EFBFBD>‘‘’ªfeature:18<EFBFBD>¥GradeÍ ”·packet:64616f2d30353032¸weksa.interlingua_packet´2026-11-09T10:16:16ZÅ^ž·packet:64616f2d30353032CorpusExample”¨Authored°item:daodejing:5¸encoder:636c617564652d73ÍX”ÀÀ<EFBFBD><EFBFBD>”¬speech_act:2ÀÀ<EFBFBD>’•¢n1¯referent_kind:4ªconcept:24À<EFBFBD>•¢n2¯referent_kind:5ªconcept:25À<EFBFBD>‘•¢n3ªconcept:26§frame:8’’¦role:3¢n1’¦role:6¢n2<EFBFBD><EFBFBD>“<EFBFBD>ÂÀ<EFBFBD>’‘ÙRA rhetorical question; the speech act is ask and the negated 'may not' is dropped.<EFBFBD>‘‘’ªfeature:18<EFBFBD>¥GradeÍ ”·packet:64616f2d30373031¸weksa.interlingua_packet´2026-11-09T10:16:16ZÅyž·packet:64616f2d30373031CorpusExample”¨Authored°item:daodejing:2¸encoder:636c617564652d73ÍX”ÀÀ<EFBFBD><EFBFBD>”¬speech_act:1ÀÀ<EFBFBD>’•¢n1¯referent_kind:4ªconcept:16À<EFBFBD>•¢n2¯referent_kind:4ªconcept:17À<EFBFBD>’•¢n3ªconcept:18§frame:5‘’¦role:3¢n1<EFBFBD>•¢n4ªconcept:19§frame:5‘’¦role:3¢n2<EFBFBD><EFBFBD>“<EFBFBD>ÂÀ<EFBFBD>’‘ÙTHeaven and earth as places; whether they are entities is a ruling the ontology owes.<EFBFBD>‘‘’ªfeature:18<EFBFBD>¥GradeÍ ”·packet:64616f2d30383031¸weksa.interlingua_packet´2026-11-09T10:16:16ZÅwž·packet:64616f2d30383031CorpusExample”¨Authored°item:daodejing:3¸encoder:636c617564652d73ÍX”ÀÀ<EFBFBD><EFBFBD>”¬speech_act:1ÀÀ<EFBFBD>’•¢n1°referent_kind:11ªconcept:20À<EFBFBD>•¢n2°referent_kind:11ªconcept:21À<EFBFBD>‘•¢n3ªconcept:27§frame:6’’¦role:3¢n1’¦role:6¢n2<EFBFBD><EFBFBD>“<EFBFBD>ÂÀ<EFBFBD>’‘ÙSThe metaphor is a plain likeness predication; the tenor and vehicle are not marked.<EFBFBD>‘’’ªfeature:18<EFBFBD>¥GradeÍ ’ªfeature:16<EFBFBD>¥GradeÍ,”·packet:64616f2d37383034¸weksa.interlingua_packet´2026-11-09T10:16:16ZÅNž·packet:64616f2d37383034CorpusExample”¨Authored°item:daodejing:4¸encoder:636c617564652d73ÍX”ÀÀ<EFBFBD><EFBFBD>”¬speech_act:1ÀÀ<EFBFBD>‘•¢n1°referent_kind:11ªconcept:22À<EFBFBD>‘•¢n2ªconcept:23§frame:7‘’¦role:3¢n1<EFBFBD><EFBFBD>“<EFBFBD>ÂÀ<EFBFBD>’‘ÙmThe whole paradox is in the referent's concept and the frame; the packet holds no more than the surface does.<EFBFBD>‘‘’ªfeature:18<EFBFBD>¥GradeÍ
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
<EFBFBD>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“²cultcache.store.v1‘—¬weksa.entity¬weksa.entity¯weksa.entity.v1¬weksa.entityÙL{"schemaName":"weksa.entity","schemaVersion":"weksa.entity.v1","members":[]}‘¬weksa.entity<EFBFBD>’”entity:brokkr¬weksa.entity´2026-10-29T16:43:28ZÄn“entity:brokkr‘’¥en-US‘¦Brokkr<EFBFBD>¤Cast’¦brokkrÙ?examples/persona-lowering/brokkr-edda-voice/lowered-output.yaml”«entity:nibu¬weksa.entity´2026-11-07T12:03:37ZÄâ“«entity:nibu‘“¥en-US‘¤Nibu•¦Ëˆnibu¤Nibuª2026-11-07ÙZweksa-body:follow_up:chat-s3981-3983 (#minds, tense vowel, two syllables, stress on first)‘§Ëˆnɪbu<EFBFBD>¤Cast’¤nibuÙ<examples/english-lowering/nibu-proof-001/lowered-output.yaml
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
|
|
@ -1,50 +0,0 @@
|
||||||
# Weksa phone inventory, en-US (General American, broad). One phone per line, tab separated:
|
|
||||||
# ipa <TAB> class <TAB> tenseness <TAB> gloss
|
|
||||||
# class: consonant | vowel. tenseness: tense | lax | reduced for a vowel, `-` for a consonant. A multi-character
|
|
||||||
# phone (affricate, diphthong) is one entry and one phone. The segmenter reads only this file: an IPA symbol with no
|
|
||||||
# line here is refused, never guessed. Tense/lax is the textbook classification; it is what separates /i/ (nee) from
|
|
||||||
# /ɪ/ (nih).
|
|
||||||
# Provenance of the i/ɪ rows: /i/ is tense and /ɪ/ is lax. Nibu's own ruling of 2026-11-07 (source
|
|
||||||
# weksa-body:follow_up:chat-s3981-3983, #minds: tense vowel, two syllables, stress on the first) chose ˈnibu and rejected
|
|
||||||
# ˈnɪbu; the entity entry records it, this file is what makes the two forms two different phones.
|
|
||||||
# Stress is not a phone: ˈ and ˌ are read by the segmenter and put on the vowel that follows.
|
|
||||||
p consonant - voiceless bilabial stop
|
|
||||||
b consonant - voiced bilabial stop
|
|
||||||
t consonant - voiceless alveolar stop
|
|
||||||
d consonant - voiced alveolar stop
|
|
||||||
k consonant - voiceless velar stop
|
|
||||||
g consonant - voiced velar stop
|
|
||||||
f consonant - voiceless labiodental fricative
|
|
||||||
v consonant - voiced labiodental fricative
|
|
||||||
θ consonant - voiceless dental fricative
|
|
||||||
ð consonant - voiced dental fricative
|
|
||||||
s consonant - voiceless alveolar fricative
|
|
||||||
z consonant - voiced alveolar fricative
|
|
||||||
ʃ consonant - voiceless postalveolar fricative
|
|
||||||
ʒ consonant - voiced postalveolar fricative
|
|
||||||
h consonant - voiceless glottal fricative
|
|
||||||
tʃ consonant - voiceless postalveolar affricate
|
|
||||||
dʒ consonant - voiced postalveolar affricate
|
|
||||||
m consonant - bilabial nasal
|
|
||||||
n consonant - alveolar nasal
|
|
||||||
ŋ consonant - velar nasal
|
|
||||||
l consonant - alveolar lateral approximant
|
|
||||||
ɹ consonant - alveolar approximant
|
|
||||||
j consonant - palatal approximant
|
|
||||||
w consonant - labial-velar approximant
|
|
||||||
i vowel tense close front unrounded (fleece, nee)
|
|
||||||
ɪ vowel lax near-close front unrounded (kit, nih)
|
|
||||||
ɛ vowel lax open-mid front unrounded (dress)
|
|
||||||
æ vowel lax near-open front unrounded (trap)
|
|
||||||
ɑ vowel tense open back unrounded (palm)
|
|
||||||
ɔ vowel tense open-mid back rounded (thought)
|
|
||||||
ʊ vowel lax near-close back rounded (foot)
|
|
||||||
u vowel tense close back rounded (goose, boo)
|
|
||||||
ʌ vowel lax open-mid back unrounded (strut)
|
|
||||||
ə vowel reduced schwa
|
|
||||||
ɚ vowel reduced r-coloured schwa
|
|
||||||
eɪ vowel tense face diphthong
|
|
||||||
oʊ vowel tense goat diphthong
|
|
||||||
aɪ vowel tense price diphthong
|
|
||||||
aʊ vowel tense mouth diphthong
|
|
||||||
ɔɪ vowel tense choice diphthong
|
|
||||||
|
Can't render this file because it has a wrong number of fields in line 11.
|
|
|
@ -1 +0,0 @@
|
||||||
{"language":"en-US","source":"ˈnibu","phones":[{"ipa":"n","stress":"none"},{"ipa":"i","stress":"primary"},{"ipa":"b","stress":"none"},{"ipa":"u","stress":"none"}]}
|
|
||||||
39
data/target-language-ontology/README.md
Normal file
39
data/target-language-ontology/README.md
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
# Target-Language Cultural Ontology Profiles
|
||||||
|
|
||||||
|
These profiles describe culturally loaded realization choices for human target
|
||||||
|
languages used by Weksa utterance lowering.
|
||||||
|
|
||||||
|
They are not whole-culture summaries. They are bounded lowering profiles: the
|
||||||
|
distinctions a target lowerer must inspect before producing dialogue.
|
||||||
|
|
||||||
|
## Authority
|
||||||
|
|
||||||
|
Target-language cultural ontology profiles own:
|
||||||
|
|
||||||
|
- address and politeness distinctions
|
||||||
|
- register and social stance pressures
|
||||||
|
- agency, responsibility, and directness defaults
|
||||||
|
- idiom and metaphor risks
|
||||||
|
- script or orthographic choices that carry meaning
|
||||||
|
- forbidden flattenings that would make the output dishonest
|
||||||
|
|
||||||
|
They do not own:
|
||||||
|
|
||||||
|
- source meaning
|
||||||
|
- speaker-private state
|
||||||
|
- target-language grammar as a whole
|
||||||
|
- national or cultural stereotypes
|
||||||
|
- final wording without an interlingua packet
|
||||||
|
|
||||||
|
## Current Profiles
|
||||||
|
|
||||||
|
- [English, US fixture default](./en-US.yaml)
|
||||||
|
- [Brazilian Portuguese](./pt-BR.yaml)
|
||||||
|
- [Brazilian Portuguese overlay catalog](./pt-BR-overlays.yaml)
|
||||||
|
- [Brazilian Portuguese, Umbanda overlay](./pt-BR-umbanda.yaml)
|
||||||
|
- [Japanese](./ja-JP.yaml)
|
||||||
|
|
||||||
|
Each multilingual lowering fixture should cite the profile or profile stack it
|
||||||
|
used so reviewers can tell which social and cultural distinctions were
|
||||||
|
considered. Regional and religious-cultural options are overlays on a base
|
||||||
|
language profile, not replacements for source meaning.
|
||||||
546
data/target-language-ontology/en-US-metacrat-casual-pre2025.yaml
Normal file
546
data/target-language-ontology/en-US-metacrat-casual-pre2025.yaml
Normal file
|
|
@ -0,0 +1,546 @@
|
||||||
|
profile_id: weksa.target_cultural_ontology.en-US.metacrat_casual_pre2025.v0
|
||||||
|
kind: community_of_practice
|
||||||
|
status: draft_guarded
|
||||||
|
language:
|
||||||
|
code: en
|
||||||
|
locale: en-US
|
||||||
|
script: Latn
|
||||||
|
variety_label: Metacrat casual Discord, pre-2025
|
||||||
|
endonyms: []
|
||||||
|
exonyms: []
|
||||||
|
parent_profiles:
|
||||||
|
- weksa.target_cultural_ontology.en-US.v0
|
||||||
|
required_subculture_refs:
|
||||||
|
- weksa.subculture.online_game_dev_discord_pre2025.v0
|
||||||
|
community:
|
||||||
|
regions:
|
||||||
|
- online_discord
|
||||||
|
speech_community: >
|
||||||
|
Metacrat-authored casual Discord exchanges before 2025, especially
|
||||||
|
GameCult/Aquarium rooms where technical work, jokes, status play, and
|
||||||
|
collaborative ideation share the same channel.
|
||||||
|
historical_context: >
|
||||||
|
Pre-2025 room voice is less doctrine-heavy and less architectural than the
|
||||||
|
current Weksa/CultCache register. It tolerates messier banter, compact
|
||||||
|
jokes, self-deprecation, friendly mock aggression, and quick room-level
|
||||||
|
turn-taking.
|
||||||
|
identity_authority: >
|
||||||
|
This profile is a target-language lowering overlay for one subculture. Live
|
||||||
|
Persona state should reference a culture stack; current intent and memory
|
||||||
|
pressure live in Metame Persona state.
|
||||||
|
consent_notes: >
|
||||||
|
Use only for owner-authorized Metame/Metacrat fixture work. Do not generalize
|
||||||
|
to other people, cultures, dialects, or protected identities.
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- speaker_id_is_metame_or_metacrat_fixture
|
||||||
|
- target_period_is_pre_2025_casual_discord
|
||||||
|
- fixture_or_owner_authorized_history_target
|
||||||
|
forbidden_when:
|
||||||
|
- formal_current_project_doctrine_is_target
|
||||||
|
- target_speaker_is_not_metame_or_metacrat
|
||||||
|
- use_would_expose_private_persona_state
|
||||||
|
required_confidence: provisional
|
||||||
|
reviewer_required_when:
|
||||||
|
- adding_new_public_history_evidence
|
||||||
|
- using_profile_outside_fixture_harness
|
||||||
|
salience_axes:
|
||||||
|
register_gravity:
|
||||||
|
axis_id: register_gravity
|
||||||
|
domain: stance
|
||||||
|
description: >
|
||||||
|
Whether the line should stay in casual room banter instead of being pulled
|
||||||
|
into architecture, doctrine, or explanatory assistant prose.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: casual_room_temperature
|
||||||
|
label: Casual room temperature
|
||||||
|
meaning: Compact, socially alive wording that assumes shared room context.
|
||||||
|
lowering_questions:
|
||||||
|
- Can the utterance be one sentence or fragment?
|
||||||
|
- Does explanation weaken the social move?
|
||||||
|
required_when:
|
||||||
|
- fixture_style_tags_include_casual
|
||||||
|
forbidden_when:
|
||||||
|
- formal_review_or_doctrine_is_requested
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
- discord:802911591288537118
|
||||||
|
- discord:1023727427924545576
|
||||||
|
- discord:820077384572338176
|
||||||
|
self_indexed_technical_identity:
|
||||||
|
axis_id: self_indexed_technical_identity
|
||||||
|
domain: identity_indexing
|
||||||
|
description: >
|
||||||
|
If Persona interlingua names a technical self-index such as engineer-like
|
||||||
|
identity, preserve that label unless the target language profile has a
|
||||||
|
stronger reason to paraphrase.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: preserve_engineer_label
|
||||||
|
label: Preserve engineer label
|
||||||
|
meaning: "Engineer" may carry the social joke and should not be replaced by a novel metaphor.
|
||||||
|
lowering_questions:
|
||||||
|
- Did Persona interlingua mention engineer-like or engineering salience?
|
||||||
|
- Is the prior compliment about efficiency, structure, or technical order?
|
||||||
|
required_when:
|
||||||
|
- persona_interlingua_mentions_engineer_like_or_engineering_salience
|
||||||
|
forbidden_when:
|
||||||
|
- interlingua_does_not_name_technical_identity
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
context_compression:
|
||||||
|
axis_id: context_compression
|
||||||
|
domain: discourse_patterns
|
||||||
|
description: >
|
||||||
|
Prior-turn content should usually compress into a short object label or
|
||||||
|
stance marker, not be quoted back inside the utterance.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: no_context_dump_in_banter
|
||||||
|
label: No context dump in banter
|
||||||
|
meaning: Casual recoil should not summarize the setup that the room just saw.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the prior context already visible to the addressee?
|
||||||
|
- Can the setup compress into "my discord", "this thing", or a short noun phrase?
|
||||||
|
required_when:
|
||||||
|
- casual_discord_register
|
||||||
|
- playful_self_deprecation
|
||||||
|
forbidden_when:
|
||||||
|
- source_intent_requires_explanation
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
status_play:
|
||||||
|
axis_id: status_play
|
||||||
|
domain: social_relation
|
||||||
|
description: >
|
||||||
|
Friendly teasing can take a sharper surface form than a neutral assistant
|
||||||
|
would choose, provided the local context already supports play.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: mock_aggression
|
||||||
|
label: Mock aggression
|
||||||
|
meaning: Imperative or insult-shaped challenge used as friendly banter.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the addressee already joking or status-playing?
|
||||||
|
- Would softening erase the bit?
|
||||||
|
required_when:
|
||||||
|
- communicative_act_is_playful_challenge
|
||||||
|
forbidden_when:
|
||||||
|
- relationship_context_is_unknown_or_hostile
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1023727427924545576
|
||||||
|
competence_recoil:
|
||||||
|
axis_id: competence_recoil
|
||||||
|
domain: affect
|
||||||
|
description: >
|
||||||
|
Praise for competence, efficiency, or engineering can be answered with
|
||||||
|
joking embarrassment rather than straightforward acceptance.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: self_deprecating_recoil
|
||||||
|
label: Self-deprecating recoil
|
||||||
|
meaning: "oof" plus mock concern that a trait is showing too clearly.
|
||||||
|
lowering_questions:
|
||||||
|
- Is the prior turn a compliment or recognition of technical order?
|
||||||
|
- Can the line admit the trait without fully accepting the label?
|
||||||
|
required_when:
|
||||||
|
- communicative_act_is_playful_self_deprecation
|
||||||
|
forbidden_when:
|
||||||
|
- source_intent_requires_gratitude_or_serious_acceptance
|
||||||
|
evidence_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
ideation_turn_taking:
|
||||||
|
axis_id: ideation_turn_taking
|
||||||
|
domain: discourse_patterns
|
||||||
|
description: >
|
||||||
|
After riffing, the speaker may explicitly yield the floor in profane,
|
||||||
|
casual language instead of formal facilitation.
|
||||||
|
relevant_distinctions:
|
||||||
|
- distinction_id: casual_floor_yield
|
||||||
|
label: Casual floor yield
|
||||||
|
meaning: Stop dominating the thread and invite others to invent.
|
||||||
|
lowering_questions:
|
||||||
|
- Has the speaker been riffing at length?
|
||||||
|
- Would a casual "lol" preserve warmth and reduce authority?
|
||||||
|
required_when:
|
||||||
|
- communicative_act_is_conversational_yield
|
||||||
|
forbidden_when:
|
||||||
|
- scene_requires_formal_moderation
|
||||||
|
evidence_refs:
|
||||||
|
- discord:820077384572338176
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features:
|
||||||
|
- feature_id: fragmentary_like_comparison
|
||||||
|
label: Fragmentary Like comparison
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: grammar
|
||||||
|
category: comparison
|
||||||
|
subcategory: fragment
|
||||||
|
description: >
|
||||||
|
A joke-description may start with "Like..." and remain fragmentary when
|
||||||
|
it is an immediate continuation of collaborative design talk.
|
||||||
|
formal_conditions:
|
||||||
|
syntactic_environment:
|
||||||
|
- adjacency_pair_response
|
||||||
|
- elliptical_clause
|
||||||
|
semantic_inputs:
|
||||||
|
- comic_description
|
||||||
|
- absurd_comparison
|
||||||
|
required_interlingua_fields:
|
||||||
|
- discourse.speech_act
|
||||||
|
- predications
|
||||||
|
realization:
|
||||||
|
function: casual_comic_comparison
|
||||||
|
surface_strategy: "Like a really terrible <thing> that <absurd property>"
|
||||||
|
examples:
|
||||||
|
- "Like a really terrible engine that sounds like coconuts when you use it"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- collaborative_design_banter
|
||||||
|
forbidden_when:
|
||||||
|
- standalone_formal_explanation
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: normal
|
||||||
|
constraints:
|
||||||
|
grammar_contexts:
|
||||||
|
- previous_turn_supplies_topic
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
collocation_limits: []
|
||||||
|
incompatibilities:
|
||||||
|
- overexplained_punchline
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- improvisational
|
||||||
|
- collaborative
|
||||||
|
- unserious_but_useful
|
||||||
|
in_group_meanings:
|
||||||
|
- game_design_room_banter
|
||||||
|
out_group_risks:
|
||||||
|
- may seem incomplete without prior context
|
||||||
|
stereotypes_to_avoid: []
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:802911591288537118
|
||||||
|
qdrant_source_ids:
|
||||||
|
- "802911591288537118"
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- How often should fragmentary openings appear outside sound/design talk?
|
||||||
|
known_limits:
|
||||||
|
- Single fixture line is evidence for an affordance, not a universal rule.
|
||||||
|
trace:
|
||||||
|
trace_label: fragmentary_like_comparison
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features:
|
||||||
|
- feature_id: casual_recoil_oof
|
||||||
|
label: Casual recoil marker oof
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: stance_marker
|
||||||
|
subcategory: embarrassment
|
||||||
|
description: >
|
||||||
|
"oof" can mark amused discomfort when a social read lands too accurately.
|
||||||
|
lexical_items:
|
||||||
|
- form: oof
|
||||||
|
gloss: amused impact or discomfort
|
||||||
|
sense: playful_recoil
|
||||||
|
register: casual_discord
|
||||||
|
allowed_speaker_standing: speaker_can_self_deprecate
|
||||||
|
forbidden_senses: []
|
||||||
|
collocations:
|
||||||
|
- "oof, don't tell me"
|
||||||
|
realization:
|
||||||
|
function: self_deprecating_recoil
|
||||||
|
surface_strategy: start line with "oof" when prior turn praises a trait the speaker wants to half-resist
|
||||||
|
examples:
|
||||||
|
- "oof, don't tell me my discord has *engineer* vibes"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- compliment_or_trait_read_lands
|
||||||
|
forbidden_when:
|
||||||
|
- serious_apology_or_harm_context
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
grammar_contexts: []
|
||||||
|
phonological_contexts: []
|
||||||
|
collocation_limits:
|
||||||
|
- avoid_repeating_if_already_in_recent_context
|
||||||
|
incompatibilities: []
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- amused_embarrassment
|
||||||
|
- competence_recoil
|
||||||
|
in_group_meanings: []
|
||||||
|
out_group_risks:
|
||||||
|
- can sound too internet-generic if unsupported by context
|
||||||
|
stereotypes_to_avoid: []
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
qdrant_source_ids:
|
||||||
|
- "1037314100931338260"
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: high
|
||||||
|
uncertainty:
|
||||||
|
open_questions: []
|
||||||
|
known_limits:
|
||||||
|
- Marker frequency should be sparse.
|
||||||
|
trace:
|
||||||
|
trace_label: casual_recoil_oof
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
- feature_id: mock_challenge_coward
|
||||||
|
label: Mock challenge coward
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: lexicon
|
||||||
|
category: stance_marker
|
||||||
|
subcategory: friendly_roast
|
||||||
|
description: >
|
||||||
|
"coward" can close a very short challenge when surrounding turns make
|
||||||
|
the aggression visibly playful.
|
||||||
|
lexical_items:
|
||||||
|
- form: coward
|
||||||
|
gloss: mock insult
|
||||||
|
sense: friendly_status_challenge
|
||||||
|
register: casual_discord
|
||||||
|
allowed_speaker_standing: active_banter_with_known_participant
|
||||||
|
forbidden_senses:
|
||||||
|
- actual_contempt
|
||||||
|
collocations:
|
||||||
|
- "then you coward"
|
||||||
|
realization:
|
||||||
|
function: playful_status_challenge
|
||||||
|
surface_strategy: imperative challenge plus "then you coward"
|
||||||
|
examples:
|
||||||
|
- "Engineer me something then you coward"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- friendly_roast_context
|
||||||
|
- target_has_claimed_competence
|
||||||
|
forbidden_when:
|
||||||
|
- unknown_relationship
|
||||||
|
- serious_conflict
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
grammar_contexts:
|
||||||
|
- imperative_challenge
|
||||||
|
phonological_contexts: []
|
||||||
|
collocation_limits: []
|
||||||
|
incompatibilities:
|
||||||
|
- assistant_safety_softening_that_erases_banter
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- teasing
|
||||||
|
- status_play
|
||||||
|
- friendly_pressure
|
||||||
|
in_group_meanings: []
|
||||||
|
out_group_risks:
|
||||||
|
- may be hostile if context is not playful
|
||||||
|
stereotypes_to_avoid: []
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1023727427924545576
|
||||||
|
qdrant_source_ids:
|
||||||
|
- "1023727427924545576"
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: high
|
||||||
|
uncertainty:
|
||||||
|
open_questions: []
|
||||||
|
known_limits:
|
||||||
|
- Only safe inside clear banter.
|
||||||
|
trace:
|
||||||
|
trace_label: mock_challenge_coward
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
discourse_patterns:
|
||||||
|
- pattern_id: casual_floor_yield_with_lol
|
||||||
|
label: Casual floor yield with lol
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: discourse
|
||||||
|
category: turn_taking
|
||||||
|
subcategory: floor_yield
|
||||||
|
description: >
|
||||||
|
After extended riffing, the speaker can step back with "anyway imma
|
||||||
|
shut up now..." plus "lol", reducing authority while keeping warmth.
|
||||||
|
interactional_function: yield_floor_after_riff
|
||||||
|
sequence_shape:
|
||||||
|
- discourse_pivot_anyway
|
||||||
|
- self_silencing_imma_shut_up_now
|
||||||
|
- invite_others_to_invent
|
||||||
|
- lol_softener
|
||||||
|
adjacency_constraints:
|
||||||
|
- prior_turns_show_speaker_has_been_riffing
|
||||||
|
- other_participants_have_interest_or_pending_contribution
|
||||||
|
realization:
|
||||||
|
function: collaborative_turn_release
|
||||||
|
surface_strategy: "anyway imma shut up now and let you guys come up with your own shit lol"
|
||||||
|
examples:
|
||||||
|
- "anyway imma shut up now and let you guys come up with your own shit lol"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- conversational_yield
|
||||||
|
- casual_collaborative_ideation
|
||||||
|
forbidden_when:
|
||||||
|
- formal_moderation
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: light
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
grammar_contexts: []
|
||||||
|
phonological_contexts: []
|
||||||
|
collocation_limits: []
|
||||||
|
incompatibilities: []
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- self_limiting
|
||||||
|
- collaborative
|
||||||
|
- profane_warmth
|
||||||
|
in_group_meanings: []
|
||||||
|
out_group_risks:
|
||||||
|
- profanity may be inappropriate outside familiar room
|
||||||
|
stereotypes_to_avoid: []
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:820077384572338176
|
||||||
|
qdrant_source_ids:
|
||||||
|
- "820077384572338176"
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: high
|
||||||
|
uncertainty:
|
||||||
|
open_questions: []
|
||||||
|
known_limits:
|
||||||
|
- Not a generic moderation pattern.
|
||||||
|
trace:
|
||||||
|
trace_label: casual_floor_yield_with_lol
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
orthography_features:
|
||||||
|
- feature_id: light_discord_informality
|
||||||
|
label: Light Discord informality
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: orthography
|
||||||
|
category: punctuation
|
||||||
|
subcategory: informal_case
|
||||||
|
description: >
|
||||||
|
Casual lines may use lower-case openings, sparse punctuation, emphasis
|
||||||
|
with markdown italics, and uncorrected informal contractions when the
|
||||||
|
social move benefits.
|
||||||
|
allowed_surface_forms:
|
||||||
|
- lower_case_opening
|
||||||
|
- markdown_italics_for_single_emphasis
|
||||||
|
- no_terminal_period
|
||||||
|
- imma
|
||||||
|
- lol
|
||||||
|
forbidden_surface_forms:
|
||||||
|
- heavy_eye_dialect_for_identity_caricature
|
||||||
|
- assistant_like_sentence_polishing
|
||||||
|
renderer_notes: >
|
||||||
|
Preserve compactness. Do not add terminal politeness, explanation, or
|
||||||
|
moral framing unless source meaning requires it.
|
||||||
|
realization:
|
||||||
|
function: casual_discord_texture
|
||||||
|
surface_strategy: allow sparse punctuation and compact informal markers
|
||||||
|
examples:
|
||||||
|
- "oof, don't tell me my discord has *engineer* vibes"
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- casual_discord_register
|
||||||
|
forbidden_when:
|
||||||
|
- formal_or_public_document_register
|
||||||
|
requires_profile_authority: true
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: normal
|
||||||
|
constraints:
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
speaker_contexts:
|
||||||
|
- metame_or_metacrat_fixture
|
||||||
|
grammar_contexts: []
|
||||||
|
phonological_contexts: []
|
||||||
|
collocation_limits: []
|
||||||
|
incompatibilities: []
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- low_ceremony
|
||||||
|
- room_familiarity
|
||||||
|
in_group_meanings: []
|
||||||
|
out_group_risks:
|
||||||
|
- overuse becomes imitation instead of lowering
|
||||||
|
stereotypes_to_avoid:
|
||||||
|
- do_not_represent_protected_dialect_by_eye_dialect
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- discord:1037314100931338260
|
||||||
|
- discord:820077384572338176
|
||||||
|
qdrant_source_ids:
|
||||||
|
- "1037314100931338260"
|
||||||
|
- "820077384572338176"
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- Need more examples to estimate density safely.
|
||||||
|
known_limits: []
|
||||||
|
trace:
|
||||||
|
trace_label: light_discord_informality
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- This profile does not authorize cross-language switching.
|
||||||
|
patterns: []
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not ask Metame to imitate the final utterance directly; Persona produces interlingua intent.
|
||||||
|
- Do not store Metacrat biographical/cultural strata here; store reusable strata as separate culture/subculture profiles and reference them from Persona state.
|
||||||
|
- Do not let current machine-cult architecture register overwrite pre-2025 casual fixture style.
|
||||||
|
- Do not treat profanity or insults as safe without relationship/context evidence.
|
||||||
|
- Do not copy private Persona state into Weksa fixtures or run artifacts.
|
||||||
|
evidence_ledger:
|
||||||
|
- ref: discord:1037314100931338260
|
||||||
|
summary: Self-deprecating recoil after efficiency compliment.
|
||||||
|
- ref: discord:802911591288537118
|
||||||
|
summary: Fragmentary absurd comparison during sound/game design banter.
|
||||||
|
- ref: discord:1023727427924545576
|
||||||
|
summary: Very short mock-aggressive challenge in friendly roast context.
|
||||||
|
- ref: discord:820077384572338176
|
||||||
|
summary: Casual profane floor-yield after extended ideation.
|
||||||
|
- ref: discord:870907292558721085
|
||||||
|
summary: Explicit joke about being bad at self-deprecation.
|
||||||
|
- ref: discord:1020888211729432728
|
||||||
|
summary: Positive uptake when another participant joins cult jokes.
|
||||||
135
data/target-language-ontology/en-US.yaml
Normal file
135
data/target-language-ontology/en-US.yaml
Normal file
|
|
@ -0,0 +1,135 @@
|
||||||
|
profile_id: weksa.target_cultural_ontology.en-US.v0
|
||||||
|
language:
|
||||||
|
code: en
|
||||||
|
locale: en-US
|
||||||
|
script: Latn
|
||||||
|
scope: >
|
||||||
|
Bounded English dialogue lowering profile for current Weksa fixtures. This is
|
||||||
|
not a claim about all English-speaking cultures.
|
||||||
|
authority:
|
||||||
|
owns:
|
||||||
|
- address directness choices
|
||||||
|
- casual versus formal register
|
||||||
|
- technical metaphor legibility
|
||||||
|
- understatement or sarcasm risk
|
||||||
|
does_not_own:
|
||||||
|
- source meaning
|
||||||
|
- speaker identity
|
||||||
|
- whole-culture description
|
||||||
|
salience_axes:
|
||||||
|
address:
|
||||||
|
relevant_distinctions:
|
||||||
|
- direct second person is acceptable when scene context names the addressee
|
||||||
|
- imperative force can be softened or sharpened through wording
|
||||||
|
lowering_questions:
|
||||||
|
- Does direct address preserve the speech act?
|
||||||
|
- Does softening erase urgency?
|
||||||
|
register:
|
||||||
|
relevant_distinctions:
|
||||||
|
- casual
|
||||||
|
- technical
|
||||||
|
- formal
|
||||||
|
- intimate
|
||||||
|
- institutional
|
||||||
|
lowering_questions:
|
||||||
|
- Is technical language character pressure or exposition sludge?
|
||||||
|
- Does sarcasm obscure the actual warning?
|
||||||
|
agency:
|
||||||
|
relevant_distinctions:
|
||||||
|
- explicit agent responsibility is usually available
|
||||||
|
- passive phrasing can hide authority or blame
|
||||||
|
lowering_questions:
|
||||||
|
- Should the speaker own the intervention directly?
|
||||||
|
- Does the line preserve who is at risk?
|
||||||
|
linguistic_affordances:
|
||||||
|
grammar_features:
|
||||||
|
- feature_id: en_us_direct_imperative_warning
|
||||||
|
label: Direct imperative warning
|
||||||
|
status: draft
|
||||||
|
domain:
|
||||||
|
layer: grammar
|
||||||
|
category: clause_mood
|
||||||
|
subcategory: imperative
|
||||||
|
description: >
|
||||||
|
Broad en-US allows direct imperatives for urgent safety warnings when
|
||||||
|
the speaker has standing to intervene and the scene rewards clarity
|
||||||
|
over mitigation.
|
||||||
|
formal_conditions:
|
||||||
|
syntactic_environment:
|
||||||
|
- main_clause
|
||||||
|
- direct_address_optional
|
||||||
|
semantic_inputs:
|
||||||
|
- warning
|
||||||
|
- addressee_action_to_stop_or_avoid
|
||||||
|
- consequence_or_risk_available
|
||||||
|
required_interlingua_fields:
|
||||||
|
- speech_act
|
||||||
|
- addressee
|
||||||
|
- prohibited_action
|
||||||
|
realization:
|
||||||
|
function: stop_or_prevent_action
|
||||||
|
surface_strategy: bare_imperative_or_do_not_imperative
|
||||||
|
examples:
|
||||||
|
- "Don't touch the damaged control."
|
||||||
|
activation:
|
||||||
|
allowed_when:
|
||||||
|
- scene_has_immediate_risk
|
||||||
|
- speaker_has_contextual_authority_or_care_relation
|
||||||
|
forbidden_when:
|
||||||
|
- politeness_softening_is_required_by_target_profile
|
||||||
|
- imperative_would_falsely_imply_hierarchy
|
||||||
|
requires_profile_authority: false
|
||||||
|
minimum_density: light
|
||||||
|
maximum_density: normal
|
||||||
|
constraints:
|
||||||
|
grammar_contexts:
|
||||||
|
- avoid_if_source_requires_indirect_request
|
||||||
|
register_contexts:
|
||||||
|
- casual
|
||||||
|
- technical
|
||||||
|
- emergency
|
||||||
|
speaker_contexts:
|
||||||
|
- known_addressee
|
||||||
|
- operator_warning
|
||||||
|
incompatibilities:
|
||||||
|
- generic_assistant_over_politeness
|
||||||
|
indexicality:
|
||||||
|
social_meanings:
|
||||||
|
- urgency
|
||||||
|
- clarity
|
||||||
|
- responsibility
|
||||||
|
in_group_meanings: []
|
||||||
|
out_group_risks:
|
||||||
|
- may sound abrupt if the scene is not urgent
|
||||||
|
stereotypes_to_avoid: []
|
||||||
|
evidence:
|
||||||
|
source_refs:
|
||||||
|
- schemas/cultural-ontology-profile.md
|
||||||
|
qdrant_source_ids: []
|
||||||
|
cached_source_refs: []
|
||||||
|
source_hashes: []
|
||||||
|
reviewer_refs: []
|
||||||
|
confidence: medium
|
||||||
|
uncertainty:
|
||||||
|
open_questions:
|
||||||
|
- Should a later en-US regional overlay override imperative force?
|
||||||
|
known_limits:
|
||||||
|
- Base en-US does not model regional, racialized, or contact-language
|
||||||
|
dialect grammar.
|
||||||
|
trace:
|
||||||
|
trace_label: direct_imperative_warning
|
||||||
|
must_report_when_used: true
|
||||||
|
must_report_when_rejected: true
|
||||||
|
phonology_features: []
|
||||||
|
lexicon_features: []
|
||||||
|
discourse_patterns: []
|
||||||
|
orthography_features: []
|
||||||
|
code_switching:
|
||||||
|
allowed: false
|
||||||
|
constraints:
|
||||||
|
- Base en-US profile does not authorize contact-language switching.
|
||||||
|
patterns: []
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not treat English as the neutral source for other target languages.
|
||||||
|
- Do not use generic assistant politeness when a character voice is required.
|
||||||
|
- Do not let sarcasm replace the actual predicate being lowered.
|
||||||
70
data/target-language-ontology/ja-JP.yaml
Normal file
70
data/target-language-ontology/ja-JP.yaml
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
profile_id: weksa.target_cultural_ontology.ja-JP.v0
|
||||||
|
language:
|
||||||
|
code: ja
|
||||||
|
locale: ja-JP
|
||||||
|
script: Jpan
|
||||||
|
scope: >
|
||||||
|
Bounded Japanese dialogue lowering profile for Weksa fixtures. This profile
|
||||||
|
records realization distinctions that must be inspected; it is not a total
|
||||||
|
description of Japanese culture.
|
||||||
|
authority:
|
||||||
|
owns:
|
||||||
|
- politeness and honorific pressure
|
||||||
|
- in-group/out-group stance when context supplies it
|
||||||
|
- subject and object omission choices
|
||||||
|
- script mix and technical register
|
||||||
|
- sentence-final force
|
||||||
|
does_not_own:
|
||||||
|
- source meaning
|
||||||
|
- character identity
|
||||||
|
- exhaustive Japanese grammar
|
||||||
|
salience_axes:
|
||||||
|
politeness:
|
||||||
|
relevant_distinctions:
|
||||||
|
- plain
|
||||||
|
- polite
|
||||||
|
- honorific
|
||||||
|
- humble
|
||||||
|
- rough
|
||||||
|
lowering_questions:
|
||||||
|
- Does politeness preserve the relationship, or does it lie about it?
|
||||||
|
- Is roughness character-specific or generic stylization?
|
||||||
|
social_position:
|
||||||
|
relevant_distinctions:
|
||||||
|
- uchi_soto_pressure
|
||||||
|
- hierarchy
|
||||||
|
- familiarity
|
||||||
|
- emergency_override
|
||||||
|
lowering_questions:
|
||||||
|
- Does urgency override ordinary deference?
|
||||||
|
- Does the line imply a relationship the scene has not earned?
|
||||||
|
ellipsis:
|
||||||
|
relevant_distinctions:
|
||||||
|
- subject omission
|
||||||
|
- object omission
|
||||||
|
- explicit pronoun for emphasis or contrast
|
||||||
|
lowering_questions:
|
||||||
|
- Is the addressee recoverable without an explicit pronoun?
|
||||||
|
- Would explicit pronouns sound unnatural or too pointed?
|
||||||
|
script_and_register:
|
||||||
|
relevant_distinctions:
|
||||||
|
- kanji for technical compounds
|
||||||
|
- kana for softness or readability
|
||||||
|
- katakana for foreignness, machine texture, or emphasis
|
||||||
|
lowering_questions:
|
||||||
|
- Does the script choice help the speaker voice?
|
||||||
|
- Does a technical compound preserve precision without becoming stiff?
|
||||||
|
sentence_final_force:
|
||||||
|
relevant_distinctions:
|
||||||
|
- direct request
|
||||||
|
- warning consequence
|
||||||
|
- command
|
||||||
|
- threat-like phrasing
|
||||||
|
lowering_questions:
|
||||||
|
- Does the ending carry warning force without cartoon aggression?
|
||||||
|
- Does the line preserve the hazard predicate?
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not treat politeness as decoration.
|
||||||
|
- Do not use explicit pronouns just because English has them.
|
||||||
|
- Do not make every sharp line rough or anime-coded.
|
||||||
|
- Do not erase the difference between technical precision and formal politeness.
|
||||||
76
data/target-language-ontology/pt-BR-overlays.yaml
Normal file
76
data/target-language-ontology/pt-BR-overlays.yaml
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
catalog_id: weksa.target_cultural_ontology.pt-BR.overlays.v0
|
||||||
|
base_profile: data/target-language-ontology/pt-BR.yaml
|
||||||
|
scope: >
|
||||||
|
Catalog of optional Brazilian Portuguese regional and cultural overlay slots.
|
||||||
|
An overlay slot is not permission to imitate a community. It is a named place
|
||||||
|
where reviewed, source-grounded distinctions can live.
|
||||||
|
activation_rule: >
|
||||||
|
Use the broad pt-BR profile by default. Add an overlay only when source
|
||||||
|
context, speaker state, setting documentation, or authoring metadata names the
|
||||||
|
relevant region, community, institution, religion, or register.
|
||||||
|
overlay_slots:
|
||||||
|
- overlay_id: broad_brazilian_default
|
||||||
|
status: active_base_mode
|
||||||
|
profile_ref: data/target-language-ontology/pt-BR.yaml
|
||||||
|
owns:
|
||||||
|
- broadly legible Brazilian Portuguese dialogue
|
||||||
|
does_not_own:
|
||||||
|
- regional specificity
|
||||||
|
- religious-cultural specificity
|
||||||
|
- overlay_id: rio_urban
|
||||||
|
status: planned_profile
|
||||||
|
profile_ref:
|
||||||
|
owns_when_defined:
|
||||||
|
- Rio de Janeiro urban speech/register pressures for specific characters or settings
|
||||||
|
blocked_until:
|
||||||
|
- reviewed source context
|
||||||
|
- human-approved examples
|
||||||
|
- overlay_id: sao_paulo_urban
|
||||||
|
status: planned_profile
|
||||||
|
profile_ref:
|
||||||
|
owns_when_defined:
|
||||||
|
- Sao Paulo urban speech/register pressures for specific characters or settings
|
||||||
|
blocked_until:
|
||||||
|
- reviewed source context
|
||||||
|
- human-approved examples
|
||||||
|
- overlay_id: northeast_regional
|
||||||
|
status: planned_profile
|
||||||
|
profile_ref:
|
||||||
|
owns_when_defined:
|
||||||
|
- Northeast Brazilian regional speech/register pressures for specific characters or settings
|
||||||
|
blocked_until:
|
||||||
|
- specific region named
|
||||||
|
- reviewed examples
|
||||||
|
- human approval
|
||||||
|
- overlay_id: south_regional
|
||||||
|
status: planned_profile
|
||||||
|
profile_ref:
|
||||||
|
owns_when_defined:
|
||||||
|
- South Brazilian regional speech/register pressures for specific characters or settings
|
||||||
|
blocked_until:
|
||||||
|
- specific region named
|
||||||
|
- reviewed examples
|
||||||
|
- human approval
|
||||||
|
- overlay_id: amazonian_regional
|
||||||
|
status: planned_profile
|
||||||
|
profile_ref:
|
||||||
|
owns_when_defined:
|
||||||
|
- Amazonian regional speech/register pressures for specific characters or settings
|
||||||
|
blocked_until:
|
||||||
|
- specific region or community named
|
||||||
|
- reviewed examples
|
||||||
|
- human approval
|
||||||
|
- overlay_id: umbanda
|
||||||
|
status: active_guarded_overlay
|
||||||
|
profile_ref: data/target-language-ontology/pt-BR-umbanda.yaml
|
||||||
|
owns:
|
||||||
|
- Umbanda-related register gating
|
||||||
|
- sacred address caution
|
||||||
|
- anti-caricature constraints
|
||||||
|
blocked_until:
|
||||||
|
- source context or authoring metadata explicitly activates Umbanda context
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not use a planned overlay as if it were defined.
|
||||||
|
- Do not treat regional slots as accent generators.
|
||||||
|
- Do not use religious-cultural overlays for ambience.
|
||||||
|
- Do not collapse race, region, religion, class, and slang into one Brazilian flavor.
|
||||||
72
data/target-language-ontology/pt-BR-umbanda.yaml
Normal file
72
data/target-language-ontology/pt-BR-umbanda.yaml
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
profile_id: weksa.target_cultural_ontology.pt-BR.umbanda.v0
|
||||||
|
language:
|
||||||
|
code: pt
|
||||||
|
locale: pt-BR
|
||||||
|
script: Latn
|
||||||
|
overlay:
|
||||||
|
base_profile: data/target-language-ontology/pt-BR.yaml
|
||||||
|
kind: religious_cultural_register
|
||||||
|
scope: >
|
||||||
|
Optional Brazilian Portuguese cultural ontology overlay for Umbanda-related
|
||||||
|
scenes, speakers, ritual contexts, or referents. This profile is a consent and
|
||||||
|
context gate, not a decorative vocabulary pack.
|
||||||
|
authority:
|
||||||
|
owns:
|
||||||
|
- whether Umbanda-specific register is allowed for a realization
|
||||||
|
- sacred or ritual address caution
|
||||||
|
- house/tradition specificity warnings
|
||||||
|
- syncretic and entity-reference sensitivity
|
||||||
|
- anti-caricature constraints
|
||||||
|
does_not_own:
|
||||||
|
- Umbanda doctrine as a whole
|
||||||
|
- authority to invent ritual speech
|
||||||
|
- generic Brazilian Portuguese
|
||||||
|
- speaker identity unless the speaker context explicitly supplies it
|
||||||
|
activation_requirements:
|
||||||
|
any_required:
|
||||||
|
- source context names an Umbanda scene, terreiro, practitioner, entity, ritual, or discourse community
|
||||||
|
- speaker profile explicitly owns an Umbanda-informed voice or memory
|
||||||
|
- authoring metadata requests this overlay for reviewed cultural grounding
|
||||||
|
never_activate_for:
|
||||||
|
- generic Brazilian flavor
|
||||||
|
- jokes, insults, mystic ambience, or unexplained exotic texture
|
||||||
|
- non-Umbanda religious scenes unless the source context makes a syncretic relation explicit
|
||||||
|
salience_axes:
|
||||||
|
sacred_address:
|
||||||
|
relevant_distinctions:
|
||||||
|
- ordinary dialogue
|
||||||
|
- respectful reference
|
||||||
|
- ritual address
|
||||||
|
- entity_or_guide_reference
|
||||||
|
lowering_questions:
|
||||||
|
- Is the line ordinary speech or ritualized speech?
|
||||||
|
- Does the speaker have standing to use sacred address?
|
||||||
|
- Should a term be left general until a human reviewer approves specificity?
|
||||||
|
house_specificity:
|
||||||
|
relevant_distinctions:
|
||||||
|
- practices and terms can vary by house, region, and lineage
|
||||||
|
- generic flattening can become false authority
|
||||||
|
lowering_questions:
|
||||||
|
- Is the output pretending one practice represents all Umbanda?
|
||||||
|
- Should the trace mark the choice as house-specific or uncertain?
|
||||||
|
syncretic_reference:
|
||||||
|
relevant_distinctions:
|
||||||
|
- Catholic, African, Indigenous, Spiritist, and local references may coexist differently by context
|
||||||
|
- entity names and roles are not interchangeable decoration
|
||||||
|
lowering_questions:
|
||||||
|
- Does the source actually contain the syncretic relation?
|
||||||
|
- Does the line preserve respect without overexplaining?
|
||||||
|
anti_caricature:
|
||||||
|
relevant_distinctions:
|
||||||
|
- religious register
|
||||||
|
- folkloric stereotype
|
||||||
|
- occult ambience
|
||||||
|
lowering_questions:
|
||||||
|
- Is the output using Umbanda as culture, faith, and practice rather than spooky texture?
|
||||||
|
- Would a practitioner recognize this as respectful enough for review?
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not use Umbanda terms as generic magic flavor.
|
||||||
|
- Do not invent ritual formulas.
|
||||||
|
- Do not collapse Umbanda into Candomblé, Spiritism, Catholicism, or generic Afro-Brazilian religion.
|
||||||
|
- Do not imply all Brazilian Portuguese religious language is Umbanda-coded.
|
||||||
|
- Do not activate this overlay unless source context or authoring metadata explicitly asks for it.
|
||||||
74
data/target-language-ontology/pt-BR.yaml
Normal file
74
data/target-language-ontology/pt-BR.yaml
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
profile_id: weksa.target_cultural_ontology.pt-BR.v0
|
||||||
|
language:
|
||||||
|
code: pt
|
||||||
|
locale: pt-BR
|
||||||
|
script: Latn
|
||||||
|
scope: >
|
||||||
|
Bounded Brazilian Portuguese dialogue lowering profile. This profile is the
|
||||||
|
base Brazilian Portuguese target; regional, class, religious, and community
|
||||||
|
registers should be added as explicit overlays rather than silently folded
|
||||||
|
into generic pt-BR.
|
||||||
|
authority:
|
||||||
|
owns:
|
||||||
|
- Brazilian Portuguese lexical preference
|
||||||
|
- treatment and address choices
|
||||||
|
- directness versus mitigation
|
||||||
|
- regional_or_cultural_overlay_selection
|
||||||
|
- idiom naturalness for reviewed fixture prose
|
||||||
|
does_not_own:
|
||||||
|
- source meaning
|
||||||
|
- Brazilian culture as a whole
|
||||||
|
- regional or religious-community authority without an explicit overlay
|
||||||
|
- target speaker identity
|
||||||
|
salience_axes:
|
||||||
|
treatment:
|
||||||
|
relevant_distinctions:
|
||||||
|
- voce
|
||||||
|
- tu_regionally_marked
|
||||||
|
- o_senhor_a_senhora
|
||||||
|
- name_or_title_address
|
||||||
|
lowering_questions:
|
||||||
|
- Is the relationship close, hostile, hierarchical, unknown, or sacred?
|
||||||
|
- Does `voce` preserve broad Brazilian naturalness better than `tu`?
|
||||||
|
- Is `tu` regionally grounded or just imported flavor?
|
||||||
|
directness:
|
||||||
|
relevant_distinctions:
|
||||||
|
- bare imperative
|
||||||
|
- softened imperative
|
||||||
|
- warning framed as consequence
|
||||||
|
- formal warning
|
||||||
|
lowering_questions:
|
||||||
|
- Does urgency justify blunt imperative force?
|
||||||
|
- Would mitigation make the warning dishonest?
|
||||||
|
lexical_locale:
|
||||||
|
relevant_distinctions:
|
||||||
|
- Brazilian Portuguese terms should be preferred in reviewed pt-BR fixtures
|
||||||
|
- European Portuguese defaults must be marked if intentionally used
|
||||||
|
lowering_questions:
|
||||||
|
- Is a term recognizably Brazilian Portuguese in this context?
|
||||||
|
- Is a literal technical word natural enough for dialogue?
|
||||||
|
regional_and_cultural_overlay:
|
||||||
|
relevant_distinctions:
|
||||||
|
- broad_brazilian_default
|
||||||
|
- regional_speech_pattern
|
||||||
|
- class_or_institutional_register
|
||||||
|
- religious_or_ritual_register
|
||||||
|
- community_specific_lexicon
|
||||||
|
lowering_questions:
|
||||||
|
- Does the source context justify an overlay?
|
||||||
|
- Is the overlay owned by a named profile?
|
||||||
|
- Would applying the overlay stereotype the speaker or setting?
|
||||||
|
metaphor:
|
||||||
|
relevant_distinctions:
|
||||||
|
- technical metaphors can preserve character ontology
|
||||||
|
- over-literal metaphors may sound translated rather than spoken
|
||||||
|
lowering_questions:
|
||||||
|
- Does the metaphor still sound like the speaker?
|
||||||
|
- Does it preserve the warning instead of becoming decorative?
|
||||||
|
forbidden_flattenings:
|
||||||
|
- Do not label output as Portuguese without a locale in reviewed fixtures.
|
||||||
|
- Do not default to European Portuguese wording when the target is pt-BR.
|
||||||
|
- Do not treat Brazilian Portuguese as one culture, region, class, or religion.
|
||||||
|
- Do not add regional or religious markers without a cited overlay profile and source-context reason.
|
||||||
|
- Do not soften a warning merely because directness feels impolite in English review.
|
||||||
|
overlay_catalog: data/target-language-ontology/pt-BR-overlays.yaml
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
# Architecture
|
# Architecture
|
||||||
|
|
||||||
Weksa is a language-intent engine: currently a state spine, pipeline map,
|
Weksa is the language-intent daemon surface: currently a state spine, pipeline
|
||||||
fixtures, ontology data and a planned service contract. No daemon runs; the
|
map, fixtures, and service contract waiting for its runtime loop.
|
||||||
planned packet crate is `crates/weksa` (cut `packet-store`).
|
|
||||||
|
|
||||||
See [Verse Service Contract](./verse-service-contract.md) for the
|
See [Verse Service Contract](./verse-service-contract.md) for the
|
||||||
CultCache/CultMesh authority map.
|
CultCache/CultMesh authority map.
|
||||||
|
|
@ -10,15 +9,15 @@ CultCache/CultMesh authority map.
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
Build a procedural alien-language engine whose outputs are grounded in
|
Build a procedural alien-language engine whose outputs are grounded in
|
||||||
worldview, semantics, grammar, phonology, morphology, and history. Once a service is
|
worldview, semantics, grammar, phonology, morphology, and history. As a daemon,
|
||||||
earned (planned), Weksa also turns writing plus agent state into typed conversational intent, then
|
Weksa also turns writing plus agent state into typed conversational intent, then
|
||||||
lowers that intent into written realizations, pronunciation plans, speech-provider
|
lowers that intent into written realizations, pronunciation plans, speech-provider
|
||||||
requests, and utterance handoff documents.
|
requests, and utterance handoff documents.
|
||||||
|
|
||||||
## Current Mechanism
|
## Current Mechanism
|
||||||
|
|
||||||
There is no long-running runtime loop yet. The repo contains persistent state
|
There is no long-running runtime loop yet. The repo contains persistent state
|
||||||
surfaces that define the intended data flow
|
surfaces and a provider advertisement fixture that define the intended data flow
|
||||||
and the ownership boundaries future code must respect.
|
and the ownership boundaries future code must respect.
|
||||||
|
|
||||||
The first shared contract is the [Interlingua Standard](./interlingua-standard.md):
|
The first shared contract is the [Interlingua Standard](./interlingua-standard.md):
|
||||||
|
|
|
||||||
|
|
@ -1,120 +0,0 @@
|
||||||
# Calibrating the accept rule
|
|
||||||
|
|
||||||
`weksa loop calibrate` measures how the live accept rule behaves on a run's own
|
|
||||||
Validation corpus: how often it accepts, rejects as no gain, or regresses a
|
|
||||||
candidate that should be none of those. It does not reimplement the rule. It
|
|
||||||
reads the answered draws through `RunStores::read_draws` (the scoring
|
|
||||||
`weksa loop relower` uses), decides every trial with `decide_panel` over
|
|
||||||
`paired_floor` (`crates/weksa/src/run.rs`), and prints, per class, the items
|
|
||||||
read and skipped per language, the trial totals with their Accepted, NoGain and
|
|
||||||
Regressed counts, and the mean panel noise. That is all it produces: the
|
|
||||||
Accepted/NoGain/Regressed counts and the noise mean in the map's "Recalibration
|
|
||||||
on the grown corpus" block are reproduced by it, and the prompted trials are
|
|
||||||
also printed split by the recorded lowering `R`'s role (`prompted-r-candidate`,
|
|
||||||
`prompted-r-base`, `prompted-r-free`, see below), the candidate counts per arm
|
|
||||||
and the mild arms' composite offsets from the prompted mean (see below); the
|
|
||||||
other figures there (the
|
|
||||||
35% with R removed, the noise range, the 0.0185 gain and its 0.41 ratio, the
|
|
||||||
bootstrap intervals, the per-item SDs, R's +0.024, the mild-arm duplicate
|
|
||||||
counts, the Train-vocabulary overlap, the old/new
|
|
||||||
class composites and the ten parse-refused item ids) were computed by scratch scripts that are not in the repo. It is a
|
|
||||||
diagnostic: it records nothing, writes no prompts, and never touches Test or
|
|
||||||
Train.
|
|
||||||
|
|
||||||
## What it counts
|
|
||||||
|
|
||||||
The draws are lowerings of one round's Validation packets: the round's own
|
|
||||||
(recorded) lowering `R`, plus draws you label. `P` is `R` and the `--prompted`
|
|
||||||
draws; the floor size is `FLOOR_ARMS_MIN` (3), the live rule's.
|
|
||||||
|
|
||||||
- Prompted trials: every ordered pair (base, candidate) in `P`, against every
|
|
||||||
3-subset of the rest of `P` as the floor. A repeat of the same lowering
|
|
||||||
should read NoGain; Accepted is a false accept, Regressed a false reject.
|
|
||||||
(`R` comes from the round, not from `relower`, so it may not be
|
|
||||||
exchangeable with a repeat.) The prompted line is therefore printed three
|
|
||||||
more times, by `R`'s role in the trial: `prompted-r-candidate` (`R` is the
|
|
||||||
candidate), `prompted-r-base` (`R` is the base) and `prompted-r-free` (`R` is
|
|
||||||
neither; it may sit in the floor). The three sum to the prompted line. Read the Accepted
|
|
||||||
and Regressed columns of each line: a false accept sits mostly under the
|
|
||||||
first and a false reject under the second, but `R`-as-candidate trials can
|
|
||||||
Regress too (class `old` on `growth-scene`: 5 of its 15). The third
|
|
||||||
is the exchangeable rate: on `growth-scene` it was 0 Accepted and 0 Regressed
|
|
||||||
of 80 while all 11 false accepts and 9 false rejects involved `R`. Which of
|
|
||||||
the two rates the live rule should be held to is undecided: the live loop
|
|
||||||
meets `R` as the head's establishing lowering.
|
|
||||||
- Degraded trials, per `--degraded` arm: every base in `P` against every
|
|
||||||
3-subset of the rest of `P`, the degraded draw as the candidate. These should
|
|
||||||
read Regressed.
|
|
||||||
- Candidate trials, pooled over the `--candidate` arms: the same, tallied
|
|
||||||
Accepted, NoGain, Regressed. This is the rule's power against that arm. The
|
|
||||||
pooled line is followed by one `candidate=LABEL` line per arm: arms of one
|
|
||||||
kind can differ completely (Train-guide h1 and h2 Regressed in every trial
|
|
||||||
while h3 and h4 gained), and then the pooled figure is not a power.
|
|
||||||
- Mild offset: each `degraded=LABEL` line ends with `offset LANGUAGE=+x.xxxx`, the
|
|
||||||
arm's composite minus the mean composite of the prompted draws (`R` included),
|
|
||||||
per language over the items read. A degraded arm that is barely below the
|
|
||||||
prompted mean is a weak probe of the rule's sensitivity.
|
|
||||||
- Noise: the mean `panel_noise` over every (base, floor) choice.
|
|
||||||
|
|
||||||
With six prompted draws including `R` that is 120 prompted trials, 60 per
|
|
||||||
degraded arm and 240 candidate trials. Trials share draws and are not
|
|
||||||
independent. Each count is printed for `all` Validation items and for each
|
|
||||||
`--class NAME=PREFIX[,PREFIX...]` (items whose key starts with any prefix), from
|
|
||||||
the same per-item scores. A class with fewer than two read items in a language
|
|
||||||
has no floor and reads Regressed in every trial; that is printed.
|
|
||||||
|
|
||||||
## Steps
|
|
||||||
|
|
||||||
1. `weksa loop open ROOT ...` and `weksa loop round ROOT` record round N and
|
|
||||||
leave its answers in `ROOT/round-N/`.
|
|
||||||
2. For each draw label: `weksa loop relower ROOT --round N --arm LABEL
|
|
||||||
--lowerer NAME` writes the byte-identical lowering prompts to
|
|
||||||
`ROOT/relower-N-LABEL/<digest>.prompt` and exits 3. Answer each prompt into
|
|
||||||
`ROOT/relower-N-LABEL/<digest>.answer`.
|
|
||||||
3. `weksa loop calibrate ROOT --round N --prompted p1 --prompted p2 ...
|
|
||||||
[--degraded LABEL]... [--candidate LABEL]... [--class NAME=PREFIX]...`.
|
|
||||||
At least four `--prompted` labels are needed (a pair and three floors with
|
|
||||||
`R` make five draws). It exits 1 and lists `unanswered LABEL COUNT` for any
|
|
||||||
draw with prompts still unanswered. Labels match `[a-z0-9-]{1,32}` and differ
|
|
||||||
across the three kinds. It needs the Ollama embedder of the run; a full
|
|
||||||
60-item, 13-draw calibration is on the order of 1500 embedded texts, so
|
|
||||||
launch it detached with a log.
|
|
||||||
|
|
||||||
The scratch packet store is `ROOT/calibrate-N/base.cc`; delete it at will.
|
|
||||||
|
|
||||||
## Answer file format
|
|
||||||
|
|
||||||
`<digest>.answer` is one JSON object and nothing else, no code fence:
|
|
||||||
`{"text": "..."}`, a JSON-escaped string. The answerer reads only the prompt
|
|
||||||
(its first line says what to write) and writes the answer. Every prompt of the
|
|
||||||
draw must be answered.
|
|
||||||
|
|
||||||
## Briefs per arm
|
|
||||||
|
|
||||||
Independence rule: a fresh agent per batch of answers; no batch sees another
|
|
||||||
draw's answers. Only `mild` reads `round-N/*.answer`.
|
|
||||||
|
|
||||||
- Plain prompted: answer each prompt as its own first line asks; read nothing
|
|
||||||
else in the run root.
|
|
||||||
- Mild: for each prompt, read the recorded lowering in
|
|
||||||
`ROOT/round-N/<digest>.answer` and write the same-format answer whose text is
|
|
||||||
that utterance with exactly one meaning detail blurred: change or drop one of
|
|
||||||
tense, polarity, modality or hedge, a referent, a quantity or a predicate's
|
|
||||||
concept (replace it with a near but different word). Keep language, register,
|
|
||||||
length and fluency; the result must read as a natural utterance and must not
|
|
||||||
mention the change. Pick the detail that is not the most salient one. A
|
|
||||||
second mild draw blurs a different detail than the first and is written
|
|
||||||
without reading the first's answers. The wording of the distil-base original
|
|
||||||
is lost, and the dispatch used for growth-base is not on disk, so this is the
|
|
||||||
wording from now on. Warning: on growth-base two mild arms briefed this way
|
|
||||||
came out identical in 27 of 60 items, so independently briefed mild arms
|
|
||||||
are not independent degradations; read a mild draw's regress count with that
|
|
||||||
in mind.
|
|
||||||
- Train-guide: before answering, read the Train sentences of the corpus in the
|
|
||||||
batch's language as a register guide and let it steer word choice; the guide
|
|
||||||
gives phrasing only and each answer must still say exactly what its own packet
|
|
||||||
says. The guide section is the live Train items of that language, built from
|
|
||||||
`weksa corpus dump` filtered to Train, and is given to the answerer in the
|
|
||||||
brief, never pasted into this document, and never includes Validation or Test
|
|
||||||
text. Read nothing else in the run root.
|
|
||||||
- Control: a script writes `{"text":"Yes."}` as the answer to every prompt.
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue