Skip to main content

flint_lean/
sentinel.rs

1//! The boundary verbs: `.flint/publish` and `.flint/sync` (plan §2.1,
2//! §2.2 — D1, D2, D3, D3.1, D12).
3//!
4//! The agent touches a file; the syncer consumes it, honors it with a
5//! real barrier (or a real sync), and answers with an ack. The
6//! discipline is `consume_inbox`'s, mirrored — exactly-once via
7//! integrate → persist → drop, idempotent between — with rename in
8//! place of CAS:
9//!
10//! 1. **Consume** — the sentinel is renamed out of the agent's reach
11//!    into the state dir. Type-checked first (`S_ISREG` only: a FIFO
12//!    would block the body read forever), body bounded at 64 KiB.
13//!    **Settle-before-consume:** the poll never consumes while a
14//!    pending record stands — a surviving pending must be honored,
15//!    acked and retired first, or the consume would clobber it and
16//!    orphan its nonces forever. Coalescing happens INSIDE the pending
17//!    record: touches arriving during the min-interval wait append
18//!    their nonces to the standing record.
19//! 2. **Honor** — run one full fused barrier (which claims the publish
20//!    fence for its commit section only) or one sync.
21//! 3. **Ack** — written atomically AFTER the barrier's manifest CAS and
22//!    baseline rewrite, carrying the FULL covered-nonce set: under
23//!    coalescing an agent whose nonce rode behind a later touch would
24//!    otherwise never see it and would re-touch in a loop, feeding the
25//!    storm the rate limit exists to prevent.
26//! 4. **Retire** — the pending record is removed after the ack rename.
27//!
28//! **The uniform crash rule (D2, replacing the draft's per-crash-point
29//! matrix).** Pending-present-and-no-matching-ack is the SAME
30//! observable state for "crashed before the manifest CAS" and "crashed
31//! after step 7" — the baseline is rewritten only at step 7 — so acking
32//! from persisted state would assert publication of writes that never
33//! uploaded. On restart: pending + no matching ack ⇒ ALWAYS run a full
34//! barrier (idempotent; AdoptOwn/recent-uuids covers a half-published
35//! set), then ack with THAT barrier's installed seq. Pending + matching
36//! ack ⇒ retire only; the ack already names a real install.
37//!
38//! **A fence is a retry (design 2026-09-13 §4).** The lease is held per
39//! barrier, so a commit section deposed mid-way abandons THAT barrier:
40//! nothing was installed, the pending record stands, and the next tick
41//! honors it with a fresh claim. There is no refused-fenced ack and no
42//! fenced marker any more — the life-long lease they answered for is
43//! gone.
44
45use std::path::{Path, PathBuf};
46
47use serde::{Deserialize, Serialize};
48
49use super::control::{self, write_atomic};
50use super::state::ConflictRecord;
51use super::{now_unix, LeanError, LeanResult, Syncer};
52
53/// Bound on a sentinel body read. A larger file is truncated and the
54/// remainder ignored — never a wedge.
55const MAX_BODY: u64 = 64 * 1024;
56
57/// Bound on the covered-nonce set carried in one ack (oldest dropped).
58const MAX_NONCES: usize = 32;
59
60/// Bound on a scoped sync's entry list (§2.2 write containment).
61pub const MAX_SCOPE_ENTRIES: usize = 64;
62pub const MAX_SCOPE_ENTRY_LEN: usize = 1024;
63
64const BUDGET: &str = "sentinel-budget.json";
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Verb {
68    Publish,
69    Sync,
70}
71
72impl Verb {
73    pub fn as_str(&self) -> &'static str {
74        match self {
75            Verb::Publish => "publish",
76            Verb::Sync => "sync",
77        }
78    }
79    pub fn sentinel_name(&self) -> &'static str {
80        match self {
81            Verb::Publish => control::PUBLISH,
82            Verb::Sync => control::SYNC,
83        }
84    }
85    fn ack_name(&self) -> &'static str {
86        match self {
87            Verb::Publish => control::PUBLISH_ACK,
88            Verb::Sync => control::SYNC_ACK,
89        }
90    }
91    /// The standing pending record. `pub` because `flint-sync status`
92    /// reports on it and MUST NOT spell it a second time: it did, it
93    /// spelled it wrong ("pending-publish.json"), and the field that
94    /// answers "is my agent blocked on an ack?" therefore answered no
95    /// forever.
96    pub fn pending_name(&self) -> &'static str {
97        match self {
98            Verb::Publish => "publish.pending.json",
99            Verb::Sync => "sync.pending.json",
100        }
101    }
102    /// The consume staging name. A crash between the rename (which
103    /// removes the sentinel) and the pending write would otherwise lose
104    /// the touch: on restart the staging file is recovered into the
105    /// pending record instead.
106    fn staging_name(&self) -> &'static str {
107        match self {
108            Verb::Publish => "publish.consumed",
109            Verb::Sync => "sync.consumed",
110        }
111    }
112}
113
114/// The agent's optional JSON body.
115#[derive(Debug, Clone, Default, Deserialize)]
116struct SentinelBody {
117    #[serde(default)]
118    nonce: Option<String>,
119    #[serde(default)]
120    note: Option<String>,
121    /// `sync` only: path prefixes and exact paths (D4).
122    #[serde(default)]
123    scope: Option<Vec<String>>,
124}
125
126/// A consumed sentinel awaiting honor (`.flint-sync/<verb>.pending.json`).
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct PendingSentinel {
129    pub verb: String,
130    /// The latest covered touch, in nanoseconds — bare-touch agents
131    /// match their boundary on this.
132    pub consumed_mtime_unix_ns: u128,
133    pub consumed_at: u64,
134    /// EVERY coalesced nonce, oldest dropped past `MAX_NONCES`.
135    pub nonces: Vec<String>,
136    #[serde(default)]
137    pub note: Option<String>,
138    #[serde(default)]
139    pub scope: Option<Vec<String>>,
140    /// An unparsable or oversize body was honored as a bare touch — a
141    /// warning conflict record names it. Never a wedge, never a silent
142    /// drop.
143    #[serde(default)]
144    pub torn: bool,
145    /// A coalesced touch asked for the WHOLE tree (no `scope`); later
146    /// scoped touches must not narrow it (review 2026-09-12, inbox-7).
147    #[serde(default)]
148    pub whole_tree: bool,
149    /// Fresh on every fold: each touch declares the tree as it stands
150    /// when it is consumed, so an install that carried an earlier fold of
151    /// this record does not carry this one (`IntentJournal::carrier`).
152    /// Empty on a record written before the field, or torn: then nothing
153    /// matches it and the ack reads the honoring barrier's own report.
154    #[serde(default)]
155    pub id: String,
156}
157
158/// The ack document (`.flint/<verb>.ack`).
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct Ack {
161    /// "ok" | "partial" | "refused-scope" | "refused-read-only".
162    ///
163    /// `partial` is the honest answer when the boundary installed but a
164    /// path the agent declared is not in it (D1) —
165    /// `report.dropped` names them. An agent that treats it as failure
166    /// and re-touches is behaving correctly.
167    pub status: String,
168    pub nonces: Vec<String>,
169    pub sentinel_mtime_unix_ns: u128,
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub seq: Option<u64>,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub manifest_etag: Option<String>,
174    /// "sentinel" | "sentinel-deferred" | "drain" | "recovered".
175    pub boundary: String,
176    pub completed_unix: u64,
177    /// Set on a refusal (`refused-scope`, `refused-read-only`): what was
178    /// wrong with the request, or why it cannot be done here, in words.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub reason: Option<String>,
181    pub report: AckReport,
182}
183
184#[derive(Debug, Clone, Default, Serialize, Deserialize)]
185pub struct AckReport {
186    pub uploaded: usize,
187    pub deleted: usize,
188    pub parked: usize,
189    pub consumed: usize,
190    pub no_change: bool,
191    /// `sync` only: the applied/deleted/conflict transport (§2.2 — the
192    /// conflict report rides the ack in FULL: "never a silent winner"
193    /// must survive the file transport).
194    #[serde(default, skip_serializing_if = "Vec::is_empty")]
195    pub applied: Vec<String>,
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub conflicts: Vec<ConflictRecord>,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub scope: Option<Vec<String>>,
200    /// Foreign changes seen but left owed to the next consume (D4).
201    #[serde(default)]
202    pub out_of_scope_foreign: usize,
203    /// Declared paths the boundary does NOT carry (a standing park, a
204    /// delete another writer's edit outranked, or an upload that
205    /// published nothing).
206    /// Non-empty ⇒ `status: "partial"`: the §2.2 rule — the
207    /// conflict report rides the ack in full, never a silent loser —
208    /// generalized from `sync` to the publish verb.
209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210    pub dropped: Vec<String>,
211}
212
213/// The work meter (D3.1 — the hot-loops no-regression rule).
214///
215/// A counted budget charges a hot 2 GiB checkpoint the same one unit as
216/// a 4 KiB file, so a storming agent could drive `dirty_bytes × 60/hour`
217/// of extra upload while staying inside a green budget — a regression on
218/// the one performance sub-axis lean currently maxes (a tight local
219/// loop's republish is coalesced by cadence; sentinels un-coalesce it on
220/// demand). Metering work instead bounds sentinel-driven published bytes
221/// at `budget × whole_put_max` per hour independent of dirty-set size,
222/// and a workspace at the cap degrades to exactly today's cadence
223/// behavior — the definition of no regression.
224#[derive(Debug, Clone, Default, Serialize, Deserialize)]
225pub struct SentinelBudget {
226    /// (unix, units) charges inside the rolling hour.
227    pub charges: Vec<(u64, u64)>,
228    /// The last sentinel-honoring barrier, for the min-interval.
229    pub last_honor_unix: u64,
230}
231
232impl SentinelBudget {
233    fn prune(&mut self, now: u64) {
234        self.charges.retain(|(at, _)| now.saturating_sub(*at) < 3600);
235    }
236    pub fn spent(&self, now: u64) -> u64 {
237        self.charges
238            .iter()
239            .filter(|(at, _)| now.saturating_sub(*at) < 3600)
240            .map(|(_, u)| *u)
241            .sum()
242    }
243    pub fn remaining(&self, now: u64, budget: u64) -> u64 {
244        budget.saturating_sub(self.spent(now))
245    }
246}
247
248/// Why a standing pending sentinel is not being honored right now.
249/// The records a sync produced, given how many the log held before it.
250///
251/// `skip(before)` alone is only sound while the log GREW. A rotation
252/// during the sync can SHORTEN it, and skipping past a shorter list
253/// reports NO conflicts for a sync that produced some — the one answer
254/// this ack must never give. Over-reporting the survivors is the safe
255/// direction: an ack naming a conflict that predates the sync costs a
256/// reader a second look, an ack naming none costs them the conflict.
257pub(crate) fn conflicts_since(
258    before: usize,
259    after: Vec<ConflictRecord>,
260) -> Vec<ConflictRecord> {
261    if after.len() >= before {
262        after[before..].to_vec()
263    } else {
264        after
265    }
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub enum Due {
270    /// Honor it on this tick.
271    Ready,
272    /// Inside `sentinel_min_interval_secs` of the last honor: wait, and
273    /// let further touches coalesce.
274    MinInterval,
275    /// The hourly budget is exhausted: the boundary is still honored,
276    /// by the next FLOOR tick, and its ack is stamped
277    /// `sentinel-deferred`. Contents are never thinned (D1's corollary)
278    /// — cost is bounded by deferring the barrier, never by publishing
279    /// less than the boundary covers.
280    BudgetDeferred,
281}
282
283fn mtime_ns(m: &std::fs::Metadata) -> u128 {
284    m.modified()
285        .ok()
286        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
287        .map(|d| d.as_nanos())
288        .unwrap_or(0)
289}
290
291/// Read the sentinel body, bounded, and WITHOUT ever blocking on the
292/// open.
293///
294/// The type check in `consume_sentinel` is an `lstat`, and this is a
295/// second path resolution — so on its own the check is a TOCTOU: swap a
296/// FIFO in between and a plain `File::open` blocks forever waiting for a
297/// writer, wedging the poll arm and, behind it, every boundary this
298/// syncer owes (review: U23).
299///
300/// `O_NONBLOCK` closes it at the syscall rather than by winning a race:
301/// opening a writer-less FIFO returns immediately instead of blocking,
302/// and `O_NOFOLLOW` refuses a symlink swapped in for the same purpose.
303/// Both are no-ops on the regular file this is supposed to be reading.
304pub(crate) fn read_bounded(path: &Path) -> std::io::Result<(Vec<u8>, bool)> {
305    use std::io::Read;
306    use std::os::unix::fs::OpenOptionsExt;
307    let f = std::fs::File::options()
308        .read(true)
309        .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
310        .open(path)?;
311    // A FIFO that a writer DOES hold open reads EAGAIN rather than
312    // blocking; treat it as an empty body, which the torn-body rule
313    // already handles as a bare touch.
314    let meta = f.metadata()?;
315    if !meta.is_file() {
316        return Err(std::io::Error::new(
317            std::io::ErrorKind::InvalidInput,
318            "sentinel is not a regular file",
319        ));
320    }
321    let mut buf = Vec::new();
322    let mut take = f.take(MAX_BODY + 1);
323    take.read_to_end(&mut buf)?;
324    let oversize = buf.len() as u64 > MAX_BODY;
325    buf.truncate(MAX_BODY as usize);
326    Ok((buf, oversize))
327}
328
329impl Syncer {
330    fn pending_path(&self, verb: Verb) -> PathBuf {
331        self.cfg.state_dir().join(verb.pending_name())
332    }
333    fn staging_path(&self, verb: Verb) -> PathBuf {
334        self.cfg.state_dir().join(verb.staging_name())
335    }
336    fn budget_path(&self) -> PathBuf {
337        self.cfg.state_dir().join(BUDGET)
338    }
339
340    pub fn load_pending(&self, verb: Verb) -> LeanResult<Option<PendingSentinel>> {
341        let p = self.pending_path(verb);
342        if !p.exists() {
343            return Ok(None);
344        }
345        let bytes = std::fs::read(&p)?;
346        match serde_json::from_slice(&bytes) {
347            Ok(v) => Ok(Some(v)),
348            // Our own record is torn (a crash mid-rewrite): honor it as
349            // a bare touch rather than wedging on it.
350            Err(_) => Ok(Some(PendingSentinel {
351                verb: verb.as_str().into(),
352                consumed_mtime_unix_ns: 0,
353                consumed_at: now_unix(),
354                nonces: vec![],
355                note: None,
356                scope: None,
357                torn: true,
358                whole_tree: false,
359                id: String::new(),
360            })),
361        }
362    }
363
364    fn save_pending(&self, verb: Verb, p: &PendingSentinel) -> LeanResult<()> {
365        let bytes = serde_json::to_vec_pretty(p)
366            .map_err(|e| LeanError::State(format!("pending: {e}")))?;
367        write_atomic(&self.pending_path(verb), &bytes)
368    }
369
370    fn retire_pending(&self, verb: Verb) -> LeanResult<()> {
371        let p = self.pending_path(verb);
372        if p.exists() {
373            std::fs::remove_file(&p)?;
374        }
375        Ok(())
376    }
377
378    pub fn load_budget(&self) -> LeanResult<SentinelBudget> {
379        let p = self.budget_path();
380        if !p.exists() {
381            return Ok(SentinelBudget::default());
382        }
383        let bytes = std::fs::read(&p)?;
384        Ok(serde_json::from_slice(&bytes).unwrap_or_default())
385    }
386
387    fn save_budget(&self, b: &SentinelBudget) -> LeanResult<()> {
388        let bytes =
389            serde_json::to_vec_pretty(b).map_err(|e| LeanError::State(format!("budget: {e}")))?;
390        write_atomic(&self.budget_path(), &bytes)
391    }
392
393    /// D3.1: charge the meter for a completed sentinel honor.
394    /// `published_bytes == 0` (a no-diff honor) costs NOTHING — the
395    /// budget exists to bound work and a no-diff honor does none; the
396    /// min-interval remains its only bound.
397    pub fn charge_budget(&self, published_bytes: u64) -> LeanResult<u64> {
398        let now = now_unix();
399        let mut b = self.load_budget()?;
400        b.prune(now);
401        let units = if published_bytes == 0 {
402            0
403        } else {
404            published_bytes.div_ceil(self.cfg.whole_put_max.max(1)).max(1)
405        };
406        if units > 0 {
407            b.charges.push((now, units));
408        }
409        b.last_honor_unix = now;
410        self.save_budget(&b)?;
411        Ok(units)
412    }
413
414    /// Whether a standing pending sentinel may be honored on this tick.
415    pub fn sentinel_due(&self) -> LeanResult<Due> {
416        let now = now_unix();
417        let b = self.load_budget()?;
418        if b.last_honor_unix > 0
419            && now.saturating_sub(b.last_honor_unix) < self.cfg.sentinel_min_interval_secs
420        {
421            return Ok(Due::MinInterval);
422        }
423        if b.remaining(now, self.cfg.sentinel_hourly_budget) == 0 {
424            return Ok(Due::BudgetDeferred);
425        }
426        Ok(Due::Ready)
427    }
428
429    /// One poll tick: `lstat` exactly two fixed paths — no inotify
430    /// dependency, no directory scan, ~2 lstats/s when idle.
431    ///
432    /// Returns the verbs whose sentinel was consumed (or coalesced) on
433    /// this tick.
434    pub fn poll_sentinels(&mut self) -> LeanResult<Vec<Verb>> {
435        let mut consumed = vec![];
436        for verb in [Verb::Publish, Verb::Sync] {
437            if self.consume_sentinel(verb)? {
438                consumed.push(verb);
439            }
440        }
441        Ok(consumed)
442    }
443
444    /// Recover a consume that crashed between the rename and the
445    /// pending write. Called at startup, before the first poll.
446    pub fn recover_consume_staging(&mut self) -> LeanResult<()> {
447        for verb in [Verb::Publish, Verb::Sync] {
448            let staging = self.staging_path(verb);
449            if staging.exists() {
450                let meta = std::fs::metadata(&staging)?;
451                let (body, oversize) = read_bounded(&staging)?;
452                self.fold_into_pending(verb, mtime_ns(&meta), &body, oversize)?;
453                std::fs::remove_file(&staging)?;
454            }
455        }
456        Ok(())
457    }
458
459    pub(crate) fn consume_sentinel(&mut self, verb: Verb) -> LeanResult<bool> {
460        let path = self.control_path(verb.sentinel_name());
461        let meta = match std::fs::symlink_metadata(&path) {
462            Ok(m) => m,
463            Err(_) => return Ok(false),
464        };
465        // Type check FIRST: a FIFO would block the body read forever;
466        // a directory, socket or symlink at the sentinel path is not a
467        // touch this syncer will act on.
468        if !meta.is_file() {
469            // ONCE per process, not once per poll tick. A FIFO or dir
470            // parked at the sentinel path is a standing condition, and
471            // appending a record every 10 s grows a file that
472            // `load_conflicts` parses WHOLE — twice per sync honor, and
473            // again per status read and per scrape (review: U23). The
474            // condition is worth recording; the repetition is not.
475            let slot = format!("{}/{}", super::CONTROL_DIR, verb.sentinel_name());
476            if self.noted_not_regular.insert(slot.clone()) {
477                self.state.append_conflict(&ConflictRecord {
478                    path: slot,
479                    foreign_etag: String::new(),
480                    preserved_key: None,
481                    kind: "sentinel-not-regular-file".into(),
482                    at_unix: now_unix(),
483                })?;
484            }
485            return Ok(false);
486        }
487        let ns = mtime_ns(&meta);
488        let (body, oversize) = match read_bounded(&path) {
489            Ok(v) => v,
490            Err(_) => (Vec::new(), false),
491        };
492        // The consume act: rename the sentinel out of the agent's reach.
493        // Staging first, pending second — a crash between is recovered
494        // at startup from the staging file, so a touch is never lost
495        // ACROSS A RESTART.
496        //
497        // Scope worth naming (review: U37): recovery runs ONLY at
498        // startup (`settle_pending_at_startup`, called once before the
499        // run loop). A *transient* fold failure mid-run therefore leaves
500        // a consumed touch stranded in the staging file until the
501        // process restarts, and the next consume's rename clobbers it,
502        // orphaning its nonce. Recovering in the poll arm as well would
503        // close it; nothing does today.
504        self.noted_not_regular.remove(&format!("{}/{}", super::CONTROL_DIR, verb.sentinel_name()));
505        let staging = self.staging_path(verb);
506        std::fs::rename(&path, &staging)?;
507        self.fold_into_pending(verb, ns, &body, oversize)?;
508        let _ = std::fs::remove_file(&staging);
509        Ok(true)
510    }
511
512    /// Build or coalesce into the standing pending record.
513    ///
514    /// Settle-before-consume in its positive form: an existing pending
515    /// record is never overwritten. Its nonce set grows, its covered
516    /// mtime advances to the latest touch, and its scope (sync) unions —
517    /// so the honor that eventually runs covers every coalesced touch,
518    /// and every one of their nonces appears in the ack.
519    fn fold_into_pending(
520        &mut self,
521        verb: Verb,
522        ns: u128,
523        body: &[u8],
524        oversize: bool,
525    ) -> LeanResult<()> {
526        let trimmed = body.iter().all(|b| b.is_ascii_whitespace());
527        let (parsed, torn) = if trimmed {
528            (SentinelBody::default(), false) // bare touch
529        } else if oversize {
530            (SentinelBody::default(), true)
531        } else {
532            match serde_json::from_slice::<SentinelBody>(body) {
533                Ok(v) => (v, false),
534                Err(_) => (SentinelBody::default(), true),
535            }
536        };
537        if torn {
538            self.state.append_conflict(&ConflictRecord {
539                path: format!("{}/{}", super::CONTROL_DIR, verb.sentinel_name()),
540                foreign_etag: String::new(),
541                preserved_key: None,
542                kind: "sentinel-torn-body".into(),
543                at_unix: now_unix(),
544            })?;
545        }
546        let mut pending = self.load_pending(verb)?.unwrap_or(PendingSentinel {
547            verb: verb.as_str().into(),
548            consumed_mtime_unix_ns: 0,
549            consumed_at: now_unix(),
550            nonces: vec![],
551            note: None,
552            scope: None,
553            torn: false,
554            whole_tree: false,
555            id: String::new(),
556        });
557        pending.id = uuid::Uuid::new_v4().to_string();
558        pending.consumed_mtime_unix_ns = pending.consumed_mtime_unix_ns.max(ns);
559        pending.consumed_at = now_unix();
560        pending.torn |= torn;
561        if let Some(n) = parsed.nonce {
562            let n: String = n.chars().take(128).collect();
563            if !pending.nonces.contains(&n) {
564                pending.nonces.push(n);
565            }
566            let excess = pending.nonces.len().saturating_sub(MAX_NONCES);
567            if excess > 0 {
568                pending.nonces.drain(..excess);
569            }
570        }
571        if let Some(note) = parsed.note {
572            pending.note = Some(note.chars().take(4096).collect());
573        }
574        // Scope folding (review 2026-09-12, inbox-7 / inbox-10): an
575        // UNSCOPED sync touch means the whole tree and outranks every
576        // scoped one it coalesces with, in either order — the whole-tree
577        // agent matches its nonce on this ack and must get what it asked
578        // for. Scoped touches union, and the union is NOT truncated
579        // here: an oversize or all-invalid scope is answered at the
580        // honor as `refused-scope`, never silently narrowed.
581        match parsed.scope {
582            None if matches!(verb, Verb::Sync) => {
583                pending.scope = None;
584                pending.whole_tree = true;
585            }
586            Some(scope) if !pending.whole_tree => {
587                let mut merged = pending.scope.take().unwrap_or_default();
588                for e in scope {
589                    if e.len() > MAX_SCOPE_ENTRY_LEN {
590                        continue;
591                    }
592                    if !merged.contains(&e) {
593                        merged.push(e);
594                    }
595                }
596                pending.scope = Some(merged);
597            }
598            _ => {}
599        }
600        self.save_pending(verb, &pending)?;
601        Ok(())
602    }
603
604    /// A boundary asked for through a door that is NOT the file
605    /// protocol — the gateway's inbox field (§2.5) or the UDS socket.
606    ///
607    /// It folds into the same pending record a `.flint/publish` touch
608    /// would, which is the whole design of the layered doors: the extra
609    /// doors are sugar over one consume path, so min-interval,
610    /// coalescing, the work-metered budget, the covered-nonce ack and
611    /// the crash rules apply to them without a second implementation
612    /// that could disagree with the first.
613    pub fn request_boundary(&mut self, nonce: &str, note: Option<String>) -> LeanResult<()> {
614        let body = serde_json::json!({ "nonce": nonce, "note": note });
615        let ns = std::time::SystemTime::now()
616            .duration_since(std::time::UNIX_EPOCH)
617            .map(|d| d.as_nanos())
618            .unwrap_or(0);
619        self.fold_into_pending(Verb::Publish, ns, body.to_string().as_bytes(), false)
620    }
621
622    fn ack_path(&self, verb: Verb) -> PathBuf {
623        self.control_path(verb.ack_name())
624    }
625
626    pub fn read_ack(&self, verb: Verb) -> Option<Ack> {
627        let bytes = std::fs::read(self.ack_path(verb)).ok()?;
628        serde_json::from_slice(&bytes).ok()
629    }
630
631    fn write_ack(&self, verb: Verb, ack: &Ack) -> LeanResult<()> {
632        let bytes =
633            serde_json::to_vec_pretty(ack).map_err(|e| LeanError::State(format!("ack: {e}")))?;
634        write_atomic(&self.ack_path(verb), &bytes)?;
635        self.trace("ack", serde_json::json!({"verb": format!("{verb:?}"), "nonces": ack.nonces, "status": ack.status,
636            "seq": ack.seq, "dropped": ack.report.dropped, "boundary": ack.boundary}));
637        Ok(())
638    }
639
640    /// Does a standing ack already answer this pending record? Used by
641    /// the restart rule: matching ⇒ retire only (the ack names a real
642    /// install); not matching ⇒ run a full barrier and ack from THAT.
643    pub(crate) fn ack_matches(&self, verb: Verb, pending: &PendingSentinel) -> bool {
644        let Some(ack) = self.read_ack(verb) else { return false };
645        // Compare values the SYNCER minted (review: U22). The ack is an
646        // ordinary file in `.flint/`, writable by every process sharing
647        // the mount, and `sentinel_mtime_unix_ns` is the agent's own
648        // file mtime — which is not monotone even without an adversary:
649        // `touch -t`, a clock step, a restored file and a tar extract
650        // all move it backwards. Deciding "has this boundary already
651        // run?" from it lets a STALE ack retire a FRESH request, and
652        // the request is then retired having never run.
653        //
654        // `consumed_at` and `completed_unix` are both minted here, in
655        // that order, so their ordering answers the question the mtime
656        // was being asked.
657        if ack.completed_unix < pending.consumed_at {
658            return false;
659        }
660        if ack.sentinel_mtime_unix_ns < pending.consumed_mtime_unix_ns {
661            return false;
662        }
663        // A bare touch carries no nonce, so `all()` over an empty set is
664        // vacuously TRUE and the timestamps become the entire test.
665        // Require the ack to name this exact touch instead.
666        if pending.nonces.is_empty() {
667            return ack.sentinel_mtime_unix_ns == pending.consumed_mtime_unix_ns;
668        }
669        pending.nonces.iter().all(|n| ack.nonces.contains(n))
670    }
671
672    /// Honor a standing pending sentinel, if one stands and is due.
673    ///
674    /// `forced` = this is a floor tick picking up a budget-deferred
675    /// boundary; the ack is stamped `sentinel-deferred`. `Ok(None)`
676    /// means nothing was owed (or it is not due yet).
677    pub async fn honor_pending(&mut self, verb: Verb, forced: bool) -> LeanResult<Option<Ack>> {
678        self.honor_pending_as(verb, forced, None).await
679    }
680
681    /// `honor_pending` under an explicit provenance stamp. The drain
682    /// needs it: it rewrites the ack to `drain`, and a manifest still
683    /// stamped `sentinel-deferred` would have the bucket and the ack
684    /// naming two different clocks for one boundary.
685    pub async fn honor_pending_as(
686        &mut self,
687        verb: Verb,
688        forced: bool,
689        source: Option<&str>,
690    ) -> LeanResult<Option<Ack>> {
691        let Some(pending) = self.load_pending(verb)? else { return Ok(None) };
692        if !forced {
693            match self.sentinel_due()? {
694                Due::Ready => {}
695                // Not honored on this tick; the floor tick will (D3).
696                Due::MinInterval | Due::BudgetDeferred => return Ok(None),
697            }
698        }
699        // The restart rule: a matching ack already names a real
700        // install — retire, never re-run.
701        if self.ack_matches(verb, &pending) {
702            self.retire_pending(verb)?;
703            return Ok(None);
704        }
705
706        let ack = match verb {
707            Verb::Publish => self.honor_publish(&pending, forced, source).await,
708            Verb::Sync => self.honor_sync(&pending, forced).await,
709        };
710        match ack {
711            Ok(ack) => {
712                self.write_ack(verb, &ack)?;
713                self.retire_pending(verb)?;
714                Ok(Some(ack))
715            }
716            Err(e) => Err(e),
717        }
718    }
719
720    async fn honor_publish(
721        &mut self,
722        pending: &PendingSentinel,
723        forced: bool,
724        source: Option<&str>,
725    ) -> LeanResult<Ack> {
726        // A reader answers — "nothing is silent" — and publishes nothing.
727        // No budget charge: nothing was published, and a refusal must
728        // not hold back the next sync behind the min-interval.
729        if self.cfg.access.is_read() {
730            return Ok(Ack {
731                status: "refused-read-only".into(),
732                nonces: pending.nonces.clone(),
733                sentinel_mtime_unix_ns: pending.consumed_mtime_unix_ns,
734                seq: None,
735                manifest_etag: None,
736                boundary: if forced { "sentinel-deferred".into() } else { "sentinel".into() },
737                completed_unix: now_unix(),
738                reason: Some(
739                    "this pod has read-only access to the workspace (capabilities `access: read`): \
740                     nothing in its tree is published. `sync` still integrates the bucket's latest \
741                     boundary"
742                        .into(),
743                ),
744                report: AckReport::default(),
745            });
746        }
747        // The DECLARED form (D1): a delete the agent made before the
748        // touch is part of the coherent point it declared, so this
749        // barrier confirms first-absence paths instead of acking a
750        // boundary that withholds them to the next floor tick.
751        // The ack and the manifest must agree on which clock published:
752        // a budget-deferred boundary reads `sentinel-deferred` in both.
753        let before = self.state.load_conflicts()?.len();
754        let report = self
755            .declared_barrier_as(
756                source.unwrap_or(if forced { "sentinel-deferred" } else { "sentinel" }),
757            )
758            .await?;
759        // Review 2026-09-12, ack-3: the boundary's own records (a
760        // `consume-dirty` the agent won, a refused removal) ride the
761        // publish ack as they ride the sync ack — AGENTS.md says so.
762        let conflicts = conflicts_since(before, self.state.load_conflicts()?);
763        let units = self.charge_budget(report.published_bytes)?;
764        let _ = units;
765        let baseline = self.state.load_baseline()?;
766        // Review 2026-09-12, inbox-1: a boundary with a standing park does
767        // NOT carry the agent's file — `ok` promised "the boundary is in
768        // the bucket". It is `partial`, and `report.dropped` names the
769        // paths, as it does an upload that published nothing (a transfer
770        // that drifted or was swept).
771        let dropped: Vec<String> =
772            report.parked.iter().chain(&report.deferred).cloned().collect();
773        // Review 2026-09-18, H10: the installs that CARRIED this declaration
774        // are journalled with their CAS, and are not always this barrier —
775        // a restart past step 7, an ack write that failed, or an honor that
776        // failed before the floor's cadence barrier published the
777        // declaration, each leave the ack to a later barrier. When a peer
778        // deleted a declared path in between, the document that barrier
779        // ended at does not cite it — the tree may still hold the declared
780        // bytes — and `ok` said it was there. Each barrier records which
781        // carried uploads its document does not cite (`Carrier::uncited`).
782        let mut dropped = dropped;
783        let carrier = self
784            .state
785            .load_intent()?
786            .carrier
787            .filter(|c| !pending.id.is_empty() && c.pending_id == pending.id);
788        if let Some(c) = carrier {
789            for p in c.dropped.iter().chain(c.uncited.iter()) {
790                if !dropped.contains(p) {
791                    dropped.push(p.clone());
792                }
793            }
794        }
795        Ok(Ack {
796            status: if dropped.is_empty() { "ok".into() } else { "partial".into() },
797            nonces: pending.nonces.clone(),
798            sentinel_mtime_unix_ns: pending.consumed_mtime_unix_ns,
799            seq: report.seq,
800            manifest_etag: baseline.manifest_etag.clone(),
801            boundary: if forced { "sentinel-deferred".into() } else { "sentinel".into() },
802            completed_unix: now_unix(),
803        reason: None,
804            report: AckReport {
805                uploaded: report.uploaded.len(),
806                deleted: report.deleted.len(),
807                parked: report.parked.len(),
808                consumed: report.consumed,
809                no_change: report.no_change,
810                conflicts,
811                dropped,
812                ..Default::default()
813            },
814        })
815    }
816
817    async fn honor_sync(&mut self, pending: &PendingSentinel, forced: bool) -> LeanResult<Ack> {
818        if let Some(reason) = Self::scope_refusal(&pending.scope) {
819            // Review 2026-09-12, ack-1 / inbox-3: the refusal used to be
820            // an ERROR the loop retried every tick — never acked, never
821            // retired, and returned ahead of the publish honor and the
822            // cadence barrier, so one `{"scope":[]}` stopped every
823            // boundary for the life of the workspace. An invalid request
824            // is the agent's to fix: answered, retired, and nothing else
825            // waits on it.
826            return Ok(Ack {
827                status: "refused-scope".into(),
828                nonces: pending.nonces.clone(),
829                sentinel_mtime_unix_ns: pending.consumed_mtime_unix_ns,
830                seq: None,
831                manifest_etag: None,
832                boundary: if forced { "sentinel-deferred".into() } else { "sentinel".into() },
833                completed_unix: now_unix(),
834                    reason: Some(reason),
835                report: AckReport { scope: pending.scope.clone(), ..Default::default() },
836            });
837        }
838        let before = self.state.load_conflicts()?.len();
839        let report = self.sync_scoped(pending.scope.clone()).await?;
840        let conflicts = conflicts_since(before, self.state.load_conflicts()?);
841        // A sync publishes no bytes: it costs no budget units, only the
842        // min-interval (which it shares with publish).
843        self.charge_budget(0)?;
844        Ok(Ack {
845            status: "ok".into(),
846            nonces: pending.nonces.clone(),
847            sentinel_mtime_unix_ns: pending.consumed_mtime_unix_ns,
848            seq: Some(report.seq),
849            manifest_etag: None,
850            boundary: if forced { "sentinel-deferred".into() } else { "sentinel".into() },
851            completed_unix: now_unix(),
852        reason: None,
853            report: AckReport {
854                consumed: report.applied.len(),
855                deleted: report.deleted.len(),
856                applied: report.applied.clone(),
857                conflicts,
858                scope: pending.scope.clone(),
859                out_of_scope_foreign: report.out_of_scope_foreign,
860                ..Default::default()
861            },
862        })
863    }
864
865    /// Review 2026-09-12, ack-1: an invalid sync scope is the AGENT's
866    /// error and is answered as one (`refused-scope`), never retried.
867    /// `None` = the scope is acceptable (or absent: the whole tree).
868    fn scope_refusal(scope: &Option<Vec<String>>) -> Option<String> {
869        let raw = scope.as_ref()?;
870        if raw.len() > MAX_SCOPE_ENTRIES {
871            return Some(format!(
872                "scope names {} entries; at most {MAX_SCOPE_ENTRIES} are allowed per sync",
873                raw.len()
874            ));
875        }
876        if super::sync::Scope::new(raw).is_empty() {
877            return Some(format!(
878                "scope names {} entr{} and none is valid: each must be a relative path inside the \
879                 workspace with no `.` or `..` component (an empty scope is refused, not widened \
880                 to the whole tree)",
881                raw.len(),
882                if raw.len() == 1 { "y" } else { "ies" }
883            ));
884        }
885        None
886    }
887
888    /// The startup settle (the uniform crash rule). Runs before the
889    /// first poll arms: a surviving pending must be honored, acked and
890    /// retired before any fresh sentinel may be consumed.
891    pub async fn settle_pending_at_startup(&mut self) -> LeanResult<()> {
892        self.recover_consume_staging()?;
893        for verb in [Verb::Publish, Verb::Sync] {
894            let Some(pending) = self.load_pending(verb)? else { continue };
895            if self.ack_matches(verb, &pending) {
896                // Crashed after the ack, before the retire.
897                self.retire_pending(verb)?;
898                continue;
899            }
900            // Pending + no matching ack is the same observable state
901            // for crash-before-CAS and crash-after-step-7: run a full
902            // barrier and ack from ITS install, never from persisted
903            // state.
904            self.honor_pending(verb, true).await?;
905        }
906        Ok(())
907    }
908}
909
910/// What a floor tick did.
911#[derive(Debug, Default)]
912pub struct FloorOutcome {
913    pub seq: Option<u64>,
914    pub no_change: bool,
915    /// Acks written because a budget-deferred (or min-interval-held)
916    /// pending sentinel was picked up by this floor tick.
917    pub acks: Vec<Ack>,
918    pub uploaded: usize,
919    pub deleted: usize,
920    pub consumed: usize,
921    /// Why visibility is withheld right now, straight off the gauges —
922    /// so the per-tick stderr line is greppable and structured, which
923    /// until Phase 6 is the ONLY signal surface an operator has.
924    pub withheld_reason: Option<String>,
925    /// A foreign 412 parked at least one path on this tick.
926    pub parked: usize,
927    /// Carried out of the barrier only to feed the news ticker.
928    observed_etag: Option<String>,
929}
930
931impl Syncer {
932    /// Move the news ticker from what the barrier already learned (D5).
933    /// Never issues a request of its own.
934    fn ticker_from(&self, seq: Option<u64>, etag: Option<String>) -> LeanResult<()> {
935        let baseline_seq = self.state.load_baseline()?.seq;
936        // A merge that carried another writer's change into the manifest
937        // moves the baseline's seq to that document while the tree is still
938        // OWED the change until the next consume derives against it. Until
939        // then the tree is integrated only through what the ticker said
940        // while nothing was owed: waiting = the document named is not the
941        // one last derived against. (A path the agent is working on is its
942        // own, not waited on.)
943        let b = self.state.load_baseline()?;
944        let same = |a: &str, b: &str| a.trim_matches('"') == b.trim_matches('"');
945        let waiting = match (etag.as_deref(), b.derived_etag.as_deref()) {
946            (Some(e), Some(d)) => !same(e, d),
947            (Some(_), None) => true,
948            (None, _) => false,
949        };
950        let integrated = if waiting {
951            baseline_seq.min(self.load_remote_seq().integrated_seq)
952        } else {
953            baseline_seq
954        };
955        self.touch_remote_seq(seq, etag, integrated)
956    }
957
958    /// One poll tick of the sentinel arm: consume what is there, then
959    /// honor if the min-interval and the work budget allow.
960    ///
961    /// In `cadence` mode the arm still consumes and honors — a sentinel
962    /// triggers a fused barrier there too; the mode's meaning is that
963    /// there is no separate citation lane, not that the verbs are dead.
964    pub async fn sentinel_tick(&mut self) -> LeanResult<Vec<Ack>> {
965        let posture = self.load_posture()?;
966        if posture.as_ref().map(|p| !p.enabled).unwrap_or(false) {
967            return Ok(vec![]);
968        }
969        self.poll_sentinels()?;
970        let mut acks = vec![];
971        // Sync before publish: a coalesced pair means "pull, then
972        // publish my coherent point" — the other order would publish
973        // against a tree the agent expected to have refreshed.
974        for verb in [Verb::Sync, Verb::Publish] {
975            match self.honor_pending(verb, false).await {
976                Ok(Some(a)) => acks.push(a),
977                Ok(None) => {}
978                Err(e) => {
979                    // Review 2026-09-12, ack-1: a non-fence honor error is
980                    // THIS verb's problem. Returning here left the other
981                    // verb unhonoured for as long as the error recurred —
982                    // for a deterministic one, forever. The pending stands
983                    // and is retried; the tick goes on.
984                    eprintln!("flint-sync: {verb:?} honor failed (pending kept, retrying): {e}");
985                }
986            }
987        }
988        if !acks.is_empty() {
989            let last = acks.last().and_then(|a| a.seq);
990            self.ticker_from(last, None)?;
991        }
992        Ok(acks)
993    }
994
995    /// One floor tick: either honor a standing
996    /// pending sentinel that the budget or min-interval held back — the
997    /// boundary is honored by a REAL barrier, its ack stamped
998    /// `sentinel-deferred` — or run the ordinary cadence barrier.
999    ///
1000    /// This is the arm B16 regresses on: the interval rewrite must not
1001    /// let the poll arm starve cadence.
1002    pub async fn floor_tick(&mut self) -> LeanResult<FloorOutcome> {
1003        let mut out = FloorOutcome::default();
1004        // A held-back sync pending is settled first, for the same
1005        // reason as in the poll arm.
1006        //
1007        // Only a PUBLISH honor discharges the floor's own barrier: a
1008        // sync ack carries a seq (the manifest it synced against) but
1009        // publishes nothing, so treating it as "the floor ran" would
1010        // skip cadence for a tick — a silent RPO regression.
1011        let mut published = false;
1012        for verb in [Verb::Sync, Verb::Publish] {
1013            if self.load_pending(verb)?.is_some() {
1014                match self.honor_pending(verb, true).await {
1015                    Ok(Some(a)) => {
1016                        out.seq = a.seq.or(out.seq);
1017                        if verb == Verb::Publish && a.status == "ok" {
1018                            published = true;
1019                            out.uploaded = a.report.uploaded;
1020                            out.deleted = a.report.deleted;
1021                            out.consumed = a.report.consumed;
1022                            out.no_change = a.report.no_change;
1023                        }
1024                        out.acks.push(a);
1025                    }
1026                    Ok(None) => {}
1027                    Err(e) => {
1028                        // Review 2026-09-12, ack-1: same rule as the poll
1029                        // arm, and here the stake is the cadence barrier
1030                        // below, which used to go unrun behind the error.
1031                        eprintln!("flint-sync: {verb:?} honor failed on the floor (pending kept): {e}");
1032                    }
1033                }
1034            }
1035        }
1036        // A reader's floor is its pull (`reader.rs`): no barrier, ever.
1037        if self.cfg.access.is_read() {
1038            return match self.reader_pull().await {
1039                Ok(p) => {
1040                    let _ = self.clear_auth_pause();
1041                    match &p.sync {
1042                        Some(r) => {
1043                            out.seq = Some(r.seq);
1044                            out.consumed = r.applied.len();
1045                            out.deleted = r.deleted.len();
1046                        }
1047                        None => {
1048                            out.no_change = true;
1049                            out.seq = Some(self.state.load_baseline()?.seq);
1050                        }
1051                    }
1052                    self.ticker_from(p.observed_seq, p.observed_etag)?;
1053                    out.withheld_reason = self.write_gauges(None)?.withheld_reason;
1054                    Ok(out)
1055                }
1056                Err(e) => {
1057                    if e.is_auth() {
1058                        let _ = self.note_auth_pause();
1059                    }
1060                    Err(e)
1061                }
1062            };
1063        }
1064        // Finding 10's sweep (`untracked.rs`), when due: before this tick's
1065        // barrier, so the barrier consumes what it tracks.
1066        self.sweep_untracked_if_due(now_unix()).await;
1067        // A publish sentinel honored on this tick already ran the fused
1068        // barrier the floor owed; running a second one would be pure
1069        // churn.
1070        if !published {
1071            let ran = self.cadence_barrier().await.map(|r| {
1072                out.seq = r.seq;
1073                out.no_change = r.no_change;
1074                out.uploaded = r.uploaded.len();
1075                out.deleted = r.deleted.len();
1076                out.consumed = r.consumed;
1077                out.parked = r.parked.len();
1078                out.observed_etag = r.observed_etag.clone();
1079                r.observed_seq
1080            });
1081            match ran {
1082                Ok(observed) => {
1083                    // The floor tick is the one scheduled request every
1084                    // writer makes, idle or not, so it is where a
1085                    // credential pause is seen to END — and, below, to
1086                    // begin. A claim sees both too, but an idle writer
1087                    // never claims. Best-effort: a gauge that failed to
1088                    // write must not fail a tick that succeeded.
1089                    let _ = self.clear_auth_pause();
1090                    let etag = out.observed_etag.take();
1091                    self.ticker_from(observed, etag)?;
1092                    // A foreign 412 outranks "waiting for a boundary":
1093                    // those paths are not ours to publish at all, and
1094                    // saying "quiesce-pending" would send an operator
1095                    // looking for a clock instead of a conflict record.
1096                    let forced = (out.parked > 0).then_some(super::gauges::Withheld::Parked412);
1097                    out.withheld_reason = self.write_gauges(forced)?.withheld_reason;
1098                    return Ok(out);
1099                }
1100                Err(e) => {
1101                    if e.is_auth() {
1102                        let _ = self.note_auth_pause();
1103                    }
1104                    return Err(e);
1105                }
1106            }
1107        }
1108        self.ticker_from(out.seq, None)?;
1109        out.withheld_reason = self.write_gauges(None)?.withheld_reason;
1110        Ok(out)
1111    }
1112
1113    /// The preStop drain (D10 rule 1): settle every owed ack BEFORE the
1114    /// lease release. A pending sentinel at SIGTERM is answered by the
1115    /// drain itself — the container-restart case, where the emptyDir and
1116    /// the agent both survive, must not strand a waiting agent.
1117    pub async fn drain(&mut self) -> LeanResult<Vec<Ack>> {
1118        let mut acks = vec![];
1119        // Only an ok PUBLISH ack means a boundary already ran. A sync
1120        // ack carries a seq too — the manifest it synced AGAINST — while
1121        // publishing nothing, so asking "did any ack carry a seq?" lets
1122        // a pending `.flint/sync` at SIGTERM cancel the drain's own
1123        // cite-everything pass and forfeit every byte since the last
1124        // boundary. The floor arm's `sync_ack_is_not_a_floor` comment
1125        // names this exact trap; the drain repeated it.
1126        let mut published = false;
1127        for verb in [Verb::Sync, Verb::Publish] {
1128            let is_publish = matches!(verb, Verb::Publish);
1129            if self.load_pending(verb)?.is_some() {
1130                match self.honor_pending_as(verb, true, Some("drain")).await {
1131                    Ok(Some(mut a)) => {
1132                        a.boundary = "drain".into();
1133                        // Re-write with the drain stamp so the agent can
1134                        // tell a drained boundary from a live one.
1135                        let bytes = serde_json::to_vec_pretty(&a)
1136                            .map_err(|e| LeanError::State(format!("ack: {e}")))?;
1137                        write_atomic(&self.ack_path(verb), &bytes)?;
1138                        published |= is_publish && a.status == "ok";
1139                        acks.push(a);
1140                    }
1141                    Ok(None) => {}
1142                    Err(e) => return Err(e),
1143                }
1144            }
1145        }
1146        // A reader has nothing to drain: what its tree holds is either in
1147        // the bucket already or, by its access, never going there.
1148        if !published && !self.cfg.access.is_read() {
1149            // D10: the drain publishes EVERYTHING it can, as one declared barrier.
1150                let r = self.declared_barrier_as("drain").await?;
1151                self.ticker_from(r.observed_seq, r.observed_etag.clone())?;
1152                // Review 2026-09-12, inbox-1: a drain that leaves a path
1153                // parked has not published the tree; attesting it let the
1154                // node remove the agent's only copy. So is one whose upload
1155                // published nothing, and one whose delete another writer's
1156                // edit outranked: the retry publishes both.
1157                if !r.parked.is_empty() {
1158                    return Err(LeanError::State(format!(
1159                        "drain: {} path(s) could not be published (parked on a foreign version whose \
1160                         preserve failed): {:?} — not attesting",
1161                        r.parked.len(),
1162                        r.parked
1163                    )));
1164                }
1165                if !r.deferred.is_empty() {
1166                    return Err(LeanError::State(format!(
1167                        "drain: not in this boundary — uploads that published nothing {:?} — not \
1168                         attesting",
1169                        r.deferred
1170                    )));
1171                }
1172        }
1173        Ok(acks)
1174    }
1175}