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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! Poison-resistant continual observation, episodic recall, and quarantine sync.
//!
//! Basis: Join-semilattice quarantine ledger (`Consistent` | `Conflicted`) paired with
//! atomic materialization into fast episodic memory (`episodic.json`) and reconciliation
//! into durable trainer examples (`examples.json`).
//! Minimality: Raw model self-predictions are unrepresentable; only external oracle
//! observations (`BehavioralCorrection` or `Teacher`) enter the semilattice. Promotion
//! and training readiness are derived from `(quarantine.json, examples.json, active.json)`
//! without redundant boolean flags.
//! Tightness: Literal arguments are scrubbed at ingestion into canonical dummy constants
//! (`"example"` or `"https://example.org"`), preventing PII persistence while preserving
//! exact `parse_command` clause structure.
//! Law: `Consistent(a) ⊔ Obs(b) = Conflicted({a, b})` for `a != b`, and `Conflicted` is an
//! absorbing top element excluded from both `episodic.json` and `examples.json`.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::io::{
    ProjectLock, atomic_bytes, atomic_json, canonical, digest, manifest, project_catalog, read_json,
    read_run,
};
use super::project_info;
use super::types::{Activation, ProjectInfo, RunStatus, WorkflowError};
use crate::actions::{Action, ActionKind, ParsedClause, Program, parse_command};
use crate::catalog::{
    ActionCatalog, ArgContract, OpenAction, OpenProgram, StringDomain, parse_open_command,
};
use crate::dataset::{
    Example, ExampleFile, clause_key, frozen_maps, materialize_with_catalog,
    merge_examples_with_catalog, parse_examples_with_catalog, training_phrase_with_catalog,
};
use crate::episodic::EpisodicMemory;

/// Verified external supervision source; model self-predictions are unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OracleSource {
    /// User cancelled, undid, or received a refusal, then executed a target command.
    BehavioralCorrection,
    /// Higher-tier teacher agent resolved an unserved or uncertain instruction.
    Teacher,
}

/// Ground-truth supervision supplied by an external oracle for a raw instruction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum OracleResolution {
    /// One or two action labels matching the parsed clauses of `instruction` in order.
    Actions {
        /// Closed-set action labels (excluding `"reject"`).
        labels: Vec<String>,
    },
    /// The single-clause instruction requires capabilities outside the 48-action DSL.
    Reject,
}

/// One external oracle observation submitted to a workspace.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ObservationInput {
    /// Raw English instruction entered by the user; literals are scrubbed before storage.
    pub instruction: String,
    /// Verified external supervision source.
    pub source: OracleSource,
    /// Ground-truth action assignment or rejection.
    pub resolution: OracleResolution,
    /// Explicit hard-example flag; defaults to true for corrections/refusals.
    #[serde(default = "default_hard")]
    pub hard: bool,
}

/// Corrections and fallbacks represent model boundary failures by default.
const fn default_hard() -> bool {
    true
}

/// Monotonic semilattice state for one normalized clause skeleton.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum ClauseState {
    /// Every oracle observation for this clause agreed on a single label.
    Consistent {
        /// Privacy-scrubbed canonical single-clause instruction.
        instruction: String,
        /// Agreed closed-set label (`ActionKind` label or `"reject"`).
        label: String,
        /// Number of agreeing observations recorded.
        observations: u32,
        /// Whether hard-example oversampling applies during retraining.
        hard: bool,
    },
    /// Two or more distinct labels were observed; permanently excluded as ambiguous.
    Conflicted {
        /// Distinct labels asserted for this clause skeleton.
        labels: BTreeSet<String>,
        /// Total observations recorded across conflicting labels.
        observations: u32,
    },
}

impl ClauseState {
    /// Join one new `(label, hard)` observation into this semilattice state.
    fn join(self, label: String, hard: bool) -> Self {
        match self {
            Self::Consistent {
                instruction,
                label: existing_label,
                observations,
                hard: existing_hard,
            } => {
                if existing_label == label {
                    Self::Consistent {
                        instruction,
                        label: existing_label,
                        observations: observations.saturating_add(1),
                        hard: existing_hard || hard,
                    }
                } else {
                    Self::Conflicted {
                        labels: BTreeSet::from([existing_label, label]),
                        observations: observations.saturating_add(1),
                    }
                }
            }
            Self::Conflicted {
                mut labels,
                observations,
            } => {
                labels.insert(label);
                Self::Conflicted {
                    labels,
                    observations: observations.saturating_add(1),
                }
            }
        }
    }
}

/// Persisted quarantine state stored at `<project>/quarantine.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct QuarantineLedger {
    /// Schema version, currently one.
    format_version: u32,
    /// Map from canonical normalized clause key to monotonic `ClauseState`.
    clauses: BTreeMap<String, ClauseState>,
    /// Count of observations skipped because they matched held-out calibration/benchmarks.
    withheld_skipped: u64,
    /// Count of observations skipped because they contradicted frozen base training rows.
    frozen_conflicts: u64,
}

impl Default for QuarantineLedger {
    fn default() -> Self {
        Self {
            format_version: 1,
            clauses: BTreeMap::new(),
            withheld_skipped: 0,
            frozen_conflicts: 0,
        }
    }
}

/// Per-clause outcome produced when ingesting an `ObservationInput`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClauseDisposition {
    /// Clause is consistent and active in fast episodic memory.
    Recorded,
    /// Clause contradicted an earlier observation, sibling clause, or manual example.
    Conflicted,
    /// Clause matched a held-out calibration, benchmark, or task-suite sentence.
    Withheld,
    /// Clause already exists in the frozen shared training set with the same label.
    AlreadyKnown,
    /// Clause contradicted the frozen shared training set and was ignored.
    FrozenConflict,
    /// Syntax, clause count, or argument arity did not match a single valid observation.
    SkippedSyntax,
}

/// Summary of continual-learning state derived from project files.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LearnStatus {
    /// Canonical project path.
    pub project: PathBuf,
    /// Absolute path to `<project>/episodic.json` for fast session binding.
    pub episodic_file: PathBuf,
    /// Optional `<project>/catalog.json` when backed by an open bi-encoder workspace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub catalog_file: Option<PathBuf>,
    /// Number of unambiguous clauses tracked in quarantine.
    pub consistent_count: usize,
    /// Number of unsynchronized additions, hard upgrades, or conflict expungements vs `examples.json`.
    pub pending_sync_count: usize,
    /// Total examples not yet consolidated into the active model (including synced-but-untrained).
    pub unconsolidated_count: usize,
    /// Whether the current materialized generation already failed a non-cancelled run.
    pub generation_exhausted: bool,
    /// Number of ambiguous clauses permanently quarantined.
    pub conflicted_count: usize,
    /// Number of active entries in `episodic.json`.
    pub episodic_count: usize,
    /// Total observations skipped to protect held-out benchmarks/calibration.
    pub withheld_skipped: u64,
    /// Total observations rejected due to contradicting frozen base rows.
    pub frozen_conflicts: u64,
}

/// Result of recording one external oracle observation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ObserveReport {
    /// Ordered final disposition for each inspected clause.
    pub dispositions: Vec<ClauseDisposition>,
    /// Updated workspace learning summary.
    pub status: LearnStatus,
}

/// Result of synchronizing clean quarantine supervision into `examples.json`.
#[derive(Debug, Serialize)]
pub struct SyncReport {
    /// Updated project snapshot after reconciling `examples.json`.
    pub project_info: ProjectInfo,
    /// Updated continual-learning ledger counters.
    pub status: LearnStatus,
    /// Number of consistent examples newly added or upgraded in `examples.json`.
    pub synced_examples: usize,
    /// Number of conflicted examples expunged from `examples.json`.
    pub expunged_conflicts: usize,
}

/// Load `<project>/quarantine.json` or return an empty ledger if not yet created.
fn load_ledger(project: &Path) -> Result<QuarantineLedger, WorkflowError> {
    let path = project.join("quarantine.json");
    if !path.exists() {
        return Ok(QuarantineLedger::default());
    }
    let ledger: QuarantineLedger = read_json(&path)?;
    if ledger.format_version != 1 {
        return Err(WorkflowError::Invalid("unsupported quarantine format_version"));
    }
    Ok(ledger)
}

/// Materialize all consistent clauses into `<project>/episodic.json` atomically.
fn write_episodic(
    project: &Path,
    ledger: &QuarantineLedger,
    catalog: Option<&ActionCatalog>,
) -> Result<EpisodicMemory, WorkflowError> {
    let mut entries = BTreeMap::new();
    for (key, state) in &ledger.clauses {
        if let ClauseState::Consistent { label, .. } = state {
            entries.insert(key.clone(), label.clone());
        }
    }
    let memory = EpisodicMemory::new_with_catalog(entries, catalog)?;
    atomic_json(&project.join("episodic.json"), &memory)?;
    Ok(memory)
}

/// Map current `examples.json` entries by canonical clause key to `(label, hard)`.
fn authored_map(
    authored: &ExampleFile,
    catalog: Option<&ActionCatalog>,
) -> Result<BTreeMap<String, (String, bool)>, WorkflowError> {
    let mut map = BTreeMap::new();
    for example in &authored.examples {
        let key = clause_key(&training_phrase_with_catalog(example, catalog)?)?;
        map.insert(key, (example.label.clone(), example.hard));
    }
    Ok(map)
}

/// Compute active generation and whether `current_gen` already had a terminal failure/ineligible run.
fn inspect_consolidation_runs(
    project: &Path,
    current_gen: &str,
    authored_map: &BTreeMap<String, (String, bool)>,
    catalog: Option<&ActionCatalog>,
) -> Result<(usize, bool), WorkflowError> {
    let active_keys: BTreeSet<String> = if project.join("active.json").is_file() {
        let active: Activation = read_json(&project.join("active.json"))?;
        if active.current.run == "baseline" {
            BTreeSet::new()
        } else {
            let run_dir = project.join("runs").join(&active.current.run);
            let run_cat = if run_dir.join("catalog.json").is_file() {
                Some(ActionCatalog::load_or_builtin(&run_dir.join("catalog.json"))?)
            } else {
                catalog.cloned()
            };
            let active_examples = parse_examples_with_catalog(
                &fs::read(run_dir.join("examples.json"))?,
                run_cat.as_ref(),
            )?;
            authored_map_keys(&active_examples, run_cat.as_ref())?
        }
    } else {
        BTreeSet::new()
    };

    let mut generation_exhausted = false;
    if project.join("runs").is_dir() {
        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"))?;
                let run = read_run(project, &id)?;
                if run.generation == current_gen {
                    match run.status {
                        RunStatus::Failed => generation_exhausted = true,
                        RunStatus::Benchmarked => {
                            let report_path = project.join("runs").join(&id).join("benchmark.json");
                            if report_path.is_file() {
                                let bench: super::types::BenchmarkInfo = read_json(&report_path)?;
                                if !bench.eligible {
                                    generation_exhausted = true;
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    let current_keys: BTreeSet<String> = authored_map.keys().cloned().collect();
    let symmetric_diff = current_keys.symmetric_difference(&active_keys).count();
    Ok((symmetric_diff, generation_exhausted))
}

/// Extract canonical clause keys from an `ExampleFile`.
fn authored_map_keys(
    examples: &ExampleFile,
    catalog: Option<&ActionCatalog>,
) -> Result<BTreeSet<String>, WorkflowError> {
    let mut keys = BTreeSet::new();
    for example in &examples.examples {
        keys.insert(clause_key(&training_phrase_with_catalog(example, catalog)?)?);
    }
    Ok(keys)
}

/// Derive exact synchronization and consolidation counters from `(project, ledger, episodic)`.
fn compute_status(
    project: &Path,
    ledger: &QuarantineLedger,
    episodic_count: usize,
    catalog: Option<&ActionCatalog>,
) -> Result<LearnStatus, WorkflowError> {
    let examples_bytes = fs::read(project.join("examples.json"))?;
    let current_gen = digest(&examples_bytes);
    let authored = authored_map(&parse_examples_with_catalog(&examples_bytes, catalog)?, catalog)?;

    let mut consistent_count = 0_usize;
    let mut pending_sync_count = 0_usize;
    let mut conflicted_count = 0_usize;
    for (key, state) in &ledger.clauses {
        match state {
            ClauseState::Consistent { label, hard, .. } => {
                consistent_count += 1;
                let synced = authored
                    .get(key)
                    .is_some_and(|(auth_label, auth_hard)| auth_label == label && (*auth_hard || !hard));
                if !synced {
                    pending_sync_count += 1;
                }
            }
            ClauseState::Conflicted { .. } => {
                conflicted_count += 1;
                if authored.contains_key(key) {
                    pending_sync_count += 1;
                }
            }
        }
    }
    let (unconsolidated_synced, generation_exhausted) =
        inspect_consolidation_runs(project, &current_gen, &authored, catalog)?;
    let unconsolidated_count = pending_sync_count.saturating_add(unconsolidated_synced);
    Ok(LearnStatus {
        project: project.to_path_buf(),
        episodic_file: project.join("episodic.json"),
        catalog_file: catalog.map(|_| project.join("catalog.json")),
        consistent_count,
        pending_sync_count,
        unconsolidated_count,
        generation_exhausted: pending_sync_count == 0 && generation_exhausted,
        conflicted_count,
        episodic_count,
        withheld_skipped: ledger.withheld_skipped,
        frozen_conflicts: ledger.frozen_conflicts,
    })
}

/// Reconcile `quarantine.json` and `episodic.json` when `examples.json` is manually updated.
pub(super) fn reconcile_manual_examples(
    project: &Path,
    merged: &ExampleFile,
    replaced: bool,
) -> Result<(), WorkflowError> {
    if !project.join("quarantine.json").exists() {
        return Ok(());
    }
    let catalog = project_catalog(project)?;
    let cat_ref = catalog.as_ref();
    let mut ledger = load_ledger(project)?;
    let manual = authored_map(merged, cat_ref)?;
    if replaced {
        let mut retained = BTreeMap::new();
        for (key, state) in ledger.clauses {
            match state {
                ClauseState::Consistent {
                    instruction,
                    observations,
                    ..
                } => {
                    if let Some((new_label, new_hard)) = manual.get(&key) {
                        retained.insert(
                            key,
                            ClauseState::Consistent {
                                instruction,
                                label: new_label.clone(),
                                observations,
                                hard: *new_hard,
                            },
                        );
                    }
                }
                ClauseState::Conflicted {
                    labels,
                    observations,
                } => {
                    if let Some((new_label, new_hard)) = manual.get(&key) {
                        if let Some(example) = merged.examples.iter().find(|ex| {
                            training_phrase_with_catalog(ex, cat_ref)
                                .ok()
                                .and_then(|p| clause_key(&p).ok())
                                .as_deref()
                                == Some(key.as_str())
                        }) {
                            retained.insert(
                                key,
                                ClauseState::Consistent {
                                    instruction: example.instruction.clone(),
                                    label: new_label.clone(),
                                    observations: 1,
                                    hard: *new_hard,
                                },
                            );
                        }
                    } else {
                        retained.insert(
                            key,
                            ClauseState::Conflicted {
                                labels,
                                observations,
                            },
                        );
                    }
                }
            }
        }
        ledger.clauses = retained;
    } else {
        for (key, (manual_label, manual_hard)) in &manual {
            if let Some(existing) = ledger.clauses.remove(key) {
                ledger
                    .clauses
                    .insert(key.clone(), existing.join(manual_label.clone(), *manual_hard));
            }
        }
    }
    atomic_json(&project.join("quarantine.json"), &ledger)?;
    write_episodic(project, &ledger, cat_ref)?;
    Ok(())
}

/// Replace any literal argument in `clause` with a privacy-safe canonical placeholder.
fn sanitize_clause(clause: &ParsedClause, expects_url: bool) -> String {
    if clause.name.is_none() {
        return clause.text.clone();
    }
    let dummy = if expects_url {
        "\"https://example.org\""
    } else {
        "\"example\""
    };
    clause
        .text
        .split_whitespace()
        .map(|word| if word == "NAME" { dummy } else { word })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Extract privacy-scrubbed `(clause_key, sanitized_instruction, label)` triples.
fn extract_candidates(
    input: &ObservationInput,
    catalog: Option<&ActionCatalog>,
) -> Result<Result<Vec<(String, String, String)>, ClauseDisposition>, WorkflowError> {
    let soft_syntax = input.source == OracleSource::BehavioralCorrection;
    let parsed_input = match catalog {
        Some(_) => parse_open_command(&input.instruction),
        None => parse_command(&input.instruction),
    };
    match &input.resolution {
        OracleResolution::Actions { labels } => {
            if !(1..=2).contains(&labels.len()) {
                return Err(WorkflowError::Invalid(
                    "action resolution must supply one or two labels",
                ));
            }
            let clauses = match parsed_input {
                Ok(parsed) => parsed,
                Err(_) if soft_syntax => return Ok(Err(ClauseDisposition::SkippedSyntax)),
                Err(err) => return Err(crate::dataset::DatasetError::from(err).into()),
            };
            if clauses.len() != labels.len() {
                if soft_syntax {
                    return Ok(Err(ClauseDisposition::SkippedSyntax));
                }
                return Err(WorkflowError::Invalid(
                    "clause count does not match resolved action labels",
                ));
            }
            match catalog {
                Some(cat) => {
                    let mut validated = Vec::with_capacity(clauses.len());
                    let mut candidates = Vec::with_capacity(clauses.len());
                    for (clause, label) in clauses.iter().zip(labels) {
                        let Some(spec) = cat.get(label) else {
                            return Err(crate::dataset::DatasetError::Label(label.clone()).into());
                        };
                        let action = match OpenAction::new(spec, clause.name.clone()) {
                            Ok(act) => act,
                            Err(_) if soft_syntax => {
                                return Ok(Err(ClauseDisposition::SkippedSyntax));
                            }
                            Err(err) => return Err(crate::dataset::DatasetError::from(err).into()),
                        };
                        validated.push(action);
                        let expects_url = matches!(
                            spec.contract,
                            ArgContract::String {
                                domain: StringDomain::HttpUrl,
                                ..
                            }
                        );
                        let sanitized = sanitize_clause(clause, expects_url);
                        let key = clause_key(&clause.text)?;
                        candidates.push((key, sanitized, label.clone()));
                    }
                    if let Err(err) = OpenProgram::new(validated) {
                        if soft_syntax {
                            return Ok(Err(ClauseDisposition::SkippedSyntax));
                        }
                        return Err(crate::dataset::DatasetError::from(err).into());
                    }
                    Ok(Ok(candidates))
                }
                None => {
                    let mut validated = Vec::with_capacity(clauses.len());
                    let mut candidates = Vec::with_capacity(clauses.len());
                    for (clause, label) in clauses.iter().zip(labels) {
                        let kind = ActionKind::from_label(label)
                            .map_err(crate::dataset::DatasetError::from)?;
                        let action = match Action::new(kind, clause.name.clone()) {
                            Ok(act) => act,
                            Err(_) if soft_syntax => {
                                return Ok(Err(ClauseDisposition::SkippedSyntax));
                            }
                            Err(err) => return Err(crate::dataset::DatasetError::from(err).into()),
                        };
                        validated.push(action);
                        let sanitized =
                            sanitize_clause(clause, matches!(kind, ActionKind::BrowserUrl));
                        let key = clause_key(&clause.text)?;
                        candidates.push((key, sanitized, label.clone()));
                    }
                    if let Err(err) = Program::new(validated) {
                        if soft_syntax {
                            return Ok(Err(ClauseDisposition::SkippedSyntax));
                        }
                        return Err(crate::dataset::DatasetError::from(err).into());
                    }
                    Ok(Ok(candidates))
                }
            }
        }
        OracleResolution::Reject => {
            let Ok(clauses) = parsed_input else {
                return Ok(Err(ClauseDisposition::SkippedSyntax));
            };
            if clauses.len() != 1 {
                return Ok(Err(ClauseDisposition::SkippedSyntax));
            }
            let clause = &clauses[0];
            let sanitized = sanitize_clause(clause, false);
            let key = clause_key(&clause.text)?;
            if key.is_empty() {
                return Ok(Err(ClauseDisposition::SkippedSyntax));
            }
            Ok(Ok(vec![(key, sanitized, String::from("reject"))]))
        }
    }
}

/// Inspect continual-learning status for `project` without mutating files.
pub fn learn_status(project: &Path) -> Result<LearnStatus, WorkflowError> {
    let project = canonical(project)?;
    manifest(&project)?;
    let catalog = project_catalog(&project)?;
    let ledger = load_ledger(&project)?;
    let episodic =
        EpisodicMemory::load_optional_with_catalog(&project.join("episodic.json"), catalog.as_ref())?;
    compute_status(&project, &ledger, episodic.entries.len(), catalog.as_ref())
}

/// Record an external oracle observation, updating quarantine and `episodic.json` atomically.
pub fn learn_observe(
    project: &Path,
    input: &ObservationInput,
) -> Result<ObserveReport, WorkflowError> {
    let project = canonical(project)?;
    let _lock = ProjectLock::acquire(&project)?;
    manifest(&project)?;
    let catalog = project_catalog(&project)?;
    let cat_ref = catalog.as_ref();
    let candidates = match extract_candidates(input, cat_ref)? {
        Ok(items) => items,
        Err(disposition) => {
            let ledger = load_ledger(&project)?;
            let episodic =
                EpisodicMemory::load_optional_with_catalog(&project.join("episodic.json"), cat_ref)?;
            return Ok(ObserveReport {
                dispositions: vec![disposition],
                status: compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?,
            });
        }
    };
    let training = fs::read(project.join("frozen/training.json"))?;
    let evaluation = fs::read(project.join("frozen/evaluation.json"))?;
    let (frozen_known, reserved) = frozen_maps(&training, &evaluation)?;
    let authored = authored_map(
        &parse_examples_with_catalog(&fs::read(project.join("examples.json"))?, cat_ref)?,
        cat_ref,
    )?;

    let mut ledger = load_ledger(&project)?;
    let mut staged_outcomes: Vec<Result<String, ClauseDisposition>> =
        Vec::with_capacity(candidates.len());
    for (key, sanitized, label) in candidates {
        if reserved.contains(&key) {
            ledger.withheld_skipped = ledger.withheld_skipped.saturating_add(1);
            staged_outcomes.push(Err(ClauseDisposition::Withheld));
            continue;
        }
        if let Some(frozen_label) = frozen_known.get(&key) {
            if frozen_label == &label {
                staged_outcomes.push(Err(ClauseDisposition::AlreadyKnown));
            } else {
                ledger.frozen_conflicts = ledger.frozen_conflicts.saturating_add(1);
                staged_outcomes.push(Err(ClauseDisposition::FrozenConflict));
            }
            continue;
        }
        let next = match ledger.clauses.remove(&key) {
            Some(existing) => existing.join(label, input.hard),
            None => match authored.get(&key) {
                Some((manual_label, _)) if manual_label != &label => ClauseState::Conflicted {
                    labels: BTreeSet::from([manual_label.clone(), label]),
                    observations: 1,
                },
                Some((_, manual_hard)) => ClauseState::Consistent {
                    instruction: sanitized,
                    label,
                    observations: 1,
                    hard: *manual_hard || input.hard,
                },
                None => ClauseState::Consistent {
                    instruction: sanitized,
                    label,
                    observations: 1,
                    hard: input.hard,
                },
            },
        };
        ledger.clauses.insert(key.clone(), next);
        staged_outcomes.push(Ok(key));
    }
    let dispositions = staged_outcomes
        .into_iter()
        .map(|item| match item {
            Err(early) => early,
            Ok(key) => match ledger.clauses.get(&key) {
                Some(ClauseState::Consistent { .. }) => ClauseDisposition::Recorded,
                _ => ClauseDisposition::Conflicted,
            },
        })
        .collect();
    atomic_json(&project.join("quarantine.json"), &ledger)?;
    let episodic = write_episodic(&project, &ledger, cat_ref)?;
    let status = compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?;
    Ok(ObserveReport {
        dispositions,
        status,
    })
}

/// Synchronize consistent quarantine examples into `examples.json` and expunge conflicts.
pub fn learn_sync(project: &Path) -> Result<SyncReport, WorkflowError> {
    let project = canonical(project)?;
    let _lock = ProjectLock::acquire(&project)?;
    manifest(&project)?;
    let catalog = project_catalog(&project)?;
    let cat_ref = catalog.as_ref();
    let training = fs::read(project.join("frozen/training.json"))?;
    let evaluation = fs::read(project.join("frozen/evaluation.json"))?;
    let ledger = load_ledger(&project)?;
    let current =
        parse_examples_with_catalog(&fs::read(project.join("examples.json"))?, cat_ref)?;
    let before_map = authored_map(&current, cat_ref)?;

    let mut expunged_conflicts = 0_usize;
    let mut retained = ExampleFile::default();
    for example in current.examples {
        let key = clause_key(&training_phrase_with_catalog(&example, cat_ref)?)?;
        if matches!(ledger.clauses.get(&key), Some(ClauseState::Conflicted { .. })) {
            expunged_conflicts += 1;
            continue;
        }
        retained.examples.push(example);
    }

    let mut incoming = ExampleFile::default();
    let mut synced_examples = 0_usize;
    for (key, state) in &ledger.clauses {
        if let ClauseState::Consistent {
            instruction,
            label,
            hard,
            ..
        } = state
        {
            let already = before_map
                .get(key)
                .is_some_and(|(auth_label, auth_hard)| auth_label == label && (*auth_hard || !hard));
            if !already {
                synced_examples += 1;
            }
            incoming.examples.push(Example {
                instruction: instruction.clone(),
                label: label.clone(),
                hard: *hard,
            });
        }
    }

    let merged = merge_examples_with_catalog(&training, &evaluation, retained, incoming, cat_ref)?;
    let serialized = serde_json::to_vec_pretty(&merged)?;
    materialize_with_catalog(
        &training,
        &evaluation,
        parse_examples_with_catalog(&serialized, cat_ref)?,
        cat_ref,
    )?;
    atomic_bytes(&project.join("examples.json"), &serialized)?;

    let episodic = write_episodic(&project, &ledger, cat_ref)?;
    let status = compute_status(&project, &ledger, episodic.entries.len(), cat_ref)?;
    let project_info = project_info(&project)?;
    Ok(SyncReport {
        project_info,
        status,
        synced_examples,
        expunged_conflicts,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workflow::{init_project, replace_examples};

    fn setup_workspace(temp: &Path) -> Result<PathBuf, WorkflowError> {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let workspace = temp.join("learn-workspace");
        init_project(
            &workspace,
            root,
            &root.join("data/training.json"),
            &root.join("data/evaluation.json"),
        )?;
        Ok(workspace)
    }

    #[test]
    fn observation_scrubs_private_literals_and_populates_episodic_memory() -> Result<(), WorkflowError>
    {
        let temp = tempfile::tempdir()?;
        let workspace = setup_workspace(temp.path())?;
        let report = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from(
                    "inspect confidential ledger \"/Users/alice/secret-tax-2026.org\" then tidy up panes",
                ),
                source: OracleSource::Teacher,
                resolution: OracleResolution::Actions {
                    labels: vec![
                        String::from("find-file"),
                        String::from("balance-windows"),
                    ],
                },
                hard: true,
            },
        )?;
        assert_eq!(
            report.dispositions,
            vec![ClauseDisposition::Recorded, ClauseDisposition::Recorded]
        );
        assert_eq!(report.status.episodic_count, 2);
        assert_eq!(report.status.pending_sync_count, 2);
        assert_eq!(report.status.unconsolidated_count, 2);

        let raw_quarantine = fs::read_to_string(workspace.join("quarantine.json"))?;
        assert!(!raw_quarantine.contains("secret-tax-2026"));
        assert!(raw_quarantine.contains("\\\"example\\\""));

        let episodic = EpisodicMemory::load_optional(&workspace.join("episodic.json"))?;
        assert_eq!(
            episodic.lookup_clause("inspect confidential ledger NAME")?,
            Some("find-file")
        );
        assert_eq!(
            episodic.lookup_clause("tidy up panes")?,
            Some("balance-windows")
        );
        Ok(())
    }

    #[test]
    fn conflicting_and_intra_request_self_conflicting_clauses_quarantine_and_expunge()
    -> Result<(), WorkflowError> {
        let temp = tempfile::tempdir()?;
        let workspace = setup_workspace(temp.path())?;
        learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("step backward right now"),
                source: OracleSource::BehavioralCorrection,
                resolution: OracleResolution::Actions {
                    labels: vec![String::from("lispm-browser-back")],
                },
                hard: true,
            },
        )?;
        let synced = learn_sync(&workspace)?;
        assert_eq!(synced.synced_examples, 1);
        assert_eq!(synced.status.pending_sync_count, 0);
        // Still unconsolidated because no finalized run is active yet!
        assert_eq!(synced.status.unconsolidated_count, 1);

        let conflict = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("step backward right now"),
                source: OracleSource::BehavioralCorrection,
                resolution: OracleResolution::Actions {
                    labels: vec![String::from("lispm-finder-back")],
                },
                hard: true,
            },
        )?;
        assert_eq!(conflict.dispositions, vec![ClauseDisposition::Conflicted]);
        assert_eq!(conflict.status.episodic_count, 0);
        assert_eq!(conflict.status.pending_sync_count, 1);

        let cleaned = learn_sync(&workspace)?;
        assert_eq!(cleaned.expunged_conflicts, 1);
        assert_eq!(cleaned.project_info.added_examples, 0);
        assert_eq!(cleaned.status.unconsolidated_count, 0);

        // Intra-request identical clause skeleton with distinct actions reports both Conflicted.
        let self_conflict = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from(
                    "launch resource \"https://example.org\" then launch resource \"notes.el\"",
                ),
                source: OracleSource::Teacher,
                resolution: OracleResolution::Actions {
                    labels: vec![
                        String::from("lispm-browser-open-url"),
                        String::from("find-file"),
                    ],
                },
                hard: true,
            },
        )?;
        assert_eq!(
            self_conflict.dispositions,
            vec![ClauseDisposition::Conflicted, ClauseDisposition::Conflicted]
        );
        assert_eq!(self_conflict.status.episodic_count, 0);
        Ok(())
    }

    #[test]
    fn manual_replace_examples_reconciles_quarantine_and_episodic_memory()
    -> Result<(), WorkflowError> {
        let temp = tempfile::tempdir()?;
        let workspace = setup_workspace(temp.path())?;
        learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("beam into dossier \"notes.el\""),
                source: OracleSource::Teacher,
                resolution: OracleResolution::Actions {
                    labels: vec![String::from("find-file")],
                },
                hard: true,
            },
        )?;
        let synced = learn_sync(&workspace)?;
        assert_eq!(synced.project_info.added_examples, 1);

        // Explicitly replacing examples with an empty file removes deleted entries from quarantine.
        let empty = serde_json::to_vec(&ExampleFile::default())?;
        let after_replace = replace_examples(&workspace, &empty, &synced.project_info.generation)?;
        assert_eq!(after_replace.added_examples, 0);
        let status = learn_status(&workspace)?;
        assert_eq!(status.consistent_count, 0);
        assert_eq!(status.episodic_count, 0);

        // Subsequent learn_sync does not resurrect the manually deleted example.
        let resynced = learn_sync(&workspace)?;
        assert_eq!(resynced.project_info.added_examples, 0);
        Ok(())
    }

    #[test]
    fn behavioral_arity_mismatch_held_out_and_multiclause_reject_are_safe()
    -> Result<(), WorkflowError> {
        let temp = tempfile::tempdir()?;
        let workspace = setup_workspace(temp.path())?;

        // Behavioral correction with mismatched arity (0 quotes for find-file) skips gracefully.
        let mismatch = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("hop to next pane"),
                source: OracleSource::BehavioralCorrection,
                resolution: OracleResolution::Actions {
                    labels: vec![String::from("find-file")],
                },
                hard: true,
            },
        )?;
        assert_eq!(mismatch.dispositions, vec![ClauseDisposition::SkippedSyntax]);

        let evaluation_bytes = fs::read(workspace.join("frozen/evaluation.json"))?;
        let evaluation: crate::evaluation::EvaluationData =
            serde_json::from_slice(&evaluation_bytes)?;
        let held_out_phrase = evaluation
            .corpora
            .values()
            .flat_map(|c| &c.cases)
            .find(|case| case.action.is_some() && parse_command(&case.input).is_ok_and(|p| p.len() == 1))
            .expect("held-out single-action case");

        let withheld = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: held_out_phrase.input.clone(),
                source: OracleSource::Teacher,
                resolution: OracleResolution::Actions {
                    labels: vec![
                        held_out_phrase
                            .action
                            .clone()
                            .expect("supported case action"),
                    ],
                },
                hard: true,
            },
        )?;
        assert_eq!(withheld.dispositions, vec![ClauseDisposition::Withheld]);
        assert_eq!(withheld.status.withheld_skipped, 1);
        assert_eq!(withheld.status.episodic_count, 0);

        let multiclause_reject = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("compile everything then save the current buffer"),
                source: OracleSource::Teacher,
                resolution: OracleResolution::Reject,
                hard: true,
            },
        )?;
        assert_eq!(
            multiclause_reject.dispositions,
            vec![ClauseDisposition::SkippedSyntax]
        );
        assert_eq!(multiclause_reject.status.episodic_count, 0);
        Ok(())
    }

    #[test]
    fn open_biencoder_workspace_syncs_new_actions_and_learns_beyond_48()
    -> Result<(), Box<dyn std::error::Error>> {
        let _serial = crate::runtime::test_serial_guard();
        let temp = tempfile::tempdir()?;
        let base_dir = temp.path().join("base-biencoder");
        let vocab = BTreeMap::from([
            ("<pad>".into(), 0),
            ("<unk>".into(), 1),
            ("<cls>".into(), 2),
            ("NAME".into(), 3),
        ]);
        let meta = crate::biencoder::BiEncoderMetadata {
            model_type: String::from(crate::biencoder::BIENCODER_MODEL_TYPE),
            architecture: crate::config::ModelConfig {
                width: 64,
                layers: 1,
                heads: 4,
                feedforward: 128,
                char_buckets: 2048,
                max_ngrams: 32,
                max_words: 60,
                dropout: 0.0,
            },
            reject_prototypes: 8,
            vocab,
            thresholds: crate::config::Thresholds {
                probability: 0.5,
                margin: 0.0,
            },
            extra: BTreeMap::new(),
        };
        let mut bundle =
            crate::biencoder::BiEncoderBundle::new(meta, 42, ActionCatalog::builtin())?;
        bundle.save(&base_dir)?;

        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let workspace = temp.path().join("open-workspace");
        let info = init_project(
            &workspace,
            &base_dir,
            &root.join("data/training.json"),
            &root.join("data/evaluation.json"),
        )?;
        assert!(info.catalog_file.is_some());
        assert_eq!(info.labels.len(), 49);

        let mut extended = ActionCatalog::builtin();
        extended.actions.push(crate::catalog::ActionSpec {
            id: String::from("lispm-1password"),
            function: String::from("lispm-1password"),
            contract: ArgContract::Fixed { args: vec![] },
            description: String::from("Open 1Password vault manager"),
            mode: None,
        });
        let sync_cat = crate::workflow::sync_catalog(&workspace, &extended)?;
        assert_eq!(sync_cat.added_actions, 1);
        assert_eq!(sync_cat.total_actions, 49);

        let obs = learn_observe(
            &workspace,
            &ObservationInput {
                instruction: String::from("open the 1password credential vault"),
                source: OracleSource::BehavioralCorrection,
                resolution: OracleResolution::Actions {
                    labels: vec![String::from("lispm-1password")],
                },
                hard: true,
            },
        )?;
        assert_eq!(obs.dispositions, vec![ClauseDisposition::Recorded]);
        assert_eq!(obs.status.episodic_count, 1);

        let synced = learn_sync(&workspace)?;
        assert_eq!(synced.synced_examples, 1);
        assert_eq!(synced.project_info.added_examples, 1);
        assert_eq!(synced.project_info.labels.len(), 50);
        Ok(())
    }
}