kb
What it does
kb (.framework/functions/kb.ts) is the knowledge-base surface: a thin ?action= dispatcher over the shared implementation in .framework/functions/_shared/kb.ts. It maintains embeddings vector rows for published knowledge items and serves semantic search over them, gated by the calling app's knowledge envelope.
| Action | Handler | Purpose |
|---|---|---|
ingest | kbIngest | Embed one items record's declared vector fields into embeddings. |
revoke | kbRevoke | Revoke + delete a document's embeddings and clear its ingest lease. |
reindex | kbReindex | Re-ingest every published item of a type (batched, 10 in flight). |
search | kbSearch | Vector search via match_embeddings, best-match-per-document. Default action. |
publish | kbPublish | PATCH status: 'published' through admin-data, then ingest. |
Route and methods
/api/kb?action=<action>—public/_redirectsmaps/api/*to/.netlify/functions/:splat. The action comes fromctx.query.actiononly — it must be a query parameter; the HTTP method itself is not checked, and the body carries the parameters.- The function is configured with a 120s timeout in
netlify.toml(reindex sweeps a whole corpus).
Authentication
createHandler resolves a principal and rejects anonymous requests with 401. There is no role gate on the actions themselves; authorization is enforced downstream:
kbSearchrunsresolveKnowledgeScope— deny-by-default unless the caller's app declaresconfig.knowledge— and each result is passed throughsanitizeRecordDatabefore returning.kbPublishgoes through admin-dataupdate(a synthetic PATCH), so field-level permissions and triggers apply.kbIngest/kbRevoke/kbReindexoperate viaadminDb— they rely on the caller being trusted to name a document;body.account_idon ingest lets an operator ingest a record owned by another account.
Request contract
ingest: { id (required, items.id), account_id? }
revoke: { id (required) }
reindex: { type_slug (required), app_id? } — app_id narrows the items re-ingested.
search:
| Field | Default | Notes |
|---|---|---|
query | — | Required. |
type_slugs | [] | The caller's pick — intersected with the app envelope; picks outside it deny the call. |
sources | ['kb'] | 'kb' for knowledge items, 'code' for legacy cil_* chunk vectors — the CIL corpus is retired (079) but preserved rows remain readable. |
app_id | null | Post-filter on metadata.app_id. |
vector_fields | [] | Restrict to specific metadata.vector_type values. |
limit / offset | 10 / 0 | Page over best-match documents. |
similarity_threshold | 0.15 | Minimum cosine similarity. |
filters | {} | Post-filter on the resolved items row. |
publish: { id (required) }
Response contract
ingest→{ ok, message, count?, in_progress? }.messageis one ofembeddings generated,embeddings reused (unchanged content),record is not published; embeddings revoked if any,embedding already in progress(within_progress: true— not a success signal for stampers), orno content to embed.revoke→{ ok, message: 'embeddings revoked', count }, or{ ok, skipped: true, message: 'document is published — embeddings retained', count: 0 }— revoke re-checks current status at execution time and refuses to strip a now-published document.reindex→{ ok, count, errors?: [{ id, error }] }— per-item failures are collected, not fatal.search→{ results, count, error? }; results are{ id, document_id, type_slug, title, snippet, app_id, similarity, status, created_at, source, data }sorted by similarity.errorcarriesknowledge_denied: <reason>when the envelope refuses.publish→{ record, ingest }— the admin-data update result plus the ingest result.
Side effects
ingest: reads the record's stampeddesign_schema.functionality.kb—vector_fields(default['title', 'content']),chunk_field(defaultcontent),chunk_size(800),chunk_overlap(100),security_level(deny-by-defaultinternal),supersede_keys. Field text is normalized (rich-text HTML stripped, bare UUID tokens dropped) and hashed — adocument_leasesrow (migration054) dedupes unchanged re-embeds (reused) and fences concurrent workers (processing). Prior embeddings are cleared viarevoke_embeddings_for_item+ delete, chunks are embedded in one batchedcallOpenAIEmbeddingscall (text-embedding-3-small), and new rows are inserted withmetadata.{type_slug, item_type, app_id, vector_type, security_level, status}andapproved_atset. Olderpublisheditems sharing asupersede_keysvalue are archived withsuperseded_by/superseded_atand their embeddings revoked.revoke:revoke_embeddings_for_itemRPC + embeddings row delete + unconditionaldocument_leasesdelete (warn-only on failure).reindex: sweepspublisheditems of the type in batches of 10, callingkbIngesteach — sequential ingest would exceed the function budget.publish: admin-data PATCH setsstatus: 'published'(permissions, audit, triggers run), thenkbIngestruns immediately in the same request.search: onecallOpenAIEmbeddingscall for the query embedding plusmatch_embeddingsRPC per requested vector type.
Errors
| Condition | Error |
|---|---|
| Missing inputs | id is required · type_slug is required · query is required |
| Unknown record | record not found |
| Unknown type | type not found: <type_slug> |
| Bad action | unknown kb action: <action> |
| RPC/insert failures | thrown — the lease is released with failed status |
Agent notes
- Ingest outcomes are tri-state.
in_progress: truemeans another worker owns this content's embed — callers that stamp embedding state on the record must not write success or failure; the owning worker's completion reconciles the corpus. A fenced lease release (superseded mid-flight) warns without throwing. - Search is deny-by-default. No
config.knowledgeenvelope on the app →knowledge_denied. The envelope declaresaccount(self, orself_and_descendantsviaget_accessible_accounts),platform(spine-system account, ownsourcesallowlist), and project-scoped code chunks — the last only when an explicit project id list survives the envelope∩pick intersection. When the app declaresrequired_roles, the principal must hold one (system_admin bypasses). document_idis polymorphic. Regular records keyembeddingsby their items UUID; code-chunk vectors key it by astable_idstring —kbSearchsplits theitemslookup (idvsdata->>stable_id) to handle both.- Pipelines don't call this endpoint. The
kb_ingest/kb_revokestage handlers lazy-importkbIngest/kbRevokedirectly and resolveitem_idfrom trigger data;search_knowledgeuses its own text-search path overembeddings, notkbSearch. adminUpdateis imported lazily to avoid a circular-import deadlock throughpipeline-runner— preserve that pattern if adding admin-data calls.- See AI agents, prompt configs, and embeddings for how these vectors feed agent retrieval.