flint_lean/control.rs
1//! The `.flint/` control namespace (boundary-verbs plan §2.0, D0/D11):
2//! the agent's side of the file protocol.
3//!
4//! The app container ships UNCHANGED — no HTTP client, no CLI binary,
5//! no library can be assumed in its image. The only interface every
6//! agent is guaranteed to have is the shared workspace mount, so the
7//! boundary verbs are *files*. This module owns everything the syncer
8//! writes there:
9//!
10//! - `capabilities.json` — the marker an agent MUST check before
11//! touching a sentinel. Absence ⇒ an old syncer ⇒ sentinels are live
12//! ammunition (they would be scanned and published, §2.0).
13//! - `remote.seq` — the news ticker (D5), fed from information the
14//! barrier already has: zero added bucket requests.
15//! - the pre-existing-`.flint/` pre-flight (D0.4), which disables
16//! sentinel consumption for a workspace that was already using the
17//! namespace as data.
18//!
19//! **Trust statement (plan §1.2):** every file here is writable by
20//! every process sharing the mount. Acks are advisory coordination
21//! signals, NOT attestations — an in-pod process can forge one. The
22//! authoritative durability signal is a remote read the pod cannot
23//! forge (gateway `GET /status`, or the manifest itself).
24
25use std::path::{Path, PathBuf};
26
27use serde::{Deserialize, Serialize};
28
29use super::{now_unix, LeanResult, Syncer, SENTINEL_PROTOCOL};
30
31pub const CAPABILITIES: &str = "capabilities.json";
32/// `.flint/AGENTS.md` — the workspace contract, written beside the
33/// marker so an agent reads the protocol of the syncer it is talking to
34/// (an old syncer writes neither; a fenced one still says so in the
35/// marker). The text is the crate's `AGENTS.md`; the test
36/// `agent_guide_names_every_advertised_verb` keeps the two from drifting.
37pub const AGENT_GUIDE: &str = "AGENTS.md";
38pub const AGENT_GUIDE_TEXT: &str = include_str!("../AGENTS.md");
39pub const REMOTE_SEQ: &str = "remote.seq";
40pub const PUBLISH: &str = "publish";
41pub const PUBLISH_ACK: &str = "publish.ack";
42pub const SYNC: &str = "sync";
43pub const SYNC_ACK: &str = "sync.ack";
44
45/// State-dir file recording the sticky pre-flight verdict. Sticky
46/// matters: the marker's own absence is one of the pre-flight's inputs,
47/// so a second startup would otherwise see the marker it just wrote and
48/// silently re-enable the verbs it disabled.
49const POSTURE: &str = "sentinels.json";
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct BootStamp {
53 pub holder_id: String,
54 pub boot_unix: u64,
55}
56
57/// `.flint/capabilities.json` (D11). Written atomically at EVERY `run`
58/// startup — after claim succeeds, before the first poll — and again
59/// during first checkout, so it exists the instant the agent may start.
60///
61/// The startup write is load-bearing on the live-tree restart row:
62/// `checkout()` returns at `marker_present()` without materializing
63/// anything, so pinning the marker write inside checkout would upgrade
64/// a fleet whose live workspaces never get it — sentinels dead on
65/// exactly the pods the upgrade targeted.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct Capabilities {
68 pub protocol: u32,
69 pub verbs: Vec<String>,
70 /// Always `"live"`. It used to read `"fenced"` for a syncer deposed
71 /// from a life-long lease; the lease is now held per barrier
72 /// (design 2026-09-13 §4), a lost commit section is retried at the
73 /// next floor, and there is no terminal state left to report. Kept
74 /// so the marker's schema is stable for an agent that reads it.
75 pub state: String,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub reason: Option<String>,
78 pub sentinel_min_interval_secs: u64,
79 pub sentinel_hourly_budget: u64,
80 pub syncer_version: String,
81 /// The rollback tell (D11): an agent that observes a syncer
82 /// restart while this stamp is UNCHANGED is looking at a stale
83 /// marker left by a downgrade — the safety catch painted green.
84 pub boot: BootStamp,
85}
86
87/// `.flint/remote.seq` — the news ticker (D5).
88///
89/// `observed_seq > integrated_seq` means "there is news you have not
90/// integrated — consider dropping a `.flint/sync` at your next safe
91/// point". The agent polls one LOCAL file: no network, no client, no
92/// credentials, and N agents cost zero bucket requests rather than
93/// N×HEAD.
94#[derive(Debug, Clone, Default, Serialize, Deserialize)]
95pub struct RemoteSeq {
96 pub observed_seq: u64,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 pub observed_etag: Option<String>,
99 pub integrated_seq: u64,
100 /// Refreshed on EVERY successful HEAD tick — a local rename, zero
101 /// bucket cost. Without the heartbeat an agent cannot distinguish
102 /// "no news" from "syncer dead" on an idle-but-healthy workspace.
103 /// Contract: older than 3×floor ⇒ syncer or proxy problem.
104 pub updated_unix: u64,
105 /// Advisory news from the gateway (D14): a HITL/CI party asked this
106 /// workspace to pull. The syncer performs NO tree mutation on
107 /// receipt — it moves the ticker and stops.
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub sync_requested_unix: Option<u64>,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 pub sync_requested_by: Option<String>,
112 /// `integrated_seq` at the moment the request was carried. Once the
113 /// workspace integrates past it the request is stale and clears
114 /// itself — the agent pulled, whether or not it did so on account
115 /// of the request.
116 #[serde(skip_serializing_if = "Option::is_none")]
117 pub sync_requested_at_seq: Option<u64>,
118}
119
120/// The sticky pre-flight verdict (D0.4).
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct SentinelPosture {
123 pub enabled: bool,
124 /// Fleet-visible reason, mirrored into `capabilities.json` and the
125 /// `SentinelVerbsActive` condition.
126 #[serde(skip_serializing_if = "Option::is_none")]
127 pub reason: Option<String>,
128}
129
130pub fn write_atomic(path: &Path, bytes: &[u8]) -> LeanResult<()> {
131 // `.flint/` is app-writable by construction — the agent drops its
132 // sentinels there — so both the parent and the temp name are
133 // attacker-reachable, and `remote.seq` is rewritten every tick.
134 super::safefs::check_parent(path)?;
135 if let Some(parent) = path.parent() {
136 std::fs::create_dir_all(parent)?;
137 }
138 let tmp = path.with_file_name(format!(
139 "{}.tmp",
140 path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()
141 ));
142 super::safefs::write_via_tmp(path, &tmp, bytes, None).map(|_| ())
143}
144
145fn write_json<T: Serialize>(path: &Path, v: &T) -> LeanResult<()> {
146 let bytes = serde_json::to_vec_pretty(v)
147 .map_err(|e| super::LeanError::State(format!("{}: {e}", path.display())))?;
148 write_atomic(path, &bytes)
149}
150
151impl Syncer {
152 pub fn control_path(&self, name: &str) -> PathBuf {
153 self.cfg.control_dir().join(name)
154 }
155
156 fn posture_path(&self) -> PathBuf {
157 self.cfg.state_dir().join(POSTURE)
158 }
159
160 pub fn load_posture(&self) -> LeanResult<Option<SentinelPosture>> {
161 let p = self.posture_path();
162 if !p.exists() {
163 return Ok(None);
164 }
165 let bytes = std::fs::read(&p)?;
166 serde_json::from_slice(&bytes)
167 .map(Some)
168 .map_err(|e| super::LeanError::State(format!("posture: {e}")))
169 }
170
171 /// The pre-existing-`.flint/` pre-flight (D0.4).
172 ///
173 /// Reserving `.flint/` is a BREAKING change for a workspace already
174 /// using it as data: its writes silently stop publishing and —
175 /// worse — files literally named `.flint/publish` or `.flint/sync`
176 /// would be *consumed* (renamed away) by the sentinel poll: a data
177 /// grab from a non-participating workspace. When either signature
178 /// is present, sentinel consumption is disabled for the workspace:
179 /// the poll arm never arms, `capabilities.json` reports no verbs
180 /// with the reason, and the operator surfaces it as
181 /// `SentinelVerbsActive=False`.
182 ///
183 /// The verdict is STICKY once written — see `POSTURE`.
184 pub fn sentinel_preflight(&self) -> LeanResult<SentinelPosture> {
185 if self.cfg.sentinel_mode == super::SentinelMode::Off {
186 let posture =
187 SentinelPosture { enabled: false, reason: Some("sentinels-off".into()) };
188 write_json(&self.posture_path(), &posture)?;
189 return Ok(posture);
190 }
191 if let Some(prior) = self.load_posture()? {
192 if !prior.enabled && self.cfg.sentinel_mode != super::SentinelMode::Force {
193 return Ok(prior);
194 }
195 }
196
197 // (a) the baseline cites a path under the reserved namespace.
198 let baseline = self.state.load_baseline()?;
199 let legacy_cited = baseline.entries.keys().any(|p| super::scan::is_control_path(p))
200 || baseline.inst_base.keys().any(|p| super::scan::is_control_path(p));
201
202 // (b) a sentinel-named file exists before this tree has ever
203 // been given a capability marker (i.e. before any syncer
204 // that understands the protocol ran here).
205 let never_marked = !self.control_path(CAPABILITIES).exists();
206 let sentinel_named = self.control_path(PUBLISH).exists() || self.control_path(SYNC).exists();
207 let preexisting = legacy_cited || (never_marked && sentinel_named);
208
209 let posture = if preexisting && self.cfg.sentinel_mode != super::SentinelMode::Force {
210 SentinelPosture { enabled: false, reason: Some("preexisting-flint-paths".into()) }
211 } else if preexisting {
212 // `force` requires the operator of record to have accepted
213 // the consumption behavior explicitly.
214 SentinelPosture { enabled: true, reason: Some("forced-over-preexisting".into()) }
215 } else {
216 SentinelPosture { enabled: true, reason: None }
217 };
218 write_json(&self.posture_path(), &posture)?;
219 Ok(posture)
220 }
221
222 /// Write `.flint/capabilities.json` for the current posture.
223 pub fn write_capabilities(&self, posture: &SentinelPosture) -> LeanResult<()> {
224 let verbs: Vec<String> = if !posture.enabled {
225 vec![]
226 } else {
227 ["publish", "sync", "remote-seq"].iter().map(|s| s.to_string()).collect()
228 };
229 let holder_id = self
230 .lease
231 .as_ref()
232 .map(|l| l.holder_id.clone())
233 .or_else(|| {
234 self.state.load_incarnation().ok().flatten().map(|i| i.holder_id)
235 })
236 .unwrap_or_else(|| "unclaimed".into());
237 let caps = Capabilities {
238 protocol: SENTINEL_PROTOCOL,
239 verbs,
240 state: "live".into(),
241 reason: posture.reason.clone(),
242 sentinel_min_interval_secs: self.cfg.sentinel_min_interval_secs,
243 sentinel_hourly_budget: self.cfg.sentinel_hourly_budget,
244 syncer_version: super::SYNCER_VERSION.to_string(),
245 boot: BootStamp { holder_id, boot_unix: now_unix() },
246 };
247 write_json(&self.control_path(CAPABILITIES), &caps)?;
248 write_atomic(&self.control_path(AGENT_GUIDE), AGENT_GUIDE_TEXT.as_bytes())
249 }
250
251 pub fn read_capabilities(&self) -> Option<Capabilities> {
252 let bytes = std::fs::read(self.control_path(CAPABILITIES)).ok()?;
253 serde_json::from_slice(&bytes).ok()
254 }
255
256 pub fn load_remote_seq(&self) -> RemoteSeq {
257 std::fs::read(self.control_path(REMOTE_SEQ))
258 .ok()
259 .and_then(|b| serde_json::from_slice(&b).ok())
260 .unwrap_or_default()
261 }
262
263 /// Move the ticker (D5). `observed` is what the barrier's existing
264 /// manifest HEAD (or its completed install) already told us — this
265 /// never issues a request of its own.
266 ///
267 /// `updated_unix` refreshes on every call (the liveness heartbeat);
268 /// `observed_seq`/`observed_etag` change only when they change.
269 pub fn touch_remote_seq(
270 &self,
271 observed_seq: Option<u64>,
272 observed_etag: Option<String>,
273 integrated_seq: u64,
274 ) -> LeanResult<()> {
275 let mut t = self.load_remote_seq();
276 if let Some(seq) = observed_seq {
277 t.observed_seq = seq;
278 }
279 if observed_etag.is_some() {
280 t.observed_etag = observed_etag;
281 }
282 t.integrated_seq = integrated_seq;
283 if t.observed_seq < integrated_seq {
284 // Our own install is the newest news we know of.
285 t.observed_seq = integrated_seq;
286 }
287 // A request the workspace has already integrated past is stale
288 // news and self-clears (D14).
289 if t.sync_requested_at_seq.map(|at| integrated_seq > at).unwrap_or(false) {
290 t.sync_requested_unix = None;
291 t.sync_requested_by = None;
292 t.sync_requested_at_seq = None;
293 }
294 t.updated_unix = now_unix();
295 write_json(&self.control_path(REMOTE_SEQ), &t)
296 }
297
298 /// Carry an advisory sync request into the ticker (D14). The
299 /// asymmetry with `boundary_request` is about blast radius, not
300 /// principle: a boundary publishes what is already on disk and
301 /// touches no local file, whereas `sync` re-derives the tree
302 /// against the current remote manifest and DELETES local files for
303 /// remotely-deleted paths. Performing that on a remote's say-so
304 /// would upgrade what a leaked gateway bearer can do from "publish,
305 /// plus hand over these N named objects" to "rewrite and delete
306 /// across a running agent's tree, at my timing, under a scope I
307 /// choose".
308 pub fn carry_sync_request(&self, requested_unix: u64, requestor: &str) -> LeanResult<()> {
309 let mut t = self.load_remote_seq();
310 let newer = t.sync_requested_unix.map(|p| requested_unix > p).unwrap_or(true);
311 if !newer {
312 return Ok(());
313 }
314 t.sync_requested_unix = Some(requested_unix);
315 t.sync_requested_by = Some(requestor.to_string());
316 t.sync_requested_at_seq = Some(t.integrated_seq);
317 t.updated_unix = now_unix();
318 write_json(&self.control_path(REMOTE_SEQ), &t)
319 }
320}