Skip to main content

flint_lean/
checkout.rs

1//! Checkout + the restart matrix (plan §2.1).
2//!
3//! | State on wake            | Action                                  |
4//! |--------------------------|-----------------------------------------|
5//! | No marker, empty tree    | full checkout                           |
6//! | No marker, partial tree  | resume (local-wins skips present paths) |
7//! | Marker present           | NEVER re-materialize: reload baseline,  |
8//! |                          | rescan rebuilds dirt, lease self-       |
9//! |                          | recognizes via the persisted id         |
10//!
11//! Re-checkout over a live tree is forbidden: local-wins protects only
12//! PRESENT paths, so it would resurrect the agent's unpublished deletes
13//! (`LeanRematerialize.cfg` rediscovers exactly that). The marker is
14//! written LAST — it is the agent-start gate.
15
16use std::collections::BTreeSet;
17
18use flint_store::StoreError;
19
20use super::barrier::{contained_path, contained_path_stat, mtime_nanos_of, mtime_of, write_file_atomic};
21use super::manifest;
22use super::state::BaselineEntry;
23use super::{LeanError, LeanResult, Syncer};
24
25#[derive(Debug, Default)]
26pub struct CheckoutReport {
27    pub materialized: usize,
28    pub skipped_present: usize,
29    pub bytes: u64,
30    /// Restart-matrix row taken.
31    pub resumed_live_tree: bool,
32    /// Citations left in place rather than materialized (D0.3 legacy
33    /// `.flint/` paths, containment refusals). Never a silent drop:
34    /// each has a conflict record.
35    pub refused: usize,
36    /// Phase attribution for the agent-blocking path. Without these the
37    /// checkout wall clock cannot be split between the manifest GET,
38    /// the fan-out fetch window, and the local commit — which is the
39    /// one fact any read-path decision here rests on.
40    pub manifest_secs: f64,
41    pub fetch_secs: f64,
42    pub commit_secs: f64,
43    /// Passes re-run because the pointer moved past the document a
44    /// pass read and a handle it cited was collected (handles design
45    /// 2026-09-19): the checkout re-resolves instead of asking the
46    /// caller to.
47    pub reresolved: u32,
48    /// The admitted set this checkout was scoped to, or `None` for the
49    /// whole manifest.
50    pub scope: Option<Vec<String>>,
51    /// Citations the scope DECLINED. Zero for an unscoped checkout, and
52    /// the number that says a scope did anything at all: a scope that
53    /// admits everything reads exactly like no scope.
54    pub out_of_scope: usize,
55    /// Objects materialised through the RANGED path. On a cluster
56    /// nothing else can tell "ranging did not help" from "ranging did
57    /// not run" — the knob is a threshold and a threshold that never
58    /// fires reads exactly like an optimisation that does not work.
59    pub ranged: usize,
60}
61
62/// Materialise one object as PARALLEL RANGES, writing each at its
63/// offset as it lands.
64///
65/// Returns `Ok(None)` when the caller should fall through to the
66/// whole-object arm — either because ranging does not apply, or because
67/// the store answered with one of the two POLICY-BEARING errors. That
68/// second case is deliberate: `PreconditionFailed` and `NotFound` mean
69/// two different things here depending on `sole_writer`,
70/// and all three refusals are written once, in the whole-object arm
71/// below. Re-deciding them here would put the same policy in two
72/// places, which is how the two drift apart. The cost is one wasted
73/// request on a path that is already an incident.
74///
75/// Every other error propagates after the per-range retries: a transport
76/// failure is a failure, not a quiet fallback that would hide a broken
77/// network behind a slower code path.
78async fn fetch_ranged(
79    store: &std::sync::Arc<dyn flint_store::ObjectStore>,
80    key: &str,
81    etag: &str,
82    size: u64,
83    target: &std::path::Path,
84    tmp: &std::path::Path,
85    mode: Option<u32>,
86    chunk_bytes: u64,
87    parallelism: usize,
88    expect_crc: u64,
89) -> LeanResult<Option<u64>> {
90    use futures::stream::StreamExt;
91
92    /// A range that failed for a reason the caller must distinguish.
93    enum RangeFail {
94        /// 412/404 — the whole-object arm owns this policy.
95        Fallback,
96        Fatal(LeanError),
97    }
98
99    const RANGE_RETRIES: u32 = 3;
100    let chunk_bytes = chunk_bytes.max(1);
101    let mut parts: Vec<(u64, u64)> = Vec::new();
102    let mut at = 0u64;
103    while at < size {
104        let len = chunk_bytes.min(size - at);
105        parts.push((at, len));
106        at += len;
107    }
108    if parts.len() < 2 {
109        // One range is one whole GET with extra steps.
110        return Ok(None);
111    }
112
113    // SHARED so each range writes ITSELF, on the blocking pool. Before
114    // this the write ran on the task that polls the fan-out, so a pwrite
115    // of one range stalled the FETCH of every other range in flight —
116    // concurrency that could never overlap I/O with I/O. Measured on
117    // i4i.large against an in-memory S3: system time beat user time 6:1
118    // and the process never exceeded 1.31 of 2 cores, flat from 4
119    // streams to 32.
120    let sink = std::sync::Arc::new(super::safefs::RangedTmp::create(target, tmp, size, mode)?);
121    let mut ranges = futures::stream::iter(parts.into_iter().map(|(off, len)| {
122        let store = store.clone();
123        let key = key.to_string();
124        let etag = etag.to_string();
125        let sink = sink.clone();
126        async move {
127            let mut attempt: u32 = 0;
128            let b = loop {
129                // EVERY range carries the same If-Match, which is what
130                // makes the assembled file one object rather than a
131                // splice of two: a write between range 3 and range 4
132                // fails range 4 instead of silently interleaving
133                // generations.
134                match store.get_range_segments(&key, off, len, &etag).await {
135                    Ok(b) => break b,
136                    Err(StoreError::PreconditionFailed(_)) | Err(StoreError::NotFound(_)) => {
137                        return Err(RangeFail::Fallback)
138                    }
139                    Err(_) if attempt < RANGE_RETRIES => {
140                        attempt += 1;
141                        // The retry is per RANGE: a cut connection at
142                        // range N of a multi-GiB object must not throw
143                        // away N ranges of progress.
144                        tokio::time::sleep(std::time::Duration::from_millis(
145                            300 * u64::from(attempt),
146                        ))
147                        .await;
148                    }
149                    Err(e) => {
150                        return Err(RangeFail::Fatal(LeanError::State(format!(
151                            "get_range {key} at {off}+{len} after {RANGE_RETRIES} retries: {e}"
152                        ))))
153                    }
154                }
155            };
156            // The SDK's own frames, never flattened into one buffer.
157            // Summed rather than `b.is_empty()`: an empty range can also
158            // arrive as one zero-length segment, which is the same hole.
159            let n: u64 = b.iter().map(|seg| seg.len() as u64).sum();
160            // Checked HERE rather than at the drain: a hole must be
161            // refused before it is written, not after.
162            if n == 0 {
163                return Err(RangeFail::Fatal(LeanError::State(format!(
164                    "get_range {key} at {off} returned an empty range before the object's \
165                     end — refusing a hole"
166                ))));
167            }
168            let crc = tokio::task::spawn_blocking(move || {
169                // Segments are contiguous and in order within the range,
170                // so each lands at the running offset. The file is
171                // positional throughout, so siblings still cannot race.
172                // The range's CRC-64 is taken here, on the same pass, so
173                // the drain can fold the ranges in offset order and
174                // compare the whole against the manifest before the
175                // rename makes the file visible.
176                let mut h = flint_store::Crc64Nvme::new();
177                let mut at = off;
178                for seg in &b {
179                    sink.write_at(at, seg)?;
180                    h.update(seg);
181                    at += seg.len() as u64;
182                }
183                Ok::<u64, LeanError>(h.finalize())
184            })
185            .await
186            .map_err(|e| {
187                RangeFail::Fatal(LeanError::State(format!(
188                    "write task for {key} at {off} did not complete: {e}"
189                )))
190            })?
191            .map_err(RangeFail::Fatal)?;
192            Ok((off, n, crc))
193        }
194    }))
195    .buffer_unordered(parallelism.max(1));
196
197    let mut bytes = 0u64;
198    let mut crcs: Vec<(u64, u64, u64)> = Vec::new();
199    while let Some(next) = ranges.next().await {
200        match next {
201            Ok((off, n, crc)) => {
202                bytes += n;
203                crcs.push((off, n, crc));
204            }
205            Err(RangeFail::Fallback) => {
206                drop(ranges);
207                let _ = std::fs::remove_file(tmp);
208                return Ok(None);
209            }
210            Err(RangeFail::Fatal(e)) => {
211                drop(ranges);
212                let _ = std::fs::remove_file(tmp);
213                return Err(e);
214            }
215        }
216    }
217    // Every range future is finished and dropped, so this is the last
218    // reference. try_unwrap rather than a clone-tolerant commit: if a
219    // writer were somehow still alive, renaming now would publish a
220    // file still being written into.
221    drop(ranges);
222    let sink = std::sync::Arc::try_unwrap(sink).map_err(|_| {
223        LeanError::State(format!(
224            "ranged materialisation of {}: a range writer outlived the fan-out",
225            target.display()
226        ))
227    })?;
228    // The whole object's CRC-64 from its ranges: `crc64_combine`
229    // composes A-then-B, so the fold runs in offset order whatever
230    // order the ranges landed in. Checked BEFORE the rename, for the
231    // same reason a hole is: a wrong file must never become visible.
232    // Unconditional: this arm fetches only under If-Match on the cited
233    // etag, so the bytes are always the manifest's to describe.
234    crcs.sort_unstable_by_key(|(off, _, _)| *off);
235    let mut folded: Option<u64> = None;
236    for (_, len, crc) in &crcs {
237        folded = Some(match folded {
238            None => *crc,
239            Some(acc) => flint_store::crc64_combine(acc, *crc, *len),
240        });
241    }
242    if folded != Some(expect_crc) {
243        drop(sink);
244        let _ = std::fs::remove_file(tmp);
245        return Err(LeanError::State(format!(
246            "manifest cites {key} at etag {etag} with CRC-64 {}, but the {} ranges fetched \
247             under that etag fold to {} — the object is corrupt or the store returned the \
248             wrong bytes; refusing to materialise {} (nothing renamed into place)",
249            flint_store::crc64_to_b64(expect_crc),
250            crcs.len(),
251            folded.map(flint_store::crc64_to_b64).unwrap_or_else(|| "nothing".into()),
252            target.display()
253        )));
254    }
255    sink.commit()?;
256    Ok(Some(bytes))
257}
258
259/// CRC-64/NVME of a local file, in the same base64 form the manifest
260/// carries. Streamed: a resumed checkout may be verifying a 20 GiB
261/// workspace and must not hold it in memory.
262fn local_crc64_b64(path: &std::path::Path) -> Option<String> {
263    use std::io::Read;
264    let mut f = std::fs::File::open(path).ok()?;
265    let mut h = flint_store::Crc64Nvme::new();
266    let mut buf = vec![0u8; 1 << 20];
267    loop {
268        let n = f.read(&mut buf).ok()?;
269        if n == 0 {
270            break;
271        }
272        h.update(&buf[..n]);
273    }
274    Some(flint_store::crc64_to_b64(h.finalize()))
275}
276
277/// One admitted citation's outcome from the fan-out materializer.
278    struct Fetched {
279        /// Took the ranged path (report-only).
280        ranged: bool,
281        path: String,
282        be: Option<BaselineEntry>,
283        skipped: bool,
284        bytes: u64,
285        /// A citation this checkout refused to materialize (D0.3 /
286        /// containment): left cited, surfaced as a conflict.
287        refused: Option<String>,
288    }
289
290/// Names a scope for a human in an error: the whole manifest, or the
291/// entries themselves. The entries matter — "a different scope" sends
292/// the reader to go and diff two things they cannot see.
293fn describe_scope(s: Option<&[String]>) -> String {
294    match s {
295        None => "UNSCOPED (the whole manifest)".to_string(),
296        Some(e) => format!("scoped to {:?}", e),
297    }
298}
299
300impl Syncer {
301    /// Materialize an ADMITTED SET under a bounded fan-out window:
302    /// each entry's guarded fetch + atomic write is independent (the
303    /// 0b rig measured the sequential loop at ~1,000-2,000 files/s and
304    /// 3.3 s/GiB; fan-out multiplies directly against both).
305    ///
306    /// Takes the admitted set rather than the manifest, so the one
307    /// decision about WHICH citations get materialized lives at the call
308    /// site and every caller inherits the same LPT ordering, the same
309    /// in-flight byte bound, and the same D0.3 refusals. A caller
310    /// that admits a subset owes its own budget arithmetic over that
311    /// subset — this function refuses nothing on size.
312    async fn materialize<'a>(
313        &'a self,
314        mut admission: Vec<(&'a String, &'a super::manifest::LeanEntry)>,
315        sole_writer: bool,
316    ) -> Vec<LeanResult<Fetched>> {
317        // LARGEST FIRST. `m.entries` is a BTreeMap, so iterating it
318        // admits in PATH order, which appends the biggest object's
319        // transfer to the tail of the fan-out window: a multi-GiB
320        // checkpoint whose name sorts late is a whole transfer of pure
321        // makespan after every other slot has drained. Longest-
322        // processing-time-first bounds that at (4/3 - 1/3k) x optimal.
323        // `size` is already in the entry, so this costs no request and
324        // one sort; on a size-uniform tree it is exactly a no-op.
325        //
326        // Nothing downstream may depend on admission order:
327        // `buffer_unordered` already yields in COMPLETION order, and the
328        // budget refusals above ran over the whole map before this.
329        admission.sort_unstable_by(|a, b| b.1.size.cmp(&a.1.size).then_with(|| a.0.cmp(b.0)));
330        // The in-flight BYTE bound (see `fetch_inflight_max_bytes`).
331        // Permits are 1 MiB units; an entry larger than the whole budget
332        // clamps to the budget rather than deadlocking on a permit count
333        // the semaphore can never grant.
334        const FETCH_UNIT: u64 = 1 << 20;
335        let budget_units =
336            (self.cfg.fetch_inflight_max_bytes / FETCH_UNIT).clamp(1, u32::MAX as u64) as u32;
337        let gate = std::sync::Arc::new(tokio::sync::Semaphore::new(budget_units as usize));
338        use futures::stream::{self, StreamExt};
339        let this: &super::Syncer = self;
340            let range_min = this.cfg.range_get_min_bytes;
341            let range_chunk = this.cfg.range_get_chunk_bytes;
342            let range_par = this.cfg.range_get_parallelism;
343        // SHARDED DRIVERS. Every fetch future used to be polled by ONE
344        // `buffer_unordered` task on the block_on thread, so each
345        // request's SDK work (build, sign, orchestrate, parse, collect,
346        // checksum) ran on one thread whatever `fanout` said: the main
347        // thread saturated at ~8,000 files/s on a 2-vCPU VM with half a
348        // core idle. Spawning every fetch as its own task fixed that and
349        // then lost to the single driver on a 6-vCPU loopback rig (7.6k
350        // vs 11.4k) — with no RTT to hide behind, a wake per response
351        // per task costs more than the parallelism buys.
352        //
353        // So: `fetch_drivers` driver tasks, each running its own
354        // `buffer_unordered` over a round-robin slice of the (already
355        // largest-first) admission list. A driver's fetches stay on one
356        // task — one wake path, the batching the single driver had —
357        // and the per-request work spreads over that many cores.
358        let drivers = this.cfg.fetch_drivers.max(1);
359        let per_driver = (this.cfg.fanout.max(1) / drivers).max(1);
360        let mut shards: Vec<Vec<(String, super::manifest::LeanEntry)>> =
361            (0..drivers).map(|_| Vec::new()).collect();
362        for (i, (path, entry)) in admission.into_iter().enumerate() {
363            shards[i % drivers].push((path.clone(), entry.clone()));
364        }
365        let store_all = this.store.clone();
366        let root_all = this.cfg.root.clone();
367        let mut set = tokio::task::JoinSet::new();
368        for shard in shards {
369            let store_d = store_all.clone();
370            let root_d = root_all.clone();
371            let gate_d = gate.clone();
372            set.spawn(async move {
373        stream::iter(shard.into_iter().map(|(path, entry)| {
374            let store = store_d.clone();
375            let root = root_d.clone();
376            let local = root_d.join(&path);
377            let gate = gate_d.clone();
378            // THE CHARGE MUST DESCRIBE THE PATH THAT WILL RUN.
379            //
380            // `fetch_inflight_max_bytes` is a bound on BYTES HELD IN
381            // MEMORY, and the two arms hold wildly different amounts.
382            // `get_whole` returns the entire object, so charging
383            // `entry.size` is exactly right for it. The ranged arm does
384            // not: it is `buffer_unordered(range_par)` over per-chunk
385            // `get_range` calls, each written at its offset as it
386            // lands, so it holds `range_par * range_chunk` — 64 MiB at
387            // the shipped defaults — WHATEVER the object's size.
388            //
389            // Charging a ranged 1 GiB fetch 1 GiB of a 512 MiB budget
390            // therefore mis-states its footprint by ~16x, and the
391            // `clamp` turns that into the pathology: an entry at or
392            // over the budget takes the WHOLE semaphore, so object
393            // concurrency collapses to ONE and `fanout` is dead code.
394            // On a 6 x 1 GiB tree that leaves 4 streams on a 25 Gbps
395            // link — measured at 325 MiB/s, 11% of the guarantee, and
396            // identical on a node with 12x the vCPU and 32x the
397            // bandwidth. The bound was never the memory it names.
398            let ranged_eligible = range_min > 0 && entry.size >= range_min;
399            let whole_units =
400                entry.size.div_ceil(FETCH_UNIT).clamp(1, budget_units as u64) as u32;
401            let ranged_units = (range_par.max(1) as u64)
402                .saturating_mul(range_chunk.max(1))
403                .min(entry.size)
404                .div_ceil(FETCH_UNIT)
405                .clamp(1, budget_units as u64) as u32;
406            let want = if ranged_eligible { ranged_units } else { whole_units };
407            async move {
408                // Held until this entry's bytes have reached disk.
409                let mut permit = gate
410                    .clone()
411                    .acquire_many_owned(want)
412                    .await
413                    .map_err(|_| LeanError::State("fetch budget closed".into()))?;
414                // D0.3: a legacy `files/.flint/...` citation is
415                // never materialized (it would collide with the
416                // control files); it stays cited and a conflict
417                // record names it. Same arm refuses a citation
418                // whose path escapes the workspace.
419                // The walk hands back the final component's lstat as
420                // well, which is the resume check's whole question.
421                let (target, present) = match contained_path_stat(&root, &path) {
422                    Ok(t) => t,
423                    Err(e) => {
424                        return Ok(Fetched {
425                            ranged: false,
426                            path: path.clone(),
427                            be: None,
428                            skipped: true,
429                            bytes: 0,
430                            refused: Some(e.to_string()),
431                        })
432                    }
433                };
434                if let Some(st) = present {
435                    // Resume: a present path is one THIS checkout
436                    // already fetched, so re-downloading it would
437                    // pay bucket GETs for bytes that are on disk.
438                    //
439                    // But only if it is the same bytes. A checkout
440                    // that died halfway leaves generation N on
441                    // disk, and the manifest can MOVE before the
442                    // replacement pod resumes (a HITL write, a
443                    // sibling's barrier — routine on this fleet).
444                    // Adopting then would stamp the baseline with
445                    // the NEW entry's etag over the OLD content:
446                    // the scan reads the file as clean and never
447                    // uploads it, a sync reads baseline == manifest
448                    // and never re-fetches it, and the workspace
449                    // holds bytes nothing will ever reconcile. The
450                    // divergence is silent and permanent.
451                    //
452                    // The check is local-only: size from the stat
453                    // the walk already took, then crc of the local
454                    // file. No bucket request either way — which is
455                    // why it can be unconditional rather than a knob.
456                    let same = st.len() == entry.size
457                        && local_crc64_b64(&local)
458                            .map(|got| got == entry.crc64_b64)
459                            .unwrap_or(false);
460                    if same {
461                        return Ok(Fetched {
462                            ranged: false,
463                            path: path.clone(),
464                            be: Some(BaselineEntry {
465                                etag: entry.etag.clone(),
466                                key: Some(entry.key.clone()),
467                                generation: entry.generation,
468                                size: st.len(),
469                                mtime_unix: mtime_of(&st),
470                                mtime_nanos: Some(mtime_nanos_of(&st)),
471                                crc64_b64: Some(entry.crc64_b64.clone()),
472                            }),
473                            skipped: true,
474                            bytes: 0,
475                            refused: None,
476                        });
477                    }
478                    // Fall through and re-materialize.
479                }
480                // RANGED FIRST, when the object is big enough to
481                // pay for it.
482                let ranged_bytes = if range_min > 0 && entry.size >= range_min {
483                    let tmp = target.with_file_name(format!(
484                        "{}.flint-sync-tmp",
485                        target.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()
486                    ));
487                    let want = flint_store::crc64_from_b64(&entry.crc64_b64).ok_or_else(|| {
488                        LeanError::State(format!(
489                            "manifest cites {} with a CRC-64 that is not one: {:?}",
490                            entry.key, entry.crc64_b64
491                        ))
492                    })?;
493                    fetch_ranged(
494                        &store,
495                        &entry.key,
496                        &entry.etag,
497                        entry.size,
498                        &target,
499                        &tmp,
500                        Some(entry.mode),
501                        range_chunk,
502                        range_par,
503                        want,
504                    )
505                    .await?
506                } else {
507                    None
508                };
509                if let Some(n) = ranged_bytes {
510                    let st = std::fs::metadata(&local)?;
511                    return Ok(Fetched {
512                        ranged: true,
513                        path: path.clone(),
514                        be: Some(BaselineEntry {
515                            etag: entry.etag.clone(),
516                            key: Some(entry.key.clone()),
517                            generation: entry.generation,
518                            size: st.len(),
519                            mtime_unix: mtime_of(&st),
520                            mtime_nanos: Some(mtime_nanos_of(&st)),
521                            // The fold above equalled it, or we would
522                            // not be here.
523                            crc64_b64: Some(entry.crc64_b64.clone()),
524                        }),
525                        skipped: false,
526                        bytes: n,
527                        refused: None,
528                    });
529                }
530
531                // TOP UP BEFORE BUFFERING THE WHOLE OBJECT.
532                //
533                // Reaching here having been charged the ranged rate
534                // means `fetch_ranged` declined — either the object is
535                // one chunk (harmless: it holds less than the ranged
536                // charge) or it hit the 412/404 policy fallback, which
537                // hands the whole object to `get_whole` below. In that
538                // second case we are about to hold `entry.size` while
539                // charged for 64 MiB, and N concurrent fallbacks would
540                // walk RSS straight through the bound this semaphore
541                // exists to enforce.
542                //
543                // Released BEFORE re-acquiring, never upgraded in
544                // place: holding `want` while waiting for
545                // `whole_units` is a deadlock the moment two entries
546                // do it at once against a full budget.
547                if want < whole_units {
548                    drop(permit);
549                    permit = gate
550                        .clone()
551                        .acquire_many_owned(whole_units)
552                        .await
553                        .map_err(|_| LeanError::State("fetch budget closed".into()))?;
554                }
555                let _permit = permit;
556
557                let (meta, body) = match store.get_whole(&entry.key, Some(&entry.etag)).await {
558                        Ok(ok) => ok,
559                        // A cited HANDLE is immutable: nothing in the
560                        // protocol writes one twice (P2: a UI save goes to
561                        // a fresh handle and commits), so a handle whose
562                        // etag moved was written by something outside it.
563                        // Refused, never adopted — adopting bytes no
564                        // manifest cites was a citation-repair source
565                        // (M4), and the S3-wins arm that did it served a
566                        // HITL write the inbox had not re-cited yet, which
567                        // no longer exists.
568                        Err(StoreError::PreconditionFailed(_)) => {
569                            let who = if sole_writer {
570                                " This workspace is published by a SOLE WRITER — if this is \
571                                 forge's legible export, look for a read-write mount over its \
572                                 prefix; the export republishes only what git changed and will \
573                                 not repair this on its own."
574                            } else {
575                                ""
576                            };
577                            return Err(LeanError::State(format!(
578                                "manifest cites {} at an etag the object no longer carries: \
579                                 something outside the protocol overwrote an immutable handle. \
580                                 Refusing to adopt bytes no manifest cites.{who}",
581                                entry.key
582                            )));
583                        }
584                        Err(StoreError::NotFound(_)) => {
585                            return Err(LeanError::State(format!(
586                                "manifest cites {} but the object is gone — refusing a \
587                                 silent hole (mixed-writer bucket?)",
588                                entry.key
589                            )));
590                        }
591                        Err(e) => return Err(e.into()),
592                };
593                // OFF the fan-out task, for the same reason the ranged arm
594                // is: write_file_atomic is a blocking create+write+fsync+
595                // rename, and running it inline here froze every other
596                // in-flight fetch sharing this task. Small files ALL come
597                // through this arm — 8 KiB is far below the 16 MiB
598                // effective ranged threshold — which is why raising fanout
599                // stopped paying above 128 with half a core sitting idle:
600                // 3,200 files/s at 1.29 of 2 cores, flat from 128 to 512.
601                //
602                // And VERIFIED against the manifest before it is written.
603                // This is the one integrity check that does not depend on
604                // the backend: S3 returns a checksum header the SDK
605                // validates, Ozone returns no CRC-64 at all so the SDK
606                // validates nothing, and a body that is wrong under the
607                // cited etag — bit-rot, a broken gateway, a cache serving
608                // the wrong object — passes If-Match either way. Until
609                // 2026-09-12 the manifest's CRC was compared only on the
610                // RESUME path, so a corrupt fresh fetch was written, cited
611                // in the baseline and read by the agent as the file.
612                let expect_crc = Some(entry.crc64_b64.clone());
613                let (st, got) = {
614                    let target_w = target.clone();
615                    let body_w = body.clone(); // Bytes: a refcount bump, not a copy
616                    let mode_w = entry.mode;
617                    let key_err = entry.key.clone();
618                    let key_crc = entry.key.clone();
619                    let etag_err = entry.etag.clone();
620                    let rel_err = path.clone();
621                    tokio::task::spawn_blocking(
622                        move || -> LeanResult<(std::fs::Metadata, String)> {
623                            let got = flint_store::crc64_to_b64(flint_store::crc64_nvme(&body_w));
624                            if let Some(want) = expect_crc {
625                                if got != want {
626                                    let who = format!("manifest cites {rel_err} ({key_crc} at etag {etag_err}) with");
627                                    return Err(LeanError::State(format!(
628                                        "{who} CRC-64 {want}, but the bytes fetched under that \
629                                         etag hash to {got} — the object is corrupt or the store \
630                                         returned the wrong bytes; refusing to materialise it \
631                                         (nothing written)"
632                                    )));
633                                }
634                            }
635                            let st = write_file_atomic(&target_w, &body_w, Some(mode_w))?;
636                            Ok((st, got))
637                        },
638                    )
639                    .await
640                    .map_err(|e| {
641                        LeanError::State(format!(
642                            "write task for {key_err} did not complete: {e}"
643                        ))
644                    })??
645                };
646                Ok(Fetched {
647                    ranged: false,
648                    path: path.clone(),
649                    be: Some(BaselineEntry {
650                        etag: meta.etag.clone(),
651                        key: Some(entry.key.clone()),
652                        generation: entry.generation,
653                        size: st.len(),
654                        mtime_unix: mtime_of(&st),
655                        mtime_nanos: Some(mtime_nanos_of(&st)),
656                        crc64_b64: Some(got),
657                    }),
658                    skipped: false,
659                    bytes: body.len() as u64,
660                    refused: None,
661                })
662            }
663        }))
664        .buffer_unordered(per_driver)
665        .collect::<Vec<LeanResult<Fetched>>>()
666        .await
667            });
668        }
669        let mut out = Vec::new();
670        while let Some(r) = set.join_next().await {
671            match r {
672                Ok(v) => out.extend(v),
673                Err(e) => out.push(Err(LeanError::State(format!(
674                    "fetch driver did not complete: {e}"
675                )))),
676            }
677        }
678        out
679    }
680
681    /// Materialize the workspace from the manifest. Idempotent across
682    /// crashes (resume skips present paths); refuses over budget
683    /// BEFORE the first byte.
684    pub async fn checkout(&mut self) -> LeanResult<CheckoutReport> {
685        self.checkout_scoped(None).await
686    }
687
688    /// Materialize only the citations an explicit scope admits.
689    ///
690    /// The safety argument is `classify` (`scan.rs`), which derives
691    /// deletions by iterating `baseline.entries.keys()`: a path this
692    /// checkout never materialized is never cited, so it can never be
693    /// classified absent and can never have its object DELETEd. So the
694    /// DELETE sites need no scope filter: the admission filter here is
695    /// that whole argument. What the tree is OWED does need one, below.
696    ///
697    /// The held set is what the baseline cites plus what the scope covers.
698    /// A path outside both that changes REMOTELY is not owed: the consume
699    /// and the sync decline it (`Prop_ScopeRespected` in `LeanP1.tla`).
700    /// A file the AGENT writes outside the scope publishes like any other,
701    /// and from then on the baseline holds it. `rescope` narrows or widens
702    /// the set later.
703    /// Name the right culprit when a fetch could not be served.
704    ///
705    /// Two of `materialize`'s refusals — the SOLE WRITER 412 and the
706    /// cited-object-is-gone 404 — read the same
707    /// evidence ("this object is not what the manifest said") and
708    /// accuse a stranger of writing the bucket. There is a second
709    /// explanation, and after 2026-09-11 it is the LIKELIER one:
710    /// `checkout` no longer holds the epoch, so the workspace's own
711    /// publisher may have published a new generation between the
712    /// manifest we loaded and the object we asked for. A reader is then
713    /// citing a manifest one generation stale, and every word of
714    /// "something other than its publisher wrote that object" is false.
715    ///
716    /// One GET of the pointer tells them apart, and it is paid only on
717    /// a path that is already returning an error. A pointer that has
718    /// not moved leaves the original refusal exactly as written — the
719    /// stranger accusation is still the right one, and softening it for
720    /// every caller to buy this would be the worse trade.
721    /// Has the pointer moved past the document this checkout read? One
722    /// GET of the pointer; unreadable reads as "no", so nothing is
723    /// retried on a store that cannot answer.
724    async fn pointer_moved_past(&self, read_seq: u64) -> bool {
725        match manifest::load_pointer(self.store.as_ref(), &self.cfg).await {
726            Ok(Some(p)) => p.pointer.seq > read_seq,
727            Ok(None) | Err(_) => false,
728        }
729    }
730
731    async fn say_who_moved_it(&self, read_seq: u64, e: LeanError) -> LeanError {
732        let now = match manifest::load_pointer(self.store.as_ref(), &self.cfg).await {
733            Ok(Some(p)) => p.pointer.seq,
734            // No pointer, or we cannot read one. Either way we have
735            // learned nothing, so we must not overwrite what we know.
736            Ok(None) | Err(_) => return e,
737        };
738        if now <= read_seq {
739            return e;
740        }
741        LeanError::State(format!(
742            "this checkout read manifest seq {read_seq} and the workspace is now at \
743             seq {now}: its publisher published while the checkout was running, so \
744             the citation it was still fetching is one generation stale. Re-run \
745             checkout. (The underlying refusal, which names a stranger and in this \
746             case means nothing of the kind: {e})"
747        ))
748    }
749
750    pub async fn checkout_scoped(
751        &mut self,
752        scope: Option<Vec<String>>,
753    ) -> LeanResult<CheckoutReport> {
754        // Validated BEFORE the live-tree row, because a malformed scope
755        // is a configuration error whether or not this tree is already
756        // up, and the one thing it must never do is quietly widen.
757        // `Scope::new` silently drops entries that are too long, past
758        // MAX_SCOPE_ENTRIES, or contain `.`/`..`; three malformed paths
759        // normalize to an EMPTY scope, and an empty scope reads
760        // everywhere as "no restriction" = the whole manifest. Same rule
761        // and same shape as `sync_scoped`.
762        let scope = match scope {
763            None => None,
764            Some(raw) => {
765                let s = super::sync::Scope::new(&raw);
766                if s.is_empty() {
767                    return Err(LeanError::State(format!(
768                        "checkout scope named {} entr{} and NONE survived validation — \
769                         refusing, because an empty scope widens to the WHOLE MANIFEST",
770                        raw.len(),
771                        if raw.len() == 1 { "y" } else { "ies" }
772                    )));
773                }
774                Some(s)
775            }
776        };
777        let requested: Option<Vec<String>> = scope.as_ref().map(|s| s.entries().to_vec());
778
779        let mut report = CheckoutReport::default();
780        report.scope = requested.clone();
781        if self.state.marker_present() {
782            // The live-tree row: never re-materialize. But a live tree
783            // holds what it holds, and `checkout` cannot change that —
784            // so a caller whose scope disagrees with the one on disk
785            // gets an error, never a success naming a set it did not
786            // get. The dangerous direction is the quiet one: a caller
787            // that asks for the whole tree and resumes a 3-file
788            // workspace believes it is holding 2001 paths.
789            let held = self.state.load_scope()?;
790            if held != requested {
791                return Err(LeanError::State(format!(
792                    "this workspace is already checked out {}, and the request asks for \
793                     {} — checkout cannot change the admitted set of a live tree, and \
794                     resuming it would return success for a set you did not get",
795                    describe_scope(held.as_deref()),
796                    describe_scope(requested.as_deref()),
797                )));
798            }
799            report.resumed_live_tree = true;
800            return Ok(report);
801        }
802
803        let mut baseline = self.state.load_baseline()?;
804        let mut present: BTreeSet<String> = BTreeSet::new();
805        let mut attempt = 0u32;
806        let (m, metag, results) = loop {
807            attempt += 1;
808            let t_start = std::time::Instant::now();
809            let loaded = manifest::load(self.store.as_ref(), &self.cfg).await?;
810            report.manifest_secs = t_start.elapsed().as_secs_f64();
811            let (m, metag) = match loaded {
812                Some(l) => (l.manifest, Some(l.etag)),
813                None => (Default::default(), None),
814            };
815
816            // ADMISSION FIRST, budgets second. The order is load-bearing:
817            // a budget is a promise about what THIS checkout will write, and
818            // a 3-file scoped checkout summed over the whole 2001-file
819            // manifest is refused for bytes it was never going to fetch.
820            let admission: Vec<(&String, &super::manifest::LeanEntry)> = match &scope {
821                None => m.entries.iter().collect(),
822                Some(s) => m.entries.iter().filter(|(p, _)| s.covers(p)).collect(),
823            };
824            report.out_of_scope = m.entries.len() - admission.len();
825
826            // Budgets: refuse before materializing anything.
827            let total_bytes: u64 = admission.iter().map(|(_, e)| e.size).sum();
828            if self.cfg.max_bytes > 0 && total_bytes > self.cfg.max_bytes {
829                return Err(LeanError::Budget(format!(
830                    "checkout is {} bytes; budget {}",
831                    total_bytes, self.cfg.max_bytes
832                )));
833            }
834            if self.cfg.max_files > 0 && admission.len() as u64 > self.cfg.max_files {
835                return Err(LeanError::Budget(format!(
836                    "checkout is {} files; budget {}",
837                    admission.len(),
838                    self.cfg.max_files
839                )));
840            }
841
842            let t_fetch = std::time::Instant::now();
843            // A mirror's publisher is the only party entitled to write it,
844            // so an object off its citation was moved by a stranger.
845            // Adopting it would copy bytes no manifest cites into this
846            // tree, silently — drill C4.
847            let results = self.materialize(admission, m.sole_writer).await;
848            report.fetch_secs += t_fetch.elapsed().as_secs_f64();
849            // A citation that could not be served has a second explanation
850            // under handles (design 2026-09-19): the workspace's own
851            // publisher moved the pointer past the document this pass read
852            // and its collector took the handle. Then the pass is simply
853            // re-run against the new document — bounded, and cheap: every
854            // file already on disk at the cited bytes is adopted, not
855            // fetched again — instead of telling the caller to. A pointer
856            // that has not moved leaves the refusal exactly as written.
857            let moved = results.iter().any(|r| r.is_err()) && self.pointer_moved_past(m.seq).await;
858            if moved && attempt < 3 {
859                report.reresolved += 1;
860                continue;
861            }
862            break (m, metag, results);
863        };
864        let t_commit = std::time::Instant::now();
865        for r in results {
866            let f = match r {
867                Ok(f) => f,
868                Err(e) => return Err(self.say_who_moved_it(m.seq, e).await),
869            };
870            if let Some(why) = f.refused {
871                self.state.append_conflict(&super::state::ConflictRecord {
872                    path: f.path.clone(),
873                    foreign_etag: String::new(),
874                    preserved_key: None,
875                    kind: format!("checkout-refused: {why}"),
876                    at_unix: super::now_unix(),
877                })?;
878                report.refused += 1;
879                continue;
880            }
881            if f.ranged {
882                report.ranged += 1;
883            }
884            if f.skipped {
885                report.skipped_present += 1;
886            } else {
887                report.materialized += 1;
888                report.bytes += f.bytes;
889            }
890            present.insert(f.path.clone());
891            if let Some(be) = f.be {
892                baseline.entries.insert(f.path, be);
893            }
894        }
895
896        baseline.seq = m.seq;
897        baseline.manifest_etag = metag;
898        // Checked out whole or scoped, the tree owes nothing: the baseline
899        // (the merge base since P1-lite) holds what was materialised, and the
900        // consume never owes a path the scope declined. So this document is
901        // derived, and nothing is skipped.
902        baseline.derived_etag = Some(baseline.manifest_etag.clone().unwrap_or_default());
903        baseline.skipped.clear();
904        baseline.prev_scan = present;
905        // Every materialised file reaches stable storage BEFORE the
906        // baseline and the marker that vouch for it: after a power loss
907        // the tree is then at least as durable as its description, so
908        // the next scan cannot read a zero-length survivor as a local
909        // edit and publish it over the good version.
910        self.state.sync_tree()?;
911        self.state.save_baseline(&baseline)?;
912        // Before the marker, always — including the `None` case, which
913        // REMOVES any scope a crashed predecessor left behind. The
914        // marker is the agent-start gate; a scope that landed after it
915        // would leave a window in which an agent is cleared to run
916        // against a tree whose admitted set is not yet durable, and a
917        // crash there yields a workspace holding three files that
918        // claims, by the absence of any scope, to hold all of them.
919        self.state.save_scope(requested.as_deref())?;
920        // D11: the capability marker and the gauges exist BEFORE the
921        // agent-start gate opens, so the first thing the agent does can
922        // be to read them. `run` writes capabilities around checkout
923        // too; doing it here as well covers the standalone `checkout`
924        // subcommand, which otherwise leaves an agent with no marker to
925        // read and therefore no way to know the verbs exist.
926        let posture = self.sentinel_preflight()?;
927        self.write_capabilities(&posture)?;
928        self.write_gauges(None)?;
929        // The marker is written LAST: the agent-start gate.
930        self.state.write_marker()?;
931        report.commit_secs = t_commit.elapsed().as_secs_f64();
932        Ok(report)
933    }
934}
935
936// ── the narrow / widen verb (scoped-read design §4) ──────────────────
937
938#[derive(Debug, Default)]
939pub struct RescopeReport {
940    /// The scope this workspace now holds. `None` = the whole tree.
941    pub target: Option<Vec<String>>,
942    /// Citations removed from the held set — the NARROW half.
943    pub uncited: usize,
944    /// Files removed from the tree. Normally equal to `uncited`; lower
945    /// when a path was already gone.
946    pub unlinked: usize,
947    /// Newly admitted citations fetched — the WIDEN half.
948    pub materialized: usize,
949    pub bytes: u64,
950    /// Admitted and already held: the scope grew over paths the
951    /// workspace had. Zero work, and the number that tells a widen that
952    /// did nothing from a widen that had nothing to do.
953    pub already_held: usize,
954    /// Paths whose unpublished local changes a rescope kept, each with a
955    /// conflict record: on a narrow, paths that should have left the held
956    /// set (KEPT, cited — a narrow may unwatch a file, never discard an
957    /// edit); on a widen, admitted paths where the agent had made a file
958    /// the tree does not cite yet (kept, uncited, published by the next
959    /// barrier).
960    pub kept_dirty: Vec<String>,
961    /// This call finished a rescope a crash had left half-applied.
962    pub replayed: bool,
963}
964
965impl Syncer {
966    /// Move the workspace to `target`: stop holding what it no longer
967    /// admits, and fetch what it newly does.
968    ///
969    /// ## Why this cannot be `rm` plus a scope edit
970    ///
971    /// `classify` reads exactly the two states a narrow passes through:
972    /// present-in-scan-absent-from-baseline is an **upload**, and
973    /// present-in-baseline-absent-from-scan-and-`prev_scan` is a
974    /// **delete**. So unlink-then-uncite crashes into publishing
975    /// deletions, and uncite-then-unlink crashes into re-uploading
976    /// identical bytes and re-citing everything just dropped. Neither
977    /// order is safe alone. The invariant, stated for the model:
978    /// **a narrow is an unwatch, never an absence.**
979    ///
980    /// What makes it safe is the INTENT, not the order: the target is
981    /// durable before the first mutation and cleared after the last,
982    /// `run_barrier` replays any intent it finds before it does
983    /// anything else, and the replay is idempotent. The order within
984    /// still matters for the window where the intent itself is lost —
985    /// uncite first, so the failure mode is a file that gets
986    /// re-uploaded rather than one that gets DELETED from the bucket.
987    ///
988    /// ## Why the verb takes a SET
989    ///
990    /// `manifest::load` fetches the pointer and every chunk regardless
991    /// of scope, so the floor is one whole-manifest load per call.
992    /// A per-path verb would pay that floor per path.
993    pub async fn rescope(&mut self, target: Option<Vec<String>>) -> LeanResult<RescopeReport> {
994        if let Some(raw) = &target {
995            // An all-rejected scope is REFUSED, never widened to the
996            // whole tree — `Scope::new` silently drops malformed
997            // entries, and `sync.rs` already shipped the bug where that
998            // turned a typo into maximum privilege.
999            if super::sync::Scope::new(raw).is_empty() {
1000                return Err(LeanError::State(format!(
1001                    "every entry of the requested scope was rejected ({raw:?}); refusing to \
1002                     read that as the whole tree"
1003                )));
1004            }
1005        }
1006        if !self.state.marker_present() {
1007            return Err(LeanError::State(
1008                "rescope needs a checked-out workspace — run checkout first".into(),
1009            ));
1010        }
1011
1012        // The strict check belongs at the DOOR, before anything is
1013        // written: a caller asking to drop a path it has unpublished
1014        // edits to gets told, and the old scope stands untouched. The
1015        // replay below cannot be this strict — it must converge — so it
1016        // keeps such paths instead. Two postures, deliberately.
1017        let leaving = self.paths_leaving(&target)?;
1018        let dirty = self.dirty_among(&leaving)?;
1019        if !dirty.is_empty() {
1020            return Err(LeanError::State(format!(
1021                "these paths would leave the scope but have unpublished local changes: {:?} — \
1022                 publish or discard them first",
1023                dirty
1024            )));
1025        }
1026
1027        let intent = super::state::ScopeIntent { target, drop: leaving, held: Default::default() };
1028        self.state.save_scope_intent(&intent)?;
1029        self.apply_scope_intent(&intent).await
1030    }
1031
1032    /// Finish a rescope a crash left half-applied. `None` when there is
1033    /// none in flight. Idempotent: running it twice is running it once.
1034    pub async fn replay_scope_intent(&mut self) -> LeanResult<Option<RescopeReport>> {
1035        let Some(intent) = self.state.load_scope_intent()? else { return Ok(None) };
1036        let mut report = self.apply_scope_intent(&intent).await?;
1037        report.replayed = true;
1038        Ok(Some(report))
1039    }
1040
1041    /// Which held paths the target scope would stop admitting.
1042    fn paths_leaving(&self, target: &Option<Vec<String>>) -> LeanResult<Vec<String>> {
1043        let baseline = self.state.load_baseline()?;
1044        let scope = target.as_ref().map(|r| super::sync::Scope::new(r));
1045        Ok(baseline
1046            .entries
1047            .keys()
1048            .filter(|p| scope.as_ref().map(|s| !s.covers(p)).unwrap_or(false))
1049            .cloned()
1050            .collect())
1051    }
1052
1053    /// Which of `paths` carry local changes the bucket has not seen.
1054    /// The same three states `sync` calls dirty, for the same reason.
1055    fn dirty_among(&self, paths: &[String]) -> LeanResult<Vec<String>> {
1056        if paths.is_empty() {
1057            return Ok(vec![]);
1058        }
1059        let baseline = self.state.load_baseline()?;
1060        let scanned = super::scan::scan(&self.cfg.root)?;
1061        let c = super::scan::classify(&scanned, &baseline);
1062        Ok(paths
1063            .iter()
1064            .filter(|p| {
1065                c.uploads.contains(*p) || c.deletes.contains(*p) || c.first_absence.contains(*p)
1066            })
1067            .cloned()
1068            .collect())
1069    }
1070
1071    async fn apply_scope_intent(
1072        &mut self,
1073        intent: &super::state::ScopeIntent,
1074    ) -> LeanResult<RescopeReport> {
1075        let target = intent.target.clone();
1076        let mut report = RescopeReport { target: target.clone(), ..Default::default() };
1077        let scope = target.as_ref().map(|r| super::sync::Scope::new(r));
1078        let covered = |p: &str| scope.as_ref().map(|s| s.covers(p)).unwrap_or(true);
1079
1080        // §4.4's floor: the whole manifest, scope or no scope.
1081        let loaded = manifest::load(self.store.as_ref(), &self.cfg).await?;
1082        let (m, metag) = match loaded {
1083            Some(l) => (l.manifest, Some(l.etag)),
1084            None => (Default::default(), None),
1085        };
1086
1087        let mut baseline = self.state.load_baseline()?;
1088        // THE RECORDED set, never re-derived — see `ScopeIntent::drop`.
1089        // Re-deriving from the baseline loses the whole set the moment
1090        // the uncite lands; re-deriving from the tree cannot tell a
1091        // leftover from a file the agent created.
1092        let leaving: Vec<String> = intent.drop.clone();
1093        // Converging posture: a dirty path is KEPT rather than dropped,
1094        // so a replay can never be stuck refusing forever.
1095        //
1096        // A path already uncited by a crashed run reads as dirty here
1097        // (present in scan, absent from the baseline ⇒ `uploads`), and
1098        // keeping it would undo the very step that crashed. So dirt is
1099        // judged against what the path IS: still cited and modified, or
1100        // not cited at all and therefore already half-dropped.
1101        let still_cited: Vec<String> =
1102            leaving.iter().filter(|p| baseline.entries.contains_key(*p)).cloned().collect();
1103        let dirty = self.dirty_among(&still_cited)?;
1104        for p in &dirty {
1105            self.state.append_conflict(&super::state::ConflictRecord {
1106                path: p.clone(),
1107                foreign_etag: String::new(),
1108                preserved_key: None,
1109                kind: "rescope-kept-locally-dirty".into(),
1110                at_unix: super::now_unix(),
1111            })?;
1112        }
1113        report.kept_dirty = dirty.clone();
1114        let drop_set: Vec<String> =
1115            leaving.into_iter().filter(|p| !dirty.contains(p)).collect();
1116
1117        // What the uncite drops, durable with the intent before it lands. A
1118        // replay keeps what an earlier run recorded: those paths are no
1119        // longer in the baseline to read it from.
1120        let mut recorded = intent.clone();
1121        for p in &drop_set {
1122            if let Some(be) = baseline.entries.get(p) {
1123                recorded.held.insert(p.clone(), be.clone());
1124            }
1125        }
1126        if recorded != *intent {
1127            self.state.save_scope_intent(&recorded)?;
1128        }
1129
1130        // UNCITE FIRST, and durably, before a single file leaves the
1131        // tree. Both halves must happen, and the intent guarantees
1132        // they will; this order decides only which way a lost intent
1133        // fails — toward a file that reads as a local add (re-uploaded,
1134        // recoverable) rather than one that reads as a local delete
1135        // (published as a DELETE, not recoverable).
1136        for p in &drop_set {
1137            baseline.entries.remove(p);
1138            baseline.prev_scan.remove(p);
1139        }
1140        report.uncited = drop_set.len();
1141        self.state.save_baseline(&baseline)?;
1142
1143        for p in &drop_set {
1144            let local = self.cfg.root.join(p);
1145            // The same containment the barrier demands: a citation is
1146            // not a licence to unlink whatever a path resolves to.
1147            if contained_path(&self.cfg.root, p).is_err() {
1148                continue;
1149            }
1150            super::barrier::consume_window("rescope-before-unlink", p);
1151            // Only the bytes the uncite dropped. A file that is no longer
1152            // them is the agent's, written since: kept, uncited, recorded;
1153            // the next barrier publishes it as the agent's add.
1154            if std::fs::symlink_metadata(&local).is_ok()
1155                && super::barrier::local_dirty(&local, recorded.held.get(p))
1156            {
1157                self.state.append_conflict(&super::state::ConflictRecord {
1158                    path: p.clone(),
1159                    foreign_etag: String::new(),
1160                    preserved_key: None,
1161                    kind: "rescope-kept-agent-write".into(),
1162                    at_unix: super::now_unix(),
1163                })?;
1164                report.kept_dirty.push(p.clone());
1165                continue;
1166            }
1167            match std::fs::remove_file(&local) {
1168                Ok(()) => report.unlinked += 1,
1169                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1170                Err(e) => return Err(LeanError::Io(e)),
1171            }
1172        }
1173
1174        // WIDEN: admitted citations this workspace does not hold.
1175        let mut add: Vec<(&String, &super::manifest::LeanEntry)> =
1176            m.entries.iter().filter(|(p, _)| covered(p) && !baseline.entries.contains_key(*p)).collect();
1177        // A file already at an admitted path that this tree does not cite
1178        // is the agent's (made since the last barrier; the scan has not
1179        // published it yet). Materialize would fetch the document's
1180        // version over it (checkout's resume rule, which is right only
1181        // for its own half-written fetches). The consume calls such a path
1182        // dirty and leaves it; so does the widen: kept, uncited, and named
1183        // in a record. The next barrier publishes it as the agent's add,
1184        // and the merge records the version it replaces (review
1185        // 2026-09-29, R3). Bytes that ARE the document's are adopted as
1186        // before, which is what lets a crashed widen's replay converge.
1187        let mut kept_local: Vec<String> = Vec::new();
1188        add.retain(|(p, e)| {
1189            let local = self.cfg.root.join(p);
1190            let Ok(st) = std::fs::symlink_metadata(&local) else { return true };
1191            let same = st.is_file()
1192                && st.len() == e.size
1193                && local_crc64_b64(&local).map(|got| got == e.crc64_b64).unwrap_or(false);
1194            if !same {
1195                kept_local.push((*p).clone());
1196            }
1197            same
1198        });
1199        for p in &kept_local {
1200            self.state.append_conflict(&super::state::ConflictRecord {
1201                path: p.clone(),
1202                foreign_etag: m.entries[p].etag.clone(),
1203                preserved_key: None,
1204                kind: "rescope-kept-local-unpublished".into(),
1205                at_unix: super::now_unix(),
1206            })?;
1207        }
1208        report.kept_dirty.extend(kept_local);
1209        report.already_held =
1210            m.entries.keys().filter(|p| covered(p) && baseline.entries.contains_key(*p)).count();
1211        if !add.is_empty() {
1212            let results = self.materialize(add, m.sole_writer).await;
1213            for r in results {
1214                let f = r?;
1215                if let Some(why) = f.refused {
1216                    self.state.append_conflict(&super::state::ConflictRecord {
1217                        path: f.path.clone(),
1218                        foreign_etag: String::new(),
1219                        preserved_key: None,
1220                        kind: format!("rescope-refused: {why}"),
1221                        at_unix: super::now_unix(),
1222                    })?;
1223                    continue;
1224                }
1225                if !f.skipped {
1226                    report.materialized += 1;
1227                    report.bytes += f.bytes;
1228                }
1229                baseline.prev_scan.insert(f.path.clone());
1230                if let Some(be) = f.be {
1231                    baseline.entries.insert(f.path, be);
1232                }
1233            }
1234        }
1235
1236        baseline.seq = m.seq;
1237        baseline.manifest_etag = metag;
1238        // What the held set is owed changed with it: the next consume
1239        // derives in full rather than trusting the cheap path's record
1240        // (a widened path it kept or could not take is owed from here).
1241        baseline.derived_etag = None;
1242        baseline.skipped.clear();
1243
1244        self.state.sync_tree()?;
1245        self.state.save_baseline(&baseline)?;
1246        self.state.save_scope(target.as_deref())?;
1247        // LAST. While this document exists the workspace is mid-rescope
1248        // and `run_barrier` will replay before doing anything else.
1249        self.state.clear_scope_intent()?;
1250        Ok(report)
1251    }
1252}