Skip to main content

lex_api/
handlers.rs

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