ModelPort and AnswerFiles; the encode prompt lists the live inventory and has a digest

The encoder's instructions are written, Prompt::encode takes the run inventory
and revision, and Prompt::digest names a prompt for AnswerFiles: a prompt with
no answer file is written to <digest>.prompt and nothing else happens.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Weksa 2026-11-10 03:47:24 +00:00
commit 77d8b13952
5 changed files with 321 additions and 21 deletions

View file

@ -15,16 +15,30 @@
use std::marker::PhantomData;
use crate::corpus::CorpusItem;
use crate::inventory::{Inventory, InventoryEntry, OptionLabel, ValueKind};
use crate::packet::EntityId;
use crate::split::{Checkpoint, Split, SplitScheme};
use crate::split::{Checkpoint, Split, SplitScheme, fnv1a64, hex16};
use crate::store::{CorpusStore, normalized};
/// The instructions a mint prompt starts with. golf-loop-en edits the wording
/// here.
pub const MINT_INSTRUCTIONS: &str = "Mint glosses from the lines below.";
/// The instructions an encode prompt starts with.
pub const ENCODE_INSTRUCTIONS: &str = "Encode the line below.";
/// The instructions an encode prompt starts with: the encoder's whole brief.
/// Fixed per run by `PROMPT_SOURCE_DIGEST`.
pub const ENCODE_INSTRUCTIONS: &str = "\
Encode the line below as one packet draft, the meaning of the line and nothing else.
Answer with one JSON object and nothing else: no code fence, no commentary.
Fields:
- confidence: 0 to 1000.
- context: {setting, medium, participants, audience}; setting and medium are concept ids or null, participants and audience are lists of node ids.
- discourse: {speech_act, addressee, addressee_consent, features}; speech_act is a speech_act id, addressee a node id or null, addressee_consent always null.
- referents: a list of {id, kind, concept, entity, features}; kind is a referent_kind id, concept a concept id, entity an entity id from the entities line or null.
- 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. 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 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
@ -124,9 +138,9 @@ pub enum OfferRefusal {
/// use weksa::context::{EncoderOffer, TrainItems};
/// use weksa::split::Checkpoint;
/// use weksa::{CorpusItem, score::TestReadings};
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems) {
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems, inv: &weksa::Inventory) {
/// if let Ok(o) = EncoderOffer::for_checkpoint(i, &mut c) {
/// let _ = weksa::context::Prompt::encode(&o, t);
/// let _ = weksa::context::Prompt::encode(&o, t, inv, 1);
/// }
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
/// }
@ -136,10 +150,10 @@ pub enum OfferRefusal {
/// use weksa::context::{EncoderOffer, TrainItems};
/// use weksa::split::Checkpoint;
/// use weksa::{CorpusItem, score::TestReadings};
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems) {
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems, inv: &weksa::Inventory) {
/// let o = EncoderOffer::for_checkpoint(i, &mut c).unwrap();
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
/// let _ = weksa::context::Prompt::encode(&o, t);
/// let _ = weksa::context::Prompt::encode(&o, t, inv, 1);
/// }
/// ```
pub struct EncoderOffer<'cp> {
@ -263,6 +277,32 @@ fn block(item: &CorpusItem, prior: Option<&TrainItems>) -> String {
lines.join("\n")
}
/// One inventory line: the id and gloss, and for a feature or extension its
/// value kind (with the labels of an options feature) and the slots it sits in.
fn entry_line(entry: &InventoryEntry) -> String {
let mut line = format!("{}: {}", entry.id, entry.gloss);
let kind = entry.value_kind.as_ref().map(|kind| match kind {
ValueKind::Grade => "grade".to_string(),
ValueKind::Flag => "flag".to_string(),
ValueKind::Options(set) => {
let labels: Vec<String> = Vec::<OptionLabel>::from(set.clone())
.iter()
.map(OptionLabel::to_string)
.collect();
format!("options {}", labels.join("|"))
}
});
if let Some(kind) = kind {
let slots: Vec<String> = entry.applies_to.iter().map(|s| format!("{s:?}")).collect();
line.push_str(&format!(" [{kind}"));
if !slots.is_empty() {
line.push_str(&format!("; slots {}", slots.join(",")));
}
line.push(']');
}
line
}
/// Printed in place of a prior turn whose text no live Train item holds.
const ELIDED: &str = "[elided]";
@ -278,19 +318,36 @@ impl Prompt {
}
/// [`ENCODE_INSTRUCTIONS`], the one offered item with its prior turns resolved
/// against `train`, and the entities a packet for it may cite.
pub fn encode(offer: &EncoderOffer, train: &TrainItems) -> Prompt {
/// against `train`, the entities a packet for it may cite, and the entries
/// of `inventory` live at `rev`.
pub fn encode(
offer: &EncoderOffer,
train: &TrainItems,
inventory: &Inventory,
rev: u32,
) -> Prompt {
let ids: Vec<&str> = offer.entities.iter().map(EntityId::as_str).collect();
let mut text = format!(
"{ENCODE_INSTRUCTIONS}\n\n{}\n\nentities: {}\n\ninventory rev:{rev}",
block(&offer.item, Some(train)),
ids.join(", ")
);
for entry in inventory.entries().filter(|e| e.live_at(rev)) {
text.push('\n');
text.push_str(&entry_line(entry));
}
Prompt {
text: format!(
"{ENCODE_INSTRUCTIONS}\n\n{}\n\nentities: {}",
block(&offer.item, Some(train)),
ids.join(", ")
),
text,
items: vec![offer.item.id.clone()],
}
}
/// 16 lowercase hex digits of FNV-1a 64 of the text: the name of the prompt
/// in files and records.
pub fn digest(&self) -> String {
hex16(fnv1a64(self.text.as_bytes()))
}
pub fn text(&self) -> &str {
&self.text
}

View file

@ -10,6 +10,7 @@ pub mod entity;
pub mod form;
pub mod inventory;
pub mod lower;
pub mod model;
pub mod packet;
pub mod phones;
pub mod run;

78
crates/weksa/src/model.rs Normal file
View file

@ -0,0 +1,78 @@
//! The loop's only door to a model. A model is the Claude session: it reads a
//! prompt file and writes an answer file, and a rerun picks the answer up. No
//! subprocess, network or binary lives here (golf-loop-in-claude).
use std::fmt;
use std::io::ErrorKind;
use std::path::PathBuf;
use crate::context::Prompt;
/// A model answering [`Prompt`]s and nothing else.
pub trait ModelPort {
/// The id of the answering model, pinned by the run.
fn model(&self) -> &str;
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError>;
}
/// Why a prompt got no answer. Display names the kind only.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PortError {
/// Nobody has answered yet.
Unanswered,
Io(ErrorKind),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Unanswered => f.write_str("the prompt is unanswered"),
PortError::Io(kind) => write!(f, "io error {kind:?}"),
}
}
}
impl std::error::Error for PortError {}
/// Answers from files in one directory: `<digest>.answer` is the reply to the
/// prompt whose digest is `<digest>`; a prompt with no answer is written to
/// `<digest>.prompt` for whoever answers.
pub struct AnswerFiles {
dir: PathBuf,
model: String,
}
impl AnswerFiles {
pub fn new(dir: PathBuf, model: String) -> Self {
Self { dir, model }
}
}
impl ModelPort for AnswerFiles {
fn model(&self) -> &str {
&self.model
}
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError> {
let io = |e: std::io::Error| PortError::Io(e.kind());
let digest = prompt.digest();
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"));
match std::fs::read(&path) {
Ok(held) if held == prompt.text().as_bytes() => {}
Ok(_) => return Err(PortError::Io(ErrorKind::AlreadyExists)),
Err(e) if e.kind() == ErrorKind::NotFound => {
std::fs::write(&path, prompt.text()).map_err(io)?
}
Err(e) => return Err(io(e)),
}
Err(PortError::Unanswered)
}
}

View file

@ -158,11 +158,17 @@ fn prompts_render_deterministically() {
assert_eq!(Prompt::mint(&t).item_keys(), ["item:a:1", "item:a:2"]);
let offer = run.offer("item:a:2").unwrap().unwrap();
let inv = run.inventory().inventory().unwrap();
assert_eq!(
Prompt::encode(&offer, &t).text(),
format!("{ENCODE}\n\n[item:a:2] entity:nibu: Second line.\n\nentities: entity:nibu")
Prompt::encode(&offer, &t, &inv, 0).text(),
format!(
"{ENCODE}\n\n[item:a:2] entity:nibu: Second line.\n\nentities: entity:nibu\n\ninventory rev:0"
)
);
assert_eq!(
Prompt::encode(&offer, &t, &inv, 0).item_keys(),
["item:a:2"]
);
assert_eq!(Prompt::encode(&offer, &t).item_keys(), ["item:a:2"]);
}
#[test]
@ -261,10 +267,11 @@ fn encoder_offer_entities_are_the_items_own() {
"a sibling's entity is not the item's"
);
assert_eq!(offer.key(), "item:a:1");
let p = Prompt::encode(&offer, &t);
let inv = c.run.inventory().inventory().unwrap();
let p = Prompt::encode(&offer, &t, &inv, 0);
assert!(
p.text()
.ends_with("entities: entity:brokkr, entity:hero, entity:kay")
.ends_with("entities: entity:brokkr, entity:hero, entity:kay\n\ninventory rev:0")
);
assert!(p.text().contains("[item:a:1]"));
assert!(!p.text().contains("item:a:2") && !p.text().contains("Someone waits"));
@ -377,8 +384,9 @@ fn prior_turns_print_only_text_a_live_train_item_holds() {
"mint prints no prior turns"
);
let inv = run.inventory().inventory().unwrap();
let encode = |key: &str| {
Prompt::encode(&run.offer(key).unwrap().unwrap(), &t)
Prompt::encode(&run.offer(key).unwrap().unwrap(), &t, &inv, 0)
.text()
.to_string()
};
@ -417,7 +425,8 @@ fn encode_with_prior(train_text: &str, prior_text: &str) -> (String, Result<(),
store.add(reply.clone(), &entities).unwrap();
let run = run_over(dir.path());
let t = run.train().unwrap();
let p = Prompt::encode(&run.offer("item:a:2").unwrap().unwrap(), &t);
let inv = run.inventory().inventory().unwrap();
let p = Prompt::encode(&run.offer("item:a:2").unwrap().unwrap(), &t, &inv, 0);
let text = p.text().to_string();
// The store's own rule, as the oracle for key equality; after the prompt is
// built, because an admitted probe would itself become a held line.

View file

@ -143,3 +143,158 @@ fn source_digests_cover_their_files() {
weksa::run::LOWERER_SOURCE_DIGEST
);
}
/// The encode prompt of `item:nibu:1` over `world()` at revision 4.
fn prompt() -> weksa::context::Prompt {
let w = world();
let run = run_over(w.dir.path());
let inv = run.inventory().inventory().unwrap();
weksa::context::Prompt::encode(
&run.offer("item:nibu:1").unwrap().unwrap(),
&run.train().unwrap(),
&inv,
4,
)
}
#[test]
fn encode_prompt_lists_the_live_inventory() {
let w = world();
let run = run_over(w.dir.path());
let inv = run.inventory().inventory().unwrap();
let train = run.train().unwrap();
let offer = run.offer("item:nibu:1").unwrap().unwrap();
let at = |rev| weksa::context::Prompt::encode(&offer, &train, &inv, rev);
let listed = |text: &str| -> Vec<String> {
let (_, tail) = text.split_once("\n\ninventory rev:").unwrap();
tail.lines().skip(1).map(str::to_string).collect()
};
let ids = |lines: &[String]| -> Vec<String> {
lines
.iter()
.map(|l| l.split(':').take(2).collect::<Vec<_>>().join(":"))
.collect()
};
let p4 = at(4);
assert!(p4.text().contains("\n\ninventory rev:4\n"));
let lines4 = listed(p4.text());
let live4: Vec<String> = inv
.entries()
.filter(|e| e.live_at(4))
.map(|e| e.id.to_string())
.collect();
assert_eq!(ids(&lines4), live4, "every live entry, in id order");
assert!(live4.contains(&common::CONCEPT_LATE.to_string()));
assert!(
!live4.contains(&common::CONCEPT_RETIRED.to_string()),
"retired at 3"
);
let ids2 = ids(&listed(at(2).text()));
assert!(
ids2.contains(&common::CONCEPT_RETIRED.to_string()),
"live at 2"
);
assert!(
!ids2.contains(&common::CONCEPT_LATE.to_string()),
"not yet introduced"
);
// A line carries the gloss; a feature its kind and slots, an options feature its labels.
let line = |id: &str| {
lines4
.iter()
.find(|l| l.starts_with(&format!("{id}: ")))
.unwrap()
.clone()
};
assert_eq!(
line(common::CONCEPT_A),
format!("{}: {}", common::CONCEPT_A, common::CONCEPT_A)
);
assert!(
line(common::HEDGE).contains("[grade; slots "),
"{}",
line(common::HEDGE)
);
assert!(
line(common::MODALITY).contains("[options "),
"{}",
line(common::MODALITY)
);
assert!(
line(common::MODALITY).contains("potential"),
"{}",
line(common::MODALITY)
);
assert!(
line(common::EXT).ends_with("[grade]"),
"an extension has a kind and no slots: {}",
line(common::EXT)
);
assert!(
at(4)
.text()
.starts_with(weksa::context::ENCODE_INSTRUCTIONS)
);
assert_eq!(at(4).digest().len(), 16);
assert_eq!(at(4).digest(), p4.digest());
assert_ne!(at(4).digest(), at(2).digest());
assert_eq!(
p4.digest(),
format!("{:016x}", fnv1a64(p4.text().as_bytes()))
);
}
#[test]
fn answer_files_write_the_prompt_and_read_the_answer() {
use std::io::ErrorKind;
use weksa::model::{AnswerFiles, ModelPort, PortError};
let p = prompt();
let dir = tempfile::tempdir().unwrap();
let round = dir.path().join("round-1");
let mut files = AnswerFiles::new(round.clone(), "answerer".into());
assert_eq!(files.model(), "answerer");
// No answer: the prompt is written under its digest, and nothing else.
assert_eq!(files.answer(&p), Err(PortError::Unanswered));
let prompt_file = round.join(format!("{}.prompt", p.digest()));
assert_eq!(std::fs::read_to_string(&prompt_file).unwrap(), p.text());
assert_eq!(std::fs::read_dir(&round).unwrap().count(), 1);
// Asking again leaves the equal file alone.
let before = std::fs::metadata(&prompt_file).unwrap().modified().unwrap();
assert_eq!(files.answer(&p), Err(PortError::Unanswered));
assert_eq!(
std::fs::metadata(&prompt_file).unwrap().modified().unwrap(),
before
);
// A different file under the digest is refused, not overwritten.
std::fs::write(&prompt_file, "other").unwrap();
assert_eq!(
files.answer(&p),
Err(PortError::Io(ErrorKind::AlreadyExists))
);
assert_eq!(std::fs::read_to_string(&prompt_file).unwrap(), "other");
// The answer is read as it was written, whitespace and all.
let answer = round.join(format!("{}.answer", p.digest()));
std::fs::write(&answer, " {\"x\": 1}\n").unwrap();
assert_eq!(files.answer(&p).unwrap(), " {\"x\": 1}\n");
std::fs::write(&answer, [0xff, 0xfe]).unwrap();
assert_eq!(files.answer(&p), Err(PortError::Io(ErrorKind::InvalidData)));
// A directory that cannot be made is an io error of its kind.
std::fs::write(dir.path().join("file"), "").unwrap();
let mut blocked = AnswerFiles::new(dir.path().join("file").join("round"), "m".into());
assert!(matches!(blocked.answer(&p), Err(PortError::Io(_))));
assert_eq!(
PortError::Unanswered.to_string(),
"the prompt is unanswered"
);
assert_eq!(
PortError::Io(ErrorKind::InvalidData).to_string(),
"io error InvalidData"
);
}