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