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