surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
//! Execution (SPEC 8.4) and apply commits (SPEC 8.7).
//!
//! Per target file, holding the store lock: re-read and re-plan if the file
//! changed since planning (up to three times), back up the original bytes,
//! self-check the edited text, write a temp file, compare-and-swap against
//! the planned bytes, replace, then update the ledger and the journal. A
//! failed file never stops the others.
//!
//! [`apply_in`] runs inside a [`Transaction`]: the run is recorded in
//! `machines/<machine-id>.applied.toml` and the `Surjection-Apply` trailer of
//! that transaction's single commit. [`run`] wraps it in its own
//! transaction, which commits only when a file was written.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant};

use crate::access::{self, ReadOnlyKind};
use crate::adapters::adapter;
use crate::apply::backup;
use crate::apply::journal::{FileRecord, Journal, RecordedError};
use crate::apply::ledger::{EntryKind, Ledger, LedgerEntry, LedgerKey, LedgerSlot, Origin};
use crate::apply::plan::{
    self, Action, EntryPlan, EntryState, OpCounts, Plan, PlanOptions, ProjectSelection,
    ScopeFilter, TargetPlan, read_target,
};
use crate::apply::render::{DesiredState, RenderCx};
use crate::apply::{ApplyEnv, import, placeholder_path, temp_path};
use crate::error::{CoreError, ErrorCode};
use crate::formats::{Document, NativeMap, NativeValue};
use crate::layering::ProjectRepo;
use crate::model::applied::{AppliedRecord, AppliedTarget, ApplyOutcome, ApplyTrigger};
use crate::model::ids;
use crate::model::settings::ApplyMode;
use crate::model::{SCHEMA_VERSION, TomlDocument};
use crate::store::{ApplyRef, CommitId, Machine, Operation, Store, Transaction, utc_datetime};

/// Times a file is re-planned after it changed underneath (SPEC 8.4).
const MAX_REPLANS: u32 = 3;
/// How long a replace is retried while another process holds the file.
const LOCK_RETRY: Duration = Duration::from_secs(2);

/// One apply run's inputs.
#[derive(Debug, Clone)]
pub struct ApplyRequest {
    pub options: PlanOptions,
    pub trigger: ApplyTrigger,
}

/// What one target got.
#[derive(Debug, Clone)]
pub struct TargetResult {
    pub clients: Vec<&'static str>,
    pub scope: crate::model::applied::Scope,
    /// The project of a project or project-local target.
    pub project_id: Option<String>,
    /// The project folder `<P>`, when known.
    pub project: Option<PathBuf>,
    pub file: PathBuf,
    /// Operations done (zero when the file was not written).
    pub counts: OpCounts,
    pub outcome: ApplyOutcome,
    /// Why the file failed or is blocked as a whole.
    pub error: Option<CoreError>,
    /// The plan the file was executed with (after any re-plan).
    pub entries: Vec<EntryPlan>,
    pub written: bool,
    pub backup: Option<PathBuf>,
    pub warnings: Vec<CoreError>,
    /// This account cannot write the file: found by the write probe while
    /// planning, or the OS refused the write (`read_only_target`, SPEC
    /// 8.2).
    pub read_only: Option<ReadOnlyKind>,
}

impl TargetResult {
    pub fn unresolved(&self) -> usize {
        self.entries.iter().filter(|entry| entry.unresolved).count()
    }
}

/// The result of an apply run.
#[derive(Debug, Clone)]
pub struct ApplyReport {
    pub apply_id: String,
    pub trigger: ApplyTrigger,
    pub outcome: ApplyOutcome,
    pub targets: Vec<TargetResult>,
    pub warnings: Vec<CoreError>,
    /// Store servers changed by `import` resolutions.
    pub imported: Vec<String>,
    /// Whether the run was recorded in the store (`applied.toml` and the
    /// `Surjection-Apply` trailer).
    pub recorded: bool,
}

impl ApplyReport {
    /// Files written.
    pub fn writes(&self) -> usize {
        self.targets.iter().filter(|target| target.written).count()
    }

    /// Entries that need a decision that was not given.
    pub fn unresolved(&self) -> usize {
        self.targets.iter().map(TargetResult::unresolved).sum()
    }

    /// What the run left for the user, most severe first (SPEC 14 exit
    /// codes 1, 4, 5 and 7; the CLI maps it to its exit code, the app to
    /// its notice).
    pub fn status(&self) -> ApplyStatus {
        status_of(self.targets.iter())
    }

    /// [`Self::status`] over project `id`'s own targets: what trusting that
    /// project left, whatever another project still waits for. The instant
    /// apply after a trust covers the whole machine (#10).
    pub fn project_status(&self, id: &str) -> ApplyStatus {
        status_of(
            self.targets
                .iter()
                .filter(|target| target.project_id.as_deref() == Some(id)),
        )
    }
}

fn status_of<'a>(mut targets: impl Iterator<Item = &'a TargetResult> + Clone) -> ApplyStatus {
    if targets
        .clone()
        .any(|target| target.outcome == ApplyOutcome::Failed)
    {
        ApplyStatus::FileFailed
    } else if targets.clone().any(|target| target.unresolved() > 0) {
        ApplyStatus::NeedsDecision
    } else if targets
        .clone()
        .flat_map(|target| &target.entries)
        .any(EntryPlan::blocked_by_secret)
    {
        ApplyStatus::MissingSecrets
    } else if targets.any(|target| {
        target
            .error
            .as_ref()
            .is_some_and(|error| error.code() == ErrorCode::TrustRequired)
    }) {
        ApplyStatus::TrustRequired
    } else {
        ApplyStatus::Done
    }
}

/// What an apply run left for the user ([`ApplyReport::status`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ApplyStatus {
    /// Nothing: every file is written or needed no change.
    Done,
    /// A file could not be written.
    FileFailed,
    /// Entries need a decision (collision, conflict, drift).
    NeedsDecision,
    /// Entries are blocked by secrets this machine cannot provide.
    MissingSecrets,
    /// A project waits for its manifests to be trusted.
    TrustRequired,
}

/// What a store change touched. Its instant apply plans and writes only
/// those targets (#15), so an unrelated project waiting for trust, or a
/// drifted file elsewhere, neither slows the change nor shows in its
/// result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Touched {
    /// Anything (client preferences, settings, secrets): every target.
    All,
    /// These store servers (added, edited, enabled for other clients,
    /// removed): the targets [`PlanOptions::servers`] selects.
    Servers(Vec<String>),
    /// The known project at this folder (trusted, initialized): its
    /// targets only.
    Project(PathBuf),
}

impl Touched {
    /// The plan that covers what was touched.
    pub fn options(&self) -> PlanOptions {
        match self {
            Touched::All => PlanOptions::default(),
            Touched::Servers(ids) => PlanOptions {
                servers: Some(ids.clone()),
                ..PlanOptions::default()
            },
            Touched::Project(root) => PlanOptions {
                scope: ScopeFilter::Project,
                projects: ProjectSelection::Only(root.clone()),
                ..PlanOptions::default()
            },
        }
    }
}

/// In instant mode (`apply_mode`, the default), applies a staged store edit
/// inside its transaction, so the edit and its apply are one commit
/// (SPEC 8.7): the targets the edit `touched`. `None` in review mode. The
/// desired state is loaded once, for the mode and the plan.
pub fn instant_apply(
    tx: &mut Transaction<'_>,
    ax: &ApplyEnv<'_>,
    touched: &Touched,
) -> Result<Option<ApplyReport>, CoreError> {
    // `surject eject` without filters: this machine is not managed until
    // the user starts managing again.
    if crate::eject::status_at(ax.fs, &ax.home.state_dir())?.is_some_and(|ejected| ejected.all()) {
        return Ok(None);
    }
    let machine = tx.machine().id.clone();
    let desired = DesiredState::load(tx, Some(&machine))?;
    if desired.apply_mode() != ApplyMode::Instant {
        return Ok(None);
    }
    let request = ApplyRequest {
        options: touched.options(),
        trigger: ApplyTrigger::Instant,
    };
    apply_with(tx, ax, &request, Some(desired)).map(Some)
}

/// Plans against the store's working tree (or an empty desired state when
/// there is no store yet). Read-only: creates no ledger key, lock or file.
pub fn preview(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    options: &PlanOptions,
) -> Result<Plan, CoreError> {
    let inputs = PlanInputs::load(store, ax)?;
    plan::plan(
        &ax.render_cx(inputs.memory),
        &inputs.desired,
        &inputs.ledger,
        &inputs.key,
        options,
    )
}

/// What a read-only plan runs against: the desired state of the store's
/// working tree, the ledger, its key and the secret memory.
pub(crate) struct PlanInputs {
    pub(crate) desired: DesiredState,
    pub(crate) ledger: Ledger,
    pub(crate) key: LedgerKey,
    pub(crate) memory: std::sync::Arc<crate::secrets::scanner::SecretMemory>,
}

impl PlanInputs {
    /// Loads the inputs without creating anything (no ledger key, lock or
    /// file); an empty desired state when there is no store yet.
    pub(crate) fn load(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Self, CoreError> {
        let state_dir = ax.home.state_dir();
        let machine = Machine::load(ax.fs, &state_dir)?;
        let desired = match store {
            Some(store) => DesiredState::load(store, machine.as_ref().map(|m| m.id.as_str()))?,
            None => DesiredState::empty(),
        };
        let ledger = Ledger::load(ax.fs, &state_dir)?;
        // Without a key file nothing was ever hashed: any key plans the same.
        let key = match LedgerKey::load(ax.fs, &state_dir)? {
            Some(key) => key,
            None => LedgerKey::from_bytes([0; 32]),
        };
        let memory = match store {
            Some(store) => store.secret_memory().clone(),
            None => std::sync::Arc::new(crate::secrets::scanner::SecretMemory::new()?),
        };
        Ok(Self {
            desired,
            ledger,
            key,
            memory,
        })
    }
}

/// A standalone apply run in its own transaction: one commit when a file
/// was written, none otherwise (SPEC 8.7).
pub fn run(
    store: &Store<'_>,
    ax: &ApplyEnv<'_>,
    request: &ApplyRequest,
) -> Result<(ApplyReport, Option<CommitId>), CoreError> {
    let operation = Operation::new("apply", "apply");
    let committed = store.transaction(operation, |tx| apply_in(tx, ax, request))?;
    Ok((committed.value, committed.commit))
}

/// Plans against the transaction's view of the store (staged edits
/// included), executes, and records the run in the transaction: always
/// when the transaction commits anyway (an instant-mode edit, a rollback),
/// otherwise only when a file was written. Staged edits are validated and
/// leak-scanned first, so an edit the commit would refuse never reaches a
/// client file.
pub fn apply_in(
    tx: &mut Transaction<'_>,
    ax: &ApplyEnv<'_>,
    request: &ApplyRequest,
) -> Result<ApplyReport, CoreError> {
    apply_with(tx, ax, request, None)
}

/// [`apply_in`] with the transaction's desired state loaded already.
fn apply_with(
    tx: &mut Transaction<'_>,
    ax: &ApplyEnv<'_>,
    request: &ApplyRequest,
    desired: Option<DesiredState>,
) -> Result<ApplyReport, CoreError> {
    tx.check()?;
    let state_dir = ax.home.state_dir();
    let machine = tx.machine().clone();
    let cx = ax.render_cx(tx.store().secret_memory().clone());
    let mut ledger = Ledger::load(ax.fs, &state_dir)?;
    let key = LedgerKey::load_or_create(ax.fs, &state_dir)?;

    let mut desired = match desired {
        Some(desired) => desired,
        None => DesiredState::load(tx, Some(&machine.id))?,
    };
    let mut plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
    let mut imported = Vec::new();
    if plan
        .targets
        .iter()
        .flat_map(|target| &target.entries)
        .any(import::is_store_resolution)
    {
        let resolutions = import::stage_resolutions(tx, &plan, &desired)?;
        imported = resolutions.changed;
        desired = DesiredState::load(tx, Some(&machine.id))?;
        plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
        // Whatever still asks for an import or a release of a desired
        // entry could not be staged.
        for entry in plan
            .targets
            .iter_mut()
            .flat_map(|target| &mut target.entries)
        {
            if !import::is_store_resolution(entry) {
                continue;
            }
            let reason = resolutions
                .failed
                .iter()
                .find(|(client, name, _)| {
                    Some(client.as_str()) == entry.client && *name == entry.name
                })
                .map(|(_, _, err)| err.clone());
            let fallback = if entry.action == Action::Release {
                "the entry is still desired for this client after the release"
            } else {
                "the store definition still renders differently after the import"
            };
            entry.action = Action::Skip;
            entry.unresolved = true;
            entry.problem =
                Some(reason.unwrap_or_else(|| CoreError::new(ErrorCode::InvalidValue, fallback)));
        }
    }

    let base = tx.store().head()?;
    let now = ax.env.now();
    let apply_id = ids::new_ulid(now)?;
    let mut journal = Journal::start(
        ax.fs,
        &state_dir,
        &apply_id,
        request.trigger,
        utc_datetime(now).to_string(),
    )?;
    let mut executor = Executor {
        cx: &cx,
        ax,
        key: &key,
        options: &request.options,
        run_dir: backup::run_dir(ax.home, now, &apply_id),
        written_at: utc_datetime(now).to_string(),
        store_commit: base.short().to_owned(),
    };
    let mut targets: Vec<TargetResult> = Vec::with_capacity(plan.targets.len());
    // SPEC 8.4 step 5: the ownership of a written file is saved right after
    // it; ledger-only changes (adopt, refresh, forget, release) go with the
    // next save. `unsaved` are the targets whose changes are not saved yet.
    let mut unsaved: Vec<usize> = Vec::new();
    for target in plan.targets {
        let (mut result, changed) = executor.execute(target, &mut ledger);
        let index = targets.len();
        if changed {
            unsaved.push(index);
        }
        if changed && result.written {
            if let Err(err) = ledger.save(ax.fs, &state_dir) {
                for earlier in unsaved.drain(..).filter(|earlier| *earlier != index) {
                    ownership_lost(&mut targets[earlier], &err);
                    journal.files[earlier] = file_record(&targets[earlier]);
                }
                ownership_lost(&mut result, &err);
            }
            unsaved.clear();
        }
        if let Err(err) = journal.record(ax.fs, &state_dir, file_record(&result)) {
            // What was done stays owned, whatever stops the run.
            if !unsaved.is_empty() {
                let _ = ledger.save(ax.fs, &state_dir);
            }
            return Err(err);
        }
        targets.push(result);
    }
    if !unsaved.is_empty()
        && let Err(err) = ledger.save(ax.fs, &state_dir)
    {
        for index in unsaved {
            ownership_lost(&mut targets[index], &err);
            journal.files[index] = file_record(&targets[index]);
        }
    }
    let outcome = run_outcome(&targets);
    let writes = targets.iter().filter(|target| target.written).count();

    let commits_anyway = tx.has_changes();
    let recorded = commits_anyway || writes > 0;
    if recorded {
        let record = AppliedRecord {
            schema: SCHEMA_VERSION,
            machine_id: machine.id.clone(),
            apply_id: apply_id.clone(),
            time: utc_datetime(now),
            store_revision: base.as_str().to_owned(),
            trigger: request.trigger,
            outcome,
            targets: targets
                .iter()
                .map(|target| AppliedTarget {
                    client: target.clients[0].to_owned(),
                    scope: target.scope,
                    project_id: target.project_id.clone(),
                    file: placeholder_path(ax.env, &target.file, target.project.as_deref()),
                    create: target.counts.create,
                    update: target.counts.update,
                    remove: target.counts.remove,
                    disable: target.counts.disable,
                    outcome: target.outcome,
                    extra: toml::Table::new(),
                })
                .collect(),
            extra: toml::Table::new(),
        };
        let relative = format!("machines/{}.applied.toml", machine.id);
        tx.write(&relative, TomlDocument::new(record).to_text()?)?;
        tx.set_apply(ApplyRef {
            id: apply_id.clone(),
            outcome,
        });
        if !commits_anyway {
            tx.set_summary(summary(&targets));
        }
    }
    journal.finish(ax.fs, &state_dir, outcome)?;
    backup::prune(ax.fs, ax.home, now)?;
    crate::diagnostics::log::event(
        "apply",
        &[
            ("targets", &targets.len()),
            ("writes", &writes),
            ("outcome", &format!("{outcome:?}").to_lowercase()),
        ],
    );

    Ok(ApplyReport {
        apply_id,
        trigger: request.trigger,
        outcome,
        targets,
        warnings: plan.warnings,
        imported,
        recorded,
    })
}

/// `apply: 2 files (claude-code, codex)`.
fn summary(targets: &[TargetResult]) -> String {
    let written: Vec<&TargetResult> = targets.iter().filter(|target| target.written).collect();
    let mut clients: Vec<&str> = Vec::new();
    for target in &written {
        for client in &target.clients {
            if !clients.contains(client) {
                clients.push(client);
            }
        }
    }
    let files = if written.len() == 1 { "file" } else { "files" };
    format!("apply: {} {files} ({})", written.len(), clients.join(", "))
}

/// The outcome of a run from its targets: `ok` when every target is ok,
/// `failed` or `blocked` when none got anywhere, `partial` otherwise.
fn run_outcome(targets: &[TargetResult]) -> ApplyOutcome {
    let count = |outcome| targets.iter().filter(|t| t.outcome == outcome).count();
    let (ok, partial, failed) = (
        count(ApplyOutcome::Ok),
        count(ApplyOutcome::Partial),
        count(ApplyOutcome::Failed),
    );
    if ok == targets.len() {
        ApplyOutcome::Ok
    } else if ok + partial == 0 && failed > 0 {
        ApplyOutcome::Failed
    } else if ok + partial == 0 {
        ApplyOutcome::Blocked
    } else {
        ApplyOutcome::Partial
    }
}

fn file_record(result: &TargetResult) -> FileRecord {
    FileRecord {
        clients: result.clients.iter().map(|c| (*c).to_owned()).collect(),
        scope: result.scope,
        file: result.file.to_string_lossy().into_owned(),
        outcome: result.outcome,
        create: result.counts.create,
        update: result.counts.update,
        remove: result.counts.remove,
        disable: result.counts.disable,
        written: result.written,
        backup: result
            .backup
            .as_ref()
            .map(|path| path.to_string_lossy().into_owned()),
        old_values: false,
        backup_removed: false,
        error: result.error.as_ref().map(RecordedError::from),
    }
}

struct Executor<'a> {
    cx: &'a RenderCx<'a>,
    ax: &'a ApplyEnv<'a>,
    key: &'a LedgerKey,
    options: &'a PlanOptions,
    run_dir: PathBuf,
    written_at: String,
    store_commit: String,
}

impl Executor<'_> {
    /// Executes one target; also returns whether its ownership changed in
    /// `ledger`.
    fn execute(&mut self, plan: TargetPlan, ledger: &mut Ledger) -> (TargetResult, bool) {
        let mut plan = plan;
        let mut replans = 0;
        loop {
            let current = match read_target(self.ax.fs, &plan.file) {
                Ok(bytes) => bytes,
                Err(err) => return (failed(plan, err), false),
            };
            if current != plan.before {
                replans += 1;
                if replans > MAX_REPLANS {
                    let err = changed_during_apply(&plan.file);
                    return (failed(plan, err), false);
                }
                plan = self.replan(plan, current, ledger);
                continue;
            }
            if let Some(problem) = plan.problem.clone() {
                return (
                    finished(plan, ApplyOutcome::Blocked, Some(problem), false, None),
                    false,
                );
            }
            if let Err(err) = self.exclude(&plan) {
                return (failed(plan, err), false);
            }
            let Some(after) = plan.after.clone() else {
                // Ledger-only work (adopt, refresh, forget, release).
                let changed = self.update_ledger(&plan, ledger);
                let outcome = entry_outcome(&plan, false);
                return (finished(plan, outcome, None, false, None), changed);
            };
            if let Err(err) = self_check(&plan, &after) {
                return (failed(plan, err), false);
            }
            let backup = match &current {
                Some(bytes) => {
                    match backup::save(self.ax.fs, self.ax.home, &self.run_dir, &plan.file, bytes) {
                        Ok(path) => Some(path),
                        Err(err) => return (failed(plan, err), false),
                    }
                }
                None => None,
            };
            match self.write(&plan, &after) {
                Ok(true) => {}
                Ok(false) => {
                    // Compare-and-swap failed: the file changed after the
                    // re-read above. Re-plan against what is there now.
                    replans += 1;
                    if replans > MAX_REPLANS {
                        let err = changed_during_apply(&plan.file);
                        return (failed(plan, err), false);
                    }
                    let now = match read_target(self.ax.fs, &plan.file) {
                        Ok(bytes) => bytes,
                        Err(err) => return (failed(plan, err), false),
                    };
                    plan = self.replan(plan, now, ledger);
                    continue;
                }
                Err(err) => return (failed(plan, err), false),
            }
            let changed = self.update_ledger(&plan, ledger);
            let outcome = entry_outcome(&plan, true);
            return (finished(plan, outcome, None, true, backup), changed);
        }
    }

    fn replan(&self, plan: TargetPlan, bytes: Option<Vec<u8>>, ledger: &Ledger) -> TargetPlan {
        plan::plan_target(self.cx, plan.input, bytes, ledger, self.key, self.options)
    }

    /// Temp file, compare-and-swap, replace. `Ok(false)` when the file no
    /// longer holds the planned bytes; the temp file is removed then.
    fn write(&self, plan: &TargetPlan, after: &[u8]) -> Result<bool, CoreError> {
        swap_file(self.ax.fs, &plan.file, plan.before.as_deref(), after)
    }

    /// SPEC 6.5: a project file that holds private entries and that the
    /// project's repository does not track is hidden through its
    /// `info/exclude`, before anything is written and also when nothing
    /// is (an adopted entry, an earlier failure). A failure fails the
    /// target: nothing private is written into a file git may pick up.
    fn exclude(&self, plan: &TargetPlan) -> Result<(), CoreError> {
        let (true, Some(root)) = (plan.input.exclude, plan.project.as_deref()) else {
            return Ok(());
        };
        if let Some(repo) = ProjectRepo::discover(root)? {
            repo.exclude(self.ax.fs, &plan.file)?;
        }
        Ok(())
    }
}

/// SPEC 8.4 step 4: writes `after` to a temp file next to `file` (with the
/// file's permissions when it exists), checks that `file` still holds
/// `expected` (compare-and-swap), then replaces it, retrying a Windows
/// sharing violation for [`LOCK_RETRY`] before `file_locked`. `Ok(false)`
/// when the file changed; the temp file is removed then.
pub(crate) fn swap_file(
    fs: &dyn crate::fs::Fs,
    file: &Path,
    expected: Option<&[u8]>,
    after: &[u8],
) -> Result<bool, CoreError> {
    let io = |what: &str, at: &Path, err: std::io::Error| access::write_error(fs, what, at, &err);
    if let Some(dir) = file.parent() {
        fs.create_dir_all(dir)
            .map_err(|err| io("cannot create directory", dir, err))?;
    }
    let temp = temp_path(file)?;
    let like = expected.is_some().then_some(file);
    fs.write_new(&temp, after, like)
        .map_err(|err| io("cannot write temp file", &temp, err))?;
    let discard = || {
        let _ = fs.remove_file(&temp);
    };
    match read_target(fs, file) {
        Ok(now) if now.as_deref() == expected => {}
        Ok(_) => {
            discard();
            return Ok(false);
        }
        Err(err) => {
            discard();
            return Err(err);
        }
    }
    let deadline = Instant::now() + LOCK_RETRY;
    let mut pause = Duration::from_millis(25);
    loop {
        match fs.replace(&temp, file) {
            Ok(()) => return Ok(true),
            Err(err) if is_sharing_violation(&err) && Instant::now() < deadline => {
                // Access denied here is also what a read-only file gives
                // (the read-only attribute, an ACL without DELETE on the
                // file and FILE_DELETE_CHILD on its folder) as well as a
                // handle held without delete sharing: only a file the
                // probe (which asks for write and delete) finds writable is
                // waited for as a lock.
                if let Some(kind) = refused(fs, &err, file) {
                    discard();
                    return Err(access::read_only_target(kind, file));
                }
                thread::sleep(pause.min(deadline.saturating_duration_since(Instant::now())));
                pause = (pause * 2).min(Duration::from_millis(200));
            }
            Err(err) if is_sharing_violation(&err) => {
                discard();
                return Err(CoreError::new(
                    ErrorCode::FileLocked,
                    format!(
                        "another process kept the file open for {} s: {err}",
                        LOCK_RETRY.as_secs()
                    ),
                )
                .with_path(file));
            }
            Err(err) => {
                discard();
                return Err(io("cannot replace file", file, err));
            }
        }
    }
}

impl Executor<'_> {
    /// Records every entry's new ownership state in `ledger` (saved once
    /// after the run, see [`apply_in`]). Returns whether it changed.
    fn update_ledger(&self, plan: &TargetPlan, ledger: &mut Ledger) -> bool {
        let file = plan.file.to_string_lossy().into_owned();
        let slot = LedgerSlot {
            scope: plan.scope,
            project_id: plan.project_id.as_deref(),
            file: &file,
            container: &plan.pointer,
        };
        let known = ledger.slot_entries(&slot);
        // What this batch did to a key so far, for a later entry of the
        // same key (duplicate keys in a file): its origin, `None` once
        // removed.
        let mut done: HashMap<String, Option<Option<Origin>>> = HashMap::new();
        let mut changes: Vec<(String, Option<LedgerEntry>)> = Vec::new();
        for entry in &plan.entries {
            let origin = match entry.action {
                Action::Create => Some(Origin::Created),
                Action::Adopt | Action::AdoptOverwrite => Some(Origin::Adopted),
                Action::Update | Action::Disable | Action::Refresh => Some(
                    match done.get(&entry.name) {
                        Some(origin) => origin.flatten(),
                        None => known.get(&entry.name).and_then(|known| known.origin),
                    }
                    .unwrap_or(Origin::Created),
                ),
                Action::Remove | Action::Forget | Action::Release => {
                    done.insert(entry.name.clone(), None);
                    changes.push((entry.name.clone(), None));
                    None
                }
                Action::None | Action::Import | Action::Skip => None,
            };
            let Some(origin) = origin else {
                continue;
            };
            let (Some(client), Some(value)) = (entry.client, &entry.written) else {
                continue;
            };
            let written_hash = match plan.kind {
                EntryKind::McpEntry => match plan::canonical(client, value) {
                    Some(canonical) => Some(self.key.hash(&canonical)),
                    None => continue,
                },
                // A list member is its own value.
                EntryKind::ListMember => None,
            };
            let row = LedgerEntry {
                kind: plan.kind,
                client: client.to_owned(),
                scope: plan.scope,
                project_id: plan.project_id.clone(),
                file: file.clone(),
                container: plan.pointer.clone(),
                key: entry.name.clone(),
                server_id: entry.server_id.clone(),
                origin: Some(origin),
                written_hash,
                written_at: Some(self.written_at.clone()),
                store_commit: Some(self.store_commit.clone()),
                delivery: entry.delivery.map(str::to_owned),
                extra: serde_json::Map::new(),
            };
            done.insert(entry.name.clone(), Some(Some(origin)));
            changes.push((entry.name.clone(), Some(row)));
        }
        drop(known);
        ledger.update_slot(&slot, changes)
    }
}

fn changed_during_apply(file: &Path) -> CoreError {
    CoreError::new(
        ErrorCode::FileChangedDuringApply,
        format!(
            "the file kept changing during apply ({MAX_REPLANS} re-plans); it was left as it is"
        ),
    )
    .with_path(file)
}

/// The outcome of a target that was executed: blocked or unresolved
/// entries make it `partial` when something was done, `blocked` otherwise.
fn entry_outcome(plan: &TargetPlan, wrote: bool) -> ApplyOutcome {
    let stuck = plan
        .entries
        .iter()
        .any(|entry| entry.state == EntryState::Blocked || entry.unresolved);
    let did = wrote
        || plan.entries.iter().any(|entry| {
            matches!(
                entry.action,
                Action::Adopt | Action::Refresh | Action::Forget | Action::Release
            )
        });
    match (stuck, did) {
        (false, _) => ApplyOutcome::Ok,
        (true, true) => ApplyOutcome::Partial,
        (true, false) => ApplyOutcome::Blocked,
    }
}

fn finished(
    mut plan: TargetPlan,
    outcome: ApplyOutcome,
    error: Option<CoreError>,
    written: bool,
    backup: Option<PathBuf>,
) -> TargetResult {
    if written {
        plan.warnings
            .extend(restart_required(&plan.clients, &plan.file));
    }
    TargetResult {
        counts: if written {
            plan.counts()
        } else {
            OpCounts::default()
        },
        clients: plan.clients,
        scope: plan.scope,
        project_id: plan.project_id,
        project: plan.project,
        file: plan.file,
        outcome,
        error,
        entries: plan.entries,
        written,
        backup,
        warnings: plan.warnings,
        read_only: plan.read_only,
    }
}

/// `restart_required` for each client of a written file that reads it only
/// at launch (Claude Desktop, gate V2 AP-6).
fn restart_required(clients: &[&'static str], file: &Path) -> Vec<CoreError> {
    clients
        .iter()
        .filter_map(|&client| adapter(client))
        .filter(|spec| {
            spec.mcp
                .as_ref()
                .is_some_and(|mcp| mcp.caps.restart_required)
        })
        .map(|spec| {
            CoreError::new(
                ErrorCode::RestartRequired,
                format!(
                    "{0} reads this file only at launch: fully quit {0} (also from the system \
                     tray or menu bar) and start it again to load the change",
                    spec.display_name
                ),
            )
            .with_path(file)
        })
        .collect()
}

/// A target whose new ownership could not be saved: it fails, and what was
/// written stays written (with its backup and restart notes).
fn ownership_lost(target: &mut TargetResult, err: &CoreError) {
    target.outcome = ApplyOutcome::Failed;
    target.error = Some(err.clone());
    target.counts = OpCounts::default();
}

fn failed(mut plan: TargetPlan, err: CoreError) -> TargetResult {
    // A write the OS refused as read only: blocked like a file the probe
    // found read only, never a failure; the run goes on (SPEC 8.2). The
    // file is marked read only only when the refused write was its own
    // (the file, its temp file, a folder on its way); a read-only
    // `info/exclude` blocks the target without blaming its file.
    if let Some(kind) = err.read_only() {
        if err.path().is_some_and(|at| own_write(&plan.file, at)) {
            plan.read_only = Some(kind);
        }
        for entry in &mut plan.entries {
            if entry.action.writes() {
                entry.state = EntryState::Blocked;
                entry.action = Action::None;
                entry.unresolved = false;
                entry.problem = Some(err.clone());
            }
        }
        return finished(plan, ApplyOutcome::Blocked, Some(err), false, None);
    }
    finished(plan, ApplyOutcome::Failed, Some(err), false, None)
}

/// Whether a write at `at` was one of `file`'s own: the file, a sibling
/// (its temp file) or a folder on its way.
fn own_write(file: &Path, at: &Path) -> bool {
    at == file || at.parent() == file.parent() || file.starts_with(at)
}

/// Of a replace refused with access denied on Windows, the kind of
/// read-only file it hit, when the write probe finds `file` read only;
/// `None` for a file another process holds (retried, then
/// `file_locked`).
#[cfg(windows)]
fn refused(fs: &dyn crate::fs::Fs, err: &std::io::Error, file: &Path) -> Option<ReadOnlyKind> {
    if err.raw_os_error() != Some(5) {
        return None;
    }
    fs.write_probe().and_then(|probe| probe(file).read_only())
}

#[cfg(not(windows))]
fn refused(_fs: &dyn crate::fs::Fs, _err: &std::io::Error, _file: &Path) -> Option<ReadOnlyKind> {
    None
}

#[cfg(windows)]
fn is_sharing_violation(err: &std::io::Error) -> bool {
    // ERROR_ACCESS_DENIED (a handle without FILE_SHARE_DELETE),
    // ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION.
    matches!(err.raw_os_error(), Some(5 | 32 | 33))
}

#[cfg(not(windows))]
fn is_sharing_violation(_err: &std::io::Error) -> bool {
    false
}

/// SPEC 8.4 step 3: the edited text parses, owned entries read back as
/// planned, and everything else (other entries of the container and
/// everything outside it) is unchanged.
fn self_check(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
    let fail = |detail: String| {
        Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
    };
    let format = plan.input.target.format;
    if plan.kind == EntryKind::ListMember {
        return self_check_list(plan, after);
    }
    let after_doc = match Document::parse(after, format) {
        Ok(doc) => doc,
        Err(err) => return fail(format!("the edited file does not parse: {err}")),
    };
    let before_doc = match &plan.before {
        Some(bytes) => Document::parse(bytes, format)?,
        None => plan.input.target.new_document(),
    };
    let container: Vec<&str> = plan.container.iter().map(String::as_str).collect();
    let mut planned: Vec<&str> = Vec::new();
    for entry in &plan.entries {
        planned.push(&entry.name);
        let got = after_doc.get(&container, &entry.name)?;
        let ok = match entry.action {
            Action::Create | Action::Update | Action::AdoptOverwrite | Action::Disable => {
                match (entry.client, &entry.written, &got) {
                    (Some(client), Some(want), Some(got)) => {
                        plan::canonical(client, got) == plan::canonical(client, want)
                    }
                    _ => false,
                }
            }
            Action::Remove => got.is_none(),
            _ => got == entry.observed,
        };
        if !ok {
            return fail(format!(
                "entry {:?} does not read back as planned",
                entry.name
            ));
        }
    }
    for name in before_doc.list(&container)? {
        if !planned.contains(&name.as_str())
            && before_doc.get(&container, &name)? != after_doc.get(&container, &name)?
        {
            return fail(format!("entry {name:?} is not owned but changed"));
        }
    }
    if outside(&before_doc, &container)? != outside(&after_doc, &container)? {
        return fail("something outside the server container changed".to_owned());
    }
    Ok(())
}

/// [`self_check`] of a list target: planned members are present or absent
/// as planned, every other member and everything outside the list is
/// unchanged.
fn self_check_list(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
    let fail = |detail: String| {
        Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
    };
    let format = plan.input.target.format;
    let after_doc = match Document::parse(after, format) {
        Ok(doc) => doc,
        Err(err) => return fail(format!("the edited file does not parse: {err}")),
    };
    let before_doc = match &plan.before {
        Some(bytes) => Document::parse(bytes, format)?,
        None => plan.input.target.new_document(),
    };
    let list: Vec<&str> = plan.container.iter().map(String::as_str).collect();
    let before = plan::list_members(&before_doc, &list)?;
    let after_members = plan::list_members(&after_doc, &list)?;
    for entry in &plan.entries {
        let want = match entry.action {
            Action::Create => true,
            Action::Remove => false,
            _ => before.contains(&entry.name),
        };
        if after_members.contains(&entry.name) != want {
            return fail(format!(
                "list member {:?} does not read back as planned",
                entry.name
            ));
        }
    }
    let others = |members: &[String]| -> Vec<String> {
        members
            .iter()
            .filter(|member| !plan.entries.iter().any(|entry| entry.name == **member))
            .cloned()
            .collect()
    };
    if others(&before) != others(&after_members) {
        return fail("a list member that is not owned changed".to_owned());
    }
    if outside(&before_doc, &list)? != outside(&after_doc, &list)? {
        return fail("something outside the list changed".to_owned());
    }
    Ok(())
}

/// The whole document without the container at `path` (and the empty
/// objects that held only it). For a list keyed by a `[field]` segment
/// (Continue's `mcpServers`), only the items the container addresses by
/// name are taken out: items without a scalar `field`, items that are not
/// mappings and later items repeating a name stay, so a change to them
/// fails the check.
fn outside(doc: &Document, path: &[&str]) -> Result<NativeValue, CoreError> {
    let mut root = document_value(doc)?;
    strip_container(&mut root, path);
    Ok(root)
}

/// The whole document as one value.
pub(crate) fn document_value(doc: &Document) -> Result<NativeValue, CoreError> {
    let mut root = NativeMap::new();
    for key in doc.list(&[])? {
        if let Some(value) = doc.get(&[], &key)? {
            root.insert(key, value);
        }
    }
    Ok(NativeValue::Object(root))
}

/// Takes the container at `path` out of `root` (a [`document_value`]), as
/// [`outside`] describes.
pub(crate) fn strip_container(root: &mut NativeValue, path: &[&str]) {
    let keys = crate::formats::mapping_path(path);
    let Some(segment) = path.get(keys.len()) else {
        remove_path(root, keys);
        return;
    };
    let field = &segment[1..segment.len() - 1];
    let empty = match value_at_mut(root, keys) {
        Some(NativeValue::Array(items)) => {
            let mut seen: Vec<NativeValue> = Vec::new();
            items.retain(|item| {
                let name = item
                    .as_object()
                    .and_then(|entry| entry.get(field))
                    .filter(|name| !matches!(name, NativeValue::Array(_) | NativeValue::Object(_)));
                match name {
                    Some(name) if !seen.contains(name) => {
                        seen.push(name.clone());
                        false
                    }
                    _ => true,
                }
            });
            items.is_empty()
        }
        Some(NativeValue::Object(map)) => map.is_empty(),
        Some(NativeValue::Null) => true,
        _ => false,
    };
    if empty {
        remove_path(root, keys);
    }
}

/// The value at `path` in nested objects.
fn value_at_mut<'v>(value: &'v mut NativeValue, path: &[&str]) -> Option<&'v mut NativeValue> {
    path.iter().try_fold(value, |value, key| match value {
        NativeValue::Object(map) => map.get_mut(key),
        _ => None,
    })
}

/// Removes `path` from `value`, then each ancestor left empty.
fn remove_path(value: &mut NativeValue, path: &[&str]) -> bool {
    let NativeValue::Object(map) = value else {
        return false;
    };
    match path {
        [] => false,
        [last] => {
            map.remove(last);
            map.is_empty()
        }
        [first, rest @ ..] => {
            let Some(child) = map.get_mut(first) else {
                return false;
            };
            if remove_path(child, rest) {
                map.remove(first);
            }
            map.is_empty()
        }
    }
}

// The self-check rejects bad writes the editors never make, so its
// container comparison is tested here rather than through an apply.
#[cfg(test)]
mod tests {
    use super::outside;
    use crate::formats::{Document, Format};

    const CONTINUE: &[&str] = &["mcpServers", "[name]"];

    const BEFORE: &str = "name: Local\nmcpServers:\n  - name: files\n    command: npx\n  - uses: owner/block\n  - just-text\n  - name: files\n    command: duplicate\n";

    fn same_outside(before: &str, after: &str) -> bool {
        let parse = |text: &str| Document::parse(text.as_bytes(), Format::Yaml).unwrap();
        outside(&parse(before), CONTINUE).unwrap() == outside(&parse(after), CONTINUE).unwrap()
    }

    #[test]
    fn named_list_items_are_the_only_ones_left_out() {
        // Owned, named items may change, come and go.
        assert!(same_outside(
            BEFORE,
            &BEFORE.replace("command: npx", "command: bunx")
        ));
        assert!(same_outside(
            BEFORE,
            &format!("{BEFORE}  - name: search\n    url: https://x.example.com\n")
        ));
        assert!(same_outside(
            "name: Local\n",
            "name: Local\nmcpServers:\n  - name: a\n"
        ));
        assert!(same_outside("mcpServers:\n", "mcpServers:\n  - name: a\n"));
        // Items without a scalar name, non-mappings and later duplicates
        // are compared like everything else outside the container.
        assert!(!same_outside(
            BEFORE,
            &BEFORE.replace("owner/block", "owner/other")
        ));
        assert!(!same_outside(
            BEFORE,
            &BEFORE.replace("just-text", "other-text")
        ));
        assert!(!same_outside(
            BEFORE,
            &BEFORE.replace("duplicate", "changed")
        ));
        assert!(!same_outside(
            BEFORE,
            &BEFORE.replace("  - just-text\n", "")
        ));
        assert!(!same_outside(
            BEFORE,
            &BEFORE.replace("name: Local", "name: Other")
        ));
    }
}