Bladeren bron

Merge: server-side JavaScript functions (QuickJS runtime, slice 1)

Functions that serve HTTP routes, run in a sandboxed QuickJS runner next
to the data, and are authorized by the same code an API key goes through.

The load-bearing decisions, each with a test named for it: a code push can
never widen access; a function is a Principal with a policy and never
admin; ctx.collections is a direct gateway call rather than loopback HTTP;
ctx.fetch resolves a name once and pins the connection to the address the
SSRF guard approved; a delivered-then-unanswered run is never retried,
because the handler may be running and a retry would double-execute it.

399/399 in the Debian 13 container with BUILD_RUNNER=ON. The runner is
opt-in because it vendors QuickJS over the network at configure time.

ctx.env is deliberately deferred: nothing has decided where a project's
secrets live, so a function cannot hold a credential yet.
fszontagh 1 maand geleden
bovenliggende
commit
2289608da7
64 gewijzigde bestanden met toevoegingen van 10384 en 108 verwijderingen
  1. 3 0
      .gitignore
  2. 16 0
      CLAUDE.md
  3. 15 0
      CMakeLists.txt
  4. 20 0
      api/llms.txt
  5. 518 0
      api/openapi.json
  6. 311 0
      docs/superpowers/specs/2026-10-06-function-runtime-design.md
  7. 6 1
      packaging/devstack/run-tests.sh
  8. 178 0
      runner/CMakeLists.txt
  9. 13 0
      runner/config/runner.json
  10. 76 0
      runner/include/runner/host_context.hpp
  11. 205 0
      runner/include/runner/js_runtime.hpp
  12. 883 0
      runner/src/host_context.cpp
  13. 156 0
      runner/src/host_prelude.js
  14. 688 0
      runner/src/js_runtime.cpp
  15. 310 0
      runner/src/main.cpp
  16. 325 0
      runner/src/run_service.cpp
  17. 201 0
      runner/src/run_service.hpp
  18. 486 0
      runner/tests/host_context_test.cpp
  19. 518 0
      runner/tests/js_runtime_test.cpp
  20. 503 0
      runner/tests/run_service_test.cpp
  21. 10 0
      src/CMakeLists.txt
  22. 12 0
      src/config.cpp
  23. 12 0
      src/config.hpp
  24. 4 0
      src/errors.cpp
  25. 2 1
      src/errors.hpp
  26. 94 0
      src/function_record.cpp
  27. 86 0
      src/function_record.hpp
  28. 73 0
      src/function_registry.cpp
  29. 49 0
      src/function_registry.hpp
  30. 104 0
      src/function_run_log.cpp
  31. 47 0
      src/function_run_log.hpp
  32. 413 0
      src/functions/descriptor.cpp
  33. 103 0
      src/functions/descriptor.hpp
  34. 463 0
      src/functions/net_guard.cpp
  35. 157 0
      src/functions/net_guard.hpp
  36. 342 0
      src/handlers/function_dispatch.cpp
  37. 328 0
      src/handlers/functions.cpp
  38. 6 4
      src/handlers/project_settings.cpp
  39. 3 44
      src/handlers/vectors.cpp
  40. 29 5
      src/main.cpp
  41. 17 0
      src/principal.cpp
  42. 48 0
      src/principal.hpp
  43. 24 8
      src/project_settings.cpp
  44. 29 6
      src/project_settings.hpp
  45. 305 0
      src/runner_client.cpp
  46. 101 0
      src/runner_client.hpp
  47. 41 8
      src/server.cpp
  48. 27 0
      src/server.hpp
  49. 4 4
      src/settings_store.cpp
  50. 11 4
      src/settings_store.hpp
  51. 49 0
      src/vector_search.cpp
  52. 33 0
      src/vector_search.hpp
  53. 61 0
      tests/CMakeLists.txt
  54. 9 1
      tests/api_fixture.hpp
  55. 3 3
      tests/test_api_integration.cpp
  56. 6 0
      tests/test_errors.cpp
  57. 251 0
      tests/test_function_record.cpp
  58. 213 0
      tests/test_function_run_log.cpp
  59. 377 0
      tests/test_functions_descriptor.cpp
  60. 457 0
      tests/test_functions_net_guard.cpp
  61. 75 0
      tests/test_principal.cpp
  62. 64 15
      tests/test_project_settings.cpp
  63. 407 0
      tests/test_runner_client.cpp
  64. 4 4
      tests/test_stores.cpp

+ 3 - 0
.gitignore

@@ -19,3 +19,6 @@ compile_commands.json
 # Client debs vendored into the Docker build when the pinned version has
 # dropped out of the apt repo index (build.sh populates this).
 packaging/vendor/*.deb
+
+# Agent worktrees and local session state
+.claude/

+ 16 - 0
CLAUDE.md

@@ -32,6 +32,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
 - `webui/` — React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
+- `runner/` — the **function runner service**, a second binary (`smartbotic-vectorapi-runner`). Three layers split by what they must link, which is also what decides where each can be tested: `runner_core` (QuickJS engine + pool, no database), `runner_protocol` (`/run`, `/validate`, `/health` as JSON in / JSON out, no transport and no database — which is why its 30 tests run on the dev host), `runner_host` (the `ctx.*` surface; links `vectorapi_core`). `src/main.cpp` is the only part that links the world and the only part the dev host cannot build. The QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
 - `api/` — `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` — `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` — design spec (esp. **Addendum A**) + the 3 implementation plans.
 
@@ -44,6 +45,19 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - TS: no `any`, no TS `enum`, no constructor parameter-property shorthand (tsconfig `erasableSyntaxOnly`). Iterating parsed JSON: bind to a named var first (range-for over `nlohmann::json::parse(...)[...]` dangles).
 - Commits: conventional prefixes (`feat`/`fix`/`build`/`docs`/`test`). Branch for feature work; `main` is pushed to `ssh://git.smartbotics.ai:10022/fszontagh/smartbotic-vectorapi.git`.
 
+## Function runtime (slice 1, in progress)
+
+- **A function is a principal, not a key holder** (`principal.hpp`). `requireCapabilityCore()` answers project/scope/rate-limit questions for any caller; the `ApiKey` overload adds the things only an HTTP request has (Origin allow-list, captcha), because those are meaningless for a cron or event run. One implementation, so function access and HTTP access cannot drift.
+- **A code push can never widen access.** `mergeForCodePush()` (`function_record.hpp`, pure) takes `policy` and `enabled` from the stored row and **never reads the ones in the payload** - not unioned, not used as a fallback. A first registration inherits the project default. Identity is `function_id` from the script's `on` block and `path` carries no meaning, so a rename keeps the row and its policy.
+- `builtinDefaultFunctionPolicy()` grants **nothing**: unreviewed code reaches no collection until an admin says so. Widening it is a security-posture change, and a test asserts the current floor.
+- **Descriptor parsing never throws** (`functions/descriptor.hpp`, pure): a script author's typo is data. Unknown keys are ignored so a script written for a later server still loads. 404 and 405 stay distinct, so a 405 can carry its `Allow:` union.
+- **Routes:** functions are managed at `/api/v1/projects/{p}/functions*` (project-manage; **policy is admin-only**) and served to the world at **`/fn/{project}/*`**, which is **unauthenticated** — the project segment is therefore hostile input: charset-restricted (no `:`, the `qualify()` separator), confirmed against `listProjects()` before anything qualifies a collection, and a `..` segment is refused anywhere (httplib percent-decodes before the handler sees the path, and `..` can be captured by a `:name` param). Disabled and invalid functions are absent from the descriptor list, so they 404 rather than 403, and function error text never reaches the caller — it goes to the run log, with the `run_id` in the response.
+- **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
+- **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
+- **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving — re-resolving IS the rebinding window. One resolution, one classification.
+- **`ctx.env` is empty and functions cannot hold a secret yet**: nothing has decided where a project's secrets live or who may read them, and an empty env is the only answer that cannot leak one. The one piece of slice 1 deliberately deferred.
+- **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A custom blocklist from settings *replaces* the defaults rather than extending them.
+
 ## Data model & runtime config
 
 - Bootstrap `config.json` is minimal: `log_level`, `http.{bind_address,port}`, `database.address`. Everything else lives in the DB and **hot-reloads** (subscribe + atomic snapshot swap).
@@ -63,6 +77,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
+- **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.
+- **QuickJS's job queue belongs to the `JSRuntime`, not the `JSContext`.** A fresh context per run is therefore *not* enough to isolate tenants: a run that times out mid-microtask leaves its jobs queued, and they would execute inside the next tenant's run. The core flushes them with the deadline forced into the past and marks the runtime `poisoned()` if anything survives; the pool destroys a poisoned runtime instead of leasing it out. An OOM poisons it too.
 - **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline — do not revert to the CDN loader.
 - systemd unit is `Type=notify`; the binary must be built with `libsystemd` (it is, when `libsystemd-dev` is present) or change to `Type=exec`.
 

+ 15 - 0
CMakeLists.txt

@@ -15,6 +15,12 @@ endif()
 
 option(BUILD_TESTS "Build tests" ON)
 option(BUILD_WEBUI "Build the React web UI via npm" ON)
+# The function runner vendors QuickJS over the network at configure time, so it
+# stays opt-in: an ordinary build and the whole existing test cycle must not
+# start depending on a GitHub fetch. Build it on its own with
+#   cmake -S runner -B build-runner
+# which also works on the dev host, where the root project cannot configure.
+option(BUILD_RUNNER "Build the QuickJS function runner" OFF)
 
 include(GNUInstallDirs)
 list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
@@ -49,6 +55,12 @@ if(BUILD_TESTS)
     add_subdirectory(tests)
 endif()
 
+# After the BUILD_TESTS block on purpose: runner/CMakeLists.txt registers tests,
+# which needs enable_testing() to have run already.
+if(BUILD_RUNNER)
+    add_subdirectory(runner)
+endif()
+
 if(BUILD_WEBUI)
     include(WebUI OPTIONAL)   # provided by plan 2; absent is fine
 endif()
@@ -56,6 +68,9 @@ endif()
 # Install: config conffile, api docs
 install(FILES ${CMAKE_SOURCE_DIR}/config/config.json
     DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/smartbotic-vectorapi)
+install(FILES ${CMAKE_SOURCE_DIR}/runner/config/runner.json
+    DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/smartbotic-vectorapi
+    OPTIONAL)
 install(FILES ${CMAKE_SOURCE_DIR}/api/openapi.json
               ${CMAKE_SOURCE_DIR}/api/llms.txt
     DESTINATION ${CMAKE_INSTALL_DATADIR}/smartbotic-vectorapi

+ 20 - 0
api/llms.txt

@@ -143,6 +143,26 @@ Precedence for one embedding call: the collection's own `embedding_model` wins,
 - `PUT  /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. An empty string is rejected with **422**. Setting `openai_api_base` without an `openai_api_key` for the same project is rejected with **422** `embedding_base_requires_key`, so the global credential is never sent to a foreign endpoint. A project key without a project base URL is allowed (own key, default endpoint).
 - `DELETE /api/v1/projects/{project}/settings/embeddings` - Drop every override; the project inherits the global settings again.
 
+## Functions
+
+Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
+
+**The id lives in the source, not in the URL.** A script exports `export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }`, and that `id` is the registry row's identity. `path` records where the author keeps the file and carries no meaning, so moving `kb-search.js` to `lib/search.js` keeps the same row - and the policy an admin granted travels with it.
+
+**Every write is compiled on a runner before it is stored.** The engine that validates is the engine that will execute. A compile failure is **422** `compile_failed` with the error; an `on` block with no id is **422** `missing_function_id`; no healthy runner is **503** `no_runner` and nothing is stored. Code is never stored unvalidated.
+
+**A code push can never widen access.** `policy` is server state: a `policy` field sent with a `POST`/`PUT` body is ignored (not merged, not consulted as a fallback), and `enabled` is likewise preserved, so re-pushing code does not re-enable a function an operator turned off. A first registration inherits the project's default policy, which currently grants **no collection at all** - the function runs, logs and can call out, but reaches no data until an admin grants it a rule.
+
+- `GET  /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}]}`.
+- `POST /api/v1/projects/{project}/functions` `{source, path?}` - Register a new function; the id comes from the validated `on` block, so there is no `function_id` field to send. An id already in use is **409** `function_exists` (PUT it to update).
+- `GET  /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
+- `PUT  /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
+- `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
+- `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
+- `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
+- `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
+- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, started_at}]}`. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
+
 ## Stats
 
 - `GET /api/v1/projects/{project}/stats` - Per-project stats (collections, document counts). Accessible to any key granted the project.

+ 518 - 0
api/openapi.json

@@ -14,6 +14,93 @@
       }
     },
     "schemas": {
+      "FunctionDescriptor": {
+        "type": "object",
+        "description": "The validated `on` block the script exports. Server-held: it is whatever the runner parsed out of the source, never sent by a client.",
+        "properties": {
+          "id": { "type": "string", "description": "The function's identity, declared in the source. The file path is incidental, so a rename carries the policy with it." },
+          "type": { "type": "string", "enum": ["http", "cron", "db"], "description": "Only `http` is dispatched in this release; the others parse so a newer script gets a clear message rather than being treated as a route." },
+          "route": { "type": "string", "description": "HTTP trigger: the path pattern, with `:name` segments captured into ctx.params" },
+          "method": { "type": "array", "items": { "type": "string" }, "description": "HTTP trigger: accepted methods, upper-cased. ABSENT means every method, not none." },
+          "schedule": { "type": "string", "description": "Cron trigger: validated for shape only; nothing schedules it yet" },
+          "table": { "type": "string", "description": "Database trigger: the collection watched" },
+          "event": { "type": "string", "enum": ["INSERT", "UPDATE", "DELETE"] },
+          "timeoutMs": { "type": "integer", "description": "Declared wall-clock budget. Omitted when the script did not declare one; a declared value is still clamped to the runner's configured maximum." },
+          "singleFlight": { "type": "boolean" }
+        },
+        "required": ["id", "type"]
+      },
+      "FunctionPolicy": {
+        "type": "object",
+        "description": "What a function may touch, in exactly the vocabulary API keys use - a function is a principal, not a key holder. Policy is SERVER state: it is set only by an admin through PUT .../functions/{id}/policy, and a `policy` field sent with a code push is ignored. An empty or absent rule set grants no collection at all, which is what a first registration inherits.",
+        "properties": {
+          "rules": {
+            "type": "array",
+            "items": { "$ref": "#/components/schemas/KeyScopeRule" },
+            "description": "A function reaches a collection only if a matching rule exists for the (collection, op) pair. Unlike a key scope, an empty array is legal: it is the deny-everything default."
+          },
+          "origins": { "type": "array", "items": { "type": "string" }, "description": "Unused for functions; carried because the policy shares the key-scope shape" },
+          "rate_limit_per_min": { "type": "integer", "minimum": 0, "description": "Maximum runs per minute. 0 means unlimited." },
+          "expires_at": { "type": "integer", "description": "Unix epoch seconds after which the policy is treated as expired. 0 means never." }
+        }
+      },
+      "FunctionSummary": {
+        "type": "object",
+        "description": "A registry row without its source. Listings return this shape so one response does not ship every function's whole body.",
+        "properties": {
+          "function_id": { "type": "string", "description": "Declared in the script's `on` block. Called `function_id`, not `id`, because the database client strips a top-level `id` from stored bodies." },
+          "path": { "type": "string", "description": "Where the author keeps the file. Carries no meaning: changing it keeps the same row, and the policy with it." },
+          "content_hash": { "type": "string", "description": "sha256 of the source, lower-case hex. The runner caches compiled bytecode by this." },
+          "descriptor": { "$ref": "#/components/schemas/FunctionDescriptor" },
+          "policy": { "$ref": "#/components/schemas/FunctionPolicy" },
+          "enabled": { "type": "boolean", "description": "Server state: re-pushing code never re-enables a function an operator turned off" },
+          "valid": { "type": "boolean" },
+          "last_error": { "type": "string" },
+          "created_at": { "type": "integer" },
+          "updated_at": { "type": "integer" }
+        },
+        "required": ["function_id", "descriptor", "policy", "enabled", "valid"]
+      },
+      "Function": {
+        "allOf": [
+          { "$ref": "#/components/schemas/FunctionSummary" },
+          {
+            "type": "object",
+            "properties": { "source": { "type": "string", "description": "The JavaScript as stored. Returned by the single-function GET only." } }
+          }
+        ]
+      },
+      "FunctionRun": {
+        "type": "object",
+        "description": "One recorded run. The log is append-only and trimmed to the newest N runs per function on every write, so an old run_id eventually stops resolving.",
+        "properties": {
+          "run_id": { "type": "string" },
+          "function_id": { "type": "string" },
+          "trigger": { "type": "string", "enum": ["http", "invoke"], "description": "`http` for a dispatched request, `invoke` for a manual POST .../invoke" },
+          "ok": { "type": "boolean" },
+          "status": { "type": "integer" },
+          "duration_ms": { "type": "integer" },
+          "error": { "type": "string" },
+          "console": { "type": "array", "items": { "type": "string" } },
+          "started_at": { "type": "integer", "description": "Unix epoch seconds" }
+        }
+      },
+      "FunctionRunResult": {
+        "type": "object",
+        "description": "What one run produced. The HTTP status of the invoke call reports whether the run could be PERFORMED; this envelope reports what the function did.",
+        "properties": {
+          "run_id": { "type": "string", "description": "Also the id of the run-log entry this invoke appended" },
+          "ok": { "type": "boolean" },
+          "status": { "type": "integer", "description": "The status the function returned" },
+          "headers": { "type": "object", "additionalProperties": { "type": "string" } },
+          "body": { "description": "Whatever the function returned; any JSON type, including null" },
+          "console": { "type": "array", "items": { "type": "string" } },
+          "duration_ms": { "type": "integer" },
+          "error": { "type": "string" },
+          "timed_out": { "type": "boolean" },
+          "out_of_memory": { "type": "boolean" }
+        }
+      },
       "ProjectEmbeddingSettings": {
         "type": "object",
         "description": "Three views of a project's embedding configuration. In overrides, an empty string means the field is inherited.",
@@ -1530,6 +1617,437 @@
         }
       }
     },
+    "/api/v1/projects/{project}/functions": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        }
+      ],
+      "get": {
+        "summary": "List this project's functions, without their sources",
+        "operationId": "listFunctions",
+        "responses": {
+          "200": {
+            "description": "Function list",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "functions": { "type": "array", "items": { "$ref": "#/components/schemas/FunctionSummary" } }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" }
+        }
+      },
+      "post": {
+        "summary": "Register a new function. The source is compiled on a runner BEFORE it is stored, and its id comes from the script's `on` block - not from this request.",
+        "description": "The id is read from the validated descriptor, so there is no `function_id` field to send. A `policy` field is ignored: policy is server state, changed only by an admin through PUT .../functions/{id}/policy. A first registration inherits the project's default policy, which currently grants no collection at all.",
+        "operationId": "createFunction",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "source": { "type": "string", "description": "The JavaScript module. Must export an `on` object declaring at least an id." },
+                  "path": { "type": "string", "description": "Where the author keeps the file. Stored as-is and never used as an identity." }
+                },
+                "required": ["source"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "201": {
+            "description": "Function stored",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "409": {
+            "description": "A function with this id already exists (code function_exists) - PUT it to update",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "422": {
+            "description": "The source did not compile (code compile_failed), the `on` block declares no id (code missing_function_id), or `source` is missing (code validation)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner to validate against (code no_runner / runner_unreachable). Code is never stored unvalidated.",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "get": {
+        "summary": "Get one function, including its source",
+        "operationId": "getFunction",
+        "responses": {
+          "200": {
+            "description": "The function",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Function" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" }
+        }
+      },
+      "put": {
+        "summary": "Push code to this function. Validated on a runner first, and the stored policy and enabled flag are preserved - a code push can never widen access.",
+        "description": "The id in the URL must equal the id the script declares; a mismatch is 422 rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (201).",
+        "operationId": "updateFunction",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "source": { "type": "string" },
+                  "path": { "type": "string" }
+                },
+                "required": ["source"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Function updated",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "201": {
+            "description": "Function registered (the id was unused)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "422": {
+            "description": "The source did not compile (code compile_failed), declares no id (code missing_function_id), or declares an id other than the one in the URL (code id_mismatch, with details.declared and details.url)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner to validate against (code no_runner / runner_unreachable)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      },
+      "delete": {
+        "summary": "Delete a function, its code and its policy",
+        "operationId": "deleteFunction",
+        "responses": {
+          "200": {
+            "description": "Deleted",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": { "deleted": { "type": "string" } }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/policy": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "put": {
+        "summary": "Replace what this function may touch (ADMIN ONLY). The only route that changes a policy.",
+        "description": "Developers push code, admins grant access - the same split API keys already have, which is why this route is admin-only while the rest of the function routes are not. An empty rule set is accepted and means the function reaches no collection.",
+        "operationId": "setFunctionPolicy",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "description": "Either {\"policy\": {...}} or the policy object itself.",
+                "properties": { "policy": { "$ref": "#/components/schemas/FunctionPolicy" } }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Policy replaced",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires an admin key" },
+          "404": { "description": "No such function" },
+          "422": {
+            "description": "Malformed policy: a rule without a collection or ops, or an unknown op (code validation)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/enabled": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "put": {
+        "summary": "Enable or disable a function. Server state: a later code push does not re-enable it.",
+        "operationId": "setFunctionEnabled",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": { "enabled": { "type": "boolean" } },
+                "required": ["enabled"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Updated",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "function_id": { "type": "string" },
+                    "enabled": { "type": "boolean" }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "422": { "description": "`enabled` missing or not a boolean (code validation)" }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/invoke": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "post": {
+        "summary": "Run a function once with a synthesised trigger, and record the run",
+        "description": "Every field of the body is optional: an empty body invokes the function with its own route as the path and POST as the method. The call answers 200 whenever the run was PERFORMED, even if the function itself failed - its status, error and console output are in the envelope. The run is appended to the function's log either way.",
+        "operationId": "invokeFunction",
+        "requestBody": {
+          "required": false,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "method": { "type": "string", "description": "Defaults to POST" },
+                  "path": { "type": "string", "description": "Defaults to the route the descriptor declares" },
+                  "params": { "type": "object", "description": "ctx.params - what a real route match would have captured", "additionalProperties": { "type": "string" } },
+                  "query": { "type": "object", "description": "ctx.query", "additionalProperties": { "type": "string" } },
+                  "headers": { "type": "object", "additionalProperties": { "type": "string" } },
+                  "body": { "description": "ctx.body; any JSON type" }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "The run was performed; the envelope says what the function did",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionRunResult" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "409": {
+            "description": "The function is disabled (code function_disabled) or marked invalid (code function_invalid)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner (code no_runner), or no runner could be reached for this run (code runner_unreachable, with details.run_id - the failed attempt is still logged)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/logs": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "get": {
+        "summary": "This function's recorded runs, newest first",
+        "description": "The log keeps only the newest N runs per function (trimmed on every write), so a limit above N returns N.",
+        "operationId": "listFunctionRuns",
+        "parameters": [
+          {
+            "name": "limit",
+            "in": "query",
+            "required": false,
+            "schema": { "type": "integer", "minimum": 1 },
+            "description": "Maximum runs to return; defaults to 50 and is clamped to how many the server keeps"
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "Run log",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "function_id": { "type": "string" },
+                    "runs": { "type": "array", "items": { "$ref": "#/components/schemas/FunctionRun" } }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "422": { "description": "`limit` is not a positive integer (code validation)" }
+        }
+      }
+    },
     "/api/v1/settings": {
       "get": {
         "summary": "Get current settings (admin only); openai_api_key is masked to a boolean openai_api_key_set",

+ 311 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -0,0 +1,311 @@
+# Function runtime (QuickJS) - design
+
+Server-side JavaScript in smartbotic-vectorapi: user-supplied functions that
+serve HTTP routes, and later run on a schedule or on database events.
+
+Status: approved 2026-10-06. This document is the contract for implementation.
+
+## Why
+
+n8n covers orchestration well, but two things it cannot do: react to database
+changes (only vectorapi holds the `subscribe()` streams), and run logic next to
+the data (a chunk-embed-upsert loop costs one HTTP hop per item through n8n).
+
+## Shape
+
+```
+person / LLM ──POST /projects/{p}/functions──▶ vectorapi
+                                                 │ validate on a runner, then store
+                                                 ▼
+                                      <project>:vectorapi_functions
+                                                 │
+ HTTP request ──▶ route match ──dispatch(sync)──▶ ┌──────────┐
+                                                  │  runner  │  QuickJS pool
+ cron / DB event ──▶ enqueue ──claim──▶ job queue │  (N inst)│  reads registry + data itself
+                                                  └────┬─────┘
+                                                       ▼
+                                             smartbotic-database
+```
+
+The runner is a second binary in this repo linking `vectorapi_core`. It holds
+its own `DbGateway`, so `ctx.collections(...)` is a direct call - never loopback
+HTTP to vectorapi - and it enforces policy with the same `KeyScope` code
+vectorapi uses. One implementation of authorization, two processes.
+
+vectorapi does NOT link QuickJS.
+
+## Identity and policy
+
+A function is a principal, not a key holder. No secret: it never authenticates
+over the wire, it *is* the server.
+
+```cpp
+struct FunctionIdentity { std::string project; std::string id; KeyScope scope; };
+```
+
+- **`id` is declared in the script** (`export const on = { id: 'kb-search', ... }`).
+  The file path is incidental, so renames and moves carry the policy with them.
+  Duplicate ids fail the load (both marked invalid). A missing id is an error,
+  never a silent path fallback.
+- **Policy is server state**, stored on the function's registry row and edited by
+  an admin. Pushing code can never widen access.
+- **First registration inherits** `default_function_policy` from the project's
+  settings document (beside the per-project embedding overrides).
+- A function whose source is removed keeps its row marked `missing` rather than
+  being deleted, so a mistake cannot silently drop a policy.
+
+### The Principal refactor
+
+`requireCapability()` today takes an `ApiKey`. It becomes:
+
+```cpp
+struct Principal { std::vector<std::string> projects; bool admin; const KeyScope* scope; };
+```
+
+with `ApiKey` and `FunctionIdentity` both convertible to it. This is the only
+way function access and HTTP access cannot drift apart. Mechanical but broad: it
+touches every handler's auth call.
+
+## The ctx.* surface
+
+Mirrors vectorapi's own concepts and its documented `field:op:value` filter
+grammar, so knowledge transfers from the HTTP API.
+
+```js
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+
+export default async function (ctx) {
+  const docs = await ctx.collections('kb_chunks')
+      .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
+  const hits = await ctx.collections('kb_chunks')
+      .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
+  await ctx.collections('audit').insert({ topic: ctx.params.topic });
+  return { status: 200, body: { docs, hits } };
+}
+```
+
+- documents: `.filter() .limit() .offset() .sort()` then
+  `.find() .get(id) .insert(doc) .update(id, doc) .patch(id, fields) .delete(id)`
+- vectors: `.search({query_text|query_vector, top_k, min_score, filters})`,
+  `.store({text|vector, metadata})` - embedding resolves through the existing
+  precedence, so a project's provider override applies
+- `ctx.env` (secrets), `ctx.fetch` (SSRF-guarded egress), `ctx.log`
+- NOT in slice 1: filesystem, storage
+
+Host calls are synchronous; `await` works because awaiting a non-promise is a
+no-op. The ergonomic builder is a JS prelude over a few native bindings
+(`__hostDb`, `__hostFetch`), keeping common logic in C++ and scripts small.
+
+`ctx.*` makes no loopback HTTP call. `.search({query_text})` does make an
+OUTBOUND call to the embedding provider - that is not loopback.
+
+## Storage
+
+One document per function in `<project>:vectorapi_functions`:
+
+```
+{ function_id, path, source, content_hash, descriptor, policy,
+  enabled, valid, last_error, created_at, updated_at }
+```
+
+`function_id`, not `id`: the database client strips a top-level `id` from stored
+bodies (the same reason API keys store `key_id`).
+
+## HTTP surface
+
+| Route | Who |
+|---|---|
+| `GET/POST /api/v1/projects/{p}/functions` | project-manage |
+| `GET/PUT/DELETE .../functions/{id}` | project-manage |
+| `PUT .../functions/{id}/policy` | **admin** |
+| `PUT .../functions/{id}/enabled` | project-manage |
+| `POST .../functions/{id}/invoke` | project-manage |
+| `GET .../functions/{id}/logs` | project-manage |
+
+Code and capability are split on purpose: developers write functions, admins
+grant what they may touch - mirroring keys, which are already admin-only.
+
+**Validation runs on a runner**, not in vectorapi: a write is compiled and its
+`on` block parsed before storage, and rejected with the compile error otherwise.
+The engine that validates is therefore the engine that will execute. Creating a
+function with no healthy runner returns 503.
+
+## Runner protocol
+
+Runner discovery is a static list in vectorapi's config, health-checked.
+Dynamic registration waits until autoscaling actually exists.
+
+HTTP functions, synchronous, retried on the next healthy runner:
+
+```
+POST /run  { project, function_id, trigger:{method,path,params,query,headers,body} }
+    ->     { status, headers, body, console[], duration_ms, error? }
+POST /validate { source, path }  -> { ok, descriptor?, error? }
+GET  /health
+```
+
+The payload is small because the runner reads source, `content_hash` and policy
+from the registry itself and caches compiled bytecode by hash.
+
+Cron and DB-event jobs go through one global `vectorapi_function_jobs`
+collection with a `project` field:
+
+```
+{ project, function_id, trigger, state: pending|claimed|done|failed,
+  claimed_by, claimed_at, attempts, depth, run_after }
+```
+
+A runner claims with `updateIfVersion()`; a version conflict means another
+runner won it. A claim older than a timeout returns to `pending`, which is how a
+runner dying mid-job gets retried elsewhere.
+
+The **scheduler stays in vectorapi**: there must be exactly one, or N runners
+each fire every cron. vectorapi is already the singleton and already holds the
+subscribe streams DB events will need.
+
+## Safety
+
+- Per-run limits: memory, wall time (descriptor `timeoutMs`, clamped to a
+  configured max), stack. A fresh `JSContext` per run so nothing leaks between
+  tenants. The pool recycles a runtime whose allocation stays high.
+- SSRF guard: CIDR blocklist from settings with built-in defaults, DNS resolve
+  then classify every returned address, fail closed on unparseable input. It
+  blocks loopback, so a function cannot call its own API. Intentional.
+- `rateLimitPerMin` already exists in `KeyScope` and applies unchanged.
+- The job record carries `depth` from day one, though nothing reads it until DB
+  events land: retrofitting a self-trigger guard is how you get an infinite loop
+  in production.
+
+## Slice 1
+
+**In**: runner binary (pool, host context, policy enforcement, `/run`,
+`/validate`, `/health`), functions CRUD, HTTP dispatch on route match, manual
+invoke, run logs.
+
+**Out**, each its own later cycle: cron, DB events, shared modules (needs a
+module loader with path jailing - a security boundary, not a convenience),
+filesystem, storage API, git export.
+
+## Testing
+
+Unit: descriptor parsing, route matching, policy enforcement, limit enforcement,
+SSRF classification. Integration through `packaging/devstack`, extended to run a
+runner alongside: deploy a function, call it, then assert the things that must
+FAIL - a denied collection, a wall-time timeout, a blocked egress.
+
+## Risks
+
+- Two binaries that must version together, the same discipline as the client ABI
+  pin.
+- The `Principal` refactor is broad, touching every handler's auth call.
+- HTTP functions gain a network hop; measure the latency before anyone builds a
+  chatty endpoint on it.
+
+## Addendum: slice-1 implementation decisions
+
+Recorded as they were settled, because each one either corrects the design
+above or fills a gap it left open.
+
+**The job queue correction.** "A fresh `JSContext` per run so nothing leaks
+between tenants" is not sufficient: QuickJS keeps the microtask queue on the
+`JSRuntime`. A run that times out mid-microtask leaves jobs queued, and they
+would execute inside the *next* tenant's run. The core flushes them with the
+deadline forced into the past, and marks the runtime poisoned if anything
+survives; the pool destroys a poisoned runtime rather than leasing it. This is
+the one rule the implementation adds that the design did not state.
+
+**The Principal refactor is narrower than estimated.** The design calls it
+"mechanical but broad: it touches every handler's auth call". It touches none.
+`requireCapability()` split into a transport-free core plus an HTTP wrapper that
+keeps the Origin and captcha checks, so the 32 existing call sites are unchanged.
+The broad-refactor risk listed below did not materialise.
+
+**The default policy floor grants nothing.** `builtinDefaultFunctionPolicy()`
+returns an empty `KeyScope`: a newly registered function can run, log and call
+out, but reaches no collection until an admin grants one. The failure mode of
+the permissive choice is silent - a function quietly reading data nobody meant
+to expose looks exactly like a function that works. Marked `TODO(policy)` for
+confirmation, since it trades real developer friction for that.
+
+**A code push ignores, rather than validates, an incoming policy.** A
+validating version would have to answer "is this narrower than what is stored?",
+and subset-checking a glob-and-op-set grammar is where a privilege escalation
+bug would live. Ignoring the field has no such failure mode.
+
+**QuickJS: quickjs-ng, pinned to an exact tag.** Bytecode carries no version
+stamp, so an upgrade makes a cached blob misread rather than fail. `JsBytecode`
+is an in-process cache only; persisting it would need a build fingerprint.
+
+**The runner does not link `vectorapi_core` yet.** The design says it does. The
+execution core deliberately links neither it nor the database client, which is
+what lets it build and test on the dev host. The host-binding workstream adds a
+target that links both on top of `runner_core`; it does not move the dependency
+into the core.
+
+**`BUILD_RUNNER` is off by default.** The runner vendors QuickJS over the
+network at configure time, and neither an ordinary build nor the existing test
+cycle may start depending on a GitHub fetch.
+
+### Still open
+
+- **Status mapping at the dispatch edge.** `timed_out` and `out_of_memory` are
+  classified, but nothing says what HTTP status each becomes. `errors.hpp`
+  currently has no 504.
+- **The SSRF replace-vs-union question.** A custom blocklist replaces the
+  built-in defaults, so adding one CIDR silently unblocks loopback, RFC1918 and
+  the cloud metadata endpoint. The alternative is always-union plus an explicit
+  opt-out.
+- **TOCTOU on `ctx.fetch`.** The guard resolves the name and the HTTP client
+  resolves it again. `ctx.fetch` must connect to the approved address with a
+  `Host:` override, and must ignore `http_proxy`/`https_proxy`, or the rebinding
+  window stays open.
+- **Return shape** of the default export, and who validates it.
+- **Unhandled rejections** in background microtasks after the handler returned.
+
+## Slice 1: what shipped
+
+Complete and green at 399/399 in the Debian 13 container with
+`BUILD_RUNNER=ON`: the Principal refactor, descriptor parsing and route
+matching, the SSRF guard, the function registry with policy as server state,
+the QuickJS engine and pool, the runner service (`ctx.*`, `/run`, `/validate`,
+`/health`, the binary), functions CRUD, HTTP dispatch at `/fn/{project}/*`,
+manual invoke, and run logs.
+
+**Deferred, and the only piece of slice 1 that did not ship: `ctx.env`.** The
+field exists and is always empty. Nothing in the design decides where a
+project's secrets are stored or who may read them, and an empty env is the only
+answer that cannot leak one. Two independent implementations arrived at the same
+refusal to guess. A function therefore cannot hold a credential, which also
+means `ctx.fetch` can currently only reach endpoints that need none. This wants
+its own cycle, next to the per-project embedding key that already exists.
+
+### Resolved from "Still open"
+
+- **Status mapping.** A function that threw → 500 (from the caller's side we
+  *are* the server; the runner is an implementation detail, not an upstream the
+  client asked us to proxy). Wall-time timeout → **504**, which needed a new
+  `ErrCode::GatewayTimeout`. Out of memory → 500, not 503: a per-run ceiling
+  breach is deterministic, so "come back later" would be a lie. No healthy
+  runner → 503 with `Retry-After`.
+- **Return shape.** An object whose keys are a non-empty subset of
+  `{status, headers, body}` is an envelope; anything else is the body of a 200;
+  an object that MIXES them fails the run. Both lenient and strict readings of
+  `{status: 200, docs: []}` are wrong and the strict one fails silently, which
+  is the bug `documentBody()` already fixed once.
+- **TOCTOU on `ctx.fetch`.** Closed. A hostname resolves exactly once and the
+  connection is pinned to a checked address.
+- **The SSRF replace-vs-union question.** Still open, and still a replace.
+
+### Newly open
+
+- **The runner has no authentication** and binds `127.0.0.1`. `RunnerPool` sends
+  no credential, so none was invented. This needs deciding before runners ever
+  sit on a shared network - which was the stated reason for making the runner a
+  separate service.
+- `listProjects()` runs on every `/fn/*` request: a database round trip on the
+  hot path, and the first thing to cache once anyone measures this.
+- `JsLimits` is fixed at construction, unlike every other setting in this
+  codebase, which hot-reloads. Changing the wall-time ceiling needs a restart.
+- Repeated query keys (`?tag=a&tag=b`) collapse to the last value, because the
+  trigger's `query` is an object. Widening it is a protocol change on both sides.
+- `HEAD` on `/fn/*` is unroutable: cpp-httplib has no `Server::Head` registrar.

+ 6 - 1
packaging/devstack/run-tests.sh

@@ -20,6 +20,9 @@ DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.11.4-1_amd64.deb}"
 CLIENT_DEV_DEB="${CLIENT_DEV_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client-dev_2.11.4-1_amd64.deb}"
 CLIENT_DEB="${CLIENT_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client_2.11.4-1_amd64.deb}"
 FILTER="${1:-}"
+# BUILD_RUNNER=ON also builds and tests the QuickJS runner. Off by default
+# because it vendors QuickJS from GitHub at configure time.
+BUILD_RUNNER="${BUILD_RUNNER:-OFF}"
 
 docker image inspect "$BASE_IMAGE" >/dev/null 2>&1 || {
     echo "base image $BASE_IMAGE missing; build it with packaging/build.sh --rebuild-base" >&2
@@ -37,6 +40,7 @@ docker run --rm \
     -v "$CLIENT_DEB:/tmp/client.deb:ro" \
     -v "$CLIENT_DEV_DEB:/tmp/client-dev.deb:ro" \
     -e "CTEST_FILTER=$FILTER" \
+    -e "BUILD_RUNNER=$BUILD_RUNNER" \
     "$BASE_IMAGE" bash -euo pipefail -c '
         apt-get update -qq >/dev/null
         apt-get install -y -qq --no-install-recommends \
@@ -51,7 +55,8 @@ docker run --rm \
         (exec 3<>/dev/tcp/127.0.0.1/9004) 2>/dev/null || { echo "database never came up:"; tail -20 /tmp/db.log; exit 1; }
 
         cmake -B /build -G Ninja -DCMAKE_BUILD_TYPE=Release \
-              -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF -S /src
+              -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF \
+              -DBUILD_RUNNER="${BUILD_RUNNER}" -S /src
         cmake --build /build -j"$(nproc)"
         if [[ -n "${CTEST_FILTER:-}" ]]; then
             ctest --test-dir /build --output-on-failure -R "$CTEST_FILTER"

+ 178 - 0
runner/CMakeLists.txt

@@ -0,0 +1,178 @@
+# The function runner's execution core.
+#
+# This directory builds two ways: as a subdirectory of the root project, and as
+# a project of its own (`cmake -S runner -B build-runner`). The second is how it
+# gets built and tested on the dev host, where the root project cannot configure
+# at all because smartbotic-db-client is unbuildable there (see CLAUDE.md).
+if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
+    cmake_minimum_required(VERSION 3.20)
+    project(smartbotic-vectorapi-runner LANGUAGES C CXX)
+    set(CMAKE_CXX_STANDARD 20)
+    set(CMAKE_CXX_STANDARD_REQUIRED ON)
+    set(CMAKE_CXX_EXTENSIONS OFF)
+    if(NOT CMAKE_BUILD_TYPE)
+        set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type" FORCE)
+    endif()
+    option(BUILD_TESTS "Build tests" ON)
+    enable_testing()
+endif()
+
+# QuickJS is C, and the root project declares CXX only.
+enable_language(C)
+
+#
+# Deliberately self-contained: it links neither vectorapi_core nor
+# smartbotic-db-client, so it configures, builds and tests on the dev host whose
+# protobuf is too new for the database client (see CLAUDE.md gotchas). The
+# host-binding workstream that does need the gateway links THAT on top of this
+# target, it does not move the dependency in here.
+
+include(FetchContent)
+
+# quickjs-ng rather than Bellard's quickjs: it ships a real CMake build, exports
+# the module/promise/bytecode entry points we need as public API
+# (JS_GetModuleNamespace, JS_PromiseState, JS_SetMaxStackSize), builds clean
+# under a C++ TU's expectations, and is the variant that is actually maintained.
+# Pinned to an exact tag - bytecode has no version stamp, so a silent QuickJS
+# upgrade would make cached blobs misread.
+set(SVAPI_QUICKJS_TAG "v0.17.0" CACHE STRING "quickjs-ng git tag to vendor")
+
+set(QJS_ENABLE_INSTALL OFF CACHE BOOL "" FORCE)   # quickjs must not land in our .deb
+set(QJS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
+set(QJS_BUILD_LIBC OFF CACHE BOOL "" FORCE)       # no std/os modules: slice 1 has no filesystem
+set(QJS_BUILD_CLI_WITH_MIMALLOC OFF CACHE BOOL "" FORCE)
+set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
+
+# quickjs-ng adds qjs/qjsc/api-test unconditionally; EXCLUDE_FROM_ALL keeps them
+# out of our default build. The guard is for CMake < 3.28, where the option does
+# not exist yet and the extra targets are merely wasted build time.
+if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
+    FetchContent_Declare(quickjs
+        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
+        GIT_TAG        ${SVAPI_QUICKJS_TAG}
+        GIT_SHALLOW    TRUE
+        EXCLUDE_FROM_ALL)
+else()
+    FetchContent_Declare(quickjs
+        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
+        GIT_TAG        ${SVAPI_QUICKJS_TAG}
+        GIT_SHALLOW    TRUE)
+endif()
+FetchContent_MakeAvailable(quickjs)
+
+# Found by the root project already; the guard is what makes this directory
+# usable on its own.
+if(NOT TARGET nlohmann_json::nlohmann_json)
+    find_package(nlohmann_json REQUIRED)
+endif()
+
+add_library(runner_core STATIC
+    src/js_runtime.cpp)
+target_include_directories(runner_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
+target_link_libraries(runner_core PUBLIC nlohmann_json::nlohmann_json PRIVATE qjs)
+target_compile_features(runner_core PUBLIC cxx_std_20)
+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.
+    if(NOT TARGET GTest::gtest_main)
+        find_package(GTest QUIET)
+        if(NOT GTest_FOUND)
+            message(STATUS "GTest not found on the system - fetching googletest")
+            FetchContent_Declare(googletest
+                GIT_REPOSITORY https://github.com/google/googletest.git
+                GIT_TAG        v1.15.2)
+            set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
+            FetchContent_MakeAvailable(googletest)
+        endif()
+    endif()
+    include(GoogleTest)
+
+    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

+ 205 - 0
runner/include/runner/js_runtime.hpp

@@ -0,0 +1,205 @@
+#pragma once
+#include <nlohmann/json.hpp>
+
+#include <condition_variable>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+/// QuickJS execution core for the function runner.
+///
+/// The contract is docs/superpowers/specs/2026-10-06-function-runtime-design.md
+/// ("Safety"): per-run memory, wall-time and stack limits, and a fresh
+/// `JSContext` per run so nothing leaks between tenants. QuickJS itself is kept
+/// behind a pimpl so no other translation unit in the runner has to see
+/// quickjs.h - and so vectorapi, which must not link QuickJS at all, could
+/// still include this header if it ever needed the types.
+namespace svapi::runner {
+
+/// Per-run ceilings. `wall_time_ms` is the configured maximum, not a default a
+/// descriptor can raise: run()'s override is clamped to it.
+struct JsLimits {
+    size_t memory_limit_bytes = 128u * 1024 * 1024;
+    int64_t wall_time_ms = 2000;
+    size_t max_stack_bytes = 512u * 1024;
+};
+
+/// A compiled module, serialised as QuickJS bytecode. The runner caches these
+/// by `content_hash`, so the representation has to be a plain byte blob.
+///
+/// The blob is only portable across processes running the SAME QuickJS build on
+/// the same architecture - QuickJS stamps no version into it and will happily
+/// misread a foreign blob. It is a cache, never a storage format: the registry
+/// keeps `source`.
+struct JsBytecode {
+    std::vector<uint8_t> bytes;
+    bool empty() const { return bytes.empty(); }
+};
+
+/// Outcome of one run. `timed_out` and `out_of_memory` are classified rather
+/// than folded into `error`, because the HTTP layer maps them to different
+/// statuses and an operator needs to tell a slow function from a broken one.
+struct JsResult {
+    bool ok = false;
+    nlohmann::json value;
+    std::string error;
+    std::vector<std::string> console_output;
+    bool timed_out = false;
+    bool out_of_memory = false;
+    int64_t duration_ms = 0;
+};
+
+/// Handles for a host-binding implementation, as opaque pointers so this header
+/// stays free of QuickJS types. `js_context` is a `JSContext*`; `ctx_object`
+/// points at the `JSValue` run() is about to pass to the default export, owned
+/// by run() and valid only for the duration of the install call.
+struct JsBindingTarget {
+    void* js_context = nullptr;
+    void* ctx_object = nullptr;
+};
+
+/// Extension point for the workstream that adds `ctx.collections`, `ctx.fetch`
+/// and `ctx.env`. It exists now only so run()'s signature does not have to
+/// change later; this file deliberately ships no implementation of it.
+class JsHostBindings {
+public:
+    virtual ~JsHostBindings() = default;
+
+    /// Decorate the ctx object for one run. Returning false with `error` set
+    /// fails the run before any user code executes.
+    virtual bool install(const JsBindingTarget& target, std::string& error) = 0;
+};
+
+/// One QuickJS runtime. Not thread-safe: QuickJS allows a runtime to be used
+/// from one thread at a time, which is what JsRuntimePool guarantees.
+class JsRuntime {
+public:
+    explicit JsRuntime(JsLimits limits = {});
+    ~JsRuntime();
+
+    JsRuntime(const JsRuntime&) = delete;
+    JsRuntime& operator=(const JsRuntime&) = delete;
+
+    /// Compile `source` as an ES module. `filename` only shows up in
+    /// diagnostics, so it should be whatever the operator will recognise.
+    std::optional<JsBytecode> compile(std::string_view source, const std::string& filename,
+                                      std::string& error_out);
+
+    /// Evaluate the module in a FRESH context and call its default export with
+    /// `ctx_arg`, awaiting the result. `wall_time_override_ms` > 0 narrows the
+    /// deadline and is clamped to `limits().wall_time_ms`.
+    JsResult run(const JsBytecode& bytecode, const nlohmann::json& ctx_arg,
+                 int64_t wall_time_override_ms = 0, JsHostBindings* host = nullptr);
+
+    /// Evaluate the module in a fresh context and read one named export WITHOUT
+    /// calling the default export. This is how a function's `on` descriptor is
+    /// read, so it must never execute the handler body. A declared-but-missing
+    /// export yields a null json, not an error.
+    std::optional<nlohmann::json> readExport(const JsBytecode& bytecode,
+                                             const std::string& export_name,
+                                             std::string& error_out);
+
+    /// Bytes currently held by the runtime's allocator, as QuickJS accounts
+    /// them. The pool uses this to decide whether to recycle.
+    size_t mallocBytes() const;
+
+    /// Force a full GC. The pool calls this before judging mallocBytes(),
+    /// because a finished run leaves its realm unreachable but not collected.
+    void collectGarbage();
+
+    /// Re-anchor QuickJS's stack-overflow detection to the calling thread.
+    /// A runtime records the stack top when it is created, so a pooled runtime
+    /// handed to a different thread would otherwise mis-measure the stack.
+    void updateStackTop();
+
+    /// True when this runtime must not serve another tenant: a run left
+    /// microtasks queued (the job queue lives on the runtime, not the context,
+    /// so a fresh context cannot clear it) or the allocator hit its limit.
+    bool poisoned() const;
+
+    const JsLimits& limits() const;
+
+private:
+    struct Impl;
+    std::unique_ptr<Impl> impl_;
+};
+
+/// Fixed-size pool of runtimes. Runtimes are pooled, contexts never are.
+class JsRuntimePool {
+public:
+    /// RAII lease. Holding one is what gives a thread exclusive use of a
+    /// runtime; dropping it hands the runtime back (or retires it).
+    class Lease {
+    public:
+        Lease() = default;
+        ~Lease();
+        Lease(Lease&& other) noexcept;
+        Lease& operator=(Lease&& other) noexcept;
+        Lease(const Lease&) = delete;
+        Lease& operator=(const Lease&) = delete;
+
+        JsRuntime& operator*() const { return *runtime_; }
+        JsRuntime* operator->() const { return runtime_; }
+        bool valid() const { return runtime_ != nullptr; }
+
+        /// Hand the runtime back early.
+        void release();
+
+    private:
+        friend class JsRuntimePool;
+        Lease(JsRuntimePool* pool, std::unique_ptr<JsRuntime> runtime);
+
+        JsRuntimePool* pool_ = nullptr;
+        JsRuntime* runtime_ = nullptr;
+        std::unique_ptr<JsRuntime> owned_;
+    };
+
+    /// `recycle_above_bytes` == 0 means half of `limits.memory_limit_bytes`:
+    /// a runtime still holding that much after a GC is discarded instead of
+    /// being handed on, so one greedy run cannot degrade every later tenant.
+    explicit JsRuntimePool(size_t size, JsLimits limits = {}, size_t recycle_above_bytes = 0);
+    ~JsRuntimePool();
+
+    JsRuntimePool(const JsRuntimePool&) = delete;
+    JsRuntimePool& operator=(const JsRuntimePool&) = delete;
+
+    /// Block until a runtime is free, then hand it out stack-top-corrected for
+    /// the calling thread.
+    Lease acquire();
+
+    /// Change the target size. Growing is immediate; shrinking only discards
+    /// idle runtimes - an in-use one is retired when its lease is dropped.
+    void resize(size_t size);
+
+    /// Target size, which after a shrink can be below the number of runtimes
+    /// still leased out.
+    size_t size() const;
+
+    /// Runtimes sitting idle right now. Diagnostics only: it can be stale the
+    /// instant it returns.
+    size_t idle() const;
+
+    /// Runtimes thrown away since construction - poisoned, over the allocation
+    /// watermark, or surplus after a shrink. Worth exporting as a metric: a
+    /// climbing count means functions are leaving memory pinned.
+    size_t retired() const;
+
+private:
+    void give_back(std::unique_ptr<JsRuntime> runtime);
+
+    mutable std::mutex mutex_;
+    std::condition_variable cv_;
+    std::vector<std::unique_ptr<JsRuntime>> idle_;
+    size_t live_ = 0;     // created runtimes: idle plus leased out
+    size_t target_ = 0;
+    size_t retired_ = 0;
+    JsLimits limits_;
+    size_t recycle_above_bytes_ = 0;
+};
+
+} // 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(' '));
+  };
+})

+ 688 - 0
runner/src/js_runtime.cpp

@@ -0,0 +1,688 @@
+#include "runner/js_runtime.hpp"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cstring>
+#include <stdexcept>
+#include <utility>
+
+#include "quickjs.h"
+
+namespace svapi::runner {
+namespace {
+
+int64_t nowMs() {
+    using namespace std::chrono;
+    return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
+}
+
+/// Console capture is bounded: a function in a loop could otherwise turn
+/// console.log into an unmetered allocation channel, and the run result travels
+/// over HTTP to whoever invoked it.
+constexpr size_t kMaxConsoleLines = 1000;
+constexpr size_t kMaxConsoleBytes = 64u * 1024;
+
+/// How many pending jobs a timed-out run may be flushed with before the runtime
+/// is declared poisoned. Flushing happens with the deadline already expired, so
+/// each job is interrupted at its first bytecode op; the cap only bounds a
+/// module that keeps re-enqueueing from that interrupted frame.
+constexpr int kPoisonFlushBudget = 256;
+
+/// Per-run state, hung off the context. One context per run means this is
+/// created and destroyed with the run, which is exactly the lifetime we want.
+struct RunState {
+    std::vector<std::string> console;
+    size_t console_bytes = 0;
+    bool console_truncated = false;
+
+    void add(std::string line) {
+        if (console.size() >= kMaxConsoleLines || console_bytes >= kMaxConsoleBytes) {
+            if (!console_truncated) {
+                console_truncated = true;
+                console.emplace_back("[console output truncated]");
+            }
+            return;
+        }
+        console_bytes += line.size();
+        console.push_back(std::move(line));
+    }
+};
+
+/// Shared with the interrupt handler, which QuickJS may call from inside any JS
+/// frame - including one running under JS_ExecutePendingJob.
+struct RuntimeState {
+    std::atomic<int64_t> deadline_ms{0};  // 0 = no run in progress, no deadline
+    std::atomic<bool> interrupted{false};
+};
+
+int interruptHandler(JSRuntime*, void* opaque) {
+    auto* state = static_cast<RuntimeState*>(opaque);
+    const int64_t deadline = state->deadline_ms.load(std::memory_order_relaxed);
+    if (deadline == 0 || nowMs() < deadline) return 0;
+    state->interrupted.store(true, std::memory_order_relaxed);
+    return 1;  // unwinds the whole JS stack with an uncatchable-ish InternalError
+}
+
+std::string toText(JSContext* ctx, JSValueConst v) {
+    const char* s = JS_ToCString(ctx, v);
+    if (!s) {
+        JS_FreeValue(ctx, JS_GetException(ctx));  // stringification itself can throw
+        return "<unprintable>";
+    }
+    std::string out(s);
+    JS_FreeCString(ctx, s);
+    return out;
+}
+
+/// Format a thrown value the way an operator wants to read it: the message
+/// first, then the stack if QuickJS attached one.
+std::string formatThrown(JSContext* ctx, JSValue exc) {
+    std::string text;
+    if (JS_IsNull(exc) || JS_IsUndefined(exc)) {
+        // QuickJS throws a bare null when it could not even allocate the Error
+        // object, which in practice only happens under the memory limit.
+        text = "out of memory";
+    } else {
+        text = toText(ctx, exc);
+        if (JS_IsObject(exc)) {
+            JSValue stack = JS_GetPropertyStr(ctx, exc, "stack");
+            if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {
+                std::string st = toText(ctx, stack);
+                if (!st.empty()) text += "\n" + st;
+            }
+            JS_FreeValue(ctx, stack);
+        }
+    }
+    JS_FreeValue(ctx, exc);
+    return text;
+}
+
+std::string takeException(JSContext* ctx) { return formatThrown(ctx, JS_GetException(ctx)); }
+
+/// Values cross the boundary as JSON, which is also the only shape the registry
+/// and the HTTP protocol can carry. Non-serialisable values (functions,
+/// undefined) come back as null rather than failing the run.
+bool fromJs(JSContext* ctx, JSValueConst v, nlohmann::json& out, std::string& error) {
+    JSValue json = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
+    if (JS_IsException(json)) {
+        error = takeException(ctx);
+        JS_FreeValue(ctx, json);
+        return false;
+    }
+    if (JS_IsUndefined(json)) {  // undefined, a function, a symbol
+        JS_FreeValue(ctx, json);
+        out = nullptr;
+        return true;
+    }
+    const std::string text = toText(ctx, json);
+    JS_FreeValue(ctx, json);
+    out = nlohmann::json::parse(text, nullptr, false);
+    if (out.is_discarded()) {
+        error = "the returned value is not representable as JSON";
+        return false;
+    }
+    return true;
+}
+
+JSValue toJs(JSContext* ctx, const nlohmann::json& j) {
+    const std::string text = j.dump();
+    return JS_ParseJSON(ctx, text.c_str(), text.size(), "<ctx>");
+}
+
+/// console.log/warn/error. The level travels as a prefix because the protocol
+/// carries one flat `console[]` array and a timeout diagnosis usually hinges on
+/// whether the last line was an error.
+JSValue consoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int magic) {
+    auto* state = static_cast<RunState*>(JS_GetContextOpaque(ctx));
+    if (!state) return JS_UNDEFINED;
+
+    std::string line;
+    if (magic == 1) line = "[warn] ";
+    if (magic == 2) line = "[error] ";
+    for (int i = 0; i < argc; i++) {
+        if (i > 0) line += ' ';
+        // Objects as JSON, primitives as text: "[object Object]" in a log is
+        // worse than useless when debugging a function.
+        if (JS_IsObject(argv[i]) && !JS_IsFunction(ctx, argv[i])) {
+            JSValue json = JS_JSONStringify(ctx, argv[i], JS_UNDEFINED, JS_UNDEFINED);
+            if (!JS_IsException(json) && !JS_IsUndefined(json)) {
+                line += toText(ctx, json);
+                JS_FreeValue(ctx, json);
+                continue;
+            }
+            if (JS_IsException(json)) JS_FreeValue(ctx, JS_GetException(ctx));
+            JS_FreeValue(ctx, json);
+        }
+        line += toText(ctx, argv[i]);
+    }
+    state->add(std::move(line));
+    return JS_UNDEFINED;
+}
+
+void installConsole(JSContext* ctx) {
+    JSValue global = JS_GetGlobalObject(ctx);
+    JSValue console = JS_NewObject(ctx);
+    JS_SetPropertyStr(ctx, console, "log",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "log", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "info",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "info", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "debug",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "debug", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "warn",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "warn", 1, JS_CFUNC_generic_magic, 1));
+    JS_SetPropertyStr(ctx, console, "error",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "error", 1, JS_CFUNC_generic_magic, 2));
+    JS_SetPropertyStr(ctx, global, "console", console);
+    JS_FreeValue(ctx, global);
+}
+
+} // namespace
+
+struct JsRuntime::Impl {
+    JSRuntime* rt = nullptr;
+    JsLimits limits;
+    RuntimeState state;
+    bool poisoned = false;
+
+    /// Fresh context for one run or one descriptor read. Nothing a tenant can
+    /// reach survives this object, which is the whole point.
+    JSContext* newContext(RunState* run_state) {
+        JSContext* ctx = JS_NewContext(rt);
+        if (!ctx) return nullptr;
+        JS_SetContextOpaque(ctx, run_state);
+        installConsole(ctx);
+        return ctx;
+    }
+
+    void armDeadline(int64_t budget_ms) {
+        state.interrupted.store(false, std::memory_order_relaxed);
+        state.deadline_ms.store(nowMs() + budget_ms, std::memory_order_relaxed);
+    }
+
+    void disarmDeadline() { state.deadline_ms.store(0, std::memory_order_relaxed); }
+
+    bool expired() const {
+        const int64_t deadline = state.deadline_ms.load(std::memory_order_relaxed);
+        return deadline != 0 && nowMs() >= deadline;
+    }
+
+    bool interrupted() const { return state.interrupted.load(std::memory_order_relaxed); }
+
+    size_t mallocBytes() const {
+        JSMemoryUsage usage{};
+        JS_ComputeMemoryUsage(rt, &usage);
+        return static_cast<size_t>(usage.malloc_size);
+    }
+
+    /// An allocation failure may surface either as an InternalError carrying
+    /// "out of memory" or, when even that Error could not be allocated, as a
+    /// bare null. Neither is reliable on its own, so corroborate with the
+    /// allocator: close to the ceiling, an error is a memory error.
+    bool looksLikeOom(const std::string& error) const {
+        if (error.find("out of memory") != std::string::npos) return true;
+        return nearMemoryCeiling();
+    }
+
+    bool nearMemoryCeiling() const {
+        if (limits.memory_limit_bytes == 0) return false;
+        return mallocBytes() >= limits.memory_limit_bytes / 10 * 9;
+    }
+
+    /// Run queued microtasks until the queue drains or the deadline passes.
+    /// The C++ clock check only stops the LOOP; what stops a single job that
+    /// never returns is the interrupt handler firing inside it.
+    void drainJobs(std::string& job_error) {
+        while (JS_IsJobPending(rt)) {
+            if (expired() || interrupted()) return;
+            JSContext* job_ctx = nullptr;
+            const int rc = JS_ExecutePendingJob(rt, &job_ctx);
+            if (rc == 0) return;
+            if (rc < 0 && job_ctx && job_error.empty()) job_error = takeException(job_ctx);
+        }
+    }
+
+    /// Resolve `value` to a settled, non-promise value, draining microtasks as
+    /// needed. Consumes `value`.
+    JSValue await(JSContext* ctx, JSValue value, std::string& error) {
+        for (;;) {
+            std::string job_error;
+            drainJobs(job_error);
+
+            const JSPromiseStateEnum st = JS_PromiseState(ctx, value);
+            if (st == JS_PROMISE_NOT_A_PROMISE) {
+                if (!job_error.empty() && error.empty()) error = job_error;
+                return value;
+            }
+            if (st == JS_PROMISE_FULFILLED) {
+                JSValue inner = JS_PromiseResult(ctx, value);
+                JS_FreeValue(ctx, value);
+                value = inner;  // a promise resolving to a promise must be followed
+                continue;
+            }
+            if (st == JS_PROMISE_REJECTED) {
+                JS_PromiseMarkAsHandled(ctx, value);
+                JSValue reason = JS_PromiseResult(ctx, value);
+                JS_FreeValue(ctx, value);
+                error = formatThrown(ctx, reason);
+                return JS_UNDEFINED;
+            }
+            // Still pending with nothing left to run: either we ran out of time
+            // or the function returned a promise nobody will ever settle.
+            JS_PromiseMarkAsHandled(ctx, value);
+            JS_FreeValue(ctx, value);
+            if (error.empty()) {
+                error = interrupted() || expired()
+                            ? "wall-time limit exceeded"
+                            : (job_error.empty() ? "the returned promise never settled" : job_error);
+            }
+            return JS_UNDEFINED;
+        }
+    }
+
+    /// Instantiate and evaluate module bytecode in `ctx`. Returns the module
+    /// definition, or nullptr with `error` set.
+    JSModuleDef* evaluateModule(JSContext* ctx, const JsBytecode& bytecode, std::string& error) {
+        JSValue obj = JS_ReadObject(ctx, bytecode.bytes.data(), bytecode.bytes.size(),
+                                    JS_READ_OBJ_BYTECODE);
+        if (JS_IsException(obj)) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, obj);
+            return nullptr;
+        }
+        if (!JS_IsModule(obj)) {
+            JS_FreeValue(ctx, obj);
+            error = "the compiled artifact is not an ES module";
+            return nullptr;
+        }
+        if (JS_ResolveModule(ctx, obj) < 0) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, obj);
+            return nullptr;
+        }
+        auto* module = static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(obj));
+
+        // JS_EvalFunction consumes obj and, because a module may top-level
+        // await, hands back a promise rather than a finished evaluation.
+        JSValue eval_result = JS_EvalFunction(ctx, obj);
+        if (JS_IsException(eval_result)) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, eval_result);
+            return nullptr;
+        }
+        JS_FreeValue(ctx, await(ctx, eval_result, error));
+        if (!error.empty()) return nullptr;
+        return module;
+    }
+
+    /// After a timed-out run the job queue still holds this tenant's
+    /// microtasks, and that queue belongs to the RUNTIME, not the context a
+    /// fresh run would get. Try to flush it with the deadline still expired;
+    /// if anything survives, the runtime can never be reused.
+    void settleAfterRun() {
+        if (!JS_IsJobPending(rt)) return;
+        // Flush with the deadline forced into the past, so the interrupt
+        // handler aborts every leftover job at its first bytecode op. Without
+        // this a single leftover job spinning in a loop would hang the flush.
+        state.deadline_ms.store(nowMs() - 1, std::memory_order_relaxed);
+        for (int i = 0; i < kPoisonFlushBudget && JS_IsJobPending(rt); i++) {
+            JSContext* job_ctx = nullptr;
+            if (JS_ExecutePendingJob(rt, &job_ctx) < 0 && job_ctx) {
+                JS_FreeValue(job_ctx, JS_GetException(job_ctx));
+            }
+        }
+        if (JS_IsJobPending(rt)) poisoned = true;
+        disarmDeadline();
+    }
+};
+
+JsRuntime::JsRuntime(JsLimits limits) : impl_(std::make_unique<Impl>()) {
+    impl_->limits = limits;
+    impl_->rt = JS_NewRuntime();
+    if (!impl_->rt) throw std::runtime_error("JS_NewRuntime failed");
+    JS_SetMemoryLimit(impl_->rt, limits.memory_limit_bytes);
+    JS_SetMaxStackSize(impl_->rt, limits.max_stack_bytes);
+    JS_SetInterruptHandler(impl_->rt, interruptHandler, &impl_->state);
+}
+
+JsRuntime::~JsRuntime() {
+    if (impl_ && impl_->rt) {
+        // JS_FreeRuntime is the only call that clears leftover jobs, which is
+        // why a poisoned runtime is destroyed rather than cleaned up.
+        impl_->disarmDeadline();
+        JS_FreeRuntime(impl_->rt);
+    }
+}
+
+const JsLimits& JsRuntime::limits() const { return impl_->limits; }
+
+size_t JsRuntime::mallocBytes() const { return impl_->mallocBytes(); }
+
+void JsRuntime::updateStackTop() { JS_UpdateStackTop(impl_->rt); }
+
+void JsRuntime::collectGarbage() { JS_RunGC(impl_->rt); }
+
+bool JsRuntime::poisoned() const { return impl_->poisoned; }
+
+std::optional<JsBytecode> JsRuntime::compile(std::string_view source, const std::string& filename,
+                                             std::string& error_out) {
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        error_out = "out of memory";
+        return std::nullopt;
+    }
+
+    // Compiling arbitrary source is itself unbounded work (a pathological
+    // regexp or a huge literal), so it runs under the same wall-time ceiling.
+    impl_->armDeadline(impl_->limits.wall_time_ms);
+
+    std::optional<JsBytecode> result;
+    // JS_Eval requires a NUL-terminated buffer, which a string_view is not.
+    const std::string src(source);
+    JSValue obj = JS_Eval(ctx, src.c_str(), src.size(), filename.c_str(),
+                          JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+    if (JS_IsException(obj)) {
+        error_out = takeException(ctx);
+    } else {
+        size_t size = 0;
+        uint8_t* buf = JS_WriteObject(ctx, &size, obj, JS_WRITE_OBJ_BYTECODE);
+        if (!buf) {
+            error_out = takeException(ctx);
+        } else {
+            JsBytecode bc;
+            bc.bytes.assign(buf, buf + size);
+            js_free(ctx, buf);
+            result = std::move(bc);
+        }
+    }
+    JS_FreeValue(ctx, obj);
+
+    impl_->disarmDeadline();
+    JS_FreeContext(ctx);
+    if (!result && error_out.empty()) error_out = "compilation failed";
+    return result;
+}
+
+JsResult JsRuntime::run(const JsBytecode& bytecode, const nlohmann::json& ctx_arg,
+                        int64_t wall_time_override_ms, JsHostBindings* host) {
+    JsResult result;
+    const auto started = std::chrono::steady_clock::now();
+    const auto finish = [&] {
+        result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+                                 std::chrono::steady_clock::now() - started)
+                                 .count();
+        return result;
+    };
+
+    if (bytecode.empty()) {
+        result.error = "no compiled function to run";
+        return finish();
+    }
+    if (impl_->poisoned) {
+        result.error = "this runtime was retired and must not run another function";
+        return finish();
+    }
+
+    // A descriptor may ask for less time than the ceiling, never more.
+    int64_t budget = impl_->limits.wall_time_ms;
+    if (wall_time_override_ms > 0) budget = std::min(budget, wall_time_override_ms);
+
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        result.error = "out of memory";
+        result.out_of_memory = true;
+        impl_->poisoned = true;
+        return finish();
+    }
+
+    impl_->armDeadline(budget);
+
+    std::string error;
+    if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
+        JSValue ns = JS_GetModuleNamespace(ctx, module);
+        if (JS_IsException(ns)) {
+            error = takeException(ctx);
+        } else {
+            JSValue fn = JS_GetPropertyStr(ctx, ns, "default");
+            if (JS_IsException(fn)) {
+                error = takeException(ctx);
+            } else if (!JS_IsFunction(ctx, fn)) {
+                error = "the module has no default export function";
+            } else {
+                JSValue arg = toJs(ctx, ctx_arg);
+                if (JS_IsException(arg)) {
+                    error = takeException(ctx);
+                } else {
+                    if (host) {
+                        // install() decorates this object in place; it may not
+                        // swap the handle, which run() owns.
+                        JsBindingTarget target;
+                        target.js_context = ctx;
+                        target.ctx_object = &arg;
+                        std::string host_error;
+                        if (!host->install(target, host_error)) {
+                            error = host_error.empty() ? "host bindings failed to install"
+                                                       : host_error;
+                        }
+                    }
+                    if (error.empty()) {
+                        JSValue returned = JS_Call(ctx, fn, JS_UNDEFINED, 1, &arg);
+                        if (JS_IsException(returned)) {
+                            error = takeException(ctx);
+                            JS_FreeValue(ctx, returned);
+                        } else {
+                            JSValue settled = impl_->await(ctx, returned, error);
+                            if (error.empty()) fromJs(ctx, settled, result.value, error);
+                            JS_FreeValue(ctx, settled);
+                        }
+                    }
+                }
+                JS_FreeValue(ctx, arg);
+            }
+            JS_FreeValue(ctx, fn);
+        }
+        JS_FreeValue(ctx, ns);
+    }
+
+    // The handler fires inside a JS frame; the clock catches the case where the
+    // deadline passed between two microtasks, with no frame to interrupt.
+    const bool out_of_time = impl_->interrupted() || impl_->expired();
+    impl_->disarmDeadline();
+
+    result.console_output = std::move(run_state.console);
+    if (error.empty()) {
+        result.ok = true;
+    } else {
+        result.error = error;
+        if (out_of_time) {
+            result.timed_out = true;
+            result.error = "wall-time limit of " + std::to_string(budget) + " ms exceeded";
+        } else if (impl_->looksLikeOom(error)) {
+            result.out_of_memory = true;
+            // The allocator is at its ceiling with this tenant's data still
+            // reachable; hand this runtime back to nobody.
+            impl_->poisoned = true;
+        }
+    }
+
+    impl_->settleAfterRun();
+    JS_FreeContext(ctx);
+    return finish();
+}
+
+std::optional<nlohmann::json> JsRuntime::readExport(const JsBytecode& bytecode,
+                                                    const std::string& export_name,
+                                                    std::string& error_out) {
+    if (bytecode.empty()) {
+        error_out = "no compiled function to read";
+        return std::nullopt;
+    }
+    if (impl_->poisoned) {
+        error_out = "this runtime was retired";
+        return std::nullopt;
+    }
+
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        error_out = "out of memory";
+        return std::nullopt;
+    }
+
+    // Module evaluation runs top-level code, so it needs the same ceiling as a
+    // run. The default export is never called: reading a descriptor must not
+    // have side effects.
+    impl_->armDeadline(impl_->limits.wall_time_ms);
+
+    std::optional<nlohmann::json> result;
+    std::string error;
+    if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
+        JSValue ns = JS_GetModuleNamespace(ctx, module);
+        if (JS_IsException(ns)) {
+            error = takeException(ctx);
+        } else {
+            JSValue value = JS_GetPropertyStr(ctx, ns, export_name.c_str());
+            if (JS_IsException(value)) {
+                error = takeException(ctx);
+            } else {
+                nlohmann::json parsed;
+                if (fromJs(ctx, value, parsed, error)) result = std::move(parsed);
+            }
+            JS_FreeValue(ctx, value);
+        }
+        JS_FreeValue(ctx, ns);
+    }
+
+    const bool out_of_time = impl_->interrupted() || impl_->expired();
+    impl_->disarmDeadline();
+    if (!result) {
+        error_out = out_of_time ? "wall-time limit exceeded while loading the module"
+                                : (error.empty() ? "could not read export '" + export_name + "'"
+                                                 : error);
+        if (!out_of_time && impl_->looksLikeOom(error)) impl_->poisoned = true;
+    }
+
+    impl_->settleAfterRun();
+    JS_FreeContext(ctx);
+    return result;
+}
+
+// ---------------------------------------------------------------------------
+// Pool
+// ---------------------------------------------------------------------------
+
+JsRuntimePool::Lease::Lease(JsRuntimePool* pool, std::unique_ptr<JsRuntime> runtime)
+    : pool_(pool), runtime_(runtime.get()), owned_(std::move(runtime)) {}
+
+JsRuntimePool::Lease::Lease(Lease&& other) noexcept
+    : pool_(other.pool_), runtime_(other.runtime_), owned_(std::move(other.owned_)) {
+    other.pool_ = nullptr;
+    other.runtime_ = nullptr;
+}
+
+JsRuntimePool::Lease& JsRuntimePool::Lease::operator=(Lease&& other) noexcept {
+    if (this != &other) {
+        release();
+        pool_ = other.pool_;
+        runtime_ = other.runtime_;
+        owned_ = std::move(other.owned_);
+        other.pool_ = nullptr;
+        other.runtime_ = nullptr;
+    }
+    return *this;
+}
+
+JsRuntimePool::Lease::~Lease() { release(); }
+
+void JsRuntimePool::Lease::release() {
+    if (pool_ && owned_) pool_->give_back(std::move(owned_));
+    pool_ = nullptr;
+    runtime_ = nullptr;
+    owned_.reset();
+}
+
+JsRuntimePool::JsRuntimePool(size_t size, JsLimits limits, size_t recycle_above_bytes)
+    : target_(size), limits_(limits), recycle_above_bytes_(recycle_above_bytes) {
+    if (recycle_above_bytes_ == 0) recycle_above_bytes_ = limits_.memory_limit_bytes / 2;
+}
+
+JsRuntimePool::~JsRuntimePool() = default;
+
+size_t JsRuntimePool::size() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return target_;
+}
+
+size_t JsRuntimePool::idle() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return idle_.size();
+}
+
+size_t JsRuntimePool::retired() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return retired_;
+}
+
+JsRuntimePool::Lease JsRuntimePool::acquire() {
+    std::unique_lock<std::mutex> lock(mutex_);
+    cv_.wait(lock, [this] { return !idle_.empty() || live_ < target_; });
+
+    std::unique_ptr<JsRuntime> runtime;
+    if (!idle_.empty()) {
+        runtime = std::move(idle_.back());
+        idle_.pop_back();
+    } else {
+        // Runtimes are created on demand, so a pool sized for peak load costs
+        // nothing until that load arrives.
+        runtime = std::make_unique<JsRuntime>(limits_);
+        live_++;
+    }
+    lock.unlock();
+
+    // QuickJS measures stack depth against the stack top it recorded at
+    // creation; a pooled runtime almost always runs on a different thread.
+    runtime->updateStackTop();
+    return Lease(this, std::move(runtime));
+}
+
+void JsRuntimePool::give_back(std::unique_ptr<JsRuntime> runtime) {
+    // Decide outside the lock: a GC on a bloated runtime can take a while, and
+    // nothing else may touch this runtime while its lease is being dropped.
+    bool retire = runtime->poisoned();
+    if (!retire && runtime->mallocBytes() > recycle_above_bytes_) {
+        // Only the figure AFTER a full GC means anything. A finished run
+        // normally leaves its whole realm unreachable but not yet collected,
+        // and dropping a perfectly good runtime over that would defeat pooling.
+        runtime->collectGarbage();
+        retire = runtime->mallocBytes() > recycle_above_bytes_;
+    }
+
+    std::lock_guard<std::mutex> lock(mutex_);
+    if (!retire && live_ > target_) retire = true;  // the pool shrank while this was out
+    if (retire) {
+        runtime.reset();
+        live_--;
+        retired_++;
+    } else {
+        idle_.push_back(std::move(runtime));
+    }
+    cv_.notify_one();
+}
+
+void JsRuntimePool::resize(size_t size) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    target_ = size;
+    // Only idle runtimes can go now; a leased one is retired by give_back,
+    // because destroying a runtime another thread is executing in would take
+    // the process down with it.
+    while (live_ > target_ && !idle_.empty()) {
+        idle_.pop_back();
+        live_--;
+        retired_++;
+    }
+    cv_.notify_all();
+}
+
+} // namespace svapi::runner

+ 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);
+}

+ 518 - 0
runner/tests/js_runtime_test.cpp

@@ -0,0 +1,518 @@
+// Tests for the QuickJS execution core. These are the executable form of the
+// safety contract in docs/superpowers/specs/2026-10-06-function-runtime-design.md
+// ("Safety"): per-run limits, a fresh context per run, nothing leaking between
+// tenants. They must stay runnable on the dev host, so nothing here touches the
+// database client.
+#include <gtest/gtest.h>
+
+#include <atomic>
+#include <chrono>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "runner/js_runtime.hpp"
+
+using svapi::runner::JsBytecode;
+using svapi::runner::JsLimits;
+using svapi::runner::JsResult;
+using svapi::runner::JsRuntime;
+using svapi::runner::JsRuntimePool;
+
+namespace {
+
+JsBytecode compileOk(JsRuntime& rt, const std::string& src) {
+    std::string error;
+    auto bc = rt.compile(src, "test.js", error);
+    EXPECT_TRUE(bc.has_value()) << "compile failed: " << error;
+    if (!bc) return JsBytecode{};
+    EXPECT_FALSE(bc->empty());
+    return *bc;
+}
+
+} // namespace
+
+TEST(JsRuntime, ReturnsTheDefaultExportsValue) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function (ctx) { return { hi: ctx.name, n: 2 + 3 }; }");
+
+    JsResult r = rt.run(bc, nlohmann::json{{"name", "world"}});
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value.at("hi"), "world");
+    EXPECT_EQ(r.value.at("n"), 5);
+    EXPECT_FALSE(r.timed_out);
+    EXPECT_FALSE(r.out_of_memory);
+}
+
+TEST(JsRuntime, AwaitsAnAsyncDefaultExport) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export default async function (ctx) {"
+                        "  const v = await Promise.resolve(ctx.a + ctx.b);"
+                        "  return { sum: v };"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json{{"a", 20}, {"b", 22}});
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value.at("sum"), 42);
+}
+
+TEST(JsRuntime, ReportsASyntaxErrorCleanly) {
+    JsRuntime rt;
+    std::string error;
+    auto bc = rt.compile("export default function ( { return", "broken.js", error);
+    EXPECT_FALSE(bc.has_value());
+    EXPECT_NE(error.find("SyntaxError"), std::string::npos) << error;
+    // The filename must survive into the diagnostic, otherwise an operator
+    // cannot tell which function failed to load.
+    EXPECT_NE(error.find("broken.js"), std::string::npos) << error;
+}
+
+TEST(JsRuntime, ReportsAThrownErrorWithoutClaimingSuccess) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function () { throw new TypeError('nope'); }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("nope"), std::string::npos) << r.error;
+    EXPECT_FALSE(r.timed_out);
+}
+
+TEST(JsRuntime, ReportsARejectedPromise) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default async function () { throw new Error('async boom'); }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("async boom"), std::string::npos) << r.error;
+}
+
+TEST(JsRuntime, MissingDefaultExportIsAnError) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export const on = { id: 'x' };");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("default export"), std::string::npos) << r.error;
+}
+
+TEST(JsRuntime, InfiniteLoopHitsTheWallTimeLimit) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { for (;;) {} }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(r.duration_ms, 5000);
+}
+
+// A module that keeps re-enqueueing microtasks never returns to the C++ loop,
+// so only the interrupt handler firing inside JS_ExecutePendingJob can stop it.
+TEST(JsRuntime, EndlessMicrotaskChainHitsTheWallTimeLimit) {
+    JsLimits limits;
+    limits.wall_time_ms = 200;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  const spin = () => Promise.resolve().then(spin);"
+                        "  spin();"
+                        "  return new Promise(() => {});"
+                        "}");
+
+    auto started = std::chrono::steady_clock::now();
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                       std::chrono::steady_clock::now() - started)
+                       .count();
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(elapsed, 5000);
+}
+
+// A timed-out run can leave queued jobs that each spin forever. Flushing them
+// must stay bounded, or the wall-time limit would be defeated by whatever runs
+// after the deadline rather than before it.
+TEST(JsRuntime, LeftoverSpinningJobsDoNotHangAfterTheDeadline) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  for (let i = 0; i < 50; i++) { Promise.resolve().then(() => { for (;;) {} }); }"
+                        "  return new Promise(() => {});"
+                        "}");
+
+    auto started = std::chrono::steady_clock::now();
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                       std::chrono::steady_clock::now() - started)
+                       .count();
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(elapsed, 5000);
+}
+
+TEST(JsRuntime, AWallTimeOverrideIsClampedToTheConfiguredMaximum) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { for (;;) {} }");
+
+    // A descriptor asking for 60s may not escape the configured ceiling.
+    JsResult r = rt.run(bc, nlohmann::json::object(), 60000);
+    EXPECT_TRUE(r.timed_out);
+    EXPECT_LT(r.duration_ms, 5000);
+}
+
+TEST(JsRuntime, AllocationStormHitsTheMemoryLimit) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 8u * 1024 * 1024;
+    limits.wall_time_ms = 10000;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  const keep = [];"
+                        "  for (let i = 0; i < 1000000; i++) { keep.push(new Array(256).fill(i)); }"
+                        "  return keep.length;"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.out_of_memory) << r.error;
+    EXPECT_FALSE(r.timed_out) << r.error;
+}
+
+TEST(JsRuntime, CapturesConsoleOutput) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  console.log('hello', 1, { a: 2 });"
+                        "  console.warn('careful');"
+                        "  console.error('bad');"
+                        "  return true;"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    ASSERT_EQ(r.console_output.size(), 3u);
+    EXPECT_NE(r.console_output[0].find("hello 1"), std::string::npos) << r.console_output[0];
+    EXPECT_NE(r.console_output[0].find("\"a\":2"), std::string::npos) << r.console_output[0];
+    EXPECT_NE(r.console_output[1].find("careful"), std::string::npos) << r.console_output[1];
+    EXPECT_NE(r.console_output[2].find("bad"), std::string::npos) << r.console_output[2];
+}
+
+TEST(JsRuntime, ConsoleOutputFromATimedOutRunIsStillReturned) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { console.log('before the hang'); for (;;) {} }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_TRUE(r.timed_out);
+    ASSERT_EQ(r.console_output.size(), 1u);
+    EXPECT_NE(r.console_output[0].find("before the hang"), std::string::npos);
+}
+
+TEST(JsRuntime, ReadExportReturnsTheOnDescriptor) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic',"
+                        "                    method: 'GET' };\n"
+                        "export default function () { throw new Error('must not run'); }");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    ASSERT_TRUE(on.has_value()) << error;
+    EXPECT_EQ(on->at("id"), "kb-search");
+    EXPECT_EQ(on->at("type"), "http");
+    EXPECT_EQ(on->at("route"), "/kb/:topic");
+    EXPECT_EQ(on->at("method"), "GET");
+}
+
+TEST(JsRuntime, ReadExportOfAMissingNameIsNull) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function () { return 1; }");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    ASSERT_TRUE(on.has_value()) << error;
+    EXPECT_TRUE(on->is_null());
+}
+
+TEST(JsRuntime, ReadExportReportsAModuleThatThrowsAtTopLevel) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "throw new Error('top level boom');\nexport const on = {};");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    EXPECT_FALSE(on.has_value());
+    EXPECT_NE(error.find("top level boom"), std::string::npos) << error;
+}
+
+// The tenant-isolation requirement: one run may never see another run's globals.
+TEST(JsRuntime, GlobalsDoNotLeakBetweenRuns) {
+    JsRuntime rt;
+    auto writer = compileOk(rt, "export default function () { globalThis.leaked = 'tenant-a'; return 1; }");
+    auto reader = compileOk(rt, "export default function () { return typeof globalThis.leaked; }");
+
+    JsResult first = rt.run(writer, nlohmann::json::object());
+    ASSERT_TRUE(first.ok) << first.error;
+
+    JsResult second = rt.run(reader, nlohmann::json::object());
+    ASSERT_TRUE(second.ok) << second.error;
+    EXPECT_EQ(second.value, "undefined");
+}
+
+TEST(JsRuntime, PrototypePollutionDoesNotLeakBetweenRuns) {
+    JsRuntime rt;
+    auto poison = compileOk(rt, "export default function () { Object.prototype.pwned = 7; return 1; }");
+    auto probe = compileOk(rt, "export default function () { return ({}).pwned === undefined; }");
+
+    ASSERT_TRUE(rt.run(poison, nlohmann::json::object()).ok);
+    JsResult r = rt.run(probe, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, true);
+}
+
+TEST(JsRuntime, SameBytecodeRunsRepeatedly) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function (ctx) { return ctx.i * 2; }");
+    for (int i = 0; i < 5; i++) {
+        JsResult r = rt.run(bc, nlohmann::json{{"i", i}});
+        ASSERT_TRUE(r.ok) << r.error;
+        EXPECT_EQ(r.value, i * 2);
+    }
+}
+
+TEST(JsRuntime, RunsAgainAfterATimeout) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto hang = compileOk(rt, "export default function () { for (;;) {} }");
+    auto fine = compileOk(rt, "export default function () { return 'alive'; }");
+
+    EXPECT_TRUE(rt.run(hang, nlohmann::json::object()).timed_out);
+    JsResult r = rt.run(fine, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, "alive");
+}
+
+TEST(JsRuntime, NoHostGlobalsAreExposed) {
+    JsRuntime rt;
+    // Slice 1 has no filesystem, no storage and no egress: a script must not
+    // find a way out through a leftover global.
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  return ['std', 'os', 'require', 'fetch', 'XMLHttpRequest', 'process']"
+                        "      .filter((n) => typeof globalThis[n] !== 'undefined');"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_TRUE(r.value.empty()) << r.value.dump();
+}
+
+// QuickJS accounts every allocation it makes, so a JSValue this code forgets to
+// free shows up as a runtime whose footprint climbs run after run. That is the
+// only leak detector available on the dev host (no sanitizer runtimes), so it
+// is worth a test of its own.
+TEST(JsRuntime, RepeatedRunsDoNotLeakRuntimeMemory) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export const on = { id: 'leaky' };\n"
+                        "export default async function (ctx) {"
+                        "  console.log('iteration', ctx.i);"
+                        "  const o = await Promise.resolve({ list: [1, 2, 3], s: 'x'.repeat(100) });"
+                        "  return o;"
+                        "}");
+    auto thrower = compileOk(rt, "export default function () { throw new Error('every time'); }");
+
+    const auto cycle = [&](int i) {
+        ASSERT_TRUE(rt.run(bc, nlohmann::json{{"i", i}}).ok);
+        ASSERT_FALSE(rt.run(thrower, nlohmann::json::object()).ok);
+        std::string error;
+        ASSERT_TRUE(rt.readExport(bc, "on", error).has_value()) << error;
+    };
+
+    for (int i = 0; i < 20; i++) cycle(i);
+    rt.collectGarbage();
+    const size_t baseline = rt.mallocBytes();
+
+    for (int i = 0; i < 200; i++) cycle(i);
+    rt.collectGarbage();
+    const size_t after = rt.mallocBytes();
+
+    // Some slack for the atom table, which grows but never shrinks; a real leak
+    // here is linear in the iteration count and blows straight past it.
+    EXPECT_LT(after, baseline + 256u * 1024)
+        << "baseline " << baseline << " grew to " << after << " over 200 runs";
+}
+
+TEST(JsRuntime, MallocBytesIsReported) {
+    JsRuntime rt;
+    EXPECT_GT(rt.mallocBytes(), 0u);
+}
+
+TEST(JsRuntimePool, ServesConcurrentThreadsSafely) {
+    JsRuntimePool pool(4);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function (ctx) { return ctx.n + 1; }");
+
+    std::atomic<int> ok{0};
+    std::atomic<int> failed{0};
+    std::vector<std::thread> threads;
+    for (int t = 0; t < 16; t++) {
+        threads.emplace_back([&pool, &bc, &ok, &failed, t] {
+            for (int i = 0; i < 10; i++) {
+                auto lease = pool.acquire();
+                JsResult r = lease->run(bc, nlohmann::json{{"n", t}});
+                if (r.ok && r.value == t + 1) {
+                    ok++;
+                } else {
+                    failed++;
+                }
+            }
+        });
+    }
+    for (auto& th : threads) th.join();
+    EXPECT_EQ(failed.load(), 0);
+    EXPECT_EQ(ok.load(), 160);
+}
+
+TEST(JsRuntimePool, AcquireBlocksUntilARuntimeIsFree) {
+    JsRuntimePool pool(1);
+    std::atomic<bool> second_got_it{false};
+
+    auto lease = pool.acquire();
+    std::thread waiter([&pool, &second_got_it] {
+        auto l = pool.acquire();
+        second_got_it = true;
+    });
+
+    std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    EXPECT_FALSE(second_got_it.load()) << "the single runtime was handed out twice";
+
+    lease.release();
+    waiter.join();
+    EXPECT_TRUE(second_got_it.load());
+}
+
+TEST(JsRuntimePool, ResizeDoesNotDestroyAnInUseRuntime) {
+    JsRuntimePool pool(3);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function () { return 'still here'; }");
+
+    auto lease = pool.acquire();
+    pool.resize(1);
+    EXPECT_EQ(pool.size(), 1u);
+
+    // The lease stays valid even though the pool shrank below the number of
+    // runtimes that were handed out.
+    JsResult r = lease->run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, "still here");
+
+    lease.release();
+    EXPECT_LE(pool.size(), 1u);
+}
+
+TEST(JsRuntimePool, ResizeUpAllowsMoreConcurrentLeases) {
+    JsRuntimePool pool(1);
+    auto first = pool.acquire();
+    pool.resize(2);
+    auto second = pool.acquire();   // would block forever at size 1
+    EXPECT_TRUE(second.valid());
+}
+
+TEST(JsRuntimePool, RecyclesARuntimeWhoseAllocationStaysHigh) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 64u * 1024 * 1024;
+    // A watermark below a bare runtime's own footprint, so "still over the
+    // watermark after a GC" is guaranteed and the retirement path is what the
+    // test observes - not QuickJS's reclamation behaviour on a given version.
+    JsRuntimePool pool(1, limits, 1024);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function () { return 1; }");
+
+    {
+        auto lease = pool.acquire();
+        ASSERT_TRUE(lease->run(bc, nlohmann::json::object()).ok);
+        EXPECT_GT(lease->mallocBytes(), 1024u);
+    }
+    EXPECT_EQ(pool.retired(), 1u) << "a runtime over the watermark was kept";
+
+    // Retiring must not shrink the pool: the next tenant still gets served.
+    auto lease = pool.acquire();
+    ASSERT_TRUE(lease.valid());
+    EXPECT_EQ(pool.size(), 1u);
+    EXPECT_TRUE(lease->run(bc, nlohmann::json::object()).ok);
+}
+
+// The other half of the rule: a run whose memory a GC reclaims must NOT cost a
+// runtime, or pooling buys nothing under normal load.
+TEST(JsRuntimePool, KeepsARuntimeWhoseMemoryTheGcReclaims) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 64u * 1024 * 1024;
+    JsRuntimePool pool(1, limits, 1024 * 1024);
+    JsRuntime compiler;
+    auto bloat = compileOk(compiler,
+                           "export default function () {"
+                           "  globalThis.keep = [];"
+                           "  for (let i = 0; i < 20000; i++) { globalThis.keep.push(new Array(64).fill(i)); }"
+                           "  return globalThis.keep.length;"
+                           "}");
+
+    size_t peak = 0;
+    {
+        auto lease = pool.acquire();
+        JsResult r = lease->run(bloat, nlohmann::json::object());
+        ASSERT_TRUE(r.ok) << r.error;
+        peak = lease->mallocBytes();
+    }
+    EXPECT_GT(peak, 1024u * 1024) << "the bloat run did not actually allocate";
+    EXPECT_EQ(pool.retired(), 0u);
+
+    auto lease = pool.acquire();
+    EXPECT_LT(lease->mallocBytes(), 1024u * 1024) << "the runtime was handed on still bloated";
+}
+
+TEST(JsRuntimePool, RetiresARuntimeLeftWithPendingJobs) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntimePool pool(1, limits);
+    JsRuntime compiler;
+    auto spin = compileOk(compiler,
+                          "export default function () {"
+                          "  const again = () => Promise.resolve().then(again);"
+                          "  again();"
+                          "  return new Promise(() => {});"
+                          "}");
+    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 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())
+        << "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") << "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"));
+}

+ 10 - 0
src/CMakeLists.txt

@@ -4,14 +4,20 @@ add_library(vectorapi_core STATIC
     db_errors.cpp
     json_http.cpp
     filters.cpp
+    vector_search.cpp
     db_gateway.cpp
     settings.cpp
     project_settings.cpp
     outbound_http.cpp
     apikey.cpp
+    principal.cpp
     key_store.cpp
     settings_store.cpp
     collection_registry.cpp
+    function_record.cpp
+    function_registry.cpp
+    function_run_log.cpp
+    runner_client.cpp
     embeddings.cpp
     embedding_cache.cpp
     rate_limiter.cpp
@@ -30,6 +36,10 @@ add_library(vectorapi_core STATIC
     handlers/settings.cpp
     handlers/project_settings.cpp
     handlers/relations.cpp
+    handlers/functions.cpp
+    handlers/function_dispatch.cpp
+    functions/descriptor.cpp
+    functions/net_guard.cpp
 )
 target_include_directories(vectorapi_core PUBLIC
     ${CMAKE_CURRENT_SOURCE_DIR}

+ 12 - 0
src/config.cpp

@@ -15,6 +15,18 @@ Config Config::fromJson(const nlohmann::json& j) {
     if (j.contains("database") && j["database"].is_object()) {
         c.dbAddress = j["database"].value("address", c.dbAddress);
     }
+    if (j.contains("functions") && j["functions"].is_object()) {
+        const auto& f = j["functions"];
+        if (f.contains("runners") && f["runners"].is_array()) {
+            // Bind before iterating: a range-for over a temporary subobject of a
+            // parsed document dangles (see CLAUDE.md).
+            const nlohmann::json& runners = f["runners"];
+            for (const auto& e : runners)
+                if (e.is_string() && !e.get<std::string>().empty())
+                    c.runnerEndpoints.push_back(e.get<std::string>());
+        }
+        c.functionRunsKept = f.value("runs_kept", c.functionRunsKept);
+    }
     return c;
 }
 

+ 12 - 0
src/config.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include <cstdint>
 #include <string>
+#include <vector>
 #include <nlohmann/json.hpp>
 
 namespace svapi {
@@ -12,6 +13,17 @@ struct Config {
     std::string dbAddress = "localhost:9004";
     std::string webuiDir  = "/usr/share/smartbotic-vectorapi/webui";
 
+    /// Function runner endpoints ("host:port"). Empty disables the function
+    /// routes outright: with nowhere to validate a script, storing one would
+    /// mean storing unchecked code.
+    ///
+    /// A static list on purpose - dynamic registration is only worth its
+    /// failure modes once autoscaling exists.
+    std::vector<std::string> runnerEndpoints;
+    /// Runs kept per function. There is no scheduler to prune them yet, so the
+    /// log is trimmed on write; unbounded, a busy function fills the database.
+    uint32_t functionRunsKept = 50;
+
     static Config fromJson(const nlohmann::json& j);
     static Config load(const std::string& path);  // reads file then fromJson
 };

+ 4 - 0
src/errors.cpp

@@ -12,6 +12,10 @@ int httpStatus(ErrCode code) {
         case ErrCode::Unprocessable:    return 422;
         case ErrCode::TooManyRequests:  return 429;
         case ErrCode::Unavailable:      return 503;
+        // A function that ran past its wall-time budget. 504 rather than 408:
+        // nothing was slow about the client, the upstream we were waiting on
+        // did not answer. Nothing but function dispatch produces this.
+        case ErrCode::GatewayTimeout:   return 504;
         case ErrCode::Internal:      return 500;
     }
     return 500;

+ 2 - 1
src/errors.hpp

@@ -6,7 +6,8 @@
 namespace svapi {
 
 enum class ErrCode { BadRequest, Unauthorized, Forbidden, NotFound, Conflict,
-                     Unprocessable, TooManyRequests, Unavailable, Internal };
+                     Unprocessable, TooManyRequests, Unavailable, GatewayTimeout,
+                     Internal };
 
 int httpStatus(ErrCode code);
 

+ 94 - 0
src/function_record.cpp

@@ -0,0 +1,94 @@
+#include "function_record.hpp"
+#include <openssl/evp.h>
+#include <array>
+
+namespace svapi {
+
+std::string functionContentHash(const std::string& source) {
+    std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
+    unsigned int len = 0;
+    // EVP rather than the deprecated SHA256() one-shot: OpenSSL 3 marks the
+    // legacy low-level calls deprecated and the build turns warnings into noise.
+    EVP_MD_CTX* ctx = EVP_MD_CTX_new();
+    if (ctx == nullptr) return {};
+    if (EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr) == 1 &&
+        EVP_DigestUpdate(ctx, source.data(), source.size()) == 1) {
+        EVP_DigestFinal_ex(ctx, digest.data(), &len);
+    }
+    EVP_MD_CTX_free(ctx);
+
+    static const char* kHex = "0123456789abcdef";
+    std::string out;
+    out.reserve(static_cast<std::size_t>(len) * 2);
+    for (unsigned int i = 0; i < len; ++i) {
+        out.push_back(kHex[digest[i] >> 4]);
+        out.push_back(kHex[digest[i] & 0x0f]);
+    }
+    return out;
+}
+
+KeyScope builtinDefaultFunctionPolicy() {
+    // Deny everything. A function with no rules can run, log and call out
+    // through ctx.fetch, but it cannot touch a single collection until someone
+    // grants it one. The failure mode of the alternative is silent: a function
+    // that quietly reads data nobody meant to expose looks exactly like a
+    // function that works.
+    return KeyScope{};
+}
+
+FunctionRecord FunctionRecord::fromJson(const nlohmann::json& j) {
+    FunctionRecord f;
+    f.functionId  = j.value("function_id", "");
+    f.path        = j.value("path", "");
+    f.source      = j.value("source", "");
+    f.contentHash = j.value("content_hash", "");
+    if (j.contains("descriptor") && j.at("descriptor").is_object()) f.descriptor = j.at("descriptor");
+    // An absent policy grants nothing. Defaulting to anything else would mean a
+    // truncated or hand-edited row silently widens what a function may touch.
+    if (j.contains("policy") && j.at("policy").is_object()) f.policy = KeyScope::fromJson(j.at("policy"));
+    f.enabled   = j.value("enabled", true);
+    f.valid     = j.value("valid", true);
+    f.lastError = j.value("last_error", "");
+    f.createdAt = j.value("created_at", 0ull);
+    f.updatedAt = j.value("updated_at", 0ull);
+    return f;
+}
+
+nlohmann::json FunctionRecord::toJson() const {
+    nlohmann::json j = toSummaryJson();
+    j["source"] = source;
+    return j;
+}
+
+nlohmann::json FunctionRecord::toSummaryJson() const {
+    // `function_id`, never `id`: the database client strips a top-level `id`
+    // from stored bodies, which would leave the row with no identity.
+    return {{"function_id", functionId},
+            {"path", path},
+            {"content_hash", contentHash},
+            {"descriptor", descriptor},
+            {"policy", policy.toJson()},
+            {"enabled", enabled},
+            {"valid", valid},
+            {"last_error", lastError},
+            {"created_at", createdAt},
+            {"updated_at", updatedAt}};
+}
+
+FunctionRecord mergeForCodePush(const FunctionRecord* existing, FunctionRecord incoming,
+                                const KeyScope& projectDefault) {
+    // Code and trigger declaration come from the push; identity, policy and
+    // operator state come from the server. `incoming.policy` is deliberately
+    // never read - not unioned, not consulted as a fallback - so there is no
+    // path by which pushing code changes what the code may reach.
+    if (existing == nullptr) {
+        incoming.policy = projectDefault;
+        return incoming;
+    }
+    incoming.policy    = existing->policy;
+    incoming.enabled   = existing->enabled;
+    incoming.createdAt = existing->createdAt;
+    return incoming;
+}
+
+} // namespace svapi

+ 86 - 0
src/function_record.hpp

@@ -0,0 +1,86 @@
+#pragma once
+#include "apikey.hpp"
+#include <nlohmann/json.hpp>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// One stored function: its code, its trigger declaration, and the policy that
+/// says what it may touch.
+///
+/// `functionId` is declared in the script's `on` block and is the row's
+/// identity; `path` is where the author happened to keep the file and carries
+/// no meaning. That is what makes a rename safe: moving kb-search.js to
+/// lib/search.js rewrites `path` and keeps the same row, so the policy an admin
+/// granted travels with the function instead of being silently reset.
+///
+/// Stored as one document per function in the project's
+/// `vectorapi_functions` collection under `functionId`. The field is
+/// `function_id`, not
+/// `id`, because the database client strips a top-level `id` from stored bodies
+/// (the same reason API keys store `key_id`).
+struct FunctionRecord {
+    std::string functionId;
+    std::string path;
+    std::string source;
+    std::string contentHash;
+    /// The validated `on` block, as functions::FunctionDescriptor::toJson().
+    /// Held as JSON so this header stays independent of the runner's parser.
+    nlohmann::json descriptor = nlohmann::json::object();
+    /// What the function may do, in exactly the vocabulary API keys already use.
+    /// A function is a principal, not a key holder: same questions, same answers,
+    /// one implementation.
+    KeyScope policy;
+    bool enabled = true;
+    /// False when the last push failed to compile, or when the runner rejected
+    /// the `on` block. An invalid function keeps its row, and its policy.
+    bool valid = true;
+    std::string lastError;
+    uint64_t createdAt = 0;
+    uint64_t updatedAt = 0;
+
+    static FunctionRecord fromJson(const nlohmann::json& j);
+    /// Full form, for storage.
+    nlohmann::json toJson() const;
+    /// Without `source`, for list responses - a registry listing should not
+    /// ship every function's whole body.
+    nlohmann::json toSummaryJson() const;
+};
+
+/// Combine an incoming code push with whatever is already stored.
+///
+/// THE RULE: pushing code can never widen access. Policy is server state, set
+/// by an admin, so this function takes the policy from `existing` and ignores
+/// anything the push claimed. A first registration - `existing == nullptr` -
+/// inherits `projectDefault` instead.
+///
+/// Everything else (source, hash, descriptor, path, validity) comes from the
+/// push. `enabled` is likewise server state: re-pushing code must not silently
+/// re-enable a function an operator deliberately turned off.
+///
+/// Pure, so the invariant is unit-tested here rather than inferred from handler
+/// behaviour.
+FunctionRecord mergeForCodePush(const FunctionRecord* existing, FunctionRecord incoming,
+                                const KeyScope& projectDefault);
+
+/// The policy a FIRST registration inherits when the project has not configured
+/// its own `default_function_policy`.
+///
+/// This is the floor of the whole function runtime: whatever it returns is what
+/// code reaches production with before any admin has looked at it. It therefore
+/// errs toward nothing - an author who needs access asks for it, and the grant
+/// is visible in the registry row.
+///
+/// TODO(policy): confirm this posture. Alternatives, in increasing convenience
+/// and decreasing safety: read+list on every collection (a function can always
+/// read its project's data), read+list on a configured prefix, or full access
+/// within the project. See the note in handlers/functions.cpp when that lands.
+KeyScope builtinDefaultFunctionPolicy();
+
+/// sha256 of `source`, lower-case hex. The runner caches compiled bytecode by
+/// this, so it must change whenever a byte of the source does.
+std::string functionContentHash(const std::string& source);
+
+} // namespace svapi

+ 73 - 0
src/function_registry.cpp

@@ -0,0 +1,73 @@
+#include "function_registry.hpp"
+#include <ctime>
+
+namespace svapi {
+namespace {
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+} // namespace
+
+FunctionRegistry::FunctionRegistry(DbGateway& db) : db_(db) {}
+
+void FunctionRegistry::ensure(const std::string& project) {
+    const std::string c = coll(project);
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, false, 0, 0);
+}
+
+void FunctionRegistry::bootstrap(const std::vector<std::string>& projects) {
+    for (const auto& p : projects) ensure(p);
+}
+
+std::optional<FunctionRecord> FunctionRegistry::get(const std::string& project,
+                                                    const std::string& functionId) {
+    if (auto doc = db_.client().get(coll(project), functionId))
+        return FunctionRecord::fromJson(*doc);
+    return std::nullopt;
+}
+
+std::vector<FunctionRecord> FunctionRegistry::list(const std::string& project) {
+    std::vector<FunctionRecord> out;
+    smartbotic::database::Client::QueryOptions opts;
+    opts.limit = 100000;
+    for (const auto& doc : db_.client().find(coll(project), opts))
+        out.push_back(FunctionRecord::fromJson(doc));
+    return out;
+}
+
+FunctionRecord FunctionRegistry::put(const std::string& project, const FunctionRecord& incoming,
+                                     const KeyScope& projectDefault) {
+    ensure(project);
+    const std::optional<FunctionRecord> existing = get(project, incoming.functionId);
+    FunctionRecord row =
+        mergeForCodePush(existing ? &*existing : nullptr, incoming, projectDefault);
+    if (row.createdAt == 0) row.createdAt = nowSec();
+    row.updatedAt = nowSec();
+    db_.client().upsert(coll(project), row.toJson(), row.functionId);
+    return row;
+}
+
+bool FunctionRegistry::setPolicy(const std::string& project, const std::string& functionId,
+                                 const KeyScope& policy) {
+    std::optional<FunctionRecord> row = get(project, functionId);
+    if (!row) return false;
+    row->policy = policy;
+    row->updatedAt = nowSec();
+    db_.client().upsert(coll(project), row->toJson(), functionId);
+    return true;
+}
+
+bool FunctionRegistry::setEnabled(const std::string& project, const std::string& functionId,
+                                  bool enabled) {
+    std::optional<FunctionRecord> row = get(project, functionId);
+    if (!row) return false;
+    row->enabled = enabled;
+    row->updatedAt = nowSec();
+    db_.client().upsert(coll(project), row->toJson(), functionId);
+    return true;
+}
+
+bool FunctionRegistry::remove(const std::string& project, const std::string& functionId) {
+    return db_.client().remove(coll(project), functionId);
+}
+
+} // namespace svapi

+ 49 - 0
src/function_registry.hpp

@@ -0,0 +1,49 @@
+#pragma once
+#include "db_gateway.hpp"
+#include "function_record.hpp"
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// Project-scoped function registry.
+class FunctionRegistry {
+public:
+    explicit FunctionRegistry(DbGateway& db);
+
+    /// Ensure the registry collection for `project` exists (idempotent).
+    void ensure(const std::string& project);
+
+    /// 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 registry invisible even
+    /// though the data survives (same reason CollectionRegistry::bootstrap
+    /// exists).
+    void bootstrap(const std::vector<std::string>& projects);
+
+    std::optional<FunctionRecord> get(const std::string& project, const std::string& functionId);
+    std::vector<FunctionRecord> list(const std::string& project);
+
+    /// Store a code push, preserving server-held policy via mergeForCodePush.
+    /// Returns the record as stored.
+    FunctionRecord put(const std::string& project, const FunctionRecord& incoming,
+                       const KeyScope& projectDefault);
+
+    /// Replace a function's policy. Admin-only at the HTTP layer; this is the
+    /// only way a policy ever changes.
+    bool setPolicy(const std::string& project, const std::string& functionId,
+                   const KeyScope& policy);
+
+    bool setEnabled(const std::string& project, const std::string& functionId, bool enabled);
+
+    bool remove(const std::string& project, const std::string& functionId);
+
+private:
+    DbGateway& db_;
+    std::string coll(const std::string& project) const {
+        return qualify(project, "vectorapi_functions");
+    }
+};
+
+} // namespace svapi

+ 104 - 0
src/function_run_log.cpp

@@ -0,0 +1,104 @@
+#include "function_run_log.hpp"
+
+namespace svapi {
+namespace {
+
+/// One trim pass deletes at most this many rows. The pass runs on every append,
+/// so a backlog - `keepPerFunction` lowered from 1000 to 10, or rows written by
+/// an older build - drains over the following appends instead of turning one
+/// invocation into a thousand deletes.
+constexpr uint32_t kMaxTrimPerAppend = 64;
+
+/// Rows of one function, newest first. `started_at` is the sort key because it
+/// is the only ordering the caller controls; two runs inside the same second
+/// are therefore ordered arbitrarily, which only decides which of two equally
+/// old rows is dropped first.
+smartbotic::database::Client::QueryOptions newestFirst(const std::string& functionId,
+                                                       uint32_t offset, uint32_t limit) {
+    smartbotic::database::Client::QueryOptions opts;
+    opts.filters.push_back(smartbotic::database::Client::Filter::eq("function_id", functionId));
+    opts.sortField = "started_at";
+    opts.sortDescending = true;
+    opts.offset = offset;
+    opts.limit = limit;
+    return opts;
+}
+
+/// Drop everything past the newest `keep` runs of one function.
+///
+/// Deletes by the body's `run_id`, not by a returned `id`: the client strips a
+/// top-level `id` from stored bodies, so the document id has to be carried in
+/// the body to be readable again (the same reason API keys store `key_id`).
+void trimOldest(smartbotic::database::Client& c, const std::string& collection,
+                const std::string& functionId, uint32_t keep) {
+    if (keep == 0) return;  // 0 = keep everything, as elsewhere in this codebase
+    for (const auto& doc : c.find(collection, newestFirst(functionId, keep, kMaxTrimPerAppend))) {
+        const std::string runId = doc.value("run_id", std::string());
+        if (!runId.empty()) c.remove(collection, runId);
+    }
+}
+
+}  // namespace
+
+FunctionRunLog FunctionRunLog::fromJson(const nlohmann::json& j) {
+    FunctionRunLog e;
+    e.runId      = j.value("run_id", "");
+    e.functionId = j.value("function_id", "");
+    e.trigger    = j.value("trigger", "");
+    e.ok         = j.value("ok", false);
+    e.status     = j.value("status", 0);
+    e.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
+    e.error      = j.value("error", "");
+    if (j.contains("console") && j.at("console").is_array()) {
+        const nlohmann::json& lines = j.at("console");
+        for (const auto& line : lines)
+            if (line.is_string()) e.console.push_back(line.get<std::string>());
+    }
+    e.startedAt = j.value("started_at", 0ull);
+    return e;
+}
+
+nlohmann::json FunctionRunLog::toJson() const {
+    // `run_id`, never `id` - see trimOldest above.
+    return {{"run_id", runId},
+            {"function_id", functionId},
+            {"trigger", trigger},
+            {"ok", ok},
+            {"status", status},
+            {"duration_ms", durationMs},
+            {"error", error},
+            {"console", console},
+            {"started_at", startedAt}};
+}
+
+FunctionRunLogStore::FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction)
+    : db_(db), keep_(keepPerFunction) {}
+
+void FunctionRunLogStore::ensure(const std::string& project) {
+    const std::string c = coll(project);
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, false, 0, 0);
+}
+
+void FunctionRunLogStore::append(const std::string& project, const FunctionRunLog& entry) {
+    ensure(project);
+    db_.client().upsert(coll(project), entry.toJson(), entry.runId);
+    // Trimmed here rather than by a background job: there is no scheduler yet,
+    // and a busy function would otherwise fill the database unnoticed.
+    trimOldest(db_.client(), coll(project), entry.functionId, keep_);
+}
+
+std::vector<FunctionRunLog> FunctionRunLogStore::list(const std::string& project,
+                                                      const std::string& functionId,
+                                                      uint32_t limit) {
+    // A caller asking for more than is kept cannot get more than is kept, so
+    // clamping here keeps a huge ?limit= from becoming a huge query.
+    if (limit == 0) limit = 50;
+    if (keep_ != 0 && limit > keep_) limit = keep_;
+    std::vector<FunctionRunLog> out;
+    for (const auto& doc : db_.client().find(coll(project), newestFirst(functionId, 0, limit)))
+        out.push_back(FunctionRunLog::fromJson(doc));
+    return out;
+}
+
+}  // namespace svapi

+ 47 - 0
src/function_run_log.hpp

@@ -0,0 +1,47 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// One recorded run. Kept deliberately small: a run log is written on every
+/// invocation, so anything stored here is stored thousands of times.
+struct FunctionRunLog {
+    std::string runId;
+    std::string functionId;
+    std::string trigger;      // "http" | "invoke"
+    bool ok = false;
+    int status = 0;
+    int64_t durationMs = 0;
+    std::string error;
+    std::vector<std::string> console;
+    uint64_t startedAt = 0;
+
+    static FunctionRunLog fromJson(const nlohmann::json& j);
+    nlohmann::json toJson() const;
+};
+
+/// Append-only per-project run log in `<project>:vectorapi_function_runs`.
+///
+/// Trimmed on write rather than by a background job: there is no scheduler yet,
+/// and an unbounded log on a busy function is how a database fills up quietly.
+class FunctionRunLogStore {
+public:
+    FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction);
+
+    void ensure(const std::string& project);
+    void append(const std::string& project, const FunctionRunLog& entry);
+    std::vector<FunctionRunLog> list(const std::string& project, const std::string& functionId,
+                                     uint32_t limit);
+
+private:
+    DbGateway& db_;
+    uint32_t keep_;
+    std::string coll(const std::string& project) const {
+        return qualify(project, "vectorapi_function_runs");
+    }
+};
+
+} // namespace svapi

+ 413 - 0
src/functions/descriptor.cpp

@@ -0,0 +1,413 @@
+#include "functions/descriptor.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <set>
+
+namespace svapi::functions {
+namespace {
+
+std::string upper(std::string s) {
+    for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
+    return s;
+}
+
+std::string trim(const std::string& s) {
+    const auto notSpace = [](unsigned char c) { return !std::isspace(c); };
+    const auto first = std::find_if(s.begin(), s.end(), notSpace);
+    const auto last = std::find_if(s.rbegin(), s.rend(), notSpace).base();
+    return first < last ? std::string(first, last) : std::string();
+}
+
+ParseResult fail(std::string message) {
+    ParseResult r;
+    r.ok = false;
+    r.error = std::move(message);
+    return r;
+}
+
+/// Split on '/' keeping interior empty fields (so "/a//b" cannot match "/a/b"),
+/// then drop the one empty field a leading and a trailing slash each produce.
+std::vector<std::string> segments(const std::string& s) {
+    std::vector<std::string> out;
+    std::string cur;
+    for (const char c : s) {
+        if (c == '/') {
+            out.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    out.push_back(cur);
+    if (!out.empty() && out.front().empty()) out.erase(out.begin());
+    if (!out.empty() && out.back().empty()) out.pop_back();
+    return out;
+}
+
+bool isParamSegment(const std::string& seg) { return !seg.empty() && seg.front() == ':'; }
+
+// ------------------------------------------------------------------- cron
+
+struct CronField {
+    const char* name;
+    int min;
+    int max;
+    /// Three-letter aliases, lowest value first ("jan" = 1, "sun" = 0), or null
+    /// for the numeric-only fields.
+    const char* const* names;
+    int namesBase;
+};
+
+const char* const kMonthNames[] = {"jan", "feb", "mar", "apr", "may", "jun",
+                                   "jul", "aug", "sep", "oct", "nov", "dec", nullptr};
+const char* const kDowNames[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat", nullptr};
+
+const CronField kCronFields[5] = {
+    {"minute", 0, 59, nullptr, 0},
+    {"hour", 0, 23, nullptr, 0},
+    {"day-of-month", 1, 31, nullptr, 0},
+    {"month", 1, 12, kMonthNames, 1},
+    // 7 is Sunday as well, which every cron implementation accepts.
+    {"day-of-week", 0, 7, kDowNames, 0},
+};
+
+/// Resolve one endpoint of a cron range: digits, or a three-letter alias where
+/// the field has them. Returns false when it is neither, or out of range.
+bool cronValue(const std::string& tok, const CronField& f, int& out) {
+    if (tok.empty()) return false;
+    const bool numeric = std::all_of(tok.begin(), tok.end(),
+                                     [](unsigned char c) { return std::isdigit(c) != 0; });
+    if (numeric) {
+        try {
+            out = std::stoi(tok);
+        } catch (const std::exception&) {
+            return false; // absurdly long digit run
+        }
+    } else if (f.names != nullptr) {
+        const std::string low = [&] {
+            std::string s = tok;
+            for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+            return s;
+        }();
+        out = -1;
+        for (int i = 0; f.names[i] != nullptr; ++i) {
+            if (low == f.names[i]) {
+                out = f.namesBase + i;
+                break;
+            }
+        }
+        if (out < 0) return false;
+    } else {
+        return false;
+    }
+    return out >= f.min && out <= f.max;
+}
+
+/// Shape check for one comma list of a cron field: "*", "5", "1-5", "*/2",
+/// "1-5/2", "0,30". No schedule is computed here - that is the scheduler's job.
+bool cronFieldValid(const std::string& field, const CronField& f) {
+    if (field.empty()) return false;
+    std::size_t pos = 0;
+    while (pos <= field.size()) {
+        const std::size_t comma = field.find(',', pos);
+        const std::string item =
+            field.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
+        if (item.empty()) return false;
+
+        std::string base = item;
+        const std::size_t slash = item.find('/');
+        if (slash != std::string::npos) {
+            base = item.substr(0, slash);
+            const std::string step = item.substr(slash + 1);
+            if (step.empty() || step.find('/') != std::string::npos) return false;
+            if (!std::all_of(step.begin(), step.end(),
+                             [](unsigned char c) { return std::isdigit(c) != 0; }))
+                return false;
+            // Length-capped before converting: parsing must never throw, and no
+            // real step needs more than two digits.
+            if (step.size() > 2) return false;
+            if (std::stoi(step) < 1) return false; // "*/0" would never fire
+        }
+
+        if (base != "*") {
+            const std::size_t dash = base.find('-', 1); // 1: no negative endpoints
+            if (dash == std::string::npos) {
+                int v = 0;
+                if (!cronValue(base, f, v)) return false;
+            } else {
+                int lo = 0;
+                int hi = 0;
+                if (!cronValue(base.substr(0, dash), f, lo)) return false;
+                if (!cronValue(base.substr(dash + 1), f, hi)) return false;
+                if (lo > hi) return false;
+            }
+        }
+
+        if (comma == std::string::npos) break;
+        pos = comma + 1;
+        if (pos == field.size()) return false; // trailing comma
+    }
+    return true;
+}
+
+/// Validate a 5-field cron expression's shape. Returns an empty string when the
+/// expression is well formed, otherwise the first problem found.
+std::string cronError(const std::string& schedule) {
+    std::vector<std::string> fields;
+    std::string cur;
+    for (const char c : schedule) {
+        if (std::isspace(static_cast<unsigned char>(c)) != 0) {
+            if (!cur.empty()) fields.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    if (!cur.empty()) fields.push_back(cur);
+
+    if (fields.size() != 5)
+        return "cron 'schedule' must have exactly 5 fields (minute hour day-of-month month "
+               "day-of-week), got " +
+               std::to_string(fields.size());
+    for (std::size_t i = 0; i < 5; ++i) {
+        if (!cronFieldValid(fields[i], kCronFields[i]))
+            return std::string("cron 'schedule' field ") + std::to_string(i + 1) + " (" +
+                   kCronFields[i].name + ") is not valid: '" + fields[i] + "'";
+    }
+    return {};
+}
+
+// ------------------------------------------------------------------- http
+
+/// Returns an empty string when `route` is a usable pattern.
+std::string routeError(const std::string& route) {
+    if (route.empty()) return "http 'route' is required and must not be empty";
+    if (route.front() != '/') return "http 'route' must start with '/': '" + route + "'";
+    std::set<std::string> seen;
+    for (const std::string& seg : segments(route)) {
+        if (!isParamSegment(seg)) continue;
+        const std::string name = seg.substr(1);
+        if (name.empty()) return "http 'route' has an unnamed ':' parameter: '" + route + "'";
+        if (!seen.insert(name).second)
+            return "http 'route' declares parameter ':" + name + "' twice: '" + route + "'";
+    }
+    return {};
+}
+
+/// Accept a single string or an array of strings; normalise to upper case and
+/// drop duplicates while keeping declaration order. An empty result means the
+/// key was absent, which is "any method".
+std::string parseMethods(const nlohmann::json& on, std::vector<std::string>& out) {
+    if (!on.contains("method")) return {};
+    const nlohmann::json& m = on.at("method");
+
+    std::vector<std::string> raw;
+    if (m.is_string()) {
+        raw.push_back(m.get<std::string>());
+    } else if (m.is_array()) {
+        if (m.empty())
+            return "'method' must not be an empty array (omit the key to accept any method)";
+        for (const nlohmann::json& e : m) {
+            if (!e.is_string()) return "'method' array must contain only strings";
+            raw.push_back(e.get<std::string>());
+        }
+    } else {
+        return "'method' must be a string or an array of strings";
+    }
+
+    std::set<std::string> seen;
+    for (const std::string& r : raw) {
+        const std::string norm = upper(trim(r));
+        if (norm.empty()) return "'method' must not contain an empty value";
+        if (!std::all_of(norm.begin(), norm.end(),
+                         [](unsigned char c) { return std::isalpha(c) != 0; }))
+            return "'method' value is not an HTTP method: '" + r + "'";
+        if (seen.insert(norm).second) out.push_back(norm);
+    }
+    return {};
+}
+
+} // namespace
+
+bool FunctionDescriptor::acceptsMethod(const std::string& method) const {
+    if (methods.empty()) return true; // no declaration = every method
+    const std::string norm = upper(method);
+    return std::find(methods.begin(), methods.end(), norm) != methods.end();
+}
+
+nlohmann::json FunctionDescriptor::toJson() const {
+    nlohmann::json j = nlohmann::json::object();
+    j["id"] = id;
+    switch (type) {
+    case TriggerType::Http:
+        j["type"] = "http";
+        j["route"] = route;
+        if (!methods.empty()) j["method"] = methods;
+        break;
+    case TriggerType::Cron:
+        j["type"] = "cron";
+        j["schedule"] = schedule;
+        break;
+    case TriggerType::Db:
+        j["type"] = "db";
+        j["table"] = table;
+        j["event"] = event == DbEvent::Insert ? "INSERT"
+                     : event == DbEvent::Update ? "UPDATE"
+                                                : "DELETE";
+        break;
+    }
+    if (timeoutMs > 0) j["timeoutMs"] = timeoutMs;
+    // Written out explicitly: the default depends on the trigger type, so an
+    // omitted key would not survive a type change on reload.
+    j["singleFlight"] = singleFlight;
+    return j;
+}
+
+ParseResult parseDescriptor(const nlohmann::json& on) {
+    if (!on.is_object()) return fail("the exported 'on' must be an object");
+
+    FunctionDescriptor d;
+
+    // Identity first, so the error a script author sees names the thing that
+    // matters most. An id is never inferred from the file path.
+    if (!on.contains("id")) return fail("'id' is required: the function's identity, not its path");
+    if (!on.at("id").is_string()) return fail("'id' must be a string");
+    d.id = trim(on.at("id").get<std::string>());
+    if (d.id.empty()) return fail("'id' must not be empty");
+
+    if (on.contains("type")) {
+        if (!on.at("type").is_string()) return fail("'type' must be a string");
+        const std::string t = on.at("type").get<std::string>();
+        if (t == "http") {
+            d.type = TriggerType::Http;
+        } else if (t == "cron") {
+            d.type = TriggerType::Cron;
+        } else if (t == "db") {
+            d.type = TriggerType::Db;
+        } else {
+            return fail("'type' must be one of http, cron, db: '" + t + "'");
+        }
+    }
+
+    switch (d.type) {
+    case TriggerType::Http: {
+        if (!on.contains("route")) return fail("http 'route' is required");
+        if (!on.at("route").is_string()) return fail("http 'route' must be a string");
+        d.route = on.at("route").get<std::string>();
+        if (const std::string e = routeError(d.route); !e.empty()) return fail(e);
+        if (const std::string e = parseMethods(on, d.methods); !e.empty()) return fail(e);
+        break;
+    }
+    case TriggerType::Cron: {
+        if (!on.contains("schedule")) return fail("cron 'schedule' is required");
+        if (!on.at("schedule").is_string()) return fail("cron 'schedule' must be a string");
+        d.schedule = on.at("schedule").get<std::string>();
+        if (const std::string e = cronError(d.schedule); !e.empty()) return fail(e);
+        break;
+    }
+    case TriggerType::Db: {
+        if (!on.contains("table")) return fail("db 'table' is required");
+        if (!on.at("table").is_string()) return fail("db 'table' must be a string");
+        d.table = trim(on.at("table").get<std::string>());
+        if (d.table.empty()) return fail("db 'table' must not be empty");
+        if (!on.contains("event")) return fail("db 'event' is required");
+        if (!on.at("event").is_string()) return fail("db 'event' must be a string");
+        const std::string raw = on.at("event").get<std::string>();
+        const std::string ev = upper(trim(raw));
+        if (ev == "INSERT") {
+            d.event = DbEvent::Insert;
+        } else if (ev == "UPDATE") {
+            d.event = DbEvent::Update;
+        } else if (ev == "DELETE") {
+            d.event = DbEvent::Delete;
+        } else {
+            return fail("db 'event' must be one of INSERT, UPDATE, DELETE: '" + raw + "'");
+        }
+        break;
+    }
+    }
+
+    if (on.contains("timeoutMs")) {
+        const nlohmann::json& t = on.at("timeoutMs");
+        if (!t.is_number_integer()) return fail("'timeoutMs' must be an integer number of ms");
+        d.timeoutMs = t.get<long long>();
+        if (d.timeoutMs <= 0) return fail("'timeoutMs' must be greater than 0");
+    }
+
+    // Cron defaults to single flight: a schedule firing again while the last
+    // run is still going is almost never what the author meant. HTTP requests
+    // are concurrent by nature, so they default to off.
+    d.singleFlight = d.type == TriggerType::Cron;
+    if (on.contains("singleFlight")) {
+        if (!on.at("singleFlight").is_boolean()) return fail("'singleFlight' must be a boolean");
+        d.singleFlight = on.at("singleFlight").get<bool>();
+    }
+
+    // Any other key is ignored on purpose: a script written for a newer server
+    // must still load here.
+    ParseResult r;
+    r.ok = true;
+    r.descriptor = std::move(d);
+    return r;
+}
+
+bool matchRoute(const std::string& pattern, const std::string& path, RouteParams& params) {
+    params.clear();
+    const std::vector<std::string> pseg = segments(pattern);
+    const std::vector<std::string> xseg = segments(path);
+    if (pseg.size() != xseg.size()) return false;
+
+    RouteParams captured;
+    for (std::size_t i = 0; i < pseg.size(); ++i) {
+        if (isParamSegment(pseg[i])) {
+            // An empty segment would bind a parameter to nothing, which no
+            // handler expects; "/u/" must not satisfy "/u/:handle".
+            if (xseg[i].empty()) return false;
+            captured[pseg[i].substr(1)] = xseg[i];
+        } else if (pseg[i] != xseg[i]) {
+            return false;
+        }
+    }
+    params = std::move(captured);
+    return true;
+}
+
+RouteMatch matchHttpRoute(const std::vector<FunctionDescriptor>& descriptors,
+                          const std::string& method, const std::string& path) {
+    RouteMatch out;
+    std::set<std::string> allowed;
+    bool routeExists = false;
+
+    for (const FunctionDescriptor& d : descriptors) {
+        if (d.type != TriggerType::Http) continue; // a stale route field opens nothing
+        RouteParams params;
+        if (!matchRoute(d.route, path, params)) continue;
+        routeExists = true;
+        if (d.acceptsMethod(method)) {
+            out.status = RouteMatchStatus::Matched;
+            out.descriptor = &d; // first declaration wins: dispatch stays deterministic
+            out.params = std::move(params);
+            return out;
+        }
+        // Only reachable for a descriptor that declared methods, since an empty
+        // list accepts everything and would have matched above.
+        allowed.insert(d.methods.begin(), d.methods.end());
+    }
+
+    if (!routeExists) return out; // NotFound, no Allow header to offer
+    out.status = RouteMatchStatus::MethodNotAllowed;
+    out.allowedMethods.assign(allowed.begin(), allowed.end());
+    return out;
+}
+
+std::string allowHeaderValue(const std::vector<std::string>& methods) {
+    std::string out;
+    for (const std::string& m : methods) {
+        if (!out.empty()) out += ", ";
+        out += m;
+    }
+    return out;
+}
+
+} // namespace svapi::functions

+ 103 - 0
src/functions/descriptor.hpp

@@ -0,0 +1,103 @@
+#pragma once
+#include <map>
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi::functions {
+
+/// What makes a function run. Slice 1 dispatches only Http, but the whole
+/// vocabulary is parsed now so a script written against a later server is
+/// rejected with a clear message rather than silently treated as an HTTP route.
+enum class TriggerType { Http, Cron, Db };
+
+enum class DbEvent { Insert, Update, Delete };
+
+/// Captured path parameters, keyed by the `:name` in the pattern. Ordered so
+/// two matches of the same route compare equal regardless of segment order.
+using RouteParams = std::map<std::string, std::string>;
+
+/// The validated `on` object a script exports:
+///   export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+///
+/// `id` is the function's identity and lives in the source, never derived from
+/// the file path - a rename must carry the policy with it (design doc,
+/// "Identity and policy"). Everything else is trigger configuration.
+struct FunctionDescriptor {
+    std::string id;
+    TriggerType type = TriggerType::Http;
+
+    // Http
+    std::string route;
+    /// Normalised to upper case, deduplicated, declaration order preserved.
+    /// EMPTY MEANS ANY METHOD - it is not "no method allowed".
+    std::vector<std::string> methods;
+
+    // Cron. Validated for shape only; nothing here schedules anything.
+    std::string schedule;
+
+    // Db
+    std::string table;
+    DbEvent event = DbEvent::Insert;
+
+    // Common
+    /// 0 means "not declared"; the runner then applies its configured default.
+    /// A declared value is still clamped to the configured maximum elsewhere.
+    long long timeoutMs = 0;
+    bool singleFlight = false;
+
+    /// True when this descriptor would serve `method`. Case-insensitive, and
+    /// true for every method when none were declared.
+    bool acceptsMethod(const std::string& method) const;
+
+    /// The form stored on the registry row. Round-trips through parseDescriptor.
+    nlohmann::json toJson() const;
+};
+
+/// Parsing never throws on user input: a script author's typo is data, not an
+/// exception. `error` names the first problem found, in declaration-check order.
+struct ParseResult {
+    bool ok = false;
+    FunctionDescriptor descriptor;
+    std::string error;
+};
+
+/// Validate the `on` object exported by a script (or read back from the
+/// registry). Unknown keys are ignored so a newer script still loads on an
+/// older server. Pure: no I/O, no global state.
+ParseResult parseDescriptor(const nlohmann::json& on);
+
+/// Match one route pattern against one request path. Both are split on '/' with
+/// leading and trailing slashes ignored; segment counts must then be equal. A
+/// `:name` segment captures into `params`, any other segment compares
+/// byte-exactly (case-sensitively). `params` is cleared first, so it is empty
+/// whenever the function returns false.
+bool matchRoute(const std::string& pattern, const std::string& path, RouteParams& params);
+
+/// Why route resolution ended the way it did. NotFound and MethodNotAllowed are
+/// kept apart on purpose: collapsing them would let a GET reach a function that
+/// declared `method: 'POST'`, and would lose the `Allow:` header a 405 owes the
+/// client.
+enum class RouteMatchStatus { NotFound, MethodNotAllowed, Matched };
+
+struct RouteMatch {
+    RouteMatchStatus status = RouteMatchStatus::NotFound;
+    /// Only set when status == Matched; the referenced descriptor is borrowed
+    /// from the container passed to matchHttpRoute and must outlive the match.
+    const FunctionDescriptor* descriptor = nullptr;
+    RouteParams params;
+    /// Only set when status == MethodNotAllowed: the sorted, deduplicated union
+    /// of the methods every function on this path declared.
+    std::vector<std::string> allowedMethods;
+};
+
+/// Resolve `method` + `path` against the project's HTTP descriptors. Non-HTTP
+/// descriptors are skipped whatever their other fields say. Among several
+/// candidates the first in `descriptors` wins, so dispatch stays deterministic.
+RouteMatch matchHttpRoute(const std::vector<FunctionDescriptor>& descriptors,
+                          const std::string& method, const std::string& path);
+
+/// Render an `Allow:` header value ("GET, PUT"). Empty for an empty list.
+std::string allowHeaderValue(const std::vector<std::string>& methods);
+
+} // namespace svapi::functions

+ 463 - 0
src/functions/net_guard.cpp

@@ -0,0 +1,463 @@
+#include "functions/net_guard.hpp"
+
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+
+#include <algorithm>
+#include <cctype>
+#include <cstring>
+#include <mutex>
+
+namespace svapi::functions {
+namespace {
+
+// --- small helpers ---------------------------------------------------------
+
+std::string trim(const std::string& s) {
+    const auto notSpace = [](unsigned char c) { return std::isspace(c) == 0; };
+    auto b = std::find_if(s.begin(), s.end(), notSpace);
+    auto e = std::find_if(s.rbegin(), s.rend(), notSpace).base();
+    return (b < e) ? std::string(b, e) : std::string();
+}
+
+std::string toLower(std::string s) {
+    std::transform(s.begin(), s.end(), s.begin(),
+                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+    return s;
+}
+
+bool allDigits(const std::string& s) {
+    return !s.empty() && std::all_of(s.begin(), s.end(),
+                                     [](unsigned char c) { return std::isdigit(c) != 0; });
+}
+
+/// A parsed IP literal: family plus the raw bytes (4 used for v4).
+struct RawAddr {
+    bool v4 = true;
+    std::array<std::uint8_t, 16> bytes{};
+};
+
+/// Parse a bare IP literal. inet_pton is deliberate: it accepts ONLY the
+/// canonical dotted-quad / RFC 4291 forms and rejects the obfuscated spellings
+/// that SSRF payloads lean on (shortened "127.1", octal "0177.0.0.1", hex
+/// "0x7f.0.0.1", the bare integer "2130706433"). Those all end up unparseable
+/// here, and unparseable means blocked, which is the behaviour we want.
+std::optional<RawAddr> parseIpLiteral(const std::string& ip) {
+    if (ip.empty()) return std::nullopt;
+    RawAddr out;
+    in_addr v4{};
+    if (::inet_pton(AF_INET, ip.c_str(), &v4) == 1) {
+        out.v4 = true;
+        std::memcpy(out.bytes.data(), &v4.s_addr, 4);
+        return out;
+    }
+    in6_addr v6{};
+    if (::inet_pton(AF_INET6, ip.c_str(), &v6) == 1) {
+        out.v4 = false;
+        std::memcpy(out.bytes.data(), v6.s6_addr, 16);
+        return out;
+    }
+    return std::nullopt;
+}
+
+/// Is this v6 address an IPv4-mapped one (::ffff:a.b.c.d)?
+bool isV4Mapped(const RawAddr& a) {
+    if (a.v4) return false;
+    for (int i = 0; i < 10; ++i) {
+        if (a.bytes[i] != 0) return false;
+    }
+    return a.bytes[10] == 0xff && a.bytes[11] == 0xff;
+}
+
+/// The embedded IPv4 address of a v4-mapped v6 address.
+RawAddr unmapV4(const RawAddr& a) {
+    RawAddr out;
+    out.v4 = true;
+    std::copy(a.bytes.begin() + 12, a.bytes.begin() + 16, out.bytes.begin());
+    return out;
+}
+
+void maskInPlace(std::array<std::uint8_t, 16>& bytes, int bits, bool v4) {
+    const int len = v4 ? 4 : 16;
+    for (int i = 0; i < len; ++i) {
+        const int consumed = i * 8;
+        if (bits >= consumed + 8) continue;
+        if (bits <= consumed) {
+            bytes[static_cast<std::size_t>(i)] = 0;
+        } else {
+            const int keep = bits - consumed;  // 1..7
+            const auto mask = static_cast<std::uint8_t>(0xffu << (8 - keep));
+            bytes[static_cast<std::size_t>(i)] &= mask;
+        }
+    }
+    for (int i = len; i < 16; ++i) bytes[static_cast<std::size_t>(i)] = 0;
+}
+
+bool prefixEqual(const std::array<std::uint8_t, 16>& a,
+                 const std::array<std::uint8_t, 16>& b, int bits) {
+    const int whole = bits / 8;
+    for (int i = 0; i < whole; ++i) {
+        if (a[static_cast<std::size_t>(i)] != b[static_cast<std::size_t>(i)]) return false;
+    }
+    const int rest = bits % 8;
+    if (rest != 0) {
+        const auto mask = static_cast<std::uint8_t>(0xffu << (8 - rest));
+        if ((a[static_cast<std::size_t>(whole)] & mask) !=
+            (b[static_cast<std::size_t>(whole)] & mask)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+bool rangeContainsRaw(const CidrRange& r, const RawAddr& a) {
+    if (r.v4 != a.v4) return false;  // family mismatch: just not a member
+    return prefixEqual(r.addr, a.bytes, r.bits);
+}
+
+std::string cidrToString(const CidrRange& r) {
+    char buf[INET6_ADDRSTRLEN] = {0};
+    const char* p = r.v4 ? ::inet_ntop(AF_INET, r.addr.data(), buf, sizeof(buf))
+                         : ::inet_ntop(AF_INET6, r.addr.data(), buf, sizeof(buf));
+    std::string s = (p != nullptr) ? std::string(p) : std::string("?");
+    return s + "/" + std::to_string(r.bits);
+}
+
+bool hasControlChars(const std::string& s) {
+    return std::any_of(s.begin(), s.end(), [](unsigned char c) {
+        return c < 0x20 || c == 0x7f;
+    });
+}
+
+} // namespace
+
+// --- parseHttpUrl ----------------------------------------------------------
+
+std::optional<HttpUrlParts> parseHttpUrl(const std::string& url) {
+    const std::string raw = trim(url);
+    if (raw.empty()) return std::nullopt;
+    // A control character inside a URL is how a request gets smuggled past the
+    // host's own parser (CR/LF header injection), so refuse the URL instead of
+    // guessing which half is real.
+    if (hasControlChars(raw)) return std::nullopt;
+
+    const auto sep = raw.find("://");
+    if (sep == std::string::npos || sep == 0) return std::nullopt;
+    const std::string scheme = toLower(raw.substr(0, sep));
+    // http/https only. file:, gopher:, dict:, data: and friends each turn an
+    // SSRF into something worse (local file read, memcached/redis commands).
+    if (scheme != "http" && scheme != "https") return std::nullopt;
+
+    const std::string rest = raw.substr(sep + 3);
+    const auto pathStart = rest.find_first_of("/?#");
+    std::string authority = (pathStart == std::string::npos) ? rest : rest.substr(0, pathStart);
+    std::string path = (pathStart == std::string::npos) ? "/" : rest.substr(pathStart);
+    if (path.empty() || path.front() != '/') path = "/" + path;
+
+    // Drop userinfo: "http://expected-host@10.0.0.1/" must be classified as
+    // 10.0.0.1, which is the host that would actually be connected to.
+    const auto at = authority.rfind('@');
+    if (at != std::string::npos) authority = authority.substr(at + 1);
+    if (authority.empty()) return std::nullopt;
+
+    std::string host;
+    std::string portText;
+    if (authority.front() == '[') {
+        const auto close = authority.find(']');
+        if (close == std::string::npos) return std::nullopt;
+        // Brackets are URL syntax, not part of the address. Strip them so the
+        // host can be fed straight to inet_pton/getaddrinfo, both of which
+        // reject a bracketed literal.
+        host = authority.substr(1, close - 1);
+        const std::string after = authority.substr(close + 1);
+        if (!after.empty()) {
+            if (after.front() != ':') return std::nullopt;
+            portText = after.substr(1);
+        }
+    } else {
+        const auto colon = authority.find(':');
+        if (colon == std::string::npos) {
+            host = authority;
+        } else {
+            host = authority.substr(0, colon);
+            portText = authority.substr(colon + 1);
+            // A second colon means an unbracketed IPv6 literal, which is not a
+            // valid URL authority; parsing it as host:port would silently
+            // misclassify the destination.
+            if (portText.find(':') != std::string::npos) return std::nullopt;
+        }
+    }
+    if (host.empty()) return std::nullopt;
+
+    HttpUrlParts out;
+    out.scheme = scheme;
+    out.host = toLower(host);
+    out.path = path;
+    if (portText.empty()) {
+        // An empty but present ":" ("http://host:/x") is malformed.
+        if (authority.find(':') != std::string::npos && authority.back() == ':') {
+            return std::nullopt;
+        }
+        out.port = (scheme == "https") ? 443 : 80;
+    } else {
+        if (!allDigits(portText) || portText.size() > 5) return std::nullopt;
+        const long p = std::stol(portText);
+        if (p < 1 || p > 65535) return std::nullopt;
+        out.port = static_cast<int>(p);
+    }
+    return out;
+}
+
+// --- CIDR ------------------------------------------------------------------
+
+std::optional<CidrRange> parseCidr(const std::string& cidr) {
+    const std::string text = trim(cidr);
+    if (text.empty()) return std::nullopt;
+
+    std::string addrPart = text;
+    std::string bitsPart;
+    const auto slash = text.find('/');
+    if (slash != std::string::npos) {
+        addrPart = text.substr(0, slash);
+        bitsPart = text.substr(slash + 1);
+        // Reject a second slash rather than ignoring the tail: "10.0.0.0/8/8"
+        // is a config mistake, and a guard must not quietly accept nonsense.
+        if (bitsPart.find('/') != std::string::npos) return std::nullopt;
+    }
+
+    const auto addr = parseIpLiteral(trim(addrPart));
+    if (!addr) return std::nullopt;
+
+    CidrRange out;
+    out.v4 = addr->v4;
+    out.addr = addr->bytes;
+    const int maxBits = addr->v4 ? 32 : 128;
+    if (bitsPart.empty() && slash != std::string::npos) return std::nullopt;
+    if (slash == std::string::npos) {
+        out.bits = maxBits;  // a bare address is a host route
+    } else {
+        const std::string b = trim(bitsPart);
+        if (!allDigits(b) || b.size() > 3) return std::nullopt;
+        const int bits = std::stoi(b);
+        if (bits < 0 || bits > maxBits) return std::nullopt;
+        out.bits = bits;
+    }
+    // Host bits set in the input ("10.1.2.3/8") are masked off, not rejected:
+    // the operator meant the /8, and a range that matched nothing would be a
+    // silent hole in the blocklist.
+    maskInPlace(out.addr, out.bits, out.v4);
+    return out;
+}
+
+bool cidrContains(const CidrRange& range, const std::string& ip) {
+    const auto addr = parseIpLiteral(ip);
+    if (!addr) return false;
+    return rangeContainsRaw(range, *addr);
+}
+
+// --- SsrfPolicy ------------------------------------------------------------
+
+const std::vector<std::string>& SsrfPolicy::defaultBlockedCidrs() {
+    // Everything an egress guard must refuse by default. The IPv4 private and
+    // loopback space plus 169.254.0.0/16, which is where every cloud provider
+    // parks its credential-serving metadata service, and the IPv6 equivalents.
+    static const std::vector<std::string> kDefaults = {
+        // IPv4
+        "0.0.0.0/8",           // "this host on this network"
+        "10.0.0.0/8",          // RFC1918
+        "100.64.0.0/10",       // carrier-grade NAT
+        "127.0.0.0/8",         // loopback - blocks a function calling our own API
+        "169.254.0.0/16",      // link-local, incl. cloud metadata 169.254.169.254
+        "172.16.0.0/12",       // RFC1918
+        "192.0.0.0/24",        // IETF protocol assignments
+        "192.0.2.0/24",        // TEST-NET-1
+        "192.168.0.0/16",      // RFC1918
+        "198.18.0.0/15",       // benchmarking
+        "198.51.100.0/24",     // TEST-NET-2
+        "203.0.113.0/24",      // TEST-NET-3
+        "224.0.0.0/4",         // multicast
+        "240.0.0.0/4",         // reserved, incl. 255.255.255.255 broadcast
+        // IPv6
+        "::/96",               // unspecified, ::1, and the deprecated
+                               // IPv4-compatible form "::127.0.0.1"
+        "::1/128",             // loopback (also inside ::/96; kept explicit)
+        "64:ff9b::/96",        // NAT64 well-known prefix: another way to spell
+                               // an IPv4 destination
+        "64:ff9b:1::/48",      // NAT64 local-use prefix
+        "100::/64",            // discard-only
+        "2001:db8::/32",       // documentation
+        "2002::/16",           // 6to4, embeds an IPv4 address
+        "fc00::/7",            // unique local (covers fd00::/8)
+        "fe80::/10",           // link-local
+        "ff00::/8",            // multicast
+    };
+    return kDefaults;
+}
+
+SsrfPolicy SsrfPolicy::withDefaults() {
+    return fromStrings(defaultBlockedCidrs(), nullptr);
+}
+
+SsrfPolicy SsrfPolicy::fromStrings(const std::vector<std::string>& cidrs,
+                                   std::vector<std::string>* invalid) {
+    SsrfPolicy p;
+    p.ranges_.reserve(cidrs.size());
+    for (const auto& s : cidrs) {
+        if (trim(s).empty()) continue;  // blank lines in config are not errors
+        if (auto r = parseCidr(s)) {
+            p.ranges_.push_back(*r);
+        } else if (invalid != nullptr) {
+            // Reported rather than swallowed: a typo in the blocklist is a hole
+            // in the guard, and the operator has to be able to see it.
+            invalid->push_back(s);
+        }
+    }
+    return p;
+}
+
+std::optional<std::string> SsrfPolicy::blockedBy(const std::string& ip) const {
+    const auto addr = parseIpLiteral(ip);
+    if (!addr) return std::nullopt;  // callers of isBlocked() fail closed instead
+    for (const auto& r : ranges_) {
+        if (rangeContainsRaw(r, *addr)) return cidrToString(r);
+    }
+    // An IPv4-mapped IPv6 address (::ffff:127.0.0.1) reaches exactly the same
+    // peer as its embedded IPv4 address, and many stacks will happily connect
+    // to it. Checking only the v6 form is the classic bypass of a v4
+    // blocklist, so re-check the embedded address.
+    if (isV4Mapped(*addr)) {
+        const RawAddr inner = unmapV4(*addr);
+        for (const auto& r : ranges_) {
+            if (rangeContainsRaw(r, inner)) return cidrToString(r);
+        }
+    }
+    return std::nullopt;
+}
+
+bool SsrfPolicy::isBlocked(const std::string& ip) const {
+    if (!parseIpLiteral(ip)) {
+        // FAIL CLOSED. Not a valid IP literal means we could not classify the
+        // destination, and an unclassified destination has not been proved
+        // safe. Returning false here would re-open the guard to every
+        // obfuscated address form (decimal, octal, hex, bracketed) that
+        // inet_pton refuses to parse.
+        return true;
+    }
+    return blockedBy(ip).has_value();
+}
+
+// --- process-wide snapshot -------------------------------------------------
+
+namespace {
+
+std::mutex& policyMutex() {
+    static std::mutex m;
+    return m;
+}
+
+std::shared_ptr<const SsrfPolicy>& policySlot() {
+    static std::shared_ptr<const SsrfPolicy> slot =
+        std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults());
+    return slot;
+}
+
+} // namespace
+
+std::shared_ptr<const SsrfPolicy> currentSsrfPolicy() {
+    // The lock is held only long enough to copy the shared_ptr; the caller then
+    // owns its snapshot and a concurrent replacement cannot pull it out from
+    // under an in-flight run.
+    std::lock_guard<std::mutex> lk(policyMutex());
+    return policySlot();
+}
+
+void setSsrfPolicy(std::shared_ptr<const SsrfPolicy> policy) {
+    // Never leave the slot empty: a null policy would block nothing, i.e. a
+    // failed settings reload would silently disable the guard.
+    if (!policy) policy = std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults());
+    std::lock_guard<std::mutex> lk(policyMutex());
+    policySlot() = std::move(policy);
+}
+
+// --- host classification ---------------------------------------------------
+
+std::optional<std::string> blockReasonForAddresses(const std::string& host,
+                                                   const std::vector<std::string>& addresses,
+                                                   const SsrfPolicy& policy) {
+    if (addresses.empty()) {
+        return "host '" + host + "' did not resolve to any address; egress blocked";
+    }
+    // EVERY address, not just the first. An attacker controls the DNS for his
+    // own name and can return one public and one internal address (multi-A
+    // records, DNS rebinding); if any answer is internal the name is unsafe,
+    // because we cannot control which one the connect picks.
+    for (const auto& ip : addresses) {
+        if (const auto range = policy.blockedBy(ip)) {
+            return "host '" + host + "' resolves to " + ip + ", which is in the blocked range " +
+                   *range;
+        }
+        if (policy.isBlocked(ip)) {
+            // Reached when the address itself was unparseable: fail closed.
+            return "host '" + host + "' resolves to '" + ip +
+                   "', which could not be classified; egress blocked";
+        }
+    }
+    return std::nullopt;
+}
+
+std::optional<std::string> ssrfBlockReason(const std::string& host, const SsrfPolicy& policy) {
+    if (trim(host).empty()) return "empty host; egress blocked";
+
+    // A literal needs no DNS, and must not get any: resolving it could only
+    // introduce a difference between what we check and what we connect to.
+    if (parseIpLiteral(host)) {
+        if (const auto range = policy.blockedBy(host)) {
+            return "address " + host + " is in the blocked range " + *range;
+        }
+        return std::nullopt;
+    }
+
+    addrinfo hints{};
+    hints.ai_family = AF_UNSPEC;  // both families; a v6 answer is just as routable
+    hints.ai_socktype = SOCK_STREAM;
+    addrinfo* res = nullptr;
+    const int rc = ::getaddrinfo(host.c_str(), nullptr, &hints, &res);
+    if (rc != 0 || res == nullptr) {
+        if (res != nullptr) ::freeaddrinfo(res);
+        // Resolution failure blocks. An unresolved name has not been shown to
+        // point somewhere safe, and letting the HTTP client try anyway would
+        // move the decision to code that does no checking at all.
+        return "host '" + host + "' could not be resolved (" + ::gai_strerror(rc) +
+               "); egress blocked";
+    }
+
+    std::vector<std::string> addresses;
+    for (const addrinfo* ai = res; ai != nullptr; ai = ai->ai_next) {
+        char buf[INET6_ADDRSTRLEN] = {0};
+        const char* p = nullptr;
+        if (ai->ai_family == AF_INET) {
+            const auto* sa = reinterpret_cast<const sockaddr_in*>(ai->ai_addr);
+            p = ::inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof(buf));
+        } else if (ai->ai_family == AF_INET6) {
+            const auto* sa = reinterpret_cast<const sockaddr_in6*>(ai->ai_addr);
+            p = ::inet_ntop(AF_INET6, &sa->sin6_addr, buf, sizeof(buf));
+        } else {
+            // An address family we cannot classify is not something we hand to
+            // a connect: fail closed on the whole host.
+            ::freeaddrinfo(res);
+            return "host '" + host + "' resolved to an unsupported address family; egress blocked";
+        }
+        if (p == nullptr) {
+            ::freeaddrinfo(res);
+            return "host '" + host + "' resolved to an address that could not be read; egress blocked";
+        }
+        addresses.emplace_back(p);
+    }
+    ::freeaddrinfo(res);
+
+    return blockReasonForAddresses(host, addresses, policy);
+}
+
+} // namespace svapi::functions

+ 157 - 0
src/functions/net_guard.hpp

@@ -0,0 +1,157 @@
+#pragma once
+
+// Egress guard for the function runtime's ctx.fetch().
+//
+// WHY this file exists at all: a sandboxed user script runs on a host that sits
+// next to smartbotic-database on localhost and inside a private network. An
+// unguarded fetch() would turn "run my little JS function" into an authenticated
+// pivot into the internal network (SSRF) - the database port, the cloud metadata
+// service at 169.254.169.254, every other host on the LAN. This module is the
+// control that prevents that, so every rule here is load bearing.
+//
+// Two principles run through the whole file and must not be "simplified" away:
+//
+//   1. FAIL CLOSED. Anything the guard cannot parse, resolve or classify is
+//      treated as blocked. A classifier that does not understand its input has
+//      not proved the destination safe.
+//   2. CLASSIFY EVERY ADDRESS. A hostname can resolve to many addresses, and an
+//      attacker controls his own DNS. Checking only the first answer is a known
+//      bypass (multi-A records, DNS rebinding).
+//
+// Residual risk this module does NOT remove: the classify-then-connect gap
+// (TOCTOU). The name is resolved here and resolved again by the HTTP client, so
+// a hostile DNS server with a 0-second TTL can answer differently the second
+// time. Closing that needs the caller to connect to the address this guard
+// approved (pinned IP + Host header), not to the name. See the note on
+// ssrfBlockReason().
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi::functions {
+
+/// The pieces of an absolute http/https URL that the guard needs.
+struct HttpUrlParts {
+    std::string scheme;  ///< "http" or "https", lower-cased
+    std::string host;    ///< lower-cased; IPv6 literals have the brackets REMOVED
+    int port = 0;        ///< explicit port, else 80/443
+    std::string path;    ///< path plus query and fragment; "/" when absent
+};
+
+/// Parse an absolute http/https URL.
+///
+/// Returns nullopt for anything else: a missing or unknown scheme (file:,
+/// gopher:, dict:, data: ... all of which are classic SSRF escalations), an
+/// empty host, a port that is not 1-65535, an unterminated IPv6 bracket, or a
+/// URL containing control characters (header/request smuggling).
+///
+/// Userinfo ("http://user:pass@host/") is stripped, because the host that gets
+/// classified must be the host that gets connected to.
+///
+/// An IPv6 literal arrives bracketed in a URL ("http://[::1]/") but inet_pton
+/// and getaddrinfo reject brackets, so `host` is stored WITHOUT them and can be
+/// passed straight to either.
+std::optional<HttpUrlParts> parseHttpUrl(const std::string& url);
+
+/// A CIDR range, stored family-tagged with the network address already masked.
+struct CidrRange {
+    bool v4 = true;                       ///< true: IPv4 (first 4 bytes of `addr`)
+    std::array<std::uint8_t, 16> addr{};  ///< network address, host bits zeroed
+    int bits = 0;                         ///< prefix length (0-32 for v4, 0-128 for v6)
+
+    bool isV4() const { return v4; }
+};
+
+/// Parse "10.0.0.0/8", "fc00::/7", or a bare address (treated as a host route,
+/// /32 or /128). Host bits set in the input are masked off rather than rejected,
+/// because "10.1.2.3/8" in a config file means the /8 and must not silently
+/// match nothing.
+std::optional<CidrRange> parseCidr(const std::string& cidr);
+
+/// Is `ip` (a bare IP literal, no brackets) inside `range`?
+///
+/// A family mismatch is simply "not a member", not an error: a blocklist mixes
+/// v4 and v6 ranges and every address is checked against all of them. An
+/// unparseable `ip` is likewise "not a member" here - this function answers only
+/// the membership question. Failing closed on garbage is SsrfPolicy::isBlocked's
+/// job, which is the function callers are supposed to use.
+bool cidrContains(const CidrRange& range, const std::string& ip);
+
+/// A set of blocked CIDR ranges plus the classification rules around it.
+class SsrfPolicy {
+public:
+    /// The built-in blocklist: loopback, RFC1918, link-local (cloud metadata),
+    /// carrier NAT, and the IPv6 equivalents, plus the deprecated IPv6
+    /// transition prefixes that are really just other spellings of an IPv4
+    /// address.
+    static const std::vector<std::string>& defaultBlockedCidrs();
+
+    /// Policy built from the built-in defaults.
+    static SsrfPolicy withDefaults();
+
+    /// Policy built from raw config strings. This REPLACES the defaults rather
+    /// than extending them, so an operator can deliberately widen egress.
+    /// Entries that do not parse are skipped and appended to `invalid` (when
+    /// non-null) so the caller can log them: a typo in the blocklist is a hole
+    /// in the guard and must be visible, not silent.
+    static SsrfPolicy fromStrings(const std::vector<std::string>& cidrs,
+                                  std::vector<std::string>* invalid);
+
+    /// Is this address literal blocked?
+    ///
+    /// Returns true - FAIL CLOSED - when `ip` is not a valid IP literal at all.
+    /// Callers use this as "may I connect here?", so an unparseable answer must
+    /// be "no". Do not change this to return false for unknown input.
+    ///
+    /// An IPv4-mapped IPv6 address (::ffff:127.0.0.1) is additionally checked as
+    /// its embedded IPv4 address; skipping that is the classic way a v4-only
+    /// blocklist gets walked around.
+    bool isBlocked(const std::string& ip) const;
+
+    /// Which range blocks `ip`, as CIDR text, or nullopt when nothing matches.
+    /// Unlike isBlocked() this returns nullopt for an unparseable literal, so
+    /// it is a reporting helper for logs and messages - security decisions go
+    /// through isBlocked(), which fails closed.
+    std::optional<std::string> blockedBy(const std::string& ip) const;
+
+    std::size_t size() const { return ranges_.size(); }
+
+private:
+    std::vector<CidrRange> ranges_;
+};
+
+/// The process-wide policy snapshot. Readers get a shared_ptr they own for the
+/// duration of a run, so a runtime replacement never invalidates a policy a
+/// request is already using and readers are never blocked behind a writer.
+std::shared_ptr<const SsrfPolicy> currentSsrfPolicy();
+
+/// Install a new snapshot (startup, or a settings hot-reload). Passing nullptr
+/// restores the built-in defaults - the cache never ends up empty, because an
+/// empty policy would allow everything.
+void setSsrfPolicy(std::shared_ptr<const SsrfPolicy> policy);
+
+/// Classify `host` (a name or a bare IP literal, no brackets) against `policy`.
+///
+/// Returns nullopt when the destination is allowed, or a human-readable reason
+/// when it is not. A literal IP is classified directly, with no DNS lookup. A
+/// name is resolved with getaddrinfo and EVERY returned address is classified;
+/// one blocked address blocks the host. Resolution failure, or a name that
+/// resolves to nothing, is also blocked (fail closed).
+///
+/// NOTE on TOCTOU: this validates the name, and the HTTP client will resolve it
+/// again. To close the rebinding window the caller should connect to the
+/// approved address rather than re-resolving the name.
+std::optional<std::string> ssrfBlockReason(const std::string& host, const SsrfPolicy& policy);
+
+/// The classification half of ssrfBlockReason, split out so the "check every
+/// address, not just the first" rule is testable without a resolver. `host` is
+/// only used in the message. An empty list is a resolution failure: blocked.
+std::optional<std::string> blockReasonForAddresses(const std::string& host,
+                                                   const std::vector<std::string>& addresses,
+                                                   const SsrfPolicy& policy);
+
+} // namespace svapi::functions

+ 342 - 0
src/handlers/function_dispatch.cpp

@@ -0,0 +1,342 @@
+// Public dispatch of user functions under /fn/*.
+//
+// This is the only route group in the server with NO authentication: the
+// pre-routing handler authenticates /api/* and nothing else, exactly as it
+// leaves /healthz and /docs open (handlers/meta.cpp). A function that serves
+// HTTP is published on purpose, so the gate is the registry - `enabled` and
+// `valid` - not a key.
+//
+// Because it is public, everything below treats the request path as hostile.
+#include "auth.hpp"
+#include "errors.hpp"
+#include "functions/descriptor.hpp"
+#include "json_http.hpp"
+#include "server.hpp"
+#include <algorithm>
+#include <ctime>
+#include <spdlog/spdlog.h>
+
+namespace svapi {
+namespace {
+
+/// Response headers a function may not set: httplib owns the framing, and a
+/// function that could forge Content-Length or Transfer-Encoding could smuggle
+/// a second response past any proxy in front of us.
+bool reservedResponseHeader(const std::string& lower) {
+    static const char* kReserved[] = {"content-length", "transfer-encoding", "connection",
+                                      "keep-alive",     "upgrade",           "trailer",
+                                      "te",             "host"};
+    for (const char* r : kReserved) if (lower == r) return true;
+    return false;
+}
+
+/// Request headers never forwarded into user code.
+///
+/// Cookie is the dangerous one: the web UI is served from this same origin, so
+/// a logged-in admin's browser attaches the session cookie to /fn/* as well,
+/// and forwarding it would hand that admin's session to every function author
+/// in the project. Authorization goes for the same reason.
+bool secretRequestHeader(const std::string& lower) {
+    return lower == "cookie" || lower == "set-cookie" || lower == "authorization"
+        || lower == "proxy-authorization" || lower == "x-captcha-token";
+}
+
+std::string lowerCase(std::string s) {
+    std::transform(s.begin(), s.end(), s.begin(),
+                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+    return s;
+}
+
+/// A project name we are willing to put through qualify(). Deliberately
+/// stricter than the database's own rules: ':' is the project/collection
+/// separator qualify() builds on, '/' and '.' are path tricks, and anything
+/// outside this set has no business naming a project. Rejecting here means the
+/// unvetted segment never reaches a collection name.
+bool safeProjectSegment(const std::string& p) {
+    if (p.empty() || p.size() > 64) return false;
+    if (p == "." || p == "..") return false;
+    for (unsigned char c : p) {
+        const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
+                     || (c >= '0' && c <= '9') || c == '-' || c == '_';
+        if (!ok) return false;
+    }
+    return true;
+}
+
+/// httplib percent-decodes before we see the path, so "%2e%2e" arrives as "..".
+/// A ".." segment can never match a literal pattern segment, but it CAN be
+/// captured by a `:name` parameter and handed to a function that uses it as a
+/// key, so it is refused at the edge instead.
+bool hasDotDotSegment(const std::string& path) {
+    size_t i = 0;
+    while (i < path.size()) {
+        const size_t end = path.find('/', i);
+        const std::string seg = path.substr(i, end == std::string::npos ? end : end - i);
+        if (seg == "..") return true;
+        if (end == std::string::npos) break;
+        i = end + 1;
+    }
+    return false;
+}
+
+nlohmann::json headerJson(const httplib::Request& req) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [name, value] : req.headers) {
+        const std::string lower = lowerCase(name);
+        if (secretRequestHeader(lower)) continue;
+        // Lower-cased keys so a script can look one up without guessing the
+        // casing a client happened to send.
+        out[lower] = value;
+    }
+    return out;
+}
+
+/// Repeated query keys collapse to the last value, because the trigger shape is
+/// fixed at {method, path, params, query, headers, body} and `query` is an
+/// object. A function needing `?tag=a&tag=b` needs that shape widened first;
+/// guessing an array here would make the field's type depend on the request.
+nlohmann::json queryJson(const httplib::Request& req) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [name, value] : req.params) out[name] = value;
+    return out;
+}
+
+/// JSON when the request says JSON and it parses, the raw string otherwise,
+/// null when there is no body. A parse failure is NOT a 400: the function may
+/// legitimately accept text with a wrong content type, and guessing on its
+/// behalf would make /fn/* stricter than the function it fronts.
+nlohmann::json triggerBody(const httplib::Request& req) {
+    if (req.body.empty()) return nullptr;
+    const std::string ct = lowerCase(req.get_header_value("Content-Type"));
+    if (ct.find("json") != std::string::npos) {
+        try {
+            return nlohmann::json::parse(req.body);
+        } catch (const std::exception&) {
+            // fall through to the raw string
+        }
+    }
+    return req.body;
+}
+
+nlohmann::json routeParamsJson(const functions::RouteParams& params) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [k, v] : params) out[k] = v;
+    return out;
+}
+
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+
+/// An unresolvable /fn path. One shape for "no such project", "no such
+/// function", "disabled" and "invalid": a public route must not let an
+/// unauthenticated caller enumerate which projects or functions exist.
+void sendNotFound(httplib::Response& res) {
+    sendJson(res, 404, errorBody("not_found", "no function serves this route"));
+}
+
+/// Write a successful run's own response. The function chose the status, the
+/// headers and the body; our job is only to stop it breaking the protocol.
+void sendFunctionResponse(httplib::Response& res, const RunnerRunResult& r) {
+    int status = r.status;
+    if (status < 100 || status > 599) status = 200;  // a nonsense status is not a response
+    res.status = status;
+
+    std::string contentType;
+    int emitted = 0;
+    if (r.headers.is_object()) {
+        for (const auto& [name, value] : r.headers.items()) {
+            if (++emitted > 32) break;  // a header flood is a denial of service, not a response
+            if (!value.is_string()) continue;
+            const std::string lower = lowerCase(name);
+            if (reservedResponseHeader(lower)) continue;
+            if (lower == "content-type") { contentType = value.get<std::string>(); continue; }
+            res.set_header(name, value.get<std::string>());
+        }
+    }
+
+    if (r.body.is_null()) {
+        if (!contentType.empty()) res.set_header("Content-Type", contentType);
+        return;  // no body; a 204 stays a 204
+    }
+    if (r.body.is_string()) {
+        res.set_content(r.body.get<std::string>(),
+                        contentType.empty() ? "text/plain; charset=utf-8" : contentType);
+        return;
+    }
+    res.set_content(r.body.dump(), contentType.empty() ? "application/json" : contentType);
+}
+
+/// Writing the log must never change the answer: a database hiccup on an
+/// append would otherwise turn a function that worked into a 500.
+void recordRun(ServerDeps& d, const std::string& project, const FunctionRunLog& entry) {
+    try {
+        d.functionRuns.append(project, entry);
+    } catch (const std::exception& e) {
+        spdlog::warn("could not record run {} of {}/{}: {}", entry.runId, project,
+                     entry.functionId, e.what());
+    }
+}
+
+void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res) {
+    const std::string project = req.matches[1];
+    std::string path = req.matches.size() > 2 ? std::string(req.matches[2]) : std::string();
+    if (path.empty()) path = "/";
+
+    if (!safeProjectSegment(project) || hasDotDotSegment(path)) { sendNotFound(res); return; }
+
+    // The project must exist before anything qualifies a collection with it, so
+    // a crafted segment cannot conjure a registry read in a namespace of its own.
+    const std::vector<std::string> projects = d.db.listProjects();
+    if (std::find(projects.begin(), projects.end(), project) == projects.end()) {
+        sendNotFound(res);
+        return;
+    }
+
+    std::vector<FunctionRecord> rows = d.functions.list(project);
+    // matchHttpRoute resolves ties by declaration order, so the order we hand it
+    // decides which function serves an overlapping route. The database makes no
+    // promise about list() order, so sort: the same two functions must not swap
+    // a shared route across a restart.
+    std::sort(rows.begin(), rows.end(),
+              [](const FunctionRecord& a, const FunctionRecord& b) {
+                  return a.functionId < b.functionId;
+              });
+
+    std::vector<functions::FunctionDescriptor> descriptors;
+    std::vector<std::string> ids;
+    descriptors.reserve(rows.size());
+    ids.reserve(rows.size());
+    for (const FunctionRecord& row : rows) {
+        // A disabled or invalid function is invisible, not 403: a public caller
+        // learns nothing about what the project holds.
+        if (!row.enabled || !row.valid) continue;
+        functions::ParseResult parsed = functions::parseDescriptor(row.descriptor);
+        if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Http) continue;
+        descriptors.push_back(std::move(parsed.descriptor));
+        ids.push_back(row.functionId);
+    }
+
+    const functions::RouteMatch match = functions::matchHttpRoute(descriptors, req.method, path);
+    if (match.status == functions::RouteMatchStatus::NotFound) { sendNotFound(res); return; }
+    if (match.status == functions::RouteMatchStatus::MethodNotAllowed) {
+        // 405 and 404 stay distinct, and a 405 owes the client an Allow header.
+        res.set_header("Allow", functions::allowHeaderValue(match.allowedMethods));
+        sendJson(res, 405, errorBody("method_not_allowed",
+                                     "this route does not serve " + req.method));
+        return;
+    }
+
+    // match.descriptor borrows from `descriptors`, which has not been touched
+    // since, so its offset is the index of the record it came from.
+    const size_t idx = static_cast<size_t>(match.descriptor - descriptors.data());
+    const std::string functionId = ids[idx];
+
+    const std::string runId = randomToken();
+    FunctionRunLog entry;
+    entry.runId = runId;
+    entry.functionId = functionId;
+    entry.trigger = "http";
+    entry.startedAt = nowSec();
+
+    if (!d.runners) {
+        // Nothing to dispatch to. Still logged: "the function was reached but no
+        // runner existed" is the operational fact worth having.
+        entry.ok = false;
+        entry.status = 503;
+        entry.error = "no runner configured";
+        recordRun(d, project, entry);
+        sendJson(res, 503, errorBody("runner_unavailable", "no function runner is configured"));
+        return;
+    }
+
+    const nlohmann::json trigger{{"method", req.method},
+                                 {"path", path},
+                                 {"params", routeParamsJson(match.params)},
+                                 {"query", queryJson(req)},
+                                 {"headers", headerJson(req)},
+                                 {"body", triggerBody(req)}};
+
+    const RunnerRunResult r = d.runners->run(project, functionId, trigger);
+
+    entry.ok = r.ok;
+    entry.durationMs = r.durationMs;
+    entry.console = r.console;
+    entry.error = r.error;
+
+    // The status mapping. Three of these four are OUR fault or OUR limit, so
+    // none of them exposes the function's error text to an unauthenticated
+    // caller - the full message goes to the run log, which the project's own
+    // people read through GET .../functions/{id}/logs.
+    if (r.transportFailure) {
+        // We never got an answer from any runner. 503 with Retry-After, because
+        // the same request may well succeed once a runner is back.
+        entry.status = 503;
+        res.set_header("Retry-After", "5");
+        sendJson(res, 503, errorBody("runner_unavailable", "no function runner is available"));
+    } else if (r.timedOut) {
+        // 504: the thing we delegated to never finished. Not 408 - nothing was
+        // slow about the client.
+        entry.status = httpStatus(ErrCode::GatewayTimeout);
+        sendJson(res, entry.status,
+                 errorBody("function_timeout", "the function exceeded its time limit",
+                           {{"function_id", functionId}, {"run_id", runId}}));
+    } else if (r.outOfMemory) {
+        // 500, not 503: the function asked for more memory than it may have, so
+        // the identical request will fail identically and "come back later" would
+        // be a lie. Not 507 either - that is about storage, and inventing a rare
+        // status buys a client nothing it can act on.
+        entry.status = 500;
+        sendJson(res, 500, errorBody("function_out_of_memory",
+                                     "the function exceeded its memory limit",
+                                     {{"function_id", functionId}, {"run_id", runId}}));
+    } else if (!r.ok) {
+        // The function threw. 500, the same answer an unhandled exception in our
+        // own handlers gets: from the caller's side this IS the server. Not 502 -
+        // the runner is an implementation detail, not an upstream the client
+        // asked us to proxy.
+        entry.status = 500;
+        sendJson(res, 500, errorBody("function_error", "the function failed",
+                                     {{"function_id", functionId}, {"run_id", runId}}));
+    } else {
+        entry.status = r.status;
+        sendFunctionResponse(res, r);
+    }
+
+    recordRun(d, project, entry);
+}
+
+} // namespace
+
+void registerFunctionDispatchRoutes(ApiServer& s) {
+    auto& svr = s.raw();
+    ServerDeps* d = &s.deps();
+
+    // Project in the path, because there is no key to read one from.
+    //
+    // The alternatives were a single configured dispatch project (one project
+    // gets public functions, the rest silently cannot - and it needs a config
+    // field this change does not own) and a Host-header map (right answer for
+    // custom domains, but it needs that same config and a vhost table). Naming
+    // the project in the path needs neither, and it matches the shape every
+    // other route already has: /api/v1/projects/{p}/... .
+    //
+    // It does mean any caller can address any project's functions by naming it.
+    // That is addressing, not a leak: a published HTTP function is published,
+    // and a project name is not a credential. What must not happen is a crafted
+    // path reaching a project the caller did not name, which is why the segment
+    // is charset-checked, confirmed against listProjects(), and used for exactly
+    // one registry read - and why the remainder is matched ONLY against that
+    // project's descriptors.
+    const char* pattern = R"(/fn/([^/]+)((?:/.*)?))";
+    auto handler = [d](const httplib::Request& req, httplib::Response& res) {
+        dispatch(*d, req, res);
+    };
+    svr.Get(pattern, handler);
+    svr.Post(pattern, handler);
+    svr.Put(pattern, handler);
+    svr.Patch(pattern, handler);
+    svr.Delete(pattern, handler);
+    // No HEAD: cpp-httplib has no registrar for it, so a HEAD never reaches a
+    // handler. OPTIONS is answered by the server-wide CORS pre-flight route.
+}
+
+} // namespace svapi

+ 328 - 0
src/handlers/functions.cpp

@@ -0,0 +1,328 @@
+#include "errors.hpp"
+#include "function_record.hpp"
+#include "json_http.hpp"
+#include "project_settings.hpp"
+#include "server.hpp"
+#include <cstdlib>
+#include <ctime>
+#include <limits>
+
+namespace svapi {
+namespace {
+
+/// The runner pool, or 503.
+///
+/// "No runner configured" and "every runner is down" are the same answer to the
+/// caller: the route exists, the capability behind it does not right now. It is
+/// never a 404 - a 404 would say the function feature is not part of this API.
+RunnerPool& requireRunner(ServerDeps& d) {
+    if (d.runners == nullptr)
+        throw ApiError(ErrCode::Unavailable, "no_runner",
+                       "no function runner is configured on this server");
+    if (!d.runners->anyHealthy())
+        throw ApiError(ErrCode::Unavailable, "no_runner",
+                       "no healthy function runner is available");
+    return *d.runners;
+}
+
+/// What a code push carries. `policy` is deliberately absent: see below.
+struct CodePush {
+    std::string source;
+    std::string path;
+};
+
+CodePush codePush(const nlohmann::json& body) {
+    if (!body.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "the body must be an object");
+    if (!body.contains("source") || !body["source"].is_string() ||
+        body["source"].get<std::string>().empty())
+        throw ApiError(ErrCode::Unprocessable, "validation", "source is required");
+    if (body.contains("path") && !body["path"].is_string())
+        throw ApiError(ErrCode::Unprocessable, "validation", "path must be a string");
+    // A `policy` field in a code push is IGNORED, not rejected: a client that
+    // GETs a function and PUTs it back would otherwise be unable to write at
+    // all, and ignoring the field has no escalation failure mode, while
+    // "is this narrower than what is stored?" is where one would live (design
+    // doc, Addendum). Policy changes go through the admin-only policy route.
+    return {body["source"].get<std::string>(), body.value("path", "")};
+}
+
+/// Compile the push on a runner and turn the result into a storable row.
+///
+/// The engine that validates is the engine that will execute, so nothing is
+/// stored that has not compiled on a real runner.
+FunctionRecord validateOnRunner(ServerDeps& d, const CodePush& push) {
+    RunnerValidateResult v = requireRunner(d).validate(push.source, push.path);
+    if (v.transportFailure)
+        throw ApiError(ErrCode::Unavailable, "runner_unreachable",
+                       v.error.empty() ? "the function runner could not be reached" : v.error);
+    if (!v.ok)
+        throw ApiError(ErrCode::Unprocessable, "compile_failed",
+                       v.error.empty() ? "the function did not compile" : v.error);
+
+    const std::string declared =
+        v.descriptor.is_object() ? v.descriptor.value("id", std::string()) : std::string();
+    if (declared.empty())
+        throw ApiError(ErrCode::Unprocessable, "missing_function_id",
+                       "the script's `on` block must declare an id; the file path is never "
+                       "used as a fallback");
+
+    FunctionRecord rec;
+    rec.functionId  = declared;
+    rec.path        = push.path;
+    rec.source      = push.source;
+    rec.contentHash = functionContentHash(push.source);
+    rec.descriptor  = v.descriptor;
+    rec.valid       = true;
+    return rec;
+}
+
+/// The policy a first registration inherits: the project's configured
+/// `default_function_policy`, else the built-in floor, which grants no
+/// collection at all.
+///
+/// Only ever consulted for a FIRST registration - mergeForCodePush keeps an
+/// existing function's policy - so changing a project's default never
+/// retroactively alters anything already deployed.
+KeyScope projectDefaultPolicy(ServerDeps& d, const std::string& project) {
+    const auto proj = d.settings.projectSnapshot(project);
+    return defaultFunctionPolicyFor(proj.get());
+}
+
+/// Validate and read a policy document. Shaped like keys.cpp parseScope, with
+/// one deliberate difference: an empty rule set is legal here. It is the
+/// deny-everything default a function starts on, so an admin must be able to
+/// put it back.
+KeyScope parsePolicy(const nlohmann::json& body) {
+    // {"policy":{...}} and a bare scope object are both unambiguous, so both
+    // are accepted - the admin UI sends the first, a curl the second.
+    const nlohmann::json& p = body.contains("policy") ? body.at("policy") : body;
+    if (!p.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "policy must be an object");
+    if (p.contains("rules")) {
+        if (!p["rules"].is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation", "policy.rules must be an array");
+        for (const auto& r : p["rules"]) {
+            if (!r.is_object() || r.value("collection", std::string()).empty())
+                throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs a collection");
+            if (!r.contains("ops") || !r["ops"].is_array() || r["ops"].empty())
+                throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs ops");
+            for (const auto& o : r["ops"])
+                if (!o.is_string() || !keyOpFromString(o.get<std::string>()))
+                    throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in policy");
+        }
+    }
+    return KeyScope::fromJson(p);
+}
+
+/// A function that cannot run, as an error - or nothing.
+///
+/// 409 rather than 422: the request is fine, the server's state refuses it, and
+/// the caller fixes it by enabling or re-pushing the function, not by editing
+/// the request.
+void requireRunnable(const FunctionRecord& fn) {
+    if (!fn.valid)
+        throw ApiError(ErrCode::Conflict, "function_invalid",
+                       fn.lastError.empty() ? "this function is marked invalid" : fn.lastError);
+    if (!fn.enabled)
+        throw ApiError(ErrCode::Conflict, "function_disabled", "this function is disabled");
+}
+
+uint32_t limitParam(const httplib::Request& req, uint32_t fallback) {
+    if (!req.has_param("limit")) return fallback;
+    const std::string raw = req.get_param_value("limit");
+    if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
+        throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
+    unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
+    if (wide == 0 || wide > std::numeric_limits<uint32_t>::max())
+        throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
+    return static_cast<uint32_t>(wide);
+}
+
+/// The trigger a manual invoke synthesises. Every field is optional: invoking a
+/// function with no body is the common case ("does it still run?"), so the
+/// defaults have to produce a usable request.
+nlohmann::json manualTrigger(const FunctionRecord& fn, const nlohmann::json& body) {
+    const std::string route =
+        fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string();
+    nlohmann::json t;
+    t["method"]  = body.value("method", std::string("POST"));
+    t["path"]    = body.value("path", route);
+    t["params"]  = body.contains("params") && body["params"].is_object()
+                       ? body["params"] : nlohmann::json::object();
+    t["query"]   = body.contains("query") && body["query"].is_object()
+                       ? body["query"] : nlohmann::json::object();
+    t["headers"] = body.contains("headers") && body["headers"].is_object()
+                       ? body["headers"] : nlohmann::json::object();
+    t["body"]    = body.contains("body") ? body["body"] : nlohmann::json();
+    return t;
+}
+
+nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) {
+    return {{"run_id", runId},
+            {"ok", r.ok},
+            {"status", r.status},
+            {"headers", r.headers},
+            {"body", r.body},
+            {"console", r.console},
+            {"duration_ms", r.durationMs},
+            {"error", r.error},
+            {"timed_out", r.timedOut},
+            {"out_of_memory", r.outOfMemory}};
+}
+
+}  // namespace
+
+void registerFunctionRoutes(ApiServer& s) {
+    auto& svr = s.raw(); ServerDeps* d = &s.deps();
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        d->functions.ensure(project);
+        nlohmann::json arr = nlohmann::json::array();
+        // Summaries, never full rows: a listing that shipped every function's
+        // source would grow without bound in the one response people poll.
+        for (const auto& fn : d->functions.list(project)) arr.push_back(fn.toSummaryJson());
+        sendJson(res, 200, {{"functions", arr}});
+    });
+
+    svr.Post(R"(/api/v1/projects/([^/]+)/functions)",
+             [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
+        // POST creates. An id that already exists is a genuine conflict, and
+        // answering 409 keeps a second author from quietly overwriting the
+        // first's code just because both chose the same `on.id`.
+        if (d->functions.get(project, incoming.functionId))
+            throw ApiError(ErrCode::Conflict, "function_exists",
+                           "a function with this id already exists - PUT it to update",
+                           {{"function_id", incoming.functionId}});
+        FunctionRecord stored =
+            d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
+        sendJson(res, 201, stored.toSummaryJson());
+    });
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, fn->toJson());   // the single-function view carries the source
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
+        // The id lives in the source, so the URL cannot rename a function. Say
+        // which is which: silently trusting either one would either move the
+        // code to another function's row or move a policy to other code.
+        if (incoming.functionId != id)
+            throw ApiError(ErrCode::Unprocessable, "id_mismatch",
+                           "the script's `on` block declares id '" + incoming.functionId +
+                               "' but the URL names '" + id +
+                               "' - the id is part of the source, not of the URL",
+                           {{"declared", incoming.functionId}, {"url", id}});
+        const bool existed = d->functions.get(project, id).has_value();
+        // put() preserves the stored policy and enabled flag via
+        // mergeForCodePush, which is why a push can never widen access.
+        FunctionRecord stored =
+            d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
+        sendJson(res, existed ? 200 : 201, stored.toSummaryJson());
+    });
+
+    svr.Delete(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        if (!d->functions.remove(project, id))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, {{"deleted", id}});
+    });
+
+    // ADMIN ONLY, and the only route that changes a policy. Developers push
+    // code, admins grant what it may touch - the same split keys already have.
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/policy)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireAdmin(requireKey(*d, req));
+        KeyScope policy = parsePolicy(bodyJson(req));
+        if (!d->functions.setPolicy(project, id, policy))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, fn->toSummaryJson());
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/enabled)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto body = bodyJson(req);
+        if (!body.contains("enabled") || !body["enabled"].is_boolean())
+            throw ApiError(ErrCode::Unprocessable, "validation", "enabled must be a boolean");
+        if (!d->functions.setEnabled(project, id, body["enabled"].get<bool>()))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, {{"function_id", id}, {"enabled", body["enabled"].get<bool>()}});
+    });
+
+    svr.Post(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/invoke)",
+             [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        requireRunnable(*fn);
+        RunnerPool& pool = requireRunner(*d);
+
+        const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req);
+        // A run id is just a random token with no secret meaning; generateApiKey
+        // is reused rather than adding a second hex generator.
+        const std::string runId = generateApiKey();
+        const uint64_t startedAt = static_cast<uint64_t>(std::time(nullptr));
+        RunnerRunResult r = pool.run(project, id, manualTrigger(*fn, body));
+
+        FunctionRunLog entry;
+        entry.runId      = runId;
+        entry.functionId = id;
+        entry.trigger    = "invoke";
+        entry.ok         = r.ok;
+        entry.status     = r.status;
+        entry.durationMs = r.durationMs;
+        entry.error      = r.error;
+        entry.console    = r.console;
+        entry.startedAt  = startedAt;
+        // Logged before the 503 below: an attempt that never reached a runner is
+        // exactly the one an operator goes looking for afterwards.
+        d->functionRuns.append(project, entry);
+
+        if (r.transportFailure)
+            throw ApiError(ErrCode::Unavailable, "runner_unreachable",
+                           r.error.empty() ? "the function runner could not be reached" : r.error,
+                           {{"run_id", runId}});
+        // 200 even when the function itself failed: an invoke REPORTS a run, it
+        // does not serve it. The function's own status lives in the envelope, and
+        // flattening it into the HTTP status would make "the function returned
+        // 500" indistinguishable from "the invoke could not be performed".
+        sendJson(res, 200, runEnvelope(runId, r));
+    });
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/logs)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        if (!d->functions.get(project, id))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        nlohmann::json arr = nlohmann::json::array();
+        for (const auto& e : d->functionRuns.list(project, id, limitParam(req, 50)))
+            arr.push_back(e.toJson());
+        sendJson(res, 200, {{"function_id", id}, {"runs", arr}});
+    });
+}
+
+}  // namespace svapi

+ 6 - 4
src/handlers/project_settings.cpp

@@ -26,7 +26,7 @@ void applyOverride(const nlohmann::json& body, const char* name, std::string& fi
     field = s;
 }
 
-nlohmann::json viewJson(const Settings& global, const ProjectEmbeddingSettings* p) {
+nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
     // An empty CollectionMeta means "no per-collection model pin", so this shows
     // what a collection without its own model would resolve to.
     const CollectionMeta none;
@@ -67,7 +67,7 @@ void registerProjectSettingsRoutes(ApiServer& s) {
 
         // Start from what is stored so a partial PUT leaves the rest alone.
         auto current = d->settings.projectSnapshot(project);
-        ProjectEmbeddingSettings updated = current ? *current : ProjectEmbeddingSettings{};
+        ProjectSettings updated = current ? *current : ProjectSettings{};
         updated.project = project;
         applyOverride(body, "openai_api_base", updated.openaiApiBase);
         applyOverride(body, "openai_api_key", updated.openaiApiKey);
@@ -85,8 +85,10 @@ void registerProjectSettingsRoutes(ApiServer& s) {
             throw ApiError(ErrCode::Unprocessable, "embedding_base_requires_key",
                            "openai_api_base requires openai_api_key for the same project");
 
-        // No overrides left: drop the document so the project plainly inherits.
-        if (!updated.hasOverrides()) d->settings.removeProject(project);
+        // Nothing stored at all: drop the document so the project plainly
+        // inherits. hasAnyOverrides, not hasEmbeddingOverrides - clearing an
+        // embedding override must not take a function policy with it.
+        if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
         else if (!d->settings.saveProject(updated))
             throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
 

+ 3 - 44
src/handlers/vectors.cpp

@@ -7,16 +7,11 @@
 #include "project_settings.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
+#include "vector_search.hpp"
 #include <algorithm>
-#include <unordered_set>
 namespace svapi {
 namespace {
 
-// Upper bound on how deep a filtered search will scan the similarity ranking,
-// and on how many filter-matching ids we fetch. A filtered search stays exact
-// while the collection is within this bound.
-constexpr uint32_t kFilterScanCap = 10000;
-
 // Parse the optional `filters` body field into DB filters. Same grammar and
 // operator set as the documents endpoint, because the DB evaluates them.
 std::vector<smartbotic::database::Client::Filter> parseSearchFilters(const nlohmann::json& body) {
@@ -116,44 +111,8 @@ void registerVectorRoutes(ApiServer& s) {
         auto filters = parseSearchFilters(body);
         const std::string coll = qualify(project, name);
 
-        std::vector<smartbotic::database::Client::SimilarityResult> results;
-        if (filters.empty()) {
-            results = d->db.client().similaritySearch(coll, q, topK, minScore);
-        } else {
-            // The DB evaluates the filters (same engine as /documents), so every
-            // operator behaves identically on both endpoints. It will not return
-            // the stored vectors, so scoring still has to come from
-            // similaritySearch - we intersect the two.
-            smartbotic::database::Client::QueryOptions opts;
-            opts.filters = filters;
-            opts.limit   = kFilterScanCap;
-            std::unordered_set<std::string> allowed;
-            for (const auto& doc : d->db.client().find(coll, opts)) {
-                const std::string id = doc.value("_id", "");
-                if (!id.empty()) allowed.insert(id);
-            }
-            if (!allowed.empty()) {
-                // Walk the ranking from the top, widening until topK matches are
-                // found or the collection is exhausted. Because the scan is in
-                // descending score order, stopping as soon as topK matches are
-                // collected still yields the true topK: anything unseen scores
-                // lower than everything already kept.
-                uint32_t scan = std::max<uint32_t>(topK * 4, 64);
-                while (true) {
-                    auto page = d->db.client().similaritySearch(coll, q, scan, minScore);
-                    results.clear();
-                    for (const auto& r : page) {
-                        if (!allowed.count(r.id)) continue;
-                        results.push_back(r);
-                        if (results.size() >= topK) break;
-                    }
-                    if (results.size() >= topK) break;      // enough matches
-                    if (page.size() < scan) break;          // ranking exhausted
-                    if (scan >= kFilterScanCap) break;      // bounded work
-                    scan = std::min(scan * 4, kFilterScanCap);
-                }
-            }
-        }
+        const std::vector<smartbotic::database::Client::SimilarityResult> results =
+            vectorSearch(d->db.client(), coll, q, topK, minScore, filters);
 
         nlohmann::json arr = nlohmann::json::array();
         for (const auto& r : results) arr.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});

+ 29 - 5
src/main.cpp

@@ -1,6 +1,7 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "config.hpp"
+#include <memory>
 #include "db_gateway.hpp"
 #include "key_store.hpp"
 #include "server.hpp"
@@ -70,15 +71,38 @@ int main(int argc, char** argv) {
     // from the API (GET /collections empty, document ops 404) even though the
     // data survives on disk. KeyStore::bootstrap already does this for
     // vectorapi_keys, which is why keys survive but the registry didn't. (issue #1)
-    {
-        auto projects = db.listProjects();  // always includes the default project
-        registry.bootstrap(projects);
-        spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
+    const std::vector<std::string> projects = db.listProjects();  // includes the default
+    registry.bootstrap(projects);
+    spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
+
+    svapi::FunctionRegistry functions(db);
+    svapi::FunctionRunLogStore functionRuns(db, cfg.functionRunsKept);
+    // Same reason CollectionRegistry::bootstrap exists: the database only
+    // surfaces a collection through find() once it has been opened in this
+    // process, so without this every project's function registry reads back
+    // empty after a restart even though the rows are on disk.
+    for (const std::string& project : projects) {
+        functions.ensure(project);
+        functionRuns.ensure(project);
+    }
+
+    // Null when no runners are configured, which the function routes report as
+    // 503 rather than as a missing feature.
+    std::unique_ptr<svapi::RunnerPool> runners;
+    if (!cfg.runnerEndpoints.empty()) {
+        svapi::RunnerPool::Options ro;
+        ro.endpoints = cfg.runnerEndpoints;
+        runners = std::make_unique<svapi::RunnerPool>(ro);
+        spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size());
+    } else {
+        spdlog::info("no function runners configured - function routes will answer 503");
     }
 
     svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes));
 
-    svapi::ServerDeps deps{db, settings, keys, registry, sessions, cfg.webuiDir, shareDir};
+    svapi::ServerDeps deps{db,        settings,     keys,          registry,
+                           sessions,  functions,    functionRuns,  runners.get(),
+                           cfg.webuiDir, shareDir};
     svapi::ApiServer server(std::move(deps));
     server.registerRoutes();
 

+ 17 - 0
src/principal.cpp

@@ -0,0 +1,17 @@
+#include "principal.hpp"
+#include <algorithm>
+
+namespace svapi {
+
+bool Principal::canAccess(const std::string& project) const {
+    if (admin) return true;
+    if (!projects) return false;
+    return std::find(projects->begin(), projects->end(), "*") != projects->end()
+        || std::find(projects->begin(), projects->end(), project) != projects->end();
+}
+
+Principal Principal::of(const ApiKey& k) {
+    return Principal{k.id, &k.projects, k.admin, k.scope ? &*k.scope : nullptr};
+}
+
+} // namespace svapi

+ 48 - 0
src/principal.hpp

@@ -0,0 +1,48 @@
+#pragma once
+#include "apikey.hpp"
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// Who is asking.
+///
+/// Authorization used to be expressed directly in terms of ApiKey, which was
+/// fine while every caller held one. A server-side function holds no key: it
+/// never authenticates over the wire, it IS the server, and giving it one would
+/// mean storing a usable secret inside a function definition. It still needs
+/// the same questions answered - may it reach this project, may it perform this
+/// op on this collection - and those answers must come from the SAME code, or
+/// function access and HTTP access will drift apart.
+///
+/// So Principal is the one notion of a caller: an ApiKey converts to it, and so
+/// does a function identity.
+///
+/// Holds non-owning pointers, so it must not outlive whatever it was built
+/// from. That is always a stack-local key or identity for the duration of one
+/// request or one function run.
+struct Principal {
+    /// Identifies the caller for rate limiting and attribution: a key id, or a
+    /// function id. Distinct namespaces, so a function cannot consume a key's
+    /// rate-limit budget.
+    std::string id;
+
+    /// May contain "*". Never null.
+    const std::vector<std::string>* projects = nullptr;
+
+    bool admin = false;
+
+    /// Null means unscoped: full access within the granted projects. A scoped
+    /// caller is restricted to the rules it carries.
+    const KeyScope* scope = nullptr;
+
+    /// True if admin, or the project list contains "*" or this project.
+    /// Deliberately mirrors ApiKey::canAccess, and a test pins them together.
+    bool canAccess(const std::string& project) const;
+
+    /// Explicit on purpose: an implicit conversion would make every existing
+    /// requireAdmin(key) call ambiguous against the Principal overload.
+    static Principal of(const ApiKey& k);
+};
+
+} // namespace svapi

+ 24 - 8
src/project_settings.cpp

@@ -1,28 +1,39 @@
 #include "project_settings.hpp"
 #include "collection_registry.hpp"
+#include "function_record.hpp"
 #include "settings.hpp"
 
 namespace svapi {
 
-ProjectEmbeddingSettings ProjectEmbeddingSettings::fromJson(const nlohmann::json& j) {
-    ProjectEmbeddingSettings p;
+ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
+    ProjectSettings p;
     p.project               = j.value("project", p.project);
     p.openaiApiBase         = j.value("openai_api_base", p.openaiApiBase);
     p.openaiApiKey          = j.value("openai_api_key", p.openaiApiKey);
     p.defaultEmbeddingModel = j.value("default_embedding_model", p.defaultEmbeddingModel);
+    // Absent and present-but-empty are different: an absent key means "inherit
+    // the built-in floor", while a stored empty object is an admin deliberately
+    // saying "a new function here gets nothing". Both deny, but only the second
+    // survives a change to the built-in default.
+    if (j.contains("default_function_policy") && j.at("default_function_policy").is_object())
+        p.defaultFunctionPolicy = KeyScope::fromJson(j.at("default_function_policy"));
     return p;
 }
 
-nlohmann::json ProjectEmbeddingSettings::toJson() const {
-    return {{"project", project},
-            {"openai_api_base", openaiApiBase},
-            {"openai_api_key", openaiApiKey},
-            {"default_embedding_model", defaultEmbeddingModel}};
+nlohmann::json ProjectSettings::toJson() const {
+    nlohmann::json j = {{"project", project},
+                        {"openai_api_base", openaiApiBase},
+                        {"openai_api_key", openaiApiKey},
+                        {"default_embedding_model", defaultEmbeddingModel}};
+    // Written only when set, so round-tripping a project that never configured
+    // one does not quietly pin today's built-in default into storage.
+    if (defaultFunctionPolicy) j["default_function_policy"] = defaultFunctionPolicy->toJson();
+    return j;
 }
 
 std::string projectSettingsDocId(const std::string& project) { return "project_" + project; }
 
-ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddingSettings* proj,
+ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll) {
     ResolvedEmbedding r{global.openaiApiBase, global.openaiApiKey, global.defaultEmbeddingModel};
     if (proj) {
@@ -34,4 +45,9 @@ ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddin
     return r;
 }
 
+KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj) {
+    if (proj && proj->defaultFunctionPolicy) return *proj->defaultFunctionPolicy;
+    return builtinDefaultFunctionPolicy();
+}
+
 } // namespace svapi

+ 29 - 6
src/project_settings.hpp

@@ -1,5 +1,7 @@
 #pragma once
+#include "apikey.hpp"
 #include <nlohmann/json.hpp>
+#include <optional>
 #include <string>
 
 namespace svapi {
@@ -7,7 +9,8 @@ namespace svapi {
 struct Settings;
 struct CollectionMeta;
 
-/// Per-project embedding overrides. An empty field means "inherit the global
+/// Per-project settings: embedding overrides, and the policy a newly
+/// registered function inherits. An empty field means "inherit the global
 /// value" - there is no separate presence flag, because an empty base URL, API
 /// key or model is meaningless on its own.
 ///
@@ -15,23 +18,38 @@ struct CollectionMeta;
 /// `vectorapi_settings` collection under projectSettingsDocId(project). The DB
 /// client strips a top-level `id` from stored bodies, so the project name also
 /// travels in the body as `project` (same approach as KeyStore's `key_id`).
-struct ProjectEmbeddingSettings {
+struct ProjectSettings {
     std::string project;
     std::string openaiApiBase;
     std::string openaiApiKey;
     std::string defaultEmbeddingModel;
 
-    /// True when at least one field overrides the global value.
-    bool hasOverrides() const {
+    /// The policy a function gets on FIRST registration in this project.
+    /// Unset means fall back to builtinDefaultFunctionPolicy(), which grants
+    /// nothing. Only ever consulted for a first registration - an existing
+    /// function keeps the policy an admin gave it, so changing this never
+    /// retroactively widens or narrows anything already deployed.
+    std::optional<KeyScope> defaultFunctionPolicy;
+
+    /// True when at least one EMBEDDING field overrides the global value.
+    bool hasEmbeddingOverrides() const {
         return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty();
     }
 
+    /// True when the project has anything stored at all. The settings document
+    /// is deleted when this goes false, so it has to account for every field:
+    /// keying the delete on the embedding fields alone would silently drop a
+    /// function policy the moment someone cleared an embedding override.
+    bool hasAnyOverrides() const {
+        return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value();
+    }
+
     /// A project base URL must carry its own API key, otherwise the global
     /// credential would be sent to a foreign endpoint. A project key without a
     /// base URL is fine (own key, default endpoint).
     bool baseHasItsOwnKey() const { return openaiApiBase.empty() || !openaiApiKey.empty(); }
 
-    static ProjectEmbeddingSettings fromJson(const nlohmann::json& j);
+    static ProjectSettings fromJson(const nlohmann::json& j);
     nlohmann::json toJson() const;
 };
 
@@ -50,7 +68,12 @@ struct ResolvedEmbedding {
 ///   apiBase / apiKey : project override, else global.
 ///   model            : collection pin, else project override, else global default.
 /// `proj` may be null when the project has no overrides stored.
-ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddingSettings* proj,
+ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll);
 
+/// The policy a first-time function registration in this project inherits:
+/// the project's configured default, else the built-in floor. `proj` may be
+/// null when the project has nothing stored.
+KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj);
+
 } // namespace svapi

+ 305 - 0
src/runner_client.cpp

@@ -0,0 +1,305 @@
+#include "runner_client.hpp"
+#include <httplib.h>
+#include <spdlog/spdlog.h>
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+// Why no applyOutboundDefaults() here: that helper exists for calls that leave
+// our trust boundary (embedding providers, captcha verification), where a
+// provider must see our User-Agent and must not be able to bounce a
+// credentialed request elsewhere. A runner is a first-party process from this
+// repo, addressed by a configured host:port and speaking a private protocol -
+// not a provider. Treating it as one would also drag vectorapi_core's whole
+// dependency set into a client that deliberately needs nothing but httplib,
+// which is what keeps this file testable on a host with no database client. The
+// two properties of that helper that DO matter internally are set explicitly
+// below: redirects off, and TLS verification on for an https endpoint.
+template <class Opts>
+void configureClient(httplib::Client& cli, const Opts& o) {
+    cli.set_connection_timeout(o.connectTimeoutSec, 0);
+    cli.set_read_timeout(o.readTimeoutSec, 0);
+    cli.set_write_timeout(o.readTimeoutSec, 0);
+    // A runner has no business redirecting us anywhere, and following one would
+    // turn a compromised or misconfigured runner into an SSRF primitive.
+    cli.set_follow_location(false);
+    cli.set_keep_alive(true);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+    cli.enable_server_certificate_verification(true);
+#endif
+}
+
+/// "host:port" -> "http://host:port"; an explicit scheme is kept. Trailing
+/// slashes are dropped so the base concatenates cleanly with "/run".
+std::string normalizeBase(std::string e) {
+    while (!e.empty() && e.back() == '/') e.pop_back();
+    if (e.find("://") == std::string::npos) e = "http://" + e;
+    return e;
+}
+
+/// httplib errors that prove the request never left us, so nothing ran and the
+/// next endpoint is safe to try. Everything else - a read timeout above all -
+/// means the runner may have received the request and executed the function.
+bool neverDelivered(httplib::Error e) {
+    return e == httplib::Error::Connection || e == httplib::Error::ConnectionTimeout;
+}
+
+std::string errorText(httplib::Error e) { return httplib::to_string(e); }
+
+std::vector<std::string> consoleLines(const nlohmann::json& j) {
+    std::vector<std::string> out;
+    if (!j.contains("console") || !j["console"].is_array()) return out;
+    const nlohmann::json& arr = j["console"];  // bind first: a range-for over a temporary dangles
+    for (const nlohmann::json& line : arr)
+        out.push_back(line.is_string() ? line.get<std::string>() : line.dump());
+    return out;
+}
+
+// The three helpers below are templated only so they can name RunnerPool's
+// private Endpoint type by deduction: the seam header declares no private
+// helper methods and is not ours to change, so the shared state transitions
+// live here instead of being copy-pasted into each public method.
+
+/// Indices to try, in round-robin order, skipping endpoints still inside their
+/// backoff window. Advances the rotation by one so successive calls spread.
+template <class Eps>
+std::vector<size_t> pickCandidates(Eps& eps, size_t& next, std::mutex& mu) {
+    const auto now = std::chrono::steady_clock::now();
+    std::vector<size_t> out;
+    std::lock_guard<std::mutex> lk(mu);
+    if (eps.empty()) return out;
+    const size_t start = next++ % eps.size();
+    for (size_t n = 0; n < eps.size(); ++n) {
+        const size_t i = (start + n) % eps.size();
+        // An expired backoff puts an endpoint back in rotation even while the
+        // flag still says unhealthy: the flag is a hint, the clock decides.
+        if (eps[i].healthy || now >= eps[i].notBefore) out.push_back(i);
+    }
+    return out;
+}
+
+template <class Eps>
+void markHealthy(Eps& eps, size_t i, std::mutex& mu) {
+    std::lock_guard<std::mutex> lk(mu);
+    eps[i].healthy = true;
+    eps[i].notBefore = {};
+    eps[i].lastError.clear();
+}
+
+template <class Eps>
+void markUnhealthy(Eps& eps, size_t i, std::mutex& mu, uint32_t backoffSec,
+                   const std::string& why) {
+    std::lock_guard<std::mutex> lk(mu);
+    const bool wasHealthy = eps[i].healthy;
+    eps[i].healthy = false;
+    eps[i].lastError = why;
+    eps[i].notBefore = std::chrono::steady_clock::now() + std::chrono::seconds(backoffSec);
+    // Only on the transition, or a hard-down runner floods the log once per request.
+    if (wasHealthy) spdlog::warn("runner {} marked unhealthy: {}", eps[i].base, why);
+}
+
+/// Turn a protocol response into a run result. NEVER a transport failure:
+/// reaching here means a runner answered, so whatever went wrong is the
+/// function's, not ours. A thrown exception, a wall-time timeout and an
+/// out-of-memory kill all arrive this way - the runner did its job and reported
+/// the outcome, which is precisely why none of them is retried.
+RunnerRunResult parseRun(const nlohmann::json& j) {
+    RunnerRunResult out;
+    out.transportFailure = false;
+    out.timedOut = j.value("timed_out", false);
+    out.outOfMemory = j.value("out_of_memory", false);
+    out.error = j.value("error", std::string{});
+    // `ok` is honoured when the runner sends it, so a runner can report a
+    // failure that carries no message; otherwise it is derived.
+    out.ok = j.contains("ok") && j["ok"].is_boolean()
+                 ? j["ok"].get<bool>()
+                 : (out.error.empty() && !out.timedOut && !out.outOfMemory);
+    out.status = j.contains("status") && j["status"].is_number_integer()
+                     ? j["status"].get<int>() : 200;
+    if (j.contains("headers") && j["headers"].is_object()) out.headers = j["headers"];
+    if (j.contains("body")) out.body = j["body"];
+    out.console = consoleLines(j);
+    out.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
+    return out;
+}
+
+} // namespace
+
+RunnerPool::RunnerPool(Options opts) : opts_(std::move(opts)) {
+    for (const std::string& e : opts_.endpoints) {
+        Endpoint ep;
+        ep.base = normalizeBase(e);
+        // Optimistically healthy: with no probe yet, refusing to dispatch would
+        // make a cold start look like an outage.
+        ep.healthy = true;
+        endpoints_.push_back(std::move(ep));
+    }
+}
+
+bool RunnerPool::anyHealthy() {
+    // Probes rather than trusting the cached flag: "answered /health recently"
+    // is a claim about the runner now, and a stale true is the dangerous
+    // direction - a function write would then be validated against nothing.
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Get("/health");
+        if (r && r->status == 200) {
+            markHealthy(endpoints_, i, mu_);
+            return true;
+        }
+        markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                      r ? ("health status " + std::to_string(r->status)) : errorText(r.error()));
+    }
+    return false;
+}
+
+RunnerRunResult RunnerPool::run(const std::string& project, const std::string& functionId,
+                                const nlohmann::json& trigger) {
+    const nlohmann::json payload{{"project", project},
+                                 {"function_id", functionId},
+                                 {"trigger", trigger}};
+    RunnerRunResult last;
+    last.ok = false;
+    last.transportFailure = true;
+    last.status = 503;
+    last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
+
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Post("/run", payload.dump(), "application/json");
+
+        if (!r) {
+            const std::string why = errorText(r.error());
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, why);
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner unreachable: " + why;
+            if (neverDelivered(r.error())) continue;  // nothing ran; the next runner is safe
+            // Delivered but unanswered: the handler may be running right now, so
+            // the caller gets an error and NOBODY runs it again.
+            spdlog::error("runner {} did not answer /run for {}/{}: {} - not retried, the run "
+                          "may already have had side effects", base, project, functionId, why);
+            return last;
+        }
+        if (r->status != 200) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "run status " + std::to_string(r->status));
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner returned HTTP " + std::to_string(r->status);
+            return last;  // off-protocol AFTER delivery: same reasoning as above
+        }
+
+        nlohmann::json j;
+        try {
+            j = nlohmann::json::parse(r->body);
+        } catch (const std::exception& e) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          std::string("unparseable /run response: ") + e.what());
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner response was not JSON";
+            return last;
+        }
+        if (!j.is_object()) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "non-object /run response");
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner response was not an object";
+            return last;
+        }
+
+        markHealthy(endpoints_, i, mu_);
+        return parseRun(j);
+    }
+    return last;
+}
+
+RunnerValidateResult RunnerPool::validate(const std::string& source, const std::string& path) {
+    const nlohmann::json payload{{"source", source}, {"path", path}};
+    RunnerValidateResult last;
+    last.ok = false;
+    last.transportFailure = true;
+    last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
+
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Post("/validate", payload.dump(), "application/json");
+
+        // Unlike run(), EVERY failure here is retryable. Compiling a script and
+        // reading its `on` block has no side effects, so a second attempt
+        // elsewhere can only turn a 503 into an answer; the double-execution
+        // hazard that constrains run() does not exist on this path.
+        if (!r) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, errorText(r.error()));
+            last.transportFailure = true;
+            last.error = "runner unreachable: " + errorText(r.error());
+            continue;
+        }
+        if (r->status != 200) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "validate status " + std::to_string(r->status));
+            last.transportFailure = true;
+            last.error = "runner returned HTTP " + std::to_string(r->status);
+            continue;
+        }
+        nlohmann::json j;
+        try {
+            j = nlohmann::json::parse(r->body);
+        } catch (const std::exception& e) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          std::string("unparseable /validate response: ") + e.what());
+            last.transportFailure = true;
+            last.error = "runner response was not JSON";
+            continue;
+        }
+        if (!j.is_object()) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "non-object /validate response");
+            last.transportFailure = true;
+            last.error = "runner response was not an object";
+            continue;
+        }
+
+        markHealthy(endpoints_, i, mu_);
+        RunnerValidateResult out;
+        out.transportFailure = false;
+        out.ok = j.value("ok", false);
+        out.error = j.value("error", std::string{});
+        if (j.contains("descriptor") && j["descriptor"].is_object())
+            out.descriptor = j["descriptor"];
+        return out;
+    }
+    return last;
+}
+
+nlohmann::json RunnerPool::statusJson() {
+    const auto now = std::chrono::steady_clock::now();
+    nlohmann::json arr = nlohmann::json::array();
+    size_t healthyCount = 0;
+    std::lock_guard<std::mutex> lk(mu_);
+    for (const Endpoint& ep : endpoints_) {
+        int64_t retryIn = 0;
+        if (!ep.healthy && ep.notBefore > now)
+            retryIn = std::chrono::duration_cast<std::chrono::seconds>(ep.notBefore - now).count();
+        if (ep.healthy) ++healthyCount;
+        arr.push_back({{"endpoint", ep.base},
+                       {"healthy", ep.healthy},
+                       {"last_error", ep.lastError},
+                       {"retry_in_sec", retryIn}});
+    }
+    return {{"runners", arr}, {"healthy", healthyCount}};
+}
+
+} // namespace svapi

+ 101 - 0
src/runner_client.hpp

@@ -0,0 +1,101 @@
+#pragma once
+#include <nlohmann/json.hpp>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// What one runner reported for one run.
+struct RunnerRunResult {
+    bool ok = false;
+    int status = 200;
+    nlohmann::json headers = nlohmann::json::object();
+    nlohmann::json body;
+    std::vector<std::string> console;
+    int64_t durationMs = 0;
+    std::string error;
+    bool timedOut = false;
+    bool outOfMemory = false;
+    /// True when no runner gave a usable answer, as opposed to a runner
+    /// reporting that the function failed. The two map to different HTTP
+    /// statuses: the first is our problem, the second is the function's.
+    ///
+    /// Covers both "never connected" and the more dangerous "connected, then
+    /// gave nothing usable" - a read timeout, a non-200, an unparseable body.
+    /// Only the first of those is safe to retry, because in the second the
+    /// handler may be running right now; see the three-way split in
+    /// runner_client.cpp.
+    bool transportFailure = false;
+};
+
+struct RunnerValidateResult {
+    bool ok = false;
+    /// The parsed `on` block, when the script compiled.
+    nlohmann::json descriptor;
+    std::string error;
+    bool transportFailure = false;
+};
+
+/// A static list of runners, health-checked, used round-robin.
+///
+/// Discovery is a config list on purpose: dynamic registration is only worth its
+/// failure modes once autoscaling exists. A run is retried on the next healthy
+/// runner, because a runner dying between the health check and the request is
+/// ordinary, not exceptional.
+class RunnerPool {
+public:
+    struct Options {
+        std::vector<std::string> endpoints;  // "host:port" or full base URLs
+        uint32_t connectTimeoutSec = 2;
+        /// MUST exceed the runner's `max_wall_time_ms`, or our read times out
+        /// before the runner can report its own timeout and the caller gets a
+        /// 503 ("no runner available") instead of the truthful 504. The
+        /// defaults here and in runner/config/runner.json satisfy that with
+        /// room to spare (30 s against 2 s); raising the runner's ceiling means
+        /// raising this too.
+        uint32_t readTimeoutSec = 30;
+        /// How long a failed runner is skipped before being retried.
+        uint32_t unhealthyBackoffSec = 10;
+    };
+
+    explicit RunnerPool(Options opts);
+
+    /// True when at least one runner answered /health recently. Creating or
+    /// updating a function requires this: a write is validated by the engine
+    /// that will execute it, so with no runner there is nothing to validate
+    /// against and the write is refused with 503 rather than stored unchecked.
+    bool anyHealthy();
+
+    /// POST /run on the first healthy runner. Retried on the next endpoint ONLY
+    /// when the connection was never established, so nothing can have run: a
+    /// request that was delivered and then went unanswered is NOT retried,
+    /// because the handler may be executing and a retry would run a
+    /// side-effecting function twice. `trigger` is
+    /// {method, path, params, query, headers, body}.
+    RunnerRunResult run(const std::string& project, const std::string& functionId,
+                        const nlohmann::json& trigger);
+
+    /// POST /validate - compile `source` and parse its `on` block without
+    /// running the handler.
+    RunnerValidateResult validate(const std::string& source, const std::string& path);
+
+    /// Endpoints with their last known health, for the admin UI and /healthz.
+    nlohmann::json statusJson();
+
+private:
+    struct Endpoint {
+        std::string base;
+        bool healthy = true;
+        std::chrono::steady_clock::time_point notBefore{};
+        std::string lastError;
+    };
+    Options opts_;
+    std::mutex mu_;
+    std::vector<Endpoint> endpoints_;
+    size_t next_ = 0;
+};
+
+} // namespace svapi

+ 41 - 8
src/server.cpp

@@ -32,10 +32,38 @@ ApiKey requireKey(ServerDeps& d, const httplib::Request& req) {
     if (auto k = resolveKey(d, req)) return *k;
     throw ApiError(ErrCode::Unauthorized, "unauthorized", "missing or invalid credentials");
 }
-void requireAdmin(const ApiKey& k) {
-    if (!k.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
+// --- Principal forms: the real implementations --------------------------------
+
+void requireAdmin(const Principal& p) {
+    if (!p.admin) throw ApiError(ErrCode::Forbidden, "forbidden", "admin privilege required");
+}
+void requireProjectAccess(const Principal& p, const std::string& project) {
+    if (!p.canAccess(project))
+        throw ApiError(ErrCode::Forbidden, "forbidden", "not granted project '" + project + "'");
+}
+void requireProjectManage(const Principal& p, const std::string& project) {
+    requireProjectAccess(p, project);
+    if (p.scope)
+        throw ApiError(ErrCode::Forbidden, "forbidden", "scoped callers cannot manage collections");
+}
+
+void requireCapabilityCore(const Principal& p, const std::string& project,
+                           const std::string& collection, KeyOp op) {
+    requireProjectAccess(p, project);
+    if (!p.scope) return;                                   // unscoped: full access
+    const KeyScope& sc = *p.scope;
+    if (!sc.findRule(collection, op))
+        throw ApiError(ErrCode::Forbidden, "forbidden", "scope does not permit this operation");
+    if (!rateLimiter().allow(p.id, sc.rateLimitPerMin))
+        throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
 }
+
+// --- ApiKey forms: kept so no handler changes, and so the HTTP-only checks
+// --- (Origin, captcha) stay where a request actually exists.
+
+void requireAdmin(const ApiKey& k) { requireAdmin(Principal::of(k)); }
 void requireProjectAccess(const ApiKey& k, const std::string& project) {
+    // Message keeps saying "key" here: this form is only reached by a key holder.
     if (!k.canAccess(project))
         throw ApiError(ErrCode::Forbidden, "forbidden", "key not granted project '" + project + "'");
 }
@@ -47,18 +75,15 @@ void requireProjectManage(const ApiKey& k, const std::string& project) {
 
 void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
                        const std::string& project, const std::string& collection, KeyOp op) {
-    requireProjectAccess(k, project);
+    // Grant, rule and rate limit are the caller-agnostic part.
+    requireCapabilityCore(Principal::of(k), project, collection, op);
     if (!k.scope) return;                                   // legacy full-access key
     const KeyScope& sc = *k.scope;
-    const KeyScopeRule* rule = sc.findRule(collection, op);
-    if (!rule)
-        throw ApiError(ErrCode::Forbidden, "forbidden", "key scope does not permit this operation");
+    const KeyScopeRule* rule = sc.findRule(collection, op);  // re-read for requireHumanToken
     std::string origin;
     if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
     if (!sc.originAllowed(origin))
         throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
-    if (!rateLimiter().allow(k.id, sc.rateLimitPerMin))
-        throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
     if (rule->requireHumanToken) {
         std::string token;
         if (auto it = req.headers.find("X-Captcha-Token"); it != req.headers.end()) token = it->second;
@@ -86,6 +111,9 @@ void ApiServer::registerRoutes() {
         if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
             && req.path.rfind("/api/", 0) != 0
             && req.path.rfind("/ui/", 0) != 0
+            // /fn/* is user function dispatch: a path that matches no function
+            // owes the caller a real 404, not the SPA shell with status 200.
+            && req.path.rfind("/fn/", 0) != 0
             && req.path.rfind("/docs", 0) != 0
             && req.path != "/openapi.json" && req.path != "/llms.txt"
             && req.path != "/healthz" && req.path != "/readyz"
@@ -141,6 +169,11 @@ void ApiServer::registerRoutes() {
     registerSettingsRoutes(*this);
     registerProjectSettingsRoutes(*this);
     registerRelationRoutes(*this);
+    registerFunctionRoutes(*this);
+    // LAST. Function dispatch owns /fn/* , and registering it after the
+    // built-in routes means a user function can never shadow one of them even
+    // if cpp-httplib's matching order ever changes.
+    registerFunctionDispatchRoutes(*this);
 
     if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
     if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);

+ 27 - 0
src/server.hpp

@@ -3,6 +3,10 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "db_gateway.hpp"
+#include "function_registry.hpp"
+#include "function_run_log.hpp"
+#include "principal.hpp"
+#include "runner_client.hpp"
 #include "key_store.hpp"
 #include "settings_store.hpp"
 #include <httplib.h>
@@ -17,6 +21,11 @@ struct ServerDeps {
     KeyStore& keys;
     CollectionRegistry& registry;
     SessionStore& sessions;
+    FunctionRegistry& functions;
+    FunctionRunLogStore& functionRuns;
+    /// Null when no runner endpoints are configured: the function routes then
+    /// answer 503 rather than pretending the feature is absent.
+    RunnerPool* runners = nullptr;
     std::string webuiDir;   // static SPA root ("" disables)
     std::string shareDir;   // openapi.json + llms.txt dir
 };
@@ -48,6 +57,20 @@ void   requireProjectManage(const ApiKey& k, const std::string& project);  // th
 void   requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
                          const std::string& project, const std::string& collection, KeyOp op);
 
+// The same checks expressed for any caller, not just a key holder. The ApiKey
+// forms above delegate here, and a server-side function - which has no key, no
+// origin and no captcha token - calls these directly, so both paths are
+// authorized by one implementation.
+void   requireAdmin(const Principal& p);
+void   requireProjectAccess(const Principal& p, const std::string& project);
+void   requireProjectManage(const Principal& p, const std::string& project);
+
+// Project grant + scope rule + rate limit. Everything that needs an HTTP
+// request (Origin allow-list, captcha) stays in the ApiKey overload above,
+// because those questions are meaningless for a cron or event-triggered run.
+void   requireCapabilityCore(const Principal& p, const std::string& project,
+                             const std::string& collection, KeyOp op);
+
 // Shared with handlers/relations.cpp; documents.cpp needs them for the 409 payload
 // on a relation-blocked delete.
 std::string unqualify(const std::string& project, const std::string& name);
@@ -67,5 +90,9 @@ void registerStatsRoutes(ApiServer&);
 void registerSettingsRoutes(ApiServer&);
 void registerProjectSettingsRoutes(ApiServer&);
 void registerRelationRoutes(ApiServer&);
+void registerFunctionRoutes(ApiServer&);
+// Registered LAST: it claims /fn/* , and a function route must never shadow
+// a built-in /api/* route.
+void registerFunctionDispatchRoutes(ApiServer&);
 
 } // namespace svapi

+ 4 - 4
src/settings_store.cpp

@@ -30,7 +30,7 @@ void SettingsStore::reloadProjectsFromDb() {
     auto docs = db_.client().find(coll_, opts);
     auto m = std::make_shared<ProjectMap>();
     for (const auto& d : docs) {
-        ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(d);
+        ProjectSettings p = ProjectSettings::fromJson(d);
         // The global settings document lives in the same collection and carries
         // no `project` field - that absence is what tells the two apart.
         if (p.project.empty()) continue;
@@ -38,13 +38,13 @@ void SettingsStore::reloadProjectsFromDb() {
         // before the left, so inlining std::move(p) would move the name out
         // from under (*m)[p.project] and file the entry under "".
         const std::string name = p.project;
-        (*m)[name] = std::make_shared<const ProjectEmbeddingSettings>(std::move(p));
+        (*m)[name] = std::make_shared<const ProjectSettings>(std::move(p));
     }
     std::lock_guard<std::mutex> lk(m_);
     projects_ = m;
 }
 
-std::shared_ptr<const ProjectEmbeddingSettings>
+std::shared_ptr<const ProjectSettings>
 SettingsStore::projectSnapshot(const std::string& project) const {
     std::shared_ptr<const ProjectMap> m;
     {
@@ -55,7 +55,7 @@ SettingsStore::projectSnapshot(const std::string& project) const {
     return it == m->end() ? nullptr : it->second;
 }
 
-bool SettingsStore::saveProject(const ProjectEmbeddingSettings& p) {
+bool SettingsStore::saveProject(const ProjectSettings& p) {
     if (p.project.empty()) return false;
     db_.client().upsert(coll_, p.toJson(), projectSettingsDocId(p.project));
     reloadProjectsFromDb();

+ 11 - 4
src/settings_store.hpp

@@ -9,6 +9,13 @@
 
 namespace svapi {
 
+/// The collection holding the global settings document and the per-project
+/// override documents. Named here rather than spelled out at each use: the
+/// runner reads the same two documents through its own gateway, and a second
+/// spelling of this name would mean a function silently resolving its
+/// embedding config against a collection nobody writes.
+constexpr const char* kSettingsCollection = "vectorapi_settings";
+
 /// DB-backed settings store. Holds two things that share one collection and
 /// therefore one change subscription: the global settings document
 /// (`vectorapi_settings/current`) and the per-project embedding overrides
@@ -18,7 +25,7 @@ namespace svapi {
 class SettingsStore {
 public:
     SettingsStore(DbGateway& db,
-                  std::string collection = "vectorapi_settings",
+                  std::string collection = kSettingsCollection,
                   std::string docId     = "current");
 
     /// Ensure the (encrypted) collection exists.  Load or seed the settings
@@ -38,11 +45,11 @@ public:
 
     /// Per-project embedding overrides, or nullptr when the project inherits
     /// everything (thread-safe, lock-free after copy).
-    std::shared_ptr<const ProjectEmbeddingSettings> projectSnapshot(const std::string& project) const;
+    std::shared_ptr<const ProjectSettings> projectSnapshot(const std::string& project) const;
 
     /// Persist one project's overrides (`p.project` names it) and refresh the
     /// project snapshot. Returns true on success.
-    bool saveProject(const ProjectEmbeddingSettings& p);
+    bool saveProject(const ProjectSettings& p);
 
     /// Drop a project's overrides so it inherits the global settings again.
     /// Returns false when the project had no overrides stored.
@@ -57,7 +64,7 @@ private:
     /// Reload every `project_*` document into the project snapshot map.
     void reloadProjectsFromDb();
 
-    using ProjectMap = std::unordered_map<std::string, std::shared_ptr<const ProjectEmbeddingSettings>>;
+    using ProjectMap = std::unordered_map<std::string, std::shared_ptr<const ProjectSettings>>;
 
     DbGateway&   db_;
     std::string  coll_;

+ 49 - 0
src/vector_search.cpp

@@ -0,0 +1,49 @@
+#include "vector_search.hpp"
+#include <algorithm>
+#include <unordered_set>
+
+namespace svapi {
+
+std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+    smartbotic::database::Client& client, const std::string& coll,
+    const std::vector<float>& query, uint32_t topK, float minScore,
+    const std::vector<smartbotic::database::Client::Filter>& filters) {
+    if (filters.empty()) return client.similaritySearch(coll, query, topK, minScore);
+
+    smartbotic::database::Client::QueryOptions opts;
+    opts.filters = filters;
+    opts.limit   = kVectorFilterScanCap;
+    std::unordered_set<std::string> allowed;
+    // Bind the result before iterating: a range-for over a temporary dangles
+    // (CLAUDE.md).
+    const std::vector<nlohmann::json> matched = client.find(coll, opts);
+    for (const auto& doc : matched) {
+        const std::string id = doc.value("_id", "");
+        if (!id.empty()) allowed.insert(id);
+    }
+    std::vector<smartbotic::database::Client::SimilarityResult> results;
+    if (allowed.empty()) return results;
+
+    // Walk the ranking from the top, widening until topK matches are found or
+    // the ranking is exhausted. Because the scan is in descending score order,
+    // stopping as soon as topK matches are collected still yields the true
+    // topK: anything unseen scores lower than everything already kept.
+    uint32_t scan = std::max<uint32_t>(topK * 4, 64);
+    while (true) {
+        const std::vector<smartbotic::database::Client::SimilarityResult> page =
+            client.similaritySearch(coll, query, scan, minScore);
+        results.clear();
+        for (const auto& r : page) {
+            if (!allowed.count(r.id)) continue;
+            results.push_back(r);
+            if (results.size() >= topK) break;
+        }
+        if (results.size() >= topK) break;            // enough matches
+        if (page.size() < scan) break;                // ranking exhausted
+        if (scan >= kVectorFilterScanCap) break;      // bounded work
+        scan = std::min(scan * 4, kVectorFilterScanCap);
+    }
+    return results;
+}
+
+} // namespace svapi

+ 33 - 0
src/vector_search.hpp

@@ -0,0 +1,33 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <smartbotic/database/client.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// The most candidates a filtered vector search will scan. Bounds the work one
+/// request can cost; a query whose filter matches only deep in the ranking
+/// returns fewer than top_k rather than walking the whole collection.
+constexpr uint32_t kVectorFilterScanCap = 10000;
+
+/// Vector similarity search with optional database-evaluated filters.
+///
+/// ONE implementation on purpose. This is reached from the HTTP route
+/// (`handlers/vectors.cpp`) and from a function's `ctx.collections(...).search()`
+/// in the runner, and the two must not drift: the project guarantees that a
+/// filter means the same thing wherever it is written (CLAUDE.md, "Filters").
+/// When this lived in the route's lambda, the runner had to copy it, cap and
+/// loop included.
+///
+/// `filters` are evaluated by the database, the same engine `/documents` uses,
+/// so every operator behaves identically on both. The database will not return
+/// stored vectors, so scoring still comes from similaritySearch and the two
+/// results are intersected - which means scores are identical to those of an
+/// unfiltered query.
+std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+    smartbotic::database::Client& client, const std::string& qualifiedCollection,
+    const std::vector<float>& query, uint32_t topK, float minScore,
+    const std::vector<smartbotic::database::Client::Filter>& filters);
+
+} // namespace svapi

+ 61 - 0
tests/CMakeLists.txt

@@ -77,3 +77,64 @@ gtest_discover_tests(test_project_settings)
 add_executable(test_outbound_http test_outbound_http.cpp)
 target_link_libraries(test_outbound_http PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_outbound_http)
+
+add_executable(test_principal test_principal.cpp)
+target_link_libraries(test_principal PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_principal)
+
+# The two function-runtime units below are pure: no database client, no I/O. They
+# compile their sources directly instead of linking vectorapi_core, so these two
+# targets still build and run on a host where smartbotic-db-client cannot compile
+# (see CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+add_executable(test_functions_descriptor
+    test_functions_descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp)
+target_include_directories(test_functions_descriptor PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_descriptor PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_functions_descriptor)
+
+add_executable(test_functions_net_guard
+    test_functions_net_guard.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/net_guard.cpp)
+target_include_directories(test_functions_net_guard PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_net_guard PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_functions_net_guard)
+
+# Pure half of the function registry (record shape + the code-push merge rule);
+# no database client, so it builds on the Void dev host too.
+add_executable(test_function_record
+    test_function_record.cpp
+    ${CMAKE_SOURCE_DIR}/src/function_record.cpp
+    ${CMAKE_SOURCE_DIR}/src/apikey.cpp)
+target_include_directories(test_function_record PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_function_record PRIVATE
+    nlohmann_json::nlohmann_json OpenSSL::Crypto GTest::gtest_main)
+gtest_discover_tests(test_function_record)
+
+# The run-log store against a link-time fake database: the test defines the few
+# Client members the store calls, so this target must NOT link vectorapi_core,
+# which would bring the real client back and fail to link on the dev host. It
+# needs the client's headers only.
+add_executable(test_function_run_log
+    test_function_run_log.cpp
+    ${CMAKE_SOURCE_DIR}/src/function_run_log.cpp)
+target_include_directories(test_function_run_log PRIVATE
+    ${CMAKE_SOURCE_DIR}/src
+    $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)
+target_link_libraries(test_function_run_log PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_function_run_log)
+
+# RunnerPool talks to nothing but httplib, so this target compiles its source
+# directly rather than linking vectorapi_core, and still builds and runs on a
+# host where smartbotic-db-client cannot compile.
+add_executable(test_runner_client
+    test_runner_client.cpp
+    ${CMAKE_SOURCE_DIR}/src/runner_client.cpp)
+target_include_directories(test_runner_client PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_compile_definitions(test_runner_client PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT)
+target_link_libraries(test_runner_client PRIVATE
+    httplib::httplib nlohmann_json::nlohmann_json spdlog::spdlog
+    OpenSSL::SSL OpenSSL::Crypto GTest::gtest_main)
+gtest_discover_tests(test_runner_client)

+ 9 - 1
tests/api_fixture.hpp

@@ -16,6 +16,8 @@ class ApiFixture : public ::testing::Test {
 protected:
     std::unique_ptr<DbGateway> db_;
     std::unique_ptr<CollectionRegistry> registry_;
+    std::unique_ptr<FunctionRegistry> functions_;
+    std::unique_ptr<FunctionRunLogStore> functionRuns_;
     std::unique_ptr<SettingsStore> settings_;
     std::unique_ptr<KeyStore> keys_;
     std::unique_ptr<SessionStore> sessions_;
@@ -49,6 +51,8 @@ protected:
         db_->ensureProject(project_);
 
         registry_ = std::make_unique<CollectionRegistry>(*db_);
+        functions_ = std::make_unique<FunctionRegistry>(*db_);
+        functionRuns_ = std::make_unique<FunctionRunLogStore>(*db_, 50);
         registry_->ensure(project_);
         settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
         settings_->bootstrap("");
@@ -76,7 +80,11 @@ protected:
         std::ofstream(webuiDir_ + "/index.html")
             << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
 
-        ServerDeps deps{*db_, *settings_, *keys_, *registry_, *sessions_, webuiDir_, apiDocsDir()};
+        // `runners` stays null: these tests have no function runner, and the
+        // function routes answer 503 for that, which is itself worth asserting.
+        ServerDeps deps{*db_,      *settings_,  *keys_,         *registry_,
+                        *sessions_, *functions_, *functionRuns_, nullptr,
+                        webuiDir_,  apiDocsDir()};
         server_ = std::make_unique<ApiServer>(std::move(deps));
         server_->registerRoutes();
         port_ = server_->bindToAnyPort("127.0.0.1");

+ 3 - 3
tests/test_api_integration.cpp

@@ -1282,7 +1282,7 @@ std::string projSettingsPath(const std::string& project) {
 }
 }  // namespace
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsDefaultToInherited) {
+TEST_F(ApiFixture, ProjectSettingsDefaultToInherited) {
     auto c = admin();
     auto r = c.Get(projSettingsPath(project_).c_str());
     ASSERT_EQ(r->status, 200);
@@ -1344,14 +1344,14 @@ TEST_F(ApiFixture, ProjectOverrideClearedWithExplicitNull) {
     EXPECT_EQ(j["overrides"]["default_embedding_model"], "");
 }
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsRejectEmptyStringValues) {
+TEST_F(ApiFixture, ProjectSettingsRejectEmptyStringValues) {
     auto c = admin();
     auto r = c.Put(projSettingsPath(project_).c_str(),
         nlohmann::json{{"default_embedding_model", ""}}.dump(), "application/json");
     EXPECT_EQ(r->status, 422);
 }
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsAuthorization) {
+TEST_F(ApiFixture, ProjectSettingsAuthorization) {
     auto c = admin();
     // A plain (non-admin, unscoped) key granted this project may manage it.
     auto mk = c.Post("/api/v1/keys",

+ 6 - 0
tests/test_errors.cpp

@@ -48,3 +48,9 @@ TEST(Errors, ErrorBodyOmitsEmptyDetails) {
     auto body = svapi::errorBody("validation", "bad");
     EXPECT_FALSE(body["error"].contains("details"));
 }
+
+TEST(Errors, GatewayTimeoutIsFiveOhFour) {
+    // Added for function dispatch: a function that blew its wall-time budget is
+    // an upstream that did not answer, not a slow client (which would be 408).
+    EXPECT_EQ(httpStatus(ErrCode::GatewayTimeout), 504);
+}

+ 251 - 0
tests/test_function_record.cpp

@@ -0,0 +1,251 @@
+#include <gtest/gtest.h>
+#include "function_record.hpp"
+using namespace svapi;
+
+namespace {
+
+KeyScope scopeWith(const std::string& collection, std::set<KeyOp> ops,
+                   uint32_t rateLimit = 0) {
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = collection;
+    r.ops = std::move(ops);
+    s.rules.push_back(r);
+    s.rateLimitPerMin = rateLimit;
+    return s;
+}
+
+FunctionRecord stored(const std::string& id, KeyScope policy) {
+    FunctionRecord f;
+    f.functionId = id;
+    f.path = "functions/" + id + ".js";
+    f.source = "export default () => 1";
+    f.contentHash = functionContentHash(f.source);
+    f.descriptor = {{"id", id}, {"type", "http"}, {"route", "/" + id}};
+    f.policy = std::move(policy);
+    f.enabled = true;
+    f.valid = true;
+    f.createdAt = 1000;
+    f.updatedAt = 1000;
+    return f;
+}
+
+/// Does `policy` let `op` through on `collection`?
+bool allows(const KeyScope& policy, const std::string& collection, KeyOp op) {
+    return policy.findRule(collection, op) != nullptr;
+}
+
+} // namespace
+
+// ----------------------------------------------------------- content hash
+
+TEST(FunctionContentHash, IsStableAndLowerCaseHex) {
+    const std::string h = functionContentHash("export default () => 1");
+    EXPECT_EQ(h.size(), 64u) << "sha256 hex is 64 characters";
+    EXPECT_EQ(h, functionContentHash("export default () => 1"));
+    for (const char c : h)
+        EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) << "not lower-case hex: " << c;
+}
+
+TEST(FunctionContentHash, ChangesWhenASingleByteChanges) {
+    // The runner caches compiled bytecode by this hash. A collision between two
+    // different sources would run yesterday's code.
+    EXPECT_NE(functionContentHash("a"), functionContentHash("b"));
+    EXPECT_NE(functionContentHash("return 1"), functionContentHash("return 1 "));
+}
+
+TEST(FunctionContentHash, HandlesEmptySource) {
+    EXPECT_EQ(functionContentHash("").size(), 64u);
+}
+
+// ------------------------------------------------------------ JSON shape
+
+TEST(FunctionRecord, RoundTripsThroughJson) {
+    const FunctionRecord in = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read, KeyOp::List}, 60));
+    const FunctionRecord out = FunctionRecord::fromJson(in.toJson());
+
+    EXPECT_EQ(out.functionId, in.functionId);
+    EXPECT_EQ(out.path, in.path);
+    EXPECT_EQ(out.source, in.source);
+    EXPECT_EQ(out.contentHash, in.contentHash);
+    EXPECT_EQ(out.descriptor, in.descriptor);
+    EXPECT_EQ(out.enabled, in.enabled);
+    EXPECT_EQ(out.valid, in.valid);
+    EXPECT_EQ(out.createdAt, in.createdAt);
+    EXPECT_EQ(out.updatedAt, in.updatedAt);
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete));
+    EXPECT_EQ(out.policy.rateLimitPerMin, 60u);
+}
+
+TEST(FunctionRecord, StoresIdentityAsFunctionIdNotId) {
+    // The database client strips a top-level `id` from stored bodies, so a
+    // record keyed on `id` would come back with no identity at all.
+    const nlohmann::json j = stored("kb-search", KeyScope{}).toJson();
+    EXPECT_TRUE(j.contains("function_id"));
+    EXPECT_EQ(j.at("function_id"), "kb-search");
+    EXPECT_FALSE(j.contains("id")) << "a top-level id would be stripped by the DB client";
+}
+
+TEST(FunctionRecord, SummaryOmitsTheSourceButKeepsTheHash) {
+    // Listing every function should not ship every function's whole body; the
+    // hash is what a client needs to tell whether its copy is current.
+    const nlohmann::json j = stored("kb-search", KeyScope{}).toSummaryJson();
+    EXPECT_FALSE(j.contains("source"));
+    EXPECT_TRUE(j.contains("content_hash"));
+    EXPECT_EQ(j.at("function_id"), "kb-search");
+}
+
+TEST(FunctionRecord, MissingFieldsParseToSafeDefaults) {
+    const FunctionRecord f = FunctionRecord::fromJson(nlohmann::json::object());
+    EXPECT_TRUE(f.functionId.empty());
+    EXPECT_TRUE(f.policy.rules.empty()) << "an absent policy must grant nothing";
+    EXPECT_TRUE(f.descriptor.is_object());
+}
+
+// --------------------------------------------- the code-push merge rule
+
+TEST(MergeForCodePush, FirstRegistrationInheritsTheProjectDefault) {
+    const KeyScope projectDefault = scopeWith("kb_*", {KeyOp::Read, KeyOp::List});
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(nullptr, incoming, projectDefault);
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete));
+}
+
+TEST(MergeForCodePush, APushCannotWidenItsOwnPolicy) {
+    // The whole point. A function author pushing code is not an admin, so a
+    // policy in the payload is ignored - never merged, never unioned.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", scopeWith("*", {KeyOp::Read, KeyOp::Insert,
+                                                                  KeyOp::Update, KeyOp::Delete}));
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+    EXPECT_FALSE(allows(out.policy, "kb_chunks", KeyOp::Delete)) << "the push widened its policy";
+    EXPECT_FALSE(allows(out.policy, "secrets", KeyOp::Read)) << "the push reached a new collection";
+}
+
+TEST(MergeForCodePush, APushCannotNarrowOrClearItsPolicyEither) {
+    // Not a security hole, but the same rule: policy is server state. A push
+    // carrying an empty policy must not wipe what an admin granted, or every
+    // deploy from a client that omits the field would silently break the
+    // function.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, FirstRegistrationIgnoresAClaimedPolicyToo) {
+    // A first push must not be able to grant itself anything by arriving with a
+    // policy before any admin has looked at it.
+    FunctionRecord incoming = stored("kb-search", scopeWith("*", {KeyOp::Delete}));
+
+    const FunctionRecord out = mergeForCodePush(nullptr, incoming, scopeWith("kb_*", {KeyOp::Read}));
+
+    EXPECT_FALSE(allows(out.policy, "anything", KeyOp::Delete));
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, CodeAndDescriptorComeFromThePush) {
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.source = "export default () => 2";
+    incoming.contentHash = functionContentHash(incoming.source);
+    incoming.descriptor = {{"id", "kb-search"}, {"type", "http"}, {"route", "/kb/v2"}};
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_EQ(out.source, "export default () => 2");
+    EXPECT_EQ(out.contentHash, functionContentHash("export default () => 2"));
+    EXPECT_EQ(out.descriptor.at("route"), "/kb/v2");
+}
+
+TEST(MergeForCodePush, ARenameKeepsThePolicyAndMovesThePath) {
+    // Identity lives in the script's `on` block, so moving the file changes
+    // `path` and nothing else. If policy were keyed on the path, every rename
+    // would silently reset a function's privileges.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.path = "lib/search/kb.js";
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_EQ(out.path, "lib/search/kb.js");
+    EXPECT_EQ(out.functionId, "kb-search");
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read)) << "a rename dropped the policy";
+}
+
+TEST(MergeForCodePush, ADisabledFunctionStaysDisabledAcrossAPush) {
+    // An operator turned this off, probably because it was misbehaving.
+    // Re-deploying must not quietly start it again.
+    FunctionRecord existing = stored("kb-search", KeyScope{});
+    existing.enabled = false;
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.enabled = true;
+
+    EXPECT_FALSE(mergeForCodePush(&existing, incoming, KeyScope{}).enabled);
+}
+
+TEST(MergeForCodePush, PreservesTheOriginalCreationTime) {
+    const FunctionRecord existing = stored("kb-search", KeyScope{});
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.createdAt = 9999;
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+    EXPECT_EQ(out.createdAt, 1000u) << "created_at belongs to the first registration";
+}
+
+TEST(MergeForCodePush, AFailedPushMarksTheRowInvalidWithoutLosingThePolicy) {
+    // A function whose source no longer compiles keeps its row and its policy,
+    // so fixing the syntax error does not also mean re-granting access.
+    const FunctionRecord existing = stored("kb-search", scopeWith("kb_chunks", {KeyOp::Read}));
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+    incoming.valid = false;
+    incoming.lastError = "SyntaxError: unexpected token";
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_FALSE(out.valid);
+    EXPECT_EQ(out.lastError, "SyntaxError: unexpected token");
+    EXPECT_TRUE(allows(out.policy, "kb_chunks", KeyOp::Read));
+}
+
+TEST(MergeForCodePush, ASuccessfulPushClearsAPreviousError) {
+    FunctionRecord existing = stored("kb-search", KeyScope{});
+    existing.valid = false;
+    existing.lastError = "SyntaxError: unexpected token";
+    FunctionRecord incoming = stored("kb-search", KeyScope{});
+
+    const FunctionRecord out = mergeForCodePush(&existing, incoming, KeyScope{});
+
+    EXPECT_TRUE(out.valid);
+    EXPECT_TRUE(out.lastError.empty()) << "a stale error would be reported forever";
+}
+
+// ------------------------------------------------------- the default floor
+
+TEST(BuiltinDefaultFunctionPolicy, GrantsNoCollectionAccess) {
+    // Whatever this policy is, it is what unreviewed code runs with. If the
+    // posture is ever widened, widen it here and this test says so out loud
+    // rather than the change passing unnoticed.
+    const KeyScope p = builtinDefaultFunctionPolicy();
+    EXPECT_TRUE(p.rules.empty());
+    for (const KeyOp op : {KeyOp::Read, KeyOp::List, KeyOp::Search, KeyOp::Insert,
+                           KeyOp::Update, KeyOp::Delete})
+        EXPECT_EQ(p.findRule("any_collection", op), nullptr);
+}
+
+TEST(MergeForCodePush, AProjectWithNoConfiguredDefaultGrantsNothing) {
+    FunctionRecord incoming;
+    incoming.functionId = "kb-search";
+    const FunctionRecord out =
+        mergeForCodePush(nullptr, incoming, builtinDefaultFunctionPolicy());
+    EXPECT_TRUE(out.policy.rules.empty());
+}

+ 213 - 0
tests/test_function_run_log.cpp

@@ -0,0 +1,213 @@
+// FunctionRunLogStore against a fake database.
+//
+// The fake is supplied at LINK time: this file defines the handful of
+// `smartbotic::database::Client` members function_run_log.cpp calls, so the
+// target never links the real client. That is what makes the trim rule - the
+// one piece of behaviour here worth asserting - testable on a host where
+// libsmartbotic-db-client cannot be linked at all (CLAUDE.md, "The Void dev
+// host can no longer build the C++ natively").
+//
+// Every stub ignores `this` and works on the file-static `g_db` below, so no
+// Client or DbGateway object is ever constructed or read; the references handed
+// to the store point at storage nothing dereferences.
+#include "function_run_log.hpp"
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <map>
+
+using nlohmann::json;
+using Client = smartbotic::database::Client;
+
+namespace {
+
+/// collection -> document id -> body.
+std::map<std::string, std::map<std::string, json>> g_db;
+std::map<std::string, bool> g_created;
+
+void resetDb() { g_db.clear(); g_created.clear(); }
+
+}  // namespace
+
+namespace smartbotic::database {
+
+bool Client::createCollection(const std::string& name, uint32_t, bool, uint32_t, uint32_t) {
+    g_created[name] = true;
+    g_db[name];
+    return true;
+}
+
+std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
+    if (!g_created.count(name)) return std::nullopt;
+    CollectionInfo info;
+    info.name = name;
+    info.documentCount = g_db[name].size();
+    return info;
+}
+
+std::pair<std::string, bool> Client::upsert(const std::string& collection, const json& data,
+                                            const std::string& id, uint32_t, const std::string&) {
+    const bool isNew = g_db[collection].count(id) == 0;
+    json body = data;
+    body.erase("id");  // the real client strips a top-level `id` from the body
+    g_db[collection][id] = std::move(body);
+    return {id, isNew};
+}
+
+bool Client::remove(const std::string& collection, const std::string& id) {
+    return g_db[collection].erase(id) > 0;
+}
+
+std::vector<json> Client::find(const std::string& collection, const QueryOptions& options) {
+    std::vector<json> rows;
+    for (const auto& [id, body] : g_db[collection]) {
+        bool keep = true;
+        for (const auto& f : options.filters) {
+            // Only the one operator the store uses; anything else is a test bug.
+            EXPECT_EQ(static_cast<int>(f.op), static_cast<int>(FilterOp::EQ));
+            if (body.value(f.field, json()) != f.value) { keep = false; break; }
+        }
+        if (keep) rows.push_back(body);
+    }
+    if (!options.sortField.empty()) {
+        const std::string& key = options.sortField;
+        std::stable_sort(rows.begin(), rows.end(), [&](const json& a, const json& b) {
+            const uint64_t av = a.value(key, 0ull), bv = b.value(key, 0ull);
+            return options.sortDescending ? av > bv : av < bv;
+        });
+    }
+    std::vector<json> page;
+    for (size_t i = options.offset; i < rows.size() && page.size() < options.limit; ++i)
+        page.push_back(rows[i]);
+    return page;
+}
+
+}  // namespace smartbotic::database
+
+namespace svapi {
+
+/// Mirrors db_gateway.cpp. That translation unit cannot be linked here: it
+/// constructs a real Client, whose PIMPL lives in the library this target
+/// exists to avoid. The store only needs the mapping to be injective per
+/// project, which this is.
+std::string qualify(const std::string& project, const std::string& collection) {
+    if (project.empty() || project == "default") return collection;
+    return project + ":" + collection;
+}
+
+Client& DbGateway::client() {
+    alignas(Client) static unsigned char storage[sizeof(void*) * 4];
+    return *reinterpret_cast<Client*>(storage);
+}
+
+}  // namespace svapi
+
+namespace {
+
+/// A DbGateway reference whose object is never touched: every call reaching it
+/// lands in a stub above.
+svapi::DbGateway& fakeGateway() {
+    alignas(svapi::DbGateway) static unsigned char storage[sizeof(void*) * 8];
+    return *reinterpret_cast<svapi::DbGateway*>(storage);
+}
+
+svapi::FunctionRunLog entry(const std::string& runId, const std::string& fnId, uint64_t startedAt) {
+    svapi::FunctionRunLog e;
+    e.runId      = runId;
+    e.functionId = fnId;
+    e.trigger    = "invoke";
+    e.ok         = true;
+    e.status     = 200;
+    e.durationMs = 7;
+    e.startedAt  = startedAt;
+    return e;
+}
+
+class FunctionRunLogTest : public ::testing::Test {
+protected:
+    void SetUp() override { resetDb(); }
+};
+
+TEST_F(FunctionRunLogTest, RoundTripsEveryField) {
+    svapi::FunctionRunLog e = entry("r1", "kb-search", 1700000000);
+    e.ok      = false;
+    e.status  = 500;
+    e.error   = "TypeError: x is not a function";
+    e.console = {"first", "second"};
+
+    const svapi::FunctionRunLog back = svapi::FunctionRunLog::fromJson(e.toJson());
+    EXPECT_EQ(back.runId, "r1");
+    EXPECT_EQ(back.functionId, "kb-search");
+    EXPECT_EQ(back.trigger, "invoke");
+    EXPECT_FALSE(back.ok);
+    EXPECT_EQ(back.status, 500);
+    EXPECT_EQ(back.durationMs, 7);
+    EXPECT_EQ(back.error, "TypeError: x is not a function");
+    EXPECT_EQ(back.console, std::vector<std::string>({"first", "second"}));
+    EXPECT_EQ(back.startedAt, 1700000000u);
+}
+
+// `run_id`, not `id`: the client strips a top-level `id`, which would leave a
+// stored run with no identity to delete by.
+TEST_F(FunctionRunLogTest, StoresItsIdInTheBody) {
+    EXPECT_TRUE(svapi::FunctionRunLog().toJson().contains("run_id"));
+    EXPECT_FALSE(svapi::FunctionRunLog().toJson().contains("id"));
+}
+
+TEST_F(FunctionRunLogTest, AbsentFieldsDoNotInventARun) {
+    const svapi::FunctionRunLog e = svapi::FunctionRunLog::fromJson(json::object());
+    EXPECT_TRUE(e.runId.empty());
+    EXPECT_FALSE(e.ok);        // a row with no verdict is not a success
+    EXPECT_EQ(e.status, 0);
+    EXPECT_TRUE(e.console.empty());
+}
+
+TEST_F(FunctionRunLogTest, AppendKeepsOnlyTheNewestPerFunction) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 3);
+    for (uint64_t i = 1; i <= 6; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", 1000 + i));
+
+    const auto rows = store.list("p1", "fn", 100);
+    ASSERT_EQ(rows.size(), 3u);
+    EXPECT_EQ(rows[0].runId, "r6");   // newest first
+    EXPECT_EQ(rows[1].runId, "r5");
+    EXPECT_EQ(rows[2].runId, "r4");
+}
+
+// Trimming is per function, so a chatty function cannot evict a quiet one's
+// history out from under an operator reading it.
+TEST_F(FunctionRunLogTest, TrimIsScopedToOneFunction) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 2);
+    store.append("p1", entry("q1", "quiet", 1));
+    for (uint64_t i = 1; i <= 5; ++i)
+        store.append("p1", entry("c" + std::to_string(i), "chatty", 100 + i));
+
+    EXPECT_EQ(store.list("p1", "quiet", 100).size(), 1u);
+    EXPECT_EQ(store.list("p1", "chatty", 100).size(), 2u);
+}
+
+TEST_F(FunctionRunLogTest, KeepZeroMeansKeepEverything) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 0);
+    for (uint64_t i = 1; i <= 10; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", i));
+    EXPECT_EQ(store.list("p1", "fn", 100).size(), 10u);
+}
+
+// A listing can never return more than is kept, so the store clamps rather
+// than letting ?limit=1000000 become a million-row query.
+TEST_F(FunctionRunLogTest, ListClampsLimitToWhatIsKept) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 4);
+    for (uint64_t i = 1; i <= 4; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", i));
+    EXPECT_EQ(store.list("p1", "fn", 1000000).size(), 4u);
+    EXPECT_EQ(store.list("p1", "fn", 2).size(), 2u);
+}
+
+TEST_F(FunctionRunLogTest, ProjectsDoNotShareARunLog) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 10);
+    store.append("p1", entry("a", "fn", 1));
+    store.append("p2", entry("b", "fn", 1));
+    ASSERT_EQ(store.list("p1", "fn", 10).size(), 1u);
+    EXPECT_EQ(store.list("p1", "fn", 10)[0].runId, "a");
+}
+
+}  // namespace

+ 377 - 0
tests/test_functions_descriptor.cpp

@@ -0,0 +1,377 @@
+// Unit tests for the pure half of the function runtime: descriptor parsing and
+// HTTP route matching. No database, no network - this target deliberately does
+// not link vectorapi_core so it also builds where the DB client cannot.
+#include <gtest/gtest.h>
+
+#include <nlohmann/json.hpp>
+
+#include "functions/descriptor.hpp"
+
+using nlohmann::json;
+using namespace svapi::functions;
+
+namespace {
+
+FunctionDescriptor parseOk(const json& on) {
+    const ParseResult r = parseDescriptor(on);
+    EXPECT_TRUE(r.ok) << r.error;
+    return r.descriptor;
+}
+
+std::string parseErr(const json& on) {
+    const ParseResult r = parseDescriptor(on);
+    EXPECT_FALSE(r.ok) << "expected a rejection";
+    EXPECT_FALSE(r.error.empty());
+    return r.error;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------- identity
+
+TEST(Descriptor, MissingIdIsAnError) {
+    // A path fallback would let a rename silently create a second principal
+    // carrying the project's default policy, so this is never tolerated.
+    const std::string err = parseErr(json{{"type", "http"}, {"route", "/kb"}});
+    EXPECT_NE(err.find("id"), std::string::npos);
+}
+
+TEST(Descriptor, EmptyOrNonStringIdIsAnError) {
+    parseErr(json{{"id", ""}, {"type", "http"}, {"route", "/kb"}});
+    parseErr(json{{"id", 42}, {"type", "http"}, {"route", "/kb"}});
+    parseErr(json{{"id", "  "}, {"type", "http"}, {"route", "/kb"}});
+}
+
+TEST(Descriptor, NonObjectOnIsAnError) {
+    parseErr(json("http"));
+    parseErr(json::array({1, 2}));
+    parseErr(json(nullptr));
+}
+
+TEST(Descriptor, ParsingIsPureAndRepeatable) {
+    // The registry re-parses every row on each reload; two parses of one body
+    // must agree exactly, and parsing one body must not perturb the next.
+    const json a = json{{"id", "a"}, {"type", "http"}, {"route", "/a"}, {"method", "post"}};
+    const json b = json{{"id", "b"}, {"type", "cron"}, {"schedule", "*/5 * * * *"}};
+    const FunctionDescriptor a1 = parseOk(a);
+    const FunctionDescriptor b1 = parseOk(b);
+    const FunctionDescriptor a2 = parseOk(a);
+    EXPECT_EQ(a1.toJson(), a2.toJson());
+    EXPECT_EQ(b1.id, "b");
+    EXPECT_EQ(a2.methods, (std::vector<std::string>{"POST"}));
+}
+
+// -------------------------------------------------------------------- type
+
+TEST(Descriptor, TypeDefaultsToHttp) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}});
+    EXPECT_EQ(d.type, TriggerType::Http);
+}
+
+TEST(Descriptor, UnknownTypeIsAnError) {
+    const std::string err = parseErr(json{{"id", "x"}, {"type", "queue"}});
+    EXPECT_NE(err.find("queue"), std::string::npos);
+}
+
+// -------------------------------------------------------------------- http
+
+TEST(Descriptor, HttpNeedsARoute) {
+    parseErr(json{{"id", "x"}, {"type", "http"}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", ""}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", 7}});
+}
+
+TEST(Descriptor, RouteMustStartWithASlash) {
+    const std::string err = parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "kb/:topic"}});
+    EXPECT_NE(err.find("'/'"), std::string::npos);
+}
+
+TEST(Descriptor, RouteParamsMustBeNamedAndUnique) {
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:"}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:a/:a"}});
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:a/:b"}});
+    EXPECT_EQ(d.route, "/kb/:a/:b");
+}
+
+TEST(Descriptor, AbsentMethodMeansAnyMethod) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}});
+    EXPECT_TRUE(d.methods.empty());
+    EXPECT_TRUE(d.acceptsMethod("GET"));
+    EXPECT_TRUE(d.acceptsMethod("DELETE"));
+}
+
+TEST(Descriptor, MethodNormalisesFromAString) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}, {"method", "post"}});
+    EXPECT_EQ(d.methods, (std::vector<std::string>{"POST"}));
+    EXPECT_TRUE(d.acceptsMethod("post"));
+    EXPECT_FALSE(d.acceptsMethod("GET"));
+}
+
+TEST(Descriptor, MethodNormalisesFromAnArrayAndDeduplicates) {
+    const FunctionDescriptor d = parseOk(
+        json{{"id", "x"}, {"route", "/x"}, {"method", json::array({"get", "POST", "Get"})}});
+    EXPECT_EQ(d.methods, (std::vector<std::string>{"GET", "POST"}));
+}
+
+TEST(Descriptor, BadMethodShapesAreRejected) {
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", json::array()}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", json::array({"GET", 7})}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", ""}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", 7}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", "GET POST"}});
+}
+
+TEST(Descriptor, HttpIgnoresCronAndDbFields) {
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "http"}, {"route", "/x"}, {"schedule", "nonsense"}});
+    EXPECT_TRUE(d.schedule.empty());
+    EXPECT_TRUE(d.table.empty());
+}
+
+// -------------------------------------------------------------------- cron
+
+TEST(Descriptor, CronNeedsAFiveFieldSchedule) {
+    parseErr(json{{"id", "x"}, {"type", "cron"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * * *"}});
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "*/5 * * * *"}}).schedule,
+              "*/5 * * * *");
+}
+
+TEST(Descriptor, CronFieldRangesAreChecked) {
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "60 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* 24 * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * 0 * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * 13 *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * 8"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "*/0 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "5-1 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "a * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0, * * * *"}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0,30 1-5/2 */2 JAN-DEC mon"}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "  0 3 * * 0  "}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0 3 * * 7"}});
+}
+
+TEST(Descriptor, CronDefaultsToSingleFlight) {
+    // Overlapping runs of one schedule are almost never what the author meant,
+    // so cron opts in by default while HTTP (concurrent by nature) does not.
+    EXPECT_TRUE(
+        parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * *"}}).singleFlight);
+    EXPECT_FALSE(parseOk(json{{"id", "x"}, {"route", "/x"}}).singleFlight);
+    EXPECT_FALSE(parseOk(json{{"id", "x"},
+                              {"type", "cron"},
+                              {"schedule", "* * * * *"},
+                              {"singleFlight", false}})
+                     .singleFlight);
+    EXPECT_TRUE(parseOk(json{{"id", "x"}, {"route", "/x"}, {"singleFlight", true}}).singleFlight);
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"singleFlight", "yes"}});
+}
+
+// ---------------------------------------------------------------------- db
+
+TEST(Descriptor, DbNeedsATableAndAnEvent) {
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"event", "INSERT"}});
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}});
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"table", ""}, {"event", "INSERT"}});
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "update"}});
+    EXPECT_EQ(d.table, "kb");
+    EXPECT_EQ(d.event, DbEvent::Update);
+}
+
+TEST(Descriptor, DbEventMustBeOneOfTheThree) {
+    const std::string err =
+        parseErr(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "UPSERT"}});
+    EXPECT_NE(err.find("UPSERT"), std::string::npos);
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "DELETE"}}).event,
+              DbEvent::Delete);
+}
+
+// ------------------------------------------------------------------ common
+
+TEST(Descriptor, TimeoutMsMustBeAPositiveInteger) {
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 1500}}).timeoutMs, 1500);
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"route", "/x"}}).timeoutMs, 0); // 0 = unset
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 0}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", -1}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", "1500"}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 1.5}});
+}
+
+TEST(Descriptor, UnknownKeysAreIgnored) {
+    // Forward compatibility: a newer script must still load on an older server.
+    const FunctionDescriptor d = parseOk(json{{"id", "x"},
+                                              {"route", "/x"},
+                                              {"method", "GET"},
+                                              {"retries", 3},
+                                              {"labels", json::array({"a"})},
+                                              {"futureThing", json::object()}});
+    EXPECT_EQ(d.id, "x");
+    EXPECT_EQ(d.route, "/x");
+}
+
+TEST(Descriptor, TheFirstProblemIsNamed) {
+    const ParseResult r = parseDescriptor(json{{"type", "http"}, {"route", "bad"}});
+    ASSERT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("id"), std::string::npos);
+    EXPECT_EQ(r.error.find("route"), std::string::npos);
+}
+
+TEST(Descriptor, RoundTripsThroughJson) {
+    // The descriptor is stored on the registry row, so what we write back must
+    // parse to the same thing on reload.
+    const FunctionDescriptor d = parseOk(json{{"id", "kb-search"},
+                                              {"route", "/kb/:topic"},
+                                              {"method", json::array({"GET", "HEAD"})},
+                                              {"timeoutMs", 2000}});
+    const ParseResult again = parseDescriptor(d.toJson());
+    ASSERT_TRUE(again.ok) << again.error;
+    EXPECT_EQ(again.descriptor.toJson(), d.toJson());
+}
+
+// ------------------------------------------------------------- matchRoute
+
+TEST(MatchRoute, CapturesAParam) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/u/:handle", "/u/alice", p));
+    EXPECT_EQ(p, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchRoute, SegmentCountsMustMatch) {
+    RouteParams p{{"stale", "value"}};
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u/alice/x", p));
+    EXPECT_TRUE(p.empty()) << "params must be cleared on no match";
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u", p));
+    EXPECT_FALSE(matchRoute("/u/:handle/x", "/u/alice", p));
+}
+
+TEST(MatchRoute, LiteralsCompareCaseSensitively) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/about", "/about", p));
+    EXPECT_TRUE(p.empty());
+    EXPECT_FALSE(matchRoute("/about", "/About", p));
+}
+
+TEST(MatchRoute, LeadingAndTrailingSlashesAreIgnored) {
+    RouteParams p;
+    EXPECT_TRUE(matchRoute("/about", "about", p));
+    EXPECT_TRUE(matchRoute("about/", "/about", p));
+    ASSERT_TRUE(matchRoute("/u/:handle/", "/u/alice", p));
+    EXPECT_EQ(p, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchRoute, RootMatchesRoot) {
+    RouteParams p;
+    EXPECT_TRUE(matchRoute("/", "/", p));
+    EXPECT_TRUE(matchRoute("/", "", p));
+    EXPECT_FALSE(matchRoute("/", "/a", p));
+    EXPECT_FALSE(matchRoute("/a", "/", p));
+}
+
+TEST(MatchRoute, MultipleParamsAndMixedSegments) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/kb/:topic/doc/:id", "/kb/hu/doc/42", p));
+    EXPECT_EQ(p, (RouteParams{{"id", "42"}, {"topic", "hu"}}));
+    EXPECT_FALSE(matchRoute("/kb/:topic/doc/:id", "/kb/hu/docs/42", p));
+}
+
+TEST(MatchRoute, AParamDoesNotMatchAnEmptySegment) {
+    RouteParams p;
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u/", p));
+}
+
+// --------------------------------------------- 404 vs 405 (method-aware)
+
+namespace {
+
+std::vector<FunctionDescriptor> table() {
+    std::vector<FunctionDescriptor> v;
+    v.push_back(parseOk(json{{"id", "get-user"}, {"route", "/u/:handle"}, {"method", "GET"}}));
+    v.push_back(parseOk(json{{"id", "put-user"}, {"route", "/u/:handle"}, {"method", "put"}}));
+    v.push_back(parseOk(json{{"id", "any-about"}, {"route", "/about"}}));
+    v.push_back(parseOk(
+        json{{"id", "post-kb"}, {"route", "/kb"}, {"method", json::array({"POST", "PATCH"})}}));
+    v.push_back(parseOk(json{{"id", "cron-job"}, {"type", "cron"}, {"schedule", "* * * * *"}}));
+    return v;
+}
+
+} // namespace
+
+TEST(MatchHttp, UnknownRouteIsNotFound) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/nope");
+    EXPECT_EQ(m.status, RouteMatchStatus::NotFound);
+    EXPECT_EQ(m.descriptor, nullptr);
+    EXPECT_TRUE(m.allowedMethods.empty());
+}
+
+TEST(MatchHttp, MatchedRouteCarriesTheParams) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/u/alice");
+    ASSERT_EQ(m.status, RouteMatchStatus::Matched);
+    ASSERT_NE(m.descriptor, nullptr);
+    EXPECT_EQ(m.descriptor->id, "get-user");
+    EXPECT_EQ(m.params, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchHttp, WrongMethodOnAKnownRouteIs405WithTheUnionOfMethods) {
+    // The bug class this guards: a GET reaching a function that declared POST.
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "DELETE", "/u/alice");
+    ASSERT_EQ(m.status, RouteMatchStatus::MethodNotAllowed);
+    EXPECT_EQ(m.descriptor, nullptr);
+    EXPECT_TRUE(m.params.empty());
+    EXPECT_EQ(m.allowedMethods, (std::vector<std::string>{"GET", "PUT"}));
+    EXPECT_EQ(allowHeaderValue(m.allowedMethods), "GET, PUT");
+}
+
+TEST(MatchHttp, MultiMethodDescriptorContributesEveryMethodToAllow) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/kb");
+    ASSERT_EQ(m.status, RouteMatchStatus::MethodNotAllowed);
+    EXPECT_EQ(m.allowedMethods, (std::vector<std::string>{"PATCH", "POST"}));
+}
+
+TEST(MatchHttp, AMethodlessDescriptorTakesEveryMethod) {
+    const auto t = table();
+    for (const char* verb : {"GET", "POST", "DELETE", "OPTIONS"}) {
+        const RouteMatch m = matchHttpRoute(t, verb, "/about");
+        ASSERT_EQ(m.status, RouteMatchStatus::Matched) << verb;
+        EXPECT_EQ(m.descriptor->id, "any-about");
+    }
+}
+
+TEST(MatchHttp, NonHttpDescriptorsNeverMatch) {
+    const auto t = table();
+    EXPECT_EQ(matchHttpRoute(t, "GET", "/cron-job").status, RouteMatchStatus::NotFound);
+    FunctionDescriptor cron =
+        parseOk(json{{"id", "c"}, {"type", "cron"}, {"schedule", "* * * * *"}});
+    cron.route = "/about"; // a stale field must not open a route
+    const std::vector<FunctionDescriptor> only{cron};
+    EXPECT_EQ(matchHttpRoute(only, "GET", "/about").status, RouteMatchStatus::NotFound);
+}
+
+TEST(MatchHttp, TheCallerGivenMethodIsCaseInsensitive) {
+    const auto t = table();
+    EXPECT_EQ(matchHttpRoute(t, "get", "/u/alice").status, RouteMatchStatus::Matched);
+}
+
+TEST(MatchHttp, FirstDeclarationWinsAmongstEqualCandidates) {
+    // Deterministic dispatch matters more than being clever about it; the
+    // registry rejects duplicate ids, but two ids may still claim one route.
+    std::vector<FunctionDescriptor> v;
+    v.push_back(parseOk(json{{"id", "first"}, {"route", "/dup"}, {"method", "GET"}}));
+    v.push_back(parseOk(json{{"id", "second"}, {"route", "/dup"}, {"method", "GET"}}));
+    const RouteMatch m = matchHttpRoute(v, "GET", "/dup");
+    ASSERT_EQ(m.status, RouteMatchStatus::Matched);
+    EXPECT_EQ(m.descriptor->id, "first");
+}
+
+TEST(MatchHttp, EmptyTableIsNotFound) {
+    const std::vector<FunctionDescriptor> none;
+    EXPECT_EQ(matchHttpRoute(none, "GET", "/x").status, RouteMatchStatus::NotFound);
+}
+
+TEST(MatchHttp, AllowHeaderOfNothingIsEmpty) { EXPECT_EQ(allowHeaderValue({}), ""); }

+ 457 - 0
tests/test_functions_net_guard.cpp

@@ -0,0 +1,457 @@
+#include <gtest/gtest.h>
+
+#include "functions/net_guard.hpp"
+
+#include <algorithm>
+#include <atomic>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+using namespace svapi::functions;
+
+// ---------------------------------------------------------------------------
+// parseHttpUrl
+// ---------------------------------------------------------------------------
+
+TEST(ParseHttpUrl, PlainHttpGetsDefaultPortAndRootPath) {
+    auto u = parseHttpUrl("http://example.com");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "http");
+    EXPECT_EQ(u->host, "example.com");
+    EXPECT_EQ(u->port, 80);
+    EXPECT_EQ(u->path, "/");
+}
+
+TEST(ParseHttpUrl, HttpsDefaultPort) {
+    auto u = parseHttpUrl("https://example.com/a/b?q=1");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "https");
+    EXPECT_EQ(u->port, 443);
+    EXPECT_EQ(u->path, "/a/b?q=1");
+}
+
+TEST(ParseHttpUrl, ExplicitPortWins) {
+    auto u = parseHttpUrl("http://example.com:8080/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->port, 8080);
+    EXPECT_EQ(u->host, "example.com");
+    EXPECT_EQ(u->path, "/x");
+}
+
+TEST(ParseHttpUrl, SchemeIsCaseInsensitiveAndNormalised) {
+    auto u = parseHttpUrl("HTTPS://Example.COM/");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->scheme, "https");
+    // The host is lower-cased so the guard and the logs agree on one spelling.
+    EXPECT_EQ(u->host, "example.com");
+}
+
+TEST(ParseHttpUrl, UserinfoIsStrippedFromTheAuthority) {
+    // "http://user:pass@127.0.0.1/" must classify as 127.0.0.1, not as a host
+    // literally named "user:pass@127.0.0.1" that no blocklist would match.
+    auto u = parseHttpUrl("http://user:pass@127.0.0.1/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->host, "127.0.0.1");
+    EXPECT_EQ(u->port, 80);
+}
+
+TEST(ParseHttpUrl, BracketedIpv6LiteralHasBracketsStripped) {
+    auto u = parseHttpUrl("http://[::1]/health");
+    ASSERT_TRUE(u.has_value());
+    // Stored unbracketed so it can go straight to inet_pton/getaddrinfo.
+    EXPECT_EQ(u->host, "::1");
+    EXPECT_EQ(u->port, 80);
+    EXPECT_EQ(u->path, "/health");
+}
+
+TEST(ParseHttpUrl, BracketedIpv6LiteralWithPort) {
+    auto u = parseHttpUrl("https://[fe80::1%25eth0]:9443/x");
+    ASSERT_TRUE(u.has_value());
+    EXPECT_EQ(u->host, "fe80::1%25eth0");
+    EXPECT_EQ(u->port, 9443);
+}
+
+TEST(ParseHttpUrl, RejectsNonHttpSchemes) {
+    EXPECT_FALSE(parseHttpUrl("file:///etc/passwd").has_value());
+    EXPECT_FALSE(parseHttpUrl("gopher://127.0.0.1:9004/_").has_value());
+    EXPECT_FALSE(parseHttpUrl("ftp://example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("data:text/plain,hi").has_value());
+    EXPECT_FALSE(parseHttpUrl("dict://127.0.0.1:11211/stat").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsMissingScheme) {
+    EXPECT_FALSE(parseHttpUrl("example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("//example.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("/relative/path").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsEmptyHost) {
+    EXPECT_FALSE(parseHttpUrl("http://").has_value());
+    EXPECT_FALSE(parseHttpUrl("http:///path").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://:8080/path").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://[]/path").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsBadPort) {
+    EXPECT_FALSE(parseHttpUrl("http://example.com:0/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:70000/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:abc/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com:80x/x").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsUnterminatedIpv6Bracket) {
+    EXPECT_FALSE(parseHttpUrl("http://[::1/x").has_value());
+}
+
+TEST(ParseHttpUrl, RejectsEmptyAndWhitespaceInput) {
+    EXPECT_FALSE(parseHttpUrl("").has_value());
+    EXPECT_FALSE(parseHttpUrl("   ").has_value());
+    // Embedded control characters allow request smuggling against the host's
+    // own parser, so the guard refuses the URL rather than guessing.
+    EXPECT_FALSE(parseHttpUrl("http://exam\r\nple.com/x").has_value());
+    EXPECT_FALSE(parseHttpUrl("http://example.com/x\ny").has_value());
+}
+
+// ---------------------------------------------------------------------------
+// parseCidr / cidrContains
+// ---------------------------------------------------------------------------
+
+TEST(ParseCidr, Ipv4RangeParses) {
+    auto r = parseCidr("10.0.0.0/8");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(r->isV4());
+    EXPECT_EQ(r->bits, 8);
+}
+
+TEST(ParseCidr, Ipv6RangeParses) {
+    auto r = parseCidr("fc00::/7");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_FALSE(r->isV4());
+    EXPECT_EQ(r->bits, 7);
+}
+
+TEST(ParseCidr, BareAddressIsAHostRoute) {
+    auto v4 = parseCidr("8.8.8.8");
+    ASSERT_TRUE(v4.has_value());
+    EXPECT_EQ(v4->bits, 32);
+    EXPECT_TRUE(cidrContains(*v4, "8.8.8.8"));
+    EXPECT_FALSE(cidrContains(*v4, "8.8.8.9"));
+
+    auto v6 = parseCidr("::1");
+    ASSERT_TRUE(v6.has_value());
+    EXPECT_EQ(v6->bits, 128);
+}
+
+TEST(ParseCidr, RejectsGarbage) {
+    EXPECT_FALSE(parseCidr("").has_value());
+    EXPECT_FALSE(parseCidr("not-an-ip/8").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/33").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/-1").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/8/8").has_value());
+    EXPECT_FALSE(parseCidr("fc00::/129").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/eight").has_value());
+    EXPECT_FALSE(parseCidr("10.0.0.0/08x").has_value());
+    EXPECT_FALSE(parseCidr("[::1]/128").has_value());
+}
+
+TEST(CidrContains, Ipv4EdgesOfTheRange) {
+    auto r = parseCidr("172.16.0.0/12");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "172.16.0.0"));       // first address
+    EXPECT_TRUE(cidrContains(*r, "172.31.255.255"));   // last address
+    EXPECT_FALSE(cidrContains(*r, "172.15.255.255"));  // one below
+    EXPECT_FALSE(cidrContains(*r, "172.32.0.0"));      // one above
+}
+
+TEST(CidrContains, Ipv4SlashThirtyTwoAndSlashZero) {
+    auto host = parseCidr("192.0.2.5/32");
+    ASSERT_TRUE(host.has_value());
+    EXPECT_TRUE(cidrContains(*host, "192.0.2.5"));
+    EXPECT_FALSE(cidrContains(*host, "192.0.2.6"));
+
+    auto all = parseCidr("0.0.0.0/0");
+    ASSERT_TRUE(all.has_value());
+    EXPECT_TRUE(cidrContains(*all, "8.8.8.8"));
+    EXPECT_TRUE(cidrContains(*all, "255.255.255.255"));
+}
+
+TEST(CidrContains, Ipv6EdgesOfTheRange) {
+    auto r = parseCidr("fe80::/10");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "fe80::"));
+    EXPECT_TRUE(cidrContains(*r, "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
+    EXPECT_FALSE(cidrContains(*r, "fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
+    EXPECT_FALSE(cidrContains(*r, "fec0::"));
+}
+
+TEST(CidrContains, FamilyMismatchIsSimplyNotAMember) {
+    auto v4 = parseCidr("10.0.0.0/8");
+    auto v6 = parseCidr("fc00::/7");
+    ASSERT_TRUE(v4.has_value());
+    ASSERT_TRUE(v6.has_value());
+    EXPECT_FALSE(cidrContains(*v4, "fc00::1"));
+    EXPECT_FALSE(cidrContains(*v6, "10.0.0.1"));
+}
+
+TEST(CidrContains, NonLiteralAddressIsNotAMember) {
+    auto r = parseCidr("10.0.0.0/8");
+    ASSERT_TRUE(r.has_value());
+    // cidrContains answers only the membership question; failing closed on
+    // garbage is SsrfPolicy::isBlocked's job.
+    EXPECT_FALSE(cidrContains(*r, "nonsense"));
+    EXPECT_FALSE(cidrContains(*r, ""));
+}
+
+TEST(CidrContains, HostBitsSetInTheRangeStillMatchTheWholeNetwork) {
+    // "10.1.2.3/8" is sloppy but common in config; treat it as 10.0.0.0/8
+    // rather than silently matching nothing.
+    auto r = parseCidr("10.1.2.3/8");
+    ASSERT_TRUE(r.has_value());
+    EXPECT_TRUE(cidrContains(*r, "10.0.0.1"));
+    EXPECT_TRUE(cidrContains(*r, "10.255.255.254"));
+}
+
+// ---------------------------------------------------------------------------
+// SsrfPolicy
+// ---------------------------------------------------------------------------
+
+TEST(SsrfPolicy, DefaultsBlockEveryDocumentedRange) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    const char* blocked[] = {
+        "127.0.0.1",        // 127.0.0.0/8 loopback
+        "127.255.255.255",
+        "10.1.2.3",         // 10.0.0.0/8
+        "172.16.5.5",       // 172.16.0.0/12
+        "192.168.1.1",      // 192.168.0.0/16
+        "169.254.169.254",  // cloud metadata
+        "0.0.0.0",          // 0.0.0.0/8 "this host"
+        "100.64.0.1",       // carrier NAT
+        "::1",              // IPv6 loopback
+        "fc00::1",          // unique local
+        "fd12:3456::1",     // inside fc00::/7
+        "fe80::1",          // link local
+    };
+    for (const char* ip : blocked) {
+        EXPECT_TRUE(p.isBlocked(ip)) << "should be blocked: " << ip;
+    }
+}
+
+TEST(SsrfPolicy, PublicAddressesAreNotBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    const char* allowed[] = {
+        "8.8.8.8", "1.1.1.1", "93.184.216.34",
+        "172.15.0.1",   // just below 172.16.0.0/12
+        "172.32.0.1",   // just above
+        "100.63.255.255", "100.128.0.1",
+        "2606:4700:4700::1111",
+        "2001:4860:4860::8888",
+    };
+    for (const char* ip : allowed) {
+        EXPECT_FALSE(p.isBlocked(ip)) << "should be allowed: " << ip;
+    }
+}
+
+TEST(SsrfPolicy, Ipv4MappedIpv6BypassIsCaught) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // ::ffff:127.0.0.1 is the classic blocklist bypass: an IPv6 literal whose
+    // embedded IPv4 is loopback. It must be classified as its IPv4 address.
+    EXPECT_TRUE(p.isBlocked("::ffff:127.0.0.1"));
+    EXPECT_TRUE(p.isBlocked("::ffff:10.0.0.1"));
+    EXPECT_TRUE(p.isBlocked("::ffff:169.254.169.254"));
+    EXPECT_TRUE(p.isBlocked("::ffff:7f00:1"));   // same address, hex form
+    EXPECT_TRUE(p.isBlocked("::ffff:a00:1"));    // ::ffff:10.0.0.1 in hex
+    // A mapped public address stays reachable - the unwrapping must not block
+    // everything it touches.
+    EXPECT_FALSE(p.isBlocked("::ffff:8.8.8.8"));
+}
+
+TEST(SsrfPolicy, Ipv4CompatibleAndNatSixtyFourLoopbackAreCaught) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(p.isBlocked("::127.0.0.1"));      // deprecated v4-compatible form
+    EXPECT_TRUE(p.isBlocked("64:ff9b::7f00:1"));  // NAT64 well-known prefix
+}
+
+TEST(SsrfPolicy, UnspecifiedIpv6AndOtherReservedFormsAreBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(p.isBlocked("::"));
+}
+
+TEST(SsrfPolicy, GarbageInputFailsClosed) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // Anything that is not a valid IP literal is blocked: a classifier that
+    // cannot parse its input has not proved the destination safe. Do not
+    // "simplify" this to return false.
+    EXPECT_TRUE(p.isBlocked(""));
+    EXPECT_TRUE(p.isBlocked("example.com"));
+    EXPECT_TRUE(p.isBlocked("127.0.0.1.1"));
+    EXPECT_TRUE(p.isBlocked("127.1"));            // short form inet_pton rejects
+    EXPECT_TRUE(p.isBlocked("0x7f.0.0.1"));       // hex-octet obfuscation
+    EXPECT_TRUE(p.isBlocked("2130706433"));       // decimal-integer loopback
+    EXPECT_TRUE(p.isBlocked("[::1]"));            // brackets must be stripped first
+    EXPECT_TRUE(p.isBlocked(" 8.8.8.8"));
+    EXPECT_TRUE(p.isBlocked("8.8.8.8 "));
+}
+
+TEST(SsrfPolicy, EmptyPolicyBlocksNothingValidButStillFailsClosed) {
+    std::vector<std::string> bad;
+    const SsrfPolicy p = SsrfPolicy::fromStrings({}, &bad);
+    EXPECT_TRUE(bad.empty());
+    EXPECT_EQ(p.size(), 0u);
+    EXPECT_FALSE(p.isBlocked("127.0.0.1"));
+    // Even with no ranges, unparseable input is never declared safe.
+    EXPECT_TRUE(p.isBlocked("not-an-ip"));
+}
+
+TEST(SsrfPolicy, FromStringsReportsWhatItCouldNotParse) {
+    std::vector<std::string> bad;
+    const SsrfPolicy p = SsrfPolicy::fromStrings(
+        {"192.0.2.0/24", "junk/8", "fc00::/7", "10.0.0.0/99", "  "}, &bad);
+    EXPECT_EQ(p.size(), 2u);
+    // A blank entry is tolerated (blank lines in config), a malformed one is
+    // reported so the operator can see the hole in his blocklist.
+    ASSERT_EQ(bad.size(), 2u);
+    EXPECT_EQ(bad[0], "junk/8");
+    EXPECT_EQ(bad[1], "10.0.0.0/99");
+    EXPECT_TRUE(p.isBlocked("192.0.2.7"));
+    EXPECT_TRUE(p.isBlocked("fc00::9"));
+    // A custom list replaces the defaults; it does not extend them.
+    EXPECT_FALSE(p.isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicy, FromStringsToleratesSurroundingWhitespaceAndANullReport) {
+    const SsrfPolicy p = SsrfPolicy::fromStrings({" 192.0.2.0/24 ", "bogus"}, nullptr);
+    EXPECT_EQ(p.size(), 1u);
+    EXPECT_TRUE(p.isBlocked("192.0.2.1"));
+}
+
+TEST(SsrfPolicy, DefaultCidrListIsTheDocumentedMinimum) {
+    const auto& d = SsrfPolicy::defaultBlockedCidrs();
+    for (const char* want : {"127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12",
+                             "192.168.0.0/16", "169.254.0.0/16", "0.0.0.0/8",
+                             "100.64.0.0/10", "::1/128", "fc00::/7", "fe80::/10"}) {
+        EXPECT_NE(std::find(d.begin(), d.end(), std::string(want)), d.end())
+            << "default set is missing " << want;
+    }
+    // Every built-in string must itself parse, or the default policy silently
+    // has a hole in it.
+    for (const auto& s : d) {
+        EXPECT_TRUE(parseCidr(s).has_value()) << "unparseable default: " << s;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Process-wide policy cache
+// ---------------------------------------------------------------------------
+
+TEST(SsrfPolicyCache, DefaultsToTheBuiltInSet) {
+    auto p = currentSsrfPolicy();
+    ASSERT_TRUE(p != nullptr);
+    EXPECT_TRUE(p->isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicyCache, IsReplaceableAtRuntime) {
+    auto original = currentSsrfPolicy();
+    setSsrfPolicy(std::make_shared<const SsrfPolicy>(
+        SsrfPolicy::fromStrings({"192.0.2.0/24"}, nullptr)));
+    auto replaced = currentSsrfPolicy();
+    EXPECT_TRUE(replaced->isBlocked("192.0.2.1"));
+    EXPECT_FALSE(replaced->isBlocked("127.0.0.1"));
+    // The snapshot a reader already holds keeps working after the swap.
+    EXPECT_TRUE(original->isBlocked("127.0.0.1"));
+    setSsrfPolicy(original);
+    EXPECT_TRUE(currentSsrfPolicy()->isBlocked("127.0.0.1"));
+}
+
+TEST(SsrfPolicyCache, NullReplacementRestoresTheDefaults) {
+    setSsrfPolicy(nullptr);
+    auto p = currentSsrfPolicy();
+    ASSERT_TRUE(p != nullptr);
+    EXPECT_TRUE(p->isBlocked("169.254.169.254"));
+}
+
+TEST(SsrfPolicyCache, ConcurrentReadsAndSwapsAreSafe) {
+    auto original = currentSsrfPolicy();
+    std::atomic<bool> stop{false};
+    std::vector<std::thread> readers;
+    for (int i = 0; i < 4; ++i) {
+        readers.emplace_back([&] {
+            while (!stop.load()) {
+                auto snap = currentSsrfPolicy();
+                ASSERT_TRUE(snap != nullptr);
+                (void)snap->isBlocked("127.0.0.1");
+            }
+        });
+    }
+    for (int i = 0; i < 200; ++i) {
+        setSsrfPolicy(std::make_shared<const SsrfPolicy>(SsrfPolicy::withDefaults()));
+    }
+    stop.store(true);
+    for (auto& t : readers) t.join();
+    setSsrfPolicy(original);
+}
+
+// ---------------------------------------------------------------------------
+// ssrfBlockReason
+// ---------------------------------------------------------------------------
+
+TEST(SsrfBlockReason, LiteralIpIsClassifiedWithoutDns) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = ssrfBlockReason("127.0.0.1", p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("127.0.0.1"), std::string::npos);
+
+    EXPECT_FALSE(ssrfBlockReason("8.8.8.8", p).has_value());
+    EXPECT_FALSE(ssrfBlockReason("2606:4700:4700::1111", p).has_value());
+}
+
+TEST(SsrfBlockReason, MappedLiteralIsBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(ssrfBlockReason("::ffff:127.0.0.1", p).has_value());
+}
+
+TEST(SsrfBlockReason, EmptyHostIsBlocked) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(ssrfBlockReason("", p).has_value());
+}
+
+TEST(SsrfBlockReason, LocalhostResolvesAndIsBlocked) {
+    // localhost resolves from /etc/hosts, so this exercises the getaddrinfo
+    // path without needing a network or live DNS.
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = ssrfBlockReason("localhost", p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("localhost"), std::string::npos);
+}
+
+TEST(SsrfBlockReason, UnresolvableHostFailsClosed) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    // ".invalid" is reserved by RFC 2606 and never resolves, so no live DNS is
+    // consulted for a useful answer here. Resolution failure must block, not
+    // allow: an unresolved name has not been proved safe.
+    EXPECT_TRUE(ssrfBlockReason("nx.invalid", p).has_value());
+}
+
+TEST(SsrfBlockReason, EveryResolvedAddressIsClassifiedNotJustTheFirst) {
+    // Multi-A / DNS rebinding bypass: a name whose first address is public and
+    // whose second is internal must still be refused. The resolver is not
+    // involved for literals, so this drives the same classification loop over
+    // an explicit address list.
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    EXPECT_TRUE(blockReasonForAddresses("mixed.example", {"8.8.8.8", "10.0.0.5"}, p).has_value());
+    EXPECT_TRUE(blockReasonForAddresses("mixed.example", {"8.8.8.8", "::1"}, p).has_value());
+    EXPECT_FALSE(blockReasonForAddresses("ok.example", {"8.8.8.8", "1.1.1.1"}, p).has_value());
+    // No addresses at all is a resolution failure: fail closed.
+    EXPECT_TRUE(blockReasonForAddresses("empty.example", {}, p).has_value());
+}
+
+TEST(SsrfBlockReason, ReasonNamesTheOffendingAddressAndRange) {
+    const SsrfPolicy p = SsrfPolicy::withDefaults();
+    auto why = blockReasonForAddresses("mixed.example", {"8.8.8.8", "10.0.0.5"}, p);
+    ASSERT_TRUE(why.has_value());
+    EXPECT_NE(why->find("10.0.0.5"), std::string::npos);
+    EXPECT_NE(why->find("mixed.example"), std::string::npos);
+}

+ 75 - 0
tests/test_principal.cpp

@@ -0,0 +1,75 @@
+#include <gtest/gtest.h>
+#include "apikey.hpp"
+#include "principal.hpp"
+using namespace svapi;
+
+namespace {
+ApiKey plainKey(std::vector<std::string> projects, bool admin = false) {
+    ApiKey k;
+    k.id = "key-1";
+    k.projects = std::move(projects);
+    k.admin = admin;
+    return k;
+}
+ApiKey scopedKey(std::vector<std::string> projects, KeyScope scope) {
+    ApiKey k = plainKey(std::move(projects));
+    k.scope = std::move(scope);
+    return k;
+}
+KeyScope readOnly(const std::string& collection) {
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = collection;
+    r.ops = {KeyOp::Read, KeyOp::List};
+    s.rules.push_back(r);
+    return s;
+}
+}  // namespace
+
+TEST(Principal, MirrorsTheKeyItWasBuiltFrom) {
+    const ApiKey k = plainKey({"acme"});
+    const Principal p = Principal::of(k);
+    EXPECT_EQ(p.id, "key-1");
+    EXPECT_FALSE(p.admin);
+    EXPECT_EQ(p.scope, nullptr) << "an unscoped key must present as unscoped";
+    EXPECT_TRUE(p.canAccess("acme"));
+    EXPECT_FALSE(p.canAccess("other"));
+}
+
+TEST(Principal, AdminAndWildcardReachEveryProject) {
+    EXPECT_TRUE(Principal::of(plainKey({}, /*admin*/ true)).canAccess("anything"));
+    EXPECT_TRUE(Principal::of(plainKey({"*"})).canAccess("anything"));
+}
+
+TEST(Principal, CarriesTheScopeByReference) {
+    const ApiKey k = scopedKey({"acme"}, readOnly("docs"));
+    const Principal p = Principal::of(k);
+    ASSERT_NE(p.scope, nullptr);
+    EXPECT_NE(p.scope->findRule("docs", KeyOp::Read), nullptr);
+    EXPECT_EQ(p.scope->findRule("docs", KeyOp::Delete), nullptr);
+}
+
+// A function is a principal with no key behind it: no secret, no origin, no
+// captcha - just a project and a scope. Constructing one directly is what lets
+// the runner reuse the same authorization code as an HTTP request.
+TEST(Principal, CanBeBuiltWithoutAnApiKey) {
+    const std::vector<std::string> projects{"acme"};
+    const KeyScope scope = readOnly("kb_chunks");
+    const Principal p{"fn:kb-search", &projects, false, &scope};
+    EXPECT_TRUE(p.canAccess("acme"));
+    EXPECT_FALSE(p.canAccess("other"));
+    ASSERT_NE(p.scope, nullptr);
+    EXPECT_NE(p.scope->findRule("kb_chunks", KeyOp::List), nullptr);
+}
+
+TEST(Principal, AccessChecksAgreeWithTheKeysOwnAnswer) {
+    // The two must never diverge: Principal is meant to be the single notion of
+    // "who is asking", not a second one that drifts.
+    for (const ApiKey& k : {plainKey({"acme"}), plainKey({"*"}), plainKey({}, true),
+                            scopedKey({"acme"}, readOnly("docs"))}) {
+        const Principal p = Principal::of(k);
+        for (const char* project : {"acme", "other", "default"})
+            EXPECT_EQ(p.canAccess(project), k.canAccess(project))
+                << "disagreement on project " << project;
+    }
+}

+ 64 - 15
tests/test_project_settings.cpp

@@ -21,23 +21,23 @@ CollectionMeta unpinnedCollection() {
 }  // namespace
 
 TEST(ProjectSettings, DefaultsAreAllEmptyMeaningInherit) {
-    ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(nlohmann::json::object());
+    ProjectSettings p = ProjectSettings::fromJson(nlohmann::json::object());
     EXPECT_EQ(p.openaiApiBase, "");
     EXPECT_EQ(p.openaiApiKey, "");
     EXPECT_EQ(p.defaultEmbeddingModel, "");
-    EXPECT_FALSE(p.hasOverrides());
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
 }
 
 TEST(ProjectSettings, RoundTripPreservesFields) {
     nlohmann::json j{{"openai_api_base", "https://api.mistral.ai"},
                      {"openai_api_key", "sk-proj"},
                      {"default_embedding_model", "mistral-embed"}};
-    ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(j);
+    ProjectSettings p = ProjectSettings::fromJson(j);
     EXPECT_EQ(p.openaiApiBase, "https://api.mistral.ai");
     EXPECT_EQ(p.openaiApiKey, "sk-proj");
     EXPECT_EQ(p.defaultEmbeddingModel, "mistral-embed");
-    EXPECT_TRUE(p.hasOverrides());
-    EXPECT_EQ(ProjectEmbeddingSettings::fromJson(p.toJson()).toJson(), p.toJson());
+    EXPECT_TRUE(p.hasEmbeddingOverrides());
+    EXPECT_EQ(ProjectSettings::fromJson(p.toJson()).toJson(), p.toJson());
 }
 
 TEST(ProjectSettings, NoProjectOverrideResolvesToGlobal) {
@@ -50,7 +50,7 @@ TEST(ProjectSettings, NoProjectOverrideResolvesToGlobal) {
 
 TEST(ProjectSettings, EmptyProjectOverrideResolvesToGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.apiBase, "https://api.openai.com");
     EXPECT_EQ(r.apiKey, "sk-global");
@@ -59,7 +59,7 @@ TEST(ProjectSettings, EmptyProjectOverrideResolvesToGlobal) {
 
 TEST(ProjectSettings, ProjectBaseAndKeyOverrideGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-proj";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
@@ -71,7 +71,7 @@ TEST(ProjectSettings, ProjectBaseAndKeyOverrideGlobal) {
 TEST(ProjectSettings, ProjectKeyAloneKeepsGlobalBase) {
     // The metering case: a customer's own key billed against the default endpoint.
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiKey = "sk-customer";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.apiBase, "https://api.openai.com");
@@ -80,7 +80,7 @@ TEST(ProjectSettings, ProjectKeyAloneKeepsGlobalBase) {
 
 TEST(ProjectSettings, ProjectModelOverridesGlobalDefault) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.defaultEmbeddingModel = "text-embedding-3-large";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.model, "text-embedding-3-large");
@@ -90,7 +90,7 @@ TEST(ProjectSettings, ProjectModelOverridesGlobalDefault) {
 
 TEST(ProjectSettings, CollectionModelPinBeatsProjectAndGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.defaultEmbeddingModel = "text-embedding-3-large";
     CollectionMeta m = unpinnedCollection();
     m.embeddingModel = "bge-m3";
@@ -108,20 +108,20 @@ TEST(ProjectSettings, CollectionModelPinBeatsGlobalWithoutProject) {
 
 TEST(ProjectSettings, BaseWithoutKeyIsRejected) {
     // Guards the global credential: a foreign endpoint must carry its own key.
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     EXPECT_FALSE(p.baseHasItsOwnKey());
 }
 
 TEST(ProjectSettings, BaseWithKeyIsAccepted) {
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-proj";
     EXPECT_TRUE(p.baseHasItsOwnKey());
 }
 
 TEST(ProjectSettings, KeyWithoutBaseNeedsNoPairing) {
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiKey = "sk-customer";
     EXPECT_TRUE(p.baseHasItsOwnKey());
 }
@@ -134,9 +134,58 @@ TEST(ProjectSettings, DocIdIsDerivedFromProjectName) {
 TEST(ProjectSettings, JsonCarriesProjectNameBecauseDbStripsId) {
     // The DB client strips a top-level `id` from stored bodies, so the project
     // name has to live in the body itself (same trick as key_store's key_id).
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-proj";
     EXPECT_EQ(p.toJson().value("project", ""), "acme");
-    EXPECT_EQ(ProjectEmbeddingSettings::fromJson(p.toJson()).project, "acme");
+    EXPECT_EQ(ProjectSettings::fromJson(p.toJson()).project, "acme");
+}
+
+// --------------------------------------------- default function policy
+
+TEST(DefaultFunctionPolicy, FallsBackToTheBuiltinFloorWhenUnset) {
+    const ProjectSettings p;
+    EXPECT_TRUE(defaultFunctionPolicyFor(&p).rules.empty());
+    EXPECT_TRUE(defaultFunctionPolicyFor(nullptr).rules.empty())
+        << "a project with nothing stored must still resolve to the floor";
+}
+
+TEST(DefaultFunctionPolicy, UsesTheProjectOverrideWhenSet) {
+    ProjectSettings p;
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = "kb_*";
+    r.ops = {KeyOp::Read, KeyOp::List};
+    s.rules.push_back(r);
+    p.defaultFunctionPolicy = s;
+
+    const KeyScope got = defaultFunctionPolicyFor(&p);
+    EXPECT_NE(got.findRule("kb_chunks", KeyOp::Read), nullptr);
+    EXPECT_EQ(got.findRule("kb_chunks", KeyOp::Delete), nullptr);
+}
+
+TEST(DefaultFunctionPolicy, AnEmptyStoredPolicyIsNotTheSameAsAbsent) {
+    // Both deny everything today, but a stored empty policy is an explicit
+    // decision that must survive a change to the built-in floor.
+    ProjectSettings p;
+    p.defaultFunctionPolicy = KeyScope{};
+    EXPECT_TRUE(p.hasAnyOverrides());
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
+
+    const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
+    EXPECT_TRUE(back.defaultFunctionPolicy.has_value());
+}
+
+TEST(ProjectSettings, APolicyOnlyProjectIsNotTreatedAsEmpty) {
+    // The embeddings handler deletes the settings document when the project has
+    // nothing stored. If that test used the embedding fields alone, clearing an
+    // embedding override would silently drop the function policy with it.
+    ProjectSettings p;
+    p.defaultFunctionPolicy = KeyScope{};
+    EXPECT_TRUE(p.hasAnyOverrides());
+}
+
+TEST(ProjectSettings, AnUnsetPolicyIsNotWrittenToStorage) {
+    const ProjectSettings p;
+    EXPECT_FALSE(p.toJson().contains("default_function_policy"));
 }

+ 407 - 0
tests/test_runner_client.cpp

@@ -0,0 +1,407 @@
+// RunnerPool unit tests.
+//
+// Every test here runs against a real cpp-httplib server in-process, so the
+// pool's HTTP path is exercised for real without a QuickJS runner and without
+// the database client - which is what lets this target build on the dev host
+// (CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+//
+// The test this file exists for is RunFailureIsNotRetried. Everything else
+// guards it: if a runner answering "your function threw" were treated as a
+// transport failure, the pool would run a side-effecting function a second time
+// on the next runner, and nothing in production would report that it had.
+
+#include "runner_client.hpp"
+#include <gtest/gtest.h>
+#include <httplib.h>
+#include <atomic>
+#include <memory>
+#include <string>
+#include <thread>
+
+using namespace svapi;
+using nlohmann::json;
+
+namespace {
+
+// 127.0.0.1:1 refuses immediately instead of timing out: a dead endpoint has to
+// be deterministic, and "bind a port then close it" races with the next test.
+constexpr const char* kDeadEndpoint = "127.0.0.1:1";
+
+/// A runner stand-in: counts requests per path and replies with whatever the
+/// test configured.
+class FakeRunner {
+public:
+    FakeRunner() = default;
+    ~FakeRunner() { stop(); }
+
+    /// Replies to POST /run with `status` and `body` verbatim.
+    void onRun(int status, std::string body) {
+        runStatus_ = status;
+        runBody_ = std::move(body);
+    }
+    void onValidate(int status, std::string body) {
+        validateStatus_ = status;
+        validateBody_ = std::move(body);
+    }
+    void healthy(bool v) { healthy_ = v; }
+
+    void start() {
+        svr_.Get("/health", [this](const httplib::Request&, httplib::Response& res) {
+            ++healthCalls_;
+            res.status = healthy_ ? 200 : 500;
+            res.set_content(healthy_ ? R"({"status":"ok"})" : R"({"status":"bad"})",
+                            "application/json");
+        });
+        svr_.Post("/run", [this](const httplib::Request& req, httplib::Response& res) {
+            ++runCalls_;
+            lastRunBody_ = req.body;
+            res.status = runStatus_;
+            res.set_content(runBody_, "application/json");
+        });
+        svr_.Post("/validate", [this](const httplib::Request& req, httplib::Response& res) {
+            ++validateCalls_;
+            lastValidateBody_ = req.body;
+            res.status = validateStatus_;
+            res.set_content(validateBody_, "application/json");
+        });
+        port_ = svr_.bind_to_any_port("127.0.0.1");
+        thread_ = std::thread([this] { svr_.listen_after_bind(); });
+        svr_.wait_until_ready();
+    }
+
+    void stop() {
+        if (!thread_.joinable()) return;
+        svr_.stop();
+        thread_.join();
+    }
+
+    std::string endpoint() const { return "127.0.0.1:" + std::to_string(port_); }
+    int runCalls() const { return runCalls_; }
+    int healthCalls() const { return healthCalls_; }
+    int validateCalls() const { return validateCalls_; }
+    const std::string& lastRunBody() const { return lastRunBody_; }
+    const std::string& lastValidateBody() const { return lastValidateBody_; }
+
+private:
+    httplib::Server svr_;
+    std::thread thread_;
+    int port_ = 0;
+    std::atomic<bool> healthy_{true};
+    std::atomic<int> healthCalls_{0}, runCalls_{0}, validateCalls_{0};
+    int runStatus_ = 200;
+    int validateStatus_ = 200;
+    std::string runBody_ = R"({"status":200,"body":{}})";
+    std::string validateBody_ = R"({"ok":true,"descriptor":{}})";
+    std::string lastRunBody_, lastValidateBody_;
+};
+
+RunnerPool::Options opts(std::vector<std::string> endpoints, uint32_t backoffSec = 10) {
+    RunnerPool::Options o;
+    o.endpoints = std::move(endpoints);
+    o.connectTimeoutSec = 2;
+    o.readTimeoutSec = 5;
+    o.unhealthyBackoffSec = backoffSec;
+    return o;
+}
+
+const json kTrigger = json{{"method", "GET"}, {"path", "/kb/x"},
+                           {"params", json::object()}, {"query", json::object()},
+                           {"headers", json::object()}, {"body", nullptr}};
+
+} // namespace
+
+// ---------------------------------------------------------------- no endpoints
+
+TEST(RunnerPool, NoEndpointsIsNeverHealthy) {
+    RunnerPool pool(opts({}));
+    EXPECT_FALSE(pool.anyHealthy());
+    EXPECT_TRUE(pool.statusJson()["runners"].empty());
+}
+
+TEST(RunnerPool, NoEndpointsFailsAsTransport) {
+    RunnerPool pool(opts({}));
+    RunnerRunResult r = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.transportFailure);
+    EXPECT_FALSE(r.error.empty());
+
+    RunnerValidateResult v = pool.validate("export default () => {}", "a.js");
+    EXPECT_FALSE(v.ok);
+    EXPECT_TRUE(v.transportFailure);
+}
+
+// -------------------------------------------------------------- normalisation
+
+TEST(RunnerPool, EndpointFormsNormaliseToTheSameBase) {
+    RunnerPool pool(opts({"127.0.0.1:9100", "http://127.0.0.1:9100/", "http://127.0.0.1:9100"}));
+    const json s = pool.statusJson();
+    ASSERT_EQ(s["runners"].size(), 3u);
+    for (const json& e : s["runners"])
+        EXPECT_EQ(e["endpoint"].get<std::string>(), "http://127.0.0.1:9100");
+}
+
+TEST(RunnerPool, HttpsEndpointKeepsItsScheme) {
+    RunnerPool pool(opts({"https://runner.internal:8443/"}));
+    EXPECT_EQ(pool.statusJson()["runners"][0]["endpoint"].get<std::string>(),
+              "https://runner.internal:8443");
+}
+
+// --------------------------------------------------------------------- health
+
+TEST(RunnerPool, HealthProbeMarksReachableAndUnreachable) {
+    FakeRunner r;
+    r.start();
+    RunnerPool pool(opts({kDeadEndpoint, r.endpoint()}));
+    EXPECT_TRUE(pool.anyHealthy());
+    EXPECT_GE(r.healthCalls(), 1);
+
+    const json s = pool.statusJson();
+    ASSERT_EQ(s["runners"].size(), 2u);
+    EXPECT_FALSE(s["runners"][0]["healthy"].get<bool>());
+    EXPECT_FALSE(s["runners"][0]["last_error"].get<std::string>().empty());
+    EXPECT_TRUE(s["runners"][1]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, NonOkHealthStatusIsUnhealthy) {
+    FakeRunner r;
+    r.healthy(false);
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+    EXPECT_FALSE(pool.anyHealthy());
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+// ------------------------------------------------------------------------ run
+
+TEST(RunnerPool, RunParsesTheRunnerResponse) {
+    FakeRunner r;
+    r.onRun(200, R"({"status":201,"headers":{"X-A":"b"},"body":{"hits":2},
+                     "console":["one","two"],"duration_ms":7})");
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+
+    RunnerRunResult res = pool.run("proj", "kb-search", kTrigger);
+    EXPECT_TRUE(res.ok);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(res.status, 201);
+    EXPECT_EQ(res.headers["X-A"].get<std::string>(), "b");
+    EXPECT_EQ(res.body["hits"].get<int>(), 2);
+    ASSERT_EQ(res.console.size(), 2u);
+    EXPECT_EQ(res.console[0], "one");
+    EXPECT_EQ(res.durationMs, 7);
+
+    // The wire payload is the protocol in the design doc, not a renaming of it.
+    const json sent = json::parse(r.lastRunBody());
+    EXPECT_EQ(sent["project"].get<std::string>(), "proj");
+    EXPECT_EQ(sent["function_id"].get<std::string>(), "kb-search");
+    EXPECT_EQ(sent["trigger"]["path"].get<std::string>(), "/kb/x");
+}
+
+// THE test. A runner that answers "the function threw" has done its job
+// correctly; re-running elsewhere would execute the function twice.
+TEST(RunnerPool, RunFailureIsNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"TypeError: x is not a function","duration_ms":3})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_FALSE(res.transportFailure) << "a function failure is not a transport failure";
+    EXPECT_EQ(res.error, "TypeError: x is not a function");
+    EXPECT_EQ(first.runCalls(), 1);
+    EXPECT_EQ(second.runCalls(), 0) << "the function must not run a second time";
+
+    // The runner that reported the failure is working, so it stays healthy.
+    EXPECT_TRUE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, TimeoutAndOomAreFunctionFailuresNotTransportFailures) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"wall time exceeded","timed_out":true})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_TRUE(res.timedOut);
+    EXPECT_FALSE(res.outOfMemory);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0) << "a timed-out run may have had side effects already";
+}
+
+TEST(RunnerPool, OutOfMemoryIsReportedAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"out of memory","out_of_memory":true})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.outOfMemory);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0);
+}
+
+TEST(RunnerPool, UnreachableRunnerIsRetriedOnTheNext) {
+    FakeRunner live;
+    live.onRun(200, R"({"status":200,"body":{"ok":1}})");
+    live.start();
+    RunnerPool pool(opts({kDeadEndpoint, live.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.ok);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(live.runCalls(), 1);
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, AllRunnersUnreachableIsATransportFailure) {
+    RunnerPool pool(opts({kDeadEndpoint, kDeadEndpoint}));
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_TRUE(res.transportFailure);
+}
+
+// A runner that answers something other than the protocol is broken, not a
+// function that failed: we cannot tell whether the handler ran, so the caller
+// gets our-fault (transport) and nobody re-runs it.
+TEST(RunnerPool, UnparseableRunnerResponseIsTransportAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, "<html>bad gateway</html>");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.transportFailure);
+    EXPECT_FALSE(res.ok);
+    EXPECT_EQ(second.runCalls(), 0) << "the handler may already have run";
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, HttpErrorStatusFromTheRunnerIsTransportAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(503, R"({"error":"no capacity"})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0);
+}
+
+// ------------------------------------------------------------- round robin
+
+TEST(RunnerPool, SuccessiveRunsRotateAcrossRunners) {
+    FakeRunner a, b;
+    a.start();
+    b.start();
+    RunnerPool pool(opts({a.endpoint(), b.endpoint()}));
+    for (int i = 0; i < 4; ++i) EXPECT_TRUE(pool.run("p", "f", kTrigger).ok);
+    EXPECT_EQ(a.runCalls(), 2);
+    EXPECT_EQ(b.runCalls(), 2);
+}
+
+// --------------------------------------------------------------- backoff
+
+// Three calls rotate 0,1,0 over two endpoints, so the broken endpoint is a
+// candidate on calls 1 and 3. Whether call 3 touches it is exactly the backoff.
+TEST(RunnerPool, BackoffSkipsAFailedRunnerUntilItExpires) {
+    FakeRunner broken, live;
+    broken.onRun(500, R"({"error":"boom"})");
+    broken.start();
+    live.start();
+
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}, /*backoffSec=*/3600));
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    EXPECT_EQ(broken.runCalls(), 1) << "inside the backoff window the runner is skipped";
+}
+
+TEST(RunnerPool, ZeroBackoffRetriesTheFailedRunnerImmediately) {
+    FakeRunner broken, live;
+    broken.onRun(500, R"({"error":"boom"})");
+    broken.start();
+    live.start();
+
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}, /*backoffSec=*/0));
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    EXPECT_EQ(broken.runCalls(), 2) << "an expired backoff puts the runner back in rotation";
+}
+
+// Every endpoint unhealthy must not mean "no candidates forever": with the
+// backoff expired the pool tries again rather than failing closed on stale state.
+TEST(RunnerPool, AnEndpointPastItsBackoffIsAttemptedAgain) {
+    FakeRunner live;
+    live.start();
+    RunnerPool pool(opts({live.endpoint()}, /*backoffSec=*/0));
+    live.healthy(false);
+    EXPECT_FALSE(pool.anyHealthy());
+    live.healthy(true);
+    EXPECT_TRUE(pool.anyHealthy());
+}
+
+// -------------------------------------------------------------- validate
+
+TEST(RunnerPool, ValidateParsesDescriptor) {
+    FakeRunner r;
+    r.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb","type":"http","route":"/kb"}})");
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok);
+    EXPECT_FALSE(v.transportFailure);
+    EXPECT_EQ(v.descriptor["id"].get<std::string>(), "kb");
+
+    const json sent = json::parse(r.lastValidateBody());
+    EXPECT_EQ(sent["source"].get<std::string>(), "export const on = {}");
+    EXPECT_EQ(sent["path"].get<std::string>(), "kb.js");
+}
+
+TEST(RunnerPool, ValidateCompileErrorIsNotATransportFailure) {
+    FakeRunner first, second;
+    first.onValidate(200, R"({"ok":false,"error":"SyntaxError: unexpected token"})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("oops(", "a.js");
+    EXPECT_FALSE(v.ok);
+    EXPECT_FALSE(v.transportFailure);
+    EXPECT_EQ(v.error, "SyntaxError: unexpected token");
+    EXPECT_EQ(second.validateCalls(), 0) << "a compile error is the same on every runner";
+}
+
+// Validation has no side effects, so unlike run() it may be retried after a
+// request that was delivered but never answered.
+TEST(RunnerPool, ValidateRetriesAnUnreachableRunner) {
+    FakeRunner live;
+    live.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb"}})");
+    live.start();
+    RunnerPool pool(opts({kDeadEndpoint, live.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok);
+    EXPECT_EQ(live.validateCalls(), 1);
+}
+
+TEST(RunnerPool, ValidateRetriesARunnerThatAnsweredOffProtocol) {
+    FakeRunner broken, live;
+    broken.onValidate(500, "nope");
+    broken.start();
+    live.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb"}})");
+    live.start();
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok) << "validate is pure, so a broken runner is worth retrying past";
+    EXPECT_EQ(live.validateCalls(), 1);
+}

+ 4 - 4
tests/test_stores.cpp

@@ -86,7 +86,7 @@ TEST(SettingsStore, ProjectOverridesRoundTripThroughDb) {
     ss.bootstrap("");
     EXPECT_EQ(ss.projectSnapshot("acme"), nullptr);
 
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project               = "acme";
     p.openaiApiBase         = "https://api.mistral.ai";
     p.openaiApiKey          = "sk-acme";
@@ -110,7 +110,7 @@ TEST(SettingsStore, ProjectOverridesSurviveAFreshStore) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-acme";
     ss.saveProject(p);
@@ -132,7 +132,7 @@ TEST(SettingsStore, RemoveProjectRevertsToInherit) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-acme";
     ss.saveProject(p);
@@ -152,7 +152,7 @@ TEST(SettingsStore, ProjectDocsDoNotCorruptGlobalSettings) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("sk-global");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project       = "acme";
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-acme";