flint_lean/sync.rs
1//! The sync verb (v1, HITL — decided §9 Q4), plus the scoped form the
2//! `.flint/sync` sentinel invokes (boundary-verbs plan §2.2, D4).
3//! Harness- or sentinel-invoked, never background.
4//!
5//! Sync BEGINS with a full scan: "locally dirty" means dirty per THAT
6//! scan against the baseline — never per the last barrier's snapshot
7//! (otherwise sync honors a remote delete over the agent's un-scanned
8//! latest work: the review's steady-state destruction finding). Policy:
9//! locally-dirty wins; remote deletions apply only to locally-clean
10//! paths; adds/changes fetch through the store; every skipped apply is
11//! a surfaced conflict, never silent.
12//!
13//! **The scope rule (D4) is a correctness rule, not an optimization.**
14//! A scoped sync moves the baseline — which is also the merge base since
15//! P1-lite — only for the paths it applied or verified in scope, and
16//! leaves `baseline.seq` / `baseline.manifest_etag` UNTOUCHED. What it
17//! leaves out stays OWED: the next barrier's consume derives it and takes
18//! it, untouched from today. And a path the WORKSPACE'S scope declined
19//! (a scoped checkout) is never fetched here either: the baseline does
20//! not hold it, and only the held set and the scope's cover are owed.
21
22use std::collections::{BTreeMap, BTreeSet};
23
24use serde::Serialize;
25
26use flint_store::{crc64_nvme, crc64_to_b64, GenerationStamps, PosixStamps, StoreError};
27
28use super::barrier::{mtime_nanos_of, mtime_of};
29use super::state::{BaselineEntry, ConflictRecord};
30use super::{manifest, now_unix, scan, LeanError, LeanResult, Syncer};
31
32#[derive(Debug, Default, Serialize)]
33pub struct SyncReport {
34 pub applied: Vec<String>,
35 pub deleted: Vec<String>,
36 pub conflicts: Vec<String>,
37 pub seq: u64,
38 /// Remote changes seen but left owed because they fell outside the
39 /// requested scope (D4): the next barrier's consume takes those the
40 /// tree holds. Zero for a whole-tree
41 /// sync.
42 #[serde(default)]
43 pub out_of_scope_foreign: usize,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub scope: Option<Vec<String>>,
46}
47
48/// A normalized scope: path prefixes and exact paths, matched on
49/// COMPONENT boundaries (`"in"` never matches `internal/`).
50#[derive(Debug, Clone)]
51pub struct Scope {
52 entries: Vec<String>,
53}
54
55impl Scope {
56 pub fn new(raw: &[String]) -> Scope {
57 let mut entries = vec![];
58 for e in raw.iter().take(super::sentinel::MAX_SCOPE_ENTRIES) {
59 if e.len() > super::sentinel::MAX_SCOPE_ENTRY_LEN {
60 continue;
61 }
62 let norm = e.trim_matches('/').replace('\\', "/");
63 if norm.is_empty() || norm.split('/').any(|c| c == ".." || c == ".") {
64 continue;
65 }
66 entries.push(norm);
67 }
68 Scope { entries }
69 }
70
71 pub fn is_empty(&self) -> bool {
72 self.entries.is_empty()
73 }
74
75 pub fn entries(&self) -> &[String] {
76 &self.entries
77 }
78
79 /// Component-boundary match: an entry covers itself exactly and
80 /// everything beneath it, never a sibling sharing a name prefix.
81 pub fn covers(&self, path: &str) -> bool {
82 self.entries.iter().any(|e| {
83 path == e.as_str()
84 || path.strip_prefix(e.as_str()).map(|r| r.starts_with('/')).unwrap_or(false)
85 })
86 }
87}
88
89impl Syncer {
90 /// Whole-tree sync: advances `seq` and the cheap path's record once it
91 /// has taken everything owed; `manifest_etag` stays where the last
92 /// barrier left it (`reader.rs` relies on that).
93 pub async fn sync(&mut self) -> LeanResult<SyncReport> {
94 self.sync_scoped(None).await
95 }
96
97 pub async fn sync_scoped(&mut self, scope: Option<Vec<String>>) -> LeanResult<SyncReport> {
98 // An all-rejected scope is REFUSED, never widened. `Scope::new`
99 // silently drops entries that are too long, past
100 // MAX_SCOPE_ENTRIES, or contain `.`/`..` — so a caller naming
101 // three malformed paths used to get `None`, and `in_scope`'s
102 // `.unwrap_or(true)` turned that into the WHOLE TREE. A
103 // whole-tree sync re-derives against the remote manifest and
104 // DELETES local files for remotely-deleted paths, so the failure
105 // mode of a typo was maximum privilege. An error must not
106 // return a legal value.
107 let scope = match scope {
108 None => None,
109 Some(raw) => {
110 let s = Scope::new(&raw);
111 if s.is_empty() {
112 return Err(LeanError::State(format!(
113 "sync scope named {} entr{} and NONE survived validation — \
114 refusing, because an empty scope widens to the WHOLE TREE",
115 raw.len(),
116 if raw.len() == 1 { "y" } else { "ies" }
117 )));
118 }
119 Some(s)
120 }
121 };
122 let in_scope = |path: &str| scope.as_ref().map(|s| s.covers(path)).unwrap_or(true);
123 let mut report = SyncReport::default();
124 report.scope = scope.as_ref().map(|s| s.entries().to_vec());
125 let mut baseline = self.state.load_baseline()?;
126
127 // 1. The scan comes FIRST; dirt is judged against it alone.
128 let scanned = scan::scan(&self.cfg.root)?;
129 let classified = scan::classify(&scanned, &baseline);
130 let locally_dirty = |path: &str| {
131 classified.uploads.contains(path)
132 || classified.deletes.contains(path)
133 || classified.first_absence.contains(path)
134 };
135
136 // 2. Remote truth: the committed document (since P2 the gateway
137 // commits each UI verb, so there is no inbox overlay).
138 let loaded = manifest::load(self.store.as_ref(), &self.cfg).await?;
139 // The agent's paths this sync leaves untaken (dirty), for the
140 // consume's cheap path: owed again if the agent backs out.
141 let mut dirty_skips: BTreeSet<String> = BTreeSet::new();
142 let (theirs, metag) = match loaded {
143 Some(l) => (l.manifest, Some(l.etag)),
144 // No document at all. For a tree that holds nothing that is a
145 // new workspace, and there is nothing to do. For one that
146 // holds paths it is a wiped or re-pointed prefix, and reading
147 // it as an EMPTY document would delete every clean file here —
148 // perhaps the last copy. The consume takes nothing in this
149 // case; the sync refuses (review 2026-09-29, S1).
150 None if baseline.entries.is_empty() => (Default::default(), None),
151 None => {
152 return Err(LeanError::State(format!(
153 "sync: the workspace has no document (no pointer, no manifest) but this tree's \
154 baseline holds {} paths — refusing to read a missing document as an empty \
155 one, which would delete every clean file here",
156 baseline.entries.len()
157 )))
158 }
159 };
160 // Something owed could not be taken now (a fetch that lost to a
161 // newer document, a failed write): the next consume derives again
162 // even if the pointer does not move — exactly the consume's `left`
163 // (review 2026-09-29, S2/S3).
164 let mut left = false;
165 // Path -> (etag, HANDLE): the entry's own key, which is what the
166 // fetch below reads (design 2026-09-19: a handle is fetched by
167 // name; the bare path is nobody's to read).
168 let remote: BTreeMap<String, (String, String)> =
169 theirs.entries.iter().map(|(p, e)| (p.clone(), (e.etag.clone(), e.key.clone()))).collect();
170 // The writer's CRC for each remote etag: the manifest's.
171 let remote_crc: BTreeMap<String, Option<String>> = theirs
172 .entries
173 .iter()
174 .map(|(p, e)| (p.clone(), Some(e.crc64_b64.clone())))
175 .collect();
176
177 // The workspace's own scope (a scoped checkout): a path it neither
178 // holds nor covers is not this tree's to fetch.
179 let held_scope = self.state.load_scope()?.map(|v| Scope::new(&v));
180 let held = |b: &super::state::Baseline, p: &str| {
181 b.entries.contains_key(p) || held_scope.as_ref().is_none_or(|s| s.covers(p))
182 };
183
184 // 3. Remote deletions: in the baseline, gone from the manifest —
185 // apply only on locally-clean paths.
186 //
187 // BEFORE the adds, and that order is a correctness rule, not
188 // a tidiness one. A remote generation that turned the file
189 // `build` into the directory `build/log.txt` sends both a
190 // deletion and an add; with the adds first, the add is
191 // refused for containment (`sync-refused-containment`) while
192 // the file is still there, and the deletion then takes the
193 // file away — one sync leaves the workspace without either,
194 // and sync is harness-invoked, never background, so "the next
195 // sync fixes it" may be never. The two passes act on disjoint
196 // path sets (this one takes what is NOT in `remote`, that one
197 // what IS), so nothing else moves with the order.
198 let base_paths: Vec<String> = baseline.entries.keys().cloned().collect();
199 for path in base_paths {
200 if remote.contains_key(&path) {
201 continue;
202 }
203 if !in_scope(&path) {
204 report.out_of_scope_foreign += 1;
205 continue;
206 }
207 let local = self.cfg.root.join(&path);
208 if !local.exists() {
209 baseline.entries.remove(&path);
210 continue;
211 }
212 super::barrier::consume_window("before-delete", &path);
213 // H7: judged by the step-1 scan AND by a fresh stat now — a
214 // write since the scan is the agent's, and it stays.
215 if locally_dirty(&path) || super::barrier::local_dirty(&local, baseline.entries.get(&path)) {
216 self.state.append_conflict(&ConflictRecord {
217 path: path.clone(),
218 foreign_etag: String::new(),
219 preserved_key: None,
220 kind: "sync-remote-delete-vs-dirty".into(),
221 at_unix: now_unix(),
222 })?;
223 report.conflicts.push(path.clone());
224 dirty_skips.insert(path.clone());
225 continue;
226 }
227 std::fs::remove_file(&local)?;
228 baseline.entries.remove(&path);
229 report.deleted.push(path.clone());
230 }
231
232 // 4. Apply adds/changes (remote differs from the baseline).
233 for (path, (etag, key)) in &remote {
234 if baseline.entries.get(path).map(|b| &b.etag == etag).unwrap_or(false) {
235 continue;
236 }
237 if !held(&baseline, path) {
238 continue;
239 }
240 if !in_scope(path) {
241 // D4: NOT integrated — it stays owed, and the next
242 // barrier's consume takes it.
243 report.out_of_scope_foreign += 1;
244 continue;
245 }
246 if locally_dirty(path) {
247 // The phantom-conflict rule (§2.2): `sync` saves the
248 // baseline only at the end, so a crash mid-apply
249 // followed by a re-honor makes already-applied paths
250 // scan dirty against the stale baseline. Declaring a
251 // conflict there would report a conflict for a path
252 // whose local bytes ARE the remote bytes, and the path
253 // would then re-publish as a spurious generation bump.
254 // Compare content identity first.
255 // The remote's crc, read off the object we would apply
256 // (the backend's attestation) before the manifest's.
257 // One HEAD, only on the dirty-vs-remote path.
258 let remote_meta = match self.store.head(key).await {
259 Ok(m) if m.etag == *etag => Some(m),
260 _ => None,
261 };
262 // The remote's CRC: the backend's attestation when it
263 // offers one, else the writer's for this etag — client-
264 // computed, so it exists on a backend that attests none
265 // (Ozone). Without either the bytes cannot be judged
266 // identical, and the path is a conflict as before.
267 let want: Option<String> = remote_meta.as_ref().and_then(|m| {
268 m.crc64_b64.clone().or_else(|| remote_crc.get(path).cloned().flatten())
269 });
270 let local_path = self.cfg.root.join(path);
271 let local_crc =
272 std::fs::read(&local_path).ok().map(|b| crc64_to_b64(crc64_nvme(&b)));
273 let identical = want.is_some() && want == local_crc;
274 if identical {
275 let st = std::fs::metadata(&local_path)?;
276 let stamps =
277 remote_meta.as_ref().and_then(|m| GenerationStamps::from_meta(&m.meta));
278 baseline.entries.insert(
279 path.clone(),
280 BaselineEntry {
281 etag: etag.clone(),
282 key: Some(key.clone()),
283 generation: stamps
284 .map(|s| s.generation)
285 .or_else(|| theirs.entries.get(path).map(|e| e.generation))
286 .unwrap_or(0),
287 size: st.len(),
288 mtime_unix: mtime_of(&st),
289 mtime_nanos: Some(mtime_nanos_of(&st)),
290 crc64_b64: local_crc,
291 },
292 );
293 report.applied.push(path.clone());
294 continue;
295 }
296 self.state.append_conflict(&ConflictRecord {
297 path: path.clone(),
298 foreign_etag: etag.clone(),
299 preserved_key: None, // remote version stays in the bucket
300 kind: "sync-dirty".into(),
301 at_unix: now_unix(),
302 })?;
303 report.conflicts.push(path.clone());
304 dirty_skips.insert(path.clone());
305 continue;
306 }
307 let fetched = self.store.get_whole(key, Some(etag)).await;
308 let (meta, body) = match fetched {
309 Ok(ok) => ok,
310 Err(StoreError::PreconditionFailed(_)) | Err(StoreError::NotFound(_)) => {
311 // Superseded mid-sync, or not readable yet: owed still.
312 left = true;
313 continue;
314 }
315 Err(e) => return Err(e.into()),
316 };
317 let mode = PosixStamps::from_meta(&meta.meta).map(|p| p.mode);
318 // VERIFIED before it is written, exactly as checkout's fresh
319 // fetch is: against the writer's CRC for this etag (the
320 // manifest's), else the backend's attestation when it offers
321 // one. What the baseline records is OURS, over the bytes
322 // written.
323 let got = crc64_to_b64(crc64_nvme(&body));
324 let want =
325 remote_crc.get(path).cloned().flatten().or_else(|| meta.crc64_b64.clone());
326 if let Some(want) = want {
327 if want != got {
328 return Err(LeanError::State(format!(
329 "sync: {path} (etag {etag}) is cited with CRC-64 {want}, but the bytes \
330 fetched under that etag hash to {got} — the object is corrupt or the \
331 store returned the wrong bytes; refusing to apply it (nothing written)"
332 )));
333 }
334 }
335 // A path this tree can never safely materialise is refused and
336 // NOT left owed (as the consume does); a write that fails for
337 // any other reason below is transient and stays owed.
338 if let Err(e) = super::barrier::check_contained(&self.cfg.root, path) {
339 self.state.append_conflict(&ConflictRecord {
340 path: path.clone(),
341 foreign_etag: etag.clone(),
342 preserved_key: None,
343 kind: format!("sync-refused-containment: {e}"),
344 at_unix: now_unix(),
345 })?;
346 report.conflicts.push(path.clone());
347 continue;
348 }
349 super::barrier::consume_window("before-write", path);
350 // Review 2026-09-18, H7: dirt was judged by the scan at step 1,
351 // and a whole-tree sync fetches for minutes after it; a path
352 // the agent writes since then is modified, and its version
353 // wins. So the licence is checked once more against a fresh
354 // stat, with the temp written, immediately before the rename.
355 let local = self.cfg.root.join(path);
356 let base = baseline.entries.get(path).cloned();
357 let still_clean = || !super::barrier::local_dirty(&local, base.as_ref());
358 let written = super::barrier::contained_path(&self.cfg.root, path)
359 .and_then(|target| super::barrier::write_file_atomic_if(&target, &body, mode, &still_clean));
360 let st = match written {
361 Ok(Some(st)) => st,
362 Ok(None) => {
363 self.state.append_conflict(&ConflictRecord {
364 path: path.clone(),
365 foreign_etag: etag.clone(),
366 preserved_key: None, // remote version stays in the bucket
367 kind: "sync-dirty".into(),
368 at_unix: now_unix(),
369 })?;
370 report.conflicts.push(path.clone());
371 dirty_skips.insert(path.clone());
372 continue;
373 }
374 Err(e) => {
375 // TRANSIENT (a full disk, a directory it cannot write
376 // to): surfaced, never a wedge, and still owed.
377 self.state.append_conflict(&ConflictRecord {
378 path: path.clone(),
379 foreign_etag: etag.clone(),
380 preserved_key: None,
381 kind: format!("sync-write-failed (will retry): {e}"),
382 at_unix: now_unix(),
383 })?;
384 report.conflicts.push(path.clone());
385 left = true;
386 continue;
387 }
388 };
389 // The baseline records the inode this sync wrote (its fstat),
390 // never a fresh stat of the path an agent may have written
391 // since (H7).
392 super::barrier::consume_window("after-rename", path);
393 let stamps = GenerationStamps::from_meta(&meta.meta);
394 baseline.entries.insert(
395 path.clone(),
396 BaselineEntry {
397 etag: meta.etag.clone(),
398 key: Some(key.clone()),
399 generation: stamps.map(|s| s.generation).unwrap_or(0),
400 size: st.len(),
401 mtime_unix: mtime_of(&st),
402 mtime_nanos: Some(mtime_nanos_of(&st)),
403 crc64_b64: Some(got),
404 },
405 );
406 report.applied.push(path.clone());
407 }
408
409 // 5. What this sync leaves owed. Whole-tree, the sync derived against
410 // this document: what it left is the agent's (dirty) and is owed
411 // the moment the agent backs out — the consume's cheap path record,
412 // as a consume would write it. Scoped, it derived only part: the
413 // next consume derives again (D4 keeps manifest_etag where it was).
414 match &scope {
415 None if !left => {
416 baseline.seq = theirs.seq;
417 baseline.derived_etag = Some(metag.clone().unwrap_or_default());
418 baseline.skipped = dirty_skips;
419 report.seq = theirs.seq;
420 }
421 // Something is still owed: nothing is recorded as derived, and
422 // the tree is not integrated with this document yet.
423 None => {
424 baseline.derived_etag = None;
425 baseline.skipped.clear();
426 report.seq = baseline.seq;
427 }
428 Some(_) => {
429 baseline.derived_etag = None;
430 baseline.skipped.clear();
431 report.seq = baseline.seq;
432 }
433 }
434 let rescan = scan::scan(&self.cfg.root)?;
435 baseline.prev_scan = rescan.keys().cloned().collect();
436 // Materialised files before the baseline that vouches for them.
437 self.state.sync_tree()?;
438 self.state.save_baseline(&baseline)?;
439 self.trace("sync", serde_json::json!({"scoped": scope.is_some(), "applied": report.applied.len(),
440 "deleted": report.deleted.len(), "conflicts": report.conflicts.len(), "seq": report.seq}));
441 Ok(report)
442 }
443}