//! Serializable project state and explicitly bound benchmark evidence. use serde::{Deserialize, Serialize}; use serde_json::Value; use std::path::PathBuf; use thiserror::Error; /// Failure to perform one explicit project state transition. #[derive(Debug, Error)] pub enum WorkflowError { /// Another operation currently owns the project write lock. #[error("project is busy; retry after the current update")] Busy, /// The caller's optimistic dataset generation is stale. #[error("examples changed since they were inspected; refresh the project before importing")] GenerationChanged, /// Immutable source or model bytes no longer match their recorded identity. #[error("immutable project artifact changed: {0}")] Changed(PathBuf), /// The requested operation is incompatible with the project/run state. #[error("invalid project operation: {0}")] Invalid(&'static str), /// No partial benchmark or model is activated after cancellation. #[error("project operation cancelled")] Cancelled, /// A candidate does not meet frozen benchmark nonregression constraints. #[error("candidate is not eligible: correctness, errors or supported coverage regressed")] Ineligible, /// Filesystem access failed. #[error(transparent)] Io(#[from] std::io::Error), /// Project metadata failed strict JSON decoding. #[error(transparent)] Json(#[from] serde_json::Error), /// Authoritative example and split validation failed. #[error(transparent)] Dataset(#[from] crate::dataset::DatasetError), /// Episodic fast-path memory failed validation. #[error(transparent)] Episodic(#[from] crate::episodic::EpisodicError), /// Native training failed or was cancelled. #[error(transparent)] Training(#[from] crate::training::TrainingError), /// Frozen evaluation failed; infrastructure errors are never refusals. #[error(transparent)] Evaluation(#[from] crate::evaluation::EvaluationError), /// A real Emacs task runner or its evidence failed validation. #[error(transparent)] TaskBenchmark(#[from] crate::task_benchmark::TaskBenchmarkError), /// Base model configuration is not an accepted inference artifact. #[error(transparent)] Config(#[from] crate::config::ConfigError), /// Open action catalog validation or decoding failed. #[error(transparent)] Catalog(#[from] crate::catalog::CatalogError), /// Bi-encoder or closed model metadata failed verification. #[error(transparent)] Model(#[from] crate::model::ModelError), /// Another process-wide native operation owns the numerical runtime. #[error(transparent)] Runtime(#[from] crate::runtime::RuntimeError), } impl WorkflowError { /// Identify cancellation independently of rendered error text. pub fn is_cancelled(&self) -> bool { matches!( self, Self::Cancelled | Self::Training(crate::training::TrainingError::Cancelled) ) || matches!(self, Self::TaskBenchmark(error) if error.is_cancelled()) } } /// Immutable identity of both files defining a model's predictions. /// Cloning this value preserves identity without duplicating any resource. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ArtifactIdentity { /// Exact metadata, vocabulary and threshold bytes. pub config_sha256: String, /// Exact serialized tensor bytes. pub weights_sha256: String, } /// A compact project view, containing absolute paths suitable for Emacs. #[derive(Debug, Serialize)] pub struct ProjectInfo { /// Canonical project directory. pub project: PathBuf, /// Exact current examples-file hash required by append/import. pub generation: String, /// The immutable 48 actions followed by the rejection label. pub labels: Vec, /// Shared plus additional distinct training rows. pub training_rows: usize, /// Distinct rows contributed by this project's authored examples. pub added_examples: usize, /// Frozen baseline directory, never overwritten by training. pub baseline_model: PathBuf, /// Identity checked whenever the project is opened. pub baseline: ArtifactIdentity, /// Frozen materialized benchmark file. pub evaluation_data: PathBuf, /// Frozen real-Emacs task suite, absent for legacy command-only projects. pub task_suite: Option, /// All durable attempt records, including failed and cancelled runs. pub runs: Vec, /// Explicitly activated finalized model, if any. pub active_model: Option, /// Open action catalog file when backed by a bi-encoder baseline. #[serde(skip_serializing_if = "Option::is_none")] pub catalog_file: Option, } /// Summary returned after merging newly discovered actions into `/catalog.json`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CatalogSyncReport { /// Canonical project path. pub project: PathBuf, /// Absolute path to `/catalog.json`. pub catalog_file: PathBuf, /// Total actions in the merged catalog. pub total_actions: usize, /// Number of newly added actions. pub added_actions: usize, } /// Reproducible candidate training options; the baseline is never fine-tuned in place. #[derive(Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RunOptions { /// Number of optimizer updates, including selection checkpoints. pub steps: u32, /// Native sampling and model initialization seed. pub seed: u64, /// Process-wide LibTorch CPU thread count. pub threads: i32, } impl Default for RunOptions { fn default() -> Self { Self { steps: 3200, seed: 42, threads: 2, } } } /// Durable lifecycle state; failure never grants activation permission. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RunStatus { /// The run owns immutable input bytes and is computing. Training, /// Eligible calibration weights were successfully published. Trained, /// Both models were scored against identical frozen benchmark bytes. Benchmarked, /// An eligible candidate was copied to its immutable final location. Finalized, /// Training or publication failed; any partial output is unusable. Failed, /// Cancellation prevented successful publication. Cancelled, } /// The complete durable identity of one retraining attempt. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct RunInfo { /// Generated directory basename; path traversal is rejected on lookup. pub id: String, /// Absolute candidate model path. pub model: PathBuf, /// Requested optimizer updates. pub steps: u32, /// Requested initialization and sampling seed. pub seed: u64, /// Requested process-wide CPU pool size. pub threads: i32, /// Exact examples snapshot used for this run. pub generation: String, /// Exact materialized trainer input binding all calibration evidence. pub training_data_sha256: String, /// Explicit run transition state. pub status: RunStatus, /// Identity of a successfully published model. pub artifact: Option, /// Hash of the internally generated benchmark evidence, if available. pub benchmark_sha256: Option, /// Immutable finalized model location, if eligible and finalized. pub finalized_model: Option, /// Infrastructure error associated with failed attempts. pub error: Option, } /// Disjoint supported or unsupported benchmark outcomes. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Scores { /// Number of observations. pub total: usize, /// Correct accepted supported commands. pub correct: usize, /// Wrong accepted commands, including unsupported false accepts. pub wrong: usize, /// Explicit refusals, kept separate from accepted correctness. pub rejected: usize, } /// Per-corpus evidence for the no-extra-rejection eligibility rule. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Comparison { /// Frozen corpus name. pub corpus: String, /// Baseline supported outcomes. pub baseline_supported: Scores, /// Candidate supported outcomes. pub candidate_supported: Scores, /// Baseline unsupported outcomes. pub baseline_unsupported: Scores, /// Candidate unsupported outcomes. pub candidate_unsupported: Scores, /// Correctness, false acceptance and supported refusal bounds all hold. pub eligible: bool, } /// Internal benchmark evidence bound to a project run and both exact artifacts. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct BenchmarkInfo { /// Schema identity. pub format_version: u32, /// Run whose candidate was scored. pub run: String, /// Hash of the run's immutable trainer input. pub training_data_sha256: String, /// Exact frozen benchmark bytes, shared by both reports. pub evaluation_data_sha256: String, /// Complete artifact-bound baseline report. pub baseline: Value, /// Complete artifact-bound candidate report. pub candidate: Value, /// Transparent per-corpus partitions and eligibility constraints. pub comparison: Vec, /// Executed task comparison required whenever the project freezes a task suite. #[serde(default, skip_serializing_if = "Option::is_none")] pub task_comparison: Option, /// Every frozen corpus meets the nonregression predicate. pub eligible: bool, /// Absolute durable evidence path. pub path: PathBuf, } /// An eligible finalized artifact ready for explicit activation. #[derive(Debug, Serialize)] pub struct FinalizedInfo { /// Run identity. pub run: String, /// Immutable finalized model path. pub model: PathBuf, /// Exact files verified against benchmark evidence. pub artifact: ArtifactIdentity, } /// Frozen project source identities; all mutable state lives in separate files. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct Manifest { /// Schema identity. pub format_version: u32, /// Immutable baseline model identity. pub baseline: ArtifactIdentity, /// Original portable training/calibration bytes. pub training_sha256: String, /// Frozen independent materialized benchmark bytes. pub evaluation_sha256: String, /// Optional execution suite frozen when creating this project, never silently upgraded. #[serde(default, skip_serializing_if = "Option::is_none")] pub task_suite: Option, } /// Explicit inputs enabling isolated real-Emacs benchmarks for a new project. #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct TaskSuiteOptions { /// Reviewed task descriptions and state-oracle identities. pub data: PathBuf, /// Self-contained Lisp runner copied into the project's frozen directory. pub runner: PathBuf, /// Local Emacs executable used for both sides of each comparison. pub emacs: PathBuf, /// Maximum elapsed time for one isolated Emacs batch invocation. pub timeout_seconds: u64, } /// Immutable execution-suite identities and explicit runtime configuration. /// Cloning copies evidence values and paths, never a running Emacs process. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct FrozenTaskSuite { /// Exact bytes of frozen/emacs-tasks.json. pub tasks_sha256: String, /// Exact bytes of frozen/emacs-task-runner.el. pub runner_sha256: String, /// Absolute executable path; each comparison also binds its actual bytes. pub emacs: PathBuf, /// Timeout shared by baseline and candidate execution. pub timeout_seconds: u64, } /// Explicit activation with enough evidence to restore the preceding artifact. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct Activation { /// Current selected model and its bound run identity. pub current: ActiveModel, /// Previous selection retained for an explicit rollback. pub previous: Option, } /// One verified finalized artifact selected for inference. #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct ActiveModel { /// Finalized candidate run, or `baseline` for the original snapshot. pub run: String, /// Absolute immutable artifact directory. pub model: PathBuf, /// Expected artifact bytes. pub artifact: ArtifactIdentity, }