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