lispm-llm / src /workflow_learn.rs
Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified
Raw History Blame Contribute Delete
44.1 kB
//! Poison-resistant continual observation, episodic recall, and quarantine sync. //! //! Basis: Join-semilattice quarantine ledger (`Consistent` | `Conflicted`) paired with //! atomic materialization into fast episodic memory (`episodic.json`) and reconciliation //! into durable trainer examples (`examples.json`). //! Minimality: Raw model self-predictions are unrepresentable; only external oracle //! observations (`BehavioralCorrection` or `Teacher`) enter the semilattice. Promotion //! and training readiness are derived from `(quarantine.json, examples.json, active.json)` //! without redundant boolean flags. //! Tightness: Literal arguments are scrubbed at ingestion into canonical dummy constants //! (`"example"` or `"https://example.org"`), preventing PII persistence while preserving //! exact `parse_command` clause structure. //! Law: `Consistent(a) ⊔ Obs(b) = Conflicted({a, b})` for `a != b`, and `Conflicted` is an //! absorbing top element excluded from both `episodic.json` and `examples.json`. use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use super::io::{ ProjectLock, atomic_bytes, atomic_json, canonical, digest, manifest, project_catalog, read_json, read_run, }; use super::project_info; use super::types::{Activation, ProjectInfo, RunStatus, WorkflowError}; use crate::actions::{Action, ActionKind, ParsedClause, Program, parse_command}; use crate::catalog::{ ActionCatalog, ArgContract, OpenAction, OpenProgram, StringDomain, parse_open_command, }; use crate::dataset::{ Example, ExampleFile, clause_key, frozen_maps, materialize_with_catalog, merge_examples_with_catalog, parse_examples_with_catalog, training_phrase_with_catalog, }; use crate::episodic::EpisodicMemory; /// Verified external supervision source; model self-predictions are unrepresentable. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum OracleSource { /// User cancelled, undid, or received a refusal, then executed a target command. BehavioralCorrection, /// Higher-tier teacher agent resolved an unserved or uncertain instruction. Teacher, } /// Ground-truth supervision supplied by an external oracle for a raw instruction. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum OracleResolution { /// One or two action labels matching the parsed clauses of `instruction` in order. Actions { /// Closed-set action labels (excluding `"reject"`). labels: Vec<String>, }, /// The single-clause instruction requires capabilities outside the 48-action DSL. Reject, } /// One external oracle observation submitted to a workspace. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ObservationInput { /// Raw English instruction entered by the user; literals are scrubbed before storage. pub instruction: String, /// Verified external supervision source. pub source: OracleSource, /// Ground-truth action assignment or rejection. pub resolution: OracleResolution, /// Explicit hard-example flag; defaults to true for corrections/refusals. #[serde(default = "default_hard")] pub hard: bool, } /// Corrections and fallbacks represent model boundary failures by default. const fn default_hard() -> bool { true } /// Monotonic semilattice state for one normalized clause skeleton. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)] pub enum ClauseState { /// Every oracle observation for this clause agreed on a single label. Consistent { /// Privacy-scrubbed canonical single-clause instruction. instruction: String, /// Agreed closed-set label (`ActionKind` label or `"reject"`). label: String, /// Number of agreeing observations recorded. observations: u32, /// Whether hard-example oversampling applies during retraining. hard: bool, }, /// Two or more distinct labels were observed; permanently excluded as ambiguous. Conflicted { /// Distinct labels asserted for this clause skeleton. labels: BTreeSet<String>, /// Total observations recorded across conflicting labels. observations: u32, }, } impl ClauseState { /// Join one new `(label, hard)` observation into this semilattice state. fn join(self, label: String, hard: bool) -> Self { match self { Self::Consistent { instruction, label: existing_label, observations, hard: existing_hard, } => { if existing_label == label { Self::Consistent { instruction, label: existing_label, observations: observations.saturating_add(1), hard: existing_hard || hard, } } else { Self::Conflicted { labels: BTreeSet::from([existing_label, label]), observations: observations.saturating_add(1), } } } Self::Conflicted { mut labels, observations, } => { labels.insert(label); Self::Conflicted { labels, observations: observations.saturating_add(1), } } } } } /// Persisted quarantine state stored at `<project>/quarantine.json`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct QuarantineLedger { /// Schema version, currently one. format_version: u32, /// Map from canonical normalized clause key to monotonic `ClauseState`. clauses: BTreeMap<String, ClauseState>, /// Count of observations skipped because they matched held-out calibration/benchmarks. withheld_skipped: u64, /// Count of observations skipped because they contradicted frozen base training rows. frozen_conflicts: u64, } impl Default for QuarantineLedger { fn default() -> Self { Self { format_version: 1, clauses: BTreeMap::new(), withheld_skipped: 0, frozen_conflicts: 0, } } } /// Per-clause outcome produced when ingesting an `ObservationInput`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ClauseDisposition { /// Clause is consistent and active in fast episodic memory. Recorded, /// Clause contradicted an earlier observation, sibling clause, or manual example. Conflicted, /// Clause matched a held-out calibration, benchmark, or task-suite sentence. Withheld, /// Clause already exists in the frozen shared training set with the same label. AlreadyKnown, /// Clause contradicted the frozen shared training set and was ignored. FrozenConflict, /// Syntax, clause count, or argument arity did not match a single valid observation. SkippedSyntax, } /// Summary of continual-learning state derived from project files. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LearnStatus { /// Canonical project path. pub project: PathBuf, /// Absolute path to `<project>/episodic.json` for fast session binding. pub episodic_file: PathBuf, /// Optional `<project>/catalog.json` when backed by an open bi-encoder workspace. #[serde(default, skip_serializing_if = "Option::is_none")] pub catalog_file: Option<PathBuf>, /// Number of unambiguous clauses tracked in quarantine. pub consistent_count: usize, /// Number of unsynchronized additions, hard upgrades, or conflict expungements vs `examples.json`. pub pending_sync_count: usize, /// Total examples not yet consolidated into the active model (including synced-but-untrained). pub unconsolidated_count: usize, /// Whether the current materialized generation already failed a non-cancelled run. pub generation_exhausted: bool, /// Number of ambiguous clauses permanently quarantined. pub conflicted_count: usize, /// Number of active entries in `episodic.json`. pub episodic_count: usize, /// Total observations skipped to protect held-out benchmarks/calibration. pub withheld_skipped: u64, /// Total observations rejected due to contradicting frozen base rows. pub frozen_conflicts: u64, } /// Result of recording one external oracle observation. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ObserveReport { /// Ordered final disposition for each inspected clause. pub dispositions: Vec<ClauseDisposition>, /// Updated workspace learning summary. pub status: LearnStatus, } /// Result of synchronizing clean quarantine supervision into `examples.json`. #[derive(Debug, Serialize)] pub struct SyncReport { /// Updated project snapshot after reconciling `examples.json`. pub project_info: ProjectInfo, /// Updated continual-learning ledger counters. pub status: LearnStatus, /// Number of consistent examples newly added or upgraded in `examples.json`. pub synced_examples: usize, /// Number of conflicted examples expunged from `examples.json`. pub expunged_conflicts: usize, } /// Load `<project>/quarantine.json` or return an empty ledger if not yet created. fn load_ledger(project: &Path) -> Result<QuarantineLedger, WorkflowError> { let path = project.join("quarantine.json"); if !path.exists() { return Ok(QuarantineLedger::default()); } let ledger: QuarantineLedger = read_json(&path)?; if ledger.format_version != 1 { return Err(WorkflowError::Invalid("unsupported quarantine format_version")); } Ok(ledger) } /// Materialize all consistent clauses into `<project>/episodic.json` atomically. fn write_episodic( project: &Path, ledger: &QuarantineLedger, catalog: Option<&ActionCatalog>, ) -> Result<EpisodicMemory, WorkflowError> { let mut entries = BTreeMap::new(); for (key, state) in &ledger.clauses { if let ClauseState::Consistent { label, .. } = state { entries.insert(key.clone(), label.clone()); } } let memory = EpisodicMemory::new_with_catalog(entries, catalog)?; atomic_json(&project.join("episodic.json"), &memory)?; Ok(memory) } /// Map current `examples.json` entries by canonical clause key to `(label, hard)`. fn authored_map( authored: &ExampleFile, catalog: Option<&ActionCatalog>, ) -> Result<BTreeMap<String, (String, bool)>, WorkflowError> { let mut map = BTreeMap::new(); for example in &authored.examples { let key = clause_key(&training_phrase_with_catalog(example, catalog)?)?; map.insert(key, (example.label.clone(), example.hard)); } Ok(map) } /// Compute active generation and whether `current_gen` already had a terminal failure/ineligible run. fn inspect_consolidation_runs( project: &Path, current_gen: &str, authored_map: &BTreeMap<String, (String, bool)>, catalog: Option<&ActionCatalog>, ) -> Result<(usize, bool), WorkflowError> { let active_keys: BTreeSet<String> = if project.join("active.json").is_file() { let active: Activation = read_json(&project.join("active.json"))?; if active.current.run == "baseline" { BTreeSet::new() } else { let run_dir = project.join("runs").join(&active.current.run); let run_cat = if run_dir.join("catalog.json").is_file() { Some(ActionCatalog::load_or_builtin(&run_dir.join("catalog.json"))?) } else { catalog.cloned() }; let active_examples = parse_examples_with_catalog( &fs::read(run_dir.join("examples.json"))?, run_cat.as_ref(), )?; authored_map_keys(&active_examples, run_cat.as_ref())? } } else { BTreeSet::new() }; let mut generation_exhausted = false; if project.join("runs").is_dir() { for entry in fs::read_dir(project.join("runs"))? { let entry = entry?; if entry.file_type()?.is_dir() && entry.path().join("run.json").is_file() { let id = entry .file_name() .into_string() .map_err(|_| WorkflowError::Invalid("non-Unicode run id"))?; let run = read_run(project, &id)?; if run.generation == current_gen { match run.status { RunStatus::Failed => generation_exhausted = true, RunStatus::Benchmarked => { let report_path = project.join("runs").join(&id).join("benchmark.json"); if report_path.is_file() { let bench: super::types::BenchmarkInfo = read_json(&report_path)?; if !bench.eligible { generation_exhausted = true; } } } _ => {} } } } } } let current_keys: BTreeSet<String> = authored_map.keys().cloned().collect(); let symmetric_diff = current_keys.symmetric_difference(&active_keys).count(); Ok((symmetric_diff, generation_exhausted)) } /// Extract canonical clause keys from an `ExampleFile`. fn authored_map_keys( examples: &ExampleFile, catalog: Option<&ActionCatalog>, ) -> Result<BTreeSet<String>, WorkflowError> { let mut keys = BTreeSet::new(); for example in &examples.examples { keys.insert(clause_key(&training_phrase_with_catalog(example, catalog)?)?); } Ok(keys) } /// Derive exact synchronization and consolidation counters from `(project, ledger, episodic)`. fn compute_status( project: &Path, ledger: &QuarantineLedger, episodic_count: usize, catalog: Option<&ActionCatalog>, ) -> Result<LearnStatus, WorkflowError> { let examples_bytes = fs::read(project.join("examples.json"))?; let current_gen = digest(&examples_bytes); let authored = authored_map(&parse_examples_with_catalog(&examples_bytes, catalog)?, catalog)?; let mut consistent_count = 0_usize; let mut pending_sync_count = 0_usize; let mut conflicted_count = 0_usize; for (key, state) in &ledger.clauses { match state { ClauseState::Consistent { label, hard, .. } => { consistent_count += 1; let synced = authored .get(key) .is_some_and(|(auth_label, auth_hard)| auth_label == label && (*auth_hard || !hard)); if !synced { pending_sync_count += 1; } } ClauseState::Conflicted { .. } => { conflicted_count += 1; if authored.contains_key(key) { pending_sync_count += 1; } } } } let (unconsolidated_synced, generation_exhausted) = inspect_consolidation_runs(project, &current_gen, &authored, catalog)?; let unconsolidated_count = pending_sync_count.saturating_add(unconsolidated_synced); Ok(LearnStatus { project: project.to_path_buf(), episodic_file: project.join("episodic.json"), catalog_file: catalog.map(|_| project.join("catalog.json")), consistent_count, pending_sync_count, unconsolidated_count, generation_exhausted: pending_sync_count == 0 && generation_exhausted, conflicted_count, episodic_count, withheld_skipped: ledger.withheld_skipped, frozen_conflicts: ledger.frozen_conflicts, }) } /// Reconcile `quarantine.json` and `episodic.json` when `examples.json` is manually updated. pub(super) fn reconcile_manual_examples( project: &Path, merged: &ExampleFile, replaced: bool, ) -> Result<(), WorkflowError> { if !project.join("quarantine.json").exists() { return Ok(()); } let catalog = project_catalog(project)?; let cat_ref = catalog.as_ref(); let mut ledger = load_ledger(project)?; let manual = authored_map(merged, cat_ref)?; if replaced { let mut retained = BTreeMap::new(); for (key, state) in ledger.clauses { match state { ClauseState::Consistent { instruction, observations, .. } => { if let Some((new_label, new_hard)) = manual.get(&key) { retained.insert( key, ClauseState::Consistent { instruction, label: new_label.clone(), observations, hard: *new_hard, }, ); } } ClauseState::Conflicted { labels, observations, } => { if let Some((new_label, new_hard)) = manual.get(&key) { if let Some(example) = merged.examples.iter().find(|ex| { training_phrase_with_catalog(ex, cat_ref) .ok() .and_then(|p| clause_key(&p).ok()) .as_deref() == Some(key.as_str()) }) { retained.insert( key, ClauseState::Consistent { instruction: example.instruction.clone(), label: new_label.clone(), observations: 1, hard: *new_hard, }, ); } } else { retained.insert( key, ClauseState::Conflicted { labels, observations, }, ); } } } } ledger.clauses = retained; } else { for (key, (manual_label, manual_hard)) in &manual { if let Some(existing) = ledger.clauses.remove(key) { ledger .clauses .insert(key.clone(), existing.join(manual_label.clone(), *manual_hard)); } } } atomic_json(&project.join("quarantine.json"), &ledger)?; write_episodic(project, &ledger, cat_ref)?; Ok(()) } /// Replace any literal argument in `clause` with a privacy-safe canonical placeholder. fn sanitize_clause(clause: &ParsedClause, expects_url: bool) -> String { if clause.name.is_none() { return clause.text.clone(); } let dummy = if expects_url { "\"https://example.org\"" } else { "\"example\"" }; clause .text .split_whitespace() .map(|word| if word == "NAME" { dummy } else { word }) .collect::<Vec<_>>() .join(" ") } /// Extract privacy-scrubbed `(clause_key, sanitized_instruction, label)` triples. fn extract_candidates( input: &ObservationInput, catalog: Option<&ActionCatalog>, ) -> Result<Result<Vec<(String, String, String)>, ClauseDisposition>, WorkflowError> { let soft_syntax = input.source == OracleSource::BehavioralCorrection; let parsed_input = match catalog { Some(_) => parse_open_command(&input.instruction), None => parse_command(&input.instruction), }; match &input.resolution { OracleResolution::Actions { labels } => { if !(1..=2).contains(&labels.len()) { return Err(WorkflowError::Invalid( "action resolution must supply one or two labels", )); } let clauses = match parsed_input { Ok(parsed) => parsed, Err(_) if soft_syntax => return Ok(Err(ClauseDisposition::SkippedSyntax)), Err(err) => return Err(crate::dataset::DatasetError::from(err).into()), }; if clauses.len() != labels.len() { if soft_syntax { return Ok(Err(ClauseDisposition::SkippedSyntax)); } return Err(WorkflowError::Invalid( "clause count does not match resolved action labels", )); } match catalog { Some(cat) => { let mut validated = Vec::with_capacity(clauses.len()); let mut candidates = Vec::with_capacity(clauses.len()); for (clause, label) in clauses.iter().zip(labels) { let Some(spec) = cat.get(label) else { return Err(crate::dataset::DatasetError::Label(label.clone()).into()); }; let action = match OpenAction::new(spec, clause.name.clone()) { Ok(act) => act, Err(_) if soft_syntax => { return Ok(Err(ClauseDisposition::SkippedSyntax)); } Err(err) => return Err(crate::dataset::DatasetError::from(err).into()), }; validated.push(action); let expects_url = matches!( spec.contract, ArgContract::String { domain: StringDomain::HttpUrl, .. } ); let sanitized = sanitize_clause(clause, expects_url); let key = clause_key(&clause.text)?; candidates.push((key, sanitized, label.clone())); } if let Err(err) = OpenProgram::new(validated) { if soft_syntax { return Ok(Err(ClauseDisposition::SkippedSyntax)); } return Err(crate::dataset::DatasetError::from(err).into()); } Ok(Ok(candidates)) } None => { let mut validated = Vec::with_capacity(clauses.len()); let mut candidates = Vec::with_capacity(clauses.len()); for (clause, label) in clauses.iter().zip(labels) { let kind = ActionKind::from_label(label) .map_err(crate::dataset::DatasetError::from)?; let action = match Action::new(kind, clause.name.clone()) { Ok(act) => act, Err(_) if soft_syntax => { return Ok(Err(ClauseDisposition::SkippedSyntax)); } Err(err) => return Err(crate::dataset::DatasetError::from(err).into()), }; validated.push(action); let sanitized = sanitize_clause(clause, matches!(kind, ActionKind::BrowserUrl)); let key = clause_key(&clause.text)?; candidates.push((key, sanitized, label.clone())); } if let Err(err) = Program::new(validated) { if soft_syntax { return Ok(Err(ClauseDisposition::SkippedSyntax)); } return Err(crate::dataset::DatasetError::from(err).into()); } Ok(Ok(candidates)) } } } OracleResolution::Reject => { let Ok(clauses) = parsed_input else { return Ok(Err(ClauseDisposition::SkippedSyntax)); }; if clauses.len() != 1 { return Ok(Err(ClauseDisposition::SkippedSyntax)); } let clause = &clauses[0]; let sanitized = sanitize_clause(clause, false); let key = clause_key(&clause.text)?; if key.is_empty() { return Ok(Err(ClauseDisposition::SkippedSyntax)); } Ok(Ok(vec![(key, sanitized, String::from("reject"))])) } } } /// Inspect continual-learning status for `project` without mutating files. pub fn learn_status(project: &Path) -> Result<LearnStatus, WorkflowError> { let project = canonical(project)?; manifest(&project)?; let catalog = project_catalog(&project)?; let ledger = load_ledger(&project)?; let episodic = EpisodicMemory::load_optional_with_catalog(&project.join("episodic.json"), catalog.as_ref())?; compute_status(&project, &ledger, episodic.entries.len(), catalog.as_ref()) } /// Record an external oracle observation, updating quarantine and `episodic.json` atomically. pub fn learn_observe( project: &Path, input: &ObservationInput, ) -> Result<ObserveReport, WorkflowError> { let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; manifest(&project)?; let catalog = project_catalog(&project)?; let cat_ref = catalog.as_ref(); let candidates = match extract_candidates(input, cat_ref)? { Ok(items) => items, Err(disposition) => { let ledger = load_ledger(&project)?; let episodic = EpisodicMemory::load_optional_with_catalog(&project.join("episodic.json"), cat_ref)?; return Ok(ObserveReport { dispositions: vec![disposition], status: compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?, }); } }; let training = fs::read(project.join("frozen/training.json"))?; let evaluation = fs::read(project.join("frozen/evaluation.json"))?; let (frozen_known, reserved) = frozen_maps(&training, &evaluation)?; let authored = authored_map( &parse_examples_with_catalog(&fs::read(project.join("examples.json"))?, cat_ref)?, cat_ref, )?; let mut ledger = load_ledger(&project)?; let mut staged_outcomes: Vec<Result<String, ClauseDisposition>> = Vec::with_capacity(candidates.len()); for (key, sanitized, label) in candidates { if reserved.contains(&key) { ledger.withheld_skipped = ledger.withheld_skipped.saturating_add(1); staged_outcomes.push(Err(ClauseDisposition::Withheld)); continue; } if let Some(frozen_label) = frozen_known.get(&key) { if frozen_label == &label { staged_outcomes.push(Err(ClauseDisposition::AlreadyKnown)); } else { ledger.frozen_conflicts = ledger.frozen_conflicts.saturating_add(1); staged_outcomes.push(Err(ClauseDisposition::FrozenConflict)); } continue; } let next = match ledger.clauses.remove(&key) { Some(existing) => existing.join(label, input.hard), None => match authored.get(&key) { Some((manual_label, _)) if manual_label != &label => ClauseState::Conflicted { labels: BTreeSet::from([manual_label.clone(), label]), observations: 1, }, Some((_, manual_hard)) => ClauseState::Consistent { instruction: sanitized, label, observations: 1, hard: *manual_hard || input.hard, }, None => ClauseState::Consistent { instruction: sanitized, label, observations: 1, hard: input.hard, }, }, }; ledger.clauses.insert(key.clone(), next); staged_outcomes.push(Ok(key)); } let dispositions = staged_outcomes .into_iter() .map(|item| match item { Err(early) => early, Ok(key) => match ledger.clauses.get(&key) { Some(ClauseState::Consistent { .. }) => ClauseDisposition::Recorded, _ => ClauseDisposition::Conflicted, }, }) .collect(); atomic_json(&project.join("quarantine.json"), &ledger)?; let episodic = write_episodic(&project, &ledger, cat_ref)?; let status = compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?; Ok(ObserveReport { dispositions, status, }) } /// Synchronize consistent quarantine examples into `examples.json` and expunge conflicts. pub fn learn_sync(project: &Path) -> Result<SyncReport, WorkflowError> { let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; manifest(&project)?; let catalog = project_catalog(&project)?; let cat_ref = catalog.as_ref(); let training = fs::read(project.join("frozen/training.json"))?; let evaluation = fs::read(project.join("frozen/evaluation.json"))?; let ledger = load_ledger(&project)?; let current = parse_examples_with_catalog(&fs::read(project.join("examples.json"))?, cat_ref)?; let before_map = authored_map(&current, cat_ref)?; let mut expunged_conflicts = 0_usize; let mut retained = ExampleFile::default(); for example in current.examples { let key = clause_key(&training_phrase_with_catalog(&example, cat_ref)?)?; if matches!(ledger.clauses.get(&key), Some(ClauseState::Conflicted { .. })) { expunged_conflicts += 1; continue; } retained.examples.push(example); } let mut incoming = ExampleFile::default(); let mut synced_examples = 0_usize; for (key, state) in &ledger.clauses { if let ClauseState::Consistent { instruction, label, hard, .. } = state { let already = before_map .get(key) .is_some_and(|(auth_label, auth_hard)| auth_label == label && (*auth_hard || !hard)); if !already { synced_examples += 1; } incoming.examples.push(Example { instruction: instruction.clone(), label: label.clone(), hard: *hard, }); } } let merged = merge_examples_with_catalog(&training, &evaluation, retained, incoming, cat_ref)?; let serialized = serde_json::to_vec_pretty(&merged)?; materialize_with_catalog( &training, &evaluation, parse_examples_with_catalog(&serialized, cat_ref)?, cat_ref, )?; atomic_bytes(&project.join("examples.json"), &serialized)?; let episodic = write_episodic(&project, &ledger, cat_ref)?; let status = compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?; let project_info = project_info(&project)?; Ok(SyncReport { project_info, status, synced_examples, expunged_conflicts, }) } #[cfg(test)] mod tests { use super::*; use crate::workflow::{init_project, replace_examples}; fn setup_workspace(temp: &Path) -> Result<PathBuf, WorkflowError> { let root = Path::new(env!("CARGO_MANIFEST_DIR")); let workspace = temp.join("learn-workspace"); init_project( &workspace, root, &root.join("data/training.json"), &root.join("data/evaluation.json"), )?; Ok(workspace) } #[test] fn observation_scrubs_private_literals_and_populates_episodic_memory() -> Result<(), WorkflowError> { let temp = tempfile::tempdir()?; let workspace = setup_workspace(temp.path())?; let report = learn_observe( &workspace, &ObservationInput { instruction: String::from( "inspect confidential ledger \"/Users/alice/secret-tax-2026.org\" then tidy up panes", ), source: OracleSource::Teacher, resolution: OracleResolution::Actions { labels: vec![ String::from("find-file"), String::from("balance-windows"), ], }, hard: true, }, )?; assert_eq!( report.dispositions, vec![ClauseDisposition::Recorded, ClauseDisposition::Recorded] ); assert_eq!(report.status.episodic_count, 2); assert_eq!(report.status.pending_sync_count, 2); assert_eq!(report.status.unconsolidated_count, 2); let raw_quarantine = fs::read_to_string(workspace.join("quarantine.json"))?; assert!(!raw_quarantine.contains("secret-tax-2026")); assert!(raw_quarantine.contains("\\\"example\\\"")); let episodic = EpisodicMemory::load_optional(&workspace.join("episodic.json"))?; assert_eq!( episodic.lookup_clause("inspect confidential ledger NAME")?, Some("find-file") ); assert_eq!( episodic.lookup_clause("tidy up panes")?, Some("balance-windows") ); Ok(()) } #[test] fn conflicting_and_intra_request_self_conflicting_clauses_quarantine_and_expunge() -> Result<(), WorkflowError> { let temp = tempfile::tempdir()?; let workspace = setup_workspace(temp.path())?; learn_observe( &workspace, &ObservationInput { instruction: String::from("step backward right now"), source: OracleSource::BehavioralCorrection, resolution: OracleResolution::Actions { labels: vec![String::from("lispm-browser-back")], }, hard: true, }, )?; let synced = learn_sync(&workspace)?; assert_eq!(synced.synced_examples, 1); assert_eq!(synced.status.pending_sync_count, 0); // Still unconsolidated because no finalized run is active yet! assert_eq!(synced.status.unconsolidated_count, 1); let conflict = learn_observe( &workspace, &ObservationInput { instruction: String::from("step backward right now"), source: OracleSource::BehavioralCorrection, resolution: OracleResolution::Actions { labels: vec![String::from("lispm-finder-back")], }, hard: true, }, )?; assert_eq!(conflict.dispositions, vec![ClauseDisposition::Conflicted]); assert_eq!(conflict.status.episodic_count, 0); assert_eq!(conflict.status.pending_sync_count, 1); let cleaned = learn_sync(&workspace)?; assert_eq!(cleaned.expunged_conflicts, 1); assert_eq!(cleaned.project_info.added_examples, 0); assert_eq!(cleaned.status.unconsolidated_count, 0); // Intra-request identical clause skeleton with distinct actions reports both Conflicted. let self_conflict = learn_observe( &workspace, &ObservationInput { instruction: String::from( "launch resource \"https://example.org\" then launch resource \"notes.el\"", ), source: OracleSource::Teacher, resolution: OracleResolution::Actions { labels: vec![ String::from("lispm-browser-open-url"), String::from("find-file"), ], }, hard: true, }, )?; assert_eq!( self_conflict.dispositions, vec![ClauseDisposition::Conflicted, ClauseDisposition::Conflicted] ); assert_eq!(self_conflict.status.episodic_count, 0); Ok(()) } #[test] fn manual_replace_examples_reconciles_quarantine_and_episodic_memory() -> Result<(), WorkflowError> { let temp = tempfile::tempdir()?; let workspace = setup_workspace(temp.path())?; learn_observe( &workspace, &ObservationInput { instruction: String::from("beam into dossier \"notes.el\""), source: OracleSource::Teacher, resolution: OracleResolution::Actions { labels: vec![String::from("find-file")], }, hard: true, }, )?; let synced = learn_sync(&workspace)?; assert_eq!(synced.project_info.added_examples, 1); // Explicitly replacing examples with an empty file removes deleted entries from quarantine. let empty = serde_json::to_vec(&ExampleFile::default())?; let after_replace = replace_examples(&workspace, &empty, &synced.project_info.generation)?; assert_eq!(after_replace.added_examples, 0); let status = learn_status(&workspace)?; assert_eq!(status.consistent_count, 0); assert_eq!(status.episodic_count, 0); // Subsequent learn_sync does not resurrect the manually deleted example. let resynced = learn_sync(&workspace)?; assert_eq!(resynced.project_info.added_examples, 0); Ok(()) } #[test] fn behavioral_arity_mismatch_held_out_and_multiclause_reject_are_safe() -> Result<(), WorkflowError> { let temp = tempfile::tempdir()?; let workspace = setup_workspace(temp.path())?; // Behavioral correction with mismatched arity (0 quotes for find-file) skips gracefully. let mismatch = learn_observe( &workspace, &ObservationInput { instruction: String::from("hop to next pane"), source: OracleSource::BehavioralCorrection, resolution: OracleResolution::Actions { labels: vec![String::from("find-file")], }, hard: true, }, )?; assert_eq!(mismatch.dispositions, vec![ClauseDisposition::SkippedSyntax]); let evaluation_bytes = fs::read(workspace.join("frozen/evaluation.json"))?; let evaluation: crate::evaluation::EvaluationData = serde_json::from_slice(&evaluation_bytes)?; let held_out_phrase = evaluation .corpora .values() .flat_map(|c| &c.cases) .find(|case| case.action.is_some() && parse_command(&case.input).is_ok_and(|p| p.len() == 1)) .expect("held-out single-action case"); let withheld = learn_observe( &workspace, &ObservationInput { instruction: held_out_phrase.input.clone(), source: OracleSource::Teacher, resolution: OracleResolution::Actions { labels: vec![ held_out_phrase .action .clone() .expect("supported case action"), ], }, hard: true, }, )?; assert_eq!(withheld.dispositions, vec![ClauseDisposition::Withheld]); assert_eq!(withheld.status.withheld_skipped, 1); assert_eq!(withheld.status.episodic_count, 0); let multiclause_reject = learn_observe( &workspace, &ObservationInput { instruction: String::from("compile everything then save the current buffer"), source: OracleSource::Teacher, resolution: OracleResolution::Reject, hard: true, }, )?; assert_eq!( multiclause_reject.dispositions, vec![ClauseDisposition::SkippedSyntax] ); assert_eq!(multiclause_reject.status.episodic_count, 0); Ok(()) } #[test] fn open_biencoder_workspace_syncs_new_actions_and_learns_beyond_48() -> Result<(), Box<dyn std::error::Error>> { let _serial = crate::runtime::test_serial_guard(); let temp = tempfile::tempdir()?; let base_dir = temp.path().join("base-biencoder"); let vocab = BTreeMap::from([ ("<pad>".into(), 0), ("<unk>".into(), 1), ("<cls>".into(), 2), ("NAME".into(), 3), ]); let meta = crate::biencoder::BiEncoderMetadata { model_type: String::from(crate::biencoder::BIENCODER_MODEL_TYPE), architecture: crate::config::ModelConfig { width: 64, layers: 1, heads: 4, feedforward: 128, char_buckets: 2048, max_ngrams: 32, max_words: 60, dropout: 0.0, }, reject_prototypes: 8, vocab, thresholds: crate::config::Thresholds { probability: 0.5, margin: 0.0, }, extra: BTreeMap::new(), }; let mut bundle = crate::biencoder::BiEncoderBundle::new(meta, 42, ActionCatalog::builtin())?; bundle.save(&base_dir)?; let root = Path::new(env!("CARGO_MANIFEST_DIR")); let workspace = temp.path().join("open-workspace"); let info = init_project( &workspace, &base_dir, &root.join("data/training.json"), &root.join("data/evaluation.json"), )?; assert!(info.catalog_file.is_some()); assert_eq!(info.labels.len(), 49); let mut extended = ActionCatalog::builtin(); extended.actions.push(crate::catalog::ActionSpec { id: String::from("lispm-1password"), function: String::from("lispm-1password"), contract: ArgContract::Fixed { args: vec![] }, description: String::from("Open 1Password vault manager"), mode: None, }); let sync_cat = crate::workflow::sync_catalog(&workspace, &extended)?; assert_eq!(sync_cat.added_actions, 1); assert_eq!(sync_cat.total_actions, 49); let obs = learn_observe( &workspace, &ObservationInput { instruction: String::from("open the 1password credential vault"), source: OracleSource::BehavioralCorrection, resolution: OracleResolution::Actions { labels: vec![String::from("lispm-1password")], }, hard: true, }, )?; assert_eq!(obs.dispositions, vec![ClauseDisposition::Recorded]); assert_eq!(obs.status.episodic_count, 1); let synced = learn_sync(&workspace)?; assert_eq!(synced.synced_examples, 1); assert_eq!(synced.project_info.added_examples, 1); assert_eq!(synced.project_info.labels.len(), 50); Ok(()) } }
//! Poison-resistant continual observation, episodic recall, and quarantine sync.
//!
//! Basis: Join-semilattice quarantine ledger (`Consistent` | `Conflicted`) paired with
//! atomic materialization into fast episodic memory (`episodic.json`) and reconciliation
//! into durable trainer examples (`examples.json`).
//! Minimality: Raw model self-predictions are unrepresentable; only external oracle
//! observations (`BehavioralCorrection` or `Teacher`) enter the semilattice. Promotion
//! and training readiness are derived from `(quarantine.json, examples.json, active.json)`
//! without redundant boolean flags.
//! Tightness: Literal arguments are scrubbed at ingestion into canonical dummy constants
//! (`"example"` or `"https://example.org"`), preventing PII persistence while preserving
//! exact `parse_command` clause structure.
//! Law: `Consistent(a) ⊔ Obs(b) = Conflicted({a, b})` for `a != b`, and `Conflicted` is an
//! absorbing top element excluded from both `episodic.json` and `examples.json`.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::io::{
ProjectLock, atomic_bytes, atomic_json, canonical, digest, manifest, project_catalog, read_json,
read_run,
};
use super::project_info;
use super::types::{Activation, ProjectInfo, RunStatus, WorkflowError};
use crate::actions::{Action, ActionKind, ParsedClause, Program, parse_command};
use crate::catalog::{
ActionCatalog, ArgContract, OpenAction, OpenProgram, StringDomain, parse_open_command,
};
use crate::dataset::{
Example, ExampleFile, clause_key, frozen_maps, materialize_with_catalog,
merge_examples_with_catalog, parse_examples_with_catalog, training_phrase_with_catalog,
};
use crate::episodic::EpisodicMemory;
/// Verified external supervision source; model self-predictions are unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OracleSource {
/// User cancelled, undid, or received a refusal, then executed a target command.
BehavioralCorrection,
/// Higher-tier teacher agent resolved an unserved or uncertain instruction.
Teacher,
}
/// Ground-truth supervision supplied by an external oracle for a raw instruction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum OracleResolution {
/// One or two action labels matching the parsed clauses of `instruction` in order.
Actions {
/// Closed-set action labels (excluding `"reject"`).
labels: Vec<String>,
},
/// The single-clause instruction requires capabilities outside the 48-action DSL.
Reject,
}
/// One external oracle observation submitted to a workspace.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ObservationInput {
/// Raw English instruction entered by the user; literals are scrubbed before storage.
pub instruction: String,
/// Verified external supervision source.
pub source: OracleSource,
/// Ground-truth action assignment or rejection.
pub resolution: OracleResolution,
/// Explicit hard-example flag; defaults to true for corrections/refusals.
#[serde(default = "default_hard")]
pub hard: bool,
}
/// Corrections and fallbacks represent model boundary failures by default.
const fn default_hard() -> bool {
true
}
/// Monotonic semilattice state for one normalized clause skeleton.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum ClauseState {
/// Every oracle observation for this clause agreed on a single label.
Consistent {
/// Privacy-scrubbed canonical single-clause instruction.
instruction: String,
/// Agreed closed-set label (`ActionKind` label or `"reject"`).
label: String,
/// Number of agreeing observations recorded.
observations: u32,
/// Whether hard-example oversampling applies during retraining.
hard: bool,
},
/// Two or more distinct labels were observed; permanently excluded as ambiguous.
Conflicted {
/// Distinct labels asserted for this clause skeleton.
labels: BTreeSet<String>,
/// Total observations recorded across conflicting labels.