Skip to main content

lex_api/
handlers.rs

1//! Request routing for the agent API.
2//!
3//! Each handler is a synchronous function that returns
4//! `Result<serde_json::Value, ApiError>`. The dispatcher wraps the result
5//! in an HTTP response — successes as 200 with the JSON body, structured
6//! errors as 4xx/5xx with a JSON envelope.
7
8use indexmap::IndexMap;
9use lex_ast::canonicalize_program;
10use lex_bytecode::{compile_program, vm::Vm, Value};
11use lex_runtime::{check_program as check_policy, DefaultHandler, Policy};
12use lex_store::Store;
13use crate::publish_examples::record_examples_for_publish;
14use lex_syntax::{load_package, load_program_from_str, Manifest};
15use lex_vcs::{MergeSession, MergeSessionId};
16use serde::{Deserialize, Serialize};
17use std::collections::{BTreeMap, BTreeSet, HashMap};
18use std::path::PathBuf;
19use std::sync::{Arc, Mutex};
20use std::time::{SystemTime, UNIX_EPOCH};
21use tiny_http::{Header, Method, Request, Response};
22
23/// The function declarations in a canonicalized program, by name.
24fn stage_fns(stages: &[lex_ast::Stage]) -> BTreeMap<String, lex_ast::FnDecl> {
25    stages.iter().filter_map(|s| match s {
26        lex_ast::Stage::FnDecl(fd) => Some((fd.name.clone(), fd.clone())),
27        _ => None,
28    }).collect()
29}
30
31/// The type declarations in a canonicalized program, by name — so the
32/// publish diff captures `type`s alongside functions (#895).
33fn stage_types(stages: &[lex_ast::Stage]) -> BTreeMap<String, lex_ast::TypeDecl> {
34    stages.iter().filter_map(|s| match s {
35        lex_ast::Stage::TypeDecl(td) => Some((td.name.clone(), td.clone())),
36        _ => None,
37    }).collect()
38}
39
40pub struct State {
41    pub store: Mutex<Store>,
42    /// Filesystem root of the store. Held alongside the `Store`
43    /// itself so handlers that need to read store-level files
44    /// (e.g. `users.json` for actor auth) don't have to round-
45    /// trip through the lock.
46    pub root: PathBuf,
47    /// In-memory merge sessions, keyed by MergeSessionId. Sessions
48    /// are ephemeral by design (#134 foundation): they live for the
49    /// lifetime of the server process and are GC'd on commit. A
50    /// future slice can persist them to disk so a session survives
51    /// process restarts. For now an agent that gets unlucky with a
52    /// restart re-runs `merge/start` and gets a fresh session.
53    pub sessions: Mutex<HashMap<MergeSessionId, ApiMergeSession>>,
54    /// Optional server-imposed ceiling on the effect policy honored
55    /// by `/v1/run` and `/v1/replay`. `None` (the default, used by
56    /// single-tenant `lex serve`) runs the caller's request policy
57    /// as-is — the operator *is* the caller there, so that's
58    /// intended. When `Some`, the request policy is clamped via
59    /// [`clamp_policy`] so it can only *narrow* the ceiling, never
60    /// widen it.
61    ///
62    /// Any embedder that exposes this API to untrusted callers — a
63    /// hosted, multi-tenant gateway like lex-hub — MUST set this.
64    /// Without it the request body can grant itself `[proc]`
65    /// (arbitrary subprocess spawn), `[fs_*]` over `/`, and
66    /// unrestricted `[net]`: arbitrary code execution as the server
67    /// process. See lex-hub#6.
68    ///
69    /// NOTE: an empty scope list means "any path/host" in the
70    /// runtime, so a ceiling that puts `fs_read`/`fs_write`/`net` in
71    /// `allow_effects` MUST also populate the matching scope list
72    /// (`allow_fs_read`, …) or it re-opens the wildcard. Granting
73    /// none of those kinds is the safe default.
74    pub policy_ceiling: Option<Policy>,
75    /// Per-head op-history indexes and paged deltas behind
76    /// `/v1/ops/since` (#971), so a paged pull walks the op log once
77    /// instead of once per page. See [`crate::ops_since_http`].
78    pub(crate) ops_since: Mutex<crate::ops_since_http::OpsSinceCache>,
79    /// Optional server-imposed limits on the files-beside-the-op-log blob
80    /// space (#1007): `/v1/blobs/batch` refuses an oversize blob (413) or
81    /// one that would take the store past its quota (507), and
82    /// `/v1/ops/batch` refuses a `SetFiles` whose manifest has too many
83    /// entries. `None` (the default, single-tenant `lex serve`) is
84    /// unlimited. A hosted, multi-tenant embedder such as lex-hub should
85    /// set it — the same shape as [`policy_ceiling`](State::policy_ceiling).
86    pub blob_limits: Option<BlobLimits>,
87    /// `produced_by.tool` names that clients may NOT claim. Defaults to
88    /// empty (single-tenant `lex serve` and existing embedders behave
89    /// exactly as before). When non-empty, `POST /v1/attestations/batch`
90    /// refuses — `403` `ReservedProducer`, whole batch, nothing written —
91    /// any attestation whose `produced_by.tool` matches an entry. An entry
92    /// is an exact name, or — when it ends in `*` — a prefix
93    /// (`"lex-store::review:*"` reserves every `lex-store::review:<who>`
94    /// producer, whose suffix is variable). Matching trims and ASCII
95    /// case-folds both sides; blank entries are ignored.
96    ///
97    /// The point is to keep a name that only the server writes (the hub's
98    /// own `lex-hub-ci`, see `lex_store::HUB_CI_PRODUCER_TOOL`, and the
99    /// `lex-store::review:*` family, see `lex_store::REVIEW_PRODUCER_RESERVATION`)
100    /// from being minted by a tenant key holder. Server-internal writers
101    /// (`Store::verify_head_and_attest`, `record_review`, …) call the
102    /// store directly and are unaffected. A hosted embedder such as
103    /// lex-hub should set it; there is deliberately no default name here.
104    pub reserved_producers: Vec<String>,
105}
106
107/// Limits on one store's blob space (#1007). See [`State::blob_limits`].
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct BlobLimits {
110    /// Largest single blob accepted, in decoded bytes.
111    pub max_blob_bytes: u64,
112    /// Total decoded bytes the store's blob space may hold.
113    pub store_quota_bytes: u64,
114    /// Most entries a `SetFiles` manifest may name.
115    pub max_manifest_entries: usize,
116}
117
118/// Capabilities this server advertises on `/v1/health` (#1007). A client
119/// states the ones it speaks in the `X-Lex-Caps` request header
120/// (comma-separated).
121pub const CAPS: &[&str] = &[CAP_FILES_V1, CAP_INTENT_ORIGIN_V1];
122
123/// The server stores and serves `SetFiles` ops and their blobs (#1007).
124pub const CAP_FILES_V1: &str = "files-v1";
125
126/// The server stores and serves `Intent.origin` (#892) — the external-VCS
127/// provenance of an imported intent. A server without it deserializes an
128/// origin-bearing intent, silently drops the unknown field and re-stores an
129/// intent whose bytes no longer match its id, so `lex op push` refuses to
130/// send one to a hub that doesn't advertise this.
131pub const CAP_INTENT_ORIGIN_V1: &str = "intent-origin-v1";
132
133/// Whether an `X-Lex-Caps` header value names `cap`.
134pub(crate) fn has_cap(header: Option<&str>, cap: &str) -> bool {
135    header.is_some_and(|h| h.split(',').any(|c| c.trim().eq_ignore_ascii_case(cap)))
136}
137
138/// Server-side wrapper around [`MergeSession`] carrying the
139/// branch names that started the merge. The lex-vcs session
140/// itself only tracks `OpId` heads; commit needs the dst branch
141/// name to advance the right head, and the src branch name is
142/// kept for round-trip auditability ("which branch did we merge
143/// from?").
144pub struct ApiMergeSession {
145    pub inner: MergeSession,
146    pub src_branch: String,
147    pub dst_branch: String,
148}
149
150impl State {
151    pub fn open(root: PathBuf) -> anyhow::Result<Self> {
152        Self::open_with_ceiling(root, None)
153    }
154
155    /// Like [`State::open`] but installs a [`policy_ceiling`](State::policy_ceiling)
156    /// that `/v1/run` and `/v1/replay` clamp the caller's request
157    /// policy against. Embedders exposing this API to untrusted
158    /// callers must use this constructor (or set the field directly).
159    pub fn open_with_ceiling(
160        root: PathBuf,
161        policy_ceiling: Option<Policy>,
162    ) -> anyhow::Result<Self> {
163        Ok(Self {
164            store: Mutex::new(Store::open(&root)?),
165            root,
166            sessions: Mutex::new(HashMap::new()),
167            policy_ceiling,
168            ops_since: Mutex::new(Default::default()),
169            blob_limits: None,
170            reserved_producers: Vec::new(),
171        })
172    }
173
174    /// Install [`blob_limits`](State::blob_limits) (#1007).
175    pub fn with_blob_limits(mut self, limits: Option<BlobLimits>) -> Self {
176        self.blob_limits = limits;
177        self
178    }
179
180    /// Install [`reserved_producers`](State::reserved_producers): the
181    /// `produced_by.tool` names clients may not claim through the
182    /// attestation-writing HTTP endpoints.
183    pub fn with_reserved_producers(mut self, tools: Vec<String>) -> Self {
184        self.reserved_producers = tools;
185        self
186    }
187
188    /// The reserved producer name `att` claims, if any.
189    fn reserved_producer_claimed(&self, att: &lex_vcs::Attestation) -> Option<&str> {
190        let claimed = att.produced_by.tool.trim().to_ascii_lowercase();
191        self.reserved_producers.iter().map(String::as_str).find(|entry| {
192            let entry = entry.trim().to_ascii_lowercase();
193            match entry.strip_suffix('*') {
194                Some(prefix) => !prefix.is_empty() && claimed.starts_with(prefix),
195                None => !entry.is_empty() && claimed == entry,
196            }
197        })
198    }
199
200    /// Construct a per-tenant `State` by prefixing `store_root` with the
201    /// tenant id. Single-tenant `lex serve` is unaffected — it calls
202    /// `State::open` directly.
203    ///
204    /// `tenant_id` is restricted to `[A-Za-z0-9_-]{1,64}`: anything else
205    /// (path separators, `..`, NUL, absolute paths, dotfiles, empty
206    /// string) is rejected before touching the filesystem. Without this
207    /// `PathBuf::join("/etc")` would silently replace `store_root`, and
208    /// `PathBuf::join("../foo")` would escape the tenant root.
209    pub fn new_with_tenant(tenant_id: &str, store_root: PathBuf) -> anyhow::Result<Self> {
210        validate_tenant_id(tenant_id)?;
211        Self::open(store_root.join(tenant_id))
212    }
213
214    /// Multi-tenant constructor that also installs a policy ceiling
215    /// for `/v1/run` / `/v1/replay`. The path-traversal guard from
216    /// [`new_with_tenant`](State::new_with_tenant) and the effect
217    /// ceiling are the two halves a hosted gateway needs.
218    pub fn new_with_tenant_and_ceiling(
219        tenant_id: &str,
220        store_root: PathBuf,
221        policy_ceiling: Option<Policy>,
222    ) -> anyhow::Result<Self> {
223        validate_tenant_id(tenant_id)?;
224        Self::open_with_ceiling(store_root.join(tenant_id), policy_ceiling)
225    }
226}
227
228/// Clamp a caller-supplied [`Policy`] to a server-imposed `ceiling`
229/// so it can only *narrow* the granted capabilities, never widen
230/// them. Used by [`run_handler`] when [`State::policy_ceiling`] is
231/// set — i.e. when an embedder exposes `/v1/run` to untrusted
232/// callers and must not let the request body grant itself `[proc]`,
233/// arbitrary `[fs_*]` paths, or unrestricted `[net]`.
234///
235/// - **Effects**: set-intersection of request and ceiling. The
236///   caller may drop effects but never add one the ceiling withheld.
237/// - **Scopes** (fs paths, proc binaries, net hosts): taken from the
238///   ceiling outright. The caller cannot widen them, and — because an
239///   empty scope list means "any" in the runtime — we must not let a
240///   caller's empty list collapse the ceiling's restriction back to a
241///   wildcard.
242/// - **Budget**: the more restrictive (smaller) of the two.
243fn clamp_policy(requested: Policy, ceiling: &Policy) -> Policy {
244    let allow_effects: BTreeSet<String> = requested
245        .allow_effects
246        .intersection(&ceiling.allow_effects)
247        .cloned()
248        .collect();
249    let budget = match (requested.budget, ceiling.budget) {
250        (Some(r), Some(c)) => Some(r.min(c)),
251        (None, Some(c)) => Some(c),
252        (Some(r), None) => Some(r),
253        (None, None) => None,
254    };
255    Policy {
256        allow_effects,
257        allow_fs_read: ceiling.allow_fs_read.clone(),
258        allow_fs_write: ceiling.allow_fs_write.clone(),
259        allow_net_host: ceiling.allow_net_host.clone(),
260        allow_proc: ceiling.allow_proc.clone(),
261        allow_approval: ceiling.allow_approval.clone(),
262        budget,
263    }
264}
265
266fn validate_tenant_id(tenant_id: &str) -> anyhow::Result<()> {
267    if tenant_id.is_empty() {
268        anyhow::bail!("tenant_id must not be empty");
269    }
270    if tenant_id.len() > 64 {
271        anyhow::bail!("tenant_id must be at most 64 bytes");
272    }
273    if !tenant_id
274        .bytes()
275        .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
276    {
277        anyhow::bail!(
278            "tenant_id {tenant_id:?} contains characters outside [A-Za-z0-9_-]"
279        );
280    }
281    Ok(())
282}
283
284#[derive(Debug, Serialize, Deserialize)]
285struct ErrorEnvelope {
286    error: String,
287    #[serde(skip_serializing_if = "Option::is_none")]
288    detail: Option<serde_json::Value>,
289}
290
291pub(crate) fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {
292    let bytes = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
293    Response::from_data(bytes)
294        .with_status_code(status)
295        .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
296}
297
298pub(crate) fn error_response(status: u16, msg: impl Into<String>) -> Response<std::io::Cursor<Vec<u8>>> {
299    json_response(status, &serde_json::to_value(ErrorEnvelope {
300        error: msg.into(), detail: None,
301    }).unwrap())
302}
303
304pub(crate) fn error_with_detail(status: u16, msg: impl Into<String>, detail: serde_json::Value)
305    -> Response<std::io::Cursor<Vec<u8>>>
306{
307    json_response(status, &serde_json::to_value(ErrorEnvelope {
308        error: msg.into(), detail: Some(detail),
309    }).unwrap())
310}
311
312/// The actionable next step for a refused unsatisfiable pair (#992). Shared
313/// with the `lex op push` client, which prints it verbatim.
314pub const UNSATISFIABLE_PAIR_HINT: &str =
315    "republish from source to retire the stranded entry (#995)";
316
317/// `StoreError::UnsatisfiablePair` → **422**, never 500 (#992). The request
318/// asked to move a head onto a `(sig, stage)` pair no store can hold — a
319/// problem with the client's data, not the server. The body names the pair,
320/// the sig that actually owns the stage, and what to do about it:
321///
322/// ```json
323/// { "error": "UnsatisfiablePair",
324///   "detail": { "sig_id": "...", "stage_id": "...", "filed_under": "...",
325///               "hint": "republish from source to retire the stranded entry (#995)" } }
326/// ```
327///
328/// `None` for any other error, so callers fall through to their own mapping.
329pub(crate) fn unsatisfiable_pair_response(err: &lex_store::StoreError)
330    -> Option<Response<std::io::Cursor<Vec<u8>>>>
331{
332    let lex_store::StoreError::UnsatisfiablePair { sig_id, stage_id, filed_under } = err else {
333        return None;
334    };
335    Some(error_with_detail(422, "UnsatisfiablePair", serde_json::json!({
336        "sig_id": sig_id,
337        "stage_id": stage_id,
338        "filed_under": filed_under,
339        "message": err.to_string(),
340        "hint": UNSATISFIABLE_PAIR_HINT,
341    })))
342}
343
344/// Map a `StoreError` from a write path (`apply_operation` /
345/// `apply_operation_checked`) to an HTTP response. The only special
346/// case today is `Contention` (#262 multi-writer CAS retries
347/// exhausted), which maps to 503 with a `Retry-After` header so
348/// clients back off rather than hammering the same branch tip.
349pub(crate) fn write_error_response(prefix: &str, err: lex_store::StoreError)
350    -> Response<std::io::Cursor<Vec<u8>>>
351{
352    if let Some(resp) = unsatisfiable_pair_response(&err) {
353        return resp;
354    }
355    if let lex_store::StoreError::Contention { branch, attempts } = &err {
356        let body = serde_json::to_vec(&ErrorEnvelope {
357            error: format!("{prefix}: branch '{branch}' is contended (attempts={attempts})"),
358            detail: Some(serde_json::json!({
359                "kind": "contention",
360                "branch": branch,
361                "attempts": attempts,
362            })),
363        }).unwrap_or_else(|_| b"{}".to_vec());
364        return Response::from_data(body)
365            .with_status_code(503)
366            .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
367            .with_header(Header::from_bytes(&b"Retry-After"[..], &b"1"[..]).unwrap());
368    }
369    // #292 slice 3: budget overflow → 503 with `Retry-After: 0`.
370    // Unlike Contention (where a retry might land after another
371    // writer finishes), there's no point retrying a budget-
372    // exceeded op — the caller needs to raise the cap, switch
373    // sessions, or refactor the work. The `Retry-After: 0`
374    // signals "don't bother retrying as-is" while still using
375    // the canonical "service refused" status code.
376    if let lex_store::StoreError::BudgetExceeded { session_id, cap, spent_after } = &err {
377        let body = serde_json::to_vec(&ErrorEnvelope {
378            error: format!(
379                "{prefix}: session `{session_id}` budget exceeded \
380                 (spent_after={spent_after}, cap={cap})"
381            ),
382            detail: Some(serde_json::json!({
383                "kind": "budget_exceeded",
384                "session_id": session_id,
385                "cap": cap,
386                "spent_after": spent_after,
387            })),
388        }).unwrap_or_else(|_| b"{}".to_vec());
389        return Response::from_data(body)
390            .with_status_code(503)
391            .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
392            .with_header(Header::from_bytes(&b"Retry-After"[..], &b"0"[..]).unwrap());
393    }
394    error_response(500, format!("{prefix}: {err}"))
395}
396
397pub fn handle(state: Arc<State>, mut req: Request) -> std::io::Result<()> {
398    let method = req.method().clone();
399    let url = req.url().to_string();
400    let path = url.split('?').next().unwrap_or("").to_string();
401    let query = url.split_once('?').map(|(_, q)| q.to_string()).unwrap_or_default();
402
403    // `X-Lex-User` is the v3d session identifier — set by humans
404    // operating the web UI through whatever proxy fronts auth, or
405    // by AI agents calling the JSON API. We pluck it once here so
406    // every handler can take it as a borrowed string.
407    let x_lex_user = req.headers().iter()
408        .find(|h| h.field.equiv("x-lex-user"))
409        .map(|h| h.value.as_str().to_string());
410    // `X-Lex-Caps` (#1007): the capabilities the client speaks, so a route
411    // can refuse to hand an old client history it would mis-store.
412    let x_lex_caps = req.headers().iter()
413        .find(|h| h.field.equiv("x-lex-caps"))
414        .map(|h| h.value.as_str().to_string());
415
416    // POST /v1/pkg/publish sends a raw tar.gz body — read bytes before routing.
417    if matches!(method, Method::Post) && path == "/v1/pkg/publish" {
418        let mut body_bytes: Vec<u8> = Vec::new();
419        let _ = req.as_reader().read_to_end(&mut body_bytes);
420        let resp = pkg_publish_handler(&state, &body_bytes);
421        return req.respond(resp);
422    }
423
424    let mut body = String::new();
425    let _ = req.as_reader().read_to_string(&mut body);
426
427    let resp = route(&state, &method, &path, &query, &body, x_lex_user.as_deref(), x_lex_caps.as_deref());
428    req.respond(resp)
429}
430
431/// Auth-gated entry point. Calls `auth(path, headers)` before routing;
432/// returns 401 JSON when it returns false. Keeps auth logic out of the
433/// product-agnostic core.
434pub fn handle_with_auth<F>(state: Arc<State>, req: Request, auth: F) -> std::io::Result<()>
435where
436    F: FnOnce(&str, &[Header]) -> bool,
437{
438    let path = req.url().split('?').next().unwrap_or("").to_string();
439    if !auth(&path, req.headers()) {
440        return req.respond(
441            Response::from_data(br#"{"error":"unauthorized"}"#.to_vec())
442                .with_status_code(401)
443                .with_header(
444                    Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap(),
445                ),
446        );
447    }
448    handle(state, req)
449}
450
451fn route(
452    state: &State,
453    method: &Method,
454    path: &str,
455    query: &str,
456    body: &str,
457    x_lex_user: Option<&str>,
458    x_lex_caps: Option<&str>,
459) -> Response<std::io::Cursor<Vec<u8>>> {
460    match (method, path) {
461        // ---- lex-tea v2 (HTML browser) ------------------------
462        (Method::Get, "/") => crate::web::activity_handler(state),
463        (Method::Get, "/web/branches") => crate::web::branches_handler(state),
464        (Method::Get, "/web/trust") => crate::web::trust_handler(state),
465        (Method::Get, "/web/attention") => crate::web::attention_handler(state),
466        (Method::Get, p) if p.starts_with("/web/branch/") => {
467            let name = &p["/web/branch/".len()..];
468            crate::web::branch_handler(state, name)
469        }
470        (Method::Get, p) if p.starts_with("/web/stage/") => {
471            let id = &p["/web/stage/".len()..];
472            crate::web::stage_html_handler(state, id)
473        }
474        // lex-tea v3 human-triage actions (#172). HTML forms post
475        // to /web/stage/<id>/{pin,defer,block,unblock} with a
476        // `reason` body. All four share one handler; the verb in
477        // the path picks the AttestationKind.
478        (Method::Post, p) if p.starts_with("/web/stage/") && (
479            p.ends_with("/pin") || p.ends_with("/defer")
480            || p.ends_with("/block") || p.ends_with("/unblock")
481        ) => {
482            let prefix_len = "/web/stage/".len();
483            let last_slash = p.rfind('/').unwrap_or(p.len());
484            let id = &p[prefix_len..last_slash];
485            let verb = &p[last_slash + 1..];
486            let decision = match verb {
487                "pin"     => crate::web::WebStageDecision::Pin,
488                "defer"   => crate::web::WebStageDecision::Defer,
489                "block"   => crate::web::WebStageDecision::Block,
490                "unblock" => crate::web::WebStageDecision::Unblock,
491                _ => unreachable!("matched in outer guard"),
492            };
493            crate::web::stage_decision_handler(state, id, body, decision, x_lex_user)
494        }
495        // ---- JSON API -----------------------------------------
496        (Method::Get, "/v1/health") => json_response(200, &serde_json::json!({"ok": true, "caps": CAPS})),
497        (Method::Post, "/v1/parse") => parse_handler(body),
498        (Method::Post, "/v1/check") => check_handler(body),
499        (Method::Post, "/v1/publish") => publish_handler(state, body),
500        (Method::Post, "/v1/patch") => patch_handler(state, body),
501        (Method::Post, "/v1/transform") => crate::transform_http::transform_handler(state, body),
502        (Method::Get, p) if p.starts_with("/v1/stage/") => {
503            let suffix = &p["/v1/stage/".len()..];
504            // Match `/v1/stage/<id>/attestations` first so a literal
505            // stage_id of "attestations" can't be misrouted.
506            if let Some(id) = suffix.strip_suffix("/attestations") {
507                stage_attestations_handler(state, id)
508            } else {
509                stage_handler(state, suffix)
510            }
511        }
512        (Method::Post, "/v1/run") => run_handler(state, body, false),
513        (Method::Post, "/v1/replay") => run_handler(state, body, true),
514        (Method::Get, p) if p.starts_with("/v1/trace/") => {
515            let id = &p["/v1/trace/".len()..];
516            trace_handler(state, id)
517        }
518        (Method::Get, "/v1/diff") => diff_handler(state, query),
519        (Method::Post, "/v1/merge/start") => merge_start_handler(state, body),
520        (Method::Post, p) if p.starts_with("/v1/merge/") && p.ends_with("/resolve") => {
521            let id = &p["/v1/merge/".len()..p.len() - "/resolve".len()];
522            merge_resolve_handler(state, id, body)
523        }
524        (Method::Post, p) if p.starts_with("/v1/merge/") && p.ends_with("/commit") => {
525            let id = &p["/v1/merge/".len()..p.len() - "/commit".len()];
526            merge_commit_handler(state, id)
527        }
528        // ---- #242: append-only sync of op log + attestation log
529        (Method::Post, "/v1/ops/batch") => ops_batch_handler(state, body),
530        (Method::Post, "/v1/attestations/batch") => attestations_batch_handler(state, body),
531        // Content half of push/pull: the stage (code) and intent blobs the
532        // op records reference. `batch` receives, `fetch` returns by id.
533        (Method::Post, "/v1/stages/batch") => crate::sync_http::stages_batch_handler(state, body),
534        (Method::Post, "/v1/stages/fetch") => crate::sync_http::stages_fetch_handler(state, body),
535        (Method::Post, "/v1/stages/missing") => crate::sync_http::stages_missing_handler(state, body),
536        (Method::Post, "/v1/intents/batch") => crate::sync_http::intents_batch_handler(state, body),
537        (Method::Post, "/v1/intents/fetch") => crate::sync_http::intents_fetch_handler(state, body),
538        // #930 P2b-1: committed lockfiles travel with the package so the
539        // write-time gate can resolve a head's pinned dependencies.
540        (Method::Post, "/v1/locks/batch") => crate::sync_http::locks_batch_handler(state, body),
541        (Method::Post, "/v1/locks/fetch") => crate::sync_http::locks_fetch_handler(state, body),
542        // #1007: files beside the op-log — content-addressed blobs a
543        // `SetFiles` manifest names. Pushed before the ops that need them.
544        (Method::Post, "/v1/blobs/missing") => crate::sync_http::blobs_missing_handler(state, body),
545        (Method::Post, "/v1/blobs/batch") => crate::sync_http::blobs_batch_handler(state, body),
546        (Method::Post, "/v1/blobs/fetch") => crate::sync_http::blobs_fetch_handler(state, body),
547        // #949 phase 1: typed issues travel with the package (content-
548        // addressed, like intents) so a pulled op-log carries its work items.
549        (Method::Post, "/v1/issues/batch") => crate::sync_http::issues_batch_handler(state, body),
550        (Method::Post, "/v1/issues/fetch") => crate::sync_http::issues_fetch_handler(state, body),
551        (Method::Get, "/v1/issues/list") => crate::sync_http::issues_list_handler(state),
552        // #949 phase 3: derived issue/project state, computed from the log —
553        // a board is a view, nobody drags cards. The `/list` literal above
554        // wins over the `/v1/issues/<id>` prefix arm below.
555        (Method::Get, "/v1/issues") => crate::issues_http::issues_state_handler(state),
556        (Method::Get, "/v1/projects") => crate::issues_http::projects_handler(state),
557        (Method::Get, p) if p.starts_with("/v1/issues/") => {
558            crate::issues_http::issue_detail_handler(state, &p["/v1/issues/".len()..])
559        }
560        // ---- #839 follow-up: branch management over HTTP so a remote
561        // client can create/switch branches (and thus drive the merge
562        // gates end to end), not just probe heads.
563        (Method::Get, "/v1/review/inbox") => crate::review_http::review_inbox_handler(state, query),
564        (Method::Post, "/v1/review/verdict") => crate::review_http::review_verdict_handler(state, body),
565        (Method::Get, "/v1/branches") => crate::branches_http::branches_list_handler(state),
566        (Method::Post, "/v1/branches") => crate::branches_http::branch_create_handler(state, body),
567        (Method::Post, p) if p.starts_with("/v1/branches/") && p.ends_with("/checkout") => {
568            let name = &p["/v1/branches/".len()..p.len() - "/checkout".len()];
569            crate::branches_http::branch_checkout_handler(state, name)
570        }
571        // Branch head: GET probes it (for `op push`'s delta), POST advances
572        // it (the ref half of push, fast-forward-only). Both in branches_http.
573        (Method::Get, p) if p.starts_with("/v1/branches/") && p.ends_with("/head") => {
574            let name = &p["/v1/branches/".len()..p.len() - "/head".len()];
575            crate::branches_http::branch_head_handler(state, name)
576        }
577        (Method::Post, p) if p.starts_with("/v1/branches/") && p.ends_with("/head") => {
578            let name = &p["/v1/branches/".len()..p.len() - "/head".len()];
579            crate::branches_http::branch_advance_head_handler(state, name, body)
580        }
581        // ---- #260: append-only fetch (inverse of #242 push)
582        // Body is a JSON array of OperationRecords reachable from
583        // `branch.head_op` but not from `after`, oldest-first.
584        (Method::Get, "/v1/ops/since") => crate::ops_since_http::ops_since_handler(state, query, x_lex_caps),
585        (Method::Get, "/v1/attestations/since") => attestations_since_handler(state, query),
586        // ---- #4: package concept ----------------------------------
587        // POST /v1/pkg/publish is handled in handle() before route()
588        // (binary body), so it doesn't appear here.
589        (Method::Get, "/v1/pkg") => pkg_list_handler(state),
590        // Owner-only visibility toggle (authed via the front door). Must
591        // precede the generic `/v1/pkg/{name}` arms; it's a PUT, so it
592        // can't collide with the GET/DELETE arms regardless.
593        (Method::Put, p) if p.starts_with("/v1/pkg/") && p.ends_with("/visibility") => {
594            let name = &p["/v1/pkg/".len()..p.len() - "/visibility".len()];
595            pkg_set_visibility_handler(state, name, body)
596        }
597        // Cut an immutable versioned release of an op-log-hosted package
598        // (#893). POST, before the generic /v1/pkg/{name} arms.
599        (Method::Post, p) if p.starts_with("/v1/pkg/") && p.ends_with("/release") => {
600            let name = &p["/v1/pkg/".len()..p.len() - "/release".len()];
601            pkg_release_handler(state, name, body)
602        }
603        (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/head") => {
604            let name = &p["/v1/pkg/".len()..p.len() - "/head".len()];
605            pkg_head_handler(state, name)
606        }
607        (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/versions") => {
608            let name = &p["/v1/pkg/".len()..p.len() - "/versions".len()];
609            pkg_versions_handler(state, name)
610        }
611        (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/api-diff") => {
612            let name = &p["/v1/pkg/".len()..p.len() - "/api-diff".len()];
613            pkg_api_diff_handler(state, name, query)
614        }
615        // /v1/pkg/{name}/{version}/archive — must match before the generic /{name}/{version}
616        (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/archive") => {
617            let inner = &p["/v1/pkg/".len()..p.len() - "/archive".len()];
618            // inner = "{name}/{version}"
619            if let Some((name, version)) = inner.split_once('/') {
620                pkg_archive_handler(state, name, version)
621            } else {
622                error_response(400, "expected /v1/pkg/{name}/{version}/archive")
623            }
624        }
625        // /v1/pkg/{name}/{version}
626        (Method::Get, p) if p.starts_with("/v1/pkg/") && p["/v1/pkg/".len()..].contains('/') => {
627            let inner = &p["/v1/pkg/".len()..];
628            if let Some((name, version)) = inner.split_once('/') {
629                pkg_get_version_handler(state, name, version)
630            } else {
631                error_response(400, "expected /v1/pkg/{name}/{version}")
632            }
633        }
634        (Method::Get, p) if p.starts_with("/v1/pkg/") => {
635            let name = &p["/v1/pkg/".len()..];
636            pkg_get_handler(state, name)
637        }
638        (Method::Delete, p) if p.starts_with("/v1/pkg/") => {
639            let name = &p["/v1/pkg/".len()..];
640            pkg_delete_handler(state, name)
641        }
642        _ => error_response(404, format!("unknown route: {method:?} {path}")),
643    }
644}
645
646#[derive(Deserialize)]
647struct ParseReq { source: String }
648
649fn parse_handler(body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
650    let req: ParseReq = match serde_json::from_str(body) {
651        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
652    };
653    match load_program_from_str(&req.source) {
654        Ok(prog) => {
655            let stages = canonicalize_program(&prog);
656            json_response(200, &serde_json::to_value(&stages).unwrap())
657        }
658        Err(e) => error_response(400, format!("syntax error: {e}")),
659    }
660}
661
662pub(crate) fn check_handler(body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
663    let req: ParseReq = match serde_json::from_str(body) {
664        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
665    };
666    let prog = match load_program_from_str(&req.source) {
667        Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
668    };
669    let stages = canonicalize_program(&prog);
670    match lex_types::check_program(&stages) {
671        Ok(_) => json_response(200, &serde_json::json!({"ok": true})),
672        Err(errs) => json_response(422, &serde_json::to_value(&errs).unwrap()),
673    }
674}
675
676#[derive(Deserialize)]
677struct PublishReq { source: String, #[serde(default)] activate: bool }
678
679pub(crate) fn publish_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
680    let req: PublishReq = match serde_json::from_str(body) {
681        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
682    };
683    let prog = match load_program_from_str(&req.source) {
684        Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
685    };
686    // #168: rewrite stdlib parse calls to parse_strict so the
687    // bytecode emitted from these stages enforces required-field
688    // checks at runtime.
689    let mut stages = canonicalize_program(&prog);
690    if let Err(errs) = lex_types::check_and_rewrite_program(&mut stages) {
691        return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
692    }
693    // #835 Tier 1: behavioral example gate. check_and_rewrite_program
694    // only type-checks `examples {}`; run them and refuse the publish
695    // if any declared example evaluates to the wrong value. Non-breaking:
696    // functions without examples (and effectful ones, which can't have
697    // them) produce no cases.
698    let example_errors = lex_runtime::evaluate_examples(&stages);
699    if !example_errors.is_empty() {
700        return error_with_detail(422, "example mismatch",
701            serde_json::to_value(&example_errors).unwrap_or_default());
702    }
703
704    let store = state.store.lock().unwrap();
705    let branch = store.current_branch();
706
707    // Compute diff between what's already on the branch and the new program.
708    let old_head = match store.branch_head(&branch) {
709        Ok(h) => h,
710        Err(e) => return error_response(500, format!("branch_head: {e}")),
711    };
712    // Fns + types (#895) on both sides. Old side is the branch head, read
713    // in one pass through the SigId the head names each stage by (#971):
714    // `get_ast` per entry re-read the whole stage index once per live
715    // declaration, and — StageIds being name-independent — resolved two
716    // functions differing only in name to one of the two, so the other was
717    // re-reported as an Add on every republish (#826).
718    let old_pairs: Vec<(String, String)> =
719        old_head.iter().map(|(sig, stg)| (sig.clone(), stg.clone())).collect();
720    let old_head_stages: Vec<lex_ast::Stage> =
721        store.get_asts_for_sigs_bulk(&old_pairs).into_iter().filter_map(Result::ok).collect();
722    let old_fns = stage_fns(&old_head_stages);
723    let new_fns = stage_fns(&stages);
724    let old_types = stage_types(&old_head_stages);
725    let new_types = stage_types(&stages);
726    let report =
727        lex_vcs::compute_diff_with_types(&old_fns, &new_fns, &old_types, &new_types, false);
728
729    // Build new imports map from any Import stages in the source.
730    let mut new_imports: lex_vcs::ImportMap = lex_vcs::ImportMap::new();
731    {
732        let entry = new_imports.entry("<source>".into()).or_default();
733        for s in &stages {
734            if let lex_ast::Stage::Import(im) = s {
735                entry.insert(lex_vcs::ImportRef {
736                    reference: im.reference.clone(),
737                    alias: im.alias.clone(),
738                });
739            }
740        }
741    }
742
743    match store.publish_program(&branch, &stages, &report, &new_imports, req.activate) {
744        Ok(outcome) => {
745            // #835 Tier 1: record the behavioral-examples verdict for each
746            // published fn-stage that declares examples. Best-effort — a
747            // failure to record must not fail an otherwise-good publish.
748            record_examples_for_publish(&store, &stages, &outcome);
749            json_response(200, &serde_json::json!({
750                "ops": outcome.ops,
751                "head_op": outcome.head_op,
752            }))
753        }
754        // The store-write gate (#130) also type-checks at the top
755        // of `publish_program`. The handler above already pre-checks,
756        // so this branch is reached only on a race or a state we
757        // didn't see at handler time. Surface the structured
758        // envelope (422) instead of a generic 500 — same shape the
759        // initial pre-check uses, so a client only has one error
760        // contract to handle.
761        Err(lex_store::StoreError::TypeError(errs)) => {
762            error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap())
763        }
764        Err(e) => write_error_response("publish_program", e),
765    }
766}
767
768#[derive(Deserialize)]
769struct PatchReq {
770    stage_id: String,
771    patch: lex_ast::Patch,
772    #[serde(default)] activate: bool,
773    /// #837 piece A: the branch to write to. Absent keeps the historical
774    /// behaviour (the server's global current branch); a supplied name is
775    /// honoured, and an unknown one is a 404.
776    #[serde(default)] branch: Option<String>,
777    /// #837 piece A: attribute the write. Absent records no intent, as before.
778    #[serde(default)] intent: Option<crate::transform_http::IntentSpec>,
779}
780
781/// POST /v1/patch — apply a structured edit to a stored stage's
782/// canonical AST, type-check the result, and publish a new stage.
783///
784/// Optional `branch` / `intent` (#837 piece A) name the branch explicitly and
785/// attribute the op; without them the request behaves exactly as it always did.
786/// For the typed transforms, and a request that *requires* a branch, see
787/// `POST /v1/transform`.
788fn patch_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
789    let req: PatchReq = match serde_json::from_str(body) {
790        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
791    };
792    let intent = match req.intent.clone() {
793        Some(spec) => match spec.into_intent(crate::transform_http::default_http_session) {
794            Ok(i) => Some(i),
795            Err(e) => return error_response(400, format!("bad request: {e}")),
796        },
797        None => None,
798    };
799    let store = state.store.lock().unwrap();
800    let explicit_branch = req.branch.is_some();
801    if let Some(b) = &req.branch {
802        match store.list_branches() {
803            Ok(bs) if bs.iter().any(|x| x == b) => {}
804            Ok(_) => return error_response(404, format!("unknown branch `{b}`")),
805            Err(e) => return error_response(500, format!("list_branches: {e}")),
806        }
807    }
808
809    // 1. Load.
810    let original = match store.get_ast(&req.stage_id) {
811        Ok(s) => s, Err(e) => return error_response(404, format!("stage: {e}")),
812    };
813
814    // 2. Apply.
815    let patched = match lex_ast::apply_patch(&original, &req.patch) {
816        Ok(s) => s,
817        Err(e) => return error_with_detail(422, "patch failed",
818            serde_json::to_value(&e).unwrap_or_default()),
819    };
820
821    // 3. No isolated check (#833): the gated apply below type-checks
822    // the *composed* program — the branch head with the patched stage
823    // swapped in. Stricter where it matters (a body that no longer
824    // composes with its callers is refused) and correct where the old
825    // isolated check was wrong (a body calling a sibling was rejected
826    // as an unknown identifier a one-stage program couldn't see).
827
828    // Routing through the gated apply so /v1/patch participates in the
829    // op DAG. We know this op is always a body change on the existing
830    // sig (a patch can't add a brand-new fn).
831    let branch = req.branch.clone().unwrap_or_else(|| store.current_branch());
832
833    // Find the sig — patched stage's sig must match the original's.
834    let sig = match lex_ast::sig_id(&patched) {
835        Some(s) => s,
836        None => return error_response(500, "patched stage has no sig_id"),
837    };
838
839    // Persist before the gate (its RepairHint on rejection is
840    // addressed to this stage); activate only once the head moved.
841    let new_id = match store.publish(&patched) {
842        Ok(id) => id, Err(e) => return error_response(500, format!("publish: {e}")),
843    };
844
845    // Determine op kind: ChangeEffectSig if effects differ, ModifyBody otherwise.
846    let original_effects: std::collections::BTreeSet<String> = match &original {
847        lex_ast::Stage::FnDecl(fd) => fd.effects.iter().map(|e| e.name.clone()).collect(),
848        _ => std::collections::BTreeSet::new(),
849    };
850    let patched_effects: std::collections::BTreeSet<String> = match &patched {
851        lex_ast::Stage::FnDecl(fd) => fd.effects.iter().map(|e| e.name.clone()).collect(),
852        _ => std::collections::BTreeSet::new(),
853    };
854    let head_now = match store.get_branch(&branch) {
855        Ok(b) => b.and_then(|b| b.head_op),
856        Err(e) => return error_response(500, format!("get_branch: {e}")),
857    };
858    let kind = if original_effects != patched_effects {
859        // #247: budget delta is part of the canonical payload now.
860        // Patch endpoints don't currently rehydrate the AST to
861        // recompute budgets, so leave them None — clients that
862        // need budget tracking should publish through the diff
863        // pipeline (`lex publish`) where `compute_diff` populates
864        // them.
865        let from_budget = lex_vcs::operation_budget_from_effects(&original_effects);
866        let to_budget = lex_vcs::operation_budget_from_effects(&patched_effects);
867        // #992: the patched stage declares the new effects, so it hashes to a
868        // different SigId and the store files it under that one. Record it, or
869        // the head keeps the old sig pointing at a stage no store holds there.
870        let to_sig_id = lex_ast::sig_id(&patched).filter(|s| *s != sig);
871        lex_vcs::OperationKind::ChangeEffectSig {
872            sig_id: sig.clone(),
873            from_stage_id: req.stage_id.clone(),
874            to_stage_id: new_id.clone(),
875            from_effects: original_effects,
876            to_effects: patched_effects,
877            from_budget,
878            to_budget,
879            to_sig_id,
880        }
881    } else {
882        let budget = lex_vcs::operation_budget_from_effects(&original_effects);
883        lex_vcs::OperationKind::ModifyBody {
884            sig_id: sig.clone(),
885            from_stage_id: req.stage_id.clone(),
886            to_stage_id: new_id.clone(),
887            from_budget: budget,
888            to_budget: budget,
889            // #992: a patch that touches the signature (types, examples)
890            // moves the sig just as an effect change does.
891            to_sig_id: lex_ast::sig_id(&patched).filter(|s| *s != sig),
892        }
893    };
894    // #992: derive the transition from the op, never hard-code `Replace`. A
895    // sig-moving op must retire the old sig and bind the new one; a `Replace`
896    // here left `(old_sig, new_stage)` at the head — a pair no store holds.
897    let transition = lex_store::transition_for_kind(&kind);
898    let op = lex_vcs::Operation::new(
899        kind,
900        head_now.into_iter().collect::<Vec<_>>(),
901    );
902    let op = match &intent {
903        Some(i) => op.with_intent(i.intent_id.clone()),
904        None => op,
905    };
906    let op_id = match store.apply_operation_gated_with_intent(&branch, op, transition, intent.as_ref()) {
907        Ok(id) => id,
908        Err(lex_store::StoreError::TypeError(errs)) => return error_with_detail(
909            422, "type errors after patch", serde_json::to_value(&errs).unwrap_or_default()),
910        Err(e) => return write_error_response("apply_operation_gated", e),
911    };
912    if req.activate {
913        if let Err(e) = store.activate(&new_id) {
914            return error_response(500, format!("activate: {e}"));
915        }
916    }
917
918    let status = format!("{:?}",
919        store.get_status(&new_id).unwrap_or(lex_store::StageStatus::Draft)).to_lowercase();
920    let mut resp = serde_json::json!({
921        "old_stage_id": req.stage_id,
922        "new_stage_id": new_id,
923        "sig_id": sig,
924        "status": status,
925        "op_id": op_id,
926    });
927    // Only echoed when the caller opted in, so a request without `branch` /
928    // `intent` gets the response it always got, byte for byte.
929    if explicit_branch {
930        resp["branch"] = serde_json::json!(branch);
931    }
932    if let Some(i) = &intent {
933        resp["intent_id"] = serde_json::json!(i.intent_id);
934    }
935    json_response(200, &resp)
936}
937
938pub(crate) fn stage_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
939    let store = state.store.lock().unwrap();
940    let meta = match store.get_metadata(id) {
941        Ok(m) => m, Err(e) => return error_response(404, format!("{e}")),
942    };
943    let ast = match store.get_ast(id) {
944        Ok(a) => a, Err(e) => return error_response(404, format!("{e}")),
945    };
946    let status = format!("{:?}", store.get_status(id).unwrap_or(lex_store::StageStatus::Draft)).to_lowercase();
947    json_response(200, &serde_json::json!({
948        "metadata": meta,
949        "ast": ast,
950        "status": status,
951    }))
952}
953
954/// `GET /v1/stage/<id>/attestations` — every persisted attestation
955/// for this stage, newest-first by arrival order. Issue #132's
956/// queryable-evidence consumer surface.
957///
958/// 404s on unknown stage_id (matches `/v1/stage/<id>`'s shape so a
959/// caller round-tripping both endpoints sees consistent errors).
960/// Empty list (200) is *evidence of absence*: the stage exists but
961/// no producer has attested it.
962pub(crate) fn stage_attestations_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
963    let store = state.store.lock().unwrap();
964    if let Err(e) = store.get_metadata(id) {
965        return error_response(404, format!("{e}"));
966    }
967    let log = match store.attestation_log() {
968        Ok(l) => l,
969        Err(e) => return error_response(500, format!("attestation log: {e}")),
970    };
971    // Newest-first by ARRIVAL order (server-assigned), not by the
972    // writer-supplied timestamp; legacy unstamped entries sort below
973    // stamped ones. `lex op pull` re-puts these in reverse (oldest
974    // first) so a puller's local arrival order matches this store's.
975    let mut listing = match log.list_for_stage_by_arrival(&id.to_string()) {
976        Ok(v) => v,
977        Err(e) => return error_response(500, format!("list_for_stage: {e}")),
978    };
979    listing.reverse();
980    json_response(200, &serde_json::json!({"attestations": listing}))
981}
982
983#[derive(Deserialize, Default)]
984struct PolicyJson {
985    #[serde(default)] allow_effects: Vec<String>,
986    #[serde(default)] allow_fs_read: Vec<String>,
987    #[serde(default)] allow_fs_write: Vec<String>,
988    #[serde(default)] budget: Option<u64>,
989}
990
991impl PolicyJson {
992    fn into_policy(self) -> Policy {
993        Policy {
994            allow_effects: self.allow_effects.into_iter().collect::<BTreeSet<_>>(),
995            allow_fs_read: self.allow_fs_read.into_iter().map(PathBuf::from).collect(),
996            allow_fs_write: self.allow_fs_write.into_iter().map(PathBuf::from).collect(),
997            allow_net_host: Vec::new(),
998            allow_proc: Vec::new(),
999            allow_approval: Vec::new(),
1000            budget: self.budget,
1001        }
1002    }
1003}
1004
1005#[derive(Deserialize)]
1006struct RunReq {
1007    source: String,
1008    #[serde(rename = "fn")] func: String,
1009    #[serde(default)] args: Vec<serde_json::Value>,
1010    #[serde(default)] policy: PolicyJson,
1011    #[serde(default)] overrides: IndexMap<String, serde_json::Value>,
1012}
1013
1014pub(crate) fn run_handler(state: &State, body: &str, with_overrides: bool) -> Response<std::io::Cursor<Vec<u8>>> {
1015    let req: RunReq = match serde_json::from_str(body) {
1016        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
1017    };
1018    let prog = match load_program_from_str(&req.source) {
1019        Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
1020    };
1021    let stages = canonicalize_program(&prog);
1022    if let Err(errs) = lex_types::check_program(&stages) {
1023        return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
1024    }
1025    let bc = compile_program(&stages);
1026    let mut policy = req.policy.into_policy();
1027    // When a server-imposed ceiling is present (multi-tenant
1028    // embedders like lex-hub), the request policy can only narrow
1029    // it — never grant itself proc/fs/net beyond what the operator
1030    // allowed. Single-tenant `lex serve` leaves the ceiling unset
1031    // and runs the caller's policy verbatim.
1032    if let Some(ceiling) = &state.policy_ceiling {
1033        policy = clamp_policy(policy, ceiling);
1034    }
1035    if let Err(violations) = check_policy(&bc, &policy) {
1036        return error_with_detail(403, "policy violation", serde_json::to_value(&violations).unwrap());
1037    }
1038
1039    let mut recorder = lex_trace::Recorder::new();
1040    if with_overrides && !req.overrides.is_empty() {
1041        recorder = recorder.with_overrides(req.overrides);
1042    }
1043    let handle = recorder.handle();
1044    let handler = DefaultHandler::new(policy);
1045    let mut vm = Vm::with_handler(&bc, Box::new(handler));
1046    vm.set_tracer(Box::new(recorder));
1047
1048    let vargs: Vec<Value> = req.args.iter().map(json_to_value).collect();
1049    let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1050    let result = vm.call(&req.func, vargs);
1051    let ended = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1052
1053    let store = state.store.lock().unwrap();
1054    let (root_out, root_err, status) = match &result {
1055        Ok(v) => (Some(value_to_json(v)), None, 200u16),
1056        Err(e) => (None, Some(format!("{e}")), 200u16),
1057    };
1058    let tree = handle.finalize(req.func.clone(), serde_json::Value::Null,
1059        root_out.clone(), root_err.clone(), started, ended);
1060    let run_id = match store.save_trace(&tree) {
1061        Ok(id) => id,
1062        Err(e) => return error_response(500, format!("save_trace: {e}")),
1063    };
1064
1065    let mut body = serde_json::json!({
1066        "run_id": run_id,
1067        "output": root_out,
1068    });
1069    if let Some(err) = root_err {
1070        body["error"] = serde_json::Value::String(err);
1071    }
1072    json_response(status, &body)
1073}
1074
1075fn trace_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
1076    let store = state.store.lock().unwrap();
1077    match store.load_trace(id) {
1078        Ok(t) => json_response(200, &serde_json::to_value(&t).unwrap()),
1079        Err(e) => error_response(404, format!("{e}")),
1080    }
1081}
1082
1083fn diff_handler(state: &State, query: &str) -> Response<std::io::Cursor<Vec<u8>>> {
1084    let mut a = None;
1085    let mut b = None;
1086    for kv in query.split('&') {
1087        if let Some((k, v)) = kv.split_once('=') {
1088            match k { "a" => a = Some(v.to_string()), "b" => b = Some(v.to_string()), _ => {} }
1089        }
1090    }
1091    let (Some(a), Some(b)) = (a, b) else {
1092        return error_response(400, "missing a or b query params");
1093    };
1094    let store = state.store.lock().unwrap();
1095    let ta = match store.load_trace(&a) { Ok(t) => t, Err(e) => return error_response(404, format!("a: {e}")) };
1096    let tb = match store.load_trace(&b) { Ok(t) => t, Err(e) => return error_response(404, format!("b: {e}")) };
1097    match lex_trace::diff_runs(&ta, &tb) {
1098        Some(d) => json_response(200, &serde_json::to_value(&d).unwrap()),
1099        None => json_response(200, &serde_json::json!({"divergence": null})),
1100    }
1101}
1102
1103fn json_to_value(v: &serde_json::Value) -> Value { Value::from_json(v) }
1104
1105fn value_to_json(v: &Value) -> serde_json::Value { v.to_json() }
1106
1107#[derive(Deserialize)]
1108struct MergeStartReq {
1109    src_branch: String,
1110    dst_branch: String,
1111}
1112
1113/// `POST /v1/merge/start` (#134) — open a stateful merge between two
1114/// branch heads and return the conflicts the agent needs to
1115/// resolve. Auto-resolved sigs (one-sided changes, identical
1116/// changes both sides) are returned for audit but don't block
1117/// commit.
1118///
1119/// Response: `{ merge_id, src_head, dst_head, lca, conflicts,
1120/// auto_resolved_count }`. The session is held in process memory
1121/// keyed by `merge_id` for subsequent `resolve` / `commit` calls
1122/// (next slices).
1123fn merge_start_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
1124    let req: MergeStartReq = match serde_json::from_str(body) {
1125        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
1126    };
1127    let store = state.store.lock().unwrap();
1128    let src_head = match store.get_branch(&req.src_branch) {
1129        Ok(Some(b)) => b.head_op,
1130        Ok(None) => return error_response(404, format!("unknown src branch `{}`", req.src_branch)),
1131        Err(e) => return error_response(500, format!("src branch read: {e}")),
1132    };
1133    let dst_head = match store.get_branch(&req.dst_branch) {
1134        Ok(Some(b)) => b.head_op,
1135        Ok(None) => return error_response(404, format!("unknown dst branch `{}`", req.dst_branch)),
1136        Err(e) => return error_response(500, format!("dst branch read: {e}")),
1137    };
1138    let log = match lex_vcs::OpLog::open(store.root()) {
1139        Ok(l) => l,
1140        Err(e) => return error_response(500, format!("op log: {e}")),
1141    };
1142    // Caller doesn't choose merge_ids — minted server-side from
1143    // wall clock + a per-process counter avoids leaking session
1144    // ids' shape into the public surface.
1145    let merge_id = mint_merge_id();
1146    let mut session = match MergeSession::start(
1147        merge_id.clone(),
1148        &log,
1149        src_head.as_ref(),
1150        dst_head.as_ref(),
1151    ) {
1152        Ok(s) => s,
1153        Err(e) => return error_response(500, format!("merge start: {e}")),
1154    };
1155    // #1007 PR 7: the files dimension of the merge. `lex-vcs` doesn't
1156    // know about manifests (see `merge_session.rs`'s module docs), so
1157    // the store computes the 3-way diff and the session just tracks the
1158    // conflicts it surfaced — the same layering `MergeResolutionChecker`
1159    // already uses for sig-conflict type-checking.
1160    let manifest_outcome = match store.manifest_merge(
1161        session.lca.as_deref(),
1162        dst_head.as_deref(),
1163        src_head.as_deref(),
1164    ) {
1165        Ok(o) => o,
1166        Err(lex_store::StoreError::AmbiguousManifest { op_id }) => {
1167            return error_with_detail(422, "AmbiguousManifest", serde_json::json!({
1168                "op_id": op_id,
1169                "reason": "a merge ancestor has an ambiguous files manifest; \
1170                           append a set_files op resolving it before merging",
1171            }));
1172        }
1173        Err(e) => return error_response(500, format!("manifest merge: {e}")),
1174    };
1175    let (file_conflicts, needs_setfiles): (Vec<lex_vcs::FileConflict>, bool) =
1176        match manifest_outcome {
1177            lex_store::ManifestMergeOutcome::NoChange => (Vec::new(), false),
1178            lex_store::ManifestMergeOutcome::Needed { conflicts, .. } => (conflicts, true),
1179        };
1180    session.attach_file_conflicts(file_conflicts, needs_setfiles);
1181
1182    let conflicts: Vec<&lex_vcs::ConflictRecord> = session.remaining_conflicts();
1183    let auto_resolved_count = session.auto_resolved.len();
1184    let remaining_file_conflicts: Vec<&lex_vcs::FileConflict> = session.remaining_file_conflicts();
1185    let body = serde_json::json!({
1186        "merge_id": merge_id,
1187        "src_head": session.src_head,
1188        "dst_head": session.dst_head,
1189        "lca":      session.lca,
1190        "conflicts": conflicts,
1191        "auto_resolved_count": auto_resolved_count,
1192        "file_conflicts": remaining_file_conflicts,
1193        "needs_setfiles": session.needs_setfiles(),
1194    });
1195    drop(conflicts);
1196    drop(remaining_file_conflicts);
1197    drop(store);
1198    let wrapped = ApiMergeSession {
1199        inner: session,
1200        src_branch: req.src_branch,
1201        dst_branch: req.dst_branch,
1202    };
1203    state.sessions.lock().unwrap().insert(merge_id, wrapped);
1204    json_response(200, &body)
1205}
1206
1207#[derive(Deserialize)]
1208struct MergeResolveReq {
1209    /// Each entry is `(conflict_id, resolution)`. The resolution is
1210    /// the same shape as `lex_vcs::Resolution`'s tagged JSON form
1211    /// — `{"kind":"take_ours"}`, `{"kind":"take_theirs"}`,
1212    /// `{"kind":"defer"}`, or `{"kind":"custom","op":{...}}`.
1213    #[serde(default)]
1214    resolutions: Vec<MergeResolveEntry>,
1215    /// File conflicts (#1007 PR 7), keyed by path instead of sig id.
1216    /// Resolution shape is `lex_vcs::FileResolution`'s tagged JSON form
1217    /// — `{"kind":"take_ours"}`, `{"kind":"take_theirs"}`, or
1218    /// `{"kind":"defer"}` (no `custom`; see the module docs on
1219    /// `merge_session::FileResolution` for why).
1220    #[serde(default)]
1221    file_resolutions: Vec<MergeFileResolveEntry>,
1222}
1223
1224#[derive(Deserialize)]
1225struct MergeResolveEntry {
1226    conflict_id: String,
1227    resolution: lex_vcs::Resolution,
1228}
1229
1230#[derive(Deserialize)]
1231struct MergeFileResolveEntry {
1232    path: lex_vcs::FilePath,
1233    resolution: lex_vcs::FileResolution,
1234}
1235
1236/// `POST /v1/merge/<id>/resolve` (#134) — submit batched
1237/// resolutions against the conflicts surfaced by `merge/start`.
1238/// Returns one verdict per input: accepted (recorded against the
1239/// session) or rejected (with structured reason). The session
1240/// stays alive across calls so an agent can iterate.
1241///
1242/// Errors:
1243/// - 404 if `merge_id` doesn't refer to a live session (a typo
1244///   or a session GC'd by a server restart).
1245/// - 400 on malformed body.
1246fn merge_resolve_handler(
1247    state: &State,
1248    merge_id: &str,
1249    body: &str,
1250) -> Response<std::io::Cursor<Vec<u8>>> {
1251    let req: MergeResolveReq = match serde_json::from_str(body) {
1252        Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
1253    };
1254    let mut sessions = state.sessions.lock().unwrap();
1255    let Some(wrapped) = sessions.get_mut(merge_id) else {
1256        return error_response(404, format!("unknown merge_id `{merge_id}`"));
1257    };
1258    let pairs: Vec<(String, lex_vcs::Resolution)> = req.resolutions.into_iter()
1259        .map(|e| (e.conflict_id, e.resolution))
1260        .collect();
1261    // #834: type-check each resolution against dst's head at submission
1262    // time (not only at commit) so the agent's "submit N, see which
1263    // broke, retry" loop gets its feedback here. The store composes the
1264    // projected program; the session owns the merge→delta semantics.
1265    let store = state.store.lock().unwrap();
1266    let checker = lex_store::MergeResolutionChecker::new(&store, wrapped.dst_branch.clone());
1267    let verdicts = wrapped.inner.resolve_checked(pairs, &checker);
1268    drop(store);
1269    let file_pairs: Vec<(lex_vcs::FilePath, lex_vcs::FileResolution)> = req.file_resolutions
1270        .into_iter()
1271        .map(|e| (e.path, e.resolution))
1272        .collect();
1273    let file_verdicts = wrapped.inner.resolve_files(file_pairs);
1274    let remaining: Vec<&lex_vcs::ConflictRecord> = wrapped.inner.remaining_conflicts();
1275    let remaining_files: Vec<&lex_vcs::FileConflict> = wrapped.inner.remaining_file_conflicts();
1276    let body = serde_json::json!({
1277        "verdicts": verdicts,
1278        "remaining_conflicts": remaining,
1279        "file_verdicts": file_verdicts,
1280        "remaining_file_conflicts": remaining_files,
1281    });
1282    json_response(200, &body)
1283}
1284
1285/// `POST /v1/merge/<id>/commit` (#134) — finalize a merge
1286/// session. Builds a `Merge` op from the auto-resolved sigs +
1287/// the conflict resolutions, applies it to the dst branch, and
1288/// returns the new head op id. The session is dropped on
1289/// success; the caller would re-run `merge/start` to land
1290/// further changes.
1291///
1292/// Errors:
1293/// - 404: unknown `merge_id`.
1294/// - 422: conflicts remaining (pass `Defer` or just don't
1295///   resolve a conflict and you land here). Body carries the
1296///   list so the caller knows which still need attention.
1297/// - 422: a `Custom` resolution was used. The data layer
1298///   supports them but landing them via HTTP needs an extra
1299///   pass to apply the custom op against the dst branch
1300///   first; deferred to a follow-up slice. Use TakeOurs /
1301///   TakeTheirs for now.
1302/// - 409: dependency conflict (#977) — the branches pin the same
1303///   package at different versions, so no merged lock exists. Body
1304///   `detail` names the package and both versions; nothing is written.
1305/// - 500: filesystem error while landing the merge op.
1306fn merge_commit_handler(
1307    state: &State,
1308    merge_id: &str,
1309) -> Response<std::io::Cursor<Vec<u8>>> {
1310    use std::collections::BTreeMap;
1311    let wrapped = match state.sessions.lock().unwrap().remove(merge_id) {
1312        Some(w) => w,
1313        None => return error_response(404, format!("unknown merge_id `{merge_id}`")),
1314    };
1315    let dst_branch = wrapped.dst_branch.clone();
1316    let src_head = wrapped.inner.src_head.clone();
1317    let dst_head = wrapped.inner.dst_head.clone();
1318    let lca = wrapped.inner.lca.clone();
1319    let auto_resolved = wrapped.inner.auto_resolved.clone();
1320
1321    // Translate auto-resolved + resolutions into the StageTransition::Merge
1322    // entries map. Only sigs whose head changes relative to dst go in.
1323    let mut entries: BTreeMap<lex_vcs::SigId, Option<lex_vcs::StageId>> = BTreeMap::new();
1324
1325    // Auto-resolved: only `Src` (one-sided change on src) modifies dst.
1326    for outcome in &auto_resolved {
1327        if let lex_vcs::MergeOutcome::Src { sig_id, stage_id } = outcome {
1328            entries.insert(sig_id.clone(), stage_id.clone());
1329        }
1330    }
1331
1332    // Conflict resolutions (sig conflicts, then file conflicts — #1007 PR 7).
1333    let commit_out = match wrapped.inner.commit() {
1334        Ok(r) => r,
1335        Err(lex_vcs::CommitError::ConflictsRemaining(ids)) => {
1336            // Re-insert isn't possible since we removed above; the
1337            // caller will need to re-start. That's acceptable: a
1338            // commit-with-unresolved-conflicts is operator error.
1339            return error_with_detail(
1340                422,
1341                "conflicts remaining",
1342                serde_json::json!({"unresolved": ids}),
1343            );
1344        }
1345        Err(lex_vcs::CommitError::FileConflictsRemaining(paths)) => {
1346            return error_with_detail(
1347                422,
1348                "file conflicts remaining",
1349                serde_json::json!({"unresolved_files": paths}),
1350            );
1351        }
1352    };
1353
1354    for (conflict_id, resolution) in commit_out.resolved {
1355        match resolution {
1356            lex_vcs::Resolution::TakeOurs => {
1357                // Dst already has its head. No entry needed.
1358            }
1359            lex_vcs::Resolution::TakeTheirs => {
1360                // Find the conflict's `theirs` stage_id in the
1361                // session snapshot. We don't have direct access to
1362                // it post-commit (commit consumed the session); but
1363                // we can reconstruct from `auto_resolved` plus the
1364                // session's pre-commit conflict map. Since we
1365                // already moved the inner session, the cleanest fix
1366                // for this slice is to rebuild from the on-disk
1367                // graph: walk src_head, find the latest stage for
1368                // the conflict's sig.
1369                match resolve_take_theirs(state, &src_head, &conflict_id) {
1370                    Ok(stage_id) => {
1371                        entries.insert(conflict_id.clone(), stage_id);
1372                    }
1373                    Err(e) => return error_response(500, format!("resolve take_theirs: {e}")),
1374                }
1375            }
1376            lex_vcs::Resolution::Custom { op } => {
1377                // The agent's brand-new op carries the merge target
1378                // in its kind (e.g. ModifyBody.to_stage_id). The op
1379                // itself isn't separately recorded in the log here
1380                // — its head-map effect is folded into the merge
1381                // op's entries map. Callers that want the op as a
1382                // first-class history entry should publish it via
1383                // /v1/publish first and submit a TakeTheirs/TakeOurs
1384                // resolution against the resulting head.
1385                match op.kind.merge_target() {
1386                    Some((sig, stage)) => {
1387                        if sig != conflict_id {
1388                            return error_with_detail(
1389                                422,
1390                                "custom op targets a different sig than the conflict",
1391                                serde_json::json!({
1392                                    "conflict_id": conflict_id,
1393                                    "op_targets": sig,
1394                                }),
1395                            );
1396                        }
1397                        entries.insert(conflict_id, stage);
1398                    }
1399                    None => {
1400                        return error_with_detail(
1401                            422,
1402                            "custom op kind doesn't yield a single sig→stage delta",
1403                            serde_json::json!({
1404                                "conflict_id": conflict_id,
1405                                "kind": serde_json::to_value(&op.kind).unwrap_or(serde_json::Value::Null),
1406                            }),
1407                        );
1408                    }
1409                }
1410            }
1411            lex_vcs::Resolution::Defer => {
1412                // Unreachable: commit() rejects Defer above.
1413                return error_response(500, "internal: Defer slipped past commit gate");
1414            }
1415        }
1416    }
1417
1418    let resolved_count = entries.len();
1419    let mut parents: Vec<lex_vcs::OpId> = Vec::new();
1420    if let Some(d) = dst_head.clone() { parents.push(d); }
1421    if let Some(s) = src_head.clone() { parents.push(s); }
1422    let op = lex_vcs::Operation::new(
1423        lex_vcs::OperationKind::Merge { resolved: resolved_count },
1424        parents,
1425    );
1426    let transition = lex_vcs::StageTransition::Merge { entries };
1427    let store = state.store.lock().unwrap();
1428
1429    // #1007 PR 7: if the manifests disagreed at all, build the merged
1430    // manifest now — auto-resolved paths plus every resolved file
1431    // conflict — so it can be landed as a `SetFiles` right after the
1432    // merge op. Recomputes the same 3-way diff `merge/start` already
1433    // showed the caller (over the same `lca`/`dst_head`/`src_head`, so
1434    // it reproduces byte-for-byte unless the store's blobs changed
1435    // underneath the session, which the manifest-closure check below
1436    // would catch anyway).
1437    let manifest_blob: Option<String> = if commit_out.needs_setfiles {
1438        match store.manifest_merge(lca.as_deref(), dst_head.as_deref(), src_head.as_deref()) {
1439            Ok(lex_store::ManifestMergeOutcome::NoChange) => None,
1440            Ok(lex_store::ManifestMergeOutcome::Needed { auto_entries, conflicts }) => {
1441                let file_resolutions: BTreeMap<lex_vcs::FilePath, lex_vcs::FileResolution> =
1442                    commit_out.resolved_files.into_iter().collect();
1443                match store.build_merged_manifest(
1444                    auto_entries,
1445                    &conflicts,
1446                    &file_resolutions,
1447                    "pending-merge",
1448                ) {
1449                    Ok(blob_id) => Some(blob_id),
1450                    Err(e) => return write_error_response("build merged manifest", e),
1451                }
1452            }
1453            Err(lex_store::StoreError::AmbiguousManifest { op_id }) => {
1454                return error_with_detail(422, "AmbiguousManifest", serde_json::json!({
1455                    "op_id": op_id,
1456                }));
1457            }
1458            Err(e) => return write_error_response("manifest merge", e),
1459        }
1460    } else {
1461        None
1462    };
1463
1464    // Gated (#833): lands the merge op, type-checks the real post-merge
1465    // head, rolls the head back on a TypeError — and (#1007 PR 7) also
1466    // appends the `SetFiles` above when `manifest_blob` is `Some`,
1467    // rolling all the way back if that fails too (see
1468    // `apply_merge_op_gated_with_manifest`'s doc comment).
1469    match store.apply_merge_op_gated_with_manifest(&dst_branch, op, transition, manifest_blob.as_deref(), None) {
1470        Ok(new_head_op) => json_response(200, &serde_json::json!({
1471            "new_head_op": new_head_op,
1472            "dst_branch": dst_branch,
1473        })),
1474        Err(lex_store::StoreError::TypeError(errs)) => error_with_detail(
1475            422, "merged program has type errors", serde_json::to_value(&errs).unwrap_or_default()),
1476        // #977: the two branches pin the same dependency at different
1477        // versions. The merge commits the union of both parents' locks and
1478        // refuses to pick a side silently; nothing was written, so the dst
1479        // branch is unchanged. 409: the request is fine, the branches'
1480        // states conflict — align the version on one branch and retry.
1481        Err(e @ lex_store::StoreError::DependencyConflict { .. }) => {
1482            let detail = match &e {
1483                lex_store::StoreError::DependencyConflict { package, dst_version, src_version } => {
1484                    serde_json::json!({
1485                        "kind": "dependency_conflict",
1486                        "package": package,
1487                        "dst_branch": dst_branch,
1488                        "dst_version": dst_version,
1489                        "src_branch": wrapped.src_branch,
1490                        "src_version": src_version,
1491                    })
1492                }
1493                _ => serde_json::Value::Null,
1494            };
1495            error_with_detail(409, e.to_string(), detail)
1496        }
1497        Err(e @ lex_store::StoreError::AmbiguousManifest { .. }) => {
1498            error_with_detail(422, "AmbiguousManifest", serde_json::json!({"detail": e.to_string()}))
1499        }
1500        Err(e @ lex_store::StoreError::InvalidManifest(_))
1501        | Err(e @ lex_store::StoreError::MissingBlobs(_)) => {
1502            error_with_detail(422, e.to_string(), serde_json::Value::Null)
1503        }
1504        Err(e) => write_error_response("apply merge op", e),
1505    }
1506}
1507
1508/// Walk the op log from `src_head` backwards to find the latest
1509/// stage assigned to `sig`. Used by the commit handler to figure
1510/// out what stage `TakeTheirs` should land. `Ok(None)` means src
1511/// removed the sig.
1512fn resolve_take_theirs(
1513    state: &State,
1514    src_head: &Option<lex_vcs::OpId>,
1515    sig: &lex_vcs::SigId,
1516) -> std::io::Result<Option<lex_vcs::StageId>> {
1517    let store = state.store.lock().unwrap();
1518    let log = lex_vcs::OpLog::open(store.root())?;
1519    let Some(head) = src_head.as_ref() else { return Ok(None); };
1520    // Walk forward from root → head, replaying each op's transition
1521    // for `sig`; the last assignment wins.
1522    let mut current: Option<lex_vcs::StageId> = None;
1523    for record in log.walk_forward(head, None)? {
1524        match &record.produces {
1525            lex_vcs::StageTransition::Create { sig_id, stage_id }
1526                if sig_id == sig => { current = Some(stage_id.clone()); }
1527            lex_vcs::StageTransition::Replace { sig_id, to, .. }
1528                if sig_id == sig => { current = Some(to.clone()); }
1529            lex_vcs::StageTransition::Remove { sig_id, .. }
1530                if sig_id == sig => { current = None; }
1531            lex_vcs::StageTransition::Rename { from, to, body_stage_id }
1532                if from == sig || to == sig => {
1533                if from == sig { current = None; }
1534                if to == sig   { current = Some(body_stage_id.clone()); }
1535            }
1536            lex_vcs::StageTransition::Merge { entries } => {
1537                if let Some(opt) = entries.get(sig) {
1538                    current = opt.clone();
1539                }
1540            }
1541            _ => {}
1542        }
1543    }
1544    Ok(current)
1545}
1546
1547fn mint_merge_id() -> MergeSessionId {
1548    use std::sync::atomic::{AtomicU64, Ordering};
1549    static COUNTER: AtomicU64 = AtomicU64::new(0);
1550    let nanos = SystemTime::now()
1551        .duration_since(UNIX_EPOCH)
1552        .map(|d| d.as_nanos())
1553        .unwrap_or(0);
1554    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1555    format!("merge_{nanos:x}_{n:x}")
1556}
1557
1558// ---- #242: append-only sync ---------------------------------------
1559
1560/// `POST /v1/ops/batch` (#242). Server endpoint for `lex op push`.
1561///
1562/// Body: a JSON array of `OperationRecord`s. The handler validates
1563/// DAG integrity by checking that every op's `parents` either
1564/// already exist on the remote *or* appear earlier in the same
1565/// batch. This lets a client send a topologically-ordered slice
1566/// without first probing for what's already there.
1567///
1568/// Response shape:
1569///
1570/// ```json
1571/// { "received": N, "added": M, "skipped": (N-M), "added_ids": [...] }
1572/// ```
1573///
1574/// Failure modes:
1575///
1576/// * `400` — body isn't a JSON array of op records.
1577/// * `422` with `{ "error": "MissingParent", "detail": { "op_id":
1578///   ..., "missing_parent": ... } }` if a parent is unreachable.
1579///   The whole batch is rejected; nothing is persisted. The client
1580///   should backfill the missing op and retry.
1581/// * `409` if the supplied `op_id` doesn't match the canonical
1582///   hash of the record's payload — content addressing must hold
1583///   over the wire.
1584/// * `422` `MissingBlobs` `{ op_id, ids }` / `InvalidManifest`
1585///   `{ op_id, manifest, reason }` for a `SetFiles` op (#1007) whose
1586///   manifest or entry blobs this store lacks, or whose manifest is not
1587///   a valid one — so a head can never name a file set it can't serve.
1588///   Blobs go first (`/v1/blobs/batch`).
1589///
1590/// Idempotency: a record whose `op_id` already exists is silently
1591/// skipped (not added, not rejected). Pushing the same payload
1592/// twice is `received == N, added == 0` on the second call.
1593pub(crate) fn ops_batch_handler(state: &State, body: &str)
1594    -> Response<std::io::Cursor<Vec<u8>>>
1595{
1596    let records: Vec<lex_vcs::OperationRecord> = match serde_json::from_str(body) {
1597        Ok(r) => r,
1598        Err(e) => return error_response(400,
1599            format!("body must be a JSON array of OperationRecord: {e}")),
1600    };
1601    let store = state.store.lock().unwrap();
1602    let log = match lex_vcs::OpLog::open(store.root()) {
1603        Ok(l) => l,
1604        Err(e) => return error_response(500, format!("opening op log: {e}")),
1605    };
1606
1607    // Validate every record before persisting any of them.
1608    //
1609    // 1. Content-addressing: the supplied `op_id` must match the
1610    //    canonical hash of `record.op`. Otherwise the client is
1611    //    sending a forged or corrupted record.
1612    // 2. DAG integrity: every parent must either already exist in
1613    //    the local log OR appear earlier in this batch.
1614    let mut batch_ids: std::collections::BTreeSet<lex_vcs::OpId> =
1615        std::collections::BTreeSet::new();
1616    for rec in &records {
1617        let expected = rec.op.op_id();
1618        if expected != rec.op_id {
1619            return error_with_detail(409, "OpIdMismatch", serde_json::json!({
1620                "supplied": rec.op_id,
1621                "expected": expected,
1622            }));
1623        }
1624        for parent in &rec.op.parents {
1625            let known = match log.get(parent) {
1626                Ok(Some(_)) => true,
1627                Ok(None) => false,
1628                Err(e) => return error_response(500, format!("op log read: {e}")),
1629            };
1630            if !known && !batch_ids.contains(parent) {
1631                return error_with_detail(422, "MissingParent", serde_json::json!({
1632                    "op_id": rec.op_id,
1633                    "missing_parent": parent,
1634                }));
1635            }
1636        }
1637        if let Err(resp) = crate::sync_http::check_set_files(&store, state.blob_limits, rec) {
1638            return resp;
1639        }
1640        batch_ids.insert(rec.op_id.clone());
1641    }
1642
1643    // Persist. `OpLog::put` is idempotent so a re-push is a no-op
1644    // for already-present records.
1645    let mut added = 0usize;
1646    let mut added_ids: Vec<&lex_vcs::OpId> = Vec::new();
1647    for rec in &records {
1648        let already_present = matches!(log.get(&rec.op_id), Ok(Some(_)));
1649        match log.put(rec) {
1650            Ok(()) => {
1651                if !already_present {
1652                    added += 1;
1653                    added_ids.push(&rec.op_id);
1654                }
1655            }
1656            Err(e) => return error_response(500, format!("op log write: {e}")),
1657        }
1658    }
1659
1660    json_response(200, &serde_json::json!({
1661        "received": records.len(),
1662        "added": added,
1663        "skipped": records.len() - added,
1664        "added_ids": added_ids,
1665    }))
1666}
1667
1668/// `POST /v1/attestations/batch` (#242). Server endpoint for `lex
1669/// attest push`.
1670///
1671/// Body: a JSON array of `Attestation`s. Validates that each
1672/// attestation's `op_id` (when set) refers to an op that already
1673/// exists on the remote — `attestation_id` is then re-derivable
1674/// from the canonical form, so cross-store dedup just works.
1675///
1676/// Response: same shape as `ops_batch_handler` but `added_ids` is
1677/// the list of accepted `attestation_id`s.
1678///
1679/// Failure modes:
1680///
1681/// * `400` for malformed JSON.
1682/// * `422` with `{ "error": "UnknownOp", "detail": { ... } }` if
1683///   an attestation's `op_id` references an op the remote doesn't
1684///   know about. Whole batch rejected.
1685/// * `409` `AttestationIdMismatch` if the supplied id doesn't
1686///   match the canonical hash.
1687/// * `403` `ReservedProducer` if any attestation claims a
1688///   `produced_by.tool` in [`State::reserved_producers`]. Whole batch
1689///   rejected, nothing written.
1690///
1691/// Idempotency: same as the ops endpoint — content-addressed dedup.
1692pub(crate) fn attestations_batch_handler(state: &State, body: &str)
1693    -> Response<std::io::Cursor<Vec<u8>>>
1694{
1695    let attestations: Vec<lex_vcs::Attestation> = match serde_json::from_str(body) {
1696        Ok(a) => a,
1697        Err(e) => return error_response(400,
1698            format!("body must be a JSON array of Attestation: {e}")),
1699    };
1700    let store = state.store.lock().unwrap();
1701    let log = match store.attestation_log() {
1702        Ok(l) => l,
1703        Err(e) => return error_response(500, format!("opening attestation log: {e}")),
1704    };
1705    let op_log = match lex_vcs::OpLog::open(store.root()) {
1706        Ok(l) => l,
1707        Err(e) => return error_response(500, format!("opening op log: {e}")),
1708    };
1709
1710    // Reserved producers first, over the WHOLE batch, so a mixed batch
1711    // (one legitimate + one reserved) is refused outright and nothing is
1712    // written. Server-internal writers (hosted CI, review, examples) call
1713    // the store directly and never come through here.
1714    for att in &attestations {
1715        if let Some(reserved) = state.reserved_producer_claimed(att) {
1716            return error_with_detail(403, "ReservedProducer", serde_json::json!({
1717                "attestation_id": att.attestation_id,
1718                "produced_by_tool": att.produced_by.tool,
1719                "reserved_tool": reserved,
1720                "message": "this producer name is reserved for the server; \
1721                            clients may not submit attestations claiming it",
1722            }));
1723        }
1724    }
1725
1726    // Validate before persisting any record.
1727    for att in &attestations {
1728        // Content-addressing: re-derive attestation_id from the
1729        // payload and reject mismatches.
1730        let expected = lex_vcs::Attestation::with_timestamp(
1731            att.stage_id.clone(),
1732            att.op_id.clone(),
1733            att.intent_id.clone(),
1734            att.kind.clone(),
1735            att.result.clone(),
1736            att.produced_by.clone(),
1737            att.cost.clone(),
1738            att.timestamp,
1739        ).attestation_id;
1740        if expected != att.attestation_id {
1741            return error_with_detail(409, "AttestationIdMismatch", serde_json::json!({
1742                "supplied": att.attestation_id,
1743                "expected": expected,
1744            }));
1745        }
1746        // The op_id field, if set, must point at an op the remote
1747        // knows about. Without this check, attestations would
1748        // dangle into a future sync that never lands the op.
1749        if let Some(op_id) = &att.op_id {
1750            match op_log.get(op_id) {
1751                Ok(Some(_)) => {}
1752                Ok(None) => return error_with_detail(422, "UnknownOp", serde_json::json!({
1753                    "attestation_id": att.attestation_id,
1754                    "op_id": op_id,
1755                })),
1756                Err(e) => return error_response(500, format!("op log read: {e}")),
1757            }
1758        }
1759    }
1760
1761    // Persist. `AttestationLog::put` is idempotent on
1762    // `attestation_id` and the by-stage index is rewritten as a
1763    // marker file, also idempotent.
1764    let mut added = 0usize;
1765    let mut added_ids: Vec<&lex_vcs::AttestationId> = Vec::new();
1766    for att in &attestations {
1767        let already_present = matches!(log.get(&att.attestation_id), Ok(Some(_)));
1768        match log.put(att) {
1769            Ok(()) => {
1770                if !already_present {
1771                    added += 1;
1772                    added_ids.push(&att.attestation_id);
1773                }
1774            }
1775            Err(e) => return error_response(500, format!("attestation log write: {e}")),
1776        }
1777    }
1778
1779    json_response(200, &serde_json::json!({
1780        "received": attestations.len(),
1781        "added": added,
1782        "skipped": attestations.len() - added,
1783        "added_ids": added_ids,
1784    }))
1785}
1786
1787/// `GET /v1/attestations/since?after-op=<op_id>&limit=<n>` (#260).
1788/// Mirror of `ops_since_handler` for the attestation log.
1789///
1790/// Returns attestations whose `op_id` field is reachable from
1791/// **any** branch's head — not just one — and not in `after_op`'s
1792/// ancestry. The cross-branch fan-out matches the push side:
1793/// attestations are stage-keyed, not branch-keyed, so a single
1794/// "since this op" filter is the right shape.
1795///
1796/// Attestations with `op_id: None` (e.g. `Override`,
1797/// `ProducerBlock`) are always included — the cutoff doesn't apply.
1798/// `--limit` caps the response.
1799pub(crate) fn attestations_since_handler(state: &State, query: &str)
1800    -> Response<std::io::Cursor<Vec<u8>>>
1801{
1802    let mut after_op: Option<String> = None;
1803    let mut limit: Option<usize> = None;
1804    for kv in query.split('&') {
1805        let Some((k, v)) = kv.split_once('=') else { continue };
1806        match k {
1807            "after-op" => after_op = Some(v.to_string()),
1808            "limit" => {
1809                limit = Some(match v.parse::<usize>() {
1810                    Ok(n) => n,
1811                    Err(_) => return error_response(400,
1812                        format!("limit must be a positive integer, got `{v}`")),
1813                });
1814            }
1815            _ => {}
1816        }
1817    }
1818
1819    let store = state.store.lock().unwrap();
1820    let log = match store.attestation_log() {
1821        Ok(l) => l,
1822        Err(e) => return error_response(500, format!("opening attestation log: {e}")),
1823    };
1824
1825    // Build the exclude set: every op_id reachable from `after_op`,
1826    // inclusive. Attestations whose op_id is in this set were
1827    // already known to the caller.
1828    let exclude: std::collections::BTreeSet<String> = match &after_op {
1829        None => std::collections::BTreeSet::new(),
1830        Some(cutoff) => {
1831            let op_log = match lex_vcs::OpLog::open(store.root()) {
1832                Ok(l) => l,
1833                Err(e) => return error_response(500, format!("opening op log: {e}")),
1834            };
1835            match op_log.walk_back(cutoff, None) {
1836                Ok(records) => records.into_iter().map(|r| r.op_id).collect(),
1837                Err(_) => {
1838                    // Cutoff op doesn't exist on this remote. Treat
1839                    // as "no exclude" — caller will get every
1840                    // attestation. They may dedup client-side.
1841                    std::collections::BTreeSet::new()
1842                }
1843            }
1844        }
1845    };
1846
1847    let all = match log.list_all() {
1848        Ok(v) => v,
1849        Err(e) => return error_response(500, format!("listing attestations: {e}")),
1850    };
1851    let mut filtered: Vec<lex_vcs::Attestation> = all
1852        .into_iter()
1853        .filter(|a| match &a.op_id {
1854            Some(op_id) => !exclude.contains(op_id),
1855            // No op_id = doesn't participate in the cutoff; always
1856            // ship it on the first pull, server-side idempotency
1857            // dedupes on the client.
1858            None => true,
1859        })
1860        .collect();
1861    // Stable order: oldest-first by `timestamp`, then by
1862    // `attestation_id` for ties. Lets the client land them
1863    // deterministically.
1864    filtered.sort_by(|a, b| {
1865        a.timestamp.cmp(&b.timestamp)
1866            .then_with(|| a.attestation_id.cmp(&b.attestation_id))
1867    });
1868    if let Some(n) = limit {
1869        filtered.truncate(n);
1870    }
1871
1872    json_response(200, &serde_json::to_value(&filtered).unwrap_or_default())
1873}
1874
1875// ── Package concept (#4) ────────────────────────────────────────────────────
1876
1877/// Full coordinates of one declared dependency, captured from the releaser's
1878/// `lex.toml` so the rendered archive can reproduce a faithful `[dependencies]`
1879/// table — carrying BOTH a vcs (`registry` + `version`) reference and a `git`
1880/// mirror when the source declared both. Every field is optional so a bare
1881/// registry dep, a bare git dep, or a dual dep all round-trip. `#[serde(default,
1882/// skip_serializing_if)]` keeps the record compact and back-compatible.
1883#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1884struct DepSpec {
1885    #[serde(default, skip_serializing_if = "Option::is_none")]
1886    registry: Option<String>,
1887    #[serde(default, skip_serializing_if = "Option::is_none")]
1888    version: Option<String>,
1889    #[serde(default, skip_serializing_if = "Option::is_none")]
1890    git: Option<String>,
1891    #[serde(default, skip_serializing_if = "Option::is_none")]
1892    branch: Option<String>,
1893    #[serde(default, skip_serializing_if = "Option::is_none")]
1894    tag: Option<String>,
1895    #[serde(default, skip_serializing_if = "Option::is_none")]
1896    rev: Option<String>,
1897    #[serde(default, skip_serializing_if = "Option::is_none")]
1898    path: Option<String>,
1899}
1900
1901impl DepSpec {
1902    /// Render this spec as the body of a `lex.toml` inline dependency table,
1903    /// e.g. `{ registry = "…", version = "^0.9", git = "…" }`. Keys are emitted
1904    /// in a stable order (vcs primary first, then the git mirror) so the
1905    /// rendered manifest is deterministic.
1906    fn to_toml_inline(&self) -> Option<String> {
1907        let mut parts: Vec<String> = Vec::new();
1908        let mut push = |k: &str, v: &Option<String>| {
1909            if let Some(val) = v {
1910                parts.push(format!("{k} = {}", toml_str(val)));
1911            }
1912        };
1913        push("registry", &self.registry);
1914        push("version", &self.version);
1915        push("git", &self.git);
1916        push("branch", &self.branch);
1917        push("tag", &self.tag);
1918        push("rev", &self.rev);
1919        push("path", &self.path);
1920        if parts.is_empty() {
1921            None
1922        } else {
1923            Some(format!("{{ {} }}", parts.join(", ")))
1924        }
1925    }
1926}
1927
1928/// Quote a string as a TOML basic string (escaping `\` and `"`).
1929fn toml_str(s: &str) -> String {
1930    format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
1931}
1932
1933/// Per-version record stored at `{store_root}/packages/{name}/{version}.json`.
1934#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1935struct PkgRecord {
1936    name: String,
1937    version: String,
1938    head_op: Option<String>,
1939    published_at: u64,
1940    /// Function names introduced or updated by this version (for retract).
1941    function_names: Vec<String>,
1942    /// External package dependencies of this release — declared by the
1943    /// releaser (from `lex.toml`) and/or extracted from the head's
1944    /// non-inlined imports. The edge set of the dependency graph (#893
1945    /// propagation). `#[serde(default)]` keeps pre-existing records readable.
1946    #[serde(default)]
1947    dependencies: Vec<String>,
1948    /// Full dependency coordinates (name → git+vcs refs) captured from the
1949    /// releaser's `lex.toml`, so the rendered install archive reproduces a
1950    /// faithful `[dependencies]` table (with both git and vcs references).
1951    /// `#[serde(default)]` keeps pre-existing records (which lack it) readable;
1952    /// when empty, the archive falls back to a bare `[package]` manifest.
1953    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
1954    dependency_specs: std::collections::BTreeMap<String, DepSpec>,
1955    /// Raw op JSON from each file in this publish.
1956    ops: Vec<serde_json::Value>,
1957}
1958
1959/// Whether a package is reachable without authentication.
1960///
1961/// Per-package (applies across all versions), GitHub-style: an org's
1962/// store can hold a mix of public and private packages. Defaults to
1963/// `Private`, so an index written before this field existed (or any
1964/// freshly published package) is private until an owner opts in.
1965#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
1966#[serde(rename_all = "lowercase")]
1967pub enum Visibility {
1968    #[default]
1969    Private,
1970    Public,
1971}
1972
1973/// Index stored at `{store_root}/packages/{name}/index.json`.
1974///
1975/// Tracks which versions have been published and which is "latest", so
1976/// consumers can resolve `{name}@latest` without listing every file.
1977#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
1978struct PkgIndex {
1979    /// The most recently published version string (human label, not OpId).
1980    latest: Option<String>,
1981    /// All published versions, newest-last.
1982    versions: Vec<PkgVersionSummary>,
1983    /// Public/private flag. `#[serde(default)]` keeps pre-existing
1984    /// `index.json` files (which lack the field) deserializing as
1985    /// `Private`.
1986    #[serde(default)]
1987    visibility: Visibility,
1988}
1989
1990#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1991struct PkgVersionSummary {
1992    version: String,
1993    head_op: Option<String>,
1994    published_at: u64,
1995}
1996
1997fn pkg_name_dir(root: &std::path::Path, name: &str) -> PathBuf {
1998    root.join("packages").join(name)
1999}
2000
2001fn pkg_index_path(root: &std::path::Path, name: &str) -> PathBuf {
2002    pkg_name_dir(root, name).join("index.json")
2003}
2004
2005fn pkg_version_path(root: &std::path::Path, name: &str, version: &str) -> PathBuf {
2006    pkg_name_dir(root, name).join(format!("{version}.json"))
2007}
2008
2009fn pkg_archive_path(root: &std::path::Path, name: &str, version: &str) -> PathBuf {
2010    pkg_name_dir(root, name).join(format!("{version}.tar.gz"))
2011}
2012
2013fn load_pkg_index(root: &std::path::Path, name: &str) -> Option<PkgIndex> {
2014    let bytes = std::fs::read(pkg_index_path(root, name)).ok()?;
2015    serde_json::from_slice(&bytes).ok()
2016}
2017
2018fn load_pkg_record(root: &std::path::Path, name: &str, version: &str) -> Option<PkgRecord> {
2019    let bytes = std::fs::read(pkg_version_path(root, name, version)).ok()?;
2020    serde_json::from_slice(&bytes).ok()
2021}
2022
2023fn load_latest_pkg_record(root: &std::path::Path, name: &str) -> Option<PkgRecord> {
2024    let index = load_pkg_index(root, name)?;
2025    let latest = index.latest.clone()?;
2026    load_pkg_record(root, name, &latest)
2027}
2028
2029/// A package is public iff its index exists and is marked `Public`.
2030/// A missing index (unknown package) is treated as private, so the
2031/// public surface never distinguishes "private" from "does not exist".
2032fn pkg_is_public(root: &std::path::Path, name: &str) -> bool {
2033    load_pkg_index(root, name).map(|i| i.visibility) == Some(Visibility::Public)
2034}
2035
2036/// Reject package/version path segments that could escape the
2037/// `packages/` directory or otherwise aren't valid names. Mirrors the
2038/// tenant-id guard's spirit (defense in depth — lex-hub validates the
2039/// tenant, this validates the package/version).
2040fn valid_pkg_segment(s: &str) -> bool {
2041    !s.is_empty()
2042        && s.len() <= 128
2043        && s != "."
2044        && s != ".."
2045        && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
2046}
2047
2048#[derive(Deserialize)]
2049struct VisibilityReq {
2050    visibility: Visibility,
2051}
2052
2053/// `PUT /v1/pkg/{name}/visibility` — set a package public or private.
2054///
2055/// Authorization is implicit: this runs against a single tenant's store,
2056/// and the caller only reaches *this* store because the front door
2057/// (lex-hub) authenticated their token and selected it. A caller can
2058/// therefore only change visibility of packages they own.
2059fn pkg_set_visibility_handler(
2060    state: &State,
2061    name: &str,
2062    body: &str,
2063) -> Response<std::io::Cursor<Vec<u8>>> {
2064    if !valid_pkg_segment(name) {
2065        return error_response(400, format!("invalid package name {name:?}"));
2066    }
2067    let req: VisibilityReq = match serde_json::from_str(body) {
2068        Ok(r) => r,
2069        Err(e) => return error_response(400, format!("bad request: {e}")),
2070    };
2071    let mut index = match load_pkg_index(&state.root, name) {
2072        Some(i) => i,
2073        None => return error_response(404, format!("package {name:?} not found")),
2074    };
2075    index.visibility = req.visibility;
2076    let bytes = serde_json::to_vec_pretty(&index).unwrap_or_default();
2077    match std::fs::write(pkg_index_path(&state.root, name), bytes) {
2078        Ok(()) => json_response(
2079            200,
2080            &serde_json::json!({ "name": name, "visibility": index.visibility }),
2081        ),
2082        Err(e) => error_response(500, format!("write index: {e}")),
2083    }
2084}
2085
2086#[derive(serde::Deserialize)]
2087struct ReleaseReq {
2088    version: String,
2089    #[serde(default)]
2090    branch: Option<String>,
2091    /// External package dependencies (from the releaser's `lex.toml`).
2092    /// Unioned with any non-inlined external imports found in the head.
2093    #[serde(default)]
2094    dependencies: Vec<String>,
2095    /// Full dependency coordinates (name → git+vcs refs) from the releaser's
2096    /// `lex.toml`, so the rendered install archive reproduces a faithful
2097    /// `[dependencies]` table. Optional (back-compatible); when omitted, the
2098    /// archive manifest carries only `[package]`.
2099    #[serde(default)]
2100    dependency_specs: std::collections::BTreeMap<String, DepSpec>,
2101}
2102
2103/// `POST /v1/pkg/{name}/release` — cut an immutable versioned release of
2104/// an **op-log-hosted** package: snapshot the current branch head as
2105/// `name@version` in the registry (#893). Unlike `POST /v1/pkg/publish`
2106/// (archive upload), this records only the op-log ref (`head_op`) — a
2107/// consumer resolves the version, `op pull`s that head, and renders
2108/// source. A published version is immutable: re-releasing an existing
2109/// version is a 409, so a resolved+locked dependency can never change
2110/// under a consumer.
2111fn pkg_release_handler(state: &State, name: &str, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2112    if !valid_pkg_segment(name) {
2113        return error_response(400, format!("invalid package name {name:?}"));
2114    }
2115    let req: ReleaseReq = match serde_json::from_str(body) {
2116        Ok(r) => r,
2117        Err(e) => return error_response(400, format!("bad request: {e}")),
2118    };
2119    let version = req.version.trim().to_string();
2120    if version.is_empty() || !valid_pkg_segment(&version) {
2121        return error_response(400, "version must be a non-empty, path-safe string (e.g. 1.2.0)");
2122    }
2123    // Immutable: a published version can never be overwritten.
2124    if load_pkg_record(&state.root, name, &version).is_some() {
2125        return error_response(
2126            409,
2127            format!("{name}@{version} already released; releases are immutable — bump the version"),
2128        );
2129    }
2130
2131    let store = state.store.lock().unwrap();
2132    let branch = req.branch.unwrap_or_else(|| store.current_branch());
2133    let head_op = match store.get_branch(&branch) {
2134        Ok(Some(b)) => b.head_op,
2135        Ok(None) => return error_response(404, format!("unknown branch {branch:?}")),
2136        Err(e) => return error_response(500, format!("get_branch: {e}")),
2137    };
2138    let Some(head_op) = head_op else {
2139        return error_response(400, format!("branch {branch:?} has no commits to release"));
2140    };
2141
2142    // Version-bump gate (#893): the version increment must be at least what
2143    // the public-API change requires — a breaking change (a removed or
2144    // re-signatured public declaration) needs a *major* bump, an addition at
2145    // least a *minor*. This is what makes `^`/`~` resolution safe: a caret
2146    // update can't silently pull a breaking change mislabeled as a patch.
2147    //
2148    // Compare against the **semver predecessor** — the highest already-published
2149    // version strictly less than the new one (not merely `latest`, so releasing
2150    // 2.0.0 after 1.5.0 diffs against 1.5.0). No predecessor (first version, or
2151    // a back-port below everything) means nothing to gate.
2152    let predecessor = load_pkg_index(&state.root, name)
2153        .map(|i| i.versions)
2154        .unwrap_or_default()
2155        .into_iter()
2156        .filter_map(|v| lex_syntax::semver::parse_exact(&v.version).map(|p| (p, v)))
2157        .filter(|(p, _)| lex_syntax::semver::parse_exact(&version).map(|n| *p < n).unwrap_or(false))
2158        .max_by_key(|(p, _)| *p)
2159        .map(|(_, v)| v);
2160    if let Some(prev) = predecessor {
2161        if let (Some(prev_head), Some(declared)) = (
2162            prev.head_op.clone(),
2163            lex_syntax::semver::bump_between(&prev.version, &version),
2164        ) {
2165            if let (Ok(prev_api), Ok(new_api)) = (
2166                lex_store::api::public_api_at_op(&store, &prev_head),
2167                lex_store::api::public_api_at_op(&store, &head_op),
2168            ) {
2169                use lex_store::api::ApiChange;
2170                use lex_syntax::semver::Bump;
2171                let (required, why) = match lex_store::api::classify_api_change(&prev_api, &new_api) {
2172                    ApiChange::Breaking(d) => (Bump::Major, d),
2173                    ApiChange::Additive(d) => (Bump::Minor, d),
2174                    ApiChange::None => (Bump::Patch, String::new()),
2175                };
2176                if declared < required {
2177                    let need = match required {
2178                        Bump::Major => "major",
2179                        Bump::Minor => "minor",
2180                        Bump::Patch => "patch",
2181                    };
2182                    return error_response(
2183                        422,
2184                        format!(
2185                            "version bump too small: {} → {version} is a {declared:?} bump, \
2186                             but the API change ({why}) requires a {need} bump",
2187                            prev.version
2188                        ),
2189                    );
2190                }
2191            }
2192        }
2193    }
2194
2195    // The package's exported function names at this head (for retract /
2196    // the catalog), read through the SigId the head names each by.
2197    let head = store.branch_head(&branch).unwrap_or_default();
2198    let pairs: Vec<(String, String)> = head.iter().map(|(s, st)| (s.clone(), st.clone())).collect();
2199    let function_names: Vec<String> = store
2200        .get_asts_for_sigs_bulk(&pairs)
2201        .into_iter()
2202        .filter_map(|r| r.ok())
2203        .filter_map(|s| match s {
2204            lex_ast::Stage::FnDecl(fd) => Some(fd.name),
2205            _ => None,
2206        })
2207        .collect();
2208    // Dependency-graph edges (#893 propagation): the releaser's declared deps
2209    // (from lex.toml) unioned with any external imports still visible in the
2210    // head (most are inlined at publish, so the declared list is primary).
2211    let mut deps: std::collections::BTreeSet<String> = req.dependencies.into_iter().collect();
2212    if let Ok(extracted) = lex_store::api::external_dependencies_at_op(&store, &head_op) {
2213        deps.extend(extracted);
2214    }
2215    // Names captured as full coordinates count as dependency-graph edges too,
2216    // so a release that sends only `dependency_specs` still records the edges.
2217    deps.extend(req.dependency_specs.keys().cloned());
2218    let dependencies: Vec<String> = deps.into_iter().collect();
2219    drop(store);
2220
2221    let published_at = std::time::SystemTime::now()
2222        .duration_since(std::time::UNIX_EPOCH)
2223        .map(|d| d.as_secs())
2224        .unwrap_or(0);
2225    let record = PkgRecord {
2226        name: name.to_string(),
2227        version: version.clone(),
2228        head_op: Some(head_op.clone()),
2229        published_at,
2230        function_names,
2231        dependencies,
2232        dependency_specs: req.dependency_specs,
2233        ops: Vec::new(),
2234    };
2235    if let Err(e) = save_pkg_record(&state.root, &record, None) {
2236        return error_response(500, format!("write release: {e}"));
2237    }
2238    json_response(
2239        201,
2240        &serde_json::json!({
2241            "name": name,
2242            "version": version,
2243            "head_op": head_op,
2244            "branch": branch,
2245        }),
2246    )
2247}
2248
2249/// Names of the tenant's PUBLIC packages, sorted. Pure (filesystem in,
2250/// names out) so the visibility filter is unit-testable.
2251fn public_pkg_names(root: &std::path::Path) -> Vec<String> {
2252    list_pkg_names(root)
2253        .into_iter()
2254        .filter(|name| pkg_is_public(root, name))
2255        .collect()
2256}
2257
2258/// `GET /v1/public/<tenant>` (org page) — list only the tenant's PUBLIC
2259/// packages (latest version of each). Private packages are omitted, so
2260/// their existence is not revealed.
2261fn public_pkg_list_handler(state: &State) -> Response<std::io::Cursor<Vec<u8>>> {
2262    let packages: Vec<serde_json::Value> = public_pkg_names(&state.root)
2263        .iter()
2264        .filter_map(|name| {
2265            let r = load_latest_pkg_record(&state.root, name)?;
2266            Some(serde_json::json!({
2267                "name": r.name,
2268                "version": r.version,
2269                "head_op": r.head_op,
2270                "published_at": r.published_at,
2271            }))
2272        })
2273        .collect();
2274    json_response(200, &serde_json::json!({ "packages": packages }))
2275}
2276
2277/// A resolved public read target. Separated from response formatting so
2278/// the routing/guard logic is unit-testable without constructing HTTP
2279/// responses. `Err(status)` is a guard failure (405 = non-GET,
2280/// 404 = invalid/unknown route).
2281#[derive(Debug, PartialEq, Eq)]
2282enum PublicTarget {
2283    List,
2284    Latest(String),
2285    Versions(String),
2286    ApiDiff(String),
2287    Head(String),
2288    Version(String, String),
2289    Archive(String, String),
2290}
2291
2292impl PublicTarget {
2293    /// The package name a target refers to, if any (`List` has none).
2294    fn pkg_name(&self) -> Option<&str> {
2295        match self {
2296            PublicTarget::List => None,
2297            PublicTarget::Latest(n)
2298            | PublicTarget::Versions(n)
2299            | PublicTarget::ApiDiff(n)
2300            | PublicTarget::Head(n)
2301            | PublicTarget::Version(n, _)
2302            | PublicTarget::Archive(n, _) => Some(n),
2303        }
2304    }
2305}
2306
2307/// Pure routing decision for `/v1/public/<tenant>` reads. `path` is the
2308/// portion after the tenant (leading `/` ok). Enforces GET-only and
2309/// per-segment name validation; does NOT consult the store (visibility
2310/// is checked by the caller, which has store access).
2311fn resolve_public(method: &Method, path: &str) -> Result<PublicTarget, u16> {
2312    if !matches!(method, Method::Get) {
2313        return Err(405);
2314    }
2315    let rest = path.trim_matches('/');
2316    if rest.is_empty() {
2317        return Ok(PublicTarget::List);
2318    }
2319    let segs: Vec<&str> = rest.split('/').collect();
2320    if !segs.iter().all(|s| valid_pkg_segment(s)) {
2321        return Err(404);
2322    }
2323    match segs.as_slice() {
2324        [n] => Ok(PublicTarget::Latest(n.to_string())),
2325        [n, "versions"] => Ok(PublicTarget::Versions(n.to_string())),
2326        [n, "api-diff"] => Ok(PublicTarget::ApiDiff(n.to_string())),
2327        [n, "head"] => Ok(PublicTarget::Head(n.to_string())),
2328        [n, v, "archive"] => Ok(PublicTarget::Archive(n.to_string(), v.to_string())),
2329        [n, v] => Ok(PublicTarget::Version(n.to_string(), v.to_string())),
2330        _ => Err(404),
2331    }
2332}
2333
2334/// Unauthenticated, read-only access to **public** packages in `state`'s
2335/// store. `path` is the portion of the URL after `/v1/public/<tenant>`
2336/// (with a leading `/`); lex-hub resolves `<tenant>` → store and calls
2337/// this. Visibility gating, GET-only enforcement, and segment validation
2338/// all live here so the whole public surface is auditable in one place.
2339///
2340/// Everything served here is package-scoped — manifests and the source
2341/// archive of a public package's own publish — so it cannot leak code
2342/// from a private package that happens to share content-addressed stages
2343/// in the same store.
2344pub fn route_public(
2345    state: &State,
2346    method: &Method,
2347    path: &str,
2348    query: &str,
2349) -> Response<std::io::Cursor<Vec<u8>>> {
2350    let target = match resolve_public(method, path) {
2351        Ok(t) => t,
2352        Err(405) => return error_response(405, "public read is GET-only"),
2353        Err(_) => return error_response(404, "not found"),
2354    };
2355    // The org listing already filters to public packages itself.
2356    if let PublicTarget::List = target {
2357        return public_pkg_list_handler(state);
2358    }
2359    // Single 404 for both "private" and "absent" — never reveal which.
2360    if let Some(name) = target.pkg_name() {
2361        if !pkg_is_public(&state.root, name) {
2362            return error_response(404, format!("package {name:?} not found"));
2363        }
2364    }
2365    match target {
2366        PublicTarget::List => unreachable!("handled above"),
2367        PublicTarget::Latest(n) => pkg_get_handler(state, &n),
2368        PublicTarget::Versions(n) => pkg_versions_handler(state, &n),
2369        PublicTarget::ApiDiff(n) => pkg_api_diff_handler(state, &n, query),
2370        PublicTarget::Head(n) => pkg_head_handler(state, &n),
2371        PublicTarget::Version(n, v) => pkg_get_version_handler(state, &n, &v),
2372        PublicTarget::Archive(n, v) => pkg_archive_handler(state, &n, &v),
2373    }
2374}
2375
2376fn save_pkg_record(
2377    root: &std::path::Path,
2378    record: &PkgRecord,
2379    // `None` for an op-log release, whose source of truth is the op-log at
2380    // `head_op` (pull + render); `Some` for an archive-upload publish.
2381    archive: Option<&[u8]>,
2382) -> std::io::Result<()> {
2383    let dir = pkg_name_dir(root, &record.name);
2384    std::fs::create_dir_all(&dir)?;
2385
2386    // Per-version record.
2387    let rec_bytes = serde_json::to_vec_pretty(record).unwrap_or_default();
2388    std::fs::write(pkg_version_path(root, &record.name, &record.version), rec_bytes)?;
2389
2390    // Archive (tar.gz) for the download endpoint, when one was uploaded.
2391    if let Some(archive) = archive {
2392        std::fs::write(pkg_archive_path(root, &record.name, &record.version), archive)?;
2393    }
2394
2395    // Update the index.
2396    let mut index = load_pkg_index(root, &record.name).unwrap_or_default();
2397    index.latest = Some(record.version.clone());
2398    if !index.versions.iter().any(|v| v.version == record.version) {
2399        index.versions.push(PkgVersionSummary {
2400            version: record.version.clone(),
2401            head_op: record.head_op.clone(),
2402            published_at: record.published_at,
2403        });
2404    }
2405    let idx_bytes = serde_json::to_vec_pretty(&index).unwrap_or_default();
2406    std::fs::write(pkg_index_path(root, &record.name), idx_bytes)
2407}
2408
2409fn list_pkg_names(root: &std::path::Path) -> Vec<String> {
2410    let dir = root.join("packages");
2411    let Ok(entries) = std::fs::read_dir(&dir) else {
2412        return Vec::new();
2413    };
2414    let mut names: Vec<String> = entries
2415        .filter_map(|e| e.ok())
2416        .filter(|e| e.path().is_dir())
2417        .filter_map(|e| e.file_name().into_string().ok())
2418        .collect();
2419    names.sort();
2420    names
2421}
2422
2423fn collect_lex_files(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
2424    let Ok(entries) = std::fs::read_dir(dir) else { return };
2425    let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
2426    entries.sort_by_key(|e| e.path());
2427    for entry in entries {
2428        let path = entry.path();
2429        if path.is_dir() {
2430            collect_lex_files(&path, out);
2431        } else if path.extension().and_then(|x| x.to_str()) == Some("lex") {
2432            out.push(path);
2433        }
2434    }
2435}
2436
2437/// `POST /v1/pkg/publish` — publish a multi-file package from a `.tar.gz`
2438/// archive containing `lex.toml` and `src/**/*.lex`.
2439fn pkg_publish_handler(state: &State, body: &[u8]) -> Response<std::io::Cursor<Vec<u8>>> {
2440    let tmp = match tempfile::TempDir::new() {
2441        Ok(t) => t,
2442        Err(e) => return error_response(500, format!("create temp dir: {e}")),
2443    };
2444    {
2445        let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(body));
2446        let mut ar = tar::Archive::new(gz);
2447        if let Err(e) = ar.unpack(tmp.path()) {
2448            return error_response(400, format!("unpack archive: {e}"));
2449        }
2450    }
2451
2452    let toml_path = tmp.path().join("lex.toml");
2453    if !toml_path.exists() {
2454        return error_response(400, "archive must contain lex.toml at root");
2455    }
2456    let manifest = match Manifest::load(&toml_path) {
2457        Ok(m) => m,
2458        Err(e) => return error_response(400, format!("lex.toml: {e}")),
2459    };
2460    let (pkg_name, pkg_version) = match &manifest.package {
2461        Some(m) => (m.name.clone(), m.version.clone()),
2462        None => return error_response(400, "lex.toml must have a [package] section"),
2463    };
2464
2465    // Reject a same-(name, version) re-publish BEFORE any store write:
2466    // this ran after the publish loop, so a 409'd duplicate still
2467    // appended its ops to the tenant's op log (#826).
2468    if load_pkg_record(&state.root, &pkg_name, &pkg_version).is_some() {
2469        return error_response(
2470            409,
2471            format!(
2472                "package {pkg_name}@{pkg_version} already published; \
2473                 bump the version in lex.toml to publish a new release"
2474            ),
2475        );
2476    }
2477
2478    let src_dir = tmp.path().join("src");
2479    if !src_dir.exists() {
2480        return error_response(400, "archive must contain a src/ directory");
2481    }
2482    let mut lex_files: Vec<PathBuf> = Vec::new();
2483    collect_lex_files(&src_dir, &mut lex_files);
2484    if lex_files.is_empty() {
2485        return error_response(400, "no .lex files found in src/");
2486    }
2487
2488    let store = state.store.lock().unwrap();
2489    let branch = store.current_branch();
2490
2491    // `old_fns_by_name` mirrors the branch's current function set,
2492    // GROUPED by name rather than collapsed to one entry per name. The
2493    // branch is tenant-wide and carries history: several live functions
2494    // can share a bare name (#818 — three unrelated `validate`s across
2495    // `field.lex`/`schema.lex`/`validator.lex` in a real package, all
2496    // published before names were file-prefixed). `SigId` disambiguates
2497    // them correctly — it hashes the full signature, not just the name —
2498    // so the bug was ever collapsing multiple SigIds sharing a name down
2499    // to one `FnDecl`, silently discarding the others and corrupting
2500    // later diffs against them. The package side can no longer produce
2501    // such a collision: one pass, one prefix-mangled name per
2502    // declaration (#828).
2503    //
2504    // Reading it once, outside any per-file loop, is what fixed #813:
2505    // `branch_head` walks the whole branch op history and `get_ast` is a
2506    // disk fetch per live function, so re-deriving this per file was
2507    // O(files * (history_size + live_fn_count)) — tens of minutes on a
2508    // tenant with 110k+ accumulated ops. Since #828 there is one pass, so
2509    // the shape is structural rather than a discipline to maintain.
2510    let old_head = match store.branch_head(&branch) {
2511        Ok(h) => h,
2512        Err(e) => return error_response(500, format!("branch_head: {e}")),
2513    };
2514    // Resolve each AST through the SigId the branch head names, never its
2515    // StageId: StageIds are name-independent, so two live functions
2516    // differing only in name share one, `stage_index` maps it to just one
2517    // of their sigs, and the name that lookup missed got re-reported as an
2518    // Add on every publish of unchanged source (#826). It also skips that
2519    // index (#825) — see `get_asts_for_sigs_bulk`.
2520    let old_pairs: Vec<(String, String)> =
2521        old_head.iter().map(|(sig, stage)| (sig.clone(), stage.clone())).collect();
2522    let mut old_fns_by_name: BTreeMap<String, Vec<lex_ast::FnDecl>> = BTreeMap::new();
2523    for fd in store.get_asts_for_sigs_bulk(&old_pairs)
2524        .into_iter()
2525        .filter_map(|r| r.ok())
2526        .filter_map(|s| match s { lex_ast::Stage::FnDecl(fd) => Some(fd), _ => None })
2527    {
2528        old_fns_by_name.entry(fd.name.clone()).or_default().push(fd);
2529    }
2530    // Old `type`s on the branch, by (mangled) name — captured too (#895).
2531    // Types aren't overloaded, so a plain name map needs no take_matching.
2532    let mut old_types_by_name: BTreeMap<String, lex_ast::TypeDecl> = BTreeMap::new();
2533    for td in store.get_asts_for_sigs_bulk(&old_pairs)
2534        .into_iter()
2535        .filter_map(|r| r.ok())
2536        .filter_map(|s| match s { lex_ast::Stage::TypeDecl(td) => Some(td), _ => None })
2537    {
2538        old_types_by_name.insert(td.name.clone(), td);
2539    }
2540    // A name-independent fingerprint of a function's *contract*
2541    // (effects, param types, return type, examples — everything SigId
2542    // hashes except the name). Used only to disambiguate when multiple
2543    // candidates share a bare name: if this file's own declaration
2544    // structurally matches exactly one of them, that's unambiguously
2545    // the same evolving function; otherwise it's a new, unrelated
2546    // declaration that happens to reuse a name used elsewhere.
2547    fn structural_key(fd: &lex_ast::FnDecl) -> Option<String> {
2548        let mut anon = fd.clone();
2549        anon.name = String::new();
2550        lex_ast::sig_id(&lex_ast::Stage::FnDecl(anon))
2551    }
2552
2553    // Look up (and consume) the candidate in `map[name]` that matches
2554    // `new_fd`'s identity. One candidate is taken as unambiguous (so a
2555    // signature-changing edit still reads as a modification of the same
2556    // function); several always require an exact structural match to
2557    // disambiguate, and no match means this is a distinct, unrelated
2558    // declaration reusing a name used elsewhere — `None` rather than a
2559    // guess that mis-attributes history. Safe because the candidate pool
2560    // is complete and never grows: it is built once, up front, from the
2561    // whole branch.
2562    fn take_matching(
2563        map: &mut BTreeMap<String, Vec<lex_ast::FnDecl>>,
2564        name: &str,
2565        new_fd: &lex_ast::FnDecl,
2566    ) -> Option<lex_ast::FnDecl> {
2567        let candidates = map.get_mut(name)?;
2568        let idx = match candidates.len() {
2569            0 => return None,
2570            1 => 0,
2571            _ => {
2572                let want = structural_key(new_fd);
2573                candidates.iter().position(|c| structural_key(c) == want)?
2574            }
2575        };
2576        let matched = candidates.remove(idx);
2577        if candidates.is_empty() {
2578            map.remove(name);
2579        }
2580        Some(matched)
2581    }
2582
2583    // ---- one pass over the whole package -------------------------
2584    // `load_package` merges every file in the archive into ONE program
2585    // through a single shared loader pass. The flattening per-file loads
2586    // this replaced gave each top-level file its own copy of everything
2587    // it imported, so a shared dependency was canonicalized,
2588    // type-checked, diffed and published once per importing file: the
2589    // real 21-file `lex-schema` package, whose `error.lex` is imported by
2590    // 17 of its files, produced 2,239 `FnDecl`s for 693 distinct names
2591    // and paid for all 2,239 (#828). Collapsing 21 `publish_program`
2592    // calls into one matters even more than the 3.2x itself, because each
2593    // call independently reads every live function on the branch and
2594    // walks the op log for `old_imports`.
2595    //
2596    // The cost is that nothing is published under its bare source name
2597    // any more: `fn validate` in `src/field.lex` is
2598    // `field_<hash>.validate`. That is what makes one program safe to
2599    // check as a unit — the checker's global scope is keyed by name, and
2600    // two files may each declare their own `validate` (#818) — and it is
2601    // the naming change #828 asks for in exchange for the single pass.
2602    // The archive-publish path type-checks the loaded program with no
2603    // dependency resolver, so it still inlines registry/git deps to stay
2604    // self-contained (#930). The op-log-native `op push` path publishes
2605    // without inlining and resolves at the gate instead.
2606    let loaded = match load_package(&lex_files, tmp.path(), &pkg_name, /*inline_packages=*/ true) {
2607        Ok(p) => p,
2608        Err(e) => return error_response(400, format!("load package: {e}")),
2609    };
2610    let mut stages = canonicalize_program(&loaded.program);
2611    // Type errors are reported for the package, not per file: every name
2612    // in them carries its file's mangling prefix, so the offending file
2613    // is still named. Nothing is published unless the whole package
2614    // checks, where before each file published as it was processed and a
2615    // later failure left the earlier files' ops applied.
2616    if let Err(errs) = lex_types::check_and_rewrite_program(&mut stages) {
2617        return error_with_detail(
2618            422,
2619            format!("type errors in package {pkg_name}"),
2620            serde_json::to_value(&errs).unwrap(),
2621        );
2622    }
2623    let new_fns = stage_fns(&stages);
2624    let all_function_names: Vec<String> = new_fns.keys().cloned().collect();
2625
2626    // Resolve each declaration against the branch's current state. No
2627    // in-request bookkeeping is needed now: one pass means each name is
2628    // declared once, so there is no earlier file in this request whose
2629    // just-published version a later one has to diff against.
2630    let mut old_fns: BTreeMap<String, lex_ast::FnDecl> = BTreeMap::new();
2631    for (name, new_fd) in &new_fns {
2632        if let Some(fd) = take_matching(&mut old_fns_by_name, name, new_fd) {
2633            old_fns.insert(name.clone(), fd);
2634        }
2635    }
2636    let new_types = stage_types(&stages);
2637    // Only diff old types this publish also declares — one on the branch
2638    // but absent from this file-set is left alone (as unclaimed old fns
2639    // are), not read as removed.
2640    let old_types: BTreeMap<String, lex_ast::TypeDecl> = new_types
2641        .keys()
2642        .filter_map(|n| old_types_by_name.get(n).map(|td| (n.clone(), td.clone())))
2643        .collect();
2644    let report =
2645        lex_vcs::compute_diff_with_types(&old_fns, &new_fns, &old_types, &new_types, false);
2646
2647    // Imports stay attributed per file — `AddImport`/`RemoveImport` carry
2648    // an `in_file`, and history records these same root-relative keys.
2649    // Each file now gets only the modules it imports itself; a flattened
2650    // per-file load could not tell those from its children's.
2651    //
2652    // `imports_by_file` carries each import's real `as` alias (#909/#930), so
2653    // a non-default `import "..." as x` round-trips as `x`.
2654    let mut new_imports = lex_vcs::ImportMap::new();
2655    for (file, modules) in &loaded.imports_by_file {
2656        let entry = new_imports.entry(file.clone()).or_default();
2657        for (reference, alias) in modules {
2658            entry.insert(lex_vcs::ImportRef {
2659                reference: reference.clone(),
2660                alias: alias.clone(),
2661            });
2662        }
2663    }
2664
2665    // Record each declaration's source file (#894) so an HTTP-published
2666    // package de-flattens in `export-git` too, not just a CLI-published one.
2667    let outcome = match store.publish_program_with_intent(
2668        &branch,
2669        &stages,
2670        &report,
2671        &new_imports,
2672        false,
2673        None,
2674        None,
2675        &loaded.module_prefixes,
2676    ) {
2677        Ok(outcome) => outcome,
2678        Err(lex_store::StoreError::TypeError(errs)) => {
2679            return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
2680        }
2681        Err(e) => return write_error_response("publish_program", e),
2682    };
2683    let all_ops: Vec<serde_json::Value> = match serde_json::to_value(&outcome.ops) {
2684        Ok(serde_json::Value::Array(arr)) => arr,
2685        _ => Vec::new(),
2686    };
2687    let final_head_op = outcome.head_op;
2688
2689    // Deliberately no "genuinely removed" cleanup pass here. Whatever
2690    // remains in `old_fns_by_name` was never claimed by any file in
2691    // THIS archive — but the branch this walks is scoped to the whole
2692    // TENANT, not to this one package: a tenant that has ever published
2693    // more than one package (confirmed in production — `lex-schema` and
2694    // `lex-ocpi` share a tenant) has every other package's functions
2695    // sitting in `old_fns_by_name` too, forever unclaimed by any file in
2696    // *this* package's own archive. An earlier version of this handler
2697    // treated all such leftovers as "removed" and would have emitted
2698    // RemoveFunction ops for a completely unrelated package's functions
2699    // on every single publish. Caught before it shipped (`diff_to_ops`
2700    // failed atomically on a stale SigId before applying anything, so
2701    // no data was actually lost) — see alpibrusl/lex-lang#818's
2702    // follow-up. Nothing here currently tracks which package "owns" a
2703    // given branch function, so there's no reliable way to tell a
2704    // genuine same-package removal from another package's untouched
2705    // function; leaving a deleted function's stage un-removed (it just
2706    // sits there, unreferenced) is the safe default until package-scoped
2707    // ownership is tracked, not silently deleting a stranger's data.
2708    // Since #828 the same applies to a package's own previous names: the
2709    // first publish after file-prefixed naming landed leaves the bare
2710    // names it used to publish under sitting unreferenced, for the same
2711    // reason — this view cannot tell them from another package's.
2712
2713    let now = SystemTime::now()
2714        .duration_since(UNIX_EPOCH)
2715        .map(|d| d.as_secs())
2716        .unwrap_or(0);
2717    // External deps from the head's non-inlined imports (archive publish; the
2718    // op-log release route also accepts declared deps from lex.toml).
2719    let dependencies: Vec<String> = final_head_op
2720        .as_ref()
2721        .and_then(|h| lex_store::api::external_dependencies_at_op(&store, h).ok())
2722        .unwrap_or_default();
2723    let record = PkgRecord {
2724        name: pkg_name.clone(),
2725        version: pkg_version,
2726        head_op: final_head_op.clone(),
2727        published_at: now,
2728        function_names: all_function_names,
2729        dependencies,
2730        // The archive-upload path stores the uploaded archive verbatim (its
2731        // lex.toml already carries the full dependency table), so it is served
2732        // directly rather than re-rendered — no captured specs needed here.
2733        dependency_specs: Default::default(),
2734        ops: all_ops.clone(),
2735    };
2736    if let Err(e) = save_pkg_record(&state.root, &record, Some(body)) {
2737        return error_response(500, format!("save package index: {e}"));
2738    }
2739
2740    json_response(200, &serde_json::json!({
2741        "package": pkg_name,
2742        "ops": all_ops,
2743        "head_op": final_head_op,
2744    }))
2745}
2746
2747/// `GET /v1/pkg` — list packages published by this tenant (latest version of each).
2748fn pkg_list_handler(state: &State) -> Response<std::io::Cursor<Vec<u8>>> {
2749    let names = list_pkg_names(&state.root);
2750    let packages: Vec<serde_json::Value> = names.iter()
2751        .filter_map(|name| {
2752            let idx = load_pkg_index(&state.root, name)?;
2753            let latest = idx.latest.as_deref()?;
2754            let r = load_pkg_record(&state.root, name, latest)?;
2755            Some(serde_json::json!({
2756                "name": r.name,
2757                "version": r.version,
2758                "head_op": r.head_op,
2759                "published_at": r.published_at,
2760            }))
2761        })
2762        .collect();
2763    json_response(200, &serde_json::json!({ "packages": packages }))
2764}
2765
2766/// `GET /v1/pkg/{name}` — latest version details for a package.
2767fn pkg_get_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2768    match load_latest_pkg_record(&state.root, name) {
2769        Some(r) => json_response(200, &serde_json::json!({
2770            "name": r.name,
2771            "version": r.version,
2772            "head_op": r.head_op,
2773            "published_at": r.published_at,
2774            "function_names": r.function_names,
2775            "ops": r.ops,
2776        })),
2777        None => error_response(404, format!("package {name:?} not found")),
2778    }
2779}
2780
2781/// `GET /v1/pkg/{name}/versions` — all published versions for a package.
2782fn pkg_versions_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2783    match load_pkg_index(&state.root, name) {
2784        Some(idx) => json_response(200, &serde_json::json!({
2785            "name": name,
2786            "latest": idx.latest,
2787            "versions": idx.versions,
2788        })),
2789        None => error_response(404, format!("package {name:?} not found")),
2790    }
2791}
2792
2793/// `GET /v1/pkg/{name}/api-diff?from=<v>&to=<v>` — how the public API changed
2794/// between two releases (#893 propagation): the classification and the
2795/// mechanically-propagatable renames, so `lex propagate` can auto-derive its
2796/// `--rename` edits from a hosted release pair rather than have them restated.
2797fn pkg_api_diff_handler(state: &State, name: &str, query: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2798    let mut from: Option<String> = None;
2799    let mut to: Option<String> = None;
2800    for kv in query.split('&') {
2801        match kv.split_once('=') {
2802            Some(("from", v)) => from = Some(v.to_string()),
2803            Some(("to", v)) => to = Some(v.to_string()),
2804            _ => {}
2805        }
2806    }
2807    let (Some(from), Some(to)) = (from, to) else {
2808        return error_response(400, "api-diff requires ?from=<version>&to=<version>");
2809    };
2810    let head_of = |v: &str| load_pkg_record(&state.root, name, v).and_then(|r| r.head_op);
2811    let (Some(from_head), Some(to_head)) = (head_of(&from), head_of(&to)) else {
2812        return error_response(404, format!("{name}: unknown release in {from}..{to}"));
2813    };
2814
2815    let store = state.store.lock().unwrap();
2816    let (prev_api, new_api) = match (
2817        lex_store::api::public_api_at_op(&store, &from_head),
2818        lex_store::api::public_api_at_op(&store, &to_head),
2819    ) {
2820        (Ok(a), Ok(b)) => (a, b),
2821        _ => return error_response(500, "could not read package APIs for the given releases"),
2822    };
2823    let (change, detail) = match lex_store::api::classify_api_change(&prev_api, &new_api) {
2824        lex_store::api::ApiChange::Breaking(d) => ("breaking", d),
2825        lex_store::api::ApiChange::Additive(d) => ("additive", d),
2826        lex_store::api::ApiChange::None => ("none", String::new()),
2827    };
2828    let renames = lex_store::api::detect_renames(&prev_api, &new_api);
2829    json_response(200, &serde_json::json!({
2830        "name": name, "from": from, "to": to,
2831        "change": change, "detail": detail, "renames": renames,
2832    }))
2833}
2834
2835/// `GET /v1/pkg/{name}/{version}` — specific version details.
2836fn pkg_get_version_handler(state: &State, name: &str, version: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2837    match load_pkg_record(&state.root, name, version) {
2838        Some(r) => json_response(200, &serde_json::json!({
2839            "name": r.name,
2840            "version": r.version,
2841            "head_op": r.head_op,
2842            "published_at": r.published_at,
2843            "function_names": r.function_names,
2844            "dependencies": r.dependencies,
2845            "ops": r.ops,
2846        })),
2847        None => error_response(404, format!("package {name:?}@{version:?} not found")),
2848    }
2849}
2850
2851/// `GET /v1/pkg/{name}/{version}/archive` — download the source tar.gz.
2852fn pkg_archive_handler(state: &State, name: &str, version: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2853    let gzip = |bytes: Vec<u8>| {
2854        Response::from_data(bytes).with_status_code(200).with_header(
2855            tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"application/gzip"[..]).unwrap(),
2856        )
2857    };
2858
2859    // 1. A stored archive (the `lex pkg publish --registry` upload path).
2860    if let Ok(bytes) = std::fs::read(pkg_archive_path(&state.root, name, version)) {
2861        return gzip(bytes);
2862    }
2863
2864    // 2. An op-log-native release (op push + `POST …/release`, #911) has no
2865    //    stored archive — render one from the pinned op-log head so the
2866    //    package installs like any other (#920).
2867    if let Some(record) = load_pkg_record(&state.root, name, version) {
2868        if let Some(head_op) = record.head_op.clone() {
2869            match render_op_log_archive(state, name, version, &head_op, &record.dependency_specs) {
2870                Ok(bytes) => return gzip(bytes),
2871                Err(e) => {
2872                    return error_response(500, format!("rendering archive for {name:?}@{version:?}: {e}"));
2873                }
2874            }
2875        }
2876    }
2877
2878    error_response(404, format!("archive for {name:?}@{version:?} not found"))
2879}
2880
2881/// The archive path for a single-module head that records no source file of
2882/// its own — every op predating `in_file`. Historical, and kept so already
2883/// released packages in that state do not change name underneath their
2884/// dependents; the cure for them is a re-push, not a rename here (#988).
2885const DEFAULT_ARCHIVE_MODULE: &str = "src/lib.lex";
2886
2887/// Build a gzip-tar package archive (`lex.toml` + the package's `src/*.lex`)
2888/// by rendering the op-log head `head_op` to source — the composition of a
2889/// registry release (#911) with the op-log, so an `op push`-hosted package is
2890/// installable without a separately-uploaded archive (#920).
2891fn render_op_log_archive(
2892    state: &State,
2893    name: &str,
2894    version: &str,
2895    head_op: &str,
2896    dependency_specs: &std::collections::BTreeMap<String, DepSpec>,
2897) -> Result<Vec<u8>, String> {
2898    // De-flatten the head into its source tree — one file for a single-module
2899    // package, or the full `src/*.lex` layout for a multi-module one (#894).
2900    // The same renderer `lex export-git` uses, so the installed source matches
2901    // the git mirror. Either way the *names* come from the head itself; this
2902    // used to invent `src/lib.lex` for the single-module arm (#988).
2903    let (files, lock): (Vec<(String, String)>, Option<String>) = {
2904        let store = state.store.lock().unwrap();
2905        // #943: ship the lock this head was published against, so a consumer
2906        // that installs this package resolves ITS dependencies against the
2907        // pins it was built with. Without it a cached package directory has
2908        // no `lex.lock`, and any caret registry dependency of a dependency
2909        // was unresolvable (`UnlockedRegistryDep`).
2910        let lock = store.committed_lock_inherited(head_op).ok().flatten();
2911        let head = lex_store::render::package_head_at_op(&store, head_op)
2912            .map_err(|e| format!("reading head {head_op}: {e}"))?;
2913        let files = match lex_store::render::render_source(&store, &head)
2914            .map_err(|e| format!("rendering source at {head_op}: {e}"))?
2915        {
2916            lex_store::render::RenderedSource::Single { path, src } => {
2917                // A head that records no file keeps the registry's historical
2918                // name; one that does keeps its own (#988).
2919                vec![(path.unwrap_or_else(|| DEFAULT_ARCHIVE_MODULE.to_string()), src)]
2920            }
2921            lex_store::render::RenderedSource::Multi(tree) => tree.into_iter().collect(),
2922        };
2923        (files, lock)
2924    };
2925
2926    // Reconstruct the manifest from the release record. When the release
2927    // captured full dependency coordinates, emit a faithful `[dependencies]`
2928    // table (carrying both git and vcs references where the source declared
2929    // both); otherwise a bare `[package]` (pre-dependency-capture releases).
2930    let mut manifest = format!("[package]\nname = \"{name}\"\nversion = \"{version}\"\n");
2931    let dep_lines: Vec<String> = dependency_specs
2932        .iter()
2933        .filter_map(|(dep_name, spec)| spec.to_toml_inline().map(|inline| format!("{dep_name} = {inline}")))
2934        .collect();
2935    if !dep_lines.is_empty() {
2936        manifest.push_str("\n[dependencies]\n");
2937        for line in dep_lines {
2938            manifest.push_str(&line);
2939            manifest.push('\n');
2940        }
2941    }
2942    let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2943    {
2944        let mut ar = tar::Builder::new(&mut enc);
2945        let mut append = |p: &str, data: &[u8]| -> std::io::Result<()> {
2946            let mut h = tar::Header::new_gnu();
2947            h.set_size(data.len() as u64);
2948            h.set_mode(0o644);
2949            h.set_cksum();
2950            ar.append_data(&mut h, p, data)
2951        };
2952        append("lex.toml", manifest.as_bytes()).map_err(|e| e.to_string())?;
2953        if let Some(lock) = &lock {
2954            append("lex.lock", lock.as_bytes()).map_err(|e| e.to_string())?;
2955        }
2956        for (path, src) in &files {
2957            append(path, src.as_bytes()).map_err(|e| e.to_string())?;
2958        }
2959        ar.finish().map_err(|e| e.to_string())?;
2960    }
2961    enc.finish().map_err(|e| e.to_string())
2962}
2963
2964/// `GET /v1/pkg/{name}/head` — head op for a package's latest version.
2965fn pkg_head_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2966    match load_latest_pkg_record(&state.root, name) {
2967        Some(r) => json_response(200, &serde_json::json!({
2968            "name": r.name,
2969            "version": r.version,
2970            "head_op": r.head_op,
2971        })),
2972        None => error_response(404, format!("package {name:?} not found")),
2973    }
2974}
2975
2976/// `DELETE /v1/pkg/{name}` — retract the latest version of a package.
2977fn pkg_delete_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2978    let record = match load_latest_pkg_record(&state.root, name) {
2979        Some(r) => r,
2980        None => return error_response(404, format!("package {name:?} not found")),
2981    };
2982
2983    let store = state.store.lock().unwrap();
2984    let branch = store.current_branch();
2985
2986    let head = match store.branch_head(&branch) {
2987        Ok(h) => h,
2988        Err(e) => return error_response(500, format!("branch_head: {e}")),
2989    };
2990
2991    // Build old_fns from this package's function names that are still on
2992    // the branch, reading each AST through the SigId the head names. A
2993    // StageId-keyed read is ambiguous when two live functions differ only
2994    // in name (#826), and here that ambiguity decides what gets REMOVED:
2995    // it could both miss one of this package's functions and match a name
2996    // belonging to another package sharing the stage.
2997    let head_pairs: Vec<(String, String)> = head
2998        .iter()
2999        .map(|(sig, stage)| (sig.clone(), stage.clone()))
3000        .collect();
3001    let old_fns: BTreeMap<String, lex_ast::FnDecl> = store
3002        .get_asts_for_sigs_bulk(&head_pairs)
3003        .into_iter()
3004        .filter_map(|r| r.ok())
3005        .filter_map(|s| match s {
3006            lex_ast::Stage::FnDecl(fd)
3007                if record.function_names.contains(&fd.name) => Some((fd.name.clone(), fd)),
3008            _ => None,
3009        })
3010        .collect();
3011
3012    let new_fns: BTreeMap<String, lex_ast::FnDecl> = BTreeMap::new();
3013    let report = lex_vcs::compute_diff(&old_fns, &new_fns, false);
3014    let empty_imports = lex_vcs::ImportMap::new();
3015
3016    match store.publish_program(&branch, &[], &report, &empty_imports, false) {
3017        Ok(outcome) => {
3018            // Remove the version record and archive, then update the index.
3019            let ver = record.version.clone();
3020            let _ = std::fs::remove_file(pkg_version_path(&state.root, name, &ver));
3021            let _ = std::fs::remove_file(pkg_archive_path(&state.root, name, &ver));
3022            // Update index: remove this version, set latest to previous if any.
3023            if let Some(mut idx) = load_pkg_index(&state.root, name) {
3024                idx.versions.retain(|v| v.version != ver);
3025                idx.latest = idx.versions.last().map(|v| v.version.clone());
3026                if idx.versions.is_empty() {
3027                    let _ = std::fs::remove_dir_all(pkg_name_dir(&state.root, name));
3028                } else {
3029                    let bytes = serde_json::to_vec_pretty(&idx).unwrap_or_default();
3030                    let _ = std::fs::write(pkg_index_path(&state.root, name), bytes);
3031                }
3032            }
3033            json_response(200, &serde_json::json!({
3034                "deleted": name,
3035                "version": ver,
3036                "ops": outcome.ops,
3037                "head_op": outcome.head_op,
3038            }))
3039        }
3040        Err(lex_store::StoreError::TypeError(errs)) => {
3041            error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap())
3042        }
3043        Err(e) => write_error_response("retract package", e),
3044    }
3045}
3046
3047#[cfg(test)]
3048mod dep_spec_tests {
3049    use super::DepSpec;
3050
3051    #[test]
3052    fn a_dual_spec_renders_both_git_and_vcs_refs_vcs_first() {
3053        let spec = DepSpec {
3054            registry: Some("vcs.lexlang.org/lex-official/lex-schema".into()),
3055            version: Some("^0.9".into()),
3056            git: Some("https://github.com/alpibrusl/lex-schema".into()),
3057            ..Default::default()
3058        };
3059        assert_eq!(
3060            spec.to_toml_inline().as_deref(),
3061            Some("{ registry = \"vcs.lexlang.org/lex-official/lex-schema\", version = \"^0.9\", git = \"https://github.com/alpibrusl/lex-schema\" }"),
3062        );
3063    }
3064
3065    #[test]
3066    fn bare_git_and_bare_registry_specs_render_their_own_keys() {
3067        let git = DepSpec { git: Some("https://x/g".into()), tag: Some("v1".into()), ..Default::default() };
3068        assert_eq!(git.to_toml_inline().as_deref(), Some("{ git = \"https://x/g\", tag = \"v1\" }"));
3069        let reg = DepSpec { registry: Some("vcs/r".into()), version: Some("1.0.0".into()), ..Default::default() };
3070        assert_eq!(reg.to_toml_inline().as_deref(), Some("{ registry = \"vcs/r\", version = \"1.0.0\" }"));
3071    }
3072
3073    #[test]
3074    fn an_empty_spec_renders_nothing() {
3075        assert_eq!(DepSpec::default().to_toml_inline(), None);
3076    }
3077}
3078
3079#[cfg(test)]
3080mod policy_ceiling_tests {
3081    use super::*;
3082    use lex_runtime::Policy;
3083    use std::path::PathBuf;
3084
3085    /// A maximally-permissive policy of the kind a malicious caller
3086    /// would put in a `/v1/run` body: every dangerous effect plus
3087    /// fs over `/`.
3088    fn permissive_request() -> Policy {
3089        Policy {
3090            allow_effects: ["io", "fs_read", "fs_write", "net", "proc"]
3091                .iter()
3092                .map(|s| s.to_string())
3093                .collect(),
3094            allow_fs_read: vec![PathBuf::from("/")],
3095            allow_fs_write: vec![PathBuf::from("/")],
3096            allow_net_host: Vec::new(),
3097            allow_proc: Vec::new(),
3098            allow_approval: Vec::new(),
3099            budget: None,
3100        }
3101    }
3102
3103    #[test]
3104    fn ceiling_drops_effects_the_caller_was_not_granted() {
3105        let ceiling = Policy {
3106            allow_effects: ["io", "time"].iter().map(|s| s.to_string()).collect(),
3107            ..Policy::default()
3108        };
3109        let got = clamp_policy(permissive_request(), &ceiling);
3110        assert!(got.allow_effects.contains("io"));
3111        assert!(!got.allow_effects.contains("proc"), "proc must not survive a ceiling without it");
3112        assert!(!got.allow_effects.contains("fs_write"));
3113        assert!(!got.allow_effects.contains("net"));
3114        // `time` is in the ceiling but not the request → intersection drops it.
3115        assert!(!got.allow_effects.contains("time"));
3116    }
3117
3118    #[test]
3119    fn ceiling_scopes_override_caller_scopes() {
3120        let ceiling = Policy {
3121            allow_effects: ["fs_read"].iter().map(|s| s.to_string()).collect(),
3122            allow_fs_read: vec![PathBuf::from("/srv/tenant")],
3123            ..Policy::default()
3124        };
3125        let got = clamp_policy(permissive_request(), &ceiling);
3126        // Caller asked for "/" but only the ceiling's scope survives —
3127        // an empty/wider caller list can never widen the ceiling.
3128        assert_eq!(got.allow_fs_read, vec![PathBuf::from("/srv/tenant")]);
3129        assert!(got.allow_fs_write.is_empty());
3130        assert!(got.allow_proc.is_empty());
3131        assert!(got.allow_net_host.is_empty());
3132    }
3133
3134    #[test]
3135    fn ceiling_caps_budget_and_prefers_the_smaller() {
3136        // Caller wants unlimited; ceiling caps it.
3137        let mut req = permissive_request();
3138        req.budget = None;
3139        let ceiling = Policy { budget: Some(1_000), ..Policy::default() };
3140        assert_eq!(clamp_policy(req, &ceiling).budget, Some(1_000));
3141
3142        // Caller asks for less than the ceiling → keep the caller's.
3143        let mut req2 = permissive_request();
3144        req2.budget = Some(50);
3145        let ceiling2 = Policy { budget: Some(1_000), ..Policy::default() };
3146        assert_eq!(clamp_policy(req2, &ceiling2).budget, Some(50));
3147    }
3148
3149    #[test]
3150    fn empty_ceiling_is_pure_only() {
3151        let got = clamp_policy(permissive_request(), &Policy::default());
3152        assert!(got.allow_effects.is_empty(), "an empty ceiling grants nothing");
3153        assert!(got.allow_proc.is_empty());
3154        assert!(got.allow_fs_write.is_empty());
3155    }
3156}
3157
3158#[cfg(test)]
3159mod public_read_tests {
3160    use super::*;
3161
3162    /// Write a minimal package (index + per-version record + an archive
3163    /// blob) straight into a temp store, bypassing the publish pipeline.
3164    fn seed_pkg(root: &std::path::Path, name: &str, version: &str) {
3165        let record = PkgRecord {
3166            name: name.to_string(),
3167            version: version.to_string(),
3168            head_op: Some(format!("op-{name}")),
3169            published_at: 1,
3170            function_names: vec![format!("{name}.f")],
3171            dependencies: vec![],
3172            dependency_specs: Default::default(),
3173            ops: vec![],
3174        };
3175        save_pkg_record(root, &record, Some(format!("ARCHIVE:{name}@{version}").as_bytes()))
3176            .expect("seed package");
3177    }
3178
3179    #[test]
3180    fn new_package_defaults_to_private() {
3181        let tmp = tempfile::TempDir::new().unwrap();
3182        seed_pkg(tmp.path(), "lex-schema", "0.9.2");
3183        assert!(!pkg_is_public(tmp.path(), "lex-schema"));
3184        // Unknown packages are also "not public" — never distinguished.
3185        assert!(!pkg_is_public(tmp.path(), "does-not-exist"));
3186    }
3187
3188    #[test]
3189    fn set_visibility_round_trips_and_index_persists() {
3190        let tmp = tempfile::TempDir::new().unwrap();
3191        let state = State::open(tmp.path().to_path_buf()).unwrap();
3192        seed_pkg(tmp.path(), "lex-schema", "0.9.2");
3193
3194        let _ = pkg_set_visibility_handler(&state, "lex-schema", r#"{"visibility":"public"}"#);
3195        assert!(pkg_is_public(tmp.path(), "lex-schema"));
3196        // The version list survives the index rewrite (we don't clobber it).
3197        let idx = load_pkg_index(tmp.path(), "lex-schema").unwrap();
3198        assert_eq!(idx.latest.as_deref(), Some("0.9.2"));
3199        assert_eq!(idx.versions.len(), 1);
3200
3201        let _ = pkg_set_visibility_handler(&state, "lex-schema", r#"{"visibility":"private"}"#);
3202        assert!(!pkg_is_public(tmp.path(), "lex-schema"));
3203    }
3204
3205    #[test]
3206    fn set_visibility_on_unknown_package_is_a_noop() {
3207        let tmp = tempfile::TempDir::new().unwrap();
3208        let state = State::open(tmp.path().to_path_buf()).unwrap();
3209        // No package seeded → handler returns 404 and writes nothing.
3210        let _ = pkg_set_visibility_handler(&state, "ghost", r#"{"visibility":"public"}"#);
3211        assert!(load_pkg_index(tmp.path(), "ghost").is_none());
3212    }
3213
3214    #[test]
3215    fn public_listing_omits_private_packages() {
3216        let tmp = tempfile::TempDir::new().unwrap();
3217        let state = State::open(tmp.path().to_path_buf()).unwrap();
3218        seed_pkg(tmp.path(), "pub-pkg", "1.0.0");
3219        seed_pkg(tmp.path(), "priv-pkg", "1.0.0");
3220        let _ = pkg_set_visibility_handler(&state, "pub-pkg", r#"{"visibility":"public"}"#);
3221
3222        let names = public_pkg_names(tmp.path());
3223        assert_eq!(names, vec!["pub-pkg".to_string()]);
3224    }
3225
3226    #[test]
3227    fn resolve_public_maps_routes() {
3228        let get = Method::Get;
3229        assert_eq!(resolve_public(&get, "").unwrap(), PublicTarget::List);
3230        assert_eq!(resolve_public(&get, "/").unwrap(), PublicTarget::List);
3231        assert_eq!(
3232            resolve_public(&get, "/lex-schema").unwrap(),
3233            PublicTarget::Latest("lex-schema".into())
3234        );
3235        assert_eq!(
3236            resolve_public(&get, "/lex-schema/versions").unwrap(),
3237            PublicTarget::Versions("lex-schema".into())
3238        );
3239        assert_eq!(
3240            resolve_public(&get, "/lex-schema/head").unwrap(),
3241            PublicTarget::Head("lex-schema".into())
3242        );
3243        assert_eq!(
3244            resolve_public(&get, "/lex-schema/0.9.2").unwrap(),
3245            PublicTarget::Version("lex-schema".into(), "0.9.2".into())
3246        );
3247        assert_eq!(
3248            resolve_public(&get, "/lex-schema/0.9.2/archive").unwrap(),
3249            PublicTarget::Archive("lex-schema".into(), "0.9.2".into())
3250        );
3251    }
3252
3253    #[test]
3254    fn resolve_public_rejects_bad_method_and_traversal() {
3255        // Non-GET → 405.
3256        assert_eq!(resolve_public(&Method::Put, "/lex-schema"), Err(405));
3257        assert_eq!(resolve_public(&Method::Post, "").err(), Some(405));
3258        // Path traversal / invalid segments → 404, never a filesystem touch.
3259        assert_eq!(resolve_public(&Method::Get, "/.."), Err(404));
3260        assert_eq!(resolve_public(&Method::Get, "/lex-schema/../etc"), Err(404));
3261        assert_eq!(resolve_public(&Method::Get, "/a/b/c/d"), Err(404));
3262        // Slashes elsewhere can't smuggle a deep path: each segment is checked.
3263        assert!(resolve_public(&Method::Get, "/lex schema").is_err());
3264    }
3265}