# CLAUDE.md - smartbotic-vectorapi C++20 REST API fronting `smartbotic-database` (gRPC) for n8n + other clients. Stores RAG vectors + JSON, organized into **projects** with **multi-key per-project-grant auth**. React admin UI. Ships as Debian `.deb`s. ## Build / test / run ```bash # Backend + web UI (Release) cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_WEBUI=ON -S . cmake --build build -j"$(nproc)" # Tests (GoogleTest). Integration tests need a running smartbotic-database on localhost:9004; # they GTEST_SKIP() cleanly if it's unreachable. BUILD_WEBUI=OFF to skip the npm build during test cycles. cmake -B build -G Ninja -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF -S . && cmake --build build -j"$(nproc)" ctest --test-dir build --output-on-failure # Run locally (use the repo's api/ for /openapi.json,/llms.txt,/docs and the built UI) SMARTBOTIC_VECTORAPI_KEY=dev ./build/src/smartbotic-vectorapi \ --config config/config.json --share-dir "$PWD/api" --webui-dir "$PWD/build/webui/dist" # Native host build: clang, the whole repo including the runner, ~100 s, and the # compile_commands.json that clangd reads. Development only - it links the # host's protobuf/gRPC, not the versions the .deb is built against. scripts/host-build.sh --client # --client also rebuilds libsmartbotic-db-client into the prefix scripts/host-build.sh --test # + ctest, SERIALLY (see the ApiFixture note below) # Web UI only cd webui && npm install && npm run build # → webui/dist ; `npm run dev` for the :3000 proxy dev server # Local backend for UI work, or when you want Debian's exact toolchain # packaging/devstack: DB + API from the release .debs in a Debian 13 container. docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svapi-devstack ``` ## Architecture (where things live) - `src/` - the server. `vectorapi_core` static lib + `main.cpp`. Namespace `svapi`. Flat headers, quoted includes. - `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. `pages/Functions.tsx` holds `fn`/`tab` in the URL (a draft is `?new=1` and carries no source, so it is deliberately not shareable); `components/ScopeRules.tsx` is the `rules`/`ops` editor shared by key scopes and function policies, with `allowEmpty` for the latter because an empty function policy is legal. `require_human_token` is hidden for function policies: it is a captcha header check in `requireCapability`, and a function is authorized through `requireCapabilityCore`, which never sees an HTTP request - offering it would store a field that silently does nothing. 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`). **Four** 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_net` (libcurl + the IMAP/MIME parsers + the mail budget + the error map; links neither `vectorapi_core` nor the database client, so its ~200 tests run on the dev host too), `runner_host` (the `ctx.*` surface; links `vectorapi_core` AND `runner_net`). `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. ## Conventions - C++20, `nlohmann/json`, `spdlog`, cpp-httplib (FetchContent, OpenSSL on). Handlers `throw svapi::ApiError`; a global exception handler maps to `{error:{code,message}}` + HTTP status (`errors.hpp`: 400/401/403/404/422/503/500). - Filters: `field:op:value` (`op` ∈ eq/ne/gt/gte/lt/lte/in/contains/exists/regex/search). Used by `/documents` (`?filter=`, repeatable) **and** vector `/search` (`filters` body array) - both parse with `parseFilter()` and are evaluated by the DB, so semantics never diverge. `contains` is array membership; `search` is the substring op. Vector search intersects the DB's filter result with the similarity ranking (scores stay identical to an unfiltered query), scanning at most 10000 candidates. - **Embedding config precedence:** collection `embedding_model` pin → project override → global default; endpoint + API key are the project override when set, else global. Resolved by the pure `resolveEmbedding()` (`project_settings.hpp`) - unit-test precedence there, not through the handlers. - **Every outbound request to an external provider goes through `applyOutboundDefaults()`** (`outbound_http.hpp`): `User-Agent: smartbotic-vectorapi/` and nothing else, TLS verification on, redirects off. Never let cpp-httplib's default UA reach a provider. - **clangd, clang-format and clang-tidy are configured** (`.clangd`, `.clang-format`) and read `build-host/compile_commands.json`, so they cover `src/`, `tests/` and `runner/` including `runner/src/main.cpp`. The tidy set is narrow on purpose (`bugprone`/`cert`/`clang-analyzer`/`misc`/`performance`): the broad `modernize`/`readability` families bury real findings under thousands of style notes. `.clang-format` **describes the style the code already uses** rather than imposing one, so it is close to a no-op; `LambdaBodyIndentation: OuterScope` is the setting that matters, since every route handler is a lambda whose body is indented from the statement. Even so the codebase is hand-laid-out and not formatter-clean, so format **new or changed code only** (`git clang-format`), never whole files. - 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 - **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. - **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) and `job` (reached only by being enqueued, which is where slow work belongs). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug. - **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over. - **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents. - **`embedTimeoutMs` on `.search()`/`.store()` is validated, not coerced.** A non-integer or non-positive value is 422, and exceeding it is **504** `embedding_timeout` (distinct from the run simply running out of budget, because the remedies differ). It went unnoticed for a release while being silently accepted and ignored, which is exactly why an unsupported option must be refused rather than dropped. - **Wall time has TWO ceilings** (`functions/wall_budget.hpp`): an HTTP one (~2 s, which `RunnerPool::readTimeoutSec` must exceed) and a JOB one, which is exempt because a queue-claimed run holds no socket. `RunService::run` takes the kind as a PARAMETER, never inferred from the descriptor, and defaults to Http - the narrow budget - so a caller that forgets is slow rather than dangerous. Precedence: `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`, resolved by the pure `resolveWallBudget()`. **The project cap is per kind** (`{http, job}` on `PUT /projects/{p}/settings/functions`): one number could not express "10 s for routes, 60 s for jobs", so capping a project's routes also cut its cron work and the only safe setting was no cap. `FunctionView` carries BOTH and `RunService::run` selects, because `lookup()` does not know how a run was triggered. The engine's `JsLimits::wall_time_ms` is raised to the highest ceiling at construction, or the clamp inside `JsRuntime::run` would kill every job at the HTTP value. - **Job runs draw from their OWN pool lane.** A lease is held for a run's whole duration, every `ctx.fetch` included, so without a lane N slow jobs leave one runtime for every interactive route and the second overlapping HTTP run blocks until the read timeout fires - a 503 from a healthy runner. Worst-case memory is `(pool + job_pool) x memory_limit_bytes`, so the two lanes ADD. - **The database-event loop guard reads the event's actor** (client 2.12.0). Every write a function makes is stamped `fn:/:` via the `actor` parameter, and `Event::actor` carries it back - so provenance costs nothing and lives in the audit trail, NOT in a field inside user documents (which would travel into every export forever). A chain is refused past `events.max_depth` generations and logged at error. - **Delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs again, so cron and db functions must be idempotent. `singleFlight` (default true for cron) skips a tick while the previous run is still going, which bounds stacking but is not exactly-once. - **`jobs.enabled` is OFF by default in the runner**, so a runner upgrade never starts draining a queue in a deployment whose server has no scheduler. On a host that wants cron it MUST be turned on, or the scheduler enqueues work nothing ever runs - the most confusing possible way for cron to look broken. - **Project files** are small named binary assets per project (`file_store.hpp`), so everything customer-specific - a logo, a signature image - is tenant DATA rather than something bundled into a function's source. **PROJECT ISOLATION IS OURS, NOT THE DATABASE'S:** the database namespaces files by `Client::Config::project`, this service runs ONE client configured for `default` (collections are qualified per call instead), and the file API has no per-call project argument - so every project's files share one database namespace and are separated only by the `related_id` we stamp and filter on. Every lookup must therefore filter on BOTH project and name, and nothing outside `file_store.cpp` may address a file by its database id. A bug there is a cross-tenant leak, not a mis-sorted list. - **Files answer to the scope rules under the reserved `_files` pseudo-collection**, so `requireCapabilityCore` is the one implementation and file access cannot drift from collection access. The leading underscore makes it unshadowable - collection-create rejects `_`-prefixed names. `ctx.files` is **read only**: writing a tenant's asset is a management act and the HTTP route requires project-manage for it. - **Two different file size caps, answering two different questions.** `max_file_bytes` (global settings, default 2 MiB) bounds what can be STORED; `kCtxFileMaxBytes` (1 MiB) bounds what one function run may LOAD. A file stored when the limit was generous must not be able to pull megabytes into a 64 MiB JS heap on every run afterwards. The database imposes a cap of its own (`storage.files.max_file_size_mb`, default 500), which is far above either. - **A file upload does NOT replace by name at the database layer** - two uploads of one name leave two records - so `FileStore::put` deletes the previous ones itself, uploading FIRST so a failure leaves the old file intact. Reads take the NEWEST record, because an interrupted put can leave two and a read that picked arbitrarily would serve stale bytes some of the time. - **Project secrets** live in `:vectorapi_secrets`, encrypted and deliberately NOT in the collection registry - so the documents API and `ctx.collections` both 404 it, and even a policy granting every collection cannot read it. Writes are admin-only; no GET ever returns a value. A `SVAPI_FN___` host variable WINS over a stored secret of the same name, which is the break-glass a stolen API credential cannot shadow. - **The runner SUBSCRIBES to project settings; it does not poll.** `ProjectWallMax` wraps a `SettingsStore` with `reloadAll()` plus `startWatch()`, so a changed cap reaches the next run immediately. It used to be a hand-rolled cache on a `project_budget_ttl_sec` TTL, which made clearing a cap look broken for up to 15 s and produced a false bug report. **`reloadAll()`, never `bootstrap()`** - bootstrap WRITES, seeding the settings document, and a runner must never author configuration it only reads. - **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run. - **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN___` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets. - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile. - **`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 settings blocklist is **UNIONED** with the built-in defaults by `SsrfPolicy::fromSettings()`, never substituted for them - an operator adding one CIDR must not silently reopen loopback, RFC1918 and the metadata endpoint. `function_egress_allow_private` is the explicit opt-out and relaxes **only** `privateBlockedCidrs()`; 169.254.0.0/16, link-local, multicast, reserved space and the IPv6 spellings of an IPv4 destination (NAT64, 6to4, `::/96`) stay blocked whatever it is set to. Note the opt-out does expose loopback, where our own API listens. ## Mail surface (`ctx.mail`, IMAP + SMTP) - **Scope is IMAP read + SMTP send, deliberately.** No FTP, FTPS, POP3 or WebDAV/CalDAV. SFTP was dropped by the owner, which is what keeps vendoring to ONE upstream - SFTP needs libssh2, which is far less watched than curl while having had remotely reachable issues. **WebDAV is out because it is HTTP**, and curl's HTTP is compiled OUT: `ctx.fetch` is cpp-httplib with its own guard, its own pinning and its own outbound defaults, and two HTTP clients with two sets of defaults is exactly how the two drift. Re-enabling it also brings redirects back, which then need `CURLOPT_REDIR_PROTOCOLS_STR` set separately and `FOLLOWLOCATION` off. - **`runner_net` is a separate target for testability, not tidiness.** `runner_host` links `vectorapi_core` and the database client, so putting the IMAP and MIME code there would make the largest and most defect-prone part of the feature the one part only the Docker path can compile. The division at the boundary is strict: `runner_host` converts JS values to a plain request struct and back, and does nothing else - no curl call, no IMAP knowledge, no timeout arithmetic above that line. - **libcurl is VENDORED at `curl-8_22_0`** (`SVAPI_CURL_TAG`, `SVAPI_VENDOR_CURL=ON`; `OFF` links the system one and is what the dev loop uses, because vendoring costs minutes). The pin comment carries the obligations, and they are real: **CVE tracking is ours now**, a statically linked curl is invisible to `apt`, and a fix means a rebuild and a republish of both binaries rather than an unattended upgrade. Judge an advisory against **what this service reaches** - exactly `imaps`/`imap`/`smtps`/`smtp` - the same discipline the httplib pin uses. `PROXY` is compiled out rather than disabled per handle, because curl reads `*_proxy` from the environment where httplib does not and `runner.env` is a file an operator edits; a stray proxy variable would silently reroute a destination the SSRF guard had already approved. `NETRC` is out so credentials can only come from project secrets. Cookies/ALTSVC/HSTS are out because each is persistent cross-request state, which a multi-tenant pool must not accumulate. A build from a git tag reports its version as `8.22.0-DEV`. - **A fetch goes through `CURLOPT_CUSTOMREQUEST` with `BODY.PEEK[]`, NEVER curl's `;UID=` URL form.** Measured against a live server elsewhere: the URL form **always** sets `\Seen`. Undoing it afterwards with a `UID STORE -FLAGS` is worse than the disease - it removes a flag it may not have set, so a message the user had **already read comes back unread**, and a timeout between the fetch and the undo leaves the message read anyway, which is the exact outcome peek exists to prevent. A test asserts no `STORE`, `+FLAGS` or `-FLAGS` ever reaches the wire. - **curl consumes the closing `)` AND the tagged completion line; untagged response lines are what reach the write callback.** Measured by byte count, which is the only way to see it: a fetch whose fake response was a 30-byte untagged line plus a 50-byte literal plus `)\r\n` plus the tagged `OK` delivered exactly 80 bytes. **An earlier version of this note claimed the tagged line DOES arrive, and that was wrong** - it came from a substring check for `" OK "` that matched `* OK [UIDVALIDITY 1]`, an untagged line. The consequence is real: a successful fetch's raw buffer legitimately parses as **`NeedMore`**, because the framing it was told to expect was never sent, so the binding restores the framing and re-parses rather than treating that as a short read. Restoring framing is safe only because it cannot satisfy an unsent `{n}`, so a genuinely truncated literal still reports `NeedMore`. Never resolve this with a terminator search. Separately: a `BODY.PEEK[...]` fetch comes back labelled **`BODY[...]`** without the `.PEEK`, so a parser looking for the string it sent finds nothing. - **A server that announces `{n}` LARGER than the body it sends corrupts silently, and only its CONTENT gives it away.** curl counts the response's own framing toward the announced count and reports **success**: measured against 8.22.0, an announce of 50 for a 40-byte body yielded `CURLE_OK` and a 50-byte literal ending `)A003 OK`, which `ctx.mail` then returned as a 200 whose header and text both carried those ten octets. It cannot be caught structurally - curl strips the real framing in the healthy case too, so a padded response and a correct one are byte-for-byte the same SHAPE (untagged line, literal header, exactly n bytes, nothing after). `literalEndsWithFraming()` (`net/imap_fetch.cpp`, pure) therefore matches the tail, and `parseCurlFetch` refuses a body that ends in framing. **The tag it matches is CURL'S, not ours**: `customRequestFor` strips the tag from every command, so curl re-tags on the wire (measured: `A001`, `A002`, ... sequential) and our own `ImapTagger` value never reaches the server at all. **`Malformed`, not `NeedMore`** - a truncated transfer is transient and worth retrying, while a server that miscounts its own literal will miscount it again, so this is `mail_protocol_error` 502 and NOT retryable. An earlier note here described this defect as the DIRECT parse returning `Ok`; measured, the direct parse returns `NeedMore` and the corruption arrives through the framed re-parse, so a fix aimed at the direct path would have aimed at nothing. - **A `UID FETCH` naming more than one uid delivers ZERO bytes to the write callback** (`7,9` and `7:9` both; a single `7` delivers normally). So a read is one command per uid, all on the one session and the one LOGIN. Measured; it is why the obvious batching optimisation does not work. - **A uid absent from the mailbox arrives as zero bytes, and that is `Ok` with no messages.** The caller skips it. Nothing a returned message carries ever comes from the raw buffer, which is what makes the "tagged completion line returned as the e-mail body" bug structurally impossible here rather than merely absent. - **curl dot-stuffs the payload it is given, so the renderer must not.** Both doing it corrupts any line beginning with a period; neither doing it truncates the message at a lone `.`. The renderer additionally emits a leading period as `=2E` in quoted-printable, so the protection holds either way. - **Non-ASCII IMAP SEARCH is REFUSED by field name, not sent.** Doing it properly needs `SEARCH CHARSET UTF-8` with the term as an octet-counted literal, which is a multi-step exchange the one-shot transport does not drive. Sending the raw bytes is **worse than failing**: the server matches nothing and zero results is indistinguishable from "there is no such mail". That shipped elsewhere and produced silently wrong answers against Hungarian mail. The refusal names the field and says to filter on an ASCII-safe criterion and match the accented text after fetching. Mailbox NAMES are unaffected and still go out as modified UTF-7. - **An SMTP refusal after DATA arrives as `CURLcode` 8 (`WEIRD_SERVER_REPLY`) with `CURLINFO_RESPONSE_CODE` 550.** So a reply code the server actually sent **wins over curl's generic transport complaint** for the generic codes; otherwise a bad recipient was reported as a protocol fault. Codes that already carry more meaning than a reply code, such as a denied login, keep their own answer. A 4xx reply is transient (`mail_server_busy`, 503), a 5xx is the caller's problem (`mail_rejected`, **422** - a 550 is overwhelmingly a bad recipient or a rejected sender, and blaming the server sends them looking in the wrong place). - **Retryability is a PARAMETER, never inferred.** `sideEffecting` is the caller saying whether the operation changes anything at the far end, for the same reason the run kind is a parameter to `RunService::run`. A failure is retryable only when nothing can have happened: DNS and connect failures are, a mailbox read that times out is, and a **send is never retryable** past the point delivery was possible, because a duplicate cannot be recalled. **A rejected login is not retryable either** - repeating it is how an account gets locked or an IP blocked, which is far more expensive than the failure being retried. A timeout is **504**, not 503, because 503's whole meaning is "retry as-is". - **The mail budget has a THIRD number the embedding budget does not: `totalMs`.** An embedding call is one request/response, so bounding connect and read bounds it. A mailbox read is several round trips on one connection, and a read timeout bounds each quiet period and **not their sum** - a server answering every command just inside the read timeout holds a pooled runtime far past the run's budget without ever tripping it. `resolveMailBudget()` (`net/mail_budget.hpp`, pure) otherwise mirrors `resolveEmbedBudget()`, connect capped at half. - **`mailGlobalInit()` is called once from the runner's `main` before any worker starts, and FAILS CLOSED.** `curl_global_init` is not thread-safe and a lazy first-use from two pool threads is a real race. It also checks `CURL_VERSION_THREADSAFE` and refuses to start without it, in the same spirit as the runner refusing to start with no token on a non-loopback bind. **`CURLOPT_NOSIGNAL` on every handle**, or curl uses `SIGALRM` for resolution timeouts, which is unsafe off the main thread and can longjmp out of a worker - and a single-threaded test never shows it. - **One handle per (run, account), destroyed with the session. No `CURLSH`, no cross-tenant reuse.** A handle carries connection state and credentials. A fresh handle per command would mean a TCP connect, a TLS handshake and a LOGIN for every command, which is both slow and what gets an account throttled; a test asserts one LOGIN serves three commands. - **VERIFIED AGAINST A LIVE SERVER on 2026-10-08** (Dovecot-ish on `mail.onmail.hu`, IMAP 993 implicit TLS and SMTP 587 STARTTLS, credentials in `/data/dev/.env`). Everything below was measured against that server, not a fixture, and every fake-server claim in this section survived it: `LIST` and modified-UTF-7 decoding, `EXAMINE` reporting `PERMANENTFLAGS ()` read-only, `UID SEARCH` including `UNSEEN`, **a peek fetch of a genuinely UNSEEN message leaving it unseen** (the weak version of this test uses an already-seen message and proves nothing), the direct parse of a good fetch returning `NeedMore` while the framed re-parse returns `Ok`, no tagged line in the buffer, and **a multi-uid `UID FETCH` delivering zero bytes**. A full send-and-read-back round trip confirmed an accented Hungarian subject surviving as two `=?UTF-8?B?` encoded words and decoding back exactly, quoted-printable chosen for the accented text, a lone `.` body line arriving intact and not double-stuffed, an RFC 2231 attachment filename, and `BODYSTRUCTURE` part numbering of `1.1` for the text inside a `multipart/alternative` inside a `multipart/mixed` with the attachment at `2`. Note `EXAMINE` alone prevents a flag change, so that test confirms the read path is safe but does NOT isolate `BODY.PEEK`'s own contribution. - **The fake IMAP/SMTP servers are committed** (`runner/tests/fake_mail_server.hpp`): in-process TCP listeners on **ephemeral** ports. Ephemeral because a fixed port collides - twice during development a test reached a stale server from an earlier run and "passed" against the wrong process. They **mask credentials** before recording a transcript, and the SMTP one answers a bare `AUTH PLAIN` with a **334 challenge, not 235**: answering 235 made an earlier harness report a working login for a client that had sent no credentials. It also **un-stuffs** the leading period during DATA, as a real receiver does, or a correct client looks like it double-stuffed. - `src/functions/mime_words.*` is **adapted from an existing internal implementation**, is owned elsewhere, and changes flow one way INTO this repo. If a decoding bug turns up here, report it rather than fixing only this copy. ## 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). - Global service collections (DB `default` project, **no leading underscore** - see gotcha): `vectorapi_keys`, `vectorapi_settings`. The settings collection holds the global doc (`current`) **and** one `project_` doc per project carrying that project's embedding overrides (empty field = inherit; the body repeats `project` because the DB strips `id`). Per-project registry: `:vectorapi_collections`. The `vectorapi_` prefix is reserved (collection-create rejects `_` and `vectorapi_`). - First run with no keys generates an admin key (`projects:["*"], admin:true`) and logs it once; `SMARTBOTIC_VECTORAPI_KEY` seeds it, `OPENAI_API_KEY` seeds embeddings. ## ⚠️ Gotchas (hard-won - don't relearn these) - **DB v2.3.1: `_`-prefixed collections misroute when project-qualified.** Writes land in MemoryStore (mirror skips `_`-names) but reads of `default:_foo` route to LMDB → null. → service collections use **no leading underscore** (`vectorapi_*`). Suspected DB bug. - **`dropCollection` left the collection's indexes declared, before database 2.12.2.** The documents and the metadata went; the declared indexes, unique ones included, stayed. A collection later created under the same name inherited a constraint nobody declared - a legitimate write refused as a duplicate, measured directly: a recycled name on 2.12.0 answered `unique constraint violated on recyc#sku`. Collection-create and collection-delete therefore undeclare indexes explicitly, which is idempotent on 2.12.2 and the correct behaviour against anything older. **The create-time repair must be gated on "is anything still attached to this name", NOT on `getCollectionInfo`** (`anythingAttachedTo()` in `handlers/collections.cpp`): a poisoned name has no collection, so a presence check skips the repair in exactly the case that needs it. 2.12.2 also made `dropIndex` work on an absent collection, which is what lets an already-poisoned name be repaired at all - on 2.12.1 nothing could clear one. - **The ApiFixture tests share one database and a FIXED project name** (`svapitest_apiproj`), so `ctest` must run **serially** - `-j` makes them delete each other's state - and the fixture has to purge the previous run itself. It drops each of the project's indexes before its collection, because neither `dropProject` nor `dropCollection` does (see the two caveats here). None of this shows up in `packaging/devstack`, whose database is new every time; it only appears once the suite runs against a persistent one, which the native host build now does. - **DB v2.3.1: `dropProject` does not physically purge collection data.** A recycled project name is otherwise blocked by stale collections/registry → the project-delete handler drops the registry + collections first, and collection-create drops invisible orphans (after the registry "exists" check). - **WE strip `id` from a document body, not the database client.** This note used to say the client did it, and that is measured as false on client 2.12.1: inserting `{"id":"body-id-value"}` with an explicit document id stores the body field verbatim and it reads back alongside the real `_id` metadata. The stripping is ours, in `documentBody()` (`documents_util.hpp`), which erases `id` and then calls `stripDbMetadata()` to drop the six reserved keys. Keep doing it: the database stores a reserved key as an ordinary user field while every read overwrites it with the real metadata, so a body carrying `_version` would put an invisible shadow copy on disk that no read ever shows and no filter can reach. Our layer is what keeps stored documents clean (the database is fixing this server-side in 2.13.0, for every other client). API keys store their stable id as `key_id` in the body (exposed as `id` externally) - that predates this and the stored rows are not worth migrating, but it was never forced by the client. - **Debian 13 (trixie) gRPC cmake config is broken** unless `protobuf-compiler-grpc` + `libgrpc++-dev` + `libprotobuf-dev` are installed - `find_package(gRPC CONFIG)` (used transitively by `smartbotic-db-clientConfig.cmake`) fails on a `gRPCTargets.cmake` referencing missing plugin files. The Docker base installs them. - **Abseil ABI:** `smartbotic-database`/client debs must be built against the system's current Abseil; a stale build crash-loops on `libabsl_*.so.`. Rebuild the DB if it won't start. - **`--rebuild-base` is required when `DB_CLIENT_VERSION` moves.** The client version is baked into the Docker BASE image, so bumping the variable alone leaves the release build compiling against the old headers - it fails on the new entry points, or worse, silently links the old ones. Note `devstack/run-tests.sh` installs the client debs explicitly, so the TEST path can be on a newer client than the RELEASE path: a green suite is not evidence about the packages. - **`systemctl start` on an already-running unit is a no-op.** A package postinst starts the service, so any config written AFTER apt needs a `restart`, not a `start` - otherwise the process keeps the config that existed at install time and the file on disk disagrees with the running state. Compare the file mtime against `systemctl show -p ActiveEnterTimestamp` when a setting appears not to apply. - **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together. - **The apt repo now indexes EVERY published version, so a rollback is an ordinary apt command.** It used to list only the newest, which made `pkg=` uninstallable the moment anything newer was published - and that was never retention, only indexing: `dpkg-scanpackages` emits one version per package unless given `-m`, while the pool had kept every `.deb` all along (a publish reported "3 added, 309 unchanged"). Fixed 2026-10-08 in the deb-repo tooling; the trixie index went from 33 stanzas to 1191. **A downgrade needs `--allow-downgrades`** (`apt-get install --allow-downgrades pkg=0.7.1-1 ...`), and downgrade the three app packages TOGETHER or apt resolves a split version set. A plain `apt install pkg` still picks the newest, so ordinary installs are unaffected. The backup step still stages the installed `.deb`s out of `/var/cache/apt/archives/`, which stays the right belt-and-braces for a rollback when the repo itself is unreachable. - **"The dev host cannot build the C++" was a misdiagnosis - it was a stale `protoc`.** The host builds everything natively; use `scripts/host-build.sh`. The old symptom was real: generated protos wanted `google/protobuf/map_field_inl.h`, a header protobuf 35 removed. But nothing in the database's tree includes that header - an **old protoc emits the include**. The host had libprotobuf 35.1 and gRPC 1.83 from the distro, and a hand-dropped static **protoc 25.2 in `~/.local/bin`** shadowing everything, while the distro's compiler package (`protobuf-35.1`, separate from `protobuf-devel`, which ships no protoc) was never installed. `find_program(PROTOC protoc REQUIRED)` took the 25.2 binary from PATH, generated code for a protobuf 25 runtime and compiled it against 35 headers. With a matching protoc the client and all of vectorapi compile and link natively. `host-build.sh` therefore picks protoc **by version rather than PATH order** and refuses to run on a mismatch, because the failure otherwise surfaces as a missing header deep in generated code rather than as a version complaint. - **`FailedPrecondition` means three different things** and must be branched on `FailureDetail.reason`: `missing_parent` and `delete_restricted` are 422, `read_only` is **503**, and an absent or unrecognised reason is **500**, never a guessed 422. Mapping the bare code to 422 told a caller that a read-only database was its own validation mistake, so it would fix its payload and retry forever instead of waiting. Use the `FailureDetail&` overloads wherever a call offers one - the reason-less `Failure` form cannot tell these apart. - **A version conflict is `ErrorCode::Aborted`** (client 2.12.0) carrying `currentVersion`, and maps to **409** `version_conflict`. It used to arrive as `Unknown` and fold into 503 "retry as-is", which is the opposite of the required instruction: re-read first. Never match on the message text for this. - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null. - **Null and absent are both unconstrained on a unique index** since database 2.12.0 - only real values collide. Before that, two nulls collided. - **`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. - **`Client::get` returns nullopt for BOTH "absent" and "transport failed"** - it throws only for PERMISSION_DENIED - so a registry lookup cannot tell them apart from the return value. Unhandled, that reaches a caller as 404 "no such collection" for a collection that exists, and a 404 is unretryable BY DESIGN for a careful client, because adding it to a retry set would retry every genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to exactly this. `CollectionRegistry::get` therefore **retries once** (a transient failure usually succeeds, and logs a warning saying so) and then asks `healthCheck()` before reporting absence, throwing **503** when the database is unreachable. Reported upstream too: the client should distinguish, the way it already does for a permission denial. - **A filtered vector search can return FEWER hits than match, and the response now says so.** The walk goes only `kVectorFilterScanCap` (10000) deep into the ranking, so on a larger collection a filter whose matches lie deeper is silently short - measured at 455 returned of 553 true matches on 12448 rows. `VectorSearchResult::scanCapped` is set ONLY when the walk hit the cap while still short of `topK` and the ranking was not exhausted, so a filter that merely matches fewer rows than `top_k` is correctly reported as complete rather than crying wolf. The HTTP route adds `scan_capped`/`scanned`; `ctx...search()` keeps its ARRAY return and warns in the run console instead. - **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`, or `duplicate_id` when `reason` says so (database 2.12.1: a taken document id and a taken unique field value are the same code but different remedies), 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. - **`/etc/smartbotic-vectorapi` must stay mode 0751, not 0750.** The runner runs as its own user and needs `+x` to traverse the directory to `runner.json`; it still cannot list it, and the server's `0640` files stay unreadable to it. Both `server.postinst` and `runner.postinst` set it, and a server upgrade resetting it to `0750` breaks the runner on its **next restart** - a failure that surfaces weeks later with no obvious cause. - **The deb `Depends` lists are HAND-MAINTAINED** - `create-debs.sh` copies each `control.*` template verbatim and never runs `dpkg-shlibdeps`, so a new shared-library dependency does **not** appear by itself; it surfaces as a service that refuses to start on a customer box. The mail surface added two to `control.runner`, both confirmed with `ldd` against the built binary rather than guessed: **`ca-certificates`**, because the vendored curl detects the CA bundle at CONFIGURE time and bakes the path in, and with TLS verification always on a missing bundle makes *every* mail connection fail as `mail_tls_untrusted` (which reads as a broken mail server, not a missing package); and **`libidn2-0`**, because the vendored curl keeps IDN support. IDN is deliberately not compiled out - mail hostnames are usually ASCII, but breaking an internationalised one to save a dependency is the wrong trade. **zlib, zstd and brotli are deliberately absent**: they are HTTP content encodings, HTTP is compiled out of the vendored curl, and leaving them enabled made them real package dependencies for capabilities the code cannot reach. - **Installing the runner does not enable functions.** `config.json` ships with no `functions.runners` endpoints, and the server disables the function routes when the list is empty (answering 503). An operator has to add the endpoint by hand, and set the same `SVAPI_RUNNER_TOKEN` in both `vectorapi.env` and `runner.env`. - **cpp-httplib is pinned (`cmake/Dependencies.cmake`) and the pin carries its reasoning.** Currently v0.59.0. Check for an upgrade periodically: it serves the public HTTP surface AND every outbound call, upstream ships security fixes most releases, and we were 17 releases behind before anyone looked. When evaluating one, judge each fix against **what this service actually reaches** rather than the changelog's severity - `CPPHTTPLIB_REQUEST_URI_MAX_LENGTH` (8192, enforced before routing) means a long-path attack answers 414 before routing and never reaches the regex matcher, so the headline regex stack-overflow fix was never our exposure (verified against a running server, after first proving which process held the port - an earlier run of this test hit an unrelated service listening on the port I had picked), while the request-PARSING fixes (chunked transfer-coding matching, Content-Length truncation, chunk-size control characters) are. Deliberately NOT on the newest release when its fixes are for backends or features we do not use. - **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`. ## Deploy / publish ```bash ./packaging/build.sh # Debian-13 .debs → dist/debian13/ (3 packages: server, webui, runner) ./packaging/build.sh --no-runner # skip the runner package ./packaging/build.sh --repo --suite trixie --sync # + publish to repository.smartbotics.ai (outward-facing!) ``` Publishing uploads to the live apt repo - only with explicit confirmation. The deb-repo tooling is `/data/dev/smartbotics/smartbotics-deb-repo/scripts/` (override with `DEB_REPO_DIR`). **Release packages always come from the Docker path.** The dev host (zeus) runs Void Linux, so `--local` there compiles, runs the tests and leaves a runnable binary in `build/src/` but refuses to build `.deb`s (and refuses `--install`/`--repo`/`--sync`) - a Void-linked package would not install on Debian 13. `--local` still packages normally on a Debian-family host.