Procházet zdrojové kódy

build: the dev host can build the C++ after all, plus clangd

"The Void dev host can no longer build the C++ natively" was a misdiagnosis we
carried for months. The symptom was real - generated protos wanted
google/protobuf/map_field_inl.h, which 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 (separate from protobuf-devel, which ships no protoc) was never
installed. find_program(PROTOC protoc REQUIRED) took 25.2 from PATH, generated
code for a protobuf 25 runtime, and compiled it against 35 headers.

With a matching protoc the database client and all of vectorapi compile and
link natively. scripts/host-build.sh does it with clang: 139 targets in about
100 seconds, 794/794 tests, and it can compile runner/src/main.cpp, which
previously only the container could - the reason that file kept breaking. It
picks protoc by version rather than PATH order and refuses to run on a
mismatch, because otherwise the failure surfaces as a missing header deep in
generated code rather than as a version complaint.

That build also produces the compile_commands.json clangd needs, so .clangd and
.clang-format are now configured over src/, tests/ and runner/. The clang-tidy
set is deliberately narrow; .clang-format describes the style the code already
uses rather than imposing one, and the code is hand-laid-out rather than
formatter-clean, so it is for new and changed code only.

Release packages still come from the Debian image: this build links the host's
protobuf and gRPC, not the versions the .deb is built against.
fszontagh před 1 měsícem
rodič
revize
18c70daf57
4 změnil soubory, kde provedl 242 přidání a 16 odebrání
  1. 29 0
      .clang-format
  2. 48 0
      .clangd
  3. 25 16
      CLAUDE.md
  4. 140 0
      scripts/host-build.sh

+ 29 - 0
.clang-format

@@ -0,0 +1,29 @@
+# Describes the style the codebase ALREADY uses, so running it is close to a
+# no-op on existing files. Derived by measuring: 4-space indent, no tabs,
+# references bound to the type, attached braces, and a 100-column line (the
+# 99th percentile of existing lines is exactly 100).
+Language: Cpp
+BasedOnStyle: LLVM
+IndentWidth: 4
+TabWidth: 4
+UseTab: Never
+ColumnLimit: 100
+PointerAlignment: Left
+ReferenceAlignment: Left
+AccessModifierOffset: -2
+AllowShortFunctionsOnASingleLine: Inline
+AllowShortIfStatementsOnASingleLine: WithoutElse
+AllowShortLoopsOnASingleLine: true
+BreakBeforeBraces: Attach
+# The single most important setting here. Every route handler is a lambda
+# passed to svr.Get/Post/..., and the codebase indents its body 4 from the
+# STATEMENT, not from the lambda's column. Without OuterScope, clang-format
+# re-indents every handler body in the project.
+LambdaBodyIndentation: OuterScope
+# The flat quoted-include convention: our own headers are one group and must
+# not be re-sorted into the system block.
+IncludeBlocks: Preserve
+SortIncludes: CaseSensitive
+# A braced initialiser holding a JSON object literal is laid out by hand to show
+# its shape; letting clang-format repack it destroys the readability.
+Cpp11BracedListStyle: true

+ 48 - 0
.clangd

@@ -0,0 +1,48 @@
+# clangd now reads a REAL native build: build-host/compile_commands.json, which
+# covers src/, tests/ and runner/ including runner/src/main.cpp. Generate it
+# with scripts/host-build.sh.
+CompileFlags:
+  CompilationDatabase: build-host
+  Add:
+    # clangd defaults to its own driver; the build uses clang++ 21, and these
+    # keep the diagnostics the compiler would actually give.
+    - -Wall
+    - -Wextra
+  Remove:
+    # Emitted by the generated protos' build flags and meaningless to the
+    # indexer, which parses rather than codegens.
+    - -fno-canonical-system-headers
+
+Diagnostics:
+  UnusedIncludes: Strict
+  MissingIncludes: Strict
+  ClangTidy:
+    # Narrow on purpose. The checks here are the ones that catch real bugs in
+    # this codebase; the broad modernize/readability families would bury them
+    # under thousands of style notes on 20k lines of existing code.
+    Add:
+      - bugprone-*
+      - cert-*
+      - clang-analyzer-*
+      - misc-*
+      - performance-*
+    Remove:
+      # Handlers legitimately take JSON by value and move it onward.
+      - performance-unnecessary-value-param
+      # Fires on every GoogleTest macro.
+      - misc-use-anonymous-namespace
+      # Our ApiError-throwing handlers are not noexcept candidates.
+      - bugprone-exception-escape
+      # std::rand is not used for anything security-relevant in tests.
+      - cert-msc30-c
+      - cert-msc50-cpp
+      # Deliberate: see the include-what-you-use note above.
+      - misc-include-cleaner
+
+InlayHints:
+  Enabled: true
+  ParameterNames: true
+  DeducedTypes: true
+
+Hover:
+  ShowAKA: true

+ 25 - 16
CLAUDE.md

@@ -1,4 +1,4 @@
-# CLAUDE.md — smartbotic-vectorapi
+# 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.
 
@@ -18,30 +18,37 @@ ctest --test-dir build --output-on-failure
 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 (the dev host can no longer build C++ - see gotcha)
+# 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.
+- `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`). 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.
+- `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`). 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.
 
 ## 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.
+- **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/<version>` 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`.
 
@@ -51,10 +58,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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.
+- **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.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.
 - **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 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.
@@ -70,21 +77,23 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 ## 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_<name>` doc per project carrying that project's embedding overrides (empty field = inherit; the body repeats `project` because the DB strips `id`). Per-project registry: `<project>:vectorapi_collections`. The `vectorapi_` prefix is reserved (collection-create rejects `_` and `vectorapi_`).
+- 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_<name>` doc per project carrying that project's embedding overrides (empty field = inherit; the body repeats `project` because the DB strips `id`). Per-project registry: `<project>: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)
+## ⚠️ 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` does not undeclare the collection's indexes** (database 2.12.1). The documents and the collection metadata go; the declared indexes, unique ones included, and their postings stay. A collection later created under the same name therefore inherits a constraint nobody declared, so a legitimate write is refused as a duplicate and the new owner's own `POST /indexes` reports `already_existed` instead of validating their data. Collection-create (the invisible-orphan drop) and collection-delete both undeclare indexes first for this reason. Worse, once the collection is gone the declaration is **unreachable and unrepairable**: `getCollectionInfo` says absent, `listIndexes` still names the field, and `dropIndex`/`dropCollection` both return false without clearing it, so the name is permanently poisoned. Reported to the database session; `dropIndex` on an absent collection is the fix that would let an existing one be repaired.
+- **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).
 - **DB client strips an `id` field from stored doc bodies.** So API keys store their stable id as `key_id` in the body (exposed as `id` externally); document handlers strip `id` before insert and use the separate id param.
-- **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.
+- **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.<old>`. 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 drops superseded versions on publish**, so `pkg=<old version>` is uninstallable afterwards. Old `.deb`s survive in `$DEB_REPO_DIR/dist`; `build.sh` vendors the pinned client from there into `packaging/vendor/`, and a prod rollback needs them scp'd to the target first.
-- **The Void dev host can no longer build the C++ natively.** Void moved to protobuf 35 / gRPC 1.83; protobuf 35 removed `google/protobuf/map_field_inl.h`, which the database's generated protos include, so `libsmartbotic-db-client` neither compiles nor links there (the installed `.so` still wants `libgrpc++.so.1.61`). Release builds are unaffected because they run in the Debian 13 image. For local backend work use `packaging/devstack`; `ctest` cannot run on this host.
+- **"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.
@@ -96,7 +105,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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.
 - **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`.
-- **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline — do not revert to the CDN loader.
+- **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
@@ -106,6 +115,6 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 ./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`).
+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.

+ 140 - 0
scripts/host-build.sh

@@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+# Build vectorapi natively on the dev host, with clang, including the runner.
+#
+# This exists because the host CAN build everything, contrary to a note this
+# repo carried for a long time. The blocker was never protobuf 35: it was a
+# stale protoc earlier in PATH. An old protoc emits generated code that
+# includes google/protobuf/map_field_inl.h, a header protobuf 35 removed, and
+# compiling that against the installed headers is what failed. A protoc
+# matching libprotobuf fixes it, and then the database client and all of
+# vectorapi build and link natively.
+#
+# What this buys: a ~100 s full build instead of a container round trip, clang's
+# diagnostics, a real compile_commands.json for clangd, and the ability to
+# compile runner/src/main.cpp, which previously only the container could.
+#
+#   scripts/host-build.sh            # configure + build
+#   scripts/host-build.sh --test     # + run the suite (serially; see below)
+#   scripts/host-build.sh --client   # also rebuild the database client first
+#
+# Release packages still come from packaging/build.sh and the Debian image.
+# This build is for development only: it links the host's protobuf/gRPC, not
+# the versions the .deb is built against.
+set -euo pipefail
+
+REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+PREFIX="${SVAPI_HOST_PREFIX:-/data/dev/smartbotics/.hostprefix}"
+DB_SRC="${SVAPI_DB_SRC:-/data/dev/smartbotics/smartbotic-database}"
+BUILD="$REPO/build-host"
+WITH_CLIENT=0
+RUN_TESTS=0
+for a in "$@"; do
+    case "$a" in
+        --client) WITH_CLIENT=1 ;;
+        --test)   RUN_TESTS=1 ;;
+        *) echo "unknown argument: $a" >&2; exit 2 ;;
+    esac
+done
+
+# The protoc must match the installed libprotobuf. Comparing the two is the
+# whole point: a mismatch is the failure this script exists to prevent, and it
+# shows up as a missing header deep in generated code rather than as a version
+# complaint, so check it up front and say so plainly.
+lib_ver="$(pkg-config --modversion protobuf)"
+lib_major="${lib_ver%%.*}"
+find_protoc() {
+    for p in "${SVAPI_PROTOC:-}" "$PREFIX/bin/protoc" /usr/bin/protoc "$(command -v protoc || true)"; do
+        [[ -n "$p" && -x "$p" ]] || continue
+        if [[ "$("$p" --version | awk '{print $2}' | cut -d. -f1)" == "$lib_major" ]]; then
+            echo "$p"; return 0
+        fi
+    done
+    return 1
+}
+if ! PROTOC="$(find_protoc)"; then
+    cat >&2 <<EOF
+No protoc matching libprotobuf $lib_ver found.
+
+  installed libprotobuf : $lib_ver  (so major $lib_major)
+  protoc in PATH        : $(command -v protoc >/dev/null && protoc --version || echo "none")
+
+Get a matching one, then re-run:
+  - Void:  sudo xbps-install protobuf-$lib_major.<minor>
+           ('protobuf-devel' does NOT ship protoc; the compiler is its own package)
+  - or:    download protoc-$lib_major.<minor>-linux-x86_64.zip from
+           https://github.com/protocolbuffers/protobuf/releases and point
+           SVAPI_PROTOC at its bin/protoc
+
+Note a stale protoc earlier in PATH (commonly ~/.local/bin/protoc) will be
+found before the system one. This script ignores PATH order and picks by
+version, but the database's own CMake does not.
+EOF
+    exit 1
+fi
+echo "protoc: $PROTOC ($("$PROTOC" --version)) against libprotobuf $lib_ver"
+
+if (( WITH_CLIENT )); then
+    [[ -d "$DB_SRC" ]] || { echo "database source not at $DB_SRC" >&2; exit 1; }
+    echo "=== building libsmartbotic-db-client from $DB_SRC into $PREFIX ==="
+    cmake -B /tmp/svapi-dbclient -G Ninja -S "$DB_SRC" \
+        -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" \
+        -DPROTOC="$PROTOC" \
+        -DSMARTBOTIC_DB_BUILD_CLIENT=ON -DSMARTBOTIC_DB_BUILD_SERVICE=OFF \
+        -DSMARTBOTIC_DB_BUILD_CLI=OFF -DSMARTBOTIC_DB_BUILD_TESTS=OFF >/dev/null
+    cmake --build /tmp/svapi-dbclient -j"$(nproc)"
+    cmake --install /tmp/svapi-dbclient >/dev/null
+    # `cmake --install` ships the library and headers but no CMake package, so
+    # find_package(smartbotic-db-client) would fail: only the .deb carries a
+    # config, written by the database's create-debs.sh. Write a relocatable one.
+    libdir="$(cd "$PREFIX" && ls -d lib64 lib 2>/dev/null | head -1)"
+    mkdir -p "$PREFIX/$libdir/cmake/smartbotic-db-client"
+    cat > "$PREFIX/$libdir/cmake/smartbotic-db-client/smartbotic-db-clientConfig.cmake" <<'EOF'
+# Host build of smartbotic-db-client, not the Debian package. Relocatable:
+# every path derives from this file's location.
+include(CMakeFindDependencyMacro)
+find_dependency(Protobuf REQUIRED)
+find_dependency(gRPC CONFIG QUIET)
+if(NOT gRPC_FOUND)
+    find_package(PkgConfig REQUIRED)
+    pkg_check_modules(GRPC REQUIRED IMPORTED_TARGET grpc++)
+endif()
+get_filename_component(_sbdb_prefix "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE)
+if(NOT TARGET smartbotic::db-client)
+    add_library(smartbotic::db-client SHARED IMPORTED)
+    set_target_properties(smartbotic::db-client PROPERTIES
+        IMPORTED_LOCATION "${_sbdb_prefix}/@LIBDIR@/libsmartbotic-db-client.so"
+        INTERFACE_INCLUDE_DIRECTORIES "${_sbdb_prefix}/include")
+    if(TARGET gRPC::grpc++)
+        set_property(TARGET smartbotic::db-client APPEND PROPERTY
+            INTERFACE_LINK_LIBRARIES protobuf::libprotobuf gRPC::grpc++)
+    else()
+        set_property(TARGET smartbotic::db-client APPEND PROPERTY
+            INTERFACE_LINK_LIBRARIES protobuf::libprotobuf PkgConfig::GRPC)
+    endif()
+endif()
+EOF
+    sed -i "s|@LIBDIR@|$libdir|" \
+        "$PREFIX/$libdir/cmake/smartbotic-db-client/smartbotic-db-clientConfig.cmake"
+fi
+
+[[ -d "$PREFIX/include/smartbotic" ]] || {
+    echo "no database client at $PREFIX - run with --client first" >&2; exit 1; }
+
+echo "=== configuring $BUILD (clang, Debug, runner on) ==="
+cmake -B "$BUILD" -G Ninja -S "$REPO" \
+    -DCMAKE_BUILD_TYPE=Debug \
+    -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
+    -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
+    -DCMAKE_PREFIX_PATH="$PREFIX" \
+    -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF -DBUILD_RUNNER=ON
+cmake --build "$BUILD" -j"$(nproc)"
+ln -sfn build-host/compile_commands.json "$REPO/compile_commands.json"
+echo "compile_commands.json -> build-host (clangd is ready)"
+
+if (( RUN_TESTS )); then
+    # SERIALLY, deliberately. The ApiFixture tests all share one database, one
+    # fixed project name and the two global service collections, so running
+    # them in parallel makes them delete each other's state.
+    echo "=== ctest (serial) ==="
+    ctest --test-dir "$BUILD" --output-on-failure
+fi