//! A local collect → retrain → compare → finalize → activate workflow. //! //! The immutable baseline and benchmark are project identities. User examples //! are the only editable dataset; each run snapshots them before computation. //! Training from fresh weights uses the shared corpus plus authored examples. //! No operation silently replaces the selected inference artifact. #[path = "workflow_io.rs"] mod io; #[path = "workflow_learn.rs"] mod learn; #[path = "workflow_runs.rs"] mod runs; #[path = "workflow_tasks.rs"] mod tasks; #[path = "workflow_types.rs"] mod types; pub use learn::{ ClauseDisposition, ClauseState, LearnStatus, ObservationInput, ObserveReport, OracleResolution, OracleSource, SyncReport, learn_observe, learn_status, learn_sync, }; pub use runs::{ benchmark_report, benchmark_run, finalize_run, finalize_run_with_control, train_project, }; pub use types::{ ArtifactIdentity, BenchmarkInfo, CatalogSyncReport, Comparison, FinalizedInfo, FrozenTaskSuite, ProjectInfo, RunInfo, RunOptions, RunStatus, Scores, TaskSuiteOptions, WorkflowError, }; use crate::biencoder::BiEncoderMetadata; use crate::catalog::ActionCatalog; use crate::config::{ArtifactConfig, expected_labels}; use crate::dataset::{ ExampleFile, materialize_with_catalog, merge_examples_with_catalog, parse_examples_with_catalog, }; use io::{ ProjectLock, atomic_bytes, atomic_json, canonical, copy_model, digest, manifest, project_catalog, read_json, read_run, verify_identity, }; use std::fs; use std::path::Path; use types::{Activation, ActiveModel, Manifest}; /// Rules stored with every initialized project, alongside its editable examples. const RULES: &str = "# LispM training project\n\nImport JSON with format_version: 1 and examples: [{instruction, label, hard}].\nUse one English action per example, one existing action label or reject, and JSON-quoted literal arguments.\nMark hard examples with hard: true. Unknown paraphrases may use existing action labels.\nLabel unsupported operations reject; never relabel a supported paraphrase merely to improve metrics.\nDo not copy calibration or benchmark phrases into examples. Normalized duplicates do not add weight; conflicting labels fail.\nThe frozen directory and baseline are immutable. Retraining uses shared training rows plus your examples, with the original calibration/reference unchanged.\nCompare both artifacts against the same frozen benchmark. Finalize only candidates that preserve correctness and coverage without increasing errors.\nActivation is explicit and retains the preceding model identity for rollback.\n"; /// Validate a portable benchmark without constructing a numerical model. fn validate_benchmark(bytes: &[u8]) -> Result<(), WorkflowError> { crate::evaluation::validate_data_bytes(bytes)?; Ok(()) } /// Validate a model directory's config/catalog without allocating tensor runtime state. fn validate_model_directory(directory: &Path) -> Result { if crate::engine::is_biencoder_artifact(directory)? { let meta: BiEncoderMetadata = read_json(&directory.join("config.json"))?; meta.validate()?; ActionCatalog::load_or_builtin(&directory.join("catalog.json"))?; Ok(true) } else { ArtifactConfig::load(directory.join("config.json"))?.validate_artifact()?; Ok(false) } } /// Initialize a new local project without altering any source directory or file. /// /// The destination must not exist. Configuration is validated without tensors; /// model scoring later validates and binds the actual weights under the runtime /// guard. A failed initialization removes only its newly created destination. pub fn init_project( project: &Path, base_model: &Path, training_data: &Path, evaluation_data: &Path, ) -> Result { init_project_with_tasks(project, base_model, training_data, evaluation_data, None) } /// Freeze command cohorts and optional real-Emacs task inputs into a new project. /// /// Task instructions also become a command-evaluation corpus, reserving their /// normalized clauses against later authored-data imports. Existing projects /// retain their original frozen benchmark and are never upgraded in place. pub fn init_project_with_tasks( project: &Path, base_model: &Path, training_data: &Path, evaluation_data: &Path, task_options: Option<&TaskSuiteOptions>, ) -> Result { let is_biencoder = validate_model_directory(base_model)?; let training = fs::read(training_data)?; let mut evaluation = fs::read(evaluation_data)?; crate::training::validate_training_data_bytes(&training)?; validate_benchmark(&evaluation)?; let prepared = task_options .map(|options| tasks::prepare(options, &mut evaluation)) .transpose()?; fs::create_dir(project)?; let result = (|| { let project = canonical(project)?; let baseline = copy_model(base_model, &project.join("baseline"))?; validate_model_directory(&project.join("baseline"))?; for name in ["frozen", "runs", "finalized"] { fs::create_dir(project.join(name))?; } if is_biencoder { let initial_catalog = ActionCatalog::load_or_builtin(&project.join("baseline/catalog.json"))?; atomic_json(&project.join("catalog.json"), &initial_catalog)?; } atomic_bytes(&project.join("frozen/training.json"), &training)?; atomic_bytes(&project.join("frozen/evaluation.json"), &evaluation)?; if let Some(inputs) = &prepared { inputs.write(&project)?; } atomic_json(&project.join("examples.json"), &ExampleFile::default())?; atomic_bytes(&project.join("RULES.md"), RULES.as_bytes())?; atomic_json( &project.join("project.json"), &Manifest { format_version: if prepared.is_some() { 2 } else { 1 }, baseline, training_sha256: digest(&training), evaluation_sha256: digest(&evaluation), task_suite: prepared.as_ref().map(|inputs| inputs.suite.clone()), }, )?; project_info(&project) })(); if result.is_err() { let _ = fs::remove_dir_all(project); } result } /// Return current absolute paths after checking immutable project identities. pub fn project_info(project: &Path) -> Result { let project = canonical(project)?; let source = manifest(&project)?; let catalog = project_catalog(&project)?; let examples = fs::read(project.join("examples.json"))?; let data = materialize_with_catalog( &fs::read(project.join("frozen/training.json"))?, &fs::read(project.join("frozen/evaluation.json"))?, parse_examples_with_catalog(&examples, catalog.as_ref())?, catalog.as_ref(), )?; let mut runs = Vec::new(); 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"))?; runs.push(read_run(&project, &id)?); } } runs.sort_by(|left, right| left.id.cmp(&right.id)); let active_model = if project.join("active.json").is_file() { let active: Activation = read_json(&project.join("active.json"))?; verify_active(&project, &active.current)?; Some(active.current.model) } else { None }; let labels = match &catalog { Some(cat) => cat.labels_with_reject(), None => expected_labels(), }; let catalog_file = catalog.map(|_| project.join("catalog.json")); Ok(ProjectInfo { generation: digest(&examples), labels, training_rows: data.training_rows, added_examples: data.added_examples, baseline_model: project.join("baseline"), baseline: source.baseline, evaluation_data: project.join("frozen/evaluation.json"), task_suite: source.task_suite, runs, active_model, catalog_file, project, }) } /// Merge newly discovered Emacs or `lispm-kit` actions into `/catalog.json`. pub fn sync_catalog( project: &Path, incoming: &ActionCatalog, ) -> Result { incoming.validate()?; let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; manifest(&project)?; let Some(current) = project_catalog(&project)? else { return Err(WorkflowError::Invalid( "catalog-sync requires a bi-encoder workspace", )); }; let before = current.actions.len(); let merged = current.merge(incoming)?; let catalog_file = project.join("catalog.json"); atomic_json(&catalog_file, &merged)?; Ok(CatalogSyncReport { project, catalog_file, total_actions: merged.actions.len(), added_actions: merged.actions.len().saturating_sub(before), }) } /// Merge an import against the exact inspected generation, replacing atomically. /// /// A stale generation or concurrent writer fails instead of losing an update. /// Existing shared data is never edited and imported calibration fields fail the /// strict examples schema. Identical normalized examples do not increase weight. pub fn import_examples( project: &Path, examples_json: &[u8], expected_generation: &str, ) -> Result { update_examples( project, examples_json, expected_generation, ExampleUpdate::Merge, ) } /// Replace only authored examples, allowing label corrections and deletions. /// /// The expected generation is mandatory. Shared training rows, calibration, /// incumbent reference, existing run snapshots and the benchmark never change. pub fn replace_examples( project: &Path, examples_json: &[u8], expected_generation: &str, ) -> Result { update_examples( project, examples_json, expected_generation, ExampleUpdate::Replace, ) } /// Select whether current authored examples participate in the validated merge. enum ExampleUpdate { /// Preserve previous authored examples and append new normalized identities. Merge, /// Use only supplied authored examples, allowing corrections or removals. Replace, } /// Perform one generation-checked authored-data update under the project lock. fn update_examples( project: &Path, examples_json: &[u8], expected_generation: &str, mode: ExampleUpdate, ) -> Result { let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; manifest(&project)?; let path = project.join("examples.json"); let original = fs::read(&path)?; if digest(&original) != expected_generation { return Err(WorkflowError::GenerationChanged); } let catalog = project_catalog(&project)?; let training = fs::read(project.join("frozen/training.json"))?; let evaluation = fs::read(project.join("frozen/evaluation.json"))?; let current = match mode { ExampleUpdate::Merge => parse_examples_with_catalog(&original, catalog.as_ref())?, ExampleUpdate::Replace => ExampleFile::default(), }; let merged = merge_examples_with_catalog( &training, &evaluation, current, parse_examples_with_catalog(examples_json, catalog.as_ref())?, catalog.as_ref(), )?; let serialized = serde_json::to_vec_pretty(&merged)?; materialize_with_catalog( &training, &evaluation, parse_examples_with_catalog(&serialized, catalog.as_ref())?, catalog.as_ref(), )?; atomic_bytes(&path, &serialized)?; learn::reconcile_manual_examples(&project, &merged, matches!(mode, ExampleUpdate::Replace))?; project_info(&project) } /// Verify an active selection against its finalized run and artifact evidence. fn verify_active(project: &Path, active: &ActiveModel) -> Result<(), WorkflowError> { if active.run == "baseline" { let source = manifest(project)?; if active.model != project.join("baseline") || active.artifact != source.baseline { return Err(WorkflowError::Invalid( "baseline activation identity mismatch", )); } return verify_identity(&active.model, &source.baseline); } let run = read_run(project, &active.run)?; if run.status != RunStatus::Finalized || run.finalized_model.as_ref() != Some(&active.model) || run.artifact.as_ref() != Some(&active.artifact) { return Err(WorkflowError::Invalid( "active model does not name a finalized run", )); } verify_identity(&active.model, &active.artifact) } /// Select a verified finalized candidate and atomically retain its predecessor. pub fn activate_run(project: &Path, run_id: &str) -> Result { let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; let source = manifest(&project)?; let run = read_run(&project, run_id)?; if run.status != RunStatus::Finalized { return Err(WorkflowError::Invalid("finalize before activation")); } let model = run .finalized_model .ok_or(WorkflowError::Invalid("missing finalized model"))?; let artifact = run .artifact .ok_or(WorkflowError::Invalid("missing finalized identity"))?; verify_identity(&model, &artifact)?; let path = project.join("active.json"); let previous = if path.is_file() { let prior: Activation = read_json(&path)?; verify_active(&project, &prior.current)?; if prior.current.run == run_id { return project_info(&project); } Some(prior.current) } else { Some(ActiveModel { run: "baseline".into(), model: project.join("baseline"), artifact: source.baseline, }) }; atomic_json( &path, &Activation { current: ActiveModel { run: run_id.into(), model, artifact, }, previous, }, )?; project_info(&project) } /// Restore the previous explicit activation after rechecking its immutable files. pub fn rollback(project: &Path) -> Result { let project = canonical(project)?; let _lock = ProjectLock::acquire(&project)?; manifest(&project)?; let path = project.join("active.json"); let active: Activation = read_json(&path)?; let previous = active .previous .ok_or(WorkflowError::Invalid("no preceding activation"))?; verify_active(&project, &previous)?; atomic_json( &path, &Activation { current: previous, previous: Some(active.current), }, )?; project_info(&project) }