File size: 15,264 Bytes
2109241
 
 
 
 
 
 
 
 
4a54697
 
2109241
 
18de23f
 
36fe364
 
2109241
4a54697
 
 
 
2109241
 
 
 
4a54697
 
2109241
 
4a54697
 
2109241
4a54697
 
 
2109241
4a54697
 
2109241
 
 
 
 
 
 
 
 
 
18de23f
2109241
 
 
4a54697
 
 
 
 
 
 
 
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
4a54697
2109241
18de23f
2109241
 
18de23f
 
 
2109241
 
 
 
4a54697
2109241
 
 
4a54697
 
 
 
 
2109241
 
18de23f
 
 
2109241
 
 
 
 
18de23f
2109241
 
 
18de23f
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
4a54697
2109241
4a54697
2109241
 
4a54697
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a54697
 
 
 
 
2109241
 
4a54697
2109241
 
 
 
 
18de23f
2109241
 
4a54697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
4a54697
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a54697
2109241
 
 
4a54697
2109241
 
4a54697
2109241
 
 
4a54697
 
2109241
 
4a54697
 
 
 
 
 
2109241
4a54697
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! 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<bool, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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 `<project>/catalog.json`.
pub fn sync_catalog(
    project: &Path,
    incoming: &ActionCatalog,
) -> Result<CatalogSyncReport, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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<ProjectInfo, WorkflowError> {
    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)
}