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