Skip to main content

flint_lean/
lib.rs

1//! flint-lean: the checkout/publish syncer core (plan of record:
2//! docs/plans/flint-lean-plan.md v2).
3//!
4//! Lean is a SEPARATE front end from the hub: no NFS, no daemon in the
5//! data path. An agent pod gets a full local checkout on an emptyDir
6//! (real ext4/APFS POSIX), and a syncer publishes snapshots to the
7//! bucket through a barrier. Durability is RPO-shaped (the flush floor);
8//! coherence is snapshot-level (the subtree manifest CAS is the atomic
9//! commit point). This module reuses `tier::store` (ObjectStore,
10//! GenerationStamps, conditional puts, the epoch cell) as a library and
11//! deliberately does NOT reuse the hub's flush/arbitration machinery —
12//! the plan pins that: the hub's 412 arbitration is LOCAL-WINS-overwrite
13//! (`tier/flush.rs`), which is exactly wrong under HITL second writers.
14//!
15//! The protocol here is the machine checked by `lean/formal/
16//! LeanSubtree.tla` (20-run gate). The load-bearing rules, each of
17//! which a model mutation rediscovers when broken:
18//!
19//! - **Barrier order**: consume inbox → scan → intent/window → uploads
20//!   → manifest CAS (merge) → deletes LAST as GC of keys the NEW
21//!   manifest no longer references → baseline rewrite. (v1's
22//!   upload→delete→CAS order dangles the manifest on a crash.)
23//! - **HITL writes land as object + inbox entry, never direct manifest
24//!   edits**; the barrier never runs against an unconsumed inbox.
25//! - **Never If-Match-overwrite an ETag this syncer did not itself
26//!   publish or consume**: a foreign 412 parks the path and surfaces a
27//!   conflict; own-crashed-PUT is recognized by flush_uuid and adopted.
28//! - **GC deletes are HEAD-guarded** on the recognized ETag.
29//! - **Takeover rotation**: a successor CAS-rewrites the manifest
30//!   (seq++, content-identical) BEFORE serving, so a deposed
31//!   straggler's manifest CAS 412s; every publish carries its epoch.
32//! - **Restart matrix**: marker present ⇒ never re-materialize (a
33//!   re-checkout would resurrect unpublished deletes); reload the
34//!   persisted baseline, rescan, self-recognize the lease via the
35//!   persisted incarnation id (emptyDir-scoped — a replacement pod gets
36//!   a fresh identity and takes the takeover path).
37//! - **Deletion basis**: a path is delete-eligible only if absent in
38//!   two consecutive scans AND present in our own baseline (the
39//!   rename-vs-walk guard).
40
41pub mod barrier;
42pub mod checkout;
43pub mod chunk;
44pub mod control;
45pub mod gauges;
46pub use gauges::{status_report, Gauges, StatusReport};
47pub mod inbox;
48pub mod lease;
49pub mod manifest;
50pub mod metrics;
51pub mod reader;
52pub mod scan;
53pub(crate) mod safefs;
54pub mod sentinel;
55pub mod state;
56pub mod sync;
57pub mod trace;
58pub mod uds;
59pub mod verbs;
60
61#[cfg(test)]
62mod tests;
63#[cfg(test)] mod tests_upload_gate;
64
65use std::path::PathBuf;
66use std::sync::Arc;
67
68use flint_store::ObjectStore;
69
70/// Reserved control namespace inside the subtree prefix. Never scanned,
71/// never part of a checkout, never GC'd by the barrier.
72pub const LEAN_DIR: &str = ".flint/lean";
73
74/// The syncer's durable bookkeeping directory inside the workspace
75/// (emptyDir-scoped: survives container restarts, dies with the pod).
76pub const STATE_DIR: &str = ".flint-sync";
77
78/// The workspace-local control namespace (boundary-verbs plan D0): the
79/// agent's side of the file protocol. Reserved exactly as the gateway
80/// reserves `.flint/` on the HTTP side (flint-lean-gateway's `path_ok`) — the scan
81/// skips it, `classify` never makes it delete-eligible, and checkout
82/// never materializes a `files/.flint/...` citation into it.
83pub const CONTROL_DIR: &str = ".flint";
84
85/// Protocol version advertised in `.flint/capabilities.json`.
86pub const SENTINEL_PROTOCOL: u32 = 1;
87
88/// This binary's version, echoed to the agent (`capabilities.json`) and
89/// to the operator (the lease cell's echo, §2.6). Both mixed-version
90/// holes — agent↔syncer and operator↔syncer — are detected by
91/// comparing what is RUNNING against what was asked for, and neither
92/// comparison exists without a version on the running side.
93pub const SYNCER_VERSION: &str = env!("CARGO_PKG_VERSION");
94
95/// Default whole-object publish ceiling; larger files go through the
96/// multipart compose path (`tier/flush.rs` uses the same 64 MiB split).
97pub const WHOLE_PUT_MAX: u64 = 64 * 1024 * 1024;
98
99#[derive(Debug, thiserror::Error)]
100pub enum LeanError {
101    #[error("store: {0}")]
102    Store(#[from] flint_store::StoreError),
103    #[error("io: {0}")]
104    Io(#[from] std::io::Error),
105    #[error("state: {0}")]
106    State(String),
107    /// The cell moved under a commit section: this barrier is
108    /// abandoned — its manifest is never installed, its uploads stand
109    /// as uncited generations the next barrier adopts by `flush_uuid`.
110    /// Not a process exit and not a terminal state: the lease is held
111    /// per barrier, so the next one claims again.
112    #[error("fenced: {0}")]
113    Fenced(String),
114    /// A budget refused the operation (checkout bytes/file-count).
115    #[error("budget: {0}")]
116    Budget(String),
117    /// A precondition the OPERATOR must change refused the run (the
118    /// prefix is claimed by another project). A restart cannot fix it,
119    /// so the binary exits `EXIT_REFUSED` — the code the CSI delivery
120    /// reads as final. Any other non-zero exit is retried in place by
121    /// `restartPolicy: OnFailure`, and a refusal sharing that code was a
122    /// crash loop the plugin reported to the tenant as "checkout in
123    /// progress" for as long as it lived (audit 2026-09-03, finding 5,
124    /// leg S22).
125    #[error("refused: {0}")]
126    Refused(String),
127}
128
129/// Process exit code for `LeanError::Refused` (sysexits `EX_CONFIG`).
130/// Mirrored as `SYNCER_EXIT_REFUSED` in the CSI node plugin, which does
131/// not depend on this crate; drill leg S22 is where the two are checked
132/// against each other.
133pub const EXIT_REFUSED: i32 = 78;
134
135impl LeanError {
136    /// The store refused our credentials (401/403, `ExpiredToken`,
137    /// `RequestTimeTooSkewed`): a broker, token or clock fault.
138    ///
139    /// A predicate rather than a `LeanError` variant on purpose.
140    /// `Store` is built by `#[from]`, so every `?` in the crate
141    /// constructs it implicitly; a variant would have to be produced by
142    /// hand at each of those sites and would be missed at exactly the
143    /// one that mattered. Reading through the wrapper cannot be
144    /// bypassed by a conversion nobody remembered to special-case.
145    pub fn is_auth(&self) -> bool {
146        matches!(self, LeanError::Store(flint_store::StoreError::Auth(_)))
147    }
148}
149
150pub type LeanResult<T> = Result<T, LeanError>;
151
152/// Sentinel posture knob (D0.4). `auto` = verbs on unless the
153/// pre-existing-`.flint/` pre-flight trips; `force` accepts consumption
154/// of pre-existing sentinel-named files.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum SentinelMode {
157    Auto,
158    Off,
159    Force,
160}
161
162impl SentinelMode {
163    pub fn parse(s: &str) -> Option<SentinelMode> {
164        match s {
165            "auto" => Some(SentinelMode::Auto),
166            "off" => Some(SentinelMode::Off),
167            "force" => Some(SentinelMode::Force),
168            _ => None,
169        }
170    }
171    pub fn as_str(&self) -> &'static str {
172        match self {
173            SentinelMode::Auto => "auto",
174            SentinelMode::Off => "off",
175            SentinelMode::Force => "force",
176        }
177    }
178}
179
180/// What this syncer may do to the bucket (per-user access design §4.4).
181///
182/// `Read` is a syncer that follows the workspace and never writes to it:
183/// no fence, no barrier, no inbox consume, no garbage collection. Its
184/// floor tick pulls — the inbox and the pointer, and a `sync` when
185/// either moved — and a `publish` is answered `refused-read-only`. It is
186/// what a read-only credential is SUFFICIENT for; the credential, not
187/// this flag, is what keeps a reader's bytes out of the bucket.
188#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
189pub enum Access {
190    #[default]
191    ReadWrite,
192    Read,
193}
194
195impl Access {
196    /// `FLINT_SYNC_ACCESS`: `read` | `readWrite`.
197    pub fn parse(s: &str) -> Option<Access> {
198        match s {
199            "read" => Some(Access::Read),
200            "readWrite" => Some(Access::ReadWrite),
201            _ => None,
202        }
203    }
204    pub fn as_str(&self) -> &'static str {
205        match self {
206            Access::ReadWrite => "readWrite",
207            Access::Read => "read",
208        }
209    }
210    pub fn is_read(&self) -> bool {
211        *self == Access::Read
212    }
213}
214
215#[derive(Clone)]
216pub struct LeanConfig {
217    /// Bucket key prefix for this subtree (project- or subtree-scoped;
218    /// the proxy's tenancy boundary).
219    pub prefix: String,
220    /// Workspace root (the agent's tree).
221    pub root: PathBuf,
222    /// Publish cadence floor, seconds (the durability contract).
223    pub floor_secs: u64,
224    /// Stamp `sole_writer` on every manifest this syncer installs.
225    ///
226    /// Set for a workspace that is PUBLISHED rather than worked in —
227    /// forge's legible export is the shipped case. It tells every later
228    /// reader that an object off its citation was moved by a stranger,
229    /// so the reader refuses instead of adopting.
230    pub sole_writer: bool,
231    /// Read or read-write (`Access`). Default read-write.
232    pub access: Access,
233    /// Whole-object ceiling; larger files use multipart compose.
234    pub whole_put_max: u64,
235    /// Entries per manifest chunk, in expectation, and the floor and
236    /// ceiling around it (chunked design §3). Config rather than
237    /// constants because §4 already anticipates this moving: the
238    /// pointer body is O(entries / target), and past ~10M entries the
239    /// target is one of the two things that can be changed instead of
240    /// adding a second level. Not surfaced on the CRD — nothing has
241    /// needed to tune it per workspace yet, and a knob with no caller
242    /// is a support burden.
243    /// Publish the manifest as a CHUNK LIST rather than one generation
244    /// object per citation (chunked design). Default ON since
245    /// 2026-09-04.
246    ///
247    /// The migration is FAIL-CLOSED and one-way per workspace: a
248    /// pointer-era binary cannot parse a chunked pointer, which is the
249    /// point — every layout change has to make an old reader REFUSE
250    /// rather than conclude the project is empty and re-seed over it.
251    ///
252    /// Small projects are not penalised, which is what made turning it
253    /// on unconditional rather than threshold-gated: under the target a
254    /// project is ONE chunk, so it costs a pointer plus one object and
255    /// two GETs to read — exactly what the single-generation layout
256    /// already cost. The indirection was paid for by step one.
257    ///
258    /// `false` is still a supported READ path forever (a workspace that
259    /// has not published since the migration) and is what the
260    /// single-layout tests set explicitly.
261    pub chunked: bool,
262    /// How long an unreferenced chunk must have sat before the reaper
263    /// may take it. Config rather than a constant because the model
264    /// makes it load-bearing in a workload-dependent way: it must
265    /// outlive the LONGEST publish, not the longest plausible one
266    /// (`LeanChunkGCRacyGrace`).
267    pub orphan_grace_secs: u64,
268    pub chunk_target: usize,
269    pub chunk_min: usize,
270    pub chunk_max: usize,
271    /// Checkout refusal budgets (0 = unlimited).
272    pub max_bytes: u64,
273    pub max_files: u64,
274    /// Window deadline slack beyond the barrier start, seconds. A dead
275    /// syncer's window is ignorable past this deadline.
276    pub window_slack_secs: u64,
277    /// Bounded concurrency for uploads and checkout fetches. The 0b
278    /// rig measured the sequential loops at 561-854 PUTs/s and
279    /// 1,000-2,000 GETs/s; fan-out multiplies directly against those.
280    pub fanout: usize,
281    /// Concurrent UPLOADS. Deliberately separate from `fanout`, and
282    /// measured separately: the read path's width is what the checkout
283    /// rig moved, this one is what the publish rig moved. Both paths are
284    /// byte-bounded, by different gates — the read side by
285    /// `fetch_inflight_max_bytes` here, the upload side by the store's
286    /// own gate (`with_upload_inflight_max_bytes`, 256 MiB from the
287    /// binary), which charges every whole body and every multipart part
288    /// from before its read until its PUT returns. So this number sets
289    /// request concurrency, not peak RSS.
290    pub upload_fanout: usize,
291    /// The project this workspace claims to be, stamped from the CR
292    /// (`FLINT_SYNC_PROJECT_ID`). When set, `lease::verify_claim`
293    /// refuses to run over a prefix whose claim cell names another
294    /// project — the operator's refuse-foreign, enforced on the DATA
295    /// plane (audit 2026-09-03, finding 5). `None` = unstamped: no
296    /// check, the pre-operator posture.
297    pub project_id: Option<String>,
298    /// Ceiling on bytes in flight across the checkout fan-out window.
299    ///
300    /// `fanout` bounds the number of concurrent fetches but NOT their
301    /// size, and `get_whole` holds each whole object in RAM before it
302    /// reaches disk — so peak RSS was `fanout x largest object`, an
303    /// unbounded product of two numbers nobody sets together. A 32-wide
304    /// window over 64 MiB objects is 2 GiB in a syncer that ships with
305    /// no memory limit at all. Each entry takes permits proportional to
306    /// its size, so small-file trees still run the full width.
307    pub fetch_inflight_max_bytes: u64,
308    /// Driver tasks for the checkout fan-out (see `materialize`). Each
309    /// runs `fanout / fetch_drivers` fetches at a time over its own
310    /// slice of the tree, so the per-request SDK work spreads over that
311    /// many cores instead of one. Default: the machine's cores, at most
312    /// 8 (`FLINT_SYNC_FETCH_DRIVERS` / `spec.fetchDrivers`, 0 = auto).
313    /// Measured 2026-09-12: one driver is the ~3,300 files/s plateau on
314    /// i4i.xlarge whatever `fanout` says; four are 6,188-6,521 at
315    /// fanout 256, and fanout 256 beats 128 for the first time.
316    pub fetch_drivers: usize,
317
318    /// Materialise an object this size or larger as PARALLEL RANGES
319    /// rather than one whole-object GET. `0` disables it.
320    ///
321    /// Defaults to 8 MiB on the measurement that the repo's rule asked
322    /// for — runcr, i4i.large spot, us-west-1, one AZ, n=3, arms
323    /// interleaved per rep, RANGES not means:
324    ///
325    ///   6 x 1 GiB          71.33-71.88 s  ->  21.24-23.96 s
326    ///   4 GiB + 2k x 16 K  57.02-57.83 s  ->  15.30-18.30 s
327    ///   20k x 8 KiB        16.92-19.44 s  ->  16.40-17.39 s
328    ///
329    /// The third row is the one that justifies a THRESHOLD rather than
330    /// ranging everything: every object there is under it, the ranged
331    /// path never fires, and the arms agree. Before this, the shipped
332    /// path lost a cold 6 GiB checkout to a plain `aws s3 cp` of the
333    /// same prefix on the same node (21.7 s); it now ties it.
334    ///
335    /// Ranging also LOWERS peak RSS for a large object — see below — so
336    /// this default costs memory nothing and returns some.
337    ///
338    /// NOTE the interaction with `range_get_chunk_bytes`: a single part
339    /// is "one whole GET with extra steps" and `fetch_ranged` declines
340    /// it, so an object in [`range_get_min_bytes`, `range_get_chunk_bytes`)
341    /// passes this threshold and still takes the whole-object path. With
342    /// the defaults below the EFFECTIVE threshold is therefore 16 MiB,
343    /// not 8.
344    ///
345    /// Two costs of `get_whole` are paid together and this is what
346    /// removes both: one object is one TCP stream, so a multi-GiB
347    /// checkpoint runs at single-connection throughput no matter how
348    /// wide the fan-out; and the body is held whole in RAM before it
349    /// reaches disk, which is the product `fetch_inflight_max_bytes`
350    /// exists to bound. Ranges write at their offset as they land, so
351    /// peak RSS per object becomes `range_get_chunk_bytes x
352    /// range_get_parallelism` instead of the object's size.
353    pub range_get_min_bytes: u64,
354    /// Bytes per range request. Large enough that per-request overhead
355    /// is noise against S3's first-byte latency; small enough that a
356    /// retried range is cheap.
357    pub range_get_chunk_bytes: u64,
358    /// Ranges in flight FOR ONE OBJECT. The checkout's byte semaphore
359    /// still bounds the whole window, so this multiplies concurrency
360    /// only where the fan-out has run out of objects to work on — which
361    /// is exactly the tail this exists to shorten.
362    pub range_get_parallelism: usize,
363
364    // --- boundary verbs (plan docs/plans/flint-lean-boundary-verbs-plan.md) ---
365    /// Sentinel posture (D0.4 pre-flight override).
366    pub sentinel_mode: SentinelMode,
367    /// A consumed sentinel arriving sooner than this after the previous
368    /// sentinel-honoring barrier waits; touches inside the interval
369    /// coalesce into the pending record.
370    pub sentinel_min_interval_secs: u64,
371    /// Work-metered hourly cap (D3.1): a honor charges
372    /// `max(1, ceil(published_bytes / whole_put_max))` units, or 0 for
373    /// a no-diff honor. Exhaustion defers honors to the floor tick —
374    /// the workspace degrades to exactly cadence behavior.
375    pub sentinel_hourly_budget: u64,
376    /// Sentinel poll cadence (env-only, not a fleet contract).
377    pub sentinel_poll_secs: u64,
378
379    // --- the publish fence (design 2026-09-13 §4; `lease.rs`) ---
380    /// How often a barrier waiting for the cell re-reads it.
381    pub claim_poll_secs: u64,
382    /// The poll cadence of the waiter at the head of the queue
383    /// (`lease::CLAIM_POLL_HEAD_MS`).
384    pub claim_poll_head_ms: u64,
385    /// Minimum spacing between two observations that COUNT toward the
386    /// dead-holder (`QUIET_POLLS`) and abandoned-handoff thresholds.
387    /// The tests set it to 0 so a deposal takes six polls, not a minute.
388    pub claim_quiet_spacing_secs: u64,
389    /// Longest a barrier waits for the cell before it is abandoned and
390    /// retried at the next floor.
391    pub claim_deadline_secs: u64,
392    /// DRILL-ONLY (`FLINT_SYNC_DRILL_HOLD_COMMIT_SECS`, never stamped by
393    /// the operator): sleep this long inside the commit section, right
394    /// after the claim. The one straggler the per-barrier lease still
395    /// has is a holder that stalls INSIDE its commit section, and that
396    /// section is milliseconds long — no drill can hit it by timing, so
397    /// this is how `run-writers.sh` opens the window. 0 = off.
398    pub drill_hold_commit_secs: u64,
399    /// DRILL-ONLY (`FLINT_SYNC_DRILL_HOLD_GC_SECS`, never stamped by the
400    /// operator): sleep this long between the garbage collector's HEAD of
401    /// a path and its conditional DELETE, once per barrier. That gap is
402    /// where another writer's lease-free upload can land (the model's
403    /// LeanBarrierLeaseGCUnconditional), and it is two requests long, so
404    /// a drill opens it on purpose. 0 = off.
405    pub drill_hold_gc_secs: u64,
406    /// The protocol event trace (`trace.rs`); `None` = off.
407    pub event_trace: Option<trace::Sink>,
408}
409
410impl LeanConfig {
411    pub fn new(prefix: &str, root: impl Into<PathBuf>) -> Self {
412        LeanConfig {
413            prefix: prefix.trim_end_matches('/').to_string(),
414            root: root.into(),
415            floor_secs: 60,
416            // Off by default: a workspace an agent WORKS IN wants the
417            // S3-wins arm, where an object past its citation is a human
418            // whose bytes should win. Only a published mirror sets it.
419            sole_writer: false,
420            access: Access::ReadWrite,
421            whole_put_max: WHOLE_PUT_MAX,
422            chunked: true,
423            orphan_grace_secs: manifest::ORPHAN_GRACE_SECS,
424            chunk_target: chunk::CHUNK_TARGET,
425            chunk_min: chunk::CHUNK_MIN,
426            chunk_max: chunk::CHUNK_MAX,
427            max_bytes: 0,
428            max_files: 0,
429            window_slack_secs: 180,
430            fanout: 128,
431            upload_fanout: 32,
432            project_id: None,
433            // 128 MiB (was 512): fits the deployed worker's 1Gi limit on a
434            // tree of 1 GiB objects at no cost in wall time (door drill
435            // 2026-09-12 §5, finding 4).
436            fetch_inflight_max_bytes: 128 * 1024 * 1024,
437            fetch_drivers: std::thread::available_parallelism()
438                .map(|n| n.get())
439                .unwrap_or(1)
440                .clamp(1, 8),
441            range_get_min_bytes: 8 * 1024 * 1024,
442            range_get_chunk_bytes: 16 * 1024 * 1024,
443            range_get_parallelism: 4,
444            sentinel_mode: SentinelMode::Auto,
445            sentinel_min_interval_secs: 5,
446            sentinel_hourly_budget: 60,
447            sentinel_poll_secs: 1,
448            claim_poll_secs: lease::CLAIM_POLL_SECS,
449            claim_poll_head_ms: lease::CLAIM_POLL_HEAD_MS,
450            claim_quiet_spacing_secs: lease::QUIET_SPACING_SECS,
451            claim_deadline_secs: lease::CLAIM_DEADLINE_SECS,
452            drill_hold_commit_secs: 0,
453            drill_hold_gc_secs: 0,
454            event_trace: None,
455        }
456    }
457
458    pub fn file_key(&self, path: &str) -> String {
459        format!("{}/files/{}", self.prefix, path)
460    }
461    /// The LEGACY single-object manifest key. Still read (a workspace
462    /// written before the pointer layout has one) and, once migrated,
463    /// overwritten with a document that cannot parse as a manifest —
464    /// see `manifest::REFUSAL_DOC` for why deleting it would be a
465    /// data-loss shape rather than a tidy-up.
466    pub fn manifest_key(&self) -> String {
467        format!("{}/{}/manifest", self.prefix, LEAN_DIR)
468    }
469    /// The pointer: the ONLY mutable metadata object. Small, CAS'd on
470    /// every citation and on every takeover rotation.
471    pub fn current_key(&self) -> String {
472        format!("{}/{}/current", self.prefix, LEAN_DIR)
473    }
474    /// One immutable generation of the entries.
475    ///
476    /// Zero-padded seq FIRST, so a plain lexical listing is also
477    /// chronological — what the reaper and a human with `mc ls` both
478    /// want — and the writer's flush uuid after it, so the key is
479    /// unique per WRITE rather than per generation. Two writers that
480    /// reach the same seq therefore write two different objects and
481    /// race only at the pointer, which is the one place a race should
482    /// be decided; and a path that legitimately rewrites without
483    /// bumping is not refused by a write-once key it never meant to
484    /// collide with.
485    pub fn generation_key(&self, seq: u64, flush_uuid: &str) -> String {
486        format!("{}/{}/manifests/{seq:020}-{flush_uuid}", self.prefix, LEAN_DIR)
487    }
488
489    /// A chunk object, addressed by CONTENT rather than by generation.
490    /// Two generations that share a chunk share the object, which is
491    /// where the O(changed) publish actually comes from — naming chunks
492    /// by seq would rewrite every one of them on every publish even
493    /// when their contents were identical.
494    pub fn chunk_key(&self, addr: &str) -> String {
495        format!("{}/{}/chunks/{addr}", self.prefix, LEAN_DIR)
496    }
497    pub fn inbox_key(&self) -> String {
498        format!("{}/{}/inbox", self.prefix, LEAN_DIR)
499    }
500    pub fn epoch_key(&self) -> String {
501        format!("{}/{}/epoch", self.prefix, LEAN_DIR)
502    }
503    /// The operator's claim cell for this prefix (`lean_operator::
504    /// reconcile::claim_key` writes it; the syncer only READS it).
505    pub fn claim_key(&self) -> String {
506        format!("{}/{}/claim", self.prefix, LEAN_DIR)
507    }
508    pub fn conflict_key(&self, uuid: &str, path: &str) -> String {
509        format!("{}/{}/conflicts/{}/{}", self.prefix, LEAN_DIR, uuid, path)
510    }
511
512    /// A per-user DRAFT: a durable edit that has NOT been published.
513    ///
514    /// Under `LEAN_DIR`, which is the whole safety argument: that
515    /// namespace is never scanned, never checked out, never cited by a
516    /// manifest, and never swept (both sweeps are prefix-scoped —
517    /// `manifest::sweep_generations` to `manifests/`, `sweep_chunks` to
518    /// `chunks/`). So a draft is durable in the bucket while being
519    /// invisible to `classify`, to `checkout`, to every other user, and
520    /// to the agent — which is exactly what "saved but not published"
521    /// has to mean.
522    ///
523    /// Body and meta live under DISJOINT subtrees rather than sharing
524    /// one with a suffix: with `drafts/<u>/<path>.meta` a file legally
525    /// named `notes.meta` would have its BODY at the key that is
526    /// `notes`'s META, and one user's draft would silently read as
527    /// another draft's base etag.
528    pub fn draft_body_key(&self, user: &str, path: &str) -> String {
529        format!("{}/{}/drafts/{}/body/{}", self.prefix, LEAN_DIR, user, path)
530    }
531    /// The draft's base: which version of `files/<path>` it was edited
532    /// against. Written AFTER the body, so the only crash residue is a
533    /// body with no meta — an INCOMPLETE draft, which `promote` refuses
534    /// by name rather than publishing against a base it had to guess.
535    pub fn draft_meta_key(&self, user: &str, path: &str) -> String {
536        format!("{}/{}/drafts/{}/meta/{}", self.prefix, LEAN_DIR, user, path)
537    }
538    /// Listing prefix for one user's draft metas (the resume view).
539    pub fn draft_meta_prefix(&self, user: &str) -> String {
540        format!("{}/{}/drafts/{}/meta/", self.prefix, LEAN_DIR, user)
541    }
542    pub fn state_dir(&self) -> PathBuf {
543        self.root.join(STATE_DIR)
544    }
545    /// The workspace-local control namespace (D0).
546    pub fn control_dir(&self) -> PathBuf {
547        self.root.join(CONTROL_DIR)
548    }
549}
550
551/// Everything a syncer operation needs: store + config + durable state.
552pub struct Syncer {
553    pub store: Arc<dyn ObjectStore>,
554    pub cfg: LeanConfig,
555    pub state: state::SyncerState,
556    /// The lease held for the CURRENT commit section, if any. `None`
557    /// between barriers: the cell arbitrates who installs a manifest and
558    /// nothing else (design 2026-09-13 §4), so a barrier claims after
559    /// its uploads and releases after its baseline rewrite.
560    pub lease: Option<flint_store::EpochLease>,
561    /// Standing conditions already written to `conflicts.jsonl` by THIS
562    /// process, so a condition that persists across every poll tick is
563    /// recorded once rather than per tick. Deliberately in-memory: a
564    /// restart is a new incarnation and should re-record what it finds.
565    pub noted_not_regular: std::collections::BTreeSet<String>,
566}
567
568/// Seconds since the epoch, saturating at 0 on a clock before it.
569pub fn now_unix() -> u64 {
570    std::time::SystemTime::now()
571        .duration_since(std::time::UNIX_EPOCH)
572        .map(|d| d.as_secs())
573        .unwrap_or(0)
574}