Эх сурвалжийг харах

feat(runner): the function runner service - ctx surface, protocol, binary

Three layers, split by what they have to link, which is also what decides
where they can be tested:

runner_protocol is /run, /validate and /health as JSON in, JSON out - no
transport, no database. It takes a FunctionSource and a HostBindingsFactory,
so 30 tests drive every dispatch branch on a host where the database
client cannot compile at all.

runner_host is the ctx surface. Every collection access goes through
requireCapabilityCore() on a Principal built from the function's policy -
the same code an HTTP request takes, which is the whole reason Principal
exists. A function is never admin, and the scope pointer is ALWAYS set:
a null scope would mean unscoped full access, so that one line is what
makes an empty policy actually deny.

ctx.collections(...) is a direct gateway call, never loopback HTTP to our
own API - which would double the hops, re-authenticate for no reason and
need a credential a function deliberately does not have.

ctx.fetch closes the rebinding window the SSRF guard's header warns
about: a hostname is resolved exactly ONCE, classified with
blockReasonForAddresses(), and the connection is pinned to a checked
address with set_hostname_addr_map while SNI and Host: keep the real
name. Gating on ssrfBlockReason() instead would have forced a second
resolution, which IS the window. A literal IP still takes the no-DNS
path. cpp-httplib honours no proxy environment variable, verified.

main.cpp is the only part that links the world, and the only part that
cannot be built on the dev host.

The prelude is embedded as a raw string at configure time rather than
read at runtime: a deployed runner must not be able to execute a
different prelude because someone dropped a file beside the binary.

/validate compiles through the pool but deliberately NOT through the
bytecode cache - caller-supplied source must never land in a cache that
stored functions read from. A test is named for it.

Return shape follows the precedent documentBody() already set: an object
mixing envelope keys with others fails the run rather than being guessed
at, because the strict reading would silently drop the author's data.

RetiresARuntimeLeftWithPendingJobs no longer asserts which way a race
lands. Whether a job survives the bounded flush depends on how many were
queued when the deadline passed; it passed on the dev host and failed in
the build container. Both outcomes are safe, so the test now asserts what
must hold either way - the next tenant gets a clean runtime - and checks
retirement only when poisoning actually happened.
fszontagh 1 сар өмнө
parent
commit
fc63a26871

+ 80 - 0
runner/CMakeLists.txt

@@ -76,6 +76,21 @@ set_target_properties(runner_core PROPERTIES POSITION_INDEPENDENT_CODE ON)
 find_package(Threads REQUIRED)
 target_link_libraries(runner_core PUBLIC Threads::Threads)
 
+# Headers shared with the server: apikey.hpp (KeyScope) and
+# functions/descriptor.hpp. Both are pure, which is why the protocol layer may
+# use them without dragging in the database client.
+set(SVAPI_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")
+
+# /run, /validate and /health as JSON in, JSON out: no transport, no database,
+# which is what keeps the protocol testable on the dev host.
+add_library(runner_protocol STATIC src/run_service.cpp)
+target_include_directories(runner_protocol PUBLIC
+    ${CMAKE_CURRENT_SOURCE_DIR}/src
+    ${SVAPI_SRC_DIR})
+target_link_libraries(runner_protocol PUBLIC runner_core nlohmann_json::nlohmann_json)
+target_compile_features(runner_protocol PUBLIC cxx_std_20)
+set_target_properties(runner_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
 if(BUILD_TESTS)
     # Same find-then-fetch dance as tests/CMakeLists.txt, guarded so that
     # wiring this directory into the root project does not fetch twice.
@@ -95,4 +110,69 @@ if(BUILD_TESTS)
     add_executable(test_js_runtime tests/js_runtime_test.cpp)
     target_link_libraries(test_js_runtime PRIVATE runner_core GTest::gtest_main)
     gtest_discover_tests(test_js_runtime PROPERTIES TIMEOUT 120)
+
+    if(NOT TARGET OpenSSL::Crypto)
+        find_package(OpenSSL REQUIRED)   # apikey.cpp uses RAND_bytes
+    endif()
+    # Compiles the two pure server sources directly rather than linking
+    # vectorapi_core, the same approach tests/CMakeLists.txt uses, so this
+    # target still builds where smartbotic-db-client cannot.
+    add_executable(test_run_service
+        tests/run_service_test.cpp
+        ${SVAPI_SRC_DIR}/functions/descriptor.cpp
+        ${SVAPI_SRC_DIR}/apikey.cpp)
+    target_link_libraries(test_run_service PRIVATE
+        runner_protocol OpenSSL::Crypto GTest::gtest_main)
+    gtest_discover_tests(test_run_service PROPERTIES TIMEOUT 120)
+endif()
+
+# The host bindings: the ctx.* surface. A SEPARATE target from runner_core
+# because this is the half that links vectorapi_core and the database client,
+# which is exactly why runner_core itself still builds and tests on the dev
+# host (CLAUDE.md). Guarded, so configuring runner/ standalone still works.
+if(TARGET vectorapi_core)
+    # The JS prelude is embedded as a raw string literal, so the binary carries
+    # no runtime file dependency: a deployed runner cannot be made to execute a
+    # different prelude by swapping a file beside it.
+    set(SVAPI_HOST_PRELUDE "${CMAKE_CURRENT_SOURCE_DIR}/src/host_prelude.js")
+    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SVAPI_HOST_PRELUDE}")
+    file(READ "${SVAPI_HOST_PRELUDE}" SVAPI_HOST_PRELUDE_TEXT)
+    file(CONFIGURE
+        OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/host_prelude_js.hpp"
+        CONTENT "#pragma once
+// GENERATED from runner/src/host_prelude.js - do not edit.
+namespace svapi::runner::generated {
+inline constexpr const char* kHostPreludeJs = R\"JS(
+${SVAPI_HOST_PRELUDE_TEXT})JS\";
+} // namespace svapi::runner::generated
+"
+        @ONLY)
+
+    add_library(runner_host STATIC src/host_context.cpp)
+    target_include_directories(runner_host PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/generated)
+    # qjs again, PRIVATE on runner_core: host_context.cpp includes quickjs.h.
+    target_link_libraries(runner_host PUBLIC runner_core vectorapi_core PRIVATE qjs)
+    target_compile_features(runner_host PUBLIC cxx_std_20)
+    set_target_properties(runner_host PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+    if(BUILD_TESTS)
+        add_executable(test_host_context tests/host_context_test.cpp)
+        target_link_libraries(test_host_context PRIVATE runner_host GTest::gtest_main)
+        gtest_discover_tests(test_host_context PROPERTIES TIMEOUT 120)
+    endif()
+endif()
+
+# The binary links vectorapi_core (registry + gateway) and host_context.cpp, and
+# includes <svapi/version.hpp>, which only the root project generates. So it
+# exists only inside the root project; a standalone runner build stops at the
+# protocol layer and its tests.
+if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
+    add_executable(smartbotic-vectorapi-runner src/main.cpp)
+    target_link_libraries(smartbotic-vectorapi-runner PRIVATE
+        runner_protocol runner_host vectorapi_core
+        $<$<BOOL:${SYSTEMD_FOUND}>:PkgConfig::SYSTEMD>)
+    if(SYSTEMD_FOUND)
+        target_compile_definitions(smartbotic-vectorapi-runner PRIVATE HAVE_SYSTEMD)
+    endif()
+    install(TARGETS smartbotic-vectorapi-runner RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
 endif()

+ 13 - 0
runner/config/runner.json

@@ -0,0 +1,13 @@
+{
+  "log_level": "info",
+  "http": { "bind_address": "127.0.0.1", "port": 8090, "read_timeout_sec": 30 },
+  "database": { "address": "localhost:9004" },
+  "runtime": {
+    "pool_size": 4,
+    "memory_limit_bytes": 134217728,
+    "max_wall_time_ms": 2000,
+    "default_wall_time_ms": 0,
+    "max_stack_bytes": 524288,
+    "bytecode_cache_entries": 64
+  }
+}

+ 76 - 0
runner/include/runner/host_context.hpp

@@ -0,0 +1,76 @@
+#pragma once
+#include "apikey.hpp"
+#include "db_gateway.hpp"
+#include "functions/net_guard.hpp"
+#include "runner/js_runtime.hpp"
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+/// The `ctx` object a function receives.
+///
+/// This is the only place user JavaScript can reach the outside world, so it is
+/// also where policy is enforced. Two rules define it:
+///
+///   1. NO LOOPBACK HTTP. `ctx.collections(...)` is a direct DbGateway call, not
+///      a request back to vectorapi. A function calling its own API would double
+///      the hop count, re-authenticate for no reason, and need a credential that
+///      a function deliberately does not have. (`ctx.fetch` to an outbound
+///      provider is a different thing and is allowed, guarded.)
+///   2. ONE AUTHORIZATION IMPLEMENTATION. Every collection access goes through
+///      the same KeyScope check an HTTP request goes through, via
+///      requireCapabilityCore() on a Principal built from the function identity.
+///      If this file grew its own check, function access and HTTP access would
+///      drift apart, which is the whole reason Principal exists.
+namespace svapi::runner {
+
+/// Everything one run needs from the server. Built by the runner from the
+/// function's registry row plus the incoming trigger; never from the script.
+struct HostContextConfig {
+    std::string project;
+    std::string functionId;
+    /// From the registry row. The script cannot influence this - see
+    /// mergeForCodePush().
+    KeyScope policy;
+    /// {method, path, params, query, headers, body} for an HTTP trigger.
+    nlohmann::json trigger = nlohmann::json::object();
+    /// Secrets exposed as `ctx.env`. Values the function may read; never logged.
+    nlohmann::json env = nlohmann::json::object();
+    /// Wall-clock budget left for the whole run, used to bound outbound calls so
+    /// one slow provider cannot outlive the run that is waiting for it.
+    int64_t deadlineMs = 0;
+};
+
+/// Installs `ctx` for one run. One instance per run: it holds that run's
+/// identity and policy, and it is not reusable.
+class HostContext : public JsHostBindings {
+public:
+    HostContext(DbGateway& db, HostContextConfig config);
+    ~HostContext() override;
+
+    HostContext(const HostContext&) = delete;
+    HostContext& operator=(const HostContext&) = delete;
+
+    bool install(const JsBindingTarget& target, std::string& error) override;
+
+    /// Lines the function wrote with ctx.log, in order.
+    const std::vector<std::string>& logLines() const;
+
+    /// Outbound requests ctx.fetch refused, as human-readable reasons. Surfaced
+    /// in the run result so a blocked egress is visible rather than looking like
+    /// a network error the author must guess at.
+    const std::vector<std::string>& blockedEgress() const;
+
+private:
+    struct Impl;
+    std::unique_ptr<Impl> impl_;
+};
+
+/// The JavaScript prelude evaluated before the user module, which turns the few
+/// native bindings (`__hostDb`, `__hostFetch`, `__hostLog`) into the chainable
+/// builder the design document specifies. Kept in JS because a fluent builder is
+/// natural there and miserable in C++; kept SMALL because everything it does not
+/// do is done in C++ where it can be tested without an engine.
+std::string_view hostPreludeSource();
+
+} // namespace svapi::runner

+ 883 - 0
runner/src/host_context.cpp

@@ -0,0 +1,883 @@
+#include "runner/host_context.hpp"
+
+#include "collection_registry.hpp"
+#include "db_errors.hpp"
+#include "embedding_cache.hpp"
+#include "embeddings.hpp"
+#include "errors.hpp"
+#include "filters.hpp"
+#include "outbound_http.hpp"
+#include "principal.hpp"
+#include "project_settings.hpp"
+#include "server.hpp"
+#include "settings.hpp"
+#include "settings_store.hpp"
+#include "vector_search.hpp"
+
+// Generated from runner/src/host_prelude.js at configure time. The .js file is
+// the editable copy; nothing reads it at runtime, so the binary has no file
+// dependency and a deployed runner cannot be made to execute a different
+// prelude by swapping a file next to it.
+#include "host_prelude_js.hpp"
+
+#include <httplib.h>
+#include <quickjs.h>
+
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <sys/socket.h>
+
+#include <algorithm>
+#include <cctype>
+#include <chrono>
+#include <cstdint>
+#include <functional>
+#include <limits>
+#include <map>
+#include <optional>
+#include <unordered_map>
+#include <utility>
+
+namespace svapi::runner {
+namespace {
+
+/// Same bounds the execution core puts on console capture, for the same reason:
+/// ctx.log is otherwise an unmetered allocation channel, and the lines travel
+/// back over HTTP to whoever invoked the function.
+constexpr size_t kMaxLogLines = 1000;
+constexpr size_t kMaxLogBytes = 64u * 1024;
+
+/// What one outbound call gets when the run carries no explicit budget. Never
+/// unbounded: a provider that never answers would pin a pooled runtime for as
+/// long as the socket stays open.
+constexpr int64_t kDefaultOutboundTimeoutMs = 10000;
+
+int64_t nowMs() {
+    using namespace std::chrono;
+    return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
+}
+
+bool isAddressLiteral(const std::string& host) {
+    unsigned char buf[16];
+    return inet_pton(AF_INET, host.c_str(), buf) == 1 ||
+           inet_pton(AF_INET6, host.c_str(), buf) == 1;
+}
+
+// --- the C++/JS value boundary ---------------------------------------------
+
+JSValue toJs(JSContext* ctx, const nlohmann::json& j) {
+    const std::string text = j.dump();
+    return JS_ParseJSON(ctx, text.c_str(), text.size(), "<host>");
+}
+
+std::string toText(JSContext* ctx, JSValueConst v) {
+    const char* s = JS_ToCString(ctx, v);
+    if (!s) {
+        JS_FreeValue(ctx, JS_GetException(ctx));
+        return std::string();
+    }
+    std::string out(s);
+    JS_FreeCString(ctx, s);
+    return out;
+}
+
+/// A JS argument as JSON. `undefined` becomes null rather than failing, because
+/// the prelude passes every optional field through and most are absent.
+nlohmann::json fromJs(JSContext* ctx, JSValueConst v) {
+    JSValue json = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
+    if (JS_IsException(json)) {
+        JS_FreeValue(ctx, JS_GetException(ctx));
+        JS_FreeValue(ctx, json);
+        return nullptr;
+    }
+    if (JS_IsUndefined(json)) {
+        JS_FreeValue(ctx, json);
+        return nullptr;
+    }
+    const std::string text = toText(ctx, json);
+    JS_FreeValue(ctx, json);
+    nlohmann::json out = nlohmann::json::parse(text, nullptr, false);
+    return out.is_discarded() ? nlohmann::json(nullptr) : out;
+}
+
+/// An ApiError as a catchable JS Error carrying the slug and status, so a
+/// function can branch on `e.code` instead of matching message text. `details`
+/// is forwarded too: it is how relation impacts on a blocked delete reach the
+/// script rather than being flattened into a sentence.
+JSValue throwApiError(JSContext* ctx, const ApiError& e) {
+    JSValue err = JS_NewError(ctx);
+    JS_SetPropertyStr(ctx, err, "message", JS_NewString(ctx, e.what()));
+    JS_SetPropertyStr(ctx, err, "code", JS_NewString(ctx, e.slug.c_str()));
+    JS_SetPropertyStr(ctx, err, "status", JS_NewInt32(ctx, httpStatus(e.code)));
+    if (!e.details.empty()) JS_SetPropertyStr(ctx, err, "details", toJs(ctx, e.details));
+    return JS_Throw(ctx, err);
+}
+
+} // namespace
+
+/// The pure seams, in a named namespace so the test can reach them: the policy
+/// decision and the request/response shaping, split out of the native bindings
+/// so each is testable without an engine, a resolver or a database. Not in the
+/// public header - they are an implementation detail of the bindings, not part
+/// of the `ctx` contract.
+namespace hostdetail {
+
+/// Where ctx.fetch may connect, and to which address.
+struct EgressDecision {
+    bool allowed = false;
+    std::string pinnedAddress;  ///< the address the guard approved, to connect to
+    std::string reason;         ///< why not, when !allowed
+};
+
+/// Injected so the classification rules are testable without a resolver.
+using Resolver = std::function<std::vector<std::string>(const std::string&)>;
+
+/// The op a builder call needs granted.
+///
+/// Deliberately op-for-op what the HTTP handlers ask for: documents.cpp takes
+/// List for a listing and Read for a point get, vectors.cpp takes Search for
+/// /search and Insert for a vector write. If this table drifted, a function
+/// would reach data through a weaker grant than the equivalent HTTP call needs,
+/// which is exactly the divergence Principal exists to prevent.
+std::optional<KeyOp> keyOpForDbOp(const std::string& op) {
+    if (op == "find")   return KeyOp::List;
+    if (op == "get")    return KeyOp::Read;
+    if (op == "insert") return KeyOp::Insert;
+    if (op == "update") return KeyOp::Update;
+    if (op == "patch")  return KeyOp::Update;
+    if (op == "delete") return KeyOp::Delete;
+    if (op == "search") return KeyOp::Search;
+    if (op == "store")  return KeyOp::Insert;
+    return std::nullopt;
+}
+
+/// Names the collection and the op, because the author of a refused function
+/// has to know WHICH grant to ask an admin for. "forbidden" on its own sends
+/// them guessing through a policy they cannot see.
+std::string deniedMessage(const std::string& collection, const std::string& op,
+                          const std::string& why) {
+    return "collection '" + collection + "', operation '" + op + "': " + why;
+}
+
+/// The builder's accumulated state as database query options. Shaped here, in a
+/// pure function, rather than inside the native binding: the filter grammar and
+/// the paging arguments are where a mistake is silent, and this is testable
+/// without an engine or a database.
+smartbotic::database::Client::QueryOptions queryOptionsFrom(const nlohmann::json& payload) {
+    smartbotic::database::Client::QueryOptions opts;
+    if (!payload.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "the query must be an object");
+
+    nlohmann::json filters = payload.value("filters", nlohmann::json::array());
+    if (!filters.is_array())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "filters must be an array of \"field:op:value\" strings");
+    for (const auto& f : filters) {
+        if (!f.is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "each filter must be a \"field:op:value\" string");
+        // THE shared parser. Same grammar, same operator set, same errors as
+        // ?filter= on /documents, and the database evaluates the result - so a
+        // function and an HTTP call can never disagree about what a filter means.
+        opts.filters.push_back(parseFilter(f.get<std::string>()));
+    }
+
+    // is_number_integer() rather than is_number_unsigned(): a value that
+    // travelled through JSON arrives unsigned, but one built in C++ (a test,
+    // or a future caller) does not, and the two must agree. A float or a
+    // negative value is still refused, as ?limit= refuses them over HTTP.
+    auto unsignedField = [&payload](const char* name) -> uint32_t {
+        if (!payload.contains(name) || payload.at(name).is_null()) return 0;
+        const nlohmann::json& v = payload.at(name);
+        if (!v.is_number_integer())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string(name) + " must be a non-negative integer");
+        const int64_t wide = v.get<int64_t>();
+        if (wide < 0 || wide > std::numeric_limits<uint32_t>::max())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string(name) + " must be a non-negative integer");
+        return static_cast<uint32_t>(wide);
+    };
+    opts.limit  = unsignedField("limit");
+    opts.offset = unsignedField("offset");
+
+    if (payload.contains("sort") && !payload.at("sort").is_null()) {
+        const nlohmann::json& sort = payload.at("sort");
+        if (!sort.is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation", "sort must be a field name");
+        opts.sortField = sort.get<std::string>();
+    }
+    if (payload.contains("desc") && !payload.at("desc").is_null()) {
+        const nlohmann::json& desc = payload.at("desc");
+        if (!desc.is_boolean())
+            throw ApiError(ErrCode::Unprocessable, "validation", "desc must be a boolean");
+        opts.sortDescending = desc.get<bool>();
+    }
+    return opts;
+}
+
+/// How long one outbound call may take: what is left of the run's budget,
+/// narrowed by whatever the caller asked for. A caller can ask for less and
+/// never for more, so one slow provider cannot outlive the run waiting on it.
+/// A non-positive result means the budget is gone and nothing should connect.
+int64_t outboundTimeoutMs(int64_t deadline_ms, int64_t elapsed_ms, int64_t requested_ms) {
+    int64_t budget = deadline_ms > 0 ? deadline_ms - elapsed_ms : kDefaultOutboundTimeoutMs;
+    if (requested_ms > 0 && requested_ms < budget) budget = requested_ms;
+    return budget;
+}
+
+/// Where ctx.fetch is allowed to connect, and to which address.
+///
+/// `resolve` is injected so the two rules that matter - classify EVERY address,
+/// fail closed - are testable without a resolver.
+///
+/// On the TOCTOU gap the design addendum asks to close: ssrfBlockReason() is the
+/// mandated gate for a literal, where there is no name and therefore no
+/// rebinding window at all. For a NAME it cannot be the gate, because it
+/// discards the addresses it approved and the caller would have to resolve
+/// again - which is the rebinding window. So a name is resolved exactly once
+/// here and classified with blockReasonForAddresses(), which net_guard.hpp
+/// documents as ssrfBlockReason's own classification half. One classifier, one
+/// lookup, and the address the connection pins was the address that was checked.
+EgressDecision decideEgress(const functions::HttpUrlParts& parts,
+                            const functions::SsrfPolicy& policy, const Resolver& resolve) {
+    EgressDecision d;
+    if (isAddressLiteral(parts.host)) {
+        if (auto why = functions::ssrfBlockReason(parts.host, policy)) {
+            d.reason = *why;
+            return d;
+        }
+        d.allowed = true;
+        d.pinnedAddress = parts.host;
+        return d;
+    }
+
+    const std::vector<std::string> addresses = resolve(parts.host);
+    if (auto why = functions::blockReasonForAddresses(parts.host, addresses, policy)) {
+        d.reason = *why;
+        return d;
+    }
+    d.allowed = true;
+    // Any approved address would do; the first keeps the resolver's own
+    // ordering, which is what an unpinned client would have used.
+    d.pinnedAddress = addresses.front();
+    return d;
+}
+
+std::vector<std::string> resolveWithGetaddrinfo(const std::string& host) {
+    std::vector<std::string> out;
+    addrinfo hints{};
+    hints.ai_family = AF_UNSPEC;
+    hints.ai_socktype = SOCK_STREAM;
+    addrinfo* res = nullptr;
+    if (getaddrinfo(host.c_str(), nullptr, &hints, &res) != 0) return out;
+    for (addrinfo* p = res; p != nullptr; p = p->ai_next) {
+        char buf[INET6_ADDRSTRLEN] = {0};
+        const void* addr = nullptr;
+        if (p->ai_family == AF_INET)
+            addr = &reinterpret_cast<sockaddr_in*>(p->ai_addr)->sin_addr;
+        else if (p->ai_family == AF_INET6)
+            addr = &reinterpret_cast<sockaddr_in6*>(p->ai_addr)->sin6_addr;
+        if (addr != nullptr && inet_ntop(p->ai_family, addr, buf, sizeof(buf)) != nullptr)
+            out.emplace_back(buf);
+    }
+    freeaddrinfo(res);
+    return out;
+}
+
+} // namespace hostdetail
+
+// ---------------------------------------------------------------------------
+
+struct HostContext::Impl {
+    DbGateway& db;
+    HostContextConfig config;
+    CollectionRegistry registry;
+
+    /// Principal::projects is a non-owning pointer, so the list it points at
+    /// has to outlive every authorize() call: it lives here, not on the stack.
+    std::vector<std::string> projects;
+    std::string principalId;
+
+    int64_t startedMs = nowMs();
+
+    std::vector<std::string> log;
+    size_t logBytes = 0;
+    bool logTruncated = false;
+    std::vector<std::string> blocked;
+
+    /// The registry row per collection, read once per run. A row cannot
+    /// meaningfully change mid-run, and the HTTP path pays this read once per
+    /// request too.
+    std::unordered_map<std::string, std::optional<CollectionMeta>> metaCache;
+
+    /// Pinned for the whole run so a settings hot-reload cannot change the
+    /// egress rules between two fetches of the same function.
+    std::shared_ptr<const functions::SsrfPolicy> ssrf = functions::currentSsrfPolicy();
+
+    bool settingsLoaded = false;
+    Settings global;
+    std::optional<ProjectSettings> projectEmbedding;
+
+    Impl(DbGateway& gateway, HostContextConfig cfg)
+        : db(gateway), config(std::move(cfg)), registry(gateway) {
+        projects.push_back(config.project);
+        // A separate namespace from key ids, so a function cannot spend a key's
+        // rate-limit budget (and the other way round).
+        principalId = "fn:" + config.project + "/" + config.functionId;
+    }
+
+    /// A function is never admin: admin is a key-level flag, and a policy is a
+    /// KeyScope. The scope pointer is ALWAYS set, which is what makes an empty
+    /// policy grant nothing - a null scope would mean unscoped full access.
+    Principal principal() const {
+        return Principal{principalId, &projects, false, &config.policy};
+    }
+
+    /// The one authorization check. requireCapabilityCore() decides; this only
+    /// re-labels the refusal so the message names what was refused.
+    void authorize(const std::string& collection, KeyOp op) {
+        try {
+            requireCapabilityCore(principal(), config.project, collection, op);
+        } catch (const ApiError& e) {
+            throw ApiError(e.code, e.slug,
+                           hostdetail::deniedMessage(collection, keyOpToString(op), e.what()),
+                           e.details);
+        }
+    }
+
+    void addLog(std::string line) {
+        if (log.size() >= kMaxLogLines || logBytes >= kMaxLogBytes) {
+            if (!logTruncated) {
+                logTruncated = true;
+                log.emplace_back("[log output truncated]");
+            }
+            return;
+        }
+        logBytes += line.size();
+        log.push_back(std::move(line));
+    }
+
+    int64_t elapsedMs() const { return nowMs() - startedMs; }
+
+    // --- collections --------------------------------------------------------
+
+    const CollectionMeta& meta(const std::string& collection) {
+        auto it = metaCache.find(collection);
+        if (it == metaCache.end())
+            it = metaCache.emplace(collection, registry.get(config.project, collection)).first;
+        if (!it->second)
+            throw ApiError(ErrCode::NotFound, "not_found", "no such collection '" + collection + "'");
+        return *it->second;
+    }
+
+    const CollectionMeta& vectorMeta(const std::string& collection) {
+        const CollectionMeta& m = meta(collection);
+        if (m.kind != "vector")
+            throw ApiError(ErrCode::Unprocessable, "not_vector",
+                           "collection '" + collection + "' is not a vector collection");
+        return m;
+    }
+
+    /// The global settings document plus this project's overrides, read once.
+    ///
+    /// Read directly rather than through SettingsStore because the seam gives
+    /// the runner a DbGateway and nothing else - and because SettingsStore's
+    /// bootstrap() WRITES (it seeds the document), which a runner must never do
+    /// to the configuration it is merely reading. The precedence itself still
+    /// comes from the one pure resolveEmbedding().
+    void loadSettings() {
+        if (settingsLoaded) return;
+        settingsLoaded = true;
+        const std::string coll = qualify("default", kSettingsCollection);
+        if (auto doc = db.client().get(coll, "current")) global = Settings::fromJson(*doc);
+        if (auto doc = db.client().get(coll, projectSettingsDocId(config.project)))
+            projectEmbedding = ProjectSettings::fromJson(*doc);
+    }
+
+    /// Embed `text` for a vector op. Mirrors handlers/vectors.cpp: the same
+    /// cache, keyed the same way, so a function and an HTTP call that embed the
+    /// same string cost one provider call between them.
+    std::vector<float> embed(const CollectionMeta& m, const std::string& text) {
+        loadSettings();
+        ResolvedEmbedding cfg =
+            resolveEmbedding(global, projectEmbedding ? &*projectEmbedding : nullptr, m);
+
+        EmbeddingCache::Key key{cfg.apiBase, cfg.model, text};
+        if (auto hit = embeddingCache().get(key)) return *hit;
+
+        // The provider call is outbound work, so it answers to the run's budget
+        // like ctx.fetch does. Seconds, because that is the client's unit.
+        const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), 0);
+        if (budget <= 0)
+            throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
+                           "the run's time budget is exhausted; not calling the embedding provider");
+        const uint32_t readSec = std::min<uint32_t>(
+            global.embeddingReadTimeoutSec, static_cast<uint32_t>((budget + 999) / 1000));
+
+        EmbeddingClient emb(cfg.apiBase, cfg.apiKey, global.embeddingConnectTimeoutSec,
+                            std::max<uint32_t>(readSec, 1), global.embeddingClientPoolSize);
+        std::vector<float> v = emb.embed(cfg.model, text);
+        embeddingCache().put(key, v);
+        return v;
+    }
+
+    /// The query vector for a search or a store, from `vecField` or `textField`.
+    /// Same shape and same dimension check as handlers/vectors.cpp.
+    std::vector<float> resolveVector(const CollectionMeta& m, const nlohmann::json& payload,
+                                     const char* vecField, const char* textField) {
+        std::vector<float> v;
+        if (payload.contains(vecField) && payload.at(vecField).is_array()) {
+            v = payload.at(vecField).get<std::vector<float>>();
+        } else if (payload.contains(textField) && payload.at(textField).is_string()) {
+            v = embed(m, payload.at(textField).get<std::string>());
+        } else {
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           std::string("provide '") + vecField + "' or '" + textField + "'");
+        }
+        if (v.size() != m.vectorDimension)
+            throw ApiError(ErrCode::Unprocessable, "dimension_mismatch",
+                           "expected dimension " + std::to_string(m.vectorDimension) + ", got " +
+                               std::to_string(v.size()));
+        return v;
+    }
+
+    /// `__hostDb(collection, op, payload)`.
+    ///
+    /// Order is load bearing: authorize, then validate the arguments, then
+    /// touch the database. Authorizing last would let an unauthorized call be
+    /// told whether a collection exists; validating after the registry read
+    /// would spend a round trip on a request that was malformed anyway.
+    nlohmann::json dbCall(const std::string& collection, const std::string& op,
+                          const nlohmann::json& payload) {
+        auto keyOp = hostdetail::keyOpForDbOp(op);
+        if (!keyOp)
+            throw ApiError(ErrCode::BadRequest, "validation",
+                           "unknown collection operation '" + op + "'");
+        authorize(collection, *keyOp);
+
+        if (op == "find")   return find(collection, payload);
+        if (op == "get")    return get(collection, payload);
+        if (op == "insert") return insert(collection, payload);
+        if (op == "update") return update(collection, payload);
+        if (op == "patch")  return patch(collection, payload);
+        if (op == "delete") return remove(collection, payload);
+        if (op == "search") return search(collection, payload);
+        return store(collection, payload);
+    }
+
+    std::string documentId(const nlohmann::json& payload) {
+        if (!payload.is_object() || !payload.contains("id") || !payload.at("id").is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation", "a document id is required");
+        std::string id = payload.at("id").get<std::string>();
+        if (id.empty())
+            throw ApiError(ErrCode::Unprocessable, "validation", "a document id is required");
+        return id;
+    }
+
+    /// The document a write carries. No `{"data":...}` unwrapping here: that
+    /// shape exists because an HTTP body has no other way to say "this is the
+    /// document", while `.insert(doc)` already passes the document itself. `id`
+    /// is stripped because it is the document's identity, not a field - the
+    /// same reason documentBody() strips it on the HTTP side.
+    nlohmann::json documentFrom(const nlohmann::json& payload) {
+        if (!payload.is_object() || !payload.contains("doc") || !payload.at("doc").is_object())
+            throw ApiError(ErrCode::Unprocessable, "validation", "the document must be an object");
+        nlohmann::json out = payload.at("doc");
+        out.erase("id");
+        return out;
+    }
+
+    nlohmann::json find(const std::string& collection, const nlohmann::json& payload) {
+        auto opts = hostdetail::queryOptionsFrom(payload);
+        meta(collection);
+        nlohmann::json out = nlohmann::json::array();
+        for (const auto& doc : db.client().find(qualify(config.project, collection), opts))
+            out.push_back(doc);
+        return out;
+    }
+
+    /// Null for a missing document rather than a 404: a script that asks for a
+    /// document by id and tests the answer is ordinary JavaScript, and the
+    /// alternative is wrapping every .get() in try/catch. The authorization and
+    /// the data are identical to the HTTP route; only the shape of "absent"
+    /// differs, and only because the HTTP route has a status code to spend.
+    nlohmann::json get(const std::string& collection, const nlohmann::json& payload) {
+        const std::string id = documentId(payload);
+        meta(collection);
+        auto doc = db.client().get(qualify(config.project, collection), id);
+        return doc ? *doc : nlohmann::json(nullptr);
+    }
+
+    nlohmann::json insert(const std::string& collection, const nlohmann::json& payload) {
+        nlohmann::json doc = documentFrom(payload);
+        // An explicit id is honoured, exactly as POST /documents honours
+        // body.id, so a function can write an idempotent row.
+        std::string id;
+        if (payload.at("doc").is_object() && payload.at("doc").contains("id") &&
+            payload.at("doc").at("id").is_string())
+            id = payload.at("doc").at("id").get<std::string>();
+        meta(collection);
+        std::string newId;
+        try {
+            newId = db.client().insert(qualify(config.project, collection), doc, id);
+        } catch (const smartbotic::database::Client::Error& e) {
+            throw apiErrorFor(e);
+        }
+        if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
+        return nlohmann::json{{"id", newId}};
+    }
+
+    nlohmann::json update(const std::string& collection, const nlohmann::json& payload) {
+        const std::string id = documentId(payload);
+        nlohmann::json doc = documentFrom(payload);
+        meta(collection);
+        smartbotic::database::Client::Failure failure;
+        if (!db.client().update(qualify(config.project, collection), id, doc, failure))
+            throw apiErrorFor(failure, "no such document");
+        return nlohmann::json{{"id", id}};
+    }
+
+    nlohmann::json patch(const std::string& collection, const nlohmann::json& payload) {
+        const std::string id = documentId(payload);
+        nlohmann::json fields = documentFrom(payload);
+        meta(collection);
+        smartbotic::database::Client::Failure failure;
+        const uint64_t v = db.client().patch(qualify(config.project, collection), id, fields, failure);
+        if (v == 0) throw apiErrorFor(failure, "no such document");
+        return nlohmann::json{{"id", id}, {"version", v}};
+    }
+
+    nlohmann::json remove(const std::string& collection, const nlohmann::json& payload) {
+        const std::string id = documentId(payload);
+        meta(collection);
+        const std::string c = qualify(config.project, collection);
+        smartbotic::database::Client::Failure failure;
+        if (!db.client().remove(c, id, failure)) {
+            // A restrict relation is the one refusal the script can act on, so
+            // it arrives as the impact list on the error rather than a sentence
+            // - same payload the HTTP route answers with.
+            if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
+                auto why = db.client().describeDelete(c, id);
+                if (why.success && why.wouldBeBlocked)
+                    throw ApiError(ErrCode::Conflict, "relation_restricted",
+                                   "delete blocked by a relation",
+                                   {{"impacts", impactsJson(config.project, why)}});
+            }
+            throw apiErrorFor(failure, "no such document");
+        }
+        return nlohmann::json{{"deleted", id}};
+    }
+
+    /// Vector search. The filter-then-rank intersection is the same algorithm
+    /// and the same scan cap as handlers/vectors.cpp, because the two must
+    /// return the same rows with the same scores for the same query. It is
+    /// duplicated rather than shared only because it currently lives inside
+    /// that route's lambda; extracting it is a separate, mechanical change.
+    nlohmann::json search(const std::string& collection, const nlohmann::json& payload) {
+        auto filters = hostdetail::queryOptionsFrom(payload).filters;
+        const CollectionMeta& m = vectorMeta(collection);
+        std::vector<float> q = resolveVector(m, payload, "query_vector", "query_text");
+
+        // Same default as POST /search, so a function and an HTTP call that
+        // omit top_k get the same number of hits.
+        uint32_t topK = 5;
+        if (payload.contains("top_k") && payload.at("top_k").is_number_integer()) {
+            const int64_t wide = payload.at("top_k").get<int64_t>();
+            if (wide > 0 && wide <= std::numeric_limits<uint32_t>::max())
+                topK = static_cast<uint32_t>(wide);
+        }
+        float minScore = 0.0f;
+        if (payload.contains("min_score") && payload.at("min_score").is_number())
+            minScore = payload.at("min_score").get<float>();
+
+        const std::string c = qualify(config.project, collection);
+        // The shared implementation, not a copy: a filter must mean the same
+        // thing here as it does on the HTTP route, scan cap included.
+        const std::vector<smartbotic::database::Client::SimilarityResult> results =
+            vectorSearch(db.client(), c, q, topK, minScore, filters);
+
+        // An array, not {results:[...]}: the design's own example reads the
+        // return value as the hits.
+        nlohmann::json out = nlohmann::json::array();
+        for (const auto& r : results)
+            out.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
+        return out;
+    }
+
+    nlohmann::json store(const std::string& collection, const nlohmann::json& payload) {
+        const CollectionMeta& m = vectorMeta(collection);
+        std::vector<float> vec = resolveVector(m, payload, "vector", "text");
+
+        nlohmann::json doc = nlohmann::json::object();
+        if (payload.contains("metadata") && payload.at("metadata").is_object())
+            doc = payload.at("metadata");
+        doc.erase("id");
+        if (payload.contains("text") && payload.at("text").is_string())
+            doc["text"] = payload.at("text");
+        doc["_vector"] = vec;
+
+        std::string id;
+        if (payload.contains("id") && payload.at("id").is_string())
+            id = payload.at("id").get<std::string>();
+        std::string newId;
+        try {
+            newId = db.client().insert(qualify(config.project, collection), doc, id);
+        } catch (const smartbotic::database::Client::Error& e) {
+            throw apiErrorFor(e);
+        }
+        if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
+        return nlohmann::json{{"id", newId}};
+    }
+
+    // --- egress -------------------------------------------------------------
+
+    /// `__hostFetch(url, options)`.
+    nlohmann::json fetch(const std::string& url, const nlohmann::json& options) {
+        auto parts = functions::parseHttpUrl(url);
+        if (!parts) {
+            // Fail closed, and say so out loud: file:, gopher: and a bare
+            // hostname are all refused here, and an author who cannot see why
+            // would otherwise read it as a network failure.
+            const std::string reason = "refused '" + url + "': not an absolute http(s) URL";
+            blocked.push_back(reason);
+            throw ApiError(ErrCode::Forbidden, "egress_blocked", reason);
+        }
+
+        auto decision = hostdetail::decideEgress(*parts, *ssrf, hostdetail::resolveWithGetaddrinfo);
+        if (!decision.allowed) {
+            blocked.push_back(decision.reason);
+            throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
+        }
+
+        int64_t requested = 0;
+        if (options.contains("timeoutMs") && options.at("timeoutMs").is_number_integer())
+            requested = std::max<int64_t>(options.at("timeoutMs").get<int64_t>(), 0);
+        const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), requested);
+        // Checked BEFORE connecting, so an exhausted budget costs no socket.
+        // Not an egress refusal: nothing about the destination was wrong.
+        if (budget <= 0)
+            throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
+                           "the run's time budget is exhausted; not connecting to '" + parts->host + "'");
+
+        // The client is built on the NAME, so SNI, certificate verification and
+        // the Host header are all the name the policy approved, and the address
+        // map is what actually gets connected to. That pair is how the
+        // classify-then-connect gap closes: no second resolution happens.
+        //
+        // httplib reads no http_proxy/https_proxy environment variable and
+        // set_proxy() is never called here, so a proxy cannot reroute an
+        // approved destination to an unapproved one.
+        const bool bracketed = parts->host.find(':') != std::string::npos;
+        const std::string origin = parts->scheme + "://" +
+                                   (bracketed ? "[" + parts->host + "]" : parts->host) + ":" +
+                                   std::to_string(parts->port);
+        httplib::Client cli(origin);
+        applyOutboundDefaults(cli);
+        cli.set_hostname_addr_map({{parts->host, decision.pinnedAddress}});
+        const time_t sec = static_cast<time_t>((budget + 999) / 1000);
+        cli.set_connection_timeout(sec, 0);
+        cli.set_read_timeout(sec, 0);
+        cli.set_write_timeout(sec, 0);
+
+        httplib::Request req;
+        req.method = "GET";
+        if (options.contains("method") && options.at("method").is_string()) {
+            req.method = options.at("method").get<std::string>();
+            std::transform(req.method.begin(), req.method.end(), req.method.begin(),
+                           [](unsigned char c) { return std::toupper(c); });
+        }
+        // The fragment is a client-side notion and has no business on the wire.
+        req.path = parts->path.substr(0, parts->path.find('#'));
+        if (req.path.empty()) req.path = "/";
+        if (options.contains("headers") && options.at("headers").is_object())
+            for (auto it = options.at("headers").begin(); it != options.at("headers").end(); ++it)
+                if (it.value().is_string()) req.headers.emplace(it.key(), it.value().get<std::string>());
+        if (options.contains("body") && options.at("body").is_string()) {
+            req.body = options.at("body").get<std::string>();
+            if (req.headers.find("Content-Type") == req.headers.end())
+                req.headers.emplace("Content-Type", "application/json");
+        }
+
+        auto result = cli.send(req);
+        if (!result)
+            throw ApiError(ErrCode::Unavailable, "fetch_failed",
+                           "request to '" + parts->host + "' failed: " + httplib::to_string(result.error()));
+
+        nlohmann::json headers = nlohmann::json::object();
+        for (const auto& [name, value] : result->headers) headers[name] = value;
+        return nlohmann::json{{"status", result->status},
+                              {"ok", result->status >= 200 && result->status < 300},
+                              {"headers", headers},
+                              {"body", result->body}};
+    }
+
+    // --- the native bindings ------------------------------------------------
+    //
+    // Static members of Impl rather than free functions, because the seam
+    // header declares Impl a PRIVATE nested type of HostContext: only code
+    // inside that scope may name it.
+
+    /// The Impl behind a binding, carried as the function's own data rather
+    /// than in a global or the context opaque - the core already uses the
+    /// context opaque for its RunState, and a global would make two concurrent
+    /// runs in one process share an identity.
+    static Impl* implFrom(JSContext* ctx, JSValueConst* data) {
+        uint64_t bits = 0;
+        if (JS_ToBigUint64(ctx, &bits, data[0]) != 0) return nullptr;
+        return reinterpret_cast<Impl*>(static_cast<uintptr_t>(bits));
+    }
+
+    /// Every binding body funnels through here. A C++ exception escaping into
+    /// QuickJS's C frames is undefined behaviour, so NOTHING may propagate out:
+    /// an ApiError becomes a catchable JS Error and anything else becomes an
+    /// internal one.
+    template <typename Fn>
+    static JSValue guarded(JSContext* ctx, Fn&& body) {
+        try {
+            return body();
+        } catch (const ApiError& e) {
+            return throwApiError(ctx, e);
+        } catch (const std::exception& e) {
+            return throwApiError(ctx, ApiError(ErrCode::Internal, "internal", e.what()));
+        } catch (...) {
+            return throwApiError(ctx,
+                                 ApiError(ErrCode::Internal, "internal", "unknown host failure"));
+        }
+    }
+
+    static JSValue hostDb(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
+                          JSValueConst* data) {
+        return guarded(ctx, [&]() -> JSValue {
+            Impl* impl = implFrom(ctx, data);
+            if (!impl || argc < 3)
+                throw ApiError(ErrCode::Internal, "internal",
+                               "__hostDb called with a bad argument list");
+            const std::string collection = toText(ctx, argv[0]);
+            const std::string op = toText(ctx, argv[1]);
+            return toJs(ctx, impl->dbCall(collection, op, fromJs(ctx, argv[2])));
+        });
+    }
+
+    static JSValue hostFetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
+                             JSValueConst* data) {
+        return guarded(ctx, [&]() -> JSValue {
+            Impl* impl = implFrom(ctx, data);
+            if (!impl || argc < 1)
+                throw ApiError(ErrCode::Internal, "internal",
+                               "__hostFetch called with a bad argument list");
+            const std::string url = toText(ctx, argv[0]);
+            nlohmann::json options = argc > 1 ? fromJs(ctx, argv[1]) : nlohmann::json::object();
+            if (!options.is_object()) options = nlohmann::json::object();
+            return toJs(ctx, impl->fetch(url, options));
+        });
+    }
+
+    static JSValue hostLog(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
+                           JSValueConst* data) {
+        return guarded(ctx, [&]() -> JSValue {
+            Impl* impl = implFrom(ctx, data);
+            if (impl && argc >= 1) impl->addLog(toText(ctx, argv[0]));
+            return JS_UNDEFINED;
+        });
+    }
+};
+
+namespace {
+
+/// A trigger field, or an empty object when the trigger does not carry it. A
+/// cron or event run has no HTTP shape at all, and `ctx.query.q` must then read
+/// as undefined rather than throwing on undefined.query.
+nlohmann::json triggerObject(const nlohmann::json& trigger, const char* field) {
+    if (trigger.is_object() && trigger.contains(field) && trigger.at(field).is_object())
+        return trigger.at(field);
+    return nlohmann::json::object();
+}
+
+std::string triggerString(const nlohmann::json& trigger, const char* field) {
+    if (trigger.is_object() && trigger.contains(field) && trigger.at(field).is_string())
+        return trigger.at(field).get<std::string>();
+    return std::string();
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+
+HostContext::HostContext(DbGateway& db, HostContextConfig config)
+    : impl_(std::make_unique<Impl>(db, std::move(config))) {}
+
+HostContext::~HostContext() = default;
+
+const std::vector<std::string>& HostContext::logLines() const { return impl_->log; }
+const std::vector<std::string>& HostContext::blockedEgress() const { return impl_->blocked; }
+
+std::string_view hostPreludeSource() { return generated::kHostPreludeJs; }
+
+bool HostContext::install(const JsBindingTarget& target, std::string& error) {
+    auto* ctx = static_cast<JSContext*>(target.js_context);
+    auto* ctxObject = static_cast<JSValue*>(target.ctx_object);
+    if (ctx == nullptr || ctxObject == nullptr) {
+        error = "host bindings need both a context and a ctx object";
+        return false;
+    }
+
+    // The data fields first: plain values, shaped in C++ where the shaping is
+    // testable, leaving the prelude with nothing to do but the builder.
+    const nlohmann::json& trigger = impl_->config.trigger;
+    JS_SetPropertyStr(ctx, *ctxObject, "method",
+                      JS_NewString(ctx, triggerString(trigger, "method").c_str()));
+    JS_SetPropertyStr(ctx, *ctxObject, "path",
+                      JS_NewString(ctx, triggerString(trigger, "path").c_str()));
+    JS_SetPropertyStr(ctx, *ctxObject, "params", toJs(ctx, triggerObject(trigger, "params")));
+    JS_SetPropertyStr(ctx, *ctxObject, "query", toJs(ctx, triggerObject(trigger, "query")));
+    JS_SetPropertyStr(ctx, *ctxObject, "headers", toJs(ctx, triggerObject(trigger, "headers")));
+    // The body is whatever arrived, including a JSON array or a bare string.
+    JS_SetPropertyStr(ctx, *ctxObject, "body",
+                      toJs(ctx, trigger.is_object() ? trigger.value("body", nlohmann::json())
+                                                    : nlohmann::json()));
+    JS_SetPropertyStr(ctx, *ctxObject, "env",
+                      toJs(ctx, impl_->config.env.is_object() ? impl_->config.env
+                                                              : nlohmann::json::object()));
+
+    // The bindings are passed INTO the prelude rather than set on globalThis,
+    // so user code cannot reach them and skip the builder's argument checks.
+    JSValue cookie = JS_NewBigUint64(ctx, static_cast<uint64_t>(reinterpret_cast<uintptr_t>(impl_.get())));
+    JSValueConst data[1] = {cookie};
+    JSValue db = JS_NewCFunctionData(ctx, Impl::hostDb, 3, 0, 1, data);
+    JSValue fetch = JS_NewCFunctionData(ctx, Impl::hostFetch, 2, 0, 1, data);
+    JSValue log = JS_NewCFunctionData(ctx, Impl::hostLog, 1, 0, 1, data);
+    JS_FreeValue(ctx, cookie);
+
+    const std::string_view prelude = hostPreludeSource();
+    JSValue factory = JS_Eval(ctx, prelude.data(), prelude.size(), "<host-prelude>",
+                              JS_EVAL_TYPE_GLOBAL);
+    bool ok = true;
+    if (JS_IsException(factory)) {
+        // A broken prelude is our bug, never the tenant's, so it fails the run
+        // before any user code executes rather than surfacing as a missing
+        // ctx.collections halfway through.
+        JSValue exc = JS_GetException(ctx);
+        error = "the host prelude failed to evaluate: " + toText(ctx, exc);
+        JS_FreeValue(ctx, exc);
+        ok = false;
+    } else {
+        JSValueConst args[4] = {*ctxObject, db, fetch, log};
+        JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 4, args);
+        if (JS_IsException(applied)) {
+            JSValue exc = JS_GetException(ctx);
+            error = "the host prelude failed to install: " + toText(ctx, exc);
+            JS_FreeValue(ctx, exc);
+            ok = false;
+        }
+        JS_FreeValue(ctx, applied);
+    }
+
+    JS_FreeValue(ctx, factory);
+    JS_FreeValue(ctx, db);
+    JS_FreeValue(ctx, fetch);
+    JS_FreeValue(ctx, log);
+    return ok;
+}
+
+} // namespace svapi::runner

+ 156 - 0
runner/src/host_prelude.js

@@ -0,0 +1,156 @@
+// The ergonomics half of the `ctx` surface.
+//
+// WHY this is JavaScript: the design specifies a fluent, chainable builder
+// (`.filter(...).limit(20).find()`). Building one in C++ would mean a JSValue
+// class per stage with hand-rolled refcounting, for logic that is four lines
+// here. WHY it stays small: everything this file does not do is done in C++,
+// where it can be tested without an engine. So this file accumulates arguments
+// and validates their SHAPE; it decides nothing. Authorization, the filter
+// grammar, the egress guard and the deadline all live on the other side of
+// __hostDb / __hostFetch and cannot be influenced from here.
+//
+// The bindings arrive as an argument rather than on globalThis so that user
+// code cannot reach them directly and skip the builder's argument checks.
+//
+// Host calls are SYNCHRONOUS. The design relies on `await` of a non-promise
+// being a no-op, which is why nothing here returns a promise: a sync host call
+// cannot deadlock on a microtask queue the run may never drain.
+(function (ctx, __hostDb, __hostFetch, __hostLog) {
+  'use strict';
+
+  function need(cond, message) {
+    if (!cond) throw new TypeError(message);
+  }
+
+  // A chained call returns a NEW ref: `ctx.collections('c')` is a value a
+  // script may hold and branch on, and a mutating .filter() would make the
+  // second use silently carry the first one's filters.
+  function ref(name, query) {
+    const self = {
+      // Test hook: the accumulated state, so the immutability rule is
+      // assertable without a database behind the terminal calls.
+      _query: function () {
+        return { filters: query.filters.slice(), limit: query.limit,
+                 offset: query.offset, sort: query.sort, desc: query.desc };
+      },
+
+      filter: function (spec) {
+        need(typeof spec === 'string', ".filter() takes a 'field:op:value' string");
+        return ref(name, { filters: query.filters.concat([spec]), limit: query.limit,
+                           offset: query.offset, sort: query.sort, desc: query.desc });
+      },
+      limit: function (n) {
+        need(Number.isInteger(n) && n >= 0, '.limit() takes a non-negative integer');
+        return ref(name, { filters: query.filters, limit: n, offset: query.offset,
+                           sort: query.sort, desc: query.desc });
+      },
+      offset: function (n) {
+        need(Number.isInteger(n) && n >= 0, '.offset() takes a non-negative integer');
+        return ref(name, { filters: query.filters, limit: query.limit, offset: n,
+                           sort: query.sort, desc: query.desc });
+      },
+      // "-field" for descending, mirroring the one place the HTTP API spells
+      // this with a separate ?desc= parameter. One argument is the only shape
+      // that chains.
+      sort: function (field) {
+        need(typeof field === 'string' && field.length > 0, '.sort() takes a field name');
+        const desc = field.charAt(0) === '-';
+        return ref(name, { filters: query.filters, limit: query.limit, offset: query.offset,
+                           sort: desc ? field.slice(1) : field, desc: desc });
+      },
+
+      // --- documents ---
+      find: function () {
+        return __hostDb(name, 'find', self._query());
+      },
+      get: function (id) {
+        need(typeof id === 'string' && id.length > 0, '.get() takes a document id');
+        return __hostDb(name, 'get', { id: id });
+      },
+      insert: function (doc) {
+        need(doc !== null && typeof doc === 'object', '.insert() takes a document object');
+        return __hostDb(name, 'insert', { doc: doc });
+      },
+      update: function (id, doc) {
+        need(typeof id === 'string' && id.length > 0, '.update() takes a document id');
+        need(doc !== null && typeof doc === 'object', '.update() takes a document object');
+        return __hostDb(name, 'update', { id: id, doc: doc });
+      },
+      patch: function (id, fields) {
+        need(typeof id === 'string' && id.length > 0, '.patch() takes a document id');
+        need(fields !== null && typeof fields === 'object', '.patch() takes a fields object');
+        return __hostDb(name, 'patch', { id: id, doc: fields });
+      },
+      // Legal as a method name since ES5, and it is the name the design shows.
+      delete: function (id) {
+        need(typeof id === 'string' && id.length > 0, '.delete() takes a document id');
+        return __hostDb(name, 'delete', { id: id });
+      },
+
+      // --- vectors ---
+      // The filters the chain accumulated are merged in, so
+      // `.filter(...).search({...})` behaves the way the chain reads. An
+      // explicit `filters` array in the argument is appended, not replaced:
+      // dropping either set silently would widen the result.
+      search: function (opts) {
+        need(opts !== null && typeof opts === 'object', '.search() takes an options object');
+        const extra = opts.filters === undefined || opts.filters === null ? [] : opts.filters;
+        need(Array.isArray(extra), '.search() filters must be an array of strings');
+        return __hostDb(name, 'search', {
+          query_text: opts.query_text,
+          query_vector: opts.query_vector,
+          top_k: opts.top_k,
+          min_score: opts.min_score,
+          filters: query.filters.concat(extra)
+        });
+      },
+      store: function (opts) {
+        need(opts !== null && typeof opts === 'object', '.store() takes an options object');
+        return __hostDb(name, 'store', {
+          text: opts.text,
+          vector: opts.vector,
+          metadata: opts.metadata,
+          id: opts.id
+        });
+      }
+    };
+    return self;
+  }
+
+  ctx.collections = function (name) {
+    need(typeof name === 'string' && name.length > 0,
+         'ctx.collections() takes a collection name');
+    return ref(name, { filters: [], limit: 0, offset: 0, sort: '', desc: false });
+  };
+
+  ctx.fetch = function (url, options) {
+    need(typeof url === 'string' && url.length > 0, 'ctx.fetch() takes a URL string');
+    const o = options === undefined || options === null ? {} : options;
+    need(typeof o === 'object', 'ctx.fetch() options must be an object');
+    const res = __hostFetch(url, {
+      method: o.method,
+      headers: o.headers,
+      body: o.body,
+      timeoutMs: o.timeoutMs
+    });
+    // `json()` is a method rather than an eagerly parsed field so a non-JSON
+    // body is the caller's problem at the point they ask for it, not a failed
+    // fetch of a response that arrived perfectly well.
+    res.json = function () { return JSON.parse(res.body); };
+    return res;
+  };
+
+  ctx.log = function () {
+    const parts = [];
+    for (let i = 0; i < arguments.length; i++) {
+      const v = arguments[i];
+      // Objects as JSON: "[object Object]" in a log is worse than useless when
+      // debugging a function. Matches the core's console formatting.
+      if (v !== null && typeof v === 'object') {
+        try { parts.push(JSON.stringify(v)); continue; } catch (e) { /* cyclic */ }
+      }
+      parts.push(String(v));
+    }
+    __hostLog(parts.join(' '));
+  };
+})

+ 310 - 0
runner/src/main.cpp

@@ -0,0 +1,310 @@
+// The function runner binary.
+//
+// It is the second process of the design in
+// docs/superpowers/specs/2026-10-06-function-runtime-design.md: vectorapi
+// routes and schedules, the runner executes. Everything interesting about the
+// protocol lives in run_service.{hpp,cpp}; this file is wiring - config,
+// logging, the database connection, the two seams RunService takes, and a
+// cpp-httplib server that does nothing but shuttle JSON between them.
+//
+// It deliberately holds the only code here that links vectorapi_core and the
+// database client, which is what keeps run_service testable on a host where
+// that client cannot compile at all (CLAUDE.md).
+#include "db_gateway.hpp"
+#include "function_record.hpp"
+#include "function_registry.hpp"
+#include "run_service.hpp"
+#include "runner/host_context.hpp"
+
+#include <svapi/version.hpp>
+
+#include <httplib.h>
+#include <nlohmann/json.hpp>
+#include <spdlog/spdlog.h>
+#ifdef HAVE_SYSTEMD
+#include <systemd/sd-daemon.h>
+#else
+#define sd_notify(u, s) do {} while (0)
+#endif
+
+#include <atomic>
+#include <chrono>
+#include <csignal>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace {
+
+std::atomic<bool> g_running{true};
+void onSignal(int) { g_running = false; }
+
+/// The runner's own bootstrap config. Separate from svapi::Config because the
+/// two processes need different things: no web UI here, but the per-run
+/// ceilings and the pool size, which an operator sizes against the host.
+///
+/// Same posture as the server's config though: minimal, and only what has to be
+/// known BEFORE the database is reachable. Anything that can hot-reload belongs
+/// in the database, not here.
+struct RunnerConfig {
+    std::string logLevel = "info";
+    /// Loopback by default. The runner has no authentication of its own - the
+    /// protocol vectorapi speaks to it carries no credential - so it must not
+    /// be reachable from anywhere an attacker is. Widening this bind address is
+    /// a decision about network placement, and it should be a deliberate one.
+    std::string httpBind = "127.0.0.1";
+    uint16_t httpPort = 8090;
+    std::string dbAddress = "localhost:9004";
+
+    size_t poolSize = 4;
+    size_t memoryLimitBytes = 128u * 1024 * 1024;
+    int64_t maxWallTimeMs = 2000;
+    /// Applied when a descriptor declares no timeoutMs. 0 = use the ceiling.
+    int64_t defaultWallTimeMs = 0;
+    size_t maxStackBytes = 512u * 1024;
+    size_t bytecodeCacheEntries = 64;
+    /// How long a single /run or /validate request may occupy a server thread.
+    /// Above the wall-time ceiling on purpose: a run that is about to be killed
+    /// should report its own timeout rather than have the socket cut first.
+    int readTimeoutSec = 30;
+
+    static RunnerConfig fromJson(const nlohmann::json& j) {
+        RunnerConfig c;
+        c.logLevel = j.value("log_level", c.logLevel);
+        if (j.contains("http") && j["http"].is_object()) {
+            const auto& h = j["http"];
+            c.httpBind = h.value("bind_address", c.httpBind);
+            c.httpPort = h.value("port", c.httpPort);
+            c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
+        }
+        if (j.contains("database") && j["database"].is_object())
+            c.dbAddress = j["database"].value("address", c.dbAddress);
+        if (j.contains("runtime") && j["runtime"].is_object()) {
+            const auto& r = j["runtime"];
+            c.poolSize = r.value("pool_size", c.poolSize);
+            c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
+            c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs);
+            c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
+            c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
+            c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
+        }
+        return c;
+    }
+
+    static RunnerConfig load(const std::string& path) {
+        std::ifstream f(path);
+        if (!f) throw std::runtime_error("cannot open config file: " + path);
+        nlohmann::json j;
+        f >> j;
+        return fromJson(j);
+    }
+};
+
+/// RunService's registry seam, over the real FunctionRegistry.
+///
+/// The whole adapter is this one translation, which is the point: the protocol
+/// layer never learns that a database exists, and this class holds no logic a
+/// test would want to reach.
+class RegistryFunctionSource : public svapi::runner::FunctionSource {
+public:
+    explicit RegistryFunctionSource(svapi::FunctionRegistry& registry) : registry_(registry) {}
+
+    svapi::runner::FunctionView lookup(const std::string& project,
+                                       const std::string& functionId) override {
+        svapi::runner::FunctionView view;
+        std::optional<svapi::FunctionRecord> row;
+        try {
+            row = registry_.get(project, functionId);
+        } catch (const std::exception& e) {
+            // A database failure is not a missing function, but the /run
+            // contract has no third answer. Logged loudly so the two are
+            // distinguishable in the journal even though the caller sees a 404.
+            spdlog::error("registry read failed for {}:{} - {}", project, functionId, e.what());
+            return view;
+        }
+        if (!row) return view;
+        view.found = true;
+        view.source = row->source;
+        view.contentHash = row->contentHash;
+        view.descriptor = row->descriptor;
+        view.policy = row->policy;
+        view.enabled = row->enabled;
+        view.valid = row->valid;
+        view.lastError = row->lastError;
+        return view;
+    }
+
+private:
+    svapi::FunctionRegistry& registry_;
+};
+
+/// RunService's ctx seam, over the real HostContext.
+class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
+public:
+    explicit GatewayHostBindings(svapi::DbGateway& db) : db_(db) {}
+
+    bool create(const Request& request, svapi::runner::HostBindingsLease& out,
+                std::string& error) override {
+        svapi::runner::HostContextConfig cfg;
+        cfg.project = request.project;
+        cfg.functionId = request.functionId;
+        cfg.policy = request.policy;
+        cfg.trigger = request.trigger;
+        cfg.deadlineMs = request.deadlineMs;
+        // cfg.env stays empty: ctx.env is secrets, and nothing has yet decided
+        // where a project's secrets are stored or who may read them. An empty
+        // env is the only answer that cannot leak one.
+        try {
+            auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
+            svapi::runner::HostContext* raw = host.get();
+            out.bindings = std::move(host);
+            out.collectConsole = [raw] {
+                std::vector<std::string> lines = raw->logLines();
+                // Refused egress is reported as console output rather than
+                // swallowed: a blocked fetch otherwise reaches the author
+                // looking like an ordinary network error he will debug forever.
+                for (const auto& blocked : raw->blockedEgress())
+                    lines.push_back("egress blocked: " + blocked);
+                return lines;
+            };
+            return true;
+        } catch (const std::exception& e) {
+            error = std::string("host context unavailable: ") + e.what();
+            return false;
+        }
+    }
+
+private:
+    svapi::DbGateway& db_;
+};
+
+/// Parse a request body, or answer 400 with the same error envelope the rest of
+/// the protocol uses.
+bool readJsonBody(const httplib::Request& req, httplib::Response& res, nlohmann::json& out) {
+    try {
+        out = nlohmann::json::parse(req.body.empty() ? "{}" : req.body);
+    } catch (const std::exception& e) {
+        res.status = 400;
+        res.set_content(nlohmann::json{{"ok", false},
+                                       {"error", std::string("invalid JSON body: ") + e.what()}}
+                            .dump(),
+                        "application/json");
+        return false;
+    }
+    return true;
+}
+
+void reply(httplib::Response& res, const svapi::runner::ProtocolResponse& out) {
+    res.status = out.httpStatus;
+    res.set_content(out.body.dump(), "application/json");
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+    std::string configPath = "/etc/smartbotic-vectorapi/runner.json";
+    for (int i = 1; i < argc; ++i) {
+        if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i];
+        else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) {
+            std::cout << "smartbotic-vectorapi-runner " << svapi::VERSION << " ("
+                      << svapi::GIT_COMMIT << ")\n";
+            return 0;
+        }
+    }
+
+    RunnerConfig cfg;
+    try { cfg = RunnerConfig::load(configPath); }
+    catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; }
+    spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
+
+    std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
+
+    svapi::DbGateway db(cfg.dbAddress);
+    spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
+    for (int i = 0; i < 30 && !db.connect(); ++i) std::this_thread::sleep_for(std::chrono::seconds(1));
+    if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
+
+    svapi::FunctionRegistry registry(db);
+    // Re-open every project's function collection. The database only surfaces a
+    // collection through find()/list() once it has been opened in the current
+    // process, so without this a restart leaves every function invisible even
+    // though the rows survive - the same trap CollectionRegistry::bootstrap and
+    // KeyStore::bootstrap exist for.
+    {
+        auto projects = db.listProjects();
+        registry.bootstrap(projects);
+        spdlog::info("opened the function registry for {} project(s)", projects.size());
+    }
+
+    svapi::runner::RunServiceOptions options;
+    options.poolSize = cfg.poolSize;
+    options.limits.memory_limit_bytes = cfg.memoryLimitBytes;
+    options.limits.wall_time_ms = cfg.maxWallTimeMs;
+    options.limits.max_stack_bytes = cfg.maxStackBytes;
+    options.defaultTimeoutMs = cfg.defaultWallTimeMs;
+    options.bytecodeCacheEntries = cfg.bytecodeCacheEntries;
+    options.version = svapi::VERSION;
+
+    RegistryFunctionSource source(registry);
+    GatewayHostBindings host(db);
+    svapi::runner::RunService service(source, options, &host);
+
+    httplib::Server server;
+    server.set_read_timeout(cfg.readTimeoutSec, 0);
+    server.set_write_timeout(cfg.readTimeoutSec, 0);
+    // The pool already bounds concurrency; matching the thread count to it
+    // keeps requests waiting in the accept queue instead of piling up threads
+    // that all block on acquire().
+    server.new_task_queue = [&cfg] {
+        return new httplib::ThreadPool(static_cast<size_t>(cfg.poolSize) + 2);
+    };
+
+    server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
+        nlohmann::json body;
+        if (!readJsonBody(req, res, body)) return;
+        reply(res, service.run(body));
+    });
+
+    server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) {
+        nlohmann::json body;
+        if (!readJsonBody(req, res, body)) return;
+        reply(res, service.validate(body));
+    });
+
+    server.Get("/health", [&service](const httplib::Request&, httplib::Response& res) {
+        reply(res, service.health());
+    });
+
+    // An unexpected throw must not take the process down: one bad function
+    // would otherwise stop every other tenant's.
+    server.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
+                                    std::exception_ptr ep) {
+        std::string what = "unknown error";
+        try { std::rethrow_exception(ep); }
+        catch (const std::exception& e) { what = e.what(); }
+        catch (...) {}
+        spdlog::error("unhandled exception on {} {}: {}", req.method, req.path, what);
+        res.status = 500;
+        res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json");
+    });
+
+    std::thread http([&] {
+        spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms)", cfg.httpBind,
+                     cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs);
+        if (!server.listen(cfg.httpBind, cfg.httpPort)) {
+            spdlog::error("bind failed");
+            g_running = false;
+        }
+    });
+    sd_notify(0, "READY=1");
+    while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
+    sd_notify(0, "STOPPING=1");
+    server.stop();
+    if (http.joinable()) http.join();
+    return 0;
+}

+ 325 - 0
runner/src/run_service.cpp

@@ -0,0 +1,325 @@
+#include "run_service.hpp"
+
+#include "functions/descriptor.hpp"
+
+#include <utility>
+
+namespace svapi::runner {
+namespace {
+
+/// A refusal that never ran any user code. `ok` is false and `status` carries
+/// the shape the caller should relay, so vectorapi can forward the body as-is.
+ProtocolResponse refusal(int functionStatus, const std::string& message) {
+    ProtocolResponse out;
+    out.body = {{"ok", false},
+                {"status", functionStatus},
+                {"headers", nlohmann::json::object()},
+                {"body", nullptr},
+                {"console", nlohmann::json::array()},
+                {"duration_ms", 0},
+                {"error", message},
+                {"timed_out", false},
+                {"out_of_memory", false}};
+    return out;
+}
+
+/// A payload the runner could not understand. This is the one failure that is
+/// the CALLER's fault rather than the function's, so it is the only one that
+/// leaves the /run status non-200.
+ProtocolResponse badRequest(const std::string& message) {
+    ProtocolResponse out;
+    out.httpStatus = 400;
+    out.body = {{"ok", false}, {"error", message}};
+    return out;
+}
+
+std::string requiredString(const nlohmann::json& j, const char* key, std::string& error) {
+    if (!j.contains(key) || !j.at(key).is_string() || j.at(key).get<std::string>().empty()) {
+        error = std::string("'") + key + "' is required and must be a non-empty string";
+        return {};
+    }
+    return j.at(key).get<std::string>();
+}
+
+const char* const kEnvelopeKeys[] = {"status", "headers", "body"};
+
+bool isEnvelopeKey(const std::string& key) {
+    for (const char* k : kEnvelopeKeys)
+        if (key == k) return true;
+    return false;
+}
+
+ShapedResponse shapeFailure(const std::string& reason) {
+    ShapedResponse out;
+    out.ok = false;
+    out.status = 500;
+    out.error = "invalid_return: " + reason;
+    return out;
+}
+
+} // namespace
+
+ShapedResponse shapeReturnValue(const nlohmann::json& value) {
+    ShapedResponse out;
+    out.ok = true;
+    out.status = 200;
+    out.body = value;
+
+    if (!value.is_object()) return out;  // a non-object can only be a body
+
+    size_t envelopeKeys = 0;
+    std::vector<std::string> strangers;
+    for (auto it = value.begin(); it != value.end(); ++it) {
+        if (isEnvelopeKey(it.key())) ++envelopeKeys;
+        else strangers.push_back(it.key());
+    }
+    if (envelopeKeys == 0) return out;  // an ordinary data object is the body
+    if (!strangers.empty()) {
+        // Neither reading is defensible, so neither is guessed at. See the rule
+        // on shapeReturnValue in the header.
+        std::string list;
+        for (const auto& s : strangers) list += (list.empty() ? "" : ", ") + s;
+        return shapeFailure("a response envelope may only contain status, headers and body; "
+                            "found also: " + list);
+    }
+
+    out.body = value.contains("body") ? value.at("body") : nlohmann::json(nullptr);
+
+    if (value.contains("status")) {
+        const nlohmann::json& s = value.at("status");
+        if (!s.is_number_integer()) return shapeFailure("'status' must be an integer");
+        const long long code = s.get<long long>();
+        if (code < 100 || code > 599) return shapeFailure("'status' must be between 100 and 599");
+        out.status = static_cast<int>(code);
+    }
+
+    if (value.contains("headers")) {
+        const nlohmann::json& h = value.at("headers");
+        if (!h.is_object()) return shapeFailure("'headers' must be an object");
+        for (auto it = h.begin(); it != h.end(); ++it) {
+            const nlohmann::json& v = it.value();
+            if (v.is_string()) out.headers[it.key()] = v.get<std::string>();
+            else if (v.is_number() || v.is_boolean()) out.headers[it.key()] = v.dump();
+            else
+                return shapeFailure("header '" + it.key() +
+                                    "' must be a string, number or boolean");
+        }
+    }
+    return out;
+}
+
+int failureStatus(const JsResult& result) {
+    if (result.timed_out) return 504;
+    return 500;  // out_of_memory included, for the reason given in the header
+}
+
+RunService::RunService(FunctionSource& source, RunServiceOptions options,
+                       HostBindingsFactory* host)
+    : source_(source), options_(std::move(options)), host_(host),
+      pool_(options_.poolSize == 0 ? 1 : options_.poolSize, options_.limits) {}
+
+RunService::~RunService() = default;
+
+std::optional<JsBytecode> RunService::bytecodeFor(const std::string& contentHash,
+                                                  const std::string& source,
+                                                  const std::string& filename,
+                                                  JsRuntime& runtime, std::string& error) {
+    {
+        std::lock_guard<std::mutex> lock(cache_mutex_);
+        auto it = cache_index_.find(contentHash);
+        if (it != cache_index_.end()) {
+            cache_lru_.splice(cache_lru_.begin(), cache_lru_, it->second);
+            return it->second->second;
+        }
+    }
+    // Compiled outside the lock: two threads racing on the same hash duplicate
+    // the work once, which is cheaper than serialising every cold compile.
+    auto compiled = runtime.compile(source, filename, error);
+    if (!compiled) return std::nullopt;
+    cachePut(contentHash, *compiled);
+    return compiled;
+}
+
+void RunService::cachePut(const std::string& contentHash, JsBytecode bytecode) {
+    std::lock_guard<std::mutex> lock(cache_mutex_);
+    auto it = cache_index_.find(contentHash);
+    if (it != cache_index_.end()) {
+        it->second->second = std::move(bytecode);
+        cache_lru_.splice(cache_lru_.begin(), cache_lru_, it->second);
+        return;
+    }
+    cache_lru_.emplace_front(contentHash, std::move(bytecode));
+    cache_index_[contentHash] = cache_lru_.begin();
+    const size_t cap = options_.bytecodeCacheEntries == 0 ? 1 : options_.bytecodeCacheEntries;
+    while (cache_lru_.size() > cap) {
+        cache_index_.erase(cache_lru_.back().first);
+        cache_lru_.pop_back();
+    }
+}
+
+ProtocolResponse RunService::run(const nlohmann::json& request) {
+    if (!request.is_object()) return badRequest("request body must be a JSON object");
+    std::string error;
+    const std::string project = requiredString(request, "project", error);
+    if (!error.empty()) return badRequest(error);
+    const std::string functionId = requiredString(request, "function_id", error);
+    if (!error.empty()) return badRequest(error);
+
+    nlohmann::json trigger = nlohmann::json::object();
+    if (request.contains("trigger") && request.at("trigger").is_object())
+        trigger = request.at("trigger");
+
+    // Read on EVERY run, cache hit or not: `enabled` and `valid` are registry
+    // state, and a cached module must never keep a function alive that an
+    // operator has just turned off.
+    const FunctionView fn = source_.lookup(project, functionId);
+    if (!fn.found)
+        return refusal(404, "function '" + functionId + "' not found in project '" + project + "'");
+    if (!fn.enabled) return refusal(409, "function '" + functionId + "' is disabled");
+    if (!fn.valid)
+        return refusal(422, "function '" + functionId + "' is marked invalid: " +
+                                (fn.lastError.empty() ? "no stored error" : fn.lastError));
+    if (fn.source.empty()) return refusal(422, "function '" + functionId + "' has no source");
+
+    // A declared timeout only ever narrows; JsRuntime::run clamps it to the
+    // configured ceiling, so a descriptor cannot buy itself more wall time.
+    int64_t wallMs = options_.defaultTimeoutMs;
+    if (fn.descriptor.is_object() && fn.descriptor.contains("timeoutMs") &&
+        fn.descriptor.at("timeoutMs").is_number_integer())
+        wallMs = fn.descriptor.at("timeoutMs").get<int64_t>();
+    const int64_t effectiveMs =
+        (wallMs > 0 && wallMs < options_.limits.wall_time_ms) ? wallMs : options_.limits.wall_time_ms;
+
+    auto lease = pool_.acquire();
+    if (!lease.valid()) return refusal(503, "no runtime available");
+
+    std::string compileError;
+    auto bytecode = bytecodeFor(fn.contentHash, fn.source, functionId + ".js", *lease,
+                                compileError);
+    if (!bytecode) {
+        // The registry said `valid`, so the stored source should compile. When
+        // it does not, the function is what is broken, not the call - 422, the
+        // same answer a stored-invalid row gets.
+        return refusal(422, compileError);
+    }
+
+    HostBindingsLease host;
+    if (host_) {
+        HostBindingsFactory::Request hostRequest;
+        hostRequest.project = project;
+        hostRequest.functionId = functionId;
+        hostRequest.policy = fn.policy;
+        hostRequest.trigger = trigger;
+        hostRequest.deadlineMs = effectiveMs;
+        std::string hostError;
+        if (!host_->create(hostRequest, host, hostError))
+            return refusal(500, hostError.empty() ? "host bindings unavailable" : hostError);
+    }
+
+    // The base ctx is the trigger and nothing else. Identity, secrets and the
+    // callable surface (ctx.collections, ctx.fetch, ctx.log, ctx.env) are the
+    // host bindings' business, which keeps this file out of the way of the
+    // policy decisions made there.
+    nlohmann::json ctxArg = trigger.is_object() ? trigger : nlohmann::json::object();
+
+    JsResult result = lease->run(*bytecode, ctxArg, effectiveMs, host.bindings.get());
+
+    nlohmann::json console = nlohmann::json::array();
+    for (const auto& line : result.console_output) console.push_back(line);
+    if (host.collectConsole) {
+        // Appended rather than interleaved: console.log goes through the engine
+        // and ctx.log through the host, and nothing records a common ordering.
+        for (const auto& line : host.collectConsole()) console.push_back(line);
+    }
+
+    ProtocolResponse out;
+    out.body = {{"console", console},
+                {"duration_ms", result.duration_ms},
+                {"timed_out", result.timed_out},
+                {"out_of_memory", result.out_of_memory}};
+
+    if (!result.ok) {
+        out.body["ok"] = false;
+        out.body["status"] = failureStatus(result);
+        out.body["headers"] = nlohmann::json::object();
+        out.body["body"] = nullptr;
+        out.body["error"] = result.error.empty() ? "function failed without a message"
+                                                 : result.error;
+        return out;
+    }
+
+    const ShapedResponse shaped = shapeReturnValue(result.value);
+    out.body["ok"] = shaped.ok;
+    out.body["status"] = shaped.status;
+    out.body["headers"] = shaped.headers;
+    out.body["body"] = shaped.body;
+    if (!shaped.ok) {
+        out.body["body"] = nullptr;
+        out.body["error"] = shaped.error;
+    }
+    return out;
+}
+
+ProtocolResponse RunService::validate(const nlohmann::json& request) {
+    if (!request.is_object()) return badRequest("request body must be a JSON object");
+    std::string error;
+    const std::string source = requiredString(request, "source", error);
+    if (!error.empty()) return badRequest(error);
+    const std::string path =
+        request.contains("path") && request.at("path").is_string()
+            ? request.at("path").get<std::string>()
+            : "function.js";
+
+    auto lease = pool_.acquire();
+    if (!lease.valid()) {
+        ProtocolResponse out;
+        out.httpStatus = 503;
+        out.body = {{"ok", false}, {"error", "no runtime available"}};
+        return out;
+    }
+
+    ProtocolResponse out;
+    std::string compileError;
+    // Compiled through the pool but deliberately NOT through bytecodeFor: this
+    // source is unstored and caller-supplied, and a cache it could write into
+    // would let one /validate call decide what a stored function executes.
+    auto bytecode = lease->compile(source, path, compileError);
+    if (!bytecode) {
+        out.body = {{"ok", false}, {"error", compileError}};
+        return out;
+    }
+
+    std::string readError;
+    // readExport, not run: validation evaluates the module to reach its `on`
+    // binding and must never call the handler.
+    auto on = lease->readExport(*bytecode, "on", readError);
+    if (!on) {
+        out.body = {{"ok", false}, {"error", readError}};
+        return out;
+    }
+    if (on->is_null()) {
+        out.body = {{"ok", false},
+                    {"error", "the module exports no 'on' descriptor (expected "
+                              "`export const on = { id: '...', type: 'http', ... }`)"}};
+        return out;
+    }
+
+    const functions::ParseResult parsed = functions::parseDescriptor(*on);
+    if (!parsed.ok) {
+        out.body = {{"ok", false}, {"error", parsed.error}};
+        return out;
+    }
+    out.body = {{"ok", true}, {"descriptor", parsed.descriptor.toJson()}};
+    return out;
+}
+
+ProtocolResponse RunService::health() {
+    ProtocolResponse out;
+    out.body = {{"status", "ok"},
+                {"version", options_.version},
+                {"pool",
+                 {{"size", pool_.size()}, {"idle", pool_.idle()}, {"retired", pool_.retired()}}}};
+    return out;
+}
+
+} // namespace svapi::runner

+ 201 - 0
runner/src/run_service.hpp

@@ -0,0 +1,201 @@
+#pragma once
+#include "apikey.hpp"
+#include "runner/js_runtime.hpp"
+#include <nlohmann/json.hpp>
+
+#include <cstdint>
+#include <functional>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+/// The runner's protocol layer: `/run`, `/validate`, `/health` as pure
+/// JSON-in/JSON-out, with no transport and no database in sight.
+///
+/// The contract is docs/superpowers/specs/2026-10-06-function-runtime-design.md
+/// ("Runner protocol"). Two deliberate shapes:
+///
+///   1. NO httplib HERE. main.cpp owns the cpp-httplib server and does nothing
+///      but parse a body, call one of these methods and copy the result onto
+///      the response. Everything that can be wrong about a request - a bad
+///      payload, a missing function, a disabled one, a return value that is not
+///      a response - is therefore decided in code a unit test can reach.
+///   2. NO DATABASE HERE. The registry and the `ctx` host bindings arrive
+///      through FunctionSource and HostBindingsFactory. That is what lets this
+///      file build and its tests run on the dev host, where
+///      smartbotic-db-client cannot compile at all (CLAUDE.md). The production
+///      implementations of both seams live in main.cpp, which links everything.
+namespace svapi::runner {
+
+/// The registry row, reduced to what one run actually needs.
+///
+/// The /run payload is small on purpose (design doc): vectorapi sends an
+/// identity, and the runner reads the code, the hash and the policy itself.
+struct FunctionView {
+    bool found = false;
+    std::string source;
+    /// Cache key for compiled bytecode. Must change whenever a source byte does,
+    /// which is why it comes from the registry rather than being recomputed.
+    std::string contentHash;
+    /// The stored `on` block, as functions::FunctionDescriptor::toJson().
+    nlohmann::json descriptor = nlohmann::json::object();
+    KeyScope policy;
+    bool enabled = true;
+    bool valid = true;
+    /// Why `valid` is false, surfaced in the refusal so the caller does not have
+    /// to re-read the registry to find out.
+    std::string lastError;
+};
+
+/// Where functions come from. Wrapped around FunctionRegistry in production;
+/// implemented in-memory by the tests.
+class FunctionSource {
+public:
+    virtual ~FunctionSource() = default;
+    virtual FunctionView lookup(const std::string& project, const std::string& functionId) = 0;
+};
+
+/// One run's `ctx` host bindings, plus the way to read back what they recorded.
+struct HostBindingsLease {
+    /// May be null: a null binding set runs the function with the bare ctx the
+    /// engine builds, which is what the protocol tests use.
+    std::unique_ptr<JsHostBindings> bindings;
+    /// Called AFTER the run. ctx.log lines and refused-egress notes live on the
+    /// HostContext, not in JsResult::console_output, so without this a blocked
+    /// fetch would reach the caller looking like an ordinary network error.
+    std::function<std::vector<std::string>()> collectConsole;
+};
+
+/// Builds the host bindings for one run. Separate from FunctionSource because
+/// the two fail differently: a lookup failure is the function's problem, a
+/// binding failure is the runner's.
+class HostBindingsFactory {
+public:
+    virtual ~HostBindingsFactory() = default;
+
+    struct Request {
+        std::string project;
+        std::string functionId;
+        KeyScope policy;
+        nlohmann::json trigger = nlohmann::json::object();
+        /// The effective, already-clamped wall budget. Passed on so an outbound
+        /// call cannot outlive the run waiting for it.
+        int64_t deadlineMs = 0;
+    };
+
+    /// Returning false with `error` set fails the run before any user code runs.
+    virtual bool create(const Request& request, HostBindingsLease& out, std::string& error) = 0;
+};
+
+struct RunServiceOptions {
+    /// Ceilings, not defaults. A descriptor's `timeoutMs` narrows
+    /// `limits.wall_time_ms`; it can never raise it (JsRuntime::run clamps).
+    JsLimits limits;
+    size_t poolSize = 4;
+    /// Applied when the descriptor declares no `timeoutMs`. 0 means "use the
+    /// ceiling", which is what a single-tenant deployment wants.
+    int64_t defaultTimeoutMs = 0;
+    /// Compiled modules kept in memory. In-process only: QuickJS bytecode
+    /// carries no version stamp, so persisting it would need a build
+    /// fingerprint (design doc Addendum).
+    size_t bytecodeCacheEntries = 64;
+    /// Reported by /health so an operator can tell which binary answered.
+    std::string version;
+};
+
+/// What main.cpp copies onto the cpp-httplib response.
+struct ProtocolResponse {
+    /// The status of the /run CALL, which is not the status the function
+    /// produced. Only two things make this non-200: a payload the runner could
+    /// not understand (400) and the runner itself being unable to serve (503).
+    /// A function that is missing, disabled, invalid or throwing is a 200 whose
+    /// BODY says so - otherwise RunnerPool would retry every runner in turn for
+    /// a function that is equally broken on all of them.
+    int httpStatus = 200;
+    nlohmann::json body = nlohmann::json::object();
+};
+
+class RunService {
+public:
+    RunService(FunctionSource& source, RunServiceOptions options,
+               HostBindingsFactory* host = nullptr);
+    ~RunService();
+
+    RunService(const RunService&) = delete;
+    RunService& operator=(const RunService&) = delete;
+
+    /// POST /run. Never throws on user input: the caller is vectorapi relaying
+    /// to a client, so every outcome has to be a body it can forward.
+    ProtocolResponse run(const nlohmann::json& request);
+
+    /// POST /validate - compile the source and read its `on` block WITHOUT
+    /// calling the default export. The engine that validates is the engine that
+    /// executes, which is the whole reason validation lives here and not in
+    /// vectorapi.
+    ProtocolResponse validate(const nlohmann::json& request);
+
+    ProtocolResponse health();
+
+private:
+    /// Compiled module plus the hash it was compiled from. Looked up by hash, so
+    /// a code push invalidates by changing the key rather than by eviction.
+    std::optional<JsBytecode> bytecodeFor(const std::string& contentHash,
+                                          const std::string& source,
+                                          const std::string& filename, JsRuntime& runtime,
+                                          std::string& error);
+    void cachePut(const std::string& contentHash, JsBytecode bytecode);
+
+    FunctionSource& source_;
+    RunServiceOptions options_;
+    HostBindingsFactory* host_;
+    JsRuntimePool pool_;
+
+    std::mutex cache_mutex_;
+    /// Front is most recently used; the map points into the list so a hit is a
+    /// splice rather than a copy of the blob.
+    std::list<std::pair<std::string, JsBytecode>> cache_lru_;
+    std::unordered_map<std::string, std::list<std::pair<std::string, JsBytecode>>::iterator>
+        cache_index_;
+};
+
+/// Turn a default export's return value into {status, headers, body}.
+///
+/// THE RULE: an object whose keys are a non-empty subset of {status, headers,
+/// body} is a response envelope; anything else is the body of a 200. An object
+/// that MIXES envelope keys with other keys is rejected rather than guessed at -
+/// the same call the document write path already makes for `{"data":...}` plus
+/// siblings (CLAUDE.md: 422 `ambiguous_body`), and for the same reason: the
+/// permissive reading silently drops half of what the author wrote, which is a
+/// bug that takes a release to notice.
+///
+/// Exposed because it is the part of the protocol most likely to be argued
+/// about, and arguing about it should mean editing a test, not a server.
+struct ShapedResponse {
+    bool ok = false;
+    int status = 200;
+    /// Header values flattened to strings: a number or boolean is stringified,
+    /// anything structured is an error, because there is no honest way to put an
+    /// object in an HTTP header.
+    nlohmann::json headers = nlohmann::json::object();
+    nlohmann::json body;
+    std::string error;
+};
+ShapedResponse shapeReturnValue(const nlohmann::json& value);
+
+/// HTTP status a run failure reports in the response BODY.
+///
+/// `timed_out` is 504: the function is the upstream that did not answer in
+/// time, which is exactly what 504 means, and 408 is wrong because nothing was
+/// slow about the client. `out_of_memory` is 500 rather than 503: breaching a
+/// per-run memory ceiling is a defect in the function and will fail identically
+/// on the next attempt, so advertising it as "temporarily unavailable" would
+/// invite a retry loop. The two stay distinguishable as flags in the body
+/// whatever the status, because an operator needs to tell a slow function from a
+/// broken one.
+int failureStatus(const JsResult& result);
+
+} // namespace svapi::runner

+ 486 - 0
runner/tests/host_context_test.cpp

@@ -0,0 +1,486 @@
+// Tests for the `ctx` surface a function receives.
+//
+// These are the executable form of two rules from
+// docs/superpowers/specs/2026-10-06-function-runtime-design.md:
+//
+//   "ONE AUTHORIZATION IMPLEMENTATION" - every collection access is decided by
+//   requireCapabilityCore() on a Principal built from the function's policy, and
+//   a denial reaches the script as a catchable JS error naming the collection
+//   and the op, never as an empty result.
+//
+//   "SSRF guard ... fail closed" - ctx.fetch refuses before it connects, and the
+//   refusal is recorded so the author sees a refusal rather than guessing at a
+//   network error.
+//
+// Deliberately DATABASE-FREE. Every assertion here is about a decision taken
+// BEFORE the gateway is touched - policy, filter grammar, egress, trigger
+// plumbing, log bounds - so the gateway is pointed at a port nothing listens on
+// and never connected. An integration test that needs real documents belongs in
+// packaging/devstack, not here.
+#include <gtest/gtest.h>
+
+#include <functional>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "apikey.hpp"
+#include "db_gateway.hpp"
+#include "errors.hpp"
+#include "functions/net_guard.hpp"
+#include "principal.hpp"
+#include "runner/host_context.hpp"
+#include "server.hpp"
+#include "runner/js_runtime.hpp"
+
+using svapi::ApiError;
+using svapi::KeyOp;
+using svapi::KeyScope;
+using svapi::KeyScopeRule;
+using svapi::runner::HostContext;
+using svapi::runner::HostContextConfig;
+using svapi::runner::JsResult;
+using svapi::runner::JsRuntime;
+
+// The pure seams host_context.cpp exposes for exactly this file: the policy
+// decision and the request/response shaping, split out of the native bindings
+// so they can be tested without an engine, a resolver or a database. Declared
+// here rather than in the public header because they are an implementation
+// detail of the bindings, not part of the `ctx` contract.
+namespace svapi::runner::hostdetail {
+
+std::optional<KeyOp> keyOpForDbOp(const std::string& op);
+std::string deniedMessage(const std::string& collection, const std::string& op,
+                          const std::string& why);
+smartbotic::database::Client::QueryOptions queryOptionsFrom(const nlohmann::json& payload);
+int64_t outboundTimeoutMs(int64_t deadline_ms, int64_t elapsed_ms, int64_t requested_ms);
+
+struct EgressDecision {
+    bool allowed = false;
+    std::string pinnedAddress;
+    std::string reason;
+};
+using Resolver = std::function<std::vector<std::string>(const std::string&)>;
+EgressDecision decideEgress(const functions::HttpUrlParts& parts, const functions::SsrfPolicy& policy,
+                            const Resolver& resolve);
+
+} // namespace svapi::runner::hostdetail
+
+namespace detail = svapi::runner::hostdetail;
+
+namespace {
+
+KeyScope policyFor(const std::string& collection, std::set<KeyOp> ops) {
+    KeyScope s;
+    s.rules.push_back(KeyScopeRule{collection, std::move(ops), false});
+    return s;
+}
+
+struct Outcome {
+    JsResult result;
+    std::vector<std::string> log;
+    std::vector<std::string> blocked;
+};
+
+Outcome runScript(HostContextConfig cfg, const std::string& src) {
+    // Port 1 on loopback: a gateway that is never connected. A test reaching
+    // this is a test whose decision leaked past the policy gate.
+    svapi::DbGateway db("127.0.0.1:1", 100);
+    JsRuntime rt;
+    std::string error;
+    auto bc = rt.compile(src, "test.js", error);
+    EXPECT_TRUE(bc.has_value()) << "compile failed: " << error;
+    if (!bc) return {};
+
+    HostContext host(db, std::move(cfg));
+    Outcome out;
+    out.result = rt.run(*bc, nlohmann::json::object(), 0, &host);
+    out.log = host.logLines();
+    out.blocked = host.blockedEgress();
+    return out;
+}
+
+HostContextConfig httpTrigger(KeyScope policy) {
+    HostContextConfig cfg;
+    cfg.project = "acme";
+    cfg.functionId = "kb-search";
+    cfg.policy = std::move(policy);
+    cfg.trigger = {{"method", "GET"},
+                   {"path", "/kb/cats"},
+                   {"params", {{"topic", "cats"}}},
+                   {"query", {{"q", "mice"}}},
+                   {"headers", {{"x-trace", "abc"}}},
+                   {"body", {{"n", 7}}}};
+    cfg.env = {{"PROVIDER_KEY", "s3cret"}};
+    cfg.deadlineMs = 2000;
+    return cfg;
+}
+
+// The script's own catch block, so an assertion reads the error the FUNCTION
+// sees rather than whatever the runner happened to log.
+const char* kCatchTemplate = R"(
+export default async function (ctx) {
+  try { return { threw: false, value: await (%BODY%) }; }
+  catch (e) { return { threw: true, name: e.name, code: e.code, message: String(e.message) }; }
+}
+)";
+
+std::string catching(const std::string& body) {
+    std::string src = kCatchTemplate;
+    const std::string marker = "%BODY%";
+    src.replace(src.find(marker), marker.size(), body);
+    return src;
+}
+
+} // namespace
+
+// --- the trigger and the environment ---------------------------------------
+
+TEST(HostContext, ExposesTheTriggerAsCtxFields) {
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  return { m: ctx.method, p: ctx.path, topic: ctx.params.topic,"
+                         "           q: ctx.query.q, h: ctx.headers['x-trace'], n: ctx.body.n };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("m"), "GET");
+    EXPECT_EQ(out.result.value.at("p"), "/kb/cats");
+    EXPECT_EQ(out.result.value.at("topic"), "cats");
+    EXPECT_EQ(out.result.value.at("q"), "mice");
+    EXPECT_EQ(out.result.value.at("h"), "abc");
+    EXPECT_EQ(out.result.value.at("n"), 7);
+}
+
+TEST(HostContext, MissingTriggerFieldsArriveAsEmptyObjects) {
+    // A cron or event trigger carries no HTTP shape at all. A function that
+    // reads ctx.query.q must then see undefined, not crash on undefined.query.
+    HostContextConfig cfg;
+    cfg.project = "acme";
+    cfg.functionId = "nightly";
+    auto out = runScript(std::move(cfg),
+                         "export default function (ctx) {"
+                         "  return { m: ctx.method, p: ctx.path, q: ctx.query.q === undefined,"
+                         "           keys: Object.keys(ctx.params).length };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("m"), "");
+    EXPECT_EQ(out.result.value.at("p"), "");
+    EXPECT_EQ(out.result.value.at("q"), true);
+    EXPECT_EQ(out.result.value.at("keys"), 0);
+}
+
+TEST(HostContext, ExposesEnvButKeepsItOutOfTheLog) {
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  ctx.log('starting');"
+                         "  return { k: ctx.env.PROVIDER_KEY, missing: ctx.env.NOPE === undefined };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("k"), "s3cret");
+    EXPECT_EQ(out.result.value.at("missing"), true);
+    ASSERT_EQ(out.log.size(), 1u);
+    EXPECT_EQ(out.log[0], "starting");
+}
+
+// --- ctx.log ----------------------------------------------------------------
+
+TEST(HostContext, LogKeepsOrderAndFormatsObjectsAsJson) {
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  ctx.log('one');"
+                         "  ctx.log('two', 2);"
+                         "  ctx.log({ a: 1 });"
+                         "  return null;"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.log.size(), 3u);
+    EXPECT_EQ(out.log[0], "one");
+    EXPECT_EQ(out.log[1], "two 2");
+    EXPECT_EQ(out.log[2], "{\"a\":1}");
+}
+
+TEST(HostContext, LogCaptureIsBounded) {
+    // Same reason the core caps console: an unbounded ctx.log is an unmetered
+    // allocation channel, and the lines travel back over HTTP to the invoker.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  for (let i = 0; i < 50000; i++) ctx.log('line ' + i);"
+                         "  return null;"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_LT(out.log.size(), 50000u);
+    ASSERT_FALSE(out.log.empty());
+    EXPECT_EQ(out.log.back(), "[log output truncated]");
+}
+
+// --- authorization ----------------------------------------------------------
+
+TEST(HostContext, DeniedCollectionAccessThrowsAJsErrorNamingCollectionAndOp) {
+    // An empty policy is the floor every function starts at
+    // (builtinDefaultFunctionPolicy), so this is the default experience.
+    auto out = runScript(httpTrigger({}), catching("ctx.collections('kb_chunks').find()"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "forbidden");
+    const std::string msg = out.result.value.at("message");
+    EXPECT_NE(msg.find("kb_chunks"), std::string::npos) << msg;
+    EXPECT_NE(msg.find("list"), std::string::npos) << msg;
+}
+
+TEST(HostContext, DenialIsNeverASilentEmptyResult) {
+    // The failure mode this rules out: .find() answering [] on a collection the
+    // function may not read, which looks exactly like an empty collection.
+    auto out = runScript(httpTrigger({}),
+                         "export default async function (ctx) {"
+                         "  const docs = await ctx.collections('kb_chunks').find();"
+                         "  return { length: docs.length };"
+                         "}");
+    EXPECT_FALSE(out.result.ok);
+    EXPECT_NE(out.result.error.find("kb_chunks"), std::string::npos) << out.result.error;
+}
+
+TEST(HostContext, EachBuilderCallAsksForTheOpItsHttpTwinAsksFor) {
+    // The denial message carries the op, which is how this asserts the mapping
+    // without a database: find->list, get->read, insert->insert, update and
+    // patch->update, delete->delete, search->search, store->insert. Divergence
+    // here is divergence from the HTTP handlers.
+    struct Case { const char* call; const char* op; };
+    const Case cases[] = {
+        {"ctx.collections('c').find()", "list"},
+        {"ctx.collections('c').get('x')", "read"},
+        {"ctx.collections('c').insert({a:1})", "insert"},
+        {"ctx.collections('c').update('x', {a:1})", "update"},
+        {"ctx.collections('c').patch('x', {a:1})", "update"},
+        {"ctx.collections('c').delete('x')", "delete"},
+        {"ctx.collections('c').search({ query_vector: [1,2] })", "search"},
+        {"ctx.collections('c').store({ vector: [1,2] })", "insert"},
+    };
+    for (const auto& c : cases) {
+        auto out = runScript(httpTrigger({}), catching(c.call));
+        ASSERT_TRUE(out.result.ok) << c.call << ": " << out.result.error;
+        EXPECT_EQ(out.result.value.at("threw"), true) << c.call;
+        const std::string msg = out.result.value.at("message");
+        EXPECT_NE(msg.find(c.op), std::string::npos) << c.call << " -> " << msg;
+    }
+}
+
+// The GRANT direction cannot be driven through JS here: past the gate the
+// binding calls the real database client, and an unconnected client crashes
+// rather than throwing, so the script would take the process down instead of
+// reporting an error. The rule under test is the gate's answer, so ask the gate
+// directly - same Principal, same call the binding makes.
+TEST(HostContext, APolicyGrantGetsPastTheGate) {
+    const std::vector<std::string> projects{"acme"};
+    const KeyScope policy = policyFor("kb_chunks", {KeyOp::List});
+    const svapi::Principal p{"fn:acme/kb-search", &projects, false, &policy};
+    EXPECT_NO_THROW(svapi::requireCapabilityCore(p, "acme", "kb_chunks", KeyOp::List));
+    EXPECT_THROW(svapi::requireCapabilityCore(p, "acme", "kb_chunks", KeyOp::Delete), ApiError)
+        << "the same policy must still refuse an op it does not grant";
+}
+
+TEST(HostContext, APolicyRuleIsPerOpNotPerCollection) {
+    auto out = runScript(httpTrigger(policyFor("kb_chunks", {KeyOp::List})),
+                         catching("ctx.collections('kb_chunks').delete('x')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("code"), "forbidden");
+}
+
+TEST(HostContext, APrefixGlobInThePolicyWorksAsItDoesOverHttp) {
+    // Same reason as above: assert the gate, not the database behind it.
+    const std::vector<std::string> projects{"acme"};
+    const KeyScope policy = policyFor("catalog_*", {KeyOp::List});
+    const svapi::Principal p{"fn:acme/catalog", &projects, false, &policy};
+    EXPECT_NO_THROW(svapi::requireCapabilityCore(p, "acme", "catalog_items", KeyOp::List));
+    EXPECT_THROW(svapi::requireCapabilityCore(p, "acme", "other_items", KeyOp::List), ApiError)
+        << "a prefix glob must not reach a collection outside the prefix";
+}
+
+// --- the filter grammar -----------------------------------------------------
+
+TEST(HostContext, FilterStringsAreParsedByTheSharedGrammar) {
+    // parseFilter() rejects an unknown operator, so a bad filter must surface
+    // as the SAME complaint an HTTP ?filter= makes - proof the builder hands
+    // its filters to the shared parser rather than inventing a grammar.
+    auto out = runScript(httpTrigger(policyFor("kb_chunks", {KeyOp::List})),
+                         catching("ctx.collections('kb_chunks').filter('topic:wat:cats').find()"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    const std::string msg = out.result.value.at("message");
+    EXPECT_NE(msg.find("wat"), std::string::npos) << msg;
+}
+
+TEST(HostContext, VectorSearchFiltersUseTheSameGrammar) {
+    auto out = runScript(
+        httpTrigger(policyFor("kb_chunks", {KeyOp::Search})),
+        catching("ctx.collections('kb_chunks').search({ query_vector: [1], filters: ['l:wat:hu'] })"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    const std::string msg = out.result.value.at("message");
+    EXPECT_NE(msg.find("wat"), std::string::npos) << msg;
+}
+
+TEST(HostContext, TheBuilderIsImmutableSoARefCanBeReused) {
+    // ctx.collections(...) is a value a script may hold and branch on. If
+    // .filter() mutated it, a second use would silently carry the first one's
+    // filters - a correctness bug with no visible symptom.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  const base = ctx.collections('c');"
+                         "  const a = base.filter('x:eq:1');"
+                         "  return { base: base._query().filters.length,"
+                         "           a: a._query().filters.length };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("base"), 0);
+    EXPECT_EQ(out.result.value.at("a"), 1);
+}
+
+// --- ctx.fetch --------------------------------------------------------------
+
+TEST(HostContext, FetchRefusesLoopbackAndRecordsIt) {
+    auto out = runScript(httpTrigger({}), catching("ctx.fetch('http://127.0.0.1:9004/')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked");
+    ASSERT_EQ(out.blocked.size(), 1u);
+    EXPECT_NE(out.blocked[0].find("127.0.0.1"), std::string::npos) << out.blocked[0];
+}
+
+TEST(HostContext, FetchRefusesANonHttpScheme) {
+    // Fail closed: file:, gopher: and friends are classic SSRF escalations and
+    // parseHttpUrl answers nullopt for all of them.
+    auto out = runScript(httpTrigger({}), catching("ctx.fetch('file:///etc/passwd')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked");
+    EXPECT_EQ(out.blocked.size(), 1u);
+}
+
+TEST(HostContext, FetchRefusesTheCloudMetadataEndpoint) {
+    auto out = runScript(httpTrigger({}),
+                         catching("ctx.fetch('http://169.254.169.254/latest/meta-data/')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked");
+}
+
+TEST(HostContext, FetchStopsWhenTheRunsBudgetIsGone) {
+    // One slow provider must not outlive the run that is waiting for it. The
+    // budget is checked before connecting, so an exhausted one costs no socket.
+    HostContextConfig cfg = httpTrigger({});
+    cfg.deadlineMs = 1;
+    auto out = runScript(std::move(cfg),
+                         catching("(() => { const t = Date.now();"
+                                  "          while (Date.now() - t < 20) {}"
+                                  "          return ctx.fetch('http://8.8.8.8/'); })()"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "deadline_exceeded");
+    EXPECT_TRUE(out.blocked.empty());  // a budget refusal is not an egress refusal
+}
+
+// --- the pure seams ---------------------------------------------------------
+
+TEST(HostDetail, OpVocabularyMatchesTheHttpHandlers) {
+    EXPECT_EQ(detail::keyOpForDbOp("find"), KeyOp::List);
+    EXPECT_EQ(detail::keyOpForDbOp("get"), KeyOp::Read);
+    EXPECT_EQ(detail::keyOpForDbOp("insert"), KeyOp::Insert);
+    EXPECT_EQ(detail::keyOpForDbOp("update"), KeyOp::Update);
+    EXPECT_EQ(detail::keyOpForDbOp("patch"), KeyOp::Update);
+    EXPECT_EQ(detail::keyOpForDbOp("delete"), KeyOp::Delete);
+    EXPECT_EQ(detail::keyOpForDbOp("search"), KeyOp::Search);
+    EXPECT_EQ(detail::keyOpForDbOp("store"), KeyOp::Insert);
+    EXPECT_FALSE(detail::keyOpForDbOp("drop").has_value());
+}
+
+TEST(HostDetail, DenialMessageNamesTheCollectionAndTheOp) {
+    const std::string m = detail::deniedMessage("kb_chunks", "list", "scope does not permit");
+    EXPECT_NE(m.find("kb_chunks"), std::string::npos) << m;
+    EXPECT_NE(m.find("list"), std::string::npos) << m;
+    EXPECT_NE(m.find("scope does not permit"), std::string::npos) << m;
+}
+
+TEST(HostDetail, QueryOptionsCarryTheBuildersAccumulatedState) {
+    auto opts = detail::queryOptionsFrom({{"filters", {"a:eq:1", "b:gt:2"}},
+                                          {"limit", 20},
+                                          {"offset", 5},
+                                          {"sort", "created_at"},
+                                          {"desc", true}});
+    EXPECT_EQ(opts.filters.size(), 2u);
+    EXPECT_EQ(opts.limit, 20u);
+    EXPECT_EQ(opts.offset, 5u);
+    EXPECT_EQ(opts.sortField, "created_at");
+    EXPECT_TRUE(opts.sortDescending);
+}
+
+TEST(HostDetail, QueryOptionsRejectNonsenseRatherThanGuessing) {
+    EXPECT_THROW(detail::queryOptionsFrom({{"filters", "a:eq:1"}}), ApiError);
+    EXPECT_THROW(detail::queryOptionsFrom({{"filters", {7}}}), ApiError);
+    EXPECT_THROW(detail::queryOptionsFrom({{"limit", -1}}), ApiError);
+    EXPECT_THROW(detail::queryOptionsFrom({{"sort", 3}}), ApiError);
+}
+
+TEST(HostDetail, OutboundTimeoutIsWhatIsLeftOfTheRunsBudget) {
+    EXPECT_EQ(detail::outboundTimeoutMs(2000, 500, 0), 1500);
+    EXPECT_EQ(detail::outboundTimeoutMs(2000, 500, 300), 300);   // the caller asked for less
+    EXPECT_EQ(detail::outboundTimeoutMs(2000, 500, 9000), 1500);  // and cannot ask for more
+    EXPECT_LE(detail::outboundTimeoutMs(2000, 2000, 300), 0);     // exhausted
+    EXPECT_LE(detail::outboundTimeoutMs(500, 900, 0), 0);
+    // No budget configured: a sane cap, never unbounded.
+    EXPECT_GT(detail::outboundTimeoutMs(0, 0, 0), 0);
+    EXPECT_LE(detail::outboundTimeoutMs(0, 0, 0), 60000);
+}
+
+TEST(HostDetail, EgressPinsTheAddressTheGuardApproved) {
+    auto policy = svapi::functions::SsrfPolicy::withDefaults();
+    auto parts = svapi::functions::parseHttpUrl("https://provider.example/v1/x");
+    ASSERT_TRUE(parts.has_value());
+    auto d = detail::decideEgress(*parts, policy,
+                                  [](const std::string&) { return std::vector<std::string>{"93.184.216.34"}; });
+    EXPECT_TRUE(d.allowed) << d.reason;
+    EXPECT_EQ(d.pinnedAddress, "93.184.216.34");
+}
+
+TEST(HostDetail, EgressClassifiesEveryAddressNotJustTheFirst) {
+    // The multi-A bypass: a hostile name whose first answer is public and whose
+    // second is loopback. One blocked address blocks the host.
+    auto policy = svapi::functions::SsrfPolicy::withDefaults();
+    auto parts = svapi::functions::parseHttpUrl("http://rebind.example/");
+    ASSERT_TRUE(parts.has_value());
+    auto d = detail::decideEgress(
+        *parts, policy,
+        [](const std::string&) { return std::vector<std::string>{"93.184.216.34", "127.0.0.1"}; });
+    EXPECT_FALSE(d.allowed);
+    EXPECT_TRUE(d.pinnedAddress.empty());
+}
+
+TEST(HostDetail, EgressFailsClosedOnAResolutionFailure) {
+    auto policy = svapi::functions::SsrfPolicy::withDefaults();
+    auto parts = svapi::functions::parseHttpUrl("http://nx.example/");
+    ASSERT_TRUE(parts.has_value());
+    auto d = detail::decideEgress(*parts, policy,
+                                  [](const std::string&) { return std::vector<std::string>{}; });
+    EXPECT_FALSE(d.allowed);
+    EXPECT_FALSE(d.reason.empty());
+}
+
+TEST(HostDetail, AnAddressLiteralIsClassifiedWithoutAResolver) {
+    // No DNS means no rebinding window at all, so the resolver must not even be
+    // consulted - and the pin is the literal itself.
+    auto policy = svapi::functions::SsrfPolicy::withDefaults();
+    bool resolved = false;
+    auto resolver = [&resolved](const std::string&) {
+        resolved = true;
+        return std::vector<std::string>{};
+    };
+
+    auto blocked = svapi::functions::parseHttpUrl("http://10.0.0.5/");
+    ASSERT_TRUE(blocked.has_value());
+    EXPECT_FALSE(detail::decideEgress(*blocked, policy, resolver).allowed);
+
+    auto allowed = svapi::functions::parseHttpUrl("http://8.8.8.8/");
+    ASSERT_TRUE(allowed.has_value());
+    auto d = detail::decideEgress(*allowed, policy, resolver);
+    EXPECT_TRUE(d.allowed) << d.reason;
+    EXPECT_EQ(d.pinnedAddress, "8.8.8.8");
+    EXPECT_FALSE(resolved);
+}

+ 16 - 5
runner/tests/js_runtime_test.cpp

@@ -490,18 +490,29 @@ TEST(JsRuntimePool, RetiresARuntimeLeftWithPendingJobs) {
                           "}");
     auto probe = compileOk(compiler, "export default function () { return 'clean'; }");
 
+    bool poisonedAfterTimeout = false;
     {
         auto lease = pool.acquire();
         JsResult r = lease->run(spin, nlohmann::json::object());
         EXPECT_TRUE(r.timed_out) << r.error;
-        // Unexecuted microtasks live on the runtime, not the context, so this
-        // runtime can never be handed to another tenant.
-        EXPECT_TRUE(lease->poisoned());
+        // Unexecuted microtasks live on the runtime, not the context, so a
+        // runtime that still holds them must never be handed to another tenant.
+        //
+        // NOT asserted as "poisoned() is true": whether any job survives the
+        // bounded flush is a race against how many were queued when the
+        // deadline passed, and it resolves differently on a faster machine.
+        // Both outcomes are safe, and asserting one of them made this test fail
+        // in the Debian build container while passing on the dev host. What
+        // must hold either way is below: the NEXT tenant sees a clean runtime.
+        poisonedAfterTimeout = lease->poisoned();
     }
 
     auto lease = pool.acquire();
-    EXPECT_FALSE(lease->poisoned());
+    EXPECT_FALSE(lease->poisoned())
+        << "a poisoned runtime was leased out instead of being destroyed";
     JsResult r = lease->run(probe, nlohmann::json::object());
     ASSERT_TRUE(r.ok) << r.error;
-    EXPECT_EQ(r.value, "clean");
+    EXPECT_EQ(r.value, "clean") << "leftover work from the previous tenant ran in this one";
+    if (poisonedAfterTimeout)
+        EXPECT_EQ(pool.retired(), 1u) << "a poisoned runtime must be retired, not recycled";
 }

+ 503 - 0
runner/tests/run_service_test.cpp

@@ -0,0 +1,503 @@
+// Tests for the runner's protocol layer: the /run, /validate and /health
+// contract in docs/superpowers/specs/2026-10-06-function-runtime-design.md
+// ("Runner protocol"), plus the two things that document leaves open - the
+// shape a default export must return, and what a timeout or a memory breach
+// becomes in the response.
+//
+// They run a real QuickJS engine but no database: the registry and the ctx host
+// bindings arrive through the seams RunService takes, which is what keeps this
+// file runnable on the dev host (CLAUDE.md: smartbotic-db-client does not
+// compile there).
+#include <gtest/gtest.h>
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "run_service.hpp"
+
+using svapi::KeyScope;
+using svapi::runner::FunctionSource;
+using svapi::runner::FunctionView;
+using svapi::runner::HostBindingsFactory;
+using svapi::runner::HostBindingsLease;
+using svapi::runner::ProtocolResponse;
+using svapi::runner::RunService;
+using svapi::runner::RunServiceOptions;
+using svapi::runner::shapeReturnValue;
+
+namespace {
+
+/// In-memory stand-in for FunctionRegistry. Counts lookups, because the
+/// bytecode cache must not change how often the registry is read: the registry
+/// is the authority on `enabled` and `valid`, so a cache hit still has to look.
+class FakeSource : public FunctionSource {
+public:
+    FunctionView lookup(const std::string& project, const std::string& functionId) override {
+        ++lookups;
+        auto it = rows.find(project + "/" + functionId);
+        if (it == rows.end()) return FunctionView{};
+        return it->second;
+    }
+
+    void put(const std::string& project, const std::string& id, FunctionView row) {
+        row.found = true;
+        if (row.contentHash.empty()) row.contentHash = "h-" + id;
+        rows[project + "/" + id] = std::move(row);
+    }
+
+    std::map<std::string, FunctionView> rows;
+    int lookups = 0;
+};
+
+FunctionView httpFunction(const std::string& source, long long timeoutMs = 0) {
+    FunctionView v;
+    v.source = source;
+    v.descriptor = {{"id", "f"}, {"type", "http"}, {"route", "/f"}};
+    if (timeoutMs > 0) v.descriptor["timeoutMs"] = timeoutMs;
+    return v;
+}
+
+nlohmann::json runRequest(const std::string& id = "f") {
+    return {{"project", "p"},
+            {"function_id", id},
+            {"trigger", {{"method", "GET"}, {"path", "/f"}, {"params", nlohmann::json::object()},
+                         {"query", nlohmann::json::object()},
+                         {"headers", nlohmann::json::object()},
+                         {"body", nullptr}}}};
+}
+
+RunServiceOptions fastOptions() {
+    RunServiceOptions o;
+    o.poolSize = 2;
+    o.limits.wall_time_ms = 1000;
+    return o;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------- dispatch
+
+TEST(RunServiceDispatch, MissingFunctionIsA404ShapedBody) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest("nope"));
+    // The CALL succeeded; the function is what is missing. A 404 on the call
+    // itself would make RunnerPool try every other runner for a function that
+    // is absent from the registry they all share.
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 404);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("nope"), std::string::npos)
+        << r.body.at("error");
+}
+
+TEST(RunServiceDispatch, DisabledFunctionDoesNotRun) {
+    FakeSource src;
+    FunctionView v = httpFunction("export default function () { return { body: 'ran' }; }");
+    v.enabled = false;
+    src.put("p", "f", v);
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 409);
+    EXPECT_TRUE(r.body.at("body").is_null()) << r.body.dump();
+}
+
+TEST(RunServiceDispatch, InvalidFunctionDoesNotRunAndSurfacesItsStoredError) {
+    FakeSource src;
+    FunctionView v = httpFunction("export default function () { return { body: 'ran' }; }");
+    v.valid = false;
+    v.lastError = "SyntaxError: unexpected token";
+    src.put("p", "f", v);
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 422);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("unexpected token"), std::string::npos)
+        << r.body.at("error");
+}
+
+TEST(RunServiceDispatch, MalformedPayloadIsA400OnTheCall) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    for (const nlohmann::json bad : {nlohmann::json(nlohmann::json::array()),
+                                     nlohmann::json{{"function_id", "f"}},
+                                     nlohmann::json{{"project", "p"}},
+                                     nlohmann::json{{"project", ""}, {"function_id", "f"}}}) {
+        ProtocolResponse r = svc.run(bad);
+        EXPECT_EQ(r.httpStatus, 400) << bad.dump();
+        EXPECT_FALSE(r.body.at("error").get<std::string>().empty());
+    }
+    EXPECT_EQ(src.lookups, 0) << "a payload that was not understood must not reach the registry";
+}
+
+TEST(RunServiceDispatch, AMissingTriggerIsAnEmptyTriggerNotAnError) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function (ctx) { return { m: ctx.method }; }"));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run({{"project", "p"}, {"function_id", "f"}});
+    ASSERT_TRUE(r.body.at("ok").get<bool>()) << r.body.dump();
+    EXPECT_EQ(r.body.at("status"), 200);
+}
+
+// ------------------------------------------------------------- return shape
+
+TEST(RunServiceShape, EnvelopeFieldsAreHonoured) {
+    FakeSource src;
+    src.put("p", "f",
+            httpFunction("export default function () {"
+                         "  return { status: 201, headers: { 'X-Thing': 'a' }, body: { id: 7 } };"
+                         "}"));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    ASSERT_TRUE(r.body.at("ok").get<bool>()) << r.body.dump();
+    EXPECT_EQ(r.body.at("status"), 201);
+    EXPECT_EQ(r.body.at("headers").at("X-Thing"), "a");
+    EXPECT_EQ(r.body.at("body").at("id"), 7);
+}
+
+TEST(RunServiceShape, APlainObjectIsTheBodyOfA200) {
+    // The ergonomic case the design document's own example implies: a function
+    // that just returns its data should not have to wrap it.
+    EXPECT_TRUE(shapeReturnValue({{"docs", {1, 2}}}).ok);
+    EXPECT_EQ(shapeReturnValue({{"docs", {1, 2}}}).status, 200);
+    EXPECT_EQ(shapeReturnValue({{"docs", {1, 2}}}).body.at("docs").size(), 2u);
+}
+
+TEST(RunServiceShape, NonObjectReturnsAreTheBody) {
+    for (const nlohmann::json v : {nlohmann::json(7), nlohmann::json("hi"), nlohmann::json(true),
+                                   nlohmann::json({1, 2, 3}), nlohmann::json(nullptr)}) {
+        auto shaped = shapeReturnValue(v);
+        EXPECT_TRUE(shaped.ok) << v.dump() << ": " << shaped.error;
+        EXPECT_EQ(shaped.status, 200) << v.dump();
+        EXPECT_EQ(shaped.body, v) << v.dump();
+    }
+}
+
+TEST(RunServiceShape, APartialEnvelopeFillsItsDefaults) {
+    auto onlyStatus = shapeReturnValue({{"status", 204}});
+    ASSERT_TRUE(onlyStatus.ok) << onlyStatus.error;
+    EXPECT_EQ(onlyStatus.status, 204);
+    EXPECT_TRUE(onlyStatus.body.is_null());
+    EXPECT_TRUE(onlyStatus.headers.empty());
+
+    auto onlyBody = shapeReturnValue({{"body", "text"}});
+    ASSERT_TRUE(onlyBody.ok) << onlyBody.error;
+    EXPECT_EQ(onlyBody.status, 200);
+    EXPECT_EQ(onlyBody.body, "text");
+}
+
+TEST(RunServiceShape, MixingEnvelopeKeysWithDataIsRejected) {
+    // Deliberately NOT guessed at, for the reason documented on
+    // shapeReturnValue: the permissive reading drops the sibling keys silently.
+    auto shaped = shapeReturnValue({{"status", 200}, {"docs", nlohmann::json::array()}});
+    EXPECT_FALSE(shaped.ok);
+    EXPECT_NE(shaped.error.find("docs"), std::string::npos) << shaped.error;
+}
+
+TEST(RunServiceShape, ANonIntegerOrOutOfRangeStatusIsRejected) {
+    EXPECT_FALSE(shapeReturnValue({{"status", "ok"}}).ok);
+    EXPECT_FALSE(shapeReturnValue({{"status", 99}}).ok);
+    EXPECT_FALSE(shapeReturnValue({{"status", 600}}).ok);
+    EXPECT_FALSE(shapeReturnValue({{"status", 200.5}}).ok);
+    EXPECT_TRUE(shapeReturnValue({{"status", 599}}).ok);
+}
+
+TEST(RunServiceShape, HeaderValuesAreStringifiedAndStructuredOnesRejected) {
+    auto shaped = shapeReturnValue(
+        {{"status", 200}, {"headers", {{"X-N", 5}, {"X-B", true}, {"X-S", "s"}}}});
+    ASSERT_TRUE(shaped.ok) << shaped.error;
+    EXPECT_EQ(shaped.headers.at("X-N"), "5");
+    EXPECT_EQ(shaped.headers.at("X-B"), "true");
+    EXPECT_EQ(shaped.headers.at("X-S"), "s");
+
+    EXPECT_FALSE(shapeReturnValue({{"headers", {{"X", nlohmann::json::array()}}}}).ok);
+    EXPECT_FALSE(shapeReturnValue({{"headers", "not-an-object"}}).ok);
+}
+
+TEST(RunServiceShape, AnUnshapeableReturnValueFailsTheRun) {
+    FakeSource src;
+    src.put("p", "f",
+            httpFunction("export default function () { return { status: 200, oops: 1 }; }"));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 500);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("invalid_return"), std::string::npos)
+        << r.body.at("error");
+}
+
+// ------------------------------------------------------------- run failures
+
+TEST(RunServiceFailure, AThrownErrorIsOkFalseWith500) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { throw new Error('boom'); }"));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 500);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("boom"), std::string::npos)
+        << r.body.at("error");
+    EXPECT_FALSE(r.body.at("timed_out").get<bool>());
+    EXPECT_FALSE(r.body.at("out_of_memory").get<bool>());
+}
+
+TEST(RunServiceFailure, ATimeoutIs504AndStaysDistinguishable) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { for (;;) {} }", 60));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 504);
+    EXPECT_TRUE(r.body.at("timed_out").get<bool>());
+    EXPECT_FALSE(r.body.at("out_of_memory").get<bool>());
+}
+
+TEST(RunServiceFailure, TheDescriptorTimeoutCannotRaiseTheConfiguredCeiling) {
+    FakeSource src;
+    // Asks for five seconds against a 120ms ceiling. If the override were not
+    // clamped this test would take 5s instead of ~0.12s.
+    src.put("p", "f", httpFunction("export default function () { for (;;) {} }", 5000));
+    RunServiceOptions o = fastOptions();
+    o.limits.wall_time_ms = 120;
+    RunService svc(src, o);
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_TRUE(r.body.at("timed_out").get<bool>());
+    EXPECT_LT(r.body.at("duration_ms").get<int64_t>(), 2000);
+}
+
+TEST(RunServiceFailure, AMemoryBreachIs500AndFlagsOutOfMemory) {
+    FakeSource src;
+    src.put("p", "f",
+            httpFunction("export default function () {"
+                         "  const a = []; for (;;) a.push(new Array(10000).fill('x'));"
+                         "}"));
+    RunServiceOptions o = fastOptions();
+    o.limits.memory_limit_bytes = 2u * 1024 * 1024;
+    o.limits.wall_time_ms = 5000;
+    RunService svc(src, o);
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    // 500, not 503: the ceiling is per-run and deterministic, so advertising it
+    // as "try again later" would just build a retry loop.
+    EXPECT_EQ(r.body.at("status"), 500);
+    EXPECT_TRUE(r.body.at("out_of_memory").get<bool>());
+}
+
+// ---------------------------------------------------------------- console
+
+TEST(RunServiceConsole, EngineAndHostLinesBothReachTheResponse) {
+    class LoggingHost : public HostBindingsFactory {
+    public:
+        bool create(const Request& request, HostBindingsLease& out, std::string&) override {
+            seen = request;
+            out.collectConsole = [] { return std::vector<std::string>{"host: blocked 10.0.0.1"}; };
+            return true;
+        }
+        Request seen;
+    };
+
+    FakeSource src;
+    FunctionView v = httpFunction("export default function () { console.log('from js'); "
+                                  "return { body: 1 }; }");
+    v.policy.rateLimitPerMin = 42;  // proves the registry policy, not the script, is passed on
+    src.put("p", "f", v);
+    LoggingHost host;
+    RunService svc(src, fastOptions(), &host);
+
+    ProtocolResponse r = svc.run(runRequest());
+    ASSERT_TRUE(r.body.at("ok").get<bool>()) << r.body.dump();
+    const auto console = r.body.at("console").get<std::vector<std::string>>();
+    ASSERT_EQ(console.size(), 2u) << r.body.at("console").dump();
+    EXPECT_NE(console[0].find("from js"), std::string::npos);
+    EXPECT_NE(console[1].find("blocked"), std::string::npos);
+    EXPECT_EQ(host.seen.project, "p");
+    EXPECT_EQ(host.seen.functionId, "f");
+    EXPECT_EQ(host.seen.policy.rateLimitPerMin, 42u);
+    EXPECT_GT(host.seen.deadlineMs, 0);
+}
+
+TEST(RunServiceConsole, AFailedBindingInstallFailsTheRunBeforeUserCode) {
+    class BrokenHost : public HostBindingsFactory {
+    public:
+        bool create(const Request&, HostBindingsLease&, std::string& error) override {
+            error = "no gateway";
+            return false;
+        }
+    };
+
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { return { body: 'ran' }; }"));
+    BrokenHost host;
+    RunService svc(src, fastOptions(), &host);
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 500);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("no gateway"), std::string::npos);
+}
+
+// ----------------------------------------------------------- bytecode cache
+
+TEST(RunServiceCache, CompiledBytecodeIsReusedForTheSameContentHash) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { return { body: 'first' }; }"));
+    RunService svc(src, fastOptions());
+
+    ASSERT_EQ(svc.run(runRequest()).body.at("body"), "first");
+
+    // Same hash, different source. The cache is keyed by hash, so the stale
+    // bytecode is what must run - which is exactly how we observe the hit
+    // without reaching into the service.
+    src.rows.at("p/f").source = "export default function () { return { body: 'second' }; }";
+    EXPECT_EQ(svc.run(runRequest()).body.at("body"), "first");
+
+    // A real code push changes the hash, and then the new source must win.
+    src.rows.at("p/f").contentHash = "h2";
+    EXPECT_EQ(svc.run(runRequest()).body.at("body"), "second");
+}
+
+TEST(RunServiceCache, TheRegistryIsStillReadOnEveryRun) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { return { body: 1 }; }"));
+    RunService svc(src, fastOptions());
+
+    svc.run(runRequest());
+    svc.run(runRequest());
+    EXPECT_EQ(src.lookups, 2) << "enabled/valid live in the registry; a cached module must not "
+                                 "let a disabled function keep running";
+}
+
+TEST(RunServiceCache, ASourceThatNoLongerCompilesFailsTheRunNotTheProcess) {
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function ( { broken"));
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.run(runRequest());
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_EQ(r.body.at("status"), 422);
+    EXPECT_NE(r.body.at("error").get<std::string>().find("SyntaxError"), std::string::npos)
+        << r.body.at("error");
+}
+
+// ---------------------------------------------------------------- /validate
+
+TEST(RunServiceValidate, CompilesAndReturnsTheParsedDescriptor) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.validate(
+        {{"source", "export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', "
+                    "method: 'GET' };\n"
+                    "export default async function (ctx) { return { body: ctx.params.topic }; }"},
+         {"path", "kb-search.js"}});
+    ASSERT_EQ(r.httpStatus, 200);
+    ASSERT_TRUE(r.body.at("ok").get<bool>()) << r.body.dump();
+    EXPECT_EQ(r.body.at("descriptor").at("id"), "kb-search");
+    EXPECT_EQ(r.body.at("descriptor").at("route"), "/kb/:topic");
+}
+
+TEST(RunServiceValidate, DoesNotCallTheDefaultExport) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    // If validation ran the handler this would be a failure instead of an ok.
+    ProtocolResponse r = svc.validate(
+        {{"source", "export const on = { id: 'x', type: 'http', route: '/x' };\n"
+                    "export default function () { throw new Error('handler ran'); }"},
+         {"path", "x.js"}});
+    EXPECT_TRUE(r.body.at("ok").get<bool>()) << r.body.dump();
+}
+
+TEST(RunServiceValidate, ReportsACompileErrorWithTheFilename) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.validate({{"source", "export default function ( {"},
+                                       {"path", "broken.js"}});
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_NE(r.body.at("error").get<std::string>().find("SyntaxError"), std::string::npos)
+        << r.body.at("error");
+    EXPECT_NE(r.body.at("error").get<std::string>().find("broken.js"), std::string::npos)
+        << r.body.at("error");
+}
+
+TEST(RunServiceValidate, RejectsAMissingOnExport) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.validate({{"source", "export default function () { return 1; }"},
+                                       {"path", "no-on.js"}});
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_NE(r.body.at("error").get<std::string>().find("on"), std::string::npos)
+        << r.body.at("error");
+}
+
+TEST(RunServiceValidate, RejectsADescriptorTheParserRefuses) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    // No id: the design document is explicit that a missing id is an error and
+    // never a silent fallback to the file path.
+    ProtocolResponse r = svc.validate(
+        {{"source", "export const on = { type: 'http', route: '/x' };\n"
+                    "export default function () { return 1; }"},
+         {"path", "x.js"}});
+    EXPECT_FALSE(r.body.at("ok").get<bool>());
+    EXPECT_FALSE(r.body.at("error").get<std::string>().empty());
+}
+
+TEST(RunServiceValidate, RejectsAMissingSource) {
+    FakeSource src;
+    RunService svc(src, fastOptions());
+
+    ProtocolResponse r = svc.validate({{"path", "x.js"}});
+    EXPECT_EQ(r.httpStatus, 400);
+}
+
+TEST(RunServiceValidate, DoesNotPoisonTheRunPathsCache) {
+    // /validate compiles arbitrary unstored source. If it shared the run cache
+    // keyed by anything a caller controls, one validate call could make a
+    // DIFFERENT function execute the submitted code.
+    FakeSource src;
+    src.put("p", "f", httpFunction("export default function () { return { body: 'real' }; }"));
+    RunService svc(src, fastOptions());
+
+    svc.validate({{"source", "export const on = { id: 'f', type: 'http', route: '/f' };\n"
+                             "export default function () { return { body: 'injected' }; }"},
+                  {"path", "f.js"}});
+    EXPECT_EQ(svc.run(runRequest()).body.at("body"), "real");
+}
+
+// ------------------------------------------------------------------ /health
+
+TEST(RunServiceHealth, ReportsThePoolAndIsAlways200) {
+    FakeSource src;
+    RunServiceOptions o = fastOptions();
+    o.version = "0.4.0";
+    RunService svc(src, o);
+
+    ProtocolResponse r = svc.health();
+    EXPECT_EQ(r.httpStatus, 200);
+    EXPECT_EQ(r.body.at("status"), "ok");
+    EXPECT_EQ(r.body.at("version"), "0.4.0");
+    EXPECT_EQ(r.body.at("pool").at("size"), 2);
+    EXPECT_TRUE(r.body.at("pool").contains("idle"));
+    EXPECT_TRUE(r.body.at("pool").contains("retired"));
+}