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