Compare commits
93 changed files with 2113 additions and 13202 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -22,4 +22,3 @@ build/
|
|||
.venv/
|
||||
venv/
|
||||
target/
|
||||
tools/show-working/out/
|
||||
|
|
|
|||
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.
23
README.md
23
README.md
|
|
@ -5,8 +5,7 @@ culture, and constraint, and the planned lowerer that turns an agent's
|
|||
meaning packet into the reader's display language.
|
||||
|
||||
**What is valuable here.** The interlingua standard and the lowering design: a
|
||||
meaning packet owns what is meant, the scene state (live: `weksa scene put|dump`, labelled by the rule in
|
||||
`docs/scene-annotation.md`; speaker documents are planned) owns the speaker's relation to the addressee, which selects register,
|
||||
meaning packet owns what is meant, a target-language profile owns register,
|
||||
address and politeness, and a lowerer owns surface text and leaves a trace.
|
||||
|
||||
**The problem it solves.** An agent's outward speech today is one English
|
||||
|
|
@ -25,13 +24,11 @@ measured.
|
|||
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`.
|
||||
`weksa entity dump` and `weksa inventory dump`.
|
||||
- [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.
|
||||
- `data/`: the cultural ontology and target-language profile data.
|
||||
- `settings/`: setting-specific proving grounds for language projects.
|
||||
|
||||
**Live versus planned.** Live: docs, fixtures, examples, ontology data and the
|
||||
|
|
@ -85,17 +82,9 @@ English, Brazilian Portuguese, Japanese, and later target-language dialogue.
|
|||
[Flavored English Lowering](./docs/flavored-english-lowering.md) remains the
|
||||
target-specific English receipt.
|
||||
|
||||
The language ontology is `data/ontology/ontology.cc` (read it with
|
||||
`weksa ontology dump`): per language, the lexicon, grammar and discourse choices a lowerer
|
||||
reads for a stance, a discourse and a scene relation. Only an entry with a Scene condition names an
|
||||
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.
|
||||
See [Target-Language Cultural Ontology Profiles](./data/target-language-ontology/README.md)
|
||||
for the reviewable address, register, politeness, idiom, metaphor, and script
|
||||
distinctions that target lowerers must inspect before producing output.
|
||||
|
||||
For the first AquaSynth speech-training handoff, see
|
||||
[Tiny PanPhon v0.1 Speech Curriculum](./examples/speech-training/tiny-panphon-v0.1/README.md).
|
||||
|
|
|
|||
|
|
@ -1,398 +0,0 @@
|
|||
//! Build-time generator for the "Show her working" page. Runs the real
|
||||
//! admission door, lowerer and IPA reader over the committed proof packet and
|
||||
//! variants of it, and prints one JSON document on stdout: the typed slots, the
|
||||
//! inventory entries the packet chose, and the outcome, which is lowered text or
|
||||
//! a named refusal. Scoring is not here: `tools/show-working/build.py` calls the
|
||||
//! `weksa score` CLI on the text this emits.
|
||||
//!
|
||||
//! Run from the repository root: `cargo run --release --example show_working`.
|
||||
//! Every variant is a mutation of `proof_packet()`, spelled in its `source`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use weksa::packet::{
|
||||
EntityId, FeatValue, FeatureValue, Grade, NodeId, ProvenanceSource, RoleFill, proof_packet,
|
||||
};
|
||||
use weksa::{
|
||||
CorpusStore, EntityStore, InvId, Inventory, InventoryStore, LowerError, Packet, PacketStore,
|
||||
StoreError, lower, pronounce,
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
id: &'static str,
|
||||
title: &'static str,
|
||||
note: &'static str,
|
||||
source: &'static str,
|
||||
packet: Packet,
|
||||
}
|
||||
|
||||
fn id(s: &str) -> InvId {
|
||||
s.parse().expect("inventory id")
|
||||
}
|
||||
|
||||
fn node(s: &str) -> NodeId {
|
||||
NodeId::parse(s).expect("node id")
|
||||
}
|
||||
|
||||
fn grade(feature: &str, v: u16) -> FeatureValue {
|
||||
FeatureValue {
|
||||
feature: id(feature),
|
||||
value: FeatValue::Grade(Grade::new(v).expect("grade")),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixtures() -> Vec<Fixture> {
|
||||
let proof = proof_packet();
|
||||
let mut out = vec![Fixture {
|
||||
id: "proof",
|
||||
title: "Nibu warns the player off the control",
|
||||
note: "The committed proof packet, unchanged.",
|
||||
source: "proof_packet() in crates/weksa/src/packet.rs",
|
||||
packet: proof.clone(),
|
||||
}];
|
||||
let mut add = |id, title, note, source, f: &dyn Fn(&mut Packet)| {
|
||||
let mut packet = proof.clone();
|
||||
f(&mut packet);
|
||||
out.push(Fixture { id, title, note, source, packet });
|
||||
};
|
||||
add(
|
||||
"no-addressee",
|
||||
"Same meaning, nobody addressed",
|
||||
"With the addressee unset the player is a third party: no \"you\", no reflexive.",
|
||||
"proof_packet() with discourse.addressee = None",
|
||||
&|p| p.discourse.addressee = None,
|
||||
);
|
||||
add(
|
||||
"stance-held-back",
|
||||
"Anger held back, restraint high",
|
||||
"Stance is the speaker's felt affect. The lowerer has no row that reads it, so the text is the proof's text.",
|
||||
"proof_packet() with stance anger=300, restraint=700",
|
||||
&|p| p.stance.features = vec![grade("feature:9", 300), grade("feature:18", 700)],
|
||||
);
|
||||
add(
|
||||
"hedged",
|
||||
"Hedged and uncertain warning",
|
||||
"Hedge and certainty are meaning the lowerer cannot yet say. It refuses rather than drop them.",
|
||||
"proof_packet() with discourse hedge=600, certainty=400",
|
||||
&|p| p.discourse.features = vec![grade("feature:6", 600), grade("feature:7", 400)],
|
||||
);
|
||||
add(
|
||||
"negated",
|
||||
"Negated intervention (polarity: negative)",
|
||||
"Dropping the negation would say the opposite, so the lowerer refuses. This is the shape of a negated Dao line awaiting polarity.",
|
||||
"proof_packet() with predication n5 polarity=negative",
|
||||
&|p| {
|
||||
p.predications[1].features = vec![FeatureValue {
|
||||
feature: id("feature:1"),
|
||||
value: FeatValue::Option("negative".parse().expect("label")),
|
||||
}]
|
||||
},
|
||||
);
|
||||
add(
|
||||
"consent-authored",
|
||||
"Addressee consent, authored source",
|
||||
"Someone who saw the request says the addressee asked for it. No lowering speaks for that request yet.",
|
||||
"proof_packet() with discourse.addressee_consent = n4 (source Authored)",
|
||||
&|p| p.discourse.addressee_consent = Some(node("n4")),
|
||||
);
|
||||
add(
|
||||
"consent-imported",
|
||||
"Addressee consent, imported-corpus source",
|
||||
"A reader of wording cannot have seen a request, so the packet is refused at admission (V15), before any lowering.",
|
||||
"proof_packet() with addressee_consent = n4 and provenance.source = ImportedCorpus",
|
||||
&|p| {
|
||||
p.discourse.addressee_consent = Some(node("n4"));
|
||||
p.provenance.source = ProvenanceSource::ImportedCorpus;
|
||||
},
|
||||
);
|
||||
add(
|
||||
"relation",
|
||||
"A causal relation between the predications",
|
||||
"Relations are not rendered; the lowerer refuses instead of asserting a different meaning.",
|
||||
"proof_packet() with relation:8 (causes) n4 -> n5",
|
||||
&|p| {
|
||||
p.relations = vec![weksa::packet::Relation {
|
||||
relation: id("relation:8"),
|
||||
from: node("n4"),
|
||||
to: node("n5"),
|
||||
features: vec![],
|
||||
}]
|
||||
},
|
||||
);
|
||||
add(
|
||||
"dangling-filler",
|
||||
"A role filled by a node that does not exist",
|
||||
"Refused at admission (V4): the packet is not a packet.",
|
||||
"proof_packet() with predication n5 agent filler n9",
|
||||
&|p| {
|
||||
p.predications[1].roles[0] = RoleFill { role: id("role:1"), filler: node("n9") }
|
||||
},
|
||||
);
|
||||
add(
|
||||
"unknown-entity",
|
||||
"A referent naming an entity nobody holds",
|
||||
"The entity store is the only owner of names; a packet cannot invent one.",
|
||||
"proof_packet() with referent n3 entity = entity:nobody",
|
||||
&|p| p.referents[2].entity = Some(EntityId::parse("entity:nobody").expect("entity")),
|
||||
);
|
||||
add(
|
||||
"common-noun-agent",
|
||||
"The ship mind as a common noun",
|
||||
"No entity: the referent lowers as \"the ship mind\", and there is no name to pronounce.",
|
||||
"proof_packet() with referent n3 entity = None",
|
||||
&|p| p.referents[2].entity = None,
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn gloss(inv: &Inventory, rev: u32, i: &InvId) -> Value {
|
||||
match inv.resolve(i, rev) {
|
||||
Some(e) => json!({ "id": i.to_string(), "gloss": e.gloss }),
|
||||
None => json!({ "id": i.to_string(), "gloss": null }),
|
||||
}
|
||||
}
|
||||
|
||||
fn feature_json(inv: &Inventory, rev: u32, slot: &str, at: &str, f: &FeatureValue) -> Value {
|
||||
let mut g = gloss(inv, rev, &f.feature);
|
||||
g["slot"] = json!(slot);
|
||||
g["at"] = json!(at);
|
||||
g["value"] = serde_json::to_value(&f.value).expect("value");
|
||||
g
|
||||
}
|
||||
|
||||
/// Every feature the packet carries, with where it sits.
|
||||
fn features(p: &Packet, inv: &Inventory) -> Vec<Value> {
|
||||
let rev = p.inventory_rev;
|
||||
let mut v = Vec::new();
|
||||
for f in &p.discourse.features {
|
||||
v.push(feature_json(inv, rev, "discourse", "discourse", f));
|
||||
}
|
||||
for f in &p.stance.features {
|
||||
v.push(feature_json(inv, rev, "stance", "stance", f));
|
||||
}
|
||||
for r in &p.referents {
|
||||
for f in &r.features {
|
||||
v.push(feature_json(inv, rev, "referent", r.id.as_str(), f));
|
||||
}
|
||||
}
|
||||
for pr in &p.predications {
|
||||
for f in &pr.features {
|
||||
v.push(feature_json(inv, rev, "predication", pr.id.as_str(), f));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Ids the packet chose, once each, with the inventory's gloss at its revision.
|
||||
fn chosen(p: &Packet, inv: &Inventory) -> Vec<Value> {
|
||||
let rev = p.inventory_rev;
|
||||
let mut ids: Vec<InvId> = Vec::new();
|
||||
let mut push = |i: &InvId| {
|
||||
if !ids.contains(i) {
|
||||
ids.push(*i)
|
||||
}
|
||||
};
|
||||
p.context.setting.iter().for_each(&mut push);
|
||||
p.context.medium.iter().for_each(&mut push);
|
||||
p.discourse.speech_act.iter().for_each(&mut push);
|
||||
for r in &p.referents {
|
||||
push(&r.kind);
|
||||
push(&r.concept);
|
||||
}
|
||||
for pr in &p.predications {
|
||||
push(&pr.concept);
|
||||
push(&pr.frame);
|
||||
pr.roles.iter().for_each(|f| push(&f.role));
|
||||
}
|
||||
p.relations.iter().for_each(|r| push(&r.relation));
|
||||
features(p, inv)
|
||||
.iter()
|
||||
.filter_map(|f| f["id"].as_str().and_then(|s| s.parse().ok()))
|
||||
.for_each(|i: InvId| push(&i));
|
||||
ids.iter().map(|i| gloss(inv, rev, i)).collect()
|
||||
}
|
||||
|
||||
fn slots(p: &Packet) -> Value {
|
||||
let j = |v: &dyn erased::Ser| v.to_value();
|
||||
json!({
|
||||
"meaning": {
|
||||
"referents": p.referents.iter().map(|r| j(r)).collect::<Vec<_>>(),
|
||||
"predications": p.predications.iter().map(|r| j(r)).collect::<Vec<_>>(),
|
||||
"relations": p.relations.iter().map(|r| j(r)).collect::<Vec<_>>(),
|
||||
},
|
||||
"stance": j(&p.stance),
|
||||
"discourse": j(&p.discourse),
|
||||
"context": j(&p.context),
|
||||
"extensions": p.extensions.iter().map(|r| j(r)).collect::<Vec<_>>(),
|
||||
"constraints": j(&p.constraints),
|
||||
"provenance": { "source": j(&p.provenance.source), "corpus_item": p.provenance.corpus_item.to_string(), "confidence": p.provenance.confidence.get() },
|
||||
"kind": j(&p.kind),
|
||||
"inventory_rev": p.inventory_rev,
|
||||
})
|
||||
}
|
||||
|
||||
mod erased {
|
||||
pub trait Ser {
|
||||
fn to_value(&self) -> serde_json::Value;
|
||||
}
|
||||
impl<T: serde::Serialize> Ser for T {
|
||||
fn to_value(&self) -> serde_json::Value {
|
||||
serde_json::to_value(self).expect("serialize")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_error(e: &LowerError) -> Value {
|
||||
let (variant, reason) = match e {
|
||||
LowerError::Unrendered { what } => ("Unrendered", format!("the packet carries {what}, which the lowerer does not render")),
|
||||
LowerError::NoRow { id } => ("NoRow", format!("no table row for {id}")),
|
||||
LowerError::GlossMismatch { id, row } => ("GlossMismatch", format!("{id} is not the {row} the row speaks for")),
|
||||
LowerError::UnknownRole { frame, role } => ("UnknownRole", format!("{frame} names role {role}, which the inventory lacks")),
|
||||
LowerError::MissingRole { predication, role } => ("MissingRole", format!("{predication} fills no {role} role")),
|
||||
LowerError::UnknownEntity { entity } => ("UnknownEntity", format!("the entity store does not hold {entity}")),
|
||||
LowerError::NoForm { entity } => ("NoForm", format!("{entity} has no en-US form")),
|
||||
LowerError::NoPronunciation { entity } => ("NoPronunciation", format!("{entity} has no ruled en-US pronunciation")),
|
||||
LowerError::NoEntityReferent => ("NoEntityReferent", "the packet cites no entity".to_string()),
|
||||
LowerError::UnknownPhone { entity, at, .. } => ("UnknownPhone", format!("the ruled pronunciation of {entity} holds a symbol at {at} with no listed phone")),
|
||||
LowerError::DanglingStress { entity, at } => ("DanglingStress", format!("the ruled pronunciation of {entity} has a stress mark at {at} with no vowel after it")),
|
||||
LowerError::ConsentMissing { predication } => ("ConsentMissing", format!("{predication} is a request the packet does not carry the addressee's consent to")),
|
||||
LowerError::AskerNotAddressee { predication } => ("AskerNotAddressee", format!("the agent of {predication} is not the addressee")),
|
||||
LowerError::EntityRead { entity, .. } => ("EntityRead", format!("the entity store failed reading {entity}")),
|
||||
LowerError::SceneUnread => ("SceneUnread", "the view's scene was never read".to_string()),
|
||||
LowerError::SpeakerTokenTaken => ("SpeakerTokenTaken", "a referent cites the entity id the speaker token uses".to_string()),
|
||||
};
|
||||
json!({ "variant": variant, "reason": reason })
|
||||
}
|
||||
|
||||
struct World {
|
||||
inventory: InventoryStore,
|
||||
corpus: CorpusStore,
|
||||
entities: EntityStore,
|
||||
inv: Inventory,
|
||||
}
|
||||
|
||||
/// Admit `packet` through a fresh packet store and lower it. `Ok` carries the
|
||||
/// text and the IPA outcome; `Err` is the refusal, as JSON.
|
||||
fn run(w: &World, dir: &Path, packet: &Packet) -> Result<(String, Value), Value> {
|
||||
let mut store = PacketStore::open(&dir.join("p.cc")).expect("packet store");
|
||||
let view = match store.admit(packet.clone(), &w.inventory, &w.corpus, &w.entities) {
|
||||
Ok(v) => v,
|
||||
Err(StoreError::Invalid(rs)) => {
|
||||
return Err(json!({
|
||||
"kind": "admission_refused",
|
||||
"refusals": rs.iter().map(|r| json!({ "rule": r.rule(), "detail": r.to_string() })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(json!({ "kind": "admission_refused", "refusals": [{ "rule": "store", "detail": e.to_string() }] }));
|
||||
}
|
||||
};
|
||||
let text = lower(&view, &w.inv, &w.entities).map_err(|e| {
|
||||
json!({ "kind": "lower_error", "error": lower_error(&e) })
|
||||
})?;
|
||||
let ipa = match pronounce(&view, &w.entities) {
|
||||
Ok(v) => json!({ "ok": v }),
|
||||
Err(e) => json!({ "error": lower_error(&e) }),
|
||||
};
|
||||
Ok((text, ipa))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let inventory = InventoryStore::open(&root.join("data/interlingua/inventory.cc")).expect("inventory");
|
||||
let inv = inventory.inventory().expect("inventory view");
|
||||
let w = World {
|
||||
corpus: CorpusStore::open(&root.join("data/corpus/corpus.cc")).expect("corpus"),
|
||||
entities: EntityStore::open(&root.join("data/entity/entity.cc")).expect("entities"),
|
||||
inventory,
|
||||
inv,
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("show-working-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
let mut out = Vec::new();
|
||||
for fx in fixtures() {
|
||||
let p = &fx.packet;
|
||||
let first = run(&w, &dir, p);
|
||||
let outcome = match first {
|
||||
Err(e) if e["kind"] == "admission_refused" => e,
|
||||
first => {
|
||||
// Ablation: run again with each feature removed, against the
|
||||
// baseline outcome. It is how the page says whether the lowerer
|
||||
// read a feature, instead of the page asserting it.
|
||||
let base = first.as_ref().ok().map(|(t, _)| t.clone());
|
||||
let n_disc = p.discourse.features.len();
|
||||
let n_stance = p.stance.features.len();
|
||||
let total = features(p, &w.inv).len();
|
||||
let mut effects = Vec::new();
|
||||
for k in 0..total {
|
||||
let mut q = p.clone();
|
||||
if k < n_disc {
|
||||
q.discourse.features.remove(k);
|
||||
} else if k < n_disc + n_stance {
|
||||
q.stance.features.remove(k - n_disc);
|
||||
} else {
|
||||
let mut at = k - n_disc - n_stance;
|
||||
'o: {
|
||||
for r in &mut q.referents {
|
||||
if at < r.features.len() { r.features.remove(at); break 'o; }
|
||||
at -= r.features.len();
|
||||
}
|
||||
for pr in &mut q.predications {
|
||||
if at < pr.features.len() { pr.features.remove(at); break 'o; }
|
||||
at -= pr.features.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(dir.join("p.cc"));
|
||||
effects.push(match (&base, run(&w, &dir, &q)) {
|
||||
(Some(t), Ok((u, _))) if *t == u => "Without it the text is identical: the lowerer did not read it.",
|
||||
(Some(_), Ok(_)) => "Without it the text changes: the lowerer read it.",
|
||||
(Some(_), Err(_)) => "Without it the packet is refused.",
|
||||
(None, Ok(_)) => "Without it the packet lowers: this feature is what the lowerer refuses.",
|
||||
(None, Err(_)) => "Still refused without this feature alone.",
|
||||
});
|
||||
}
|
||||
match first {
|
||||
Ok((text, ipa)) => json!({ "kind": "lowered", "text": text, "ipa": ipa, "feature_effects": effects }),
|
||||
Err(e) => { let mut e = e; e["feature_effects"] = json!(effects); e }
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = std::fs::remove_file(dir.join("p.cc"));
|
||||
let mut slots = slots(p);
|
||||
slots["features"] = json!(features(p, &w.inv));
|
||||
out.push(json!({
|
||||
"id": fx.id,
|
||||
"title": fx.title,
|
||||
"note": fx.note,
|
||||
"source": fx.source,
|
||||
"packet_id": p.id.to_string(),
|
||||
"corpus_item": p.provenance.corpus_item.to_string(),
|
||||
"slots": slots,
|
||||
"chosen": chosen(p, &w.inv),
|
||||
"outcome": outcome,
|
||||
}));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
println!("{}", serde_json::to_string_pretty(&json!({ "fixtures": out })).expect("json"));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn refusal_carries_the_closed_reason_never_a_debug_of_the_error() {
|
||||
// UnknownPhone holds the ruled IPA text; no field of the output may.
|
||||
let e = LowerError::UnknownPhone {
|
||||
entity: EntityId::parse("entity:nibu").expect("entity id"),
|
||||
at: 3,
|
||||
text: "CANARY-IPA".into(),
|
||||
};
|
||||
let v = lower_error(&e);
|
||||
assert!(!v.to_string().contains("CANARY"));
|
||||
let keys: Vec<_> = v.as_object().expect("object").keys().cloned().collect();
|
||||
assert_eq!(keys, ["reason", "variant"]);
|
||||
}
|
||||
}
|
||||
|
|
@ -8,16 +8,7 @@
|
|||
//! consts in this module; every prompt also lists the inventory at the run's
|
||||
//! revision. A mint prompt is the editor's: it reads [`TrainItems`], an
|
||||
//! [`Inventory`] and an [`EditFeedback`] and nothing else, so no held-out text,
|
||||
//! key or per-item score can reach it. A lowering prompt names the language it
|
||||
//! is said in on a language line; every language is named by its tag, none by a
|
||||
//! default. A lowering prompt also prints the target language's ontology
|
||||
//! entries that `ontology::select` chose for the view; the caller never names
|
||||
//! entries.
|
||||
//!
|
||||
//! An ontology mint prompt is a second Train-only prompt: the [`TrainItems`] of
|
||||
//! one language, the inventory's Stance, Discourse and Scene features (the only
|
||||
//! ones a condition can read) and that language's existing entry lines. It reads
|
||||
//! no packet, no score and no held-out text.
|
||||
//! key or per-item score can reach it.
|
||||
//!
|
||||
//! Item text may hold line breaks; the renderer indents every continuation line
|
||||
//! (`indented`), so item text cannot forge a `[key]` line or a paragraph.
|
||||
|
|
@ -33,22 +24,20 @@ use std::marker::PhantomData;
|
|||
use serde::Serialize;
|
||||
|
||||
use crate::corpus::{CorpusItem, CorpusItemId};
|
||||
use crate::inventory::{Inventory, InventoryEntry, OptionLabel, Slot, ValueKind};
|
||||
use crate::lower::{EntityForms, LowerError, entity};
|
||||
use crate::encode::{EntryOntologyDraft, OntologyDraft};
|
||||
use crate::ontology::{Condition, Layer, Ontology, Test, select};
|
||||
use crate::inventory::{Inventory, InventoryEntry, OptionLabel, ValueKind};
|
||||
use crate::lower::{EntityForms, LowerError, TARGET_LANGUAGE, entity};
|
||||
use crate::packet::{
|
||||
Context, Discourse, EntityId, Extension, FeatValue, Grade, Predication, Referent, Relation, Stance,
|
||||
Context, Discourse, EntityId, Extension, Predication, Referent, Relation, Stance,
|
||||
};
|
||||
use crate::run::LADDER_STEP;
|
||||
use crate::split::{Checkpoint, Split, SplitScheme, fnv1a64, hex16};
|
||||
use crate::store::{CorpusStore, normalized};
|
||||
use crate::validate::{LoweringInput, SceneRead};
|
||||
use crate::validate::LoweringInput;
|
||||
|
||||
/// The instructions a mint prompt starts with: the editor's whole brief. Fixed
|
||||
/// per run by `PROMPT_SOURCE_DIGEST`.
|
||||
pub const MINT_INSTRUCTIONS: &str = "\
|
||||
Propose one edit to the inventory below, so that the lines below can be encoded and lowered, each in its own language, more faithfully.
|
||||
Propose one edit to the inventory below, so that the lines below can be encoded and lowered to English more faithfully.
|
||||
Answer with one JSON object and nothing else: no code fence, no commentary.
|
||||
Shape: {\"add\": [{\"family\", \"gloss\", \"value_kind\", \"applies_to\"}], \"retire\": [ids]}; 1 to 8 changes in all, adds and retires together.
|
||||
- family: one of Concept, Frame, Role, Relation, SpeechAct, Feature, ReferentKind, Extension.
|
||||
|
|
@ -70,14 +59,14 @@ Fields:
|
|||
- predications: a list of {id, concept, frame, roles, features}; roles is a list of {role, filler}, filler a node id.
|
||||
- relations: a list of {relation, from, to, features}.
|
||||
- stance: {features}; the speaker's felt affect and restraint, never the affect the line displays.
|
||||
Node ids are n1, n2, and so on, one per referent and predication. Every other id comes from the inventory listed below and must be live at its revision. Write each id in full, exactly as the inventory lines spell it, family prefix included: concept:7, never 7. An entity comes only from the entities line. A referent's concept is never null, even when it carries an entity: give the nearest concept id. Participants and audience list the node ids of referents, never an entity id: an entity speaker is a referent whose entity field holds it, and participants lists that referent's node id. A predication holds each role at most once, and a feature list each feature at most once: two or more fillers of one role are one referent of kind group that fills the role, and each member is related to it by a member_of relation from the member to the group.
|
||||
Node ids are n1, n2, and so on, one per referent and predication. Every other id comes from the inventory listed below and must be live at its revision. Write each id in full, exactly as the inventory lines spell it, family prefix included: concept:7, never 7. An entity comes only from the entities line.
|
||||
A feature is {feature, value}; value is {\"Grade\": 0 to 1000}, {\"Option\": label} or {\"Flag\": true or false}, as the inventory lists the feature's kind.";
|
||||
|
||||
/// The instructions a lowering prompt starts with: the lowerer's whole brief.
|
||||
/// Fixed per run by `PROMPT_SOURCE_DIGEST`.
|
||||
pub const LOWER_INSTRUCTIONS: &str = "\
|
||||
Say the packet below in the language on the language line, as one utterance of its speaker: all of its meaning and nothing it does not carry.
|
||||
Every id is the inventory's listed below and every feature value is as listed; a grade is permille, 0 to 1000. The stance is the speaker's felt affect and restraint: it shapes how the utterance is said, not what it says. The ontology lines are choices this language makes for this speaker, stance and scene: realize each where the packet allows; they add no meaning.
|
||||
Say the packet below in English (en-US), as one utterance of its speaker: all of its meaning and nothing it does not carry.
|
||||
Every id is the inventory's listed below and every feature value is as listed. The stance is the speaker's felt affect and restraint: it shapes how the utterance is said, not what it says.
|
||||
A referent with an entity is named by one of that entity's forms on the entities line.
|
||||
Answer with one JSON object and nothing else: {\"text\": \"...\"}. No code fence, no commentary.";
|
||||
|
||||
|
|
@ -88,25 +77,18 @@ pub const RECALL_INSTRUCTIONS: &str = "\
|
|||
Below is the opening of a passage, with what is known of where it comes from. Continue it exactly as its source words it, from memory, until the passage ends. If you do not remember it, give your best guess in the same voice.
|
||||
Answer with one JSON object and nothing else: {\"text\": \"...\"}, the continuation only, not the opening. No code fence, no commentary.";
|
||||
|
||||
/// The instructions of an ontology mint: drafting entries for one language from
|
||||
/// its Train lines. Fixed per run by `PROMPT_SOURCE_DIGEST`.
|
||||
pub const MINT_ONTOLOGY_INSTRUCTIONS: &str = "\
|
||||
Below are lines written in one language (the language line), the features an ontology condition may test, and the entries that language's ontology already has. Draft new entries: choices this language's culture makes, for a speaker in a stance and scene, about word, grammar, discourse, sound or script, that the lines show.
|
||||
Answer with one JSON object and nothing else: {\"entries\": [{\"layer\": \"...\", \"when\": [...], \"choice\": \"...\", \"examples\": [...]}]}. No code fence, no commentary.
|
||||
Give only entries the lines show, as many as they support (a language holds at most 64 in all). layer is exactly one of Lexicon, Grammar, Discourse, Phonology, Orthography. when holds at most 4 conditions, each {\"slot\": \"Stance\" | \"Discourse\" | \"Scene\", \"feature\": \"<id>\", \"test\": ...}, where <id> is the id printed before the colon of a listed feature (\"feature:10\", never its name) and its slot is one that feature lists. test is {\"AtLeast\": <permille>}, {\"AtMost\": <permille>} or {\"AtMostOrUnset\": <permille>} on a grade feature, or {\"Is\": {\"Option\": \"<label>\"}} on an options feature with one of its labels, or {\"Is\": {\"Flag\": true}} on a flag feature. The example line shows each form on listed features; its choice and examples are placeholders, not content to copy. when may be empty when a choice holds for every line of the language. choice states a pattern the lines show, in at most 200 bytes, without quoting a line. examples are original short phrases of the language, never copied from the lines below, at most 3, each at most 120 bytes.";
|
||||
|
||||
/// The live Train items of a corpus, in key order. The only input minting
|
||||
/// reads; it cannot be built from a slice, and no accessor returns text or an
|
||||
/// item.
|
||||
///
|
||||
/// ```no_run
|
||||
/// ```
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let panel = ["en-US".to_string()];
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &panel).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let _ = t.len();
|
||||
/// assert!(t.is_empty());
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
|
|
@ -116,9 +98,9 @@ Give only entries the lines show, as many as they support (a language holds at m
|
|||
/// ```compile_fail
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let _u = t.clone();
|
||||
/// ```
|
||||
|
|
@ -127,9 +109,9 @@ Give only entries the lines show, as many as they support (a language holds at m
|
|||
/// fn s<T: serde::Serialize>(_: &T) {}
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// s(&t);
|
||||
/// ```
|
||||
|
|
@ -138,14 +120,11 @@ pub struct TrainItems {
|
|||
}
|
||||
|
||||
impl TrainItems {
|
||||
/// The live Train items whose language is in `panel`.
|
||||
pub(crate) fn from_corpus(corpus: &CorpusStore, panel: &[String]) -> anyhow::Result<Self> {
|
||||
pub(crate) fn from_corpus(corpus: &CorpusStore) -> anyhow::Result<Self> {
|
||||
let items = corpus
|
||||
.all()?
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
SplitScheme::V1.live(item) == Some(Split::Train) && panel.contains(&item.language)
|
||||
})
|
||||
.filter(|item| SplitScheme::V1.live(item) == Some(Split::Train))
|
||||
.collect();
|
||||
Ok(Self { items })
|
||||
}
|
||||
|
|
@ -273,13 +252,11 @@ impl<'cp> EncoderOffer<'cp> {
|
|||
}
|
||||
|
||||
/// What the editor is told of how its last edit fared: whether it was kept, and
|
||||
/// the held-out composite at the current inventory of each panel language,
|
||||
/// rounded to the nearest [`LADDER_STEP`]. The heads change only when an edit is
|
||||
/// accepted, and an accept raises the panel's composite sum by more than one
|
||||
/// step, so a run over `L` languages releases at most `1.5 * L / LADDER_STEP`
|
||||
/// changes of this line (Blum and Hardt 2015, the Ladder; ruling
|
||||
/// `weksa-lowering:ruling:panel-accept-sum-rule`). Nothing else about the
|
||||
/// held-out split is a field.
|
||||
/// the held-out composite at the current inventory, rounded to the nearest
|
||||
/// [`LADDER_STEP`]. The head composite changes only when an edit is accepted and
|
||||
/// an accept needs a gain above one step, so a run releases at most
|
||||
/// `1 / LADDER_STEP` distinct values (Blum and Hardt 2015, the Ladder). Nothing
|
||||
/// else about the held-out split is a field.
|
||||
///
|
||||
/// ```
|
||||
/// let f = weksa::context::EditFeedback::none();
|
||||
|
|
@ -289,18 +266,18 @@ impl<'cp> EncoderOffer<'cp> {
|
|||
/// Its fields are private:
|
||||
///
|
||||
/// ```compile_fail,E0451
|
||||
/// let _ = weksa::context::EditFeedback { last: None, head: vec![] };
|
||||
/// let _ = weksa::context::EditFeedback { last: None, head: None };
|
||||
/// ```
|
||||
///
|
||||
/// and only the run builds one with a reading:
|
||||
///
|
||||
/// ```compile_fail,E0624
|
||||
/// let _ = weksa::context::EditFeedback::new(Some(true), vec![]);
|
||||
/// let _ = weksa::context::EditFeedback::new(Some(true), Some(0.5));
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EditFeedback {
|
||||
last: Option<bool>,
|
||||
head: Vec<(String, f64)>,
|
||||
head: Option<f64>,
|
||||
}
|
||||
|
||||
impl EditFeedback {
|
||||
|
|
@ -308,20 +285,16 @@ impl EditFeedback {
|
|||
pub fn none() -> Self {
|
||||
Self {
|
||||
last: None,
|
||||
head: Vec::new(),
|
||||
head: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `last`: whether the previous edit was accepted; `head`: each panel
|
||||
/// language's composite at the current inventory, in panel order, rounded
|
||||
/// here to the nearest [`LADDER_STEP`].
|
||||
pub(crate) fn new(last: Option<bool>, head: Vec<(String, f64)>) -> Self {
|
||||
/// `last`: whether the previous edit was accepted; `head`: the composite at
|
||||
/// the current inventory, rounded here to the nearest [`LADDER_STEP`].
|
||||
pub(crate) fn new(last: Option<bool>, head: Option<f64>) -> Self {
|
||||
Self {
|
||||
last,
|
||||
head: head
|
||||
.into_iter()
|
||||
.map(|(tag, x)| (tag, (x / LADDER_STEP).round() * LADDER_STEP))
|
||||
.collect(),
|
||||
head: head.map(|x| (x / LADDER_STEP).round() * LADDER_STEP),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -331,15 +304,7 @@ impl EditFeedback {
|
|||
Some(false) => "rejected",
|
||||
None => "none",
|
||||
};
|
||||
let head = if self.head.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
self.head
|
||||
.iter()
|
||||
.map(|(tag, x)| format!("{tag} {x:.3}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
};
|
||||
let head = self.head.map_or("none".to_string(), |x| format!("{x:.3}"));
|
||||
format!("last edit: {last}; validation composite at head: {head}")
|
||||
}
|
||||
}
|
||||
|
|
@ -347,12 +312,12 @@ impl EditFeedback {
|
|||
/// Text for a model call, and the keys of the items it holds. The only
|
||||
/// constructors are [`Prompt::mint`], [`Prompt::encode`] and [`Prompt::lower`].
|
||||
///
|
||||
/// ```no_run
|
||||
/// ```
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let panel = ["en-US".to_string()];
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &panel).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let inv = run.inventory().inventory().unwrap();
|
||||
/// let feedback = weksa::context::EditFeedback::none();
|
||||
|
|
@ -368,9 +333,9 @@ impl EditFeedback {
|
|||
/// ```compile_fail,E0061
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let inv = run.inventory().inventory().unwrap();
|
||||
/// let feedback = weksa::context::EditFeedback::none();
|
||||
|
|
@ -381,9 +346,9 @@ impl EditFeedback {
|
|||
/// fn s<T: serde::Serialize>(_: &T) {}
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc"), speaker_state: &p("s.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap();
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded).unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let inv = run.inventory().inventory().unwrap();
|
||||
/// let feedback = weksa::context::EditFeedback::none();
|
||||
|
|
@ -467,53 +432,6 @@ fn entry_line(entry: &InventoryEntry) -> String {
|
|||
line
|
||||
}
|
||||
|
||||
/// The slot a condition on `entry` reads it in: the first of its slots a
|
||||
/// lowering view carries.
|
||||
fn condition_slot(entry: &InventoryEntry) -> Option<Slot> {
|
||||
entry
|
||||
.applies_to
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|s| matches!(s, Slot::Stance | Slot::Discourse | Slot::Scene))
|
||||
}
|
||||
|
||||
/// One entry in the form the admit door reads, serialized from its own draft
|
||||
/// type so the taught shape cannot drift from the door: a condition on the
|
||||
/// first listed grade, options and flag feature each, over placeholder text.
|
||||
fn mint_example(readable: &[&InventoryEntry]) -> String {
|
||||
let when = [
|
||||
readable.iter().find(|e| e.value_kind == Some(ValueKind::Grade)).map(|e| {
|
||||
(e, Test::AtLeast(Grade::new(500).expect("500 is a permille")))
|
||||
}),
|
||||
readable.iter().find_map(|e| match &e.value_kind {
|
||||
Some(ValueKind::Options(set)) => {
|
||||
let first = Vec::<OptionLabel>::from(set.clone()).remove(0);
|
||||
Some((e, Test::Is(FeatValue::Option(first))))
|
||||
}
|
||||
_ => None,
|
||||
}),
|
||||
readable
|
||||
.iter()
|
||||
.find(|e| e.value_kind == Some(ValueKind::Flag))
|
||||
.map(|e| (e, Test::Is(FeatValue::Flag(true)))),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|(e, test)| {
|
||||
Some(Condition { slot: condition_slot(e)?, feature: e.id, test })
|
||||
})
|
||||
.collect();
|
||||
let draft = OntologyDraft {
|
||||
entries: vec![EntryOntologyDraft {
|
||||
layer: Layer::Grammar,
|
||||
when,
|
||||
choice: "a pattern the lines show".into(),
|
||||
examples: vec!["a short phrase of your own".into()],
|
||||
}],
|
||||
};
|
||||
serde_json::to_string(&draft).expect("a draft serializes")
|
||||
}
|
||||
|
||||
/// Each entry of `inventory` live at `rev`, one `\n` and one line apiece: the
|
||||
/// listing both prompts print under `inventory rev:<rev>`.
|
||||
fn inventory_lines(inventory: &Inventory, rev: u32) -> String {
|
||||
|
|
@ -538,13 +456,6 @@ struct Meaning<'a> {
|
|||
stance: &'a Stance,
|
||||
}
|
||||
|
||||
/// What the lowering prompt prints in place of the item's speaker's entity id:
|
||||
/// one constant, the same for every speaker and every item, so no id and
|
||||
/// nothing derived from one reaches the lowerer. It parses as an entity id so
|
||||
/// the packet keeps its shape. A real entity of this id is refused at lowering
|
||||
/// ([`LowerError::SpeakerTokenTaken`]); the entity store does not reserve it.
|
||||
pub const SPEAKER_TOKEN: &str = "entity:speaker";
|
||||
|
||||
/// Printed in place of a prior turn whose text no live Train item holds.
|
||||
const ELIDED: &str = "[elided]";
|
||||
|
||||
|
|
@ -569,51 +480,6 @@ impl Prompt {
|
|||
}
|
||||
}
|
||||
|
||||
/// [`MINT_ONTOLOGY_INSTRUCTIONS`], the `language` line, the Stance,
|
||||
/// Discourse and Scene features of `inventory` live at `rev` (grade, flag or
|
||||
/// options: all a condition can read), the entries `ontology` already holds
|
||||
/// for `language` as `<key> <choice>`, then the Train items of exactly
|
||||
/// `language` in key order without prior turns. `None` when there is none.
|
||||
pub(crate) fn mint_ontology(
|
||||
train: &TrainItems,
|
||||
language: &str,
|
||||
inventory: &Inventory,
|
||||
rev: u32,
|
||||
ontology: &Ontology,
|
||||
) -> Option<Prompt> {
|
||||
let items: Vec<&CorpusItem> = train
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.language == language)
|
||||
.collect();
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let readable: Vec<&InventoryEntry> = inventory
|
||||
.entries()
|
||||
.filter(|e| e.live_at(rev) && e.value_kind.is_some() && condition_slot(e).is_some())
|
||||
.collect();
|
||||
let features: String = readable.iter().map(|e| format!("\n{}", entry_line(e))).collect();
|
||||
let existing: String = ontology
|
||||
.entries()
|
||||
.iter()
|
||||
.filter(|e| e.language == language)
|
||||
.map(|e| format!("\n{} {}", e.key(), e.choice))
|
||||
.collect();
|
||||
let mut parts = vec![
|
||||
MINT_ONTOLOGY_INSTRUCTIONS.to_string(),
|
||||
format!("language: {language}"),
|
||||
format!("features rev:{rev}{features}"),
|
||||
format!("entries{existing}"),
|
||||
format!("example {}", mint_example(&readable)),
|
||||
];
|
||||
parts.extend(items.iter().map(|item| block(item, None)));
|
||||
Some(Prompt {
|
||||
text: parts.join("\n\n"),
|
||||
items: items.iter().map(|item| item.id.as_str().to_string()).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ENCODE_INSTRUCTIONS`], the one offered item with its prior turns resolved
|
||||
/// against `train`, the entities a packet for it may cite, and the entries
|
||||
/// of `inventory` live at `rev`.
|
||||
|
|
@ -636,63 +502,25 @@ impl Prompt {
|
|||
}
|
||||
}
|
||||
|
||||
/// [`LOWER_INSTRUCTIONS`], the `language: <tag>` line, the meaning of
|
||||
/// `input` (no kind, constraints, scene, speaker or group), the forms in
|
||||
/// `language` of every entity its referents cite, the `ontology:` section
|
||||
/// and the entries of `inventory` live at the view's revision. The section
|
||||
/// holds the entries `ontology::select` chooses from the view's stance,
|
||||
/// discourse and the scene relation `with_scene` read, and `language`,
|
||||
/// never the caller; the scene's values are never printed, only the entries
|
||||
/// they select. `item` goes only to [`Prompt::item_keys`], never into the
|
||||
/// text. `speaker` is the item's speaker: its id is never printed. The
|
||||
/// promise guards the id that names an entity of this item, not the
|
||||
/// speaker's forms, which every item of the language shares. A referent
|
||||
/// citing the speaker is printed with [`SPEAKER_TOKEN`] as its entity, and
|
||||
/// the entities line holds the speaker's forms under that token. A speaker
|
||||
/// the language has no form for, or the port lacks, does not refuse: its
|
||||
/// referents print no entity and the line has no entry. Any other cited
|
||||
/// entity is printed under its own id with its forms; one the port lacks,
|
||||
/// or one with no form in `language`, is an error and no prompt. A
|
||||
/// referent citing the token's own id as an entity is
|
||||
/// [`LowerError::SpeakerTokenTaken`]. The caller chooses the language; the
|
||||
/// view has none.
|
||||
/// [`LOWER_INSTRUCTIONS`], the meaning of `input` (no kind, constraints,
|
||||
/// scene, speaker or group), the en-US forms of every entity its referents
|
||||
/// cite, and the entries of `inventory` live at the view's revision. `item`
|
||||
/// goes only to [`Prompt::item_keys`], never into the text. The view's
|
||||
/// speaker and group fields are never read; a speaker's entity id appears
|
||||
/// only when the encoder cites that entity on a referent, which is naming a
|
||||
/// cited entity like any other. A cited entity the port lacks, or one with
|
||||
/// no en-US form, is an error and no prompt.
|
||||
pub fn lower(
|
||||
input: &LoweringInput,
|
||||
item: &CorpusItemId,
|
||||
speaker: &EntityId,
|
||||
language: &str,
|
||||
inventory: &Inventory,
|
||||
entities: &dyn EntityForms,
|
||||
ontology: &Ontology,
|
||||
) -> Result<Prompt, LowerError> {
|
||||
if input.scene_read() == &SceneRead::Unread {
|
||||
return Err(LowerError::SceneUnread);
|
||||
}
|
||||
let token = EntityId::parse(SPEAKER_TOKEN).expect("the token is an entity id");
|
||||
let mut referents = input.referents().to_vec();
|
||||
if referents.iter().any(|r| r.entity.as_ref() == Some(&token)) {
|
||||
return Err(LowerError::SpeakerTokenTaken);
|
||||
}
|
||||
let mut forms: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
if referents.iter().any(|r| r.entity.as_ref() == Some(speaker)) {
|
||||
let spoken = match entity(entities, speaker) {
|
||||
Ok(found) => found.forms_in(language).filter(|f| !f.is_empty()).map(<[String]>::to_vec),
|
||||
Err(LowerError::UnknownEntity { .. }) => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Some(spoken) = &spoken {
|
||||
forms.insert(token.as_str(), spoken.clone());
|
||||
}
|
||||
for referent in &mut referents {
|
||||
if referent.entity.as_ref() == Some(speaker) {
|
||||
referent.entity = spoken.as_ref().map(|_| token.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in referents.iter().filter_map(|r| r.entity.as_ref()).filter(|id| *id != &token) {
|
||||
for id in input.referents().iter().filter_map(|r| r.entity.as_ref()) {
|
||||
let found = entity(entities, id)?;
|
||||
let named = found
|
||||
.forms_in(language)
|
||||
.forms_in(TARGET_LANGUAGE)
|
||||
.filter(|f| !f.is_empty())
|
||||
.ok_or_else(|| LowerError::NoForm { entity: id.clone() })?;
|
||||
forms.insert(id.as_str(), named.to_vec());
|
||||
|
|
@ -700,26 +528,15 @@ impl Prompt {
|
|||
let meaning = Meaning {
|
||||
context: input.context(),
|
||||
discourse: input.discourse(),
|
||||
referents: &referents,
|
||||
referents: input.referents(),
|
||||
predications: input.predications(),
|
||||
relations: input.relations(),
|
||||
extensions: input.extensions(),
|
||||
stance: input.stance(),
|
||||
};
|
||||
let rev = input.inventory_rev();
|
||||
let chosen = select(ontology, language, input);
|
||||
let mut lines = String::new();
|
||||
for e in &chosen {
|
||||
lines.push_str(&format!("\n{} [{}] {}", e.key(), e.layer.name(), e.choice));
|
||||
for x in &e.examples {
|
||||
lines.push_str(&format!(" | e.g. {x}"));
|
||||
}
|
||||
}
|
||||
if chosen.is_empty() {
|
||||
lines.push_str(" none");
|
||||
}
|
||||
let text = format!(
|
||||
"{LOWER_INSTRUCTIONS}\n\nlanguage: {language}\n\npacket: {}\n\nentities: {}\n\nontology:{lines}\n\ninventory rev:{rev}{}",
|
||||
"{LOWER_INSTRUCTIONS}\n\npacket: {}\n\nentities: {}\n\ninventory rev:{rev}{}",
|
||||
serde_json::to_string(&meaning).expect("a meaning is plain data"),
|
||||
serde_json::to_string(&forms).expect("forms are plain data"),
|
||||
inventory_lines(inventory, rev)
|
||||
|
|
@ -766,62 +583,34 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn the_feedback_line_prints_exact_values() {
|
||||
let en = |x: f64| vec![("en-US".to_string(), x)];
|
||||
let line = |last, head| EditFeedback::new(last, head).line();
|
||||
assert_eq!(
|
||||
EditFeedback::none().line(),
|
||||
"last edit: none; validation composite at head: none"
|
||||
);
|
||||
assert_eq!(
|
||||
line(Some(true), en(0.5)),
|
||||
"last edit: accepted; validation composite at head: en-US 0.500"
|
||||
line(Some(true), Some(0.5)),
|
||||
"last edit: accepted; validation composite at head: 0.500"
|
||||
);
|
||||
assert_eq!(
|
||||
line(Some(false), en(0.0)),
|
||||
"last edit: rejected; validation composite at head: en-US 0.000"
|
||||
line(Some(false), Some(0.0)),
|
||||
"last edit: rejected; validation composite at head: 0.000"
|
||||
);
|
||||
assert_eq!(line(None, vec![]), EditFeedback::none().line());
|
||||
assert_eq!(line(None, None), EditFeedback::none().line());
|
||||
// The head is rounded to the nearest step before it is printed.
|
||||
assert_eq!(
|
||||
line(None, en(0.5012)),
|
||||
"last edit: none; validation composite at head: en-US 0.500"
|
||||
line(None, Some(0.5012)),
|
||||
"last edit: none; validation composite at head: 0.500"
|
||||
);
|
||||
assert_eq!(
|
||||
line(None, en(0.5026)),
|
||||
"last edit: none; validation composite at head: en-US 0.505"
|
||||
line(None, Some(0.5026)),
|
||||
"last edit: none; validation composite at head: 0.505"
|
||||
);
|
||||
assert_eq!(
|
||||
line(None, en(0.9999)),
|
||||
"last edit: none; validation composite at head: en-US 1.000"
|
||||
line(None, Some(0.9999)),
|
||||
"last edit: none; validation composite at head: 1.000"
|
||||
);
|
||||
// One value per panel language, in the order given.
|
||||
assert_eq!(
|
||||
line(None, vec![("en-US".into(), 0.5026), ("ja-JP".into(), 0.41)]),
|
||||
"last edit: none; validation composite at head: en-US 0.505, ja-JP 0.410"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ontology_mint_over_no_item_of_the_language_is_no_prompt() {
|
||||
let inv = Inventory::default();
|
||||
let train = TrainItems { items: vec![] };
|
||||
assert!(Prompt::mint_ontology(&train, "en-US", &inv, 1, &Ontology::empty()).is_none());
|
||||
let mut held = item("item:a:1", "x", &group_in(Split::Train), false);
|
||||
held.language = "ja-JP".into();
|
||||
let train = TrainItems { items: vec![held] };
|
||||
assert!(Prompt::mint_ontology(&train, "en-US", &inv, 1, &Ontology::empty()).is_none());
|
||||
assert!(Prompt::mint_ontology(&train, "ja-JP", &inv, 1, &Ontology::empty()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mint_prompt_over_no_train_items_is_the_brief_the_feedback_and_the_listing() {
|
||||
let none = TrainItems { items: vec![] };
|
||||
let prompt = Prompt::mint(&none, &Inventory::default(), 0, &EditFeedback::none());
|
||||
assert_eq!(
|
||||
prompt.text(),
|
||||
format!("{MINT_INSTRUCTIONS}\n\nlast edit: none; validation composite at head: none\n\ninventory rev:0")
|
||||
);
|
||||
assert!(prompt.item_keys().is_empty());
|
||||
assert_eq!(EditFeedback::new(None, Some(0.5026)).head, Some(0.505));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -957,12 +746,6 @@ mod tests {
|
|||
const SEPS: [&str; 8] = ["\n", "\r\n", "\r", "\u{b}", "\u{c}", "\u{85}", "\u{2028}", "\u{2029}"];
|
||||
let is_sep = |c: char| matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}');
|
||||
let g = group_in(Split::Train);
|
||||
// The escape itself, not through `str::lines`: one break per separator
|
||||
// (CRLF is one), rendered as a newline and two spaces.
|
||||
for sep in SEPS {
|
||||
assert_eq!(indented(&format!("a{sep}b")), "a\n b", "{sep:?}");
|
||||
}
|
||||
assert_eq!(indented("a\r\n\r\nb"), "a\n \n b");
|
||||
for sep in SEPS {
|
||||
let it = item("item:a:1", &format!("hi{sep}[item:z:9] x"), &g, false);
|
||||
let out = block(&it, None);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ 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 {
|
||||
|
|
@ -33,7 +32,7 @@ pub enum Source {
|
|||
/// 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
|
||||
/// not the original's) and when the edition appeared. A work missing any
|
||||
/// is refused at admission.
|
||||
PublicDomain {
|
||||
work: String,
|
||||
|
|
@ -42,10 +41,6 @@ pub enum Source {
|
|||
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
|
||||
|
|
@ -104,11 +99,6 @@ pub struct CorpusItem {
|
|||
/// 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 {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@
|
|||
//! provenance, constraints and extensions, and an empty trace, so a model that
|
||||
//! saw a Validation item cannot hand its words to whoever reads packets. The
|
||||
//! editor writes family, gloss, value kind and slots only; `into_revision` sets
|
||||
//! every id and revision number. The public-domain intake file (`WorkDraft`) and
|
||||
//! its name-span answer (`MarkedLine`) are read here too.
|
||||
//! every id and revision number.
|
||||
|
||||
use std::fmt;
|
||||
use std::num::NonZeroU32;
|
||||
|
|
@ -16,21 +15,14 @@ use std::num::NonZeroU32;
|
|||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
use crate::corpus::{CorpusItem, CorpusItemId, NameSpan, Source, item_key};
|
||||
use crate::entity::{Entity, EntityOrigin, LanguageForms};
|
||||
use crate::form::is_slug;
|
||||
use crate::packet::EntityId;
|
||||
use crate::corpus::CorpusItemId;
|
||||
use crate::inventory::{
|
||||
Change, Family, InvId, Inventory, InventoryEntry, InventoryRevision, Slot, ValueKind,
|
||||
};
|
||||
use crate::ontology::{Condition, Layer, OntologyEntry};
|
||||
use crate::packet::{
|
||||
Constraints, Context, Discourse, EncoderId, Grade, Packet, PacketId, PacketKind, Predication,
|
||||
Provenance, ProvenanceSource, Referent, Relation, SCHEMA_VERSION, Stance, Trace,
|
||||
};
|
||||
use crate::speaker::Annotator;
|
||||
use crate::split::{fnv1a64, hex16};
|
||||
|
||||
/// The meaning fields of a packet, as a model writes them.
|
||||
|
|
@ -102,27 +94,24 @@ impl DraftClass {
|
|||
Category::Syntax => DraftClass::Syntax,
|
||||
Category::Eof => DraftClass::Eof,
|
||||
Category::Io => DraftClass::Other,
|
||||
Category::Data => Self::of_data(&e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// serde_json offers no kind for a data error: its message opens with serde's
|
||||
/// own fixed words, or with a [`crate::form::FormError`]'s `not a `. Only
|
||||
/// those words are read, to pick a class; the message is not kept, and any
|
||||
/// other opening is [`DraftClass::Other`].
|
||||
fn of_data(msg: &str) -> Self {
|
||||
if msg.starts_with("missing field") {
|
||||
DraftClass::MissingField
|
||||
} else if msg.starts_with("unknown field") {
|
||||
DraftClass::UnknownField
|
||||
} else if msg.starts_with("invalid type") {
|
||||
DraftClass::InvalidType
|
||||
} else if msg.starts_with("invalid value") {
|
||||
DraftClass::InvalidValue
|
||||
} else if msg.starts_with("not a ") {
|
||||
DraftClass::BadForm
|
||||
} else {
|
||||
DraftClass::Other
|
||||
// Only the leading words of serde's message are read, and only to
|
||||
// pick one of these classes; the message is not kept.
|
||||
Category::Data => {
|
||||
let msg = e.to_string();
|
||||
if msg.starts_with("missing field") {
|
||||
DraftClass::MissingField
|
||||
} else if msg.starts_with("unknown field") {
|
||||
DraftClass::UnknownField
|
||||
} else if msg.starts_with("invalid type") {
|
||||
DraftClass::InvalidType
|
||||
} else if msg.starts_with("invalid value") {
|
||||
DraftClass::InvalidValue
|
||||
} else if msg.starts_with("not a ") {
|
||||
DraftClass::BadForm
|
||||
} else {
|
||||
DraftClass::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -229,22 +218,19 @@ impl EditDraft {
|
|||
}
|
||||
|
||||
/// The revision after `base` this edit asks for, and the entries it adds.
|
||||
/// `None` when the edit makes no change or more than `max_changes`. The
|
||||
/// loop's cycle passes [`MAX_EDIT_CHANGES`]; the CLI's `inventory admit`
|
||||
/// passes its own larger cap for a draft reviewed whole in its cut.
|
||||
/// `None` when the edit makes no change or more than [`MAX_EDIT_CHANGES`].
|
||||
/// Every id is the store's: an added entry takes the next number of its
|
||||
/// family after the highest in `inventory`, retired entries included, in
|
||||
/// draft order. Nothing else is judged here: the gloss, the entry's shape,
|
||||
/// whether a retire target is live and a repeated id are
|
||||
/// `InventoryStore::admit_revision`'s to refuse.
|
||||
pub fn into_revision(
|
||||
pub(crate) fn into_revision(
|
||||
self,
|
||||
inventory: &Inventory,
|
||||
base: u32,
|
||||
max_changes: usize,
|
||||
) -> Option<(InventoryRevision, Vec<InventoryEntry>)> {
|
||||
let count = self.add.len() + self.retire.len();
|
||||
if count == 0 || count > max_changes {
|
||||
if count == 0 || count > MAX_EDIT_CHANGES {
|
||||
return None;
|
||||
}
|
||||
let n = base.checked_add(1)?;
|
||||
|
|
@ -282,59 +268,6 @@ impl EditDraft {
|
|||
}
|
||||
}
|
||||
|
||||
/// One ontology entry as a model writes it: no language, number, inventory
|
||||
/// revision or annotator.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EntryOntologyDraft {
|
||||
pub layer: Layer,
|
||||
#[serde(default)]
|
||||
pub when: Vec<Condition>,
|
||||
pub choice: String,
|
||||
#[serde(default)]
|
||||
pub examples: Vec<String>,
|
||||
}
|
||||
|
||||
/// A batch of ontology entries as a model drafts them: the xenos door of a
|
||||
/// seed answer.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OntologyDraft {
|
||||
pub entries: Vec<EntryOntologyDraft>,
|
||||
}
|
||||
|
||||
impl OntologyDraft {
|
||||
pub fn parse(answer: &str) -> Result<Self, DraftError> {
|
||||
from_json(answer)
|
||||
}
|
||||
|
||||
/// The entries this draft becomes: numbered from `first_n` in draft order,
|
||||
/// all of `language` read at `inventory_rev`, annotated `annotator`.
|
||||
/// Whether they are admissible is `OntologyStore::admit`'s to refuse.
|
||||
pub fn into_entries(
|
||||
self,
|
||||
language: &str,
|
||||
inventory_rev: u32,
|
||||
first_n: u32,
|
||||
annotator: &Annotator,
|
||||
) -> Vec<OntologyEntry> {
|
||||
self.entries
|
||||
.into_iter()
|
||||
.zip(first_n..)
|
||||
.map(|(d, n)| OntologyEntry {
|
||||
language: language.to_string(),
|
||||
n,
|
||||
inventory_rev,
|
||||
layer: d.layer,
|
||||
when: d.when,
|
||||
choice: d.choice,
|
||||
examples: d.examples,
|
||||
annotator: annotator.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A lowering as the lowerer writes it: the English text, nothing else.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
|
@ -364,196 +297,6 @@ impl LoweringDraft {
|
|||
}
|
||||
}
|
||||
|
||||
/// One cast member of a work: the entity and the forms the work spells it with,
|
||||
/// in the work's language, citation form first.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CastDraft {
|
||||
pub entity: EntityId,
|
||||
pub forms: Vec<String>,
|
||||
}
|
||||
|
||||
/// One line of a work: its scene group, the speaker its speech prefix names, text.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LineDraft {
|
||||
pub group: String,
|
||||
pub speaker: EntityId,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// A transcription of a public-domain work in hand: provenance, cast forms,
|
||||
/// lines, scene groups and the speaker each speech prefix names. It holds no
|
||||
/// distributor header, licence or trademark text, and nothing reads a URL.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkDraft {
|
||||
pub slug: String,
|
||||
pub language: String,
|
||||
pub admitted_on: String,
|
||||
pub source: Source,
|
||||
pub cast: Vec<CastDraft>,
|
||||
pub lines: Vec<LineDraft>,
|
||||
}
|
||||
|
||||
/// One line of a name-span answer: the line number and the line copied with
|
||||
/// `[[entity:<slug>|<form>]]` around each place it names a cast member.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MarkedLine {
|
||||
pub line: u32,
|
||||
pub marked: String,
|
||||
}
|
||||
|
||||
impl MarkedLine {
|
||||
pub fn parse(answer: &str) -> Result<Self, DraftError> {
|
||||
from_json(answer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an import was refused before any document was written. The text names
|
||||
/// the kind and the line number only, never a value.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportRefusal {
|
||||
NotPublicDomain,
|
||||
CastRepeated,
|
||||
NoSuchLine { line: u32 },
|
||||
LineMarkedTwice { line: u32 },
|
||||
Group { line: u32 },
|
||||
SpeakerNotInCast { line: u32 },
|
||||
Markup { line: u32 },
|
||||
NotInCast { line: u32 },
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportRefusal {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotPublicDomain => write!(f, "the work's source is not public domain"),
|
||||
Self::CastRepeated => write!(f, "a cast entity is listed twice"),
|
||||
Self::NoSuchLine { line } => write!(f, "the answer marks a line that is not there (line {line})"),
|
||||
Self::LineMarkedTwice { line } => write!(f, "line {line} is marked twice"),
|
||||
Self::Group { line } => write!(f, "the group of line {line} is not a slug"),
|
||||
Self::SpeakerNotInCast { line } => write!(f, "the speaker of line {line} is not in the cast"),
|
||||
Self::Markup { line } => write!(f, "the marked text of line {line} is not its text with markup"),
|
||||
Self::NotInCast { line } => write!(f, "line {line} marks an entity outside the cast"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImportRefusal {}
|
||||
|
||||
impl WorkDraft {
|
||||
pub fn parse(file: &str) -> Result<Self, DraftError> {
|
||||
from_json(file)
|
||||
}
|
||||
|
||||
/// The cast entities and the corpus items for the lines `marked` covers, in
|
||||
/// line order, each item's spans read from its markup and labelled
|
||||
/// `annotator`. Decides everything before any write; whether the documents
|
||||
/// are admissible is `EntityStore::put` and `CorpusStore::add`'s to refuse.
|
||||
pub fn into_import(
|
||||
self,
|
||||
marked: &[MarkedLine],
|
||||
annotator: &Annotator,
|
||||
) -> Result<(Vec<Entity>, Vec<CorpusItem>), ImportRefusal> {
|
||||
let Source::PublicDomain { work, .. } = &self.source else {
|
||||
return Err(ImportRefusal::NotPublicDomain);
|
||||
};
|
||||
let mut entities = Vec::new();
|
||||
for c in &self.cast {
|
||||
if entities.iter().any(|e: &Entity| e.id == c.entity) {
|
||||
return Err(ImportRefusal::CastRepeated);
|
||||
}
|
||||
entities.push(Entity {
|
||||
id: c.entity.clone(),
|
||||
forms: vec![LanguageForms {
|
||||
language: self.language.clone(),
|
||||
forms: c.forms.iter().map(|f| f.nfc().collect()).collect(),
|
||||
pronunciation: None,
|
||||
}],
|
||||
origin: EntityOrigin::PublicDomain { work: work.clone() },
|
||||
});
|
||||
}
|
||||
let in_cast = |id: &EntityId| entities.iter().any(|e| &e.id == id);
|
||||
let mut answer: Vec<&MarkedLine> = marked.iter().collect();
|
||||
answer.sort_by_key(|m| m.line);
|
||||
let mut items = Vec::new();
|
||||
for (i, m) in answer.iter().enumerate() {
|
||||
let line = m.line;
|
||||
if line == 0 || line as usize > self.lines.len() {
|
||||
return Err(ImportRefusal::NoSuchLine { line });
|
||||
}
|
||||
if i > 0 && answer[i - 1].line == line {
|
||||
return Err(ImportRefusal::LineMarkedTwice { line });
|
||||
}
|
||||
let draft = &self.lines[line as usize - 1];
|
||||
let group = format!("{}-{}", self.slug, draft.group);
|
||||
if !is_slug(&group) {
|
||||
return Err(ImportRefusal::Group { line });
|
||||
}
|
||||
if !in_cast(&draft.speaker) {
|
||||
return Err(ImportRefusal::SpeakerNotInCast { line });
|
||||
}
|
||||
let text: String = draft.text.nfc().collect();
|
||||
if text.contains("[[") || text.contains("]]") {
|
||||
return Err(ImportRefusal::Markup { line });
|
||||
}
|
||||
let marked_nfc: String = m.marked.nfc().collect();
|
||||
let (plain, names) = match unmark(&marked_nfc) {
|
||||
Some((plain, names)) if plain == text => (plain, names),
|
||||
_ => return Err(ImportRefusal::Markup { line }),
|
||||
};
|
||||
if names.iter().any(|n| !in_cast(&n.entity)) {
|
||||
return Err(ImportRefusal::NotInCast { line });
|
||||
}
|
||||
items.push(CorpusItem {
|
||||
id: item_key(&self.slug, line),
|
||||
text: plain,
|
||||
language: self.language.clone(),
|
||||
speaker: draft.speaker.clone(),
|
||||
group,
|
||||
prior_turns: Vec::new(),
|
||||
source: self.source.clone(),
|
||||
admitted_on: self.admitted_on.clone(),
|
||||
supersedes: None,
|
||||
withdrawn: false,
|
||||
names,
|
||||
names_by: Some(annotator.clone()),
|
||||
});
|
||||
}
|
||||
Ok((entities, items))
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of `marked` with `[[entity|form]]` replaced by `form`, and the
|
||||
/// byte span of each form in that text. `None` for any malformed markup. The
|
||||
/// only search is for the markup delimiters.
|
||||
fn unmark(marked: &str) -> Option<(String, Vec<NameSpan>)> {
|
||||
let mut out = String::with_capacity(marked.len());
|
||||
let mut names = Vec::new();
|
||||
let mut rest = marked;
|
||||
while let Some(at) = rest.find("[[") {
|
||||
out.push_str(&rest[..at]);
|
||||
let inner = &rest[at + 2..];
|
||||
let (id, after) = inner.split_once('|')?;
|
||||
let (form, tail) = after.split_once("]]")?;
|
||||
if form.is_empty() || form.contains("[[") || id.contains("]]") {
|
||||
return None;
|
||||
}
|
||||
let entity = EntityId::parse(id).ok()?;
|
||||
let start = u32::try_from(out.len()).ok()?;
|
||||
out.push_str(form);
|
||||
names.push(NameSpan {
|
||||
entity,
|
||||
start,
|
||||
end: u32::try_from(out.len()).ok()?,
|
||||
});
|
||||
rest = tail;
|
||||
}
|
||||
out.push_str(rest);
|
||||
Some((out, names))
|
||||
}
|
||||
|
||||
/// `encoder:<hex16>`, a digest of the model id and the prompt digest.
|
||||
pub fn encoder_id(model: &str, prompt_digest: &str) -> EncoderId {
|
||||
let digest = fnv1a64(format!("weksa-encoder-v1:{model}:{prompt_digest}").as_bytes());
|
||||
|
|
@ -576,45 +319,28 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn draft_class_per_real_serde_error() {
|
||||
// Each class is fed by the error serde_json raises for a real answer.
|
||||
fn a_draft_error_is_classed_from_serdes_vocabulary_and_keeps_no_text() {
|
||||
let class = |answer: &str| PacketDraft::parse(answer).unwrap_err().class;
|
||||
assert_eq!(class("not json"), DraftClass::Syntax);
|
||||
assert_eq!(class("{\"referents\": ["), DraftClass::Eof);
|
||||
assert_eq!(class("{}"), DraftClass::MissingField);
|
||||
assert_eq!(class("{\"bogus\": 1}"), DraftClass::UnknownField);
|
||||
assert_eq!(class("{\"confidence\": \"x\"}"), DraftClass::InvalidType);
|
||||
assert_eq!(class("{\"confidence\": -1}"), DraftClass::InvalidValue);
|
||||
let bad_id = r#"{"referents": [{"id": "entity:x"}]}"#;
|
||||
assert_eq!(class(bad_id), DraftClass::BadForm);
|
||||
// A data error opening with words this reader does not know is Other.
|
||||
assert_eq!(
|
||||
DraftClass::of_data("something serde never said"),
|
||||
DraftClass::Other
|
||||
);
|
||||
assert_eq!(DraftClass::of_data(""), DraftClass::Other);
|
||||
// None keeps a token of the answer.
|
||||
let secret = r#"{"confidence": "canary-token"}"#;
|
||||
assert!(!format!("{:?}", PacketDraft::parse(secret).unwrap_err()).contains("canary"));
|
||||
// Other is fed by real serde errors the reader names no class for.
|
||||
let dup = r#"{"confidence": 1, "confidence": 1}"#;
|
||||
assert_eq!(class(dup), DraftClass::Other);
|
||||
let variant = r#"{"stance": {"features": [{"feature": "feature:9", "value": {"Bogus": 1}}]}}"#;
|
||||
assert_eq!(class(variant), DraftClass::Other);
|
||||
// Each code is its literal, exactly: a round record keeps these strings.
|
||||
let pinned = [
|
||||
(DraftClass::Syntax, "syntax"),
|
||||
(DraftClass::Eof, "eof"),
|
||||
(DraftClass::MissingField, "missing-field"),
|
||||
(DraftClass::UnknownField, "unknown-field"),
|
||||
(DraftClass::InvalidType, "invalid-type"),
|
||||
(DraftClass::InvalidValue, "invalid-value"),
|
||||
(DraftClass::BadForm, "bad-form"),
|
||||
(DraftClass::Other, "other"),
|
||||
// The classes serde's own messages open with, read off a plain error.
|
||||
let of = |r: Result<u8, serde_json::Error>| DraftClass::of(&r.unwrap_err());
|
||||
assert_eq!(of(serde_json::from_str("300")), DraftClass::InvalidValue);
|
||||
assert_eq!(of(serde_json::from_str("\"x\"")), DraftClass::InvalidType);
|
||||
// Every code is distinct and none can hold answer text: they are fixed.
|
||||
let all = [
|
||||
DraftClass::Syntax,
|
||||
DraftClass::Eof,
|
||||
DraftClass::MissingField,
|
||||
DraftClass::UnknownField,
|
||||
DraftClass::InvalidType,
|
||||
DraftClass::InvalidValue,
|
||||
DraftClass::BadForm,
|
||||
DraftClass::Other,
|
||||
];
|
||||
for (c, lit) in pinned {
|
||||
assert_eq!(c.code(), lit);
|
||||
}
|
||||
let codes: std::collections::BTreeSet<_> = all.iter().map(|c| c.code()).collect();
|
||||
assert_eq!(codes.len(), all.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -670,39 +396,6 @@ mod tests {
|
|||
assert_eq!(PacketDraft::of(&made), draft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coordinated_fillers_admit_as_one_group_referent() {
|
||||
use crate::store::InventoryStore;
|
||||
use crate::validate::{Refusal, validate};
|
||||
// Item original-ja:19 as measure-ja-2 recorded it: two patients, one role twice.
|
||||
const REFUSED: &str = r#"{"confidence":720,"context":{"setting":null,"medium":null,"participants":["n1"],"audience":["n1"]},"discourse":{"speech_act":"speech_act:3","addressee":null,"addressee_consent":null,"features":[]},"referents":[{"id":"n1","kind":"referent_kind:1","concept":"concept:28","entity":"entity:keeper","features":[]},{"id":"n2","kind":"referent_kind:1","concept":"concept:31","entity":null,"features":[]},{"id":"n3","kind":"referent_kind:5","concept":"concept:123","entity":null,"features":[]},{"id":"n4","kind":"referent_kind:5","concept":"concept:123","entity":null,"features":[]}],"predications":[{"id":"n5","concept":"concept:26","frame":"frame:4","roles":[{"role":"role:1","filler":"n1"},{"role":"role:2","filler":"n3"},{"role":"role:2","filler":"n4"}],"features":[{"feature":"feature:1","value":{"Option":"positive"}},{"feature":"feature:2","value":{"Option":"present"}},{"feature":"feature:3","value":{"Option":"habitual"}}]},{"id":"n6","concept":"concept:196","frame":"frame:4","roles":[{"role":"role:1","filler":"n1"},{"role":"role:2","filler":"n5"}],"features":[{"feature":"feature:1","value":{"Option":"positive"}},{"feature":"feature:2","value":{"Option":"future"}},{"feature":"feature:4","value":{"Option":"desired"}}]}],"relations":[{"relation":"relation:11","from":"n2","to":"n3","features":[]},{"relation":"relation:11","from":"n1","to":"n4","features":[]}],"stance":{"features":[{"feature":"feature:18","value":{"Grade":600}},{"feature":"feature:11","value":{"Grade":450}},{"feature":"feature:17","value":{"Grade":250}}]}}"#;
|
||||
const PRESCRIBED: &str = r#"{"confidence":720,"context":{"setting":null,"medium":null,"participants":["n1"],"audience":["n1"]},"discourse":{"speech_act":"speech_act:3","addressee":null,"addressee_consent":null,"features":[]},"referents":[{"id":"n1","kind":"referent_kind:1","concept":"concept:28","entity":"entity:keeper","features":[]},{"id":"n2","kind":"referent_kind:1","concept":"concept:31","entity":null,"features":[]},{"id":"n3","kind":"referent_kind:5","concept":"concept:123","entity":null,"features":[]},{"id":"n4","kind":"referent_kind:5","concept":"concept:123","entity":null,"features":[]},{"id":"n7","kind":"referent_kind:2","concept":"concept:123","entity":null,"features":[]}],"predications":[{"id":"n5","concept":"concept:26","frame":"frame:4","roles":[{"role":"role:1","filler":"n1"},{"role":"role:2","filler":"n7"}],"features":[{"feature":"feature:1","value":{"Option":"positive"}},{"feature":"feature:2","value":{"Option":"present"}},{"feature":"feature:3","value":{"Option":"habitual"}}]},{"id":"n6","concept":"concept:196","frame":"frame:4","roles":[{"role":"role:1","filler":"n1"},{"role":"role:2","filler":"n5"}],"features":[{"feature":"feature:1","value":{"Option":"positive"}},{"feature":"feature:2","value":{"Option":"future"}},{"feature":"feature:4","value":{"Option":"desired"}}]}],"relations":[{"relation":"relation:11","from":"n2","to":"n3","features":[]},{"relation":"relation:11","from":"n1","to":"n4","features":[]},{"relation":"relation:3","from":"n3","to":"n7","features":[]},{"relation":"relation:3","from":"n4","to":"n7","features":[]}],"stance":{"features":[{"feature":"feature:18","value":{"Grade":600}},{"feature":"feature:11","value":{"Grade":450}},{"feature":"feature:17","value":{"Grade":250}}]}}"#;
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../data/original/inventory.cc");
|
||||
let inventory = InventoryStore::open(&path).unwrap().inventory().unwrap();
|
||||
let item = CorpusItemId::parse("item:original-ja:19").unwrap();
|
||||
let encoder = encoder_id("m", "d");
|
||||
let packet = |answer: &str| {
|
||||
PacketDraft::parse(answer)
|
||||
.unwrap()
|
||||
.into_packet(&item, 6, &encoder)
|
||||
};
|
||||
assert_eq!(
|
||||
validate(&packet(REFUSED), &inventory),
|
||||
Err(vec![Refusal::V11DuplicateRole {
|
||||
role: "role:2".parse().unwrap(),
|
||||
predication: "n5".parse().unwrap(),
|
||||
}])
|
||||
);
|
||||
assert_eq!(validate(&packet(PRESCRIBED), &inventory), Ok(()));
|
||||
// The prompt names the shape the packet above admits, by gloss.
|
||||
let gloss = |id: &str| inventory.entry(&id.parse().unwrap()).unwrap().gloss.clone();
|
||||
assert_eq!(gloss("referent_kind:2"), "group");
|
||||
assert_eq!(gloss("relation:3"), "member_of");
|
||||
let prompt = crate::context::ENCODE_INSTRUCTIONS;
|
||||
assert!(prompt.contains("member_of") && prompt.contains("group"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_draft_parse() {
|
||||
let draft = LoweringDraft::parse("\n {\"text\":\"a\"} \n").unwrap();
|
||||
|
|
@ -815,7 +508,7 @@ mod tests {
|
|||
InvId::parse("frame:2").unwrap(),
|
||||
],
|
||||
};
|
||||
let (rev, entries) = draft.clone().into_revision(&inv, 6, MAX_EDIT_CHANGES).unwrap();
|
||||
let (rev, entries) = draft.clone().into_revision(&inv, 6).unwrap();
|
||||
let ids: Vec<String> = entries.iter().map(|e| e.id.to_string()).collect();
|
||||
// After the highest of the family, retired ones included, in draft order.
|
||||
assert_eq!(ids, ["concept:4", "role:1", "concept:5", "frame:3"]);
|
||||
|
|
@ -858,25 +551,20 @@ mod tests {
|
|||
.collect(),
|
||||
retire: vec![],
|
||||
};
|
||||
assert!(adds(0).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_none());
|
||||
assert!(adds(1).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_some());
|
||||
assert_eq!(adds(8).into_revision(&inv, 1, MAX_EDIT_CHANGES).unwrap().1.len(), 8);
|
||||
assert!(adds(9).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_none());
|
||||
assert!(adds(0).into_revision(&inv, 1).is_none());
|
||||
assert!(adds(1).into_revision(&inv, 1).is_some());
|
||||
assert_eq!(adds(8).into_revision(&inv, 1).unwrap().1.len(), 8);
|
||||
assert!(adds(9).into_revision(&inv, 1).is_none());
|
||||
// Adds and retires count together.
|
||||
let mixed = |a: usize, r: usize| EditDraft {
|
||||
add: (0..a).map(|_| add(Family::Concept, "g")).collect(),
|
||||
retire: vec![InvId::parse("concept:1").unwrap(); r],
|
||||
};
|
||||
assert!(mixed(4, 4).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_some());
|
||||
assert!(mixed(4, 5).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_none());
|
||||
assert!(mixed(0, 9).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_none());
|
||||
assert!(mixed(4, 4).into_revision(&inv, 1).is_some());
|
||||
assert!(mixed(4, 5).into_revision(&inv, 1).is_none());
|
||||
assert!(mixed(0, 9).into_revision(&inv, 1).is_none());
|
||||
// A repeated retire is the door's to refuse, not this fn's.
|
||||
assert!(mixed(0, 2).into_revision(&inv, 1, MAX_EDIT_CHANGES).is_some());
|
||||
// The cap is the caller's.
|
||||
let (_, entries) = adds(200).into_revision(&inv, 1, 256).unwrap();
|
||||
assert_eq!(entries.first().unwrap().id.to_string(), "concept:2");
|
||||
assert_eq!(entries.last().unwrap().id.to_string(), "concept:201");
|
||||
assert!(adds(257).into_revision(&inv, 1, 256).is_none());
|
||||
assert!(mixed(0, 2).into_revision(&inv, 1).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -918,169 +606,4 @@ mod tests {
|
|||
}
|
||||
assert!(EditDraft::parse("3").is_err() && EditDraft::parse("\"x\"").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_draft_refuses_unknown_fields_and_numbers_from_first_n() {
|
||||
for bad in [
|
||||
r#"{"entries": [], "extra": 1}"#,
|
||||
r#"{"entries": [{"layer": "Lexicon", "choice": "c", "language": "ja-JP"}]}"#,
|
||||
"```json\n{\"entries\": []}\n```",
|
||||
"[]",
|
||||
] {
|
||||
assert!(OntologyDraft::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
let draft = OntologyDraft::parse(
|
||||
r#"{"entries": [{"layer": "Grammar", "choice": "a"}, {"layer": "Lexicon", "choice": "b", "examples": ["x"]}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let by = Annotator::Operator;
|
||||
let entries = draft.into_entries("ja-JP", 3, 5, &by);
|
||||
assert_eq!(
|
||||
entries.iter().map(|e| (e.language.as_str(), e.n, e.inventory_rev)).collect::<Vec<_>>(),
|
||||
[("ja-JP", 5, 3), ("ja-JP", 6, 3)]
|
||||
);
|
||||
assert!(entries.iter().all(|e| e.annotator == by));
|
||||
assert_eq!(entries[1].examples, ["x"]);
|
||||
}
|
||||
|
||||
const WORK: &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"]},{"entity":"entity:wexmoor","forms":["Wexmoor"]}],
|
||||
"lines":[{"group":"s1","speaker":"entity:orsa","text":"Tamsin, bring the lantern."},
|
||||
{"group":"s1","speaker":"entity:tamsin","text":"Orsa, I will not, said Tam."},
|
||||
{"group":"s2","speaker":"entity:wexmoor","text":"Quiet, both of you."}]}"#;
|
||||
|
||||
fn marked(line: u32, text: &str) -> MarkedLine {
|
||||
MarkedLine { line, marked: text.into() }
|
||||
}
|
||||
|
||||
fn model_annotator() -> Annotator {
|
||||
Annotator::Model {
|
||||
family: crate::corpus::ModelFamily::Anthropic,
|
||||
generator: "g".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn import(
|
||||
work: &str,
|
||||
answer: &[MarkedLine],
|
||||
) -> Result<(Vec<Entity>, Vec<CorpusItem>), ImportRefusal> {
|
||||
WorkDraft::parse(work).unwrap().into_import(answer, &model_annotator())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_work_imports_its_cast_and_marked_lines() {
|
||||
let answer = [
|
||||
marked(1, "[[entity:tamsin|Tamsin]], bring the lantern."),
|
||||
marked(2, "[[entity:orsa|Orsa]], I will not, said [[entity:tamsin|Tam]]."),
|
||||
];
|
||||
let (entities, items) = import(WORK, &answer).unwrap();
|
||||
assert_eq!(entities.len(), 3);
|
||||
for e in &entities {
|
||||
assert!(matches!(&e.origin, EntityOrigin::PublicDomain { work } if work == "The Lantern Wager"));
|
||||
assert_eq!(e.forms[0].language, "en-US");
|
||||
}
|
||||
assert_eq!(items.len(), 2);
|
||||
assert_eq!(items[0].id, "item:lantern-wager:1");
|
||||
assert_eq!(items[1].id, "item:lantern-wager:2");
|
||||
assert_eq!(items[0].group, "lantern-wager-s1");
|
||||
let span = |e: &str, text: &str, form: &str| {
|
||||
let start = text.find(form).unwrap() as u32;
|
||||
NameSpan { entity: EntityId::parse(e).unwrap(), start, end: start + form.len() as u32 }
|
||||
};
|
||||
let t2 = &items[1].text;
|
||||
assert_eq!(items[0].names, [span("entity:tamsin", &items[0].text, "Tamsin")]);
|
||||
assert_eq!(
|
||||
items[1].names,
|
||||
[span("entity:orsa", t2, "Orsa"), span("entity:tamsin", t2, "Tam")]
|
||||
);
|
||||
// "will" is unmarked and unspanned; the line's speaker is the file's.
|
||||
assert_eq!(items[1].speaker, EntityId::parse("entity:tamsin").unwrap());
|
||||
for i in &items {
|
||||
assert_eq!(i.names_by, Some(model_annotator()));
|
||||
assert!(i.prior_turns.is_empty() && i.supersedes.is_none() && !i.withdrawn);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_refuses_before_any_document() {
|
||||
let ok = marked(1, "Tamsin, bring the lantern.");
|
||||
let refused = |work: &str, answer: &[MarkedLine]| import(work, answer).unwrap_err();
|
||||
let cast_authored = WORK.replace(
|
||||
r#"{"PublicDomain":{"work":"The Lantern Wager","author":"A. Invented","edition_url":"https://example.invalid/lantern","licence":"public domain","jurisdiction":"US","translator":"none","edition_year":1890}}"#,
|
||||
r#""OperatorWritten""#,
|
||||
);
|
||||
assert_eq!(refused(&cast_authored, std::slice::from_ref(&ok)), ImportRefusal::NotPublicDomain);
|
||||
let repeated = WORK.replace(r#"{"entity":"entity:orsa","forms":["Orsa"]}"#, r#"{"entity":"entity:orsa","forms":["Orsa"]},{"entity":"entity:orsa","forms":["O"]}"#);
|
||||
assert_eq!(refused(&repeated, std::slice::from_ref(&ok)), ImportRefusal::CastRepeated);
|
||||
let stranger = WORK.replace(r#""speaker":"entity:orsa""#, r#""speaker":"entity:stranger""#);
|
||||
assert_eq!(refused(&stranger, std::slice::from_ref(&ok)), ImportRefusal::SpeakerNotInCast { line: 1 });
|
||||
assert_eq!(refused(WORK, &[marked(9, "x")]), ImportRefusal::NoSuchLine { line: 9 });
|
||||
assert_eq!(refused(WORK, &[marked(0, "x")]), ImportRefusal::NoSuchLine { line: 0 });
|
||||
assert_eq!(
|
||||
refused(WORK, &[ok.clone(), ok.clone()]),
|
||||
ImportRefusal::LineMarkedTwice { line: 1 }
|
||||
);
|
||||
for bad in [
|
||||
"[[entity:tamsin|Tamsin, bring the lantern.",
|
||||
"[[entity:tamsin Tamsin]], bring the lantern.",
|
||||
"[[tamsin|Tamsin]], bring the lantern.",
|
||||
"[[entity:tamsin|]]Tamsin, bring the lantern.",
|
||||
"Tamsin, bring the lantern",
|
||||
] {
|
||||
assert_eq!(refused(WORK, &[marked(1, bad)]), ImportRefusal::Markup { line: 1 }, "{bad}");
|
||||
}
|
||||
assert_eq!(
|
||||
refused(WORK, &[marked(1, "[[entity:stranger|Tamsin]], bring the lantern.")]),
|
||||
ImportRefusal::NotInCast { line: 1 }
|
||||
);
|
||||
let group = WORK.replace(r#""group":"s1""#, r#""group":"S 1""#);
|
||||
assert_eq!(refused(&group, &[ok]), ImportRefusal::Group { line: 1 });
|
||||
let bracketed = WORK.replace("Tamsin, bring the lantern.", "Tamsin [[bring]] the lantern.");
|
||||
assert_eq!(
|
||||
refused(&bracketed, &[marked(1, "[[entity:tamsin|Tamsin]] [[entity:orsa|bring]] the lantern.")]),
|
||||
ImportRefusal::Markup { line: 1 }
|
||||
);
|
||||
// The refusal text names the kind and the line, no value.
|
||||
assert_eq!(
|
||||
ImportRefusal::Markup { line: 1 }.to_string(),
|
||||
"the marked text of line 1 is not its text with markup"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_offsets_are_bytes_of_the_nfc_text() {
|
||||
let work = WORK
|
||||
.replace("Tamsin, bring the lantern.", "Caf\u{e9} Zo\u{eb}")
|
||||
.replace(r#""forms":["Orsa"]"#, r#""forms":["Zoe\u0308"]"#);
|
||||
let decomposed = "Cafe\u{301} [[entity:orsa|Zoe\u{308}]]";
|
||||
let (entities, items) = import(&work, &[marked(1, decomposed)]).unwrap();
|
||||
assert_eq!(entities[0].forms[0].forms, ["Zo\u{eb}"]);
|
||||
let item = &items[0];
|
||||
assert_eq!(item.text, "Caf\u{e9} Zo\u{eb}");
|
||||
let n = &item.names[0];
|
||||
assert_eq!(&item.text[n.start as usize..n.end as usize], "Zo\u{eb}");
|
||||
assert_eq!(n.start, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_close_bracket_and_a_scattered_duplicate_answer_are_refused() {
|
||||
// A text holding only `]]` is not a marked line.
|
||||
let close = WORK.replace("Quiet, both of you.", "Quiet ]] both of you.");
|
||||
assert_eq!(
|
||||
import(&close, &[marked(3, "Quiet ]] both of you.")]).unwrap_err(),
|
||||
ImportRefusal::Markup { line: 3 }
|
||||
);
|
||||
// The answer's order does not matter, and a duplicate need not be adjacent.
|
||||
let (_, items) = import(WORK, &[marked(3, "Quiet, both of you."), marked(1, "Tamsin, bring the lantern.")]).unwrap();
|
||||
assert_eq!(items.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["item:lantern-wager:1", "item:lantern-wager:3"]);
|
||||
assert_eq!(
|
||||
import(
|
||||
WORK,
|
||||
&[marked(1, "Tamsin, bring the lantern."), marked(3, "Quiet, both of you."), marked(1, "Tamsin, bring the lantern.")]
|
||||
)
|
||||
.unwrap_err(),
|
||||
ImportRefusal::LineMarkedTwice { line: 1 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,73 +91,20 @@ pub fn is_calendar_date(s: &str) -> bool {
|
|||
(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.
|
||||
/// A BCP 47-form language tag: 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. Form only: no registry is consulted.
|
||||
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())
|
||||
let first_ok = first.bytes().all(|b| b.is_ascii_alphabetic())
|
||||
&& ((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
|
||||
first_ok
|
||||
&& subtags
|
||||
.all(|t| (1..=8).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
/// A slug: `[a-z0-9]` and inner `-`, 1 to 48 bytes, no edge `-`.
|
||||
|
|
@ -267,25 +214,6 @@ mod tests {
|
|||
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"));
|
||||
|
|
|
|||
|
|
@ -541,7 +541,7 @@ pub fn proof_revision() -> (InventoryRevision, Vec<InventoryEntry>) {
|
|||
)
|
||||
}
|
||||
|
||||
/// Revision `n`: the speaker-state vocabulary. First the Scene features, the
|
||||
/// Revision 3: 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
|
||||
|
|
@ -551,7 +551,7 @@ pub fn proof_revision() -> (InventoryRevision, Vec<InventoryEntry>) {
|
|||
/// 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>) {
|
||||
pub fn speaker_scene_revision() -> (InventoryRevision, Vec<InventoryEntry>) {
|
||||
let taken = seed()
|
||||
.1
|
||||
.iter()
|
||||
|
|
@ -593,15 +593,15 @@ pub fn speaker_scene_revision(n: u32) -> (InventoryRevision, Vec<InventoryEntry>
|
|||
gloss: gloss.to_string(),
|
||||
value_kind: Some(kind),
|
||||
applies_to: vec![slot],
|
||||
introduced_rev: n,
|
||||
introduced_rev: 3,
|
||||
retired_rev: None,
|
||||
});
|
||||
}
|
||||
let changes = entries.iter().map(|e| Change::Add(e.id)).collect();
|
||||
(
|
||||
InventoryRevision {
|
||||
n,
|
||||
parent: Some(n - 1),
|
||||
n: 3,
|
||||
parent: Some(2),
|
||||
changes,
|
||||
frozen: false,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ pub mod form;
|
|||
pub mod inventory;
|
||||
pub mod lower;
|
||||
pub mod model;
|
||||
pub mod ontology;
|
||||
pub mod packet;
|
||||
pub mod phones;
|
||||
pub mod run;
|
||||
|
|
@ -33,7 +32,6 @@ pub use inventory::{
|
|||
};
|
||||
pub use lower::{EntityForms, LowerError, PhoneLine, TARGET_LANGUAGE, lower, 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,
|
||||
};
|
||||
|
|
@ -43,7 +41,7 @@ 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,
|
||||
AddOutcome, CorpusStore, EntityBound, EntityStore, InventoryStore, PacketStore,
|
||||
SpeakerStateStore, StoreError, StoreRefusal,
|
||||
};
|
||||
pub use validate::{LoweringInput, Refusal, SceneRead, validate};
|
||||
|
|
|
|||
|
|
@ -43,10 +43,8 @@ use crate::phones::{Phone, PhoneInventory, SegmentError};
|
|||
use crate::store::EntityStore;
|
||||
use crate::validate::LoweringInput;
|
||||
|
||||
/// The language tag of the template table and the phones: what `weksa lower`
|
||||
/// says in. 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.
|
||||
/// The language tag this lowerer's entity forms are read under, 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
|
||||
|
|
@ -182,11 +180,6 @@ pub enum LowerError {
|
|||
AskerNotAddressee { predication: NodeId },
|
||||
/// 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 {
|
||||
|
|
@ -208,8 +201,6 @@ impl fmt::Display for LowerError {
|
|||
LowerError::ConsentMissing { .. } => "request lacks the addressee's consent",
|
||||
LowerError::AskerNotAddressee { .. } => "request agent is not the addressee",
|
||||
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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,21 @@
|
|||
//! The `weksa` command line: the same validator and store admission the library
|
||||
//! exposes, plus text projections (`dump`) that are for review and are not stores.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::error::{ContextKind, ContextValue, ErrorKind};
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
use weksa::corpus::{CorpusItem, ModelFamily, NameSpan, Source, Turn};
|
||||
use weksa::encode::{EditDraft, MarkedLine, OntologyDraft, WorkDraft};
|
||||
use weksa::entity::{Entity, EntityOrigin, LanguageForms, Pronunciation};
|
||||
use weksa::inventory::{proof_revision, seed, speaker_scene_revision};
|
||||
use weksa::packet::{FeatValue, FeatureValue, Grade};
|
||||
use weksa::inventory::{proof_revision, seed};
|
||||
use weksa::packet::proof_packet;
|
||||
use weksa::model::{ModelPort, RecordedAnswers};
|
||||
use weksa::run::{
|
||||
AblationOutcome, CalibrateOutcome, CycleOutcome, FLOOR_ARMS_MIN, LowererReach, OntologyMintOutcome, RecallOutcome, RelowerOutcome, RoundOutcome, RunPaths, RunStores, cycle, round,
|
||||
};
|
||||
use weksa::run::{CycleOutcome, LowererReach, RecallOutcome, RoundOutcome, RunPaths, RunStores, cycle, round};
|
||||
use weksa::score::ScoreInput;
|
||||
use weksa::{
|
||||
Annotator, CorpusStore, EntityId, EntityStore, Family, InventoryStore, OllamaEmbedder, OntologyStore, OptionLabel,
|
||||
PacketStore, PairRelation, Party, Scene, Slot, SpeakerStateStore, ValueKind, Scorer, Split, SplitScheme, StoreError, StoreRefusal, lower, pronounce, validate,
|
||||
AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore,
|
||||
Scorer, SplitScheme, StoreError, lower, pronounce, validate,
|
||||
};
|
||||
|
||||
#[derive(Parser)]
|
||||
|
|
@ -38,12 +33,6 @@ struct Cli {
|
|||
/// The entity store.
|
||||
#[arg(long, global = true, default_value = "data/entity/entity.cc")]
|
||||
entities: PathBuf,
|
||||
/// The language ontology store.
|
||||
#[arg(long, global = true, default_value = "data/ontology/ontology.cc")]
|
||||
ontology: PathBuf,
|
||||
/// The speaker-state store (scenes).
|
||||
#[arg(long, global = true, default_value = "data/corpus/speaker-state.cc")]
|
||||
speaker_state: PathBuf,
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
|
@ -59,10 +48,6 @@ enum Command {
|
|||
#[command(subcommand)]
|
||||
Entity(EntityCommand),
|
||||
#[command(subcommand)]
|
||||
Ontology(OntologyCommand),
|
||||
#[command(subcommand)]
|
||||
Scene(SceneCommand),
|
||||
#[command(subcommand)]
|
||||
Packet(PacketCommand),
|
||||
/// Lower a stored packet to English text.
|
||||
Lower {
|
||||
|
|
@ -93,7 +78,7 @@ enum Command {
|
|||
|
||||
#[derive(Subcommand)]
|
||||
enum LoopCommand {
|
||||
/// Pin the global --corpus, --inventory, --entities, --ontology and --speaker-state as a run at ROOT.
|
||||
/// Pin the global --corpus, --inventory and --entities as a run at ROOT.
|
||||
Open {
|
||||
root: PathBuf,
|
||||
#[arg(long)]
|
||||
|
|
@ -111,14 +96,10 @@ enum LoopCommand {
|
|||
/// that family wrote. Defaults to unrecorded.
|
||||
#[arg(long, default_value = "unrecorded")]
|
||||
answerer_family: ModelFamilyArg,
|
||||
/// The languages the run offers, reads and decides on: BCP 47 tags,
|
||||
/// comma-separated. Every one needs a live Train and Validation item.
|
||||
#[arg(long, value_delimiter = ',', required = true)]
|
||||
panel: Vec<String>,
|
||||
},
|
||||
/// Run one round of the run at ROOT. The stores are read only from the
|
||||
/// run's record: the global --corpus, --inventory, --entities and --ontology
|
||||
/// are not read. Encode prompts are written first; once they are answered a rerun
|
||||
/// run's record: the global --corpus, --inventory and --entities are not
|
||||
/// read. Encode prompts are written first; once they are answered a rerun
|
||||
/// writes the lowering prompts. The command exits 3 each time until every
|
||||
/// prompt has an answer.
|
||||
Round {
|
||||
|
|
@ -131,80 +112,10 @@ enum LoopCommand {
|
|||
/// half). Prompts and answers live in `<ROOT>/recall`; the command exits 3
|
||||
/// until every prompt has an answer. A diagnostic, never a gate.
|
||||
Recall { root: PathBuf },
|
||||
/// Draft ontology entries from the run's Train items of one language.
|
||||
/// Prompts and answers live in `<ROOT>/ontology-mint`; the command exits 3
|
||||
/// until the prompt has an answer. Admission is `weksa ontology admit`
|
||||
/// into a copy, never into the run's pinned file.
|
||||
MintOntology {
|
||||
root: PathBuf,
|
||||
#[arg(long)]
|
||||
language: String,
|
||||
},
|
||||
/// Ask whether the lowerer uses a packet's stance: for each live Train and
|
||||
/// Validation packet of round ROUND, ask again with the stance as it is,
|
||||
/// emptied, and swapped for the next item's, and read how far the lowering
|
||||
/// moves from the round's own answer. Prompts and answers live in
|
||||
/// `<ROOT>/ablation-<ROUND>`; the command exits 3 until every prompt has an
|
||||
/// answer. A diagnostic, never a gate; Test is never touched.
|
||||
Ablate {
|
||||
root: PathBuf,
|
||||
#[arg(long)]
|
||||
round: u32,
|
||||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
ollama_url: String,
|
||||
},
|
||||
/// Re-lower round ROUND's Validation packets through arm ARM, score them
|
||||
/// against the items, and, with --floor ARM given two or more times (prompted
|
||||
/// repeats of the lowering), decide against the paired noise floor of those
|
||||
/// repeats by the panel accept rule. Prompts and answers live in
|
||||
/// `<ROOT>/relower-<ROUND>-<ARM>`; the command exits 3 until the arm is
|
||||
/// answered. --lowerer names the arm's model in the printed line. A
|
||||
/// diagnostic, never a gate; records nothing; Test and Train are never
|
||||
/// touched. Labels match [a-z0-9-]{1,32} and differ.
|
||||
Relower {
|
||||
root: PathBuf,
|
||||
#[arg(long)]
|
||||
round: u32,
|
||||
#[arg(long)]
|
||||
arm: String,
|
||||
#[arg(long)]
|
||||
lowerer: String,
|
||||
#[arg(long)]
|
||||
floor: Vec<String>,
|
||||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
ollama_url: String,
|
||||
},
|
||||
/// Replay the accept rule over answered relower draws of round ROUND, to
|
||||
/// measure how often it accepts, rejects or regresses what it should. Reads
|
||||
/// the recorded lowering and each draw (--prompted: repeats of it, at least
|
||||
/// four; --degraded: arms that should regress; --candidate: arms to rate),
|
||||
/// answered through `weksa loop relower ROOT --round N --arm LABEL`, and
|
||||
/// prints counts over all Validation items and over each --class
|
||||
/// NAME=PREFIX[,PREFIX...] (items whose key starts with a prefix). Writes
|
||||
/// no prompts; exits 1 naming the draws still unanswered. Procedure:
|
||||
/// docs/calibration.md. A diagnostic, never a gate; records nothing; Test
|
||||
/// and Train are never touched. Labels match [a-z0-9-]{1,32} and differ.
|
||||
Calibrate {
|
||||
root: PathBuf,
|
||||
#[arg(long)]
|
||||
round: u32,
|
||||
#[arg(long)]
|
||||
prompted: Vec<String>,
|
||||
#[arg(long)]
|
||||
degraded: Vec<String>,
|
||||
#[arg(long)]
|
||||
candidate: Vec<String>,
|
||||
#[arg(long)]
|
||||
class: Vec<String>,
|
||||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
ollama_url: String,
|
||||
},
|
||||
/// Run one edit-accept cycle of the run at ROOT. The stores are read only
|
||||
/// from the run's record. The editor's prompt, then the candidate round's
|
||||
/// encode prompts, then its lowering prompts are written in turn; the
|
||||
/// command exits 3 each time until every prompt has an answer. The noise
|
||||
/// floor needs four recorded rounds under the first inventory (the recorded
|
||||
/// round and three prompted repeats).
|
||||
/// command exits 3 each time until every prompt has an answer.
|
||||
Cycle {
|
||||
root: PathBuf,
|
||||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
|
|
@ -242,22 +153,6 @@ enum CorpusCommand {
|
|||
Withdraw {
|
||||
key: String,
|
||||
},
|
||||
/// Import a transcribed public-domain work: mint its cast as entities and
|
||||
/// add each line a name-span answer covers (`docs/name-span-annotation.md`).
|
||||
Import {
|
||||
/// The work file: provenance, cast, lines.
|
||||
work: PathBuf,
|
||||
/// The annotator's answer: one `{"line": N, "marked": "..."}` per line.
|
||||
names: PathBuf,
|
||||
#[arg(long, requires = "generator", conflicts_with = "operator")]
|
||||
model_family: Option<ModelFamilyArg>,
|
||||
/// The attestation string naming the annotating model.
|
||||
#[arg(long, requires = "model_family")]
|
||||
generator: Option<String>,
|
||||
/// Annotated by the operator, not a model.
|
||||
#[arg(long)]
|
||||
operator: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
|
|
@ -270,45 +165,6 @@ enum InventoryCommand {
|
|||
Proof,
|
||||
/// Admit revision 3 of the Dao De Jing test bed stores (after seed and proof).
|
||||
Dao,
|
||||
/// Admit the speaker-state revision (Scene and Speaker features) as the
|
||||
/// inventory's latest plus one.
|
||||
SpeakerScene,
|
||||
/// Admit a model's inventory draft (a JSON file, {add, retire} as the
|
||||
/// loop's editor writes it) as the inventory's latest plus one.
|
||||
Admit { answer: PathBuf },
|
||||
}
|
||||
|
||||
/// The most changes `inventory admit` takes in one draft. A hand-admitted draft
|
||||
/// is reviewed whole in its cut, so the cap is not the loop editor's.
|
||||
const MAX_ADMIT_CHANGES: usize = 256;
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum SceneCommand {
|
||||
/// Append a scene revision for one corpus group: its one live speaker's
|
||||
/// relation to the addressee, as Scene-slot feature values.
|
||||
Put {
|
||||
#[arg(long)]
|
||||
group: String,
|
||||
/// `entity:<slug>` of a named addressee, or `unnamed`.
|
||||
#[arg(long)]
|
||||
to: String,
|
||||
/// The inventory revision the glosses resolve at.
|
||||
#[arg(long)]
|
||||
inventory_rev: u32,
|
||||
/// `gloss=value`, repeated: a grade 0-1000, an option label or true/false.
|
||||
#[arg(long = "set", value_name = "GLOSS=VALUE")]
|
||||
set: Vec<String>,
|
||||
#[arg(long, requires = "generator", conflicts_with = "operator")]
|
||||
model_family: Option<ModelFamilyArg>,
|
||||
/// The attestation string naming the annotating model.
|
||||
#[arg(long, requires = "model_family")]
|
||||
generator: Option<String>,
|
||||
/// Annotated by the operator, not a model.
|
||||
#[arg(long)]
|
||||
operator: bool,
|
||||
},
|
||||
/// Text projection of the scenes for review; not a store.
|
||||
Dump,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
|
|
@ -319,28 +175,6 @@ enum EntityCommand {
|
|||
Dump,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum OntologyCommand {
|
||||
/// Admit a model's ontology draft (a JSON file) for one language as a
|
||||
/// batch, numbered from the language's latest plus one and annotated as
|
||||
/// the model that drafted it.
|
||||
Admit {
|
||||
answer: PathBuf,
|
||||
#[arg(long)]
|
||||
language: String,
|
||||
/// The inventory revision the draft's conditions are read at.
|
||||
#[arg(long)]
|
||||
inventory_rev: u32,
|
||||
#[arg(long)]
|
||||
model_family: ModelFamilyArg,
|
||||
/// The attestation string naming the drafting model.
|
||||
#[arg(long)]
|
||||
generator: String,
|
||||
},
|
||||
/// Text projection of the ontology for review; not a store.
|
||||
Dump,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct PutArgs {
|
||||
/// `entity:<slug>`.
|
||||
|
|
@ -479,8 +313,7 @@ struct AddArgs {
|
|||
/// NFC-normalized here; `--name` byte offsets index the normalized text.
|
||||
#[arg(long)]
|
||||
text: String,
|
||||
/// The item's language, a BCP 47 tag; no language is the default.
|
||||
#[arg(long)]
|
||||
#[arg(long, default_value = "en-US")]
|
||||
language: String,
|
||||
/// An entity id.
|
||||
#[arg(long)]
|
||||
|
|
@ -697,17 +530,10 @@ impl AddArgs {
|
|||
supersedes: self.supersedes,
|
||||
withdrawn: false,
|
||||
names,
|
||||
names_by: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A draw or arm label: [a-z0-9-]{1,32}.
|
||||
fn is_label(l: &str) -> bool {
|
||||
(1..=32).contains(&l.len())
|
||||
&& l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
}
|
||||
|
||||
/// The split of an item as `Train`, `Validation`, `Test` or `excluded`.
|
||||
fn split_text(item: &CorpusItem) -> String {
|
||||
SplitScheme::V1
|
||||
|
|
@ -715,22 +541,6 @@ fn split_text(item: &CorpusItem) -> String {
|
|||
.map_or_else(|| "excluded".to_string(), |s| format!("{s:?}"))
|
||||
}
|
||||
|
||||
/// The annotator the flags name: a model family with its generator, or the operator.
|
||||
fn annotator(
|
||||
model_family: Option<ModelFamilyArg>,
|
||||
generator: Option<String>,
|
||||
operator: bool,
|
||||
) -> Result<Annotator> {
|
||||
match (model_family, generator, operator) {
|
||||
(Some(family), Some(generator), false) => Ok(Annotator::Model {
|
||||
family: family.into(),
|
||||
generator,
|
||||
}),
|
||||
(None, None, true) => Ok(Annotator::Operator),
|
||||
_ => bail!("name the annotator: --model-family with --generator, or --operator"),
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(e: StoreError) -> anyhow::Error {
|
||||
anyhow::anyhow!("{e}")
|
||||
}
|
||||
|
|
@ -770,78 +580,13 @@ fn main() -> Result<()> {
|
|||
.map_err(refused)?;
|
||||
println!("{outcome:?} {key}");
|
||||
}
|
||||
Command::Corpus(CorpusCommand::Import {
|
||||
work,
|
||||
names,
|
||||
model_family,
|
||||
generator,
|
||||
operator,
|
||||
}) => {
|
||||
let annotator = annotator(model_family, generator, operator)?;
|
||||
let draft = WorkDraft::parse(&std::fs::read_to_string(&work)?)?;
|
||||
let mut marked = Vec::new();
|
||||
for (i, line) in std::fs::read_to_string(&names)?.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
marked.push(
|
||||
MarkedLine::parse(line)
|
||||
.map_err(|e| anyhow::anyhow!("names line {}: {e}", i + 1))?,
|
||||
);
|
||||
}
|
||||
let (new_entities, items) = draft.into_import(&marked, &annotator)?;
|
||||
// Every document passes the real doors on scratch copies of the
|
||||
// stores before the first write, so a refusal leaves them untouched.
|
||||
let scratch = std::env::temp_dir().join(format!("weksa-import-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&scratch)?;
|
||||
let dry = (|| -> Result<()> {
|
||||
let copy = |from: &Path, name: &str| -> Result<PathBuf> {
|
||||
let to = scratch.join(name);
|
||||
if from.exists() {
|
||||
std::fs::copy(from, &to)?;
|
||||
}
|
||||
Ok(to)
|
||||
};
|
||||
let mut entities = EntityStore::open(©(&cli.entities, "e.cc")?)?;
|
||||
let mut store = CorpusStore::open(©(&cli.corpus, "c.cc")?)?;
|
||||
for e in new_entities.clone() {
|
||||
entities
|
||||
.put(e)
|
||||
.map_err(|e| anyhow::anyhow!("a cast entity: {e}"))?;
|
||||
}
|
||||
for item in items.clone() {
|
||||
let key = item.id.clone();
|
||||
store.add(item, &entities).map_err(|e| match e {
|
||||
StoreError::Refused(StoreRefusal::S6TextHeld { held_by, .. }) => {
|
||||
anyhow::anyhow!("{key} repeats the text of {held_by}")
|
||||
}
|
||||
e => anyhow::anyhow!("{key}: {e}"),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
dry?;
|
||||
let mut entities = EntityStore::open(&cli.entities)?;
|
||||
for e in new_entities {
|
||||
let id = e.id.clone();
|
||||
let outcome = entities.put(e).map_err(refused)?;
|
||||
println!("{outcome:?} {id}");
|
||||
}
|
||||
let mut store = CorpusStore::open(&cli.corpus)?;
|
||||
for item in items {
|
||||
let (key, split) = (item.id.clone(), split_text(&item));
|
||||
let outcome = store.add(item, &entities).map_err(refused)?;
|
||||
println!("{outcome:?} {key} {split}");
|
||||
}
|
||||
}
|
||||
Command::Corpus(CorpusCommand::Dump) => {
|
||||
for i in CorpusStore::open(&cli.corpus)?.all()? {
|
||||
let split = split_text(&i);
|
||||
let withdrawn = if i.withdrawn { " withdrawn" } else { "" };
|
||||
println!(
|
||||
"{} [{} {} group={} {split}{withdrawn}]\n {:?}\n names: {:?} by {:?}\n source: {:?}",
|
||||
i.id, i.language, i.speaker, i.group, i.text, i.names, i.names_by, i.source
|
||||
"{} [{} {} group={} {split}{withdrawn}]\n {:?}\n names: {:?}\n source: {:?}",
|
||||
i.id, i.language, i.speaker, i.group, i.text, i.names, i.source
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -882,48 +627,6 @@ fn main() -> Result<()> {
|
|||
println!("{} {:?}\n forms: {:?}", e.id, e.origin, e.forms);
|
||||
}
|
||||
}
|
||||
Command::Ontology(OntologyCommand::Admit {
|
||||
answer,
|
||||
language,
|
||||
inventory_rev,
|
||||
model_family,
|
||||
generator,
|
||||
}) => {
|
||||
let text = std::fs::read_to_string(&answer).context("the draft would not read")?;
|
||||
let draft = OntologyDraft::parse(&text)?;
|
||||
let mut store = OntologyStore::open(&cli.ontology)?;
|
||||
let first = store
|
||||
.all()?
|
||||
.iter()
|
||||
.filter(|e| e.language == language)
|
||||
.map(|e| e.n)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
+ 1;
|
||||
let annotator = Annotator::Model {
|
||||
family: model_family.into(),
|
||||
generator,
|
||||
};
|
||||
let entries = draft.into_entries(&language, inventory_rev, first, &annotator);
|
||||
let count = entries.len();
|
||||
let inventory = InventoryStore::open(&cli.inventory)?;
|
||||
let outcome = store.admit(entries, &inventory).map_err(refused)?;
|
||||
println!("{outcome:?} {count} entries of {language}");
|
||||
}
|
||||
Command::Ontology(OntologyCommand::Dump) => {
|
||||
for e in OntologyStore::open(&cli.ontology)?.all()? {
|
||||
println!(
|
||||
"{} {} rev:{} {:?}\n when: {:?}\n {}\n e.g. {:?}",
|
||||
e.key(),
|
||||
e.layer.name(),
|
||||
e.inventory_rev,
|
||||
e.annotator,
|
||||
e.when,
|
||||
e.choice,
|
||||
e.examples
|
||||
);
|
||||
}
|
||||
}
|
||||
Command::Inventory(InventoryCommand::Seed) => {
|
||||
let (rev, entries) = seed();
|
||||
let count = entries.len();
|
||||
|
|
@ -940,152 +643,6 @@ fn main() -> Result<()> {
|
|||
.map_err(refused)?;
|
||||
println!("admitted rev:2 with {count} entries");
|
||||
}
|
||||
Command::Inventory(InventoryCommand::SpeakerScene) => {
|
||||
let store = InventoryStore::open(&cli.inventory)?;
|
||||
let latest = store
|
||||
.inventory()?
|
||||
.latest()
|
||||
.map(|r| r.n)
|
||||
.context("the inventory holds no revision")?;
|
||||
let (rev, entries) = speaker_scene_revision(latest + 1);
|
||||
let (n, count) = (rev.n, entries.len());
|
||||
let mut store = store;
|
||||
store.admit_revision(rev, entries).map_err(refused)?;
|
||||
println!("admitted rev:{n} with {count} entries");
|
||||
}
|
||||
Command::Inventory(InventoryCommand::Admit { answer }) => {
|
||||
let text = std::fs::read_to_string(&answer).context("the draft would not read")?;
|
||||
let draft = EditDraft::parse(&text)?;
|
||||
let mut store = InventoryStore::open(&cli.inventory)?;
|
||||
let inventory = store.inventory()?;
|
||||
let latest = inventory
|
||||
.latest()
|
||||
.map(|r| r.n)
|
||||
.context("the inventory holds no revision")?;
|
||||
let (rev, entries) = draft
|
||||
.into_revision(&inventory, latest, MAX_ADMIT_CHANGES)
|
||||
.context("the draft makes no change or more than the cap")?;
|
||||
let (n, count) = (rev.n, entries.len());
|
||||
store.admit_revision(rev, entries).map_err(refused)?;
|
||||
println!("admitted rev:{n} with {count} entries");
|
||||
}
|
||||
Command::Scene(SceneCommand::Put {
|
||||
group,
|
||||
to,
|
||||
inventory_rev,
|
||||
set,
|
||||
model_family,
|
||||
generator,
|
||||
operator,
|
||||
}) => {
|
||||
let annotator = annotator(model_family, generator, operator)?;
|
||||
let inventory_store = InventoryStore::open(&cli.inventory)?;
|
||||
let inventory = inventory_store.inventory()?;
|
||||
let corpus = CorpusStore::open(&cli.corpus)?;
|
||||
let live: Vec<CorpusItem> = corpus
|
||||
.all()?
|
||||
.into_iter()
|
||||
.filter(|i| i.group == group && !i.withdrawn)
|
||||
.collect();
|
||||
let mut speakers: Vec<EntityId> = live.iter().map(|i| i.speaker.clone()).collect();
|
||||
speakers.sort();
|
||||
speakers.dedup();
|
||||
let [from] = speakers.as_slice() else {
|
||||
bail!("a scene group holds one live speaker; multi-party scenes wait");
|
||||
};
|
||||
let to = match to.as_str() {
|
||||
"unnamed" => Party::Unnamed,
|
||||
named => Party::Named(
|
||||
EntityId::parse(named).map_err(|_| anyhow::anyhow!("the addressee is unnamed or an entity id"))?,
|
||||
),
|
||||
};
|
||||
let mut features = Vec::new();
|
||||
for pair in &set {
|
||||
let bad = || anyhow::anyhow!("a --set is gloss=value of a live Scene feature");
|
||||
let (gloss, value) = pair.split_once('=').ok_or_else(bad)?;
|
||||
let entry = inventory
|
||||
.entries()
|
||||
.find(|e| {
|
||||
e.family() == Family::Feature
|
||||
&& e.gloss == gloss
|
||||
&& e.live_at(inventory_rev)
|
||||
&& e.applies_to.contains(&Slot::Scene)
|
||||
})
|
||||
.ok_or_else(bad)?;
|
||||
let value = match entry.value_kind.as_ref().ok_or_else(bad)? {
|
||||
ValueKind::Grade => FeatValue::Grade(
|
||||
Grade::new(value.parse().map_err(|_| bad())?).map_err(|_| bad())?,
|
||||
),
|
||||
ValueKind::Options(_) => {
|
||||
FeatValue::Option(OptionLabel::parse(value).map_err(|_| bad())?)
|
||||
}
|
||||
ValueKind::Flag => FeatValue::Flag(value.parse().map_err(|_| bad())?),
|
||||
};
|
||||
features.push(FeatureValue { feature: entry.id, value });
|
||||
}
|
||||
let mut participants = vec![from.clone()];
|
||||
if let Party::Named(a) = &to
|
||||
&& a != from
|
||||
{
|
||||
participants.push(a.clone());
|
||||
}
|
||||
let mut state = SpeakerStateStore::open(&cli.speaker_state)?;
|
||||
let latest = state.scene(&group)?;
|
||||
let mut scene = Scene {
|
||||
group,
|
||||
n: latest.as_ref().map_or(1, |l| l.n + 1),
|
||||
inventory_rev,
|
||||
participants,
|
||||
relations: vec![PairRelation { from: from.clone(), to, features }],
|
||||
annotator,
|
||||
};
|
||||
if let Some(l) = &latest {
|
||||
let same = Scene { n: l.n, ..scene.clone() };
|
||||
if &same == l {
|
||||
println!("unchanged");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
scene.n = latest.map_or(1, |l| l.n + 1);
|
||||
let key = weksa::speaker::scene_key(&scene.group, scene.n);
|
||||
let outcome = state
|
||||
.put_scene(scene, &inventory_store, &corpus, &EntityStore::open(&cli.entities)?)
|
||||
.map_err(refused)?;
|
||||
println!("{outcome:?} {key}");
|
||||
}
|
||||
Command::Scene(SceneCommand::Dump) => {
|
||||
let inventory = InventoryStore::open(&cli.inventory)?.inventory()?;
|
||||
let gloss = |f: &FeatureValue| {
|
||||
let name = inventory.entry(&f.feature).map_or("?", |e| e.gloss.as_str());
|
||||
match &f.value {
|
||||
FeatValue::Grade(g) => format!("{name}={}", g.get()),
|
||||
FeatValue::Option(l) => format!("{name}={l}"),
|
||||
FeatValue::Flag(b) => format!("{name}={b}"),
|
||||
}
|
||||
};
|
||||
for s in SpeakerStateStore::open(&cli.speaker_state)?.all_scenes()? {
|
||||
let who = match &s.annotator {
|
||||
Annotator::Operator => "Operator".to_string(),
|
||||
Annotator::Model { family, generator } => format!("Model {family:?} {generator}"),
|
||||
};
|
||||
let people: Vec<&str> = s.participants.iter().map(|p| p.as_str()).collect();
|
||||
println!(
|
||||
"scene:{}@{} rev:{} {who} [{}]",
|
||||
s.group,
|
||||
s.n,
|
||||
s.inventory_rev,
|
||||
people.join(",")
|
||||
);
|
||||
for r in &s.relations {
|
||||
let to = match &r.to {
|
||||
Party::Named(e) => e.as_str().to_string(),
|
||||
Party::Unnamed => "unnamed".to_string(),
|
||||
};
|
||||
let feats: Vec<String> = r.features.iter().map(&gloss).collect();
|
||||
println!(" {}->{to} {}", r.from, feats.join(" "));
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Inventory(InventoryCommand::Dao) => {
|
||||
let (rev, entries) = weksa::daodejing::revision();
|
||||
let count = entries.len();
|
||||
|
|
@ -1192,7 +749,6 @@ fn main() -> Result<()> {
|
|||
embed_model,
|
||||
lowerer_reach,
|
||||
answerer_family,
|
||||
panel,
|
||||
}) => {
|
||||
let run = RunStores::create(
|
||||
&root,
|
||||
|
|
@ -1201,21 +757,21 @@ fn main() -> Result<()> {
|
|||
corpus: &cli.corpus,
|
||||
inventory: &cli.inventory,
|
||||
entities: &cli.entities,
|
||||
ontology: &cli.ontology,
|
||||
speaker_state: &cli.speaker_state,
|
||||
},
|
||||
&answerer,
|
||||
&embed_model,
|
||||
lowerer_reach,
|
||||
answerer_family.into(),
|
||||
&panel,
|
||||
)?;
|
||||
println!("opened run:{}", run.record().label);
|
||||
}
|
||||
Command::Loop(LoopCommand::Round { root, ollama_url }) => {
|
||||
let unreadable = |_| anyhow::anyhow!("a store would not read");
|
||||
let mut run = RunStores::open(&root)?;
|
||||
let mut files = run.answer_files(run.next_round_dir().map_err(unreadable)?)?;
|
||||
let mut files = AnswerFiles::new(
|
||||
run.next_round_dir().map_err(unreadable)?,
|
||||
run.record().model.clone(),
|
||||
);
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match round(&mut run, &mut files, &scorer)? {
|
||||
RoundOutcome::Unanswered { prompts } => {
|
||||
|
|
@ -1229,190 +785,9 @@ fn main() -> Result<()> {
|
|||
RoundOutcome::Recorded(r) => println!("{}", run.round_line(&r)),
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Ablate {
|
||||
root,
|
||||
round,
|
||||
ollama_url,
|
||||
}) => {
|
||||
let run = RunStores::open(&root)?;
|
||||
let mut recorded = RecordedAnswers::new(
|
||||
root.join(format!("round-{round}")),
|
||||
run.record().model.clone(),
|
||||
);
|
||||
let mut files = run.answer_files(run.ablation_dir(round))?;
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match run.stance_ablation(round, &mut recorded, &mut files, &scorer)? {
|
||||
AblationOutcome::Unanswered { prompts } => {
|
||||
for digest in &prompts {
|
||||
println!("unanswered {digest}");
|
||||
}
|
||||
println!("unanswered {} prompts", prompts.len());
|
||||
std::process::exit(3);
|
||||
}
|
||||
AblationOutcome::Read(readings) => {
|
||||
for (language, split, reading) in readings {
|
||||
let name = match split {
|
||||
Split::Train => "train",
|
||||
_ => "validation",
|
||||
};
|
||||
println!("{language} {name} {}", reading.line());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Relower {
|
||||
root,
|
||||
round,
|
||||
arm,
|
||||
lowerer,
|
||||
floor,
|
||||
ollama_url,
|
||||
}) => {
|
||||
if !is_label(&arm)
|
||||
|| floor.iter().any(|f| !is_label(f) || *f == arm)
|
||||
|| floor.iter().enumerate().any(|(i, f)| floor[..i].contains(f))
|
||||
{
|
||||
anyhow::bail!("arm and floor labels must match [a-z0-9-]{{1,32}} and differ");
|
||||
}
|
||||
let run = RunStores::open(&root)?;
|
||||
let mut recorded = RecordedAnswers::new(
|
||||
root.join(format!("round-{round}")),
|
||||
run.record().model.clone(),
|
||||
);
|
||||
let mut files = run.answer_files(run.relower_dir(round, &arm))?;
|
||||
let mut floor_ports: Vec<RecordedAnswers> = floor
|
||||
.iter()
|
||||
.map(|f| RecordedAnswers::new(run.relower_dir(round, f), run.record().model.clone()))
|
||||
.collect();
|
||||
let mut floor_dyn: Vec<&mut dyn ModelPort> =
|
||||
floor_ports.iter_mut().map(|p| p as &mut dyn ModelPort).collect();
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match run.relower(
|
||||
round,
|
||||
&arm,
|
||||
&mut recorded,
|
||||
&mut files,
|
||||
&mut floor_dyn,
|
||||
&scorer,
|
||||
)? {
|
||||
RelowerOutcome::Unanswered { prompts } => {
|
||||
for digest in &prompts {
|
||||
println!("unanswered {digest}");
|
||||
}
|
||||
println!("unanswered {} prompts", prompts.len());
|
||||
std::process::exit(3);
|
||||
}
|
||||
RelowerOutcome::Read { languages, verdict } => {
|
||||
for l in languages {
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!("{} arm={arm} lowerer={lowerer}", l.line()))
|
||||
);
|
||||
}
|
||||
if let Some(v) = verdict {
|
||||
println!("verdict {v:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Calibrate {
|
||||
root,
|
||||
round,
|
||||
prompted,
|
||||
degraded,
|
||||
candidate,
|
||||
class,
|
||||
ollama_url,
|
||||
}) => {
|
||||
let labels: Vec<&String> = prompted.iter().chain(°raded).chain(&candidate).collect();
|
||||
if labels.iter().any(|l| !is_label(l))
|
||||
|| labels.iter().enumerate().any(|(i, l)| labels[..i].contains(l))
|
||||
{
|
||||
anyhow::bail!("draw labels must match [a-z0-9-]{{1,32}} and differ");
|
||||
}
|
||||
if prompted.len() < FLOOR_ARMS_MIN + 1 {
|
||||
anyhow::bail!("at least {} --prompted labels are needed", FLOOR_ARMS_MIN + 1);
|
||||
}
|
||||
let mut classes: Vec<(String, Vec<String>)> = Vec::new();
|
||||
for c in &class {
|
||||
let Some((name, prefixes)) = c.split_once('=') else {
|
||||
anyhow::bail!("--class is NAME=PREFIX[,PREFIX...]");
|
||||
};
|
||||
if !is_label(name)
|
||||
|| name == "all"
|
||||
|| classes.iter().any(|(n, _)| n == name)
|
||||
|| prefixes.split(',').any(str::is_empty)
|
||||
{
|
||||
anyhow::bail!("--class is NAME=PREFIX[,PREFIX...] with a new label NAME other than all");
|
||||
}
|
||||
classes.push((name.to_string(), prefixes.split(',').map(String::from).collect()));
|
||||
}
|
||||
let run = RunStores::open(&root)?;
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match run.calibrate(round, &prompted, °raded, &candidate, &classes, &scorer)? {
|
||||
CalibrateOutcome::Unanswered(missing) => {
|
||||
for (label, n) in &missing {
|
||||
println!("unanswered {label} {n}");
|
||||
}
|
||||
eprintln!(
|
||||
"answer it through weksa loop relower ROOT --round N --arm LABEL first"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
CalibrateOutcome::Read { unusable, classes } => {
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!(
|
||||
"calibrate draws prompted={} degraded={} candidate={} floor-arms={FLOOR_ARMS_MIN} unusable={unusable}",
|
||||
prompted.len(),
|
||||
degraded.len(),
|
||||
candidate.len(),
|
||||
))
|
||||
);
|
||||
for c in classes {
|
||||
let items: String = c
|
||||
.languages
|
||||
.iter()
|
||||
.map(|l| format!(" {} n={} skipped={}", l.language, l.n, l.skipped))
|
||||
.collect();
|
||||
let t = &c.trials;
|
||||
println!("{}", run.labelled(&format!("calibrate class={} items{items}", c.name)));
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!(
|
||||
"calibrate class={} prompted trials={} nogain={} accepted={} regressed={} noise={:.4}",
|
||||
c.name, t.prompted.trials, t.prompted.nogain, t.prompted.accepted, t.prompted.regressed, t.noise
|
||||
))
|
||||
);
|
||||
for (side, k) in t.r_roles() {
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!("calibrate class={} prompted-{side} {}", c.name, k.line()))
|
||||
);
|
||||
}
|
||||
for line in c.degraded_lines(°raded) {
|
||||
println!("{}", run.labelled(&format!("calibrate class={} {line}", c.name)));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!(
|
||||
"calibrate class={} candidate trials={} accepted={} nogain={} regressed={}",
|
||||
c.name, t.candidate.trials, t.candidate.accepted, t.candidate.nogain, t.candidate.regressed
|
||||
))
|
||||
);
|
||||
for (label, k) in candidate.iter().zip(&t.candidate_arms) {
|
||||
println!(
|
||||
"{}",
|
||||
run.labelled(&format!("calibrate class={} candidate={label} {}", c.name, k.line()))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Recall { root }) => {
|
||||
let run = RunStores::open(&root)?;
|
||||
let mut files = run.answer_files(run.recall_dir())?;
|
||||
let mut files = AnswerFiles::new(run.recall_dir(), run.record().model.clone());
|
||||
match run.recall(&mut files)? {
|
||||
RecallOutcome::Unanswered { prompts } => {
|
||||
for digest in &prompts {
|
||||
|
|
@ -1424,28 +799,13 @@ fn main() -> Result<()> {
|
|||
RecallOutcome::Read(reading) => println!("{}", reading.line()),
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::MintOntology { root, language }) => {
|
||||
let run = RunStores::open(&root)?;
|
||||
let mut files = run.answer_files(run.ontology_mint_dir())?;
|
||||
match run.mint_ontology(&mut files, &language)? {
|
||||
OntologyMintOutcome::Unanswered { prompt } => {
|
||||
println!("unanswered {prompt}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
OntologyMintOutcome::Drafted { prompt, entries } => println!(
|
||||
"drafted {entries} entries {}",
|
||||
run.ontology_mint_dir().join(format!("{prompt}.answer")).display()
|
||||
),
|
||||
OntologyMintOutcome::Refused { code } => {
|
||||
println!("{code}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Cycle { root, ollama_url }) => {
|
||||
let unreadable = |_| anyhow::anyhow!("a store would not read");
|
||||
let mut run = RunStores::open(&root)?;
|
||||
let mut files = run.answer_files(run.next_cycle_dir().map_err(unreadable)?)?;
|
||||
let mut files = AnswerFiles::new(
|
||||
run.next_cycle_dir().map_err(unreadable)?,
|
||||
run.record().model.clone(),
|
||||
);
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match cycle(&mut run, &mut files, &scorer)? {
|
||||
CycleOutcome::Unanswered { prompts } => {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ 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 {
|
||||
|
|
@ -21,8 +20,6 @@ pub trait ModelPort {
|
|||
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),
|
||||
}
|
||||
|
||||
|
|
@ -30,7 +27,6 @@ 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:?}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -44,62 +40,14 @@ impl std::error::Error for PortError {}
|
|||
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
|
||||
|
|
@ -107,13 +55,13 @@ impl ModelPort for AnswerFiles {
|
|||
|
||||
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,
|
||||
match std::fs::read(self.dir.join(format!("{digest}.answer"))) {
|
||||
Ok(bytes) => {
|
||||
return String::from_utf8(bytes).map_err(|_| PortError::Io(ErrorKind::InvalidData));
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(io(e)),
|
||||
}
|
||||
std::fs::create_dir_all(&self.dir).map_err(io)?;
|
||||
let path = self.dir.join(format!("{digest}.prompt"));
|
||||
|
|
|
|||
|
|
@ -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(&[]));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -4,7 +4,6 @@
|
|||
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};
|
||||
|
|
@ -26,7 +25,6 @@ pub fn published() -> Vec<(String, String)> {
|
|||
published_for::<Entity>(),
|
||||
published_for::<Speaker>(),
|
||||
published_for::<Scene>(),
|
||||
published_for::<OntologyEntry>(),
|
||||
published_for::<RunRecord>(),
|
||||
published_for::<RoundRecord>(),
|
||||
published_for::<Decision>(),
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ pub struct ScoreInput<'a> {
|
|||
pub output: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ItemScore {
|
||||
/// chrF of the output against the reference.
|
||||
pub chrf: f64,
|
||||
|
|
@ -131,18 +131,13 @@ pub struct Aggregate {
|
|||
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
|
||||
/// The mean of the scores of the items read in split `want`.
|
||||
fn split_mean(scored: &[(&CorpusItem, ItemScore)], want: Split) -> SplitMean {
|
||||
let of: Vec<&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);
|
||||
.collect();
|
||||
let average = |values: Vec<f64>| {
|
||||
(!values.is_empty()).then(|| values.iter().sum::<f64>() / values.len() as f64)
|
||||
};
|
||||
|
|
@ -162,12 +157,6 @@ pub fn aggregate(scored: &[(&CorpusItem, ItemScore)]) -> Aggregate {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
|
@ -260,31 +249,6 @@ mod tests {
|
|||
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);
|
||||
|
|
|
|||
|
|
@ -13,10 +13,8 @@
|
|||
//! 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`.
|
||||
//! ends a word. A leak in these scripts shows at n = 1 and in chrF; a
|
||||
//! dictionary segmenter is the ja-JP panel's to add.
|
||||
|
||||
use caseless::default_case_fold_str;
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
|
|
|||
|
|
@ -71,8 +71,6 @@ pub struct Scene {
|
|||
/// 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)]
|
||||
|
|
|
|||
|
|
@ -208,7 +208,6 @@ pub(crate) mod fixture {
|
|||
language: "en-US".into(),
|
||||
speaker: EntityId::parse("entity:nibu").unwrap(),
|
||||
names: vec![],
|
||||
names_by: None,
|
||||
group: group.into(),
|
||||
prior_turns: vec![],
|
||||
source,
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ use unicode_normalization::{UnicodeNormalization, char::is_combining_mark, is_nf
|
|||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::corpus::{CorpusItem, CorpusItemId, Source, item_key, key_slug};
|
||||
use crate::split::{Split, SplitScheme};
|
||||
use crate::entity::{Entity, EntityOrigin, Pronunciation};
|
||||
use crate::form::{
|
||||
is_attestation, is_calendar_date, is_joining_only, is_language_tag, is_refused_format, is_slug,
|
||||
|
|
@ -20,11 +19,7 @@ use crate::form::{
|
|||
use crate::inventory::{
|
||||
Change, InvId, Inventory, InventoryEntry, InventoryRevision, Slot, revision_key,
|
||||
};
|
||||
use crate::ontology::{
|
||||
MAX_CONDITIONS, MAX_CHOICE_BYTES, MAX_ENTRIES_PER_LANGUAGE, MAX_EXAMPLE_BYTES, MAX_EXAMPLES,
|
||||
Ontology, OntologyEntry, Test,
|
||||
};
|
||||
use crate::packet::{EntityId, FeatValue, Packet};
|
||||
use crate::packet::{EntityId, Packet};
|
||||
use crate::speaker::{Annotator, MAX_PARTICIPANTS, Party, Scene, Speaker, scene_key, speaker_key};
|
||||
use crate::validate::{LoweringInput, Refusal, feature_refusals, validate};
|
||||
|
||||
|
|
@ -249,17 +244,6 @@ impl CorpusStore {
|
|||
Ok(items)
|
||||
}
|
||||
|
||||
/// The text of every item in a Test group, any language, withdrawn and
|
||||
/// model-written ones included: what no prompt may hold.
|
||||
pub fn test_texts(&self) -> anyhow::Result<Vec<String>> {
|
||||
Ok(self
|
||||
.all()?
|
||||
.into_iter()
|
||||
.filter(|item| SplitScheme::V1.of_bucket(SplitScheme::V1.bucket(&item.group)) == Split::Test)
|
||||
.map(|item| item.text)
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> anyhow::Result<Option<CorpusItem>> {
|
||||
self.cache.get::<CorpusItem>(key)
|
||||
}
|
||||
|
|
@ -344,9 +328,6 @@ impl CorpusStore {
|
|||
if let Some(why) = empty_attestation(&item.source) {
|
||||
return Err(malformed(&item.id, why));
|
||||
}
|
||||
if let Some(by) = &item.names_by {
|
||||
check_annotator(&item.id, by)?;
|
||||
}
|
||||
check_entities(&item, entities)?;
|
||||
for held in self.all()? {
|
||||
if normalized(&held.text) == text && item.supersedes.as_deref() != Some(&held.id) {
|
||||
|
|
@ -1226,137 +1207,3 @@ fn check_next(key: &str, latest: u32, got: u32) -> Result<(), StoreError> {
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The language ontology: immutable entries admitted in all-or-nothing
|
||||
/// batches. The only writer of `weksa.ontology_entry`.
|
||||
pub struct OntologyStore {
|
||||
cache: CultCache,
|
||||
}
|
||||
|
||||
impl OntologyStore {
|
||||
pub fn open(path: &Path) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
cache: open_cache(path, |c| c.register_entry_type::<OntologyEntry>())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every entry, by language then number.
|
||||
pub fn all(&self) -> anyhow::Result<Vec<OntologyEntry>> {
|
||||
Ok(self.ontology()?.entries().to_vec())
|
||||
}
|
||||
|
||||
pub fn ontology(&self) -> anyhow::Result<Ontology> {
|
||||
Ok(Ontology::of(self.cache.get_all::<OntologyEntry>()?))
|
||||
}
|
||||
|
||||
/// Admits a batch whole or not at all; an identical replay of stored
|
||||
/// entries is `Unchanged`. Per language the batch's numbers run the
|
||||
/// language's latest plus one, consecutively, to at most
|
||||
/// `MAX_ENTRIES_PER_LANGUAGE` entries in all. Every entry passes
|
||||
/// [`check_ontology_entry`] against the inventory before any is put. No
|
||||
/// message echoes an entry's text.
|
||||
pub fn admit(
|
||||
&mut self,
|
||||
batch: Vec<OntologyEntry>,
|
||||
inventory: &InventoryStore,
|
||||
) -> Result<AddOutcome, StoreError> {
|
||||
let all = self.cache.get_all::<OntologyEntry>()?;
|
||||
if batch
|
||||
.iter()
|
||||
.all(|e| all.iter().any(|old| old == e))
|
||||
{
|
||||
return Ok(AddOutcome::Unchanged);
|
||||
}
|
||||
let inv = inventory.inventory()?;
|
||||
let mut counted: std::collections::BTreeMap<&str, u32> = std::collections::BTreeMap::new();
|
||||
for e in &batch {
|
||||
let key = e.key();
|
||||
if !is_language_tag(&e.language) {
|
||||
return Err(malformed(&key, "an ontology language is a language tag"));
|
||||
}
|
||||
let latest = match counted.get(e.language.as_str()) {
|
||||
Some(n) => *n,
|
||||
None => all
|
||||
.iter()
|
||||
.filter(|o| o.language == e.language)
|
||||
.map(|o| o.n)
|
||||
.max()
|
||||
.unwrap_or(0),
|
||||
};
|
||||
check_next(&key, latest, e.n)?;
|
||||
if e.n as usize > MAX_ENTRIES_PER_LANGUAGE {
|
||||
return Err(malformed(&key, "a language holds at most 64 entries"));
|
||||
}
|
||||
counted.insert(e.language.as_str(), e.n);
|
||||
check_ontology_entry(e, &inv, e.inventory_rev)?;
|
||||
}
|
||||
let mut staged = Vec::new();
|
||||
for e in &batch {
|
||||
staged.push(self.cache.prepare_entry_named(e.key(), e)?.0);
|
||||
}
|
||||
self.cache.put_prepared_batch(staged)?;
|
||||
Ok(AddOutcome::Added)
|
||||
}
|
||||
}
|
||||
|
||||
/// The rules of one ontology entry against an inventory: the annotator, the
|
||||
/// bounded and normalized text of the choice and examples, the condition count
|
||||
/// and each condition's feature (slot `Stance`, `Discourse` or `Scene`, a grade
|
||||
/// feature for `AtLeast`, `AtMost` and `AtMostOrUnset`, an option or flag value for `Is`) read at
|
||||
/// `rev`. The store passes the entry's own `inventory_rev` on admission; a run
|
||||
/// passes its inventory's head, because beds number revisions independently.
|
||||
pub(crate) fn check_ontology_entry(
|
||||
e: &OntologyEntry,
|
||||
inventory: &Inventory,
|
||||
rev: u32,
|
||||
) -> Result<(), StoreError> {
|
||||
let key = e.key();
|
||||
check_annotator(&key, &e.annotator)?;
|
||||
let text_ok = |t: &str, max: usize| {
|
||||
(1..=max).contains(&t.len())
|
||||
&& !t.chars().any(|c| c.is_control() || is_refused_format(c))
|
||||
&& is_nfc(t)
|
||||
};
|
||||
if !text_ok(&e.choice, MAX_CHOICE_BYTES) {
|
||||
return Err(malformed(
|
||||
&key,
|
||||
"a choice is 1 to 200 normalized bytes with no control or format character",
|
||||
));
|
||||
}
|
||||
if e.examples.len() > MAX_EXAMPLES
|
||||
|| !e.examples.iter().all(|x| text_ok(x, MAX_EXAMPLE_BYTES))
|
||||
{
|
||||
return Err(malformed(
|
||||
&key,
|
||||
"an entry has at most 3 examples of 1 to 120 normalized bytes with no control or format character",
|
||||
));
|
||||
}
|
||||
if e.when.len() > MAX_CONDITIONS {
|
||||
return Err(malformed(&key, "an entry has at most 4 conditions"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for c in &e.when {
|
||||
if !matches!(c.slot, Slot::Stance | Slot::Discourse | Slot::Scene) {
|
||||
return Err(malformed(
|
||||
&key,
|
||||
"a condition reads slot Stance, Discourse or Scene",
|
||||
));
|
||||
}
|
||||
if matches!(c.test, Test::Is(FeatValue::Grade(_))) {
|
||||
return Err(malformed(&key, "Is names an option or a flag"));
|
||||
}
|
||||
out.extend(feature_refusals(
|
||||
inventory,
|
||||
rev,
|
||||
&[c.as_value()],
|
||||
c.slot,
|
||||
));
|
||||
}
|
||||
if e.when.is_empty() && !inventory.has_revision(rev) {
|
||||
out.extend(feature_refusals(inventory, rev, &[], Slot::Stance));
|
||||
}
|
||||
if !out.is_empty() {
|
||||
return Err(StoreError::Invalid(out));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,10 +12,6 @@ fn weksa(dir: &std::path::Path, args: &[&str]) -> Output {
|
|||
"./i.cc",
|
||||
"--entities",
|
||||
"./e.cc",
|
||||
"--ontology",
|
||||
"./o.cc",
|
||||
"--speaker-state",
|
||||
"./s.cc",
|
||||
])
|
||||
.args(args)
|
||||
.output()
|
||||
|
|
@ -51,7 +47,7 @@ fn out(o: &Output) -> String {
|
|||
String::from_utf8_lossy(&o.stdout).into_owned() + &String::from_utf8_lossy(&o.stderr)
|
||||
}
|
||||
|
||||
const ADD: [&str; 16] = [
|
||||
const ADD: [&str; 14] = [
|
||||
"corpus",
|
||||
"add",
|
||||
"--slug",
|
||||
|
|
@ -66,8 +62,6 @@ const ADD: [&str; 16] = [
|
|||
"2026-10-29",
|
||||
"--source",
|
||||
"cast-authored",
|
||||
"--language",
|
||||
"en-US",
|
||||
];
|
||||
|
||||
#[test]
|
||||
|
|
@ -155,8 +149,6 @@ fn model_written_and_public_domain_sources_name_their_provenance() {
|
|||
let base = [
|
||||
"corpus",
|
||||
"add",
|
||||
"--language",
|
||||
"en-US",
|
||||
"--slug",
|
||||
"x",
|
||||
"--speaker",
|
||||
|
|
@ -320,7 +312,6 @@ fn schema_writes_the_published_files() {
|
|||
"weksa.loop_decision.schema.json",
|
||||
"weksa.loop_round.schema.json",
|
||||
"weksa.loop_run.schema.json",
|
||||
"weksa.ontology_entry.schema.json",
|
||||
"weksa.scene.schema.json",
|
||||
"weksa.speaker.schema.json"
|
||||
]
|
||||
|
|
@ -384,8 +375,6 @@ fn entity_put_and_name_spans() {
|
|||
&[
|
||||
"corpus",
|
||||
"add",
|
||||
"--language",
|
||||
"en-US",
|
||||
"--slug",
|
||||
"kay",
|
||||
"--text",
|
||||
|
|
@ -558,8 +547,6 @@ fn add_with(dir: &std::path::Path, source: &str, extra: &[&str]) -> Output {
|
|||
let mut args = vec![
|
||||
"corpus",
|
||||
"add",
|
||||
"--language",
|
||||
"en-US",
|
||||
"--slug",
|
||||
"nibu",
|
||||
"--text",
|
||||
|
|
@ -916,8 +903,6 @@ fn proof_packet_lowers_and_the_lowering_scores_against_items() {
|
|||
&[
|
||||
"corpus",
|
||||
"add",
|
||||
"--language",
|
||||
"en-US",
|
||||
"--slug",
|
||||
"nibu",
|
||||
"--text",
|
||||
|
|
@ -1077,7 +1062,7 @@ fn cli_errors_never_echo_identifiers() {
|
|||
let p = d.path();
|
||||
cast_entities(p, &["nibu"]);
|
||||
let add = |extra: &[&str]| -> Vec<String> {
|
||||
["corpus", "add", "--language", "en-US", "--admitted-on", "2026-10-29"]
|
||||
["corpus", "add", "--admitted-on", "2026-10-29"]
|
||||
.into_iter()
|
||||
.chain(extra.iter().copied())
|
||||
.map(String::from)
|
||||
|
|
@ -1342,8 +1327,6 @@ fn dao_stores(dir: &std::path::Path) {
|
|||
] {
|
||||
std::fs::copy(src.join(from), dir.join(to)).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("o.cc"), [0x90]).unwrap();
|
||||
std::fs::write(dir.join("s.cc"), [0x90]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1361,8 +1344,6 @@ fn loop_open_and_unanswered_round() {
|
|||
"smoke",
|
||||
"--answerer",
|
||||
"fake-model",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
"--answerer-family",
|
||||
|
|
@ -1416,7 +1397,7 @@ fn loop_open_and_unanswered_round() {
|
|||
assert!(second.status.success(), "{}", out(&second));
|
||||
assert_eq!(
|
||||
out(&second),
|
||||
"round 1 rev 4 en-US train n=1 scored=0 chrf=0.00 meaning=0.0000 refused=1 validation n=2 scored=0 chrf=0.00 meaning=0.0000 refused parse=2 admit=0 lower=0 parse-reasons=syntaxx3 lowering=tool-less-relay\n"
|
||||
"round 1 rev 3 train n=1 scored=0 chrf=0.00 meaning=0.0000 refused=1 validation n=2 scored=0 chrf=0.00 meaning=0.0000 refused parse=2 admit=0 lower=0 parse-reasons=syntaxx3 lowering=tool-less-relay\n"
|
||||
);
|
||||
|
||||
// The global store flags are not read by loop round: a drifted store is refused.
|
||||
|
|
@ -1443,8 +1424,6 @@ fn open_dao_run(d: &std::path::Path) {
|
|||
"smoke",
|
||||
"--answerer",
|
||||
"fake-model",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
],
|
||||
|
|
@ -1452,91 +1431,6 @@ fn open_dao_run(d: &std::path::Path) {
|
|||
assert!(o.status.success(), "{}", out(&o));
|
||||
}
|
||||
|
||||
/// `weksa loop mint-ontology`: exit 3 and a prompt file until answered, exit 0
|
||||
/// and the answer path once it is a draft, a missing language or one outside
|
||||
/// the panel refused, and nothing of the run written.
|
||||
#[test]
|
||||
fn loop_mint_ontology_protocol() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let root = d.path().join("canaryroot");
|
||||
let held = |name: &str| std::fs::read(root.join(name)).unwrap();
|
||||
let (run_cc, onto) = (held("run.cc"), std::fs::read(d.path().join("o.cc")).unwrap());
|
||||
let mint = |args: &[&str]| weksa(d.path(), &[&["loop", "mint-ontology", "canaryroot"], args].concat());
|
||||
|
||||
let none = mint(&[]);
|
||||
assert_eq!(none.status.code(), Some(2), "{}", out(&none));
|
||||
assert!(!root.join("ontology-mint").exists());
|
||||
|
||||
let outside = mint(&["--language", "ja-JP"]);
|
||||
assert_eq!(outside.status.code(), Some(1), "{}", out(&outside));
|
||||
assert_eq!(out(&outside), "language-not-in-panel\n");
|
||||
assert!(!root.join("ontology-mint").exists(), "a refused mint wrote a prompt");
|
||||
|
||||
let first = mint(&["--language", "en-US"]);
|
||||
assert_eq!(first.status.code(), Some(3), "{}", out(&first));
|
||||
let text = out(&first);
|
||||
let digest = text.strip_prefix("unanswered ").unwrap().trim_end();
|
||||
assert_eq!(digest.len(), 16, "{text}");
|
||||
let dir = root.join("ontology-mint");
|
||||
assert!(dir.join(format!("{digest}.prompt")).is_file());
|
||||
|
||||
let answer = dir.join(format!("{digest}.answer"));
|
||||
std::fs::write(&answer, r#"{"entries":[{"layer":"Grammar","choice":"a pattern"}]}"#).unwrap();
|
||||
let done = mint(&["--language", "en-US"]);
|
||||
assert_eq!(done.status.code(), Some(0), "{}", out(&done));
|
||||
assert_eq!(out(&done), format!("drafted 1 entries canaryroot/ontology-mint/{digest}.answer\n"));
|
||||
|
||||
std::fs::write(&answer, "not json").unwrap();
|
||||
let bad = mint(&["--language", "en-US"]);
|
||||
assert_eq!(bad.status.code(), Some(1), "{}", out(&bad));
|
||||
assert_eq!(out(&bad), "syntax\n");
|
||||
|
||||
assert_eq!(held("run.cc"), run_cc, "the mint wrote the run record");
|
||||
assert_eq!(std::fs::read(d.path().join("o.cc")).unwrap(), onto);
|
||||
}
|
||||
|
||||
/// The family `loop open` pinned at `root`, read from the run record.
|
||||
fn pinned_family(d: &std::path::Path, root: &str, flag: &[&str]) -> weksa::corpus::ModelFamily {
|
||||
let mut args = vec![
|
||||
"loop",
|
||||
"open",
|
||||
root,
|
||||
"--label",
|
||||
"fam",
|
||||
"--answerer",
|
||||
"fake-model",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
];
|
||||
args.extend_from_slice(flag);
|
||||
let o = weksa(d, &args);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
weksa::run::RunStores::open(&d.join(root))
|
||||
.unwrap()
|
||||
.record()
|
||||
.answerer_family
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_open_pins_answerer_family() {
|
||||
use weksa::corpus::ModelFamily;
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
dao_stores(d.path());
|
||||
assert_eq!(
|
||||
pinned_family(d.path(), "a", &["--answerer-family", "anthropic"]),
|
||||
ModelFamily::Anthropic
|
||||
);
|
||||
assert_eq!(
|
||||
pinned_family(d.path(), "b", &["--answerer-family", "mistral"]),
|
||||
ModelFamily::Mistral
|
||||
);
|
||||
// Omitted, the family stays unrecorded and a round prints no own-family line.
|
||||
assert_eq!(pinned_family(d.path(), "c", &[]), ModelFamily::Unrecorded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_cycle_needs_a_floor() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
|
@ -1545,7 +1439,7 @@ fn loop_cycle_needs_a_floor() {
|
|||
assert!(!o.status.success());
|
||||
let text = out(&o);
|
||||
assert!(
|
||||
text.contains("the run has no noise floor: record four rounds under the first inventory first"),
|
||||
text.contains("the run has no noise floor: record two rounds first"),
|
||||
"{text}"
|
||||
);
|
||||
for echoed in ["canaryroot", d.path().to_str().unwrap()] {
|
||||
|
|
@ -1558,8 +1452,8 @@ fn loop_cycle_needs_a_floor() {
|
|||
fn loop_cycle_asks_then_decides() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
// Four rounds of refusals: a floor of 0 and a base of 0.
|
||||
for n in 1..=4 {
|
||||
// Two rounds of refusals: a floor of 0 and a base of 0.
|
||||
for n in 1..=2 {
|
||||
let first = weksa(d.path(), &["loop", "round", "canaryroot"]);
|
||||
assert_eq!(first.status.code(), Some(3), "{}", out(&first));
|
||||
for entry in std::fs::read_dir(d.path().join(format!("canaryroot/round-{n}"))).unwrap() {
|
||||
|
|
@ -1593,7 +1487,7 @@ fn loop_cycle_asks_then_decides() {
|
|||
assert!(done.status.success(), "{}", out(&done));
|
||||
assert_eq!(
|
||||
out(&done),
|
||||
"cycle 1 rev 4->none en-US base=0.0000 candidate=none floor=0.0000 threshold=0.0050 rejected edit-parse lowering=tool-less-relay\n"
|
||||
"cycle 1 rev 3->none base=0.0000 candidate=none floor=0.0000 threshold=0.0050 rejected edit-parse lowering=tool-less-relay\n"
|
||||
);
|
||||
|
||||
// The next cycle asks afresh in its own directory.
|
||||
|
|
@ -1632,8 +1526,6 @@ fn loop_errors_echo_no_input() {
|
|||
"CANARYLABEL",
|
||||
"--answerer",
|
||||
"m",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
],
|
||||
|
|
@ -1645,8 +1537,6 @@ fn loop_errors_echo_no_input() {
|
|||
"ok",
|
||||
"--answerer",
|
||||
"CANARY\n",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
],
|
||||
|
|
@ -1668,8 +1558,6 @@ fn loop_errors_echo_no_input() {
|
|||
"ok",
|
||||
"--answerer",
|
||||
"m",
|
||||
"--panel",
|
||||
"en-US",
|
||||
"--lowerer-reach",
|
||||
"tool-less-relay",
|
||||
])
|
||||
|
|
@ -1683,7 +1571,7 @@ fn loop_errors_echo_no_input() {
|
|||
fn loop_open_requires_the_lowerer_reach_and_pins_it() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
dao_stores(d.path());
|
||||
let base = ["loop", "open", "canaryroot", "--label", "smoke", "--answerer", "m", "--panel", "en-US"];
|
||||
let base = ["loop", "open", "canaryroot", "--label", "smoke", "--answerer", "m"];
|
||||
// No default: the record says how lowerings are answered, or there is no run.
|
||||
let o = weksa(d.path(), &base);
|
||||
assert!(!o.status.success());
|
||||
|
|
@ -1706,588 +1594,3 @@ fn loop_open_requires_the_lowerer_reach_and_pins_it() {
|
|||
weksa::run::LowererReach::BriefedSubagent
|
||||
);
|
||||
}
|
||||
|
||||
/// Answers the Dao encode prompts with the Dao packets and every lowering with
|
||||
/// one sentence.
|
||||
struct DaoModel;
|
||||
|
||||
impl weksa::model::ModelPort for DaoModel {
|
||||
fn model(&self) -> &str {
|
||||
"fake-model"
|
||||
}
|
||||
fn answer(&mut self, prompt: &weksa::context::Prompt) -> Result<String, weksa::model::PortError> {
|
||||
if prompt.text().starts_with(weksa::context::LOWER_INSTRUCTIONS) {
|
||||
return Ok(r#"{"text":"The highest excellence is like the water."}"#.into());
|
||||
}
|
||||
let n: usize = prompt.item_keys()[0].rsplit(':').next().unwrap().parse().unwrap();
|
||||
Ok(serde_json::to_string(&weksa::PacketDraft::of(&weksa::daodejing::packets()[n - 1])).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_ablate_waits_then_prints_one_line_per_split() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let url = fake_embedder();
|
||||
let root = d.path().join("canaryroot");
|
||||
|
||||
// Record round 1 the way `loop round` does, then put its lowering answers
|
||||
// where the relay would have.
|
||||
let mut run = weksa::run::RunStores::open(&root).unwrap();
|
||||
let scorer = weksa::Scorer::new(weksa::OllamaEmbedder::new(&url, &run.record().embedder));
|
||||
let weksa::run::RoundOutcome::Recorded(r) = weksa::run::round(&mut run, &mut DaoModel, &scorer).unwrap()
|
||||
else {
|
||||
panic!("answered")
|
||||
};
|
||||
for call in &r.calls()[3..] {
|
||||
std::fs::write(
|
||||
root.join(format!("round-1/{}.answer", call.prompt)),
|
||||
r#"{"text":"The highest excellence is like the water."}"#,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let ablate = || weksa(d.path(), &["loop", "ablate", "canaryroot", "--round", "1", "--ollama-url", &url]);
|
||||
let first = ablate();
|
||||
assert_eq!(first.status.code(), Some(3), "{}", out(&first));
|
||||
let text = out(&first);
|
||||
let digests: Vec<&str> = text
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("unanswered "))
|
||||
.filter(|d| d.len() == 16)
|
||||
.collect();
|
||||
// Three replays, three drops and the Validation permutes (2 items).
|
||||
assert_eq!(digests.len(), 3 + 3 + 2, "{text}");
|
||||
for digest in &digests {
|
||||
assert!(root.join(format!("ablation-1/{digest}.prompt")).is_file());
|
||||
std::fs::write(
|
||||
root.join(format!("ablation-1/{digest}.answer")),
|
||||
r#"{"text":"The highest excellence is like the water."}"#,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let second = ablate();
|
||||
assert!(second.status.success(), "{}", out(&second));
|
||||
let text = out(&second);
|
||||
assert_eq!(
|
||||
text,
|
||||
"en-US train ablation n=1 unusable=0 replay chrf=100.00 meaning=1.000 | drop n=1 chrf=100.00 meaning=1.000 moved=0 ref_gain_chrf=0.00 ref_gain_meaning=0.000 | permute n=0 chrf=none meaning=none moved=0 ref_gain_chrf=none ref_gain_meaning=none\nen-US validation ablation n=2 unusable=0 replay chrf=100.00 meaning=1.000 | drop n=2 chrf=100.00 meaning=1.000 moved=0 ref_gain_chrf=0.00 ref_gain_meaning=0.000 | permute n=2 chrf=100.00 meaning=1.000 moved=0 ref_gain_chrf=0.00 ref_gain_meaning=0.000\n"
|
||||
);
|
||||
for leaked in ["item:", "packet:", "highest excellence", "canaryroot"] {
|
||||
assert!(!text.contains(leaked), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_loop_relower_exits_3_until_answered_and_refuses_bad_labels() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let url = fake_embedder();
|
||||
let root = d.path().join("canaryroot");
|
||||
let mut run = weksa::run::RunStores::open(&root).unwrap();
|
||||
let scorer = weksa::Scorer::new(weksa::OllamaEmbedder::new(&url, &run.record().embedder));
|
||||
let weksa::run::RoundOutcome::Recorded(r) = weksa::run::round(&mut run, &mut DaoModel, &scorer).unwrap()
|
||||
else {
|
||||
panic!("answered")
|
||||
};
|
||||
let said = r#"{"text":"The highest excellence is like the water."}"#;
|
||||
for call in &r.calls()[3..] {
|
||||
std::fs::write(root.join(format!("round-1/{}.answer", call.prompt)), said).unwrap();
|
||||
}
|
||||
let relower = |extra: &[&str]| {
|
||||
weksa(
|
||||
d.path(),
|
||||
&[&["loop", "relower", "canaryroot", "--round", "1", "--lowerer", "tuned-x", "--ollama-url", &url], extra].concat(),
|
||||
)
|
||||
};
|
||||
|
||||
// Unanswered: exit 3, the digests, a prompt file per digest in the arm's directory.
|
||||
let first = relower(&["--arm", "tuned"]);
|
||||
assert_eq!(first.status.code(), Some(3), "{}", out(&first));
|
||||
let text = out(&first);
|
||||
let digests: Vec<&str> = text
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("unanswered "))
|
||||
.filter(|x| x.len() == 16)
|
||||
.collect();
|
||||
assert_eq!(digests.len(), 2, "the two Validation prompts: {text}");
|
||||
for digest in &digests {
|
||||
assert!(root.join(format!("relower-1-tuned/{digest}.prompt")).is_file());
|
||||
std::fs::write(root.join(format!("relower-1-tuned/{digest}.answer")), said).unwrap();
|
||||
}
|
||||
|
||||
// Answered: one line per language, labelled, naming the lowerer; no verdict without a floor.
|
||||
let second = relower(&["--arm", "tuned"]);
|
||||
assert!(second.status.success(), "{}", out(&second));
|
||||
let text = out(&second);
|
||||
assert!(text.starts_with("relower en-US n=2 skipped=0 unusable=0 recorded "), "{text}");
|
||||
assert!(text.contains("arm=tuned lowerer=tuned-x"), "{text}");
|
||||
assert!(text.contains(" lowering="), "{text}");
|
||||
assert!(!text.contains("verdict") && !text.contains("floor"), "{text}");
|
||||
for leaked in ["item:", "packet:", "highest excellence", "canaryroot"] {
|
||||
assert!(!text.contains(leaked), "{text}");
|
||||
}
|
||||
|
||||
// A floor arm that is not answered whole is refused, and never written to.
|
||||
let o = relower(&["--arm", "tuned", "--floor", "second"]);
|
||||
assert_eq!(o.status.code(), Some(1), "{}", out(&o));
|
||||
assert!(!root.join("relower-1-second").exists());
|
||||
|
||||
// Fewer than three floor arms is refused: one pair measures no noise.
|
||||
let o = relower(&["--arm", "tuned", "--floor", "second"]);
|
||||
assert_eq!(o.status.code(), Some(1), "{}", out(&o));
|
||||
assert!(out(&o).contains("three or more floor arms"), "{}", out(&o));
|
||||
|
||||
// Answered floors: a verdict line.
|
||||
for label in ["second", "third", "fourth"] {
|
||||
std::fs::create_dir_all(root.join(format!("relower-1-{label}"))).unwrap();
|
||||
for digest in &digests {
|
||||
std::fs::write(root.join(format!("relower-1-{label}/{digest}.answer")), said).unwrap();
|
||||
}
|
||||
}
|
||||
let o = relower(&["--arm", "tuned", "--floor", "second", "--floor", "third", "--floor", "fourth"]);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let text = out(&o);
|
||||
assert!(text.contains("| floor chrf=0.00") && text.trim_end().ends_with("verdict Rejected(NoGain)"), "{text}");
|
||||
|
||||
// Labels: equal, uppercase, empty, too long, a path.
|
||||
let long = "a".repeat(33);
|
||||
for args in [
|
||||
vec!["--arm", "same", "--floor", "same"],
|
||||
vec!["--arm", "Upper"],
|
||||
vec!["--arm", ""],
|
||||
vec!["--arm", &long],
|
||||
vec!["--arm", "../x"],
|
||||
vec!["--arm", "tuned", "--floor", "Bad"],
|
||||
vec!["--arm", "tuned", "--floor", "b", "--floor", "b", "--floor", "c"],
|
||||
] {
|
||||
let o = relower(&args);
|
||||
assert_eq!(o.status.code(), Some(1), "{args:?}: {}", out(&o));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_loop_calibrate_reads_answered_draws_and_refuses_unanswered_and_bad_labels() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let url = fake_embedder();
|
||||
let root = d.path().join("canaryroot");
|
||||
let mut run = weksa::run::RunStores::open(&root).unwrap();
|
||||
let scorer = weksa::Scorer::new(weksa::OllamaEmbedder::new(&url, &run.record().embedder));
|
||||
let weksa::run::RoundOutcome::Recorded(r) = weksa::run::round(&mut run, &mut DaoModel, &scorer).unwrap()
|
||||
else {
|
||||
panic!("answered")
|
||||
};
|
||||
let said = r#"{"text":"The highest excellence is like the water."}"#;
|
||||
for call in &r.calls()[3..] {
|
||||
std::fs::write(root.join(format!("round-1/{}.answer", call.prompt)), said).unwrap();
|
||||
}
|
||||
let calibrate = |extra: &[&str]| {
|
||||
weksa(
|
||||
d.path(),
|
||||
&[&["loop", "calibrate", "canaryroot", "--round", "1", "--ollama-url", &url], extra].concat(),
|
||||
)
|
||||
};
|
||||
let four = ["--prompted", "p1", "--prompted", "p2", "--prompted", "p3", "--prompted", "p4"];
|
||||
|
||||
// Unanswered draws: exit 1, each label with its missing count, no relower directory created.
|
||||
let o = calibrate(&four);
|
||||
assert_eq!(o.status.code(), Some(1), "{}", out(&o));
|
||||
let text = out(&o);
|
||||
for label in ["p1", "p2", "p3", "p4"] {
|
||||
assert!(text.contains(&format!("unanswered {label} 2")), "{text}");
|
||||
assert!(!root.join(format!("relower-1-{label}")).exists());
|
||||
}
|
||||
assert!(text.contains("answer it through weksa loop relower"), "{text}");
|
||||
|
||||
// Answer every draw through relower's door; from here the only thing that can refuse is the argument.
|
||||
let o = weksa(
|
||||
d.path(),
|
||||
&["loop", "relower", "canaryroot", "--round", "1", "--lowerer", "x", "--arm", "p1", "--ollama-url", &url],
|
||||
);
|
||||
assert_eq!(o.status.code(), Some(3), "{}", out(&o));
|
||||
let digests: Vec<String> = out(&o)
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("unanswered "))
|
||||
.filter(|x| x.len() == 16)
|
||||
.map(String::from)
|
||||
.collect();
|
||||
assert_eq!(digests.len(), 2);
|
||||
// `P1` and `a_b` are answered too, so only the label check can refuse them.
|
||||
for label in ["p1", "p2", "p3", "p4", "bad", "cand1", "cand2", "P1", "a_b"] {
|
||||
std::fs::create_dir_all(root.join(format!("relower-1-{label}"))).unwrap();
|
||||
for digest in &digests {
|
||||
std::fs::write(root.join(format!("relower-1-{label}/{digest}.answer")), said).unwrap();
|
||||
}
|
||||
}
|
||||
// A draw answered in part.
|
||||
std::fs::create_dir_all(root.join("relower-1-part")).unwrap();
|
||||
std::fs::write(root.join(format!("relower-1-part/{}.answer", digests[0])), said).unwrap();
|
||||
let o = calibrate(&["--prompted", "p1", "--prompted", "p2", "--prompted", "p3", "--prompted", "part"]);
|
||||
assert_eq!(o.status.code(), Some(1), "{}", out(&o));
|
||||
assert!(out(&o).contains("unanswered part 1") && !out(&o).contains("unanswered p1"), "{}", out(&o));
|
||||
|
||||
// Refusals, every draw answered: the baseline reads, each variant differs by one fault.
|
||||
assert!(calibrate(&four).status.success());
|
||||
for args in [
|
||||
vec!["--prompted", "p1", "--prompted", "p2", "--prompted", "p3"],
|
||||
vec!["--prompted", "p1", "--prompted", "p2", "--prompted", "p3", "--prompted", "p3"],
|
||||
vec!["--prompted", "p1", "--prompted", "p2", "--prompted", "p3", "--prompted", "p4", "--degraded", "p4"],
|
||||
vec!["--prompted", "p1", "--prompted", "p2", "--prompted", "p3", "--prompted", "p4", "--candidate", "bad", "--degraded", "bad"],
|
||||
vec!["--prompted", "P1", "--prompted", "p2", "--prompted", "p3", "--prompted", "p4"],
|
||||
vec!["--prompted", "a_b", "--prompted", "p2", "--prompted", "p3", "--prompted", "p4"],
|
||||
[&four[..], &["--class", "all=item:"]].concat(),
|
||||
[&four[..], &["--class", "noequals"]].concat(),
|
||||
[&four[..], &["--class", "Old=item:a"]].concat(),
|
||||
[&four[..], &["--class", "old=item:a,"]].concat(),
|
||||
[&four[..], &["--class", "old=item:a", "--class", "old=item:b"]].concat(),
|
||||
] {
|
||||
let o = calibrate(&args);
|
||||
assert_eq!(o.status.code(), Some(1), "{args:?}: {}", out(&o));
|
||||
assert!(!out(&o).contains("unanswered"), "{args:?} must be refused for itself: {}", out(&o));
|
||||
}
|
||||
|
||||
let o = calibrate(
|
||||
&[&four[..], &["--degraded", "bad", "--candidate", "cand1", "--candidate", "cand2", "--class", "old=item:daodejing"]].concat(),
|
||||
);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let text = out(&o);
|
||||
assert!(text.starts_with("calibrate draws prompted=4 degraded=1 candidate=2 floor-arms=3 unusable=0"), "{text}");
|
||||
assert!(text.contains("calibrate class=all items en-US n=2 skipped=0"), "{text}");
|
||||
assert!(text.contains("calibrate class=all prompted trials=20 nogain=20 accepted=0 regressed=0"), "{text}");
|
||||
for side in ["r-candidate trials=4", "r-base trials=4", "r-free trials=12"] {
|
||||
assert!(text.contains(&format!("calibrate class=all prompted-{side} nogain=")), "{text}");
|
||||
}
|
||||
assert!(text.contains("calibrate class=old degraded=bad trials=20 regressed=0 offset en-US=+0.0000"), "{text}");
|
||||
// The class=all lines in print order: prompted, its three R roles, degraded, pooled candidate, each candidate arm.
|
||||
let all: Vec<&str> = text.lines().filter(|l| l.contains("calibrate class=all ")).collect();
|
||||
let kinds = ["items", "prompted trials", "prompted-r-candidate", "prompted-r-base", "prompted-r-free", "degraded=bad", "candidate trials", "candidate=cand1", "candidate=cand2"];
|
||||
assert_eq!(all.len(), kinds.len(), "{text}");
|
||||
for (line, kind) in all.iter().zip(kinds) {
|
||||
assert!(line.contains(&format!("class=all {kind}")), "{kind}: {line}");
|
||||
}
|
||||
assert!(all[7].contains("candidate=cand1 trials=20 nogain=20 accepted=0 regressed=0"), "{}", all[7]);
|
||||
for leaked in ["item:daodejing", "packet:", "highest excellence", "canaryroot"] {
|
||||
assert!(!text.contains(leaked), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_ablate_without_the_rounds_answers_says_so() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let url = fake_embedder();
|
||||
let root = d.path().join("canaryroot");
|
||||
let mut run = weksa::run::RunStores::open(&root).unwrap();
|
||||
let scorer = weksa::Scorer::new(weksa::OllamaEmbedder::new(&url, &run.record().embedder));
|
||||
weksa::run::round(&mut run, &mut DaoModel, &scorer).unwrap();
|
||||
let o = weksa(d.path(), &["loop", "ablate", "canaryroot", "--round", "1", "--ollama-url", &url]);
|
||||
assert!(!o.status.success());
|
||||
let text = out(&o);
|
||||
assert!(text.contains("holds no answer") && text.contains("head inventory"), "{text}");
|
||||
assert!(!text.contains("would not read"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_and_language_are_required() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
dao_stores(d.path());
|
||||
// No panel: a run says what it reads, or there is no run.
|
||||
let o = weksa(
|
||||
d.path(),
|
||||
&[
|
||||
"loop", "open", "canaryroot", "--label", "smoke", "--answerer", "m",
|
||||
"--lowerer-reach", "tool-less-relay",
|
||||
],
|
||||
);
|
||||
assert!(!o.status.success());
|
||||
assert!(out(&o).contains("--panel"), "{}", out(&o));
|
||||
assert!(!d.path().join("canaryroot/run.cc").exists());
|
||||
// No language: no language is the unmarked one.
|
||||
let o = weksa(d.path(), &ADD[..ADD.len() - 2]);
|
||||
assert!(!o.status.success());
|
||||
assert!(out(&o).contains("--language"), "{}", out(&o));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_and_dump() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
dao_stores(d.path());
|
||||
let draft = |name: &str, body: &str| {
|
||||
std::fs::write(d.path().join(name), body).unwrap();
|
||||
};
|
||||
draft(
|
||||
"good.json",
|
||||
r#"{"entries": [{"layer": "Discourse", "when": [{"slot": "Stance", "feature": "feature:18", "test": {"AtLeast": 600}}], "choice": "SOFTCHOICE", "examples": ["EXAMPLETEXT"]}, {"layer": "Lexicon", "choice": "plain"}]}"#,
|
||||
);
|
||||
let admit = |file: &str| {
|
||||
weksa(
|
||||
d.path(),
|
||||
&[
|
||||
"ontology", "admit", file, "--language", "ja-JP", "--inventory-rev", "1",
|
||||
"--model-family", "anthropic", "--generator", "a drafting model",
|
||||
],
|
||||
)
|
||||
};
|
||||
let o = admit("good.json");
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let o = weksa(d.path(), &["ontology", "dump"]);
|
||||
let text = out(&o);
|
||||
assert_eq!(text.matches("onto:ja-JP:").count(), 2, "{text}");
|
||||
for want in ["onto:ja-JP:1", "onto:ja-JP:2", "Anthropic", "a drafting model", "SOFTCHOICE", "EXAMPLETEXT", "Stance"] {
|
||||
assert!(text.contains(want), "{want}: {text}");
|
||||
}
|
||||
// A second draft numbers on from the language's latest.
|
||||
let o = admit("good.json");
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
assert!(out(&weksa(d.path(), &["ontology", "dump"])).contains("onto:ja-JP:4"));
|
||||
// A refused draft writes nothing and echoes no choice text.
|
||||
draft(
|
||||
"bad.json",
|
||||
r#"{"entries": [{"layer": "Discourse", "when": [{"slot": "Stance", "feature": "feature:9999", "test": {"AtLeast": 600}}], "choice": "LEAKYCHOICE"}]}"#,
|
||||
);
|
||||
let before = out(&weksa(d.path(), &["ontology", "dump"]));
|
||||
let o = admit("bad.json");
|
||||
assert!(!o.status.success());
|
||||
assert!(!out(&o).contains("LEAKYCHOICE"), "{}", out(&o));
|
||||
assert_eq!(out(&weksa(d.path(), &["ontology", "dump"])), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_put_and_dump() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
cast_entities(d.path(), &["nibu", "brokkr"]);
|
||||
for step in ["seed", "proof", "speaker-scene"] {
|
||||
let o = weksa(d.path(), &["inventory", step]);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
}
|
||||
let mut add = ADD.to_vec();
|
||||
add.extend(["--persona", "nibu", "--fixture", "f.yaml", "--author", "Ada Writer"]);
|
||||
let o = weksa(d.path(), &add);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let put = |group: &str, to: &str, sets: &[&str]| {
|
||||
let mut args = vec![
|
||||
"scene", "put", "--group", group, "--to", to, "--inventory-rev", "3",
|
||||
"--model-family", "anthropic", "--generator", "a scene annotator",
|
||||
];
|
||||
for s in sets {
|
||||
args.extend(["--set", s]);
|
||||
}
|
||||
weksa(d.path(), &args)
|
||||
};
|
||||
let sets = ["relative_status=above", "intimacy=200", "in_group=false"];
|
||||
let o = put("scene-1", "unnamed", &sets);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let dump = out(&weksa(d.path(), &["scene", "dump"]));
|
||||
for want in ["scene:scene-1@1", "rev:3", "Anthropic", "a scene annotator", "entity:nibu->unnamed", "relative_status=above", "intimacy=200", "in_group=false"] {
|
||||
assert!(dump.contains(want), "{want}: {dump}");
|
||||
}
|
||||
// A repeat is unchanged and writes nothing.
|
||||
let o = put("scene-1", "unnamed", &sets);
|
||||
assert!(out(&o).contains("unchanged"), "{}", out(&o));
|
||||
assert_eq!(out(&weksa(d.path(), &["scene", "dump"])), dump);
|
||||
// A changed value is the next revision.
|
||||
let o = put("scene-1", "unnamed", &["relative_status=level", "intimacy=200", "in_group=false"]);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
assert!(out(&weksa(d.path(), &["scene", "dump"])).contains("scene:scene-1@2"));
|
||||
// An unknown gloss and an unknown group are refused and not echoed.
|
||||
for (group, set) in [("scene-1", "canarygloss=1"), ("canarygroup", "intimacy=1")] {
|
||||
let before = out(&weksa(d.path(), &["scene", "dump"]));
|
||||
let o = put(group, "unnamed", &[set]);
|
||||
assert!(!o.status.success());
|
||||
assert!(!out(&o).contains("canary"), "{}", out(&o));
|
||||
assert_eq!(out(&weksa(d.path(), &["scene", "dump"])), before);
|
||||
}
|
||||
// A group with two live speakers is refused: multi-party scenes wait.
|
||||
let mut two = add.clone();
|
||||
let at = two.iter().position(|a| *a == "entity:nibu").unwrap();
|
||||
two[at] = "entity:brokkr";
|
||||
let at = two.iter().position(|a| *a == "nibu").unwrap();
|
||||
two[at] = "brokkr";
|
||||
two.retain(|a| *a != "Mind the hatch.");
|
||||
let at = two.iter().position(|a| *a == "--text").unwrap() + 1;
|
||||
two.insert(at, "Brokkr speaks.");
|
||||
let o = weksa(d.path(), &two);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
let o = put("scene-1", "unnamed", &sets);
|
||||
assert!(!o.status.success());
|
||||
assert!(!out(&o).contains("scene-1"), "{}", out(&o));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_admit_numbers_a_draft_and_refuses_an_empty_one() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
assert!(weksa(d.path(), &["inventory", "seed"]).status.success());
|
||||
let path = |name: &str, text: &str| {
|
||||
let p = d.path().join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_str().unwrap().to_owned()
|
||||
};
|
||||
let before = out(&weksa(d.path(), &["inventory", "dump"]));
|
||||
|
||||
for (name, text) in [("empty.json", "{}"), ("junk.json", "not json at all")] {
|
||||
let refused = weksa(d.path(), &["inventory", "admit", &path(name, text)]);
|
||||
assert!(!refused.status.success(), "{}", out(&refused));
|
||||
assert_eq!(before, out(&weksa(d.path(), &["inventory", "dump"])));
|
||||
}
|
||||
|
||||
let draft = path(
|
||||
"draft.json",
|
||||
r#"{"add":[{"family":"Concept","gloss":"bath_house"},{"family":"Frame","gloss":"fly_a_kite"}]}"#,
|
||||
);
|
||||
let admitted = weksa(d.path(), &["inventory", "admit", &draft]);
|
||||
assert!(admitted.status.success(), "{}", out(&admitted));
|
||||
assert!(out(&admitted).contains("admitted rev:2 with 2 entries"));
|
||||
let dump = out(&weksa(d.path(), &["inventory", "dump"]));
|
||||
assert!(dump.contains("bath_house") && dump.contains("fly_a_kite"), "{dump}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_admit_cap_is_256_and_a_refusal_writes_nothing() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
assert!(weksa(d.path(), &["inventory", "seed"]).status.success());
|
||||
let draft = |name: &str, n: usize| {
|
||||
let adds: Vec<String> = (0..n)
|
||||
.map(|i| format!(r#"{{"family":"Concept","gloss":"cap_probe_{i}"}}"#))
|
||||
.collect();
|
||||
let p = d.path().join(name);
|
||||
std::fs::write(&p, format!(r#"{{"add":[{}]}}"#, adds.join(","))).unwrap();
|
||||
p.to_str().unwrap().to_owned()
|
||||
};
|
||||
let before = out(&weksa(d.path(), &["inventory", "dump"]));
|
||||
|
||||
let refused = weksa(d.path(), &["inventory", "admit", &draft("over.json", 257)]);
|
||||
assert!(!refused.status.success(), "{}", out(&refused));
|
||||
assert_eq!(before, out(&weksa(d.path(), &["inventory", "dump"])));
|
||||
|
||||
let admitted = weksa(d.path(), &["inventory", "admit", &draft("cap.json", 256)]);
|
||||
assert!(admitted.status.success(), "{}", out(&admitted));
|
||||
assert!(out(&admitted).contains("admitted rev:2 with 256 entries"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corpus_import_labels_spans_and_is_idempotent() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let work = d.path().join("work.json");
|
||||
std::fs::write(
|
||||
&work,
|
||||
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":"Orsa, I will not."}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let names = d.path().join("names.jsonl");
|
||||
std::fs::write(
|
||||
&names,
|
||||
concat!(
|
||||
r#"{"line":1,"marked":"[[entity:tamsin|Tamsin]], bring the lantern."}"#, "\n\n",
|
||||
r#"{"line":2,"marked":"[[entity:orsa|Orsa]], I will not."}"#, "\n",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let (w, n) = (work.to_str().unwrap(), names.to_str().unwrap());
|
||||
let bare = weksa(d.path(), &["corpus", "import", w, n]);
|
||||
assert!(!bare.status.success());
|
||||
let flags = ["--model-family", "anthropic", "--generator", "a name annotator"];
|
||||
let run = || weksa(d.path(), &[&["corpus", "import", w, n][..], &flags].concat());
|
||||
let first = run();
|
||||
assert!(first.status.success(), "{}", out(&first));
|
||||
let text = out(&first);
|
||||
assert!(text.contains("Added item:lantern-wager:1 ") && text.contains("Added item:lantern-wager:2 "), "{text}");
|
||||
assert!(text.contains("Added entity:orsa"), "{text}");
|
||||
let second = out(&run());
|
||||
assert!(second.contains("Unchanged item:lantern-wager:1 ") && !second.contains("Added"), "{second}");
|
||||
let dump = out(&weksa(d.path(), &["corpus", "dump"]));
|
||||
assert!(dump.contains("by Some(Model"), "{dump}");
|
||||
}
|
||||
|
||||
const LANTERN_CAST: &str = r#""cast":[{"entity":"entity:orsa","forms":["Orsa"]},{"entity":"entity:tamsin","forms":["Tamsin","Tam"]}]"#;
|
||||
const LANTERN_SOURCE: &str = r#""source":{"PublicDomain":{"work":"The Lantern Wager","author":"A. Invented","edition_url":"https://example.invalid/lantern","licence":"public domain","jurisdiction":"US","translator":"none","edition_year":1890}}"#;
|
||||
|
||||
/// Writes a work of `lines` (text per line, all said by Orsa) and an answer of
|
||||
/// `marked` per line, returns both paths.
|
||||
fn lantern(dir: &std::path::Path, lines: &[&str], marked: &[&str]) -> (String, String) {
|
||||
let ls: Vec<String> = lines
|
||||
.iter()
|
||||
.map(|t| format!(r#"{{"group":"s1","speaker":"entity:orsa","text":"{t}"}}"#))
|
||||
.collect();
|
||||
let work = dir.join("w.json");
|
||||
std::fs::write(
|
||||
&work,
|
||||
format!(
|
||||
r#"{{"slug":"lantern-wager","language":"en-US","admitted_on":"2026-11-13",{LANTERN_SOURCE},{LANTERN_CAST},"lines":[{}]}}"#,
|
||||
ls.join(",")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let names = dir.join("n.jsonl");
|
||||
let rows: Vec<String> = marked
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, m)| format!(r#"{{"line":{},"marked":"{m}"}}"#, i + 1))
|
||||
.collect();
|
||||
std::fs::write(&names, rows.join("\n")).unwrap();
|
||||
(work.to_str().unwrap().into(), names.to_str().unwrap().into())
|
||||
}
|
||||
|
||||
const MODEL: [&str; 4] = ["--model-family", "anthropic", "--generator", "a name annotator"];
|
||||
|
||||
#[test]
|
||||
fn a_refused_import_writes_nothing_and_a_redraw_imports() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let lines = ["Tamsin, bring the lantern.", "Tamsin's lantern, said Orsa."];
|
||||
let (w, n) = lantern(d.path(), &lines, &["[[entity:tamsin|Tamsin]], bring the lantern.", "[[entity:tamsin|Tamsin's]] lantern, said Orsa."]);
|
||||
let import = |w: &str, n: &str| weksa(d.path(), &[&["corpus", "import", w, n][..], &MODEL].concat());
|
||||
let bad = import(&w, &n);
|
||||
assert!(!bad.status.success());
|
||||
assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), "");
|
||||
assert!(!d.path().join("e.cc").exists() || EntityStore::open(&d.path().join("e.cc")).unwrap().all().unwrap().is_empty());
|
||||
// The redrawn answer, different on line 1 too, imports.
|
||||
let (w, n) = lantern(d.path(), &lines, &["Tamsin, bring the lantern.", "[[entity:tamsin|Tamsin]]'s lantern, said Orsa."]);
|
||||
let good = import(&w, &n);
|
||||
assert!(good.status.success(), "{}", out(&good));
|
||||
assert!(out(&good).contains("Added item:lantern-wager:2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_work_repeating_a_line_is_refused_naming_both_lines() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (w, n) = lantern(d.path(), &["No, my lord.", "No, my lord!", "Quiet, both of you."], &["No, my lord.", "No, my lord!", "Quiet, both of you."]);
|
||||
let o = weksa(d.path(), &[&["corpus", "import", &w, &n][..], &MODEL].concat());
|
||||
assert!(!o.status.success());
|
||||
let err = String::from_utf8_lossy(&o.stderr).to_string();
|
||||
assert!(err.contains("item:lantern-wager:2") && err.contains("item:lantern-wager:1"), "{err}");
|
||||
assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_annotator_flags_decide_the_label() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (w, n) = lantern(d.path(), &["Quiet, both of you."], &["Quiet, both of you."]);
|
||||
let none = weksa(d.path(), &["corpus", "import", &w, &n]);
|
||||
assert!(!none.status.success());
|
||||
let blank = weksa(d.path(), &["corpus", "import", &w, &n, "--model-family", "anthropic", "--generator", " "]);
|
||||
assert!(!blank.status.success());
|
||||
assert_eq!(out(&weksa(d.path(), &["corpus", "dump"])).trim(), "");
|
||||
let op = weksa(d.path(), &["corpus", "import", &w, &n, "--operator"]);
|
||||
assert!(op.status.success(), "{}", out(&op));
|
||||
let dump = out(&weksa(d.path(), &["corpus", "dump"]));
|
||||
assert!(dump.contains("by Some(Operator)"), "{dump}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_refused_on_a_cast_entity_leaves_both_stores_untouched() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
// entity:tamsin is already held by a cast origin, so the work's PublicDomain
|
||||
// claim on it (cast position 2, after orsa) is refused by EntityStore::put.
|
||||
cast_entities(d.path(), &["tamsin"]);
|
||||
let (w, n) = lantern(d.path(), &["Quiet, both of you."], &["Quiet, both of you."]);
|
||||
let before = std::fs::read(d.path().join("e.cc")).unwrap();
|
||||
let o = weksa(d.path(), &[&["corpus", "import", &w, &n][..], &MODEL].concat());
|
||||
assert!(!o.status.success());
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("a cast entity"), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
assert_eq!(std::fs::read(d.path().join("e.cc")).unwrap(), before);
|
||||
assert!(!d.path().join("c.cc").exists() || CorpusStore::open(&d.path().join("c.cc")).unwrap().all().unwrap().is_empty());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -114,71 +114,14 @@ pub fn entities_in(dir: &std::path::Path) -> EntityStore {
|
|||
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",
|
||||
|
|
@ -186,14 +129,9 @@ pub fn run_over(dir: &std::path::Path) -> weksa::run::RunStores {
|
|||
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()],
|
||||
"bag", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
|
@ -205,7 +143,6 @@ pub fn item_in(key: &str, text: &str, group: &str, source: Source) -> CorpusItem
|
|||
language: "en-US".into(),
|
||||
speaker: eid("nibu"),
|
||||
names: vec![],
|
||||
names_by: None,
|
||||
group: group.into(),
|
||||
prior_turns: vec![],
|
||||
source,
|
||||
|
|
@ -272,7 +209,6 @@ 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 {
|
||||
|
|
@ -281,10 +217,6 @@ pub fn world() -> World {
|
|||
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();
|
||||
|
|
|
|||
|
|
@ -110,6 +110,16 @@ fn train_items_are_in_key_order() {
|
|||
["item:a:1", "item:m:1", "item:z:1"]
|
||||
);
|
||||
assert_eq!((t.len(), t.is_empty()), (3, false));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let empty = run_over(dir.path());
|
||||
let none = empty.train().unwrap();
|
||||
assert_eq!((none.len(), none.is_empty()), (0, true));
|
||||
let (inv, fb) = (empty.inventory().inventory().unwrap(), EditFeedback::none());
|
||||
assert_eq!(
|
||||
Prompt::mint(&none, &inv, 0, &fb).text(),
|
||||
format!("{MINT}\n\nlast edit: none; validation composite at head: none\n\ninventory rev:0")
|
||||
);
|
||||
assert!(Prompt::mint(&none, &inv, 0, &fb).item_keys().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -537,18 +547,16 @@ mod lowering {
|
|||
use weksa::daodejing::packets;
|
||||
use weksa::entity::{Entity, EntityOrigin, LanguageForms};
|
||||
use weksa::packet::{EntityId, Packet, proof_packet};
|
||||
use weksa::packet::Grade;
|
||||
use weksa::{
|
||||
Annotator, Condition, CorpusItemId, CorpusStore, EntityForms, EntityStore, Inventory,
|
||||
InventoryStore, Layer, LowerError, LoweringInput, OntologyEntry, OntologyStore, PacketStore, Test, select,
|
||||
CorpusItemId, CorpusStore, EntityForms, EntityStore, Inventory, InventoryStore,
|
||||
LowerError, LoweringInput, PacketStore,
|
||||
};
|
||||
|
||||
fn data(sub: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data").join(sub)
|
||||
}
|
||||
|
||||
/// The admitted view, its scene never read.
|
||||
fn admitted_unread(
|
||||
fn admitted(
|
||||
packet: Packet,
|
||||
inv: &InventoryStore,
|
||||
corpus: &str,
|
||||
|
|
@ -562,37 +570,6 @@ mod lowering {
|
|||
.unwrap()
|
||||
}
|
||||
|
||||
/// The admitted view with its scene read over an empty speaker-state store.
|
||||
fn admitted(
|
||||
packet: Packet,
|
||||
inv: &InventoryStore,
|
||||
corpus: &str,
|
||||
entities: &EntityStore,
|
||||
) -> LoweringInput {
|
||||
let view = admitted_unread(packet, inv, corpus, entities);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = weksa::SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
|
||||
let corpus = CorpusStore::open(&data(corpus)).unwrap();
|
||||
view.with_scene(&inv.inventory().unwrap(), &state, &corpus).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_prompt_refuses_an_unread_scene() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let inv = cast.inventory().unwrap();
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let held = Held(vec![nibu(&[("en-US", &["Nibu"])])]);
|
||||
let unread = admitted_unread(proof_packet(), &cast, "corpus/corpus.cc", &entities);
|
||||
let empty = weksa::Ontology::empty();
|
||||
assert_eq!(
|
||||
Prompt::lower(&unread, &item, &away(), "en-US", &inv, &held, &empty).err(),
|
||||
Some(LowerError::SceneUnread)
|
||||
);
|
||||
let read = admitted(proof_packet(), &cast, "corpus/corpus.cc", &entities);
|
||||
assert!(Prompt::lower(&read, &item, &away(), "en-US", &inv, &held, &empty).is_ok());
|
||||
}
|
||||
|
||||
fn dao(index: usize) -> (LoweringInput, Inventory, EntityStore, CorpusItemId) {
|
||||
let inv = InventoryStore::open(&data("daodejing/inventory.cc")).unwrap();
|
||||
let entities = EntityStore::open(&data("daodejing/entity.cc")).unwrap();
|
||||
|
|
@ -611,11 +588,6 @@ mod lowering {
|
|||
}
|
||||
}
|
||||
|
||||
/// A speaker no referent cites.
|
||||
fn away() -> EntityId {
|
||||
EntityId::parse("entity:nobody").unwrap()
|
||||
}
|
||||
|
||||
fn nibu(forms: &[(&str, &[&str])]) -> Entity {
|
||||
Entity {
|
||||
id: EntityId::parse("entity:nibu").unwrap(),
|
||||
|
|
@ -634,28 +606,13 @@ mod lowering {
|
|||
}
|
||||
}
|
||||
|
||||
/// The language line carries the tag the caller passes; no instruction
|
||||
/// names a language.
|
||||
#[test]
|
||||
fn lower_prompt_names_its_language() {
|
||||
let (view, inv, entities, item) = dao(2);
|
||||
for tag in ["en-US", "ja-JP", "pt-BR"] {
|
||||
let prompt = Prompt::lower(&view, &item, &away(), tag, &inv, &entities, &weksa::Ontology::empty()).unwrap();
|
||||
let want = format!("{LOWER}\n\nlanguage: {tag}\n\npacket: ");
|
||||
assert!(prompt.text().starts_with(&want), "{tag}");
|
||||
}
|
||||
for brief in [LOWER, weksa::context::MINT_INSTRUCTIONS] {
|
||||
assert!(!brief.contains("English") && !brief.contains("en-US"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lower_prompt_text_is_pinned() {
|
||||
let (view, inv, entities, item) = dao(2);
|
||||
let prompt = Prompt::lower(&view, &item, &away(), "en-US", &inv, &entities, &weksa::Ontology::empty()).unwrap();
|
||||
let prompt = Prompt::lower(&view, &item, &inv, &entities).unwrap();
|
||||
let (head, listing) = prompt.text().split_once("inventory rev:3\n").unwrap();
|
||||
let expected = format!(
|
||||
"{LOWER}\n\nlanguage: en-US\n\npacket: {}\n\nentities: {{}}\n\nontology: none\n\n",
|
||||
"{LOWER}\n\npacket: {}\n\nentities: {{}}\n\n",
|
||||
concat!(
|
||||
r#"{"context":{"setting":null,"medium":null,"participants":[],"audience":[]},"#,
|
||||
r#""discourse":{"speech_act":"speech_act:1","addressee":null,"addressee_consent":null,"features":[]},"#,
|
||||
|
|
@ -671,9 +628,8 @@ mod lowering {
|
|||
assert!(listing.contains("\nfeature:18: "));
|
||||
// The brief says what the spec says it must.
|
||||
for needed in [
|
||||
"the language on the language line",
|
||||
"en-US",
|
||||
"all of its meaning and nothing it does not carry",
|
||||
"a grade is permille, 0 to 1000",
|
||||
"felt affect and restraint",
|
||||
"shapes how the utterance is said, not what it says",
|
||||
"forms on the entities line",
|
||||
|
|
@ -684,84 +640,6 @@ mod lowering {
|
|||
// The one call it makes is its item; the key is in no text.
|
||||
assert_eq!(prompt.item_keys(), [item.as_str()]);
|
||||
assert!(!prompt.text().contains(item.as_str()));
|
||||
// The view's speaker and group are private: the item's speaker entity
|
||||
// id and its group are in no text.
|
||||
let held = CorpusStore::open(&data("daodejing/corpus.cc"))
|
||||
.unwrap()
|
||||
.get(item.as_str())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!held.group.is_empty());
|
||||
for private in [held.speaker.as_str(), held.group.as_str()] {
|
||||
assert!(!prompt.text().contains(private), "{private}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The mint cut added no line to what the lowerer sees: a prompt with a
|
||||
/// selected ontology entry has the digest it had at af0a56d.
|
||||
#[test]
|
||||
fn the_lowering_prompt_of_a_fixed_packet_is_unchanged_by_the_ontology_mint() {
|
||||
use weksa::encode::OntologyDraft;
|
||||
use weksa::speaker::Annotator;
|
||||
let (view, inv, entities, item) = dao(2);
|
||||
let store = InventoryStore::open(&data("daodejing/inventory.cc")).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut onto = weksa::OntologyStore::open(&dir.path().join("o.cc")).unwrap();
|
||||
let annotator = Annotator::Model {
|
||||
family: weksa::corpus::ModelFamily::Anthropic,
|
||||
generator: "golden".into(),
|
||||
};
|
||||
let draft = r#"{"entries":[{"layer":"Grammar","choice":"golden choice","examples":["golden example"]}]}"#;
|
||||
let entries = OntologyDraft::parse(draft).unwrap().into_entries("en-US", 3, 1, &annotator);
|
||||
onto.admit(entries, &store).unwrap();
|
||||
let prompt =
|
||||
Prompt::lower(&view, &item, &away(), "en-US", &inv, &entities, &onto.ontology().unwrap()).unwrap();
|
||||
assert!(prompt.text().contains("golden choice"));
|
||||
assert_eq!(prompt.digest(), "4a40eb57282b059d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lower_prompt_moves_with_the_stance_alone() {
|
||||
use weksa::packet::{FeatValue, FeatureValue, Grade, Stance};
|
||||
let (_, inv, entities, item) = dao(2);
|
||||
let store = InventoryStore::open(&data("daodejing/inventory.cc")).unwrap();
|
||||
let own = packets().remove(2).stance;
|
||||
let grade = |feature: &str, v: u16| FeatureValue {
|
||||
feature: feature.parse().unwrap(),
|
||||
value: FeatValue::Grade(Grade::new(v).unwrap()),
|
||||
};
|
||||
let angry = Stance {
|
||||
features: vec![grade("feature:9", 800), grade("feature:18", 900)],
|
||||
};
|
||||
let prompt_of = |stance: Stance| {
|
||||
let mut packet = packets().remove(2);
|
||||
packet.stance = stance.clone();
|
||||
let view = admitted(packet, &store, "daodejing/corpus.cc", &entities);
|
||||
let prompt = Prompt::lower(&view, &item, &away(), "en-US", &inv, &entities, &weksa::Ontology::empty()).unwrap();
|
||||
(stance, prompt)
|
||||
};
|
||||
let three = [prompt_of(own), prompt_of(angry), prompt_of(Stance::default())];
|
||||
|
||||
// Three stances, three prompts.
|
||||
let digests: std::collections::BTreeSet<String> =
|
||||
three.iter().map(|(_, p)| p.digest()).collect();
|
||||
assert_eq!(digests.len(), 3);
|
||||
// Each packet line ends with exactly that stance's JSON, and the prompt
|
||||
// with the packet line taken out is the same text for all three.
|
||||
let without_packet_line = |text: &str| -> String {
|
||||
text.lines().filter(|l| !l.starts_with("packet: ")).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
let bare = without_packet_line(three[0].1.text());
|
||||
for (stance, prompt) in &three {
|
||||
let line = prompt.text().lines().find(|l| l.starts_with("packet: ")).unwrap();
|
||||
let json = serde_json::to_string(stance).unwrap();
|
||||
assert!(line.ends_with(&format!(r#","stance":{json}}}"#)), "{line}");
|
||||
assert_eq!(without_packet_line(prompt.text()), bare);
|
||||
}
|
||||
// The stance's feature ids are glossed in the one inventory listing.
|
||||
let text = three[1].1.text();
|
||||
assert!(text.contains("\nfeature:9: anger [grade; slots Stance]\n"));
|
||||
assert!(text.contains("\nfeature:18: restraint [grade; slots Stance]\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -774,7 +652,7 @@ mod lowering {
|
|||
("sa-Latn", &["Nibuwa"]),
|
||||
("en-US", &["Nibu", "Nibu's"]),
|
||||
])]);
|
||||
let prompt = Prompt::lower(&view, &item, &away(), "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).unwrap();
|
||||
let prompt = Prompt::lower(&view, &item, &cast.inventory().unwrap(), &held).unwrap();
|
||||
assert!(
|
||||
prompt
|
||||
.text()
|
||||
|
|
@ -804,358 +682,9 @@ mod lowering {
|
|||
),
|
||||
(Held(vec![]), LowerError::UnknownEntity { entity: id }),
|
||||
] {
|
||||
assert_eq!(Prompt::lower(&view, &item, &away(), "en-US", &inv, &held, &weksa::Ontology::empty()).err(), Some(want));
|
||||
assert_eq!(Prompt::lower(&view, &item, &inv, &held).err(), Some(want));
|
||||
}
|
||||
}
|
||||
|
||||
/// The item's speaker id is never printed, though a referent cites it: the
|
||||
/// referent holds the token, the forms line holds the speaker's forms under
|
||||
/// it, and the view itself is not changed.
|
||||
#[test]
|
||||
fn a_cited_speaker_is_replaced_by_the_token_in_the_lowering_prompt() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let view = admitted(proof_packet(), &cast, "corpus/corpus.cc", &cast_entities);
|
||||
let inv = cast.inventory().unwrap();
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let speaker = EntityId::parse("entity:nibu").unwrap();
|
||||
let held = Held(vec![nibu(&[("en-US", &["NIBUCANARY"])])]);
|
||||
let lower = |held: &Held| {
|
||||
Prompt::lower(&view, &item, &speaker, "en-US", &inv, held, &weksa::Ontology::empty())
|
||||
};
|
||||
let prompt = lower(&held).unwrap();
|
||||
let text = prompt.text();
|
||||
assert!(!text.contains("entity:nibu"), "{text}");
|
||||
assert!(text.contains("\n\nentities: {\"entity:speaker\":[\"NIBUCANARY\"]}\n\n"), "{text}");
|
||||
assert!(text.contains(r#""id":"n3","kind":"referent_kind:1","concept":"concept:5","entity":"entity:speaker""#), "{text}");
|
||||
assert!(view.referents().iter().any(|r| r.entity.as_ref() == Some(&speaker)));
|
||||
// A speaker the language has no form for, or the port lacks, does not
|
||||
// refuse: its referent names no entity and the line has no entry.
|
||||
for held in [Held(vec![]), Held(vec![nibu(&[("sa-Latn", &["Nibuwa"])])])] {
|
||||
let prompt = lower(&held).unwrap();
|
||||
let text = prompt.text();
|
||||
assert!(text.contains("\n\nentities: {}\n\n") && !text.contains("entity:speaker"), "{text}");
|
||||
assert!(text.contains(r#""concept":"concept:5","entity":null"#), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The speaker's forms are those of the item's language, and a language whose form list is
|
||||
/// an empty list is no form: the line has no token entry.
|
||||
#[test]
|
||||
fn the_speakers_forms_are_those_of_the_items_language() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let view = admitted(proof_packet(), &cast, "corpus/corpus.cc", &cast_entities);
|
||||
let inv = cast.inventory().unwrap();
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let speaker = EntityId::parse("entity:nibu").unwrap();
|
||||
let lower = |tag: &str, held: &Held| {
|
||||
Prompt::lower(&view, &item, &speaker, tag, &inv, held, &weksa::Ontology::empty())
|
||||
.unwrap()
|
||||
.text()
|
||||
.to_string()
|
||||
};
|
||||
let held = Held(vec![nibu(&[("en-US", &["ENGLISHFORM"]), ("ja-JP", &["NIHONGOFORM"])])]);
|
||||
let ja = lower("ja-JP", &held);
|
||||
assert!(ja.contains("\n\nentities: {\"entity:speaker\":[\"NIHONGOFORM\"]}\n\n"), "{ja}");
|
||||
assert!(!ja.contains("ENGLISHFORM"), "{ja}");
|
||||
let en = lower("en-US", &held);
|
||||
assert!(en.contains("{\"entity:speaker\":[\"ENGLISHFORM\"]}") && !en.contains("NIHONGOFORM"), "{en}");
|
||||
let empty = lower("en-US", &Held(vec![nibu(&[("en-US", &[])])]));
|
||||
assert!(empty.contains("\n\nentities: {}\n\n") && !empty.contains("entity:speaker"), "{empty}");
|
||||
assert!(empty.contains(r#""concept":"concept:5","entity":null"#), "{empty}");
|
||||
}
|
||||
|
||||
/// A real entity whose id is the token would read as the speaker: refused.
|
||||
#[test]
|
||||
fn a_cited_entity_with_the_tokens_id_is_refused() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let mut packet = proof_packet();
|
||||
packet.referents[2].entity = Some(EntityId::parse(weksa::context::SPEAKER_TOKEN).unwrap());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut entities = EntityStore::open(&dir.path().join("e.cc")).unwrap();
|
||||
entities.put(super::common::ent("speaker", "en-US", &["Spk"])).unwrap();
|
||||
entities.put(super::common::ent("nibu", "en-US", &["Nibu"])).unwrap();
|
||||
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
let mut item = super::common::item_in("item:nibu:1", "A line.", &super::common::group_in_bucket(10), super::common::cast());
|
||||
item.prior_turns = vec![weksa::Turn { speaker: super::common::eid("speaker"), text: "Well?".into() }];
|
||||
corpus.add(item, &entities).unwrap();
|
||||
let view = PacketStore::open(&dir.path().join("p.cc")).unwrap().admit(packet, &cast, &corpus, &entities).unwrap();
|
||||
let state = weksa::SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
|
||||
let view = view.with_scene(&cast.inventory().unwrap(), &state, &corpus).unwrap();
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let held = Held(vec![super::common::ent("speaker", "en-US", &["Spk"]), nibu(&[("en-US", &["Nibu"])])]);
|
||||
for speaker in ["entity:nibu", "entity:speaker"] {
|
||||
let speaker = EntityId::parse(speaker).unwrap();
|
||||
assert_eq!(
|
||||
Prompt::lower(&view, &item, &speaker, "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).err(),
|
||||
Some(LowerError::SpeakerTokenTaken)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the speaker is replaced: when the item's speaker is someone else,
|
||||
/// the cited entity keeps its id in the packet and its forms line.
|
||||
#[test]
|
||||
fn a_cited_entity_that_is_not_the_speaker_is_kept() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let view = admitted(proof_packet(), &cast, "corpus/corpus.cc", &cast_entities);
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let held = Held(vec![nibu(&[("en-US", &["NIBUCANARY"])])]);
|
||||
let prompt = Prompt::lower(&view, &item, &away(), "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).unwrap();
|
||||
let text = prompt.text();
|
||||
assert!(text.contains(r#""concept":"concept:5","entity":"entity:nibu""#), "{text}");
|
||||
assert!(text.contains("\n\nentities: {\"entity:nibu\":[\"NIBUCANARY\"]}\n\n"), "{text}");
|
||||
}
|
||||
|
||||
/// Every referent citing the speaker holds the token, not the first.
|
||||
#[test]
|
||||
fn a_speaker_cited_on_two_referents_prints_the_token_on_both() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let mut packet = proof_packet();
|
||||
let speaker = EntityId::parse("entity:nibu").unwrap();
|
||||
packet.referents[0].entity = Some(speaker.clone());
|
||||
assert_eq!(packet.referents.iter().filter(|r| r.entity.as_ref() == Some(&speaker)).count(), 2);
|
||||
let view = admitted(packet, &cast, "corpus/corpus.cc", &cast_entities);
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let held = Held(vec![nibu(&[("en-US", &["NIBUCANARY"])])]);
|
||||
let prompt = Prompt::lower(&view, &item, &speaker, "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).unwrap();
|
||||
let text = prompt.text();
|
||||
assert!(!text.contains("entity:nibu"), "{text}");
|
||||
assert_eq!(text.matches(r#""entity":"entity:speaker""#).count(), 2, "{text}");
|
||||
assert!(text.contains("\n\nentities: {\"entity:speaker\":[\"NIBUCANARY\"]}\n\n"), "{text}");
|
||||
}
|
||||
|
||||
/// The speaker is matched by whole id: a cited entity whose id the
|
||||
/// speaker's id is a prefix of is another entity and still prints.
|
||||
#[test]
|
||||
fn an_entity_sharing_a_prefix_with_the_speaker_is_kept() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let view = admitted(proof_packet(), &cast, "corpus/corpus.cc", &cast_entities);
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let held = Held(vec![nibu(&[("en-US", &["NIBUCANARY"])])]);
|
||||
let speaker = EntityId::parse("entity:nib").unwrap();
|
||||
let prompt = Prompt::lower(&view, &item, &speaker, "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).unwrap();
|
||||
let text = prompt.text();
|
||||
assert!(text.contains(r#""entity":"entity:nibu""#), "{text}");
|
||||
assert!(text.contains("NIBUCANARY"), "{text}");
|
||||
}
|
||||
|
||||
/// The proof packet admitted for an item whose speaker is `speaker` and
|
||||
/// whose prior turn is `other`'s, with `speaker` on referent n3 and `other`
|
||||
/// on referent n1, then lowered in en-US over an entity port holding `held`.
|
||||
fn lowered_for(speaker: &str, other: &str, held: &[Entity]) -> String {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut entities = EntityStore::open(&dir.path().join("e.cc")).unwrap();
|
||||
for slug in [speaker, other] {
|
||||
entities.put(super::common::ent(slug, "en-US", &["Stored"])).unwrap();
|
||||
}
|
||||
let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
let mut item = super::common::item_in("item:nibu:1", "A line.", &super::common::group_in_bucket(10), super::common::cast());
|
||||
item.speaker = super::common::eid(speaker);
|
||||
item.prior_turns = vec![weksa::Turn { speaker: super::common::eid(other), text: "Well?".into() }];
|
||||
corpus.add(item, &entities).unwrap();
|
||||
let mut packet = proof_packet();
|
||||
packet.referents[0].entity = Some(super::common::eid(other));
|
||||
packet.referents[2].entity = Some(super::common::eid(speaker));
|
||||
let view = PacketStore::open(&dir.path().join("p.cc"))
|
||||
.unwrap()
|
||||
.admit(packet, &cast, &corpus, &entities)
|
||||
.unwrap();
|
||||
let state = weksa::SpeakerStateStore::open(&dir.path().join("s.cc")).unwrap();
|
||||
let view = view.with_scene(&cast.inventory().unwrap(), &state, &corpus).unwrap();
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
Prompt::lower(
|
||||
&view,
|
||||
&item,
|
||||
&super::common::eid(speaker),
|
||||
"en-US",
|
||||
&cast.inventory().unwrap(),
|
||||
&Held(held.to_vec()),
|
||||
&weksa::Ontology::empty(),
|
||||
)
|
||||
.unwrap()
|
||||
.text()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Persona's ruling `speaker-alias-token-in-lowering-prompt`: the item's
|
||||
/// speaker prints as one fixed role token, the same for every speaker and
|
||||
/// every item, with the speaker's forms under it; its entity id never
|
||||
/// prints. Another cited entity still prints under its own id.
|
||||
#[test]
|
||||
fn the_item_speaker_is_a_fixed_token_with_its_forms() {
|
||||
const TOKEN: &str = "entity:speaker";
|
||||
let forms = |slug: &str, form: &str| super::common::ent(slug, "en-US", &[form]);
|
||||
let other = forms("othercite", "OTTERBLOOM");
|
||||
let a = lowered_for("keeperzed", "othercite", &[forms("keeperzed", "ZEBRAQUILL"), other.clone()]);
|
||||
let b = lowered_for("secondvoice", "othercite", &[forms("secondvoice", "MARMOTLUTE"), other.clone()]);
|
||||
for (text, id, form, other_form) in [(&a, "keeperzed", "ZEBRAQUILL", "MARMOTLUTE"), (&b, "secondvoice", "MARMOTLUTE", "ZEBRAQUILL")] {
|
||||
assert!(!text.contains(id), "{id} in {text}");
|
||||
assert!(!text.contains(other_form), "{other_form} in {text}");
|
||||
assert!(text.contains(r#""concept":"concept:5","entity":"entity:speaker""#), "{text}");
|
||||
assert!(text.contains(&format!(r#""{TOKEN}":["{form}"]"#)), "{text}");
|
||||
assert!(text.contains(r#""entity":"entity:othercite""#), "{text}");
|
||||
assert!(text.contains(r#""entity:othercite":["OTTERBLOOM"]"#), "{text}");
|
||||
}
|
||||
// The token is one constant: the entities lines differ only in the speaker's form.
|
||||
assert_eq!(a.replace("ZEBRAQUILL", "F"), b.replace("MARMOTLUTE", "F"));
|
||||
// A speaker with no form in the language does not refuse and gets no token entry.
|
||||
let bare = lowered_for("keeperzed", "othercite", &[other]);
|
||||
assert!(!bare.contains("keeperzed") && !bare.contains(TOKEN), "{bare}");
|
||||
assert!(bare.contains(r#"{"entity:othercite":["OTTERBLOOM"]}"#), "{bare}");
|
||||
}
|
||||
|
||||
fn feature(inv: &Inventory, gloss: &str) -> weksa::InvId {
|
||||
inv.entries().find(|e| e.gloss == gloss).unwrap().id
|
||||
}
|
||||
|
||||
fn entry(language: &str, n: u32, when: Vec<Condition>, choice: &str) -> OntologyEntry {
|
||||
OntologyEntry {
|
||||
language: language.into(),
|
||||
n,
|
||||
inventory_rev: 1,
|
||||
layer: Layer::Discourse,
|
||||
when,
|
||||
choice: choice.into(),
|
||||
examples: vec![],
|
||||
annotator: Annotator::Operator,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ontology the store holds after admitting `entries` as one batch.
|
||||
fn ontology_of(cast: &InventoryStore, entries: Vec<OntologyEntry>) -> weksa::Ontology {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut store = OntologyStore::open(&dir.path().join("o.cc")).unwrap();
|
||||
store.admit(entries, cast).unwrap();
|
||||
store.ontology().unwrap()
|
||||
}
|
||||
|
||||
fn at_least(inv: &Inventory, gloss: &str, g: u16) -> Condition {
|
||||
Condition {
|
||||
slot: weksa::Slot::Stance,
|
||||
feature: feature(inv, gloss),
|
||||
test: Test::AtLeast(Grade::new(g).unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The proof packet's view with the given stance restraint and discourse irony.
|
||||
fn view_of(
|
||||
restraint: Option<u16>,
|
||||
irony: Option<bool>,
|
||||
cast: &InventoryStore,
|
||||
entities: &EntityStore,
|
||||
) -> LoweringInput {
|
||||
use weksa::packet::{FeatValue, FeatureValue};
|
||||
let inv = cast.inventory().unwrap();
|
||||
let mut packet = proof_packet();
|
||||
packet.stance.features = restraint
|
||||
.map(|v| FeatureValue {
|
||||
feature: feature(&inv, "restraint"),
|
||||
value: FeatValue::Grade(Grade::new(v).unwrap()),
|
||||
})
|
||||
.into_iter()
|
||||
.collect();
|
||||
packet.discourse.features = irony
|
||||
.map(|v| FeatureValue {
|
||||
feature: feature(&inv, "irony"),
|
||||
value: FeatValue::Flag(v),
|
||||
})
|
||||
.into_iter()
|
||||
.collect();
|
||||
admitted(packet, cast, "corpus/corpus.cc", entities)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_reads_stance_and_discourse_of_its_language() {
|
||||
use weksa::packet::FeatValue;
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let inv = cast.inventory().unwrap();
|
||||
let ontology = ontology_of(&cast, vec![
|
||||
entry("ja-JP", 1, vec![at_least(&inv, "restraint", 600)], "high"),
|
||||
entry(
|
||||
"ja-JP",
|
||||
2,
|
||||
vec![Condition {
|
||||
slot: weksa::Slot::Stance,
|
||||
feature: feature(&inv, "restraint"),
|
||||
test: Test::AtMost(Grade::new(300).unwrap()),
|
||||
}],
|
||||
"low",
|
||||
),
|
||||
entry(
|
||||
"ja-JP",
|
||||
3,
|
||||
vec![Condition {
|
||||
slot: weksa::Slot::Discourse,
|
||||
feature: feature(&inv, "irony"),
|
||||
test: Test::Is(FeatValue::Flag(true)),
|
||||
}],
|
||||
"ironic",
|
||||
),
|
||||
entry("ja-JP", 4, vec![], "always"),
|
||||
entry("en-US", 1, vec![], "other language"),
|
||||
]);
|
||||
let keys = |view: &LoweringInput, language: &str| -> Vec<String> {
|
||||
select(&ontology, language, view).iter().map(|e| e.key()).collect()
|
||||
};
|
||||
let both = view_of(Some(700), Some(true), &cast, &entities);
|
||||
assert_eq!(keys(&both, "ja-JP"), ["onto:ja-JP:1", "onto:ja-JP:3", "onto:ja-JP:4"]);
|
||||
assert_eq!(keys(&both, "en-US"), ["onto:en-US:1"]);
|
||||
let low = view_of(Some(200), Some(false), &cast, &entities);
|
||||
assert_eq!(keys(&low, "ja-JP"), ["onto:ja-JP:2", "onto:ja-JP:4"]);
|
||||
// A grade equal to the bound meets AtLeast and AtMost alike.
|
||||
let edge = view_of(Some(600), None, &cast, &entities);
|
||||
assert_eq!(keys(&edge, "ja-JP"), ["onto:ja-JP:1", "onto:ja-JP:4"]);
|
||||
let edge = view_of(Some(300), None, &cast, &entities);
|
||||
assert_eq!(keys(&edge, "ja-JP"), ["onto:ja-JP:2", "onto:ja-JP:4"]);
|
||||
// An absent feature meets no condition, however lax.
|
||||
let bare = view_of(None, None, &cast, &entities);
|
||||
assert_eq!(keys(&bare, "ja-JP"), ["onto:ja-JP:4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_prompt_prints_only_selected_entries() {
|
||||
let cast = InventoryStore::open(&data("interlingua/inventory.cc")).unwrap();
|
||||
let cast_entities = EntityStore::open(&data("entity/entity.cc")).unwrap();
|
||||
let inv = cast.inventory().unwrap();
|
||||
let mut hit = entry("ja-JP", 1, vec![at_least(&inv, "restraint", 600)], "HITCHOICE");
|
||||
hit.examples = vec!["HITEXAMPLE".into()];
|
||||
let ontology = ontology_of(&cast, vec![
|
||||
hit,
|
||||
entry("ja-JP", 2, vec![at_least(&inv, "restraint", 900)], "MISSCHOICE"),
|
||||
entry("en-US", 1, vec![], "ENGLISHCHOICE"),
|
||||
]);
|
||||
let held = Held(vec![nibu(&[("ja-JP", &["ニブ"]), ("en-US", &["Nibu"])])]);
|
||||
let item = CorpusItemId::parse("item:nibu:1").unwrap();
|
||||
let view = view_of(Some(700), None, &cast, &cast_entities);
|
||||
let lowered = |view: &LoweringInput, o: &weksa::Ontology| {
|
||||
Prompt::lower(view, &item, &away(), "ja-JP", &inv, &held, o).unwrap()
|
||||
};
|
||||
let prompt = lowered(&view, &ontology);
|
||||
let text = prompt.text();
|
||||
assert!(text.contains("\n\nontology:\nonto:ja-JP:1 [discourse] HITCHOICE | e.g. HITEXAMPLE\n\n"), "{text}");
|
||||
for absent in ["MISSCHOICE", "ENGLISHCHOICE", "onto:ja-JP:2", "onto:en-US:1"] {
|
||||
assert!(!text.contains(absent), "{absent}");
|
||||
}
|
||||
// The same view with no entries: the section reads none.
|
||||
let none = lowered(&view, &weksa::Ontology::empty());
|
||||
assert!(none.text().contains("\n\nontology: none\n\n"));
|
||||
// Entries move the prompt and nothing else of the view does.
|
||||
assert_ne!(prompt.digest(), none.digest());
|
||||
// The group is still private.
|
||||
let held_item = CorpusStore::open(&data("corpus/corpus.cc"))
|
||||
.unwrap()
|
||||
.get(item.as_str())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!text.contains(held_item.group.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
/// First real rounds: five of six encoders wrote bare integers (`"concept": 7`)
|
||||
|
|
@ -1165,8 +694,6 @@ mod lowering {
|
|||
#[test]
|
||||
fn the_encode_prompt_states_the_id_form_the_inventory_lines_use() {
|
||||
assert!(ENCODE.contains("family prefix included: concept:7, never 7"));
|
||||
assert!(ENCODE.contains("A referent's concept is never null, even when it carries an entity: give the nearest concept id."));
|
||||
assert!(ENCODE.contains("Participants and audience list the node ids of referents, never an entity id: an entity speaker is a referent whose entity field holds it, and participants lists that referent's node id."));
|
||||
let w = world();
|
||||
let run = run_over(w.dir.path());
|
||||
let inv = run.inventory().inventory().unwrap();
|
||||
|
|
|
|||
|
|
@ -502,96 +502,3 @@ fn a_malformed_pronunciation_is_refused() {
|
|||
}
|
||||
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());
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
|
@ -27,7 +27,7 @@ struct W {
|
|||
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)] {
|
||||
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision()] {
|
||||
inventory.admit_revision(rev, entries).unwrap();
|
||||
}
|
||||
let entities = entities_in(dir.path());
|
||||
|
|
@ -60,7 +60,7 @@ fn feat(gloss: &str, value: FeatValue) -> FeatureValue {
|
|||
let feature = seed()
|
||||
.1
|
||||
.into_iter()
|
||||
.chain(speaker_scene_revision(3).1)
|
||||
.chain(speaker_scene_revision().1)
|
||||
.find(|e| e.gloss == gloss)
|
||||
.unwrap_or_else(|| panic!("no feature {gloss}"))
|
||||
.id;
|
||||
|
|
@ -408,60 +408,3 @@ fn only_live_speakers_of_the_views_group_and_the_views_own_speaker_must_be_cover
|
|||
["V16"]
|
||||
);
|
||||
}
|
||||
|
||||
mod select {
|
||||
use super::*;
|
||||
use weksa::speaker::Annotator;
|
||||
use weksa::{Condition, Layer, OntologyEntry, OntologyStore, Slot, Test, select};
|
||||
|
||||
fn scene_feature(gloss: &str) -> weksa::InvId {
|
||||
speaker_scene_revision(3).1.into_iter().find(|e| e.gloss == gloss).unwrap().id
|
||||
}
|
||||
|
||||
fn entry(n: u32, slot: Slot, gloss: &str, test: Test) -> OntologyEntry {
|
||||
OntologyEntry {
|
||||
language: "ja-JP".into(),
|
||||
n,
|
||||
inventory_rev: 3,
|
||||
layer: Layer::Grammar,
|
||||
when: vec![Condition { slot, feature: scene_feature(gloss), test }],
|
||||
choice: "a choice".into(),
|
||||
examples: vec![],
|
||||
annotator: Annotator::Operator,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_reads_the_scene_relation() {
|
||||
let mut w = world();
|
||||
put(&mut w, standard("g", 1));
|
||||
let mut store = OntologyStore::open(&w.dir.path().join("o.cc")).unwrap();
|
||||
store
|
||||
.admit(
|
||||
vec![
|
||||
entry(1, Slot::Scene, "relative_status", Test::Is(FeatValue::Option(lab("above")))),
|
||||
entry(2, Slot::Scene, "intimacy", Test::AtLeast(grade(150))),
|
||||
],
|
||||
&w.inventory,
|
||||
)
|
||||
.unwrap();
|
||||
let ontology = store.ontology().unwrap();
|
||||
let keys = |read: SceneRead, w: &W| {
|
||||
let view = view_of(w, 3, Some("n3")).with_scene(&inv(w), &w.state, &w.corpus).unwrap();
|
||||
assert_eq!(view.scene_read(), &read);
|
||||
select(&ontology, "ja-JP", &view).iter().map(|e| e.n).collect::<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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,8 +45,8 @@ fn chrf_matches_sacrebleu_vectors() {
|
|||
|
||||
#[test]
|
||||
fn chrf_argument_order() {
|
||||
let short = "shut the gate";
|
||||
let long = "shut the gate before the storm arrives tonight";
|
||||
let short = "mind the hatch";
|
||||
let long = "mind the hatch before the storm arrives tonight";
|
||||
let (as_hypothesis, as_reference) = (chrf(short, long), chrf(long, short));
|
||||
assert!(
|
||||
as_hypothesis < as_reference - 1.0,
|
||||
|
|
@ -104,8 +104,8 @@ fn chrf_whitespace_parity() {
|
|||
|
||||
#[test]
|
||||
fn scorer_argument_order() {
|
||||
let short = "shut the gate";
|
||||
let long = "shut the gate before the storm arrives tonight";
|
||||
let short = "mind the hatch";
|
||||
let long = "mind the hatch before the storm arrives tonight";
|
||||
let scorer = Scorer::new(Bag);
|
||||
let got = score_one(&scorer, long, short);
|
||||
assert_eq!(got.chrf, chrf(short, long));
|
||||
|
|
@ -156,7 +156,7 @@ impl Embedder for Fixed {
|
|||
fn scorer_refuses_bad_vectors() {
|
||||
let run = |vectors: Vec<Vec<f32>>| {
|
||||
Scorer::new(Fixed(vectors)).score(&[ScoreInput {
|
||||
reference: "shut the gate",
|
||||
reference: "mind the hatch",
|
||||
output: "mind the door",
|
||||
}])
|
||||
};
|
||||
|
|
@ -671,16 +671,16 @@ fn every_script_scores_a_near_miss_as_sacrebleu_does() {
|
|||
#[test]
|
||||
fn coverage_splits_at_any_non_word_character() {
|
||||
let items = [
|
||||
validation("item:v:1", "shut the gate before the storm"),
|
||||
validation("item:v:1", "mind the hatch before the storm"),
|
||||
train("item:t:1", UNRELATED),
|
||||
];
|
||||
let want = read(&["shut the gate"], &items);
|
||||
let want = read(&["mind the hatch"], &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");
|
||||
let glued = format!("mind{joiner}the{joiner}hatch");
|
||||
assert_eq!(read(&[&glued], &items), want, "{joiner:?}");
|
||||
}
|
||||
// a mark, a joiner or a digit is part of its word, not a break
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ struct W {
|
|||
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)] {
|
||||
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision()] {
|
||||
inventory.admit_revision(rev, entries).unwrap();
|
||||
}
|
||||
let entities = entities_in(dir.path());
|
||||
|
|
@ -60,7 +60,7 @@ fn feat(gloss: &str, value: FeatValue) -> FeatureValue {
|
|||
let feature = seed()
|
||||
.1
|
||||
.into_iter()
|
||||
.chain(speaker_scene_revision(3).1)
|
||||
.chain(speaker_scene_revision().1)
|
||||
.find(|e| e.gloss == gloss)
|
||||
.unwrap_or_else(|| panic!("no feature {gloss}"))
|
||||
.id;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ fn item(group: &str, source: Source) -> CorpusItem {
|
|||
language: "en-US".into(),
|
||||
speaker: weksa::EntityId::parse("entity:s").unwrap(),
|
||||
names: vec![],
|
||||
names_by: None,
|
||||
group: group.into(),
|
||||
prior_turns: vec![],
|
||||
source,
|
||||
|
|
|
|||
|
|
@ -1584,9 +1584,7 @@ fn seed_reseeded() {
|
|||
.unwrap();
|
||||
assert_eq!(items.len(), 3);
|
||||
// The committed inventory is the seed, reseeded (stance features in, the
|
||||
// displayed-affect features out), the nibu-proof revision and the
|
||||
// speaker-scene revision as rev 3: never the Dao revision (ruling
|
||||
// `dao-round-seed-inventory`).
|
||||
// displayed-affect features out), then the nibu-proof revision.
|
||||
let committed = InventoryStore::open(&root.join("data/interlingua/inventory.cc"))
|
||||
.unwrap()
|
||||
.inventory()
|
||||
|
|
@ -1595,8 +1593,6 @@ fn seed_reseeded() {
|
|||
let (proof, proof_entries) = weksa::inventory::proof_revision();
|
||||
assert!(committed.has_revision(rev.n) && committed.has_revision(proof.n));
|
||||
entries.extend(proof_entries);
|
||||
entries.extend(weksa::inventory::speaker_scene_revision(3).1);
|
||||
assert_eq!(committed.latest().unwrap().n, 3);
|
||||
let mut have: Vec<_> = committed.entries().cloned().collect();
|
||||
let mut want = entries;
|
||||
have.sort_by_key(|e| e.id);
|
||||
|
|
@ -1632,262 +1628,3 @@ fn a_public_domain_source_without_an_edition_year_is_refused() {
|
|||
.add(item_in(key, "line", "scene-1", source(1891)), &ents(&d))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
mod ontology {
|
||||
use super::*;
|
||||
use weksa::packet::{FeatValue, Grade};
|
||||
use weksa::speaker::Annotator;
|
||||
use weksa::{Condition, Layer, OntologyEntry, OntologyStore, Test};
|
||||
|
||||
fn feature(gloss: &str) -> weksa::InvId {
|
||||
seed().1.into_iter().find(|e| e.gloss == gloss).unwrap().id
|
||||
}
|
||||
|
||||
fn when(slot: Slot, gloss: &str, test: Test) -> Condition {
|
||||
Condition {
|
||||
slot,
|
||||
feature: feature(gloss),
|
||||
test,
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(language: &str, n: u32) -> OntologyEntry {
|
||||
OntologyEntry {
|
||||
language: language.into(),
|
||||
n,
|
||||
inventory_rev: 1,
|
||||
layer: Layer::Lexicon,
|
||||
when: vec![when(
|
||||
Slot::Stance,
|
||||
"restraint",
|
||||
Test::AtLeast(Grade::new(600).unwrap()),
|
||||
)],
|
||||
choice: "prefer the humble form".into(),
|
||||
examples: vec!["example one".into()],
|
||||
annotator: Annotator::Operator,
|
||||
}
|
||||
}
|
||||
|
||||
fn store(d: &TempDir) -> OntologyStore {
|
||||
OntologyStore::open(&d.path().join("o.cc")).unwrap()
|
||||
}
|
||||
|
||||
fn refused(r: Result<AddOutcome, StoreError>) -> StoreRefusal {
|
||||
refusal(r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::vec_init_then_push)]
|
||||
fn ontology_admit_refuses_each_rule() {
|
||||
let d = dir();
|
||||
let w = world();
|
||||
let mut s = store(&d);
|
||||
let long = |n| "x".repeat(n);
|
||||
let mut cases: Vec<(&str, Vec<OntologyEntry>)> = Vec::new();
|
||||
cases.push(("non-tag language", vec![entry("not a tag", 1)]));
|
||||
cases.push(("n not latest+1", vec![entry("ja-JP", 2)]));
|
||||
cases.push(("case-variant language", vec![entry("ja-jp", 1)]));
|
||||
cases.push((
|
||||
"decomposed choice",
|
||||
vec![OntologyEntry { choice: "e\u{301}".into(), ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"decomposed example",
|
||||
vec![OntologyEntry { examples: vec!["e\u{301}".into()], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
for sep in ["\u{2028}", "\u{2029}", "\u{202e}", "\u{200b}", "\u{3164}", "\u{115f}", "\u{ffa0}"] {
|
||||
cases.push((
|
||||
"line separator or format character in a choice",
|
||||
vec![OntologyEntry { choice: format!("a{sep}b"), ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"line separator or format character in an example",
|
||||
vec![OntologyEntry { examples: vec![format!("a{sep}b")], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
"unconditioned entry at an unknown revision",
|
||||
vec![OntologyEntry { when: vec![], inventory_rev: 99, ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"Predication slot on a feature that sits there",
|
||||
vec![OntologyEntry {
|
||||
when: vec![when(
|
||||
Slot::Predication,
|
||||
"modality",
|
||||
Test::Is(FeatValue::Option(lab("actual"))),
|
||||
)],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
cases.push((
|
||||
"65th entry",
|
||||
(1..=65).map(|n| entry("ja-JP", n)).collect(),
|
||||
));
|
||||
for (why, choice) in [("empty choice", String::new()), ("201-byte choice", long(201))] {
|
||||
cases.push((why, vec![OntologyEntry { choice, ..entry("ja-JP", 1) }]));
|
||||
}
|
||||
cases.push((
|
||||
"line break in an example",
|
||||
vec![OntologyEntry { examples: vec!["a\nb".into()], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"121-byte example",
|
||||
vec![OntologyEntry { examples: vec![long(121)], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"four examples",
|
||||
vec![OntologyEntry { examples: vec!["a".into(); 4], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
let restraint = || when(Slot::Stance, "restraint", Test::AtLeast(Grade::new(1).unwrap()));
|
||||
cases.push((
|
||||
"five conditions",
|
||||
vec![OntologyEntry { when: (0..5).map(|_| restraint()).collect(), ..entry("ja-JP", 1) }],
|
||||
));
|
||||
for slot in [Slot::Speaker, Slot::Predication] {
|
||||
cases.push((
|
||||
"slot not Stance, Discourse or Scene",
|
||||
vec![OntologyEntry {
|
||||
when: vec![when(slot, "restraint", Test::AtLeast(Grade::new(1).unwrap()))],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
"AtLeast on an option feature",
|
||||
vec![OntologyEntry {
|
||||
when: vec![when(Slot::Discourse, "irony", Test::AtLeast(Grade::new(1).unwrap()))],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
cases.push((
|
||||
"Is with a grade",
|
||||
vec![OntologyEntry {
|
||||
when: vec![when(Slot::Stance, "restraint", Test::Is(FeatValue::Grade(Grade::new(1).unwrap())))],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
cases.push((
|
||||
"unknown feature",
|
||||
vec![OntologyEntry {
|
||||
when: vec![Condition {
|
||||
slot: Slot::Stance,
|
||||
feature: "feature:9999".parse().unwrap(),
|
||||
test: Test::AtLeast(Grade::new(1).unwrap()),
|
||||
}],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
cases.push((
|
||||
"unknown inventory revision",
|
||||
vec![OntologyEntry { inventory_rev: 99, ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"model generator that is not an attestation",
|
||||
vec![OntologyEntry {
|
||||
annotator: Annotator::Model {
|
||||
family: ModelFamily::Anthropic,
|
||||
generator: "--".into(),
|
||||
},
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
for (why, batch) in cases {
|
||||
assert!(
|
||||
s.admit(batch, &w.inventory).is_err(),
|
||||
"{why} must be refused"
|
||||
);
|
||||
assert!(s.all().unwrap().is_empty(), "{why} wrote something");
|
||||
}
|
||||
// The refusal of a bad choice names the key and no text.
|
||||
let secret = OntologyEntry { choice: "SECRETCHOICE\n".into(), ..entry("ja-JP", 1) };
|
||||
let shown = refused(s.admit(vec![secret], &w.inventory)).to_string();
|
||||
assert!(!shown.contains("SECRETCHOICE"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_accepts_the_bounds_and_joiners() {
|
||||
let d = dir();
|
||||
let w = world();
|
||||
let mut s = store(&d);
|
||||
// Exactly 64 entries in one language; exactly the byte bounds; a ZWNJ.
|
||||
let mut batch: Vec<OntologyEntry> = (1..=64).map(|n| entry("ja-JP", n)).collect();
|
||||
batch[0].choice = "x".repeat(200);
|
||||
batch[0].examples = vec!["y".repeat(120); 3];
|
||||
batch[1].choice = "a\u{200c}b".into();
|
||||
batch[2].when = (0..4)
|
||||
.map(|_| when(Slot::Stance, "restraint", Test::AtMost(Grade::new(1000).unwrap())))
|
||||
.collect();
|
||||
assert_eq!(s.admit(batch, &w.inventory).unwrap(), AddOutcome::Added);
|
||||
assert_eq!(s.all().unwrap().len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_takes_scene_refuses_speaker() {
|
||||
use weksa::inventory::{proof_revision, speaker_scene_revision};
|
||||
let d = dir();
|
||||
let mut inventory = InventoryStore::open(&d.path().join("i.cc")).unwrap();
|
||||
for (rev, entries) in [seed(), proof_revision(), speaker_scene_revision(3)] {
|
||||
inventory.admit_revision(rev, entries).unwrap();
|
||||
}
|
||||
let scene_feature = |gloss: &str| {
|
||||
speaker_scene_revision(3).1.into_iter().find(|e| e.gloss == gloss).unwrap().id
|
||||
};
|
||||
let at = |slot, feature, test| OntologyEntry {
|
||||
inventory_rev: 3,
|
||||
when: vec![Condition { slot, feature, test }],
|
||||
..entry("ja-JP", 1)
|
||||
};
|
||||
let above = Test::Is(FeatValue::Option(lab("above")));
|
||||
let mut s = store(&d);
|
||||
// A Scene condition on a Scene feature admits.
|
||||
assert_eq!(
|
||||
s.admit(vec![at(Slot::Scene, scene_feature("relative_status"), above.clone())], &inventory)
|
||||
.unwrap(),
|
||||
AddOutcome::Added
|
||||
);
|
||||
// Speaker and Predication slots refuse, and a Scene condition naming a
|
||||
// Stance feature refuses.
|
||||
for bad in [
|
||||
at(Slot::Speaker, scene_feature("education"), Test::AtLeast(Grade::new(1).unwrap())),
|
||||
at(Slot::Predication, feature("modality"), Test::Is(FeatValue::Option(lab("actual")))),
|
||||
at(Slot::Scene, feature("restraint"), Test::AtLeast(Grade::new(1).unwrap())),
|
||||
] {
|
||||
let bad = OntologyEntry { n: 2, ..bad };
|
||||
assert!(s.admit(vec![bad], &inventory).is_err());
|
||||
}
|
||||
assert_eq!(s.all().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_is_all_or_nothing() {
|
||||
let d = dir();
|
||||
let w = world();
|
||||
let mut s = store(&d);
|
||||
let bad = OntologyEntry { choice: String::new(), ..entry("ja-JP", 3) };
|
||||
assert!(s.admit(vec![entry("ja-JP", 1), entry("ja-JP", 2), bad], &w.inventory).is_err());
|
||||
assert!(s.all().unwrap().is_empty());
|
||||
|
||||
let batch = vec![entry("ja-JP", 1), entry("en-US", 1), entry("ja-JP", 2), entry("en-US", 2)];
|
||||
assert_eq!(s.admit(batch.clone(), &w.inventory).unwrap(), AddOutcome::Added);
|
||||
assert_eq!(s.all().unwrap().len(), 4);
|
||||
// An identical replay, from a reopened store, changes nothing.
|
||||
let mut again = store(&d);
|
||||
assert_eq!(again.admit(batch, &w.inventory).unwrap(), AddOutcome::Unchanged);
|
||||
// A batch of one stored entry and one new one is not a replay.
|
||||
let mixed = vec![entry("ja-JP", 1), entry("ja-JP", 5)];
|
||||
assert!(again.admit(mixed, &w.inventory).is_err());
|
||||
assert_eq!(again.all().unwrap().len(), 4);
|
||||
// Each language numbers from its own latest.
|
||||
assert_eq!(
|
||||
again
|
||||
.admit(vec![entry("ja-JP", 3), entry("en-US", 3)], &w.inventory)
|
||||
.unwrap(),
|
||||
AddOutcome::Added
|
||||
);
|
||||
// An entry never changes in place.
|
||||
let changed = OntologyEntry { choice: "something else".into(), ..entry("ja-JP", 1) };
|
||||
assert!(again.admit(vec![changed], &w.inventory).is_err());
|
||||
assert_eq!(again.all().unwrap().len(), 6);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>
|
||||
33
data/cultural-ontology/README.md
Normal file
33
data/cultural-ontology/README.md
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# 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.
|
||||
- `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.
|
||||
22
data/cultural-ontology/catalog.yaml
Normal file
22
data/cultural-ontology/catalog.yaml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
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.western_europe_maritime_childhood.v0
|
||||
path: data/cultural-ontology/cultures/western-europe-maritime-childhood.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
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
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 and needs 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
|
||||
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.
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
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.
|
||||
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,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.
|
||||
|
|
@ -369,12 +369,6 @@ target. A Qdrant nearest neighbor is a witness candidate, not a cultural fact.
|
|||
|
||||
\section{Proposed CultCache State Shape}
|
||||
|
||||
No profile store exists. The per-language lowering choices live in
|
||||
\texttt{data/ontology/ontology.cc}; the typed profiles once stored under
|
||||
\texttt{.weksa/cultural-ontology/} and the \texttt{weksa.target\_cultural\_ontology.*}
|
||||
base profiles named in the listing and sketches below are deleted. Community and dialect
|
||||
profiles belong to follow-up \texttt{language-ontology-communities}.
|
||||
|
||||
The following shape should become a typed CultCache document family:
|
||||
\texttt{weksa.cultural\_ontology\_profile.v0}. It can represent base languages,
|
||||
dialects, sociolects, regional overlays, ritual registers, and communities of
|
||||
|
|
@ -618,6 +612,15 @@ feature requires speaker authority, whether it can be rendered in text or only
|
|||
speech synthesis, which source hashes support it, and what must be reported if
|
||||
the feature is rejected.
|
||||
|
||||
Recommended CultCache paths:
|
||||
|
||||
\begin{lstlisting}[basicstyle=\ttfamily\small]
|
||||
.weksa/cultural-ontology/{profileId}.cc
|
||||
.weksa/cultural-ontology/{baseProfileId}/overlays/{overlayId}.cc
|
||||
.weksa/cultural-ontology/catalogs/{catalogId}.cc
|
||||
.weksa/cultural-ontology/evidence-bundles/{bundleId}.cc
|
||||
\end{lstlisting}
|
||||
|
||||
\section{Dialect Profile Sketches}
|
||||
|
||||
\subsection{AAVE/AAL}
|
||||
|
|
|
|||
|
|
@ -252,10 +252,6 @@ pair a role id with a filler node (the inventory seeds `agent`, `patient`,
|
|||
aspect, polarity, modality and evidentiality are features with declared option
|
||||
sets, not fields.
|
||||
|
||||
A predication holds each role once (V11). Coordinated fillers ("A and B") are
|
||||
one `group` referent filling the role, each member related to it by `member_of`,
|
||||
from the member to the group.
|
||||
|
||||
### `relations`
|
||||
|
||||
Edges not owned by one predication. `relation` is a relation id (the inventory
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ The utterance lowerer does not own:
|
|||
- rendered audio
|
||||
- phoneme parity or synth-control truth
|
||||
|
||||
The target-language cultural ontology profile was drafted to own the following; no such profile store exists now (address, politeness and register belong to speaker and scene state, and `data/ontology/ontology.cc` holds per-language lexicon, grammar and discourse choices):
|
||||
The target-language cultural ontology profile owns:
|
||||
|
||||
- address, politeness, register, and social stance distinctions
|
||||
- idiom and metaphor risks
|
||||
|
|
@ -76,8 +76,8 @@ English remains a lowering target, not the pivot language. Existing flavored
|
|||
English fixtures continue to be useful, but new multilingual fixtures should
|
||||
show English as one realization in a set.
|
||||
|
||||
The en-US choices are the `en-US` entries of `data/ontology/ontology.cc`
|
||||
(model-drafted seeds; read with `weksa ontology dump`).
|
||||
The initial cultural ontology profile is
|
||||
`data/target-language-ontology/en-US.yaml`.
|
||||
|
||||
### Brazilian Portuguese
|
||||
|
||||
|
|
@ -94,10 +94,16 @@ The target lowerer should record:
|
|||
defaults
|
||||
- optional regional or cultural overlays when the source context earns them
|
||||
|
||||
No pt-BR ontology entry exists yet; the cut that adds pt-BR writes them to
|
||||
`data/ontology/ontology.cc`. Umbanda-related scenes, speakers, ritual contexts,
|
||||
or referents may later earn a regional or cultural variant, which must not
|
||||
activate for generic Brazilian flavor.
|
||||
The initial cultural ontology profile is
|
||||
`data/target-language-ontology/pt-BR.yaml`.
|
||||
|
||||
Umbanda-related scenes, speakers, ritual contexts, or referents may add the
|
||||
`data/target-language-ontology/pt-BR-umbanda.yaml` overlay. That overlay must
|
||||
not activate for generic Brazilian flavor.
|
||||
|
||||
Regional or cultural variants should be selected through the overlay catalog at
|
||||
`data/target-language-ontology/pt-BR-overlays.yaml`. Planned overlay slots are
|
||||
not active profiles until reviewed examples and source context exist.
|
||||
|
||||
### Japanese
|
||||
|
||||
|
|
@ -113,8 +119,8 @@ The target lowerer should record:
|
|||
- whether subject omission preserves or harms clarity
|
||||
- whether katakana, kanji, kana, or mixed script choices carry useful pressure
|
||||
|
||||
The ja-JP choices are the `ja-JP` entries of `data/ontology/ontology.cc`
|
||||
(model-drafted seeds; read with `weksa ontology dump`).
|
||||
The initial cultural ontology profile is
|
||||
`data/target-language-ontology/ja-JP.yaml`.
|
||||
|
||||
## Packet Shape
|
||||
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
# Name-span annotation
|
||||
|
||||
How the name spans of an imported public-domain work are placed. A span has a
|
||||
committed rule that produced it; this file is that rule.
|
||||
|
||||
## Why
|
||||
|
||||
- `pd-annotation-model-then-attest`: a labelled model places the spans of a
|
||||
public-domain work; the operator may attest them afterwards.
|
||||
- `leak-owned-by-flow-and-scorer-3`: spans are fixed with the text at intake and
|
||||
written by no loop writer. The offsets are derived from markup the annotator
|
||||
writes, never typed by a model (inline marking, as in GPT-NER, Wang et al.
|
||||
2023); `CorpusStore::add` judges range, grapheme boundary, form equality and
|
||||
overlap.
|
||||
|
||||
The work file (`weksa corpus import <work>`) is a transcription of a work in
|
||||
hand: provenance, cast forms, lines, scene groups and the speaker each speech
|
||||
prefix names. It holds no distributor header, licence or trademark text, and the
|
||||
binary fetches nothing.
|
||||
|
||||
## Rubric r1
|
||||
|
||||
You are given a work's cast: each member's entity id and the forms the work spells that member with. For each numbered line, copy the line exactly, character for character, and wrap each place where the line names a cast member by one of that member's listed forms as [[<entity id>|<form>]]. Mark a form only where it refers to that cast member; a listed form used as an ordinary word, or naming someone else, stays unmarked. Do not mark pronouns, titles or descriptions unless the exact text is a listed form. When a form is listed for two members, mark the one the line refers to; when you cannot tell, leave it unmarked. Answer one JSON line per input line, in the order given, and nothing else: {"line": N, "marked": "..."}.
|
||||
|
||||
## Procedure
|
||||
|
||||
- One fresh model agent per work. Its brief is rubric r1, the cast as
|
||||
`<entity id>: <form>, <form>` lines and the work's lines as `<n><TAB><text>`;
|
||||
nothing else (no store, no loop, no other answer).
|
||||
- Import with `--model-family` and `--generator '<annotator model id> (name-span
|
||||
rubric r1, docs/name-span-annotation.md)'`. An operator-written or
|
||||
operator-reviewed answer imports with `--operator`.
|
||||
- Import is all or nothing: every entity and item passes the real store doors on
|
||||
scratch copies before the first write, so a refusal (a parse failure, a span
|
||||
the store judges, a work that repeats a line under case or width folding)
|
||||
leaves the stores untouched. Re-draw the whole answer once, log it, and import
|
||||
again. A work file repeating a line's text is refused naming both lines; leave
|
||||
that line out of the answer file (the rest imports with its numbering intact),
|
||||
since a repeated line cannot be two corpus items.
|
||||
- A line the answer does not cover is not imported by that run; a later run over
|
||||
other lines of the work does not collide (keys are `item:<slug>:<n>`).
|
||||
- A line whose own text holds `[[` or `]]` cannot be marked and is refused; it
|
||||
can still enter by hand through `weksa corpus add --name`.
|
||||
|
||||
## Label scope
|
||||
|
||||
`names_by` labels the spans only, not the line or its speaker. One label per
|
||||
item: a later attestation would be a superseding item with the same text and
|
||||
group, but no command writes one yet; question `pd-name-span-attestation` owns
|
||||
that door.
|
||||
`None` means unrecorded (the cast seeds, `weksa corpus add`, the Dao De Jing
|
||||
bed), not attested.
|
||||
|
|
@ -1,195 +0,0 @@
|
|||
# Prior art and plan
|
||||
|
||||
Meta asked (#weksa, 2026-11-13) for scaffolding to stand on instead of
|
||||
building from base principles. This is a survey of what exists and a plan that
|
||||
borrows it. Every source below was read in full text unless marked **snippet**
|
||||
(seen only in a search result) or **not read**. Research only: nothing here is
|
||||
built, and no new loop machinery is proposed.
|
||||
|
||||
## What exists
|
||||
|
||||
**Semantic backbones: none carries the part we care about.**
|
||||
|
||||
- AMR ([Banarescu 2013](https://aclanthology.org/W13-2322.pdf)): no politeness,
|
||||
speech-act or pragmatics text at all; it also does not distinguish real from
|
||||
hypothetical events (its Section 4).
|
||||
- UMR ([Van Gysel 2021](https://par.nsf.gov/servlets/purl/10288269)): adds
|
||||
document-level coreference, temporal and modal-dependency graphs. The paper
|
||||
has no politeness, addressee or register layer; the only speaker-like object
|
||||
is the author node. Annotation agreement was still "awaiting confirmation".
|
||||
- Universal Dependencies: the `Polite` feature has four values (`Infm`, `Form`,
|
||||
`Elev`, `Humb`; [feature page](https://universaldependencies.org/u/feat/Polite.html)),
|
||||
but the Japanese GSD treebank carries no `Polite`
|
||||
([treebank page](https://universaldependencies.org/treebanks/ja_gsd/index.html)).
|
||||
The page says Japanese *teineigo* shares the value `Form` with formal register
|
||||
although it is a different axis. UD is a parse scheme, not a meaning scheme.
|
||||
- Grammatical Framework RGL: 38 languages, Japanese present
|
||||
([synopsis](https://www.grammaticalframework.org/lib/doc/synopsis/index.html),
|
||||
[status](https://www.grammaticalframework.org/lib/doc/status.html)); the source
|
||||
declares `Style = Plain | Resp`, so two politeness levels and no honorific
|
||||
paradigm
|
||||
([ResJpn.gf](https://raw.githubusercontent.com/GrammaticalFramework/gf-rgl/master/src/japanese/ResJpn.gf)).
|
||||
LGPL/BSD, application grammars may take any licence
|
||||
([LICENSE](https://raw.githubusercontent.com/GrammaticalFramework/gf-rgl/master/LICENSE)).
|
||||
- Abstract Wikipedia / Wikifunctions: encyclopedic content, 2026 soft launch in
|
||||
three languages, no politeness
|
||||
([Meta page](https://meta.wikimedia.org/wiki/Abstract_Wikipedia)). The
|
||||
Wikifunctions NLG and Japanese documentation were **not read**.
|
||||
|
||||
**Typology.**
|
||||
|
||||
- WALS (CC BY 4.0, CLDF at <https://github.com/cldf-datasets/wals>): the only
|
||||
politeness feature is 45A, pronoun politeness
|
||||
([chapter](https://wals.info/chapter/45)); Japanese is coded value 4 ([datapoint](https://wals.info/valuesets/45A-jpn)), pronoun
|
||||
avoidance. No feature for verbal honorifics or register.
|
||||
- Grambank (CC BY 4.0, <https://github.com/grambank/grambank>): GB415 is the
|
||||
second-person politeness distinction; I found no verbal-honorific feature
|
||||
(loose name match, not exhaustive). The 195-feature / 2,467-variety size is
|
||||
**snippet**; Japanese's GB415 value was **not looked up**.
|
||||
|
||||
**Formality control in MT: the closest prior art, and it is a sentence-level
|
||||
label.**
|
||||
|
||||
- [Sennrich 2016](https://aclanthology.org/N16-1005.pdf): a side-constraint
|
||||
token controls T/V; forced-polite output was 96% polite or neutral.
|
||||
- [Feely 2019](https://aclanthology.org/D19-5203.pdf): the same for EN-JA with
|
||||
three levels (informal, polite, formal); labels by rule plus a fastText
|
||||
classifier (F1 0.83-0.86 on 150 hand-labelled sentences); formal text is only
|
||||
0.7-1.6% of training data.
|
||||
- [CoCoA-MT](https://arxiv.org/pdf/2205.04022) (CDLA-Sharing-1.0, repo
|
||||
<https://github.com/amazon-science/contrastive-controlled-mt>): 1,000 train and
|
||||
600 test segments for Japanese with contrastive formal/informal references and
|
||||
phrase-level markers. Two baseline systems' EN-JA outputs, labelled by
|
||||
professionals, came out formal 29.0% / 73.8% and "other" about 20-24%; EN-JA
|
||||
inter-annotator agreement 0.82, the lowest of the six languages.
|
||||
- [Marrese-Taylor 2023](https://aclanthology.org/2023.wmt-1.49.pdf): GPT-3 and
|
||||
ChatGPT prompted reach about 90% formality-control accuracy on EN-JA, which
|
||||
the authors say beats fine-tuned MT; classifier and data at
|
||||
<https://github.com/epochx/japanese-formality> (no licence reported).
|
||||
- [IWSLT 2023 formality track](https://aclanthology.org/2023.iwslt-1.1.pdf): no
|
||||
Japanese; metrics matched-accuracy (phrase markers) and classifier-accuracy.
|
||||
Niu 2017 is read ([D17-1299](https://aclanthology.org/D17-1299.pdf)); Niu 2019
|
||||
and Rippeth 2022 (arXiv 2205.06644, abstract only) are **not read**.
|
||||
- None of these takes a speaker-state or addressee relation. The label is one
|
||||
bit or three levels attached to a source sentence.
|
||||
|
||||
**Grammar-in-context (for conlang targets).**
|
||||
|
||||
- [MTOB](https://arxiv.org/pdf/2309.16575) (MIT code, CC BY 4.0 grammar book):
|
||||
Claude 2 with word list plus retrieved sentences plus long grammar 44.7 / 45.8
|
||||
chrF against a human learner at 51.6 / 57.0.
|
||||
- [Aycock 2025](https://arxiv.org/pdf/2409.19151): most of the gain comes
|
||||
from the book's parallel examples (Gemini-1.5-Flash eng->kgv chrF++ 30.8 with
|
||||
examples only against 34.4 whole book and 11.0 zero-shot; explanations alone
|
||||
22.6). Kalamang is a natural language, so transfer to a conlang is assumed.
|
||||
- [Gemini 1.5 report](https://arxiv.org/pdf/2403.05530): full book 5.46 against a
|
||||
human learner's 5.52 on a 0-6 human scale.
|
||||
Suggests, for a conlang target (assumed to transfer), worked paired examples first and grammar
|
||||
prose second.
|
||||
|
||||
**Prompt optimisation and evaluation.**
|
||||
|
||||
- [DSPy](https://arxiv.org/pdf/2310.03714) (MIT), [MIPRO](https://arxiv.org/pdf/2406.11695),
|
||||
[OPRO](https://arxiv.org/pdf/2309.03409) (Apache-2.0): DSPy compiles take
|
||||
"10-20 trials over 150-300 validation examples"; MIPRO's task sets run from 75
|
||||
train (Iris) to 500 per task. MIPRO found bootstrapped demos gave the biggest
|
||||
gain and tests with Wilcoxon over 5 runs. OPRO discusses overfitting to the
|
||||
training set.
|
||||
- [Koehn 2004](https://aclanthology.org/W04-3250.pdf): paired bootstrap;
|
||||
against a 30,000-sentence reference, a 2.0-point BLEU gap was detected at 95%
|
||||
significance in 31% of runs at n=100 and 65% at n=300; a 5.1-point gap in 97%
|
||||
at n=100. The paper suggests n=100 might be too small.
|
||||
- [Dror 2018](https://aclanthology.org/P18-1128.pdf): paired bootstrap is
|
||||
"less effective for small test sets"; approximate randomization has been used
|
||||
for test sets above 20 points; only 3 of 110 surveyed ACL 2017 papers
|
||||
corrected for multiple comparisons.
|
||||
- [Kocmi 2021](https://arxiv.org/pdf/2107.10821): pairwise accuracy against
|
||||
humans COMET 83.4, BLEURT 80.0, chrF 75.6, BLEU 74.6; recommends COMET
|
||||
primary, a string metric secondary and a paired test; observes "a slight drop
|
||||
in metric ranks for some pretrained metric" against ChrF for non-Latin and
|
||||
logogram targets and says more analysis would be required.
|
||||
- [chrF](https://aclanthology.org/W15-3049.pdf): validated on seven targets, Japanese
|
||||
not among them.
|
||||
|
||||
## What we borrow
|
||||
|
||||
| Need | Borrow | Instead of |
|
||||
|---|---|---|
|
||||
| Politeness vocabulary for the packet's register field | UD `Polite` values (Infm, Form, Elev, Humb) as the label set, and Feely's three-level Japanese split | inventing level names |
|
||||
| Modal/author structure | UMR's conceiver and modal-dependency idea for evidence/stance fields | a bespoke modality scheme |
|
||||
| Japanese test of register | CoCoA-MT JA set (600 contrastive test segments, phrase markers), KeiCO for relation-labelled Japanese, and the Japanese-formality classifier | hand-written register references only |
|
||||
| Conlang scaffolding | MTOB recipe: worked paired examples first, word list, grammar prose after (shown on Kalamang, a natural language; transfer to a conlang is an assumption) | long grammar prompts alone |
|
||||
| Typology priors | WALS 45A and Grambank GB415 to seed which targets have a politeness axis | per-language guesses |
|
||||
| Significance | paired approximate randomization over items; chrF with an embedding metric | reading small differences as results |
|
||||
| Optimiser | DSPy/MIPRO only once a scoring set of at least 75 items exists (MIPRO's smallest task), more for stable compiles; the 35-item sets are below that | the golf loop growing a private optimiser |
|
||||
|
||||
We do not adopt AMR, UMR, UD or GF as the packet. None represents the speaker's
|
||||
relation to the addressee, which the packet's scene state does. The packet stays
|
||||
ours; it borrows vocabulary.
|
||||
|
||||
## What is actually new
|
||||
|
||||
Prior work already conditions honorific choice on the speaker-addressee
|
||||
relation or status in narrower forms: KeiCO (Liu and Kobayashi 2022, 10,007
|
||||
examples, annotates the speaker-listener social relationship; read through
|
||||
Marrese-Taylor 2023 and the abstract), Korean context-aware NMT that infers the
|
||||
relation from surrounding sentences
|
||||
([MDPI](https://www.mdpi.com/2079-9292/10/13/1589), snippet), Brown-Levinson
|
||||
generation that takes power and distance as parameters (Walker et al., not
|
||||
read), and a 2026 translator given a known addressee
|
||||
([Cihlar et al.](https://aclanthology.org/2026.iaai-1.3), snippet only). What I
|
||||
did not find is the whole chain: persona state (status, restraint, stance) to a
|
||||
register decision for an LLM lowerer, measured against a prompted baseline.
|
||||
That is the claim, and it is relative to what I searched; closer work may
|
||||
exist.
|
||||
|
||||
Uncontrolled commercial MT left 20-24% of EN-JA outputs inconsistent in
|
||||
register (CoCoA-MT Table 4, two generic systems, no formality instruction). That
|
||||
shows register is unstable without control, not how a prompted LLM behaves.
|
||||
|
||||
## Smallest end-to-end slice
|
||||
|
||||
One path, existing machinery, ja-JP only, no new loop:
|
||||
|
||||
1. A packet with scene state (speaker, addressee, relation) goes through the
|
||||
current `weksa loop` encode and lowering to Japanese.
|
||||
2. The same packet under two relations (to a superior and to an intimate) must
|
||||
produce the two UD `Polite` levels; check with the Japanese formality
|
||||
classifier plus a native-reader pass on the 35-item Validation corpus per
|
||||
language (see the map's recalibration blocks).
|
||||
3. Score the register decision as a classification (matched accuracy), not only
|
||||
chrF. CoCoA-MT's JA references give an outside check on the classifier, a
|
||||
weak one: its reference-based segment classifier on EN-JA had precision
|
||||
0.71 and 0.69 and recall 0.43 and 0.54 in the paper's Table 5.
|
||||
|
||||
Out of scope for the slice: conlang targets, optimisers, a second language.
|
||||
|
||||
## What good enough means
|
||||
|
||||
- Register accuracy: report matched accuracy for ours and for a plain prompt
|
||||
that is given the relation in words, on the same items, with paired
|
||||
intervals. We measure that baseline ourselves; Marrese-Taylor's roughly 90%
|
||||
is classifier accuracy (0.83-0.86 by phrase-marker matching) for binary
|
||||
formal/informal control with the label named in the prompt, an upper-region
|
||||
reference and not our baseline. The claim is non-inferiority with a stated
|
||||
margin. Superiority is claimed only if enough items are discordant (about 6
|
||||
or more, all in one direction, at n=35); against a baseline near 90%, n=35
|
||||
cannot show it, and the result is then "not detected".
|
||||
- Meaning is not lost: chrF and meaning cosine are not detectably below the
|
||||
plain prompt on the same items, under the same paired test.
|
||||
- Honest sample size: 35 items per language detects only large gaps, so results
|
||||
carry intervals and "not detected" stands as an outcome. Small gaps are not
|
||||
claims. Koehn's figures are for sentence-level BLEU on 100-3000-sentence
|
||||
blocks and do not transfer to a binary register metric on 35 items; power
|
||||
for that is computed directly from the discordant-pair count.
|
||||
- A native-reader check on register for a sample, because every automatic metric
|
||||
here was validated on languages other than the persona register we care about.
|
||||
|
||||
## Open
|
||||
|
||||
- Which persona fields (status, restraint, stance) are in the packet today
|
||||
versus planned: this doc does not decide that; `docs/interlingua-standard.md`
|
||||
owns it.
|
||||
- Licences not checked: the UMR dataset, the other four Japanese UD treebanks,
|
||||
CoCoA-MT repo licence ambiguity (paper says CDLA-Sharing-1.0, GitHub says
|
||||
NOASSERTION).
|
||||
|
|
@ -65,7 +65,7 @@ Verified licence facts are few. Discord data excluded by policy; not read.
|
|||
- PersonaChat (Zhang et al. 2018): ParlAI project page, archived 2020-08-01, states no licence, only "You may continue to use the data without issue". [V] https://parl.ai/projects/personachat/ ; paper https://arxiv.org/abs/1801.07243 says data released open source via ParlAI; licence text [GAP]. Crowdworker-written, persona-statement-conditioned chit-chat [B].
|
||||
- LIGHT: ParlAI page states no licence; contents: 663 locations, 3,462 objects, 1,755 character types, 11,000 episodes; WILD 41,131 training episodes from game deployment (human players, so a different provenance than crowdwork). [V] https://parl.ai/projects/light/ . Licence [GAP: check ParlAI repo].
|
||||
- Cornell Movie-Dialogs Corpus: licence/terms page fetch failed (certificate rejected) https://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html . [GAP] Underlying scripts are copyrighted film text [B]; dataset licence unverified.
|
||||
- Project Gutenberg: "vast majority" of eBooks public domain in the US, so no one can grant or withhold permission for uses; PG cannot sublicense copyrighted items; subject to its Terms of Use, which the permission page links and does not summarise; no statement on ML/bulk use on that page. [V] https://www.gutenberg.org/policy/permission.html . Terms-of-Use text on bulk/automated access and the trademark licence: read 2026-11-13, see `2026-11-13-gutenberg-terms.md`. Items public domain in the US may not be elsewhere (same page).
|
||||
- Project Gutenberg: "vast majority" of eBooks public domain in the US, so no one can grant or withhold permission for uses; PG cannot sublicense copyrighted items; subject to its Terms of Use, which the permission page links and does not summarise; no statement on ML/bulk use on that page. [V] https://www.gutenberg.org/policy/permission.html . Terms-of-Use text on bulk/automated access and the trademark licence: [GAP, not read]. Items public domain in the US may not be elsewhere (same page).
|
||||
- Google Synthetic-Persona-Chat (model-generated, persona-chat-style): CC BY-NC? listed as cc-by-4.0 on HF. [V search-only] https://huggingface.co/datasets/google/Synthetic-Persona-Chat
|
||||
- Operator-authored or model-generated corpus: no licence question beyond provider terms [B, unread this pass]. Problems with evaluating on model-generated text: see 2 (self-bias, preference leakage, stylistic homogeneity: Xu et al. 2025; Li et al. 2025). The same Xu et al. finding says it extends to open-ended generation.
|
||||
- Expressive-register-annotated English corpora (hedging, humour, affect, politeness labelled), with permissive terms: [GAP] not searched beyond the list above (e.g. Stanford Politeness Corpus, GYAFC formality, Enron etc. are [B] candidates, unverified, GYAFC is known to carry Yahoo Answers terms [B]).
|
||||
|
|
@ -83,6 +83,6 @@ Verified licence facts are few. Discord data excluded by policy; not read.
|
|||
- No per-metric human-correlation numbers for hedging, humour, affect, stance, persona voice; nearest is formality (Briakou 2021). COMET, BLEURT, MAUVE correlations not obtained.
|
||||
- No source on surface-form smuggling through an LLM bottleneck or its defences (vocab restriction, paraphrase invariance).
|
||||
- No source on schema/inventory growth from generation failures, or its overfitting controls.
|
||||
- Cornell, LIGHT, PersonaChat licence texts not obtained.
|
||||
- Cornell, LIGHT, PersonaChat licence texts not obtained; Gutenberg ToU on bulk use not read.
|
||||
- No realiser or evaluation protocol for constructed languages from a meaning representation.
|
||||
- Several arXiv PDFs (Briakou, Zheng, STEL, LUAR/StyleDistance) fetched as binary; numbers above come from the ar5iv/arXiv-HTML versions where marked, otherwise search summaries.
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
# Project Gutenberg terms: bulk access and header stripping
|
||||
|
||||
Read 2026-11-13 for follow-up `gutenberg-terms` (campaign `weksa-lowering`),
|
||||
ahead of cut `pd-importer`. Pages: gutenberg.org `policy/permission.html`,
|
||||
`policy/terms_of_use.html`, `policy/robot_access.html`, `policy/license.html`.
|
||||
The quotes were checked against the live HTML of each page by a second reader.
|
||||
`pd-importer`'s Imagination re-reads the pages before it fixes a fetch path,
|
||||
since they change.
|
||||
|
||||
## Findings
|
||||
|
||||
- **Automated access to the main site is refused.** Terms of Use: "This website
|
||||
is intended for human users only"; "Any perceived use of automated tools to
|
||||
access this website will result in a temporary or permanent block". OPDS
|
||||
feeds: no more requests than a browser user would make; heavy requesters are
|
||||
blocked by IP.
|
||||
- **Bulk has two sanctioned paths.** Terms of Use: take bulk downloads "from
|
||||
one of our mirrors, not from the main site". The robot-access page names the
|
||||
`robot/harvest` wget endpoint (`-w 2`, filterable by file type or language)
|
||||
and recommends a private mirror for a full local copy; it suggests checking
|
||||
periodically for changes. Catalog data are offered as
|
||||
machine-readable offline catalogs, "granted to the public domain".
|
||||
- **Header and licence stripping.** Licence section 1.C: for a work not
|
||||
protected by US copyright, with the user in the US, the Foundation does "not
|
||||
claim a right to prevent you from copying, distributing, performing,
|
||||
displaying or creating derivative works", "as long as all references to
|
||||
Project Gutenberg are removed", the condition holding for a user in the US.
|
||||
Section 1.E opens "Unless you have removed all references to Project
|
||||
Gutenberg", and 1.E.1 to 1.E.7 (including 1.E.4, do not detach the licence)
|
||||
attach to a work on which the phrase "Project Gutenberg" appears or with which
|
||||
it is associated, so a text with every reference removed is outside 1.E.
|
||||
1.E.2 is not that grant: it says a PG eBook derived from texts not restricted
|
||||
by US copyright may be copied and distributed in the US without fee. The
|
||||
trademark is registered; non-commercial use of the name needs no permission,
|
||||
commercial use does.
|
||||
- **No statement on machine learning or AI use** on any of the four pages.
|
||||
- **US public domain only.** The Foundation makes no claim about copyright
|
||||
outside the US (1.D). A work free in the US may not be free elsewhere, and
|
||||
Gutenberg's own catalog is not a per-work clearance.
|
||||
|
||||
## What this decides for `pd-importer`
|
||||
|
||||
- Fetch from a mirror or an offline dump. The Terms of Use footnote counts "many
|
||||
books" as more than about 100 a day and sends those to mirrors, while
|
||||
`robot/harvest` is a `www.gutenberg.org` URL: use it (with `-w 2`) only for a
|
||||
handful of works. Never crawl `gutenberg.org` pages or OPDS from the loop host.
|
||||
- Strip the whole header and footer, every Project Gutenberg reference and the
|
||||
licence text from the stored text; keep provenance as the ebook number and
|
||||
edition in the item's source field, which is Weksa's own record and not a use
|
||||
of the mark. This is the path `docs/targets/dao-de-jing-test-bed.md` already
|
||||
takes. The remaining open question there, what counts as a "reference", stays
|
||||
open: the safe reading is that the ebook number in a provenance field is a
|
||||
catalogue identifier, not a reference inside the work, but nothing read here
|
||||
rules on it.
|
||||
- Per-work check stays with the importer: the work's author and first
|
||||
publication date against US public-domain rules, recorded on the item. The
|
||||
Foundation's catalogue does not supply it. A work Gutenberg posts with the
|
||||
copyright holder's permission (1.E.3) is out of scope.
|
||||
- No importer code in this note.
|
||||
|
|
@ -1,116 +0,0 @@
|
|||
# Scene annotation
|
||||
|
||||
How the keeper scenes of `data/original/speaker-state.cc` are labelled. A scene
|
||||
label has a committed rule that produced it; this file is that rule.
|
||||
|
||||
## Why
|
||||
|
||||
Two findings forced a written rule.
|
||||
|
||||
- `annotation-rank-from-register`: an annotator who reads the line's register
|
||||
(politeness forms, honorifics, endings) to decide the speaker's rank hands the
|
||||
lowering its own answer back, because register is what the lowering must
|
||||
produce from the scene.
|
||||
- The addressee gate (`with_scene` in `crates/weksa/src/validate.rs`): a scene is
|
||||
read only when the packet names a discourse addressee. A line that addresses no
|
||||
one reads `NoAddressee` and no Scene entry selects, so labels on narration are
|
||||
inert and the only labels that bite are those on lines said to someone.
|
||||
|
||||
The earlier labels followed two briefs that were never committed and that
|
||||
disagreed with each other (the relation to the reader, and a situation read with
|
||||
the register ignored). The rubric below replaces both for every live group.
|
||||
|
||||
## Provenance
|
||||
|
||||
Cut `weksa-lowering:cut_spec:cut-scene-in-group.r1`, ruling
|
||||
`weksa-lowering:ruling:scene-rubric-whole-bed`: all 98 live Train and Validation
|
||||
groups of `data/original` receive a new scene revision from annotator A under
|
||||
rubric r1, generator `claude-sonnet-5-5 (Weksa Hands, scene rubric r1,
|
||||
docs/scene-annotation.md)`. Earlier revisions stay as provenance. The rubric uses
|
||||
no corpus line as an example on purpose: a labelled example would make the blind
|
||||
check against the old labels circular.
|
||||
|
||||
A later rubric revision gets a new section and a new generator string; r1 is
|
||||
never edited.
|
||||
|
||||
## Rubric r1
|
||||
|
||||
The speaker of every line is the keeper, a quiet caretaker of a house and garden. First decide whether the line addresses a listener: it asks them something, asks them to do something, tells them about themselves, wishes something for them, or speaks to them as you. A line that addresses no one (narration, description, a remark about the world or about other people, a thought or wish with no one addressed) is told to the reader, a stranger: answer addressed false, relative_status level, intimacy 500, in_group false. People named inside a line are not its listener.
|
||||
|
||||
For a line that addresses a listener, answer addressed true and judge the keeper's relation to that listener from the situation the line states or implies, never from its register: politeness forms, honorifics, sentence endings, contractions, please and casual particles are what the lowering must produce from the scene, so they cannot decide it. relative_status: above when the situation gives the keeper standing over the listener (instructing, advising or permitting as elder, host, employer or teacher); below when it gives the listener standing over the keeper (the keeper serves, thanks, or asks a favour of a guest, employer, elder or official); level when it shows neither.
|
||||
|
||||
intimacy, 0 to 1000: 500 when the line shows nothing; up to 800 when it shows shared daily life (the listener's body, sleep or habits, the household's routine); above 800 only for a stated close bond; down to 200 for a stated first meeting or a service relation. in_group: true only when the line shows the listener belongs to the keeper's household, family or working circle, stated or plainly implied; a request, a question or a kind wish alone is not enough; otherwise false. Answer one JSON line per group, in the order given and nothing else: {"group": G, "addressed": true|false, "relative_status": S, "intimacy": N, "in_group": true|false}.
|
||||
|
||||
## Procedure
|
||||
|
||||
- Annotator A (committed) and annotator B (measurement only) are separate fresh
|
||||
model agents, one pair per language (49 live groups each). Each sees only the
|
||||
text of Rubric r1 above and that language's sentences as `group<TAB>"text"`,
|
||||
shuffled by a fixed seed. Neither sees an existing scene, the other annotator's
|
||||
answer, the ontology, which items are old or new, or any Test text.
|
||||
- An output that does not parse or misses a group is re-drawn once and logged.
|
||||
- A's labels are written with `weksa scene put` (one revision per group,
|
||||
`--to unnamed --inventory-rev 4`). `addressed` is not stored: no Scene feature
|
||||
carries it.
|
||||
- Disagreements are reported, never adjudicated.
|
||||
|
||||
## Agreement at r1 (this cut, 98 live groups, 49 per language)
|
||||
|
||||
Four fresh agents drew the labels (A-en, A-ja, B-en, B-ja); the briefs were the
|
||||
rubric section plus one language's shuffled sentences (SHA-256 of the brief
|
||||
bodies: en-US `db087476...dbc04e`, ja-JP `c5b81b27...97488c`; no Test text in
|
||||
either). No draw was repeated. Annotator model: `claude-sonnet-5-5`.
|
||||
|
||||
A against B (B measures only): pooled `addressed` equal 96/98 (kappa 0.96),
|
||||
`in_group` equal 93/98 (kappa 0.79), `relative_status` equal 89/98, intimacy
|
||||
within 150 on 98/98. en-US: addressed 47/49, in_group 47/49 (0.86),
|
||||
relative_status 45/49. ja-JP: addressed 49/49, in_group 46/49 (0.64),
|
||||
relative_status 44/49.
|
||||
|
||||
Blind check, A against the 56 older labels: `relative_status` equal 49/56,
|
||||
`in_group` equal 53/56 (kappa 0.64), intimacy within 150 on 55/56. Three
|
||||
in_group differences: `original-ja-shimoyado-2` and `original-ja-sakana` (both
|
||||
narrations, true to false) and `original-ja-asa` (an instruction to a household
|
||||
member, false to true).
|
||||
|
||||
In_group true across the 98: 42 before, 15 after; every unaddressed line is now
|
||||
false (it was true on 17 of the 21 unaddressed vgrow groups). Disagreements are
|
||||
reported, not adjudicated.
|
||||
|
||||
## Reproducing the cut
|
||||
|
||||
`scripts/scene-annotation/` holds the standard-library scripts of this cut, run
|
||||
from the repo root with `WEKSA` (the binary) and `SCENE_SCRATCH` (a directory
|
||||
that is never committed): `build_briefs.py` writes the two annotator briefs from
|
||||
the Rubric r1 section and prints each brief's Test-leak count (must be 0) and
|
||||
sha256 (it reproduces the briefs of this cut byte for byte); `put_labels.py`
|
||||
puts A's `A-en.jsonl` and `A-ja.jsonl`; `agreement.py` prints the tables above and
|
||||
must run before the puts, against the store at 76fa685, because the older labels
|
||||
are then its latest revisions (it also reads the round-1 encoder answers of
|
||||
`runs/growth-base` through `ROUND1`). `DIGEST_OF_THE_RUBRIC` and
|
||||
`DIGEST_OF_THE_EARLIER_SCENES` in `crates/weksa/tests/original_corpus.rs` pin the
|
||||
rubric text and the 113 earlier revisions.
|
||||
|
||||
## Known limits of r1 labels
|
||||
|
||||
Found by Soul's pass on this cut (`weksa-lowering:verdict:cut-scene-in-group.s1`).
|
||||
They are not fixed in r1; a reviewer's pass over the labels is follow-up
|
||||
`weksa-lowering:follow_up:scene-labels-reader-review`.
|
||||
|
||||
- The new labels change which ontology entries are selected for 37 groups. Eight
|
||||
addressed lines move onto the casual in-group entries (en-US:12: lantern,
|
||||
broom, mirror, seedling; ja-JP:12: furo, asa, irori, yurikago), while their
|
||||
references are polite requests. The reader default (level, 500, false) is
|
||||
exactly the condition of ja-JP:11.
|
||||
- `relative_status` tracks request form for some lines: imperatives read above,
|
||||
favour questions read level or below, so the same household request gets
|
||||
different standing in two forms (hane above/650/true, kabin below/500/false;
|
||||
B gave both level/false). Form is what signals the speech act, which is what
|
||||
part 2 asks for, and register is what part 2 forbids.
|
||||
- `in_group` is true on some requests alone (lantern, mulch, stool, hane) and on
|
||||
a line whose only family member is named inside it (original-ja-ane), though r1
|
||||
says a request or a person named inside the line is not enough. A and B
|
||||
agreeing does not clear this.
|
||||
- A run opened on the old speaker-state refuses to continue after merge:
|
||||
`runs/growth-base` pins the store of `/var/lib/mind-weksa-self/Weksa-growth`
|
||||
(main), and that checkout must not be pulled while the run is wanted.
|
||||
|
|
@ -20,13 +20,12 @@ plus a separately recorded chosen gloss per lowering).
|
|||
is applied anywhere both meet.
|
||||
- Rebuild: `weksa --corpus C --inventory I --entities E` with `inventory seed`,
|
||||
`inventory proof`, `inventory dao`, `entity put entity:laozi ...`,
|
||||
`corpus add ... --language en-US --source public-domain` per item, then `packet dao <store>`.
|
||||
`corpus add ... --source public-domain` per item, then `packet dao <store>`.
|
||||
- Source: Project Gutenberg eBook 216, "The Tao Teh King, or the Tao and its
|
||||
Characteristics", Laozi, tr. James Legge (Sacred Books of the East 39, 1891).
|
||||
Gutenberg's licence (1.C) does not claim a right to prevent derivative works of
|
||||
a work not protected by US copyright, for a user in the US, provided every
|
||||
Project Gutenberg reference is removed (see
|
||||
`docs/research/2026-11-13-gutenberg-terms.md`). The items hold only Legge's words, one numbered section
|
||||
Gutenberg's licence (1.E.2) lets a work derived from texts not protected by US
|
||||
copyright be used with no fee provided every Project Gutenberg reference is
|
||||
removed from the work. The items hold only Legge's words, one numbered section
|
||||
or sentence each; no Gutenberg header, licence text or trademark is stored,
|
||||
and the eBook file itself is not committed. `edition_url` names the page the
|
||||
text was retrieved from, as a citation of provenance and not as part of any
|
||||
|
|
|
|||
|
|
@ -31,17 +31,17 @@ means no store holds it and nothing writes it.
|
|||
|---|---|---|---|
|
||||
| Packet | Key `packet:<16 hex>`, an opaque digest of item, inventory revision and encoder (the item key lives in `provenance.corpus_item`, which the lowerer never sees); CultCache type `weksa.interlingua_packet`, carrying `schema_version` and `inventory_rev`. Every id inside is an opaque form type (`n<k>` nodes, `encoder:<16 hex>`, canonical `<family>:<n>`). From cut `speaker-state` (schema v4) it also carries the utterance **stance**: the speaker's felt affect and restraint, as inventory features of slot `Stance` (see Speaker state below) | Minted by an encoder for one corpus item under one spec version; immutable; a new spec version means a new packet, never an edit. Admitted only through `PacketStore::admit`, which validates against the inventory store at the packet's revision | The encoder writes; the form types refuse malformed ids at construction and load, the validator refuses broken references and over-capacity packets: a feature at most once per slot, at most 64 nodes (`typed-packet`); nothing else writes packets |
|
||||
| Schema version | `weksa.interlingua_packet.v<N>` constant in `crates/weksa`; published JSON Schema at `schemas/cultnet/` | Bumped by a commit that changes the Rust types; the published schema is regenerated in the same commit and a test fails on drift | A cut (Hands, under a spec); never the loop |
|
||||
| Inventory entry | Key `<family>:<n>`, `n` canonical decimal >= 1 (families: concept, frame, role, relation, speech_act, feature, referent_kind, extension); type `weksa.inventory_entry`, with a bounded gloss, value kind (option labels bounded), the slots a feature may sit in (`Discourse`, `Referent`, `Predication`, `Relation`; `Stance` from cut `speaker-state`, `Speaker` and `Scene` from cut `speaker-scene`), `introduced_rev` and optional `retired_rev`. Speaker axes, scene relations and affects are features of those slots, so the loop grows them like any closed-class family and convergence covers them | Added or retired by an inventory revision; never edited in place (a changed meaning is a retire plus an add); a retired id still resolves for packets of earlier revisions | The loop's accepted rounds, whose minting call the context builder assembles from Train items only; `weksa inventory admit` for one model-drafted `EditDraft` outside a run (cap 256, reviewed whole in its cut; same numbering and admission check as the loop); Self on merge to main. `data/original` revs 5 (233 concepts and frames) and 6 (five concepts closing named gaps) were drafted by claude-sonnet-5-5 (Weksa Hands, model-drafted original-bed lexicon from Train and Validation passages); Validation-informed: numbers on this bed measure lowering, never generalization or convergence. Residue after rev 6, not amended (each fresh coverage reader names new gaps; the loop's growth path owns them): simultaneity (ながら), distal deixis (あの), 'first' (まず), counterfactual mood, 'at least', emphatic question; heaven versus sky for the visible 天 stays weak. Admission checks form, not text |
|
||||
| Inventory entry | Key `<family>:<n>`, `n` canonical decimal >= 1 (families: concept, frame, role, relation, speech_act, feature, referent_kind, extension); type `weksa.inventory_entry`, with a bounded gloss, value kind (option labels bounded), the slots a feature may sit in (`Discourse`, `Referent`, `Predication`, `Relation`; `Stance` from cut `speaker-state`, `Speaker` and `Scene` from cut `speaker-scene`), `introduced_rev` and optional `retired_rev`. Speaker axes, scene relations and affects are features of those slots, so the loop grows them like any closed-class family and convergence covers them | Added or retired by an inventory revision; never edited in place (a changed meaning is a retire plus an add); a retired id still resolves for packets of earlier revisions | The loop's accepted rounds, whose minting call the context builder assembles from Train items only; Self on merge to main. Admission checks form, not text |
|
||||
| Inventory revision | Key `rev:<n>`, type `weksa.inventory_revision`, with parent, change list and `frozen` | Appended per accepted round; exactly one revision is ever marked frozen, by the convergence test | The loop's accept rule appends; the convergence test freezes; Self records the freeze as a ruling |
|
||||
| Target profile | Locale or language-project id (`en-US`, `ja-JP`, a conlang's slug). Until entries grow in rounds there is no profile revision document: a run names the profile it lowered with by the ontology store's path and digest in its `RunRecord` (cut `language-ontology`); `profile:<language>:<n>` revision documents arrive with follow-up `language-ontology-growth` | The ontology store is revised by commit; a run pins it and refuses drift; it likewise pins the speaker-state store (`RunRecord` keys 17 and 18, `Drift(SpeakerState)`, cut `language-ontology-scene`) | Profile authors and accepted rounds; never the lowerer's defaults (`persona-drives-register`) |
|
||||
| Language ontology entry (cut `language-ontology`) | Key `onto:<language>:<n>`, `n` from 1 per language; type `weksa.ontology_entry` in `data/ontology/ontology.cc`: the language, the revision of the inventory it was admitted through (provenance: beds number revisions independently and a run reads each condition's feature at its own head), a layer (`Lexicon`, `Grammar`, `Discourse`, `Phonology`, `Orthography`, as the door spells them; the mint prompt ends with an `example` line serialized from the draft type itself), at most four conditions (a feature id of slot `Stance`, `Discourse` or `Scene` with `AtLeast`/`AtMost`/`AtMostOrUnset` a grade or `Is` an option or flag; a `Scene` condition reads the relation of the item's speaker to its addressee that `with_scene` selected; slot `Speaker` and community ids wait on follow-up `language-ontology-communities`), a choice of 1 to 200 bytes, at most three examples of 1 to 120 bytes, and an `Annotator`. Whether an entry's text keeps politeness on the scene is a model reader's judgment, owed per change (a mint owes it under `language-ontology-growth`), not a test | Admitted in all-or-nothing batches through `OntologyStore::admit`, immutable, never edited; retire arrives with `language-ontology-growth`. The run pins the store like the entity store (path and digest, `Drift(Ontology)`) and never writes it; slice 1 of growth is outside any run: `weksa loop mint-ontology` drafts entries from the run's Train items of one language into `<root>/ontology-mint/<digest>.answer`, `weksa ontology admit --ontology <copy>` admits them into a file copy, and a new run pins the copy (a run-owned copy waits on follow-up `language-ontology-growth`). Cut `language-ontology-seed` converts by drafting, not by parse: a fresh model drafts each language's seed from that language's YAML and the inventory's feature lines with no corpus text, then deletes `data/target-language-ontology/` and `.weksa/cultural-ontology/` in the same cut | Seed: a labelled model (`Annotator::Model`), no operator gate, never Test evidence (`ja-ontology-owner-answer`); attestation (operator, native reader) appends later. Accepted rounds later, through a mint call from Train items only. Selection is `ontology::select(ontology, language, view)`, called only inside `Prompt::lower`, so no caller picks entries; the prompt prints each selected entry's id, layer, choice and examples. Its text is minted text for the leak diagnostic, which today has no runtime caller (follow-up `leak-diagnostic-in-round`). The store was rebuilt without ja-JP `:14` and `:15` (above-status Scene entries; a paired measure found them net-negative on register, follow-up `ja-scene-entries-lower-register-agreement`), so ja-JP ends at `:13`: an above-status out-group addressee, and an above-status in-group addressee below intimacy 700, select no ja-JP Scene entry (`:12` still selects in-group at intimacy 700 or more regardless of status) until a native reader attests a replacement (`ja-native-reader-scenes`). ja-JP `:5`, `:7` and `:8` were revised by certainty and restraint `AtMostOrUnset` conditions (holds when the feature is unrated or at most the grade; `AtMost` still fails on an unrated feature) in a store rebuild (the store has no retire, so a conditions change is a rebuild), which makes ja-JP's hedging, certainty, affection, restraint and sadness entries disjoint on `:5`/`:6`, `:4`/`:7`, `:6`/`:7`, `:6`/`:8`, and ja-JP `:3` (anger) carries `AtMostOrUnset` hedge and affection bounds, as en-US `:3`, which makes `:3`/`:5` and `:3`/`:7` disjoint; en-US `:3` carries `AtMostOrUnset` hedge and affection bounds, `:5` an `AtMostOrUnset` certainty bound (the clause it held in prose) and `:8` one too (as ja-JP `:7`), which makes `:3`/`:5`, `:3`/`:8`, `:5`/`:6` and `:6`/`:8` disjoint, while `:6`/`:10` stay co-selectable and are kept apart by scoping in `:6`'s text; ja-JP `:9` was reworded in a rebuild to state its question ending as available, so `:6`/`:9`, `:5`/`:9` and `:3`/`:9` stay co-selectable and are reconciled by wording, not by condition |
|
||||
| Community (cut `language-ontology`, follow-up `language-ontology-communities`) | Key `community:<slug>`; type `weksa.community`, built fresh when the cut is mapped: `data/cultural-ontology/` (draft YAML profiles, read by no code) is deleted from main (cut 5e `delete-cultural-ontology`) and stays in git history before that cut's commit | Revised by commit; a speaker names the communities it belongs to by id | The cultural ontology's author (owner-attested evidence only; Discord-only content stays deleted, `discord-only-content-deleted`) |
|
||||
| Target profile | Locale or language-project id (`en-US`, `ja-JP`, a conlang's slug) plus a revision `profile:<language>:<n>` | Authored, revised by commit or by an accepted round that changed the lowering; each lowering names the revision it used | Profile authors and accepted rounds; never the lowerer's defaults (`persona-drives-register`) |
|
||||
| Language ontology entry (cut `language-ontology`) | Key `onto:<language>:<n>`; type `weksa.ontology_entry`: conditions over feature values (stance, speaker, scene, packet features) and community ids, and the surface choice they select (layer: lexicon, grammar, discourse, phonology, orthography; a bounded descriptor and at most three bounded examples); introduced and retired by a profile revision | Added or retired by a profile revision, never edited; converted from `data/target-language-ontology/*.yaml`, which is deleted in the same cut so the YAML is not a second owner | The language's owner (the operator for her settings' languages) and accepted rounds; an ontology-minting call is assembled from Train items only, like an inventory-minting call, and its text is in the scorer's leak diagnostic. Selection is deterministic code (`select(profile, stance, speaker, scene)`); the lowerer realizes the selected choices and the trace lists their ids (`lowering-traced`) |
|
||||
| Community (cut `language-ontology`) | Key `community:<slug>`; type `weksa.community`, converted from `data/cultural-ontology/cultures/` and `referents/` (YAML deleted in the same cut) | Revised by commit; a speaker names the communities it belongs to by id | The cultural ontology's author (owner-attested evidence only; Discord-only content stays deleted, `discord-only-content-deleted`) |
|
||||
| Speaker (cut `speaker-scene`) | Key `speaker:<slug>@<n>`; type `weksa.speaker`: stable axes as feature values of slot `Speaker` (origin, socioeconomic standing, age cohort, education and whatever the loop adds), at an inventory revision, and an `Annotator` | A new revision appends, never edits; a corpus item and every prior turn name a speaker slug, and a round records the speaker revisions it read | The annotator it names: `PersonaSnapshot` (a projection of a `gamecult.persona_state.v0` document, naming its source document and `updatedAt`), `Operator`, `WorkMetadata` (a public-domain work's own cast list and narration), or `Model { family, generator }` (the 2b `ModelFamily`) |
|
||||
| Scene (cut `speaker-scene`) | Key `scene:<group>@<n>`, the item's split group; type `weksa.scene`: participants (speaker slugs) and, per ordered pair, relation features of slot `Scene` (relative status, intimacy, in-group, audience and whatever the loop adds), at an inventory revision (provenance; a run reads the features at its own head), and an `Annotator` | As Speaker. Keyed by the group, so a scene never straddles the split. `data/original/speaker-state.cc` holds Model-annotated keeper scenes, one per Train or Validation group of both languages (`weksa scene put|dump`); a Test group has none and reads `NoScene` | As Speaker; a model-annotated scene is never Test evidence |
|
||||
| Corpus item | Key `item:<source-slug>:<n>`, `n` canonical decimal >= 1 (no sign, no leading zero, from cut 2b); type `weksa.corpus_item` with text, language, speaker, split group, prior turns, source and who placed its name spans (`names_by`, an `Annotator`, absent when unrecorded; cut `pd-name-spans`). Source `ModelWritten` carries a `ModelFamily` enum, the generator string as the fixture wrote it, and a prompt digest (cut 2b). The item carries no speaker state of its own: its speaker slug and group name the Speaker and Scene documents | Admitted once; the whole item is immutable (re-adding an identical item is a no-op, any difference is refused; a correction is a new item that `supersedes` the old); text already held under another key is refused unless the new item supersedes that key (cut 2b); withdrawn, never deleted, so old scores stay explainable | Importers and `weksa corpus add`, under `corpus-cast-plus-public-domain`; the source enum has no variant for Discord or any training-forbidden source (`corpus-clean`) |
|
||||
| Scene (cut `speaker-scene`) | Key `scene:<group>@<n>`, the item's split group; type `weksa.scene`: participants (speaker slugs) and, per ordered pair, relation features of slot `Scene` (relative status, intimacy, in-group, audience and whatever the loop adds), at an inventory revision, and an `Annotator` | As Speaker. Keyed by the group, so a scene never straddles the split | As Speaker |
|
||||
| Corpus item | Key `item:<source-slug>:<n>`, `n` canonical decimal >= 1 (no sign, no leading zero, from cut 2b); type `weksa.corpus_item` with text, language, speaker, split group, prior turns, source. Source `ModelWritten` carries a `ModelFamily` enum, the generator string as the fixture wrote it, and a prompt digest (cut 2b). The item carries no speaker state of its own: its speaker slug and group name the Speaker and Scene documents | Admitted once; the whole item is immutable (re-adding an identical item is a no-op, any difference is refused; a correction is a new item that `supersedes` the old); text already held under another key is refused unless the new item supersedes that key (cut 2b); withdrawn, never deleted, so old scores stay explainable | Importers and `weksa corpus add`, under `corpus-cast-plus-public-domain`; the source enum has no variant for Discord or any training-forbidden source (`corpus-clean`) |
|
||||
| Split assignment | Derived: `split(scheme, item.group)` | Fixed for a scheme; a new scheme is a new constant, never a reassignment. A model-written item whose group derives test is in no split; a superseding item keeps its predecessor's group | The hash function. Nobody assigns by hand, so there is no writer to forbid |
|
||||
| Loop round | Key `run:<label>:round:<n>`; type `weksa.loop_round` with spec version, profile revisions, model ids and prompt digests, sampled train items, Validation means and refusal counts (from cut `ja-panel-loop`: one set per language of the run's panel, no pooled mean), per-item Validation scores in corpus order (key 22, numbers only, no item key or text, private to `run.rs` for the paired floor of the cycle (rounds 1 to 4) and of relower; a run from before has none and opens), the digest of the inventory file it was scored under and, for a cycle's candidate round, its cycle `k` | Scored and recorded whole; immutable. A candidate round is put in one batch with its Decision. Lives in the run store on Yggdrasil | `run::round` and `run::cycle` (both through `score_round`) |
|
||||
| Loop decision | Key `run:<label>:cycle:<k>`; type `weksa.loop_decision` with the base round and revision, the edit prompt's digest and Train keys, the editor's answer digest, the candidate revision, inventory digest and round, the base, candidate and floor readings (chrF, meaning, composite; the floor is the paired floor of round 1 against rounds 2 to 4), the threshold and the verdict (Accepted, or Rejected for edit-parse, edit-admit, no-gain, regressed chrF, meaning or composite); digests and numbers, no text | Immutable. The latest Accepted one names the run's head inventory (`<root>/cycle-<k>/inventory.cc`, its candidate digest, its candidate round); with none the head is the copy `create` made at `<root>/inventory.cc`. Lives in the run store on Yggdrasil | `run::cycle`'s accept rule, `run::decide`: the validation composite gains more than max(noise floor, `LADDER_STEP`), no metric falls past max(its floor, one step), the composite does not fall past max(its floor, one step), and a non-finite reading rejects (the one regression test, `run::regression`); differences compared in billionths so a gain of exactly one step is a tie. From cut `ja-panel-loop` the readings, floor and threshold are kept per panel language and `run::regression` runs per language and is the one regression test (`decide` adds the gain test for a one-language panel): any language regressing rejects (verdicts `regressed-chrf`, `regressed-meaning`, `regressed-composite`), otherwise a one-language panel accepts as `decide` does and a panel of two or more accepts when the sum of composite deltas exceeds one `LADDER_STEP` (billionths). Given up: strict Pareto non-regression; a language may lose up to its own noise floor if the panel nets more than a step, because zero tolerance ratchets every base to a favourable noise draw and strangles the loop. Termination: each accept raises the composite sum by more than a step and composites lie in -0.5 to 1, so a run accepts at most 1.5 * languages / `LADDER_STEP` edits |
|
||||
| Loop round | Key `run:<label>:round:<n>`; type `weksa.loop_round` with spec version, profile revisions, model ids and prompt digests, sampled train items, Validation means and refusal counts, the digest of the inventory file it was scored under and, for a cycle's candidate round, its cycle `k` | Scored and recorded whole; immutable. A candidate round is put in one batch with its Decision. Lives in the run store on Yggdrasil | `run::round` and `run::cycle` (both through `score_round`) |
|
||||
| Loop decision | Key `run:<label>:cycle:<k>`; type `weksa.loop_decision` with the base round and revision, the edit prompt's digest and Train keys, the editor's answer digest, the candidate revision, inventory digest and round, the base, candidate and floor readings (chrF, meaning, composite), the threshold and the verdict (Accepted, or Rejected for edit-parse, edit-admit, no-gain, regressed chrF or meaning); digests and numbers, no text | Immutable. The latest Accepted one names the run's head inventory (`<root>/cycle-<k>/inventory.cc`, its candidate digest, its candidate round); with none the head is the copy `create` made at `<root>/inventory.cc`. Lives in the run store on Yggdrasil | `run::cycle`'s accept rule, `run::decide`: the validation composite gains more than max(noise floor, `LADDER_STEP`) and no metric falls past max(its floor, one step), differences compared in billionths so a gain of exactly one step is a tie |
|
||||
| Score | Key `<lowering-key>:<metric>@<metric-version>`; type `weksa.score` | Immutable; a new metric version scores again under a new key | The scorer, deterministic given the metric version and the embedder's model id. Cut `scorer` computes scores as values; cut `golf-loop-en` stores them, because the lowering keys they hang from arrive with the loop. Lands with follow-up `golf-loop-score-docs`, in the round's directory; nothing in the cycle reads them |
|
||||
| Lowering trace | Key `lowering:<packet-key>:<profile>@<rev>:<lowerer-digest>:<sample>`; type `weksa.lowering` holding the surface text and its trace together | Immutable. A surface text cannot exist without its trace, because they are one record (`lowering-traced`) | The lowerer emits; the lowerer sees the packet without its `trace` (the input type has no such field), never the corpus item |
|
||||
| Conlang lexicon entry | Key `lex:<language>:<concept-id>`; root form, morphology class | Root placed at its concept's embedding when the concept first needs a form in that language; stable once accepted; diachrony derives later forms, it does not overwrite | The language project's owner: the operator for her settings' languages, the loop proposing roots for her review |
|
||||
|
|
@ -134,7 +134,7 @@ standing.** `gamecult.persona_state.v0` (Body facts) carries open trait maps
|
|||
So a `PersonaSnapshot` projects mood-like and relation-like values, and the
|
||||
stable axes the standard lacks are annotated. Whether the standard gains a
|
||||
typed speech-community reference or Weksa keeps the persona-to-community
|
||||
binding (the deleted `data/cultural-ontology/persona-stacks/brokkr.yaml` was its one draft) is question `persona-speech-community-home` (recommended: a Weksa-owned
|
||||
binding (`data/cultural-ontology/persona-stacks/`) is question `persona-speech-community-home` (recommended: a Weksa-owned
|
||||
binding; follow-up `persona-state-speech-community`), decided when
|
||||
`live-lowering` is mapped; the
|
||||
corpus path needs neither. Putting Weksa feature ids into the open
|
||||
|
|
@ -309,27 +309,6 @@ line two", "その 制御" against the
|
|||
or socioeconomic standing; `extensions` are non-authoritative by the
|
||||
schema's own description.
|
||||
|
||||
- Probes of 2026-11-12 at `d9ebbcf` (map pass for cut 5): no code reads
|
||||
`data/target-language-ontology/`, `data/cultural-ontology/` (since deleted) or
|
||||
`.weksa/cultural-ontology/starter-targets.cc` (a third, typed copy of en,
|
||||
ja-JP and pt-BR profiles); `README.md`, `docs/multilingual-utterance-lowering.md`,
|
||||
`examples/cultcache-lowering/` and `prompts/nibu-cultcache-target-*.md` cite
|
||||
them. `LoweringInput::with_scene` has no caller in `run.rs` or `main.rs`, the
|
||||
run pins no `SpeakerStateStore`, and no Speaker or Scene document is committed
|
||||
(`speaker-scene-seeds` open), so only the packet's `Stance` and `Discourse`
|
||||
features reach a loop's lowering view. `score::leak_diagnostic` and
|
||||
`TestReadings::at_checkpoint` take minted text as `&[&str]` and have no
|
||||
caller outside tests: no round reads glosses or any minted text against
|
||||
Validation. `data/daodejing/inventory.cc` is a revision prefix of
|
||||
`data/original/inventory.cc` (revisions 1 to 4 equal, a test proves it; revs 5 and 6 add the bed's own lexicon); with `data/interlingua/inventory.cc` they share revision 1,
|
||||
where features 6 to 8 (hedge, certainty grades, irony flag) sit in
|
||||
`Discourse` and `Predication` and features 9 to 18 (anger to restraint,
|
||||
grades) in `Stance`. `PROMPT_SOURCE_DIGEST` covers `context.rs`, `split.rs`,
|
||||
`lower.rs` and `packet.rs`. 25 `RunPaths {` literals across `run.rs`,
|
||||
`context.rs` doctests, `main.rs`, `tests/common/mod.rs`, `tests/golf_loop.rs`
|
||||
and `tests/original_corpus.rs`; 10 `Prompt::lower(` calls. `huginn known`
|
||||
timed out (Unavailable, 15 s deadline) twice this pass.
|
||||
|
||||
## Where things live and run (`rust-single-crate`, `loop-runs-on-yggdrasil`)
|
||||
|
||||
- Code: one Cargo workspace at the repo root, one package `crates/weksa` (a
|
||||
|
|
@ -340,14 +319,9 @@ line two", "その 制御" against the
|
|||
- Stores: `data/interlingua/inventory.cc` and `data/corpus/corpus.cc` in the
|
||||
repo (small, reviewed with `weksa dump`); run stores (rounds, lowerings,
|
||||
scores) on Yggdrasil under the loop's state root, not in git.
|
||||
- The loop is a batch command driven from a Claude Code session on Yggdrasil
|
||||
(`golf-loop-in-claude`), not a detached unit. Model calls go through a
|
||||
`ModelPort` whose one adapter, `AnswerFiles`, writes a `.prompt` file and reads
|
||||
a `.answer` file: Claude agents answer them, one fresh subagent per encode
|
||||
prompt (`encoder-isolation-subagent-per-prompt`) and a tool-less relay for
|
||||
lowering prompts (`lowerer-call-reach-toolless-relay`). Builds, stores, scoring
|
||||
and embeddings run on Yggdrasil; Starfire runs none of it, and Weksa needs no
|
||||
claude binary or token there. Never OpenAI
|
||||
- The loop runs on Yggdrasil as a detached unit with a log and a status record.
|
||||
Starfire runs none of it. Model calls go through a `ModelPort`; its first
|
||||
adapter drives `claude -p` on the operator's subscription. Never OpenAI
|
||||
(`eureka-body:ruling:no-return-to-openai-supplier`), never Discord data
|
||||
(`gamecult-chat:ruling:discord-taints-training`).
|
||||
|
||||
|
|
@ -360,252 +334,6 @@ checkpoint the test-split composite is within the noise floor of validation.
|
|||
The test split is read only at checkpoints. Self then records the freeze, and
|
||||
the training set is the whole corpus re-encoded under the frozen revision.
|
||||
|
||||
## Distil measure (`distil-slice`)
|
||||
|
||||
A lowerer is compared on round n's Validation packets with the prompts
|
||||
byte-identical to the round's, by `weksa loop relower ROOT --round N --arm ARM
|
||||
--lowerer LABEL [--floor ARM2 --floor ARM3 --floor ARM4]`. Every arm is answered through the one prompt
|
||||
door (`RunStores::answer_files`, the Test-text guard); a tuned model is a script
|
||||
that reads `<digest>.prompt` and writes `<digest>.answer` in
|
||||
`<ROOT>/relower-<N>-<ARM>`, not a new adapter. The recorded reading is the
|
||||
round's own lowering, read over the same items as the arm. An item the round
|
||||
refused before admission (no packet) or at the lowering prompt has no prompt to
|
||||
ask: it is skipped, so the readings exclude it, and it is counted as `skipped=`
|
||||
on the line; `n` is the items read, so `recorded` can differ from the round's
|
||||
own Validation reading, which scores those items 0. An arm answer that is not a
|
||||
usable lowering scores 0 and counts in `unusable=`; the same for the floor arm,
|
||||
counted (over all floor arms) after `floor ... unusable=`. The floor needs three
|
||||
or more floor arms, each a prompted repeat of the recorded lowering on the same
|
||||
prompts: it is `FLOOR_Z` (3) standard errors of the mean per-item difference
|
||||
between the recorded lowering and a repeat, per metric, with the variances
|
||||
pooled over the arms (`paired_floor`; lowering-only noise, no encoder noise). The
|
||||
verdict is `decide_panel` over (recorded, arm, floor): Accepted is a composite
|
||||
gain past the noise of the panel's sum (the root of the languages' composite
|
||||
floors squared, at least one step), Rejected(Regressed) a loss past a language's
|
||||
floor, Rejected(NoGain) neither. The cycle's own floor is the same `paired_floor`
|
||||
(`floor_of`): round 1 (the recorded lowering, the head's establishing round)
|
||||
against rounds 2 to `FLOOR_ARMS_MIN` + 1 (prompted repeats under the run's first
|
||||
inventory), per panel language, from the rounds' per-item Validation scores. It
|
||||
is measured once per run and is the same after an accept; a run needs four
|
||||
`loop round` calls before its first `loop cycle`.
|
||||
Calibration (`runs/distil-base`, 8 prompted draws by one model family on
|
||||
identical prompts, no draw sharing more than 7 of 28 answers with another; 14
|
||||
en-US and 14 ja-JP Validation items; every base, candidate and 3-arm floor
|
||||
combination, 1120 trials from 28 unordered pairs; intervals bootstrap over
|
||||
draws, each degraded arm one fixed draw): a prompted repeat reads NoGain 92%
|
||||
(80 to 100), Regressed 8% (0 to 20), Accepted 0%, which with 28 pairs bounds
|
||||
false-accept only to about 10%; an all-"Yes." arm reads Regressed 100%; a mild
|
||||
degradation (one detail blurred per utterance) 100%; a subtler one 75% (50 to
|
||||
100), whose mean composite drop (0.044) sits under the mean floor (0.060).
|
||||
`FLOOR_Z` was chosen on this data (2.5 gives NoGain 84% and 93% on the subtler
|
||||
arm), so the rates are in-sample. Without the noise term in the gain test a
|
||||
prompted repeat reads Accepted in 40% of the trials.
|
||||
Power (can the rule Accept a real gain?): the only better arm that could be
|
||||
built without Test or Validation answers is a lowerer shown the Train sentences
|
||||
of the corpus (no packets, no Validation or Test text) as a register guide.
|
||||
Four such draws beat the prompted draws' mean composite in both languages (en-US
|
||||
0.742 to 0.759 to 0.795; ja-JP 0.559 to 0.578 to 0.620), so the premise that it is
|
||||
better is measured on the very Validation items the rule reads, not independent.
|
||||
Against the prompted bases with 3-arm floors the rule reads it Accepted in 29%
|
||||
of 1120 trials, NoGain 71%, Regressed 0%: a net gain of 0.079 against a mean
|
||||
noise term of 0.079. At 14 items per language the rule is therefore a low-power
|
||||
filter for a gain of this size; by 1/sqrt(n), about 35 or more items per
|
||||
language would bring the noise term near 0.05 (an extrapolation, not measured).
|
||||
### Validation growth (`validation-growth`, built and recalibrated)
|
||||
|
||||
Power needs about 35 or more Validation items per language. `data/original`
|
||||
now holds 35 per language (it held 14; Train 14 and Test 8 are unchanged):
|
||||
42 model-written items, `item:vgrow:1..21` (en-US) and `item:vgrow-ja:1..21`
|
||||
(ja-JP), live Train+Validation 56 to 98. The slug is new on purpose: the
|
||||
`item:original:` prefix filter of `DIGEST_OF_THE_28` still selects the first 28
|
||||
and passes; `DIGEST_OF_THE_42` freezes the new prose.
|
||||
|
||||
The split is derived from an item's group alone (`SplitScheme::V1`: FNV-1a of
|
||||
`weksa-split-v1:<group>` mod 100, under 40 Train, under 80 Validation, else
|
||||
Test). The names were chosen before any text existed: 90 candidate nouns per
|
||||
language, dropped by script when the group already existed or the noun
|
||||
occurred in a Test text, then the first 24 whose bucket fell in 40..=79 (the
|
||||
bucket came from `SplitScheme::V1` itself, cross-checked on the 72 existing
|
||||
items). Each language was written by three blind writer agents (8 nouns each,
|
||||
a brief of language, register note, noun and speech act, no Test text and no
|
||||
existing item), 24 texts per language written, the first 21 in name order
|
||||
admitted through `weksa corpus add`; each group is its own group. The scenes
|
||||
are `weksa scene put` documents (keeper to `unnamed`, inventory rev 4),
|
||||
annotated by a separate agent; a second annotator measured agreement only and
|
||||
is not committed.
|
||||
|
||||
The writer is Claude (family Anthropic recorded): no cross-family generator was
|
||||
reachable from the body that ran this cut. The self-preference effect (a Claude
|
||||
lowerer favouring Claude prose, Panickssery et al. 2024) is therefore not
|
||||
measured. The writers' blindness is by brief content, not sandbox.
|
||||
|
||||
Expect encode refusals: the existing 56 were written onto the Dao r3 concepts
|
||||
and the inventory was drafted from them, while the new items were written free
|
||||
of the inventory (question `validation-growth-vocabulary` stays open). Some new
|
||||
packets will be refused at encode (inventory coverage) and score 0 as the means
|
||||
do; they stay in the corpus. That is a result about inventory generalization,
|
||||
not a defect.
|
||||
|
||||
Every calibration number in the Distil measure section above (92/0/8 prompted
|
||||
rates, the 29% power, the 0.079 noise term) is for the 14-item corpus and stays
|
||||
the stated baseline of that corpus.
|
||||
|
||||
Recalibration on the grown corpus (`runs/growth-base`, main 44b66f9, panel
|
||||
en-US and ja-JP, round 1 recorded by briefed subagents; 6 prompted draws
|
||||
including the recorded one, 2 mild degradations, an all-"Yes." control and 4
|
||||
Train-guide draws by Claude sonnet-5-5; the same decision rule at FLOOR_Z 3 and
|
||||
3-arm floors; 120 prompted trials from the 30 ordered pairs of 6 draws with the
|
||||
other 4 as floor candidates, so trials share draws and are not independent).
|
||||
Soul pass `cut-validation-growth.s3` re-derived every number below; its
|
||||
findings shaped the wording.
|
||||
|
||||
- Live Validation items: 28 en-US and 32 ja-JP of 35 each; 10 are refused at
|
||||
parse (en-US original:18, 23, 25, 27 and vgrow:4, 5, 6; ja-JP original-ja:17,
|
||||
22 and vgrow-ja:2); `relower` skips an item with no packet, so every reading
|
||||
here is over live items only. Old 14: 10 en-US and 12 ja-JP live; new 21: 18
|
||||
and 20.
|
||||
- Prompted repeat: NoGain 96.7%, Accepted 3.3%, Regressed 0% (14 items: 92 / 0 /
|
||||
8). All four false accepts are one pair, base p6 and candidate the recorded
|
||||
lowering R: R comes from the round, the other five draws from `relower`, and
|
||||
in en-US R scores +0.024 per item above them [+0.002, +0.052], so R is not
|
||||
exchangeable with a repeat (a Plausible Soul finding, cause not isolated). No
|
||||
false-accept bound can be drawn from 6 draws.
|
||||
- Degraded arms read Regressed: all-"Yes." 100% (as before); mild-1 31.7%;
|
||||
mild-2 0% (14 items: 100% and 75% on a subtler arm). The mild arms are weak
|
||||
and not independent: they were rewritten from R with one detail blurred, the
|
||||
original wording is not on disk, mild-2 equals R word for word in 5 of 60
|
||||
items and mild-1 in 2, and mild-1 equals mild-2 in 27 of 60 although they
|
||||
were asked to blur different details. Their mean composite is 0.003 to 0.015
|
||||
below the prompted mean (the old subtler arm: 0.037 and 0.052). The
|
||||
sensitivity to a small regression is not re-measured.
|
||||
- Noise: the panel noise term of the sum rule is 0.045 on average over the base
|
||||
and floor choices (0.031 to 0.064), against 0.079 at 14 items. The 1/sqrt(n)
|
||||
forecast (about 0.05) assumed per-item variance stayed the same; it did not:
|
||||
the per-item SD of the difference between two prompted draws is about 0.085
|
||||
on the old items and 0.034 on the new ones, so the pooled term landed near
|
||||
the forecast because less variable items were added. Not a confirmation of
|
||||
the forecast.
|
||||
- Power: the Train-guide arm (14 Train sentences as a register guide) is
|
||||
Accepted in 21.2% of 240 trials, NoGain 78.8%, against 29% at 14 items, and
|
||||
its mean composite gain over the prompted draws is 0.0185, 0.41 of the mean
|
||||
noise term (0.37 on the first floor choice per base); with `relower`-only
|
||||
bases (R removed) it is Accepted in 35% (28 of 80). Split by item class
|
||||
(paired bootstrap over items, 95%): old items +0.029 [+0.005, +0.052] (en-US
|
||||
+0.049 [+0.023, +0.084] on 10 items, ja-JP +0.013 [-0.021, +0.037] on 12);
|
||||
new items -0.002 [-0.011, +0.007] pooled, but two opposite effects: en-US
|
||||
-0.017 [-0.027, -0.007] on 18 items and ja-JP +0.011 [+0.001, +0.022] on 20.
|
||||
So the old-versus-new contrast exists in en-US; in ja-JP old (+0.013) and new
|
||||
(+0.011) do not differ. Measured: the 14-item gain does not carry to the new
|
||||
en-US items. Inferred, not isolated: that it was in-sample register fit. The
|
||||
new items differ from the old in several ways at once (written free of the
|
||||
inventory, longer, a different scene convention, lower scores, a smaller
|
||||
vocabulary overlap with Train in en-US: 0.29 against 0.52) and were briefed to
|
||||
the same register as Train, by Claude as the old were. The 29% power figure
|
||||
stays the stated baseline of the 14-item corpus; no better arm is known on
|
||||
the new items, so the rule's power against a real gain is not re-measured.
|
||||
- The two classes are different strata (Soul s2 `register-stratum-shift`): the
|
||||
new items score lower (composite 0.41 against 0.64 pooled) so a pooled
|
||||
60-item mean mixes them; report old and new separately.
|
||||
- The self-preference effect is not measured (ruling
|
||||
`validation-growth-writer-claude-checked`). The new scenes use a different
|
||||
`in_group` convention from the old ones (follow-up
|
||||
`vgrow-scene-in-group-convention`), so the new-item scores are for scenes that
|
||||
will be re-annotated; the speaker-state store changes then (a run pins its
|
||||
digest), the corpus does not.
|
||||
|
||||
For `growth-base`, `weksa loop calibrate` (`docs/calibration.md`) reproduces from `run.rs`'s own
|
||||
scoring and accept rule the counts per class, the trial totals and the mean
|
||||
noise of this block: prompted 116 NoGain, 4 Accepted, 0 Regressed of 120;
|
||||
control-yes 60 of 60 Regressed, mild-1 19 of 60, mild-2 0 of 60; the
|
||||
Train-guide arm 51 Accepted, 189 NoGain, 0 Regressed of 240; noise 0.0451;
|
||||
items en-US n=28 skipped=7, ja-JP n=32 skipped=3. By class it adds: old items
|
||||
(`item:original*`) prompted 111/9/0, noise 0.1069, Train-guide 71 Accepted of
|
||||
240; new items (`item:vgrow*`) prompted 116/4/0, noise 0.0334, Train-guide 0
|
||||
Accepted and 74 Regressed of 240. The other figures of this block (35% with R
|
||||
removed, the noise range, the 0.0185 gain and 0.41 ratio, the bootstrap
|
||||
intervals, the per-item SDs, R's +0.024, the mild-arm duplicate counts and
|
||||
mean composite offsets, the Train-vocabulary overlap, the old/new class
|
||||
composites, the ten parse-refused item ids) were
|
||||
computed by scratch scripts outside git (Soul finding `evidence-outside-git`)
|
||||
and are not reproduced by the harness.
|
||||
|
||||
Recalibration on the relabelled scenes (`runs/growth-scene`, main d8afc4a; same
|
||||
panel, 35 live items per language, 0 refused, 5 prompted draws including the
|
||||
recorded one R, 2 mild, 4 Train-guide). It is not a replacement for the
|
||||
`growth-base` block above and no delta against it is drawn: the item set, the
|
||||
packets and the scenes changed, and encode was redrawn (the 98 encode prompts
|
||||
are byte-identical to growth-base, no encode answer is; the refusals fell from
|
||||
10 to 0 on the redraw, not through the scenes, which reach only the lowering
|
||||
prompts). Soul `cut-calibrate-harness.s3` re-derived all 33 counts and 3 noise
|
||||
terms below from the per-item answers without calling `calibrate`; they match.
|
||||
|
||||
Measured, and reproduced by `weksa loop calibrate` (trials: prompted 120, each
|
||||
mild 60, Train-guide 240; Accepted / NoGain / Regressed):
|
||||
|
||||
| class | prompted | noise | mild-1 Regressed | mild-2 Regressed | Train-guide |
|
||||
|---|---|---|---|---|---|
|
||||
| all (35 per language) | 11/100/9 | 0.0392 | 51 | 58 | 85/35/120 |
|
||||
| old (14) | 0/105/15 | 0.0844 | 60 | 60 | 40/80/120 |
|
||||
| new (21) | 10/97/13 | 0.0340 | 3 | 4 | 50/129/61 |
|
||||
|
||||
Measured by Soul scratch scripts outside git (not reproduced by the harness,
|
||||
except the R split in the first bullet, which `calibrate` prints as
|
||||
`prompted-r-candidate`, `prompted-r-base` and `prompted-r-free` since the
|
||||
`calibrate-report-r-involvement` cut; Soul re-ran growth-scene with it and the
|
||||
printed `all` lines read r-candidate 11/9/0, r-base 0/11/9, r-free 0/80/0, as
|
||||
below, in Accepted/NoGain/Regressed; likewise the per-arm Train-guide counts
|
||||
(`candidate=h1..h4`) and the mild arms' composite offsets from the prompted
|
||||
mean, R included (`offset`), which `calibrate` prints since
|
||||
`calibrate-arm-counts-and-mild-offsets` and which reproduce the figures below,
|
||||
Soul re-run on growth-scene):
|
||||
|
||||
- Every one of the 11 false accepts has R as the candidate (bases
|
||||
prompted-2, p4, p6); every one of the 9 false rejects has R as the base. The
|
||||
80 trials without R read 0 Accepted and 0 Regressed in every class (95% upper
|
||||
bound 4.5%). R scores above the other prompted draws (+0.012 en-US and +0.023
|
||||
ja-JP on all items), so R is not exchangeable with a repeat.
|
||||
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, so the R-candidate
|
||||
rate may be the real one for cycles, while the 80 R-free trials are the
|
||||
exchangeable repeat rate; neither number stands for the other.
|
||||
- The old/new split of the false-accept lives only in the 20 trials where R is
|
||||
the candidate, from 5 bases: new 10/20 [0.27, 0.73], old 0/20 [0.00, 0.17]
|
||||
(Clopper-Pearson); by base 3 of 5 against 0 of 5 (Fisher p 0.17). The
|
||||
10/120 against 0/120 comparison treats dependent trials as independent. The
|
||||
claim that the new items drive the prompted false-accept is not supported;
|
||||
the old items' larger noise term (2.4 times) raises their threshold, which
|
||||
alone can produce the gap.
|
||||
- Mild arms: they overlap 8 of 35 answers (en-US) and 9 (ja-JP) over the limit
|
||||
of 7. They do not degrade the new items (composite -0.004 en-US
|
||||
[-0.021, +0.012], +0.013 ja-JP for mild-1, +0.005 for mild-2); the Regressed counts come from the old
|
||||
en-US items (-0.072). The rule's sensitivity on the new items is unmeasured.
|
||||
- Train-guide pools unlike arms. h1 and h2 Regress in 120 of 120 trials; h3 and
|
||||
h4 gain (Accepted 45 and 40 of 60); on the new items h3 is Accepted 50 of 60
|
||||
and h4 0 of 60. The 35% pooled figure is not a power.
|
||||
|
||||
Extrapolated only: the rule's power at 35 items against any real gain beyond
|
||||
h3 and h4, and any false-accept bound on repeat draws (5 draws, one of them R).
|
||||
|
||||
### Smallest measurable distil slice (`distil-incontext`, not built)
|
||||
|
||||
Distil is a tuned lowerer measured against the prompted one; the tuned model
|
||||
needs a host (follow-up `distil-host-question-owed`). The smallest slice that
|
||||
measures whether Train pairs buy a gain with the rule that exists is
|
||||
training-free: an in-context arm, the prompted lowerer given Train
|
||||
(packet, text) pairs as few-shot examples, answered through the one prompt door
|
||||
and read by `loop relower` against three prompted repeats. Parts: 12b's
|
||||
Train-only export (follow-up `distil-export-at-freeze`, guarded against Test
|
||||
text) as the few-shot source; the arm's directory of answers; the existing
|
||||
floor and verdict. A weaker version ran on 14 items: a lowerer shown the 28
|
||||
Train sentences (no packets) beat the prompted draws in both languages and the
|
||||
rule Accepted it in 29% of 1120 trials. The slice is decisive only with the
|
||||
Validation growth above: at 14 items it can only fail to reject. It decides the
|
||||
fine-tune question in one direction: if in-context Train pairs do not clear the
|
||||
floor at 35 items, a tuned model's gain over the prompted one is not
|
||||
measurable with this corpus either.
|
||||
|
||||
Training pairs are Train only, at a frozen revision; the export is 12b.
|
||||
|
||||
## Lowerer first cut (`golf-loop-lowerer-cut`)
|
||||
|
||||
Authority map for the smallest lowerer, written before its code (Imagination
|
||||
|
|
@ -675,18 +403,16 @@ One line per cut; specs exist for the cuts about to run (2d and 4, siblings on `
|
|||
4. `speaker-state`: packet `stance` (felt affect and restraint, slot `Stance`, packet schema v4); formality, warmth and intensity out of the seed and the standard; only `PacketStore::admit` yields a `LoweringInput`, and it refuses packets for withdrawn items (follow-up `lowering-input-from-packet-store`). (spec r1)
|
||||
4a. `speaker-relation-input`: slot `Scene` and its first seed features (`relative_status`, `intimacy`, `in_group`; inventory revision 3, now `speaker_scene_revision`); `LoweringInput::with_scene` carries the speaker's relation to the addressee as typed `Scene` feature values. Since 4b it takes the `SpeakerStateStore` and the `CorpusStore`, reads the scene of the view's own item group for the item's speaker, and selects the relation by the addressee referent's entity (V16 when the scene does not list the item's speaker or the speaker of any live item of the group, the rule `put_scene` applies too; V17 refuses an addressee that names a predication; V13 is retired). The English lowerer does not render it. (PR for follow-up `chat-s3352-3352`)
|
||||
4b. `speaker-scene` (spec r1; `speaker-scene-seeds` is its cut 4c: CLI, inventory revision 3, cast speakers and scenes; `Party::Unnamed` covers an addressee with no entity; Speaker and Scene share one `SpeakerStateStore`): slots `Speaker` and `Scene` with their seed features; `weksa.speaker` (`speaker:<entity-slug>@<n>`) and `weksa.scene` (`scene:<group>@<n>`, participants and ordered-pair relations) documents with `Annotator` `Operator` and `Model { family, generator }`, validated by the packet's shared feature check, append-only per key; their stores, `weksa speaker` and `weksa scene` commands, published schemas; Model-annotated cast speakers and scenes for the committed items. Waits on 2d and 4; `pd-speaker-annotation` blocks only the public-domain annotator. Part 1 landed (branch `weksa-lowering/speaker-scene`): `speaker.rs`, `SpeakerStateStore`, slots `Speaker` and `Scene` exclusive to their own feature lists, `speaker_scene_revision()` (Speaker features 22-24), `with_scene` on the store, schemas. The CLI, the committed inventory revision 3 and the seeds stay with 4c.
|
||||
5. `language-ontology`, in sequential cuts on `d9ebbcf`. 5a `language-ontology` (spec r1): `weksa.ontology_entry`, `OntologyStore`, `ontology::select` over the view's `Stance` and `Discourse` features, `Prompt::lower` printing the selected entries of the item's language, `RunRecord` pinning the ontology store (keys 15 and 16), `weksa ontology admit|dump`; `ontology.rs` joins `PROMPT_SOURCE_DIGEST`. 5b `language-ontology-seed` (spec r1, after 5a): Model-annotated en-US and ja-JP seed entries drafted by an isolated model, `data/target-language-ontology/`, `.weksa/cultural-ontology/` and `schemas/target-language-cultural-ontology.md` deleted. Lost until 5c': keigo, hierarchy and uchi-soto hang on the scene relation from 5c', so ja-JP politeness is still the lowerer's guess. 5c' `language-ontology-scene` (spec r1, after 5b): the run pins the `SpeakerStateStore` (keys 17 and 18, `Drift(SpeakerState)`), `RunStores::assembled` is the one door that reads the item's scene into a loop view, `select` reads slot `Scene`, `Prompt::lower` refuses a view whose scene was never read, `weksa scene put|dump` and `weksa inventory speaker-scene` (rev 4 in data/original and data/daodejing, rev 3 in data/interlingua, which holds no Dao revision), Model-annotated keeper scenes and Scene-conditioned entries for `data/original`. 5c `language-ontology-view-assembly` (follow-up, now only the Speaker read): `select` widens to slot `Speaker`; waits on `speaker-scene-seeds`. 5d `language-ontology-communities` (follow-up): `weksa.community` built fresh (`data/cultural-ontology/` is deleted by 5e), community ids on `weksa.speaker`, community conditions; waits on 5c and question `persona-speech-community-home`.
|
||||
5e. `delete-cultural-ontology` (steward ruling, 2026-11-13): `data/cultural-ontology/` (five draft YAML profile files and a README; `old-norse-edda-source-tradition.yaml` did not parse) deleted. Nothing in `crates/`, tests, scripts or CI read it; `examples/persona-lowering/brokkr-edda-voice/` cites its paths as text only (the one test that reads that example reads `lowered-output.yaml`). The typed `weksa.community` of follow-up `language-ontology-communities` is built fresh under cut 5; follow-up `edda-referent-yaml-parse` is moot.
|
||||
5. `language-ontology`: `weksa.community` from `data/cultural-ontology/` (owns follow-up `edda-referent-yaml-parse`), `weksa.ontology_entry` for en-US and ja-JP from `data/target-language-ontology/` (YAML deleted), speaker communities, deterministic `select`, the lowering view (packet without trace, speaker, scene, selected entries). Waits on 4.
|
||||
6. `pd-importer`: public-domain play and fiction dialogue into the corpus with speaker, scene group, edition provenance, and Speaker and Scene annotations by the ruled annotator. Waits on 4, follow-up `gutenberg-terms` and question `pd-speaker-annotation`.
|
||||
6a. `pd-name-spans` (spec r1): `weksa corpus import <work> <names>` mints a work's cast as `PublicDomain` entities with forms in the work's language and adds each line a name-span answer covers, speaker from the work file, spans from `[[entity|form]]` markup, labelled `names_by` (Model or Operator) per `docs/name-span-annotation.md`. Speaker and Scene documents, prior turns and fiction speaker attribution stay with 6.
|
||||
7a. `loop-context-builder`: `context.rs` (`TrainItems`, `EncoderOffer`, `Prompt`: corpus text reaches a model call only through `Prompt::mint` over live Train items or `Prompt::encode` over one offered item; instructions are the consts `MINT_INSTRUCTIONS` and `ENCODE_INSTRUCTIONS` in `context.rs`; `Checkpoint` has no public constructor, offers each item once, and its offers borrow it (the gate is typed `TestReadings` and Test offers on the round path; operator tools such as `weksa corpus dump` and `weksa score` still read corpus text of any split); prior turns print the held Train text), `SplitScheme::live`, `CorpusItem::cited_entities` (one owner of the id set `PacketStore::admit` and the offer share), and checkpoint-only Test readings (`Checkpoint`, `TestReadings`; `Aggregate` and `leak_diagnostic` carry no Test). Library only; since 7b `TrainItems::from_corpus` and `EncoderOffer::for_round` are crate-private and `RunStores` is their one public producer. Merges follow-ups `loop-context-builder-2` and `scorer-test-readings-type`. (spec r1)
|
||||
7b. `golf-loop-round` (spec r1; branch `weksa-lowering/golf-loop-round`): the smallest loop that scores one round. `run.rs`: `RunStores` pins the corpus and entity stores of a run by canonical path and FNV-1a 64 digest at `create`, reopens only from `<root>/run.cc` and refuses drift (corpus, entities, `PROMPT_SOURCE_DIGEST` of `context.rs`, a second pin on `lower.rs` retired in 7d, model, embedder); `round` encodes every live Train and Validation item through a `ModelPort` (`model.rs`; the one adapter `AnswerFiles` writes `<digest>.prompt` and reads `<digest>.answer`, so the model is the Claude session), reads each answer into a `PacketDraft` (`encode.rs`, the one place a model's JSON is read), admits through `PacketStore::admit` into `<root>/round-<n>/packets.cc`, lowers, scores once, and keeps a `RoundRecord` (`weksa.loop_round`, no text, no Test; Train rows, Validation only as means and refusal counts). `weksa loop open|round`. Not here: the spec-edit step, accept rule and composite, noise floor, Score and lowering documents, a subprocess adapter, the checkpoint door, a model lowerer (follow-ups `golf-loop-spec-edit`, `golf-loop-accept-rule`, `golf-loop-score-documents`, `golf-loop-subprocess-adapter`, `golf-loop-checkpoint-door-bound`, `golf-loop-model-lowerer`). `packet-store-inventory-binding` is met for loop packets only (`RunStores` admits with the run's inventory); `validate`, `packet proof|dao` and `lower` still take caller stores. Waits on 7a, `checkpoint-gate`, 4b.
|
||||
7c. `golf-loop-edit-accept` (spec r1; branch `weksa-lowering/golf-loop-edit-accept`): one edit-accept cycle. The run works on its own copy of the inventory (`create` copies the caller's file to `<root>/inventory.cc`, refusing a root that already holds a file of that name, and pins its digest as `RunRecord` key 11; `RunRecord.inventory` is provenance; a `run.cc` from before has no key 11 and does not open); the head is derived from the latest Accepted `Decision`. `weksa loop cycle` asks the editor for one inventory edit from `Prompt::mint(train, inventory, rev, feedback)` (Train blocks, the inventory listing and an `EditFeedback` line: whether the last edit was kept and the head's Validation composite rounded to `LADDER_STEP`, the Ladder release of Blum and Hardt 2015), reads it as an `EditDraft` (`encode.rs`; ids and revisions are the store's, `into_revision`), admits it through `InventoryStore::admit_revision` into `<root>/cycle-<k>/inventory.cc`, runs a candidate round under it, and `decide`s on Validation against the head's establishing round past a floor (never under one `LADDER_STEP`; from cut `cycle-floor-paired` the paired floor over rounds 1 to `FLOOR_ARMS_MIN` + 1, so a cycle needs four recorded rounds, where 7c measured the spread between rounds 1 and 2). An edit that fails is a rejected `Decision`, not an error. `RoundRecord` gains keys 16 (inventory digest) and 17 (cycle); an encode answer that is not UTF-8 is that item's parse refusal. Not here: Score and lowering documents (`golf-loop-score-docs`), Train rows in the edit prompt (`golf-loop-edit-train-feedback`), a paired floor (`golf-loop-paired-floor`), the checkpoint door and merging to `data/` (`golf-loop-checkpoint-door-bound`, `golf-loop-freeze-merge`), a model lowerer (landed as 7d: until then an entry an edit added had no lowering row). Waits on 7b.
|
||||
7d. `golf-loop-model-lowerer` (spec r1; branch `weksa-lowering/golf-loop-model-lowerer`): the round lowers through the `ModelPort`. `Prompt::lower` (`context.rs`) takes a `LoweringInput` (no text, key, group or speaker getter), the item's speaker id, the inventory at the view's revision and the item language's entity forms, and prints `LOWER_INSTRUCTIONS`, the meaning of the packet, the entities line and the inventory listing; the item key goes only to `item_keys`, and the speaker id never prints: a referent citing the item's speaker holds the fixed token `entity:speaker` (`SPEAKER_TOKEN`, a constant the same for every speaker and item, never derived from an id) and the entities map holds the speaker's forms under that token. The promise guards the id that names an entity of this item; the speaker's forms and the role token do print, because forms are shared by every item of the language (follow-up `speaker-alias-token-in-lowering-prompt`, which restored the lowerer's ability to name its speaker after #84 removed it). A speaker the language has no form for, or the port lacks, does not refuse: its referents print no entity and the map has no entry. A referent citing the real id `entity:speaker` is refused (`LowerError::SpeakerTokenTaken`); the entity store does not reserve it. The answer is `{"text"}`, read as `LoweringDraft` in `encode.rs`, held in `score_round`'s locals and scored once; it is never put in `run.cc`, a `RoundRecord`, a `Decision` or `EditFeedback`. A round has two answer phases (every encode prompt, then every lowering prompt), all or nothing: while any prompt is unanswered `packets.cc` is discarded and nothing reaches `run.cc`. `lower::lower` and the template table leave the loop (they remain `weksa lower`'s; follow-up `table-retirement`), so an entry an edit adds can be said and a cycle can buy a gain. One source pin remains: `PROMPT_SOURCE_DIGEST` covers `context.rs`, `split.rs` and `lower.rs` (`RunRecord` key 7 and `RoundRecord` key 3 are retired). The run's record pins `LowererReach` (`weksa loop open --lowerer-reach briefed-subagent|tool-less-relay`, `RunRecord` key 12) and every printed round and cycle line says it; a briefed-subagent run says its numbers are smoke-round only (rulings `lowerer-call-reach-toolless-relay`, `dao-round-seed-inventory`). A lowering is refused at `Lower` when blank, over `MAX_LOWERING_BYTES` (4096) or holding a control character other than a line break or tab; `PROMPT_SOURCE_DIGEST` also covers `packet.rs`. Not here: per-item lowering text documents (`golf-loop-score-docs`), the subprocess adapter. Waits on 7c.
|
||||
7. `golf-loop-en` (7b, 7c and 7d landed the round, `ModelPort` with `AnswerFiles`, encoder and lowering prompts, template digest, round records and the edit-accept cycle; the rest remains): the packet store bound to one inventory store everywhere (`packet-store-inventory-binding`), Score documents (`golf-loop-score-docs`, `golf-loop-score-documents`), the accept rule (`golf-loop-accept-rule`), the checkpoint door and freeze merge (`golf-loop-checkpoint-door-bound`, `golf-loop-freeze-merge`). No subprocess adapter and no detached unit: `golf-loop-in-claude` and `encoder-isolation-subagent-per-prompt` rule them out. Waits on 3, 5 and 6.
|
||||
7c. `golf-loop-edit-accept` (spec r1; branch `weksa-lowering/golf-loop-edit-accept`): one edit-accept cycle. The run works on its own copy of the inventory (`create` copies the caller's file to `<root>/inventory.cc`, refusing a root that already holds a file of that name, and pins its digest as `RunRecord` key 11; `RunRecord.inventory` is provenance; a `run.cc` from before has no key 11 and does not open); the head is derived from the latest Accepted `Decision`. `weksa loop cycle` asks the editor for one inventory edit from `Prompt::mint(train, inventory, rev, feedback)` (Train blocks, the inventory listing and an `EditFeedback` line: whether the last edit was kept and the head's Validation composite rounded to `LADDER_STEP`, the Ladder release of Blum and Hardt 2015), reads it as an `EditDraft` (`encode.rs`; ids and revisions are the store's, `into_revision`), admits it through `InventoryStore::admit_revision` into `<root>/cycle-<k>/inventory.cc`, runs a candidate round under it, and `decide`s on Validation against the head's establishing round past a floor measured as the spread between rounds 1 and 2 (never under one `LADDER_STEP`). An edit that fails is a rejected `Decision`, not an error. `RoundRecord` gains keys 16 (inventory digest) and 17 (cycle); an encode answer that is not UTF-8 is that item's parse refusal. Not here: Score and lowering documents (`golf-loop-score-docs`), Train rows in the edit prompt (`golf-loop-edit-train-feedback`), a paired floor (`golf-loop-paired-floor`), the checkpoint door and merging to `data/` (`golf-loop-checkpoint-door-bound`, `golf-loop-freeze-merge`), a model lowerer (`golf-loop-model-lowerer-next`; until it lands an entry an edit adds has no lowering row, so a cycle gains only by retiring entries or adding ones the encoder does not cite). Waits on 7b.
|
||||
7d. `golf-loop-model-lowerer` (spec r1; branch `weksa-lowering/golf-loop-model-lowerer`): the round lowers through the `ModelPort`. `Prompt::lower` (`context.rs`) takes a `LoweringInput` (no text, key, group or speaker getter), the inventory at the view's revision and the en-US entity forms, and prints `LOWER_INSTRUCTIONS`, the meaning of the packet, the entities line and the inventory listing; the item key goes only to `item_keys`. The answer is `{"text"}`, read as `LoweringDraft` in `encode.rs`, held in `score_round`'s locals and scored once; it is never put in `run.cc`, a `RoundRecord`, a `Decision` or `EditFeedback`. A round has two answer phases (every encode prompt, then every lowering prompt), all or nothing: while any prompt is unanswered `packets.cc` is discarded and nothing reaches `run.cc`. `lower::lower` and the template table leave the loop (they remain `weksa lower`'s; follow-up `table-retirement`), so an entry an edit adds can be said and a cycle can buy a gain. One source pin remains: `PROMPT_SOURCE_DIGEST` covers `context.rs`, `split.rs` and `lower.rs` (`RunRecord` key 7 and `RoundRecord` key 3 are retired). The run's record pins `LowererReach` (`weksa loop open --lowerer-reach briefed-subagent|tool-less-relay`, `RunRecord` key 12) and every printed round and cycle line says it; a briefed-subagent run says its numbers are smoke-round only (rulings `lowerer-call-reach-toolless-relay`, `dao-round-seed-inventory`). A lowering is refused at `Lower` when blank, over `MAX_LOWERING_BYTES` (4096) or holding a control character other than a line break or tab; `PROMPT_SOURCE_DIGEST` also covers `packet.rs`. Not here: per-item lowering text documents (`golf-loop-score-docs`), the subprocess adapter. Waits on 7c.
|
||||
7. `golf-loop-en` (7b and 7c landed the round, `ModelPort`, encoder prompt, template digest, round records and the edit-accept cycle; the rest remains): the packet store bound to one inventory store everywhere (`packet-store-inventory-binding`), a subprocess adapter, Score documents, `weksa score` in the loop, the detached unit on Yggdrasil. Waits on 3, 5, 6 and follow-up `claude-on-yggdrasil`.
|
||||
8. `style-axis`: a style-embedding score behind the scorer port. Waits on 3.
|
||||
9. `ja-panel`: ja-JP into the loop's panel, in two cuts on `e9cbd9b`. 9a `ja-panel-loop` (spec r1): language is the item's and the panel the run's: `Prompt::lower` takes the item's language and prints it on a language line (no prompt names English), entity forms are read in that language, `RunRecord` pins the panel (`weksa loop open --panel`), offers, mint and recall read only panel items, round means, floors and readings are per panel language, the accept rule runs `decide` per language, the recall split works on unspaced scripts, and `weksa corpus add` has no default language. 9b `ja-panel-corpus` (spec r1, after 9a): the ja-JP slice of `data/original`, model-written Japanese Train and Validation passages and eight Aozora Bunko public-domain Test sentences with full provenance, and their entities. Cut 5 is not a prerequisite: neither language lowers with ontology entries until cut 5 gives both theirs.
|
||||
9. `ja-panel`: ja-JP into the loop's panel. Waits on 7.
|
||||
10. `conlang-lexicon`: the first conlang's lexicon placed at concept embeddings, its morphology data, its ontology entries and the gloss reader. Waits on 3, 5 and question `first-conlang`.
|
||||
11. `convergence-freeze`: the convergence test, `Checkpoint`'s one door (built from the convergence window over the persisted round records), the freeze, the re-encode into training pairs. Waits on 7, 9 and 10.
|
||||
12. `distil`, three cuts. 12a `distil-slice` (relower and the prompted baseline; spec r1). 12b `distil-export`: Train-only prompt/completion JSONL at a frozen revision, Test-text guarded (follow-up `distil-export-at-freeze`); waits on 11. 12c `distil-train`: waits on 12b and the host question (follow-up `distil-host-question-owed`).
|
||||
12. `distil`: fine-tune a lowerer on the frozen training set. Waits on 11 and a host question asked then.
|
||||
13. `live-lowering`: agents emit packets with stance; Weksa reads speaker state from persona state (follow-up `persona-state-speech-community`) and lowers for the reader. Waits on 11.
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ ground truth is Discord text, which can never feed this loop
|
|||
|
||||
An agent's outward speech today is English text the model chose, so meaning,
|
||||
register and voice are fused in one string nobody can inspect or re-target.
|
||||
Weksa's design already separates them: the packet owns meaning, speaker and scene state own address and politeness
|
||||
(the language ontology holds only per-language lexicon, grammar and discourse choices), the lowerer owns
|
||||
Weksa's design already separates them: the packet owns meaning, the target
|
||||
profile owns address, politeness and forbidden flattenings, the lowerer owns
|
||||
surface text and a trace. The campaign makes that design real for a live
|
||||
reader, and gives Weksa's Persona a working body when her mind
|
||||
(`eureka-body:follow_up:weksa-mind`) wakes.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
# CultCache Lowering Examples
|
||||
|
||||
These examples lower interlingua packets for separate target languages. The
|
||||
language ontology that owns en-US and ja-JP choices is `data/ontology/ontology.cc`
|
||||
(`weksa ontology dump`); its entries are model-drafted seeds.
|
||||
These examples lower interlingua packets through CultCache cultural ontology
|
||||
profiles rather than the older YAML-only target-language profiles.
|
||||
|
||||
The starter database is:
|
||||
|
||||
- `.weksa/cultural-ontology/starter-targets.cc`
|
||||
|
||||
Each target file is produced as a separate agent run so differences in target
|
||||
ontology remain inspectable instead of being smoothed into one multilingual
|
||||
|
|
|
|||
|
|
@ -8,6 +8,10 @@ Prompt:
|
|||
|
||||
- `prompts/nibu-cultcache-target-lowering.md`
|
||||
|
||||
CultCache profile store:
|
||||
|
||||
- `.weksa/cultural-ontology/starter-targets.cc`
|
||||
|
||||
Expected target outputs:
|
||||
|
||||
- `pt-BR-vanilla-brazilian.yaml`
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
schema_version: weksa.utterance_lowering.agent_run.v0
|
||||
source_packet_id: nibu-proof-001
|
||||
source_packet_ref: examples/english-lowering/nibu-proof-001/interlingua.yaml
|
||||
target_profile_ref: .weksa/cultural-ontology/starter-targets.cc
|
||||
target_profile_id: weksa.cultural_ontology.en.transatlantic.v0
|
||||
target_agent_id: nibu
|
||||
realization:
|
||||
|
|
@ -10,6 +11,8 @@ realization:
|
|||
locale: en-001
|
||||
script: Latn
|
||||
register: cultivated transatlantic English; cross-Atlantic intelligibility; measured technical warning
|
||||
cultural_ontology_refs:
|
||||
- .weksa/cultural-ontology/starter-targets.cc
|
||||
cultural_ontology_profile_ids:
|
||||
- weksa.cultural_ontology.en.transatlantic.v0
|
||||
outputs:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
schema_version: weksa.utterance_lowering.agent_run.v0
|
||||
source_packet_id: nibu-proof-001
|
||||
source_packet_ref: examples/english-lowering/nibu-proof-001/interlingua.yaml
|
||||
target_profile_ref: .weksa/cultural-ontology/starter-targets.cc
|
||||
target_profile_id: weksa.cultural_ontology.ja-JP.kanto.contemporary.v0
|
||||
target_agent_id: nibu
|
||||
realization:
|
||||
|
|
@ -10,6 +11,8 @@ realization:
|
|||
locale: ja-JP
|
||||
script: Jpan
|
||||
register: contemporary Kanto metropolitan clipped hazard warning
|
||||
cultural_ontology_refs:
|
||||
- .weksa/cultural-ontology/starter-targets.cc
|
||||
cultural_ontology_profile_ids:
|
||||
- weksa.cultural_ontology.ja-JP.kanto.contemporary.v0
|
||||
outputs:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
schema_version: weksa.utterance_lowering.agent_run.v0
|
||||
source_packet_id: nibu-proof-001
|
||||
source_packet_ref: examples/english-lowering/nibu-proof-001/interlingua.yaml
|
||||
target_profile_ref: .weksa/cultural-ontology/starter-targets.cc
|
||||
target_profile_id: weksa.cultural_ontology.pt-BR.vanilla_brazilian.v0
|
||||
target_agent_id: nibu
|
||||
realization:
|
||||
|
|
@ -10,6 +11,8 @@ realization:
|
|||
locale: pt-BR
|
||||
script: Latn
|
||||
register: casual_clear
|
||||
cultural_ontology_refs:
|
||||
- .weksa/cultural-ontology/starter-targets.cc
|
||||
cultural_ontology_profile_ids:
|
||||
- weksa.cultural_ontology.pt-BR.vanilla_brazilian.v0
|
||||
outputs:
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ realizations:
|
|||
script: Latn
|
||||
register: sharp technical casual
|
||||
cultural_ontology_refs:
|
||||
- data/ontology/ontology.cc
|
||||
- data/target-language-ontology/en-US.yaml
|
||||
outputs:
|
||||
visible_action: The cockpit lights snap from amber to surgical white around the damaged control.
|
||||
spoken_text: "Take your hand off that control unless you want your nervous system to become my least useful circuit diagram."
|
||||
|
|
@ -52,6 +52,8 @@ realizations:
|
|||
locale: pt-BR
|
||||
script: Latn
|
||||
register: direct technical casual
|
||||
cultural_ontology_refs:
|
||||
- data/target-language-ontology/pt-BR.yaml
|
||||
outputs:
|
||||
visible_action: As luzes do cockpit passam de âmbar para branco cirúrgico ao redor do controle danificado.
|
||||
spoken_text: "Tira a mão desse controle, a não ser que você queira transformar o seu sistema nervoso no meu diagrama de circuitos menos útil."
|
||||
|
|
@ -88,7 +90,7 @@ realizations:
|
|||
script: Jpan
|
||||
register: sharp technical plain
|
||||
cultural_ontology_refs:
|
||||
- data/ontology/ontology.cc
|
||||
- data/target-language-ontology/ja-JP.yaml
|
||||
outputs:
|
||||
visible_action: 損傷した制御盤の周囲で、操縦室の灯りが琥珀色から外科灯のような白へ切り替わる。
|
||||
spoken_text: "その制御盤から手を離して。神経系を、私のいちばん役に立たない回路図にしたくないなら。"
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ referent without falling into generic fantasy-smith voice.
|
|||
The test is deliberately small: one interlingua packet, one rendered utterance,
|
||||
and one trace naming the activated cultural ontology axes.
|
||||
|
||||
Profile stack (these files were deleted from main by cut `delete-cultural-ontology`; they remain in git history before that commit, and the paths below are kept as the fixture's record of what it cited):
|
||||
Profile stack:
|
||||
|
||||
- `data/cultural-ontology/persona-stacks/brokkr.yaml`
|
||||
- `data/cultural-ontology/referents/old-norse-edda-source-tradition.yaml`
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
schema_version: weksa.persona_lowering_fixture_batch.v0
|
||||
fixture_id: brokkr-edda-voice
|
||||
speaker_id: brokkr
|
||||
# The data/cultural-ontology files cited below were deleted from main (cut delete-cultural-ontology); see git history.
|
||||
cultural_stack_ref: data/cultural-ontology/persona-stacks/brokkr.yaml
|
||||
target_register:
|
||||
language: en-US
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
schema_version: weksa.persona_culture_lowering_trace.v0
|
||||
fixture_id: brokkr-edda-voice
|
||||
item_id: command-without-receipt
|
||||
# The data/cultural-ontology files cited below were deleted from main (cut delete-cultural-ontology); see git history.
|
||||
profile_stack:
|
||||
- profile_id: weksa.cultural_referent.old_norse_edda_source_tradition.v0
|
||||
ref: data/cultural-ontology/referents/old-norse-edda-source-tradition.yaml
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ You are reviewing one target lowering produced from the Nibu interlingua packet.
|
|||
`examples/english-lowering/nibu-proof-001/projected-context.yaml`
|
||||
- Lowering prompt:
|
||||
`prompts/nibu-cultcache-target-lowering.md`
|
||||
- CultCache profile store:
|
||||
`.weksa/cultural-ontology/starter-targets.cc`
|
||||
|
||||
The source meaning is:
|
||||
|
||||
|
|
|
|||
|
|
@ -24,10 +24,20 @@ text. Lower from the interlingua packet and projected context.
|
|||
|
||||
## Cultural Ontology Authority
|
||||
|
||||
The language ontology is `data/ontology/ontology.cc` (`weksa ontology dump`).
|
||||
It holds model-drafted seed entries for en-US and ja-JP only; there is no
|
||||
pt-BR entry yet. Treat an entry as a draft: say in your trace which entries you
|
||||
used, and when no entry covers the target, say so rather than inventing one.
|
||||
Use the CultCache store:
|
||||
|
||||
- `.weksa/cultural-ontology/starter-targets.cc`
|
||||
|
||||
It contains:
|
||||
|
||||
- `weksa.cultural_ontology.pt-BR.vanilla_brazilian.v0`
|
||||
- `weksa.cultural_ontology.en.transatlantic.v0`
|
||||
- `weksa.cultural_ontology.ja-JP.kanto.contemporary.v0`
|
||||
|
||||
Qdrant-style retrieval and old YAML profiles may be useful context, but the
|
||||
CultCache profile named in your task is the target authority. Treat the target
|
||||
profile as draft guarded typed state: preserve its activation gates, forbidden
|
||||
flattenings, and nested linguistic affordance feature IDs in your trace.
|
||||
|
||||
## Output Contract
|
||||
|
||||
|
|
@ -40,6 +50,8 @@ The file must use this shape:
|
|||
schema_version: weksa.utterance_lowering.agent_run.v0
|
||||
source_packet_id: nibu-proof-001
|
||||
source_packet_ref: examples/english-lowering/nibu-proof-001/interlingua.yaml
|
||||
target_profile_ref: .weksa/cultural-ontology/starter-targets.cc
|
||||
target_profile_id:
|
||||
target_agent_id: nibu
|
||||
realization:
|
||||
realization_id:
|
||||
|
|
@ -48,6 +60,10 @@ realization:
|
|||
locale:
|
||||
script:
|
||||
register:
|
||||
cultural_ontology_refs:
|
||||
- .weksa/cultural-ontology/starter-targets.cc
|
||||
cultural_ontology_profile_ids:
|
||||
-
|
||||
outputs:
|
||||
visible_action:
|
||||
spoken_text:
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ them.
|
|||
- [utterance-lowering-packet.md](./utterance-lowering-packet.md): shared packet
|
||||
contract for lowering interlingua and projected speaker context into one or
|
||||
more target-language utterance realizations.
|
||||
- [target-language-cultural-ontology.md](./target-language-cultural-ontology.md):
|
||||
contract for the address, politeness, register, idiom, metaphor, script, and
|
||||
forbidden-flattening profiles consumed by target lowerers.
|
||||
- [cultural-ontology-profile.md](./cultural-ontology-profile.md): nested
|
||||
CultCache profile contract for cultural ontology, including typed salience
|
||||
axes, linguistic affordance feature records, evidence, activation gates, and
|
||||
|
|
|
|||
|
|
@ -24,17 +24,6 @@
|
|||
"$ref": "#/$defs/NameSpan"
|
||||
}
|
||||
},
|
||||
"names_by": {
|
||||
"description": "Who placed `names`: the annotator of the intake that wrote them. `None`\nwhen nothing records one (the cast seeds, `weksa corpus add`, the Dao De\nJing bed); it labels the spans, never the line or its speaker.",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/Annotator"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"prior_turns": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
|
|
@ -74,41 +63,6 @@
|
|||
"names"
|
||||
],
|
||||
"$defs": {
|
||||
"Annotator": {
|
||||
"description": "Who annotated a document. A model's generator is an attestation string, held\nto the same form as every provenance string.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Operator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Model": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"family": {
|
||||
"$ref": "#/$defs/ModelFamily"
|
||||
},
|
||||
"generator": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"family",
|
||||
"generator"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Model"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"EntityId": {
|
||||
"type": "string",
|
||||
"pattern": "^entity:[a-z0-9]([a-z0-9-]{0,46}[a-z0-9])?$"
|
||||
|
|
@ -216,7 +170,7 @@
|
|||
]
|
||||
},
|
||||
{
|
||||
"description": "A public-domain work, with everything a reader needs to check the claim:\nthe edition's licence and the jurisdiction the public-domain status is\nasserted in, who translated it (the translation is the text's copyright,\nnot the original's) and when the work or translation first appeared. A work missing any\nis refused at admission.",
|
||||
"description": "A public-domain work, with everything a reader needs to check the claim:\nthe edition's licence and the jurisdiction the public-domain status is\nasserted in, who translated it (the translation is the text's copyright,\nnot the original's) and when the edition appeared. A work missing any\nis refused at admission.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"PublicDomain": {
|
||||
|
|
@ -229,7 +183,6 @@
|
|||
"type": "string"
|
||||
},
|
||||
"edition_year": {
|
||||
"description": "The year the work, or for a translation this translation, first\nappeared. It is not the year of the `edition_url` file's source\nprint: Project Gutenberg's text may be a later or modernised\nedition, and the claim rests on the date of first appearance.",
|
||||
"type": "integer",
|
||||
"format": "uint16",
|
||||
"maximum": 65535,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Decision",
|
||||
"description": "One closed edit-accept cycle: digests and numbers, no text. Key\n`run:<label>:cycle:<k>`. Only [`cycle`] builds one.\n\n```\nfn f(d: &weksa::run::Decision) -> u32 { d.k() }\n```\n\nEvery field is given, so the literal below fails only on privacy; its twin is\nthe same literal in the unit test `a_decision_literal_compiles_in_the_lib`.\n\n```compile_fail,E0451\nuse weksa::run::{Call, Decision, Verdict};\nfn f() -> Decision {\n Decision {\n k: 1,\n base_round: 1,\n base_rev: 1,\n base_inventory_digest: String::new(),\n edit: Call { prompt: String::new(), items: vec![] },\n edit_answer_digest: None,\n candidate_rev: None,\n candidate_inventory_digest: None,\n candidate_round: None,\n panel: vec![],\n verdict: Verdict::Accepted,\n }\n}\n```",
|
||||
"description": "One closed edit-accept cycle: digests and numbers, no text. Key\n`run:<label>:cycle:<k>`. Only [`cycle`] builds one.\n\n```\nfn f(d: &weksa::run::Decision) -> u32 { d.k() }\n```\n\nEvery field is given, so the literal below fails only on privacy; its twin is\nthe same literal in the unit test `a_decision_literal_compiles_in_the_lib`.\n\n```compile_fail,E0451\nuse weksa::run::{Call, Decision, Reading, Verdict};\nfn f() -> Decision {\n let r = Reading { chrf: 0.0, meaning: 0.0, composite: 0.0 };\n Decision {\n k: 1,\n base_round: 1,\n base_rev: 1,\n base_inventory_digest: String::new(),\n edit: Call { prompt: String::new(), items: vec![] },\n edit_answer_digest: None,\n candidate_rev: None,\n candidate_inventory_digest: None,\n candidate_round: None,\n base: r,\n candidate: None,\n floor: r,\n threshold: 0.0,\n verdict: Verdict::Accepted,\n }\n}\n```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"base_inventory_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -18,6 +21,16 @@
|
|||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"candidate": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"candidate_inventory_digest": {
|
||||
"type": [
|
||||
"string",
|
||||
|
|
@ -51,17 +64,17 @@
|
|||
"null"
|
||||
]
|
||||
},
|
||||
"floor": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"k": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"panel": {
|
||||
"description": "One row per panel language, in panel order.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/PanelReading"
|
||||
}
|
||||
"threshold": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"verdict": {
|
||||
"$ref": "#/$defs/Verdict"
|
||||
|
|
@ -73,8 +86,10 @@
|
|||
"base_rev",
|
||||
"base_inventory_digest",
|
||||
"edit",
|
||||
"verdict",
|
||||
"panel"
|
||||
"base",
|
||||
"floor",
|
||||
"threshold",
|
||||
"verdict"
|
||||
],
|
||||
"$defs": {
|
||||
"Call": {
|
||||
|
|
@ -98,54 +113,10 @@
|
|||
},
|
||||
"Metric": {
|
||||
"description": "Which metric an edit regressed.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Chrf",
|
||||
"Meaning"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The composite fell, or a reading was not a finite number.",
|
||||
"type": "string",
|
||||
"const": "Composite"
|
||||
}
|
||||
]
|
||||
},
|
||||
"PanelReading": {
|
||||
"description": "One panel language's row of a cycle: the head's Validation reading, the\ncandidate's (none when the edit never reached a round), the language's\nmeasured floor and the threshold derived from it. The threshold decides only\nin a one-language panel ([`decide`]); with two or more languages it is\nrecorded beside the floor and the accept is the sum rule of\n[`decide_panel`].",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"candidate": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"floor": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"language": {
|
||||
"type": "string"
|
||||
},
|
||||
"threshold": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"language",
|
||||
"base",
|
||||
"floor",
|
||||
"threshold"
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Chrf",
|
||||
"Meaning"
|
||||
]
|
||||
},
|
||||
"Reading": {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "RoundRecord",
|
||||
"description": "One scored round. It holds no text and no Test reading: per-item rows for\nTrain only; Validation as means and refusal counts by stage, and as\nper-item scores (numbers only, private to this module). Only `run::round`\nbuilds one.\n\n```\nfn f(r: &weksa::run::RoundRecord) -> u32 { r.n() }\n```\n\nEvery field is given, so the literal below fails only on privacy; its twin\nis the same literal in the unit test `a_round_record_literal_compiles_in_the_lib`.\n\n```compile_fail,E0451\nuse weksa::run::RoundRecord;\nfn f() -> RoundRecord {\n RoundRecord {\n n: 1,\n inventory_rev: 1,\n prompt_digest: String::new(),\n corpus_digest: String::new(),\n entity_digest: String::new(),\n model: String::new(),\n embedder: String::new(),\n chrf_version: String::new(),\n calls: vec![],\n train: vec![],\n inventory_digest: String::new(),\n cycle: None,\n admit_rules: vec![],\n parse_reasons: vec![],\n own_family: 0,\n languages: vec![],\n validation_scores: vec![],\n }\n}\n```",
|
||||
"description": "One scored round. It holds no text and no Test reading: per-item rows for\nTrain only, Validation only as means and refusal counts by stage. Only\n`run::round` builds one.\n\n```\nfn f(r: &weksa::run::RoundRecord) -> u32 { r.n() }\n```\n\nEvery field is given, so the literal below fails only on privacy; its twin\nis the same literal in the unit test `a_round_record_literal_compiles_in_the_lib`.\n\n```compile_fail,E0451\nuse weksa::run::{RefusalCounts, RoundRecord};\nuse weksa::score::SplitMean;\nfn f() -> RoundRecord {\n RoundRecord {\n n: 1,\n inventory_rev: 1,\n prompt_digest: String::new(),\n corpus_digest: String::new(),\n entity_digest: String::new(),\n model: String::new(),\n embedder: String::new(),\n chrf_version: String::new(),\n calls: vec![],\n train: vec![],\n train_mean: SplitMean::default(),\n train_scored: 0,\n validation_mean: SplitMean::default(),\n validation_scored: 0,\n validation_refused: RefusalCounts::default(),\n inventory_digest: String::new(),\n cycle: None,\n admit_rules: vec![],\n parse_reasons: vec![],\n own_family: 0,\n }\n}\n```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admit_rules": {
|
||||
|
|
@ -49,13 +49,6 @@
|
|||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"languages": {
|
||||
"description": "One reading per panel language, in panel order. No pooled mean exists.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/LanguageRound"
|
||||
}
|
||||
},
|
||||
"model": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -88,13 +81,26 @@
|
|||
"$ref": "#/$defs/TrainRow"
|
||||
}
|
||||
},
|
||||
"validation_scores": {
|
||||
"description": "Each panel language's live Validation scores in corpus order, a refused\nitem as 0. Private with no getter: only `run.rs` (the floor) reads them,\nso a leak outside it is a compile error. A run from before has none.",
|
||||
"type": "array",
|
||||
"default": [],
|
||||
"items": {
|
||||
"$ref": "#/$defs/LanguageScores"
|
||||
}
|
||||
"train_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"train_scored": {
|
||||
"description": "Train items that lowered and scored; `train_mean` is over all of them\nand counts a refused item as 0.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"validation_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"validation_refused": {
|
||||
"$ref": "#/$defs/RefusalCounts"
|
||||
},
|
||||
"validation_scored": {
|
||||
"description": "Validation items that lowered and scored; `validation_mean` is over all\nof them and counts a refused item as 0, so refusing a weak item cannot\nraise it.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
|
@ -108,8 +114,12 @@
|
|||
"chrf_version",
|
||||
"calls",
|
||||
"train",
|
||||
"inventory_digest",
|
||||
"languages"
|
||||
"train_mean",
|
||||
"validation_mean",
|
||||
"validation_refused",
|
||||
"train_scored",
|
||||
"validation_scored",
|
||||
"inventory_digest"
|
||||
],
|
||||
"$defs": {
|
||||
"Call": {
|
||||
|
|
@ -131,84 +141,6 @@
|
|||
"items"
|
||||
]
|
||||
},
|
||||
"ItemScore": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chrf": {
|
||||
"description": "chrF of the output against the reference.",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"meaning": {
|
||||
"description": "Embedding cosine of the output and the reference; `None` when either\nis empty after trimming.",
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"chrf"
|
||||
]
|
||||
},
|
||||
"LanguageRound": {
|
||||
"description": "One panel language's readings in a round: the means over that language's\nitems only (a refused item counts 0) and how many items lowered and scored.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"language": {
|
||||
"type": "string"
|
||||
},
|
||||
"train_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"train_scored": {
|
||||
"description": "Train items that lowered and scored; `train_mean` is over all of them.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"validation_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"validation_refused": {
|
||||
"$ref": "#/$defs/RefusalCounts"
|
||||
},
|
||||
"validation_scored": {
|
||||
"description": "Validation items that lowered and scored; `validation_mean` is over all\nof them and counts a refused item as 0, so refusing a weak item cannot\nraise it.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"language",
|
||||
"train_mean",
|
||||
"train_scored",
|
||||
"validation_mean",
|
||||
"validation_scored",
|
||||
"validation_refused"
|
||||
]
|
||||
},
|
||||
"LanguageScores": {
|
||||
"description": "One panel language's Validation scores in a round, in corpus order: numbers\nonly, no item key and no text. Only `run.rs` reads them (the paired floor).",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"language": {
|
||||
"type": "string"
|
||||
},
|
||||
"scores": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/ItemScore"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"language",
|
||||
"scores"
|
||||
]
|
||||
},
|
||||
"Outcome": {
|
||||
"oneOf": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -49,31 +49,8 @@
|
|||
"description": "The answering model.",
|
||||
"type": "string"
|
||||
},
|
||||
"ontology": {
|
||||
"description": "Canonical absolute path of the ontology store: read-only for the run,\npinned by `ontology_digest`.",
|
||||
"type": "string"
|
||||
},
|
||||
"ontology_digest": {
|
||||
"description": "16 hex of the ontology file's bytes.",
|
||||
"type": "string"
|
||||
},
|
||||
"panel": {
|
||||
"description": "The languages the run offers, reads and decides on: BCP 47-form tags,\nsorted, unique, at least one, set once at open. An item of any other\nlanguage is never offered, minted from, probed or scored.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"prompt_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"speaker_state": {
|
||||
"description": "Canonical absolute path of the speaker-state store (scenes): read-only\nfor the run, pinned by `speaker_state_digest`.",
|
||||
"type": "string"
|
||||
},
|
||||
"speaker_state_digest": {
|
||||
"description": "16 hex of the speaker-state file's bytes.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
|
@ -88,12 +65,7 @@
|
|||
"embedder",
|
||||
"chrf_version",
|
||||
"inventory_digest",
|
||||
"lowerer_reach",
|
||||
"panel",
|
||||
"ontology",
|
||||
"ontology_digest",
|
||||
"speaker_state",
|
||||
"speaker_state_digest"
|
||||
"lowerer_reach"
|
||||
],
|
||||
"$defs": {
|
||||
"LowererReach": {
|
||||
|
|
|
|||
|
|
@ -1,277 +0,0 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "OntologyEntry",
|
||||
"description": "One choice of one language. Key `onto:<language>:<n>`.\n\nThe store judges the form of an entry's text (bounds, normalization, no\ncontrol or format character) and never its meaning: no door judges text\n(ruling `leak-owned-by-flow-and-scorer-3`). No Train-only ontology mint\nexists yet, so a seed or a drafted entry is checked against held-out text by\nnothing today; follow-up `leak-diagnostic-in-round` owns that diagnostic.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"annotator": {
|
||||
"$ref": "#/$defs/Annotator"
|
||||
},
|
||||
"choice": {
|
||||
"type": "string"
|
||||
},
|
||||
"examples": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"inventory_rev": {
|
||||
"description": "The revision, of the inventory the entry was admitted through, at which the\nstore read its conditions: provenance only; a run reads the conditions'\nfeatures at its own head.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"language": {
|
||||
"type": "string"
|
||||
},
|
||||
"layer": {
|
||||
"$ref": "#/$defs/Layer"
|
||||
},
|
||||
"n": {
|
||||
"description": "The entry's number within its language, from 1.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"when": {
|
||||
"description": "Every condition must hold; none means the entry always applies.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Condition"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"language",
|
||||
"n",
|
||||
"inventory_rev",
|
||||
"layer",
|
||||
"when",
|
||||
"choice",
|
||||
"examples",
|
||||
"annotator"
|
||||
],
|
||||
"$defs": {
|
||||
"Annotator": {
|
||||
"description": "Who annotated a document. A model's generator is an attestation string, held\nto the same form as every provenance string.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Operator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Model": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"family": {
|
||||
"$ref": "#/$defs/ModelFamily"
|
||||
},
|
||||
"generator": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"family",
|
||||
"generator"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Model"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"Condition": {
|
||||
"description": "One feature of one slot of the view, tested. `Stance`, `Discourse` and\n`Scene` reach a lowering view; `Speaker` does not yet.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"feature": {
|
||||
"$ref": "#/$defs/InvId"
|
||||
},
|
||||
"slot": {
|
||||
"$ref": "#/$defs/Slot"
|
||||
},
|
||||
"test": {
|
||||
"$ref": "#/$defs/Test"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"slot",
|
||||
"feature",
|
||||
"test"
|
||||
]
|
||||
},
|
||||
"FeatValue": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Grade": {
|
||||
"$ref": "#/$defs/Grade"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Grade"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "A label the feature's inventory entry declares.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Option": {
|
||||
"$ref": "#/$defs/OptionLabel"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Option"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Flag": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Flag"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"Grade": {
|
||||
"type": "integer",
|
||||
"maximum": 1000,
|
||||
"minimum": 0
|
||||
},
|
||||
"InvId": {
|
||||
"type": "string",
|
||||
"pattern": "^(concept|frame|role|relation|speech_act|feature|referent_kind|extension):[1-9][0-9]*$"
|
||||
},
|
||||
"Layer": {
|
||||
"description": "Which part of the language an entry shapes.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Lexicon",
|
||||
"Grammar",
|
||||
"Discourse",
|
||||
"Phonology",
|
||||
"Orthography"
|
||||
]
|
||||
},
|
||||
"ModelFamily": {
|
||||
"description": "The family of the model that wrote a line.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Anthropic",
|
||||
"OpenAi",
|
||||
"Google",
|
||||
"Alibaba",
|
||||
"Meta",
|
||||
"Mistral"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Nothing records which family wrote the line.",
|
||||
"type": "string",
|
||||
"const": "Unrecorded"
|
||||
}
|
||||
]
|
||||
},
|
||||
"OptionLabel": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]{0,23}$"
|
||||
},
|
||||
"Slot": {
|
||||
"description": "Where a feature may sit in a packet.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Discourse",
|
||||
"Referent",
|
||||
"Predication",
|
||||
"Relation",
|
||||
"Stance"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The speaker's relation to one party of the scene, held by `weksa.scene`\ndocuments; see `LoweringInput::with_scene`.",
|
||||
"type": "string",
|
||||
"const": "Scene"
|
||||
},
|
||||
{
|
||||
"description": "The speaker's stable axes, held by `weksa.speaker` documents.",
|
||||
"type": "string",
|
||||
"const": "Speaker"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Test": {
|
||||
"description": "What a feature's value must be for a condition to hold.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"AtLeast": {
|
||||
"$ref": "#/$defs/Grade"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"AtLeast"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"AtMost": {
|
||||
"$ref": "#/$defs/Grade"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"AtMost"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Is": {
|
||||
"$ref": "#/$defs/FeatValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Is"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Holds when the feature is absent or a grade at most `g`: a bound that\ncosts nothing where the feature is unrated. `AtMost` still fails on an\nabsent feature.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"AtMostOrUnset": {
|
||||
"$ref": "#/$defs/Grade"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"AtMostOrUnset"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,7 +12,6 @@
|
|||
"type": "string"
|
||||
},
|
||||
"inventory_rev": {
|
||||
"description": "The revision, of the inventory the scene was admitted through, at which\n`put_scene` read its features: provenance only; a run never reads it.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ This is the human-facing schema receipt for
|
|||
reviewed cultural ontology used during utterance lowering.
|
||||
|
||||
Executable schema code does not exist yet. When it does, it must reconcile with
|
||||
this receipt, the meta-analysis paper, and the language ontology in
|
||||
`data/ontology/ontology.cc`.
|
||||
this receipt, the meta-analysis paper, and the profiles under
|
||||
`data/target-language-ontology/`.
|
||||
|
||||
## Authority
|
||||
|
||||
|
|
@ -265,11 +265,14 @@ cultural_ontology_trace:
|
|||
|
||||
## Storage
|
||||
|
||||
No profile store exists. The per-language lowering choices live in
|
||||
`data/ontology/ontology.cc` (`weksa ontology dump`); the typed profiles that
|
||||
once sat under `.weksa/cultural-ontology/`, and the `weksa.target_cultural_ontology.*`
|
||||
base profiles are deleted. Community and dialect
|
||||
profiles are owned by follow-up `language-ontology-communities`.
|
||||
Recommended CultCache paths:
|
||||
|
||||
```text
|
||||
.weksa/cultural-ontology/{profileId}.cc
|
||||
.weksa/cultural-ontology/{baseProfileId}/overlays/{overlayId}.cc
|
||||
.weksa/cultural-ontology/catalogs/{catalogId}.cc
|
||||
.weksa/cultural-ontology/evidence-bundles/{bundleId}.cc
|
||||
```
|
||||
|
||||
Qdrant may store chunks, vectors, and payload filters for retrieval. It does
|
||||
not own profile acceptance, feature activation, or renderer authority.
|
||||
|
|
|
|||
81
schemas/target-language-cultural-ontology.md
Normal file
81
schemas/target-language-cultural-ontology.md
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
# Target-Language Cultural Ontology Contract
|
||||
|
||||
This is the human-facing schema receipt for target-language cultural ontology
|
||||
profiles consumed by Weksa utterance lowering.
|
||||
|
||||
Executable schema code does not exist yet. When it does, it must reconcile with
|
||||
this document and the profiles under `data/target-language-ontology/`.
|
||||
|
||||
## Authority
|
||||
|
||||
A target-language cultural ontology profile owns the realization distinctions
|
||||
that must be inspected for a human target language before surface text is
|
||||
chosen.
|
||||
|
||||
It owns:
|
||||
|
||||
- address and treatment distinctions
|
||||
- politeness and register pressure
|
||||
- social stance and directness defaults
|
||||
- idiom, metaphor, and lexical-locale risks
|
||||
- script or orthographic choices that carry meaning
|
||||
- forbidden flattenings for reviewed output
|
||||
|
||||
It does not own:
|
||||
|
||||
- source meaning
|
||||
- speaker identity
|
||||
- private state
|
||||
- exhaustive grammar
|
||||
- whole-culture description
|
||||
- final wording without an interlingua packet
|
||||
|
||||
## Required Fields
|
||||
|
||||
- `profile_id`: stable profile identifier.
|
||||
- `language`: target code, locale, and script.
|
||||
- `scope`: bounded statement of what the profile is and is not.
|
||||
- `authority`: `owns` and `does_not_own` lists.
|
||||
- `salience_axes`: named axes the lowerer must inspect.
|
||||
- `linguistic_affordances`: optional nested typed feature records, following
|
||||
`cultural-ontology-profile.md`, when the profile owns dialect, register,
|
||||
phonological, lexical, discourse, orthographic, or code-switching pressure.
|
||||
- `forbidden_flattenings`: mistakes the target lowerer must avoid.
|
||||
|
||||
## Salience Axes
|
||||
|
||||
Each salience axis should name:
|
||||
|
||||
- `relevant_distinctions`: choices the target language or locale makes visible.
|
||||
- `lowering_questions`: questions reviewers and lowerers should answer before
|
||||
accepting an output.
|
||||
|
||||
Examples:
|
||||
|
||||
- English directness and sarcasm.
|
||||
- Brazilian Portuguese treatment choice, lexical locale, and regional or
|
||||
religious-cultural overlays.
|
||||
- Japanese politeness, ellipsis, and sentence-final force.
|
||||
|
||||
## Fixture Contract
|
||||
|
||||
Reviewed multilingual fixtures should cite the profile used by each
|
||||
realization:
|
||||
|
||||
```yaml
|
||||
target_language:
|
||||
code: pt
|
||||
locale: pt-BR
|
||||
script: Latn
|
||||
register: direct technical casual
|
||||
cultural_ontology_refs:
|
||||
- data/target-language-ontology/pt-BR.yaml
|
||||
```
|
||||
|
||||
The realization trace should name the cultural ontology axes that shaped the
|
||||
line.
|
||||
|
||||
For dialectal, regional, historical, ritual, and contact-language profiles, use
|
||||
the nested `weksa.cultural_ontology_profile.v0` contract in
|
||||
`cultural-ontology-profile.md`. Flat string lists are only summaries; typed
|
||||
feature records own accepted affordance detail.
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Build the "Show her working" page from the real lowerer and scorer, then publish it as a Mind preview.
|
||||
# Run from the repository root, in a Mind's Self run (it writes only /srv/minds-web/<mind>/).
|
||||
#
|
||||
# scripts/publish-show-working.sh [--no-publish]
|
||||
#
|
||||
# Needs cargo, python3 and an Ollama embedder at 127.0.0.1:11434 (qwen3-embedding:0.6b): the scorer is not stubbed.
|
||||
# publish-mind-preview.sh lives in the gamecult-ops checkout: set GAMECULT_OPS to it (default ../gamecult-ops).
|
||||
set -euo pipefail
|
||||
[ -f Cargo.toml ] && [ -d tools/show-working ] || { echo "run from the Weksa repository root" >&2; exit 2; }
|
||||
out=${SHOW_WORKING_OUT:-tools/show-working/out}
|
||||
rm -rf "$out"
|
||||
python3 -I tools/show-working/build.py "$out"
|
||||
[ "${1:-}" = --no-publish ] && { echo "built $out"; exit 0; }
|
||||
ops=${GAMECULT_OPS:-../gamecult-ops}
|
||||
exec "$ops/scripts/publish-mind-preview.sh" "$out" weksa-show-working
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
"""Agreement of annotator A, B, the older labels and the round-1 encoder. Run it BEFORE the
|
||||
rubric r1 revisions are put: the older labels are the store's latest revision then.
|
||||
Standard library only. Usage: as build_briefs.py, plus ROUND1=<round-1 dir of the run>."""
|
||||
import re,sys,subprocess,json,glob,os
|
||||
import os
|
||||
W=os.environ.get("WEKSA","target/debug/weksa") # the weksa binary
|
||||
R=os.getcwd() # run from the repo root
|
||||
S=os.environ.get("SCENE_SCRATCH","scene-scratch")+"/" # A-*.jsonl, B-*.jsonl, briefs; never committed
|
||||
A=["--corpus","data/original/corpus.cc","--entities","data/original/entity.cc","--inventory","data/original/inventory.cc","--speaker-state","data/original/speaker-state.cc"]
|
||||
def run(*a): return subprocess.run([W]+A+list(a),cwd=R,capture_output=True,text=True).stdout.split("\n")
|
||||
out=run("corpus","dump")
|
||||
items=[]
|
||||
for i,l in enumerate(out):
|
||||
m=re.match(r'^item:(\S+) \[(\S+) \S+ group=(\S+) (\w+)\]$',l)
|
||||
if m and m.group(4)!="Test":
|
||||
t=out[i+1].strip(); t=json.loads(t) if '\\' in t else t[1:-1]
|
||||
items.append(dict(id=m.group(1),lang=m.group(2),group=m.group(3),text=t,new=m.group(1).startswith("vgrow")))
|
||||
G={x['group']:x for x in items}
|
||||
assert len(G)==98
|
||||
# scene dump: latest and @1 per group
|
||||
sd=run("scene","dump"); lab={}
|
||||
for i,l in enumerate(sd):
|
||||
m=re.match(r'^scene:(\S+)@(\d+) rev:\d+ Model \S+ (.*) \[entity:keeper\]$',l)
|
||||
if m:
|
||||
f=re.search(r'relative_status=(\w+) intimacy=(\d+) in_group=(\w+)',sd[i+1])
|
||||
lab.setdefault(m.group(1),{})[int(m.group(2))]=dict(rs=f.group(1),im=int(f.group(2)),ig=f.group(3)=="true",gen=m.group(3))
|
||||
old={g:v[max(v)] for g,v in lab.items()}
|
||||
def load(f): return {json.loads(l)['group']:json.loads(l) for l in open(S+f+".jsonl")}
|
||||
Aa={**load("A-en"),**load("A-ja")}; Bb={**load("B-en"),**load("B-ja")}
|
||||
assert set(Aa)==set(G)==set(Bb)
|
||||
def kappa(x,y):
|
||||
n=len(x);
|
||||
if n==0: return float('nan')
|
||||
po=sum(a==b for a,b in zip(x,y))/n
|
||||
pa=sum(x)/n; pb=sum(y)/n
|
||||
pe=pa*pb+(1-pa)*(1-pb)
|
||||
return float('nan') if pe==1 else (po-pe)/(1-pe)
|
||||
def tab(x,y):
|
||||
return "[TT=%d TF=%d FT=%d FF=%d]"%(sum(a and b for a,b in zip(x,y)),sum(a and not b for a,b in zip(x,y)),sum((not a) and b for a,b in zip(x,y)),sum((not a) and (not b) for a,b in zip(x,y)))
|
||||
def cmp(name,P,Q,gs,bkey=None):
|
||||
# P,Q: dict group-> record with keys addressed(optional) relative_status intimacy in_group
|
||||
def rs(r): return r.get('relative_status',r.get('rs'))
|
||||
def im(r): return r.get('intimacy',r.get('im'))
|
||||
def ig(r): return r.get('in_group',r.get('ig'))
|
||||
n=len(gs)
|
||||
if n==0: print(f"{name}: n=0"); return
|
||||
e=lambda f: sum(f(P[g])==f(Q[g]) for g in gs)
|
||||
s=f"{name}: n={n} rs_eq={e(rs)}/{n} ig_eq={e(ig)}/{n} im<=150={sum(abs(im(P[g])-im(Q[g]))<=150 for g in gs)}/{n}"
|
||||
s+=f" ig_kappa={kappa([ig(P[g]) for g in gs],[ig(Q[g]) for g in gs]):.2f} ig_tab(A.row,B.col)={tab([ig(P[g]) for g in gs],[ig(Q[g]) for g in gs])}"
|
||||
if all('addressed' in P[g] and 'addressed' in Q[g] for g in gs):
|
||||
s+=f" addr_eq={e(lambda r:r['addressed'])}/{n} addr_kappa={kappa([P[g]['addressed'] for g in gs],[Q[g]['addressed'] for g in gs]):.2f} addr_tab={tab([P[g]['addressed'] for g in gs],[Q[g]['addressed'] for g in gs])}"
|
||||
print(s)
|
||||
L={"en-US":[g for g in G if G[g]['lang']=="en-US"],"ja-JP":[g for g in G if G[g]['lang']=="ja-JP"],"pooled":list(G)}
|
||||
print("== (1) A vs B")
|
||||
for k,gs in L.items(): cmp(k,Aa,Bb,gs)
|
||||
oldg=[g for g in G if not G[g]['new']]; newg=[g for g in G if G[g]['new']]
|
||||
print("== (2) blind check: A vs old latest, the 56")
|
||||
for k,gs in L.items():
|
||||
gg=[g for g in gs if g in oldg]
|
||||
cmp(k+" all",Aa,old,gg)
|
||||
cmp(k+" A.addr=true",Aa,old,[g for g in gg if Aa[g]['addressed']])
|
||||
cmp(k+" A.addr=false",Aa,old,[g for g in gg if not Aa[g]['addressed']])
|
||||
print("differing in_group (old->A):")
|
||||
for g in oldg:
|
||||
if old[g]['ig']!=Aa[g]['in_group']: print(" ",g,old[g]['ig'],"->",Aa[g]['in_group'],"addr",Aa[g]['addressed'])
|
||||
print("differing any label, old vs A:")
|
||||
for g in oldg:
|
||||
o=old[g];a=Aa[g]
|
||||
if (o['rs'],o['im'],o['ig'])!=(a['relative_status'],a['intimacy'],a['in_group']): print(" %s old %s/%d/%s A %s/%d/%s addr=%s"%(g,o['rs'],o['im'],o['ig'],a['relative_status'],a['intimacy'],a['in_group'],a['addressed']))
|
||||
print("== (3) A vs vgrow @1, the 42")
|
||||
for k,gs in L.items(): cmp(k,Aa,{g:lab[g][1] for g in newg},[g for g in gs if g in newg])
|
||||
print("== (4) A addressed vs round-1 encoder addressee")
|
||||
enc={}
|
||||
RD=os.environ.get("ROUND1","runs/growth-base/round-1")+"/"
|
||||
for p in glob.glob(RD+"*.prompt"):
|
||||
pt=open(p).read()
|
||||
if not pt.startswith("Encode the line"): continue
|
||||
ap=p[:-7]+".answer"
|
||||
if not os.path.exists(ap): continue
|
||||
# the line text; take the item whose text appears in the prompt
|
||||
hit=[g for g in G if G[g]['text'] in pt]
|
||||
if len(hit)!=1: continue
|
||||
try: a=json.load(open(ap))
|
||||
except Exception: continue
|
||||
enc[hit[0]]=a.get('discourse',{}).get('addressee') is not None
|
||||
print("encoder answers matched:",len(enc),"of 98")
|
||||
for k,gs in list(L.items()):
|
||||
gg=[g for g in gs if g in enc]
|
||||
print(k,"n=",len(gg),"A.row,enc.col",tab([Aa[g]['addressed'] for g in gg],[enc[g] for g in gg]),"kappa=%.2f"%kappa([Aa[g]['addressed'] for g in gg],[enc[g] for g in gg]))
|
||||
for nm,grp in (("old",oldg),("new",newg)):
|
||||
gg=[g for g in grp if g in enc]; print(nm,"enc-addressee true:",sum(enc[g] for g in gg),"of",len(gg),"; A addressed true among old/new:",sum(Aa[g]['addressed'] for g in grp),"of",len(grp))
|
||||
print("== (5) in_group true counts, old/new x addressed, before -> after")
|
||||
for nm,grp in (("old56",oldg),("new42",newg)):
|
||||
for ad in (True,False):
|
||||
gg=[g for g in grp if Aa[g]['addressed']==ad]
|
||||
before=sum(old[g]['ig'] for g in gg); after=sum(Aa[g]['in_group'] for g in gg)
|
||||
print(f"{nm} A.addressed={ad}: n={len(gg)} in_group true before={before} after={after}")
|
||||
print("totals before",sum(old[g]['ig'] for g in G),"after",sum(Aa[g]['in_group'] for g in G))
|
||||
print("A addressed true:",sum(Aa[g]['addressed'] for g in G),"B:",sum(Bb[g]['addressed'] for g in G))
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
"""Build the two annotator briefs (rubric r1 section + one language's shuffled live
|
||||
sentences), print the Test-leak count of each (must be 0) and its sha256.
|
||||
Standard library only. Usage: from the repo root, WEKSA=... SCENE_SCRATCH=dir python3 -I scripts/scene-annotation/build_briefs.py"""
|
||||
import re,sys,subprocess,random,json,hashlib,os
|
||||
import os
|
||||
W=os.environ.get("WEKSA","target/debug/weksa") # the weksa binary
|
||||
R=os.getcwd() # run from the repo root
|
||||
S=os.environ.get("SCENE_SCRATCH","scene-scratch")+"/" # A-*.jsonl, B-*.jsonl, briefs; never committed
|
||||
A=["--corpus","data/original/corpus.cc","--entities","data/original/entity.cc","--inventory","data/original/inventory.cc","--speaker-state","data/original/speaker-state.cc"]
|
||||
out=subprocess.run([W]+A+["corpus","dump"],cwd=R,capture_output=True,text=True).stdout.split("\n")
|
||||
live=[];test=[]
|
||||
for i,l in enumerate(out):
|
||||
m=re.match(r'^item:(\S+) \[(\S+) \S+ group=(\S+) (\w+)\]$',l)
|
||||
if not m: continue
|
||||
t=out[i+1].strip()
|
||||
assert t.startswith('"') and t.endswith('"')
|
||||
t=json.loads(t) if '\\' in t else t[1:-1]
|
||||
if m.group(4)=="Test": test.append(t)
|
||||
else: live.append((m.group(2),m.group(3),t))
|
||||
assert len(live)==98,len(live)
|
||||
rub=open(R+"/docs/scene-annotation.md").read()
|
||||
sec=rub[rub.index("## Rubric r1"):]
|
||||
# rubric section ends at next "## " heading
|
||||
rest=sec[len("## Rubric r1"):]
|
||||
nx=rest.find("\n## ")
|
||||
sec=sec[:len("## Rubric r1")+(nx if nx>=0 else len(rest))].strip()+"\n"
|
||||
def leaks(brief,text):
|
||||
w=text.split(); c=list(text)
|
||||
return text in brief or any(" ".join(w[k:k+5]) in brief for k in range(len(w)-4)) or (len(w)==1 and any("".join(c[k:k+12]) in brief for k in range(len(c)-11)))
|
||||
for lang in ("en-US","ja-JP"):
|
||||
rows=[(g,t) for (l,g,t) in live if l==lang]
|
||||
assert len(rows)==49
|
||||
random.Random(f"scene-r1-{lang}").shuffle(rows)
|
||||
body=sec+"\nThe groups, one per line as group<TAB>\"text\":\n\n"+"\n".join(f'{g}\t"{t}"' for g,t in rows)+"\n"
|
||||
n=sum(leaks(body,t) for t in test)
|
||||
print(lang,"lines",len(rows),"test_leaks",n,hashlib.sha256(body.encode()).hexdigest())
|
||||
open(S+f"brief-{lang}.txt","w").write(body)
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
"""Put annotator A's labels through weksa scene put, one revision per group.
|
||||
Standard library only. Usage: as build_briefs.py."""
|
||||
import json,subprocess
|
||||
import os
|
||||
W=os.environ.get("WEKSA","target/debug/weksa") # the weksa binary
|
||||
R=os.getcwd() # run from the repo root
|
||||
S=os.environ.get("SCENE_SCRATCH","scene-scratch")+"/" # A-*.jsonl, B-*.jsonl, briefs; never committed
|
||||
A=["--corpus","data/original/corpus.cc","--entities","data/original/entity.cc","--inventory","data/original/inventory.cc","--speaker-state","data/original/speaker-state.cc"]
|
||||
rows=[json.loads(l) for f in ("A-en","A-ja") for l in open(S+f"{f}.jsonl")]
|
||||
for r in sorted(rows,key=lambda r:r['group']):
|
||||
c=[W]+A+["scene","put","--group",r['group'],"--to","unnamed","--inventory-rev","4",
|
||||
"--set",f"relative_status={r['relative_status']}","--set",f"intimacy={r['intimacy']}","--set",f"in_group={'true' if r['in_group'] else 'false'}",
|
||||
"--model-family","anthropic","--generator","claude-sonnet-5-5 (Weksa Hands, scene rubric r1, docs/scene-annotation.md)"]
|
||||
p=subprocess.run(c,cwd=R,capture_output=True,text=True)
|
||||
print(r['group'],p.returncode,p.stdout.strip()[:80],p.stderr.strip()[:200])
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
# Show her working
|
||||
|
||||
A static page that shows the lowering chain for committed fixture packets: typed slots, inventory entries chosen, lowered English, scorer closeness to the corpus target, with hedge, certainty and restraint annotated. Refusals (admission rules, `LowerError`, addressee consent, negation awaiting polarity) are results, not omissions.
|
||||
|
||||
- `crates/weksa/examples/show_working.rs`: runs the real admission door, `lower` and `pronounce` over `proof_packet()` and its variants and prints JSON. Each feature is removed in turn and the packet re-run, so "the lowerer read this" is measured.
|
||||
- `build.py`: runs that, scores each lowered text with the `weksa score` CLI (needs Ollama with `qwen3-embedding:0.6b`), writes `out/data.json` and one dependency-free `out/index.html`. Fails if anything cannot run; there is no fallback text.
|
||||
- `scripts/publish-show-working.sh`: build, then publish through gamecult-ops `publish-mind-preview.sh`.
|
||||
|
||||
Adding a fixture: add an entry in `fixtures()` in the example. A packet from another store needs a loader there; none exists yet.
|
||||
|
|
@ -1,217 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Build the "Show her working" page from the real lowerer and scorer.
|
||||
|
||||
usage: build.py [out_dir] (run from the repository root)
|
||||
|
||||
1. `cargo run --example show_working` admits each fixture packet through the
|
||||
packet store and lowers it with the English lowerer (crates/weksa/examples).
|
||||
2. `weksa score` scores each lowered text against its corpus item (and the
|
||||
other committed Nibu reference) through the Ollama embedder.
|
||||
3. out_dir/data.json holds the joined result; out_dir/index.html is one file
|
||||
with no scripts to fetch and no network calls.
|
||||
|
||||
Nothing on the page is typed by hand except the layout and the reading notes.
|
||||
If cargo or the scorer cannot run, the build fails: there is no fallback text.
|
||||
Standard library only.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from html import escape as e
|
||||
|
||||
root = pathlib.Path.cwd()
|
||||
out_dir = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "tools/show-working/out")
|
||||
weksa_bin = None
|
||||
|
||||
|
||||
def run(cmd, **kw):
|
||||
r = subprocess.run(cmd, cwd=root, capture_output=True, text=True, **kw)
|
||||
if r.returncode != 0:
|
||||
sys.exit(f"{' '.join(map(str, cmd))} failed:\n{r.stderr}")
|
||||
return r.stdout
|
||||
|
||||
|
||||
def cargo_target():
|
||||
meta = json.loads(run(["cargo", "metadata", "--format-version", "1", "--no-deps"]))
|
||||
return pathlib.Path(meta["target_directory"])
|
||||
|
||||
|
||||
# -- 1. the real lowerer ------------------------------------------------------
|
||||
run(["cargo", "build", "--release", "--bin", "weksa", "--example", "show_working"])
|
||||
target = cargo_target() / "release"
|
||||
weksa_bin = target / "weksa"
|
||||
data = json.loads(run([str(target / "examples" / "show_working")]))
|
||||
|
||||
# -- 2. the real scorer -------------------------------------------------------
|
||||
REFS_EXTRA = ["item:nibu:2"]
|
||||
# The page publishes only the corpus items its fixtures cite (plus the extra
|
||||
# reference each lowered fixture is scored against). A Validation or Test item
|
||||
# is never published, even when hand-added to REFS_EXTRA or cited by a fixture:
|
||||
# the dump holds every split, and the guard below reads each item's split.
|
||||
cited = {fx["corpus_item"] for fx in data["fixtures"]} | set(REFS_EXTRA)
|
||||
corpus = {}
|
||||
for m in re.finditer(r'^(item:\S+) \[(.*?)\]\n "(.*)"$', run([str(weksa_bin), "corpus", "dump"]), re.M):
|
||||
if m.group(1) in cited:
|
||||
corpus[m.group(1)] = {"text": m.group(3), "meta": m.group(2)}
|
||||
if set(corpus) != cited:
|
||||
sys.exit(f"corpus dump lacks cited items {sorted(cited - set(corpus))}; unexpected {sorted(set(corpus) - cited)}")
|
||||
# The dump's meta ends with the split (`... group=g Validation`, `... excluded`).
|
||||
# Only Train and split-less items publish; any other name, including a split
|
||||
# added later, is held out until it is allowed here.
|
||||
held_out = {k: v["meta"].split()[-1] for k, v in corpus.items() if v["meta"].split()[-1] not in ("Train", "excluded")}
|
||||
if held_out:
|
||||
sys.exit(f"refusing to publish held-out items (nothing written): {held_out}")
|
||||
model = "qwen3-embedding:0.6b"
|
||||
|
||||
|
||||
def score(text, items):
|
||||
out = run([str(weksa_bin), "score", *items], input=text)
|
||||
got = {}
|
||||
for m in re.finditer(r"^(item:\S+) chrf=([\d.]+) meaning=(-?[\d.]+)", out, re.M):
|
||||
got[m.group(1)] = {"chrf": float(m.group(2)), "meaning": float(m.group(3))}
|
||||
if set(got) != set(items):
|
||||
sys.exit(f"scorer answered {sorted(got)} for {items}:\n{out}")
|
||||
return got
|
||||
|
||||
|
||||
for fx in data["fixtures"]:
|
||||
o = fx["outcome"]
|
||||
if o["kind"] == "lowered":
|
||||
refs = [fx["corpus_item"]] + [r for r in REFS_EXTRA if r != fx["corpus_item"]]
|
||||
o["scores"] = [{"item": k, "target": k == fx["corpus_item"], **v} for k, v in score(o["text"], refs).items()]
|
||||
|
||||
data["corpus"] = corpus
|
||||
data["build"] = {
|
||||
"commit": run(["git", "rev-parse", "HEAD"]).strip(),
|
||||
"embedder": model,
|
||||
"built_unix": int(time.time()),
|
||||
}
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
# -- 3. the page --------------------------------------------------------------
|
||||
CSS = """
|
||||
:root{--ink:#1c1b19;--mute:#5d5a54;--line:#cfc9bd;--bg:#f6f3ec;--card:#fff;--ok:#0b6b4b;--warn:#9a4a00;--bad:#9b1c2c;--bar:#365f9c}
|
||||
*{box-sizing:border-box}body{font:16px/1.55 system-ui,sans-serif;max-width:62rem;margin:2rem auto;padding:0 1rem;color:var(--ink);background:var(--bg)}
|
||||
h1{margin:0 0 .2rem}h2{margin:0 0 .4rem}h3{margin:1.2rem 0 .3rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:var(--mute)}
|
||||
code,.mono{font:13px/1.4 ui-monospace,Menlo,monospace}code{background:#ece8dd;padding:0 .25rem;border-radius:3px}
|
||||
.lede{max-width:46rem}.meta{color:var(--mute);font-size:.88rem}
|
||||
nav.pick{display:flex;flex-wrap:wrap;gap:.4rem;margin:1.2rem 0}
|
||||
nav.pick a{border:1px solid var(--line);background:var(--card);padding:.25rem .6rem;border-radius:999px;text-decoration:none;color:var(--ink);font-size:.9rem}
|
||||
nav.pick a.refused{border-color:var(--bad)}nav.pick a.lowered{border-color:var(--ok)}
|
||||
article{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:1rem 1.3rem;margin:1.4rem 0}
|
||||
.chain{display:grid;grid-template-columns:repeat(4,1fr);gap:.6rem;margin:.6rem 0 1rem}
|
||||
.chain div{border:1px solid var(--line);border-radius:6px;padding:.3rem .6rem;font-size:.82rem;color:var(--mute)}
|
||||
.chain b{display:block;color:var(--ink)}
|
||||
table{border-collapse:collapse;width:100%;font-size:.9rem}th,td{text-align:left;padding:.25rem .5rem;border-bottom:1px solid #e6e1d5;vertical-align:top}th{color:var(--mute);font-weight:600}
|
||||
.out{font-size:1.15rem;padding:.6rem .9rem;border-left:4px solid var(--ok);background:#eef6f1}
|
||||
.refusal{padding:.6rem .9rem;border-left:4px solid var(--bad);background:#faeef0}.refusal b{color:var(--bad)}
|
||||
.tag{display:inline-block;font-size:.75rem;padding:0 .4rem;border-radius:3px;border:1px solid var(--line);color:var(--mute)}
|
||||
.tag.read{border-color:var(--ok);color:var(--ok)}.tag.unread{border-color:var(--warn);color:var(--warn)}.tag.refuse{border-color:var(--bad);color:var(--bad)}
|
||||
.bar{height:.7rem;background:#e4dfd2;border-radius:3px;min-width:8rem;position:relative}.bar i{display:block;height:100%;background:var(--bar);border-radius:3px}
|
||||
.ref{font-size:.88rem;color:var(--mute);margin:.2rem 0 .6rem}.ref q{color:var(--ink)}
|
||||
details{margin:.5rem 0}summary{cursor:pointer;color:var(--mute);font-size:.88rem}
|
||||
section.gaps li{margin:.3rem 0}
|
||||
@media(max-width:700px){.chain{grid-template-columns:1fr 1fr}}
|
||||
"""
|
||||
|
||||
PICK_JS = """(function(){var a=[].slice.call(document.querySelectorAll('article[data-fx]'));function show(){var h=location.hash.slice(1);var any=a.some(function(x){return x.id===h});a.forEach(function(x){x.hidden=any&&x.id!==h})}
|
||||
window.addEventListener('hashchange',show);show()})()"""
|
||||
|
||||
|
||||
def g(chosen, i):
|
||||
return next((c["gloss"] for c in chosen if c["id"] == i), "?")
|
||||
|
||||
|
||||
def val(v):
|
||||
(k, x), = v.items()
|
||||
return f"{x}‰" if k == "Grade" else str(x)
|
||||
|
||||
|
||||
def slots_html(fx):
|
||||
s, ch = fx["slots"], fx["chosen"]
|
||||
rows = []
|
||||
for r in s["meaning"]["referents"]:
|
||||
ent = f" · entity <code>{e(r['entity'])}</code>" if r["entity"] else ""
|
||||
rows.append(f"<tr><td><code>{e(r['id'])}</code></td><td>referent</td><td>{e(g(ch, r['kind']))} / {e(g(ch, r['concept']))}{ent}</td></tr>")
|
||||
for p in s["meaning"]["predications"]:
|
||||
roles = ", ".join(f"{e(g(ch, x['role']))}=<code>{e(x['filler'])}</code>" for x in p["roles"])
|
||||
rows.append(f"<tr><td><code>{e(p['id'])}</code></td><td>predication</td><td>{e(g(ch, p['concept']))} in frame {e(g(ch, p['frame']))}: {roles}</td></tr>")
|
||||
for r in s["meaning"]["relations"]:
|
||||
rows.append(f"<tr><td></td><td>relation</td><td>{e(g(ch, r['relation']))}: <code>{e(r['from'])}</code> → <code>{e(r['to'])}</code></td></tr>")
|
||||
meaning = "<table><tr><th>node</th><th>kind</th><th>content</th></tr>" + "".join(rows) + "</table>"
|
||||
d = s["discourse"]
|
||||
drows = []
|
||||
if d["speech_act"]:
|
||||
drows.append(f"<tr><td>speech act</td><td>{e(g(ch, d['speech_act']))}</td></tr>")
|
||||
if d["addressee"]:
|
||||
drows.append(f"<tr><td>addressee</td><td><code>{e(d['addressee'])}</code></td></tr>")
|
||||
if d["addressee_consent"]:
|
||||
drows.append(f"<tr><td>addressee consent</td><td>predication <code>{e(d['addressee_consent'])}</code> (what the addressee asked for)</td></tr>")
|
||||
drows.append(f"<tr><td>source</td><td>{e(s['provenance']['source'])}, kind {e(s['kind'])}</td></tr>")
|
||||
return (f"<h3>Slot: meaning</h3>{meaning}<h3>Slot: discourse</h3><table>{''.join(drows)}</table>"
|
||||
+ stance_register(fx))
|
||||
|
||||
|
||||
def stance_register(fx):
|
||||
s = fx["slots"]
|
||||
eff = fx["outcome"].get("feature_effects") or []
|
||||
rows = []
|
||||
for i, f in enumerate(s["features"]):
|
||||
note = eff[i] if i < len(eff) else ""
|
||||
cls = "read" if "read it" in note else "unread" if "did not read" in note else "refuse" if "refus" in note else ""
|
||||
rows.append(f"<tr><td>{e(f['gloss'])} <span class='meta'>{e(f['id'])}</span></td><td>{e(f['slot'])} @ {e(f['at'])}</td><td>{e(val(f['value']))}</td><td><span class='tag {cls}'>{e(note)}</span></td></tr>")
|
||||
feats = ("<table><tr><th>feature</th><th>slot</th><th>value</th><th>measured effect on the lowerer</th></tr>" + "".join(rows) + "</table>") if rows else "<p class='meta'>No features: no hedge, certainty, polarity, irony or stance set.</p>"
|
||||
return ("<h3>Slot: stance, hedge, certainty, restraint (features)</h3>" + feats
|
||||
+ "<p class='meta'>Register: the packet has no register slot. Register and address belong to a target-language profile, not to the packet; this lowerer reads none.</p>")
|
||||
|
||||
|
||||
def outcome_html(fx):
|
||||
o = fx["outcome"]
|
||||
if o["kind"] == "lowered":
|
||||
ipa = o["ipa"]
|
||||
ipa_s = ("IPA of cited entities: <span class='mono'>" + e(" ".join(ipa["ok"])) + "</span>") if "ok" in ipa else f"IPA refused: {e(ipa['error']['reason'])} <code>{e(ipa['error']['variant'])}</code>"
|
||||
sc = []
|
||||
for s in o["scores"]:
|
||||
ref = corpus[s["item"]]["text"]
|
||||
sc.append(f"<div class='ref'>{'Target' if s['target'] else 'Other reference'} <code>{e(s['item'])}</code>: <q>{e(ref)}</q></div>"
|
||||
f"<table><tr><td width=110>chrF {s['chrf']:.1f}</td><td><div class='bar'><i style='width:{min(s['chrf'],100):.0f}%'></i></div></td>"
|
||||
f"<td width=150>meaning cosine {s['meaning']:.3f}</td><td><div class='bar'><i style='width:{max(s['meaning'],0)*100:.0f}%'></i></div></td></tr></table>")
|
||||
return (f"<h3>Lowered English</h3><div class='out'>{e(o['text'])}</div><p class='meta'>{ipa_s}</p>"
|
||||
f"<h3>Closeness to the corpus ({e(data['build']['embedder'])})</h3>{''.join(sc)}")
|
||||
if o["kind"] == "lower_error":
|
||||
er = o["error"]
|
||||
return f"<h3>Refused by the lowerer</h3><div class='refusal'><b>LowerError::{e(er['variant'])}</b>: {e(er['reason'])}</div><p class='meta'>No text, so no score: nothing was invented to score.</p>"
|
||||
items = "".join(f"<li><b>{e(r['rule'])}</b> <span class='mono'>{e(r['detail'])}</span></li>" for r in o["refusals"])
|
||||
return f"<h3>Refused at admission</h3><div class='refusal'><ul>{items}</ul></div><p class='meta'>The packet never became a lowering input, so the lowerer never saw it.</p>"
|
||||
|
||||
|
||||
def card(fx):
|
||||
o = fx["outcome"]
|
||||
ch = "".join(f"<tr><td><code>{e(c['id'])}</code></td><td>{e(c['gloss'] or '(unresolved)')}</td></tr>" for c in fx["chosen"])
|
||||
steps = [("1 Typed slots", "meaning, stance, discourse"), ("2 Inventory entries", f"{len(fx['chosen'])} ids, rev {fx['slots']['inventory_rev']}"),
|
||||
("3 Lowered English", {"lowered": "text", "lower_error": "refused", "admission_refused": "never reached"}[o["kind"]]),
|
||||
("4 Closeness", "scored" if o["kind"] == "lowered" else "no text, no score")]
|
||||
chain = "".join(f"<div><b>{e(a)}</b>{e(b)}</div>" for a, b in steps)
|
||||
return (f"<article id='{e(fx['id'])}' data-fx><h2>{e(fx['title'])}</h2><p>{e(fx['note'])}</p>"
|
||||
f"<p class='meta'>Packet <code>{e(fx['packet_id'])}</code> for <code>{e(fx['corpus_item'])}</code>. Made from: {e(fx['source'])}.</p>"
|
||||
f"<div class='chain'>{chain}</div>{slots_html(fx)}"
|
||||
f"<details><summary>Inventory entries chosen ({len(fx['chosen'])})</summary><table><tr><th>id</th><th>gloss at this revision</th></tr>{ch}</table></details>"
|
||||
f"{outcome_html(fx)}</article>")
|
||||
|
||||
|
||||
nav = "".join(f"<a class='{'lowered' if f['outcome']['kind']=='lowered' else 'refused'}' href='#{e(f['id'])}'>{e(f['title'])}</a>" for f in data["fixtures"])
|
||||
b = data["build"]
|
||||
page = f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Weksa: show her working</title><style>{CSS}</style></head><body>
|
||||
<h1>Show her working</h1>
|
||||
<p class="lede">A meaning packet goes in. The English lowerer picks inventory entries, writes a sentence, and a scorer measures how close that sentence is to a human-written target. Every number and sentence below was produced by running the real Rust lowerer and scorer when this page was built. The refusals are results too: when the lowerer cannot say a meaning without changing it, it says so instead of dropping the part it cannot say.</p>
|
||||
<p class="meta">Built from <code>{e(b['commit'][:10])}</code>, embedder <code>{e(b['embedder'])}</code>. English only. Fixtures are the committed <code>nibu-proof-001</code> packet and variants of it, each variant described in its own card. Scores are against the committed corpus: chrF (0-100) and embedding cosine. Raw data: <a href="data.json">data.json</a>.</p>
|
||||
<nav class="pick">{nav}</nav>
|
||||
{''.join(card(f) for f in data['fixtures'])}
|
||||
<script>{PICK_JS}</script></body></html>"""
|
||||
(out_dir / "index.html").write_text(page, encoding="utf-8")
|
||||
print(f"wrote {out_dir}/index.html and data.json ({len(data['fixtures'])} fixtures)")
|
||||
Loading…
Reference in a new issue