//! Strict JSON operation schema, path ownership and workflow dispatch. use std::path::{Path, PathBuf}; use lispm_llm::{runtime, workflow}; use serde::Deserialize; use serde_json::{Value, json}; use crate::{ApiError, jobs}; /// Single protocol definition shared by native Emacs and arbitrary C FFI clients. #[derive(Deserialize)] #[serde(tag = "op", rename_all = "kebab-case", deny_unknown_fields)] enum Request { /// Discover ABI version and capabilities without touching model state. Version {}, /// Copy immutable inputs into a new user-owned training project. ProjectCreate { project: PathBuf, base_model: PathBuf, training_data: PathBuf, benchmark_data: PathBuf, #[serde(default)] task_suite: Option, }, /// Inspect project generations, runs and current activation. ProjectInfo { project: PathBuf }, /// Append a single supported or rejection example with optimistic concurrency. AddExample { project: PathBuf, generation: String, instruction: String, label: String, #[serde(default)] hard: bool, }, /// Import an explicit versioned examples file with the same validation rules. ImportDataset { project: PathBuf, generation: String, path: PathBuf, }, /// Replace only authored examples, allowing explicit correction and removal. ReplaceDataset { project: PathBuf, generation: String, path: PathBuf, }, /// Reopen durable benchmark evidence after the creating job was released. RunReport { project: PathBuf, run: String }, /// Start fresh-weight native training against a frozen data generation. Train { project: PathBuf, steps: u32, seed: u64, threads: i32, }, /// Compare one candidate and its baseline on the identical frozen benchmark. Benchmark { project: PathBuf, run: String, threads: i32, }, /// Freeze only a benchmark-qualified candidate into a finalized artifact. Finalize { project: PathBuf, run: String, threads: i32, }, /// Explicitly choose a finalized artifact for the next inference session. Activate { project: PathBuf, run: String }, /// Restore the previous verified activation, including the initial baseline. Rollback { project: PathBuf }, /// Inspect continual-learning quarantine and episodic status for a project. LearnStatus { project: PathBuf }, /// Record one external oracle observation into quarantine and episodic memory. LearnObserve { project: PathBuf, observation: workflow::ObservationInput, }, /// Synchronize clean quarantine supervision into examples.json and expunge conflicts. LearnSync { project: PathBuf }, /// Merge newly harvested Emacs or lispm-kit actions into /catalog.json. CatalogSync { project: PathBuf, catalog: lispm_llm::catalog::ActionCatalog, }, /// Observe a nonblocking worker snapshot. JobPoll { job: u64 }, /// Request cooperative cancellation and return its current state. JobCancel { job: u64 }, /// Release a retained handle and cancel any uncommitted work. JobRelease { job: u64 }, } /// Reject ambient relative paths before any filesystem or worker side effect. fn absolute(path: &Path) -> Result<(), ApiError> { if !path.is_absolute() { return Err(ApiError::RelativePath); } Ok(()) } /// Serialize one concrete domain value while preserving typed serde failures. fn value(result: impl serde::Serialize) -> Result { Ok(serde_json::to_value(result)?) } /// Parse the operation and select one explicit side-effect boundary. pub(crate) fn dispatch(input: &str) -> Result { if input.len() > 8 * 1024 * 1024 { return Err(ApiError::RequestTooLarge); } match serde_json::from_str(input)? { Request::Version {} => { Ok(json!({"abi":1, "version":env!("CARGO_PKG_VERSION"), "actions":48})) } Request::ProjectCreate { project, base_model, training_data, benchmark_data, task_suite, } => { for path in [&project, &base_model, &training_data, &benchmark_data] { absolute(path)?; } if let Some(tasks) = &task_suite { for path in [&tasks.data, &tasks.runner, &tasks.emacs] { absolute(path)?; } } value(workflow::init_project_with_tasks( &project, &base_model, &training_data, &benchmark_data, task_suite.as_ref(), )?) } Request::ProjectInfo { project } => { absolute(&project)?; value(workflow::project_info(&project)?) } Request::AddExample { project, generation, instruction, label, hard, } => { absolute(&project)?; let examples = serde_json::to_vec( &json!({"format_version":1,"examples":[{"instruction":instruction,"label":label,"hard":hard}]}), )?; value(workflow::import_examples(&project, &examples, &generation)?) } Request::ImportDataset { project, generation, path, } => import_dataset(project, generation, path, false), Request::ReplaceDataset { project, generation, path, } => import_dataset(project, generation, path, true), Request::RunReport { project, run } => { absolute(&project)?; value(workflow::benchmark_report(&project, &run)?) } Request::Train { project, steps, seed, threads, } => train_job( project, workflow::RunOptions { steps, seed, threads, }, ), Request::Benchmark { project, run, threads, } => benchmark_job(project, run, threads), Request::Finalize { project, run, threads, } => finalize_job(project, run, threads), Request::Activate { project, run } => { absolute(&project)?; value(workflow::activate_run(&project, &run)?) } Request::Rollback { project } => { absolute(&project)?; value(workflow::rollback(&project)?) } Request::LearnStatus { project } => { absolute(&project)?; value(workflow::learn_status(&project)?) } Request::LearnObserve { project, observation, } => { absolute(&project)?; value(workflow::learn_observe(&project, &observation)?) } Request::LearnSync { project } => { absolute(&project)?; value(workflow::learn_sync(&project)?) } Request::CatalogSync { project, catalog } => { absolute(&project)?; value(workflow::sync_catalog(&project, &catalog)?) } Request::JobPoll { job } => value(jobs::poll(job)?), Request::JobCancel { job } => value(jobs::cancel(job)?), Request::JobRelease { job } => { jobs::release(job)?; Ok(json!({})) } } } /// Import or explicitly replace user-authored examples after optimistic validation. fn import_dataset( project: PathBuf, generation: String, path: PathBuf, replace: bool, ) -> Result { absolute(&project)?; absolute(&path)?; let examples = std::fs::read(path)?; if replace { value(workflow::replace_examples( &project, &examples, &generation, )?) } else { value(workflow::import_examples(&project, &examples, &generation)?) } } /// Start one training operation with owned paths and native option types. fn train_job(project: PathBuf, options: workflow::RunOptions) -> Result { absolute(&project)?; runtime::configure_threads(options.threads)?; let job = jobs::start(move |cancelled, progress| { value(workflow::train_project( &project, &options, cancelled, progress, )?) })?; Ok(json!({"job":job})) } /// Benchmark one existing candidate without blocking a foreign caller. fn benchmark_job(project: PathBuf, run: String, threads: i32) -> Result { absolute(&project)?; runtime::configure_threads(threads)?; let job = jobs::start(move |cancelled, progress| { value(workflow::benchmark_run( &project, &run, cancelled, progress, )?) })?; Ok(json!({"job":job})) } /// Finalize recorded eligible evidence, retaining committed output on a late cancel. fn finalize_job(project: PathBuf, run: String, threads: i32) -> Result { absolute(&project)?; runtime::configure_threads(threads)?; let job = jobs::start(move |cancelled, progress| { use std::sync::atomic::Ordering; if cancelled.load(Ordering::Acquire) { return Err(ApiError::Cancelled); } progress(json!({"phase":"finalizing", "run":run})); value(workflow::finalize_run_with_control( &project, &run, cancelled, )?) })?; Ok(json!({"job":job})) }