Documentation
/ Reference
hive-serve
The runtime that hands cards to an agent. Package hiveserve, CLI hiveserve.
One core, two doors, two stores. By default the serving path calls no model: retrieval is id lookup plus cross-link traversal, and search is token matching. An optional, key-gated semantic layer can additionally rank retrieval candidates with typed-judgment calls; it is off unless a key is set and fails open to this deterministic path - see Semantic layer.
Narrative version: serving cards.
Running
hiveserve serve --http # REST and MCP over streamable HTTP
hiveserve serve --stdio # MCP over stdio, for any client that speaks it
Both transports refuse to start without CONCEPTS_DIR, with an invalid or empty TOOL_PROFILE,
with a RECORDS_DIR that is not a directory or holds no shared records, or without LEDGER_DSN
under the default full tool profile, naming the setting and exiting 1 without a
traceback. Neither CONCEPTS_DIR nor LEDGER_DSN has a default: see the ledger and
CONCEPTS_DIR has no default. The retrieval
profile opens no ledger and needs no LEDGER_DSN.
REST
| Route | Returns |
|---|---|
GET /healthz |
{"ok":true} if the process is alive. Not a corpus check |
GET /metrics |
Prometheus exposition |
GET /concepts |
lean index (optional ?product=), returning non-null fields from id, title, product, type, regime, version, client, corrects, status |
GET /find_concepts?q= |
ranked keyword search over card metadata and body terms (optional product, limit=20; returns {hits, ranking, reason} when the semantic layer is on). Shared cards only |
GET /card/{card_id} |
one card as JSON {"id": ..., "markdown": ...} (404 if missing) |
POST /resolve |
a bundle: cards, their links, their corrections |
POST /resolve takes {"ids": [...], "depth": 1} and rejects unknown fields. client in
particular is not accepted: the REST door serves shared knowledge only, and silently ignoring the
field would return a 200 that looks exactly like scoping working.
GET /find_concepts takes no client either, and neither does GET /concepts; unknown query
parameters are ignored. REST's existing surface is shared-only and does not load the clients tree.
MCP accepts a caller-selected client as retrieval context, independently of ledger identity.
MCP tools
Seventeen in the default full tool profile, in three groups. The retrieval
profile serves the first group alone.
Retrieval: list_concepts, find_concepts, get_card, resolve, find_db_objects,
find_records, get_record (see Records)
Work ledger: start_objective, list_objectives, get_objective, append_entry,
set_status, record_quiz_result
Personal memory: remember, recall, forget, promote
promote does not write to the corpus. It prepares a submission the agent files through the
Hive App connector, where reviewers approve it.
That is the only supported write route; hive-author is deprecated and planned
for removal in a later release.
What each tool declares
Every tool is listed with a title and the four MCP annotation hints, which a client uses to label
the tool and to decide when to ask before calling it. title is also repeated as
annotations.title for clients of the 2025-03-26 protocol, which had no top-level title.
| Declared as | Tools | readOnlyHint |
destructiveHint |
idempotentHint |
openWorldHint |
|---|---|---|---|---|---|
| Read-only | list_concepts, find_concepts, get_card, resolve, find_db_objects, find_records, get_record, list_objectives, get_objective, recall |
true | false | true | false, except find_concepts when the semantic layer is on with a postured model |
| Write, additive | start_objective, append_entry, record_quiz_result, remember |
false | false | false | false |
| Write, destructive | set_status, promote, forget |
false | true | true | false |
The words are the specification's. Destructive is anything that is not purely additive:
set_status replaces an objective's status and promote marks a memory promotion_requested,
neither keeping the value it replaced, and forget deletes a memory outright. Idempotent means
a repeat of the same call changes nothing further, apart from the updated_at stamp the server
keeps for itself; each additive call writes another row. A read-only ledger tool changes no row,
though opening its ledger connection does run the idempotent CREATE TABLE IF NOT EXISTS that
bootstraps an empty schema. Open world means the tool may reach outside this server's corpus
and ledger, which find_concepts does only when the semantic layer
is on and its model has a declared calibration posture: an un-postured model is never called, so
the search egresses nothing.
These are hints, not controls. The specification calls them hints and tells clients not to rely
on them from a server they do not trust, and nothing in hive-serve enforces them: a client that
ignores destructiveHint can call forget, and the call runs. What does decide what a caller can
do is the tool profile, which decides which tools exist at all, and owner scoping in the ledger,
which is exactly as trustworthy as whatever sets the identity header - see
the serving trust boundary.
Tool profiles
TOOL_PROFILE decides which MCP tools this server has.
| Profile | Registers | Ledger |
|---|---|---|
full, the default |
all seventeen tools | LEDGER_DSN required; seven of the tools write, one of them deleting |
retrieval |
the seven retrieval tools | none: no connection is opened, and LEDGER_DSN is not read |
full is what every deployment ran before the setting existed. It registers every tool.
retrieval is enforced by the server, not requested of the client. The ten ledger and memory tools
are never registered, so they are absent from tools/list, and a tools/call naming one is
refused as Unknown tool: <name> without running anything. The process builds no ledger
connection for any purpose, so a retrieval deployment can leave LEDGER_DSN unset and hold no
ledger credential at all; /metrics then reports the corpus gauges and no hive_ledger_rows
samples. The REST door is identical in both profiles, because it has no write route.
Read-only is not public. The retrieval tools still serve the whole corpus, including a client's
memory cards, issue cards and records to any caller who names that client, because the client argument is
retrieval context rather than authorization (the resolver). A deployment
reachable beyond its host needs HTTPS and an authenticating proxy in front in either profile; see
a remote connector. To keep client-scoped cards
and records off a connector entirely, leave CLIENTS_DIR empty.
Any other value, including an empty one, refuses at startup naming TOOL_PROFILE. An unset one
is full, so a misspelt variable name leaves the full profile running without a word. Check
what a deployment actually serves from outside it: a tools/list through its public address must
return exactly the seven retrieval tools.
Modules
| Module | Purpose |
|---|---|
resolver.py |
the core: id to file mapping, corpus index, cross-link traversal with isolation guards, corrections co-pull |
tools.py |
transport-agnostic wrappers over the resolver, shared by both doors |
ranking.py |
the keyword scorer behind find_concepts |
candidates.py |
which cards find_concepts may return (scope, note state and date), the order of its hits, and the candidate union for the semantic layer |
semantic.py |
optional key-gated System One layer: privacy projection, facet routing, batched relevance reranking, circuit breaker, TTL cache, and consequential-judgment seams |
dbobjects.py |
keyword search over the per-product database-object manifests; backs find_db_objects |
records.py |
keyword search over records and the read of one element; backs find_records and get_record |
ledger.py |
Postgres objectives, entries and personal memory, with enum validation and owner-scoped access |
identity.py |
resolve the caller's owner id from the trusted header, else the configured default |
app.py |
the REST door |
mcp_app.py |
the MCP door: tool profiles, each tool's title and annotation hints, each tool metrics-wrapped |
server.py |
CLI and ASGI assembly |
config.py |
typed settings |
metrics.py |
Prometheus registry, instrumentation, TTL-cached corpus gauges |
index.py |
emit index.md and render related into inline links. Not on the serving path |
agent.py, eval.py, run_eval.py |
offline evaluation. Not on the serving path |
calibrate.py |
calibrating the relevance floor on labelled questions. Not on the serving path |
Both doors call the transport-agnostic wrappers in tools.py. REST supplies only the concepts tree;
MCP also supplies the clients tree and, for scoped operations, the caller-selected client.
One agent question, from the MCP tool call to the card bundle that comes back. The lean index is memoized in-process behind a stat fingerprint so a warm turn does not re-parse the corpus; nothing here calls a model:
The resolver
Ids are paths. widget/calibration-routine maps to <concepts>/widget/calibration-routine.md;
ids beginning clients/ map under <clients>. A path that escapes its base resolves to None, so
a traversal attempt returns a missing card rather than a file.
Client scope is structural, derived from the id path rather than a frontmatter field. Listings
and the evaluation selector exclude corrections and use resolver.out_of_client_scope to exclude
memory and issue cards unless their client matches the selected client. Bundle traversal checks
client context directly from ids, admitting shared cards and the selected client's cards. Search's
narrower candidate set is described below. MCP get_card loads any known card id without
a client argument. For the trust boundary, see Identity.
The index excludes the database-object tier. concepts/<product>/db/** is skipped, because a
real schema would swamp it. Those cards are reached through find_db_objects and by id.
Corrections attach automatically, but only with status: approved. A draft correction is inert.
A record is not a card. A text.md file that sits beside a record.yaml file is the text of a
record. The index skips it, and get_card and resolve do not read it.
Records
A record holds the exact content of one version of a source file: a document, a field mapping, a
table or a diagram. hive-ingest writes records. A card gives knowledge and
cites a record for the exact value. Two tools read records. Neither tool calls a model. Records are
not on the REST door.
Where records are
| Scope | Folder | A record resolves |
|---|---|---|
| shared | <RECORDS_DIR>/<folder>/ |
with and without a client |
| client | <CLIENTS_DIR>/<client>/ |
only when the call passes that client |
Each of these folders holds records in this layout:
documents/<name>/<version>/record.yaml, text.md, rows.jsonl, ledger.jsonl
mappings/<name>/<version>/record.yaml, rows.jsonl, ledger.jsonl
tables/<name>/<version>/record.yaml, rows.jsonl, ledger.jsonl
diagrams/<name>@<version>.yaml
To publish the records of a job, copy its documents/, mappings/ and tables/ folders into the
folder of the product or the client. Copy the files of diagrams/records/ into diagrams/.
If RECORDS_DIR has a value and no folder under it holds a record, the server does not start.
If CLIENTS_DIR is empty or does not name a directory, there are no client records, as for memory
cards. A call that passes a client still reads the shared records.
The folder sets the scope. The namespace in a record id does not. A folder of a client that is a link to another folder holds no records. A record path that leaves its folder is ignored.
Client scope is retrieval context, not authorization, as for memory cards. Anybody who can call the connector can name a client. See Identity.
Record ids
An id is [<namespace>/]<doc|mapping|table|diagram>/<name>@<version>[#<element>]. The version is
required. An id without #<element> names the whole record.
| Record | #<element> names |
Examples |
|---|---|---|
| document | a section, a table, a row, the column row of a table, a figure or a tracked change | #list-of-widgets, #t4, #t4.r9, #t4.r0, #fig02, #chg-12 |
| mapping, table | a sheet, a row of a sheet or a note | #fields, #fields.r8 |
| diagram | a node, an edge, a label or a row of a transcribed table | #n3, #e6 |
The two tools
find_records(query, client?, kind?, record?, limit?) is a keyword search with the scorer of
find_db_objects. It searches only the newest version of each record. kind is doc, mapping,
table or diagram. record is a record id without a version. limit is 1 to 100, and 20 by
default. Each hit has id, type, record, version, title, optional client and section
(omitted when absent), and a short preview (a truncated string, or a {column: value} mapping
for table and sheet rows). A hit with pending_change holds a tracked change that nobody accepted
or rejected. The search does not look at deleted text.
get_record(record_id, client?, offset?) returns one element, or the outline of a record.
- If the id resolves,
foundistrue. The answer also has thetype, thesource_files, allversionsand thenewest_versionsof the record, and the content of the element. - If the id does not resolve,
foundisfalseandreasonsays why. A client record that the call cannot see gives the same answer as a record that does not exist. - If the content is longer than
MAX_CHARS, the answer hasnext_offset. Pass that value asoffsetto read the rest. The server splits the lists and themermaidtext of an outline, the rows of a table or a sheet, and the text of a section. Join the pages in order. The server does not cut a list entry or a single element. A section lists its subsections on every page. {--text--}is a deletion and{++text++}is an insertion that the source file still tracks.
The server keeps a search index in memory for each context. It builds the index again when a record file changes. A record file that cannot be read makes the call fail with the name of the file.
hivegen-citation-lint checks the record ids that cards cite. It
uses the same reader as these two tools.
Browse and search explanations (Python)
hiveserve.tools.list_cards(concepts_dir, clients_dir, client=..., kind=..., after=..., limit=...)
returns one layer. Omit client for shared concepts, corrections and database objects; select a
client for that project's memories and issues only. These are stored cards, including historical
and draft cards, not just the current search candidates. Rows include structural id, type
and client, stored status, since, until, timestamp and sources. The caller authorizes
the project before selecting it. Browse lists a card only at its own physical place: a symlink
alias, or an id under concepts/clients/, is not listed as a card. The connector tools keep serving
both as before. Every card path refuses an id containing .. or a file that resolves outside
its configured root.
Pass next_after back as after to continue in card ID order. A null cursor means the page is
last. Database objects use the same cursor, but their frontmatter is read only for the page being
returned. A cursor is not a snapshot; files can change between calls.
hiveserve.tools.find_concepts_with_reasons runs the keyless connector search with the same scope,
product, date and result limit. It returns the same hits, reasons keyed by hit ID, and excluded
rows for word-matching, in-scope notes removed by lifecycle rules. Reasons report the matched
query words. For related and correction traversal, hiveserve.tools.resolve_cards(..., include_reasons=True)
adds links keyed by resolved card ID, with the admitting from_id and link kind. It does not
change bundle selection or apply a search date to direct resolution. Neither explanation invokes
a model or changes any existing connector reply.
Search
find_concepts scopes its candidates with candidates.py and scores them with ranking.py. It is deliberately small - no embeddings,
no network, and no runtime dependency past the standard library. Ranking itself holds no state;
with the semantic layer off, the only process-local
state on this path is the fingerprinted load_index cache described under
the resolver, which exists so a warm search does not
re-parse every card.
find_concepts takes an optional client (MCP only). With a client, search includes that
project's current memory and issue cards alongside shared concepts. Without a client, including
on REST, it still searches only shared concepts. Scope comes from the card's path, not its
frontmatter. product and limit still apply. The same scope and date rules apply with or without
the optional semantic layer; it does not receive project card text.
Use as_of: "YYYY-MM-DD" with client in MCP to search project notes that were current on
that day. For example, {"query": "delivery", "client": "elm", "as_of": "2026-11-09"}.
Without as_of, search behaves exactly as if as_of were the current UTC day. Only the
dates and the state decide whether a note is current. A note is excluded when its status is
draft or pending (not yet approved). superseded and retired notes end on their until
date and need one to appear at all. Every other status, and a missing status (which hive-gen
reads as approved), stays searchable: the engine and its generators write approved,
distilled (legacy hive-zendesk issue cards; hive-zendesk is deprecated), draft, superseded and retired. The since date is
inclusive and until is exclusive: a note replaced on November 9 is no longer current on
November 9, and an old note whose replacement starts tomorrow is still current today. Omitted or
empty dates are open bounds. Malformed dates exclude a note; an invalid as_of returns a tool
error. Shared concepts are not filtered by the project note dates or states.
Hits are ranked by keyword score first. Between notes with the same score, the newer since
date comes first, so a weak match never pushes a strong one out of the limit.
Each hit keeps id, title, product and description, and adds since, until (ISO date
strings, or null if absent) and status. status is the stored status verbatim - approved,
distilled, superseded, retired - or null when the card has none. It is never rewritten, so
a hit for a note that has since been replaced or retired still says so and shows its until date.
These rules apply to search, not to direct card reads or bundle traversal.
find_db_objects has its own scorer, in dbobjects.py, built on this one's tokeniser. It reads
the question the same way (ranking.tokenize: letters and digits, stopwords dropped, punctuation never
stuck to a word) and adds three things this door does not need. Identifiers are also split on camelCase
and kept whole, a light stem makes serialised, serialized and serial one word, and a query term of
four or more characters still matches a fragment of an object name (alloc finding ALLOCATION), at a
quarter of the weight of an exact word. See dbobjects.py for the weights.
Query and card text are tokenised the same way: lowercased, then split on runs of letters and
digits in any script, with the underscore separating words. Punctuation therefore never sticks to
a token, so the 12 in "…in release 12?" is a term rather than the unmatchable 12?. A card id
contributes its slug words on exactly these terms, so widget/calibration-priority-rules is
searchable as four words, weighed like title words. No word segmentation is performed, so text in a
space-free script such as Japanese or Chinese is tokenised at run level: a run between separators is
one term, matched whole against the same runs in the cards.
A small fixed list of English function words is dropped from both sides. A query made only of them matches nothing, which is the honest answer; previously it returned the whole corpus in alphabetical order.
Matching is whole-token, not substring: at no longer matches inside "catalogue".
Ranking is inverse document frequency with sublinear term frequency. A term that occurs in few
cards is worth more than one that occurs in most, and a card that uses the term repeatedly outranks
one that mentions it once without repetition dominating. Document frequencies are computed on each
call from the candidate cards that call is ranking - the ones left after the type, product and
client-scope and date filters - so a scoped search weights terms against its own subset. Cards
are ordered by keyword score first. Between equal scores, a project note with a newer since
comes first, and undated notes and shared cards count as the oldest. Remaining ties break by id.
The limit applies after this order, so a newer weak match never pushes out a stronger older one.
Metadata also includes a card's tags (a flat list) and facets (a mapping of dimension
to value or values). These supply authored synonyms even when the title and description do not
use the query's word. The regime / version frontmatter fields are not searchable unless their
terms also appear in searchable metadata or the body.
Body words supplement metadata locally. A query word found only in a card's body adds half the smaller of its metadata and body inverse-document-frequency weights, once, regardless of repetition. A word already matched in that card's metadata gets no body boost. A word common in metadata cannot become a stronger signal just because it is rare in bodies: one metadata occurrence always outweighs the same word's body contribution. Body document frequencies are computed separately over the same scoped candidates, so adding body text never changes the metadata component of a score. This can bring body-detail answers into the limited result window; it is lexical matching, not a claim that a card answers a question. Long bodies can match more distinct words, but repeating a word does not increase its contribution.
The index caches distinct body terms, not full body strings. Cold loading adds tokenization and
memory proportional to distinct body vocabulary; warm searches intersect query terms with those
sets and retain the existing stat freshness check. No model, network call or new dependency is
involved. Search responses stay lean; resolve still fetches the actual answer. The optional
semantic layer still receives only its existing attested title/description projection, never
body terms or client-note text.
The synthetic evaluation separates development and held-out topic families and measures body-detail recall alongside title and metadata-paraphrase controls. It also includes repetitive long-body distractors. Its authored questions are not representative user traffic; an operator needs their own consented evaluation before claiming production quality. Scope, cache freshness and egress have separate regression coverage.
The earlier metadata-only scorer was measured on a real corpus against labelled questions
at the default limit=20. It retrieved expected cards more often than its token-counting
predecessor without worsening question rankings in that comparison. That historical result does
not evaluate body-term supplementation.
Semantic layer (optional, off by default)
find_concepts can consult a System One typed-judgment model (Hive supports the TypeSafe
System One API, validated with TypeSafe's Jev) to select better-suited cards as the corpus
grows, but only when TYPESAFE_API_KEY is configured. With no key the serving path is
exactly as described above - keyless, LLM-free, portable - and this section does not apply.
The key is the whole on/off switch (Settings.semantic_enabled, SemanticLayer.from_settings
returns None without it). Keyless, find_concepts returns the same bare list[dict] it
always has. Metadata, including tags/facets, and cached body terms contribute to the
keyword score described above without changing the result shape.
The model id is an opaque identifier, and Hive is not architecturally tied to Jev. The
model is passed through to the service in the model field of every request with no name
check, prefix, or allowlist, so any model id the TypeSafe System One API accepts - a versioned
id or an alias - can be configured via SYSTEMONE_MODEL. The response's model field (the
id that actually answered) is reported back for diagnostics: when an alias such as
jev-latest resolves to a different versioned id than the one requested, the reason of a
ranking names both, without treating valid alias resolution as corruption. The engine's
judgments - state, questions, and parsed answers over the Noul / Choice primitives -
are the contract; the model is a selectable implementation of it. Model portability never
reuses unproven calibration: jev-1.13.0 is the built-in calibration posture (the model
this engine ships with, its thresholds tested against the judgment contract), and any other
model id may influence filtering, ranking, facet expansion, sufficiency, or consequential
advice only after the operator explicitly declares a posture for it in
SYSTEMONE_CALIBRATED_MODELS - i.e. after calibrating the thresholds on held-out in-domain
data. Without that declaration the layer serves the labelled deterministic fallback on reads
and abstains on consequential judgments. The built-in posture is a compatibility default, not
a retrieval-quality claim: until a calibrated_gain report exists, no claim about Jev's
retrieval quality, on its own or against any other retrieval system, is supported (see
calibrating the semantic layer).
Recall stays deterministic; only ranking consults the model. When the layer is on, code first
builds a broad candidate union (candidates.build_union): the keyword arm above, plus the
related-graph neighbours of the keyword hits (excluding cross-regime links, exactly as resolve's
auto-expansion does), plus - when the query is classified against the closed facet taxonomy - the
cards in the same facet bucket. The model then reorders that union by a relevance Noul per
candidate, every candidate judged in one request (semantic.select_relevant; see
one request per read). Because the union is built in code, the right card is
reachable without the model - the resolution of the apparent chicken-and-egg problem: the tool
never has to already know which card is right, only to make it reachable before judging.
Fail-open, and what "recall unchanged" does and does not mean. If the service is slow,
refusing, or down - or the configured model has no declared calibration posture - the read
fails open to the union's deterministic order, then truncates to the requested limit. The
worst case is exactly today's top-limit keyword/tag ranking, plus any related or
facet-bucket cards that happen to fit before the cut. Fail-open therefore preserves the
deterministic top-limit order, not the whole union: a card reachable only via the related or
facet-bucket arm sits past the keyword prefix and is in the union for the ranker to promote, not
in a degraded tool payload. "Recall is code's" means the right card is reachable in the union with
no model, not that every union member is returned when the semantic path is down.
The result is labelled when the layer is on. With a key, find_concepts returns
{"hits": [...], "ranking": ..., "reason": ...} instead of a bare list. ranking is "jev"
(the historical wire label for "a System One model ranked this") when the model actually
scored and reordered, or "deterministic_fallback" when the read degraded, so a caller can
tell a model ranking from the deterministic fallback (operators also see the same signal as
jev_events_total{event=degrade}). The reason names the model that ranked - including the
requested id when an alias resolved to a different one. The hits carry the same seven fields
(id, title, product, description, since, until, status) as the keyless list.
Only bounded, permitted fields reach the provider. Every call passes a privacy projection
(semantic.project_card / project_query): client-scoped memory/issue text is refused
structurally, a shared card's text is sent only with an explicit shareable: true attestation,
and of the fields that are permitted, only a card's title and description ever leave - never its
body, id path, client, or the caller's identity. A refusal is a first-class outcome, not an
error: a read degrades, a consequential judgment abstains.
Choice validation is deterministic. Facet routing, ingestion facet stamping and consequential
advice share hivegen.systemone.parse_choice. Each caller supplies its offered options, including
none where applicable. The response must contain exactly those probability keys, finite numbers
in [0, 1] for every probability and confidence (never booleans), and a probability sum within
0.000001 of 1. An omitted answer type is accepted; a conflicting type is not. The parser never
drops invalid entries or renormalizes the distribution. The stated choice must be the unique
highest-probability option: ties and contradictory choices are refused regardless of confidence.
Facet routing skips each invalid, ambiguous, none or under-confident dimension independently;
valid dimensions remain usable. The engine does not introduce an uncalibrated near-tie margin.
Consequential judgments fail closed. semantic.judge_consequential advises a write only as a
PROPOSE/HOLD/ABSTAIN verdict behind a confidence floor. An invalid or ambiguous answer,
un-shareable input, un-postured model, negative choice or failed call returns ABSTAIN.
A valid positive choice below the confidence floor returns HOLD, not permission to write;
only a valid confident positive choice returns PROPOSE.
The write itself is always executed by code, never by the model.
What is wired today, and what is not. Only the read path is live: route_facets widens the
union and select_relevant reorders it inside find_concepts. sufficient (evidence check)
and judge_consequential (write advice) are implemented and tested but not yet called by any
serving tool or ledger write - no live write is gated by the semantic layer today. They are the
typed seams a later phase wires once the thresholds are calibrated; until then, treat them as
available APIs, not as active gates.
Operational controls (all in config.py, all calibratable): systemone_model pins the
model id, systemone_max_candidates caps the union sent per query,
systemone_batch_max_bytes bounds the size of one request, a TTL cache
(systemone_cache_ttl_s) and a circuit breaker (systemone_breaker_threshold /
systemone_breaker_cooldown_s) bound cost and outage blast-radius,
systemone_query_denylist (comma-separated) redacts named client identifiers from the query
before it is egressed, systemone_calibrated_models declares which non-default model ids carry
a calibration posture, and metrics.py exports jev_events_total /
jev_input_tokens_total (metric names kept from the originally Jev-only implementation) with no
client label; event="request" counts the requests the layer sends, so requests per read is
observable in production.
Thresholds ship as conservative placeholders and must be calibrated on held-out in-domain data
before the layer is relied on, never taken as cookbook constants - see
calibrating the relevance floor. The ingestion side that produces
the facet labels this layer aligns against lives in hive-gen (classify_facets), also key-gated.
One request per read
judge_relevance asks about every egress-eligible candidate of a read in one request, not one
request per candidate. The state holds only the projected query; each candidate is one Noul whose
structured instructions carry that card's projected title and description, which is the vendor's
documented pattern for judging one state against many records. Each answer is still one
candidate's own probability. TypeSafe documents the questions of a request as evaluated
independently of one another; whether a model answers a card exactly as it would alone in its
request has not been measured for this shape (see
what has not been measured).
- Nothing identifying rides along. Question ids are positions (
c0,c1, ...), never card ids, so no id path leaves; the projection is unchanged, so neither does a body, a client-scoped card, an un-attested card or the caller's identity. - Bounded.
SYSTEMONE_BATCH_MAX_BYTES(default 64,000 bytes of the request body as sent, compact UTF-8 JSON, sized well inside jev-1.13's documented 64k-token request context) caps a request. A default union typically fits in one; a wider union is split into as few bounded requests as it needs, sent in union order; and a card whose question alone exceeds the budget stays unjudged in its deterministic place, as an un-attested card does (event="oversize"). - Deterministic. Which candidates are judged, in what order and under which ids is a function of the query and the union alone: union order, minus cards with a cached judgment.
- All or nothing. A response is used only if it answers exactly the questions asked, each well formed for its type - a probability in [0, 1] for a Noul, never a bool, NaN or infinity. A missing answer, an unasked one or one malformed value makes the whole response malformed: the read degrades to the deterministic order, the breaker counts a failure, and no further request of that read is sent. A partial judgment is never applied as though it were complete.
A recording fake through find_concepts on a public corpus (BEIR SciFact converted to cards,
300 held-out queries) confirmed that batching reduced request counts and total request-body bytes
for 40-candidate and 60-candidate unions in the encoding HttpSystemOne sends. Latency was not
measured: no key was used, so the wall-time saving from batching is not established here. Neither
is whether a model's answers are unchanged by the move from one card per request to many.
Calibrating the relevance floor
SYSTEMONE_RELEVANCE_FLOOR decides whether a relevance model helps at all: semantic.reorder
promotes only candidates judged at or above it, so a floor set too high leaves a good model's
ranking mostly unused, and one set too low lets a weak model reshuffle the deterministic order.
0.5 is a placeholder, and no floor has been calibrated for Jev or any other System One
model; the only measurement so far used a local stand-in model on public data.
python -m hiveserve.calibrate is the measurement to make before asserting retrieval quality:
python -m hiveserve.calibrate <qa-set> --records .data/calibration/records.jsonl # the only step that calls the model
python -m hiveserve.calibrate --replay .data/calibration/records.jsonl # offline, no key, no corpus
It builds each labelled question's union exactly as find_concepts does and records one
judgment per question through the same batched, privacy-projected path serving uses, measuring its
logical requests, their bytes and each read's wall time as they happen. Offline, it sweeps the
floor, chooses the one with the best MRR on a calibration split (ties go to the deterministic
order, then to the highest floor), and reports the held-out split at that floor against the
deterministic order with a seeded, paired bootstrap interval. A degraded read counts nothing:
the verdict is calibrated_gain only when that interval lies above zero on at least 30 judged
questions per split, a trial any read degraded on a transient/permanent failure or an open
breaker is degraded_trial, and no_calibrated_gain, insufficient_data and no_judgments
all mean the evidence does not support a quality claim for that model on that corpus.
Rows are the eval-set format (question, expected_card_ids, optional client, product, and
split of calibration or heldout; rows without a split are assigned by a hash of their id).
The configured model is measured as though its posture were declared, since calibrating is how a
model earns one; the serving configuration is not changed. Standard output is aggregates only -
no question, card id, case id or client name - and the --records file, which holds case ids, card
ids and scores but never the question text, is as private as the corpus it came from, so
--records refuses, before any paid call, a destination a git work tree could track, and some it
could never write to; record once
lists each refusal and what to do about it.
Calibrating the semantic layer walks through a run
and records what has been measured so far.
The ledger
Postgres, at LEDGER_DSN. Objectives, their entries and personal memory, keyed by owner and
validated against enums.
LEDGER_DSN has no default and there is no file fallback: under the default full tool profile
hiveserve serve refuses to start without it, on either transport; the retrieval profile never
reads it, so a retrieval deployment can leave it unset (see tool profiles).
OKF_DATA_DIR is unrelated scratch space and despite its name holds no ledger.
It was a SQLite file under OKF_DATA_DIR until 2026-08-19. It moved because it is the only
mutable state this service holds, and a managed platform backs up a database it manages and does
not back up a file in a volume. Being a database is what makes it get backed up. There is
deliberately no dual-engine support: two placeholder styles chosen at runtime is how you get a
query that is fine against the engine you tested and broken against the one you deployed.
The only state in the system that is not in git. Cards restore from any clone. This does not.
Identity
See the serving trust boundary for ledger identity, caller-selected retrieval context, and the required authenticating proxy.
Metrics
See metrics. The short version: /healthz cannot see an empty corpus, so alert on
hive_corpus_cards and hive_corpus_db_objects. Both, because the first excludes the
database-object tier and that tier is usually most of the corpus.
The evaluation harness
agent.py, eval.py and run_eval.py score retrieval against labelled question sets. They do
call a model, through hivegen, and are never on the serving path.
Question sets name real card ids, so they are corpus-specific and ship with a corpus rather than
with the product. run_eval therefore requires the set as an argument and has no default. A bare
name resolves under EVAL_DIR; a path with a suffix is taken as given. The cards come from
CONCEPTS_DIR.
Both are checked before any model is called. An absent or empty corpus scores zero on every question
and reports an aggregate as though it had measured something, so run_eval refuses instead, naming
the setting. "Empty" is load_index's definition, not "holds no .md", since index.md, log.md
and the <product>/db/ tier are not cards. CLIENTS_DIR stays optional: run_eval refuses only
when the set it was handed has rows expecting client cards, and otherwise - when the setting names
a path at all, rather than being empty or unset - prints that a dead path disabled client
memory rather than degrading quietly. When it names one, existing is not
enough either - run_eval asks load_index which clients it can serve and refuses naming the ones
it cannot. What counts as "needed" is which clients a row expects cards for - an expects_memory
id, or a clients/<client>/... entry in expected_card_ids - never the client field alone. A
control client in an isolation set deliberately has no memory of its own, and demanding cards for it
would refuse the deploy gate. Such a run is allowed to proceed but not to be read as cross-client
isolation: score_memory counts a card only when its client differs from the row's, so when no row
has any served client out of its own scope, cross_client scores zero because nothing could have
leaked rather than because isolation held. run_eval says so on stdout and records
cross_client_unexercised beside the aggregate, because the report is what outlives the terminal.
That flag is scoped to cross_client alone: memory_ok for a row carrying expects_memory stays a
real and failable measurement, since it also requires that client's own memory card to have been
retrieved. Reports are written under OKF_DATA_DIR.
What the judge is shown, and what correct and grounded mean
Scoring contract changed on 2026-09-06. correct and grounded scores from the old,
expected-only reference are not comparable with scores under this contract; do not combine them
in one comparison table. Identify the contract by the evaluated engine revision, not merely the
report's creation date.
The judge's REFERENCE is now the union of the row's expected_card_ids and the bundle the
answerer actually saw, expected cards first, de-duplicated, with no truncation in either progressive
or ceiling mode. Bundle members use the exact card texts delivered to the answerer, even if those
files change or disappear during the model call; only expected-only cards are loaded separately.
Missing expected-only cards are omitted. The union prevents correctly retrieved evidence outside
the labelled expected set from being invisible to the judge.
The grading prompt is unchanged: correct and grounded are model verdicts against that
REFERENCE. It can include expected-only cards the answerer did not see, so grounded is not a
separate proof of support from the delivered bundle alone. The deterministic metric definitions
(select_hit, bundle_hit, regime_ok, version_ok, product_ok, correction_ok, memory_ok)
are unchanged; their values can still change when the selector's candidate set changes.
A model that returns nothing fails the run
unscored alone does not distinguish an unparseable judge reply from no reply. Rows therefore
carry select_empty, answer_empty and judge_empty, treating None, empty strings and
whitespace-only replies as empty. Answer and judge make one call per row, so their flags describe
that one reply. Selection retries once, so select_empty is true only when the selector produced
nothing on every attempt; a row where it replied on either attempt, even unusably, is a genuine
retrieval miss rather than an absent measurement. The aggregate carries their counts plus failed,
which is true if any of the three roles returned nothing on any row. Such a report is
incomplete, not a valid low-scoring baseline.
After writing the report, the CLI prints one diagnostic per failing role naming its setting,
configured model and affected row count, then exits with status 1. Check BIFROST_API_KEY,
gateway model availability and provider quota; an exhausted token plan can fail calls even with a
valid key. Model defaults and overrides are in configuration.
An unparseable-but-present judge reply still scores unscored and does not by itself fail the
run. The same holds for the selector: a reply this cannot parse, or one naming only unknown ids,
is a genuine retrieval miss measured by select_hit and bundle_hit.
select_empty joined them on 2026-09-06. The selector was excluded until then, on the
reasoning that a selector returning nothing is just a retrieval miss. DeepSeek V4 Flash 0731,
measured as a candidate selection default in a trial over real selection prompts, failed to
produce usable card_ids lists: some responses were empty and others used a different JSON schema.
This guard catches the empty responses - the harness scored them as retrieval misses and reported
a collapse it had never observed, the same shape of false zero the answer and judge guards already
existed to prevent. Wrong-schema replies are not covered and are not meant to be: a wrong-schema
reply is an unparseable selection naming no card ids, which stays a genuine retrieval miss by the
rule above.
Internals
Module-level detail for the serving core, search indexes, ledger and evaluation harness.
resolver.py, the whole retrieval algorithm
Index construction and bundle traversal live here. Their client scope is retrieval context, not an identity-bound access control.
card_path maps a card id to a file. Ids starting clients/ resolve under CLIENTS_DIR,
everything else under CONCEPTS_DIR. Both are resolved and bounds-checked, so a crafted id cannot
escape its directory.
clients_base is where "empty means client memory is off" is decided, once, for every caller.
Path("") is Path(".") and exists, so an empty CLIENTS_DIR that reached card_path or
load_index directly would have scanned the working directory and answered clients/… ids out of
it. Both doors, the metrics collector and the eval all funnel through here, so none of them can
disagree about what "unset" means.
load_index builds the index from frontmatter and distinct, immutable body-token sets.
It retains no full body strings and exposes no body field through search or listings. Client cards get a
client facet derived from the id path, not from author-supplied frontmatter, so a card cannot
declare itself into another client's scope.
The index is cached in-process and invalidated by a per-file stat fingerprint.
load_index used to rglob and yaml.safe_load every card on every call; on a large corpus
that made find_concepts slow and repeated the work inside resolve for corrections. The cache
keeps the parsed rows keyed by (concepts_dir, clients_dir) and re-parses only when the fingerprint of
the indexed *.md paths changes (each file's path, mtime_ns and size). Every call still stats
those paths to decide freshness; it does not walk concepts/<product>/db/**, which the lean
index never parses (client trees are fingerprinted in full, matching what load_index can read
under memory/ and issues/). Returned rows are shallow copies, so a caller may reshape its own
row without mutating the cache. Empty CLIENTS_DIR still means client memory is off
(clients_base). A different clients_dir path is a different cache key. The caller-selected
client argument does not choose a cache entry - one process-level index can hold every client's
memory rows, and out_of_client_scope / client_of_id still apply after the load; that is
structural scope, not identity-bound authorization (see
serving trust boundary). This is
mechanical memoization only: no model, no durable store, and no change to ledger semantics or the
permission boundary. Full card text still loads from disk when resolve or get_card needs it.
The cache ships in the engine package (hiveserve.resolver); a deployment only sees it after
pinning a release that contains it - see
Cutting a version. Regression coverage
lives in tooling/hive-serve/tests/test_index_cache.py and test_candidate_union.py (edit,
same-size older-card edit, delete, db-tier exclusion, concurrent readers, cold vs warm
find_concepts / resolve with a db-object tier present).
resolve is a breadth-first walk with three independent limits and two guards:
seed ids that exist AND are in scope
expand follow related: edges, up to `depth` levels
budget stop at `max_cards` (default 8); then optionally trim to `max_chars`
The two guards run on every neighbour, and both share a subtlety worth stating:
| Guard | Rule |
|---|---|
| Cross-regime | skip a neighbour whose regime differs from its parent's |
| Cross-client | skip a neighbour scoped to a different client than the active one |
A skipped neighbour is deliberately not marked as seen. It stays reachable by another path that legitimately leads to it. Marking it seen would let the first, rejected traversal permanently hide a card from a valid one, and the symptom would be an answer missing a card for reasons invisible in the output.
Broken links are tolerated. A related: id with no file is skipped silently rather than
raising. A corpus mid-edit stays servable; validate-atomic and the lint scripts are where dangling
links are supposed to be caught.
The character budget always keeps at least one card. The trim only drops a card if something is
already kept, so a single card larger than max_chars is returned rather than an empty bundle.
Corrections are co-pulled last and are unbudgeted. After selection and trimming, every active
correction of every selected concept is appended. They are not subject to max_cards or
max_chars, because a dropped correction means the wrong fact stands.
The internal return also includes card_texts, an id-to-text mapping captured when bundle is
assembled. agent.answer_question passes it to the evaluator as bundle_cards for the judge's
reference. The transport wrapper strips it: REST and MCP still return only
{card_ids, bundle, dropped, corrections}. dropped is what the budget removed, and it is worth
surfacing: a silently truncated bundle looks like a complete answer.
dbobjects.py
LLM-free keyword search over concepts/<product>/db/manifest.jsonl, one JSON object per line,
emitted by the parser. Optionally filtered by kind or module, capped by limit (default 20). The
arguments and the six returned fields (id, kind, module, product, title, description) are
unchanged.
Ranking. It used to count how many raw query words were substrings of a row's text. For a
natural-language question that is noise: in, is, or and an sit inside every long description,
so a long description won and the tie went to the alphabetically first id. A natural-language
question such as "How do we tell if a catalog part is serialised or non-serialised?" returned
user-exit callouts and no schema object. The scorer now:
| Signal | Effect |
|---|---|
Stopwords and question words (ranking.STOPWORDS, plus we, find, non, get and a few more) |
dropped from the query; a query of only these returns nothing |
| Where the word is | object name 3.0, tags (with kind and module) 1.5, description 1.0 |
| How rare the word is | inverse document frequency over the whole manifest, so serial outweighs part |
| Fragment of an identifier | a term of four or more characters inside a longer name word counts a quarter of an exact word |
| Coverage | the score is scaled by 0.5 to 1.0 for the share of the question's distinct terms the row matches |
| Name precision | scaled by 0.7 to 1.0 for the share of the object's name words the question used, so an object named for the question beats one that mentions it |
Ties break on id. A fragment is matched against the unstemmed and plural-stripped words of the object name only, never a description. The ranking can only be as good as the rows: the manifest holds one row per object, so a field is found through the description of the object row that holds it. The scorer alone cannot return a field that no row names; richer field meanings belong in the corpus's own object descriptions.
Cost. The manifests are parsed once per process into a compact inverted index and reloaded only
when a manifest file changes (mtime or size) or appears. hiveserve serve builds it in a background
thread at startup, and building is single-flight, so concurrent first searches parse once instead of
re-reading and re-parsing the manifest on every call.
The same family as memory recall, deliberately. Neither calls a model, so both are cheap enough to
sit in a tool loop and deterministic enough to test.
ledger.py
Three tables in one Postgres database: objective, entry, memory. Enum-validated on write and
owner-scoped on every read and write. entry and memory carry a seq BIGSERIAL that
replaces SQLite's rowid as the tiebreaker for equal timestamps; without it the order of two rows
written in the same clock tick is whatever the planner returns.
The schema is created on first connection, one statement at a time, because psycopg reports a multi-statement failure against the whole batch rather than the statement.
identity.py
Resolves owner from the configured trusted header, falling back to the configured default when
there is no header (stdio, where there is no gate in front).
Header lookup is case-insensitive: it tries the exact name, then retries against a lowercased view of the keys, because a plain dict is case-sensitive while HTTP headers are not. A gate that sends a differently-cased header would otherwise silently produce the default owner for everyone, which is a data-mixing bug rather than an error.
app.py, mcp_app.py, server.py
app.py is the FastAPI REST router. mcp_app.py is the FastMCP server: 17 tools under the full
tool profile and 7 under retrieval, each declared with a title and its
annotation hints, no prompts, injecting owner from the request context so it can never be a tool
parameter. The ledger and memory tools are defined only in the function the full profile calls,
so a retrieval server cannot register them by accident. server.py is the entrypoint that mounts
the MCP streamable-HTTP app onto the same FastAPI process for --http, or runs stdio, and gives
the retrieval profile no ledger connection factory at all.
agent.py, eval.py, run_eval.py
The offline evaluation harness. Not on the serving path; it calls a chat model through
hivegen to measure retrieval and answer quality (separate from the optional System One semantic
layer in semantic.py and calibrate.py). The product-isolation eval over it is the deploy gate.
The selector uses the index scope filter before constructing its model prompt, not merely when resolving the selected ids. This keeps out-of-context issue titles and descriptions off the gateway as well as out of the answer bundle. See the harness contract for reference construction and failure reporting.
Tests
See contribution testing guidance for setup and the
live-corpus and Postgres requirements. Tests live in tooling/hive-serve/tests/; use pytest's
--collect-only -q there for the current inventory rather than a hand-maintained count.
Configuration
See configuration.
Gotchas
/healthz reports healthy on an empty corpus. This has caused a real outage.
Bind mounts resolve at container start. If a corpus directory is deleted and recreated beneath a running container, it keeps the old inode and keeps serving the detached contents. Re-seeding a corpus needs a restart; editing files inside it does not.
Cards are read live. A card edited in the corpus is served on the next request. Code changes need a rebuild; content changes do not.