Skip to main content

lex_store/
store.rs

1//! `Store` — content-addressed code repository.
2//!
3//! The filesystem is the source of truth. All operations read/write JSON
4//! files under `<root>/stages/<SigId>/`. There is no SQLite cache: every
5//! query walks the directory and parses what's needed. `cargo test`
6//! runs aren't perf-critical and the §4.6 acceptance requires the
7//! rebuild-from-filesystem property anyway.
8
9use crate::branches::DEFAULT_BRANCH;
10use crate::model::*;
11use lex_ast::{sig_id, stage_id, Stage};
12use serde::de::DeserializeOwned;
13use serde::Serialize;
14use std::collections::BTreeMap;
15use std::fs;
16use std::path::{Path, PathBuf};
17use std::time::{SystemTime, UNIX_EPOCH};
18
19#[derive(Debug, thiserror::Error)]
20pub enum StoreError {
21    #[error("io error: {0}")]
22    Io(#[from] std::io::Error),
23    #[error("serialization error: {0}")]
24    Serde(#[from] serde_json::Error),
25    #[error("imports cannot be published as stages")]
26    CannotPublishImport,
27    #[error("unknown stage_id `{0}`")]
28    UnknownStage(String),
29    #[error("unknown sig_id `{0}`")]
30    UnknownSig(String),
31    #[error("invalid lifecycle transition: {0}")]
32    InvalidTransition(String),
33    #[error("unknown branch `{0}`")]
34    UnknownBranch(String),
35    /// A branch-head advance (e.g. the ref half of `op push`) was
36    /// asked to move `branch` to `attempted`, but `attempted` is not a
37    /// descendant of the branch's `current` head — a non-fast-forward
38    /// that would orphan history. Refused, git-style, so a disjoint or
39    /// diverged push can't silently clobber a shared branch. The op
40    /// objects may already be present; only the ref is left unchanged.
41    #[error("non-fast-forward on `{branch}`: {attempted} is not a descendant of current head {current}")]
42    NonFastForward { branch: String, current: lex_vcs::OpId, attempted: lex_vcs::OpId },
43    #[error("unknown blob `{0}`")]
44    UnknownBlob(String),
45    #[error("unknown blob ref `{namespace}/{key}`")]
46    UnknownBlobRef { namespace: String, key: String },
47    #[error("unknown op_id `{0}`")]
48    UnknownOp(lex_vcs::OpId),
49    /// A typed AST transform (#280) — e.g. `ReplaceMatchArm` — was
50    /// asked to operate on a node it couldn't address (wrong kind,
51    /// out-of-range arm index, unknown NodeId, etc.). Distinct from
52    /// `TypeError` (which means the transform succeeded but its
53    /// output didn't typecheck) so callers can render the right
54    /// error message.
55    #[error("transform failed: {0}")]
56    TransformError(lex_ast::TransformError),
57    #[error(transparent)]
58    Apply(#[from] lex_vcs::ApplyError),
59    /// The candidate program — i.e. the source the caller is
60    /// publishing — doesn't typecheck. The branch head is unchanged
61    /// and no op records are persisted. Issue #130's "always-valid
62    /// HEAD" invariant: the gate runs before any side effect, so a
63    /// type-broken publish leaves no footprint.
64    #[error("type errors in published program: {} error(s)", .0.len())]
65    TypeError(Vec<lex_types::TypeError>),
66    /// A dependency being resolved for the write-time gate (#930) is a
67    /// multi-module package. Per-module signature extraction (picking the
68    /// imported module's file out of the de-flattened tree) is not yet
69    /// implemented; single-module (leaf) dependencies resolve today. A
70    /// caller can treat this as "cannot resolve here" rather than a hard
71    /// failure.
72    #[error("multi-module dependency resolution is not yet supported")]
73    UnsupportedMultiModuleDependency,
74    /// A typed issue's example targets a function that isn't declared at
75    /// the head being evaluated (#949) — the example cannot be attached, so
76    /// the issue cannot be judged there.
77    #[error("issue example targets `{0}`, which is not declared at this head")]
78    IssueTarget(String),
79    /// The op was persisted but a `required_attestations` rule in
80    /// `policy.json` (#245) refused to advance the branch head past
81    /// it. The op record is durable — re-running with the missing
82    /// attestations recorded will succeed without re-persisting —
83    /// but the branch is unchanged. Surfaced as a structured JSON
84    /// envelope on the HTTP API.
85    #[error(
86        "branch advance blocked: op {} missing attestations: {}",
87        .0.op_id, .0.missing.join(", ")
88    )]
89    BranchAdvanceBlocked(crate::policy::BranchAdvanceBlocked),
90    /// All retry attempts of the CAS branch-head advance failed
91    /// because another writer kept advancing the same branch
92    /// (#262). The op record itself is durable in the op log
93    /// (orphaned), so re-running with backoff would eventually
94    /// land — return `503 Contention { retry_after }` from the
95    /// HTTP API and let the client back off.
96    #[error("branch advance contention on `{branch}`: {attempts} retries exhausted")]
97    Contention { branch: String, attempts: u32 },
98    /// The op was persisted but its stage carries an attestation
99    /// produced by a retroactively quarantined tool (#248). The
100    /// branch head is unchanged. The op record stays in the log
101    /// (audit trail intact); re-running with the producer
102    /// unblocked, or with un-contaminated attestations, succeeds
103    /// without re-persisting the op.
104    #[error(
105        "branch advance blocked: op {} touches stage {} with an attestation from \
106         quarantined producer `{}` (blocked at {}, attestation at {})",
107        .0.op_id, .0.stage_id, .0.tool_id, .0.blocked_at, .0.attestation_at
108    )]
109    ProducerBlocked(crate::policy::ProducerBlocked),
110    /// The op would push its session's monotonic budget over the
111    /// cap configured in `policy.session_budgets` (#292 slice 3).
112    /// The op is *not* persisted; the branch head is unchanged.
113    /// The caller should either start a new session, raise the
114    /// cap, or refactor to fit the budget. HTTP API maps to 503.
115    #[error("session `{session_id}` budget exceeded: spent_after={spent_after} > cap={cap}")]
116    BudgetExceeded {
117        session_id: String,
118        cap: u64,
119        spent_after: u64,
120    },
121}
122
123/// The outcome returned by [`Store::publish_program`].
124#[derive(Debug, Clone, serde::Serialize)]
125pub struct PublishOutcome {
126    pub ops: Vec<PublishOp>,
127    pub head_op: Option<lex_vcs::OpId>,
128}
129
130/// Everything a regenerator needs to *replay* an op (#836 G3), produced
131/// by [`Store::replay_request`]. The model call is external: a harness
132/// feeds `prompt` + `parent_program` to `model`, then hands the
133/// regenerated stage to [`Store::replay_compare`].
134#[derive(Debug, Clone, serde::Serialize)]
135pub struct ReplayRequest {
136    pub op_id: String,
137    /// The sig the op changed — the function to regenerate.
138    pub target_sig: String,
139    /// The target function's name (the recorded stage is a function
140    /// for every replayable op).
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub target_name: Option<String>,
143    /// The target function's rendered signature (`fn name(...) -> T`),
144    /// so a regenerator knows the interface to implement without
145    /// re-deriving it from the sig hash.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub target_signature: Option<String>,
148    /// The stage id a faithful regeneration should reproduce.
149    pub expected_stage_id: String,
150    /// The recorded intent prompt (`None` if the op carried no intent).
151    pub prompt: Option<String>,
152    /// The recorded model (`provider/name[@version]`), if any.
153    pub model: Option<String>,
154    /// The recorded session id, if any.
155    pub session_id: Option<String>,
156    /// The program the change was made against — the parent state
157    /// rendered to source — the context a regenerator needs.
158    pub parent_program: String,
159}
160
161/// The result of comparing a regenerated candidate against an op's
162/// recorded output (#836 G3), returned by [`Store::replay_compare`]
163/// after it emits the `Replay` attestation.
164#[derive(Debug, Clone, serde::Serialize)]
165pub struct ReplayOutcome {
166    pub op_id: String,
167    pub expected_stage_id: String,
168    /// The candidate's stage id when it regenerated the same sig, else
169    /// `None`.
170    pub produced_stage_id: Option<String>,
171    /// Whether the regeneration reproduced the recorded change (exact or
172    /// behavioral).
173    pub reproduced: bool,
174    /// Set when reproduction was behavioral (same values over N sampled
175    /// inputs) rather than an exact stage-id match. `None` for an exact
176    /// match or a genuine miss.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub behavioral_samples: Option<usize>,
179    /// The id of the `Replay` attestation this comparison emitted.
180    pub attestation_id: String,
181}
182
183/// One applied operation within a [`PublishOutcome`].
184#[derive(Debug, Clone, serde::Serialize)]
185pub struct PublishOp {
186    pub op_id: lex_vcs::OpId,
187    pub kind: serde_json::Value,
188}
189
190/// One entry in the per-`SigId` stage history surfaced by
191/// `Store::sig_history`. Newest-first ordering is the responsibility
192/// of the producer.
193#[derive(Debug, Clone, serde::Serialize, PartialEq)]
194pub struct StageHistoryEntry {
195    pub stage_id: String,
196    pub status: StageStatus,
197    /// Wall-clock seconds of the most recent transition.
198    pub last_at: u64,
199    /// Wall-clock seconds when this stage was first written to the
200    /// store (its initial Draft transition). `None` for stages
201    /// whose lifecycle log doesn't include an explicit Draft entry
202    /// — shouldn't happen for stages published via `Store::publish`,
203    /// but the type allows hand-edited stores.
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub published_at: Option<u64>,
206}
207
208/// Per-candidate metadata surfaced by [`Store::list_candidates`]
209/// (#294). Returned sorted by `op_id` for deterministic output.
210#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
211pub struct CandidateInfo {
212    pub op_id: lex_vcs::OpId,
213    pub stage_id: lex_vcs::StageId,
214    /// Author intent. Always set for `Candidate` ops emitted via
215    /// [`Store::propose_candidate`]; `None` only if a
216    /// hand-written raw op skipped the intent tag.
217    pub intent_id: Option<lex_vcs::IntentId>,
218}
219
220/// One line of `stage_index.jsonl`. See `Store::lookup_lifecycle`.
221#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
222struct StageIndexEntry {
223    stage_id: String,
224    sig_id: String,
225}
226
227/// Sentinel `sig_id` value recording "a full scan already established
228/// this stage_id exists nowhere in the store" (#825). Never a real
229/// sig — sig directory names are never empty.
230const MISSING_STAGE_MARKER: &str = "";
231
232/// Resolves a head's external (registry/git) dependencies to their public
233/// module signatures, so the write-time gate can type-check a head that keeps
234/// `import "<pkg>/mod" as <alias>` edges instead of inlining the dependency
235/// (#930). The returned map is keyed by import *reference* (`"lex-nt/lib"`) →
236/// that dependency module's record type (as [`crate::render::module_record_at_op`]
237/// or a source-based equivalent produces), exactly the shape
238/// [`lex_types::check_program_with_modules`] consumes.
239///
240/// Implementations differ by context and live in the crate that has the
241/// resolution machinery: the client (`lex publish`) resolves from the
242/// working-copy `lex.lock` + local package cache; the hub resolves from the
243/// committed lock + its own hosted stores (cross-tenant), which a single
244/// [`Store`] cannot reach on its own. When no resolver is installed the gate
245/// resolves an empty map — only stdlib binds and any external reference is an
246/// unbound-name error, exactly as before #930 (so inlined heads, which carry
247/// no external edges, are unaffected).
248pub trait DepResolver: Send + Sync {
249    /// `head_op` is the op the head is known by when the gate has one (merge,
250    /// patch and hub-verify reconstruct a committed head); `None` for a
251    /// candidate not yet committed (`publish`), where the client resolver
252    /// falls back to the working-copy lock.
253    fn resolve_modules(
254        &self,
255        stages: &[Stage],
256        head_op: Option<&str>,
257    ) -> BTreeMap<String, lex_types::Ty>;
258
259    /// The resolved dependencies' exported **type declarations**, keyed by the
260    /// same import reference as [`Self::resolve_modules`] (#930 completeness).
261    /// The write-time gate registers these under each import's alias so a head
262    /// that references a dependency's *type* — not just its functions — checks.
263    ///
264    /// Defaulted to empty so existing resolvers keep compiling and simply
265    /// resolve function signatures only (their previous behavior); a resolver
266    /// that can supply type declarations overrides this.
267    fn resolve_module_types(
268        &self,
269        _stages: &[Stage],
270        _head_op: Option<&str>,
271    ) -> BTreeMap<String, Vec<lex_ast::TypeDecl>> {
272        BTreeMap::new()
273    }
274
275    /// Each resolved dependency import's **module mangle prefix**, keyed by the
276    /// same import reference (#963). When a dependency is resolved as a whole
277    /// package, its exported types are named by their path-derived prefix
278    /// (`error_<hash>.DbErr`); this lets the write-time gate map the import
279    /// alias to that prefix so an alias-qualified type reference (`e.DbErr`)
280    /// resolves to the same type the dependency's own signatures name.
281    ///
282    /// Defaulted to empty: a resolver that returns bare (alias-qualified) type
283    /// names supplies none, and the gate keeps the #930 alias-qualification
284    /// path.
285    fn resolve_module_prefixes(
286        &self,
287        _stages: &[Stage],
288        _head_op: Option<&str>,
289    ) -> BTreeMap<String, String> {
290        BTreeMap::new()
291    }
292}
293
294pub struct Store {
295    root: PathBuf,
296    /// Optional dependency resolver (#930). Injected by the client or the hub;
297    /// `None` in a bare store means the gate resolves an empty module map.
298    resolver: Option<std::sync::Arc<dyn DepResolver>>,
299}
300
301impl Store {
302    /// Open or create a store rooted at `root`.
303    pub fn open(root: impl AsRef<Path>) -> Result<Self, StoreError> {
304        let root = root.as_ref().to_path_buf();
305        fs::create_dir_all(root.join("stages"))?;
306        fs::create_dir_all(root.join("traces"))?;
307        let store = Self { root, resolver: None };
308        store.ensure_stage_index();
309        Ok(store)
310    }
311
312    /// Install the dependency resolver the write-time gate uses to type-check
313    /// heads that keep external `import` edges (#930). Builder-style so a
314    /// caller can write `Store::open(p)?.with_dep_resolver(r)`.
315    pub fn with_dep_resolver(mut self, resolver: std::sync::Arc<dyn DepResolver>) -> Self {
316        self.resolver = Some(resolver);
317        self
318    }
319
320    /// Set the dependency resolver in place (for a `Store` already owned, e.g.
321    /// behind a `Mutex` in the HTTP `State`).
322    pub fn set_dep_resolver(&mut self, resolver: std::sync::Arc<dyn DepResolver>) {
323        self.resolver = Some(resolver);
324    }
325
326    /// The resolved dependency module map for a head being gated — the
327    /// installed resolver's answer, or empty when none is installed (#930).
328    fn resolved_modules(
329        &self,
330        stages: &[Stage],
331        head_op: Option<&str>,
332    ) -> BTreeMap<String, lex_types::Ty> {
333        match &self.resolver {
334            Some(r) => r.resolve_modules(stages, head_op),
335            None => BTreeMap::new(),
336        }
337    }
338
339    /// The resolved dependencies' exported type declarations for a head being
340    /// gated (#930 completeness) — the installed resolver's answer, or empty
341    /// when none is installed.
342    fn resolved_module_types(
343        &self,
344        stages: &[Stage],
345        head_op: Option<&str>,
346    ) -> BTreeMap<String, Vec<lex_ast::TypeDecl>> {
347        match &self.resolver {
348            Some(r) => r.resolve_module_types(stages, head_op),
349            None => BTreeMap::new(),
350        }
351    }
352
353    /// The resolved dependency import → module-prefix map for a head being
354    /// gated (#963) — the installed resolver's answer, or empty when none is
355    /// installed (then the gate keeps the #930 alias-qualified path).
356    fn resolved_module_prefixes(
357        &self,
358        stages: &[Stage],
359        head_op: Option<&str>,
360    ) -> BTreeMap<String, String> {
361        match &self.resolver {
362            Some(r) => r.resolve_module_prefixes(stages, head_op),
363            None => BTreeMap::new(),
364        }
365    }
366
367    /// One-time migration for a store that predates the reverse
368    /// index (#822), or whose previous rebuild pass never finished
369    /// (e.g. the process was killed or its client disconnected
370    /// mid-request — server-side work keeps running either way, but
371    /// a *restart* genuinely stops it): build the index in a single
372    /// pass instead of leaving every subsequent `lookup_lifecycle`
373    /// call to discover its own entry via the slow per-call scan-
374    /// and-backfill fallback.
375    ///
376    /// That per-call fallback is fine for the rare individual miss
377    /// it was designed for, but pathological as a *bulk* cold-start
378    /// strategy: on a tenant with a few thousand functions it means
379    /// redoing an O(total sigs) scan from scratch for *each* of a
380    /// few thousand cold entries — O(total sigs²) — which measured
381    /// as a near-stall (page-cache thrashing) on a memory-
382    /// constrained host. A single pass over `list_sigs()` is
383    /// O(total sigs) total.
384    ///
385    /// Gated on a dedicated completion marker
386    /// (`stage_index.complete`), NOT on `stage_index.jsonl`'s mere
387    /// existence — a partially-built index file (left behind by an
388    /// interrupted rebuild, lazy or bulk) must still trigger a
389    /// re-run so the remaining entries get backfilled in one more
390    /// cheap O(total sigs) pass, not silently be mistaken for
391    /// "already done" and fall back to the slow per-call path for
392    /// whatever's left. `rebuild_stage_index` already skips entries
393    /// it finds present, so re-running it against a partial index
394    /// only does the work that remains. The marker is written only
395    /// after a full pass returns `Ok`, so a failed pass (e.g. an I/O
396    /// error partway through `list_sigs`) is retried on the next
397    /// open rather than being marked done.
398    ///
399    /// Runs once per `Store::open` call — which, in a long-lived
400    /// server (lex-hub caches one `Store` per tenant for the life of
401    /// the process), means once per tenant per process lifetime, not
402    /// once per request. Once the marker exists (the steady state
403    /// after the first successful run on any given host) this is a
404    /// single cheap file-existence check. Best-effort like the rest
405    /// of the index: any failure here just leaves the slower per-call
406    /// fallback as the only path, never breaks correctness.
407    fn ensure_stage_index(&self) {
408        if self.stage_index_complete_marker_path().exists() {
409            return;
410        }
411        if self.rebuild_stage_index().is_ok() {
412            let _ = fs::write(self.stage_index_complete_marker_path(), "");
413        }
414    }
415
416    fn stage_index_complete_marker_path(&self) -> PathBuf {
417        self.root.join("stage_index.complete")
418    }
419
420    /// Build (or top up) the reverse index in one pass over every
421    /// SigId in the store, rather than relying on `lookup_lifecycle`
422    /// to discover entries one at a time. Safe to call at any time,
423    /// including on a partially-built index (e.g. one left behind by
424    /// an interrupted request that was populating it lazily): already-
425    /// indexed stage_ids are skipped, so this only does the work that
426    /// remains. Returns the number of newly-added entries.
427    pub fn rebuild_stage_index(&self) -> Result<usize, StoreError> {
428        // A sig's lifecycle can list the same stage_id more than once
429        // (Draft, then later Active, then Deprecated all carry the
430        // same stage_id with a different status) -- track newly-seen
431        // keys locally too, not just what was already on disk at the
432        // start, so a repeated stage_id within one sig's transitions
433        // doesn't get appended to the index more than once.
434        let mut existing = self.load_stage_index();
435        let mut added = 0usize;
436        for sig in self.list_sigs()? {
437            let Ok(life) = self.read_lifecycle(&sig) else { continue };
438            for t in &life.transitions {
439                if !existing.contains_key(&t.stage_id) {
440                    self.append_stage_index_entry(&t.stage_id, &sig);
441                    existing.insert(t.stage_id.clone(), sig.clone());
442                    added += 1;
443                }
444            }
445        }
446        Ok(added)
447    }
448
449    pub fn root(&self) -> &Path {
450        &self.root
451    }
452
453    // ── Generic content-addressed blobs (#5 / M6.1) ──────────────────────────
454    //
455    // The stage store holds typed Lex ASTs; loom-style artifacts (generated
456    // code, JSON, prose) are opaque text. These blob methods give the store a
457    // generic content-addressed object alongside stages, plus a lightweight
458    // ref namespace so callers can bind names (e.g. a sprint's node ids) to
459    // blob shas without touching the operation-log branch machinery.
460    //
461    // The sha is the lowercase hex SHA-256 of the content's UTF-8 bytes —
462    // identical to Lex's `crypto.sha256_str`, so a blob written here and an
463    // artifact content-addressed in loom's SQLite store share the same id and
464    // are interchangeable by reference. Store-scoped, so under lex-hub each
465    // tenant store gets its own blob space for free.
466
467    fn blobs_dir(&self) -> PathBuf {
468        self.root.join("blobs")
469    }
470
471    fn blob_refs_dir(&self) -> PathBuf {
472        self.root.join("blobrefs")
473    }
474
475    /// Content-address `content` and persist it under `<root>/blobs/<sha>`.
476    /// Returns the sha. Idempotent: re-putting identical content is a no-op.
477    /// Concurrency-safe — writes to a unique temp file then atomically renames
478    /// onto the content-addressed path, so parallel writers of the same content
479    /// can't corrupt it.
480    pub fn put_blob(&self, content: &str) -> Result<String, StoreError> {
481        use sha2::{Digest, Sha256};
482        let sha = hex::encode(Sha256::digest(content.as_bytes()));
483        let dir = self.blobs_dir();
484        let path = dir.join(&sha);
485        if path.exists() {
486            return Ok(sha);
487        }
488        fs::create_dir_all(&dir)?;
489        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
490        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
491        let tmp = dir.join(format!(".{sha}.{}.{n}.tmp", std::process::id()));
492        fs::write(&tmp, content.as_bytes())?;
493        // rename is atomic on the same filesystem; identical content makes a
494        // last-writer-wins race harmless.
495        fs::rename(&tmp, &path)?;
496        Ok(sha)
497    }
498
499    /// Read a blob by its sha. `UnknownBlob` if absent.
500    pub fn get_blob(&self, sha: &str) -> Result<String, StoreError> {
501        match fs::read_to_string(self.blobs_dir().join(sha)) {
502            Ok(s) => Ok(s),
503            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
504                Err(StoreError::UnknownBlob(sha.to_string()))
505            }
506            Err(e) => Err(StoreError::Io(e)),
507        }
508    }
509
510    /// Whether a blob with this sha exists.
511    pub fn has_blob(&self, sha: &str) -> bool {
512        self.blobs_dir().join(sha).exists()
513    }
514
515    /// Bind `key` to a blob `sha` within `namespace` (e.g. namespace
516    /// `"loom/sprint-abc"`, key `"build-node"`). Overwrites an existing
517    /// binding. The namespace may contain `/`; neither namespace nor key may
518    /// contain a `..` path component.
519    pub fn set_blob_ref(&self, namespace: &str, key: &str, sha: &str) -> Result<(), StoreError> {
520        let dir = self.blob_ref_namespace_dir(namespace, key)?;
521        fs::create_dir_all(&dir)?;
522        fs::write(dir.join(key), sha.as_bytes())?;
523        Ok(())
524    }
525
526    /// Resolve `namespace`/`key` to a blob sha. `UnknownBlobRef` if unbound.
527    pub fn get_blob_ref(&self, namespace: &str, key: &str) -> Result<String, StoreError> {
528        let dir = self.blob_ref_namespace_dir(namespace, key)?;
529        match fs::read_to_string(dir.join(key)) {
530            Ok(s) => Ok(s.trim().to_string()),
531            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(StoreError::UnknownBlobRef {
532                namespace: namespace.to_string(),
533                key: key.to_string(),
534            }),
535            Err(e) => Err(StoreError::Io(e)),
536        }
537    }
538
539    /// Blob-ref namespace for committed lockfiles (#930 phase 2b-1).
540    const LOCK_NS: &'static str = "lock";
541
542    /// Record the `lex.lock` committed with the package head `head_op` — the
543    /// exact dependency versions and op-log heads that head was built and
544    /// type-checks against (#930 phase 2b-1: "HEAD + its committed lex.lock
545    /// always type-checks"). Content-addressed via [`Self::put_blob`] and
546    /// bound under the `lock` namespace keyed by the head op, so it is
547    /// idempotent (a re-push converges) and travels with the package through
548    /// the same object-sync path as stages and intents. Keyed by head op
549    /// rather than by branch so re-verifying a *historical* head resolves it
550    /// against the lock that head actually committed, not whatever the branch
551    /// points at now.
552    pub fn set_committed_lock(&self, head_op: &str, lock_toml: &str) -> Result<(), StoreError> {
553        let sha = self.put_blob(lock_toml)?;
554        self.set_blob_ref(Self::LOCK_NS, head_op, &sha)
555    }
556
557    /// The `lex.lock` committed with `head_op`, or `None` when the head
558    /// carries no committed lock — a dependency-free package, or one
559    /// published before locks were committed (the write-time gate then has no
560    /// registry/git dependencies to resolve, exactly as today).
561    pub fn committed_lock(&self, head_op: &str) -> Result<Option<String>, StoreError> {
562        match self.get_blob_ref(Self::LOCK_NS, head_op) {
563            Ok(sha) => Ok(Some(self.get_blob(&sha)?)),
564            Err(StoreError::UnknownBlobRef { .. }) => Ok(None),
565            Err(e) => Err(e),
566        }
567    }
568
569    /// All `key → sha` bindings in a namespace (e.g. every artifact in a
570    /// sprint). Empty map if the namespace has no bindings yet.
571    pub fn list_blob_refs(
572        &self,
573        namespace: &str,
574    ) -> Result<std::collections::BTreeMap<String, String>, StoreError> {
575        let dir = self.blob_ref_namespace_dir(namespace, "x")?;
576        let mut out = std::collections::BTreeMap::new();
577        let entries = match fs::read_dir(&dir) {
578            Ok(e) => e,
579            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
580            Err(e) => return Err(StoreError::Io(e)),
581        };
582        for entry in entries {
583            let entry = entry?;
584            if entry.file_type()?.is_file() {
585                let key = entry.file_name().to_string_lossy().to_string();
586                let sha = fs::read_to_string(entry.path())?.trim().to_string();
587                out.insert(key, sha);
588            }
589        }
590        Ok(out)
591    }
592
593    // Resolve the on-disk dir for a (namespace, key), rejecting `..` traversal
594    // and `/` in the key. `key` is validated but not joined here (callers join
595    // it themselves so `list_blob_refs` can pass a dummy).
596    fn blob_ref_namespace_dir(&self, namespace: &str, key: &str) -> Result<PathBuf, StoreError> {
597        if key.contains('/') || key.contains('\\') || key.split('/').any(|c| c == "..") {
598            return Err(StoreError::UnknownBlobRef {
599                namespace: namespace.to_string(),
600                key: key.to_string(),
601            });
602        }
603        let mut dir = self.blob_refs_dir();
604        for comp in namespace.split('/') {
605            if comp == ".." || comp.contains('\\') {
606                return Err(StoreError::UnknownBlobRef {
607                    namespace: namespace.to_string(),
608                    key: key.to_string(),
609                });
610            }
611            if !comp.is_empty() {
612                dir.push(comp);
613            }
614        }
615        Ok(dir)
616    }
617
618    fn now() -> u64 {
619        SystemTime::now()
620            .duration_since(UNIX_EPOCH)
621            .map(|d| d.as_secs())
622            .unwrap_or(0)
623    }
624
625    fn sig_dir(&self, sig: &str) -> PathBuf {
626        self.root.join("stages").join(sig)
627    }
628    fn impl_dir(&self, sig: &str) -> PathBuf {
629        self.sig_dir(sig).join("implementations")
630    }
631    fn tests_dir(&self, sig: &str) -> PathBuf {
632        self.sig_dir(sig).join("tests")
633    }
634    fn specs_dir(&self, sig: &str) -> PathBuf {
635        self.sig_dir(sig).join("specs")
636    }
637    fn lifecycle_path(&self, sig: &str) -> PathBuf {
638        self.sig_dir(sig).join("lifecycle.json")
639    }
640
641    // ---- publish ----
642
643    /// Publish a stage as **Draft**. Returns the StageId.
644    /// Idempotent: republishing the same canonical AST returns the same
645    /// StageId without writing duplicates.
646    pub fn publish(&self, stage: &Stage) -> Result<String, StoreError> {
647        self.publish_signed(stage, None)
648    }
649
650    /// Like [`Self::publish`] but optionally attaches an Ed25519
651    /// signature over the StageId (#227). When `signer` is `Some`,
652    /// the persisted metadata gets a `signature` field that
653    /// downstream consumers can verify via
654    /// [`lex_vcs::verify_stage_id`].
655    ///
656    /// Idempotency: if a metadata file already exists the signature
657    /// is *not* re-written. This preserves "republishing is a no-op"
658    /// even across different signers — promoting a signed stage
659    /// requires a fresh stage hash anyway, so a metadata overwrite
660    /// would be the wrong primitive.
661    pub fn publish_signed(
662        &self,
663        stage: &Stage,
664        signer: Option<&lex_vcs::Keypair>,
665    ) -> Result<String, StoreError> {
666        let sig = sig_id(stage).ok_or(StoreError::CannotPublishImport)?;
667        let stage_id = stage_id(stage).ok_or(StoreError::CannotPublishImport)?;
668        let name = stage_name(stage).to_string();
669
670        fs::create_dir_all(self.impl_dir(&sig))?;
671        fs::create_dir_all(self.tests_dir(&sig))?;
672        fs::create_dir_all(self.specs_dir(&sig))?;
673
674        let ast_path = self.impl_dir(&sig).join(format!("{}.ast.json", stage_id));
675        let delta_path = self.impl_dir(&sig).join(format!("{}.delta.json", stage_id));
676        let meta_path = self
677            .impl_dir(&sig)
678            .join(format!("{}.metadata.json", stage_id));
679
680        // #261 slice 3: try delta encoding against the most recent
681        // prior stage in this sig's lifecycle. Falls back to a full
682        // snapshot when (a) no prior stage exists, (b) the diff
683        // ratio is over the threshold, or (c) the delta chain is
684        // already at its cap. The decision is internal — callers
685        // see the same `Stage` object on `get_ast` regardless.
686        if !ast_path.exists() && !delta_path.exists() {
687            self.persist_stage_bytes(&sig, &stage_id, stage, &ast_path, &delta_path)?;
688        }
689        if !meta_path.exists() {
690            let signature = signer.map(|kp| kp.sign_stage_id(&stage_id));
691            let metadata = Metadata {
692                stage_id: stage_id.clone(),
693                sig_id: sig.clone(),
694                name,
695                published_at: Self::now(),
696                note: None,
697                signature,
698            };
699            write_canonical_json(&meta_path, &metadata)?;
700        }
701
702        // Lifecycle: append a Draft transition for first publish.
703        let mut life = self.read_lifecycle(&sig).unwrap_or_else(|_| Lifecycle {
704            sig_id: sig.clone(),
705            ..Default::default()
706        });
707        if !life.transitions.iter().any(|t| t.stage_id == stage_id) {
708            life.transitions.push(Transition {
709                stage_id: stage_id.clone(),
710                from: StageStatus::Draft, // synthesized; "from" of first transition is itself
711                to: StageStatus::Draft,
712                at: Self::now(),
713                reason: None,
714            });
715            self.write_lifecycle(&sig, &life)?;
716            // Register the new stage_id's owning sig up front so a
717            // later `lookup_lifecycle` (e.g. `get_ast`) never needs
718            // to fall back to a full tenant-wide scan for it.
719            self.append_stage_index_entry(&stage_id, &sig);
720        }
721        Ok(stage_id)
722    }
723
724    // ---- lifecycle ----
725
726    pub fn activate(&self, stage_id: &str) -> Result<(), StoreError> {
727        let (sig, mut life) = self.lookup_lifecycle(stage_id)?;
728        // Demote any currently-Active impls for this SigId to Deprecated.
729        let active = life.current_active().map(|s| s.to_string());
730        if let Some(prev) = active {
731            if prev != stage_id {
732                life.transitions.push(Transition {
733                    stage_id: prev,
734                    from: StageStatus::Active,
735                    to: StageStatus::Deprecated,
736                    at: Self::now(),
737                    reason: Some("superseded".into()),
738                });
739            }
740        }
741        let cur = life.status_of(stage_id);
742        if cur == Some(StageStatus::Tombstone) {
743            return Err(StoreError::InvalidTransition(
744                "tombstoned cannot be activated".into(),
745            ));
746        }
747        life.transitions.push(Transition {
748            stage_id: stage_id.into(),
749            from: cur.unwrap_or(StageStatus::Draft),
750            to: StageStatus::Active,
751            at: Self::now(),
752            reason: None,
753        });
754        self.write_lifecycle(&sig, &life)
755    }
756
757    pub fn deprecate(&self, stage_id: &str, reason: impl Into<String>) -> Result<(), StoreError> {
758        let (sig, mut life) = self.lookup_lifecycle(stage_id)?;
759        let cur = life
760            .status_of(stage_id)
761            .ok_or_else(|| StoreError::UnknownStage(stage_id.into()))?;
762        if cur != StageStatus::Active {
763            return Err(StoreError::InvalidTransition(format!(
764                "{cur:?} ⇒ Deprecated"
765            )));
766        }
767        life.transitions.push(Transition {
768            stage_id: stage_id.into(),
769            from: cur,
770            to: StageStatus::Deprecated,
771            at: Self::now(),
772            reason: Some(reason.into()),
773        });
774        self.write_lifecycle(&sig, &life)
775    }
776
777    pub fn tombstone(&self, stage_id: &str) -> Result<(), StoreError> {
778        let (sig, mut life) = self.lookup_lifecycle(stage_id)?;
779        let cur = life
780            .status_of(stage_id)
781            .ok_or_else(|| StoreError::UnknownStage(stage_id.into()))?;
782        if cur != StageStatus::Deprecated {
783            return Err(StoreError::InvalidTransition(format!(
784                "{cur:?} ⇒ Tombstone"
785            )));
786        }
787        life.transitions.push(Transition {
788            stage_id: stage_id.into(),
789            from: cur,
790            to: StageStatus::Tombstone,
791            at: Self::now(),
792            reason: None,
793        });
794        self.write_lifecycle(&sig, &life)
795    }
796
797    // ---- queries ----
798
799    /// The current Active StageId for a signature, or `None`.
800    pub fn resolve_sig(&self, sig: &str) -> Result<Option<String>, StoreError> {
801        let life = match self.read_lifecycle(sig) {
802            Ok(l) => l,
803            Err(_) => return Ok(None),
804        };
805        Ok(life.current_active().map(|s| s.to_string()))
806    }
807
808    /// Per-stage history for a SigId, ordered chronologically by
809    /// the *last* transition timestamp. Returns one entry per
810    /// distinct StageId that has ever been published under `sig`.
811    /// `Ok(vec![])` if the SigId doesn't exist in the store.
812    ///
813    /// Used by `lex blame` to render "where does this fn come from".
814    pub fn sig_history(&self, sig: &str) -> Result<Vec<StageHistoryEntry>, StoreError> {
815        let life = match self.read_lifecycle(sig) {
816            Ok(l) => l,
817            Err(_) => return Ok(Vec::new()),
818        };
819        // Collapse transitions: latest status + last_at per stage,
820        // plus the timestamp of the first Draft transition (≈ when
821        // the stage was published) when one exists.
822        let mut by_stage: indexmap::IndexMap<String, StageHistoryEntry> = indexmap::IndexMap::new();
823        for t in &life.transitions {
824            let entry = by_stage
825                .entry(t.stage_id.clone())
826                .or_insert(StageHistoryEntry {
827                    stage_id: t.stage_id.clone(),
828                    status: t.to,
829                    last_at: t.at,
830                    published_at: None,
831                });
832            entry.status = t.to;
833            entry.last_at = t.at;
834            if t.from == StageStatus::Draft && entry.published_at.is_none() {
835                entry.published_at = Some(t.at);
836            }
837            if t.to == StageStatus::Draft && entry.published_at.is_none() {
838                // Initial publication: Draft is the *destination*.
839                entry.published_at = Some(t.at);
840            }
841        }
842        let mut out: Vec<StageHistoryEntry> = by_stage.into_values().collect();
843        // Sort newest first so `lex blame` shows recent activity at top.
844        out.sort_by_key(|e| std::cmp::Reverse(e.last_at));
845        Ok(out)
846    }
847
848    pub fn get_ast(&self, stage_id: &str) -> Result<Stage, StoreError> {
849        let (sig, _) = self.lookup_lifecycle(stage_id)?;
850        let bytes = self.read_stage_canonical_bytes(&sig, stage_id)?;
851        Ok(serde_json::from_slice(&bytes)?)
852    }
853
854    /// Bulk AST fetch for callers that already know each stage's
855    /// **signature** — a branch head map, for instance, which is keyed
856    /// by SigId and whose values are the StageIds it points at.
857    ///
858    /// Prefer this over [`Self::get_asts_bulk`] whenever the SigId is in
859    /// hand, because resolving a StageId back to a SigId is not
860    /// reliable: a StageId hashes the structural signature plus the
861    /// implementation, deliberately *not* the name
862    /// (`docs/INVARIANTS.md`), so two functions that differ only in name
863    /// share one StageId while having two distinct SigIds — and two
864    /// separate ASTs, one under each sig directory. `stage_index` maps
865    /// each StageId to a single sig, so `get_ast`/`get_asts_bulk` return
866    /// whichever of those ASTs the index happens to name, i.e. the wrong
867    /// name half the time (#826). Reading straight from the sig the
868    /// caller already knows removes the ambiguity — and skips loading
869    /// the index at all.
870    ///
871    /// Returns results in the same order as `pairs`, `Err` for anything
872    /// that fails to resolve (mirroring `get_ast`'s error semantics).
873    pub fn get_asts_for_sigs_bulk(
874        &self,
875        pairs: &[(String, String)],
876    ) -> Vec<Result<Stage, StoreError>> {
877        pairs
878            .iter()
879            .map(|(sig_id, stage_id)| {
880                let bytes = self.read_stage_canonical_bytes(sig_id, stage_id)?;
881                Ok(serde_json::from_slice(&bytes)?)
882            })
883            .collect()
884    }
885
886    /// Bulk variant of [`Self::get_ast`] for callers resolving many
887    /// stage_ids at once (e.g. `pkg_publish_handler`'s `old_head`
888    /// scan over every live function in a tenant, once per publish
889    /// request). `get_ast` in a loop calls `lookup_lifecycle` once
890    /// per stage_id, and `lookup_lifecycle`'s index-hit path reads
891    /// and re-parses the *entire* `stage_index.jsonl` on every single
892    /// call — fine for one call, but O(index size × N) for N calls in
893    /// a row, which dominates once the index itself is large (#825's
894    /// follow-up: still correct and far better than the pre-index
895    /// full-tenant-scan-per-call behavior, but the per-call reparse
896    /// is itself a real, measured cost — 87.6s for 3,664 calls against
897    /// a ~14k-line index on the alpibrusl tenant).
898    ///
899    /// This loads the index once for the whole batch and keeps it in
900    /// memory across all `stage_ids`, only touching disk again to
901    /// append genuinely new entries (a positive backfill or a
902    /// negative "not found anywhere" cache, same as the single-call
903    /// path) — never to re-read what's already loaded.
904    ///
905    /// Returns results in the same order as `stage_ids`, `Err` for
906    /// anything that fails to resolve (mirroring `get_ast`'s error
907    /// semantics per call).
908    pub fn get_asts_bulk(&self, stage_ids: &[String]) -> Vec<Result<Stage, StoreError>> {
909        let mut index = self.load_stage_index();
910        let mut sigs_cache: BTreeMap<String, Option<Lifecycle>> = BTreeMap::new();
911        let mut all_sigs: Option<Vec<String>> = None;
912
913        stage_ids
914            .iter()
915            .map(|stage_id| {
916                self.lookup_lifecycle_bulk(stage_id, &mut index, &mut sigs_cache, &mut all_sigs)
917                    .and_then(|sig| {
918                        let bytes = self.read_stage_canonical_bytes(&sig, stage_id)?;
919                        Ok(serde_json::from_slice(&bytes)?)
920                    })
921            })
922            .collect()
923    }
924
925    /// Shared implementation behind [`Self::get_asts_bulk`]: identical
926    /// logic to [`Self::lookup_lifecycle`], but reads and writes the
927    /// caller-supplied `index` map instead of reloading it from disk
928    /// on every call, and memoizes `read_lifecycle` per sig and the
929    /// `list_sigs()` full-scan list across the whole batch. Disk
930    /// writes for newly-discovered entries (positive or negative)
931    /// still happen immediately, same as the single-call path — only
932    /// the repeated *reads* are batched away.
933    fn lookup_lifecycle_bulk(
934        &self,
935        stage_id: &str,
936        index: &mut BTreeMap<String, String>,
937        sigs_cache: &mut BTreeMap<String, Option<Lifecycle>>,
938        all_sigs: &mut Option<Vec<String>>,
939    ) -> Result<String, StoreError> {
940        if let Some(sig) = index.get(stage_id) {
941            if sig == MISSING_STAGE_MARKER {
942                return Err(StoreError::UnknownStage(stage_id.into()));
943            }
944            let life = sigs_cache
945                .entry(sig.clone())
946                .or_insert_with(|| self.read_lifecycle(sig).ok());
947            if let Some(life) = life {
948                if life.transitions.iter().any(|t| t.stage_id == stage_id) {
949                    return Ok(sig.clone());
950                }
951            }
952        }
953        if all_sigs.is_none() {
954            *all_sigs = Some(self.list_sigs()?);
955        }
956        for sig in all_sigs.as_ref().unwrap() {
957            let life = sigs_cache
958                .entry(sig.clone())
959                .or_insert_with(|| self.read_lifecycle(sig).ok());
960            if let Some(life) = life {
961                if life.transitions.iter().any(|t| t.stage_id == stage_id) {
962                    self.append_stage_index_entry(stage_id, sig);
963                    index.insert(stage_id.to_string(), sig.clone());
964                    return Ok(sig.clone());
965                }
966            }
967        }
968        self.append_stage_index_entry(stage_id, MISSING_STAGE_MARKER);
969        index.insert(stage_id.to_string(), MISSING_STAGE_MARKER.to_string());
970        Err(StoreError::UnknownStage(stage_id.into()))
971    }
972
973    /// Read the canonical bytes of a stage, walking back through
974    /// any delta chain (#261 slice 3). The recursion ends at a
975    /// `<stage_id>.ast.json` file (a full snapshot) or, in the
976    /// degenerate case of a missing chain, with `UnknownStage`.
977    fn read_stage_canonical_bytes(&self, sig: &str, stage_id: &str) -> Result<Vec<u8>, StoreError> {
978        let ast_path = self.impl_dir(sig).join(format!("{}.ast.json", stage_id));
979        if ast_path.exists() {
980            return Ok(fs::read(&ast_path)?);
981        }
982        let delta_path = self.impl_dir(sig).join(format!("{}.delta.json", stage_id));
983        if !delta_path.exists() {
984            return Err(StoreError::UnknownStage(stage_id.into()));
985        }
986        let delta_bytes = fs::read(&delta_path)?;
987        let delta: crate::delta::StageDelta = serde_json::from_slice(&delta_bytes)?;
988        let base_bytes = self.read_stage_canonical_bytes(sig, &delta.base_stage_id)?;
989        crate::delta::apply(&base_bytes, &delta).map_err(|e| {
990            StoreError::Io(std::io::Error::new(
991                std::io::ErrorKind::InvalidData,
992                format!("applying delta for {stage_id}: {e}"),
993            ))
994        })
995    }
996
997    /// Persist a freshly-published stage's canonical bytes (#261
998    /// slice 3). Tries delta encoding against the most recent
999    /// prior stage in the sig's lifecycle; falls back to a full
1000    /// snapshot when no base exists, the diff ratio is too high,
1001    /// or the delta chain is already at its cap.
1002    fn persist_stage_bytes(
1003        &self,
1004        sig: &str,
1005        stage_id: &str,
1006        stage: &Stage,
1007        ast_path: &Path,
1008        delta_path: &Path,
1009    ) -> Result<(), StoreError> {
1010        let new_bytes = canonical_bytes(stage)?;
1011        if let Some((base_stage_id, base_chain_length)) = self.pick_delta_base(sig, stage_id)? {
1012            let base_bytes = self.read_stage_canonical_bytes(sig, &base_stage_id)?;
1013            let (prefix, suffix, middle) = crate::delta::splice(&base_bytes, &new_bytes);
1014            let chain_length = base_chain_length + 1;
1015            if crate::delta::is_worth_encoding(middle.len(), new_bytes.len(), chain_length) {
1016                let delta = crate::delta::StageDelta {
1017                    base_stage_id,
1018                    chain_length,
1019                    common_prefix: prefix,
1020                    common_suffix: suffix,
1021                    middle_hex: hex::encode(&middle),
1022                };
1023                write_canonical_json(delta_path, &delta)?;
1024                return Ok(());
1025            }
1026        }
1027        // Fall through: full snapshot.
1028        if let Some(parent) = ast_path.parent() {
1029            fs::create_dir_all(parent)?;
1030        }
1031        fs::write(ast_path, &new_bytes)?;
1032        Ok(())
1033    }
1034
1035    /// Pick a base stage for delta encoding from the given sig's
1036    /// lifecycle. Returns `(base_stage_id, base_chain_length)` for
1037    /// the most-recent non-tombstoned prior stage, or `None` when
1038    /// there is no candidate. The chain length is read off the
1039    /// base's `.delta.json` (if any) to enforce the cap.
1040    fn pick_delta_base(
1041        &self,
1042        sig: &str,
1043        new_stage_id: &str,
1044    ) -> Result<Option<(String, usize)>, StoreError> {
1045        let life = self.read_lifecycle(sig).ok();
1046        let Some(life) = life else {
1047            return Ok(None);
1048        };
1049        // Walk transitions newest-first; pick the first prior
1050        // stage that isn't this one and isn't tombstoned.
1051        let mut latest_per_stage: indexmap::IndexMap<&str, StageStatus> = indexmap::IndexMap::new();
1052        for t in &life.transitions {
1053            latest_per_stage.insert(&t.stage_id, t.to);
1054        }
1055        let mut candidates: Vec<&str> = latest_per_stage
1056            .iter()
1057            .filter(|(id, status)| **id != new_stage_id && **status != StageStatus::Tombstone)
1058            .map(|(id, _)| *id)
1059            .collect();
1060        // Reverse to get newest-first (transitions are append-only,
1061        // so latest_per_stage's iteration order matches insertion
1062        // order, oldest-first).
1063        candidates.reverse();
1064        let Some(&base) = candidates.first() else {
1065            return Ok(None);
1066        };
1067        let base_chain_length = self.delta_chain_length(sig, base)?;
1068        Ok(Some((base.to_string(), base_chain_length)))
1069    }
1070
1071    /// Length of the delta chain ending at `stage_id`. Zero when
1072    /// the stage is a full snapshot (`.ast.json` present); the
1073    /// stored `chain_length` from `.delta.json` otherwise.
1074    fn delta_chain_length(&self, sig: &str, stage_id: &str) -> Result<usize, StoreError> {
1075        let ast_path = self.impl_dir(sig).join(format!("{}.ast.json", stage_id));
1076        if ast_path.exists() {
1077            return Ok(0);
1078        }
1079        let delta_path = self.impl_dir(sig).join(format!("{}.delta.json", stage_id));
1080        if !delta_path.exists() {
1081            return Ok(0);
1082        }
1083        let bytes = fs::read(&delta_path)?;
1084        let delta: crate::delta::StageDelta = serde_json::from_slice(&bytes)?;
1085        Ok(delta.chain_length)
1086    }
1087
1088    pub fn get_metadata(&self, stage_id: &str) -> Result<Metadata, StoreError> {
1089        let (sig, _) = self.lookup_lifecycle(stage_id)?;
1090        let path = self
1091            .impl_dir(&sig)
1092            .join(format!("{}.metadata.json", stage_id));
1093        let bytes = fs::read(&path)?;
1094        Ok(serde_json::from_slice(&bytes)?)
1095    }
1096
1097    pub fn get_status(&self, stage_id: &str) -> Result<StageStatus, StoreError> {
1098        let (_sig, life) = self.lookup_lifecycle(stage_id)?;
1099        life.status_of(stage_id)
1100            .ok_or_else(|| StoreError::UnknownStage(stage_id.into()))
1101    }
1102
1103    pub fn list_stages_by_name(&self, name: &str) -> Result<Vec<String>, StoreError> {
1104        // Walk every SigId → check metadata of any implementation; if its
1105        // name matches, include the SigId.
1106        let mut out = Vec::new();
1107        let stages_dir = self.root.join("stages");
1108        if !stages_dir.exists() {
1109            return Ok(out);
1110        }
1111        for entry in fs::read_dir(&stages_dir)? {
1112            let entry = entry?;
1113            let sig_dir = entry.path();
1114            if !sig_dir.is_dir() {
1115                continue;
1116            }
1117            let sig = entry.file_name().to_string_lossy().to_string();
1118            // Look at any one metadata file under this SigId.
1119            let impls = self.impl_dir(&sig);
1120            if !impls.exists() {
1121                continue;
1122            }
1123            for f in fs::read_dir(impls)? {
1124                let f = f?;
1125                let p = f.path();
1126                if p.extension().is_some_and(|e| e == "json")
1127                    && p.file_name()
1128                        .is_some_and(|n| n.to_string_lossy().ends_with(".metadata.json"))
1129                {
1130                    if let Ok(bytes) = fs::read(&p) {
1131                        if let Ok(m) = serde_json::from_slice::<Metadata>(&bytes) {
1132                            if m.name == name {
1133                                if !out.contains(&sig) {
1134                                    out.push(sig.clone());
1135                                }
1136                                break;
1137                            }
1138                        }
1139                    }
1140                }
1141            }
1142        }
1143        out.sort();
1144        Ok(out)
1145    }
1146
1147    pub fn list_sigs(&self) -> Result<Vec<String>, StoreError> {
1148        let stages_dir = self.root.join("stages");
1149        let mut out = Vec::new();
1150        if !stages_dir.exists() {
1151            return Ok(out);
1152        }
1153        for entry in fs::read_dir(stages_dir)? {
1154            let entry = entry?;
1155            if entry.file_type()?.is_dir() {
1156                out.push(entry.file_name().to_string_lossy().to_string());
1157            }
1158        }
1159        out.sort();
1160        Ok(out)
1161    }
1162
1163    // ---- tests/specs as metadata (§4.4) ----
1164
1165    pub fn attach_test(&self, sig: &str, test: &Test) -> Result<String, StoreError> {
1166        if !self.sig_dir(sig).exists() {
1167            return Err(StoreError::UnknownSig(sig.into()));
1168        }
1169        fs::create_dir_all(self.tests_dir(sig))?;
1170        let path = self.tests_dir(sig).join(format!("{}.json", test.id));
1171        write_canonical_json(&path, test)?;
1172        Ok(test.id.clone())
1173    }
1174
1175    pub fn list_tests(&self, sig: &str) -> Result<Vec<Test>, StoreError> {
1176        let dir = self.tests_dir(sig);
1177        if !dir.exists() {
1178            return Ok(Vec::new());
1179        }
1180        let mut out = Vec::new();
1181        for f in fs::read_dir(dir)? {
1182            let f = f?;
1183            if f.path().extension().is_some_and(|e| e == "json") {
1184                let bytes = fs::read(f.path())?;
1185                out.push(serde_json::from_slice(&bytes)?);
1186            }
1187        }
1188        Ok(out)
1189    }
1190
1191    pub fn attach_spec(&self, sig: &str, spec: &Spec) -> Result<String, StoreError> {
1192        if !self.sig_dir(sig).exists() {
1193            return Err(StoreError::UnknownSig(sig.into()));
1194        }
1195        fs::create_dir_all(self.specs_dir(sig))?;
1196        let path = self.specs_dir(sig).join(format!("{}.json", spec.id));
1197        write_canonical_json(&path, spec)?;
1198        Ok(spec.id.clone())
1199    }
1200
1201    pub fn list_specs(&self, sig: &str) -> Result<Vec<Spec>, StoreError> {
1202        let dir = self.specs_dir(sig);
1203        if !dir.exists() {
1204            return Ok(Vec::new());
1205        }
1206        let mut out = Vec::new();
1207        for f in fs::read_dir(dir)? {
1208            let f = f?;
1209            if f.path().extension().is_some_and(|e| e == "json") {
1210                let bytes = fs::read(f.path())?;
1211                out.push(serde_json::from_slice(&bytes)?);
1212            }
1213        }
1214        Ok(out)
1215    }
1216
1217    // ---- traces (§4.2 / M7) ----
1218
1219    // Native run-trace store — gated behind the `trace` feature (depends on
1220    // lex-trace). Off when a lower crate (lex-runtime) depends on lex-store to
1221    // avoid a dependency cycle; the blob/stage store below is unaffected.
1222    #[cfg(feature = "trace")]
1223    fn trace_path(&self, run_id: &str) -> PathBuf {
1224        self.root.join("traces").join(run_id).join("trace.json")
1225    }
1226
1227    #[cfg(feature = "trace")]
1228    pub fn save_trace(&self, tree: &lex_trace::TraceTree) -> Result<String, StoreError> {
1229        let path = self.trace_path(&tree.run_id);
1230        write_canonical_json(&path, tree)?;
1231        Ok(tree.run_id.clone())
1232    }
1233
1234    #[cfg(feature = "trace")]
1235    pub fn load_trace(&self, run_id: &str) -> Result<lex_trace::TraceTree, StoreError> {
1236        let bytes = fs::read(self.trace_path(run_id))?;
1237        Ok(serde_json::from_slice(&bytes)?)
1238    }
1239
1240    pub fn list_traces(&self) -> Result<Vec<String>, StoreError> {
1241        let dir = self.root.join("traces");
1242        if !dir.exists() {
1243            return Ok(Vec::new());
1244        }
1245        let mut out = Vec::new();
1246        for entry in fs::read_dir(dir)? {
1247            let entry = entry?;
1248            if entry.file_type()?.is_dir() {
1249                out.push(entry.file_name().to_string_lossy().to_string());
1250            }
1251        }
1252        out.sort();
1253        Ok(out)
1254    }
1255
1256    // ---- internals ----
1257
1258    /// `<root>/stage_index.jsonl` — an append-only, best-effort
1259    /// reverse index (`StageId` -> owning `SigId`), one JSON object
1260    /// per line. Backs `lookup_lifecycle`'s fast path; see its doc
1261    /// comment. Not a second source of truth: every entry is
1262    /// reconstructible from `stages/<sig>/lifecycle.json`, so a
1263    /// missing, truncated, or entirely absent index file only costs
1264    /// a slower lookup (the pre-existing full scan), never
1265    /// correctness — matching this module's "filesystem is the
1266    /// source of truth" stance (see the module doc comment) rather
1267    /// than introducing an actual second database.
1268    fn stage_index_path(&self) -> PathBuf {
1269        self.root.join("stage_index.jsonl")
1270    }
1271
1272    /// Best-effort load of the whole reverse index into memory.
1273    /// Tolerates a missing file (no index yet) and a corrupt or
1274    /// torn last line (a crash mid-append under the single-writer
1275    /// Tier-1 assumption) by skipping lines that don't parse,
1276    /// rather than failing the lookup that triggered the load.
1277    fn load_stage_index(&self) -> std::collections::BTreeMap<String, String> {
1278        let mut out = std::collections::BTreeMap::new();
1279        let Ok(raw) = fs::read_to_string(self.stage_index_path()) else {
1280            return out;
1281        };
1282        for line in raw.lines() {
1283            if let Ok(entry) = serde_json::from_str::<StageIndexEntry>(line) {
1284                out.insert(entry.stage_id, entry.sig_id);
1285            }
1286        }
1287        out
1288    }
1289
1290    /// Best-effort append of one new `(stage_id, sig_id)` pair.
1291    /// Failure (e.g. a read-only filesystem) only costs a future
1292    /// full scan for this stage_id, never correctness, so it's
1293    /// swallowed rather than propagated.
1294    fn append_stage_index_entry(&self, stage_id: &str, sig: &str) {
1295        use std::io::Write;
1296        let entry = StageIndexEntry { stage_id: stage_id.into(), sig_id: sig.into() };
1297        let Ok(line) = serde_json::to_string(&entry) else { return };
1298        if let Ok(mut f) = fs::OpenOptions::new()
1299            .create(true)
1300            .append(true)
1301            .open(self.stage_index_path())
1302        {
1303            let _ = writeln!(f, "{line}");
1304        }
1305    }
1306
1307    /// Find which SigId owns a StageId, and that sig's lifecycle.
1308    ///
1309    /// Before the reverse index (#822): a full scan over *every*
1310    /// SigId in the tenant (`list_sigs()`, not scoped to the
1311    /// package being looked at), reading and parsing each one's
1312    /// `lifecycle.json` until a match turned up. `get_ast` — called
1313    /// once per pre-existing function when building a publish
1314    /// request's `old_fns_by_name` (`lex-api/src/handlers.rs`) —
1315    /// calls this once per function, so a tenant with a few thousand
1316    /// published functions turned a single publish into millions of
1317    /// individual file reads; measured at roughly an hour on the
1318    /// `alpibrusl` tenant's ~2,400-function store.
1319    ///
1320    /// Now: check the persisted reverse index first (one sequential
1321    /// file read instead of up to N separate ones). A miss — the
1322    /// index doesn't exist yet, or this stage_id predates it — falls
1323    /// back to the full scan and backfills the index so the next
1324    /// lookup for the same stage_id is fast.
1325    fn lookup_lifecycle(&self, stage_id: &str) -> Result<(String, Lifecycle), StoreError> {
1326        let index = self.load_stage_index();
1327        if let Some(sig) = index.get(stage_id) {
1328            if sig == MISSING_STAGE_MARKER {
1329                // A previous full scan already established this
1330                // stage_id exists nowhere in the store. Re-scanning
1331                // would find nothing again -- see #825: a genuinely
1332                // orphaned reference (e.g. from data predating some
1333                // store migration) is looked up on *every* call that
1334                // needs it, forever, so without this negative cache
1335                // it silently costs a full O(total sigs) scan each
1336                // time, indistinguishable from the positive case at
1337                // the call site. Measured directly: on the alpibrusl
1338                // tenant, 988 of 3,664 branch-head entries are
1339                // orphaned this way, turning one `pkg publish`'s
1340                // old_fns_by_name build into ~16M wasted lifecycle
1341                // reads.
1342                return Err(StoreError::UnknownStage(stage_id.into()));
1343            }
1344            if let Ok(life) = self.read_lifecycle(sig) {
1345                if life.transitions.iter().any(|t| t.stage_id == stage_id) {
1346                    return Ok((sig.clone(), life));
1347                }
1348            }
1349            // Index entry is stale or wrong (shouldn't happen in
1350            // practice — sig ownership of a stage_id is permanent).
1351            // Fall through to the full scan below rather than trust it.
1352        }
1353        for sig in self.list_sigs()? {
1354            if let Ok(life) = self.read_lifecycle(&sig) {
1355                if life.transitions.iter().any(|t| t.stage_id == stage_id) {
1356                    self.append_stage_index_entry(stage_id, &sig);
1357                    return Ok((sig, life));
1358                }
1359            }
1360        }
1361        // Genuinely not found anywhere: cache that fact so the next
1362        // lookup for this exact stage_id is an index hit, not another
1363        // full scan. Safe even if this stage_id somehow gets a real
1364        // sig later (content-addressed publish is idempotent, so
1365        // "later" only means "a byte-identical stage republished
1366        // under a real sig") — `append_stage_index_entry`'s later,
1367        // real entry is a later line in the file, and `load_stage_index`
1368        // folds duplicate keys last-write-wins, so the real entry wins.
1369        self.append_stage_index_entry(stage_id, MISSING_STAGE_MARKER);
1370        Err(StoreError::UnknownStage(stage_id.into()))
1371    }
1372
1373    fn read_lifecycle(&self, sig: &str) -> Result<Lifecycle, StoreError> {
1374        let path = self.lifecycle_path(sig);
1375        if !path.exists() {
1376            return Ok(Lifecycle {
1377                sig_id: sig.into(),
1378                transitions: Vec::new(),
1379            });
1380        }
1381        let bytes = fs::read(&path)?;
1382        Ok(serde_json::from_slice(&bytes)?)
1383    }
1384
1385    fn write_lifecycle(&self, sig: &str, life: &Lifecycle) -> Result<(), StoreError> {
1386        write_canonical_json(&self.lifecycle_path(sig), life)
1387    }
1388
1389    /// Apply a published program to a branch as a sequence of typed
1390    /// operations. Returns the ordered list of op_ids + the new
1391    /// head_op. The caller (`lex publish` CLI, `lex serve`'s HTTP
1392    /// handler) is responsible for computing the `DiffReport` against
1393    /// the current branch head — the diff infrastructure lives in
1394    /// `lex-vcs::compute_diff` (previously `lex-cli`) to keep this
1395    /// layer from owning diffing logic.
1396    ///
1397    /// On success: every op in the returned list is durable in the
1398    /// op log and the branch's head_op points at the last one.
1399    /// On a no-op (no diff): returns empty `ops` and the existing
1400    /// `head_op` unchanged.
1401    pub fn publish_program(
1402        &self,
1403        branch: &str,
1404        stages: &[lex_ast::Stage],
1405        diff: &lex_vcs::DiffReport,
1406        new_imports: &lex_vcs::ImportMap,
1407        activate: bool,
1408    ) -> Result<PublishOutcome, StoreError> {
1409        self.publish_program_signed(branch, stages, diff, new_imports, activate, None)
1410    }
1411
1412    /// Signed variant of [`Self::publish_program`] (#227). Every
1413    /// stage written under this batch gets the same signer; per-stage
1414    /// keys aren't supported because the agent identity model treats
1415    /// a publish as a single authorial act.
1416    pub fn publish_program_signed(
1417        &self,
1418        branch: &str,
1419        stages: &[lex_ast::Stage],
1420        diff: &lex_vcs::DiffReport,
1421        new_imports: &lex_vcs::ImportMap,
1422        activate: bool,
1423        signer: Option<&lex_vcs::Keypair>,
1424    ) -> Result<PublishOutcome, StoreError> {
1425        // Single-file / test callers don't publish a mangled package, so
1426        // there are no module prefixes to record (`in_file` stays `None`).
1427        self.publish_program_with_intent(
1428            branch,
1429            stages,
1430            diff,
1431            new_imports,
1432            activate,
1433            signer,
1434            None,
1435            &std::collections::BTreeMap::new(),
1436        )
1437    }
1438
1439    /// [`Self::publish_program_signed`] plus an optional `intent_id`
1440    /// (#131 / #839): when given, every op this publish emits is stamped
1441    /// with it, so the op log records *why* the change happened — the
1442    /// prompt / model / session an agent was acting under — not only
1443    /// what it was. `lex recall --intent <id>` and `lex op replay` read
1444    /// it back. The caller records the [`lex_vcs::Intent`] in the
1445    /// [`lex_vcs::IntentLog`] beforehand; this only links ops to it.
1446    /// `None` is the existing (intent-less) behavior, so op ids for
1447    /// intent-less publishes are unchanged.
1448    // A batch publish legitimately takes the branch, program, diff,
1449    // imports, activate flag, signer, and now the intent — bundling
1450    // them into a struct for one optional field would obscure more
1451    // than it clarifies.
1452    #[allow(clippy::too_many_arguments)]
1453    pub fn publish_program_with_intent(
1454        &self,
1455        branch: &str,
1456        stages: &[lex_ast::Stage],
1457        diff: &lex_vcs::DiffReport,
1458        new_imports: &lex_vcs::ImportMap,
1459        activate: bool,
1460        signer: Option<&lex_vcs::Keypair>,
1461        intent_id: Option<lex_vcs::IntentId>,
1462        // Mangling prefix → package source file, for a multi-module
1463        // package publish; empty for a single file. Recorded as each
1464        // `AddFunction`/`AddType`'s `in_file` so `export-git` can
1465        // de-flatten the package (#894).
1466        module_prefixes: &std::collections::BTreeMap<String, String>,
1467    ) -> Result<PublishOutcome, StoreError> {
1468        use std::collections::{BTreeMap, BTreeSet};
1469
1470        // #130's write-time gate: verify the candidate program
1471        // typechecks (and effects are correctly declared) before
1472        // any disk side-effect. If anything fails, return the
1473        // structured envelope and leave the branch head unchanged
1474        // — the store's "always-valid HEAD" invariant only holds
1475        // because this is the only batch-publish path that
1476        // advances heads. Single-op writes via the lower-level
1477        // `apply_operation` are not gated yet (#130 follow-up).
1478        // #930: resolve any external dependency edges the head keeps
1479        // (empty when no resolver is installed or the head is inlined).
1480        let modules = self.resolved_modules(stages, None);
1481        let module_types = self.resolved_module_types(stages, None);
1482        let dep_prefixes = self.resolved_module_prefixes(stages, None);
1483        if let Err(errors) = lex_types::check_program_with_deps(stages, &modules, &module_types, &dep_prefixes) {
1484            return Err(StoreError::TypeError(errors));
1485        }
1486
1487        // Build old-side views from the current branch. There used to be
1488        // an `old_name_to_sig: BTreeMap<String, SigId>` built here too,
1489        // keyed by bare function name — but a bare name is not unique
1490        // across a package's files (#818: two files can legitimately
1491        // both declare a local `validate` helper with different
1492        // signatures), so a name-keyed map silently collapsed distinct
1493        // SigIds onto one. `diff` now carries each entry's own resolved
1494        // `old_sig_id` directly (see `diff_report`'s doc comments), so
1495        // `diff_to_ops` no longer needs this lookup at all.
1496        let old_head = self.branch_head(branch)?;
1497        // Read every live function's effects through the SigId the head
1498        // names, in one batch. Two reasons, both load-bearing:
1499        //
1500        //   * Cost. This was a `get_ast` per live function, and
1501        //     `get_ast`'s index-hit path re-reads and re-parses the whole
1502        //     `stage_index.jsonl` on every call — O(index × live fns) per
1503        //     publish, paid again for every `publish_program` call a
1504        //     multi-file publish makes (#828; measured 34s for a no-op
1505        //     republish of a real 21-file package against only 698 live
1506        //     functions, nearly all of it here).
1507        //   * Correctness. A StageId is name-independent, so two live
1508        //     functions differing only in name share one and the index
1509        //     maps it to a single sig — resolving by StageId therefore
1510        //     attributed one function's effects to the *other* one's sig,
1511        //     the same ambiguity #826 fixed in `pkg_publish_handler`.
1512        let head_pairs: Vec<(String, String)> = old_head
1513            .iter()
1514            .map(|(sig, stage)| (sig.clone(), stage.clone()))
1515            .collect();
1516        let old_effects: BTreeMap<String, BTreeSet<String>> = head_pairs
1517            .iter()
1518            .zip(self.get_asts_for_sigs_bulk(&head_pairs))
1519            .filter_map(|((sig, _), ast)| match ast.ok()? {
1520                lex_ast::Stage::FnDecl(fd) => {
1521                    let s: BTreeSet<String> =
1522                        fd.effects.iter().map(|e| e.name.clone()).collect();
1523                    Some((sig.clone(), s))
1524                }
1525                _ => None,
1526            })
1527            .collect();
1528        let old_imports = self.derive_imports_from_oplog(branch)?;
1529
1530        let op_kinds = lex_vcs::diff_to_ops(lex_vcs::DiffInputs {
1531            old_head: &old_head,
1532            old_effects: &old_effects,
1533            old_imports: &old_imports,
1534            new_stages: stages,
1535            new_imports,
1536            diff,
1537            module_prefixes,
1538        })
1539        .map_err(|e| StoreError::InvalidTransition(format!("diff_to_ops: {e}")))?;
1540
1541        let mut ops_out: Vec<PublishOp> = Vec::new();
1542        let mut last_op_id: Option<lex_vcs::OpId> = None;
1543        for kind in op_kinds {
1544            // Persist the underlying stage AST/metadata if this op
1545            // produces or replaces one.
1546            if let Some(stg) = stage_for_kind(&kind, stages) {
1547                if !matches!(stg, lex_ast::Stage::Import(_)) {
1548                    self.publish_signed(stg, signer)?;
1549                    if activate {
1550                        if let Some(stage_id_str) = stage_id(stg) {
1551                            let _ = self.activate(&stage_id_str);
1552                        }
1553                    }
1554                }
1555            }
1556            let transition = transition_for_kind(&kind);
1557            let attestable = attestable_stage_ids(&transition);
1558            let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
1559            let op =
1560                lex_vcs::Operation::new(kind.clone(), head_now.into_iter().collect::<Vec<_>>());
1561            // #131 / #839: stamp the caller's intent so the op log records
1562            // why this change happened, not just what it was. The CAS
1563            // retry path preserves `intent_id` when it rebuilds the op.
1564            let op = match &intent_id {
1565                Some(id) => op.with_intent(id.clone()),
1566                None => op,
1567            };
1568            let op_id = self.apply_operation(branch, op, transition)?;
1569            self.record_typecheck_passed(&attestable, &op_id)?;
1570            ops_out.push(PublishOp {
1571                op_id: op_id.clone(),
1572                kind: serde_json::to_value(&kind).map_err(StoreError::Serde)?,
1573            });
1574            last_op_id = Some(op_id);
1575        }
1576
1577        let head_op = match last_op_id {
1578            Some(id) => Some(id),
1579            // No ops applied; return whatever the head was already.
1580            None => self.get_branch(branch)?.and_then(|b| b.head_op),
1581        };
1582
1583        Ok(PublishOutcome {
1584            ops: ops_out,
1585            head_op,
1586        })
1587    }
1588
1589    pub fn derive_imports_from_oplog(
1590        &self,
1591        branch: &str,
1592    ) -> Result<lex_vcs::ImportMap, StoreError> {
1593        use lex_vcs::OperationKind::*;
1594        let log = lex_vcs::OpLog::open(self.root())?;
1595        let head = match self.get_branch(branch)?.and_then(|b| b.head_op) {
1596            Some(h) => h,
1597            None => return Ok(Default::default()),
1598        };
1599        let mut out: lex_vcs::ImportMap = Default::default();
1600        for r in log.walk_forward(&head, None)? {
1601            match r.op.kind {
1602                AddImport { in_file, module, alias } => {
1603                    // The op omits the alias when it's the module's
1604                    // default (last path segment) to keep its OpId
1605                    // stable; rebuild it the same way on the way out.
1606                    let alias =
1607                        alias.unwrap_or_else(|| lex_vcs::default_import_alias(&module));
1608                    out.entry(in_file)
1609                        .or_default()
1610                        .insert(lex_vcs::ImportRef { reference: module, alias });
1611                }
1612                RemoveImport { in_file, module } => {
1613                    // Removal is keyed by reference (the op carries no
1614                    // alias), so drop any binding of that module.
1615                    if let Some(set) = out.get_mut(&in_file) {
1616                        set.retain(|ir| ir.reference != module);
1617                    }
1618                }
1619                _ => {}
1620            }
1621        }
1622        Ok(out)
1623    }
1624
1625    /// Apply an operation to a branch and advance its head_op.
1626    ///
1627    /// The single advance path. Validates parents via `lex_vcs::apply`,
1628    /// persists the operation via the op log, then atomically advances
1629    /// the branch file's head_op via `set_branch_head_op`.
1630    ///
1631    /// Errors:
1632    /// - `UnknownBranch`: branch does not exist (no op is persisted).
1633    /// - `Apply(ApplyError::StaleParent)`: the op's parents don't
1634    ///   match the branch head — head is unchanged. Callers that
1635    ///   want retry-on-stale (e.g. `lex publish` re-running against
1636    ///   a moved head) match on this variant explicitly.
1637    /// - `Apply(ApplyError::UnknownMergeParent)`: a merge op's
1638    ///   second parent isn't in the log.
1639    /// - `Io`: filesystem error during persist or branch advance.
1640    ///
1641    /// Crash recovery: between op persist and branch advance, a crash
1642    /// can leave an orphan op record in the log with no branch
1643    /// pointing at it. The op is content-addressed and cheap to
1644    /// re-derive from the same source. See
1645    /// Apply a single op against `branch`, gated on the candidate
1646    /// program typechecking. The per-op variant of #130's
1647    /// write-time gate — counterpart to [`Self::publish_program`]'s
1648    /// batch-mode check.
1649    ///
1650    /// `candidate` is the sequence of `Stage`s that *would* exist
1651    /// on this branch after the op is applied. Caller's
1652    /// responsibility: today neither `lex-store` nor `lex-vcs`
1653    /// reconstruct the candidate from the op + branch state on
1654    /// behalf of the caller. The natural callers (HTTP `POST
1655    /// /v1/publish` for a single op; agent harnesses driving
1656    /// merges via the future #134 API) already have the candidate
1657    /// in memory.
1658    ///
1659    /// On rejection: branch head unchanged, no op record persisted.
1660    /// Same atomicity guarantee as the publish path.
1661    ///
1662    /// # Why a separate method, not a flag on `apply_operation`
1663    ///
1664    /// `apply_operation` accepting `Option<&[Stage]>` and silently
1665    /// skipping the gate on `None` is exactly the kind of
1666    /// "secretly opt-out" path #130 is trying to remove. The honest
1667    /// split: `apply_operation` for the one caller that already
1668    /// typechecked its input up front (`publish_program`),
1669    /// `apply_operation_checked` for callers holding the candidate,
1670    /// [`Self::apply_operation_gated`] for single-parent callers
1671    /// that hold only the transition (`/v1/patch`), and
1672    /// [`Self::apply_merge_op_gated`] for merge commits (#833).
1673    pub fn apply_operation_checked(
1674        &self,
1675        branch: &str,
1676        op: lex_vcs::Operation,
1677        transition: lex_vcs::StageTransition,
1678        candidate: &[lex_ast::Stage],
1679    ) -> Result<lex_vcs::OpId, StoreError> {
1680        let modules = self.resolved_modules(candidate, None); // #930
1681        let module_types = self.resolved_module_types(candidate, None);
1682        let dep_prefixes = self.resolved_module_prefixes(candidate, None);
1683        if let Err(errors) = lex_types::check_program_with_deps(candidate, &modules, &module_types, &dep_prefixes) {
1684            // #281: emit a `RepairHint` attestation against each
1685            // candidate stage the transition was about to produce.
1686            // The op record itself isn't persisted (the gate is
1687            // pre-persistence), but the candidate stage IS — the
1688            // transform-flow methods publish before this call.
1689            // The attached hint lets `lex repair <op_id>` and
1690            // future LLM-assisted apply paths read the structured
1691            // errors without re-running the typecheck.
1692            let attestable = attestable_stage_ids(&transition);
1693            let failed_op_id = op.op_id();
1694            let _ = self.record_repair_hint(&attestable, &failed_op_id, &errors);
1695            return Err(StoreError::TypeError(errors));
1696        }
1697        // #292 slice 3: per-session budget gate. After typecheck
1698        // passes, refuse the op if it would push its session's
1699        // monotonic spend over the configured cap. Sessions
1700        // without an intent_id, or with an intent whose session
1701        // has no cap configured, sail through.
1702        self.check_session_budget(&op)?;
1703        let attestable = attestable_stage_ids(&transition);
1704        let op_effects = op_declared_effects(&op.kind);
1705        // #262: CAS retry loop. Single-parent ops can be safely
1706        // re-persisted under a new parent on contention (the kind
1707        // is invariant; only `parents` changes). Merge ops (already
1708        // 2-parent) come through the merge engine which has its own
1709        // coordination; we don't retry them here — we'll see the
1710        // first attempt's CAS fail and surface Contention.
1711        self.cas_retry_advance(branch, op, transition, |new_head| {
1712            self.record_typecheck_passed(&attestable, &new_head.op_id)?;
1713            self.run_required_attestations_gate(branch, &new_head.op_id, &attestable, &op_effects)
1714        })
1715    }
1716
1717    /// The program that would exist on `branch` after `transition`
1718    /// is applied: the branch head (snapshot-cached) with the
1719    /// transition replayed over it, every resulting `(sig, stage)`
1720    /// bulk-loaded. Exact for a **single-parent** transition — the
1721    /// candidate [`Self::apply_operation_gated`] wants. Not valid for
1722    /// a merge: a `StageTransition::Merge` records only the delta
1723    /// relative to dst, while the op-DAG replay that computes a
1724    /// merge's real head walks both parents (#833).
1725    pub fn candidate_program_for(
1726        &self,
1727        branch: &str,
1728        transition: &lex_vcs::StageTransition,
1729    ) -> Result<Vec<Stage>, StoreError> {
1730        let mut head = self.branch_head(branch)?;
1731        crate::branches::apply_transition(&mut head, transition);
1732        let pairs: Vec<(String, String)> = head.into_iter().collect();
1733        self.get_asts_for_sigs_bulk(&pairs).into_iter().collect()
1734    }
1735
1736    /// [`Self::apply_operation_checked`] for a **single-parent** op
1737    /// where the caller holds only the transition: assembles the
1738    /// candidate via [`Self::candidate_program_for`] and runs the
1739    /// gate. Same rejection semantics — `TypeError`, a `RepairHint`
1740    /// attestation, head unchanged, nothing persisted. This is the
1741    /// write path for `/v1/patch` (#833). Merge ops must not use it
1742    /// (see `candidate_program_for`); they go through
1743    /// [`Self::apply_merge_op_gated`].
1744    pub fn apply_operation_gated(
1745        &self,
1746        branch: &str,
1747        op: lex_vcs::Operation,
1748        transition: lex_vcs::StageTransition,
1749    ) -> Result<lex_vcs::OpId, StoreError> {
1750        debug_assert!(
1751            op.parents.len() <= 1,
1752            "apply_operation_gated is single-parent only; merges use apply_merge_op_gated"
1753        );
1754        let candidate = self.candidate_program_for(branch, &transition)?;
1755        self.apply_operation_checked(branch, op, transition, &candidate)
1756    }
1757
1758    /// The gated write path for **merge** commits (`commit_merge`,
1759    /// `POST /v1/merge/<id>/commit`, `lex merge commit`).
1760    ///
1761    /// A `StageTransition::Merge` records only the delta relative to
1762    /// dst; the sig->stage map every consumer reads is recomputed by
1763    /// replaying the op DAG, which for a merge walks *both* parents
1764    /// and can surface sigs the delta never mentions. So the only way
1765    /// to know the true post-merge program is to replay it — land the
1766    /// op and read `branch_head`. This lands the merge op,
1767    /// type-checks the resulting head, and on a failure rolls the
1768    /// head back and returns `TypeError`.
1769    ///
1770    /// Before #833 the merge paths landed through the ungated
1771    /// `apply_operation`, so a merge whose result didn't compose
1772    /// (e.g. dst still calls `helper`, an agent-supplied resolution
1773    /// dropped it) advanced the head with nothing to catch it.
1774    ///
1775    /// Rollback leaves the rejected merge op as an unreachable record
1776    /// (reclaimed by `lex op gc`, the same orphan crash-recovery
1777    /// already tolerates). A stage the merge names that was never
1778    /// published surfaces as the underlying `StoreError` from the
1779    /// bulk read — the "never advance onto content that can't be
1780    /// loaded" invariant from the other side.
1781    pub fn apply_merge_op_gated(
1782        &self,
1783        branch: &str,
1784        op: lex_vcs::Operation,
1785        transition: lex_vcs::StageTransition,
1786    ) -> Result<lex_vcs::OpId, StoreError> {
1787        let head_before = self.get_branch(branch)?.and_then(|b| b.head_op);
1788        // Capture the stages this merge introduces before `transition`
1789        // is moved into `apply_operation`; used for the TypeCheck
1790        // attestation below.
1791        let attestable = attestable_stage_ids(&transition);
1792        let op_id = self.apply_operation(branch, op, transition)?;
1793
1794        let verdict = (|| -> Result<(), StoreError> {
1795            let head = self.branch_head(branch)?;
1796            let pairs: Vec<(String, String)> = head.into_iter().collect();
1797            let stages: Vec<Stage> =
1798                self.get_asts_for_sigs_bulk(&pairs).into_iter().collect::<Result<_, _>>()?;
1799            // #930: per-head dep resolution for the merge path is a follow-up;
1800            // None lets a client resolver use its working-copy lock.
1801            let modules = self.resolved_modules(&stages, None);
1802            let module_types = self.resolved_module_types(&stages, None);
1803            let dep_prefixes = self.resolved_module_prefixes(&stages, None);
1804            if let Err(errors) = lex_types::check_program_with_deps(&stages, &modules, &module_types, &dep_prefixes) {
1805                return Err(StoreError::TypeError(errors));
1806            }
1807            Ok(())
1808        })();
1809
1810        if let Err(e) = verdict {
1811            // Roll the head back. The empty-dst case never reaches
1812            // here (it fast-forwards without a merge op), so
1813            // `head_before` is always `Some` on this arm.
1814            if let Some(prev) = head_before {
1815                self.set_branch_head_op(branch, prev)?;
1816            }
1817            return Err(e);
1818        }
1819        // #835: the merge's post-merge head type-checked, but until now
1820        // that verdict left no trace in the attestation log — so a
1821        // merged stage looked un-type-checked to `lex blame
1822        // --with-evidence` and the attestation queries, unlike a
1823        // published or patched stage. Emit `TypeCheck::Passed` for the
1824        // stages the merge introduced, mirroring the publish / patch
1825        // paths (`record_typecheck_passed`). Emitted only after the
1826        // check passes and the head is committed, so a rolled-back
1827        // merge records nothing.
1828        self.record_typecheck_passed(&attestable, &op_id)?;
1829        Ok(op_id)
1830    }
1831
1832    /// Type-check the program that would result from overlaying a merge
1833    /// `delta` onto `branch`'s current head — **without moving the
1834    /// head** (#834). `delta` maps `sig_id -> Some(stage)` to set that
1835    /// sig to `stage`, or `sig_id -> None` to remove it, exactly the
1836    /// `entries` a `StageTransition::Merge` records.
1837    ///
1838    /// This is the read-only, resolve-time counterpart of
1839    /// `apply_merge_op_gated`'s commit-time gate: it lets a merge
1840    /// session tell an agent *which resolution broke type-checking* the
1841    /// moment it is submitted, instead of only after a failed commit.
1842    /// `Ok(())` means the projected program composes; a type failure is
1843    /// `Err(StoreError::TypeError(..))`; a read failure is the
1844    /// corresponding `StoreError` I/O variant.
1845    pub fn typecheck_merge_projection(
1846        &self,
1847        branch: &str,
1848        delta: &std::collections::BTreeMap<String, Option<String>>,
1849    ) -> Result<(), StoreError> {
1850        let mut head = self.branch_head(branch)?;
1851        for (sig, stage) in delta {
1852            match stage {
1853                Some(s) => { head.insert(sig.clone(), s.clone()); }
1854                None => { head.remove(sig); }
1855            }
1856        }
1857        let pairs: Vec<(String, String)> = head.into_iter().collect();
1858        let stages: Vec<Stage> =
1859            self.get_asts_for_sigs_bulk(&pairs).into_iter().collect::<Result<_, _>>()?;
1860        let modules = self.resolved_modules(&stages, None); // #930 (patch path)
1861        let module_types = self.resolved_module_types(&stages, None);
1862        let dep_prefixes = self.resolved_module_prefixes(&stages, None);
1863        if let Err(errors) = lex_types::check_program_with_deps(&stages, &modules, &module_types, &dep_prefixes) {
1864            return Err(StoreError::TypeError(errors));
1865        }
1866        Ok(())
1867    }
1868
1869    /// #838: attempt a typed three-way merge of a single sig's body for
1870    /// a `ModifyModify` conflict — the intra-function, better-than-git
1871    /// case where two agents edited *disjoint* subtrees of the same
1872    /// function (different match arms, different let bindings).
1873    ///
1874    /// `base` / `ours` (the dst side) / `theirs` (the src side) are the
1875    /// three stage ids the merge engine surfaced for `sig_id`. Loads
1876    /// the three `FnDecl`s, structurally merges the bodies
1877    /// ([`lex_vcs::merge_bodies`]), and accepts the result *only if* the
1878    /// merged function also type-checks against `dst_branch`'s head — a
1879    /// body that composes syntactically but not by type is still a
1880    /// conflict (#838). On success the merged stage is published
1881    /// (content-addressed, idempotent; orphaned and GC-reclaimable if
1882    /// the merge is never committed) and its id returned; `None` means
1883    /// "fall back to a whole-function conflict."
1884    ///
1885    /// Deliberately narrow for this slice: only pure body divergence is
1886    /// merged. If the two sides disagree on anything but the body
1887    /// (examples, type params — the signature is identical by
1888    /// construction, since all three share `sig_id`), or either stage
1889    /// isn't a function, it falls back to a conflict.
1890    pub fn try_semantic_body_merge(
1891        &self,
1892        dst_branch: &str,
1893        sig_id: &str,
1894        base: &str,
1895        ours: &str,
1896        theirs: &str,
1897    ) -> Result<Option<String>, StoreError> {
1898        use lex_ast::Stage::FnDecl;
1899        let (base_fd, ours_fd, theirs_fd) =
1900            match (self.get_ast(base), self.get_ast(ours), self.get_ast(theirs)) {
1901                (Ok(FnDecl(b)), Ok(FnDecl(o)), Ok(FnDecl(t))) => (b, o, t),
1902                // A non-function stage (type decl / import) or a stage
1903                // that can't be loaded isn't an intra-body merge.
1904                _ => return Ok(None),
1905            };
1906
1907        // Only the body may diverge between the two sides.
1908        if !fndecl_same_except_body(&ours_fd, &theirs_fd) {
1909            return Ok(None);
1910        }
1911
1912        let merged_body =
1913            match lex_vcs::merge_bodies(&base_fd.body, &ours_fd.body, &theirs_fd.body) {
1914                lex_vcs::BodyMerge::Merged(b) => b,
1915                lex_vcs::BodyMerge::Conflict => return Ok(None),
1916            };
1917
1918        let mut merged_fd = ours_fd.clone();
1919        merged_fd.body = merged_body;
1920        let merged_stage = lex_ast::Stage::FnDecl(merged_fd);
1921        let new_stage_id = match stage_id(&merged_stage) {
1922            Some(id) => id,
1923            None => return Ok(None),
1924        };
1925
1926        // Type-check the merged fn in context: dst's head with this sig
1927        // swapped to the merged stage. Requires the merged stage to be
1928        // loadable, so publish first (idempotent, content-addressed).
1929        self.publish(&merged_stage)?;
1930        let mut delta = std::collections::BTreeMap::new();
1931        delta.insert(sig_id.to_string(), Some(new_stage_id.clone()));
1932        match self.typecheck_merge_projection(dst_branch, &delta) {
1933            Ok(()) => Ok(Some(new_stage_id)),
1934            // Composes syntactically, not by type → still a conflict.
1935            Err(StoreError::TypeError(_)) => Ok(None),
1936            Err(e) => Err(e),
1937        }
1938    }
1939
1940    /// #836 G3: assemble everything a regenerator needs to *replay* an
1941    /// op — re-derive the change from its recorded cause. Returns the
1942    /// op's recorded intent (prompt / model / session), the target sig
1943    /// and the stage id it produced, and the program the change was
1944    /// made against (the parent state, rendered to source). An external
1945    /// harness feeds the prompt + parent program to the recorded model,
1946    /// then hands the regenerated stage back to [`Self::replay_compare`]
1947    /// (lex owns the deterministic comparison; the model call is the
1948    /// harness's, matching the rest of the architecture).
1949    ///
1950    /// Errors with `UnknownOp` if the op_id is unknown, or
1951    /// `InvalidTransition` if the op didn't produce a stage (a removal /
1952    /// import / merge has nothing to regenerate).
1953    pub fn replay_request(&self, op_id: &str) -> Result<ReplayRequest, StoreError> {
1954        let log = lex_vcs::OpLog::open(self.root())?;
1955        let record = log
1956            .get(&op_id.to_string())?
1957            .ok_or_else(|| StoreError::UnknownOp(op_id.to_string()))?;
1958        let (target_sig, expected_stage_id) = produced_sig_stage(&record.produces)
1959            .ok_or_else(|| StoreError::InvalidTransition(format!("op {op_id} produced no stage to replay")))?;
1960
1961        let (prompt, model, session_id) = match &record.op.intent_id {
1962            Some(id) => {
1963                let intents = lex_vcs::IntentLog::open(self.root())?;
1964                match intents.get(id)? {
1965                    Some(i) => (Some(i.prompt), Some(model_label(&i.model)), Some(i.session_id)),
1966                    None => (None, None, None),
1967                }
1968            }
1969            None => (None, None, None),
1970        };
1971
1972        // The program the op was applied against: the head state at its
1973        // (first) parent, rendered with the canonical printer. A root
1974        // op has no parent → empty program.
1975        let parent_program = match record.op.parents.first() {
1976            Some(parent) => self.program_source_at_op(parent)?,
1977            None => String::new(),
1978        };
1979
1980        // The target function's name + signature, from the recorded
1981        // stage — a regenerator needs the interface, not just the hash.
1982        let (target_name, target_signature) = match self.get_ast(&expected_stage_id) {
1983            Ok(lex_ast::Stage::FnDecl(fd)) => {
1984                (Some(fd.name.clone()), Some(lex_vcs::render_signature(&fd)))
1985            }
1986            _ => (None, None),
1987        };
1988
1989        Ok(ReplayRequest {
1990            op_id: op_id.to_string(),
1991            target_sig,
1992            target_name,
1993            target_signature,
1994            expected_stage_id,
1995            prompt,
1996            model,
1997            session_id,
1998            parent_program,
1999        })
2000    }
2001
2002    /// #836 G3: compare a regenerated `candidate` against what the op
2003    /// recorded producing, and emit the `Replay` attestation. The
2004    /// reproducibility claim made concrete — a faithful regeneration of
2005    /// the same function from the same cause yields the same
2006    /// content-addressed stage id.
2007    ///
2008    /// `reproduced` is true iff the candidate is the same sig *and* the
2009    /// same stage id the op recorded. A candidate for a different sig
2010    /// counts as "not reproduced" (`produced_stage_id: None`) rather
2011    /// than an error — it's a legitimate, if negative, replay result.
2012    /// The attestation is addressed to the op's recorded stage, so
2013    /// `list_for_stage` surfaces it alongside the TypeCheck/Examples
2014    /// evidence.
2015    pub fn replay_compare(
2016        &self,
2017        op_id: &str,
2018        candidate: &Stage,
2019    ) -> Result<ReplayOutcome, StoreError> {
2020        let (target_sig, expected_stage_id) = self.replay_target(op_id)?;
2021        let cand_sig = lex_ast::sig_id(candidate);
2022        let cand_stage = stage_id(candidate);
2023        let produced_stage_id = match (cand_sig.as_deref(), &cand_stage) {
2024            // Same function regenerated: the produced stage is
2025            // whatever it content-addresses to.
2026            (Some(s), Some(st)) if s == target_sig => Some(st.clone()),
2027            // A different sig (or an unhashable stage) isn't a
2028            // regeneration of this op's change.
2029            _ => None,
2030        };
2031        let reproduced = produced_stage_id.as_deref() == Some(expected_stage_id.as_str());
2032        let detail = if reproduced {
2033            None
2034        } else {
2035            Some("regeneration did not reproduce the recorded stage".to_string())
2036        };
2037        self.emit_replay(op_id, &expected_stage_id, produced_stage_id, reproduced, None, detail)
2038    }
2039
2040    /// Record a *negative* replay result for a regeneration that never
2041    /// yielded a comparable stage — the output didn't parse, or didn't
2042    /// define the target sig (#836 G3). Emits a `Replay { reproduced:
2043    /// false, produced_stage_id: None }` attestation with `reason` in
2044    /// its `Failed` detail, so an automated `lex op replay` run always
2045    /// records a verdict rather than aborting. `reason` is caller-supplied
2046    /// (e.g. "regenerated source did not parse").
2047    pub fn replay_record_miss(&self, op_id: &str, reason: &str) -> Result<ReplayOutcome, StoreError> {
2048        let (_target_sig, expected_stage_id) = self.replay_target(op_id)?;
2049        self.emit_replay(op_id, &expected_stage_id, None, false, None, Some(reason.to_string()))
2050    }
2051
2052    /// `(target_sig, expected_stage_id)` for a replayable op, or an
2053    /// error if the op is unknown or produced no stage.
2054    fn replay_target(&self, op_id: &str) -> Result<(String, String), StoreError> {
2055        let log = lex_vcs::OpLog::open(self.root())?;
2056        let record = log
2057            .get(&op_id.to_string())?
2058            .ok_or_else(|| StoreError::UnknownOp(op_id.to_string()))?;
2059        produced_sig_stage(&record.produces)
2060            .ok_or_else(|| StoreError::InvalidTransition(format!("op {op_id} produced no stage to replay")))
2061    }
2062
2063    /// Record a replay verdict the caller has already decided — used by
2064    /// the CLI's behavioral tier, which does the (VM-backed) equivalence
2065    /// check the store deliberately can't. `expected_stage_id` is looked
2066    /// up from the op. Set `behavioral_samples` to `Some(n)` when the
2067    /// candidate reproduced *behaviorally* over `n` sampled inputs rather
2068    /// than by exact stage-id match; the attestation then records that
2069    /// weaker-but-real claim distinctly.
2070    pub fn replay_record(
2071        &self,
2072        op_id: &str,
2073        produced_stage_id: Option<String>,
2074        reproduced: bool,
2075        behavioral_samples: Option<usize>,
2076        fail_detail: Option<String>,
2077    ) -> Result<ReplayOutcome, StoreError> {
2078        let (_target_sig, expected_stage_id) = self.replay_target(op_id)?;
2079        self.emit_replay(op_id, &expected_stage_id, produced_stage_id, reproduced, behavioral_samples, fail_detail)
2080    }
2081
2082    /// Compute the exact-match verdict for a candidate *without* emitting
2083    /// an attestation — `(expected_stage_id, produced_stage_id, exact)`.
2084    /// Lets a caller (the CLI) fall back to a behavioral check on a valid
2085    /// but non-identical candidate and emit a single verdict, instead of
2086    /// [`Self::replay_compare`]'s emit-immediately shape.
2087    pub fn replay_stage_of(
2088        &self,
2089        op_id: &str,
2090        candidate: &Stage,
2091    ) -> Result<(String, Option<String>, bool), StoreError> {
2092        let (target_sig, expected_stage_id) = self.replay_target(op_id)?;
2093        let cand_sig = lex_ast::sig_id(candidate);
2094        let cand_stage = stage_id(candidate);
2095        let produced_stage_id = match (cand_sig.as_deref(), &cand_stage) {
2096            (Some(s), Some(st)) if s == target_sig => Some(st.clone()),
2097            _ => None,
2098        };
2099        let exact = produced_stage_id.as_deref() == Some(expected_stage_id.as_str());
2100        Ok((expected_stage_id, produced_stage_id, exact))
2101    }
2102
2103    /// Emit the `Replay` attestation and build the outcome. Shared by
2104    /// [`Self::replay_compare`], [`Self::replay_record_miss`], and
2105    /// [`Self::replay_record`].
2106    fn emit_replay(
2107        &self,
2108        op_id: &str,
2109        expected_stage_id: &str,
2110        produced_stage_id: Option<String>,
2111        reproduced: bool,
2112        behavioral_samples: Option<usize>,
2113        fail_detail: Option<String>,
2114    ) -> Result<ReplayOutcome, StoreError> {
2115        let model = {
2116            let log = lex_vcs::OpLog::open(self.root())?;
2117            match log.get(&op_id.to_string())?.and_then(|r| r.op.intent_id) {
2118                Some(id) => lex_vcs::IntentLog::open(self.root())?
2119                    .get(&id)?
2120                    .map(|i| model_label(&i.model)),
2121                None => None,
2122            }
2123        };
2124        let result = if reproduced {
2125            lex_vcs::AttestationResult::Passed
2126        } else {
2127            lex_vcs::AttestationResult::Failed {
2128                detail: fail_detail.unwrap_or_else(|| "not reproduced".into()),
2129            }
2130        };
2131        let attestation = lex_vcs::Attestation::new(
2132            expected_stage_id.to_string(),
2133            Some(op_id.to_string()),
2134            None,
2135            lex_vcs::AttestationKind::Replay {
2136                expected_stage_id: expected_stage_id.to_string(),
2137                produced_stage_id: produced_stage_id.clone(),
2138                reproduced,
2139                behavioral_samples,
2140                model,
2141            },
2142            result,
2143            replay_producer(),
2144            None,
2145        );
2146        let attestation_id = attestation.attestation_id.clone();
2147        self.attestation_log()?.put(&attestation)?;
2148        Ok(ReplayOutcome {
2149            op_id: op_id.to_string(),
2150            expected_stage_id: expected_stage_id.to_string(),
2151            produced_stage_id,
2152            reproduced,
2153            behavioral_samples,
2154            attestation_id,
2155        })
2156    }
2157
2158    /// The program at an op (that op and all its ancestors applied), as
2159    /// canonical stages. The behavioral replay tier needs the whole
2160    /// program — a regenerated function may call helpers from its parent
2161    /// state, so it can only be run in context. Exposed for the CLI's
2162    /// equivalence check; `op_id` may be any op in the log.
2163    pub fn program_stages_at_op(&self, op_id: &str) -> Result<Vec<Stage>, StoreError> {
2164        let oid: lex_vcs::OpId = op_id.to_string();
2165        let log = lex_vcs::OpLog::open(self.root())?;
2166        let mut map: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
2167        for rec in log.walk_forward(&oid, None)? {
2168            crate::branches::apply_transition(&mut map, &rec.produces);
2169        }
2170        let pairs: Vec<(String, String)> = map.into_iter().collect();
2171        let stages: Vec<Stage> =
2172            self.get_asts_for_sigs_bulk(&pairs).into_iter().collect::<Result<_, _>>()?;
2173        Ok(stages)
2174    }
2175
2176    /// The program at an op, rendered to source. Used to give a replay
2177    /// regenerator the context the change was made against.
2178    fn program_source_at_op(&self, op_id: &lex_vcs::OpId) -> Result<String, StoreError> {
2179        Ok(lex_ast::print_stages(&self.program_stages_at_op(op_id)?))
2180    }
2181
2182    /// Open the attestation log rooted at this store. The log lives
2183    /// under `<root>/attestations/`; opening is idempotent and cheap
2184    /// (`fs::create_dir_all`). Exposed publicly so consumers — `lex
2185    /// blame --with-evidence`, `GET /v1/stage/<id>/attestations` —
2186    /// can read what the store gate emitted without round-tripping
2187    /// through this crate's API surface.
2188    /// Recompute a producer's trust score from its recent
2189    /// attestation history and emit a fresh `ProducerTrust`
2190    /// attestation (#293). Score = `passed / (passed + failed
2191    /// + inconclusive)` over the last `window` attestations
2192    /// produced by `tool_id`, expressed in thousandths
2193    /// (`0..=1000`).
2194    ///
2195    /// Refuses to grant trust when the tool has an active
2196    /// `ProducerBlock` — the block wins as a hard veto. Returns
2197    /// `Ok(None)` for "no attestations to score" (a brand-new
2198    /// producer); the caller can choose how to handle it
2199    /// (typically: skip the publish until evidence accrues).
2200    ///
2201    /// `granted_by` is the identity of the actor running the
2202    /// recompute (typically the human admin, or "lex-ci-bot"
2203    /// for an automated nightly).
2204    pub fn recompute_producer_trust(
2205        &self,
2206        tool_id: &str,
2207        window: usize,
2208        granted_by: &str,
2209    ) -> Result<Option<lex_vcs::AttestationId>, StoreError> {
2210        let log = self.attestation_log()?;
2211        let all = log.list_all()?;
2212        // Hard veto: don't grant trust to a blocked tool.
2213        if lex_vcs::active_producer_block(&all, tool_id).is_some() {
2214            return Err(StoreError::InvalidTransition(format!(
2215                "cannot recompute trust for `{tool_id}` — \
2216                 producer is currently blocked"
2217            )));
2218        }
2219        // Filter to attestations from this tool, newest-first by
2220        // timestamp, then take the window.
2221        let mut from_tool: Vec<&lex_vcs::Attestation> = all
2222            .iter()
2223            .filter(|a| a.produced_by.tool == tool_id)
2224            // Ignore self-referential trust attestations (we're
2225            // scoring evidence, not previous trust statements).
2226            .filter(|a| {
2227                !matches!(
2228                    a.kind,
2229                    lex_vcs::AttestationKind::ProducerTrust { .. }
2230                        | lex_vcs::AttestationKind::TrustWaived { .. }
2231                )
2232            })
2233            .collect();
2234        from_tool.sort_by_key(|a| std::cmp::Reverse(a.timestamp));
2235        from_tool.truncate(window);
2236        if from_tool.is_empty() {
2237            return Ok(None);
2238        }
2239        let (mut passed, mut total) = (0u64, 0u64);
2240        for a in &from_tool {
2241            total += 1;
2242            if matches!(a.result, lex_vcs::AttestationResult::Passed) {
2243                passed += 1;
2244            }
2245        }
2246        let score = if total == 0 {
2247            0
2248        } else {
2249            let raw = (passed as f64) * 1000.0 / (total as f64);
2250            raw.round().clamp(0.0, 1000.0) as u32
2251        };
2252        let head_op = self
2253            .list_branches()?
2254            .into_iter()
2255            .find_map(|b| self.get_branch(&b).ok().flatten().and_then(|x| x.head_op))
2256            .unwrap_or_else(|| "fresh".into());
2257        let evidence = format!(
2258            "window={window}, sample={}, head_op={head_op:.16}",
2259            from_tool.len()
2260        );
2261        let attestation = lex_vcs::Attestation::new(
2262            tool_id.to_string(),
2263            None,
2264            None,
2265            lex_vcs::AttestationKind::ProducerTrust {
2266                tool_id: tool_id.into(),
2267                score_thousandths: score,
2268                evidence,
2269                granted_by: granted_by.into(),
2270            },
2271            lex_vcs::AttestationResult::Passed,
2272            producer_trust_producer(),
2273            None,
2274        );
2275        let id = attestation.attestation_id.clone();
2276        log.put(&attestation)?;
2277        Ok(Some(id))
2278    }
2279
2280    /// The latest live `ProducerTrust` score (thousandths, `0..=1000`) for
2281    /// every producer that currently has trust: the newest score per tool by
2282    /// timestamp, excluding any tool under an active `ProducerBlock` (a block
2283    /// is a hard veto over trust, matching `recompute_producer_trust`).
2284    ///
2285    /// Used to export a capsule trusted-keys keyring from *earned* trust — the
2286    /// producer id doubles as the publisher's signing key downstream, so this
2287    /// turns track record into the allowlist `capsule install` consumes.
2288    pub fn live_producer_trust_scores(
2289        &self,
2290    ) -> Result<std::collections::BTreeMap<String, u32>, StoreError> {
2291        let log = self.attestation_log()?;
2292        let all = log.list_all()?;
2293        // Newest score per tool.
2294        let mut latest: std::collections::BTreeMap<String, (u64, u32)> =
2295            std::collections::BTreeMap::new();
2296        for a in &all {
2297            if let lex_vcs::AttestationKind::ProducerTrust {
2298                tool_id,
2299                score_thousandths,
2300                ..
2301            } = &a.kind
2302            {
2303                let entry = latest.entry(tool_id.clone()).or_insert((0, 0));
2304                if a.timestamp >= entry.0 {
2305                    *entry = (a.timestamp, *score_thousandths);
2306                }
2307            }
2308        }
2309        // Drop blocked producers; a block vetoes trust.
2310        let mut scores = std::collections::BTreeMap::new();
2311        for (tool, (_, score)) in latest {
2312            if lex_vcs::active_producer_block(&all, &tool).is_some() {
2313                continue;
2314            }
2315            scores.insert(tool, score);
2316        }
2317        Ok(scores)
2318    }
2319
2320    pub fn attestation_log(&self) -> Result<lex_vcs::AttestationLog, StoreError> {
2321        Ok(lex_vcs::AttestationLog::open(self.root())?)
2322    }
2323
2324    /// Emit one `TypeCheck::Passed` attestation per stage produced by
2325    /// a successful gated apply. Idempotent on `attestation_id` —
2326    /// re-running the same gate run dedups via content addressing.
2327    ///
2328    /// Failure modes: `io::Error` from the attestation log (disk
2329    /// full, perms). The op has already landed by the time this
2330    /// runs; an error here means the op is durable but the evidence
2331    /// is missing. We propagate so the caller sees the partial
2332    /// state rather than silently swallowing — re-attesting the
2333    /// same op against the same op_id is idempotent (content
2334    /// addressing) so a retry is safe once the underlying issue is
2335    /// fixed.
2336    fn record_typecheck_passed(
2337        &self,
2338        stage_ids: &[String],
2339        op_id: &lex_vcs::OpId,
2340    ) -> Result<(), StoreError> {
2341        if stage_ids.is_empty() {
2342            return Ok(());
2343        }
2344        let log = self.attestation_log()?;
2345        for stage_id in stage_ids {
2346            let attestation = lex_vcs::Attestation::new(
2347                stage_id.clone(),
2348                Some(op_id.clone()),
2349                None,
2350                lex_vcs::AttestationKind::TypeCheck,
2351                lex_vcs::AttestationResult::Passed,
2352                typecheck_producer(),
2353                None,
2354            );
2355            log.put(&attestation)?;
2356        }
2357        Ok(())
2358    }
2359
2360    /// The hosted CI runner (#93): independently re-run the write-time
2361    /// type-check gate on a branch head and record the verdict as a
2362    /// `lex-hub-ci`-produced `TypeCheck` attestation for the stages the
2363    /// advance introduced. Called after an `op push` fast-forwards the
2364    /// head, so `require-attestation type_check` gates are backed by a
2365    /// producer that actually verified the code server-side, not by
2366    /// whatever attestation a client chose to attach. Does NOT move or
2367    /// roll back the head — the client's own always-valid-HEAD gate is
2368    /// what refuses a bad publish; this produces the trusted verdict on
2369    /// top of an already-committed advance (so a client that bypassed
2370    /// its gate is caught by a `TypeCheck::Failed` from `lex-hub-ci`).
2371    ///
2372    /// `from_head` is the branch head *before* the advance; the ops
2373    /// between it and `to_head` are the ones whose stages get attested.
2374    /// Idempotent: attestations are content-addressed, so re-verifying
2375    /// the same head is a no-op.
2376    pub fn verify_head_and_attest(
2377        &self,
2378        branch: &str,
2379        from_head: Option<&str>,
2380        to_head: &str,
2381    ) -> Result<HubCiVerdict, StoreError> {
2382        // Reconstruct the program at the new head and re-check it.
2383        let head = self.branch_head(branch)?;
2384        let pairs: Vec<(String, String)> = head.into_iter().collect();
2385        let decls: Vec<Stage> =
2386            self.get_asts_for_sigs_bulk(&pairs).into_iter().collect::<Result<_, _>>()?;
2387        let checked_stages = decls.len();
2388        // #930: the SigId→stage map holds only fn/type declarations — the
2389        // head's `import` edges are AddImport ops, absent here. Reconstruct
2390        // them so a non-inlined head's `<alias>.name` references bind: the
2391        // resolver scans these imports to resolve each dependency, and the
2392        // checker's Pass 1 binds the alias to the resolved module. (Without
2393        // this the alias is unbound and the head fails as `unknown_identifier`,
2394        // even with the dependency correctly resolved.)
2395        let head_imports = crate::render::package_head_at_op(self, to_head)
2396            .map(|ph| {
2397                ph.flat_imports
2398                    .into_iter()
2399                    .map(|(reference, alias)| {
2400                        Stage::Import(lex_ast::Import { reference, alias })
2401                    })
2402                    .collect::<Vec<_>>()
2403            })
2404            .unwrap_or_default();
2405        let mut stages = head_imports;
2406        stages.extend(decls);
2407        // #930: the hub gate resolves this head's external dependencies from
2408        // the lock committed with `to_head` (via the installed cross-store
2409        // resolver); empty when none is installed or the head is inlined.
2410        let modules = self.resolved_modules(&stages, Some(to_head));
2411        let module_types = self.resolved_module_types(&stages, Some(to_head));
2412        let dep_prefixes = self.resolved_module_prefixes(&stages, Some(to_head));
2413        let result = match lex_types::check_program_with_deps(&stages, &modules, &module_types, &dep_prefixes) {
2414            Ok(_) => lex_vcs::AttestationResult::Passed,
2415            Err(errors) => lex_vcs::AttestationResult::Failed {
2416                detail: serde_json::to_string(&errors).unwrap_or_else(|_| "type errors".into()),
2417            },
2418        };
2419        let passed = matches!(result, lex_vcs::AttestationResult::Passed);
2420
2421        // Stages introduced by THIS advance (from_head exclusive → to_head).
2422        let log = lex_vcs::OpLog::open(self.root())?;
2423        let to = to_head.to_string();
2424        let records = match from_head {
2425            Some(f) => log
2426                .walk_forward_since(&to, &f.to_string())?
2427                .unwrap_or_else(|| log.walk_forward(&to, None).unwrap_or_default()),
2428            None => log.walk_forward(&to, None)?,
2429        };
2430        let mut introduced: Vec<String> = Vec::new();
2431        for rec in &records {
2432            introduced.extend(attestable_stage_ids(&rec.produces));
2433        }
2434
2435        let alog = self.attestation_log()?;
2436        for sid in &introduced {
2437            let att = lex_vcs::Attestation::new(
2438                sid.clone(),
2439                Some(to_head.to_string()),
2440                None,
2441                lex_vcs::AttestationKind::TypeCheck,
2442                result.clone(),
2443                hub_ci_producer(),
2444                None,
2445            );
2446            alog.put(&att)?;
2447        }
2448
2449        let detail = match &result {
2450            lex_vcs::AttestationResult::Failed { detail } => Some(detail.clone()),
2451            _ => None,
2452        };
2453        Ok(HubCiVerdict { passed, checked_stages, attested_stages: introduced.len(), detail })
2454    }
2455
2456    /// Emit an `Examples::Passed` attestation for a published stage
2457    /// whose behavioral `examples {}` block was run and passed (#835,
2458    /// Tier 1). Mirrors [`Self::record_typecheck_passed`]. The
2459    /// behavioral run itself happens one layer up (lex-api / lex-cli)
2460    /// because it needs the bytecode compiler + VM, which this crate
2461    /// deliberately doesn't depend on; the store only records the
2462    /// verdict. `file_hash` uses the stage id — the stage fully
2463    /// determines its own examples.
2464    pub fn record_examples_passed(
2465        &self,
2466        stage_id: &str,
2467        op_id: &lex_vcs::OpId,
2468        count: usize,
2469    ) -> Result<(), StoreError> {
2470        let log = self.attestation_log()?;
2471        let attestation = lex_vcs::Attestation::new(
2472            stage_id.to_string(),
2473            Some(op_id.clone()),
2474            None,
2475            lex_vcs::AttestationKind::Examples { file_hash: stage_id.to_string(), count },
2476            lex_vcs::AttestationResult::Passed,
2477            examples_producer(),
2478            None,
2479        );
2480        log.put(&attestation)?;
2481        Ok(())
2482    }
2483
2484    /// Record a structured `Review` verdict on a stage (#836 G4).
2485    /// The verdict maps onto the attestation `result` so existing
2486    /// result-based tooling reads it: Approve->Passed,
2487    /// Reject->Failed, RequestChanges->Inconclusive.
2488    pub fn record_review(
2489        &self,
2490        stage_id: &str,
2491        op_id: Option<lex_vcs::OpId>,
2492        reviewer: &str,
2493        verdict: lex_vcs::ReviewVerdict,
2494        notes: Option<String>,
2495    ) -> Result<lex_vcs::AttestationId, StoreError> {
2496        let result = match verdict {
2497            lex_vcs::ReviewVerdict::Approve => lex_vcs::AttestationResult::Passed,
2498            lex_vcs::ReviewVerdict::Reject => lex_vcs::AttestationResult::Failed {
2499                detail: notes.clone().unwrap_or_else(|| "rejected".into()),
2500            },
2501            lex_vcs::ReviewVerdict::RequestChanges => lex_vcs::AttestationResult::Inconclusive {
2502                detail: notes.clone().unwrap_or_else(|| "changes requested".into()),
2503            },
2504        };
2505        let att = lex_vcs::Attestation::new(
2506            stage_id.to_string(),
2507            op_id,
2508            None,
2509            lex_vcs::AttestationKind::Review { reviewer: reviewer.to_string(), verdict, notes },
2510            result,
2511            review_producer(reviewer),
2512            None,
2513        );
2514        let id = att.attestation_id.clone();
2515        self.attestation_log()?.put(&att)?;
2516        Ok(id)
2517    }
2518
2519    /// The latest `Review` verdict recorded on a stage, if any
2520    /// (#836 G4). "Latest" is by attestation timestamp; ties keep the
2521    /// last one seen. Used by `promote_candidate` to honor a standing
2522    /// Reject.
2523    pub fn latest_review_verdict(
2524        &self,
2525        stage_id: &str,
2526    ) -> Result<Option<lex_vcs::ReviewVerdict>, StoreError> {
2527        let log = self.attestation_log()?;
2528        let mut latest: Option<(u64, lex_vcs::ReviewVerdict)> = None;
2529        for a in log.list_for_stage(&stage_id.to_string())? {
2530            if let lex_vcs::AttestationKind::Review { verdict, .. } = a.kind {
2531                if latest.as_ref().map(|(t, _)| a.timestamp >= *t).unwrap_or(true) {
2532                    latest = Some((a.timestamp, verdict));
2533                }
2534            }
2535        }
2536        Ok(latest.map(|(_, v)| v))
2537    }
2538
2539    /// Consult `policy.session_budgets` for the op's session
2540    /// (resolved via `op.intent_id → Intent.session_id`) and
2541    /// refuse if applying would push the session's monotonic spend
2542    /// over the configured cap (#292 slice 3).
2543    ///
2544    /// Ops without an `intent_id`, or whose intent has no
2545    /// configured cap, return Ok without any disk read.
2546    fn check_session_budget(&self, op: &lex_vcs::Operation) -> Result<(), StoreError> {
2547        let Some(intent_id) = op.intent_id.as_deref() else {
2548            return Ok(());
2549        };
2550        let intent_log = lex_vcs::IntentLog::open(self.root())?;
2551        let Some(intent) = intent_log.get(&intent_id.to_string())? else {
2552            // Dangling intent — treat as "no session" and let it
2553            // sail through. Slice 1's ledger already documents
2554            // this as graceful-degradation semantics.
2555            return Ok(());
2556        };
2557        let policy = crate::policy::load(self.root())?.unwrap_or_default();
2558        let Some(cap) = policy.session_budgets.cap_for(&intent.session_id) else {
2559            return Ok(());
2560        };
2561        // Recompute the session's current spend + the contribution
2562        // from this op. Re-running the ledger walk on every gated
2563        // op is O(branch history); see #292 slice 1's note about
2564        // a future on-disk cache.
2565        let current = self.session_budget(&intent.session_id)?;
2566        let increment = crate::budget::monotonic_spend_of(&op.kind);
2567        let spent_after = current.spent.saturating_add(increment);
2568        if spent_after > cap {
2569            return Err(StoreError::BudgetExceeded {
2570                session_id: intent.session_id,
2571                cap,
2572                spent_after,
2573            });
2574        }
2575        Ok(())
2576    }
2577
2578    /// Emit `RepairHint` attestations for a TypeError-rejected op
2579    /// (#281). One per candidate stage in the transition. The hint
2580    /// records the *would-be* op_id (deterministic, content-
2581    /// addressed even though the op record was never persisted)
2582    /// and the structured errors.
2583    ///
2584    /// #306 slice 3: `suggested_transform` is populated from the
2585    /// static (rule_tag → likely_transform) table for the *first*
2586    /// error in the batch. The LLM-driven `lex repair --apply`
2587    /// flow can still overwrite this with a higher-quality
2588    /// suggestion; the static value is the floor, not the ceiling.
2589    ///
2590    /// Best-effort: a write failure here is swallowed by the
2591    /// caller (the original `TypeError` is the load-bearing
2592    /// signal; missing the hint is recoverable on a retry).
2593    fn record_repair_hint(
2594        &self,
2595        stage_ids: &[String],
2596        failed_op_id: &lex_vcs::OpId,
2597        errors: &[lex_types::TypeError],
2598    ) -> Result<(), StoreError> {
2599        if stage_ids.is_empty() {
2600            return Ok(());
2601        }
2602        let errors_json = serde_json::to_value(errors).map_err(StoreError::Serde)?;
2603        // #306 slice 3: look up the static suggested_transform for
2604        // the first error's rule_tag. Multiple errors per op are
2605        // possible — when they fire in lockstep (e.g. one bad let
2606        // binding propagates to several use sites), the first
2607        // error's rule_tag is usually the load-bearing one to fix.
2608        let suggested_transform = errors
2609            .first()
2610            .and_then(|e| lex_types::suggested_transform_for(e.rule_tag()));
2611        let log = self.attestation_log()?;
2612        for stage_id in stage_ids {
2613            let attestation = lex_vcs::Attestation::new(
2614                stage_id.clone(),
2615                None, // the failed op was never persisted; not the
2616                // attestation's op_id (which is for a
2617                // *successful* op).
2618                None,
2619                lex_vcs::AttestationKind::RepairHint {
2620                    failed_op_id: failed_op_id.clone(),
2621                    errors: errors_json.clone(),
2622                    suggested_transform: suggested_transform.clone(),
2623                },
2624                lex_vcs::AttestationResult::Failed {
2625                    detail: format!(
2626                        "op {} rejected: {} type error(s)",
2627                        failed_op_id,
2628                        errors.len()
2629                    ),
2630                },
2631                repair_hint_producer(),
2632                None,
2633            );
2634            log.put(&attestation)?;
2635        }
2636        Ok(())
2637    }
2638
2639    /// Emit `Trace` attestations linking an already-committed `op`
2640    /// to the run that produced it (#257). One attestation per
2641    /// produced stage (matching the `TypeCheck` emission contract
2642    /// — see [`Self::apply_operation_checked`]) with
2643    /// `op_id: Some(op_id)` set, so `lex trace --op <op_id>`
2644    /// surfaces the run.
2645    ///
2646    /// Returns the number of attestations emitted (zero for ops
2647    /// that produce no attestable stage, e.g. `Remove` /
2648    /// `ImportOnly`).
2649    ///
2650    /// Idempotent: re-emitting for the same
2651    /// `(run_id, root_target, op_id, stage_id, producer, result)`
2652    /// tuple dedups via content addressing.
2653    ///
2654    /// `op_id` must already exist in the op log — an unknown op
2655    /// surfaces as `StoreError::UnknownOp`.
2656    pub fn record_op_trace(
2657        &self,
2658        run_id: &str,
2659        root_target: &str,
2660        op_id: &lex_vcs::OpId,
2661        result: lex_vcs::AttestationResult,
2662        producer: lex_vcs::ProducerDescriptor,
2663    ) -> Result<usize, StoreError> {
2664        let log = lex_vcs::OpLog::open(self.root())?;
2665        let rec = log
2666            .get(op_id)?
2667            .ok_or_else(|| StoreError::UnknownOp(op_id.clone()))?;
2668        let stage_ids = attestable_stage_ids(&rec.produces);
2669        if stage_ids.is_empty() {
2670            return Ok(0);
2671        }
2672        let attlog = self.attestation_log()?;
2673        let mut emitted = 0;
2674        for stage_id in stage_ids {
2675            let attestation = lex_vcs::Attestation::new(
2676                stage_id,
2677                Some(op_id.clone()),
2678                None,
2679                lex_vcs::AttestationKind::Trace {
2680                    run_id: run_id.into(),
2681                    root_target: root_target.into(),
2682                },
2683                result.clone(),
2684                producer.clone(),
2685                None,
2686            );
2687            attlog.put(&attestation)?;
2688            emitted += 1;
2689        }
2690        Ok(emitted)
2691    }
2692
2693    /// Walk `ops_since(branch_head, base)` and emit per-stage
2694    /// `Trace` attestations for each new op, linking them to the
2695    /// run that produced them (#257). Used by `lex run --trace`
2696    /// after the VM exits: snapshot `base = branch_head` before
2697    /// the run, then call this with the post-run head.
2698    ///
2699    /// `base = None` means "every op currently reachable from the
2700    /// branch head" — generally not what you want for a single
2701    /// run; pass the pre-run head.
2702    ///
2703    /// Returns the total number of attestations emitted across
2704    /// every new op. Zero is the common case (the run committed no
2705    /// ops).
2706    ///
2707    /// Idempotent on the per-op level via [`Self::record_op_trace`].
2708    pub fn record_run_committed_ops_since(
2709        &self,
2710        run_id: &str,
2711        root_target: &str,
2712        branch: &str,
2713        base: Option<&lex_vcs::OpId>,
2714        result: lex_vcs::AttestationResult,
2715        producer: lex_vcs::ProducerDescriptor,
2716    ) -> Result<usize, StoreError> {
2717        let head = match self.get_branch(branch)?.and_then(|b| b.head_op) {
2718            Some(h) => h,
2719            None => return Ok(0),
2720        };
2721        let log = lex_vcs::OpLog::open(self.root())?;
2722        let new_ops = log.ops_since(&head, base)?;
2723        let mut total = 0;
2724        for rec in new_ops {
2725            total += self.record_op_trace(
2726                run_id,
2727                root_target,
2728                &rec.op_id,
2729                result.clone(),
2730                producer.clone(),
2731            )?;
2732        }
2733        Ok(total)
2734    }
2735
2736    /// Apply a typed `ReplaceMatchArm` transform (#280) and emit a
2737    /// `OperationKind::ReplaceMatchArm` op that records the
2738    /// semantic shape of the edit, not just the byte effect.
2739    ///
2740    /// Steps:
2741    ///   1. Load the source stage's canonical bytes (delta-aware).
2742    ///   2. Run [`lex_ast::replace_match_arm`] to produce the new
2743    ///      `Stage`. Pure function, no I/O.
2744    ///   3. Publish the new stage. Idempotent on the
2745    ///      content-addressed `to_stage_id`.
2746    ///   4. Assemble the candidate program (every active stage on
2747    ///      the branch, with the rewritten one swapped in) and call
2748    ///      [`Self::apply_operation_checked`] — re-typechecks and
2749    ///      runs every existing gate (TypeCheck attestation,
2750    ///      required_attestations, producer-block walk-back).
2751    ///
2752    /// Failure modes:
2753    ///   * [`StoreError::TransformError`] — transform didn't apply.
2754    ///     The branch is unchanged; no stage published.
2755    ///   * [`StoreError::TypeError`] — transform produced an
2756    ///     ill-typed program. The new stage is on disk (idempotent
2757    ///     on its content hash) but the branch is unchanged. Same
2758    ///     "publish without advance" semantics as #245.
2759    ///   * Everything else from `apply_operation_checked`.
2760    pub fn apply_replace_match_arm(
2761        &self,
2762        branch: &str,
2763        from_stage_id: &str,
2764        match_node: &lex_ast::NodeId,
2765        arm_index: usize,
2766        new_body: lex_ast::CExpr,
2767    ) -> Result<lex_vcs::OpId, StoreError> {
2768        let from_stage = self.get_ast(from_stage_id)?;
2769        let new_stage = lex_ast::replace_match_arm(&from_stage, match_node, arm_index, new_body)
2770            .map_err(StoreError::TransformError)?;
2771        let sig = lex_ast::sig_id(&from_stage).ok_or(StoreError::CannotPublishImport)?;
2772        let to_stage_id = self.publish(&new_stage)?;
2773        if to_stage_id == from_stage_id {
2774            // No-op transform — the new body was structurally
2775            // identical to the old. Refuse rather than advancing
2776            // the branch with an empty edit.
2777            return Err(StoreError::InvalidTransition(format!(
2778                "replace_match_arm produced the same stage_id `{from_stage_id}`"
2779            )));
2780        }
2781
2782        // Assemble the candidate program: every active stage on
2783        // the branch, with `from_stage_id` swapped for `new_stage`.
2784        let head = self.branch_head(branch)?;
2785        let mut candidate: Vec<lex_ast::Stage> = Vec::with_capacity(head.len());
2786        for (other_sig, other_stage_id) in &head {
2787            if other_sig == &sig {
2788                candidate.push(new_stage.clone());
2789            } else {
2790                candidate.push(self.get_ast(other_stage_id)?);
2791            }
2792        }
2793        // If the source sig isn't on the current branch head, the
2794        // transform is operating on a stage that hasn't been added
2795        // yet — refuse rather than risking a candidate program
2796        // that doesn't reflect the branch's actual state.
2797        if !head.contains_key(&sig) {
2798            return Err(StoreError::InvalidTransition(format!(
2799                "sig `{sig}` not on branch `{branch}`'s head"
2800            )));
2801        }
2802
2803        // #247: budget delta captured for `lex op log --budget-drift`.
2804        let from_budget = budget_of_stage(&from_stage);
2805        let to_budget = budget_of_stage(&new_stage);
2806
2807        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
2808        let kind = lex_vcs::OperationKind::ReplaceMatchArm {
2809            sig_id: sig.clone(),
2810            from_stage_id: from_stage_id.to_string(),
2811            to_stage_id: to_stage_id.clone(),
2812            match_node: match_node.as_str().to_string(),
2813            arm_index,
2814            from_budget,
2815            to_budget,
2816        };
2817        let transition = lex_vcs::StageTransition::Replace {
2818            sig_id: sig.clone(),
2819            from: from_stage_id.to_string(),
2820            to: to_stage_id.clone(),
2821        };
2822        let op = lex_vcs::Operation::new(kind, head_now.into_iter().collect::<Vec<_>>());
2823        self.apply_operation_checked(branch, op, transition, &candidate)
2824    }
2825
2826    /// Apply a typed `RenameLocal` transform (#280) — rename a
2827    /// `let`-bound local within a fn body and emit a matching
2828    /// `OperationKind::RenameLocal`. Same end-to-end shape as
2829    /// [`Self::apply_replace_match_arm`]; see that method for the
2830    /// failure-mode taxonomy.
2831    pub fn apply_rename_local(
2832        &self,
2833        branch: &str,
2834        from_stage_id: &str,
2835        let_node: &lex_ast::NodeId,
2836        new_name: &str,
2837    ) -> Result<lex_vcs::OpId, StoreError> {
2838        let from_stage = self.get_ast(from_stage_id)?;
2839        // Read the old name before running the transform, so the
2840        // op log records the rename target rather than just the
2841        // new value.
2842        let old_name = read_let_name(&from_stage, let_node).map_err(StoreError::TransformError)?;
2843        let new_stage = lex_ast::rename_local(&from_stage, let_node, new_name)
2844            .map_err(StoreError::TransformError)?;
2845        let sig = lex_ast::sig_id(&from_stage).ok_or(StoreError::CannotPublishImport)?;
2846        let to_stage_id = self.publish(&new_stage)?;
2847        if to_stage_id == from_stage_id {
2848            return Err(StoreError::InvalidTransition(format!(
2849                "rename_local produced the same stage_id `{from_stage_id}`"
2850            )));
2851        }
2852        let head = self.branch_head(branch)?;
2853        let mut candidate: Vec<lex_ast::Stage> = Vec::with_capacity(head.len());
2854        for (other_sig, other_stage_id) in &head {
2855            if other_sig == &sig {
2856                candidate.push(new_stage.clone());
2857            } else {
2858                candidate.push(self.get_ast(other_stage_id)?);
2859            }
2860        }
2861        if !head.contains_key(&sig) {
2862            return Err(StoreError::InvalidTransition(format!(
2863                "sig `{sig}` not on branch `{branch}`'s head"
2864            )));
2865        }
2866        let from_budget = budget_of_stage(&from_stage);
2867        let to_budget = budget_of_stage(&new_stage);
2868        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
2869        let kind = lex_vcs::OperationKind::RenameLocal {
2870            sig_id: sig.clone(),
2871            from_stage_id: from_stage_id.to_string(),
2872            to_stage_id: to_stage_id.clone(),
2873            let_node: let_node.as_str().to_string(),
2874            old_name,
2875            new_name: new_name.to_string(),
2876            from_budget,
2877            to_budget,
2878        };
2879        let transition = lex_vcs::StageTransition::Replace {
2880            sig_id: sig.clone(),
2881            from: from_stage_id.to_string(),
2882            to: to_stage_id.clone(),
2883        };
2884        let op = lex_vcs::Operation::new(kind, head_now.into_iter().collect::<Vec<_>>());
2885        self.apply_operation_checked(branch, op, transition, &candidate)
2886    }
2887
2888    /// Apply a typed `InlineLet` transform (#280) — eliminate a
2889    /// `let x := v; body` by substituting `v` for every unshadowed
2890    /// `x` in `body`, then replacing the `Let` node with the
2891    /// substituted body. Same end-to-end shape as
2892    /// [`Self::apply_replace_match_arm`].
2893    pub fn apply_inline_let(
2894        &self,
2895        branch: &str,
2896        from_stage_id: &str,
2897        let_node: &lex_ast::NodeId,
2898    ) -> Result<lex_vcs::OpId, StoreError> {
2899        let from_stage = self.get_ast(from_stage_id)?;
2900        let binding_name =
2901            read_let_name(&from_stage, let_node).map_err(StoreError::TransformError)?;
2902        let new_stage =
2903            lex_ast::inline_let(&from_stage, let_node).map_err(StoreError::TransformError)?;
2904        let sig = lex_ast::sig_id(&from_stage).ok_or(StoreError::CannotPublishImport)?;
2905        let to_stage_id = self.publish(&new_stage)?;
2906        if to_stage_id == from_stage_id {
2907            return Err(StoreError::InvalidTransition(format!(
2908                "inline_let produced the same stage_id `{from_stage_id}`"
2909            )));
2910        }
2911        let head = self.branch_head(branch)?;
2912        let mut candidate: Vec<lex_ast::Stage> = Vec::with_capacity(head.len());
2913        for (other_sig, other_stage_id) in &head {
2914            if other_sig == &sig {
2915                candidate.push(new_stage.clone());
2916            } else {
2917                candidate.push(self.get_ast(other_stage_id)?);
2918            }
2919        }
2920        if !head.contains_key(&sig) {
2921            return Err(StoreError::InvalidTransition(format!(
2922                "sig `{sig}` not on branch `{branch}`'s head"
2923            )));
2924        }
2925        let from_budget = budget_of_stage(&from_stage);
2926        let to_budget = budget_of_stage(&new_stage);
2927        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
2928        let kind = lex_vcs::OperationKind::InlineLet {
2929            sig_id: sig.clone(),
2930            from_stage_id: from_stage_id.to_string(),
2931            to_stage_id: to_stage_id.clone(),
2932            let_node: let_node.as_str().to_string(),
2933            binding_name,
2934            from_budget,
2935            to_budget,
2936        };
2937        let transition = lex_vcs::StageTransition::Replace {
2938            sig_id: sig.clone(),
2939            from: from_stage_id.to_string(),
2940            to: to_stage_id.clone(),
2941        };
2942        let op = lex_vcs::Operation::new(kind, head_now.into_iter().collect::<Vec<_>>());
2943        self.apply_operation_checked(branch, op, transition, &candidate)
2944    }
2945
2946    /// Apply a typed `ExtractFunction` transform (#280 slice 4) —
2947    /// extract a sub-expression of `from_stage_id`'s body into a
2948    /// new top-level fn defined by `spec`, and emit two ops tied
2949    /// together by a shared synthetic Intent so `lex op log
2950    /// --intent <id>` groups them.
2951    ///
2952    /// The two ops:
2953    ///   1. `AddFunction { sig_id: <new_fn_sig>, stage_id: <new_fn_stage> }`
2954    ///   2. `ModifyBody { sig_id: <source_sig>, from_stage_id, to_stage_id: <modified> }`
2955    ///
2956    /// The shared Intent's prompt is structured (`extract_function:
2957    /// <new_fn_name>` plus the source identity) so downstream
2958    /// tooling can recover the typed-transform shape from the
2959    /// op-log + intent-log join.
2960    ///
2961    /// Returns `(add_fn_op_id, modify_body_op_id)`.
2962    pub fn apply_extract_function(
2963        &self,
2964        branch: &str,
2965        from_stage_id: &str,
2966        expr_node: &lex_ast::NodeId,
2967        spec: lex_ast::ExtractFnSpec,
2968    ) -> Result<(lex_vcs::OpId, lex_vcs::OpId), StoreError> {
2969        let from_stage = self.get_ast(from_stage_id)?;
2970        let new_fn_name = spec.name.clone();
2971        let (modified_stage, new_fn_stage) =
2972            lex_ast::extract_function(&from_stage, expr_node, spec)
2973                .map_err(StoreError::TransformError)?;
2974
2975        let source_sig = lex_ast::sig_id(&from_stage).ok_or(StoreError::CannotPublishImport)?;
2976        let new_fn_sig = lex_ast::sig_id(&new_fn_stage).ok_or(StoreError::CannotPublishImport)?;
2977        if source_sig == new_fn_sig {
2978            return Err(StoreError::InvalidTransition(format!(
2979                "extract_function produced a sig matching the source `{source_sig}`"
2980            )));
2981        }
2982        let new_fn_stage_id = self.publish(&new_fn_stage)?;
2983        let modified_stage_id = self.publish(&modified_stage)?;
2984        if modified_stage_id == from_stage_id {
2985            return Err(StoreError::InvalidTransition(format!(
2986                "extract_function produced the same stage_id `{from_stage_id}` for the source"
2987            )));
2988        }
2989
2990        let head = self.branch_head(branch)?;
2991        if !head.contains_key(&source_sig) {
2992            return Err(StoreError::InvalidTransition(format!(
2993                "sig `{source_sig}` not on branch `{branch}`'s head"
2994            )));
2995        }
2996
2997        // Synthesize an Intent linking the two ops. The session_id
2998        // / model fields here are not load-bearing — they exist to
2999        // make the IntentId content-addressed; downstream tooling
3000        // reads `prompt` to reconstruct the typed-transform shape.
3001        let intent = lex_vcs::Intent::new(
3002            format!(
3003                "[lex.transform.extract_function]\nnew_fn={new_fn_name}\nsource_sig={source_sig}\nfrom_stage={from_stage_id}\nexpr_node={node}",
3004                node = expr_node.as_str(),
3005            ),
3006            "lex-store::apply_extract_function",
3007            lex_vcs::ModelDescriptor {
3008                provider: "lex-store".into(),
3009                name: env!("CARGO_PKG_VERSION").into(),
3010                version: None,
3011            },
3012            None,
3013        );
3014        let intent_id = intent.intent_id.clone();
3015        lex_vcs::IntentLog::open(self.root())?.put(&intent)?;
3016
3017        // Step 1 — emit the AddFunction op for the new fn. Build
3018        // the candidate program by appending the new fn to every
3019        // stage on the current branch head.
3020        let new_fn_effects: std::collections::BTreeSet<String> = match &new_fn_stage {
3021            lex_ast::Stage::FnDecl(fd) => fd.effects.iter().map(|e| e.name.clone()).collect(),
3022            _ => Default::default(),
3023        };
3024        let new_fn_budget = budget_of_stage(&new_fn_stage);
3025        let mut candidate_with_new_fn: Vec<lex_ast::Stage> = Vec::with_capacity(head.len() + 1);
3026        for stage_id in head.values() {
3027            candidate_with_new_fn.push(self.get_ast(stage_id)?);
3028        }
3029        candidate_with_new_fn.push(new_fn_stage.clone());
3030        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
3031        let add_op = lex_vcs::Operation::new(
3032            lex_vcs::OperationKind::AddFunction {
3033                sig_id: new_fn_sig.clone(),
3034                stage_id: new_fn_stage_id.clone(),
3035                effects: new_fn_effects,
3036                budget_cost: new_fn_budget,
3037                // Single-op apply path — no package context here.
3038                in_file: None,
3039            },
3040            head_now.into_iter().collect::<Vec<_>>(),
3041        )
3042        .with_intent(intent_id.clone());
3043        let add_transition = lex_vcs::StageTransition::Create {
3044            sig_id: new_fn_sig.clone(),
3045            stage_id: new_fn_stage_id.clone(),
3046        };
3047        let add_op_id =
3048            self.apply_operation_checked(branch, add_op, add_transition, &candidate_with_new_fn)?;
3049
3050        // Step 2 — emit the ModifyBody op for the source. Build
3051        // the candidate program by replacing the source's stage
3052        // with `modified_stage` and keeping the new fn alongside.
3053        let from_budget = budget_of_stage(&from_stage);
3054        let to_budget = budget_of_stage(&modified_stage);
3055        let mut candidate_with_modified: Vec<lex_ast::Stage> = Vec::with_capacity(head.len() + 1);
3056        for (other_sig, other_stage_id) in &head {
3057            if other_sig == &source_sig {
3058                candidate_with_modified.push(modified_stage.clone());
3059            } else {
3060                candidate_with_modified.push(self.get_ast(other_stage_id)?);
3061            }
3062        }
3063        candidate_with_modified.push(new_fn_stage.clone());
3064        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
3065        let modify_op = lex_vcs::Operation::new(
3066            lex_vcs::OperationKind::ModifyBody {
3067                sig_id: source_sig.clone(),
3068                from_stage_id: from_stage_id.to_string(),
3069                to_stage_id: modified_stage_id.clone(),
3070                from_budget,
3071                to_budget,
3072            },
3073            head_now.into_iter().collect::<Vec<_>>(),
3074        )
3075        .with_intent(intent_id);
3076        let modify_transition = lex_vcs::StageTransition::Replace {
3077            sig_id: source_sig,
3078            from: from_stage_id.to_string(),
3079            to: modified_stage_id,
3080        };
3081        let modify_op_id = self.apply_operation_checked(
3082            branch,
3083            modify_op,
3084            modify_transition,
3085            &candidate_with_modified,
3086        )?;
3087
3088        Ok((add_op_id, modify_op_id))
3089    }
3090
3091    /// Propose a stage for `sig_id` without advancing the branch
3092    /// head (#294). Multiple agents can call this concurrently
3093    /// for the same sig — every call lands a fresh `Candidate`
3094    /// op chained off the current head_op. The branch head stays
3095    /// where it was; a later [`Self::promote_candidate`] picks
3096    /// the winner.
3097    ///
3098    /// The caller is responsible for typechecking `new_stage`
3099    /// against whatever program context they consider valid —
3100    /// `propose_candidate` doesn't run the gate. Type errors
3101    /// surface at promotion time, where the candidate is
3102    /// composed back into a candidate program via the standard
3103    /// `apply_operation_checked` path.
3104    ///
3105    /// The stage is published (idempotent on content hash). The
3106    /// `intent_id` is required so downstream consumers can
3107    /// distinguish proposals by author.
3108    pub fn propose_candidate(
3109        &self,
3110        branch: &str,
3111        new_stage: &lex_ast::Stage,
3112        intent_id: &lex_vcs::IntentId,
3113    ) -> Result<lex_vcs::OpId, StoreError> {
3114        let sig = lex_ast::sig_id(new_stage).ok_or(StoreError::CannotPublishImport)?;
3115        let stage_id = self.publish(new_stage)?;
3116        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
3117        let op = lex_vcs::Operation::new(
3118            lex_vcs::OperationKind::Candidate {
3119                sig_id: sig,
3120                stage_id,
3121            },
3122            head_now.into_iter().collect::<Vec<_>>(),
3123        )
3124        .with_intent(intent_id.clone());
3125        let transition = lex_vcs::StageTransition::ImportOnly;
3126        self.apply_operation(branch, op, transition)
3127    }
3128
3129    /// List every live `Candidate` op for `sig_id` — i.e. those
3130    /// not yet referenced by any `Promote` op (either as the
3131    /// winner or in the `supersedes` set). Used by `lex stage
3132    /// candidates`. Results are sorted by op_id for
3133    /// reproducibility.
3134    pub fn list_candidates(&self, sig_id: &str) -> Result<Vec<CandidateInfo>, StoreError> {
3135        let log = lex_vcs::OpLog::open(self.root())?;
3136        let all = log.list_all()?;
3137        // Collect the set of candidate op_ids referenced by any
3138        // Promote for this sig. Those candidates are no longer
3139        // live.
3140        let mut referenced: std::collections::BTreeSet<lex_vcs::OpId> = Default::default();
3141        for rec in &all {
3142            if let lex_vcs::OperationKind::Promote {
3143                sig_id: s,
3144                winner_candidate,
3145                supersedes,
3146                ..
3147            } = &rec.op.kind
3148            {
3149                if s != sig_id {
3150                    continue;
3151                }
3152                referenced.insert(winner_candidate.clone());
3153                for sup in supersedes {
3154                    referenced.insert(sup.clone());
3155                }
3156            }
3157        }
3158        let mut out: Vec<CandidateInfo> = Vec::new();
3159        for rec in all {
3160            let lex_vcs::OperationKind::Candidate {
3161                sig_id: s,
3162                stage_id,
3163            } = &rec.op.kind
3164            else {
3165                continue;
3166            };
3167            if s != sig_id {
3168                continue;
3169            }
3170            if referenced.contains(&rec.op_id) {
3171                continue;
3172            }
3173            out.push(CandidateInfo {
3174                op_id: rec.op_id.clone(),
3175                stage_id: stage_id.clone(),
3176                intent_id: rec.op.intent_id.clone(),
3177            });
3178        }
3179        out.sort_by(|a, b| a.op_id.cmp(&b.op_id));
3180        Ok(out)
3181    }
3182
3183    /// Promote a previously-landed `Candidate` op as the new
3184    /// branch head for its sig (#294). Emits a `Promote` op
3185    /// listing every other live `Candidate` for the same sig
3186    /// in its `supersedes` field. After this lands,
3187    /// [`Self::list_candidates`] returns an empty set for the
3188    /// sig.
3189    ///
3190    /// Re-typechecks the candidate program (winner stage + the
3191    /// rest of the branch) through `apply_operation_checked`, so
3192    /// a candidate that doesn't compose with the current branch
3193    /// state surfaces as `StoreError::TypeError`.
3194    pub fn promote_candidate(
3195        &self,
3196        branch: &str,
3197        candidate_op_id: &lex_vcs::OpId,
3198    ) -> Result<lex_vcs::OpId, StoreError> {
3199        let log = lex_vcs::OpLog::open(self.root())?;
3200        let candidate_rec = log
3201            .get(candidate_op_id)?
3202            .ok_or_else(|| StoreError::UnknownOp(candidate_op_id.clone()))?;
3203        let (sig, winner_stage_id) = match &candidate_rec.op.kind {
3204            lex_vcs::OperationKind::Candidate { sig_id, stage_id } => {
3205                (sig_id.clone(), stage_id.clone())
3206            }
3207            other => {
3208                return Err(StoreError::InvalidTransition(format!(
3209                    "op `{candidate_op_id}` is a `{:?}`, not a Candidate",
3210                    other
3211                )))
3212            }
3213        };
3214
3215        // #836 G4: a candidate carrying a standing `Reject` review must
3216        // not be promoted. "Standing" = the latest `Review` on the
3217        // winner's stage is a Reject; a later `Approve` (or
3218        // `RequestChanges`, which is advisory, not a veto) lifts it.
3219        // Safe by default: a candidate with no review, or an approved
3220        // one, promotes exactly as before.
3221        if let Some(lex_vcs::ReviewVerdict::Reject) = self.latest_review_verdict(&winner_stage_id)? {
3222            return Err(StoreError::InvalidTransition(format!(
3223                "candidate `{candidate_op_id}` has a standing Reject review on stage                  `{winner_stage_id}`; record an Approve review (or promote a different                  candidate) before promoting"
3224            )));
3225        }
3226
3227        // Gather every OTHER live candidate for this sig — the
3228        // ones this Promote will supersede.
3229        let live = self.list_candidates(&sig)?;
3230        let mut supersedes: Vec<lex_vcs::OpId> = live
3231            .iter()
3232            .filter(|c| &c.op_id != candidate_op_id)
3233            .map(|c| c.op_id.clone())
3234            .collect();
3235        supersedes.sort();
3236
3237        // Assemble candidate program: winner stage in place of
3238        // the sig's current head (if any), plus every other sig
3239        // unchanged.
3240        let head = self.branch_head(branch)?;
3241        let winner_stage = self.get_ast(&winner_stage_id)?;
3242        let mut candidate_program: Vec<lex_ast::Stage> = Vec::with_capacity(head.len() + 1);
3243        let mut found = false;
3244        for (other_sig, other_stage_id) in &head {
3245            if other_sig == &sig {
3246                candidate_program.push(winner_stage.clone());
3247                found = true;
3248            } else {
3249                candidate_program.push(self.get_ast(other_stage_id)?);
3250            }
3251        }
3252        if !found {
3253            // Sig doesn't have a head yet — append the winner
3254            // stage to make it a Create.
3255            candidate_program.push(winner_stage.clone());
3256        }
3257        let from_stage_id = head.get(&sig).cloned();
3258        // Budget delta from old head to winner — same shape as
3259        // ModifyBody.
3260        let from_budget = from_stage_id
3261            .as_deref()
3262            .and_then(|s| self.get_ast(s).ok())
3263            .and_then(|s| budget_of_stage(&s));
3264        let to_budget = budget_of_stage(&winner_stage);
3265
3266        let head_now = self.get_branch(branch)?.and_then(|b| b.head_op);
3267        let op = lex_vcs::Operation::new(
3268            lex_vcs::OperationKind::Promote {
3269                sig_id: sig.clone(),
3270                winner_candidate: candidate_op_id.clone(),
3271                winner_stage_id: winner_stage_id.clone(),
3272                supersedes,
3273                from_stage_id: from_stage_id.clone(),
3274                from_budget,
3275                to_budget,
3276            },
3277            head_now.into_iter().collect::<Vec<_>>(),
3278        );
3279        let transition = match &from_stage_id {
3280            Some(from) => lex_vcs::StageTransition::Replace {
3281                sig_id: sig,
3282                from: from.clone(),
3283                to: winner_stage_id,
3284            },
3285            None => lex_vcs::StageTransition::Create {
3286                sig_id: sig,
3287                stage_id: winner_stage_id,
3288            },
3289        };
3290        self.apply_operation_checked(branch, op, transition, &candidate_program)
3291    }
3292
3293    /// `set_branch_head_op` for the durability story on the branch
3294    /// file itself.
3295    pub fn apply_operation(
3296        &self,
3297        branch: &str,
3298        op: lex_vcs::Operation,
3299        transition: lex_vcs::StageTransition,
3300    ) -> Result<lex_vcs::OpId, StoreError> {
3301        let attestable = attestable_stage_ids(&transition);
3302        let op_effects = op_declared_effects(&op.kind);
3303        self.cas_retry_advance(branch, op, transition, |new_head| {
3304            self.run_required_attestations_gate(branch, &new_head.op_id, &attestable, &op_effects)
3305        })
3306    }
3307
3308    /// CAS retry loop for #262. Single-parent ops are rebuilt on
3309    /// each iteration with the current branch head as parent;
3310    /// the per-iteration callback runs the gate (and TypeCheck
3311    /// emission, for the checked path) between persist and CAS.
3312    /// Merge ops (with 2 parents already set) skip the rebuild —
3313    /// their parents are caller-supplied and meaningful — and get
3314    /// a single attempt; on CAS failure they surface `Contention`.
3315    fn cas_retry_advance<F>(
3316        &self,
3317        branch: &str,
3318        op: lex_vcs::Operation,
3319        transition: lex_vcs::StageTransition,
3320        mut between_persist_and_cas: F,
3321    ) -> Result<lex_vcs::OpId, StoreError>
3322    where
3323        F: FnMut(&lex_vcs::NewHead) -> Result<(), StoreError>,
3324    {
3325        // 32 retries handles up to ~32 concurrent writers racing on
3326        // the same branch tip. Beyond that, surfacing `Contention`
3327        // is the right signal — clients should back off or batch.
3328        const MAX_ATTEMPTS: u32 = 32;
3329        // Single-parent ops can be rebuilt on retry; merge ops
3330        // can't (their two parents are meaningful, supplied by the
3331        // merge engine). For merges, single attempt: if CAS
3332        // fails, surface Contention.
3333        let is_rebuildable = op.parents.len() <= 1;
3334        let kind = op.kind.clone();
3335        let intent_id = op.intent_id.clone();
3336
3337        let mut last_io_err: Option<StoreError> = None;
3338        let mut current_op = op;
3339        let current_transition = transition;
3340        // Only rebuild on retries — attempt 1 honors the caller's
3341        // exact op so a user-supplied bogus parent (parents =
3342        // ["someone-else"]) surfaces as `StaleParent` instead of
3343        // being silently corrected.
3344        //
3345        // Exception (#262 follow-up): an op with `parents = []`
3346        // means "I don't care; chain off whatever the current
3347        // head is." Under concurrent apply, attempt 1 can read
3348        // `head_op = Some(opA)` after a sibling writer landed,
3349        // and the persist's parent check fails StaleParent
3350        // unprompted. Rebuild attempt 1 for the empty-parents
3351        // case so the legitimate-race path retries cleanly.
3352        let mut rebuilt_already = false;
3353        for attempt in 1..=MAX_ATTEMPTS {
3354            // Read the current head BEFORE we persist — this is
3355            // the value we'll compare against in the CAS.
3356            let parent = self.get_branch(branch)?.and_then(|b| b.head_op);
3357
3358            // Rebuild the op against the current head, but only
3359            // on retries (not the caller's first attempt) and
3360            // only for single-parent operations. Multi-parent
3361            // (merge) ops are passed through unchanged.
3362            //
3363            // Empty-parents ops also rebuild on attempt 1 (see
3364            // the exception note above) so concurrent apply
3365            // doesn't false-positive on StaleParent.
3366            let should_rebuild = is_rebuildable
3367                && (rebuilt_already || (current_op.parents.is_empty() && parent.is_some()));
3368            if should_rebuild {
3369                current_op = lex_vcs::Operation {
3370                    kind: kind.clone(),
3371                    parents: parent.iter().cloned().collect(),
3372                    intent_id: intent_id.clone(),
3373                };
3374            }
3375
3376            // Persist (idempotent). On `StaleParent` from a retry
3377            // attempt (where we already rebuilt), the head changed
3378            // between our `get_branch` and this `lex_vcs::apply`
3379            // — race; rebuild and continue. On `StaleParent` from
3380            // attempt 1 (caller's input), propagate.
3381            let new_head = match self.persist_op_only_with_parent(
3382                branch,
3383                parent.as_ref(),
3384                current_op.clone(),
3385                current_transition.clone(),
3386            ) {
3387                Ok(nh) => nh,
3388                Err(StoreError::Apply(lex_vcs::ApplyError::StaleParent { .. }))
3389                    if is_rebuildable && rebuilt_already =>
3390                {
3391                    rebuilt_already = true;
3392                    continue;
3393                }
3394                Err(e) => return Err(e),
3395            };
3396
3397            // Run the caller's between-persist-and-cas hook
3398            // (TypeCheck emission + gate). If this fails, the op
3399            // record is durable but orphaned — same semantics as
3400            // pre-#262.
3401            between_persist_and_cas(&new_head)?;
3402
3403            // CAS the branch head. On success: done. On mismatch:
3404            // someone advanced in parallel; retry.
3405            match self.set_branch_head_op_cas(branch, parent, new_head.op_id.clone()) {
3406                Ok(()) => return Ok(new_head.op_id),
3407                Err(crate::branches::CasFailed::Mismatch { .. }) if is_rebuildable => {
3408                    // Try again with the new head as parent.
3409                    rebuilt_already = true;
3410                    continue;
3411                }
3412                Err(crate::branches::CasFailed::Mismatch { .. }) => {
3413                    // Merge op: surface immediately — we can't
3414                    // rebuild without rerunning the merge engine.
3415                    let _ = attempt;
3416                    return Err(StoreError::Contention {
3417                        branch: branch.into(),
3418                        attempts: 1,
3419                    });
3420                }
3421                Err(crate::branches::CasFailed::UnknownBranch(b)) => {
3422                    return Err(StoreError::UnknownBranch(b));
3423                }
3424                Err(crate::branches::CasFailed::Io(e)) => {
3425                    last_io_err = Some(StoreError::Io(std::io::Error::other(e)));
3426                    continue;
3427                }
3428            }
3429        }
3430        // Retries exhausted. Prefer surfacing the most recent IO
3431        // error if we hit one; otherwise it's pure CAS contention.
3432        match last_io_err {
3433            Some(e) => Err(e),
3434            None => Err(StoreError::Contention {
3435                branch: branch.into(),
3436                attempts: MAX_ATTEMPTS,
3437            }),
3438        }
3439    }
3440
3441    /// Persist an op against an explicitly-supplied parent. Used
3442    /// by the CAS retry loop in `cas_retry_advance` so the
3443    /// `lex_vcs::apply` parent check matches what we read at the
3444    /// top of the loop iteration (avoids a TOCTOU race against
3445    /// `persist_op_only`'s second read).
3446    fn persist_op_only_with_parent(
3447        &self,
3448        branch: &str,
3449        parent: Option<&lex_vcs::OpId>,
3450        op: lex_vcs::Operation,
3451        transition: lex_vcs::StageTransition,
3452    ) -> Result<lex_vcs::NewHead, StoreError> {
3453        if branch != DEFAULT_BRANCH && self.get_branch(branch)?.is_none() {
3454            return Err(StoreError::UnknownBranch(branch.into()));
3455        }
3456        let log = lex_vcs::OpLog::open(self.root())?;
3457        lex_vcs::apply(&log, parent, op, transition).map_err(|e| match e {
3458            lex_vcs::ApplyError::Persist(io) => StoreError::Io(io),
3459            other => StoreError::Apply(other),
3460        })
3461    }
3462
3463    /// Run the `required_attestations` gate (#245) and the
3464    /// retroactive producer-block gate (#248) over a single op
3465    /// against the store's `policy.json` and attestation log.
3466    ///
3467    /// Failure modes (in order):
3468    ///
3469    /// 1. Producer-block first: if any attestation on the op's
3470    ///    stage is from a quarantined tool, refuse with
3471    ///    `ProducerBlocked` (#248). Surfaces *before* the
3472    ///    required-attestations gate so a clearly-malicious record
3473    ///    isn't masked by a missing-Spec error.
3474    /// 2. Required-attestations next: if any required attestation
3475    ///    kind is missing, refuse with `BranchAdvanceBlocked`
3476    ///    (#245).
3477    ///
3478    /// Loads the policy / attestation log lazily; with no policy
3479    /// file and no `ProducerBlock` attestations the gate is a no-op
3480    /// (default-permissive — matches pre-#245 stores).
3481    fn run_required_attestations_gate(
3482        &self,
3483        branch: &str,
3484        op_id: &lex_vcs::OpId,
3485        stage_ids: &[String],
3486        op_effects: &std::collections::BTreeSet<String>,
3487    ) -> Result<(), StoreError> {
3488        // Build the candidate slice for the new op. Ops with no
3489        // attestable stage (imports, empty merges) get a single
3490        // `None`-stage tuple; both gates skip those.
3491        let new_op_candidate: Vec<(
3492            lex_vcs::OpId,
3493            Option<String>,
3494            std::collections::BTreeSet<String>,
3495        )> = if stage_ids.is_empty() {
3496            vec![(op_id.clone(), None, op_effects.clone())]
3497        } else {
3498            stage_ids
3499                .iter()
3500                .map(|sid| (op_id.clone(), Some(sid.clone()), op_effects.clone()))
3501                .collect()
3502        };
3503        let attest_log = self.attestation_log()?;
3504
3505        // #248 + #256: producer-block gate, walk-back style.
3506        //
3507        // The naive #248 gate only checked the new op's stage. That
3508        // missed contamination on ancestors — once `lex attest
3509        // retro-block` lands, every previously-gated op stays in
3510        // the chain even though its attestations are now from a
3511        // quarantined producer.
3512        //
3513        // #256 fixes this by walking the chain from `head_op` back
3514        // to `last_gate_checkpoint` (or genesis when the checkpoint
3515        // is invalidated), collecting each ancestor's attestable
3516        // stages, and running `check_producer_block` on the
3517        // combined set. After a successful advance,
3518        // `set_branch_head_op` moves the checkpoint to the new
3519        // head (steady-state O(new ops) per advance).
3520        let walk_back_candidate = self.collect_ancestor_candidates(branch)?;
3521        let mut producer_block_candidate = walk_back_candidate;
3522        producer_block_candidate.extend(new_op_candidate.iter().cloned());
3523        crate::policy::check_producer_block(&attest_log, &producer_block_candidate)
3524            .map_err(StoreError::ProducerBlocked)?;
3525
3526        // #245: required-attestations gate. Forward-going only —
3527        // only the new op is checked. Walking back makes no sense
3528        // here: the policy is "this advance must carry these
3529        // attestations," not "every prior op must have."
3530        let policy = match crate::policy::load(self.root())? {
3531            Some(p) if !p.required_attestations.is_empty() => p,
3532            _ => return Ok(()),
3533        };
3534        let waivers =
3535            crate::policy::check_required_attestations(&attest_log, &new_op_candidate, &policy)
3536                .map_err(StoreError::BranchAdvanceBlocked)?;
3537        // #293: emit one `TrustWaived` attestation per waiver so
3538        // the audit trail records every skip. Idempotent on
3539        // attestation_id (content-addressed dedup) — re-running
3540        // the gate with the same state writes the same files.
3541        for w in waivers {
3542            let att = lex_vcs::Attestation::new(
3543                w.stage_id,
3544                Some(op_id.clone()),
3545                None,
3546                lex_vcs::AttestationKind::TrustWaived {
3547                    producer: w.producer,
3548                    score_thousandths: w.score_thousandths,
3549                    threshold_thousandths: w.threshold_thousandths,
3550                    kind_tag: w.kind_tag,
3551                },
3552                lex_vcs::AttestationResult::Passed,
3553                trust_waived_producer(),
3554                None,
3555            );
3556            attest_log.put(&att)?;
3557        }
3558        Ok(())
3559    }
3560
3561    /// Walk the branch from `head_op` back to `last_gate_checkpoint`
3562    /// (exclusive) and return the `(op_id, stage_id, op_effects)`
3563    /// tuples for every attestable stage touched by an ancestor
3564    /// (#256). Empty when the branch is fresh, when the checkpoint
3565    /// equals the head, or when the head is None.
3566    fn collect_ancestor_candidates(&self, branch: &str) -> Result<Vec<GateCandidate>, StoreError> {
3567        let b = match self.get_branch(branch)? {
3568            Some(b) => b,
3569            None => return Ok(Vec::new()),
3570        };
3571        let Some(head) = b.head_op else {
3572            return Ok(Vec::new());
3573        };
3574        if Some(&head) == b.last_gate_checkpoint.as_ref() {
3575            // Steady-state common case: previous advance left the
3576            // checkpoint at head. Nothing to re-walk.
3577            return Ok(Vec::new());
3578        }
3579
3580        let log = lex_vcs::OpLog::open(self.root())?;
3581        let walk = log.walk_back(&head, None)?;
3582        let stop_at = b.last_gate_checkpoint.clone();
3583        let mut out = Vec::new();
3584        for rec in walk {
3585            if Some(&rec.op_id) == stop_at.as_ref() {
3586                break;
3587            }
3588            let stages = attestable_stage_ids(&rec.produces);
3589            let effects = op_declared_effects(&rec.op.kind);
3590            if stages.is_empty() {
3591                out.push((rec.op_id.clone(), None, effects));
3592            } else {
3593                for sid in stages {
3594                    out.push((rec.op_id.clone(), Some(sid), effects.clone()));
3595                }
3596            }
3597        }
3598        Ok(out)
3599    }
3600}
3601
3602fn stage_name(stage: &Stage) -> &str {
3603    match stage {
3604        Stage::FnDecl(fd) => &fd.name,
3605        Stage::TypeDecl(td) => &td.name,
3606        Stage::Import(i) => &i.alias,
3607    }
3608}
3609
3610fn stage_for_kind<'a>(
3611    kind: &lex_vcs::OperationKind,
3612    stages: &'a [lex_ast::Stage],
3613) -> Option<&'a lex_ast::Stage> {
3614    use lex_vcs::OperationKind::*;
3615    let target_sig = match kind {
3616        AddFunction { sig_id, .. }
3617        | ModifyBody { sig_id, .. }
3618        | ChangeEffectSig { sig_id, .. }
3619        | AddType { sig_id, .. }
3620        | ModifyType { sig_id, .. } => Some(sig_id.clone()),
3621        RenameSymbol { to, .. } => Some(to.clone()),
3622        _ => None,
3623    };
3624    let target_sig = target_sig?;
3625    stages
3626        .iter()
3627        .find(|s| sig_id(s).as_deref() == Some(target_sig.as_str()))
3628}
3629
3630fn transition_for_kind(kind: &lex_vcs::OperationKind) -> lex_vcs::StageTransition {
3631    use lex_vcs::OperationKind::*;
3632    use lex_vcs::StageTransition;
3633    match kind {
3634        AddFunction {
3635            sig_id, stage_id, ..
3636        }
3637        | AddType { sig_id, stage_id, .. } => StageTransition::Create {
3638            sig_id: sig_id.clone(),
3639            stage_id: stage_id.clone(),
3640        },
3641        RemoveFunction {
3642            sig_id,
3643            last_stage_id,
3644        }
3645        | RemoveType {
3646            sig_id,
3647            last_stage_id,
3648        } => StageTransition::Remove {
3649            sig_id: sig_id.clone(),
3650            last: last_stage_id.clone(),
3651        },
3652        ModifyBody {
3653            sig_id,
3654            from_stage_id,
3655            to_stage_id,
3656            ..
3657        }
3658        | ChangeEffectSig {
3659            sig_id,
3660            from_stage_id,
3661            to_stage_id,
3662            ..
3663        }
3664        | ModifyType {
3665            sig_id,
3666            from_stage_id,
3667            to_stage_id,
3668        }
3669        | ReplaceMatchArm {
3670            sig_id,
3671            from_stage_id,
3672            to_stage_id,
3673            ..
3674        }
3675        | RenameLocal {
3676            sig_id,
3677            from_stage_id,
3678            to_stage_id,
3679            ..
3680        }
3681        | InlineLet {
3682            sig_id,
3683            from_stage_id,
3684            to_stage_id,
3685            ..
3686        } => StageTransition::Replace {
3687            sig_id: sig_id.clone(),
3688            from: from_stage_id.clone(),
3689            to: to_stage_id.clone(),
3690        },
3691        RenameSymbol {
3692            from,
3693            to,
3694            body_stage_id,
3695        } => StageTransition::Rename {
3696            from: from.clone(),
3697            to: to.clone(),
3698            body_stage_id: body_stage_id.clone(),
3699        },
3700        AddImport { .. } | RemoveImport { .. } => StageTransition::ImportOnly,
3701        Merge { .. } => StageTransition::Merge {
3702            entries: Default::default(),
3703        },
3704        // #294: a Candidate proposes a stage without advancing
3705        // the branch. ImportOnly keeps the branch head untouched
3706        // — the stage IS published on disk (Store::propose_candidate
3707        // calls publish before apply), but no head delta lands.
3708        Candidate { .. } => StageTransition::ImportOnly,
3709        // A Promote advances the head exactly like ModifyBody
3710        // (or Create when the sig had no head). The winner
3711        // stage is the new branch state for that sig.
3712        Promote {
3713            sig_id,
3714            winner_stage_id,
3715            from_stage_id,
3716            ..
3717        } => match from_stage_id {
3718            Some(from) => StageTransition::Replace {
3719                sig_id: sig_id.clone(),
3720                from: from.clone(),
3721                to: winner_stage_id.clone(),
3722            },
3723            None => StageTransition::Create {
3724                sig_id: sig_id.clone(),
3725                stage_id: winner_stage_id.clone(),
3726            },
3727        },
3728    }
3729}
3730
3731/// Producer identity for TypeCheck attestations emitted by the
3732/// store-write gate. Pinned to this crate's name + version so an
3733/// attestation produced by a different `lex-store` revision is
3734/// distinguishable (content-hashed `produced_by`).
3735fn typecheck_producer() -> lex_vcs::ProducerDescriptor {
3736    lex_vcs::ProducerDescriptor {
3737        tool: "lex-store".into(),
3738        version: env!("CARGO_PKG_VERSION").into(),
3739        model: None,
3740    }
3741}
3742
3743/// Producer for attestations the hosted CI runner writes (#93). A
3744/// distinct tool name so a `require-attestation` gate — via the
3745/// producer-trust model — can weight "the hub verified this
3746/// server-side" above a client-attached `TypeCheck`.
3747fn hub_ci_producer() -> lex_vcs::ProducerDescriptor {
3748    lex_vcs::ProducerDescriptor {
3749        tool: "lex-hub-ci".into(),
3750        version: env!("CARGO_PKG_VERSION").into(),
3751        model: None,
3752    }
3753}
3754
3755/// Verdict of a hosted-CI run over a branch head (#93).
3756#[derive(Debug, Clone, serde::Serialize)]
3757pub struct HubCiVerdict {
3758    pub passed: bool,
3759    pub checked_stages: usize,
3760    pub attested_stages: usize,
3761    #[serde(skip_serializing_if = "Option::is_none")]
3762    pub detail: Option<String>,
3763}
3764
3765/// Producer for the replay-comparison attestation (#836 G3). Distinct
3766/// tool name so the comparison lex performed is attributable
3767/// separately from the (external) regeneration.
3768fn replay_producer() -> lex_vcs::ProducerDescriptor {
3769    lex_vcs::ProducerDescriptor {
3770        tool: "lex-store-replay".into(),
3771        version: env!("CARGO_PKG_VERSION").into(),
3772        model: None,
3773    }
3774}
3775
3776/// Human/audit label for a recorded model: `provider/name` (`@version`
3777/// when pinned).
3778fn model_label(m: &lex_vcs::ModelDescriptor) -> String {
3779    match &m.version {
3780        Some(v) => format!("{}/{}@{}", m.provider, m.name, v),
3781        None => format!("{}/{}", m.provider, m.name),
3782    }
3783}
3784
3785/// The `(sig_id, stage_id)` an op recorded producing, or `None` for a
3786/// transition that produces no stage (removal / import / merge) — those
3787/// have nothing to regenerate for a replay.
3788fn produced_sig_stage(t: &lex_vcs::StageTransition) -> Option<(String, String)> {
3789    use lex_vcs::StageTransition::*;
3790    match t {
3791        Create { sig_id, stage_id } => Some((sig_id.clone(), stage_id.clone())),
3792        Replace { sig_id, to, .. } => Some((sig_id.clone(), to.clone())),
3793        Rename { to, body_stage_id, .. } => Some((to.clone(), body_stage_id.clone())),
3794        Remove { .. } | ImportOnly | Merge { .. } => None,
3795    }
3796}
3797
3798/// Producer identity for `Examples::Passed` attestations emitted by
3799/// [`Store::record_examples_passed`] (#835). Distinct tool name so
3800/// the activity feed can tell an auto-emitted publish-time examples
3801/// verdict apart from an `lex agent-tool --examples` one.
3802fn examples_producer() -> lex_vcs::ProducerDescriptor {
3803    lex_vcs::ProducerDescriptor {
3804        tool: "lex-store::examples".into(),
3805        version: env!("CARGO_PKG_VERSION").into(),
3806        model: None,
3807    }
3808}
3809
3810/// Producer identity for `Review` attestations (#836). The reviewer's
3811/// own id lives in the kind; this records which tool minted the record.
3812fn review_producer(reviewer: &str) -> lex_vcs::ProducerDescriptor {
3813    lex_vcs::ProducerDescriptor {
3814        tool: format!("lex-store::review:{reviewer}"),
3815        version: env!("CARGO_PKG_VERSION").into(),
3816        model: None,
3817    }
3818}
3819
3820/// Producer identity for `RepairHint` attestations emitted by
3821/// `apply_operation_checked` on TypeError (#281). Distinct tool
3822/// name from `typecheck_producer` so consumers can filter the
3823/// activity feed for repair hints without scanning kinds.
3824fn repair_hint_producer() -> lex_vcs::ProducerDescriptor {
3825    lex_vcs::ProducerDescriptor {
3826        tool: "lex-store::repair_hint".into(),
3827        version: env!("CARGO_PKG_VERSION").into(),
3828        model: None,
3829    }
3830}
3831
3832/// Producer identity for `TrustWaived` attestations emitted by
3833/// the `required_attestations` gate on a trust-driven waiver
3834/// (#293). Distinct from `typecheck_producer` and `repair_hint`
3835/// so the audit trail clearly shows "the gate let this advance
3836/// through because trust > threshold."
3837fn trust_waived_producer() -> lex_vcs::ProducerDescriptor {
3838    lex_vcs::ProducerDescriptor {
3839        tool: "lex-store::trust_waived".into(),
3840        version: env!("CARGO_PKG_VERSION").into(),
3841        model: None,
3842    }
3843}
3844
3845/// Producer identity for `ProducerTrust` attestations emitted by
3846/// [`Store::recompute_producer_trust`]. The score-derivation
3847/// recompute is its own machine-emittable kind, distinct from
3848/// the gate-side `TrustWaived` emit (#293).
3849fn producer_trust_producer() -> lex_vcs::ProducerDescriptor {
3850    lex_vcs::ProducerDescriptor {
3851        tool: "lex-store::producer_trust".into(),
3852        version: env!("CARGO_PKG_VERSION").into(),
3853        model: None,
3854    }
3855}
3856
3857/// The set of stage_ids a transition introduces. These are the
3858/// stages a successful TypeCheck pass attests *about* — the new
3859/// head produced by Create/Replace, the renamed body, or the per-
3860/// sig resolution of a Merge. Removes and ImportOnly produce no
3861/// attestable stage; the program typechecks but no specific stage
3862/// is the subject of the claim.
3863/// One row of input to the producer-block / required-attestations
3864/// gates: `(op_id, stage_id, op_effects)`. The `stage_id` is
3865/// `None` for ops that don't touch a stage (imports, empty
3866/// merges) — the gate skips those.
3867type GateCandidate = (
3868    lex_vcs::OpId,
3869    Option<String>,
3870    std::collections::BTreeSet<String>,
3871);
3872
3873/// Effect set declared *by the operation itself* (#245). Used by
3874/// the `required_attestations` gate's `EffectsIntersect` clause.
3875///
3876/// Only `AddFunction` and `ChangeEffectSig` carry an effect set in
3877/// their op payload; for everything else this returns the empty
3878/// set, which means `EffectsIntersect` rules don't fire on those
3879/// ops. `Always` rules continue to fire regardless. A future
3880/// improvement is to extract effects from the candidate `Stage`
3881/// for `ModifyBody` ops, but the typed-effects-on-ops path (#247)
3882/// is the cleaner solution and lands separately.
3883fn op_declared_effects(kind: &lex_vcs::OperationKind) -> std::collections::BTreeSet<String> {
3884    use lex_vcs::OperationKind::*;
3885    match kind {
3886        AddFunction { effects, .. } => effects.clone(),
3887        ChangeEffectSig { to_effects, .. } => to_effects.clone(),
3888        _ => std::collections::BTreeSet::new(),
3889    }
3890}
3891
3892fn attestable_stage_ids(transition: &lex_vcs::StageTransition) -> Vec<String> {
3893    use lex_vcs::StageTransition::*;
3894    match transition {
3895        Create { stage_id, .. } => vec![stage_id.clone()],
3896        Replace { to, .. } => vec![to.clone()],
3897        Rename { body_stage_id, .. } => vec![body_stage_id.clone()],
3898        Merge { entries } => entries.values().filter_map(|opt| opt.clone()).collect(),
3899        Remove { .. } | ImportOnly => Vec::new(),
3900    }
3901}
3902
3903/// True when two `FnDecl`s are identical except for their body — the
3904/// precondition for a pure intra-body three-way merge (#838). The
3905/// signature fields are equal by construction when both share a
3906/// `sig_id`; this also guards the non-signature fields (`type_params`,
3907/// `examples`) so a side that changed those isn't silently dropped.
3908fn fndecl_same_except_body(a: &lex_ast::FnDecl, b: &lex_ast::FnDecl) -> bool {
3909    a.name == b.name
3910        && a.type_params == b.type_params
3911        && a.params == b.params
3912        && a.effects == b.effects
3913        && a.effect_row_var == b.effect_row_var
3914        && a.return_type == b.return_type
3915        && a.examples == b.examples
3916}
3917
3918fn write_canonical_json<T: Serialize>(path: &Path, value: &T) -> Result<(), StoreError> {
3919    let v = serde_json::to_value(value)?;
3920    let s = lex_ast::canon_json::to_canonical_string(&v);
3921    if let Some(parent) = path.parent() {
3922        fs::create_dir_all(parent)?;
3923    }
3924    fs::write(path, s)?;
3925    Ok(())
3926}
3927
3928/// Read the `name` of the `Let` expression at `let_node` inside
3929/// `stage`'s body. Used by [`Store::apply_rename_local`] to record
3930/// the rename source. Returns the same `TransformError` shapes as
3931/// the transformer itself so callers see a consistent error
3932/// vocabulary.
3933fn read_let_name(
3934    stage: &Stage,
3935    let_node: &lex_ast::NodeId,
3936) -> Result<String, lex_ast::TransformError> {
3937    // The transformer is itself a pure function; ask it to perform
3938    // a rename to a sentinel value and read the resulting let's
3939    // original name from the output. Cheaper than duplicating the
3940    // node-walk here, and stays correct as the transform evolves.
3941    //
3942    // We use a sentinel that's invalid as a Lex identifier so even
3943    // if the rename somehow lands, downstream parsing would
3944    // surface it loudly. (The transform path discards the renamed
3945    // value — we only need the *original* name.)
3946    let probed = lex_ast::rename_local(stage, let_node, "__lex_rename_probe__")?;
3947    let Stage::FnDecl(fd) = probed else {
3948        return Err(lex_ast::TransformError::NonFnTarget {
3949            stage_kind: "non-FnDecl",
3950        });
3951    };
3952    // Walk back to the probed let to read its old name from the
3953    // *original* stage — the probed stage's let has already been
3954    // renamed.
3955    let Stage::FnDecl(orig_fd) = stage else {
3956        return Err(lex_ast::TransformError::NonFnTarget {
3957            stage_kind: "non-FnDecl",
3958        });
3959    };
3960    // Path-based lookup matches the transformer's navigation.
3961    let path = parse_let_node_path(let_node.as_str())?;
3962    if path.is_empty() {
3963        return Err(lex_ast::TransformError::NotALet {
3964            at: let_node.as_str().into(),
3965            found_kind: "stage_root",
3966        });
3967    }
3968    if path[0] != orig_fd.params.len() + 1 {
3969        return Err(lex_ast::TransformError::UnknownNode {
3970            at: let_node.as_str().into(),
3971        });
3972    }
3973    let inner = &path[1..];
3974    let target = navigate_to_let(&orig_fd.body, inner, let_node.as_str())?;
3975    let _ = fd; // probed stage discarded
3976    Ok(target.to_string())
3977}
3978
3979fn parse_let_node_path(id: &str) -> Result<Vec<usize>, lex_ast::TransformError> {
3980    let s = id
3981        .strip_prefix("n_")
3982        .ok_or_else(|| lex_ast::TransformError::BadNodeId(id.into()))?;
3983    let mut parts = s.split('.');
3984    let head = parts
3985        .next()
3986        .ok_or_else(|| lex_ast::TransformError::BadNodeId(id.into()))?;
3987    if head != "0" {
3988        return Err(lex_ast::TransformError::BadNodeId(id.into()));
3989    }
3990    let mut out = Vec::new();
3991    for p in parts {
3992        out.push(
3993            p.parse::<usize>()
3994                .map_err(|_| lex_ast::TransformError::BadNodeId(id.into()))?,
3995        );
3996    }
3997    Ok(out)
3998}
3999
4000fn navigate_to_let<'a>(
4001    root: &'a lex_ast::CExpr,
4002    path: &[usize],
4003    at: &str,
4004) -> Result<&'a str, lex_ast::TransformError> {
4005    use lex_ast::CExpr::*;
4006    let mut current = root;
4007    for &idx in path {
4008        current = match current {
4009            Call { callee, args } => {
4010                if idx == 0 {
4011                    callee
4012                } else {
4013                    args.get(idx - 1)
4014                        .ok_or_else(|| lex_ast::TransformError::UnknownNode { at: at.into() })?
4015                }
4016            }
4017            Let { value, body, .. } => match idx {
4018                0 => value,
4019                1 => body,
4020                _ => return Err(lex_ast::TransformError::UnknownNode { at: at.into() }),
4021            },
4022            Match { scrutinee, arms } => {
4023                if idx == 0 {
4024                    scrutinee
4025                } else {
4026                    let arm_off = idx - 1;
4027                    if arm_off % 2 != 1 {
4028                        return Err(lex_ast::TransformError::UnknownNode { at: at.into() });
4029                    }
4030                    let arm_index = arm_off / 2;
4031                    &arms
4032                        .get(arm_index)
4033                        .ok_or_else(|| lex_ast::TransformError::UnknownNode { at: at.into() })?
4034                        .body
4035                }
4036            }
4037            Block { statements, result } => {
4038                if idx < statements.len() {
4039                    &statements[idx]
4040                } else if idx == statements.len() {
4041                    result
4042                } else {
4043                    return Err(lex_ast::TransformError::UnknownNode { at: at.into() });
4044                }
4045            }
4046            Constructor { args, .. }
4047            | TupleLit { items: args, .. }
4048            | ListLit { items: args, .. } => args
4049                .get(idx)
4050                .ok_or_else(|| lex_ast::TransformError::UnknownNode { at: at.into() })?,
4051            RecordLit { fields } => {
4052                &fields
4053                    .get(idx)
4054                    .ok_or_else(|| lex_ast::TransformError::UnknownNode { at: at.into() })?
4055                    .value
4056            }
4057            FieldAccess { value, .. } if idx == 0 => value,
4058            Lambda { body, .. } if idx == 0 => body,
4059            BinOp { lhs, rhs, .. } => match idx {
4060                0 => lhs,
4061                1 => rhs,
4062                _ => return Err(lex_ast::TransformError::UnknownNode { at: at.into() }),
4063            },
4064            UnaryOp { expr, .. } if idx == 0 => expr,
4065            Return { value } if idx == 0 => value,
4066            _ => return Err(lex_ast::TransformError::UnknownNode { at: at.into() }),
4067        };
4068    }
4069    let Let { name, .. } = current else {
4070        return Err(lex_ast::TransformError::NotALet {
4071            at: at.into(),
4072            found_kind: lex_cexpr_kind(current),
4073        });
4074    };
4075    Ok(name)
4076}
4077
4078fn lex_cexpr_kind(e: &lex_ast::CExpr) -> &'static str {
4079    use lex_ast::CExpr::*;
4080    match e {
4081        Literal { .. } => "Literal",
4082        Var { .. } => "Var",
4083        Call { .. } => "Call",
4084        Let { .. } => "Let",
4085        Match { .. } => "Match",
4086        Block { .. } => "Block",
4087        Constructor { .. } => "Constructor",
4088        RecordLit { .. } => "RecordLit",
4089        TupleLit { .. } => "TupleLit",
4090        ListLit { .. } => "ListLit",
4091        FieldAccess { .. } => "FieldAccess",
4092        Lambda { .. } => "Lambda",
4093        BinOp { .. } => "BinOp",
4094        UnaryOp { .. } => "UnaryOp",
4095        Return { .. } => "Return",
4096    }
4097}
4098
4099/// Extract the declared `[budget(N)]` integer from a stage's
4100/// effect set, if any (#280 + #247). Returns `None` for stages
4101/// that aren't `FnDecl` or don't carry a budget effect — same
4102/// shape as `lex_vcs::budget_from_effects`.
4103fn budget_of_stage(stage: &Stage) -> Option<u64> {
4104    let fd = match stage {
4105        Stage::FnDecl(fd) => fd,
4106        _ => return None,
4107    };
4108    let mut min_cost: Option<u64> = None;
4109    for eff in &fd.effects {
4110        if eff.name != "budget" {
4111            continue;
4112        }
4113        if let Some(lex_ast::EffectArg::Int { value }) = &eff.arg {
4114            let n = *value as u64;
4115            min_cost = Some(min_cost.map(|c| c.min(n)).unwrap_or(n));
4116        }
4117    }
4118    min_cost
4119}
4120
4121/// Serialize a stage to its canonical-JSON byte form. Used by
4122/// `publish_signed` for delta encoding (#261 slice 3) — both the
4123/// "compute the diff" path and the "write a full snapshot"
4124/// fallback need exactly the same bytes.
4125fn canonical_bytes(stage: &Stage) -> Result<Vec<u8>, StoreError> {
4126    let v = serde_json::to_value(stage)?;
4127    Ok(lex_ast::canon_json::to_canonical_string(&v).into_bytes())
4128}
4129
4130#[allow(dead_code)]
4131fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, StoreError> {
4132    let bytes = fs::read(path)?;
4133    Ok(serde_json::from_slice(&bytes)?)
4134}