diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index d6832e7..6ec2ce8 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -11,10 +11,11 @@ use weksa::corpus::{CorpusItem, ModelFamily, NameSpan, Source, Turn}; use weksa::entity::{Entity, EntityOrigin, LanguageForms, Pronunciation}; use weksa::inventory::{proof_revision, seed}; use weksa::packet::proof_packet; +use weksa::run::{Outcome, RoundOutcome, RoundRecord, RunPaths, RunStores, round}; use weksa::score::ScoreInput; use weksa::{ - CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore, Scorer, - SplitScheme, StoreError, lower, pronounce, validate, + AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore, + Scorer, SplitScheme, StoreError, lower, pronounce, validate, }; #[derive(Parser)] @@ -66,6 +67,8 @@ enum Command { Score(ScoreArgs), /// Print the split of a corpus item. Split { item_key: String }, + #[command(subcommand)] + Loop(LoopCommand), /// Write the published JSON Schemas. Schema { #[arg(long, default_value = "schemas/cultnet")] @@ -73,6 +76,30 @@ enum Command { }, } +#[derive(Subcommand)] +enum LoopCommand { + /// Pin the global --corpus, --inventory and --entities as a run at ROOT. + Open { + root: PathBuf, + #[arg(long)] + label: String, + /// The id of the model that answers prompts. + #[arg(long)] + answerer: String, + #[arg(long, default_value = "qwen3-embedding:0.6b")] + embed_model: String, + }, + /// Run one round of the run at ROOT. The stores are read only from the + /// run's record: the global --corpus, --inventory and --entities are not + /// read. Prompts without answers are written to the round's directory and + /// the command exits 3; rerun after the `.answer` files exist. + Round { + root: PathBuf, + #[arg(long, default_value = "http://127.0.0.1:11434")] + ollama_url: String, + }, +} + #[derive(Subcommand)] enum PacketCommand { /// Admit the nibu-proof-001 packet through `PacketStore::admit`. @@ -495,6 +522,35 @@ fn refused(e: StoreError) -> anyhow::Error { anyhow::anyhow!("{e}") } +/// `none` for an absent mean. +fn mean_text(value: Option, places: usize) -> String { + value.map_or("none".to_string(), |v| format!("{v:.places$}")) +} + +/// The one line a recorded round prints. +fn round_line(r: &RoundRecord) -> String { + let refused = r + .train() + .iter() + .filter(|row| matches!(row.outcome, Outcome::Refused(_))) + .count(); + let (t, v, x) = (r.train_mean(), r.validation_mean(), r.validation_refused()); + format!( + "round {} rev {} train n={} chrf={} meaning={} refused={refused} validation n={} chrf={} meaning={} refused parse={} admit={} lower={}", + r.n(), + r.inventory_rev(), + t.count, + mean_text(t.chrf, 2), + mean_text(t.meaning, 4), + v.count, + mean_text(v.chrf, 2), + mean_text(v.meaning, 4), + x.parse, + x.admit, + x.lower, + ) +} + fn main() -> Result<()> { let cli = parse_cli(); match cli.command { @@ -692,6 +748,45 @@ fn main() -> Result<()> { .context("no such item")?; println!("{}", split_text(&item)); } + Command::Loop(LoopCommand::Open { + root, + label, + answerer, + embed_model, + }) => { + let run = RunStores::create( + &root, + &label, + RunPaths { + corpus: &cli.corpus, + inventory: &cli.inventory, + entities: &cli.entities, + }, + &answerer, + &embed_model, + )?; + 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 = 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 } => { + for digest in &prompts { + println!("unanswered {digest}"); + } + let asked = run.offers().map_err(unreadable)?.len(); + println!("unanswered {} of {asked}", prompts.len()); + std::process::exit(3); + } + RoundOutcome::Recorded(r) => println!("{}", round_line(&r)), + } + } Command::Schema { out } => { std::fs::create_dir_all(&out)?; for (name, json) in weksa::schema::published() { diff --git a/crates/weksa/tests/cli.rs b/crates/weksa/tests/cli.rs index 1203d78..0fae4df 100644 --- a/crates/weksa/tests/cli.rs +++ b/crates/weksa/tests/cli.rs @@ -1315,3 +1315,145 @@ fn pronunciation_language_is_never_echoed() { ); assert!(!text.to_lowercase().contains("sentinel"), "{text}"); } + +/// Copies of the Dao De Jing stores where `weksa()` looks for them. +fn dao_stores(dir: &std::path::Path) { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing"); + for (from, to) in [ + ("corpus.cc", "c.cc"), + ("inventory.cc", "i.cc"), + ("entity.cc", "e.cc"), + ] { + std::fs::copy(src.join(from), dir.join(to)).unwrap(); + } +} + +#[test] +fn loop_open_and_unanswered_round() { + let d = tempfile::tempdir().unwrap(); + dao_stores(d.path()); + let open = |root: &str| { + weksa( + d.path(), + &[ + "loop", + "open", + root, + "--label", + "smoke", + "--answerer", + "fake-model", + ], + ) + }; + let o = open("canaryroot"); + assert!(o.status.success(), "{}", out(&o)); + assert_eq!(out(&o), "opened run:smoke\n"); + + // A second open fails and names neither the root nor a path. + let again = open("canaryroot"); + assert!(!again.status.success()); + let text = out(&again); + assert!(text.contains("already holds a run"), "{text}"); + for echoed in ["canaryroot", d.path().to_str().unwrap()] { + assert!(!text.contains(echoed), "{text}"); + } + + // Round 1 is unanswered: three digests, a count, exit 3, no round recorded. + let round = || weksa(d.path(), &["loop", "round", "canaryroot"]); + let first = round(); + 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(); + assert_eq!(digests.len(), 3, "{text}"); + assert!(text.ends_with("unanswered 3 of 3\n"), "{text}"); + assert!(!text.contains("canaryroot"), "{text}"); + for digest in &digests { + assert!( + d.path() + .join(format!("canaryroot/round-1/{digest}.prompt")) + .is_file() + ); + } + + // Answers that are not drafts record a round of refusals, with no embed call. + for digest in &digests { + std::fs::write( + d.path().join(format!("canaryroot/round-1/{digest}.answer")), + "not json", + ) + .unwrap(); + } + let second = round(); + assert!(second.status.success(), "{}", out(&second)); + assert_eq!( + out(&second), + "round 1 rev 3 train n=0 chrf=none meaning=none refused=1 validation n=0 chrf=none meaning=none refused parse=2 admit=0 lower=0\n" + ); + + // The global store flags are not read by loop round: a drifted store is refused. + let mut entities = EntityStore::open(&d.path().join("e.cc")).unwrap(); + entities.put(common::ent("kay", "en-US", &["Kay"])).unwrap(); + let drifted = round(); + assert!(!drifted.status.success()); + assert!( + out(&drifted).contains("drift in Entities"), + "{}", + out(&drifted) + ); +} + +#[test] +fn loop_errors_echo_no_input() { + let d = tempfile::tempdir().unwrap(); + dao_stores(d.path()); + let o = weksa(d.path(), &["loop", "round", "canaryroot"]); + assert!(!o.status.success()); + assert!(out(&o).contains("holds no run"), "{}", out(&o)); + for args in [ + vec![ + "loop", + "open", + "canaryroot", + "--label", + "CANARYLABEL", + "--answerer", + "m", + ], + vec![ + "loop", + "open", + "canaryroot", + "--label", + "ok", + "--answerer", + "CANARY\n", + ], + ] { + let o = weksa(d.path(), &args); + assert!(!o.status.success()); + assert!(!out(&o).to_uppercase().contains("CANARY"), "{}", out(&o)); + } + // A store path that does not exist. + let o = Command::new(env!("CARGO_BIN_EXE_weksa")) + .current_dir(d.path()) + .args([ + "--corpus", + "./canarystore.cc", + "loop", + "open", + "canaryroot", + "--label", + "ok", + "--answerer", + "m", + ]) + .output() + .unwrap(); + assert!(!o.status.success()); + assert!(!out(&o).to_uppercase().contains("CANARY"), "{}", out(&o)); +} diff --git a/docs/targets/interlingua-lowering-map.md b/docs/targets/interlingua-lowering-map.md index 0a598ca..a0b3302 100644 --- a/docs/targets/interlingua-lowering-map.md +++ b/docs/targets/interlingua-lowering-map.md @@ -403,8 +403,9 @@ One line per cut; specs exist for the cuts about to run (2d and 4, siblings on ` 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:@`) and `weksa.scene` (`scene:@`, participants and ordered-pair relations) documents with `Annotator` `Operator` and `Model { family, generator }`, validated by the packet's shared feature check, append-only per key; their stores, `weksa speaker` and `weksa scene` commands, published schemas; Model-annotated cast speakers and scenes for the committed items. Waits on 2d and 4; `pd-speaker-annotation` blocks only the public-domain annotator. Part 1 landed (branch `weksa-lowering/speaker-scene`): `speaker.rs`, `SpeakerStateStore`, slots `Speaker` and `Scene` exclusive to their own feature lists, `speaker_scene_revision()` (Speaker features 22-24), `with_scene` on the store, schemas. The CLI, the committed inventory revision 3 and the seeds stay with 4c. 5. `language-ontology`: `weksa.community` from `data/cultural-ontology/` (owns follow-up `edda-referent-yaml-parse`), `weksa.ontology_entry` for en-US and ja-JP from `data/target-language-ontology/` (YAML deleted), speaker communities, deterministic `select`, the lowering view (packet without trace, speaker, scene, selected entries). Waits on 4. 6. `pd-importer`: public-domain play and fiction dialogue into the corpus with speaker, scene group, edition provenance, and Speaker and Scene annotations by the ruled annotator. Waits on 4, follow-up `gutenberg-terms` and question `pd-speaker-annotation`. -7a. `loop-context-builder`: `context.rs` (`TrainItems`, `EncoderOffer`, `Prompt`: corpus text reaches a model call only through `Prompt::mint` over live Train items or `Prompt::encode` over one offered item; instructions are 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. Merges follow-ups `loop-context-builder-2` and `scorer-test-readings-type`. (spec r1) -7. `golf-loop-en`: the loop driver, the template wording in `context.rs` with its digest pinned per run (follow-up `template-digest-in-round-record`), the packet store bound to one inventory store (`packet-store-inventory-binding`), `ModelPort` with the `claude -p` adapter (it takes only `&Prompt`), encoder (packet with stance) and lowerer prompts, round records, Score documents, the composite and accept rule, `weksa score`, the detached unit on Yggdrasil. Waits on 3, 5, 6 and follow-up `claude-on-yggdrasil`. +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 `/run.cc` and refuses drift (corpus, entities, `PROMPT_SOURCE_DIGEST` of `context.rs`, `LOWERER_SOURCE_DIGEST` of `lower.rs`, model, embedder); `round` encodes every live Train and Validation item through a `ModelPort` (`model.rs`; the one adapter `AnswerFiles` writes `.prompt` and reads `.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 `/round-/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. +7. `golf-loop-en` (7b landed its round, `ModelPort`, encoder prompt, template digest and round records; the rest remains): the loop driver, the packet store bound to one inventory store everywhere (`packet-store-inventory-binding`), a subprocess adapter, lowerer prompts, Score documents, the composite and accept rule, `weksa score`, 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. 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`.