File size: 12,961 Bytes
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a54697
 
 
2109241
 
 
 
 
 
18de23f
 
 
2109241
 
 
4a54697
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
18de23f
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18de23f
 
2109241
 
 
 
4a54697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18de23f
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//! 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<String>,
    /// 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<FrozenTaskSuite>,
    /// All durable attempt records, including failed and cancelled runs.
    pub runs: Vec<RunInfo>,
    /// Explicitly activated finalized model, if any.
    pub active_model: Option<PathBuf>,
    /// Open action catalog file when backed by a bi-encoder baseline.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub catalog_file: Option<PathBuf>,
}

/// Summary returned after merging newly discovered actions into `<project>/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 `<project>/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<ArtifactIdentity>,
    /// Hash of the internally generated benchmark evidence, if available.
    pub benchmark_sha256: Option<String>,
    /// Immutable finalized model location, if eligible and finalized.
    pub finalized_model: Option<PathBuf>,
    /// Infrastructure error associated with failed attempts.
    pub error: Option<String>,
}

/// 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<Comparison>,
    /// Executed task comparison required whenever the project freezes a task suite.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_comparison: Option<crate::task_benchmark::TaskComparison>,
    /// 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<FrozenTaskSuite>,
}

/// 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<ActiveModel>,
}

/// 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,
}