From d4afc135416840eb4c9e1dccea2fca5b5f44323c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:26:24 +0000 Subject: [PATCH 01/29] feat(spec)!: admit knowledge_source as a governed metadata type (wip: schema, tables, kit) Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../test/metadata-type-schema-gate.test.ts | 2 + .../core/src/package-scoped-resolution.ts | 4 + packages/metadata-core/src/types.ts | 1 + packages/metadata/src/plugin.ts | 1 + packages/objectql/src/engine-top-level.ts | 4 + .../objectql/src/namespace-co-owner-names.ts | 7 +- packages/objectql/src/package-scoped-read.ts | 3 + .../objects/default-permission-sets.test.ts | 16 +- packages/runtime/src/app-plugin.ts | 2 +- packages/spec/src/ai/embedding.zod.ts | 86 ---- packages/spec/src/ai/index.ts | 3 +- .../spec/src/ai/knowledge-document.zod.ts | 26 +- packages/spec/src/ai/knowledge-source.zod.ts | 415 ++++++++++-------- packages/spec/src/api/protocol.zod.ts | 2 + .../spec/src/contracts/knowledge-adapter.ts | 28 +- .../spec/src/contracts/knowledge-service.ts | 32 +- ...wledge-source-content-fields-to-content.ts | 79 ++++ .../entries/19/knowledge-source-id-to-name.ts | 59 +++ .../19/knowledge-source-inert-keys-removed.ts | 90 ++++ packages/spec/src/conversions/registry.ts | 21 + packages/spec/src/identity/eval-user.zod.ts | 5 + .../platform-admin-capabilities.test.ts | 11 + .../src/kernel/collection-item-owner-stamp.ts | 2 +- .../spec/src/kernel/customization-package.ts | 3 + .../spec/src/kernel/metadata-plugin.zod.ts | 10 + .../spec/src/kernel/metadata-type-schemas.ts | 2 + .../manifest-collection-spelling.ts | 1 + .../retired-defs/19.ai__EmbeddingModel.ts | 8 + .../19.ai__FileKnowledgeSource.ts | 7 + .../19.ai__HttpKnowledgeSource.ts | 7 + .../19.ai__KnowledgeSourceKind.ts | 7 + .../retired-defs/19.ai__VectorStore.ts | 7 + .../19.ai__VectorStoreProvider.ts | 6 + .../19.ai__KnowledgeRefreshPolicy__cron.ts | 6 + .../19.ai__KnowledgeSource__adapterConfig.ts | 7 + .../19.ai__KnowledgeSource__embedding.ts | 6 + .../19.ai__KnowledgeSource__id.ts | 7 + .../19.ai__KnowledgeSource__vectorStore.ts | 6 + ...i__ObjectKnowledgeSource__contentFields.ts | 8 + ...9.knowledge-source-content-lists-fields.ts | 36 ++ ...nowledge-source-file-http-kinds-retired.ts | 41 ++ .../19.knowledge-source-inert-keys-retired.ts | 41 ++ .../spec/src/migrations/registry.ts.template | 33 +- packages/spec/src/security/capabilities.ts | 12 + packages/spec/src/stack.zod.ts | 4 + scripts/check-stack-collection-maps.mjs | 8 +- .../src/preview/DraftChangesPanel.tsx | 2 + .../src/views/studio-design/StudioMenu.tsx | 2 + .../studio-design/studioMenuPlacement.test.ts | 2 +- .../studio-design/studioMenuPlacement.ts | 1 + .../widgets/CapabilityMultiSelectField.tsx | 2 + .../fields/src/widgets/useFieldTranslation.ts | 1 + ui/packages/i18n/src/locales/ar.ts | 8 + ui/packages/i18n/src/locales/de.ts | 4 + ui/packages/i18n/src/locales/en.ts | 4 + ui/packages/i18n/src/locales/es.ts | 5 + ui/packages/i18n/src/locales/fr.ts | 5 + ui/packages/i18n/src/locales/ja.ts | 4 + ui/packages/i18n/src/locales/ko.ts | 4 + ui/packages/i18n/src/locales/pt-BR.ts | 5 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 4 + ui/packages/i18n/src/locales/zh-Hant.ts | 4 + 63 files changed, 925 insertions(+), 310 deletions(-) delete mode 100644 packages/spec/src/ai/embedding.zod.ts create mode 100644 packages/spec/src/conversions/entries/19/knowledge-source-content-fields-to-content.ts create mode 100644 packages/spec/src/conversions/entries/19/knowledge-source-id-to-name.ts create mode 100644 packages/spec/src/conversions/entries/19/knowledge-source-inert-keys-removed.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__EmbeddingModel.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__FileKnowledgeSource.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__HttpKnowledgeSource.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__KnowledgeSourceKind.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStore.ts create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStoreProvider.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeRefreshPolicy__cron.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__adapterConfig.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__embedding.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__id.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__vectorStore.ts create mode 100644 packages/spec/src/migrations/entries/retired-keys/19.ai__ObjectKnowledgeSource__contentFields.ts create mode 100644 packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts create mode 100644 packages/spec/src/migrations/entries/semantic/19.knowledge-source-file-http-kinds-retired.ts create mode 100644 packages/spec/src/migrations/entries/semantic/19.knowledge-source-inert-keys-retired.ts diff --git a/packages/cli/test/metadata-type-schema-gate.test.ts b/packages/cli/test/metadata-type-schema-gate.test.ts index 2e2c0ae5be7..67a1a1b7e2a 100644 --- a/packages/cli/test/metadata-type-schema-gate.test.ts +++ b/packages/cli/test/metadata-type-schema-gate.test.ts @@ -110,6 +110,8 @@ const GATED_AT: Readonly> = { skill: 'skills', // [ADR-0160 D1] `ai_context`: CLOSED from its first day, authored at `aiContexts:`. ai_context: 'aiContexts', + // [ADR-0161 K4] `knowledge_source`: strict from the release that admits the type, authored at `knowledgeSources:`. + knowledge_source: 'knowledgeSources', // [#5384] `api` GRADUATED here from NOT_YET_CLOSED — the deliberate ratchet // step this file's own note asked for. `ApiEndpointSchema` is `strictObject` // as of #5384, so the stack's `apis:` array and the registry schema now reject diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index be6b6d717b4..2517e2f4731 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -272,6 +272,10 @@ export const PACKAGE_SCOPED_TYPES = Object.freeze([ // [ADR-0150 addendum 2026-11-25] the context pack joins bucket 3 beside // `skill`: `get_record_context` resolves a bare pack name by this rule. 'ai_context', + // [ADR-0150 addendum 2026-11-25, D3] the knowledge source joins bucket 3: + // `search_knowledge` and the knowledge service resolve a bare source name + // by this rule. + 'knowledge_source', ] as const); /** A type addressed by `(package, name)` ({@link PACKAGE_SCOPED_TYPES}). */ diff --git a/packages/metadata-core/src/types.ts b/packages/metadata-core/src/types.ts index 84526f59b6c..6ba7ece4a9d 100644 --- a/packages/metadata-core/src/types.ts +++ b/packages/metadata-core/src/types.ts @@ -37,6 +37,7 @@ export const MetadataTypeSchema = z.enum([ 'tool', 'skill', 'ai_context', + 'knowledge_source', 'report', 'translation', 'role', diff --git a/packages/metadata/src/plugin.ts b/packages/metadata/src/plugin.ts index 2ed3bb25088..a8293fd21a5 100644 --- a/packages/metadata/src/plugin.ts +++ b/packages/metadata/src/plugin.ts @@ -197,6 +197,7 @@ const ARTIFACT_FIELD_TO_TYPE: Record = { tools: 'tool', skills: 'skill', aiContexts: 'ai_context', + knowledgeSources: 'knowledge_source', // `ragPipelines: 'rag_pipeline'` removed (ADR-0049 enforce-or-remove), the // fourth retirement of the `policies` shape: the stack schema declares no // `ragPipelines` key, so the strict parse below refuses a definition that diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 51660e8dd0f..41f0231720d 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4568,6 +4568,10 @@ const METADATA_ARRAY_KEYS = [ // [ADR-0160 D1] Context packs — read by the record-context service from // the registry, so a declaration lands here with its package stamped. 'aiContexts', + // [ADR-0161 K4] Knowledge sources — the knowledge service's loader reads + // them back with the package that ships each one stamped, which is the + // coordinate its registry and index keys carry (ADR-0150 D4). + 'knowledgeSources', // API Protocol 'apis', // Data Extensions diff --git a/packages/objectql/src/namespace-co-owner-names.ts b/packages/objectql/src/namespace-co-owner-names.ts index e2f5aa8f40c..330358e9b3c 100644 --- a/packages/objectql/src/namespace-co-owner-names.ts +++ b/packages/objectql/src/namespace-co-owner-names.ts @@ -91,7 +91,8 @@ export type NamespaceUniqueType = | 'hook' | 'job' | 'app' | 'page' | 'dashboard' | 'report' | 'book' | 'analytics_cube' | 'tool' - | 'ai_context'; + | 'ai_context' + | 'knowledge_source'; /** * The covered types, in the order a refusal lists them — ADR-0150's @@ -113,6 +114,10 @@ export const NAMESPACE_UNIQUE_TYPES: readonly NamespaceUniqueType[] = Object.fre 'tool', // [ADR-0150 addendum 2026-11-25, point 3] admitted by the maintainer's merge. 'ai_context', + // [ADR-0150 addendum 2026-11-25 (`knowledge_source`), point 1] admitted by the + // maintainer's merge of that addendum: one holder of a source name inside a + // namespace, so `NS-NAME` names one source. + 'knowledge_source', ]); /** Is `type` one of the covered types? */ diff --git a/packages/objectql/src/package-scoped-read.ts b/packages/objectql/src/package-scoped-read.ts index eab700cd297..2b61b5e3d20 100644 --- a/packages/objectql/src/package-scoped-read.ts +++ b/packages/objectql/src/package-scoped-read.ts @@ -124,6 +124,9 @@ export const PACKAGE_SCOPED_READ_TYPES = Object.freeze([ // [ADR-0150 addendum 2026-11-25, reader 3] `/meta/ai_context/NAME` and its // `?package=` qualifier: a bare pack name two packages hold is refused. 'ai_context', + // [ADR-0150 addendum 2026-11-25, reader 5] `/meta/knowledge_source/NAME` and + // its `?package=` qualifier: a bare source name two packages hold is refused. + 'knowledge_source', ] as const); /** A type whose by-name readers consult `(package, name)` ({@link PACKAGE_SCOPED_READ_TYPES}). */ diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.test.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.test.ts index 49116348548..13003ddc36a 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.test.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.test.ts @@ -422,7 +422,9 @@ describe('member_default lets a member react to comments; external_default does * capability by default). And `manage_connector_connections` (ADR-0143 D5 — * platform administrators hold the connector connection capability by default; * so do both organization-administrator sets since ruling B, record - * 6545223261, pinned below). And `viewAllFields` on the wildcard (the + * 6545223261, pinned below). And `manage_knowledge_sources` (ADR-0161 K4, + * ruling Q2 = B on #37304 — platform administrators hold the knowledge source + * capability by default and no other shipped set does, pinned below). And `viewAllFields` on the wildcard (the * field-axis split, ruling of record 6912661484, letter A): the read-only * "every field" vote, which duplicates the field vote the two record bits * already cast, so no answer changes; the no-behaviour-change pin is in @@ -464,6 +466,8 @@ describe('admin_full_access imports the kernel capability declaration unchanged 'manage_mailboxes', // added on purpose (ADR-0143 D5) — see the docblock above. 'manage_connector_connections', + // added on purpose (ADR-0161 K4) — see the docblock above. + 'manage_knowledge_sources', ], // [#21237] added on purpose — see the docblock above. The group is read off // the identity object's declaration, never listed here. @@ -499,6 +503,16 @@ describe('admin_full_access imports the kernel capability declaration unchanged } }); + it('[ADR-0161 K4] the knowledge source capability ships with the platform administrator and no other set', () => { + // Ruling Q2 = B on #37304: saving a knowledge source starts an egress and + // a bill, so the organization administrator holds it only by an explicit + // grant, unlike the connector connection capability above. + const holders = (defaultPermissionSets as any[]) + .filter((s) => (s.systemPermissions ?? []).includes('manage_knowledge_sources')) + .map((s) => s.name); + expect(holders).toEqual(['admin_full_access']); + }); + it('[ADR-0143 D5] the wall-less organization administrator inherits the capability through the derivation, not a second literal', () => { // `deriveWallLessOrgAdmin` copies the parent's system permissions // verbatim; the two lists are one list, so the grant reaches both diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 08013432c3e..0f29e9751c1 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -521,7 +521,7 @@ export class AppPlugin implements Plugin { // wrappers and don't count. const APP_CATEGORY_KEYS = [ 'objects', 'views', 'apps', 'pages', 'dashboards', 'reports', - 'flows', 'workflows', 'triggers', 'agents', 'tools', 'skills', 'aiContexts', + 'flows', 'workflows', 'triggers', 'agents', 'tools', 'skills', 'aiContexts', 'knowledgeSources', 'actions', 'permissions', 'positions', 'translations', 'sharingRules', 'data', 'emailTemplates', 'docs', 'books', diff --git a/packages/spec/src/ai/embedding.zod.ts b/packages/spec/src/ai/embedding.zod.ts deleted file mode 100644 index 93768d94244..00000000000 --- a/packages/spec/src/ai/embedding.zod.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -import { z } from 'zod'; -import { lazySchema } from '../shared/lazy-schema'; - -/** - * Embedding & Vector Store Primitives - * - * Platform contract for configuring embedding models and vector stores. - * - * Scope (intentionally minimal): - * - How to reference an embedding model (provider + model name + secret). - * - How to reference a vector store (provider + connection). - * - * NOT in scope (these belong to application code, not the platform): - * - Chunking strategies (fixed/semantic/recursive/markdown). - * - Retrieval pipelines (rerankers, multi-stage retrieval, filters). - * - Document loaders / ingestion DSLs. - * - End-to-end RAG pipeline orchestration. - * - * These were removed in v1 because they describe one specific way to - * build a RAG application; the platform's job is to expose the embed + - * vector primitives so any RAG strategy can be built on top. - */ - -/** - * Supported vector store providers. - * - * `custom` is the escape hatch for self-hosted or unlisted backends — - * the actual connection details live in driver-specific config. - */ -export const VectorStoreProviderSchema = lazySchema(() => z.enum([ - 'pgvector', - 'chroma', - 'qdrant', - 'pinecone', - 'weaviate', - 'milvus', - 'redis', - 'opensearch', - 'elasticsearch', - 'custom', -])); - -/** - * Embedding model reference. - * - * The platform uses this to look up an embedding adapter at runtime. - * Credentials are *referenced* (via `secretRef`) rather than inlined - * so metadata can be safely persisted. - */ -export const EmbeddingModelSchema = lazySchema(() => z.object({ - /** Provider identifier (e.g. `openai`, `cohere`, `local`). */ - provider: z.enum(['openai', 'cohere', 'azure_openai', 'huggingface', 'local', 'custom']), - /** Model identifier as understood by the provider (e.g. `text-embedding-3-large`). */ - model: z.string().describe('Provider-specific model identifier'), - /** Output vector dimensions — required so vector-store DDL can pre-size columns. */ - dimensions: z.number().int().positive().describe('Embedding vector dimensions'), - /** Optional custom endpoint (for self-hosted / proxied providers). */ - endpoint: z.string().url().optional().describe('Custom endpoint URL'), - /** Reference to a stored secret (preferred over inlining `apiKey`). */ - secretRef: z.string().optional().describe('Reference to stored API key secret'), -})); - -/** - * Vector store connection reference. - * - * Plugins / drivers implement the actual upsert / search calls; this - * schema only captures *which* store and *how to reach it*. - */ -export const VectorStoreSchema = lazySchema(() => z.object({ - /** Backing provider. */ - provider: VectorStoreProviderSchema, - /** Logical collection / index / namespace name. */ - collection: z.string().describe('Collection / index / namespace name'), - /** Optional connection string or endpoint. */ - endpoint: z.string().optional().describe('Connection string or endpoint URL'), - /** Reference to stored credentials. */ - secretRef: z.string().optional().describe('Reference to stored credential secret'), - /** Dimensions of vectors in this store (must match the embedding model). */ - dimensions: z.number().int().positive().optional(), -})); - -export type VectorStoreProvider = z.input; -export type EmbeddingModel = z.input; -export type VectorStore = z.input; diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts index 18c4594c3b3..6f920382956 100644 --- a/packages/spec/src/ai/index.ts +++ b/packages/spec/src/ai/index.ts @@ -16,7 +16,7 @@ * - Tool — Zod-typed callable surface * - Conversation — message persistence + short/long-term memory * - Model Registry — multi-provider LLM configuration - * - Embedding — embedding model + vector store references + * - Knowledge source — the `knowledge_source` kind the knowledge service indexes from (ADR-0161 K4) * - Usage — token accounting + per-call cost * - MCP — references and bindings to external MCP servers * - AI face name — the derived flat name an item is listed under (ADR-0150 D6) @@ -36,7 +36,6 @@ export { skillForm } from './skill.form'; export { aiContextForm } from './ai-context.form'; export * from './conversation.zod'; export * from './model-registry.zod'; -export * from './embedding.zod'; export * from './usage.zod'; export * from './mcp.zod'; export * from './face-name'; diff --git a/packages/spec/src/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index 4a5ba3cb82d..f2b46f9f400 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -68,15 +68,18 @@ export const KnowledgeChunkSchema = lazySchema(() => z.object({ /** * One logical document submitted to an adapter for indexing. * - * For `object` sources, one ObjectQL record produces exactly one - * document. For `file` / `http` sources, the adapter is free to split - * a single file into many documents if that's the natural unit. + * One ObjectQL record of the object a source names produces exactly one + * document, and the knowledge service assembles it (ADR-0161 K1): no caller + * hands the service a document. */ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ /** Globally-unique document id. Snake / kebab-safe. */ id: z.string().describe('Document id'), - /** Logical source this document belongs to. */ - sourceId: z.string().describe('Owning KnowledgeSource id'), + /** + * The source this document belongs to: its index key, the string the + * adapter is handed as `AdapterContext.source.name`. + */ + sourceId: z.string().describe('Index key of the owning knowledge source'), /** * Underlying ObjectQL record id when the source kind is `object`. * Powers permission-aware retrieval: hits referencing a record are @@ -102,9 +105,8 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ * The organization the document belongs to (ADR-0161 K8, item 9). Set by the * knowledge service when it assembles a document from a record: the * record's `organization_id`, under a walled tenancy posture (`group` or - * `isolated`, ADR-0105 D1). Absent for `file` / `http` sources, under the - * `single` posture, and for a record that carries no organization; a - * caller-supplied value is refused by `indexDocument`. Stored by the adapter + * `isolated`, ADR-0105 D1). Absent under the + * `single` posture and for a record that carries no organization. Stored by the adapter * and read by its search: when the search is handed * `AdapterSearchOptions.organizationIds`, only documents whose organization * is in that set are ranked, so a document without one is not. An adapter @@ -118,8 +120,7 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ * A hash of the assembled document — its content, title and metadata, and its * `organizationId` when it has one, in a stable key order, behind a version * prefix (ADR-0161 K8, item 2). Set by - * the knowledge service on every document it hands an adapter; a - * caller-supplied value is refused by `indexDocument`. Stored by the adapter + * the knowledge service on every document it hands an adapter. Stored by the adapter * and returned as stored by `listDocuments`; an unchanged hash lets a * complete reindex skip writing the document again. Adapters never compute * or alter it. @@ -129,9 +130,8 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ /** * The document's passages, cut by the knowledge service's splitter * (ADR-0161 K8, item 5). Set by the service, and only on a document handed - * to an adapter that declares `capabilities.chunks`; a caller-supplied value - * is refused by `indexDocument`. Derived from `content`, so it is not part - * of `docHash`. An adapter that receives it indexes these passages as given. + * to an adapter that declares `capabilities.chunks`. Derived from `content`, + * so it is not part of `docHash`. An adapter that receives it indexes these passages as given. */ chunks: z.array(KnowledgeChunkSchema).optional() .describe('Service-cut passages of the document, handed to an adapter that declares capabilities.chunks'), diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index d5f4538e48c..ae2995a49c7 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -1,59 +1,67 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { z } from 'zod'; -import { CronExpressionInputSchema } from '../shared/expression.zod'; +import { ROUTER_ADDRESSABLE_NAME_MESSAGE, ROUTER_ADDRESSABLE_NAME_PATTERN } from '../kernel/address-grammar'; +import { MetadataProtectionFields } from '../kernel/metadata-protection.zod'; import { lazySchema } from '../shared/lazy-schema'; -import { EmbeddingModelSchema, VectorStoreSchema } from './embedding.zod'; +import { enumWithRetiredValues, retiredKey } from '../shared/retired-key'; +import { strictObject } from '../shared/strict-object'; /** - * Knowledge Source — declarative metadata describing what to index and - * which adapter to use. + * Knowledge Source — the governed metadata type `knowledge_source` + * (ADR-0161 K4): what the knowledge service indexes, from which object, and + * through which adapter. * - * A KnowledgeSource is the metadata-level equivalent of an - * `IDataEngine` driver binding: it pairs a logical source description - * (object/file/http) with the *id* of an `IKnowledgeAdapter` plugin - * that will actually do the work. The adapter resolves the id at - * runtime via `IKnowledgeService.registerAdapter`. + * One schema for every door (ADR-0005, ADR-0161 K4 point 3): a + * `*.knowledge-source.ts` file in a package, a save through Studio or MCP, + * and a registration in code all parse with {@link KnowledgeSourceSchema}. * - * See `content/docs/protocol/knowledge.mdx` for the full design. + * See `content/docs/protocol/knowledge.mdx` for the design. */ +/** What silently happened to an undeclared key before the shapes below were closed. */ +const DROPPED_BEFORE_19 = + 'Before @objectstack/spec 19 the parse dropped a key this shape does not declare, so it changed nothing.'; + +/** The sentence every tombstone below ends with (`shared/retired-key-migrate-sentence.test.ts` pins its shape). */ +const MIGRATE_18 = + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand.'; + +/** + * The prescription for `source.kind: 'file'` and `'http'`, and for the four + * keys those two arms carried (ADR-0161 K4, point 1): the arms had no reader. + */ +const NON_OBJECT_ARM_RETIRED = + 'The `file` and `http` shapes of `knowledge_source.source` were removed in @objectstack/spec 19.0.0 (ADR-0161 K4) — ' + + 'nothing read `prefix`, `mimeTypes`, `urls` or `userAgent`: such a source was never ingested by the platform, ' + + 'and its hits skipped the permission re-read. A knowledge source indexes the records of one object: write ' + + '`source: { kind: \'object\', object, content }`. A corpus that lives outside the platform has no form in this ' + + 'version; it returns as a designed arm with the adapter that parses it. ' + + 'This edit left `os migrate meta` with no rewrite: the two shapes have no mapping, so the source is rewritten by hand.'; + /** Refresh strategies for a knowledge source. */ -export const KnowledgeRefreshPolicySchema = lazySchema(() => z.object({ - /** - * Subscribe to ObjectQL `record.*` events for `object` sources. - * Defaults to `true` for object sources; ignored for file/http. - */ - onRecordChange: z.boolean().default(true).optional(), - /** - * Cron-dialect expression for a periodic full reindex. Optional. - * - * `CronExpressionInputSchema` — the shared cron-dialect input the other - * cron-shaped fields carry (`api/export.zod.ts`, `automation/execution.zod.ts`, - * `integration/connector.zod.ts`). A bare string is shorthand for - * `{ dialect: 'cron', source }`; the parse enforces a non-empty string or an - * expression envelope and normalizes to the envelope. It does NOT judge cron - * syntax, and neither does anything downstream: this slot is parsed and - * reaches no engine. `croner` judges a cron pattern only where a schedule is - * wired (`CronSchedule.expression`, a different slot), and - * `@objectstack/formula`'s registered `cron` engine has no caller outside - * that package — so the syntax verdict belongs to whatever external - * scheduler the author hands this value to, and the describe below promises - * exactly what the parse enforces (ADR-0049 declared = enforced; #14825). - * - * `service-knowledge` does not schedule the cron itself — it merely - * surfaces the value so an automation flow / external scheduler can - * trigger `reindexSource`. - */ - cron: CronExpressionInputSchema.optional().describe( - 'Cron-dialect expression for a periodic full reindex. A bare string is shorthand for ' - + '`{ dialect: \'cron\', source }`; the parse enforces a non-empty string or an expression ' - + 'envelope and normalizes to the envelope — cron syntax is not checked here, and no engine ' - + 'evaluates this slot: the verdict belongs to whatever external scheduler you hand the value to. ' - + '`service-knowledge` does not schedule it: the value is surfaced so an automation flow / ' - + 'external scheduler can trigger `reindexSource`.', - ), -})); +export const KnowledgeRefreshPolicySchema = lazySchema(() => strictObject( + { surface: 'this refresh policy', history: DROPPED_BEFORE_19 }, + { + /** + * Keep the index in step with record events (insert, update, delete) and + * guard hard deletes. `false` hands the index to an external indexer: + * the service neither syncs nor builds the source. + */ + onRecordChange: z.boolean().default(true).optional() + .describe('Sync the index from record events (default true); false leaves the index to an external indexer'), + /** + * [ADR-0161 K6] Retired: the slot was parsed and reached no engine. + */ + cron: retiredKey( + '`knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. ' + + 'To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between ' + + 'events is the service\'s reconcile pass. ' + + MIGRATE_18, + ), + }, +)); /** The split strategies of the knowledge service's splitter (ADR-0161 K8, item 10). */ export const KnowledgeSplitStrategySchema = lazySchema(() => z.enum(['whole', 'recursive', 'markdown'])); @@ -79,139 +87,201 @@ export const KnowledgeSplitStrategySchema = lazySchema(() => z.enum(['whole', 'r * page's `knowledge.chunk_target`, or 800) and what fits in 80% of the * embedder's input limit by the shared token estimate. */ -export const KnowledgeSplitSchema = lazySchema(() => z.object({ - /** Which splitter strategy cuts the documents. */ - strategy: KnowledgeSplitStrategySchema.describe('Split strategy: whole, recursive or markdown'), - /** - * Longest passage, in characters. Wins over the settings page's - * `knowledge.chunk_target`; the embedder's input limit can lower it. - * Not read by `whole`. - */ - maxChars: z.number().int().positive().optional() - .describe('Longest passage in characters; wins over the settings default, the embedder limit can lower it'), - /** - * Adjacent pieces shorter than this are merged, up to this length - * (`recursive` and `markdown`). A value above the effective `maxChars` - * reads as `maxChars`. @default 200 - */ - minChars: z.number().int().nonnegative().optional() - .describe('Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars'), -})); - -/** Source backed by an ObjectQL object — each record becomes a document. */ -export const ObjectKnowledgeSourceSchema = lazySchema(() => z.object({ - kind: z.literal('object'), - /** Short object name (e.g. `task`, `kb_article`). */ - object: z.string().describe('Short object name to index'), - /** - * Fields to concatenate into the document body (in order). - * `*` means "use every readable text field" (adapter / service decides). - */ - contentFields: z.array(z.string()).min(1).describe('Fields contributing to document content'), - /** - * Extra fields to project into `metadata` for filtering at search - * time (e.g. `status`, `owner_id`, `tags`). - */ - metadataFields: z.array(z.string()).default([]).optional(), - /** - * Optional filter restricting which records are indexed. - * Uses ObjectQL `where` syntax. - */ - where: z.record(z.string(), z.unknown()).optional(), - /** - * How the knowledge service cuts this object's documents into passages - * ({@link KnowledgeSplitSchema}). Omitted ⇒ `recursive` with the settings - * page's `knowledge.chunk_target` (or 800) as `maxChars`. - */ - split: KnowledgeSplitSchema.optional() - .describe('How the service cuts this object\'s documents into passages; omitted means recursive'), -})); - -/** Source backed by a folder in `IStorageService`. */ -export const FileKnowledgeSourceSchema = lazySchema(() => z.object({ - kind: z.literal('file'), - /** Storage prefix to scan (e.g. `kb/handbooks/`). */ - prefix: z.string().describe('Storage prefix'), - /** Optional MIME-type allow-list. Empty = all types. */ - mimeTypes: z.array(z.string()).default([]).optional(), -})); +export const KnowledgeSplitSchema = lazySchema(() => strictObject( + { surface: 'this split', history: DROPPED_BEFORE_19 }, + { + /** Which splitter strategy cuts the documents. */ + strategy: KnowledgeSplitStrategySchema.describe('Split strategy: whole, recursive or markdown'), + /** + * Longest passage, in characters. Wins over the settings page's + * `knowledge.chunk_target`; the embedder's input limit can lower it. + * Not read by `whole`. + */ + maxChars: z.number().int().positive().optional() + .describe('Longest passage in characters; wins over the settings default, the embedder limit can lower it'), + /** + * Adjacent pieces shorter than this are merged, up to this length + * (`recursive` and `markdown`). A value above the effective `maxChars` + * reads as `maxChars`. @default 200 + */ + minChars: z.number().int().nonnegative().optional() + .describe('Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars'), + }, +)); -/** Source backed by a list of remote URLs. */ -export const HttpKnowledgeSourceSchema = lazySchema(() => z.object({ - kind: z.literal('http'), - /** URLs to fetch. */ - urls: z.array(z.string().url()).min(1), - /** Optional User-Agent header. */ - userAgent: z.string().optional(), -})); - -export const KnowledgeSourceKindSchema = lazySchema(() => z.discriminatedUnion('kind', [ - ObjectKnowledgeSourceSchema, - FileKnowledgeSourceSchema, - HttpKnowledgeSourceSchema, -])); +/** + * What a source indexes: the records of one object (ADR-0161 K4, "Referencing + * objects"). `kind` keeps one arm; the `file` and `http` arms retired with + * their four keys (K4, point 1). + */ +export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( + { + surface: 'this knowledge source\'s `source`', + history: DROPPED_BEFORE_19, + aliases: { fields: 'content', objectName: 'object', filter: 'where', metadata: 'metadataFields' }, + guidance: { + prefix: NON_OBJECT_ARM_RETIRED, + mimeTypes: NON_OBJECT_ARM_RETIRED, + urls: NON_OBJECT_ARM_RETIRED, + userAgent: NON_OBJECT_ARM_RETIRED, + }, + }, + { + kind: enumWithRetiredValues(['object'], { file: NON_OBJECT_ARM_RETIRED, http: NON_OBJECT_ARM_RETIRED }) + .describe('What the source indexes; `object` is the one kind'), + /** Short object name (e.g. `task`, `kb_article`). */ + object: z.string().describe('Short object name to index'), + /** + * The fields whose text becomes the document body, in order (ADR-0161 K5). + * + * Embedding is egress: the text of every field listed here is sent to the + * embedder and kept in an index outside the row store. So the list is + * explicit — `'*'` is refused — and a field added to the object later does + * not leave until an author adds it here. Credential-class and `internal` + * fields are never indexed, even when named. + */ + content: z.array( + z.string().refine((field) => field !== '*', { + message: + '`knowledge_source.source.content` lists field names: the `\'*\'` member was removed in @objectstack/spec ' + + '19.0.0 (ADR-0161 K5) — embedding is egress, and `\'*\'` sent every text field of the record to the ' + + 'embedder, including one added to the object later. List the fields whose text should be indexed, ' + + 'for example `content: [\'title\', \'body\']`. ' + + 'Run `os migrate meta --from 18` to list the mechanical edits for the renamed-key case; `--write` applies the ones it can prove, and reports a wildcard member for you to replace by hand.', + }), + ).min(1).describe('Fields whose text is indexed, in order; every name is listed (no wildcard)'), + /** + * [ADR-0161 K6] Retired spelling of {@link content}. + */ + contentFields: retiredKey( + '`knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'the key is spelled `content` now that a source is a metadata item; use `content`. ' + + 'Rename the key; the value (a list of field names) is unchanged, except that a `\'*\'` member is no longer ' + + 'accepted and is replaced by the field names it stood for. ' + + MIGRATE_18, + ), + /** + * Extra fields to project into `metadata` for filtering at search + * time (e.g. `status`, `owner_id`, `tags`). + */ + metadataFields: z.array(z.string()).default([]).optional(), + /** + * Optional filter restricting which records are indexed. + * Uses ObjectQL `where` syntax. + */ + where: z.record(z.string(), z.unknown()).optional(), + /** + * How the knowledge service cuts this object's documents into passages + * ({@link KnowledgeSplitSchema}). Omitted ⇒ `recursive` with the settings + * page's `knowledge.chunk_target` (or 800) as `maxChars`. + */ + split: KnowledgeSplitSchema.optional() + .describe('How the service cuts this object\'s documents into passages; omitted means recursive'), + }, +)); /** - * Canonical KnowledgeSource — the shape of a **runtime registration**, - * ⛔ not a governed metadata type. + * Canonical KnowledgeSource — the one schema of the governed metadata type + * `knowledge_source` (ADR-0161 K4; ADR-0088's three clauses are answered + * there). + * + * A source is an item with a lifecycle of its own: it ships in a package as a + * `*.knowledge-source.ts` (or `.yml`) file under the stack's + * `knowledgeSources` collection, and it is created or changed at run time + * through Studio and MCP. The knowledge service reads the published items, + * registers each one, builds and syncs its index, and reloads it when it + * changes; removing the item drops its index. It takes no environment overlay + * (ADR-0005). + * + * A source is identified by its package and its `name` (ADR-0150, addendum of + * 2026-11-25): two packages may each ship a source of one name. Where the + * name crosses the AI face — `search_knowledge`'s `sources` list and its + * `sourceIds` argument — a package's source is spelled `NAMESPACE-NAME` and an + * environment source keeps its bare name. + * + * Registration in code (`KnowledgeServicePlugin({ sources })`, + * `IKnowledgeService.registerSource`) stays a door for this same schema and + * parses with it. * - * It is not stored as metadata, not versioned and not - * environment-scoped: no knowledge-shaped entry exists in the governed - * metadata-type registry (`listMetadataTypeSchemaTypes()`), and - * `ObjectStackDefinitionSchema` carries no collection for it — so - * `defineStack({ knowledgeSources: [...] })` is refused as an - * unrecognized top-level key. `view`, `flow`, `skill`, `agent` and - * `tool` are the types that do work that way; this one does not. + * Authoring a source is an egress decision: its listed fields are sent to the + * embedding provider on the first build. Creating or changing one at run time + * needs the `manage_knowledge_sources` capability beside `manage_metadata`. * - * A source reaches the runtime through code, for the life of the - * process: `KnowledgeServicePlugin({ sources: [...] })` at kernel - * wiring, or `IKnowledgeService.registerSource(source)` afterwards; - * `listSources()` / `getSource()` read that in-memory registry back. - * Retrieval is restricted at the knowledge-service/source level — - * `search_knowledge` takes `sourceIds` — and an agent describes its - * grounding in `instructions`. + * Every key below has a reader; an undeclared key is refused, never dropped. */ -export const KnowledgeSourceSchema = lazySchema(() => z.object({ - /** Stable identifier. Snake_case. */ - id: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Snake_case source id'), - /** Human-readable label. */ - label: z.string(), - /** Optional description. */ - description: z.string().optional(), - /** - * Adapter id this source binds to (e.g. `'pgvector'`, `'memory'`). - * Resolved at runtime by `IKnowledgeService.registerAdapter`. - */ - adapter: z.string().describe('Adapter id'), - /** Adapter-specific configuration (opaque to the service). */ - adapterConfig: z.record(z.string(), z.unknown()).default({}).optional(), - /** What gets indexed. */ - source: KnowledgeSourceKindSchema, - /** - * Optional embedding model reference. Adapters that manage - * embeddings internally (Dify, Vectara) may ignore this. - */ - embedding: EmbeddingModelSchema.optional(), - /** - * Optional vector store reference. Same caveat as `embedding` — many - * adapters own their own backend. - */ - vectorStore: VectorStoreSchema.optional(), - /** - * Refresh / sync configuration. Omitted ⇒ parses to `{}` — the runtime - * default, stated here in words because the published input-shape JSON - * Schema cannot carry it beside `cron`'s transform (#14825). - */ - refresh: KnowledgeRefreshPolicySchema.default({}).optional().describe( - 'Refresh / sync configuration; omitted parses to `{}` (the runtime default — the published ' - + "input-shape JSON Schema cannot state it beside `cron`'s transform).", - ), - /** Whether `search_knowledge` may expose this source to AI agents. */ - aiExposed: z.boolean().default(true).optional(), -})); +export const KnowledgeSourceSchema = lazySchema(() => strictObject( + { + surface: 'this knowledge source', + history: DROPPED_BEFORE_19, + aliases: { title: 'label', object: 'source', exposed: 'aiExposed' }, + }, + { + /** + * The source's machine name. With the package that ships it, it + * identifies the source; it is also what its index is keyed by. + */ + name: z.string().regex(ROUTER_ADDRESSABLE_NAME_PATTERN, { message: ROUTER_ADDRESSABLE_NAME_MESSAGE }) + .describe('Source machine name (snake_case) — what search_knowledge lists and its sourceIds argument names'), + /** + * [ADR-0161 K6] Retired spelling of {@link name}. + */ + id: retiredKey( + '`knowledge_source.id` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'a knowledge source is a metadata item, and an item is identified by `name`; use `name`. ' + + 'Rename the key; the value is unchanged, so the source\'s index is found again and is not rebuilt. ' + + MIGRATE_18, + ), + /** Human-readable label. */ + label: z.string(), + /** Optional description. */ + description: z.string().optional(), + /** + * Adapter id this source binds to (e.g. `'pgvector'`, `'memory'`). + * Resolved at runtime by `IKnowledgeService.registerAdapter`. + */ + adapter: z.string().describe('Adapter id'), + /** + * [ADR-0161 K4, K6] Retired: no adapter reads per-source configuration. + */ + adapterConfig: retiredKey( + '`knowledge_source.adapterConfig` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'no adapter read it: its one reader was the retired RAGFlow adapter. Delete the key. ' + + 'An adapter takes its settings as options of the plugin that mounts it. ' + + MIGRATE_18, + ), + /** What gets indexed. */ + source: ObjectKnowledgeSourceSchema, + /** + * [ADR-0161 K6] Retired: never read. + */ + embedding: retiredKey( + '`knowledge_source.embedding` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'it was never read: no service and no adapter chose a model from it. Delete the key. ' + + 'The embedder is configured once for the deployment, and every source is embedded by it. ' + + MIGRATE_18, + ), + /** + * [ADR-0161 K6] Retired: never read. + */ + vectorStore: retiredKey( + '`knowledge_source.vectorStore` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — ' + + 'it was never read: no service and no adapter chose a store from it. Delete the key. ' + + 'The store is the adapter the deployment installs, named by `adapter`. ' + + MIGRATE_18, + ), + /** + * Refresh / sync configuration. Omitted ⇒ parses to `{}`. + */ + refresh: KnowledgeRefreshPolicySchema.default({}).optional() + .describe('Refresh / sync configuration; omitted parses to `{}`'), + /** Whether `search_knowledge` may expose this source to AI agents. */ + aiExposed: z.boolean().default(true).optional(), + ...MetadataProtectionFields, + }, +)); export type KnowledgeRefreshPolicy = z.input; -/** Post-parse shape of {@link KnowledgeRefreshPolicy} — defaults applied, transforms run (ADR-0122): `cron` is the `{ dialect: 'cron', source }` envelope. */ +/** Post-parse shape of {@link KnowledgeRefreshPolicy} — defaults applied (ADR-0122). */ export type KnowledgeRefreshPolicyParsed = z.infer; export type KnowledgeSplitStrategy = z.input; /** Post-parse shape of {@link KnowledgeSplitStrategy} (ADR-0122). */ @@ -220,9 +290,6 @@ export type KnowledgeSplit = z.input; /** Post-parse shape of {@link KnowledgeSplit} (ADR-0122). */ export type KnowledgeSplitParsed = z.infer; export type ObjectKnowledgeSource = z.input; -export type FileKnowledgeSource = z.input; -export type HttpKnowledgeSource = z.input; -export type KnowledgeSourceKind = z.input; export type KnowledgeSource = z.input; -/** Post-parse shape of {@link KnowledgeSource} — defaults applied, transforms run (ADR-0122): `refresh.cron` is the cron envelope. */ +/** Post-parse shape of {@link KnowledgeSource} — defaults applied (ADR-0122). */ export type KnowledgeSourceParsed = z.infer; diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 1c68b3370e1..8553878339b 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2786,6 +2786,8 @@ export const PACKAGE_SLOTTED_METADATA_TYPES: readonly string[] = Object.freeze([ 'webhook', 'tool', 'connector', // [ADR-0150 addendum 2026-11-25] the context pack, one slot per (package, name). 'ai_context', + // [ADR-0150 addendum 2026-11-25] the knowledge source, one slot per (package, name). + 'knowledge_source', ]); /** diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index de1492ba120..4728cd8b136 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -31,7 +31,17 @@ import type { KnowledgeSource } from '../ai/knowledge-source.zod'; * forwards-compatible. */ export interface AdapterContext { - /** The source these documents belong to. */ + /** + * The source these documents belong to, as the service hands it over. + * + * `source.name` is the source's **index key**: the one string an adapter + * keys everything it holds for the source by, and the string + * `KnowledgeDocument.sourceId` carries. For a source no package holds it is + * the name as authored. For a source a package ships it also carries that + * package (ADR-0150 D4), spelled by the service, so two packages' sources of + * one name are two keys. An adapter never derives the key, parses it or + * shows it to a person; it stores and compares it. + */ source: KnowledgeSource; /** Trace id for correlation across logs / metrics. */ traceId?: string; @@ -142,7 +152,7 @@ export interface AdapterSearchOptions { * holds a membership in. * * - **Absent** (`undefined`): no organization filter — the `single` posture, - * the system identity, a `file` / `http` source, an object outside + * the system identity, an object outside * tenancy. Rank every document of the source, as before this member. * - **Present**: rank only the documents whose * `KnowledgeDocument.organizationId` is in the set, and filter BEFORE @@ -369,6 +379,20 @@ export interface IKnowledgeAdapter { */ completeBuild?(ctx: AdapterContext): Promise; + /** + * Remove everything the adapter holds for `ctx.source` (ADR-0161 K8, + * item 4): every document, passage and vector of every generation, the one + * under construction included, and whatever it recorded about the index. + * After it `indexStatus` answers as for a source it has never seen, and a + * source registered again under the same key is built from nothing. + * + * The service calls it when a source stops being served: its metadata item + * was removed, or a package now holds its name. Calling it for a source the + * adapter holds nothing for is not an error. An adapter without it keeps + * what it holds, and the service says so once in its log, naming the source. + */ + dropSource?(ctx: AdapterContext): Promise; + /** * Optional liveness probe. When implemented, used by the service's * health endpoint and Studio "test connection" actions. diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index c9023e17aef..b22e8c76224 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -1,10 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import type { ExecutionContext } from '../kernel/execution-context.zod'; -import type { - KnowledgeDocument, - KnowledgeHit, -} from '../ai/knowledge-document.zod'; +import type { KnowledgeHit } from '../ai/knowledge-document.zod'; import type { KnowledgeSource } from '../ai/knowledge-source.zod'; import type { IKnowledgeAdapter } from './knowledge-adapter'; @@ -45,8 +42,7 @@ export interface KnowledgeSearchOptions { * source's `where`, or changed since it was indexed is not returned, and * its document is repaired in the background — except in a source with * `refresh.onRecordChange: false`, whose index an external indexer owns: - * there the hit is only not returned. A `file` / `http` hit is grouped by - * its document. + * there the hit is only not returned. * * The return type does not change: still `KnowledgeHit[]`. */ @@ -60,8 +56,7 @@ export interface KnowledgeSearchOptions { * passing an empty name, or an unknown `granularity`) is refused with * `code: 'VALIDATION_ERROR'`, `status: 400`. An `object` source that does not list the field in its * `metadataFields` answers no hits for this search (never ungrouped), and - * neither does a record with no value for it; a `file` / `http` source - * groups by its document. + * neither does a record with no value for it. */ groupBy?: string; /** Adapter-specific filter (passed opaquely). */ @@ -88,8 +83,7 @@ export interface KnowledgeSearchOptions { * parent two hops away is not reached either. * * Several entries are a union: a document is searched when any entry holds - * for it. A source no entry reaches is not searched, and a `file` / `http` - * source answers nothing under a scope. + * for it. A source no entry reaches is not searched. * * - **Absent**: no scope, as before this option. * - **Empty** (`[]`), or an entry whose `ids` is empty: nothing is in scope, @@ -138,7 +132,7 @@ export interface KnowledgeReindexResult { * Documents deleted by the purge that follows a complete walk: listed by * the adapter before the walk, not seen in it, and confirmed gone by a * re-read of their row (ADR-0161 K8, item 1). `null` when no purge ran: - * a source that is not an `object` source, no data engine bound, a refused + * no data engine bound, a refused * `limit`, a walk with `limit` or `dryRun`, a failed walk, a source with * `refresh.onRecordChange: false`, an adapter without `listDocuments`, or a * listing that failed. A number, with `ok: false`, when the purge stopped @@ -166,7 +160,11 @@ export interface KnowledgeReindexResult { * * Every adapter plugin calls `registerAdapter(id, this)` during its * `start()` hook. Sources reference adapters by id; unknown ids cause - * `search` / `indexDocument` to throw early with a clear error. + * `search` / `reindexSource` to throw early with a clear error. + * + * There is no member that pushes a document (ADR-0161 K1): the service + * assembles every document itself, from the records of the object a source + * names, on a record change and on a reindex. */ export interface IKnowledgeService { /** Register (or replace) an adapter under the given id. */ @@ -185,15 +183,9 @@ export interface IKnowledgeService { /** Look up a single source. Returns `undefined` when not registered. */ getSource(sourceId: string): KnowledgeSource | undefined; - /** Index (insert or replace) a document into the source's adapter. */ - indexDocument(sourceId: string, doc: KnowledgeDocument): Promise; - /** Remove a document from the source's adapter. */ - deleteDocument(sourceId: string, documentId: string): Promise; - /** - * Bulk reindex a source from its declared origin. Object sources - * walk the underlying object via `IDataEngine`; file / http sources - * delegate to the adapter's own ingestion. + * Bulk reindex a source: walk the object it names via `IDataEngine` and + * hand every assembled document to its adapter. */ reindexSource(sourceId: string, opts?: KnowledgeReindexOptions): Promise; diff --git a/packages/spec/src/conversions/entries/19/knowledge-source-content-fields-to-content.ts b/packages/spec/src/conversions/entries/19/knowledge-source-content-fields-to-content.ts new file mode 100644 index 00000000000..296c9d2ab4d --- /dev/null +++ b/packages/spec/src/conversions/entries/19/knowledge-source-content-fields-to-content.ts @@ -0,0 +1,79 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { MetadataConversion } from '../../types.js'; +import { mapCollection, renameKey } from '../../walk.js'; + +type Dict = Record; +const isDict = (v: unknown): v is Dict => typeof v === 'object' && v !== null && !Array.isArray(v); + +/** + * `knowledgeSources[].source.contentFields` → `source.content` (protocol 19, + * ADR-0161 K5 and K6). + * + * A list of field names moves as it is: the rename is lossless, and it changes + * no document, so no index is rebuilt (K6 item 4). + * + * The `'*'` member is the part with no mapping. It asked for every non-system + * field of the object, and `content` is the list of fields whose text is sent + * to the embedding provider: which fields those should be is the author's + * decision, never the tool's. So the key is renamed, the member is left where + * it stood, and the site is reported through `context.reportTodo`; the parse + * then refuses the member with K5's prescription until the author lists the + * fields. + * + * **Retired from the load path**: `ObjectKnowledgeSourceSchema` tombstones + * `contentFields` with the rename. No stored row carries the key. The entry + * keeps the rewrite for `os migrate meta --from 18`. + */ +const knowledgeSourceContentFieldsToContent: MetadataConversion = { + id: 'knowledge-source-content-fields-to-content', + toMajor: 19, + retiredFromLoadPath: true, + retiredAfter: '18.6.0', + surface: 'knowledge_source.source.contentFields', + summary: + "knowledge source key 'source.contentFields' → 'source.content' (the list of fields whose text is embedded; a " + + "list of field names moves unchanged. A '*' member is kept and reported as a TODO: it has no mapping, and " + + 'the parse refuses it until the author lists the fields)', + apply(stack, emit, context) { + return mapCollection(stack, 'knowledgeSources', (item, path) => { + const source = item.source; + if (!isDict(source)) return item; + const renamed = renameKey(source, 'contentFields', 'content'); + if (!renamed) return item; + emit({ from: 'contentFields', to: 'content', path: `${path}.source.content` }); + const content = renamed.content; + if (Array.isArray(content) && content.includes('*')) { + context?.reportTodo?.({ + path: `${path}.source.content`, + from: JSON.stringify(content), + reason: + "The list holds '*', which asked for every non-system field of the object. `content` takes field " + + 'names only, because each listed field is sent to the embedding provider. Replace the member with ' + + 'the names of the fields whose text should be searchable.', + }); + } + return { ...item, source: renamed }; + }); + }, + fixture: { + before: { + knowledgeSources: [ + // Minimal by the disjointness contract: the retired key and nothing the + // major's other `knowledgeSources[]` entries walk. + { name: 'support_articles', adapter: 'memory', source: { kind: 'object', object: 'article', contentFields: ['title', 'body'] } }, + // A source already on `content` keeps its identity (copy-on-write). + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + after: { + knowledgeSources: [ + { name: 'support_articles', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['title', 'body'] } }, + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + expectedNotices: 1, + }, +}; + +export { knowledgeSourceContentFieldsToContent }; diff --git a/packages/spec/src/conversions/entries/19/knowledge-source-id-to-name.ts b/packages/spec/src/conversions/entries/19/knowledge-source-id-to-name.ts new file mode 100644 index 00000000000..8bc79db6d54 --- /dev/null +++ b/packages/spec/src/conversions/entries/19/knowledge-source-id-to-name.ts @@ -0,0 +1,59 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { MetadataConversion } from '../../types.js'; +import { mapCollection, renameKey } from '../../walk.js'; + +/** + * `knowledgeSources[].id` → `name` (protocol 19, ADR-0161 K6). + * + * The knowledge source became a governed metadata type (ADR-0161 K4), and every + * metadata item is identified by `name`. The value does not change, so a + * document id — built from the source's name and the record id — and the index + * fingerprint, computed over values, stay as they are: the rename starts no + * rebuild (K6 item 4). + * + * **Retired from the load path**: `KnowledgeSourceSchema` tombstones `id` with + * the rename, so a live parse refuses it at every door, the registration in + * code included. No stored row carries the key, because a source was never + * stored as metadata before this major. The entry keeps the rewrite for + * `os migrate meta --from 18`. `renameKey` leaves an already-canonical `name` + * alone and refuses a pair that disagrees. + */ +const knowledgeSourceIdToName: MetadataConversion = { + id: 'knowledge-source-id-to-name', + toMajor: 19, + retiredFromLoadPath: true, + retiredAfter: '18.6.0', + surface: 'knowledge_source.id', + summary: + "knowledge source key 'id' → 'name' (a knowledge source is a metadata type from this major, and a metadata " + + 'item is identified by its name; the value is unchanged, so no index is rebuilt)', + apply(stack, emit) { + return mapCollection(stack, 'knowledgeSources', (source, path) => { + const renamed = renameKey(source, 'id', 'name'); + if (!renamed) return source; + emit({ from: 'id', to: 'name', path: `${path}.name` }); + return renamed; + }); + }, + fixture: { + before: { + knowledgeSources: [ + // Minimal by the disjointness contract: the retired key and nothing the + // major's other `knowledgeSources[]` entries walk. + { id: 'support_articles', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['title', 'body'] } }, + // A source already on `name` keeps its identity (copy-on-write). + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + after: { + knowledgeSources: [ + { name: 'support_articles', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['title', 'body'] } }, + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + expectedNotices: 1, + }, +}; + +export { knowledgeSourceIdToName }; diff --git a/packages/spec/src/conversions/entries/19/knowledge-source-inert-keys-removed.ts b/packages/spec/src/conversions/entries/19/knowledge-source-inert-keys-removed.ts new file mode 100644 index 00000000000..6f9bbeffe92 --- /dev/null +++ b/packages/spec/src/conversions/entries/19/knowledge-source-inert-keys-removed.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { MetadataConversion } from '../../types.js'; +import { mapCollection } from '../../walk.js'; +import { stripKeys } from '../shared.js'; + +type Dict = Record; +const isDict = (v: unknown): v is Dict => typeof v === 'object' && v !== null && !Array.isArray(v); + +/** + * `knowledgeSources[]`: `embedding`, `vectorStore`, `adapterConfig` and + * `refresh.cron` removed (protocol 19, ADR-0161 K4 and K6; ADR-0049 + * enforce-or-remove). + * + * Four keys an author could write and nothing read: + * + * - `embedding` — the knowledge service embeds with the one embedder the + * deployment configures; no code read a per-source model. + * - `vectorStore` — the store is the adapter the deployment installs; no code + * read a per-source store. + * - `adapterConfig` — its one reader was the `knowledge-ragflow` adapter, which + * left the repository before this major (K4: with no adapter reading it, the + * key does not enter the type). + * - `refresh.cron` — parsed, and it reached no scheduler. + * + * Each is a pure lossless delete, one notice per key per source: none of them + * ever changed what was indexed or searched. What an author meant by one is + * the D3 entry's subject (`knowledge-source-inert-keys-retired`). + * + * **Retired from the load path**: the schema tombstones all four, so a live + * parse refuses them. No stored row carries any of them. The entry keeps the + * delete for `os migrate meta --from 18`. + */ +const knowledgeSourceInertKeysRemoved: MetadataConversion = { + id: 'knowledge-source-inert-keys-removed', + toMajor: 19, + retiredFromLoadPath: true, + retiredAfter: '18.6.0', + surface: 'knowledge_source.embedding / knowledge_source.vectorStore / knowledge_source.adapterConfig / knowledge_source.refresh.cron', + summary: + "knowledge source keys 'embedding', 'vectorStore', 'adapterConfig' and 'refresh.cron' removed (ADR-0049 — none " + + 'was read: the deployment configures one embedder and installs one store adapter, no adapter in the ' + + 'repository reads a per-source config bag, and no scheduler read the cron expression. Schedule a rebuild ' + + 'from a flow or a job that calls the knowledge service instead)', + apply(stack, emit) { + return mapCollection(stack, 'knowledgeSources', (item, path) => { + let next = stripKeys(item, ['embedding', 'vectorStore', 'adapterConfig'], emit, path); + const refresh = next.refresh; + if (isDict(refresh)) { + const stripped = stripKeys(refresh, ['cron'], emit, `${path}.refresh`); + if (stripped !== refresh) next = { ...next, refresh: stripped }; + } + return next; + }); + }, + fixture: { + before: { + knowledgeSources: [ + // Minimal by the disjointness contract: the four retired keys and + // nothing the major's other `knowledgeSources[]` entries walk. + { + name: 'support_articles', + adapter: 'memory', + source: { kind: 'object', object: 'article', content: ['title', 'body'] }, + embedding: { provider: 'openai', model: 'text-embedding-3-small' }, + vectorStore: { provider: 'pgvector', collection: 'support_articles' }, + adapterConfig: { datasetId: 'ds_1' }, + refresh: { onRecordChange: true, cron: '0 3 * * *' }, + }, + // A source that never authored one keeps its identity (copy-on-write). + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + after: { + knowledgeSources: [ + { + name: 'support_articles', + adapter: 'memory', + source: { kind: 'object', object: 'article', content: ['title', 'body'] }, + refresh: { onRecordChange: true }, + }, + { name: 'policy_clauses', adapter: 'memory', source: { kind: 'object', object: 'clause', content: ['text'] } }, + ], + }, + // One per key carried: embedding, vectorStore, adapterConfig, refresh.cron. + expectedNotices: 4, + }, +}; + +export { knowledgeSourceInertKeysRemoved }; diff --git a/packages/spec/src/conversions/registry.ts b/packages/spec/src/conversions/registry.ts index 637d2a9485d..c1dab8dd40f 100644 --- a/packages/spec/src/conversions/registry.ts +++ b/packages/spec/src/conversions/registry.ts @@ -136,6 +136,9 @@ import { currencyConfigPrecisionRemoved } from './entries/18/currency-config-pre import { permissionModifyAllAllowDeleteFalseToTrue } from './entries/18/permission-modify-all-allow-delete-false-to-true.js'; import { permissionRlsTagsRemoved } from './entries/18/permission-rls-tags-removed.js'; import { flowDecisionModeInclusiveExplicit } from './entries/18/flow-decision-mode-inclusive-explicit.js'; +import { knowledgeSourceContentFieldsToContent } from './entries/19/knowledge-source-content-fields-to-content.js'; +import { knowledgeSourceIdToName } from './entries/19/knowledge-source-id-to-name.js'; +import { knowledgeSourceInertKeysRemoved } from './entries/19/knowledge-source-inert-keys-removed.js'; /** * One conversion of an OPEN major, with its place in that major's application @@ -301,6 +304,23 @@ const MAJOR_18_CONVERSIONS: readonly OrderedConversion[] = [ { conversion: viewPageMountRemoved, order: 29 }, ]; +/** + * Major 19's conversions, one entry per conversion — the shape + * {@link MAJOR_18_CONVERSIONS} documents, opened with the major's first + * conversions (ADR-0161 K6, the knowledge source's renames and removals). + * + * ⚠️ SORTED BY THE CONVERSION'S IDENTIFIER, NOT BY APPLICATION ORDER, for the + * reason given there: two retirements in flight then insert into different + * gaps. `order` says where a conversion applies. To add one, follow the five + * steps listed on {@link MAJOR_18_CONVERSIONS}, with `./entries/19/` as the + * directory. + */ +const MAJOR_19_CONVERSIONS: readonly OrderedConversion[] = [ + { conversion: knowledgeSourceContentFieldsToContent, order: 2 }, + { conversion: knowledgeSourceIdToName, order: 1 }, + { conversion: knowledgeSourceInertKeysRemoved, order: 3 }, +]; + /** * Every conversion, grouped by the major that introduced its canonical shape * (`toMajor`), each major's list in APPLICATION order: {@link ALL_CONVERSIONS} @@ -352,6 +372,7 @@ export const CONVERSIONS_BY_MAJOR: Readonly c.name === 'manage_connector_connections')?.scope).toBe('org'); }); + it('carries the knowledge source capability, declared platform-scoped (ADR-0161 K4, ruling Q2 = B)', () => { + // Asked beside `manage_metadata` at every door that saves a + // `knowledge_source`. Platform administrators hold it by default through + // this grant and no other shipped set does: the holder list is pinned by + // the `[ADR-0161 K4] the knowledge source capability ships with the + // platform administrator and no other set` case in plugin-security's + // `default-permission-sets.test.ts`. + expect(ADMIN_FULL_ACCESS_CAPABILITIES.systemPermissions).toContain('manage_knowledge_sources'); + expect(PLATFORM_CAPABILITIES.find((c) => c.name === 'manage_knowledge_sources')?.scope).toBe('platform'); + }); + it('every granted system permission is a declared built-in capability (ADR-0066 registry)', () => { const unknown = (ADMIN_FULL_ACCESS_CAPABILITIES.systemPermissions ?? []).filter( (name) => !PLATFORM_CAPABILITY_NAMES.has(name), diff --git a/packages/spec/src/kernel/collection-item-owner-stamp.ts b/packages/spec/src/kernel/collection-item-owner-stamp.ts index a839c430748..cf14fd5e30e 100644 --- a/packages/spec/src/kernel/collection-item-owner-stamp.ts +++ b/packages/spec/src/kernel/collection-item-owner-stamp.ts @@ -104,7 +104,7 @@ export const OWNER_STAMP_JUDGED_COLLECTIONS = Object.freeze([ 'flows', 'webhooks', 'jobs', 'positions', 'permissions', 'capabilities', 'sharingRules', 'queues', 'assignmentRules', - 'agents', 'tools', 'skills', 'aiContexts', + 'agents', 'tools', 'skills', 'aiContexts', 'knowledgeSources', 'apis', 'hooks', 'mappings', 'analyticsCubes', 'connectors', diff --git a/packages/spec/src/kernel/customization-package.ts b/packages/spec/src/kernel/customization-package.ts index 7942d49fbd0..5e30a0d57f7 100644 --- a/packages/spec/src/kernel/customization-package.ts +++ b/packages/spec/src/kernel/customization-package.ts @@ -367,6 +367,9 @@ export const OVERRIDE_TYPE_CLASSIFICATION = { // [ADR-0160 D1] A context pack does not join D2's list ("an override of a // packaged pack" is later work): excluded on the `skill` row's basis. ai_context: behaviouralSwitchFirst, + // [ADR-0150 addendum 2026-11-25, Overlays] A knowledge source joins no + // declared-override list: excluded on the `skill` row's basis. + knowledge_source: behaviouralSwitchFirst, } as const satisfies Record; /** The metadata types a declared override applies to (`disposition: 'overridable'`). */ diff --git a/packages/spec/src/kernel/metadata-plugin.zod.ts b/packages/spec/src/kernel/metadata-plugin.zod.ts index 76dc493b5ae..84456f030c6 100644 --- a/packages/spec/src/kernel/metadata-plugin.zod.ts +++ b/packages/spec/src/kernel/metadata-plugin.zod.ts @@ -207,6 +207,11 @@ export const MetadataTypeSchema = lazySchema(() => z.enum([ // and body text are handed to a model. Its reader is the render service // behind `get_record_context` (`@objectstack/service-record-context`). 'ai_context', // AI context packs (AiContextSchema, ADR-0160 D1) + // [ADR-0161 K4] A knowledge source: which object's records the knowledge + // service indexes, which fields leave the row store as content, and which + // adapter holds the index. Its reader is the knowledge service's loader + // (`@objectstack/service-knowledge`), which lands with the type. + 'knowledge_source', // Knowledge sources (KnowledgeSourceSchema, ADR-0161 K4) ])); export type MetadataType = z.input; @@ -1386,6 +1391,11 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = // row's reason: a behavioural contract an author ships or creates at run // time, and never overlaid per environment (ADR-0005's ai row). { type: 'ai_context', label: 'AI Context Pack', filePatterns: ['**/*.ai-context.ts', '**/*.ai-context.yml'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, executionPinned: false, loadOrder: 89, domain: 'ai' }, + // [ADR-0161 K4, clause 2] `knowledge_source` ships in a package or is + // created at run time, is versioned, and takes no environment overlay until + // a ruling opens that channel (ADR-0005). The `ai_context` row's flags, with + // version history on, as the clause says. + { type: 'knowledge_source', label: 'Knowledge Source', filePatterns: ['**/*.knowledge-source.ts', '**/*.knowledge-source.yml'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: true, executionPinned: false, loadOrder: 90, domain: 'ai' }, ]; // ========================================== diff --git a/packages/spec/src/kernel/metadata-type-schemas.ts b/packages/spec/src/kernel/metadata-type-schemas.ts index 7cfd721ba44..c24be52df10 100644 --- a/packages/spec/src/kernel/metadata-type-schemas.ts +++ b/packages/spec/src/kernel/metadata-type-schemas.ts @@ -73,6 +73,7 @@ import { AgentSchema } from '../ai/agent.zod'; import { ToolSchema } from '../ai/tool.zod'; import { SkillSchema } from '../ai/skill.zod'; import { AiContextSchema } from '../ai/ai-context.zod'; +import { KnowledgeSourceSchema } from '../ai/knowledge-source.zod'; import type { MetadataType } from './metadata-plugin.zod'; import { DEFAULT_METADATA_TYPE_REGISTRY } from './metadata-plugin.zod'; @@ -206,6 +207,7 @@ const BUILTIN_METADATA_TYPE_SCHEMAS: Partial> = tool: ToolSchema, skill: SkillSchema, ai_context: AiContextSchema, + knowledge_source: KnowledgeSourceSchema, }; /** diff --git a/packages/spec/src/meta-spelling/manifest-collection-spelling.ts b/packages/spec/src/meta-spelling/manifest-collection-spelling.ts index 94f13897443..156be3c95f7 100644 --- a/packages/spec/src/meta-spelling/manifest-collection-spelling.ts +++ b/packages/spec/src/meta-spelling/manifest-collection-spelling.ts @@ -91,6 +91,7 @@ export const PLURAL_TO_SINGULAR: Record = { tools: 'tool', skills: 'skill', aiContexts: 'ai_context', + knowledgeSources: 'knowledge_source', // `ragPipelines: 'rag_pipeline'` was removed (ADR-0049 enforce-or-remove): no // stack could declare the collection — `ObjectStackDefinitionSchema` never // carried the key, so `defineStack` refused it — and no producer or reader of diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__EmbeddingModel.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__EmbeddingModel.ts new file mode 100644 index 00000000000..0709c737552 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__EmbeddingModel.ts @@ -0,0 +1,8 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K6, Consequences (ADR-0049, the #3950 rule: an exported value +// schema with no consumer reads as a capability) — its ONLY composer was +// `KnowledgeSource.embedding`, removed in this major, so the def leaves with +// the key. The embedder is deployment configuration, never authored metadata. +// D3: `knowledge-source-inert-keys-retired`. +export const entry = 'ai/EmbeddingModel'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__FileKnowledgeSource.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__FileKnowledgeSource.ts new file mode 100644 index 00000000000..2df7d3165b0 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__FileKnowledgeSource.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4, point 1 as merged — the `file` source kind retired whole, with +// its keys `prefix` and `mimeTypes`: nothing read the arm, so there is nothing +// to convert it to. `ai/ObjectKnowledgeSource:kind` refuses the value with the +// prescription. D3: `knowledge-source-file-http-kinds-retired`. +export const entry = 'ai/FileKnowledgeSource'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__HttpKnowledgeSource.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__HttpKnowledgeSource.ts new file mode 100644 index 00000000000..40c7fbabd87 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__HttpKnowledgeSource.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4, point 1 as merged — the `http` source kind retired whole, with +// its keys `urls` and `userAgent`: nothing read the arm, so there is nothing to +// convert it to. `ai/ObjectKnowledgeSource:kind` refuses the value with the +// prescription. D3: `knowledge-source-file-http-kinds-retired`. +export const entry = 'ai/HttpKnowledgeSource'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__KnowledgeSourceKind.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__KnowledgeSourceKind.ts new file mode 100644 index 00000000000..5aca18f289f --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__KnowledgeSourceKind.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4, point 1 as merged — the three-arm union of source kinds left +// with its `file` and `http` arms: `KnowledgeSource.source` is the one arm that +// remains, `ai/ObjectKnowledgeSource`. D3: +// `knowledge-source-file-http-kinds-retired`. +export const entry = 'ai/KnowledgeSourceKind'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStore.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStore.ts new file mode 100644 index 00000000000..c58354018ea --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStore.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K6, Consequences (ADR-0049, the #3950 rule) — its ONLY composer was +// `KnowledgeSource.vectorStore`, removed in this major, so the def leaves with +// the key. The store is the adapter a deployment installs. D3: +// `knowledge-source-inert-keys-retired`. +export const entry = 'ai/VectorStore'; diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStoreProvider.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStoreProvider.ts new file mode 100644 index 00000000000..e7e2fad2993 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__VectorStoreProvider.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K6, Consequences (ADR-0049, the #3950 rule) — the provider enum of +// `ai/VectorStore`, its only consumer; it leaves with that def. See +// `19.ai__VectorStore.ts`. D3: `knowledge-source-inert-keys-retired`. +export const entry = 'ai/VectorStoreProvider'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeRefreshPolicy__cron.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeRefreshPolicy__cron.ts new file mode 100644 index 00000000000..8e1946d6fa5 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeRefreshPolicy__cron.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K6 (ADR-0049 enforce-or-remove) — parsed, and it reached no +// scheduler. Tombstoned with `retiredKey()`. D2: +// `knowledge-source-inert-keys-removed`; D3: `knowledge-source-inert-keys-retired`. +export const entry = 'ai/KnowledgeRefreshPolicy:cron'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__adapterConfig.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__adapterConfig.ts new file mode 100644 index 00000000000..0d82057ef73 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__adapterConfig.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4 ("if no adapter reads `adapterConfig` then, the key does not enter +// v1") — its one reader, the `knowledge-ragflow` adapter, left with #37004. +// Tombstoned with `retiredKey()`. D2: `knowledge-source-inert-keys-removed`; D3: +// `knowledge-source-inert-keys-retired`. +export const entry = 'ai/KnowledgeSource:adapterConfig'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__embedding.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__embedding.ts new file mode 100644 index 00000000000..741154015c0 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__embedding.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4, K6 (ADR-0049 enforce-or-remove) — never read: the deployment +// configures one embedder. Tombstoned with `retiredKey()`. D2: +// `knowledge-source-inert-keys-removed`; D3: `knowledge-source-inert-keys-retired`. +export const entry = 'ai/KnowledgeSource:embedding'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__id.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__id.ts new file mode 100644 index 00000000000..e7e97e289ea --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__id.ts @@ -0,0 +1,7 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K6 — the knowledge source became a governed metadata type (K4), and a +// metadata item is identified by `name`. Lossless rename, the value unchanged. +// Tombstoned with `retiredKey()`. D2: `knowledge-source-id-to-name`; D3: +// `knowledge-source-registration-governed`. +export const entry = 'ai/KnowledgeSource:id'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__vectorStore.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__vectorStore.ts new file mode 100644 index 00000000000..7373c1cad55 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__KnowledgeSource__vectorStore.ts @@ -0,0 +1,6 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K4, K6 (ADR-0049 enforce-or-remove) — never read: the store is the +// adapter the deployment installs. Tombstoned with `retiredKey()`. D2: +// `knowledge-source-inert-keys-removed`; D3: `knowledge-source-inert-keys-retired`. +export const entry = 'ai/KnowledgeSource:vectorStore'; diff --git a/packages/spec/src/migrations/entries/retired-keys/19.ai__ObjectKnowledgeSource__contentFields.ts b/packages/spec/src/migrations/entries/retired-keys/19.ai__ObjectKnowledgeSource__contentFields.ts new file mode 100644 index 00000000000..47b777ef9ab --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/19.ai__ObjectKnowledgeSource__contentFields.ts @@ -0,0 +1,8 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0161 K5, K6 — renamed `content`, the list of fields whose text is sent +// to the embedding provider; a `'*'` member has no mapping and is refused by the +// parse. Tombstoned with `retiredKey()`. D2: +// `knowledge-source-content-fields-to-content`; D3: +// `knowledge-source-content-lists-fields`. +export const entry = 'ai/ObjectKnowledgeSource:contentFields'; diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts new file mode 100644 index 00000000000..be7716f703f --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0161 K5 and K6 — the D3 entry of the `contentFields` → `content` rename. +// The rename is lossless for a list of field names and the D2 conversion +// `knowledge-source-content-fields-to-content` does it. The `'*'` member is the +// part no conversion can do: it has no mapping, because which fields leave the +// deployment for the embedding provider is the author's decision. +export const entry: SemanticMigration = { + id: 'knowledge-source-content-lists-fields', + surface: + 'A knowledge source\'s `source.contentFields`, and the `\'*\'` member that list accepted: in a ' + + '`knowledgeSources` entry and in a source registered in code (`KnowledgeServicePlugin({ sources })`, ' + + '`IKnowledgeService.registerSource`)', + replacement: + '`source.content`: a non-empty list of field names of the object the source indexes. Where the list held ' + + '`\'*\'`, write the names of the fields whose text should be searchable. A field with `secret: true`, a ' + + 'credential-class field and an `internal` field are never embedded, named or not.', + reason: + 'The D2 conversion renames the key and moves a list of field names unchanged, so no document and no index ' + + 'changes. `\'*\'` asked the service to embed every non-system field of the object, the ones added after ' + + 'the source was written included. Each field in `content` is sent, for every record the source selects, ' + + 'to the embedding provider the deployment configures, so the list is a statement of what leaves the ' + + 'deployment, and a wildcard states nothing. The parse now refuses the member and names the fix; ' + + '`os migrate meta --from 18` renames the key, keeps the member and reports the site as a hand edit. ' + + 'Which fields to list is known only to the source\'s author: the ones users search by, and none that ' + + 'should not be sent to the provider.', + acceptanceCriteria: + 'No knowledge source writes `contentFields`, and none lists `\'*\'` in `content`; the parse refuses both. For ' + + 'each source that used `\'*\'`, the fields now listed are the ones its searches should match, a search ' + + 'that found a record through a field left off the list is known and accepted, and a reindex has run: the ' + + 'changed list is a changed content recipe, which the service rebuilds inside the index generation at the ' + + 'next boot or source reload.', + conversionIds: ['knowledge-source-content-fields-to-content'], +}; diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-file-http-kinds-retired.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-file-http-kinds-retired.ts new file mode 100644 index 00000000000..6146e9a3d16 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-file-http-kinds-retired.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0161 K1, K4 (point 1, as merged) and K6 — the D3 entry of the `file` and +// `http` source kinds. No D2 conversion: nothing read either arm, so there is +// nothing to convert one to. The family is the two arms +// (`ai/FileKnowledgeSource`, `ai/HttpKnowledgeSource`) and the union they sat +// in (`ai/KnowledgeSourceKind`), all in RETIRED_DEFS_BY_MAJOR[19], with the +// push door they were served by: `IKnowledgeService.indexDocument` and +// `deleteDocument`, a published TypeScript interface with no metadata surface, +// which ADR-0087 D7 calls compiler-carried. +export const entry: SemanticMigration = { + id: 'knowledge-source-file-http-kinds-retired', + surface: + 'A knowledge source whose `source.kind` is `file` or `http`, with its keys `prefix`, `mimeTypes`, `urls` ' + + 'and `userAgent`; and host code that calls `IKnowledgeService.indexDocument` or `deleteDocument`', + replacement: + 'A source indexes the records of one object: `source: { kind: \'object\', object, content: [...] }`. Text ' + + 'that lives in files or behind URLs is searchable once it is in records: load it into an object (an ' + + 'import, a flow or a connector) and declare a source over that object. The knowledge service then ' + + 'assembles, splits and embeds each record, keeps the index in step with record changes, and re-reads ' + + 'every hit as the asking user. There is no call that hands the service a document.', + reason: + 'The schema accepted three kinds of source and the service built an index from one. A `file` or `http` ' + + 'source registered without error and indexed nothing by itself: no loader read `prefix` or `urls`, and ' + + 'its documents existed only if host code pushed each one through `indexDocument`. Documents pushed that ' + + 'way had no record behind them, so a hit could not be re-read as the asking user, which is how every ' + + 'other answer is permission-checked. The two kinds, their four keys and the two push members are ' + + 'removed together: the parse refuses the kinds and the keys and names the fix, and a call to either ' + + 'member no longer compiles. An index that host code filled through the push door is not rebuilt by the ' + + 'platform, because the platform never knew where its documents came from. Where those documents should ' + + 'live as records, and who may read them there, is the application author\'s decision.', + acceptanceCriteria: + 'No knowledge source has `source.kind` other than `object` or carries `prefix`, `mimeTypes`, `urls` or ' + + '`userAgent`, and no code calls `indexDocument` or `deleteDocument` on the knowledge service. For each ' + + 'retired source whose content still has to be searchable: the content is held in records of an object, a ' + + 'source over that object lists the fields to embed, a search finds it, and a user who may not read a ' + + 'record does not get it as a hit. Whatever an adapter still holds under a retired source\'s name is ' + + 'removed from its store.', +}; diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-inert-keys-retired.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-inert-keys-retired.ts new file mode 100644 index 00000000000..c267308d215 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-inert-keys-retired.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0161 K4 and K6 (ADR-0049 enforce-or-remove) — the D3 entry of the +// `knowledge-source-inert-keys-removed` family: four authorable keys nothing +// read (`ai/KnowledgeSource:embedding`, `ai/KnowledgeSource:vectorStore`, +// `ai/KnowledgeSource:adapterConfig`, `ai/KnowledgeRefreshPolicy:cron`) and the +// shapes that leave with the first two — `ai/EmbeddingModel`, `ai/VectorStore` +// and `ai/VectorStoreProvider` in RETIRED_DEFS_BY_MAJOR[19]. One D3 entry per +// retirement family, even when D2 is lossless. +export const entry: SemanticMigration = { + id: 'knowledge-source-inert-keys-retired', + surface: + 'A knowledge source\'s `embedding`, `vectorStore`, `adapterConfig` and `refresh.cron`, in a ' + + '`knowledgeSources` entry and in a source registered in code; and the exported schemas ' + + '`EmbeddingModelSchema`, `VectorStoreSchema` and `VectorStoreProviderSchema` with their types', + replacement: + '(removed — none of the four was read.) The embedder is configured once for the deployment, in the ' + + 'knowledge settings; the store is the adapter the deployment installs, named by the source\'s `adapter`; ' + + 'an adapter\'s own options are its plugin\'s options. To rebuild an index on a schedule, call ' + + '`reindexSource` from a flow or a job. `refresh.onRecordChange` is unchanged.', + reason: + 'The D2 conversion deletes the four keys from every `knowledgeSources` entry, one notice per key, and the ' + + 'delete is lossless: the knowledge service embedded with the deployment\'s one embedder whatever a ' + + 'source\'s `embedding` said, wrote to the store of the adapter the source names whatever `vectorStore` ' + + 'said, handed `adapterConfig` to no adapter in the repository once the one that read it left, and ' + + 'started no scheduler from `refresh.cron`. The judgment is what each was written to achieve. A source ' + + 'that named a model expected its vectors to come from that model; one that named a store expected its ' + + 'documents there; one with a cron expression expected a periodic rebuild that never ran. Whether the ' + + 'deployment\'s embedder and adapter are the intended ones, and whether a schedule is still wanted, is ' + + 'known only to the deployment\'s owner.', + acceptanceCriteria: + 'No knowledge source carries `embedding`, `vectorStore`, `adapterConfig` or `refresh.cron`; the parse ' + + 'refuses each, and no code imports EmbeddingModelSchema, VectorStoreSchema or VectorStoreProviderSchema. ' + + 'Searches answer exactly as before the upgrade. For every source whose removed key stated an intent that ' + + 'still matters: the deployment\'s knowledge settings name the embedder it expected, its `adapter` names ' + + 'the store it expected, and a flow or job calls `reindexSource` on the schedule its cron expression ' + + 'described.', + conversionIds: ['knowledge-source-inert-keys-removed'], +}; diff --git a/packages/spec/src/migrations/registry.ts.template b/packages/spec/src/migrations/registry.ts.template index f9172188748..b9ba1ad9edc 100644 --- a/packages/spec/src/migrations/registry.ts.template +++ b/packages/spec/src/migrations/registry.ts.template @@ -3718,16 +3718,25 @@ const step18: MigrationStep = { * load-time handshake (ADR-0087 D1) refuses a manifest whose range admits only * 18. That refusal is this step's first semantic entry, and the one every * upgrading author meets first. Later retirements on the v19 line add their - * entries as files; a major-19 conversion, once one exists, graduates here the - * way step 18's do. + * entries as files, and its conversions graduate here the way step 18's do + * (the first are the knowledge source's, ADR-0161 K6). */ const step19: MigrationStep = { toMajor: 19, rationale: 'Protocol 19 moves the load-time handshake: a manifest whose `engines.protocol` range admits ' + 'protocol 18 and not 19 is refused before any of its metadata loads, so each manifest an app ' - + 'or package declares moves its range to `^19`, together with its `@objectstack/*` versions.', - conversionIds: [], + + 'or package declares moves its range to `^19`, together with its `@objectstack/*` versions. ' + + 'It also admits the knowledge source as a metadata type (`knowledge_source`, ADR-0161 K4) and ' + + 'settles its keys on the way in: `id` becomes `name` and `source.contentFields` becomes ' + + '`source.content`, a list of field names in which `\'*\'` is refused, because each listed field ' + + 'is sent to the embedding provider; `embedding`, `vectorStore`, `adapterConfig` and ' + + '`refresh.cron`, which nothing read, are removed; and the `file` and `http` source kinds leave ' + + 'with their four keys, so a source indexes the records of one object.', + // Derived, not listed, as step 18's: every major-19 conversion graduates + // into this step in the order `CONVERSIONS_BY_MAJOR[19]` applies them. Add a + // conversion there, never here. + conversionIds: CONVERSIONS_BY_MAJOR[19]!.map((c) => c.id), semantic: [ // One file per entry under `entries/semantic/`, concatenated here sorted by // entry id by `gen:migration-registry` (#7297). Add an entry by adding a @@ -3896,6 +3905,14 @@ export const RETIRED_KEYS_BY_MAJOR: Readonly> // // ], + // Protocol 19's retirements, registered at the major they ship in. + 19: [ + // One file per entry under `entries/retired-keys/`, concatenated here sorted by + // entry id by `gen:migration-registry` (#7297). Add an entry by adding a + // FILE — never by editing between the markers, which is generated. + // + // + ], }; /** @@ -4025,4 +4042,12 @@ export const RETIRED_DEFS_BY_MAJOR: Readonly> // // ], + // Protocol 19's whole-def removals, registered at the major they ship in. + 19: [ + // One file per entry under `entries/retired-defs/`, concatenated here sorted by + // entry id by `gen:migration-registry` (#7297). Add an entry by adding a + // FILE — never by editing between the markers, which is generated. + // + // + ], }; diff --git a/packages/spec/src/security/capabilities.ts b/packages/spec/src/security/capabilities.ts index 74e9a09dd4b..5145eef2b29 100644 --- a/packages/spec/src/security/capabilities.ts +++ b/packages/spec/src/security/capabilities.ts @@ -111,6 +111,18 @@ export const PLATFORM_CAPABILITIES: readonly PlatformCapability[] = [ // caller's own organization's connection, and the holder never sees a // token. { name: 'manage_connector_connections', label: 'Manage Connector Connections', description: 'Connect, reconnect and revoke the holder’s organization’s connection of an OAuth2 connector instance, and read its status. A connection authorizes the platform to call the vendor on the organization’s behalf; no token is ever shown to the holder.', scope: 'org' }, + // [ADR-0161 K4, guard one; ruling Q2 = B on #37304] The knowledge source + // capability. Saving a `knowledge_source` sends the fields it lists, for + // every record it selects, to the embedding provider, and the first build is + // billed — an act of another weight than editing a layout. So every door + // that creates, changes or removes an item of that type (Studio and REST + // `/meta`, the dispatcher, the MCP draft door) asks this capability BESIDE + // `manage_metadata`, never instead of it. Held by default by platform + // administrators only (`ADMIN_FULL_ACCESS_CAPABILITIES`); every other + // position, organization administrators included, only by explicit grant. + // A grant on the indexed object's records does not imply it. `platform`: + // the item is environment metadata, as `manage_metadata`'s subjects are. + { name: 'manage_knowledge_sources', label: 'Manage Knowledge Sources', description: 'Create, change and remove knowledge sources, together with Manage Metadata. A knowledge source sends the fields it lists, for every record it selects, to the embedding provider and starts an index build that may be billed.', scope: 'platform' }, ]; /** Set of built-in capability names, for fast membership checks (lint, gating). */ diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 4277b5c4c26..c5fda20494e 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -101,6 +101,7 @@ import { retiredKey } from './shared/retired-key'; import { AgentSchema } from './ai/agent.zod'; import { SkillSchema } from './ai/skill.zod'; import { AiContextSchema } from './ai/ai-context.zod'; +import { KnowledgeSourceSchema } from './ai/knowledge-source.zod'; import { ToolSchema } from './ai/tool.zod'; // Data Protocol (additional) @@ -1230,6 +1231,7 @@ const STACK_DEFINITION_COLLECTIONS_SHAPE = { * that does neither serves no such tool, whatever packs it holds. */ aiContexts: z.array(AiContextSchema).optional().describe('AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins`'), + knowledgeSources: z.array(KnowledgeSourceSchema).optional().describe('Knowledge sources — which object\'s records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it where `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins`'), /** * ObjectQL: Data Extensions @@ -1702,6 +1704,7 @@ export const COMPOSE_KEY_DISPOSITIONS = Object.freeze({ tools: 'concat', skills: 'concat', aiContexts: 'concat', + knowledgeSources: 'concat', hooks: 'concat', mappings: 'concat', analyticsCubes: 'concat', @@ -3464,6 +3467,7 @@ const SAME_STACK_ENTRY_IDENTITY = Object.freeze({ tools: lastWinsByName('Tool', 'tools'), skills: lastWinsByName('Skill', 'skills'), aiContexts: lastWinsByName('AI context pack', 'aiContexts'), + knowledgeSources: lastWinsByName('Knowledge source', 'knowledge sources'), views: { identity: (entry) => isAggregatedViewContainer(entry) diff --git a/scripts/check-stack-collection-maps.mjs b/scripts/check-stack-collection-maps.mjs index 0264484f156..4270e1a7917 100644 --- a/scripts/check-stack-collection-maps.mjs +++ b/scripts/check-stack-collection-maps.mjs @@ -504,10 +504,10 @@ const SITES = [ }, { direction: 'missing', - keys: ['datasourceMapping', 'capabilities', 'docs', 'books', 'tools', 'skills', 'aiContexts', 'picklists'], + keys: ['datasourceMapping', 'capabilities', 'docs', 'books', 'tools', 'skills', 'aiContexts', 'knowledgeSources', 'picklists'], reason: 'no map form has ever been offered for these. `datasourceMapping` is a rule LIST whose precedence is ' - + 'positional, so a map would lose the ordering that decides which rule wins; the other six are ' + + 'positional, so a map would lose the ordering that decides which rule wins; the others are ' + 'array-only authoring surfaces (`picklists` since it was declared). Offering a map form for any of them WIDENS what parses — an ' + 'acceptance change, which belongs to its own reviewed diff rather than to this gate.', }, @@ -560,7 +560,7 @@ const SITES = [ keys: [ 'datasources', 'datasourceMapping', 'objectExtensions', 'apps', 'jobs', 'emailTemplates', 'docs', 'books', 'positions', 'capabilities', 'sharingRules', 'webhooks', 'tools', 'skills', - 'aiContexts', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', + 'aiContexts', 'knowledgeSources', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', 'queues', 'assignmentRules', ], reason: @@ -754,7 +754,7 @@ const SITES = [ 'datasources', 'datasourceMapping', 'translations', 'objects', 'objectExtensions', 'apps', 'views', 'pages', 'dashboards', 'reports', 'datasets', 'actions', 'flows', 'jobs', 'emailTemplates', 'docs', 'books', 'apis', 'webhooks', 'agents', 'tools', 'skills', - 'aiContexts', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', + 'aiContexts', 'knowledgeSources', 'hooks', 'mappings', 'analyticsCubes', 'connectors', 'data', 'picklists', 'picklistExtensions', 'queues', 'assignmentRules', ], reason: diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index c5c177446e0..8a44d688d74 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -906,6 +906,8 @@ const TYPE_COUNT: Readonly strin skill: (t, count) => t('preview.changes.typeCount.skill', { count, defaultValue: '{{count}} AI skills' }), ai_context: (t, count) => t('preview.changes.typeCount.ai_context', { count, defaultValue: '{{count}} AI context packs' }), + knowledge_source: (t, count) => + t('preview.changes.typeCount.knowledge_source', { count, defaultValue: '{{count}} knowledge sources' }), datasource: (t, count) => t('preview.changes.typeCount.datasource', { count, defaultValue: '{{count}} datasources' }), }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMenu.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMenu.tsx index e16b7cc4e34..92708bd0af1 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMenu.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMenu.tsx @@ -53,6 +53,7 @@ import { AppWindow, BarChart3, BookOpen, + LibraryBig, Bot, Boxes, Brain, @@ -178,6 +179,7 @@ const STUDIO_MENU_TYPE_ICONS: Readonly> = { queue: Inbox, capability: ListTree, ai_context: Brain, + knowledge_source: LibraryBig, }; /** The icon of each entry that is not a type: the page it opens. */ diff --git a/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts b/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts index 6fbddb2f98a..a361714e96c 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts @@ -67,7 +67,7 @@ describe('the menu placement table holds the ruled order and tiers (objectstack# 'job', 'doc', 'book', 'email_template', 'translation', 'api', 'datasource', 'external_catalog', 'position', 'assignment_rule', 'sharing_rule', 'queue', 'capability', - 'ai_context', + 'ai_context', 'knowledge_source', ]); }); diff --git a/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.ts b/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.ts index a4a471023d2..8521cc3c35b 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioMenuPlacement.ts @@ -94,4 +94,5 @@ export const STUDIO_MENU_PLACEMENT: readonly StudioMenuPlacementRow[] = Object.f { type: 'capability', tier: 'advanced' }, // 高级 — ai { type: 'ai_context', tier: 'advanced' }, + { type: 'knowledge_source', tier: 'advanced' }, ] as const satisfies readonly StudioMenuPlacementRow[]); diff --git a/ui/packages/fields/src/widgets/CapabilityMultiSelectField.tsx b/ui/packages/fields/src/widgets/CapabilityMultiSelectField.tsx index d4b7dea5ec2..ce13b55b2d3 100644 --- a/ui/packages/fields/src/widgets/CapabilityMultiSelectField.tsx +++ b/ui/packages/fields/src/widgets/CapabilityMultiSelectField.tsx @@ -169,6 +169,8 @@ const CURATED_CAPABILITY_LABELS = new Set([ 'manage_mailboxes', // ADR-0143 D5: the organization-scoped connector connection capability. 'manage_connector_connections', + // ADR-0161 K4: asked beside `manage_metadata` to author a knowledge source. + 'manage_knowledge_sources', ]); export function CapabilityMultiSelectField({ diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index 80d86cbe511..208169c3061 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -329,6 +329,7 @@ const FIELD_DEFAULTS: Record = { 'capability.label.view_all_audit_log': 'View All Audit Log', 'capability.label.manage_mailboxes': 'Manage Mailboxes', 'capability.label.manage_connector_connections': 'Manage Connector Connections', + 'capability.label.manage_knowledge_sources': 'Manage Knowledge Sources', }; export const useFieldTranslation = createSafeTranslation( diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 3cf647b8482..86c438ec4eb 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -22,6 +22,7 @@ const ar = { manage_metadata: "إدارة البيانات الوصفية", manage_mailboxes: "إدارة صناديق البريد", manage_connector_connections: "إدارة اتصالات الموصلات", + manage_knowledge_sources: "إدارة مصادر المعرفة", manage_platform_settings: "إدارة إعدادات المنصة", setup_access: "الوصول إلى الإعداد", setup_write: "كتابة الإعدادات", @@ -5943,6 +5944,13 @@ const ar = { ai_context_few: 'حزم سياق الذكاء الاصطناعي {{count}}', ai_context_many: 'حزم سياق الذكاء الاصطناعي {{count}}', ai_context_other: 'حزم سياق الذكاء الاصطناعي {{count}}', + knowledge_source: 'مصادر المعرفة {{count}}', + knowledge_source_zero: 'مصادر المعرفة {{count}}', + knowledge_source_one: 'مصدر المعرفة {{count}}', + knowledge_source_two: 'مصادر المعرفة {{count}}', + knowledge_source_few: 'مصادر المعرفة {{count}}', + knowledge_source_many: 'مصادر المعرفة {{count}}', + knowledge_source_other: 'مصادر المعرفة {{count}}', datasource: 'مصادر بيانات {{count}}', datasource_zero: 'مصادر بيانات {{count}}', datasource_one: 'مصدر بيانات {{count}}', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index d804f2f07e7..420e95a2211 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -22,6 +22,7 @@ const de = { manage_metadata: "Metadaten verwalten", manage_mailboxes: "Postfächer verwalten", manage_connector_connections: "Konnektor-Verbindungen verwalten", + manage_knowledge_sources: "Wissensquellen verwalten", manage_platform_settings: "Plattformeinstellungen verwalten", setup_access: "Zugriff auf die Einrichtung", setup_write: "Einstellungen schreiben", @@ -5341,6 +5342,9 @@ const de = { ai_context: '{{count}} KI-Kontextpakete', ai_context_one: '{{count}} KI-Kontextpaket', ai_context_other: '{{count}} KI-Kontextpakete', + knowledge_source: '{{count}} Wissensquellen', + knowledge_source_one: '{{count}} Wissensquelle', + knowledge_source_other: '{{count}} Wissensquellen', datasource: '{{count}} Datenquellen', datasource_one: '{{count}} Datenquelle', datasource_other: '{{count}} Datenquellen', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 9ea88fe3b4c..2a58d8e7fba 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -33,6 +33,7 @@ const en = { manage_metadata: 'Manage Metadata', manage_mailboxes: 'Manage Mailboxes', manage_connector_connections: 'Manage Connector Connections', + manage_knowledge_sources: 'Manage Knowledge Sources', manage_platform_settings: 'Manage Platform Settings', setup_access: 'Setup Access', setup_write: 'Write Settings', @@ -4913,6 +4914,9 @@ const en = { ai_context: '{{count}} AI context packs', ai_context_one: '{{count}} AI context pack', ai_context_other: '{{count}} AI context packs', + knowledge_source: '{{count}} knowledge sources', + knowledge_source_one: '{{count}} knowledge source', + knowledge_source_other: '{{count}} knowledge sources', datasource: '{{count}} datasources', datasource_one: '{{count}} datasource', datasource_other: '{{count}} datasources', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 120acaab624..5c259125740 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -22,6 +22,7 @@ const es = { manage_metadata: "Gestionar metadatos", manage_mailboxes: "Gestionar los buzones", manage_connector_connections: "Gestionar las conexiones de conectores", + manage_knowledge_sources: "Gestionar las fuentes de conocimiento", manage_platform_settings: "Gestionar la configuración de la plataforma", setup_access: "Acceso a la configuración", setup_write: "Escritura de la configuración", @@ -5492,6 +5493,10 @@ const es = { ai_context_one: '{{count}} paquete de contexto de IA', ai_context_many: '{{count}} de paquetes de contexto de IA', ai_context_other: '{{count}} paquetes de contexto de IA', + knowledge_source: '{{count}} fuentes de conocimiento', + knowledge_source_one: '{{count}} fuente de conocimiento', + knowledge_source_many: '{{count}} de fuentes de conocimiento', + knowledge_source_other: '{{count}} fuentes de conocimiento', datasource: '{{count}} orígenes de datos', datasource_one: '{{count}} origen de datos', datasource_many: '{{count}} de orígenes de datos', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 0ddd6d4f073..8b9f1c0dab5 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -22,6 +22,7 @@ const fr = { manage_metadata: "Gérer les métadonnées", manage_mailboxes: "Gérer les boîtes aux lettres", manage_connector_connections: "Gérer les connexions des connecteurs", + manage_knowledge_sources: "Gérer les sources de connaissances", manage_platform_settings: "Gérer les paramètres de la plateforme", setup_access: "Accès à la configuration", setup_write: "Écriture des paramètres", @@ -5488,6 +5489,10 @@ const fr = { ai_context_one: '{{count}} pack de contexte IA', ai_context_many: '{{count}} de packs de contexte IA', ai_context_other: '{{count}} packs de contexte IA', + knowledge_source: '{{count}} sources de connaissances', + knowledge_source_one: '{{count}} source de connaissances', + knowledge_source_many: '{{count}} de sources de connaissances', + knowledge_source_other: '{{count}} sources de connaissances', datasource: '{{count}} sources de données', datasource_one: '{{count}} source de données', datasource_many: '{{count}} de sources de données', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 0abf78fc895..d31d38ab1db 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -22,6 +22,7 @@ const ja = { manage_metadata: "メタデータ管理", manage_mailboxes: "メールボックスの管理", manage_connector_connections: "コネクタ接続の管理", + manage_knowledge_sources: "ナレッジソースの管理", manage_platform_settings: "プラットフォーム設定の管理", setup_access: "設定へのアクセス", setup_write: "設定の書き込み", @@ -5343,6 +5344,9 @@ const ja = { ai_context: 'AI コンテキストパック {{count}}', ai_context_one: 'AI コンテキストパック {{count}}', ai_context_other: 'AI コンテキストパック {{count}}', + knowledge_source: 'ナレッジソース {{count}}', + knowledge_source_one: 'ナレッジソース {{count}}', + knowledge_source_other: 'ナレッジソース {{count}}', datasource: 'データソース {{count}}', datasource_one: 'データソース {{count}}', datasource_other: 'データソース {{count}}', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 824351d7117..e9b248acaf7 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -22,6 +22,7 @@ const ko = { manage_metadata: "메타데이터 관리", manage_mailboxes: "메일함 관리", manage_connector_connections: "커넥터 연결 관리", + manage_knowledge_sources: "지식 소스 관리", manage_platform_settings: "플랫폼 설정 관리", setup_access: "설정 접근", setup_write: "설정 쓰기", @@ -5340,6 +5341,9 @@ const ko = { ai_context: 'AI 컨텍스트 팩 {{count}}', ai_context_one: 'AI 컨텍스트 팩 {{count}}', ai_context_other: 'AI 컨텍스트 팩 {{count}}', + knowledge_source: '지식 소스 {{count}}', + knowledge_source_one: '지식 소스 {{count}}', + knowledge_source_other: '지식 소스 {{count}}', datasource: '데이터 소스 {{count}}', datasource_one: '데이터 소스 {{count}}', datasource_other: '데이터 소스 {{count}}', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index df1670eceb9..f714ccace4c 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -22,6 +22,7 @@ const pt = { manage_metadata: "Gerenciar metadados", manage_mailboxes: "Gerenciar caixas de correio", manage_connector_connections: "Gerenciar conexões de conectores", + manage_knowledge_sources: "Gerenciar fontes de conhecimento", manage_platform_settings: "Gerenciar configurações da plataforma", setup_access: "Acesso à configuração", setup_write: "Gravação de configurações", @@ -5487,6 +5488,10 @@ const pt = { ai_context_one: '{{count}} pacote de contexto de IA', ai_context_many: '{{count}} de pacotes de contexto de IA', ai_context_other: '{{count}} pacotes de contexto de IA', + knowledge_source: '{{count}} fontes de conhecimento', + knowledge_source_one: '{{count}} fonte de conhecimento', + knowledge_source_many: '{{count}} de fontes de conhecimento', + knowledge_source_other: '{{count}} fontes de conhecimento', datasource: '{{count}} fontes de dados', datasource_one: '{{count}} fonte de dados', datasource_many: '{{count}} de fontes de dados', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 3b3732188e4..3e5efb35c79 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -22,6 +22,7 @@ const ru = { manage_metadata: "Управление метаданными", manage_mailboxes: "Управление почтовыми ящиками", manage_connector_connections: "Управление подключениями коннекторов", + manage_knowledge_sources: "Управление источниками знаний", manage_platform_settings: "Управление настройками платформы", setup_access: "Доступ к настройке", setup_write: "Запись настроек", @@ -5652,6 +5653,11 @@ const ru = { ai_context_few: 'Пакеты контекста ИИ: {{count}}', ai_context_many: 'Пакеты контекста ИИ: {{count}}', ai_context_other: 'Пакеты контекста ИИ: {{count}}', + knowledge_source: 'Источники знаний: {{count}}', + knowledge_source_one: 'Источник знаний: {{count}}', + knowledge_source_few: 'Источники знаний: {{count}}', + knowledge_source_many: 'Источники знаний: {{count}}', + knowledge_source_other: 'Источники знаний: {{count}}', datasource: 'Источники данных: {{count}}', datasource_one: 'Источник данных: {{count}}', datasource_few: 'Источники данных: {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 31506176dbb..37c8fdd01a1 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -36,6 +36,7 @@ const zh = { manage_metadata: '管理元数据', manage_mailboxes: '管理邮箱', manage_connector_connections: '管理连接器连接', + manage_knowledge_sources: '管理知识源', manage_platform_settings: '管理平台设置', setup_access: '访问 Setup', setup_write: '保存设置', @@ -4273,6 +4274,9 @@ const zh = { ai_context: 'AI 上下文包 {{count}}', ai_context_one: 'AI 上下文包 {{count}}', ai_context_other: 'AI 上下文包 {{count}}', + knowledge_source: '知识源 {{count}}', + knowledge_source_one: '知识源 {{count}}', + knowledge_source_other: '知识源 {{count}}', datasource: '数据源 {{count}}', datasource_one: '数据源 {{count}}', datasource_other: '数据源 {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index aa77a0d7f78..98a87480042 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -36,6 +36,7 @@ const zhHant = { manage_metadata: '管理中繼資料', manage_mailboxes: '管理郵箱', manage_connector_connections: '管理聯結器連線', + manage_knowledge_sources: '管理知識來源', manage_platform_settings: '管理平台設定', setup_access: '訪問 Setup', setup_write: '儲存設定', @@ -4273,6 +4274,9 @@ const zhHant = { ai_context: 'AI 上下文包 {{count}}', ai_context_one: 'AI 上下文包 {{count}}', ai_context_other: 'AI 上下文包 {{count}}', + knowledge_source: '知識來源 {{count}}', + knowledge_source_one: '知識來源 {{count}}', + knowledge_source_other: '知識來源 {{count}}', datasource: '資料來源 {{count}}', datasource_one: '資料來源 {{count}}', datasource_other: '資料來源 {{count}}', From 98cdf81ee70526d7f1a41724cb9e99af20a21b98 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:35:16 +0000 Subject: [PATCH 02/29] feat(spec)!: knowledge_source kit on protocol 19 (conversions, retired keys and defs, semantic entries), pins Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/authorable-defaults/ai.json | 3 +- packages/spec/authorable-surface/ai.json | 39 +-- packages/spec/json-schema.manifest/ai.json | 8 +- .../scripts/conversions-major18-merge.test.ts | 8 +- packages/spec/scripts/lib/default-changes.ts | 12 + packages/spec/src/ai/knowledge-source.test.ts | 309 ++++++++++++------ packages/spec/src/ai/knowledge-source.zod.ts | 5 +- .../src/kernel/metadata-create-seeds.test.ts | 6 + ...9.knowledge-source-content-lists-fields.ts | 2 +- ....knowledge-source-registration-governed.ts | 48 +++ .../stack-collection-item-owner-stamp.test.ts | 3 + .../src/type-alias-convention.pin.test.ts | 21 +- 12 files changed, 319 insertions(+), 145 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/19.knowledge-source-registration-governed.ts diff --git a/packages/spec/authorable-defaults/ai.json b/packages/spec/authorable-defaults/ai.json index b5c8f97d09a..ed75da841de 100644 --- a/packages/spec/authorable-defaults/ai.json +++ b/packages/spec/authorable-defaults/ai.json @@ -16,13 +16,12 @@ "ai/ConversationMessage:pinned = false", "ai/ConversationSession:messages = []", "ai/ConversationSession:status = \"active\"", - "ai/FileKnowledgeSource:mimeTypes = []", "ai/ImageContent:detail = \"auto\"", "ai/KnowledgeDocument:metadata = {}", "ai/KnowledgeHit:metadata = {}", "ai/KnowledgeRefreshPolicy:onRecordChange = true", - "ai/KnowledgeSource:adapterConfig = {}", "ai/KnowledgeSource:aiExposed = true", + "ai/KnowledgeSource:refresh = {}", "ai/MCPServerRef:active = true", "ai/MCPToolBinding:approval = \"never\"", "ai/ModelCapability:codeGeneration = false", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index efff07e8d37..4432b3786e5 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -213,19 +213,11 @@ "ai/DatasetToolCatalogMeasure:name", "ai/DatasetToolCatalogMeasure:polarity", "ai/DatasetToolCatalogMeasure:synonyms", - "ai/EmbeddingModel:dimensions", - "ai/EmbeddingModel:endpoint", - "ai/EmbeddingModel:model", - "ai/EmbeddingModel:provider", - "ai/EmbeddingModel:secretRef", "ai/FileContent:fileName", "ai/FileContent:fileUrl", "ai/FileContent:metadata", "ai/FileContent:mimeType", "ai/FileContent:type", - "ai/FileKnowledgeSource:kind", - "ai/FileKnowledgeSource:mimeTypes", - "ai/FileKnowledgeSource:prefix", "ai/FunctionCall:arguments", "ai/FunctionCall:name", "ai/FunctionCall:result", @@ -237,9 +229,6 @@ "ai/GetRecordContextOutput:data", "ai/GetRecordContextOutput:framing", "ai/GetRecordContextOutput:notes", - "ai/HttpKnowledgeSource:kind", - "ai/HttpKnowledgeSource:urls", - "ai/HttpKnowledgeSource:userAgent", "ai/ImageContent:detail", "ai/ImageContent:imageUrl", "ai/ImageContent:metadata", @@ -270,18 +259,26 @@ "ai/KnowledgeHit:sourceId", "ai/KnowledgeHit:sourceRecordId", "ai/KnowledgeHit:title", - "ai/KnowledgeRefreshPolicy:cron", + "ai/KnowledgeRefreshPolicy:cron [RETIRED]", "ai/KnowledgeRefreshPolicy:onRecordChange", + "ai/KnowledgeSource:_lock", + "ai/KnowledgeSource:_lockDocsUrl", + "ai/KnowledgeSource:_lockReason", + "ai/KnowledgeSource:_lockSource", + "ai/KnowledgeSource:_packageId", + "ai/KnowledgeSource:_packageVersion", + "ai/KnowledgeSource:_provenance", "ai/KnowledgeSource:adapter", - "ai/KnowledgeSource:adapterConfig", + "ai/KnowledgeSource:adapterConfig [RETIRED]", "ai/KnowledgeSource:aiExposed", "ai/KnowledgeSource:description", - "ai/KnowledgeSource:embedding", - "ai/KnowledgeSource:id", + "ai/KnowledgeSource:embedding [RETIRED]", + "ai/KnowledgeSource:id [RETIRED]", "ai/KnowledgeSource:label", + "ai/KnowledgeSource:name", "ai/KnowledgeSource:refresh", "ai/KnowledgeSource:source", - "ai/KnowledgeSource:vectorStore", + "ai/KnowledgeSource:vectorStore [RETIRED]", "ai/KnowledgeSplit:maxChars", "ai/KnowledgeSplit:minChars", "ai/KnowledgeSplit:strategy", @@ -356,7 +353,8 @@ "ai/ModelSelectionCriteria:minContextWindow", "ai/ModelSelectionCriteria:provider", "ai/ModelSelectionCriteria:tags", - "ai/ObjectKnowledgeSource:contentFields", + "ai/ObjectKnowledgeSource:content", + "ai/ObjectKnowledgeSource:contentFields [RETIRED]", "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", @@ -542,11 +540,6 @@ "ai/Tool:protection", "ai/ToolCall:function", "ai/ToolCall:id", - "ai/ToolCall:type", - "ai/VectorStore:collection", - "ai/VectorStore:dimensions", - "ai/VectorStore:endpoint", - "ai/VectorStore:provider", - "ai/VectorStore:secretRef" + "ai/ToolCall:type" ] } diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 1c268ee6298..0932577cb57 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -36,20 +36,16 @@ "ai/DatasetToolCatalogDimension", "ai/DatasetToolCatalogEntry", "ai/DatasetToolCatalogMeasure", - "ai/EmbeddingModel", "ai/FileContent", - "ai/FileKnowledgeSource", "ai/FunctionCall", "ai/GetRecordContextInput", "ai/GetRecordContextOutput", - "ai/HttpKnowledgeSource", "ai/ImageContent", "ai/KnowledgeChunk", "ai/KnowledgeDocument", "ai/KnowledgeHit", "ai/KnowledgeRefreshPolicy", "ai/KnowledgeSource", - "ai/KnowledgeSourceKind", "ai/KnowledgeSplit", "ai/KnowledgeSplitStrategy", "ai/ListDatasetsInput", @@ -101,8 +97,6 @@ "ai/TokenUsageStats", "ai/Tool", "ai/ToolCall", - "ai/TransformPipelineStep", - "ai/VectorStore", - "ai/VectorStoreProvider" + "ai/TransformPipelineStep" ] } diff --git a/packages/spec/scripts/conversions-major18-merge.test.ts b/packages/spec/scripts/conversions-major18-merge.test.ts index 9d6e63e09ed..8c31a21c709 100644 --- a/packages/spec/scripts/conversions-major18-merge.test.ts +++ b/packages/spec/scripts/conversions-major18-merge.test.ts @@ -348,7 +348,13 @@ describe('major 18 in the conversions registry — the shape the merge needs (#2 const ids = new Map(definitionsOf(SOURCE).map((d) => [d.ident, d.id])); expect(order).not.toEqual(IDENTS.map((i) => ids.get(i))); expect(APPLIED).toEqual(order); - expect(ALL_CONVERSIONS.slice(-order.length).map((c) => c.id)).toEqual(order); + // Major 19 opened with its own conversions (#37304), so major 18's are no + // longer the tail of the loader's list: they are one unbroken run of it, + // in this order, with every later major's after them. + const loaded = ALL_CONVERSIONS.map((c) => ({ id: c.id, major: c.toMajor })); + const first = loaded.findIndex((c) => c.major === 18); + expect(loaded.slice(first, first + order.length).map((c) => c.id)).toEqual(order); + expect(loaded.slice(first + order.length).every((c) => c.major > 18)).toBe(true); expect(MIGRATIONS_BY_MAJOR[18]!.conversionIds).toEqual(order); }); diff --git a/packages/spec/scripts/lib/default-changes.ts b/packages/spec/scripts/lib/default-changes.ts index 4aa649575c2..cc6a335a98b 100644 --- a/packages/spec/scripts/lib/default-changes.ts +++ b/packages/spec/scripts/lib/default-changes.ts @@ -797,5 +797,17 @@ export const DEFAULT_CHANGES_BY_MAJOR: Readonly { + const r = KnowledgeSourceSchema.safeParse(input); + expect(r.success, 'the input should be refused').toBe(false); + if (r.success) return []; + return r.error.issues.map((i) => [i.code, i.path.join('.'), i.message]); +} -describe('KnowledgeRefreshPolicySchema.cron — the typed cron slot', () => { - it('positive control: a 5-field cron on a full knowledge source parses and normalizes to the cron envelope', () => { - const r = KnowledgeSourceSchema.safeParse({ ...SOURCE, refresh: { cron: CRON_5_FIELD } }); - expect(r.success, r.success ? '' : JSON.stringify(r.error.issues)).toBe(true); - if (!r.success) return; - expect(r.data.refresh?.cron).toEqual({ dialect: 'cron', source: CRON_5_FIELD }); +describe('KnowledgeSourceSchema — the one schema of the knowledge_source type', () => { + it('positive control: a source parses, with its defaults stated', () => { + const parsed: KnowledgeSourceParsed = KnowledgeSourceSchema.parse(SOURCE); + expect(parsed).toEqual({ + ...SOURCE, + source: { ...SOURCE.source, metadataFields: [] }, + refresh: {}, + aiExposed: true, + }); }); - it('accepts the expression envelope form and passes it through', () => { - const envelope = { dialect: 'cron' as const, source: '@daily' }; - const r = KnowledgeRefreshPolicySchema.safeParse({ cron: envelope }); - expect(r.success).toBe(true); - if (!r.success) return; - expect(r.data.cron).toEqual(envelope); + it('is the schema the metadata-type registry maps `knowledge_source` to — no second schema', () => { + expect(getMetadataTypeSchema('knowledge_source')).toBe(KnowledgeSourceSchema); }); - it('absent stays absent — no `cron` key is fabricated by the parse', () => { - const withEmptyRefresh = KnowledgeSourceSchema.safeParse({ ...SOURCE, refresh: {} }); - expect(withEmptyRefresh.success).toBe(true); - if (withEmptyRefresh.success) expect(withEmptyRefresh.data.refresh?.cron).toBeUndefined(); - - const withoutRefresh = KnowledgeSourceSchema.safeParse(SOURCE); - expect(withoutRefresh.success).toBe(true); - if (withoutRefresh.success) expect(withoutRefresh.data.refresh?.cron).toBeUndefined(); + it('is registered runtime-creatable, versioned, and with no environment overlay (ADR-0161 K4 clause 2)', () => { + const row = DEFAULT_METADATA_TYPE_REGISTRY.find((t) => t.type === 'knowledge_source'); + expect(row).toMatchObject({ + type: 'knowledge_source', + domain: 'ai', + allowRuntimeCreate: true, + allowEnvironmentOverlay: false, + supportsVersioning: true, + filePatterns: ['**/*.knowledge-source.ts', '**/*.knowledge-source.yml'], + }); }); - it.each([['the empty string', ''], ['whitespace only', ' \t']])( - 'refuses a blank string (%s) with ONE `invalid_union` at `refresh.cron` whose message is the cron source-required sentence', - (_label, blank) => { - const r = KnowledgeSourceSchema.safeParse({ ...SOURCE, refresh: { cron: blank } }); - expect(r.success).toBe(false); - if (r.success) return; - expect(r.error.issues.map((i) => [i.code, i.path.join('.'), i.message])).toEqual([ - ['invalid_union', 'refresh.cron', TYPED_EXPRESSION_SOURCE_REQUIRED.cron], + it('is the stack collection `knowledgeSources`, parsed by the same schema', () => { + const ok = ObjectStackDefinitionSchema.safeParse({ knowledgeSources: [SOURCE] }); + expect(ok.success, ok.success ? '' : JSON.stringify(ok.error.issues)).toBe(true); + + const refused = ObjectStackDefinitionSchema.safeParse({ knowledgeSources: [{ ...SOURCE, bogus: 1 }] }); + expect(refused.success).toBe(false); + if (!refused.success) { + expect(refused.error.issues.map((i) => [i.code, i.path.join('.')])).toContainEqual([ + 'unrecognized_keys', + 'knowledgeSources.0', ]); + } + }); +}); + +describe('KnowledgeSourceSchema — strict: an unknown key is refused, not dropped', () => { + it.each([ + ['the source', { ...SOURCE, bogus: 1 }, '', 'this knowledge source'], + ['its `source`', { ...SOURCE, source: { ...SOURCE.source, bogus: 1 } }, 'source', "this knowledge source's `source`"], + ['its `refresh`', { ...SOURCE, refresh: { bogus: 1 } }, 'refresh', 'this refresh policy'], + [ + 'its `split`', + { ...SOURCE, source: { ...SOURCE.source, split: { strategy: 'recursive', bogus: 1 } } }, + 'source.split', + 'this split', + ], + ])('on %s', (_label, input, path, surface) => { + const issues = issuesOf(input); + expect(issues).toHaveLength(1); + const [code, at, message] = issues[0]!; + expect([code, at]).toEqual(['unrecognized_keys', path]); + expect(message).toContain(`Unrecognized key(s) on ${surface}: \`bogus\`.`); + }); + + it('names the key the author most likely meant', () => { + expect(issuesOf({ ...SOURCE, title: 'KB' })[0]![2]).toContain('`title` → `label`'); + expect(issuesOf({ ...SOURCE, source: { ...SOURCE.source, fields: ['title'] } })[0]![2]).toContain( + '`fields` → `content`', + ); + }); +}); + +describe('KnowledgeSourceSchema — the renamed and removed keys are tombstones (ADR-0161 K6)', () => { + const MIGRATE = + 'Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ' + + 'ones it can prove, and you apply the rest by hand.'; + + it.each([ + ['id', { ...SOURCE, id: 'kb_articles' }, 'id', 'use `name`'], + [ + 'source.contentFields', + { ...SOURCE, source: { ...SOURCE.source, contentFields: ['title'] } }, + 'source.contentFields', + 'use `content`', + ], + [ + 'embedding', + { ...SOURCE, embedding: { provider: 'openai', model: 'text-embedding-3-small' } }, + 'embedding', + 'The embedder is configured once for the deployment', + ], + [ + 'vectorStore', + { ...SOURCE, vectorStore: { provider: 'pgvector' } }, + 'vectorStore', + 'The store is the adapter the deployment installs', + ], + [ + 'adapterConfig', + { ...SOURCE, adapterConfig: { datasetId: 'ds_1' } }, + 'adapterConfig', + 'An adapter takes its settings as options of the plugin that mounts it', + ], + [ + 'refresh.cron', + { ...SOURCE, refresh: { cron: '0 3 * * *' } }, + 'refresh.cron', + 'call `reindexSource` from a flow or a job', + ], + ])('`%s` is refused at its own path with its prescription and the migrate sentence', (key, input, path, fix) => { + const issues = issuesOf(input); + expect(issues).toHaveLength(1); + const [code, at, message] = issues[0]!; + expect([code, at]).toEqual(['invalid_type', path]); + expect(message).toContain(`\`knowledge_source.${key}\` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6)`); + expect(message).toContain(fix); + expect(message.endsWith(MIGRATE)).toBe(true); + }); + + it.each(['file', 'http'])('the `%s` kind is refused at `source.kind` with the one-arm prescription', (kind) => { + const issues = issuesOf({ ...SOURCE, source: { kind } }); + const atKind = issues.filter(([, path]) => path === 'source.kind'); + expect(atKind).toHaveLength(1); + expect(atKind[0]![0]).toBe('invalid_value'); + expect(atKind[0]![2]).toContain( + 'The `file` and `http` shapes of `knowledge_source.source` were removed in @objectstack/spec 19.0.0 (ADR-0161 K4)', + ); + expect(atKind[0]![2]).toContain("write `source: { kind: 'object', object, content }`"); + }); + + it.each(['prefix', 'mimeTypes', 'urls', 'userAgent'])( + 'the retired arm key `%s` is refused on an object source, with the same prescription', + (key) => { + const issues = issuesOf({ ...SOURCE, source: { ...SOURCE.source, [key]: 'x' } }); + expect(issues).toHaveLength(1); + expect([issues[0]![0], issues[0]![1]]).toEqual(['unrecognized_keys', 'source']); + expect(issues[0]![2]).toContain(`\`${key}\``); + expect(issues[0]![2]).toContain('The `file` and `http` shapes of `knowledge_source.source` were removed'); }, ); +}); - it('refuses a non-string value with `invalid_union` at `cron`', () => { - const r = KnowledgeRefreshPolicySchema.safeParse({ cron: 42 }); - expect(r.success).toBe(false); - if (r.success) return; - expect(r.error.issues.map((i) => [i.code, i.path.join('.')])).toEqual([['invalid_union', 'cron']]); +describe('KnowledgeSourceSchema — `content` lists fields (ADR-0161 K5)', () => { + it("refuses `'*'` at the member's own path, with the prescription to list the fields", () => { + const issues = issuesOf({ ...SOURCE, source: { ...SOURCE.source, content: ['title', '*'] } }); + expect(issues).toHaveLength(1); + const [code, at, message] = issues[0]!; + expect([code, at]).toEqual(['invalid_format', 'source.content.1']); + expect(message).toContain("the `'*'` member was removed in @objectstack/spec 19.0.0 (ADR-0161 K5)"); + expect(message).toContain("List the fields whose text should be indexed, for example `content: ['title', 'body']`."); }); - it.each([ - ['a dialect the protocol does not declare (`js`, a retired expression dialect, ADR-0058 addendum)', 'js'], - ['a declared dialect that is not this slot\'s (`cel`)', 'cel'], - ])('refuses an envelope naming %s with ONE `invalid_union` at `cron` whose message is the cron dialect-only sentence', (_label, dialect) => { - const r = KnowledgeRefreshPolicySchema.safeParse({ cron: { dialect, source: 'x' } }); - expect(r.success).toBe(false); - if (r.success) return; - expect(r.error.issues.map((i) => [i.code, i.path.join('.'), i.message])).toEqual([ - ['invalid_union', 'cron', TYPED_EXPRESSION_DIALECT_ONLY.cron], + it('refuses an empty list and an absent one', () => { + expect(issuesOf({ ...SOURCE, source: { ...SOURCE.source, content: [] } }).map(([c, p]) => [c, p])).toEqual([ + ['too_small', 'source.content'], + ]); + const { content: _content, ...withoutContent } = SOURCE.source; + expect(issuesOf({ ...SOURCE, source: withoutContent }).map(([c, p]) => [c, p])).toEqual([ + ['invalid_type', 'source.content'], ]); }); - it('does NOT judge cron syntax at parse time — measured, and the describe promises no more (declared = enforced)', () => { - // Nothing evaluates this slot, so no engine ever issues a syntax verdict on - // it: `croner` judges `CronSchedule.expression`, a different slot, and - // `@objectstack/formula`'s registered `cron` engine has no caller outside - // that package. The verdict belongs to whatever external scheduler the - // author hands the value to. The parse only normalizes. If this case - // ever goes red because the shared dialect learned to refuse syntax, update - // the slot's describe in the same commit — do not weaken this pin. - for (const source of ['not a cron', '0 0 3 * * *', '@daily']) { - const r = KnowledgeRefreshPolicySchema.safeParse({ cron: source }); - expect(r.success, `${JSON.stringify(source)} should normalize, not be refused`).toBe(true); - if (r.success) expect(r.data.cron).toEqual({ dialect: 'cron', source }); - } + it("a field whose name merely contains `*` is not the wildcard — only the bare `'*'` member is refused here", () => { + // Whether such a field exists is the admission gate's question, at save + // and at search; the parse refuses the wildcard and nothing else. + expect(KnowledgeSourceSchema.safeParse({ ...SOURCE, source: { ...SOURCE.source, content: ['a*'] } }).success).toBe( + true, + ); + }); +}); + +describe('KnowledgeSourceSchema — `name` takes the router-addressable grammar (ADR-0150 D5)', () => { + it.each(['_internal', 'Kb', 'kb-articles', '9lives', ''])('refuses %j', (name) => { + const issues = issuesOf({ ...SOURCE, name }); + expect(issues.map(([, path]) => path)).toEqual(['name']); }); - it('names both states (ADR-0122): the bare alias is the author state, `XParsed` the parsed state', () => { - // Author state: a bare string is what an author writes. - const authored: KnowledgeRefreshPolicy = { cron: CRON_5_FIELD }; - // Parsed state: the envelope is what a consumer holds after the parse. - const parsed: KnowledgeRefreshPolicyParsed = KnowledgeRefreshPolicySchema.parse(authored); - expect(parsed.cron).toEqual({ dialect: 'cron', source: CRON_5_FIELD }); - // @ts-expect-error — a bare string is the AUTHOR shape, not the parsed one. - const notParsed: KnowledgeRefreshPolicyParsed = { cron: CRON_5_FIELD }; - expect(notParsed).toBeDefined(); - - const parsedSource: KnowledgeSourceParsed = KnowledgeSourceSchema.parse({ ...SOURCE, refresh: { cron: CRON_5_FIELD } }); - expect(parsedSource.refresh?.cron).toEqual({ dialect: 'cron', source: CRON_5_FIELD }); + it('a leading underscore is refused with the reason: the prefix is not an author\'s to take', () => { + expect(issuesOf({ ...SOURCE, name: '_p0123456789abcdef_kb' })[0]![2]).toContain('A leading "_" is reserved'); + }); +}); + +describe('KnowledgeSource — the compiler is the third channel (ADR-0161 K6 item 3)', () => { + it('a TypeScript registration that still writes `id` or `contentFields` does not compile', () => { + const viaId: KnowledgeSource = { + ...SOURCE, + // @ts-expect-error — `id` is a tombstone: its type is `never`. + id: 'kb_articles', + }; + const viaContentFields: KnowledgeSource = { + ...SOURCE, + source: { + ...SOURCE.source, + // @ts-expect-error — `contentFields` is a tombstone: its type is `never`. + contentFields: ['title'], + }, + }; + const viaFileKind: KnowledgeSource = { + ...SOURCE, + // @ts-expect-error — `source.kind` has one arm, `object`. + source: { kind: 'file', object: 'kb_article', content: ['title'] }, + }; + expect([viaId, viaContentFields, viaFileKind]).toHaveLength(3); }); }); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index ae2995a49c7..fcbea5acea6 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -141,7 +141,10 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * fields are never indexed, even when named. */ content: z.array( - z.string().refine((field) => field !== '*', { + // A pattern, not a `.refine()`: the published JSON Schema then refuses + // the member too, so a document validated against the file is not + // refused a release later by the parse. + z.string().regex(/^(?!\*$)/, { message: '`knowledge_source.source.content` lists field names: the `\'*\'` member was removed in @objectstack/spec ' + '19.0.0 (ADR-0161 K5) — embedding is egress, and `\'*\'` sent every text field of the record to the ' diff --git a/packages/spec/src/kernel/metadata-create-seeds.test.ts b/packages/spec/src/kernel/metadata-create-seeds.test.ts index b93b2159c3b..575dd5dad3c 100644 --- a/packages/spec/src/kernel/metadata-create-seeds.test.ts +++ b/packages/spec/src/kernel/metadata-create-seeds.test.ts @@ -91,6 +91,12 @@ describe('metadata create seeds validate against their spec schemas', () => { // (merge question 11). Same category as `sharing_rule`. 'queue', 'assignment_rule', + // [ADR-0161 K4] `knowledge_source` is runtime-creatable, and its create + // seed is deferred work with a name: it lands with the Studio form and + // the MCP create seed (rows 5 and 5b of #37000), which are what would + // serve one. Until then a source is created by a `/meta` save or shipped + // in a package, never from a blank form. + 'knowledge_source', ]); const seeded = new Set(listMetadataCreateSeedTypes()); const missing = listMetadataTypeSchemaTypes().filter((t) => !seeded.has(t) && !KNOWN_UNSEEDED.has(t)); diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts index be7716f703f..55395ec1a90 100644 --- a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts @@ -23,7 +23,7 @@ export const entry: SemanticMigration = { + 'the source was written included. Each field in `content` is sent, for every record the source selects, ' + 'to the embedding provider the deployment configures, so the list is a statement of what leaves the ' + 'deployment, and a wildcard states nothing. The parse now refuses the member and names the fix; ' - + '`os migrate meta --from 18` renames the key, keeps the member and reports the site as a hand edit. ' + + 'the chain replay renames the key, keeps the member and reports the site as a hand edit. ' + 'Which fields to list is known only to the source\'s author: the ones users search by, and none that ' + 'should not be sent to the provider.', acceptanceCriteria: diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-registration-governed.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-registration-governed.ts new file mode 100644 index 00000000000..6b543824135 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-registration-governed.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0161 K4 (points 1 and 3) and K6 — the D3 entry of what changes for a +// knowledge source registered in code once the same shape is a governed +// metadata type. The D2 conversion `knowledge-source-id-to-name` renames the +// one key the door's identity turned on; the rest is a narrowing of what the +// door accepts and of what a second registration does, which no conversion +// over one stack can repair. The holder of a code registration and the reading +// of a name in code are ruling 7192063608 on #37304 (ADR-0150 addendum of +// 2026-11-25, points 4 and 6). +export const entry: SemanticMigration = { + id: 'knowledge-source-registration-governed', + surface: + 'A knowledge source registered in code: `KnowledgeServicePlugin({ sources })` and ' + + '`IKnowledgeService.registerSource(source)`; the source ids code passes to `getSource`, ' + + '`unregisterSource`, `reindexSource` and `search`\'s `sourceIds`; and the `sourceId` on the hits ' + + '`search` returns', + replacement: + 'Write the source in the shape of the `knowledge_source` type: `name` where `id` stood, a name that ' + + 'starts with a letter, and no key the type does not declare. Prefer shipping it as metadata, in the ' + + 'stack\'s `knowledgeSources`. Give a source registered in code a name no source authored in the ' + + 'environment uses. Where a package ships a source of the same name, name the package\'s source by its ' + + 'face `NAMESPACE-NAME` and the one registered in code by its bare name.', + reason: + 'Before this release the code door stored what it was given: a key the schema did not declare was ' + + 'kept and ignored, an id could start with an underscore, and a second registration of an id replaced ' + + 'the first with a warning. The door now parses with the type\'s one schema, so each of those is ' + + 'refused when the source is registered, with the parse\'s own prescription; the D2 conversion renames ' + + '`id` in a stack, and a TypeScript registration that still writes it does not compile. A source ' + + 'registered in code belongs to no package: it is read as the environment\'s own source and keeps its ' + + 'name, its index and its documents, so nothing is rebuilt. It shares one slot with a source of the same ' + + 'name authored in the environment, and whichever of the two arrives second is refused (409 ' + + 'RESOURCE_CONFLICT, naming both doors) instead of replacing the first; registering the same name again ' + + 'through the code door still replaces the earlier registration. A package may ship a source of that ' + + 'name too, and both are kept: a bare name then means the one registered in code, and the package\'s is ' + + 'named by its face. A hit\'s `sourceId` is that same spelling, so it is no longer always the bare name. ' + + 'Whether a key the door used to ignore stated something the author still wants, and which of two ' + + 'same-named sources a caller meant, only the application\'s author knows.', + acceptanceCriteria: + 'Every source the application registers in code parses with `KnowledgeSourceSchema` and the application ' + + 'boots with no refusal from the knowledge service. No source registered in code shares its name with a ' + + 'source authored in the environment. Code that compares a hit\'s `sourceId`, or passes a source id to ' + + 'the knowledge service, uses the spelling `search_knowledge` lists for that source. A search that ' + + 'answered before the upgrade answers the same records after it, without a rebuild.', + conversionIds: ['knowledge-source-id-to-name'], +}; diff --git a/packages/spec/src/stack-collection-item-owner-stamp.test.ts b/packages/spec/src/stack-collection-item-owner-stamp.test.ts index a5b4a1aca15..edd4e013e7c 100644 --- a/packages/spec/src/stack-collection-item-owner-stamp.test.ts +++ b/packages/spec/src/stack-collection-item-owner-stamp.test.ts @@ -243,6 +243,9 @@ const JUDGED_FIXTURES: Record = T; import type * as M0 from './ai/agent.zod.js'; import type * as M1 from './ai/conversation.zod.js'; -import type * as M2 from './ai/embedding.zod.js'; import type * as M3 from './ai/knowledge-document.zod.js'; import type * as M4 from './ai/knowledge-source.zod.js'; import type * as M5 from './ai/mcp.zod.js'; @@ -306,7 +305,7 @@ import type * as M205 from './ai/object-query-source.zod.js'; import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 887 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -399,10 +398,6 @@ export type Iso_ai_datasetTools__QueryDatasetOutputSchema = Assert, z.infer< typeof M205.ObjectQuerySourceSchema > >>; -// ai/embedding.zod.ts -export type Iso_ai_embedding__EmbeddingModelSchema = Assert, z.infer< typeof M2.EmbeddingModelSchema > >>; -export type Iso_ai_embedding__VectorStoreProviderSchema = Assert, z.infer< typeof M2.VectorStoreProviderSchema > >>; -export type Iso_ai_embedding__VectorStoreSchema = Assert, z.infer< typeof M2.VectorStoreSchema > >>; // ai/knowledge-document.zod.ts export type Iso_ai_knowledgeDocument__KnowledgeChunkSchema = Assert, z.infer< typeof M3.KnowledgeChunkSchema > >>; @@ -410,9 +405,6 @@ export type Iso_ai_knowledgeDocument__KnowledgeDocumentSchema = Assert, z.infer< typeof M3.KnowledgeHitSchema > >>; // ai/knowledge-source.zod.ts -export type Iso_ai_knowledgeSource__FileKnowledgeSourceSchema = Assert, z.infer< typeof M4.FileKnowledgeSourceSchema > >>; -export type Iso_ai_knowledgeSource__HttpKnowledgeSourceSchema = Assert, z.infer< typeof M4.HttpKnowledgeSourceSchema > >>; -export type Iso_ai_knowledgeSource__KnowledgeSourceKindSchema = Assert, z.infer< typeof M4.KnowledgeSourceKindSchema > >>; export type Iso_ai_knowledgeSource__ObjectKnowledgeSourceSchema = Assert, z.infer< typeof M4.ObjectKnowledgeSourceSchema > >>; // ai/mcp.zod.ts @@ -1866,7 +1858,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 887 isomorphic pins', () => { + it('still declares all 881 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2991,7 +2983,14 @@ describe('ADR-0122 type-alias convention', () => { // (`ActionSchema`), both of which carry defaults, so the response gained a // parsed shape and takes `GetMetaTypesResponseParsed` instead // (Iso_api_protocol__GetMetaTypesResponseSchema removed). -1. - expect(pins).toHaveLength(887); + // 887 -> 881 is #37304 (ADR-0161 K4, K6): the knowledge source's `file` + // and `http` kinds leave with the union they sat in + // (Iso_ai_knowledgeSource__FileKnowledgeSourceSchema, + // __HttpKnowledgeSourceSchema, __KnowledgeSourceKindSchema), and + // `ai/embedding.zod.ts` leaves whole, its only composer having been the + // removed `embedding` and `vectorStore` keys (Iso_ai_embedding__*, three + // pins; RETIRED_DEFS_BY_MAJOR[19]). -6. + expect(pins).toHaveLength(881); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From 95758981f3ca7ce0d4c723ef20903b8a3e68788a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:03:18 +0000 Subject: [PATCH 03/29] feat(service-knowledge): load knowledge_source items, one slot per (package, name) The knowledge service keeps its sources in a registry keyed by (package, name) and filled through two doors that parse with the one schema: the metadata loader (boot, a published knowledge_source change, a metadata reload) and registration in code, which takes the package-less slot and refuses a retired key with its prescription instead of converting it. A caller names a source by its face; a bare name resolves by ADR-0150 D3 and a name several sources answer to is refused 409. An index is keyed by the source's index key, so two packages' sources of one name share no document. A removed item is unregistered and its index dropped; the reap guard's object set follows the sources. The file/http arms, the '*' content member, indexDocument and deleteDocument are gone with their branches. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../src/__tests__/chunk-channel.test.ts | 25 +- .../src/__tests__/contract-stubs.test.ts | 12 +- .../__tests__/event-sync-data-events.test.ts | 4 +- .../src/__tests__/index-fingerprint.test.ts | 8 +- .../src/__tests__/knowledge-build.test.ts | 14 +- .../__tests__/knowledge-search-scope.test.ts | 8 +- .../src/__tests__/knowledge-service.test.ts | 249 ++---- .../knowledge-settings-contribution.test.ts | 50 +- .../knowledge-source-admission.test.ts | 44 +- .../__tests__/knowledge-source-loader.test.ts | 407 +++++++++ .../knowledge-source-registry.test.ts | 346 ++++++++ .../src/__tests__/knowledge-tools.test.ts | 61 +- .../src/__tests__/reap-guard.test.ts | 75 +- .../services/service-knowledge/src/index.ts | 3 + .../src/knowledge-build-actions.ts | 66 +- .../service-knowledge/src/knowledge-build.ts | 12 +- .../src/knowledge-index-fingerprint.ts | 26 +- .../src/knowledge-reap-guard.ts | 24 +- .../src/knowledge-search-scope.ts | 3 +- .../src/knowledge-service-plugin.ts | 240 +++++- .../src/knowledge-service.ts | 770 +++++++++++------- .../src/knowledge-source-admission.ts | 28 +- .../src/knowledge-source-loader.ts | 259 ++++++ .../src/knowledge-source-registry.ts | 307 +++++++ .../service-knowledge/src/knowledge-tools.ts | 94 ++- .../services/service-knowledge/src/testing.ts | 273 ++++--- 26 files changed, 2537 insertions(+), 871 deletions(-) create mode 100644 packages/services/service-knowledge/src/__tests__/knowledge-source-loader.test.ts create mode 100644 packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts create mode 100644 packages/services/service-knowledge/src/knowledge-source-loader.ts create mode 100644 packages/services/service-knowledge/src/knowledge-source-registry.ts diff --git a/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts b/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts index de707287a57..962d2e0ca89 100644 --- a/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts +++ b/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts @@ -6,7 +6,7 @@ * * - the event path removes a `whole` document over the embedder's budget and * reports it at `error`, naming the source, the record, the estimate and the - * limit; `indexDocument` removes it and throws; + * limit; * - a reindex names at most `MAX_REINDEX_FAILURES` failures and counts them all; * - `maxChars` comes from the source's `split.maxChars`, else the settings * page's `knowledge.chunk_target` (read through the real settings service), @@ -15,7 +15,7 @@ import { describe, expect, it, vi } from 'vitest'; import { LiteKernel } from '@objectstack/core'; -import type { AdapterContext, IDataEngine, IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts'; +import type { AdapterContext, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, KnowledgeSplit } from '@objectstack/spec/ai'; import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; import { SettingsServicePlugin, type SettingsService } from '@objectstack/service-settings'; @@ -43,10 +43,10 @@ function recordingAdapter(limit?: { maxInputTokens?: number }) { function source(split?: KnowledgeSplit): KnowledgeSource { return { - id: 'kb', + name: 'kb', label: 'kb', adapter: 'rec', - source: { kind: 'object', object: 'article', contentFields: ['body'], ...(split ? { split } : {}) }, + source: { kind: 'object', object: 'article', content: ['body'], ...(split ? { split } : {}) }, } as KnowledgeSource; } @@ -121,17 +121,6 @@ describe('chunk channel — whole over the budget', () => { expect(upserted[0].chunks).toEqual([{ id: 'kb:r1#0', documentId: 'kb:r1', index: 0, content: LONG }]); }); - it('indexDocument removes it and throws, naming the estimate and the budget', async () => { - const { adapter, upserted, deleted } = recordingAdapter({ maxInputTokens: 512 }); - const svc = new KnowledgeService({ logger: { warn: vi.fn() } }); - svc.registerAdapter('rec', adapter); - svc.registerSource(source({ strategy: 'whole' })); - await expect(svc.indexDocument('kb', { id: 'kb:x', sourceId: 'kb', content: LONG })) - .rejects.toThrow(/did not index document 'kb:x' and removed it from the index: the whole document estimates \d+ tokens, over the embedder's input budget of 409/); - expect(upserted).toEqual([]); - expect(deleted).toEqual(['kb:x']); - }); - it(`a reindex counts every failure and names the first ${MAX_REINDEX_FAILURES}`, async () => { const { adapter, upserted } = recordingAdapter({ maxInputTokens: 512 }); const rows = Array.from({ length: MAX_REINDEX_FAILURES + 5 }, (_, i) => ({ id: `r${String(i).padStart(2, '0')}`, body: LONG })); @@ -209,17 +198,17 @@ describe('chunk channel — what the split is resolved from, read at use', () => kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false })); await kernel.bootstrap(); const settings = kernel.getService('settings'); - const svc = kernel.getService(KNOWLEDGE_SERVICE); + const svc = kernel.getService(KNOWLEDGE_SERVICE); const { adapter, upserted } = recordingAdapter(undefined); svc.registerAdapter('rec', adapter); svc.registerSource(source({ strategy: 'recursive', minChars: 100_000 })); - await svc.indexDocument('kb', { id: 'kb:a', sourceId: 'kb', content: LONG.repeat(3) }); + await svc.handleRecordUpsert('article', { id: 'a', body: LONG.repeat(3) }); expect(Math.max(...lengths(upserted))).toBeGreaterThan(640); // 800, nothing stored upserted.length = 0; // Saved after boot: the next write is cut by it. await settings.set('knowledge', 'chunk_target', 200); - await svc.indexDocument('kb', { id: 'kb:a', sourceId: 'kb', content: LONG.repeat(3) }); + await svc.handleRecordUpsert('article', { id: 'a', body: LONG.repeat(3) }); expect(Math.max(...lengths(upserted))).toBeLessThanOrEqual(200); await kernel.shutdown(); }); diff --git a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts index 31aea0f60f6..f45a932cee8 100644 --- a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts +++ b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts @@ -51,7 +51,7 @@ function rank(passages: Passage[], query: string, opts: AdapterSearchOptions): K .map(({ p, score }) => ({ chunkId: p.chunkId, documentId: p.documentId, - sourceId: opts.source.id, + sourceId: opts.source.name, sourceRecordId: p.sourceRecordId, score, snippet: p.text, @@ -69,7 +69,7 @@ class StubAdapter implements IKnowledgeAdapter { } async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { - const byDoc = this.store.get(ctx.source.id) ?? new Map(); + const byDoc = this.store.get(ctx.source.name) ?? new Map(); for (const doc of docs) { if (this.capabilities?.chunks) { if (doc.chunks === undefined) throw new Error(`chunk-stub: document '${doc.id}' arrived without chunks`); @@ -85,15 +85,15 @@ class StubAdapter implements IKnowledgeAdapter { byDoc.set(doc.id, [{ chunkId: `${doc.id}#0`, documentId: doc.id, sourceRecordId: doc.sourceRecordId, text: doc.content }]); } } - this.store.set(ctx.source.id, byDoc); + this.store.set(ctx.source.name, byDoc); } async search(query: string, opts: AdapterSearchOptions): Promise { - return rank([...(this.store.get(opts.source.id)?.values() ?? [])].flat(), query, opts); + return rank([...(this.store.get(opts.source.name)?.values() ?? [])].flat(), query, opts); } async delete(documentIds: string[], ctx: AdapterContext): Promise { - const byDoc = this.store.get(ctx.source.id); + const byDoc = this.store.get(ctx.source.name); for (const id of documentIds) byDoc?.delete(id); } } @@ -110,6 +110,7 @@ runKnowledgeAdapterContract({ refusesOtherFingerprint: false, generations: false, scope: false, + dropSource: false, }, }); @@ -125,5 +126,6 @@ runKnowledgeAdapterContract({ refusesOtherFingerprint: false, generations: false, scope: false, + dropSource: false, }, }); diff --git a/packages/services/service-knowledge/src/__tests__/event-sync-data-events.test.ts b/packages/services/service-knowledge/src/__tests__/event-sync-data-events.test.ts index 8e58022f5e3..7f425f48fc6 100644 --- a/packages/services/service-knowledge/src/__tests__/event-sync-data-events.test.ts +++ b/packages/services/service-knowledge/src/__tests__/event-sync-data-events.test.ts @@ -179,13 +179,13 @@ const DRAFT: Row = { ...PUBLISHED, body: 'Draft wording, not yet approved', stat function source(where?: Record): KnowledgeSource { return { - id: 'kb', + name: 'kb', label: 'Knowledge base', adapter: 'memory', source: { kind: 'object', object: 'kb_article', - contentFields: ['title', 'body'], + content: ['title', 'body'], ...(where ? { where } : {}), }, }; diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 34f1589684a..cd43283b192 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -20,10 +20,10 @@ import { SPLIT_ALGORITHM_VERSION, resolveSplit } from '../split/index.js'; const source = (extra: Record = {}): KnowledgeSource => ({ - id: 'kb_articles', + name: 'kb_articles', label: 'Articles', adapter: 'pgvector', - source: { kind: 'object', object: 'article', contentFields: ['title', 'body'], metadataFields: ['status'], ...extra }, + source: { kind: 'object', object: 'article', content: ['title', 'body'], metadataFields: ['status'], ...extra }, }) as KnowledgeSource; const embedding = { model: 'text-embedding-3-large', dimensions: 3072, maxInputTokens: 8191 }; @@ -47,7 +47,7 @@ describe('index fingerprint (ADR-0161 K7)', () => { computeIndexFingerprint({ source: source(), embedding, split: { ...split, maxChars: 400 } }), computeIndexFingerprint({ source: source(), embedding, split: { ...split, strategy: 'recursive' } }), computeIndexFingerprint({ source: source(), embedding }), - computeIndexFingerprint({ source: source({ contentFields: ['body', 'title'] }), embedding, split }), + computeIndexFingerprint({ source: source({ content: ['body', 'title'] }), embedding, split }), computeIndexFingerprint({ source: source({ object: 'faq' }), embedding, split }), ]; for (const v of variants) expect(v).not.toBe(base); @@ -89,6 +89,6 @@ describe('recipe hash (ADR-0161 K7)', () => { }); it('does not change with the content list, which is the fingerprint\'s', () => { - expect(computeRecipeHash({ source: source({ contentFields: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); + expect(computeRecipeHash({ source: source({ content: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); }); }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts index c1fa414b8d0..65b55814097 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts @@ -126,10 +126,10 @@ function makeAdapter(opts: { embedding?: AdapterEmbeddingDescriptor; omit?: Arra function source(overrides: Partial = {}, where?: Record): KnowledgeSource { return { - id: 'kb', + name: 'kb', label: 'Knowledge base', adapter: 'memory', - source: { kind: 'object', object: 'kb_article', contentFields: ['title', 'body'], ...(where ? { where } : {}) }, + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'], ...(where ? { where } : {}) }, ...overrides, }; } @@ -251,18 +251,16 @@ describe('readIndexState — the states of ADR-0161 K7 "What starts a rebuild"', expect(reading.detail).toContain('os knowledge rebuild'); }); - it('a failed read is unreadable and not due; a file source is not built here', async () => { + it('a failed read is unreadable and not due', async () => { const db = makeEngine(ROWS); const { adapter } = makeAdapter(); adapter.indexStatus = async () => { throw new Error('store offline'); }; const { service } = makeService(db.engine, adapter); service.registerSource(source()); - service.registerSource({ id: 'files', label: 'Files', adapter: 'memory', source: { kind: 'file', paths: ['docs/*.md'] } } as unknown as KnowledgeSource); const reading = await service.readIndexState('kb'); expect(reading).toMatchObject({ state: 'unreadable', due: false }); expect(reading.detail).toContain('store offline'); - expect(await service.readIndexState('files')).toMatchObject({ state: 'not-built-here', due: false }); }); it('a first build that opened a generation and never completed it reads as nothing built, not another fingerprint', async () => { @@ -284,7 +282,7 @@ describe('buildSourcesAtBoot — the first build', () => { const { adapter, calls } = makeAdapter(); const { service, logger } = makeService(db.engine, adapter); service.registerSource(source()); - vi.spyOn(service, 'listSources').mockImplementation(() => { throw new Error('registry torn down'); }); + vi.spyOn((service as unknown as { registry: { entries(): unknown[] } }).registry, 'entries').mockImplementation(() => { throw new Error('registry torn down'); }); await expect(service.buildSourcesAtBoot()).resolves.toBeUndefined(); expect(calls.upserted).toBe(0); @@ -461,12 +459,11 @@ describe('the rebuild and index_status settings actions', () => { await vi.waitFor(() => expect(service.buildRecord('kb')?.status).toBe('done')); }); - it('refuses a payload key other than source, a missing source, an unknown one and a file source', async () => { + it('refuses a payload key other than source, a missing source and an unknown one', async () => { const db = makeEngine(ROWS); const { adapter, calls } = makeAdapter(); const { service } = makeService(db.engine, adapter); service.registerSource(source()); - service.registerSource({ id: 'files', label: 'Files', adapter: 'memory', source: { kind: 'file', paths: ['docs/*.md'] } } as unknown as KnowledgeSource); const rebuild = knowledgeRebuildActionHandler(service); const status = knowledgeIndexStatusActionHandler(service); @@ -477,7 +474,6 @@ describe('the rebuild and index_status settings actions', () => { expect(await run(rebuild, {})).toMatchObject({ ok: false }); expect(await run(rebuild, { source: 'nope' })).toMatchObject({ ok: false }); expect(await run(status, { source: 'nope' })).toMatchObject({ ok: false }); - expect(await run(rebuild, { source: 'files' })).toMatchObject({ ok: false }); expect(calls.upserted).toBe(0); }); }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts index 80bd1a34aa8..66884553136 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts @@ -68,10 +68,10 @@ describe('readSearchScope — the bounds, before any adapter is called', () => { /** A clause source over `clause` that lists `fields` as metadata. */ function clauseSource(fields: string[]): KnowledgeSource { return { - id: 'clauses', + name: 'clauses', label: 'Clauses', adapter: 'memory', - source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: fields } as ObjectKnowledgeSource, + source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: fields } as ObjectKnowledgeSource, } as KnowledgeSource; } @@ -174,10 +174,6 @@ describe('scopeTermsFor — the terms a source is handed', () => { expect(scopeTermsFor(source, [{ object: 'clause', ids: [] }, { object: 'policy', ids: [] }], schemaOf()).terms).toEqual([]); }); - it('a file or http source is handed no term: it answers nothing under a scope', () => { - const file = { id: 'handbook', label: 'Handbook', adapter: 'memory', source: { kind: 'file', paths: ['a.md'] } } as unknown as KnowledgeSource; - expect(scopeTermsFor(file, [{ object: 'clause', ids: ['c1'] }], schemaOf()).terms).toEqual([]); - }); }); describe('scopeCheck — every hit, after the adapter answers', () => { diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 271434ea6fc..c504053239a 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -49,13 +49,13 @@ function makeAdapter(id: string, hits: KnowledgeHit[] = []): IKnowledgeAdapter & function objectSource(id: string, object: string, adapter = 'memory'): KnowledgeSource { return { - id, + name: id, label: id, adapter, source: { kind: 'object', object, - contentFields: ['title', 'notes'], + content: ['title', 'notes'], metadataFields: ['status'], } as ObjectKnowledgeSource, }; @@ -75,44 +75,13 @@ describe('KnowledgeService — adapter & source registry', () => { const svc = new KnowledgeService(); const s = objectSource('s1', 'task'); svc.registerSource(s); - expect(svc.getSource('s1')).toEqual(s); + // The source as parsed: what the author wrote, with the schema's defaults stated. + expect(svc.getSource('s1')).toEqual({ ...s, refresh: {}, aiExposed: true }); expect(svc.listSources()).toHaveLength(1); svc.unregisterSource('s1'); expect(svc.getSource('s1')).toBeUndefined(); }); - it('indexDocument / deleteDocument route to the right adapter', async () => { - const svc = new KnowledgeService(); - const a = makeAdapter('memory'); - svc.registerAdapter('memory', a); - svc.registerSource(objectSource('s1', 'task')); - const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello' }; - await svc.indexDocument('s1', doc); - // The service computes `docHash` and stamps it on the document it hands the adapter. - expect(a.upsertSpy).toHaveBeenCalledWith( - [{ ...doc, docHash: computeDocHash(doc) }], - expect.objectContaining({ reason: 'manual' }), - ); - await svc.deleteDocument('s1', 'd1'); - expect(a.deleteSpy).toHaveBeenCalledWith(['d1'], expect.objectContaining({ reason: 'manual' })); - }); - - it('indexDocument refuses a caller-supplied docHash, naming it, and writes nothing', async () => { - const svc = new KnowledgeService(); - const a = makeAdapter('memory'); - svc.registerAdapter('memory', a); - svc.registerSource(objectSource('s1', 'task')); - const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello', docHash: 'v1:caller-supplied' }; - await expect(svc.indexDocument('s1', doc)).rejects.toThrow( - /indexDocument refused document 'd1': docHash is computed by the knowledge service/, - ); - expect(a.upsertSpy).not.toHaveBeenCalled(); - }); - - it('indexDocument throws on unknown source', async () => { - const svc = new KnowledgeService(); - await expect(svc.indexDocument('nope', { id: 'd', sourceId: 'nope', content: '' })).rejects.toThrow(/unknown source/); - }); }); describe('KnowledgeService — permission-aware search', () => { @@ -145,24 +114,6 @@ describe('KnowledgeService — permission-aware search', () => { expect(findSpy).not.toHaveBeenCalled(); // dropped without a lookup }); - it('keeps file/http hits but drops object hits when no executionContext (#2981)', async () => { - // The fail-closed drop is scoped to record-backed hits; ACL-less - // file/http hits still flow (their adapter owns any enforcement). - const hits: KnowledgeHit[] = [ - { chunkId: 'c1', documentId: 'd1', sourceId: 's1', sourceRecordId: 'rec_1', score: 0.9, snippet: '' }, - { chunkId: 'c2', documentId: 'd2', sourceId: 'http_src', score: 0.5, snippet: 'web' }, - ]; - const { svc } = buildSetup(hits); - // The fixture's http hit names a source, so the source is registered: a - // hit is served only as a registered source it was searched for. - svc.registerSource({ - id: 'http_src', label: 'HTTP', adapter: 'memory', - source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); - const out = await svc.search('q'); - expect(out.map((h) => h.documentId)).toEqual(['d2']); - }); - it('passes through every hit when context is isSystem:true', async () => { const hits: KnowledgeHit[] = [ { chunkId: 'c1', documentId: 'd1', sourceId: 's1', sourceRecordId: 'rec_1', score: 0.9, snippet: '' }, @@ -190,43 +141,6 @@ describe('KnowledgeService — permission-aware search', () => { expect(opts.where).toEqual({ id: { $in: ['rec_1', 'rec_2'] } }); }); - it('keeps hits without sourceRecordId (file/http) regardless of RLS', async () => { - const hits: KnowledgeHit[] = [ - { chunkId: 'c1', documentId: 'd1', sourceId: 'http_src', score: 0.5, snippet: 'web' }, - ]; - const adapter = makeAdapter('memory', hits); - const engine = { find: vi.fn(async () => []) } as unknown as IDataEngine; - const svc = new KnowledgeService({ dataEngine: engine }); - svc.registerAdapter('memory', adapter); - svc.registerSource({ - id: 'http_src', label: 'HTTP', adapter: 'memory', - source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); - const out = await svc.search('q', { - executionContext: { userId: 'u1', positions: [], permissions: [], isSystem: false }, - }); - expect(out).toHaveLength(1); - }); - - it('without dataEngine, drops object-source hits but keeps file/http hits', async () => { - const adapter = makeAdapter('memory'); - adapter.search = vi.fn(async (_q, opts) => { - if (opts.source.id === 's1') { - return [{ chunkId: 'c1', documentId: 'd1', sourceId: 's1', sourceRecordId: 'rec_1', score: 0.9, snippet: '' }]; - } - return [{ chunkId: 'c2', documentId: 'd2', sourceId: 'http', score: 0.5, snippet: 'web' }]; - }); - const svc = new KnowledgeService(); - svc.registerAdapter('memory', adapter); - svc.registerSource(objectSource('s1', 'task')); - svc.registerSource({ - id: 'http', label: 'HTTP', adapter: 'memory', - source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); - const out = await svc.search('q', { executionContext: { userId: 'u', positions: [], permissions: [], isSystem: false } }); - expect(out.map((h) => h.documentId)).toEqual(['d2']); - }); - it('topK honoured + hits sorted by score desc', async () => { const adapter = makeAdapter('memory', [ { chunkId: 'c1', documentId: 'd1', sourceId: 's1', score: 0.3, snippet: '' }, @@ -250,7 +164,7 @@ describe('KnowledgeService — permission-aware search', () => { await svc.search('q', { sourceIds: ['s2'], executionContext: { positions: [], permissions: [], isSystem: true } }); expect(a.searchSpy).toHaveBeenCalledOnce(); const callArg = a.searchSpy.mock.calls[0][1] as { source: KnowledgeSource }; - expect(callArg.source.id).toBe('s2'); + expect(callArg.source.name).toBe('s2'); }); }); @@ -333,9 +247,9 @@ describe('KnowledgeService — reindex', () => { }); it("a refusal's remedy (operator text) reaches the warn log, never refused[].message or the thrown message", async () => { - const http = (id: string, adapter: string): KnowledgeSource => ({ - id, label: id, adapter, source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); + const over = (name: string, adapter: string): KnowledgeSource => objectSource(name, 'task', adapter); + // The system identity: a source is searched for it with no engine to re-check with. + const asSystem = { positions: [], permissions: [], isSystem: true }; const remedy = 'Run as a database owner:\nDELETE FROM "os_knowledge"."knowledge_generation" WHERE source_id = \'refusing\';'; const refusing = Object.assign(makeAdapter('refusing'), { search: vi.fn(async () => { @@ -349,11 +263,11 @@ describe('KnowledgeService — reindex', () => { const svc = new KnowledgeService({ logger: { warn } as never }); svc.registerAdapter('refusing', refusing); svc.registerAdapter('answering', answering); - svc.registerSource(http('refusing', 'refusing')); - svc.registerSource(http('answering', 'answering')); + svc.registerSource(over('refusing', 'refusing')); + svc.registerSource(over('answering', 'answering')); // Some sources answer: the refused one is named, its message alone. - const report = await svc.searchWithRefusals('q'); + const report = await svc.searchWithRefusals('q', { executionContext: asSystem }); expect(report.hits.map((h) => h.documentId)).toEqual(['d1']); expect(report.refused).toEqual([ { sourceId: 'refusing', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, message: "Knowledge source 'refusing' needs a rebuild." }, @@ -361,7 +275,7 @@ describe('KnowledgeService — reindex', () => { expect(warn.mock.calls.some(([line]) => String(line).includes('DELETE FROM'))).toBe(true); // None answers: the thrown refusal carries no remedy either. - const thrown = await svc.searchWithRefusals('q', { sourceIds: ['refusing'] }).then( + const thrown = await svc.searchWithRefusals('q', { sourceIds: ['refusing'], executionContext: asSystem }).then( () => undefined, (e: unknown) => e as { code?: string; message: string; refused?: Array<{ message: string }> }, ); @@ -429,17 +343,6 @@ describe('KnowledgeService — reindex', () => { expect(res.message).toMatch(/IDataEngine/); }); - it('returns ok:false for non-object sources (delegates to adapter)', async () => { - const svc = new KnowledgeService({ dataEngine: { find: vi.fn() } as unknown as IDataEngine }); - svc.registerAdapter('memory', makeAdapter('memory')); - svc.registerSource({ - id: 'http', label: 'HTTP', adapter: 'memory', - source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); - const res = await svc.reindexSource('http'); - expect(res.ok).toBe(false); - expect(res.message).toMatch(/adapter/); - }); }); describe('Pure helpers', () => { @@ -447,7 +350,7 @@ describe('Pure helpers', () => { expect(documentIdFor('s', 'r')).toBe('s:r'); }); - it('recordToDocument concatenates contentFields and projects metadataFields', () => { + it('recordToDocument concatenates content and projects metadataFields', () => { const src = objectSource('s1', 'task'); const objSrc = src.source as ObjectKnowledgeSource; const doc = recordToDocument(src, objSrc, { id: 'r1', title: 'Hello', notes: 'World', status: 'open' }); @@ -457,23 +360,21 @@ describe('Pure helpers', () => { expect(doc.metadata?.status).toBe('open'); }); - it('recordToDocument supports * for contentFields', () => { + it('recordToDocument reads the listed fields, in the listed order, and no other field', () => { const src: KnowledgeSource = { - id: 's1', label: 'all', adapter: 'memory', - source: { kind: 'object', object: 'task', contentFields: ['*'] } as ObjectKnowledgeSource, + name: 's1', label: 'listed', adapter: 'memory', + source: { kind: 'object', object: 'task', content: ['notes', 'title'] }, }; - const objSrc = src.source as ObjectKnowledgeSource; - const doc = recordToDocument(src, objSrc, { id: 'r1', title: 'A', notes: 'B', count: 7 }); - expect(doc.content).toContain('A'); - expect(doc.content).toContain('B'); - expect(doc.content).not.toContain('r1'); // id excluded + const doc = recordToDocument(src, src.source, { id: 'r1', title: 'A', notes: 'B', private_note: 'C', count: 7 }); + expect(doc.content).toBe('B\n\nA'); + expect(JSON.stringify(doc)).not.toContain('C'); }); }); // An index document is searchable text served to every reader its source // admits, so it never carries a credential-class field (the set the engine -// masks on read) or an `internal: true` field (the set it omits) — under `*`, -// or when a source names one explicitly. The field sets come from the same +// masks on read) or an `internal: true` field (the set it omits), even when a +// source names one. The field sets come from the same // collectors the write-response helper uses. Synthetic values. describe('recordToDocument withholds credential-class and internal fields', () => { const CREDENTIAL = 'synthetic-credential-a27f'; @@ -493,17 +394,9 @@ describe('recordToDocument withholds credential-class and internal fields', () = id: 'r1', title: 'Visible', notes: 'Body', api_token: CREDENTIAL, passphrase: `${CREDENTIAL}-p`, lookup_digest: INTERNAL, }); - const source = (contentFields: string[], metadataFields: string[] = []): KnowledgeSource => ({ - id: 's1', label: 's1', adapter: 'memory', - source: { kind: 'object', object: 'probe_doc', contentFields, metadataFields } as ObjectKnowledgeSource, - }); - - it("skips them under '*'", () => { - const src = source(['*']); - const doc = recordToDocument(src, src.source as ObjectKnowledgeSource, record(), schema); - expect(doc.content).toBe('Visible\n\nBody'); - expect(JSON.stringify(doc)).not.toContain(CREDENTIAL); - expect(JSON.stringify(doc)).not.toContain(INTERNAL); + const source = (content: string[], metadataFields: string[] = []): KnowledgeSource => ({ + name: 's1', label: 's1', adapter: 'memory', + source: { kind: 'object', object: 'probe_doc', content, metadataFields } as ObjectKnowledgeSource, }); it('skips them when named explicitly as content or metadata', () => { @@ -519,9 +412,9 @@ describe('recordToDocument withholds credential-class and internal fields', () = // source's `where` decides membership), and that row carries every column — // the payload here carries only the id. The re-read row goes through the same // gate as the reindex walk, so a withheld field stays out of the document - // whether the source takes `'*'` or names it. + // when the source names it. it.each([ - ["'*'", ['*'], [] as string[], 'Visible\n\nBody', {}], + ['named as content only', ['title', 'notes', 'api_token'], [] as string[], 'Visible\n\nBody', {}], ['named explicitly', ['title', 'api_token', 'lookup_digest'], ['passphrase', 'notes'], 'Visible', { notes: 'Body' }], ])('the event-sync path withholds them from the re-read row (%s)', async (_label, content, meta, text, metadata) => { const getSchema = vi.fn((name: string) => (name === 'probe_doc' ? schema : undefined)); @@ -547,7 +440,7 @@ describe('recordToDocument withholds credential-class and internal fields', () = const svc = new KnowledgeService({ dataEngine: { find, getSchema } as unknown as IDataEngine }); const adapter = makeAdapter('memory'); svc.registerAdapter('memory', adapter); - svc.registerSource(source(['*'])); + svc.registerSource(source(['title', 'notes', 'api_token', 'lookup_digest'])); const res = await svc.reindexSource('s1'); expect(res).toMatchObject({ ok: true, indexed: 1 }); const [docs] = adapter.upsertSpy.mock.calls[0] as unknown as [KnowledgeDocument[]]; @@ -1319,17 +1212,6 @@ describe('KnowledgeService — documents carry their organization (ADR-0161 K8, expect(computeDocHash({ ...body, organizationId: 'org_a' })).not.toBe(computeDocHash({ ...body, organizationId: 'org_b' })); }); - it('indexDocument refuses a caller-supplied organizationId, and writes nothing', async () => { - const adapter = makeAdapter('memory'); - const svc = new KnowledgeService(); - svc.registerAdapter('memory', adapter); - svc.registerSource(src); - await expect( - svc.indexDocument('s1', { id: 'd1', sourceId: 's1', content: 'x', organizationId: 'org_b' }), - ).rejects.toThrow(/organizationId/); - expect(adapter.upsertSpy).not.toHaveBeenCalled(); - }); - it('the reindex walk and the event sync stamp the organization under a walled posture', async () => { const adapter = makeAdapter('memory'); const find = vi.fn(async (_o: string, q: { where?: Record }) => @@ -1385,12 +1267,8 @@ describe('KnowledgeService — search hands the adapter the caller\'s organizati const svc = new KnowledgeService(options); svc.registerAdapter('memory', adapter); svc.registerSource(objectSource('s1', 'task')); - svc.registerSource({ - id: 'web', label: 'Web', adapter: 'memory', - source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], - }); const handed = (sourceId: string) => - adapter.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.id === sourceId)?.[1] as + adapter.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.name === sourceId)?.[1] as | Record | undefined; return { svc, adapter, handed }; @@ -1428,12 +1306,6 @@ describe('KnowledgeService — search hands the adapter the caller\'s organizati expect(h.handed('s1')).not.toHaveProperty('organizationIds'); }); - it('a file / http source is never handed a filter: its documents carry no organization', async () => { - const h = searchSetup({ posture: async () => 'isolated' }); - await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }) }); - expect(h.handed('web')).not.toHaveProperty('organizationIds'); - }); - it.each([ ['tenancy disabled', { name: 'task', tenancy: { enabled: false }, fields: { organization_id: {}, notes: {} } }], ['no organization column', { name: 'task', fields: { notes: {}, title: {}, status: {} } }], @@ -1453,7 +1325,7 @@ describe('KnowledgeService — search hands the adapter the caller\'s organizati expect(h.handed('s1')?.organizationIds).toEqual(['org_a']); }); - it('a posture that cannot be read leaves every object source unsearched, says so at error, and still searches file / http', async () => { + it('a posture that cannot be read leaves every source unsearched and says so at error', async () => { const logger = { warn: vi.fn(), error: vi.fn() }; const h = searchSetup({ posture: async () => { @@ -1463,7 +1335,7 @@ describe('KnowledgeService — search hands the adapter the caller\'s organizati }); await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }) }); expect(h.handed('s1')).toBeUndefined(); - expect(h.handed('web')).toBeDefined(); + expect(h.adapter.searchSpy).not.toHaveBeenCalled(); expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('tenancy posture could not be read')); }); }); @@ -1576,7 +1448,7 @@ describe('KnowledgeService — search refills after the permission filter', () = /** An adapter that ranks like a real one: the best `min(topK, cap)` of `corpus` for the source asked. */ function rankingAdapter(corpus: Record, cap = Infinity) { const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number }) => - (corpus[opts.source.id] ?? []).slice(0, Math.min(opts.topK, cap))); + (corpus[opts.source.name] ?? []).slice(0, Math.min(opts.topK, cap))); return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; } @@ -1594,7 +1466,7 @@ describe('KnowledgeService — search refills after the permission filter', () = const svc = new KnowledgeService({ dataEngine: engine, logger: { debug, warn: vi.fn(), error: vi.fn() } }); svc.registerAdapter('memory', adapter); for (const id of opts.sources ?? ['s1']) svc.registerSource(objectSource(id, 'task')); - const asked = () => adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.id, (c[1] as { topK: number }).topK]); + const asked = () => adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.name, (c[1] as { topK: number }).topK]); return { svc, adapter, engine, debug, asked }; } @@ -1675,22 +1547,11 @@ describe('KnowledgeService — search refills after the permission filter', () = expect(engine.find).not.toHaveBeenCalled(); }); - it('no context: object sources stay unsearched (fail closed), a file source is asked topK once', async () => { - const { svc, adapter } = setup({ s1: rankedHits('s1', 100), f1: rankedHits('f1', 100) }, []); - svc.registerSource({ id: 'f1', label: 'f1', adapter: 'memory', source: { kind: 'file', prefix: 'docs/' } }); + it('no context: no source is searched (fail closed)', async () => { + const { svc, adapter } = setup({ s1: rankedHits('s1', 100) }, []); const out = await svc.search('q', { topK: 5 }); - expect(out.every((h) => h.sourceId === 'f1')).toBe(true); - expect(adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.id, (c[1] as { topK: number }).topK])) - .toEqual([['f1', 5]]); - }); - - it('a file source beside an object source is asked topK once; only the object source is refilled', async () => { - // The file source answers all 5 it is asked, but only 2 exist; the object source's rows are unreadable. - const { svc, asked } = setup({ s1: rankedHits('s1', 100), f1: rankedHits('f1', 2) }, []); - svc.registerSource({ id: 'f1', label: 'f1', adapter: 'memory', source: { kind: 'file', prefix: 'docs/' } }); - const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); - expect(out.map((h) => h.sourceId)).toEqual(['f1', 'f1']); - expect(asked()).toEqual([['s1', 25], ['f1', 5], ['s1', 100]]); + expect(out).toEqual([]); + expect(adapter.searchSpy).not.toHaveBeenCalled(); }); it('the count the re-check removed goes to the debug log only; the answer and its type are unchanged', async () => { @@ -1737,7 +1598,7 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { /** An adapter that ranks `hits` of the source asked; `honours` applies the scope before ranking, else ignores it. */ function adapterOver(hits: Record, honours: boolean) { const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number; scope?: Term[] }) => { - const all = hits[opts.source.id] ?? []; + const all = hits[opts.source.name] ?? []; const ranked = honours && opts.scope !== undefined ? all.filter((h) => holds(h, opts.scope!)) : all; return ranked.slice(0, opts.topK); }); @@ -1762,8 +1623,8 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { function taskSource(id: string, metadataFields: string[] = ['status', 'policy'], object = 'task'): KnowledgeSource { return { - id, label: id, adapter: 'memory', - source: { kind: 'object', object, contentFields: ['title', 'notes'], metadataFields } as ObjectKnowledgeSource, + name: id, label: id, adapter: 'memory', + source: { kind: 'object', object, content: ['title', 'notes'], metadataFields } as ObjectKnowledgeSource, }; } @@ -1776,8 +1637,8 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { } = {}) { const sources = opts.sources ?? [taskSource('s1')]; const hits = Object.fromEntries(sources.map((s, i) => [ - s.id, - [...corpus(s.id), ...(i === 0 ? opts.extra ?? [] : [])].sort((a, b) => b.score - a.score), + s.name, + [...corpus(s.name), ...(i === 0 ? opts.extra ?? [] : [])].sort((a, b) => b.score - a.score), ])); const adapter = adapterOver(hits, opts.honours ?? true); const engine = engineOver(opts.readable ?? (() => true), { task: TASK_SCHEMA }); @@ -1904,7 +1765,7 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { it('a source the scope reaches is searched; one it does not reach is not', async () => { const { svc, adapter } = setup({ sources: [taskSource('s1'), taskSource('s2', ['status'], 'note')] }); const out = await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['p1'] }], executionContext: MEMBER }); - expect(adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.id)).toEqual(['s1']); + expect(adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.name)).toEqual(['s1']); expect(new Set(out.map((h) => h.sourceId))).toEqual(new Set(['s1'])); }); @@ -1941,8 +1802,8 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { describe('recordToDocument reads the title from the object\'s display field', () => { const src: KnowledgeSource = { - id: 's1', label: 's1', adapter: 'memory', - source: { kind: 'object', object: 'invoice', contentFields: ['body'] } as ObjectKnowledgeSource, + name: 's1', label: 's1', adapter: 'memory', + source: { kind: 'object', object: 'invoice', content: ['body'] } as ObjectKnowledgeSource, }; const title = (record: Record, schema?: unknown) => recordToDocument(src, src.source as ObjectKnowledgeSource, { id: 'r1', body: 'B', ...record }, schema).title; @@ -2016,8 +1877,8 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn /** A clause source: content `body`, metadata `policy`, over object `clause`. */ function clauseSource(id: string, extra: Partial = {}): KnowledgeSource { return { - id, label: id, adapter: 'memory', - source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy'], ...extra } as ObjectKnowledgeSource, + name: id, label: id, adapter: 'memory', + source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: ['policy'], ...extra } as ObjectKnowledgeSource, }; } @@ -2025,7 +1886,7 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn function hitOf(source: KnowledgeSource, row: Row, n: number, score: number, schema?: unknown): KnowledgeHit { const doc = recordToDocument(source, source.source as ObjectKnowledgeSource, row, schema); return { - chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: source.id, sourceRecordId: row.id, + chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: source.name, sourceRecordId: row.id, score, snippet: `${row.body as string} (${n})`, metadata: doc.metadata, docHash: doc.docHash, }; } @@ -2033,7 +1894,7 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn /** An adapter answering the best `topK` of `corpus[sourceId]`. */ function rankingAdapter(corpus: Record) { const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number }) => - [...(corpus[opts.source.id] ?? [])].sort((a, b) => b.score - a.score).slice(0, opts.topK)); + [...(corpus[opts.source.name] ?? [])].sort((a, b) => b.score - a.score).slice(0, opts.topK)); return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy, @@ -2083,14 +1944,14 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn readable?: string[]; engine?: boolean; }) { - const byId = Object.fromEntries(opts.sources.map((s) => [s.id, s])); + const byId = Object.fromEntries(opts.sources.map((s) => [s.name, s])); const adapter = rankingAdapter(opts.corpus(byId)); const engine = opts.engine === false ? undefined : tableEngine(opts.table, opts.readable); const logger = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() }; const svc = new KnowledgeService({ ...(engine ? { dataEngine: engine } : {}), logger }); svc.registerAdapter('memory', adapter); for (const s of opts.sources) svc.registerSource(s); - const asked = () => adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.id, (c[1] as { topK: number }).topK]); + const asked = () => adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.name, (c[1] as { topK: number }).topK]); const systemReads = () => (engine?.find.mock.calls ?? []).filter((c) => isSystemCall(c)); /** The freshness check's reads: system reads that pin ids with `$in` (the repair's re-read pins one id, `limit: 1`). */ const freshnessReads = () => systemReads().filter((c) => JSON.stringify((c[1] as { where?: unknown }).where ?? {}).includes('"$in"')); @@ -2172,21 +2033,17 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn expect(h.asked().map(([id]) => id)).not.toContain('s2'); }); - it('groupBy across several sources: the same value is one group, the best hit of either source; a file source groups by document', async () => { + it('groupBy across several sources: the same value is one group, the best hit of either source', async () => { const table = policyRows(); - const file: KnowledgeSource = { id: 'f1', label: 'f1', adapter: 'memory', source: { kind: 'file', prefix: 'docs/' } as KnowledgeSource['source'] }; - const fileHit = (doc: string, n: number, score: number): KnowledgeHit => - ({ chunkId: `${doc}#${n}`, documentId: doc, sourceId: 'f1', score, snippet: doc }); const h = setup({ - table, sources: [clauseSource('s1'), clauseSource('s2'), file], + table, sources: [clauseSource('s1'), clauseSource('s2')], corpus: ({ s1, s2 }) => ({ s1: [hitOf(s1, table[0], 0, 0.6)], s2: [hitOf(s2, table[1], 0, 0.8), hitOf(s2, table[2], 0, 0.3)], - f1: [fileHit('handbook.md', 0, 0.7), fileHit('handbook.md', 1, 0.65), fileHit('faq.md', 0, 0.2)], }), }); const out = await h.svc.search('q', { groupBy: 'policy', topK: 5, executionContext: MEMBER }); - expect(out.map((x) => x.chunkId)).toEqual(['s2:c2#0', 'handbook.md#0', 's2:c3#0', 'faq.md#0']); + expect(out.map((x) => x.chunkId)).toEqual(['s2:c2#0', 's2:c3#0']); }); it("groupBy with granularity 'chunk', an empty groupBy and an unknown granularity are refused, coded VALIDATION_ERROR / 400", async () => { diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts index fa9b53433b2..bf7087d835e 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts @@ -220,10 +220,10 @@ describe('[#24769] the two buttons the knowledge service contributes, at the HTT describe('the rebuild and index_status actions are administrator-only, at the HTTP door', async () => { // A distinctive source: its id and label must appear in no refusal. const SECRET_SOURCE: KnowledgeSource = { - id: 'board_minutes_private', + name: 'board_minutes_private', label: 'Board minutes (private)', adapter: 'memory', - source: { kind: 'object', object: 'board_minute', contentFields: ['body'] }, + source: { kind: 'object', object: 'board_minute', content: ['body'] }, } as KnowledgeSource; const kernel = new LiteKernel(); kernel.use(new FakeManifestPlugin([])); @@ -249,17 +249,17 @@ describe('the rebuild and index_status actions are administrator-only, at the HT }; /** Every method the two handlers can call on the service, watched. */ const watchService = () => - (['listSources', 'getSource', 'readIndexState', 'rebuildSource', 'buildRecord'] as const).map((m) => vi.spyOn(knowledge, m)); + (['describeSources', 'describeSource', 'readIndexState', 'rebuildSource', 'buildRecord'] as const).map((m) => vi.spyOn(knowledge, m)); afterEach(() => { vi.restoreAllMocks(); }); it.each([ - ['member', 'rebuild', { source: SECRET_SOURCE.id }], + ['member', 'rebuild', { source: SECRET_SOURCE.name }], ['member', 'rebuild', {}], ['member', 'index_status', {}], - ['member', 'index_status', { source: SECRET_SOURCE.id }], - ['bare', 'rebuild', { source: SECRET_SOURCE.id }], + ['member', 'index_status', { source: SECRET_SOURCE.name }], + ['bare', 'rebuild', { source: SECRET_SOURCE.name }], ['bare', 'index_status', {}], - ['anonymous', 'rebuild', { source: SECRET_SOURCE.id }], + ['anonymous', 'rebuild', { source: SECRET_SOURCE.name }], ['anonymous', 'index_status', {}], ] as const)('a %s caller of %s %j is refused, names no source, and reaches no handler', async (who, action, body) => { const watched = watchService(); @@ -274,7 +274,7 @@ describe('the rebuild and index_status actions are administrator-only, at the HT } // The refusal names the namespace, never a source the caller may not see. const text = JSON.stringify(answer.body); - expect(text).not.toContain(SECRET_SOURCE.id); + expect(text).not.toContain(SECRET_SOURCE.name); expect(text).not.toContain(SECRET_SOURCE.label); for (const spy of watched) expect(spy, spy.getMockName()).not.toHaveBeenCalled(); }); @@ -284,19 +284,19 @@ describe('the rebuild and index_status actions are administrator-only, at the HT const watched = watchService(); const status = await post(door('admin'), 'knowledge', 'index_status', {}); expect(status.status).toBe(200); - expect(JSON.stringify(status.body)).toContain(SECRET_SOURCE.id); + expect(JSON.stringify(status.body)).toContain(SECRET_SOURCE.name); // `rebuild` without a source is answered by the handler itself, which lists the ids. const unnamed = await post(door('admin'), 'knowledge', 'rebuild', {}); expect(unnamed.status).toBe(400); expect(unnamed.body?.error?.code).toBe('SETTINGS_ACTION_FAILED'); - expect(JSON.stringify(unnamed.body)).toContain(SECRET_SOURCE.id); + expect(JSON.stringify(unnamed.body)).toContain(SECRET_SOURCE.name); expect(watched.some((spy) => spy.mock.calls.length > 0)).toBe(true); }); it('in process, an enforced caller without the capability is refused by runAction itself', async () => { for (const action of ['rebuild', 'index_status']) { - await expect(settings.runAction('knowledge', action, { source: SECRET_SOURCE.id }, callers.member())) + await expect(settings.runAction('knowledge', action, { source: SECRET_SOURCE.name }, callers.member())) .rejects.toMatchObject({ code: 'SETTINGS_FORBIDDEN', namespace: 'knowledge', required: 'manage_platform_settings' }); } }); @@ -444,7 +444,7 @@ async function bootEmbedder(opts: { if (opts.host) kernel.use(new HostEmbedderPlugin(opts.host.embedder, opts.host.phase)); kernel.use(new KnowledgeServicePlugin({ enableEventSync: false, - sources: [{ id: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'http', urls: ['https://docs.example.com/'] } }], + sources: [{ name: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'object', object: 'doc', content: ['body'] } }], })); kernel.use(new SettingsServicePlugin({ env: opts.env ?? {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() })); kernel.use(new EmbeddingAdapterPlugin()); @@ -455,6 +455,20 @@ async function bootEmbedder(opts: { return { kernel, lines, knowledge, embedder }; } +/** + * One index write for the `docs` source, handed to its adapter as the + * service's sync hands it: the adapter embeds the content, so what the + * embedder answers — or refuses with — is what this call answers. + */ +const indexOne = (knowledge: KnowledgeService, content: string): Promise => + knowledge.getAdapter('vec').upsert( + [{ id: 'docs:d1', sourceId: 'docs', sourceRecordId: 'd1', content }], + { source: knowledge.getSource('docs')!, reason: 'manual' }, + ); + +/** The system identity: the service searches a source for it without a data engine to re-check with. */ +const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true }; + const texts = (n: number) => Array.from({ length: n }, (_, i) => `chunk ${i}`); describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.embedder_* settings', () => { @@ -470,7 +484,7 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb expect(embedder.id).toBe('openai'); expect(requests).toHaveLength(0); // nothing is sent at boot - await knowledge.indexDocument('docs', { id: 'd1', sourceId: 'docs', content: 'hello embedder' }); + await indexOne(knowledge, 'hello embedder'); expect(requests).toEqual([{ url: 'https://api.openai.com/v1/embeddings', authorization: `Bearer ${API_KEY}`, @@ -506,7 +520,7 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb saved: { embedder_provider: 'openai', embedder_api_key: API_KEY }, }); expect(embedder).toBe(own); - await knowledge.indexDocument('docs', { id: 'd1', sourceId: 'docs', content: 'hello' }); + await indexOne(knowledge, 'hello'); expect(requests).toHaveLength(0); const kept = lines.filter((l) => l.line.includes('already registered') && l.line.includes('host-own')); expect(kept).toHaveLength(1); @@ -544,12 +558,12 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb const { knowledge, embedder, lines } = await bootEmbedder(); const named = /No embedder is configured[\s\S]*ai\.embedder_provider[\s\S]*restart/; - await expect(knowledge.indexDocument('docs', { id: 'd1', sourceId: 'docs', content: 'hello' })).rejects.toThrow(named); + await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named); // The adapter's search answers the error; the service's search reports it // per source and answers no hits. await expect(knowledge.getAdapter('vec').search('hello', { source: knowledge.getSource('docs')!, topK: 5 })) .rejects.toThrow(named); - await expect(knowledge.search('hello', { sourceIds: ['docs'] })).resolves.toEqual([]); + await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]); expect(lines.some((l) => l.level === 'error' && named.test(l.line))).toBe(true); // A vector column cannot be sized from it either. expect(() => embedder.dimensions).toThrow(named); @@ -662,14 +676,14 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb const rejected = await bootEmbedder({ saved: { embedder_provider: 'openai', embedder_api_key: API_KEY, embedder_model: 'text-embedding-3-small' }, }); - await expect(rejected.knowledge.indexDocument('docs', { id: 'd1', sourceId: 'docs', content: 'hello' })) + await expect(indexOne(rejected.knowledge, 'hello')) .rejects.toThrow(/401/); const failure = await rejected.embedder.embed(['x']).then( () => { throw new Error('expected a provider error'); }, (err: unknown) => err as Error, ); expect(failure.message).not.toContain(API_KEY); - await rejected.knowledge.search('hello', { sourceIds: ['docs'] }); + await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM }); expect(requests.length).toBeGreaterThan(0); expect(rejected.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]); }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index ba2399712a8..442d35e8028 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts @@ -49,16 +49,16 @@ function hitFor(sourceId: string, recordId = 'rec_1'): KnowledgeHit { } function makeAdapter(): IKnowledgeAdapter & { searchSpy: ReturnType } { - const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [hitFor(opts.source.id)]); + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [hitFor(opts.source.name)]); return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; } -function objectSource(id: string, object: string, contentFields: string[], metadataFields?: string[]): KnowledgeSource { +function objectSource(id: string, object: string, content: string[], metadataFields?: string[]): KnowledgeSource { return { - id, + name: id, label: id, adapter: 'memory', - source: { kind: 'object', object, contentFields, ...(metadataFields ? { metadataFields } : {}) } as ObjectKnowledgeSource, + source: { kind: 'object', object, content, ...(metadataFields ? { metadataFields } : {}) } as ObjectKnowledgeSource, }; } @@ -109,7 +109,7 @@ function setup(options: { }); svc.registerAdapter('memory', adapter); for (const s of options.sources) svc.registerSource(s); - const searched = () => adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.id); + const searched = () => adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.name); return { svc, adapter, engine, searched }; } @@ -148,16 +148,17 @@ describe('field gate — a source serving a field the caller may not query is no expect(ids(await plain.svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); }); - it("`'*'` serves every declared field: one hidden field refuses it, while the fields the index never carries are not asked", async () => { + it('a source that lists every field: one hidden field refuses it, while the fields the index never carries are not asked', async () => { const withSecret: ObjectDef = { name: 'ticket', fields: { ...TICKET.fields, api_token: { type: 'password' }, internal_score: { type: 'number', internal: true } }, }; const allButSecrets = makeSecurity(() => Object.keys(TICKET.fields)); - const admitted = setup({ objects: [withSecret], sources: [objectSource('all', 'ticket', ['*'])], security: allButSecrets }); + const every = Object.keys(withSecret.fields).filter((f) => f !== 'id'); + const admitted = setup({ objects: [withSecret], sources: [objectSource('all', 'ticket', every)], security: allButSecrets }); expect(ids(await admitted.svc.search('q', { executionContext: MEMBER }))).toEqual(['all']); - const refused = setup({ objects: [withSecret], sources: [objectSource('all', 'ticket', ['*'])], security: salaryHiddenFromMembers }); + const refused = setup({ objects: [withSecret], sources: [objectSource('all', 'ticket', every)], security: salaryHiddenFromMembers }); expect(await refused.svc.search('q', { executionContext: MEMBER })).toEqual([]); }); @@ -245,36 +246,27 @@ describe('exposure gate — an object the caller\'s exposure decision refuses is expect(await svc.search('q', { executionContext: MANAGER })).toEqual([]); expect(searched()).toEqual([]); }); - - it('a file / http source is untouched by either gate', async () => { - const { svc } = setup({ - objects: [sealed], - sources: [objectSource('sealed', 'sealed', ['body']), { id: 'web', label: 'web', adapter: 'memory', source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'] }], - }); - expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['web']); - }); }); describe('no context, no engine, foreign hits — an object source no gate can judge is never served', () => { it('no context: an object source is not searched, even when its hits carry no `sourceRecordId`', async () => { const adapter = makeAdapter(); adapter.search = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [ - { chunkId: 'c', documentId: 'd', sourceId: opts.source.id, score: 0.9, snippet: 'passage' }, + { chunkId: 'c', documentId: 'd', sourceId: opts.source.name, score: 0.9, snippet: 'passage' }, ]); const svc = new KnowledgeService({ dataEngine: makeEngine([TICKET]) }); svc.registerAdapter('memory', adapter); svc.registerSource(objectSource('notes', 'ticket', ['body'])); - svc.registerSource({ id: 'web', label: 'web', adapter: 'memory', source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'] }); - expect(ids(await svc.search('q'))).toEqual(['web']); - expect((adapter.search as ReturnType).mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.id)).toEqual(['web']); - // Preservation: the system context still reaches the object source. - expect(ids(await svc.search('q', { executionContext: SYSTEM }))).toEqual(['notes', 'web']); + expect(ids(await svc.search('q'))).toEqual([]); + expect(adapter.search).not.toHaveBeenCalled(); + // Preservation: the system context still reaches the source. + expect(ids(await svc.search('q', { executionContext: SYSTEM }))).toEqual(['notes']); }); it('no data engine: an object source is not searched for an end-user context', async () => { const adapter = makeAdapter(); adapter.search = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [ - { chunkId: 'c', documentId: 'd', sourceId: opts.source.id, score: 0.9, snippet: 'passage' }, + { chunkId: 'c', documentId: 'd', sourceId: opts.source.name, score: 0.9, snippet: 'passage' }, ]); const svc = new KnowledgeService(); svc.registerAdapter('memory', adapter); @@ -286,8 +278,8 @@ describe('no context, no engine, foreign hits — an object source no gate can j it('an admitted object source\'s hit with no `sourceRecordId` cannot be re-checked and is dropped', async () => { const adapter = makeAdapter(); adapter.search = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [ - { chunkId: 'a', documentId: 'a', sourceId: opts.source.id, sourceRecordId: 'rec_1', score: 0.9, snippet: 'row' }, - { chunkId: 'b', documentId: 'b', sourceId: opts.source.id, score: 0.8, snippet: 'unplaced' }, + { chunkId: 'a', documentId: 'a', sourceId: opts.source.name, sourceRecordId: 'rec_1', score: 0.9, snippet: 'row' }, + { chunkId: 'b', documentId: 'b', sourceId: opts.source.name, score: 0.8, snippet: 'unplaced' }, ]); const svc = new KnowledgeService({ dataEngine: makeEngine([TICKET]) }); svc.registerAdapter('memory', adapter); @@ -299,7 +291,7 @@ describe('no context, no engine, foreign hits — an object source no gate can j const adapter = makeAdapter(); // Every search answers the refused source's passage as well as its own. adapter.search = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => - opts.source.id === 'notes' ? [hitFor('notes')] : [hitFor(opts.source.id), hitFor('notes')]); + opts.source.name === 'notes' ? [hitFor('notes')] : [hitFor(opts.source.name), hitFor('notes')]); const warn = vi.fn(); const svc = new KnowledgeService({ dataEngine: makeEngine([TICKET]), resolveSecurity: () => salaryHiddenFromMembers, logger: { warn } }); svc.registerAdapter('memory', adapter); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-loader.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-loader.test.ts new file mode 100644 index 00000000000..ecb34214759 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-loader.test.ts @@ -0,0 +1,407 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The loader of the governed `knowledge_source` type (#37304; ADR-0161 K4 — + * the type lands with its reader — and K7, "What starts a rebuild"): + * + * - the loader alone: an added item is registered, a changed one reloaded and + * built, an unchanged one left alone, a removed one unregistered and its + * index dropped; a row that is no source is said once; a listing that cannot + * be read changes nothing; + * - through `KnowledgeServicePlugin`: the items are loaded at boot, again when + * the metadata protocol signals a `knowledge_source` change or the kernel + * announces a metadata reload, and a composition with no metadata store + * serves the sources registered in code. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; +import { KnowledgeSourceLoader } from '../knowledge-source-loader.js'; +import { indexKeyOf } from '../knowledge-source-registry.js'; + +const ACME = 'com.acme.kb'; +const GLOBEX = 'com.globex.kb'; +const NAMESPACES: Record = { [ACME]: 'acme', [GLOBEX]: 'globex' }; + +/** A stored `knowledge_source` body; `packageId` binds the row to a package. */ +function item(name: string, packageId?: string, extra: Record = {}): Record { + return { + name, + label: `${name} label`, + adapter: 'memory', + source: { kind: 'object', object: 'note', content: ['body'] }, + ...(packageId === undefined ? {} : { _packageId: packageId }), + ...extra, + }; +} + +function droppingAdapter() { + const dropped: string[] = []; + const adapter = { + id: 'memory', + upsert: async () => undefined, + delete: async () => undefined, + search: async () => [], + dropSource: async (opts: { source: KnowledgeSource }) => { + dropped.push(opts.source.name); + }, + } as unknown as IKnowledgeAdapter; + return { adapter, dropped }; +} + +/** The loader over a real service, reading whatever `rows.current` holds. */ +function setup(opts: { buildOnReload?: boolean } = {}) { + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const { adapter, dropped } = droppingAdapter(); + const service = new KnowledgeService({ logger }); + service.registerAdapter('memory', adapter); + const rows: { current: unknown[] | null } = { current: [] }; + const readItems = vi.fn(async () => rows.current); + const built = vi.spyOn(service, 'buildReloadedSource').mockResolvedValue(undefined); + const registered = vi.spyOn(service, 'registerMetadataSource'); + const loader = new KnowledgeSourceLoader({ + service, + logger, + readItems, + namespaceOf: (packageId) => NAMESPACES[packageId], + buildOnReload: opts.buildOnReload ?? true, + }); + const faces = () => service.describeSources().map((s) => s.id); + const warnings = () => logger.warn.mock.calls.map((c) => String(c[0])); + return { loader, service, rows, readItems, built, registered, dropped, logger, faces, warnings }; +} + +describe('KnowledgeSourceLoader — one pass makes the sources agree with the published items', () => { + it("an added item is registered: a package's under its face, an environment's under its bare name", async () => { + const h = setup(); + h.rows.current = [item('notes', ACME), item('faq')]; + const result = await h.loader.reconcile('boot'); + expect(result).toEqual({ read: true, added: ['acme-notes', 'faq'], changed: [], removed: [] }); + expect(h.service.describeSources().map((s) => ({ id: s.id, door: s.door, packageId: s.packageId }))).toEqual([ + { id: 'acme-notes', door: 'metadata', packageId: ACME }, + { id: 'faq', door: 'metadata', packageId: undefined }, + ]); + // The boot's own build pass builds these; the loader starts none at boot. + expect(h.built).not.toHaveBeenCalled(); + }); + + it('two packages may each ship a source of one name: two sources, each loaded', async () => { + const h = setup(); + h.rows.current = [item('notes', ACME), item('notes', GLOBEX)]; + await h.loader.reconcile('boot'); + expect(h.faces()).toEqual(['acme-notes', 'globex-notes']); + }); + + it('an item that did not change is left alone: nothing is registered or built again', async () => { + const h = setup(); + h.rows.current = [item('notes', ACME)]; + await h.loader.reconcile('boot'); + h.registered.mockClear(); + // The same item, its keys in another order. + h.rows.current = [{ _packageId: ACME, source: { content: ['body'], object: 'note', kind: 'object' }, adapter: 'memory', label: 'notes label', name: 'notes' }]; + expect(await h.loader.reconcile('reload')).toEqual({ read: true, added: [], changed: [], removed: [] }); + expect(h.registered).not.toHaveBeenCalled(); + await Promise.resolve(); + expect(h.built).not.toHaveBeenCalled(); + }); + + it('a changed item is registered again in its own slot, and built on reload', async () => { + const h = setup(); + h.rows.current = [item('notes', ACME)]; + await h.loader.reconcile('boot'); + h.rows.current = [item('notes', ACME, { source: { kind: 'object', object: 'note', content: ['body', 'title'] } })]; + const result = await h.loader.reconcile('reload'); + expect(result).toEqual({ read: true, added: [], changed: ['acme-notes'], removed: [] }); + expect(h.service.getSource('acme-notes')?.source.content).toEqual(['body', 'title']); + expect(h.faces()).toEqual(['acme-notes']); + await vi.waitFor(() => expect(h.built).toHaveBeenCalledWith(indexKeyOf(ACME, 'notes'))); + expect(h.built).toHaveBeenCalledTimes(1); + }); + + it('an item added while the process runs is built; with buildOnReload off, it is registered and not built', async () => { + const on = setup(); + on.rows.current = [item('faq')]; + expect((await on.loader.reconcile('reload')).added).toEqual(['faq']); + await vi.waitFor(() => expect(on.built).toHaveBeenCalledWith('faq')); + + const off = setup({ buildOnReload: false }); + off.rows.current = [item('faq')]; + expect((await off.loader.reconcile('reload')).added).toEqual(['faq']); + await Promise.resolve(); + expect(off.built).not.toHaveBeenCalled(); + expect(off.faces()).toEqual(['faq']); + }); + + it('a removed item is unregistered and its index dropped; a source registered in code is never touched', async () => { + const h = setup(); + h.service.registerSource(item('coded') as unknown as KnowledgeSource); + h.rows.current = [item('notes', ACME), item('faq')]; + await h.loader.reconcile('boot'); + h.rows.current = [item('faq')]; + const result = await h.loader.reconcile('reload'); + expect(result).toEqual({ read: true, added: [], changed: [], removed: ['acme-notes'] }); + expect(h.dropped).toEqual([indexKeyOf(ACME, 'notes')]); + expect(h.faces()).toEqual(['coded', 'faq']); + // Every item gone: the code source still stands. + h.rows.current = []; + await h.loader.reconcile('reload'); + expect(h.faces()).toEqual(['coded']); + expect(h.dropped).toEqual([indexKeyOf(ACME, 'notes'), 'faq']); + }); + + it('a listing that cannot be read changes nothing: no source is unregistered, no index dropped', async () => { + const h = setup(); + h.rows.current = [item('notes', ACME)]; + await h.loader.reconcile('boot'); + h.rows.current = null; + expect(await h.loader.reconcile('reload')).toEqual({ read: false, added: [], changed: [], removed: [] }); + expect(h.faces()).toEqual(['acme-notes']); + expect(h.dropped).toEqual([]); + }); +}); + +describe('KnowledgeSourceLoader — rows that are no source', () => { + it('a row that does not parse is not served, said once with the schema\'s prescription; the rows beside it load', async () => { + const h = setup(); + h.rows.current = [ + { id: 'legacy', label: 'Legacy', adapter: 'memory', source: { kind: 'object', object: 'note', content: ['body'] } }, + { ...item('wild'), source: { kind: 'object', object: 'note', content: ['*'] } }, + item('faq'), + ]; + await h.loader.reconcile('boot'); + await h.loader.reconcile('reload'); + expect(h.faces()).toEqual(['faq']); + const lines = h.warnings().filter((l) => l.includes('is not a valid source and is not served')); + expect(lines).toHaveLength(2); + expect(lines.some((l) => l.includes('"wild"') && l.includes('content'))).toBe(true); + expect(lines.some((l) => l.includes('`id`'))).toBe(true); + }); + + it('an environment row under a name a package holds is not served: unregistered, its index dropped, said once', async () => { + const h = setup(); + // Before the package arrives, the environment's row is a source. + h.rows.current = [item('notes')]; + await h.loader.reconcile('boot'); + expect(h.faces()).toEqual(['notes']); + + h.rows.current = [item('notes'), item('notes', ACME)]; + const arrived = await h.loader.reconcile('reload'); + expect(arrived).toEqual({ read: true, added: ['acme-notes'], changed: [], removed: ['notes'] }); + expect(h.faces()).toEqual(['acme-notes']); + expect(h.dropped).toEqual(['notes']); + await h.loader.reconcile('reload'); + const lines = h.warnings().filter((l) => l.includes('authored in this environment is not served')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("'notes'"); + expect(lines[0]).toContain(`"${ACME}"`); + expect(lines[0]).toContain('Rename'); + + // The package leaves: the environment's row is a source again. + h.rows.current = [item('notes')]; + expect(await h.loader.reconcile('reload')).toEqual({ read: true, added: ['notes'], changed: [], removed: ['acme-notes'] }); + expect(h.faces()).toEqual(['notes']); + }); + + it('an environment row under a name registered in code is refused, said once naming both doors; the code source stays', async () => { + const h = setup(); + h.service.registerSource(item('notes', undefined, { label: 'Coded' }) as unknown as KnowledgeSource); + h.rows.current = [item('notes'), item('notes', ACME)]; + // A package's source of the name is unaffected by the code registration, + // and with a package holding the name the environment's row is unserved + // before it ever meets the code door. + await h.loader.reconcile('boot'); + expect(h.faces()).toEqual(['notes', 'acme-notes']); + expect(h.service.getSource('notes')?.label).toBe('Coded'); + + const alone = setup(); + alone.service.registerSource(item('notes', undefined, { label: 'Coded' }) as unknown as KnowledgeSource); + alone.rows.current = [item('notes')]; + await alone.loader.reconcile('boot'); + await alone.loader.reconcile('reload'); + expect(alone.service.describeSources().map((s) => [s.id, s.door, s.source.label])).toEqual([['notes', 'code', 'Coded']]); + const lines = alone.warnings().filter((l) => l.includes('The item is not served.')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain('Held by: a registration in code'); + expect(lines[0]).toContain('Refused: a knowledge_source metadata item authored in this environment'); + }); +}); + +describe('KnowledgeSourceLoader — passes run one after another', () => { + it('a reload asked for while one is waiting to start is answered by that one', async () => { + const h = setup(); + let release: () => void = () => undefined; + const gate = new Promise((resolve) => { release = resolve; }); + h.readItems.mockImplementationOnce(async () => { await gate; return [item('faq')]; }); + const first = h.loader.reconcile('boot'); + const second = h.loader.reconcile('reload'); + const third = h.loader.reconcile('reload'); + expect(third).toBe(second); + h.rows.current = [item('faq'), item('notes', ACME)]; + release(); + expect((await first).added).toEqual(['faq']); + expect((await second).added).toEqual(['acme-notes']); + expect(h.readItems).toHaveBeenCalledTimes(2); + // Once it ran, the next reload is a new pass. + await h.loader.reconcile('reload'); + expect(h.readItems).toHaveBeenCalledTimes(3); + }); +}); + +// ── Through the plugin ────────────────────────────────────────────── + +type Hook = (...args: unknown[]) => Promise | void; + +/** Boot the plugin over a fake kernel context; `services` are what `getService` answers. */ +async function bootPlugin( + options: ConstructorParameters[0], + services: Record, +) { + const hooks = new Map(); + let service: KnowledgeService | undefined; + const ctx: any = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + hook: (name: string, fn: Hook) => { + hooks.set(name, [...(hooks.get(name) ?? []), fn]); + }, + registerService: (_name: string, svc: KnowledgeService) => { + service = svc; + }, + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no service ${name}`); + }, + }; + const fire = async (name: string) => { + for (const fn of hooks.get(name) ?? []) await fn(); + }; + const plugin = new KnowledgeServicePlugin({ buildAtBoot: false, ...options }); + await plugin.init(ctx); + service!.registerAdapter('memory', droppingAdapter().adapter); + await plugin.start(ctx); + await fire('kernel:ready'); + await fire('kernel:bootstrapped'); + const faces = () => service!.describeSources().map((s) => s.id); + return { ctx, plugin, service: service!, fire, faces }; +} + +/** A metadata protocol double: the execution read of the type, and the mutation signal. */ +function fakeProtocol(initial: unknown[]) { + const store = { items: initial, fail: undefined as Error | undefined }; + const listeners = new Set<(evt: { type?: string; name?: string; state?: string }) => void>(); + const protocol = { + getMetaItemsForExecution: vi.fn(async (request: { type: string }) => { + if (store.fail) throw store.fail; + return { type: request.type, items: store.items }; + }), + onMetadataMutation: (listener: (evt: { type?: string; name?: string; state?: string }) => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; + const signal = (evt: { type?: string; name?: string; state?: string }) => { + for (const listener of listeners) listener(evt); + }; + return { protocol, store, signal, listeners }; +} + +/** The engine slice the plugin reads a package's namespace from. */ +const objectql = { + registry: { getPackage: (id: string) => (NAMESPACES[id] ? { manifest: { namespace: NAMESPACES[id] } } : undefined) }, +}; + +describe('KnowledgeServicePlugin — the published items are loaded', () => { + it('at boot: every published item is a source, beside the ones registered in code', async () => { + const { protocol } = fakeProtocol([item('notes', ACME), item('faq')]); + const h = await bootPlugin({ sources: [item('coded') as unknown as KnowledgeSource] }, { protocol, objectql }); + expect(h.faces()).toEqual(['coded', 'acme-notes', 'faq']); + expect(protocol.getMetaItemsForExecution).toHaveBeenCalledWith({ type: 'knowledge_source' }); + }); + + it('a read decoration on a listed item is not part of the source', async () => { + const { protocol } = fakeProtocol([{ ...item('faq'), _lock: 'none', _diagnostics: [{ code: 'x' }], _withheldFields: [] }]); + const h = await bootPlugin({}, { protocol, objectql }); + expect(h.faces()).toEqual(['faq']); + expect(h.ctx.logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('is not a valid source')); + }); + + it('a published change to a knowledge_source reloads the sources; a draft or another type does not', async () => { + const { protocol, store, signal } = fakeProtocol([item('faq')]); + const h = await bootPlugin({}, { protocol, objectql }); + const reads = () => protocol.getMetaItemsForExecution.mock.calls.length; + const before = reads(); + + store.items = [item('faq'), item('notes', ACME)]; + signal({ type: 'knowledge_source', name: 'notes', state: 'draft' }); + signal({ type: 'object', name: 'note', state: 'active' }); + await Promise.resolve(); + expect(reads()).toBe(before); + expect(h.faces()).toEqual(['faq']); + + signal({ type: 'knowledge_source', name: 'notes', state: 'active' }); + await vi.waitFor(() => expect(h.faces()).toEqual(['faq', 'acme-notes'])); + + store.items = [item('notes', ACME)]; + signal({ type: 'knowledge_source', name: 'faq', state: 'deleted' }); + await vi.waitFor(() => expect(h.faces()).toEqual(['acme-notes'])); + }); + + it('a metadata reload the kernel announces reloads the sources', async () => { + const { protocol, store } = fakeProtocol([]); + const h = await bootPlugin({}, { protocol, objectql }); + expect(h.faces()).toEqual([]); + store.items = [item('notes', GLOBEX)]; + await h.fire('metadata:reloaded'); + expect(h.faces()).toEqual(['globex-notes']); + }); + + it('a source added after boot is guarded by the lifecycle reap guard from then on', async () => { + const { protocol, store, signal } = fakeProtocol([]); + const guarded: string[] = []; + const lifecycle = { registerReapGuard: (object: string) => guarded.push(object) }; + const h = await bootPlugin({}, { protocol, objectql, lifecycle }); + expect(guarded).toEqual([]); + store.items = [item('notes', ACME)]; + signal({ type: 'knowledge_source', name: 'notes', state: 'active' }); + await vi.waitFor(() => expect(h.faces()).toEqual(['acme-notes'])); + expect(guarded).toEqual(['note']); + }); + + it('a listing that cannot be read is said at warn, and the sources stay as they were', async () => { + const { protocol, store } = fakeProtocol([item('faq')]); + const h = await bootPlugin({}, { protocol, objectql }); + store.fail = new Error('metadata store offline'); + await h.fire('metadata:reloaded'); + expect(h.faces()).toEqual(['faq']); + expect(h.ctx.logger.warn).toHaveBeenCalledWith(expect.stringContaining('metadata store offline')); + }); + + it('a package whose namespace the host cannot answer keeps its source, under its bare name', async () => { + const { protocol } = fakeProtocol([item('notes', 'com.unknown.pkg')]); + const h = await bootPlugin({}, { protocol }); + expect(h.service.describeSources().map((s) => ({ id: s.id, packageId: s.packageId }))).toEqual([ + { id: 'notes', packageId: 'com.unknown.pkg' }, + ]); + }); + + it('with no metadata protocol, the sources are the ones registered in code and nothing is reported', async () => { + const h = await bootPlugin({ sources: [item('coded') as unknown as KnowledgeSource] }, {}); + await h.fire('metadata:reloaded'); + expect(h.faces()).toEqual(['coded']); + expect(h.ctx.logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('knowledge_source')); + }); + + it('after destroy, a signal loads nothing', async () => { + const { protocol, store, signal, listeners } = fakeProtocol([]); + const h = await bootPlugin({}, { protocol, objectql }); + expect(listeners.size).toBe(1); + await h.plugin.destroy(); + expect(listeners.size).toBe(0); + store.items = [item('faq')]; + signal({ type: 'knowledge_source', name: 'faq', state: 'active' }); + await Promise.resolve(); + expect(h.faces()).toEqual([]); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts new file mode 100644 index 00000000000..ed2af6622ae --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts @@ -0,0 +1,346 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The knowledge service's registry of sources (#37304; ADR-0161 K4 and K6, + * ADR-0150's addendum of 2026-11-25; rulings on #37304 of 2026-11-26): + * + * - both doors parse with `KnowledgeSourceSchema`, and the code door refuses a + * retired key with its prescription instead of converting it; + * - one slot per `(package, name)`: a source registered in code takes the + * package-less slot, never replaced by — nor replacing — an item authored in + * the environment, and never colliding with a package's source of the name; + * - a caller names a source by its face, a bare name resolves by ADR-0150 D3, + * and a name several sources answer to is refused, coded, never picked; + * - an index is keyed by the source's index key, so two packages' sources of + * one name never share a document. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { AdapterContext, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { indexKeyOf } from '../knowledge-source-registry.js'; + +const SYSTEM = { positions: [], permissions: [], isSystem: true }; + +function source(name: string, extra: Record = {}): KnowledgeSource { + return { + name, + label: `${name} label`, + adapter: 'memory', + source: { kind: 'object', object: 'note', content: ['body'] }, + ...extra, + } as KnowledgeSource; +} + +/** An adapter that records what it is handed, and answers one hit per source it is asked. */ +function recordingAdapter() { + const upserted: KnowledgeDocument[] = []; + const searched: string[] = []; + const dropped: Array<{ name: string; reason: string }> = []; + const adapter: IKnowledgeAdapter = { + id: 'memory', + upsert: async (docs: KnowledgeDocument[]) => { + upserted.push(...docs); + }, + delete: async () => undefined, + search: async (_query: string, opts: { source: KnowledgeSource }): Promise => { + searched.push(opts.source.name); + const documentId = `${opts.source.name}:r1`; + return [{ chunkId: `${documentId}#0`, documentId, sourceId: opts.source.name, score: 1, snippet: 's', sourceRecordId: 'r1' }]; + }, + dropSource: async (opts: { source: KnowledgeSource; reason: string }, _ctx?: AdapterContext) => { + dropped.push({ name: opts.source.name, reason: opts.reason }); + }, + } as unknown as IKnowledgeAdapter; + return { adapter, upserted, searched, dropped }; +} + +function setup() { + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const recorded = recordingAdapter(); + const svc = new KnowledgeService({ logger }); + svc.registerAdapter('memory', recorded.adapter); + return { svc, logger, ...recorded }; +} + +/** The refusal a call threw, or a failure when it threw none. */ +function refusalOf(run: () => unknown): { code?: string; status?: number; message: string; candidates?: unknown } { + try { + run(); + } catch (err) { + return err as { code?: string; status?: number; message: string }; + } + throw new Error('expected a refusal, and the call returned'); +} + +describe('the code door — one schema, no conversion (ADR-0161 K6)', () => { + it.each([ + ['the retired `id`', { id: 'notes', label: 'Notes', adapter: 'memory', source: { kind: 'object', object: 'note', content: ['body'] } }, '`id`'], + ['the retired `source.contentFields`', { ...source('notes'), source: { kind: 'object', object: 'note', contentFields: ['body'] } }, 'contentFields'], + ['an unknown key', source('notes', { colour: 'blue' }), 'colour'], + ["a `'*'` content member", { ...source('notes'), source: { kind: 'object', object: 'note', content: ['*'] } }, 'content'], + ['a `file` kind', { ...source('notes'), source: { kind: 'file', prefix: 'docs/' } }, 'kind'], + ['an `http` kind', { ...source('notes'), source: { kind: 'http', urls: ['https://x.test'] } }, 'kind'], + ['a name that is not snake_case', source('Notes'), 'name'], + ])('refuses %s with VALIDATION_ERROR / 400, naming it, and registers nothing', (_label, input, named) => { + const { svc } = setup(); + const refusal = refusalOf(() => svc.registerSource(input as unknown as KnowledgeSource)); + expect(refusal.code).toBe('VALIDATION_ERROR'); + expect(refusal.status).toBe(400); + expect(refusal.message).toContain('registerSource refused'); + expect(refusal.message).toContain(named); + expect(svc.listSources()).toEqual([]); + }); + + it('a retired key is answered with what to write instead, never converted', () => { + const { svc } = setup(); + const refusal = refusalOf(() => + svc.registerSource({ id: 'notes', label: 'Notes', adapter: 'memory', source: { kind: 'object', object: 'note', content: ['body'] } } as unknown as KnowledgeSource)); + expect(refusal.message).toContain('`name`'); + expect(svc.getSource('notes')).toBeUndefined(); + }); + + it('refuses a registration that names a package: a source registered in code belongs to none', () => { + const { svc } = setup(); + const refusal = refusalOf(() => svc.registerSource(source('notes', { _packageId: 'com.acme.kb' }))); + expect(refusal.code).toBe('VALIDATION_ERROR'); + expect(refusal.status).toBe(400); + expect(refusal.message).toContain('com.acme.kb'); + expect(refusal.message).toContain('knowledgeSources'); + expect(svc.listSources()).toEqual([]); + }); + + it('registering a name again through the same door replaces the earlier registration, said at warn', () => { + const { svc, logger } = setup(); + svc.registerSource(source('notes')); + svc.registerSource(source('notes', { label: 'Second' })); + expect(svc.listSources().map((s) => s.label)).toEqual(['Second']); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('source overwritten: notes')); + }); +}); + +describe('one name, one source — the package-less slot across the two doors', () => { + it('an environment-authored item under a name registered in code is refused, naming both doors; the code source stays', () => { + const { svc } = setup(); + svc.registerSource(source('notes')); + const refusal = refusalOf(() => svc.registerMetadataSource(source('notes', { label: 'Authored' }))); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(refusal.message).toContain('Held by: a registration in code'); + expect(refusal.message).toContain('Refused: a knowledge_source metadata item authored in this environment'); + expect(svc.describeSources().map((s) => [s.id, s.door, s.source.label])).toEqual([['notes', 'code', 'notes label']]); + }); + + it('a registration in code under a name an environment-authored item holds is refused, naming both doors; the item stays', () => { + const { svc } = setup(); + svc.registerMetadataSource(source('notes', { label: 'Authored' })); + const refusal = refusalOf(() => svc.registerSource(source('notes'))); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(refusal.message).toContain('Held by: a knowledge_source metadata item authored in this environment'); + expect(refusal.message).toContain('Refused: a registration in code'); + expect(svc.describeSources().map((s) => [s.id, s.door, s.source.label])).toEqual([['notes', 'metadata', 'Authored']]); + }); + + it('a metadata item that reloads replaces its own earlier version: no refusal, no second source', () => { + const { svc, logger } = setup(); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + svc.registerMetadataSource(source('notes', { label: 'Reloaded' }), { packageId: 'com.acme.kb', namespace: 'acme' }); + expect(svc.describeSources().map((s) => [s.id, s.source.label])).toEqual([['acme-notes', 'Reloaded']]); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it("a registration in code and a package's source of one name are two sources, both kept", () => { + const { svc } = setup(); + svc.registerSource(source('notes')); + svc.registerMetadataSource(source('notes', { label: 'Packaged' }), { packageId: 'com.acme.kb', namespace: 'acme' }); + expect(svc.describeSources().map((s) => ({ id: s.id, door: s.door, packageId: s.packageId }))).toEqual([ + { id: 'notes', door: 'code', packageId: undefined }, + { id: 'acme-notes', door: 'metadata', packageId: 'com.acme.kb' }, + ]); + // The bare name answers the package-less one (ADR-0150 D3); the face answers the package's. + expect(svc.getSource('notes')?.label).toBe('notes label'); + expect(svc.getSource('acme-notes')?.label).toBe('Packaged'); + }); +}); + +describe('how a caller names a source — face, then bare name by ADR-0150 D3', () => { + function twoPackages() { + const h = setup(); + h.svc.registerMetadataSource(source('notes', { label: 'Acme' }), { packageId: 'com.acme.kb', namespace: 'acme' }); + h.svc.registerMetadataSource(source('notes', { label: 'Globex' }), { packageId: 'com.globex.kb', namespace: 'globex' }); + return h; + } + + it('two packages may each hold a source of one name; each is named by its face', () => { + const { svc } = twoPackages(); + expect(svc.describeSources().map((s) => s.id)).toEqual(['acme-notes', 'globex-notes']); + expect(svc.getSource('acme-notes')?.label).toBe('Acme'); + expect(svc.getSource('globex-notes')?.label).toBe('Globex'); + expect(svc.describeSource('globex-notes')).toMatchObject({ id: 'globex-notes', packageId: 'com.globex.kb', door: 'metadata' }); + }); + + it('a bare name two packages hold is refused RESOURCE_CONFLICT / 409, naming each candidate by its face', () => { + const { svc } = twoPackages(); + const refusal = refusalOf(() => svc.getSource('notes')); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(refusal.message).toContain("'acme-notes' (package \"com.acme.kb\")"); + expect(refusal.message).toContain("'globex-notes' (package \"com.globex.kb\")"); + expect(refusal.candidates).toEqual([ + { face: 'acme-notes', packageId: 'com.acme.kb' }, + { face: 'globex-notes', packageId: 'com.globex.kb' }, + ]); + }); + + it('a bare name one package alone holds answers that source', () => { + const { svc } = setup(); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + expect(svc.describeSource('notes')?.id).toBe('acme-notes'); + }); + + it('a spelling no source answers to names none: undefined, never a guess', () => { + const { svc } = twoPackages(); + expect(svc.getSource('acme-other')).toBeUndefined(); + expect(svc.getSource('other')).toBeUndefined(); + // An index key is no spelling of a source. + expect(svc.getSource(indexKeyOf('com.acme.kb', 'notes'))).toBeUndefined(); + }); + + it('a face two sources derive (two packages of one namespace) is refused, never picked', () => { + const { svc } = setup(); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.one', namespace: 'acme' }); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.two', namespace: 'acme' }); + const refusal = refusalOf(() => svc.getSource('acme-notes')); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(refusal.message).toContain('com.acme.one'); + expect(refusal.message).toContain('com.acme.two'); + }); + + it("search: `sourceIds` takes a face, and a hit's `sourceId` is the face of the source it came from", async () => { + const { svc, searched } = twoPackages(); + svc.registerSource(source('notes')); + const hits = await svc.search('q', { sourceIds: ['globex-notes'], executionContext: SYSTEM }); + expect(searched).toEqual([indexKeyOf('com.globex.kb', 'notes')]); + expect(hits.map((h) => h.sourceId)).toEqual(['globex-notes']); + // Unnamed: every source, each hit under its own face. + const all = await svc.search('q', { executionContext: SYSTEM }); + expect(all.map((h) => h.sourceId).sort()).toEqual(['acme-notes', 'globex-notes', 'notes']); + }); + + it('search: a bare name several packages hold is refused, coded, and no source is asked', async () => { + const { svc, searched } = twoPackages(); + const refusal = await svc.search('q', { sourceIds: ['notes'], executionContext: SYSTEM }).then( + () => { throw new Error('expected a refusal'); }, + (err: { code?: string; status?: number }) => err, + ); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(searched).toEqual([]); + }); +}); + +describe('the index key — two sources of one name never share an index', () => { + it('a package-less source is keyed by its name; a package\'s by a snake_case key that embeds no package id', () => { + expect(indexKeyOf(undefined, 'notes')).toBe('notes'); + const key = indexKeyOf('com.acme.kb', 'notes'); + expect(key).toMatch(/^_p[0-9a-f]{16}_notes$/); + expect(indexKeyOf('com.acme.kb', 'notes')).toBe(key); + expect(indexKeyOf('com.globex.kb', 'notes')).not.toBe(key); + }); + + it('one written row is one document per source, each under its own key', async () => { + const { svc, upserted } = setup(); + svc.registerSource(source('notes')); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + svc.registerMetadataSource(source('notes'), { packageId: 'com.globex.kb', namespace: 'globex' }); + await svc.handleRecordUpsert('note', { id: 'r1', body: 'hello' }); + const acme = indexKeyOf('com.acme.kb', 'notes'); + const globex = indexKeyOf('com.globex.kb', 'notes'); + expect(upserted.map((d) => [d.id, d.sourceId]).sort()).toEqual( + [['notes:r1', 'notes'], [`${acme}:r1`, acme], [`${globex}:r1`, globex]].sort(), + ); + }); + + it('listSources answers each source as authored: its own name, never the key', () => { + const { svc } = setup(); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + expect(svc.listSources().map((s) => s.name)).toEqual(['notes']); + expect(svc.indexedSources().map((s) => s.name)).toEqual([indexKeyOf('com.acme.kb', 'notes')]); + }); +}); + +describe('removal — each door removes its own', () => { + it('unregisterSource removes a source registered in code and keeps its index', () => { + const { svc, dropped } = setup(); + svc.registerSource(source('notes')); + svc.unregisterSource('notes'); + expect(svc.listSources()).toEqual([]); + expect(dropped).toEqual([]); + // Naming no source is a no-op. + expect(() => svc.unregisterSource('notes')).not.toThrow(); + }); + + it('unregisterSource refuses a metadata item RESOURCE_CONFLICT / 409, naming what removes it; the source stays', () => { + const { svc } = setup(); + svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + const refusal = refusalOf(() => svc.unregisterSource('acme-notes')); + expect(refusal.code).toBe('RESOURCE_CONFLICT'); + expect(refusal.status).toBe(409); + expect(refusal.message).toContain('delete the item'); + expect(svc.describeSources().map((s) => s.id)).toEqual(['acme-notes']); + }); + + it('dropMetadataSource unregisters the item and drops its index, handing the adapter the keyed source', async () => { + const { svc, dropped } = setup(); + svc.registerSource(source('notes')); + const entry = svc.registerMetadataSource(source('notes'), { packageId: 'com.acme.kb', namespace: 'acme' }); + expect(await svc.dropMetadataSource(entry.key)).toMatchObject({ face: 'acme-notes' }); + expect(dropped).toEqual([{ name: entry.key, reason: 'manual' }]); + expect(svc.describeSources().map((s) => s.id)).toEqual(['notes']); + // Not this door's: a source registered in code is not dropped through it. + expect(await svc.dropMetadataSource('notes')).toBeUndefined(); + expect(dropped).toHaveLength(1); + expect(svc.listSources()).toHaveLength(1); + }); + + it('a dropSource that throws is reported once at warn, naming the source; the source is still removed', async () => { + const { svc, adapter, logger } = setup(); + (adapter as { dropSource: unknown }).dropSource = async () => { throw new Error('store offline'); }; + const entry = svc.registerMetadataSource(source('notes')); + await expect(svc.dropMetadataSource(entry.key)).resolves.toMatchObject({ face: 'notes' }); + const lines = logger.warn.mock.calls.map((c) => String(c[0])); + expect(lines.filter((l) => l.includes("source 'notes' was removed, and its index was not dropped"))).toHaveLength(1); + expect(lines.join('\n')).toContain('store offline'); + expect(svc.listSources()).toEqual([]); + }); +}); + +describe('onSourcesChanged — told after every change, through either door', () => { + it('fires on a registration, a reload, a removal and a drop; not after the unsubscribe', async () => { + const { svc } = setup(); + const listener = vi.fn(); + const off = svc.onSourcesChanged(listener); + svc.registerSource(source('notes')); + const entry = svc.registerMetadataSource(source('other')); + svc.registerMetadataSource(source('other', { label: 'again' })); + svc.unregisterSource('notes'); + await svc.dropMetadataSource(entry.key); + expect(listener).toHaveBeenCalledTimes(5); + off(); + svc.registerSource(source('notes')); + expect(listener).toHaveBeenCalledTimes(5); + }); + + it('a listener that throws is reported at warn and does not stop the next one', () => { + const { svc, logger } = setup(); + const second = vi.fn(); + svc.onSourcesChanged(() => { throw new Error('listener broke'); }); + svc.onSourcesChanged(second); + expect(() => svc.registerSource(source('notes'))).not.toThrow(); + expect(second).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('listener broke')); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index 1de64044070..35115df52b1 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -35,18 +35,18 @@ function adapterWith(hitsBySource: Record): IKnowledgeAd upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: vi.fn(async (_query: string, opts: { source: KnowledgeSource }) => { - searched.push(opts.source.id); - return hitsBySource[opts.source.id] ?? []; + searched.push(opts.source.name); + return hitsBySource[opts.source.name] ?? []; }), } as unknown as IKnowledgeAdapter & { searched: string[] }; } function objectSource(id: string, object: string, extra: Partial = {}): KnowledgeSource { return { - id, + name: id, label: `${id} label`, adapter: 'memory', - source: { kind: 'object', object, contentFields: ['body'] } as ObjectKnowledgeSource, + source: { kind: 'object', object, content: ['body'] } as ObjectKnowledgeSource, ...extra, }; } @@ -163,22 +163,18 @@ describe('search_knowledge — the caller\'s execution context', () => { it('caps the answer at the default topK when none is named', async () => { const adapter = adapterWith({ - // A file source's hits name no record: nothing for the row-level re-check to drop. - policy_clauses: Array.from({ length: 9 }, (_, i) => { - const { sourceRecordId: _record, ...fileHit } = hit('policy_clauses', `p${i}`, 1 - i / 10); - return fileHit; - }), + policy_clauses: Array.from({ length: 9 }, (_, i) => hit('policy_clauses', `p${i}`, 1 - i / 10)), }); - const service = new KnowledgeService({ logger: { warn: () => undefined } }); + // Every row re-checks readable: the cap is the only thing that shortens the answer. + const dataEngine = { + find: async (_object: string, q: { where?: { id?: { $in?: string[] } } }) => + (q.where?.id?.$in ?? []).map((id) => ({ id })), + } as unknown as IDataEngine; + const service = new KnowledgeService({ dataEngine, logger: { warn: () => undefined } }); service.registerAdapter('memory', adapter); - service.registerSource({ - id: 'policy_clauses', - label: 'Policies', - adapter: 'memory', - source: { kind: 'file', uris: ['file:///p.md'] }, - } as unknown as KnowledgeSource); - const fileHits = (await service.knowledgeTools().searchKnowledge({ query: 'q' }, caller)).hits; - expect(fileHits).toHaveLength(SEARCH_KNOWLEDGE_DEFAULT_TOP_K); + service.registerSource(objectSource('policy_clauses', 'policy_clause')); + const capped = (await service.knowledgeTools().searchKnowledge({ query: 'q' }, caller)).hits; + expect(capped).toHaveLength(SEARCH_KNOWLEDGE_DEFAULT_TOP_K); }); }); @@ -230,7 +226,7 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => { const answer = adapter.search as unknown as ReturnType; const inner = answer.getMockImplementation()! as (query: string, opts: { source: KnowledgeSource }) => Promise; answer.mockImplementation(async (query: string, opts: { source: KnowledgeSource }) => { - if (refusing.includes(opts.source.id)) throw refusal(); + if (refusing.includes(opts.source.name)) throw refusal(); return inner(query, opts); }); const engine = { @@ -403,11 +399,11 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge ]; const NOTES: Row[] = [{ id: 'n1', body: 'staff note', author: 'A' }]; const clauses = objectSource('clauses', 'clause', { - source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy', 'status'] } as ObjectKnowledgeSource, + source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: ['policy', 'status'] } as ObjectKnowledgeSource, }); const notes = objectSource('notes', 'note', { aiExposed: false, - source: { kind: 'object', object: 'note', contentFields: ['body'], metadataFields: ['author'] } as ObjectKnowledgeSource, + source: { kind: 'object', object: 'note', content: ['body'], metadataFields: ['author'] } as ObjectKnowledgeSource, }); /** The hit an index answers for `row`'s passage `n`: the document's metadata and stored docHash, as an adapter returns them. */ @@ -416,7 +412,7 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge return { chunkId: `${doc.id}#${n}`, documentId: doc.id, - sourceId: source.id, + sourceId: source.name, sourceRecordId: row.id, score, snippet: `${row.body as string} (${n})`, @@ -443,8 +439,8 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number }) => { - asked.push({ source: opts.source.id, opts: opts as unknown as Record }); - return [...(corpus[opts.source.id] ?? [])].slice(0, opts.topK); + asked.push({ source: opts.source.name, opts: opts as unknown as Record }); + return [...(corpus[opts.source.name] ?? [])].slice(0, opts.topK); }), } as unknown as IKnowledgeAdapter; const matches = (row: Row, where: Record = {}): boolean => @@ -500,23 +496,6 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge expect(JSON.stringify(answer)).not.toContain('draft'); }); - it('groupBy over a file source: one hit per document, and no groupValue even where its hit carries the field', async () => { - const manuals = { - id: 'manuals', - label: 'Manuals', - adapter: 'memory', - source: { kind: 'file', uris: ['file:///manual.md'] }, - } as unknown as KnowledgeSource; - const adapter = adapterWith({ - manuals: [{ chunkId: 'manuals:m#0', documentId: 'manuals:m', sourceId: 'manuals', score: 0.95, snippet: 'manual', metadata: { policy: 'P_manual' } }], - }); - const service = new KnowledgeService({ logger: { warn: () => undefined, debug: () => undefined } }); - service.registerAdapter('memory', adapter); - service.registerSource(manuals); - const answer = await service.knowledgeTools().searchKnowledge({ query: 'q', groupBy: 'policy' }, caller); - expect(answer.hits).toEqual([{ sourceId: 'manuals', documentId: 'manuals:m', snippet: 'manual', score: 0.95 }]); - }); - it('scope: only hits from the named records', async () => { const { tools } = setupModes(); const answer = await tools.searchKnowledge({ query: 'q', scope: [{ object: 'clause', ids: ['c2', 'c3'] }] }, caller); diff --git a/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts b/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts index 2f6f977b10c..5bc9adc2135 100644 --- a/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts +++ b/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts @@ -28,6 +28,7 @@ import type { KnowledgeSource } from '@objectstack/spec/ai'; import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; import type { KnowledgeService } from '../knowledge-service.js'; +import { indexKeyOf } from '../knowledge-source-registry.js'; const FIXED_NOW = 1_700_000_000_000; const OLD = '2020-01-01T00:00:00Z'; // comfortably past every cutoff below @@ -40,10 +41,10 @@ const OBJECTS: LifecycleObjectLike[] = [ function noteSource(overrides: Partial = {}): KnowledgeSource { return { - id: 'task_notes', + name: 'task_notes', label: 'Task notes', adapter: 'fake', - source: { kind: 'object', object: 'task', contentFields: ['notes'] }, + source: { kind: 'object', object: 'task', content: ['notes'] }, ...overrides, } as KnowledgeSource; } @@ -337,11 +338,11 @@ describe('#4672 — registration seam', () => { sources: [ noteSource(), // A second source on the SAME object must not register a second guard… - noteSource({ id: 'task_titles' }), + noteSource({ name: 'task_titles' }), // …and a source on another object gets its own. noteSource({ - id: 'doc_body', - source: { kind: 'object', object: 'doc', contentFields: ['body'] }, + name: 'doc_body', + source: { kind: 'object', object: 'doc', content: ['body'] }, } as Partial), ], }, @@ -363,13 +364,9 @@ describe('#4672 — registration seam', () => { expect(ctx.logger.info).not.toHaveBeenCalledWith(expect.stringContaining('reap guards registered')); }); - it('never asks for the lifecycle service when no object source is declared', async () => { + it('never asks for the lifecycle service when no source is declared', async () => { const { asked } = await boot( - { - sources: [ - { id: 'handbooks', label: 'Handbooks', adapter: 'fake', source: { kind: 'file', prefix: 'kb/' } } as KnowledgeSource, - ], - }, + { sources: [] }, { lifecycle: lifecycleOver(reapEngine({ task: [], audit_log: [] }).engine) }, ); @@ -398,3 +395,59 @@ describe('#4672 — registration seam', () => { expect(registrations).toEqual([]); }); }); + +describe('ADR-0161 K3, item 2 — the guarded object set follows the sources', () => { + it('a source registered in code after boot, on an object no source indexed before, is guarded from then on', async () => { + const { engine, deleted, idsLeft } = reapEngine({ task: [{ id: 'k1', deleted_at: OLD }], audit_log: [] }); + const lifecycle = lifecycleOver(engine); + const { adapter, deletedDocs, reasons } = fakeAdapter(); + const { service } = await boot({ sources: [] }, { lifecycle, adapter }); + + service.registerSource(noteSource()); + await lifecycle.sweep(); + + expect(deletedDocs).toEqual(['task_notes:k1']); + expect(reasons).toEqual(['lifecycle-reap']); + expect(deleted).toEqual([{ object: 'task', id: 'k1' }]); + expect(idsLeft('task')).toEqual([]); + }); + + it("a package's knowledge_source item loaded after boot is guarded, and de-indexed under its own index key", async () => { + const { engine, deleted } = reapEngine({ task: [{ id: 'k1', deleted_at: OLD }], audit_log: [] }); + const lifecycle = lifecycleOver(engine); + const { adapter, deletedDocs } = fakeAdapter(); + const { service } = await boot({ sources: [] }, { lifecycle, adapter }); + + const entry = service.registerMetadataSource(noteSource(), { packageId: 'com.acme.kb', namespace: 'acme' }); + await lifecycle.sweep(); + + expect(entry.key).toBe(indexKeyOf('com.acme.kb', 'task_notes')); + expect(deletedDocs).toEqual([`${entry.key}:k1`]); + expect(deleted).toEqual([{ object: 'task', id: 'k1' }]); + }); + + it('an object is registered once: a later source on it, and a source that reloads, register nothing again', async () => { + const registered: string[] = []; + const fakeLifecycle: any = { registerReapGuard: (object: string) => registered.push(object) }; + const { service } = await boot({ sources: [noteSource()] }, { lifecycle: fakeLifecycle }); + expect(registered).toEqual(['task']); + + service.registerSource(noteSource({ name: 'task_titles' })); + service.registerMetadataSource(noteSource({ name: 'task_bodies' }), { packageId: 'com.acme.kb' }); + service.registerMetadataSource(noteSource({ name: 'task_bodies', label: 'again' }), { packageId: 'com.acme.kb' }); + expect(registered).toEqual(['task']); + + service.registerMetadataSource( + noteSource({ name: 'doc_body', source: { kind: 'object', object: 'doc', content: ['body'] } } as Partial), + ); + expect(registered).toEqual(['task', 'doc']); + }); + + it('a source whose index an external indexer owns adds no guard when it arrives after boot', async () => { + const registered: string[] = []; + const fakeLifecycle: any = { registerReapGuard: (object: string) => registered.push(object) }; + const { service } = await boot({ sources: [] }, { lifecycle: fakeLifecycle }); + service.registerSource(noteSource({ refresh: { onRecordChange: false } })); + expect(registered).toEqual([]); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index a2419dad168..f21b10999ed 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -6,7 +6,10 @@ export type { KnowledgeSearchRefusal, KnowledgeSearchReport, KnowledgeServiceOptions, + KnowledgeSourceDescription, } from './knowledge-service.js'; +export { KNOWLEDGE_SOURCE_TYPE, indexKeyOf } from './knowledge-source-registry.js'; +export type { KnowledgeSourceDoor, KnowledgeSourceEntry, KnowledgeSourceHolder } from './knowledge-source-registry.js'; export { ASSEMBLY_RULE_VERSION, INDEX_FINGERPRINT_VERSION, diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index 931d8fc35ca..58b3bdfe893 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -5,7 +5,9 @@ * the operator's rebuild), on the `knowledge` settings namespace beside its * `test` action: * - * - `rebuild` — payload `{ "source": "ID" }`. Starts one complete build of + * - `rebuild` — payload `{ "source": "ID" }`, where `ID` names a source the + * way `search_knowledge` lists it (`NAMESPACE-NAME` for a package's source, + * the bare name otherwise; a bare name one source has is read too). Starts one complete build of * that source (`KnowledgeService.rebuildSource`, trigger `operator`) in the * background and answers at once with the build's record; a build of the * source already running on the node that answers is refused, not doubled. @@ -26,9 +28,8 @@ */ import type { SettingsActionHandler } from '@objectstack/service-settings'; -import type { KnowledgeSource } from '@objectstack/spec/ai'; import type { KnowledgeBuildRecord, KnowledgeIndexReading } from './knowledge-build.js'; -import type { KnowledgeService } from './knowledge-service.js'; +import type { KnowledgeService, KnowledgeSourceDescription } from './knowledge-service.js'; /** The `knowledge` settings action that starts a rebuild of one source. */ export const KNOWLEDGE_REBUILD_ACTION = 'rebuild'; @@ -39,15 +40,17 @@ export const KNOWLEDGE_INDEX_STATUS_ACTION = 'index_status'; /** The part of `KnowledgeService` the two actions use. */ export type KnowledgeBuildActionsService = Pick< KnowledgeService, - 'listSources' | 'getSource' | 'readIndexState' | 'rebuildSource' | 'buildRecord' + 'describeSources' | 'describeSource' | 'readIndexState' | 'rebuildSource' | 'buildRecord' >; /** One source in an `index_status` answer. */ export interface KnowledgeIndexStatusEntry { + /** The source, as `search_knowledge` lists it: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ id: string; label: string; adapter: string; - kind: KnowledgeSource['source']['kind']; + /** The package that holds the source; absent for a source no package holds. */ + packageId?: string; /** What the adapter holds against what the service expects. */ index: KnowledgeIndexReading; /** The last build this node ran of the source, or `null`. */ @@ -76,10 +79,29 @@ function readSourcePayload(payload: unknown): { source?: string } | { refused: s } function sourceIds(service: KnowledgeBuildActionsService): string { - const ids = service.listSources().map((s) => s.id); + const ids = service.describeSources().map((s) => s.id); return ids.length === 0 ? 'none is registered' : ids.join(', '); } +/** + * The source a payload's `source` names, read by the service's one rule, or + * why it names none: no source has the name, or several do (the service's + * `409`, whose sentence lists each by the spelling that names it alone). + */ +function describe( + service: KnowledgeBuildActionsService, + ref: string, +): { source: KnowledgeSourceDescription } | { refused: string } { + let source: KnowledgeSourceDescription | undefined; + try { + source = service.describeSource(ref); + } catch (err) { + return { refused: err instanceof Error ? err.message : String(err) }; + } + if (!source) return { refused: `No knowledge source '${ref}' is registered (${sourceIds(service)}).` }; + return { source }; +} + /** The `rebuild` action, bound to `service`. */ export function knowledgeRebuildActionHandler(service: KnowledgeBuildActionsService): SettingsActionHandler { return async ({ payload }) => { @@ -88,17 +110,9 @@ export function knowledgeRebuildActionHandler(service: KnowledgeBuildActionsServ if (read.source === undefined) { return { ok: false, severity: 'error', message: `Name the source to rebuild: { "source": "ID" } (${sourceIds(service)}).` }; } - const source = service.getSource(read.source); - if (!source) { - return { ok: false, severity: 'error', message: `No knowledge source '${read.source}' is registered (${sourceIds(service)}).` }; - } - if (source.source.kind !== 'object') { - return { - ok: false, - severity: 'error', - message: `Source '${source.id}' is a ${source.source.kind} source: its adapter (${source.adapter}) ingests it, and the knowledge service does not build it.`, - }; - } + const named = describe(service, read.source); + if ('refused' in named) return { ok: false, severity: 'error', message: named.refused }; + const source = named.source; const running = service.buildRecord(source.id); if (running?.status === 'running') { return { @@ -131,23 +145,21 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions return async ({ payload }) => { const read = readSourcePayload(payload); if ('refused' in read) return { ok: false, severity: 'error', message: read.refused }; - let targets: KnowledgeSource[]; + let targets: KnowledgeSourceDescription[]; if (read.source !== undefined) { - const source = service.getSource(read.source); - if (!source) { - return { ok: false, severity: 'error', message: `No knowledge source '${read.source}' is registered (${sourceIds(service)}).` }; - } - targets = [source]; + const named = describe(service, read.source); + if ('refused' in named) return { ok: false, severity: 'error', message: named.refused }; + targets = [named.source]; } else { - targets = service.listSources(); + targets = service.describeSources(); } const sources: KnowledgeIndexStatusEntry[] = []; for (const source of targets) { sources.push({ id: source.id, - label: source.label, - adapter: source.adapter, - kind: source.source.kind, + label: source.source.label, + adapter: source.source.adapter, + ...(source.packageId === undefined ? {} : { packageId: source.packageId }), index: await service.readIndexState(source.id), build: service.buildRecord(source.id) ?? null, }); diff --git a/packages/services/service-knowledge/src/knowledge-build.ts b/packages/services/service-knowledge/src/knowledge-build.ts index ba44c994343..d21a2b3c944 100644 --- a/packages/services/service-knowledge/src/knowledge-build.ts +++ b/packages/services/service-knowledge/src/knowledge-build.ts @@ -58,8 +58,8 @@ import type { AdapterIndexStatus, KnowledgeReindexResult } from '@objectstack/sp * automatically; the operator's rebuild is the way. * - `unreadable` — reading the adapter failed. Nothing is built; `detail` * says why. - * - `not-built-here` — the service does not build this source: a `file` or - * `http` source (its adapter ingests it), or no data engine is bound. + * - `not-built-here` — the service cannot build this source here: no data + * engine is bound. */ export type KnowledgeIndexState = | 'nothing' @@ -85,8 +85,12 @@ export interface KnowledgeIndexReading { held?: AdapterIndexStatus; } -/** Who started a build: the boot's first-build pass, or an administrator. */ -export type KnowledgeBuildTrigger = 'boot' | 'operator'; +/** + * Who started a build: the boot's first-build pass, a `knowledge_source` item + * that was added or changed while the process runs (`reload`), or an + * administrator. + */ +export type KnowledgeBuildTrigger = 'boot' | 'reload' | 'operator'; /** How far a running build has walked; the totals of a finished one. */ export interface KnowledgeBuildProgress { diff --git a/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts b/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts index b4c9546cd25..7928f452911 100644 --- a/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts +++ b/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts @@ -42,7 +42,7 @@ import { createHash } from 'node:crypto'; import type { AdapterIndexExpectation, IKnowledgeAdapter } from '@objectstack/spec/contracts'; -import type { KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; import { SPLIT_ALGORITHM_VERSION, type ResolvedSplit } from './split/index.js'; import { documentTitleField } from './knowledge-source-admission.js'; @@ -55,8 +55,8 @@ export const RECIPE_HASH_VERSION = 'rh1'; /** * The version of the assembly rule — how the listed content values become one - * text (`recordToDocument`: each listed field's value, `'*'` as every string - * field, joined by a blank line). Part of the content recipe. Bump it in the + * text (`recordToDocument`: each listed field's value, joined by a blank + * line). Part of the content recipe. Bump it in the * change that makes assembly give another text for the same record and source. */ export const ASSEMBLY_RULE_VERSION = 1; @@ -80,7 +80,7 @@ export interface IndexFingerprintInput { /** What {@link computeRecipeHash} reads. */ export interface RecipeHashInput { source: KnowledgeSource; - /** The registered object definition of an object source, when the engine exposes one. */ + /** The registered definition of the source's object, when the engine exposes one. */ schema?: unknown; } @@ -108,10 +108,7 @@ export function computeIndexFingerprint(input: IndexFingerprintInput): string { /** The recipe hash of a source (ADR-0161 K7, "The recipe hash"). */ export function computeRecipeHash(input: RecipeHashInput): string { const { source, schema } = input; - if (source.source.kind !== 'object') { - return hashed(RECIPE_HASH_VERSION, { kind: source.source.kind }); - } - const objSource = source.source as ObjectKnowledgeSource; + const objSource = source.source; const withheld = [...new Set([ ...collectCredentialWriteResponseFields(schema), ...collectInternalWriteResponseFields(schema), @@ -131,17 +128,16 @@ export function indexExpectation(fingerprint: IndexFingerprintInput, recipe: Rec /** * The content recipe (K7, point 2): what assembly reads to build the text. - * For an object source, the object and the ORDERED content list — the order is - * the order of the text. Another kind is not assembled by the service; its - * recipe is its kind. + * The object and the ORDERED content list — the order is the order of the + * text. Neither hash reads the source's name or its holder, so a source keeps + * its index when only its spelling moves (ADR-0161 K6: `id` became `name`). */ function contentRecipe(source: KnowledgeSource): Record { - if (source.source.kind !== 'object') return { kind: source.source.kind }; - const objSource = source.source as ObjectKnowledgeSource; + const objSource = source.source; return { - kind: 'object', + kind: objSource.kind, object: objSource.object, - content: [...objSource.contentFields], + content: [...objSource.content], assembly: ASSEMBLY_RULE_VERSION, }; } diff --git a/packages/services/service-knowledge/src/knowledge-reap-guard.ts b/packages/services/service-knowledge/src/knowledge-reap-guard.ts index e948501667e..2aa93eeccd0 100644 --- a/packages/services/service-knowledge/src/knowledge-reap-guard.ts +++ b/packages/services/service-knowledge/src/knowledge-reap-guard.ts @@ -1,9 +1,8 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import type { IKnowledgeService } from '@objectstack/spec/contracts'; import type { KnowledgeSource } from '@objectstack/spec/ai'; import { documentIdFor, objectSourcesFor } from './knowledge-service.js'; -import type { KnowledgeLogger } from './knowledge-service.js'; +import type { KnowledgeLogger, KnowledgeService } from './knowledge-service.js'; /** * Structural shape of a `LifecycleReapGuard` (ADR-0057 amendment). @@ -21,8 +20,12 @@ type ReapGuard = ( rows: Array>, ) => Promise>; -/** The slice of `IKnowledgeService` the guard consumes — existing members only. */ -type KnowledgeReapGuardService = Pick; +/** + * The slice of `KnowledgeService` the guard consumes. `indexedSources` answers + * each source as its adapter is handed it — `name` is its index key — which + * is what a document id is built from and what the adapter's context carries. + */ +type KnowledgeReapGuardService = Pick; /** * Reap guard that DE-INDEXES a row before the platform lifecycle sweep deletes @@ -30,7 +33,7 @@ type KnowledgeReapGuardService = Pick(); for (const source of sources) { - if (source.source.kind !== 'object') continue; const object = source.source.object; // Asked through the SAME predicate the guard uses, never a second copy of // it: "is this object guarded?" and "what would the guard de-index for it?" diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index 02591043beb..3de3422314d 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -113,8 +113,7 @@ export function scopeTermsFor( schemaOf: (object: string) => unknown, ): SourceScope { const out: SourceScope = { terms: [], ambiguous: [] }; - if (source.source.kind !== 'object') return out; - const objSource = source.source as ObjectKnowledgeSource; + const objSource = source.source; let links: Map | undefined; for (const entry of scope) { if (entry.ids.length === 0) continue; diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index f6c2c6a3909..4b904985898 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -17,11 +17,14 @@ import { } from '@objectstack/embedder-openai'; import { aiTestEmbedderActionHandler } from '@objectstack/service-settings'; import { RECORD_RESTORED_EVENT } from '@objectstack/spec/data'; +import { stripReadDecorations } from '@objectstack/spec/kernel'; import { KnowledgeService } from './knowledge-service.js'; import type { KnowledgeLogger } from './knowledge-service.js'; import type { KnowledgeBuildLock } from './knowledge-build.js'; import type { KnowledgeFieldSecurity } from './knowledge-source-admission.js'; import { createKnowledgeReapGuard, guardedObjectsFor } from './knowledge-reap-guard.js'; +import { KnowledgeSourceLoader } from './knowledge-source-loader.js'; +import { KNOWLEDGE_SOURCE_TYPE } from './knowledge-source-registry.js'; import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js'; import { UnknownKeyError, UnknownNamespaceError } from '@objectstack/service-settings'; @@ -364,8 +367,8 @@ export interface KnowledgeServicePluginOptions { * const kernel = new ObjectKernel(); * kernel.use(new KnowledgeServicePlugin({ * sources: [{ - * id: 'task_notes', label: 'Task notes', adapter: 'memory', - * source: { kind: 'object', object: 'task', contentFields: ['notes'] }, + * name: 'task_notes', label: 'Task notes', adapter: 'memory', + * source: { kind: 'object', object: 'task', content: ['notes'] }, * }], * })); * await kernel.bootstrap(); @@ -404,6 +407,13 @@ export class KnowledgeServicePlugin implements Plugin { */ private realtime: IRealtimeService | undefined; private logger: KnowledgeLogger | undefined; + /** The loader of the published `knowledge_source` items (`knowledge-source-loader.ts`). */ + private loader: KnowledgeSourceLoader | undefined; + /** Dropped at destroy: the protocol's mutation signal and the service's source-change signal. */ + private unsubscribes: Array<() => void> = []; + /** The one reap guard, and the objects it is registered for so far ({@link syncReapGuards}). */ + private reapGuard: ReturnType | undefined; + private readonly guardedObjects = new Set(); constructor(private readonly options: KnowledgeServicePluginOptions = {}) {} @@ -412,9 +422,9 @@ export class KnowledgeServicePlugin implements Plugin { try { engine = ctx.getService('objectql'); } catch { - // Data engine not wired — service still works in pure-search mode - // but RLS re-checks will be conservative (drop object-source hits - // when caller is non-system). + // Data engine not wired — the service still mounts, and serves a + // caller that is not the system identity no source at all: no hit can + // be re-checked without an engine. } const logger: KnowledgeLogger = { @@ -535,12 +545,18 @@ export class KnowledgeServicePlugin implements Plugin { } async start(ctx: PluginContext): Promise { + this.loadPublishedSources(ctx); + // The embedder is provided at `kernel:bootstrapped`, after every // `kernel:ready` handler has settled: an embedder another plugin registers // in its init(), start() or `kernel:ready` (cloud `service-ai` reads its // settings there) is seen and kept, never doubled. A consumer resolves // `EMBEDDER_SERVICE` where it embeds, not at boot. ctx.hook('kernel:bootstrapped', async () => { + // The published sources once more: a package another plugin registers + // in its own `kernel:ready` handler (the install-local rehydrate) is + // listed only now, and the first build below must see its sources. + await this.reconcileSources(ctx, 'boot'); await this.provideEmbedder(ctx); // [ADR-0161 K7] The first build: every source a build is due for is // built once, in the background — after the embedder is provided, @@ -562,10 +578,15 @@ export class KnowledgeServicePlugin implements Plugin { const service = this.service; if (!service) return; + // [ADR-0161 K3, item 2] The guarded object set follows the sources: a + // source registered or loaded after boot for an object no source indexed + // before gets its guard when it arrives. + this.unsubscribes.push(service.onSourcesChanged(() => this.syncReapGuards(ctx, service))); + ctx.hook('kernel:ready', async () => { // Reap-path de-indexing first: it is independent of the realtime service, // and the branch below returns early when that one is absent. - this.installReapGuards(ctx, service); + this.syncReapGuards(ctx, service); let realtime: IRealtimeService | null = null; try { @@ -638,10 +659,10 @@ export class KnowledgeServicePlugin implements Plugin { // stale index at all: `installReapGuards` de-indexes those rows before // they are deleted. What is left is APPLICATION-level predicate writes // — a caller's own `multi: true` update/delete — which no guard sits in - // front of. That half is honestly uncovered rather than quietly - // half-claimed, and stays so until a real object source justifies the - // adapter-enumeration surface it would need (#4606's enforced-first - // rule). Reporting it accurately is the whole job of this branch. + // front of. The event stream cannot repair that half (it names no + // record); a complete reindex does, by the purge ADR-0161 K8 items 1 + // and 2 gave it. Reporting it accurately is the whole job of this + // branch. // A complete reindexSource refreshes the rows that still exist and // match and, over an adapter that lists its documents, purges the // documents of rows that are gone or no longer match — the warning @@ -723,9 +744,80 @@ export class KnowledgeServicePlugin implements Plugin { else ctx.logger.warn?.(line); } + /** + * Load the published `knowledge_source` items (ADR-0161 K4, clause 3) and + * keep the service's sources in step with them. + * + * - **At boot**: one pass at `kernel:ready`, when every plugin has started + * and the apps' packages are registered, and one more at + * `kernel:bootstrapped`, before the first build (see `start`). + * - **While the process runs**: one pass on each signal that a published + * item may have changed — the metadata protocol's mutation signal + * (`onMetadataMutation`: a save, a publish, a delete, a revert, a + * rollback, and on a cluster the same write converging on a peer), for a + * `knowledge_source` item that is not a draft; and the kernel's + * `metadata:reloaded` (a package published, installed or removed, a dev + * artifact recompiled). A draft is not a published item and loads nothing. + * + * The listing is the protocol's execution read of the type + * (`getMetaItemsForExecution`, else `getMetaItems`): the stored bodies with + * each row's package, the merge every `/meta` read serves. With no + * `protocol` service there is no metadata store, and the sources are the + * ones registered in code. + */ + private loadPublishedSources(ctx: PluginContext): void { + const service = this.service; + if (!service) return; + this.loader = new KnowledgeSourceLoader({ + service, + logger: this.logger, + buildOnReload: this.options.buildAtBoot !== false, + readItems: () => readPublishedSources(ctx), + namespaceOf: (packageId) => packageNamespaceOf(ctx, packageId), + }); + + ctx.hook('kernel:ready', async () => { + await this.reconcileSources(ctx, 'boot'); + // Resolved here, once every plugin has started, so a protocol that + // registers after this plugin is seen. + const protocol = protocolOf(ctx); + if (typeof protocol?.onMetadataMutation === 'function') { + const unsubscribe = protocol.onMetadataMutation((evt) => { + if (!evt || evt.type !== KNOWLEDGE_SOURCE_TYPE || evt.state === 'draft') return; + void this.reconcileSources(ctx, 'reload'); + }); + if (typeof unsubscribe === 'function') this.unsubscribes.push(unsubscribe); + } + }); + ctx.hook('metadata:reloaded', async () => { + await this.reconcileSources(ctx, 'reload'); + }); + } + + /** One loader pass; never throws — a failed pass is reported and changes nothing further. */ + private async reconcileSources(ctx: PluginContext, reason: 'boot' | 'reload'): Promise { + if (!this.loader) return; + try { + const result = await this.loader.reconcile(reason); + const total = result.added.length + result.changed.length + result.removed.length; + if (total === 0) return; + const part = (label: string, faces: string[]): string => (faces.length === 0 ? '' : ` ${label}: ${faces.join(', ')}.`); + ctx.logger.info?.( + `KnowledgeServicePlugin: knowledge_source items loaded.${part('Added', result.added)}` + + `${part('Changed', result.changed)}${part('Removed, index dropped', result.removed)}`, + ); + } catch (err) { + ctx.logger.warn?.( + `KnowledgeServicePlugin: loading the knowledge_source items failed (${err instanceof Error ? err.message : String(err)}); ` + + 'the sources stay as they were. The next change to a knowledge source, or a restart, loads them again.', + ); + } + } + /** * Register the lifecycle reap guard (#4672, ADR-0057 amendment) for every - * object an `object` source projects. + * object a source projects — at `kernel:ready`, and again each time the set + * of sources changes (ADR-0161 K3, item 2: the set is dynamic). * * ## Why the guard rather than an event * @@ -737,37 +829,32 @@ export class KnowledgeServicePlugin implements Plugin { * and it arrives batched and interruptible for free (500 rows a batch, 20 * batches a sweep), which is the cost bound this work would otherwise owe. * - * ## Seams, all pre-existing + * ## Seams * * Reached exactly as `service-storage` reaches it for `sys_file` byte * reclaim: duck-typed `ctx.getService('lifecycle')` + - * `registerReapGuard(object, guard)`. No spec key, no `IKnowledgeAdapter` - * member, no `packages/objectql` change (#4606's zero-addition boundary). - * Guards compose by intersection (#5535), so registering here cannot displace - * storage's byte-reclaim guard, nor it ours. + * `registerReapGuard(object, guard)`. Guards compose by intersection + * (#5535), so registering here cannot displace storage's byte-reclaim + * guard, nor it ours. * * Silent when there is no lifecycle service (a bare kernel): the sweep is - * what deletes rows, so no sweeper means no orphans to prevent. Nothing is - * concluded about the registry either — this runs at `kernel:ready`, and the - * absence is neither cached nor asserted. - * - * One guard instance serves every object (it resolves its targets from the - * `object` it is called with), and re-registering the identical function is a - * documented no-op, so re-run wiring cannot double a de-index. + * what deletes rows, so no sweeper means no orphans to prevent. The absence + * is not cached: the next change of the sources asks again. * - * ## Boundary, stated rather than implied + * ## The object set follows the sources * - * The OBJECT SET is read once, here — every object declared by boot time, - * which is every object the sources a host composes can name. A source - * registered later through `registerSource` for an object that had none at - * boot is therefore unguarded, while one for an already-guarded object is - * picked up (the guard re-resolves its targets on each call). Making the set - * itself dynamic would mean a new notification surface on the service, which - * is precisely the addition #4606 rules out until a real `object` source - * exists to justify it. + * One guard instance serves every object (it resolves its targets from the + * `object` it is called with, each call). The objects it is registered for + * are remembered, and each pass registers it for the objects that have a + * source now and had none before — a source loaded from a + * `knowledge_source` item saved after boot, or registered in code after + * boot, is guarded from that moment. An object whose last source was + * removed keeps its registration: the lifecycle service has no unregister, + * and the guard, finding no source for the object, confirms every row and + * de-indexes nothing. */ - private installReapGuards(ctx: PluginContext, service: KnowledgeService): void { - const objects = guardedObjectsFor(service.listSources()); + private syncReapGuards(ctx: PluginContext, service: KnowledgeService): void { + const objects = guardedObjectsFor(service.indexedSources()).filter((object) => !this.guardedObjects.has(object)); if (objects.length === 0) return; type LifecycleLike = { @@ -781,11 +868,14 @@ export class KnowledgeServicePlugin implements Plugin { } if (!lifecycle || typeof lifecycle.registerReapGuard !== 'function') return; - const guard = createKnowledgeReapGuard(service, this.logger); + const guard = (this.reapGuard ??= createKnowledgeReapGuard(service, this.logger)); // Called AS A METHOD, never through a detached reference: the real // `LifecycleService.registerReapGuard` reads `this.reapGuards`, so // `const register = lifecycle.registerReapGuard` throws on the first call. - for (const object of objects) lifecycle.registerReapGuard(object, guard); + for (const object of objects) { + lifecycle.registerReapGuard(object, guard); + this.guardedObjects.add(object); + } ctx.logger.info?.( `KnowledgeServicePlugin: reap guards registered with the lifecycle service for [${objects.join(', ')}] — ` + 'rows are de-indexed before the retention sweep deletes them.', @@ -812,6 +902,13 @@ export class KnowledgeServicePlugin implements Plugin { // The boot's first-build pass starts no further build; one already // walking runs to its end (a walk cannot be cancelled part-way). this.service?.stopBuilds(); + for (const unsubscribe of this.unsubscribes.splice(0)) { + try { + unsubscribe(); + } catch { + // best-effort + } + } if (!this.subscriptionId) return; try { await this.realtime?.unsubscribe(this.subscriptionId); @@ -834,3 +931,74 @@ export class KnowledgeServicePlugin implements Plugin { await this.destroy(); } } + +/** The slice of the metadata protocol the loader reads, reached duck-typed. */ +interface KnowledgeSourceProtocol { + getMetaItemsForExecution?(request: { type: string }): Promise; + getMetaItems?(request: { type: string }): Promise; + onMetadataMutation?(listener: (evt: { type?: string; name?: string; state?: string } | undefined) => void): (() => void) | void; +} + +function protocolOf(ctx: PluginContext): KnowledgeSourceProtocol | undefined { + try { + return ctx.getService('protocol') ?? undefined; + } catch { + return undefined; // no protocol service: no metadata store to read. + } +} + +/** + * The published `knowledge_source` items, or `null` when they cannot be read + * (the loader then changes nothing). No `protocol` service, or one with no + * list read, is a composition with no metadata store: it holds no item, which + * is an empty list, not a failed read. + */ +async function readPublishedSources(ctx: PluginContext): Promise { + const protocol = protocolOf(ctx); + const read = typeof protocol?.getMetaItemsForExecution === 'function' + ? protocol.getMetaItemsForExecution.bind(protocol) + : typeof protocol?.getMetaItems === 'function' + ? protocol.getMetaItems.bind(protocol) + : undefined; + if (!read) return []; + let raw: unknown; + try { + raw = await read({ type: KNOWLEDGE_SOURCE_TYPE }); + } catch (err) { + ctx.logger.warn?.( + `KnowledgeServicePlugin: the knowledge_source items could not be read (${err instanceof Error ? err.message : String(err)}); ` + + 'the sources stay as they were.', + ); + return null; + } + // The read hands back a bare array or an `{ items: [...] }` envelope, and + // each entry is the document itself or an `{ item }` wrapper. + const list = Array.isArray(raw) ? raw : (raw as { items?: unknown } | null | undefined)?.items; + if (!Array.isArray(list)) return []; + return list.map((entry) => { + const doc = entry && typeof entry === 'object' && 'item' in entry ? (entry as { item: unknown }).item : entry; + return stripReadDecorations(doc); + }); +} + +/** + * [ADR-0150 D2/D6] The manifest namespace of a package, from the engine's + * registry, or `undefined`: no engine, or an id with no package record. A + * source's face is then its bare name. + */ +function packageNamespaceOf(ctx: PluginContext, packageId: string): string | undefined { + type RegistryLike = { registry?: { getPackage?(id: string): { manifest?: { namespace?: unknown } } | undefined } }; + let engine: RegistryLike | undefined; + try { + engine = ctx.getService('objectql') ?? undefined; + } catch { + return undefined; + } + let namespace: unknown; + try { + namespace = engine?.registry?.getPackage?.(packageId)?.manifest?.namespace; + } catch { + return undefined; + } + return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 079e1b1af8c..6a92b5b9f59 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -28,6 +28,14 @@ import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/secu import { createKnowledgeTools, refusal, type KnowledgeTools } from './knowledge-tools.js'; import { resolveSplit, splitDocument, type ResolvedSplit } from './split/index.js'; import { indexExpectation } from './knowledge-index-fingerprint.js'; +import { + KnowledgeSourceRegistry, + codedError, + packageIdOfItem, + parseKnowledgeSource, + type KnowledgeSourceEntry, + type KnowledgeSourceHolder, +} from './knowledge-source-registry.js'; import { documentOrganizationId, searchOrganizationIds, @@ -136,18 +144,25 @@ export interface KnowledgeServiceOptions { * - Routes search / index calls to the right `IKnowledgeAdapter`. * - Re-checks every hit's `sourceRecordId` against the caller's * `ExecutionContext` so row-level security is preserved end-to-end. - * - Searches an `object` source for a caller only when the caller's exposure + * - Searches a source for a caller only when the caller's exposure * decision serves its object and every field it serves is one the caller * may query (`knowledge-source-admission.ts`), so field-level security and * the object's API exposure hold for passages too. - * - Walks ObjectQL when reindexing an `object` source. + * - Walks ObjectQL when reindexing a source. + * - Holds the registry of sources, one per `(package, name)` + * (`knowledge-source-registry.ts`): every by-name member reads a caller's + * `sourceId` by the one rule (a source's face, else a bare name resolved by + * ADR-0150 D3), and every answer names a source by its face. + * + * No member pushes a document: an index holds what the service assembled from + * the records of a source's object, and nothing else (ADR-0161 K1). * * Non-responsibilities (the parts plugins own): * - Chunking, embedding, vector storage, hybrid retrieval, rerank. */ export class KnowledgeService implements IKnowledgeService { private readonly adapters = new Map(); - private readonly sources = new Map(); + private readonly registry = new KnowledgeSourceRegistry(); private readonly defaultTopK: number; /** Adapters whose answer the scope check has already dropped a hit from — reported once each ({@link searchRound}). */ private readonly scopeIgnoredReported = new Set(); @@ -155,12 +170,12 @@ export class KnowledgeService implements IKnowledgeService { private readonly scopeAmbiguousReported = new Set(); /** * The tail of each document's record-sync chain, keyed by document id - * (`${source.id}:${recordId}`) — see {@link serializeRecordSync}. A key + * (the source's index key, `:`, the record id) — see {@link serializeRecordSync}. A key * lives only while a sync for it is pending. */ private readonly recordSyncTails = new Map>(); /** - * The tail of each source's reindex chain, keyed by source id — see + * The tail of each source's reindex chain, keyed by its index key — see * {@link reindexSource}. A key lives only while a walk of it is pending. */ private readonly reindexTails = new Map>(); @@ -172,10 +187,12 @@ export class KnowledgeService implements IKnowledgeService { * search finds its hash matching, which clears the entry. */ private readonly freshnessRepairs = new Set(); - /** The last build of each source on this node (`knowledge-build.ts`). */ + /** The last build of each source on this node (`knowledge-build.ts`), by index key. */ private readonly builds = new Map(); /** Set by {@link stopBuilds}: the boot pass starts no further build. */ private buildsStopped = false; + /** Told after the set of registered sources changed ({@link onSourcesChanged}). */ + private readonly sourceListeners = new Set<() => void>(); constructor(private readonly options: KnowledgeServiceOptions = {}) { this.defaultTopK = options.defaultTopK ?? 10; @@ -204,78 +221,208 @@ export class KnowledgeService implements IKnowledgeService { // ── Source registry ─────────────────────────────────────────────── + /** + * The code door: register a source that belongs to no package. It takes the + * one package-less slot of its name (`knowledge-source-registry.ts`). + * + * The source is parsed with `KnowledgeSourceSchema`, the schema every door + * parses with, and no conversion is run: a registration that still writes a + * retired key (`id`, `source.contentFields`, …), an unknown key, a `file` or + * `http` kind or a `'*'` content member is refused `400 VALIDATION_ERROR` + * with the schema's own prescription. A registration naming a package + * (`_packageId`) is refused the same way: a package ships its source in its + * `knowledgeSources` collection. + * + * Registering a name this door already registered replaces the earlier + * registration, reported at `warn`. A name the metadata door holds in the + * package-less slot is refused `409 RESOURCE_CONFLICT`, naming both doors. + */ registerSource(source: KnowledgeSource): void { - if (this.sources.has(source.id)) { - this.options.logger?.warn?.(`[knowledge] source overwritten: ${source.id}`); + const parsed = parseKnowledgeSource(source); + if (!parsed.ok) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, + ); + } + const packageId = packageIdOfItem(parsed.source); + if (packageId !== undefined) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused source '${parsed.source.name}': it names package "${packageId}" ` + + '(`_packageId`), and a source registered in code belongs to no package. Ship the source in that ' + + "package's `knowledgeSources` collection, or drop the key.", + ); } - this.sources.set(source.id, source); + const { entry, replaced } = this.registry.register(parsed.source, 'code'); + if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); + this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${entry.authored.adapter})`); + this.sourcesChanged(); + } + + /** + * The metadata door: register the source of one published `knowledge_source` + * item, already parsed ({@link parseKnowledgeSource}), for its holder. An + * item that reloads replaces its own earlier version; a package-less item + * under a name the code door holds is refused `409 RESOURCE_CONFLICT`, + * naming both doors. Called by `KnowledgeServicePlugin`'s loader, never by a + * caller holding `IKnowledgeService`. + */ + registerMetadataSource(source: KnowledgeSource, holder: KnowledgeSourceHolder = {}): KnowledgeSourceEntry { + const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( - `[knowledge] source registered: ${source.id} (adapter=${source.adapter}, kind=${source.source.kind})`, + `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${entry.authored.adapter}` + + `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, ); + this.sourcesChanged(); + return entry; } - unregisterSource(sourceId: string): void { - this.sources.delete(sourceId); + /** The sources that arrived through the metadata door, for the loader that owns them. */ + metadataSources(): KnowledgeSourceEntry[] { + return this.registry.entries().filter((entry) => entry.door === 'metadata'); } - listSources(): KnowledgeSource[] { - return [...this.sources.values()]; + /** + * Be told after a source is registered, replaced or removed, through either + * door. The lifecycle reap guard's object set follows the sources through + * it (ADR-0161 K3, item 2). A listener that throws is reported at `warn` and + * does not stop the others. Answers the unsubscribe. + */ + onSourcesChanged(listener: () => void): () => void { + this.sourceListeners.add(listener); + return () => { + this.sourceListeners.delete(listener); + }; } - getSource(sourceId: string): KnowledgeSource | undefined { - return this.sources.get(sourceId); + private sourcesChanged(): void { + for (const listener of [...this.sourceListeners]) { + try { + listener(); + } catch (err) { + this.options.logger?.warn?.(`[knowledge] a source-change listener failed (${errorText(err)}).`); + } + } } - // ── Document mutations ──────────────────────────────────────────── - /** - * Write one caller-built document. An adapter that declares - * `capabilities.chunks` receives it with the service's passages, split the - * way every other path splits ({@link prepareDocuments}). A `whole` - * document over the embedder's input budget is removed from the index and - * the call throws, naming the estimate and the budget. + * Remove a source the code door registered. The index it built stays with + * its adapter. A source that is a metadata item is not this door's to + * remove: refused `409 RESOURCE_CONFLICT`, naming the item to delete. A + * `sourceId` that names no source is a no-op. */ - async indexDocument(sourceId: string, doc: KnowledgeDocument): Promise { - const source = this.requireSource(sourceId); - const adapter = this.getAdapter(source.adapter); - // `docHash` is the service's to compute (ADR-0161 K8, item 2). A caller's - // own value is refused, never replaced in silence: a door that accepted it - // and stored something else would answer as if it had been honoured. - if (doc.docHash !== undefined) { - throw new Error( - `[knowledge] indexDocument refused document '${doc.id}': docHash is computed by the knowledge service ` + - 'from the content, title and metadata; omit it.', + unregisterSource(sourceId: string): void { + const entry = this.registry.resolve(sourceId); + if (!entry) return; + if (entry.door === 'metadata') { + throw codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] source '${entry.face}' is a knowledge_source metadata item, so unregisterSource does not remove ` + + 'it: delete the item (Studio, the metadata API, or its package), and the knowledge service unregisters it ' + + 'and drops its index.', ); } - // `organizationId` is the service's too (ADR-0161 K8, item 9): it is the - // organization of the record a document was assembled from. A caller's own - // value would place a document inside an organization's ranking scope on - // the caller's word alone. - if (doc.organizationId !== undefined) { - throw new Error( - `[knowledge] indexDocument refused document '${doc.id}': organizationId is set by the knowledge service ` + - "from the record a document is assembled from; omit it.", + this.forget(entry); + } + + /** + * The metadata door's removal: unregister the source held under `key`, and + * drop what its adapter holds for it (`IKnowledgeAdapter.dropSource`, + * ADR-0161 K8 item 4). An adapter without `dropSource`, or one that is not + * mounted, keeps what it holds, said once at `warn` naming the source; a + * `dropSource` that throws is reported the same way. Never throws. Answers + * the removed entry, or `undefined` when the key held none. + */ + async dropMetadataSource(key: string): Promise { + const entry = this.registry.byIndexKey(key); + if (!entry || entry.door !== 'metadata') return undefined; + this.forget(entry); + const kept = (why: string): void => { + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + + `What adapter '${entry.authored.adapter}' holds under the key '${entry.key}' stays until it is removed there.`, ); + }; + const adapter = this.adapters.get(entry.authored.adapter); + if (!adapter) { + kept(`adapter '${entry.authored.adapter}' is not mounted.`); + return entry; } - // The passages are the service's too (ADR-0161 K1): one splitter cuts - // every document, so a caller's own `chunks` are refused the same way. - if (doc.chunks !== undefined) { - throw new Error( - `[knowledge] indexDocument refused document '${doc.id}': chunks are cut by the knowledge service's ` + - "splitter from the content, by the source's split; omit them.", - ); + if (typeof adapter.dropSource !== 'function') { + kept(`adapter '${entry.authored.adapter}' has no dropSource.`); + return entry; } - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('manual'); - const prepared = this.prepareDocuments(plan, [{ ...doc, docHash: computeDocHash(doc) }]); - if (prepared.failed.length > 0) { - const failure = prepared.failed[0]; - await adapter.delete([doc.id], ctx); - throw new Error( - `[knowledge] indexDocument did not index document '${doc.id}' and removed it from the index: ${failure.reason}`, - ); + try { + await adapter.dropSource({ source: entry.handed, reason: 'manual' }); + this.options.logger?.info?.(`[knowledge] source '${entry.face}' was removed and its index dropped.`); + } catch (err) { + kept(`dropSource failed (${operatorText(err)}).`); } - await adapter.upsert(prepared.ready, ctx); + return entry; + } + + /** Remove `entry` and what this node remembers of it. */ + private forget(entry: KnowledgeSourceEntry): void { + this.registry.remove(entry.key); + this.builds.delete(entry.key); + this.whereUnenforceableReported.delete(entry.key); + this.sourcesChanged(); + } + + /** Every registered source, as its author wrote it (a package's source carries its `_packageId`). */ + listSources(): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.authored); + } + + /** + * Every registered source with how a caller names it: its face + * (`NAMESPACE-NAME` for a package's source, the bare name otherwise) and + * its holder. What `search_knowledge` lists and the operator's actions name. + */ + describeSources(): KnowledgeSourceDescription[] { + return this.registry.entries().map(describeEntry); + } + + /** + * Every registered source as its adapter is handed it: `name` is the + * source's index key. For the callers that write to an index on a row's + * behalf (the event sync, the lifecycle reap guard). + */ + indexedSources(): KnowledgeSource[] { + return this.handedSources(); + } + + /** The source `sourceId` names (a face, or a bare name by ADR-0150 D3), as its author wrote it. */ + getSource(sourceId: string): KnowledgeSource | undefined { + return this.registry.resolve(sourceId)?.authored; + } + + /** {@link getSource}, with the source's face and holder. */ + describeSource(sourceId: string): KnowledgeSourceDescription | undefined { + const entry = this.registry.resolve(sourceId); + return entry ? describeEntry(entry) : undefined; + } + + /** The handed source held under an index key. */ + private handed(key: string): KnowledgeSource | undefined { + return this.registry.byIndexKey(key)?.handed; + } + + private handedSources(): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.handed); + } + + /** How a log line or an answer names a handed source: its face. */ + private label(source: KnowledgeSource): string { + return this.faceOfKey(source.name); + } + + private faceOfKey(key: string): string { + return this.registry.byIndexKey(key)?.face ?? key; } /** @@ -296,14 +443,14 @@ export class KnowledgeService implements IKnowledgeService { ): Promise { const split = adapter.capabilities?.chunks === true ? resolveSplit({ - split: source.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).split : undefined, + split: source.source.split, chunkTarget: await chunkTarget(), maxInputTokens: adapter.embedding?.maxInputTokens, }) : undefined; const index = indexExpectation( { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, - { source, schema: source.source.kind === 'object' ? this.schemaFor((source.source as ObjectKnowledgeSource).object) : undefined }, + { source, schema: this.schemaFor(source.source.object) }, ); return { source, @@ -320,8 +467,7 @@ export class KnowledgeService implements IKnowledgeService { * documents as they are, without `chunks` — it splits them itself, as * before. One that does gets each document with the passages of * {@link splitDocument}, under the split {@link planIndex} resolved for - * this call: the source's `split` (an object source's key; any other source - * splits `recursive`), the settings page's `knowledge.chunk_target`, and the + * this call: the source's `split`, the settings page's `knowledge.chunk_target`, and the * adapter's reported `embedding.maxInputTokens` — read for this call, never * cached. A document the split cannot index (a `whole` document over the * budget) is answered in `failed`, never truncated; the caller removes it. @@ -360,16 +506,10 @@ export class KnowledgeService implements IKnowledgeService { } } - async deleteDocument(sourceId: string, documentId: string): Promise { - const source = this.requireSource(sourceId); - const adapter = this.getAdapter(source.adapter); - await adapter.delete([documentId], (await this.planIndex(source, adapter)).context('manual')); - } - // ── Reindex ─────────────────────────────────────────────────────── /** - * Walk an `object` source and push its documents to the adapter. + * Walk a source's object and push its documents to the adapter. * * ## Paging * @@ -449,7 +589,7 @@ export class KnowledgeService implements IKnowledgeService { sourceId: string, opts: KnowledgeReindexOptions = {}, ): Promise { - return this.reindexWith(this.requireSource(sourceId), opts); + return this.reindexWith(this.requireEntry(sourceId).handed, opts); } /** {@link reindexSource}, with a sink a build's progress is reported to after each page. */ @@ -460,22 +600,6 @@ export class KnowledgeService implements IKnowledgeService { ): Promise { const adapter = this.getAdapter(source.adapter); - if (source.source.kind !== 'object') { - // File / HTTP sources delegate to adapter-internal ingestion. - return { - ok: false, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: - `Reindex for kind=${source.source.kind} is not handled by KnowledgeService. ` + - `Trigger ingestion through the adapter (${source.adapter}) directly.`, - }; - } - const engine = this.options.dataEngine; if (!engine) { return { @@ -486,12 +610,12 @@ export class KnowledgeService implements IKnowledgeService { purged: null, failed: 0, failures: [], - message: 'KnowledgeService has no IDataEngine bound; cannot walk object source.', + message: 'KnowledgeService has no IDataEngine bound; cannot walk the source.', }; } - return chainAfter(this.reindexTails, source.id, () => - this.walkObjectSource(source, source.source as ObjectKnowledgeSource, adapter, engine, opts, progress), + return chainAfter(this.reindexTails, source.name, () => + this.walkObjectSource(source, source.source, adapter, engine, opts, progress), ); } @@ -518,7 +642,7 @@ export class KnowledgeService implements IKnowledgeService { purged: null, failed: 0, failures: [], - message: `reindex of source '${source.id}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, + message: `reindex of source '${this.label(source)}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, }; } const cap = opts.limit === undefined ? undefined : Math.floor(opts.limit); @@ -555,7 +679,7 @@ export class KnowledgeService implements IKnowledgeService { indexed: 0, skipped: 0, purged: null, - message: `reindex of source '${source.id}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, + message: `reindex of source '${this.label(source)}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, }; } @@ -580,7 +704,7 @@ export class KnowledgeService implements IKnowledgeService { purged: null, failed: 0, failures: [], - message: `reindex of source '${source.id}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, + message: `reindex of source '${this.label(source)}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, }; } } @@ -592,7 +716,7 @@ export class KnowledgeService implements IKnowledgeService { const listingNote = listing.ok || listing.reason === undefined ? undefined : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; - if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${source.id}': ${listingNote}`); + if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${this.label(source)}': ${listingNote}`); const schema = this.schemaFor(object); const seen = new Set(); @@ -618,7 +742,7 @@ export class KnowledgeService implements IKnowledgeService { purged: null, failed, failures: [...failures], - message: `reindex of source '${source.id}' stopped at page ${page}${after}: ${what}`, + message: `reindex of source '${this.label(source)}' stopped at page ${page}${after}: ${what}`, }); const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; @@ -745,7 +869,7 @@ export class KnowledgeService implements IKnowledgeService { ok: false, purged: purge.purged, message: - `reindex of source '${source.id}' walked every page, but its purge stopped after ${purge.purged} ` + + `reindex of source '${this.label(source)}' walked every page, but its purge stopped after ${purge.purged} ` + `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, }; } @@ -755,7 +879,7 @@ export class KnowledgeService implements IKnowledgeService { purged: purge.purged, message: `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + - `('${source.id}:' and the record id); they were kept, because no row can confirm them.` + + `('${source.name}:' and the record id); they were kept, because no row can confirm them.` + (failedNote === undefined ? '' : ` ${failedNote}`), }); } @@ -784,7 +908,7 @@ export class KnowledgeService implements IKnowledgeService { ...done, ok: false, message: - `reindex of source '${source.id}' walked every page, but the adapter did not complete the build ` + + `reindex of source '${this.label(source)}' walked every page, but the adapter did not complete the build ` + `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, }; } @@ -802,17 +926,19 @@ export class KnowledgeService implements IKnowledgeService { * is the `unreadable` state. Writes nothing. */ async readIndexState(sourceId: string): Promise { - const source = this.requireSource(sourceId); + return this.readIndexStateOf(this.requireEntry(sourceId)); + } + + /** {@link readIndexState} of one registered source; the reading names it by its face. */ + private async readIndexStateOf(entry: KnowledgeSourceEntry): Promise { + const source = entry.handed; const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({ - sourceId, + sourceId: entry.face, state, due, detail, ...(held === undefined ? {} : { held }), }); - if (source.source.kind !== 'object') { - return reading('not-built-here', false, `a ${source.source.kind} source is ingested by its adapter, not built by the knowledge service.`); - } if (!this.options.dataEngine) { return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); } @@ -893,7 +1019,8 @@ export class KnowledgeService implements IKnowledgeService { /** The last build of `sourceId` on this node, or `undefined` when it ran none. */ buildRecord(sourceId: string): KnowledgeBuildRecord | undefined { - const record = this.builds.get(sourceId); + const entry = this.registry.resolve(sourceId); + const record = entry === undefined ? undefined : this.builds.get(entry.key); return record === undefined ? undefined : cloneBuildRecord(record); } @@ -905,8 +1032,9 @@ export class KnowledgeService implements IKnowledgeService { * record is answered. * - The lock held by another node, or not answering, starts nothing * (`not-run`). - * - A `boot` build re-reads the adapter once it holds the lock and builds - * only when a build is still due; an `operator` build always walks. + * - A `boot` or `reload` build re-reads the adapter once it holds the lock + * and builds only when a build is still due; an `operator` build always + * walks. * - The walk is {@link reindexSource} with no `limit` and no `dryRun`: a * complete build, with `beginBuild` and `completeBuild`. * @@ -918,19 +1046,28 @@ export class KnowledgeService implements IKnowledgeService { * unknown one, as {@link reindexSource} does. */ async rebuildSource(sourceId: string, opts: { trigger: KnowledgeBuildTrigger }): Promise { - const source = this.requireSource(sourceId); - const running = this.builds.get(sourceId); + return this.rebuildOf(this.requireEntry(sourceId), opts); + } + + /** + * {@link rebuildSource} of one registered source. The record names the + * source by its face; the build's lock and this node's record of it are + * held under its index key, which no two sources share. + */ + private async rebuildOf(entry: KnowledgeSourceEntry, opts: { trigger: KnowledgeBuildTrigger }): Promise { + const source = entry.handed; + const running = this.builds.get(entry.key); if (running?.status === 'running') return cloneBuildRecord(running); const record: KnowledgeBuildRecord = { - sourceId, + sourceId: entry.face, trigger: opts.trigger, status: 'running', startedAt: new Date().toISOString(), progress: emptyBuildProgress(), }; - this.builds.set(sourceId, record); + this.builds.set(entry.key, record); const logger = this.options.logger; - const label = `[knowledge] build of source '${sourceId}' (${opts.trigger})`; + const label = `[knowledge] build of source '${entry.face}' (${opts.trigger})`; const finish = ( status: Exclude, message: string | undefined, @@ -954,7 +1091,7 @@ export class KnowledgeService implements IKnowledgeService { let handle: KnowledgeBuildLockHandle | null = null; if (lock) { try { - handle = await lock.acquire(buildLockKey(sourceId), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); + handle = await lock.acquire(buildLockKey(entry.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); } catch (err) { const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; logger?.warn(`${label}: ${message}`); @@ -976,8 +1113,8 @@ export class KnowledgeService implements IKnowledgeService { }) : () => {}; try { - if (opts.trigger === 'boot') { - const reading = await this.readIndexState(sourceId); + if (opts.trigger !== 'operator') { + const reading = await this.readIndexStateOf(entry); if (!reading.due) { const message = `nothing to build once the lock was held: ${reading.detail}`; logger?.info?.(`${label}: ${message}`); @@ -1046,39 +1183,57 @@ export class KnowledgeService implements IKnowledgeService { * background by `KnowledgeServicePlugin`, so the boot never waits for it. */ async buildSourcesAtBoot(): Promise { - const logger = this.options.logger; - let sources: KnowledgeSource[]; + let entries: KnowledgeSourceEntry[]; try { - sources = this.listSources(); + entries = this.registry.entries(); } catch (err) { - logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); + this.options.logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); return; } - for (const source of sources) { + for (const entry of entries) { if (this.buildsStopped) return; - try { - if (source.source.kind === 'object' && (source.refresh?.onRecordChange ?? true) === false) { - logger?.debug?.(`[knowledge] source '${source.id}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built at boot.`); - continue; - } - const reading = await this.readIndexState(source.id); - if (reading.due) { - logger?.info?.(`[knowledge] source '${source.id}' is built now: ${reading.detail}`); - await this.rebuildSource(source.id, { trigger: 'boot' }); - continue; - } - const line = `[knowledge] source '${source.id}' is not built at boot: ${reading.detail}`; - // What cannot be seen or read is said once, at `warn` (K7: "the - // service says so once"); a source that is current, or whose adapter - // holds documents it reports no status for, is ordinary. - if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { - logger?.warn(line); - } else { - logger?.info?.(line); - } - } catch (err) { - logger?.warn(`[knowledge] source '${source.id}': the boot build pass failed for it (${operatorText(err)}).`); + await this.buildIfDue(entry, 'boot'); + } + } + + /** + * Build the metadata item's source held under `key` when a build is due for + * it — what the boot pass does for each source, done for one: the loader + * calls it when a `knowledge_source` item is added or changed while the + * process runs (ADR-0161 K7, "What starts a rebuild": a source reload). + * Never rejects; a key that holds no source is a no-op. + */ + async buildReloadedSource(key: string): Promise { + const entry = this.registry.byIndexKey(key); + if (entry && !this.buildsStopped) await this.buildIfDue(entry, 'reload'); + } + + /** One source of {@link buildSourcesAtBoot}. Never rejects. */ + private async buildIfDue(entry: KnowledgeSourceEntry, trigger: KnowledgeBuildTrigger): Promise { + const logger = this.options.logger; + const when = trigger === 'boot' ? 'at boot' : 'on reload'; + try { + if ((entry.authored.refresh?.onRecordChange ?? true) === false) { + logger?.debug?.(`[knowledge] source '${entry.face}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built ${when}.`); + return; + } + const reading = await this.readIndexStateOf(entry); + if (reading.due) { + logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); + await this.rebuildOf(entry, { trigger }); + return; } + const line = `[knowledge] source '${entry.face}' is not built ${when}: ${reading.detail}`; + // What cannot be seen or read is said once, at `warn` (K7: "the + // service says so once"); a source that is current, or whose adapter + // holds documents it reports no status for, is ordinary. + if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { + logger?.warn(line); + } else { + logger?.info?.(line); + } + } catch (err) { + logger?.warn(`[knowledge] source '${entry.face}': the build pass failed for it (${operatorText(err)}).`); } } @@ -1102,7 +1257,7 @@ export class KnowledgeService implements IKnowledgeService { // ── Permission-aware search ─────────────────────────────────────── /** - * Search every source the caller is admitted to, re-check each object-source + * Search every source the caller is admitted to, re-check each * hit as the caller ({@link applyPermissionFilter}), and answer the best * `topK` hits by score — passages, or records under `granularity: 'record'`. * @@ -1124,7 +1279,7 @@ export class KnowledgeService implements IKnowledgeService { * matching rows would be answered from what is left of `topK` ranked hits — * the fewer rows a caller may read, the closer to empty. So when the re-check * can remove hits (a caller who is not the system identity, with an engine to - * re-check with), each `object` source is asked for + * re-check with), each source is asked for * `topK × SEARCH_FIRST_ROUND_FACTOR` hits. When the survivors name fewer * than `topK` records ({@link distinctGroups}: several passages of one * record count once), @@ -1136,16 +1291,13 @@ export class KnowledgeService implements IKnowledgeService { * `topK` below what it was asked answers fewer than asked, so it is never * asked again. * - * A `file` / `http` source is asked for `topK` once: the re-check never - * removes its hits. The system identity, and a caller the service cannot - * re-check (no context, no engine — object sources are then not searched at - * all), get one round of `topK`. + * The system identity gets one round of `topK`. A caller the service cannot + * re-check (no context, no engine) is served no source at all. * * ## Records, not chunks (`granularity: 'record'`, `groupBy`) * * Several passages of one record would fill `topK` with one record, so - * under record granularity EVERY source — `file` / `http` too, and for every - * caller — is asked `topK × SEARCH_FIRST_ROUND_FACTOR` passages, and the + * under record granularity every source — for every caller — is asked `topK × SEARCH_FIRST_ROUND_FACTOR` passages, and the * sources that answered all they were asked are refilled once, at * `topK × SEARCH_REFILL_FACTOR`, when the survivors name fewer than `topK` * groups. That refill is the cap: a search reads at most @@ -1192,6 +1344,24 @@ export class KnowledgeService implements IKnowledgeService { * `refused` lists them all. */ async searchWithRefusals(query: string, opts: KnowledgeSearchOptions = {}): Promise { + const report = await this.searchByKey(query, opts); + return { + hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), + refused: this.facedRefusals(report.refused), + }; + } + + /** The refusals of a search, each source named by its face. */ + private facedRefusals(refused: KnowledgeSearchRefusal[]): KnowledgeSearchRefusal[] { + return refused.map((r) => ({ ...r, sourceId: this.faceOfKey(r.sourceId) })); + } + + /** + * {@link searchWithRefusals} with every source named by its index key, as + * an adapter's hit names it; the public member translates each to its face. + * A whole refusal thrown from here already names the sources by face. + */ + private async searchByKey(query: string, opts: KnowledgeSearchOptions): Promise { const scope = readSearchScope(opts.scope); const topK = opts.topK ?? this.defaultTopK; const groupBy = opts.groupBy; @@ -1225,24 +1395,23 @@ export class KnowledgeService implements IKnowledgeService { const sources = await this.planSearches(admitted); const filtered = ctx !== undefined && ctx.isSystem !== true && this.options.dataEngine !== undefined; - const widened = (source: KnowledgeSource): boolean => - byRecord || (filtered && source.source.kind === 'object'); - const firstAsk = (source: KnowledgeSource): number => - widened(source) ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; + const widened = byRecord || filtered; + const firstAsk = (_source: KnowledgeSource): number => + widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; const groupOf = byRecord ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) : recordKeyOf; const refused: KnowledgeSearchRefusal[] = []; const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); - if (first.size === 0 && refused.length > 0) throw wholeRefusal(refused); + if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); const raw = [...first.values()].flatMap((answer) => answer.hits); let kept = await this.applyPermissionFilter(raw, ctx, byRecord); let removed = raw.length - kept.length; if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { const saturated = sources.filter(({ source }) => { - const answer = first.get(source.id); - return widened(source) && answer !== undefined && answer.answered >= firstAsk(source); + const answer = first.get(source.name); + return widened && answer !== undefined && answer.answered >= firstAsk(source); }); if (saturated.length > 0) { const refusedBefore = refused.length; @@ -1261,7 +1430,7 @@ export class KnowledgeService implements IKnowledgeService { const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); if (refusedInRefill.size > 0) { kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); - if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(refused); + if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(this.facedRefusals(refused)); } } } @@ -1286,17 +1455,15 @@ export class KnowledgeService implements IKnowledgeService { } /** - * The sources a `groupBy` search asks: every `file` / `http` source (it - * groups by document), and each `object` source that lists `groupBy` in its - * `metadataFields`. Any other object source answers no hits for this search - * — its hits carry no group value, and a hit is never answered ungrouped. + * The sources a `groupBy` search asks: each source that lists `groupBy` in + * its `metadataFields`. Any other source answers no hits for this search — + * its hits carry no group value, and a hit is never answered ungrouped. */ private sourcesGroupableBy(sources: T[], groupBy: string): T[] { return sources.filter(({ source }) => { - if (source.source.kind !== 'object') return true; - if (((source.source as ObjectKnowledgeSource).metadataFields ?? []).includes(groupBy)) return true; + if ((source.source.metadataFields ?? []).includes(groupBy)) return true; this.options.logger?.debug?.( - `[knowledge] source '${source.id}' not searched for groupBy ${quotedName(groupBy)}: ` + + `[knowledge] source '${this.label(source)}' not searched for groupBy ${quotedName(groupBy)}: ` + 'the field is not one of its metadataFields.', ); return false; @@ -1304,14 +1471,11 @@ export class KnowledgeService implements IKnowledgeService { } /** - * The group a hit falls in under record granularity: with `groupBy`, an - * object-source hit's `metadata[groupBy]` value (`undefined` — no group, - * never answered — when the hit carries none); without it, the hit's record. - * A `file` / `http` hit is its document either way. + * The group a hit falls in under record granularity: with `groupBy`, the + * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — + * when the hit carries none); without it, the hit's record. */ private groupKeyOf(hit: KnowledgeHit, groupBy: string | undefined): string | undefined { - const source = this.sources.get(hit.sourceId); - if (source?.source.kind !== 'object') return `document:${hit.sourceId}#${hit.documentId}`; if (groupBy === undefined) return recordKeyOf(hit); const value = hit.metadata?.[groupBy]; if (value === undefined || value === null || value === '') return undefined; @@ -1342,8 +1506,8 @@ export class KnowledgeService implements IKnowledgeService { * hash is checked for membership only. A read that fails drops that * source's checked hits (fail-closed), reported at `warn`. * - * Not checked: a `file` / `http` hit (no record to read), an object hit - * without a record id, and every hit when no data engine is bound. + * Not checked: a hit without a record id, and every hit when no data engine + * is bound. */ private async answerByRecord( hits: KnowledgeHit[], @@ -1360,7 +1524,7 @@ export class KnowledgeService implements IKnowledgeService { } const engine = this.options.dataEngine; const checkKey = (hit: KnowledgeHit): string | undefined => - engine !== undefined && hit.sourceRecordId !== undefined && this.sources.get(hit.sourceId)?.source.kind === 'object' + engine !== undefined && hit.sourceRecordId !== undefined && this.handed(hit.sourceId) !== undefined ? `${hit.sourceId}#${hit.sourceRecordId}` : undefined; const fresh = new Set(); @@ -1410,8 +1574,8 @@ export class KnowledgeService implements IKnowledgeService { } let posture: { value: TenancyPosture | undefined } | null | undefined; for (const [sourceId, records] of bySource) { - const source = this.sources.get(sourceId)!; - const objSource = source.source as ObjectKnowledgeSource; + const source = this.handed(sourceId)!; + const objSource = source.source; const ids = [...records.keys()]; const byId = { id: { $in: ids } }; const schema = this.schemaFor(objSource.object); @@ -1487,7 +1651,7 @@ export class KnowledgeService implements IKnowledgeService { */ private repairStale(source: KnowledgeSource, objSource: ObjectKnowledgeSource, recordId: string): void { if (objectSourcesFor([source], objSource.object).length === 0) return; - const docId = documentIdFor(source.id, recordId); + const docId = documentIdFor(source.name, recordId); if (this.freshnessRepairs.has(docId)) return; this.freshnessRepairs.add(docId); void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); @@ -1546,7 +1710,7 @@ export class KnowledgeService implements IKnowledgeService { const adapter = this.adapters.get(source.adapter); if (!adapter) { this.options.logger?.warn?.( - `[knowledge] source '${source.id}' references unknown adapter '${source.adapter}'; skipping.`, + `[knowledge] source '${this.label(source)}' references unknown adapter '${source.adapter}'; skipping.`, ); continue; } @@ -1564,15 +1728,15 @@ export class KnowledgeService implements IKnowledgeService { // two sources share) is dropped: that source's admission was never // asked for this hit, so serving it would skip the gates above. const served: KnowledgeHit[] = []; - for (const hit of hits) if (hit.sourceId === source.id) served.push(hit); + for (const hit of hits) if (hit.sourceId === source.name) served.push(hit); const foreign = hits.length - served.length; if (foreign > 0) { this.options.logger?.warn?.( - `[knowledge] adapter '${source.adapter}' answered ${foreign} hit(s) for source '${source.id}' that name ` + + `[knowledge] adapter '${source.adapter}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + 'another source; dropped — a hit is served only as the source it was searched for.', ); } - out.set(source.id, { + out.set(source.name, { hits: scope === undefined ? served : this.checkScope(served, scope, source), answered: hits.length, }); @@ -1581,14 +1745,14 @@ export class KnowledgeService implements IKnowledgeService { if (coded !== undefined) { // The caller reads the code and the adapter's one-sentence message; // the operator reads its remedy (the SQL to run, say) here. - refused.push({ sourceId: source.id, ...coded }); + refused.push({ sourceId: source.name, ...coded }); this.options.logger?.warn?.( - `[knowledge] source '${source.id}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, + `[knowledge] source '${this.label(source)}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, ); continue; } this.options.logger?.error?.( - `[knowledge] adapter '${source.adapter}' search failed for source '${source.id}': ${(err as Error).message}`, + `[knowledge] adapter '${source.adapter}' search failed for source '${this.label(source)}': ${(err as Error).message}`, ); } } @@ -1601,7 +1765,7 @@ export class KnowledgeService implements IKnowledgeService { * object the source indexes, a `metadata` term for an entry naming a parent * object the source reaches through the one parent link it lists in * `metadataFields`, read from the object's registered definition. A source - * no entry reaches — every `file` / `http` source among them — is not + * no entry reaches is not * searched, logged at `debug`. A source that lists two or more parent links * to an entry's object is not reached by that entry, reported once per * source and object at `warn`, naming the fields. @@ -1614,18 +1778,18 @@ export class KnowledgeService implements IKnowledgeService { for (const entry of sources) { const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); for (const { object, fields } of ambiguous) { - const key = `${entry.source.id}\u0000${object}`; + const key = `${entry.source.name}\u0000${object}`; if (this.scopeAmbiguousReported.has(key)) continue; this.scopeAmbiguousReported.add(key); this.options.logger?.warn?.( - `[knowledge] source '${entry.source.id}' lists ${fields.length} fields pointing at '${object}' ` + + `[knowledge] source '${this.label(entry.source)}' lists ${fields.length} fields pointing at '${object}' ` + `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + 'it is not told which field the scope means.', ); } if (terms.length === 0) { this.options.logger?.debug?.( - `[knowledge] source '${entry.source.id}' not searched: no entry of the search's scope reaches it.`, + `[knowledge] source '${this.label(entry.source)}' not searched: no entry of the search's scope reaches it.`, ); continue; } @@ -1646,7 +1810,7 @@ export class KnowledgeService implements IKnowledgeService { if (dropped > 0 && !this.scopeIgnoredReported.has(source.adapter)) { this.scopeIgnoredReported.add(source.adapter); this.options.logger?.warn?.( - `[knowledge] adapter '${source.adapter}' answered ${dropped} hit(s) for source '${source.id}' outside the ` + + `[knowledge] adapter '${source.adapter}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + 'Reported once for this adapter.', @@ -1659,7 +1823,7 @@ export class KnowledgeService implements IKnowledgeService { /** * Apply an ObjectQL `data.record.created`, `data.record.updated` or - * `data.record.restored` event to every `object` source bound to the + * `data.record.restored` event to every source bound to the * matching object. `record` is the event payload's `after`; its `id` names * the row. Failures are logged but never thrown — sync must not block writes. * @@ -1718,7 +1882,7 @@ export class KnowledgeService implements IKnowledgeService { for (const source of this.sourcesForObject(object)) { const sync = (): Promise => this.syncRecord(source, object, recordId, record); await (isRecordId(recordId) - ? this.serializeRecordSync(documentIdFor(source.id, String(recordId)), sync) + ? this.serializeRecordSync(documentIdFor(source.name, String(recordId)), sync) : sync()); } } @@ -1732,7 +1896,7 @@ export class KnowledgeService implements IKnowledgeService { recordId: unknown, payload: Record, ): Promise { - const objSource = source.source as ObjectKnowledgeSource; + const objSource = source.source; try { const adapter = this.getAdapter(source.adapter); const engine = this.options.dataEngine; @@ -1747,7 +1911,7 @@ export class KnowledgeService implements IKnowledgeService { } if (!isRecordId(recordId)) { this.options.logger?.warn?.( - `[knowledge] event-sync skipped for source '${source.id}': the event's record names no id, ` + + `[knowledge] event-sync skipped for source '${this.label(source)}': the event's record names no id, ` + 'so the row cannot be re-read against the source.', ); return; @@ -1758,11 +1922,11 @@ export class KnowledgeService implements IKnowledgeService { await this.writeSynced(source, adapter, doc, recordId); } else { const plan = await this.planIndex(source, adapter); - await adapter.delete([documentIdFor(source.id, String(recordId))], plan.context('event-sync')); + await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); } } catch (err) { this.options.logger?.warn?.( - `[knowledge] event-sync failed for source '${source.id}': ${(err as Error).message}`, + `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, ); } } @@ -1789,10 +1953,10 @@ export class KnowledgeService implements IKnowledgeService { await adapter.delete([f.documentId], ctx); const limit = adapter.embedding?.maxInputTokens; const message = - `[knowledge] record '${String(recordId)}' of source '${source.id}' is no longer in the index and search ` + + `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + - `Fix: give source '${source.id}' split strategy 'recursive' or 'markdown', or shorten the record.`; + `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; // `warn` is the guaranteed channel when a host injects no `error`. const logger = this.options.logger; if (logger?.error) logger.error(message); @@ -1802,10 +1966,10 @@ export class KnowledgeService implements IKnowledgeService { /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ private reportWhereUnenforceable(source: KnowledgeSource): void { - if (this.whereUnenforceableReported.has(source.id)) return; - this.whereUnenforceableReported.add(source.id); + if (this.whereUnenforceableReported.has(source.name)) return; + this.whereUnenforceableReported.add(source.name); this.options.logger?.warn?.( - `[knowledge] source '${source.id}' declares a where filter and no data engine is bound: record events ` + + `[knowledge] source '${this.label(source)}' declares a where filter and no data engine is bound: record events ` + 'for it are not synced, because the filter cannot be judged without re-reading the row. ' + 'Bind a data engine (the objectql service) to sync it.', ); @@ -1845,14 +2009,14 @@ export class KnowledgeService implements IKnowledgeService { async handleRecordDelete(object: string, recordId: string): Promise { const targets = this.sourcesForObject(object); for (const source of targets) { - const docId = documentIdFor(source.id, recordId); + const docId = documentIdFor(source.name, recordId); await this.serializeRecordSync(docId, async () => { try { const adapter = this.getAdapter(source.adapter); await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); } catch (err) { this.options.logger?.warn?.( - `[knowledge] event-sync delete failed for source '${source.id}': ${(err as Error).message}`, + `[knowledge] event-sync delete failed for source '${this.label(source)}': ${(err as Error).message}`, ); } }); @@ -1861,41 +2025,53 @@ export class KnowledgeService implements IKnowledgeService { // ── Internals ───────────────────────────────────────────────────── - private requireSource(sourceId: string): KnowledgeSource { - const source = this.sources.get(sourceId); - if (!source) { + /** + * The registered source `sourceId` names, read by the one rule + * (`KnowledgeSourceRegistry.resolve`): its face, else a bare name by + * ADR-0150 D3. Throws for a name no source has, listing the registered + * faces, and `409 RESOURCE_CONFLICT` for one that names several. + */ + private requireEntry(sourceId: string): KnowledgeSourceEntry { + const entry = this.registry.resolve(sourceId); + if (!entry) { throw new Error( - `[knowledge] unknown source '${sourceId}'. Registered: [${[...this.sources.keys()].join(', ')}]`, + `[knowledge] unknown source '${sourceId}'. Registered: [${this.registry.entries().map((e) => e.face).join(', ')}]`, ); } - return source; + return entry; } + /** + * The sources a search asks: every source whose `aiExposed` is not `false`, + * or the ones `sourceIds` names — each read by the one rule, so a name + * several sources have refuses the search (`409 RESOURCE_CONFLICT`) and a + * name none has is skipped, reported at `warn`. + */ private resolveSearchTargets(sourceIds?: string[]): KnowledgeSource[] { if (!sourceIds || sourceIds.length === 0) { - return [...this.sources.values()].filter((s) => s.aiExposed !== false); + return this.handedSources().filter((s) => s.aiExposed !== false); } - const out: KnowledgeSource[] = []; + const out = new Map(); for (const id of sourceIds) { - const s = this.sources.get(id); - if (s) out.push(s); + const entry = this.registry.resolve(id); + if (entry) out.set(entry.key, entry.handed); else this.options.logger?.warn?.(`[knowledge] search target '${id}' not registered; skipping.`); } - return out; + return [...out.values()]; } /** - * [ADR-0090 D10 rule 1] The sources this caller's search may reach: an - * `object` source over an object the caller's exposure decision refuses, or - * one serving a field the caller may not query, is not searched for that + * [ADR-0090 D10 rule 1] The sources this caller's search may reach: a + * source over an object the caller's exposure decision refuses, or one + * serving a field the caller may not query, is not searched for that * caller — see `knowledge-source-admission.ts` for the gates and why they are * asked at source granularity. Computed once per (caller, object) per search. * * The system context bypasses, as it bypasses the row re-check. A caller * with NO context, or a service with no data engine bound, cannot be judged - * and is served no `object` source at all — never searched, so no passage of - * one can reach the caller through a hit the row re-check cannot place (a - * hit with no `sourceRecordId`). Fails CLOSED: a gate that throws refuses + * and is served no source at all — never searched, so no passage of one can + * reach the caller through a hit the row re-check cannot place (a hit with + * no `sourceRecordId`). Fails CLOSED: a gate that throws refuses * every source over that object, reported once at `error`. The objects' * admissions are asked concurrently. * @@ -1911,17 +2087,16 @@ export class KnowledgeService implements IKnowledgeService { if (ctx?.isSystem) return sources.map((source) => ({ source })); const engine = this.options.dataEngine; if (!ctx || !engine) { - const kept = sources.filter((source) => source.source.kind !== 'object').map((source) => ({ source })); - if (kept.length < sources.length) { + if (sources.length > 0) { this.options.logger?.warn?.( !ctx - ? '[knowledge] retrieval with no ExecutionContext — object sources are not searched: a missing ' + + ? '[knowledge] retrieval with no ExecutionContext — no source is searched: a missing ' + 'identity is not a grant of authority, so retrieval fails closed rather than searching the whole corpus unscoped. ' + - 'Pass the caller identity (or an explicit system context) to retrieve object-backed knowledge.' - : '[knowledge] no IDataEngine bound — object sources are not searched, to stay safe.', + 'Pass the caller identity (or an explicit system context) to retrieve knowledge.' + : '[knowledge] no IDataEngine bound — no source is searched, to stay safe.', ); } - return kept; + return []; } const deps = { readSchema: (object: string): unknown => { @@ -1934,8 +2109,7 @@ export class KnowledgeService implements IKnowledgeService { }; const byObject = new Map>(); for (const source of sources) { - if (source.source.kind !== 'object') continue; - const object = (source.source as ObjectKnowledgeSource).object; + const object = source.source.object; if (byObject.has(object)) continue; byObject.set( object, @@ -1947,11 +2121,7 @@ export class KnowledgeService implements IKnowledgeService { } const out: KnowledgeSource[] = []; for (const source of sources) { - if (source.source.kind !== 'object') { - out.push(source); - continue; - } - const objSource = source.source as ObjectKnowledgeSource; + const objSource = source.source; const objectAdmission = await byObject.get(objSource.object); if (!objectAdmission) continue; // the gate threw: reported once, refused. const verdict: KnowledgeSourceAdmission = objectAdmission.refused @@ -1961,7 +2131,7 @@ export class KnowledgeService implements IKnowledgeService { out.push(source); } else { this.options.logger?.debug?.( - `[knowledge] source '${source.id}' not searched for this caller: ${verdict.reason} ` + + `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + `(object='${verdict.object}'${verdict.field ? `, field='${verdict.field}'` : ''}).`, ); } @@ -1989,58 +2159,48 @@ export class KnowledgeService implements IKnowledgeService { * that one before this runs) with the organizations its search hands the * adapter (`searchOrganizationIds`): computed here, from the caller's * execution context and the deployment's posture, never from anything the - * caller passes. A `file` / `http` source gets none — its documents carry no - * organization, and the adapter owns its ACL. + * caller passes. * - * The posture is read once per search, and only when an `object` source is - * admitted. A posture that cannot be read leaves every `object` source - * unsearched for this call (fail-closed: whether a wall stands is unknown), + * The posture is read once per search, and only when a source is admitted. + * A posture that cannot be read leaves every source unsearched for this call (fail-closed: whether a wall stands is unknown), * reported at `error`, `warn` as the fallback. */ private async scopeByOrganization( sources: KnowledgeSource[], ctx: ExecutionContext, ): Promise> { - if (!sources.some((source) => source.source.kind === 'object')) { - return sources.map((source) => ({ source })); - } + if (sources.length === 0) return []; let posture: TenancyPosture | undefined; try { posture = await this.readTenancyPosture(); } catch (err) { const report = - `[knowledge] the tenancy posture could not be read (${errorText(err)}); no object source is searched ` + + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no source is searched ` + 'for this caller (fail-closed).'; if (this.options.logger?.error) this.options.logger.error(report); else this.options.logger?.warn?.(report); - return sources.filter((source) => source.source.kind !== 'object').map((source) => ({ source })); + return []; } return sources.map((source) => { - if (source.source.kind !== 'object') return { source }; - const organizationIds = searchOrganizationIds( - ctx, - posture, - this.schemaFor((source.source as ObjectKnowledgeSource).object), - ); + const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(source.source.object)); return organizationIds === undefined ? { source } : { source, organizationIds }; }); } private sourcesForObject(object: string): KnowledgeSource[] { - return objectSourcesFor([...this.sources.values()], object); + return objectSourcesFor(this.handedSources(), object); } /** - * Drop hits whose underlying ObjectQL record the caller can't read. - * Hits of a registered file / http source are kept — the adapter is - * responsible for any ACL enforcement there; an object-source hit with no - * `sourceRecordId` cannot be re-checked and is dropped. + * Drop hits whose underlying ObjectQL record the caller can't read. A hit + * with no `sourceRecordId`, or of a source nobody registered, cannot be + * re-checked and is dropped. * * Identity handling (#2981): an **explicit** `isSystem` context (indexing / * trusted server jobs) passes every hit through — it is a deliberate, * authored elevation. A **missing** context, however, is NOT a grant of * authority: with no identity we cannot prove the caller may read the - * object-backed rows, so we FAIL CLOSED and drop object-source hits (the + * rows, so we FAIL CLOSED and drop every hit (the * same conservative posture as a missing data engine). This closes the * agent/RAG fall-open where an omitted `ToolExecutionContext.actor` used to * return unfiltered semantic search over the whole corpus. @@ -2059,21 +2219,18 @@ export class KnowledgeService implements IKnowledgeService { ): Promise { // Explicit elevation → pass through (indexing / trusted jobs). if (ctx?.isSystem) return hits; - // No identity, or no engine to re-check with → keep only hits of a - // registered file / http source. `admitSources` already kept object - // sources out of the search; this holds the same line for any hit that - // still claims one (or claims no registered source at all). - if (!ctx || !this.options.dataEngine) { - return hits.filter((h) => this.isNonObjectSourceHit(h)); - } + // No identity, or no engine to re-check with → no hit can be proven + // readable. `admitSources` already kept every source out of the search; + // this holds the same line for any hit that reached here anyway. + if (!ctx || !this.options.dataEngine) return []; // Group hits by object so we make one query per object. const byObject = new Map(); for (const hit of hits) { if (!hit.sourceRecordId) continue; - const source = this.sources.get(hit.sourceId); - if (!source || source.source.kind !== 'object') continue; - const objName = (source.source as ObjectKnowledgeSource).object; + const source = this.handed(hit.sourceId); + if (!source) continue; + const objName = source.source.object; const bucket = byObject.get(objName) ?? []; bucket.push(hit); byObject.set(objName, bucket); @@ -2114,31 +2271,49 @@ export class KnowledgeService implements IKnowledgeService { const out: KnowledgeHit[] = []; for (const hit of hits) { - if (this.isNonObjectSourceHit(hit)) { - out.push(hit); // file / http hit - continue; - } - // An object-source hit the re-check cannot place — no record id, or a - // source nobody registered — is not provably readable: dropped. - const source = this.sources.get(hit.sourceId); + // A hit the re-check cannot place — no record id, or a source nobody + // registered — is not provably readable: dropped. + const source = this.handed(hit.sourceId); if (!source || !hit.sourceRecordId) continue; - const key = `${(source.source as ObjectKnowledgeSource).object}#${hit.sourceRecordId}`; + const key = `${source.source.object}#${hit.sourceRecordId}`; if (!allowed.has(key)) continue; const title = titles.get(key); out.push(title === undefined ? hit : { ...hit, title }); } return out; } - - /** A hit of a REGISTERED source that is not an `object` source (file / http): the adapter owns its ACL. */ - private isNonObjectSourceHit(hit: KnowledgeHit): boolean { - const source = this.sources.get(hit.sourceId); - return source !== undefined && source.source.kind !== 'object'; - } } // ── Helpers ───────────────────────────────────────────────────────── +/** A registered source with how a caller names it (`KnowledgeService.describeSources`). */ +export interface KnowledgeSourceDescription { + /** The source's face: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ + id: string; + /** The source as its author wrote it. */ + source: KnowledgeSource; + /** The package that holds it; absent for a source no package holds. */ + packageId?: string; + /** Which door it arrived through: a registration in code, or a `knowledge_source` metadata item. */ + door: KnowledgeSourceEntry['door']; +} + +function describeEntry(entry: KnowledgeSourceEntry): KnowledgeSourceDescription { + return { + id: entry.face, + source: entry.authored, + ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), + door: entry.door, + }; +} + +/** ` 'NAME'` for a refusal about an input that carries a usable name (or its retired `id`), else nothing. */ +function describeName(input: unknown): string { + const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown }; + const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined; + return shown === undefined ? '' : ` ${quotedName(shown)}`; +} + /** * A source that refused a search (ADR-0161 K7, rule 5): its adapter answered * an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds @@ -2249,7 +2424,7 @@ function chainAfter( } /** - * The `object` sources whose per-record projection of `object` is kept in step + * The sources whose per-record projection of `object` is kept in step * with row changes — i.e. those the service may upsert into, delete from, or * (since #4672) de-index on behalf of, in reaction to a row's lifecycle. * @@ -2267,8 +2442,7 @@ function chainAfter( export function objectSourcesFor(sources: KnowledgeSource[], object: string): KnowledgeSource[] { return sources.filter( (source) => - source.source.kind === 'object' && - (source.source as ObjectKnowledgeSource).object === object && + source.source.object === object && (source.refresh?.onRecordChange ?? true) !== false, ); } @@ -2321,7 +2495,7 @@ async function rereadRow( export const LIST_DOCUMENTS_PAGE_SIZE = 500; /** - * How many times `topK` a search asks each `object` source for in its first + * How many times `topK` a search asks each source for in its first * round, when the permission re-check can remove hits ({@link * KnowledgeService.search}). */ @@ -2447,7 +2621,7 @@ export interface PurgeDocumentsOutcome { */ export async function purgeDocuments(input: PurgeDocumentsInput): Promise { const { source, objSource, adapter, engine } = input; - const prefix = `${source.id}:`; + const prefix = `${source.name}:`; const outcome: PurgeDocumentsOutcome = { purged: 0, kept: 0, foreign: 0 }; for (const documentId of input.candidates) { const recordId = documentId.startsWith(prefix) ? documentId.slice(prefix.length) : ''; @@ -2581,7 +2755,7 @@ function distinctGroups(hits: KnowledgeHit[], groupOf: (hit: KnowledgeHit) => st return keys.size; } -/** A hit's record: an object-source hit is its source and record id; any other hit is its document. */ +/** A hit's record: its source and record id; a hit that names no record is its document. */ function recordKeyOf(hit: KnowledgeHit): string { return hit.sourceRecordId !== undefined ? `record:${hit.sourceId}#${hit.sourceRecordId}` : `document:${hit.documentId}`; } @@ -2591,8 +2765,7 @@ function recordKeyOf(hit: KnowledgeHit): string { * {@link recordToDocument} reads for `objSource` — `id`, the content and * metadata fields, the title field, and `organization_id` under a walled * posture. `undefined` (read the whole row, as the walk and the event sync - * do) when the content list is `'*'`, when the object's fields cannot be - * enumerated, or when a field the source names is not one the object declares: + * do) when the object's fields cannot be enumerated, or when a field the source names is not one the object declares: * assembly reads such a field off the whole row, and a projection that left it * out would recompute a different hash and read every record as stale. */ @@ -2602,9 +2775,9 @@ function freshnessFields( posture: TenancyPosture | undefined, ): string[] | undefined { const declared = declaredFields(schema); - if (declared === undefined || objSource.contentFields.includes('*')) return undefined; + if (declared === undefined) return undefined; const names = new Set(declared.map(([name]) => name)); - const wanted = new Set(['id', ...objSource.contentFields, ...(objSource.metadataFields ?? [])]); + const wanted = new Set(['id', ...objSource.content, ...(objSource.metadataFields ?? [])]); const titleField = documentTitleField(schema); if (titleField !== undefined) wanted.add(titleField); if (posture !== undefined && postureEnforcesWall(posture)) wanted.add('organization_id'); @@ -2628,14 +2801,14 @@ export function documentIdFor(sourceId: string, recordId: string): string { /** * Project an ObjectQL record into a `KnowledgeDocument` per the - * source's `contentFields` / `metadataFields` config. Pure function. + * source's `content` / `metadataFields` config. Pure function. * * `schema` (the record's registered object definition) names the fields an * index never carries: credential-class fields (the set the engine masks on * read) and `internal: true` fields (the set it omits), asked through the same * collectors the write-response helper uses (`@objectstack/core`). They are - * SKIPPED — under `'*'`, and when a source names one explicitly as content or - * metadata — rather than indexed masked: an index document is searchable text + * SKIPPED when a source names one as content or metadata, rather than + * indexed masked: an index document is searchable text * served to every reader the source admits, and a mask placeholder is no * content. Without a schema nothing is withheld here (the engine's event body * and read path still apply their own projection upstream). @@ -2662,17 +2835,10 @@ export function recordToDocument( ]); const recordId = String(record.id ?? (record as any)._id ?? ''); const contentParts: string[] = []; - for (const field of objSource.contentFields) { - if (field === '*') { - for (const [k, v] of Object.entries(record)) { - if (withheld.has(k)) continue; - if (typeof v === 'string' && v.length > 0 && k !== 'id') contentParts.push(v); - } - } else { - if (withheld.has(field)) continue; - const v = record[field]; - if (v != null) contentParts.push(String(v)); - } + for (const field of objSource.content) { + if (withheld.has(field)) continue; + const v = record[field]; + if (v != null) contentParts.push(String(v)); } const metadata: Record = {}; for (const field of objSource.metadataFields ?? []) { @@ -2680,8 +2846,8 @@ export function recordToDocument( if (record[field] !== undefined) metadata[field] = record[field]; } const doc: KnowledgeDocument = { - id: documentIdFor(source.id, recordId || `unknown-${Date.now()}`), - sourceId: source.id, + id: documentIdFor(source.name, recordId || `unknown-${Date.now()}`), + sourceId: source.name, sourceRecordId: recordId || undefined, content: contentParts.join('\n\n'), title: documentTitle(record, schema, withheld), diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index 7eb7a9a24fe..95b70a0dd0f 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -1,14 +1,14 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Which `object` knowledge sources a caller's search may reach — the exposure + * Which knowledge sources a caller's search may reach — the exposure * decision and the field-level read rules, asked at SOURCE granularity before * a source is searched. * * ## Why the knowledge service owes them * * A knowledge passage is built at index time, under a system context, from - * every `contentFields` member of its source (plus the object's display field + * every `content` member of its source (plus the object's display field * as the title, and the source's `metadataFields`). The row re-check in `applyPermissionFilter` asks * only "may this caller read the row?". Every other door that serves object * rows outside the data routes also asks the spec's one exposure decision @@ -34,7 +34,7 @@ * the stored-metadata family never) — the posture the MCP record tools take. * * Then, per source, the **field gate**: every field the source serves (each - * `contentFields` member — `'*'` meaning every field the object declares — each + * `content` member, each * `metadataFields` member, the title field — `documentTitleField` — and, * while the index may hold documents assembled under the earlier title rule, a * declared `title`), less the credential-class and `internal` fields the index @@ -101,7 +101,6 @@ export type KnowledgeSourceRefusal = | 'object-api-not-served' | 'system-object-not-ai-readable' | 'field-not-queryable' - | 'fields-not-enumerable' | 'field-answer-unavailable'; export type KnowledgeSourceAdmission = @@ -131,7 +130,7 @@ type FieldAnswer = export interface ObjectAdmission { readonly object: string; readonly schema: unknown; - readonly refused?: Exclude; + readonly refused?: Exclude; readonly fields?: FieldAnswer; } @@ -240,24 +239,17 @@ export async function admitObject( /** * The fields a source serves in a passage, a hit's `title` or its `metadata`, * less the ones the index never carries (`recordToDocument`'s withheld set). - * `undefined` when `'*'` is declared and the object's fields cannot be - * enumerated. + * A source lists every field it serves (ADR-0161 K5: `content` takes no + * wildcard), so the set never depends on what else the object declares. */ -export function servedFieldsOf(objSource: ObjectKnowledgeSource, schema: unknown): Set | undefined { +export function servedFieldsOf(objSource: ObjectKnowledgeSource, schema: unknown): Set { const withheld = new Set([ ...collectCredentialWriteResponseFields(schema), ...collectInternalWriteResponseFields(schema), ]); const declared = declaredFields(schema); const served = new Set(); - for (const field of objSource.contentFields) { - if (field === '*') { - if (!declared) return undefined; - for (const [name] of declared) if (name !== 'id') served.add(name); - } else { - served.add(field); - } - } + for (const field of objSource.content) served.add(field); for (const field of objSource.metadataFields ?? []) served.add(field); // `recordToDocument` serves the title field's value whatever the source names. const titleField = documentTitleField(schema); @@ -285,13 +277,11 @@ export function admitSourceFields( } const served = servedFieldsOf(objSource, admission.schema); if (fields.kind === 'masked-only') { - // No declaration known ⇒ nothing is masked, so an unenumerable `'*'` serves nothing masked either. - for (const field of served ?? []) { + for (const field of served) { if (fields.masked.has(field)) return { admitted: false, reason: 'field-not-queryable', object, field }; } return { admitted: true }; } - if (!served) return { admitted: false, reason: 'fields-not-enumerable', object }; for (const field of served) { if (!fields.queryable.has(field)) return { admitted: false, reason: 'field-not-queryable', object, field }; } diff --git a/packages/services/service-knowledge/src/knowledge-source-loader.ts b/packages/services/service-knowledge/src/knowledge-source-loader.ts new file mode 100644 index 00000000000..2e606e49d43 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-source-loader.ts @@ -0,0 +1,259 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The loader of the governed `knowledge_source` type (ADR-0161 K4, clause 3: + * the type lands with its reader). + * + * ## What it does + * + * One pass ({@link KnowledgeSourceLoader.reconcile}) reads the published + * `knowledge_source` items and makes the knowledge service's metadata-door + * sources agree with them: + * + * - **an added item** is registered. At boot the service's first-build pass + * then reads its index and builds it when due; while the process runs, the + * loader asks for that itself (`buildReloadedSource`); + * - **a changed item** is registered again in its own slot — a reload of its + * earlier version, never a second arrival — and its fingerprint and recipe + * hash are read again, so a changed `content`, `where`, `metadataFields` or + * `split` starts the one rebuild ADR-0161 K7 gives it. An item that did not + * change is left alone: nothing is registered, read or built; + * - **a removed item** is unregistered and its index dropped + * (`IKnowledgeAdapter.dropSource`, K8 item 4). + * + * Boot and a source reload are the only two moments a rebuild starts (K7). + * + * ## Which rows are sources + * + * - A row bound to a package is that package's source: one slot per + * `(package, name)`, so two packages may each ship a source of one name + * (ADR-0150, addendum of 2026-11-25). + * - A row bound to no package, under a name no package holds, is the + * environment's own source. + * - A row bound to no package under a name a package holds is NOT served + * (ADR-0150 D4: "A package-less row that bears a package-held name is a + * customization, never a second item", and the type takes no overlay). If + * it was a source before the package arrived, it stops being one: it is + * unregistered, its index is dropped, and one `warn` names the row, the + * package that now holds the name and the remedy. An index of no source is + * a copy nobody governs, so it does not stay. Remove the package and the + * row is served again, and built as a source its adapter holds nothing for. + * - A row that does not parse with `KnowledgeSourceSchema` is no source, + * reported once at `warn` with the schema's own prescription. + * - A package-less row under a name the code door registered is refused by + * the registry (one name, one source), reported once at `warn` naming both + * doors. + * + * ## Fail direction + * + * A listing that cannot be read changes nothing: no source is unregistered + * and no index dropped on a failed read. Passes run one after another, and a + * pass asked for while one is queued is answered by that one. + */ + +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeLogger, KnowledgeService } from './knowledge-service.js'; +import { indexKeyOf, packageIdOfItem, parseKnowledgeSource } from './knowledge-source-registry.js'; + +/** What the loader reads and calls. */ +export interface KnowledgeSourceLoaderDeps { + service: Pick< + KnowledgeService, + 'registerMetadataSource' | 'dropMetadataSource' | 'metadataSources' | 'buildReloadedSource' + >; + /** + * The published `knowledge_source` items, each as its stored body with the + * row's protection envelope (`_packageId`) and without read decorations. + * `null` when the listing could not be read: the pass then changes nothing. + */ + readItems(): Promise; + /** The manifest namespace of a package, or `undefined` when the host cannot place it. */ + namespaceOf(packageId: string): string | undefined; + logger?: KnowledgeLogger; + /** + * Whether a source added or changed while the process runs is built when a + * build is due (`KnowledgeServicePluginOptions.buildAtBoot`). `false` leaves + * it to the operator's rebuild. + */ + buildOnReload: boolean; +} + +/** When a pass runs: the boot's load, or a change while the process runs. */ +export type KnowledgeSourceLoadReason = 'boot' | 'reload'; + +/** What one pass did, for its caller's log line and for tests. */ +export interface KnowledgeSourceLoadResult { + /** `false` when the listing could not be read and nothing was changed. */ + read: boolean; + /** Faces of the sources registered for the first time. */ + added: string[]; + /** Faces of the sources registered again because their item changed. */ + changed: string[]; + /** Faces of the sources unregistered, their index dropped. */ + removed: string[]; +} + +export class KnowledgeSourceLoader { + /** Per index key, the item as last registered: what "changed" is judged against. */ + private readonly registered = new Map(); + /** Refusals and unserved rows already reported, so each is said once until it changes. */ + private readonly reported = new Set(); + private queue: Promise = Promise.resolve(); + private pending: Promise | undefined; + + constructor(private readonly deps: KnowledgeSourceLoaderDeps) {} + + /** + * Run one pass, after any pass already running. A pass asked for while one + * is waiting to start is answered by that one: it has not read yet, so it + * sees whatever the second caller's change was. + */ + reconcile(reason: KnowledgeSourceLoadReason): Promise { + if (reason === 'reload' && this.pending) return this.pending; + const run = this.queue.then(() => { + if (this.pending === run) this.pending = undefined; + return this.pass(reason); + }); + if (reason === 'reload') this.pending = run; + this.queue = run.catch(() => undefined); + return run; + } + + private async pass(reason: KnowledgeSourceLoadReason): Promise { + const { service, logger } = this.deps; + const result: KnowledgeSourceLoadResult = { read: false, added: [], changed: [], removed: [] }; + const rows = await this.deps.readItems(); + if (rows === null) return result; + result.read = true; + + const stillReported = new Set(); + const reportOnce = (signature: string, line: string): void => { + stillReported.add(signature); + if (this.reported.has(signature)) return; + this.reported.add(signature); + logger?.warn?.(line); + }; + + // Parse every row; note which names a package holds. + const parsed: Array<{ source: KnowledgeSource; packageId?: string }> = []; + const packageHolders = new Map(); + for (const row of rows) { + const outcome = parseKnowledgeSource(row); + if (!outcome.ok) { + const name = rowName(row); + reportOnce( + `unparsed\u0000${name}\u0000${outcome.message}`, + `[knowledge] the knowledge_source item ${name} is not a valid source and is not served: ${outcome.message}`, + ); + continue; + } + const packageId = packageIdOfItem(outcome.source); + parsed.push(packageId === undefined ? { source: outcome.source } : { source: outcome.source, packageId }); + if (packageId !== undefined) { + const holders = packageHolders.get(outcome.source.name) ?? []; + holders.push(packageId); + packageHolders.set(outcome.source.name, holders); + } + } + + // The slots the listing fills. A package-less row under a package-held + // name fills none (ADR-0150 D4). + const desired = new Map(); + const unserved = new Map(); + for (const item of parsed) { + const holders = packageHolders.get(item.source.name); + if (item.packageId === undefined && holders !== undefined) { + unserved.set(item.source.name, holders); + continue; + } + const key = indexKeyOf(item.packageId, item.source.name); + if (desired.has(key)) { + reportOnce( + `twice\u0000${key}`, + `[knowledge] the listing holds knowledge source '${item.source.name}' twice for ` + + `${item.packageId === undefined ? 'the environment' : `package "${item.packageId}"`}; the first is served.`, + ); + continue; + } + desired.set(key, item); + } + + // Removed items, and rows that stopped being served: unregister and drop. + for (const entry of service.metadataSources()) { + if (desired.has(entry.key)) continue; + await service.dropMetadataSource(entry.key); + this.registered.delete(entry.key); + result.removed.push(entry.face); + } + for (const [name, holders] of unserved) { + const by = holders.map((id) => `"${id}"`).join(', '); + reportOnce( + `unserved\u0000${name}\u0000${holders.join('\u0000')}`, + `[knowledge] the knowledge source '${name}' authored in this environment is not served: package ${by} ` + + `${holders.length === 1 ? 'holds' : 'hold'} the name, and a package-less item under a package-held name is ` + + 'not a second source (ADR-0150 D4). It is not searched, and any index it had was dropped. Rename the ' + + "environment's source, or remove the package's.", + ); + } + + // Added and changed items. + const reloaded: string[] = []; + for (const [key, item] of desired) { + const namespace = item.packageId === undefined ? undefined : this.namespaceOf(item.packageId); + const signature = stableJson({ source: item.source, namespace: namespace ?? null }); + const before = this.registered.get(key); + if (before === signature) continue; + try { + const entry = service.registerMetadataSource(item.source, { + ...(item.packageId === undefined ? {} : { packageId: item.packageId }), + ...(namespace === undefined ? {} : { namespace }), + }); + this.registered.set(key, signature); + (before === undefined ? result.added : result.changed).push(entry.face); + reloaded.push(key); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + reportOnce(`refused\u0000${key}\u0000${message}`, `${message} The item is not served.`); + } + } + + // What was reported and no longer holds may be said again if it returns. + for (const signature of [...this.reported]) if (!stillReported.has(signature)) this.reported.delete(signature); + + if (reason === 'reload' && this.deps.buildOnReload) { + // Started, not awaited: a build can outlast any caller. One at a time, + // as the boot pass builds; `buildReloadedSource` never rejects. + void (async () => { + for (const key of reloaded) await service.buildReloadedSource(key); + })().catch(() => undefined); + } + return result; + } + + private namespaceOf(packageId: string): string | undefined { + try { + const namespace = this.deps.namespaceOf(packageId); + return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; + } catch { + return undefined; + } + } +} + +/** A row's name as a log line shows it, or a placeholder for a row that states none. */ +function rowName(row: unknown): string { + const name = (row as { name?: unknown } | null | undefined)?.name; + return typeof name === 'string' && name !== '' ? JSON.stringify(name.length > 64 ? `${name.slice(0, 64)}…` : name) : '(unnamed)'; +} + +/** `JSON.stringify` with every plain object's keys sorted. */ +function stableJson(value: unknown): string { + return JSON.stringify(value, (_key, v: unknown) => { + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + const sorted: Record = {}; + for (const k of Object.keys(v as Record).sort()) sorted[k] = (v as Record)[k]; + return sorted; + } + return v; + }); +} diff --git a/packages/services/service-knowledge/src/knowledge-source-registry.ts b/packages/services/service-knowledge/src/knowledge-source-registry.ts new file mode 100644 index 00000000000..27f05077bff --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-source-registry.ts @@ -0,0 +1,307 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The knowledge service's registry of sources: one slot per `(package, name)` + * (ADR-0150, addendum of 2026-11-25; ADR-0161 K4), filled through two doors. + * + * ## The two doors, one schema + * + * - **The metadata door**: `KnowledgeServicePlugin` loads each published + * `knowledge_source` item. Its holder is the package the item's row is + * bound to, or none for a source authored in the environment. + * - **The code door**: `KnowledgeServicePlugin({ sources })` and + * `IKnowledgeService.registerSource`. A source registered in code belongs to + * no package: it is read as the environment's own source and takes the one + * package-less slot of its name. + * + * Both parse with `KnowledgeSourceSchema` ({@link parseKnowledgeSource}), so a + * door refuses exactly what the other refuses. The code door runs no ADR-0087 + * conversion: a registration that still writes a retired key is refused with + * that key's own prescription (ADR-0161 K6, "every door runs the same kit" — + * this door's half is the refusal). + * + * ## One name, one source + * + * A slot is `(package, name)`. Two packages' sources of one name are two + * sources, and so are a package's source and a package-less one. Within the + * package-less slot, a registration from one door never replaces a source + * that arrived through the other: the second arrival is refused, naming both + * doors. The same door registering its name again replaces its own earlier + * version (a metadata item that reloads, a host that registers twice). + * + * ## The three spellings of a source + * + * - **Its name** — what the author wrote. Unique only within its holder. + * - **Its face** — how every caller names it: a package's source is + * `NAMESPACE-NAME` (ADR-0150 D6, `deriveAiFaceName`), a package-less one its + * bare name. `search_knowledge` lists and takes faces, and so do the by-name + * members of `IKnowledgeService`, the hits `search` answers and the + * operator's rebuild action. + * - **Its index key** ({@link indexKeyOf}) — what its index is keyed by: the + * document ids and what an adapter keeps for it. Never shown to a caller. + * + * ## Reading a caller's spelling ({@link KnowledgeSourceRegistry.resolve}) + * + * 1. a face answers its one source; a face two sources derive is refused, + * naming each holder; + * 2. otherwise a bare name resolves by ADR-0150 D3 for a caller with no + * package (`resolvePackageScopedHolders`): the package-less source first + * (its face is its bare name, so step 1 already answered it), else the one + * package holder, else a refusal naming each candidate by its face; + * 3. neither: no source. + * + * A refusal is `409 RESOURCE_CONFLICT` (ADR-0150 D5), never a pick. + */ + +import { createHash } from 'node:crypto'; +import { + RUNTIME_COMPATIBILITY_PACKAGE_ID, + packageScopedHolderSource, + resolvePackageScopedHolders, +} from '@objectstack/core'; +import { KnowledgeSourceSchema, deriveAiFaceName, type KnowledgeSource } from '@objectstack/spec/ai'; + +/** The metadata type a knowledge source is. */ +export const KNOWLEDGE_SOURCE_TYPE = 'knowledge_source'; + +/** Which door a source arrived through. */ +export type KnowledgeSourceDoor = 'code' | 'metadata'; + +/** How a refusal names each door. */ +const DOOR_TEXT: Record = { + code: 'a registration in code (KnowledgeServicePlugin({ sources }) or registerSource)', + metadata: 'a knowledge_source metadata item authored in this environment', +}; + +/** One registered source. */ +export interface KnowledgeSourceEntry { + /** What the source's index is keyed by ({@link indexKeyOf}). */ + readonly key: string; + /** How a caller names the source: `NAMESPACE-NAME`, or the bare name of a package-less one. */ + readonly face: string; + readonly door: KnowledgeSourceDoor; + /** The package that holds the source; absent for a package-less one. */ + readonly packageId?: string; + /** The holder's namespace, when the host could answer it. */ + readonly namespace?: string; + /** The source as its author wrote it, parsed. */ + readonly authored: KnowledgeSource; + /** + * The source as the service and every adapter are handed it: the authored + * source with `name` set to {@link key}. An adapter keys its store by the + * name of the source it is handed, so two packages' sources of one name + * never meet in a store, with no member added to the adapter contract. + */ + readonly handed: KnowledgeSource; +} + +/** Who holds a metadata item's source. */ +export interface KnowledgeSourceHolder { + packageId?: string; + namespace?: string; +} + +/** An ADR-0112 coded error. */ +export function codedError(code: string, status: number, message: string): Error { + return Object.assign(new Error(message), { code, status, httpStatus: status }); +} + +/** + * The key a source's index is held under. + * + * - A package-less source: its bare `name`. + * - A package's source: `_p`, the first 16 hex characters of SHA-256 over the + * package id, `_`, the name. A package id is free text (dots, dashes, a + * scope) and an adapter may put the key in an identifier, so the id is + * hashed, not embedded; the result stays snake_case. + * + * A name is letter-led (`KnowledgeSourceSchema` refuses a leading `_`), so no + * package-less key can equal a package's. + */ +export function indexKeyOf(packageId: string | undefined, name: string): string { + if (packageId === undefined) return name; + return `_p${createHash('sha256').update(packageId).digest('hex').slice(0, 16)}_${name}`; +} + +/** + * The package a metadata row is bound to: a non-empty `_packageId` that is not + * the package-less row's `sys_metadata` sentinel nor the runtime's + * compatibility id (the two spellings ADR-0150 D3 reads as "no package"). + */ +export function packageIdOfItem(item: unknown): string | undefined { + const id = (item as { _packageId?: unknown } | null | undefined)?._packageId; + return typeof id === 'string' && id !== '' && id !== 'sys_metadata' && id !== RUNTIME_COMPATIBILITY_PACKAGE_ID + ? id + : undefined; +} + +/** + * Parse `input` with the one schema of the type. Answers the parsed source, or + * the refusal's sentence: every issue, each at its own path with the schema's + * own message (a retired key's prescription, an unknown key's suggestion). + */ +export function parseKnowledgeSource(input: unknown): { ok: true; source: KnowledgeSource } | { ok: false; message: string } { + const parsed = KnowledgeSourceSchema.safeParse(input); + if (parsed.success) return { ok: true, source: parsed.data as KnowledgeSource }; + const issues = parsed.error.issues.map((issue) => { + const path = issue.path.join('.'); + return path === '' ? issue.message : `at \`${path}\`: ${issue.message}`; + }); + return { ok: false, message: issues.join(' ') }; +} + +/** How a refusal or a log line names an entry's holder. */ +function holderText(entry: Pick): string { + if (entry.packageId !== undefined) return `package "${entry.packageId}"`; + return entry.door === 'code' ? 'no package (registered in code)' : 'no package (authored in this environment)'; +} + +/** The registry: every registered source, one per `(package, name)`. */ +export class KnowledgeSourceRegistry { + /** By index key, in registration order. */ + private readonly byKey = new Map(); + + /** Every entry, in registration order. */ + entries(): KnowledgeSourceEntry[] { + return [...this.byKey.values()]; + } + + /** The entry held under an index key. */ + byIndexKey(key: string): KnowledgeSourceEntry | undefined { + return this.byKey.get(key); + } + + /** The entry of exactly this holder and name, with no resolution. */ + slot(packageId: string | undefined, name: string): KnowledgeSourceEntry | undefined { + const entry = this.byKey.get(indexKeyOf(packageId, name)); + return entry !== undefined && entry.packageId === packageId ? entry : undefined; + } + + /** + * Register a parsed source in its slot. Answers the entry and the one it + * replaced (the same door's earlier version of the same slot), if any. + * + * Refused, `409 RESOURCE_CONFLICT`: + * - the package-less slot is held by a source that arrived through the + * other door — naming both doors; + * - another package's source already holds the same index key (two package + * ids whose hashes agree on 64 bits) — naming both packages; never merged. + */ + register( + source: KnowledgeSource, + door: KnowledgeSourceDoor, + holder: KnowledgeSourceHolder = {}, + ): { entry: KnowledgeSourceEntry; replaced?: KnowledgeSourceEntry } { + const packageId = holder.packageId; + const key = indexKeyOf(packageId, source.name); + const existing = this.byKey.get(key); + if (existing !== undefined && existing.packageId !== packageId) { + throw codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] source '${source.name}' of ${holderText({ packageId, door })} was not registered: its index key ` + + `'${key}' is already held by source '${existing.authored.name}' of ${holderText(existing)}. Two package ids ` + + 'hash to the same key; rename one of the two sources.', + ); + } + if (existing !== undefined && existing.door !== door) { + throw codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] source '${source.name}' was not registered: the name is already held by a source that arrived ` + + `through the other door. Held by: ${DOOR_TEXT[existing.door]}. Refused: ${DOOR_TEXT[door]}. ` + + 'One name is one source (ADR-0161 K4), and a registration from one door never replaces a source from the ' + + 'other. Rename one of the two, or remove the one that is not wanted.', + ); + } + const namespace = packageId !== undefined && typeof holder.namespace === 'string' && holder.namespace !== '' + ? holder.namespace + : undefined; + const entry: KnowledgeSourceEntry = { + key, + face: packageId === undefined ? source.name : deriveAiFaceName({ name: source.name, namespace }), + door, + ...(packageId === undefined ? {} : { packageId }), + ...(namespace === undefined ? {} : { namespace }), + authored: source, + handed: { ...source, name: key }, + }; + this.byKey.set(key, entry); + return existing === undefined ? { entry } : { entry, replaced: existing }; + } + + /** Remove the entry held under an index key; answers it, or `undefined` when none was. */ + remove(key: string): KnowledgeSourceEntry | undefined { + const entry = this.byKey.get(key); + if (entry !== undefined) this.byKey.delete(key); + return entry; + } + + /** + * The source a caller's spelling names ({@link resolveSourceRef}), or + * `undefined` when it names none. Throws `409 RESOURCE_CONFLICT` when it + * names more than one. + */ + resolve(ref: string): KnowledgeSourceEntry | undefined { + return resolveSourceRef(this.entries(), ref, (entry) => ({ + face: entry.face, + name: entry.authored.name, + packageId: entry.packageId, + })); + } +} + +/** What {@link resolveSourceRef} reads of a candidate. */ +export interface KnowledgeSourceSpelling { + face: string; + name: string; + packageId?: string; +} + +/** + * The one rule for reading a caller's spelling of a source (the module doc), + * over whichever candidates the caller may name: the registry's every entry, + * or `search_knowledge`'s exposed sources — so a refusal never names a source + * the caller is not shown. Answers the candidate, or `undefined` when `ref` + * names none; throws `409 RESOURCE_CONFLICT` when it names more than one, + * listing each by its face and holder. + */ +export function resolveSourceRef( + candidates: readonly T[], + ref: string, + spell: (candidate: T) => KnowledgeSourceSpelling, +): T | undefined { + const spelled = candidates.map((candidate) => ({ candidate, ...spell(candidate) })); + const faced = spelled.filter((c) => c.face === ref); + if (faced.length === 1) return faced[0].candidate; + if (faced.length > 1) throw ambiguous(ref, faced); + const named = spelled.filter((c) => c.name === ref); + if (named.length === 0) return undefined; + // A holder holds a name once; two candidates of one holder are a malformed + // listing, never chosen between. + if (new Set(named.map((c) => c.packageId ?? null)).size !== named.length) throw ambiguous(ref, named); + const resolution = resolvePackageScopedHolders( + { type: KNOWLEDGE_SOURCE_TYPE, name: ref, callerPackageId: null }, + packageScopedHolderSource(named.map((c) => [c.packageId ?? null, c.candidate] as const)), + // A caller with no package is never asked for a closure. + () => new Set(), + ); + if (resolution.status === 'resolved') return resolution.item; + if (resolution.status === 'refused') throw ambiguous(ref, named); + return undefined; +} + +function ambiguous(ref: string, candidates: readonly KnowledgeSourceSpelling[]): Error { + const list = candidates + .map((c) => `'${c.face}' (${c.packageId === undefined ? 'held by no package' : `package "${c.packageId}"`})`) + .join(', '); + return Object.assign( + codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] ${JSON.stringify(ref.length > 64 ? `${ref.slice(0, 64)}…` : ref)} names ${candidates.length} knowledge sources: ${list}. ` + + 'Name the one you mean by its NAMESPACE-NAME spelling, as search_knowledge lists it in `sources`.', + ), + { candidates: candidates.map((c) => ({ face: c.face, ...(c.packageId === undefined ? {} : { packageId: c.packageId }) })) }, + ); +} diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index f48de464aeb..17530eb5124 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -2,8 +2,9 @@ import type { AIToolDefinition, IKnowledgeService } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeHit, KnowledgeSource } from '@objectstack/spec/ai'; import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS } from './knowledge-search-scope.js'; +import { packageIdOfItem, resolveSourceRef } from './knowledge-source-registry.js'; /** * The knowledge AI tool, `search_knowledge`, defined once with one executor @@ -28,7 +29,19 @@ import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS } from './knowledge-sear * sources whose `aiExposed` is not `false`, and a `sourceIds` entry naming * any other id, an unexposed source included, is refused `NOT_FOUND` with the * same sentence an unknown id gets, so the refusal never tells an agent that a - * withheld source exists. `IKnowledgeService.search` itself keeps searching + * withheld source exists. A `sourceIds` entry is read among the exposed + * sources only, for the same reason. + * + * ## How a source is named (ADR-0150 D6, addendum of 2026-11-25) + * + * An answer names a source by its **face**: `NAMESPACE-NAME` for a source a + * package ships, the bare name for one no package holds. `sources[].id` and a + * hit's `sourceId` carry it, and `sourceIds` takes it. A `sourceIds` entry is + * read by one rule (`resolveSourceRef`): a face answers its one source, else + * a bare name answers the source no package holds, else the one package's + * source of that name; a name two packages' sources share is refused + * `409 RESOURCE_CONFLICT`, naming each by its face. A hit's `documentId` is + * the stored document's id, opaque. `IKnowledgeService.search` itself keeps searching * an explicitly named source whatever its `aiExposed`: that service also * serves the platform's own callers, which are not agents, and `aiExposed` * governs what the AGENT tool may expose. @@ -50,9 +63,8 @@ import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS } from './knowledge-sear * ## No second gate, none bypassed (ADR-0090 D10) * * Every call reaches data only through `IKnowledgeService.search` with the - * caller's `ExecutionContext`, which re-checks each object-source hit against - * the caller's row-level security and drops object-source hits when no - * identity is passed. The executor adds no permission of its own and removes + * caller's `ExecutionContext`, which re-checks each hit against the caller's + * row-level security and serves no hit when no identity is passed. The executor adds no permission of its own and removes * none: a delegated agent's context reads what its delegating person reads. */ @@ -107,6 +119,7 @@ export interface SearchKnowledgeInput { /** One searchable source, as a `search_knowledge` answer names it. */ export interface SearchKnowledgeSourceSummary { + /** The source's face: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ id: string; label: string; description?: string; @@ -114,9 +127,9 @@ export interface SearchKnowledgeSourceSummary { /** One hit of a `search_knowledge` answer. */ export interface SearchKnowledgeHit { - /** The source the hit came from. */ + /** The source the hit came from, as `sources` lists it. */ sourceId: string; - /** The document the hit is part of. */ + /** The document the hit is part of: the stored document's id, opaque. */ documentId: string; /** The document's title, where the source gives one. */ title?: string; @@ -124,15 +137,14 @@ export interface SearchKnowledgeHit { snippet: string; /** Relevance, higher is better. */ score: number; - /** The record the passage was indexed from, for an object source: read it with the record tools. */ + /** The record the passage was indexed from: read it with the record tools. */ record?: { object: string; id: string }; /** The headings the passage sits under, outermost first, where its document has headings. */ headingPath?: string[]; /** * Under `groupBy`: the value of that field the hit's record holds — the * group the hit stands for — as the index stores it (a string, a number, a - * list for a `multiple` lookup). Absent on a hit of a `file` / `http` - * source, which answers under `groupBy` one hit per document. + * list for a `multiple` lookup). */ groupValue?: unknown; } @@ -178,7 +190,8 @@ export interface KnowledgeTools { * Run one `search_knowledge` call AS `context`. Refuses, by throwing an * ADR-0112 coded error (`code` and `status`), malformed arguments * (`VALIDATION_ERROR`, 400, naming the argument) and a `sourceIds` entry - * that names no source this tool may search (`NOT_FOUND`, 404). A caller's + * that names no source this tool may search (`NOT_FOUND`, 404) or more than + * one (`RESOURCE_CONFLICT`, 409). A caller's * string a refusal repeats is quoted and cut to 64 characters. */ searchKnowledge(input: unknown, context?: ExecutionContext): Promise; @@ -201,9 +214,8 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = + '`granularity: "record"`: one hit per record, its best passage, and `topK` counts records. To group by a ' + 'field the source indexes with its passages instead (one hit per policy for a search over clauses, say), send ' + '`groupBy` with that field\'s name: one hit per value, which the hit carries as `groupValue` (the value as the ' - + 'index stores it: a string, a number or a list). A source of indexed records that does not index that field ' - + 'answers nothing for that search; a file or web source still answers, one hit per document and with no ' - + '`groupValue`. To look inside records you already know (one ' + + 'index stores it: a string, a number or a list). A source that does not index that field ' + + 'answers nothing for that search. To look inside records you already know (one ' + 'policy, say), send `scope`: a list of `{ object, ids }` entries, at most ' + `${SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES} entries of at most ${SEARCH_KNOWLEDGE_MAX_SCOPE_IDS} ids. An entry naming ` + 'the object a source indexes searches those records\' passages; an entry naming a parent object searches the ' @@ -430,14 +442,40 @@ function parseInput(input: unknown): SearchKnowledgeInput { return parsed; } -/** The sources `search_knowledge` may search: every registered source whose `aiExposed` is not `false`. */ -function searchableSources(service: IKnowledgeService): KnowledgeSource[] { - return service.listSources().filter((source) => source.aiExposed !== false); +/** A source with the face an answer names it by. */ +interface NamedSource { + id: string; + source: KnowledgeSource; + packageId?: string; +} + +/** A knowledge service that answers each source with its face (`KnowledgeService.describeSources`). */ +interface SourceDescribingService { + describeSources(): NamedSource[]; +} + +function describesSources(service: IKnowledgeService): service is IKnowledgeService & SourceDescribingService { + return typeof (service as Partial).describeSources === 'function'; +} + +/** + * The sources `search_knowledge` may search: every registered source whose + * `aiExposed` is not `false`, each with its face. A service that does not + * describe its sources is one whose sources are named by their bare names. + */ +function searchableSources(service: IKnowledgeService): NamedSource[] { + const named: NamedSource[] = describesSources(service) + ? service.describeSources().map(({ id, source, packageId }) => ({ id, source, ...(packageId === undefined ? {} : { packageId }) })) + : service.listSources().map((source) => { + const packageId = packageIdOfItem(source); + return { id: source.name, source, ...(packageId === undefined ? {} : { packageId }) }; + }); + return named.filter(({ source }) => source.aiExposed !== false); } -function summarize(source: KnowledgeSource): SearchKnowledgeSourceSummary { +function summarize({ id, source }: NamedSource): SearchKnowledgeSourceSummary { return { - id: source.id, + id, label: source.label, ...(source.description ? { description: source.description } : {}), }; @@ -448,7 +486,7 @@ function summarize(source: KnowledgeSource): SearchKnowledgeSourceSummary { * else of the service's hit reaches the agent — not its `chunkId`, not the * stored `docHash` the record-level freshness check compares, and not its * `metadata`, of which only the `groupBy` field's value is answered, and only - * for an object source that lists that field (source admission holds every + * for a source that lists that field (source admission holds every * listed field queryable by the caller, ADR-0161 K8). */ function hitOf( @@ -456,8 +494,7 @@ function hitOf( sources: ReadonlyMap, groupBy: string | undefined, ): SearchKnowledgeHit { - const source = sources.get(hit.sourceId); - const objSource = source?.source.kind === 'object' ? (source.source as ObjectKnowledgeSource) : undefined; + const objSource = sources.get(hit.sourceId)?.source; const object = objSource?.object; const headingPath = Array.isArray(hit.headingPath) && hit.headingPath.every((h) => typeof h === 'string') ? [...hit.headingPath] @@ -502,10 +539,17 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle const { query, sourceIds, topK, scope, granularity, groupBy } = parseInput(input); const knowledge = resolve(); const searchable = searchableSources(knowledge); - const byId = new Map(searchable.map((source) => [source.id, source] as const)); + const byId = new Map(searchable.map((named) => [named.id, named.source] as const)); const summaries = searchable.map(summarize); + let named: string[] | undefined; if (sourceIds) { - const unknown = sourceIds.filter((id) => !byId.has(id)); + // Each entry read among the exposed sources, by the one rule: a name + // several of them have is refused 409 by `resolveSourceRef`. + const resolved = sourceIds.map((id) => + resolveSourceRef(searchable, id, (s) => ({ face: s.id, name: s.source.name, packageId: s.packageId })), + ); + named = [...new Set(resolved.filter((s): s is NamedSource => s !== undefined).map((s) => s.id))]; + const unknown = sourceIds.filter((_id, index) => resolved[index] === undefined); if (unknown.length > 0) { throw refusal( 'NOT_FOUND', @@ -517,7 +561,7 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle ); } } - const targets = sourceIds ?? [...byId.keys()]; + const targets = named ?? [...byId.keys()]; if (targets.length === 0) return { hits: [], sources: summaries }; // [ADR-0090 D10] As the caller: the service re-checks every object-source // hit against this context's row-level security. diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 2cc09035ec1..3cfd023558d 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -18,6 +18,8 @@ * builds: true, * refusesOtherFingerprint: true, * generations: true, + * scope: true, + * dropSource: true, * }, * }); * ``` @@ -47,7 +49,11 @@ * stores `docHash` returns it on each hit as stored, which the service's * record-level freshness check compares (pinned through a real * `KnowledgeService`), and an adapter that takes chunks returns each - * passage's `headingPath`. + * passage's `headingPath`; and `dropSource` (ADR-0161 K8, item 4) — on the + * adapter alone, every document of every generation and what it recorded + * about the index are gone and another source's are untouched, and through a + * real `KnowledgeService`, removing a metadata item's source drops its index + * or, for an adapter without the member, says once that it was kept. * * Every optional member is DECLARED by the caller in `implements`, and the * suite asserts the declaration against the adapter: a member an adapter lacks @@ -123,6 +129,12 @@ export interface KnowledgeAdapterContractOptions { * before it ranks, and returns each document's `metadata` on its hits. */ scope: boolean; + /** + * `dropSource` (ADR-0161 K8, item 4): the adapter removes everything it + * holds for a source — every document of every generation, and what it + * recorded about the index. + */ + dropSource: boolean; }; } @@ -138,10 +150,10 @@ const SOURCE_PREFIX = 'contract_'; function objectSource(id: string, extra: Partial = {}): KnowledgeSource { return { - id: `${SOURCE_PREFIX}${id}`, + name: `${SOURCE_PREFIX}${id}`, label: id, adapter: 'under_test', - source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'], ...extra }, + source: { kind: 'object', object: 'article', content: ['body'], metadataFields: ['status'], ...extra }, } as KnowledgeSource; } @@ -170,10 +182,10 @@ function docFor(withChunks: boolean) { docHash?: string, organizationId?: string, ): KnowledgeDocument => { - const id = `${source.id}:${n}`; + const id = `${source.name}:${n}`; return { id, - sourceId: source.id, + sourceId: source.name, sourceRecordId: n, content, title: `Title ${n}`, @@ -370,6 +382,9 @@ async function serviceOver( }, } : {}), + ...(typeof adapter.dropSource === 'function' + ? { dropSource: (ctx: AdapterContext) => adapter.dropSource!(ctx) } + : {}), }; const posture = setup.posture; const engine = rowsEngine(rows, setup.wall); @@ -471,6 +486,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption // The two ends of a build come together or not at all. expect(typeof adapter.beginBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); + expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -485,8 +501,8 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption await adapter.upsert([doc(b, '1', 'alpine meadow flowers')], ctxOf(b)); const hits = await adapter.search('alpine meadow', { source: a, topK: 5 }); expect(hits.length).toBeGreaterThan(0); - expect(hits[0].documentId).toBe(`${a.id}:1`); - for (const hit of hits) expect(hit.sourceId).toBe(a.id); + expect(hits[0].documentId).toBe(`${a.name}:1`); + for (const hit of hits) expect(hit.sourceId).toBe(a.name); for (let i = 1; i < hits.length; i++) expect(hits[i - 1].score).toBeGreaterThanOrEqual(hits[i].score); expect((await adapter.search('alpine meadow', { source: a, topK: 1 })).length).toBeLessThanOrEqual(1); }); @@ -497,18 +513,18 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption await adapter.upsert([doc(a, '1', 'volcanic basalt columns')], ctxOf(a)); await adapter.upsert([doc(a, '1', 'glacier ice caves')], ctxOf(a)); const stale = await adapter.search('volcanic basalt', { source: a, topK: 5 }); - expect(stale.filter((h) => h.documentId === `${a.id}:1`)).toEqual([]); + expect(stale.filter((h) => h.documentId === `${a.name}:1`)).toEqual([]); const fresh = await adapter.search('glacier ice', { source: a, topK: 5 }); - expect(fresh.map((h) => h.documentId)).toContain(`${a.id}:1`); + expect(fresh.map((h) => h.documentId)).toContain(`${a.name}:1`); }); it('a deleted document is not found; deleting an absent id is a no-op', async () => { const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); await adapter.upsert([doc(a, '1', 'copper kettle'), doc(a, '2', 'copper wire')], ctxOf(a)); - await adapter.delete([`${a.id}:1`, `${a.id}:absent`], ctxOf(a)); + await adapter.delete([`${a.name}:1`, `${a.name}:absent`], ctxOf(a)); const hits = await adapter.search('copper', { source: a, topK: 5 }); - expect(hits.map((h) => h.documentId)).toEqual([`${a.id}:2`]); + expect(hits.map((h) => h.documentId)).toEqual([`${a.name}:2`]); }); }); @@ -533,15 +549,15 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const { adapter, a } = await seeded(); // topK 1: a filter applied after ranking would keep B's better hit and drop it, answering nothing. const top = await adapter.search(ORG_QUERY, { source: a, topK: 1, organizationIds: ['org_a'] }); - expect(top.map((h) => h.documentId)).toEqual([`${a.id}:a1`]); + expect(top.map((h) => h.documentId)).toEqual([`${a.name}:a1`]); const all = await adapter.search(ORG_QUERY, { source: a, topK: 5, organizationIds: ['org_a'] }); - expect(all.map((h) => h.documentId)).toEqual([`${a.id}:a1`]); + expect(all.map((h) => h.documentId)).toEqual([`${a.name}:a1`]); }); it('ranks the documents of every organization in the set, and none stored without one', async () => { const { adapter, a } = await seeded(); const hits = await adapter.search(ORG_QUERY, { source: a, topK: 5, organizationIds: ['org_a', 'org_b'] }); - expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.id}:a1`, `${a.id}:b1`]); + expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.name}:a1`, `${a.name}:b1`]); }); it('an empty set ranks nothing — it is never read as "no filter"', async () => { @@ -552,7 +568,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('without the option every document is ranked, as before', async () => { const { adapter, a } = await seeded(); const hits = await adapter.search(ORG_QUERY, { source: a, topK: 5 }); - expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.id}:a1`, `${a.id}:b1`, `${a.id}:n1`]); + expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.name}:a1`, `${a.name}:b1`, `${a.name}:n1`]); }); }); } @@ -563,15 +579,15 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = orgRows(); const source = objectSource(`org_${posture}`); const h = await serviceOver(make, rows, source, { posture: () => posture, wall: wallOf(posture) }); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2 }); const caller = posture === 'isolated' ? CALLER_A : CALLER_AC; const hits = await h.svc.search(ORG_QUERY, { topK: 1, executionContext: caller }); // The service hands the adapter the caller's organizations, by the posture. expect(lastOf(h.searched)?.organizationIds).toEqual(posture === 'isolated' ? ['org_a'] : ['org_a', 'org_c']); - expect(hits.map((x) => x.documentId)).not.toContain(`${source.id}:rb`); + expect(hits.map((x) => x.documentId)).not.toContain(`${source.name}:rb`); if (opts.implements.organizationIds) { // Filtered before ranking: B's better document does not take A's place. - expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:ra`]); + expect(hits.map((x) => x.documentId)).toEqual([`${source.name}:ra`]); } }); } @@ -579,7 +595,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('isolated: a caller with no active organization is handed an empty set, and gets nothing', async () => { const source = objectSource('org_none'); const h = await serviceOver(make, orgRows(), source, { posture: () => 'isolated', wall: wallOf('isolated') }); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); const nobody = { ...CALLER_A, tenantId: undefined, accessible_org_ids: [] } as ExecutionContext; expect(await h.svc.search(ORG_QUERY, { topK: 5, executionContext: nobody })).toEqual([]); expect(lastOf(h.searched)?.organizationIds).toEqual([]); @@ -588,16 +604,16 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('single posture and the system identity: no filter is handed, and the results are as before', async () => { const source = objectSource('org_single'); const single = await serviceOver(make, orgRows(), source, { posture: () => 'single' }); - await single.svc.reindexSource(source.id); + await single.svc.reindexSource(source.name); const hits = await single.svc.search(ORG_QUERY, { topK: 1, executionContext: CALLER_A }); expect(lastOf(single.searched)).not.toHaveProperty('organizationIds'); - expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:rb`]); + expect(hits.map((x) => x.documentId)).toEqual([`${source.name}:rb`]); const walled = await serviceOver(make, orgRows(), source, { posture: () => 'isolated', wall: wallOf('isolated') }); - await walled.svc.reindexSource(source.id); + await walled.svc.reindexSource(source.name); const asSystem = await walled.svc.search(ORG_QUERY, { topK: 1, executionContext: SYSTEM }); expect(lastOf(walled.searched)).not.toHaveProperty('organizationIds'); - expect(asSystem.map((x) => x.documentId)).toEqual([`${source.id}:rb`]); + expect(asSystem.map((x) => x.documentId)).toEqual([`${source.name}:rb`]); }); if (opts.implements.organizationIds) { @@ -605,13 +621,13 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption let posture: TenancyPosture = 'single'; const source = objectSource('org_upgrade'); const h = await serviceOver(make, orgRows(), source, { posture: () => posture, wall: wallOf('isolated') }); - await h.svc.reindexSource(source.id); // under `single`: no document carries an organization + await h.svc.reindexSource(source.name); // under `single`: no document carries an organization posture = 'isolated'; expect(await h.svc.search(ORG_QUERY, { topK: 5, executionContext: CALLER_A })).toEqual([]); // The organization enters the hash, so the reindex writes both documents again rather than skipping them. - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); const hits = await h.svc.search(ORG_QUERY, { topK: 5, executionContext: CALLER_A }); - expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:ra`]); + expect(hits.map((x) => x.documentId)).toEqual([`${source.name}:ra`]); }); } }); @@ -724,7 +740,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('an own-object scope: every hit is one of the scoped records, and topK is filled from their passages', async () => { const source = clauseSource('scope_record'); const h = await serviceOver(make, clauseRows(), source, { schemas: { article: CLAUSE_SCHEMA } }); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 20 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 20 }); const scoped = new Set(['c03', 'c07']); const hits = await h.svc.search(SCOPE_QUERY, { topK: 5, @@ -745,7 +761,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('a parent scope: only the clauses whose listed lookup holds one of the policy ids', async () => { const source = clauseSource('scope_parent'); const h = await serviceOver(make, clauseRows(), source, { schemas: { article: CLAUSE_SCHEMA } }); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); const hits = await h.svc.search(SCOPE_QUERY, { topK: 5, scope: [{ object: 'policy', ids: ['p1'] }], @@ -768,7 +784,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption stripScope: true, logger: { warn, debug: () => undefined, info: () => undefined, error: () => undefined }, }); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); for (const ids of [['c03', 'c07'], ['c07']]) { const hits = await h.svc.search(SCOPE_QUERY, { topK: 5, scope: [{ object: 'article', ids }], executionContext: READER }); for (const hit of hits) expect(ids).toContain(hit.sourceRecordId); @@ -797,7 +813,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const { pages, entries } = await listAll(adapter, a, 3); const ids = entries.map((e) => e.documentId); expect(new Set(ids).size).toBe(ids.length); - expect([...ids].sort()).toEqual(Array.from({ length: n }, (_, i) => `${a.id}:d${i}`).sort()); + expect([...ids].sort()).toEqual(Array.from({ length: n }, (_, i) => `${a.name}:d${i}`).sort()); // 0 and 3 documents fit one page (plus, at most, an empty one after it); 4 need two. expect(pages).toBeLessThanOrEqual(n === 4 ? 3 : 2); if (n === 4) expect(pages).toBeGreaterThanOrEqual(2); @@ -810,9 +826,9 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption await adapter.upsert([doc(a, '1', 'granite quarry, revised', 'v1:replaced')], ctxOf(a)); const { entries } = await listAll(adapter, a, 10); const byId = new Map(entries.map((e) => [e.documentId, e.docHash])); - expect(byId.get(`${a.id}:1`)).toBe('v1:replaced'); - expect(byId.has(`${a.id}:2`)).toBe(true); - expect(byId.get(`${a.id}:2`)).toBeUndefined(); + expect(byId.get(`${a.name}:1`)).toBe('v1:replaced'); + expect(byId.has(`${a.name}:2`)).toBe(true); + expect(byId.get(`${a.name}:2`)).toBeUndefined(); }); it("lists only the source's own documents, and none that were deleted", async () => { @@ -821,9 +837,9 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const b = objectSource('b'); await adapter.upsert([doc(a, '1', 'tidal pool'), doc(a, '2', 'tidal flat')], ctxOf(a)); await adapter.upsert([doc(b, '1', 'tidal pool')], ctxOf(b)); - await adapter.delete([`${a.id}:2`], ctxOf(a)); + await adapter.delete([`${a.name}:2`], ctxOf(a)); const { entries } = await listAll(adapter, a, 10); - expect(entries.map((e) => e.documentId)).toEqual([`${a.id}:1`]); + expect(entries.map((e) => e.documentId)).toEqual([`${a.name}:1`]); }); }); @@ -834,9 +850,9 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption await adapter.upsert([doc(a, '1', 'basalt quarry', 'v1:opaque-as-given'), doc(a, '2', 'basalt cliffs')], ctxOf(a)); const hits = await adapter.search('basalt', { source: a, topK: 5 }); const byDoc = new Map(hits.map((h) => [h.documentId, h])); - expect(byDoc.get(`${a.id}:1`)?.docHash).toBe('v1:opaque-as-given'); - expect(byDoc.get(`${a.id}:2`)).toBeDefined(); - expect(byDoc.get(`${a.id}:2`)?.docHash).toBeUndefined(); + expect(byDoc.get(`${a.name}:1`)?.docHash).toBe('v1:opaque-as-given'); + expect(byDoc.get(`${a.name}:2`)).toBeDefined(); + expect(byDoc.get(`${a.name}:2`)?.docHash).toBeUndefined(); }); it('a record-level search answers one hit per record, and none for a record that changed or left since it was indexed', async () => { @@ -847,7 +863,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption ]; const source = objectSource('fresh', { where: { status: 'published' } }); const h = await serviceOver(make, rows, source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 3 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 3 }); const ask = () => h.svc.search('lagoon reef', { granularity: 'record', topK: 5, executionContext: SYSTEM }); expect((await ask()).map((x) => x.sourceRecordId).sort()).toEqual(['r1', 'r2', 'r3']); rows[0].body = 'lagoon reef, rewritten after indexing'; @@ -856,7 +872,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(out.map((x) => x.sourceRecordId)).toEqual(['r3']); // The stale documents are repaired in the background: r1 rewritten, r2 removed. await expect.poll(async () => (await ask()).map((x) => x.sourceRecordId).sort()).toEqual(['r1', 'r3']); - expect(h.upserted.flat().filter((id) => id === `${source.id}:r1`)).toHaveLength(2); + expect(h.upserted.flat().filter((id) => id === `${source.name}:r1`)).toHaveLength(2); }); }); @@ -865,25 +881,25 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(3); const source = objectSource('skip'); const h = await serviceOver(make, rows, source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 3, skipped: 0, purged: 0 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 3, skipped: 0, purged: 0 }); h.upserted.length = 0; - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, discovered: 3, indexed: 0, skipped: 3, purged: 0 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, discovered: 3, indexed: 0, skipped: 3, purged: 0 }); expect(h.upserted).toEqual([]); rows[1].body = 'body number 1 rewritten'; - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, skipped: 2, purged: 0 }); - expect(h.upserted).toEqual([[`${source.id}:r1`]]); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1, skipped: 2, purged: 0 }); + expect(h.upserted).toEqual([[`${source.name}:r1`]]); }); it('a complete reindex purges the documents of a deleted row and of a row that left where', async () => { const rows = rowsOf(3); const source = objectSource('purge', { where: { status: 'published' } }); const h = await serviceOver(make, rows, source); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); rows.splice(0, 1); // r0 deleted rows[1].status = 'draft'; // r2 stopped matching - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, discovered: 1, purged: 2 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, discovered: 1, purged: 2 }); const { entries } = await listAll(h.adapter, source, 10); - expect(entries.map((e) => e.documentId)).toEqual([`${source.id}:r1`]); + expect(entries.map((e) => e.documentId)).toEqual([`${source.name}:r1`]); expect((await h.adapter.search('zebra0 zebra2', { source, topK: 5 })).map((x) => x.documentId)).toEqual([]); }); @@ -891,10 +907,10 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(3); const source = objectSource('partial'); const h = await serviceOver(make, rows, source); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); rows.splice(0, 1); - expect(await h.svc.reindexSource(source.id, { limit: 10 })).toMatchObject({ ok: true, purged: null }); - expect(await h.svc.reindexSource(source.id, { dryRun: true })).toMatchObject({ ok: true, purged: null }); + expect(await h.svc.reindexSource(source.name, { limit: 10 })).toMatchObject({ ok: true, purged: null }); + expect(await h.svc.reindexSource(source.name, { dryRun: true })).toMatchObject({ ok: true, purged: null }); expect((await listAll(h.adapter, source, 10)).entries).toHaveLength(3); }); }); @@ -904,11 +920,11 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(3); const source = objectSource('nolist'); const h = await serviceOver(make, rows, source); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); rows.splice(0, 1); h.upserted.length = 0; - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0, purged: null }); - expect(h.upserted.flat()).toEqual([`${source.id}:r1`, `${source.id}:r2`]); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2, skipped: 0, purged: null }); + expect(h.upserted.flat()).toEqual([`${source.name}:r1`, `${source.name}:r2`]); }); }); } @@ -918,7 +934,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(2); const source = objectSource('fp_carry'); const h = await serviceOver(make, rows, source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2 }); await h.svc.handleRecordDelete('article', 'r0'); await h.svc.search('zebra1', { topK: 3, executionContext: SYSTEM }); expect(h.contexts.length).toBeGreaterThan(0); @@ -938,7 +954,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }; const base = await seen({}); expect(await seen({})).toEqual(base); // the same source, the same adapter: the same hashes - const content = await seen({ contentFields: ['body', 'status'] }); + const content = await seen({ content: ['body', 'status'] }); expect(content.fingerprint).not.toBe(base.fingerprint); const where = await seen({ where: { status: 'published' } }); expect(where.fingerprint).toBe(base.fingerprint); @@ -953,19 +969,19 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(3); const source = objectSource('fp_pair'); const h = await serviceOver(make, rows, source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true }); expect(h.builds).toEqual(['begin', 'complete']); - await h.svc.reindexSource(source.id, { limit: 10 }); - await h.svc.reindexSource(source.id, { dryRun: true }); + await h.svc.reindexSource(source.name, { limit: 10 }); + await h.svc.reindexSource(source.name, { dryRun: true }); expect(h.builds).toEqual(['begin', 'complete']); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true }); expect(h.builds).toEqual(['begin', 'complete', 'begin', 'complete']); }); } else { it('without beginBuild / completeBuild a complete reindex walks as before', async () => { const source = objectSource('fp_nobuild'); const h = await serviceOver(make, rowsOf(2), source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2 }); expect(h.builds).toEqual([]); }); } @@ -977,7 +993,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const before = await h.adapter.indexStatus!(ctxOf(source)); expect(before.recipeHash).toBeUndefined(); expect(before.building ?? false).toBe(false); - await h.svc.reindexSource(source.id); + await h.svc.reindexSource(source.name); const carried = h.contexts[0].index!; const after = await h.adapter.indexStatus!(ctxOf(source)); expect(after.fingerprint).toBe(carried.fingerprint); @@ -1001,29 +1017,29 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption await adapter.upsert([doc(a, '1', 'basalt columns')], ctxOf(a, FP_OLD)); await expectRebuildRefusal(adapter.upsert([doc(a, '2', 'basalt quarry')], ctxOf(a, FP_NEW))); const hits = await adapter.search('basalt', { source: a, topK: 5, index: { fingerprint: FP_OLD.fingerprint } }); - expect(hits.map((x) => x.documentId)).toEqual([`${a.id}:1`]); + expect(hits.map((x) => x.documentId)).toEqual([`${a.name}:1`]); }); it('through KnowledgeService: a changed recipe refuses the source by name, and the call whole only when none answers', async () => { const rows = rowsOf(2); const stale = objectSource('fp_stale'); const h = await serviceOver(make, rows, stale); - await h.svc.reindexSource(stale.id); + await h.svc.reindexSource(stale.name); // The content list changes: a new fingerprint the stored index was not built under. - h.svc.registerSource(objectSource('fp_stale', { contentFields: ['body', 'status'] })); + h.svc.registerSource(objectSource('fp_stale', { content: ['body', 'status'] })); const whole = await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM }).then( () => undefined, (e: unknown) => e, ); - expect(whole).toMatchObject({ code: REBUILD_REQUIRED, status: 409, refused: [{ sourceId: stale.id, code: REBUILD_REQUIRED }] }); + expect(whole).toMatchObject({ code: REBUILD_REQUIRED, status: 409, refused: [{ sourceId: stale.name, code: REBUILD_REQUIRED }] }); // A second source that can be searched answers; the stale one is named, never read as empty. const fresh = objectSource('fp_fresh'); h.svc.registerSource(fresh); - await h.svc.reindexSource(fresh.id); + await h.svc.reindexSource(fresh.name); const report = await h.svc.searchWithRefusals('zebra1', { topK: 5, executionContext: SYSTEM }); - expect(report.hits.map((x) => x.sourceId)).toEqual([fresh.id]); - expect(report.refused).toEqual([expect.objectContaining({ sourceId: stale.id, code: REBUILD_REQUIRED, status: 409 })]); - expect((await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })).map((x) => x.sourceId)).toEqual([fresh.id]); + expect(report.hits.map((x) => x.sourceId)).toEqual([fresh.name]); + expect(report.refused).toEqual([expect.objectContaining({ sourceId: stale.name, code: REBUILD_REQUIRED, status: 409 })]); + expect((await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })).map((x) => x.sourceId)).toEqual([fresh.name]); }); } @@ -1051,16 +1067,99 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const rows = rowsOf(2); const source = objectSource('fp_rebuild'); const h = await serviceOver(make, rows, source); - await h.svc.reindexSource(source.id); - h.svc.registerSource(objectSource('fp_rebuild', { contentFields: ['body', 'status'] })); + await h.svc.reindexSource(source.name); + h.svc.registerSource(objectSource('fp_rebuild', { content: ['body', 'status'] })); await expectRebuildRefusal(h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); const hits = await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM }); - expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:r1`]); + expect(hits.map((x) => x.documentId)).toEqual([`${source.name}:r1`]); }); } }); + describe('dropSource (ADR-0161 K8, item 4)', () => { + if (opts.implements.dropSource) { + it("removes every document of the source and none of another's; dropping a source it holds nothing for is no error", async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('drop_a'); + const b = objectSource('drop_b'); + await adapter.upsert([doc(a, '1', 'granite quarry'), doc(a, '2', 'granite bridge')], ctxOf(a)); + await adapter.upsert([doc(b, '1', 'granite cliffs')], ctxOf(b)); + await adapter.dropSource!(ctxOf(a)); + expect(await adapter.search('granite', { source: a, topK: 5 })).toEqual([]); + expect((await adapter.search('granite', { source: b, topK: 5 })).map((x) => x.documentId)).toEqual([`${b.name}:1`]); + if (opts.implements.listDocuments) { + expect((await listAll(adapter, a, 10)).entries).toEqual([]); + expect((await listAll(adapter, b, 10)).entries.map((e) => e.documentId)).toEqual([`${b.name}:1`]); + } + // Twice, and for a source it has never seen: neither is an error. + await expect(adapter.dropSource!(ctxOf(a))).resolves.toBeUndefined(); + await expect(adapter.dropSource!(ctxOf(objectSource('drop_never')))).resolves.toBeUndefined(); + }); + + if (opts.implements.indexStatus) { + it('after it indexStatus answers as for a source never built, and the source builds again from nothing', async () => { + const source = objectSource('drop_status'); + const h = await serviceOver(make, rowsOf(2), source); + await h.svc.reindexSource(source.name); + expect((await h.adapter.indexStatus!(ctxOf(source))).fingerprint).toBeDefined(); + await h.adapter.dropSource!(ctxOf(source)); + const after = await h.adapter.indexStatus!(ctxOf(source)); + expect(after.fingerprint).toBeUndefined(); + expect(after.recipeHash).toBeUndefined(); + expect(after.building ?? false).toBe(false); + expect(await h.svc.readIndexState(source.name)).toMatchObject({ state: 'nothing', due: true }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 2 }); + expect((await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })).length).toBeGreaterThan(0); + }); + } + + if (opts.implements.generations) { + it('removes the generation under construction too: a build left open before the drop does not survive it', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('drop_building'); + await adapter.beginBuild!(ctxOf(a, FP_OLD)); + await adapter.upsert([doc(a, '1', 'obsidian shards')], ctxOf(a, FP_OLD)); + await adapter.completeBuild!(ctxOf(a, FP_OLD)); + await adapter.beginBuild!(ctxOf(a, FP_NEW)); + await adapter.upsert([doc(a, '2', 'obsidian mirror')], ctxOf(a, FP_NEW)); + await adapter.dropSource!(ctxOf(a)); + const status = await adapter.indexStatus?.(ctxOf(a)); + if (status !== undefined) { + expect(status.fingerprint).toBeUndefined(); + expect(status.building ?? false).toBe(false); + } + // Nothing of either generation answers, under either fingerprint or none. + expect(await adapter.search('obsidian', { source: a, topK: 5 })).toEqual([]); + }); + } + } + + it('through KnowledgeService: removing a metadata item\'s source drops its index, or says once that the adapter kept it', async () => { + const source = objectSource('drop_item'); + const warn = vi.fn(); + const h = await serviceOver(make, rowsOf(2), source, { logger: { warn } }); + // The suite registers through the code door; the removal under test is + // the metadata door's, so the source is registered there instead. + h.svc.unregisterSource(source.name); + const entry = h.svc.registerMetadataSource(source); + await h.svc.reindexSource(source.name); + expect((await h.adapter.search('zebra1', { source: entry.handed, topK: 5 })).length).toBeGreaterThan(0); + await h.svc.dropMetadataSource(entry.key); + expect(h.svc.getSource(source.name)).toBeUndefined(); + const left = await h.adapter.search('zebra1', { source: entry.handed, topK: 5 }); + const kept = warn.mock.calls.filter(([line]) => /its index was not dropped/.test(String(line))); + if (opts.implements.dropSource) { + expect(left).toEqual([]); + expect(kept).toEqual([]); + } else { + expect(left.length).toBeGreaterThan(0); + expect(kept).toHaveLength(1); + expect(String(kept[0][0])).toContain(`'${source.name}'`); + } + }); + }); + describe('the chunk channel (ADR-0161 K8, item 5)', () => { const longBody = 'Glaciers carve valleys over centuries. Their ice holds ancient air bubbles. ' + @@ -1074,7 +1173,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const source = splitSource('chunks'); const rows: Row[] = [{ id: 'r1', body: longBody, status: 'published' }]; const h = await serviceOver(make, rows, source); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, failed: 0, failures: [] }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1, failed: 0, failures: [] }); const [sent] = h.received; const expected = splitDocument( sent, @@ -1095,10 +1194,10 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('a hit carries the heading path of its passage, and none for a passage without one', async () => { const adapter: IKnowledgeAdapter = await make(); const a = objectSource('headings'); - const id = `${a.id}:1`; + const id = `${a.name}:1`; await adapter.upsert( [{ - id, sourceId: a.id, sourceRecordId: '1', content: 'fjord ferry timetable. fjord glacier', metadata: {}, + id, sourceId: a.name, sourceRecordId: '1', content: 'fjord ferry timetable. fjord glacier', metadata: {}, chunks: [ { id: `${id}#0`, documentId: id, index: 0, content: 'fjord ferry timetable', headingPath: ['Travel', 'Ferries'] }, { id: `${id}#1`, documentId: id, index: 1, content: 'fjord glacier' }, @@ -1121,36 +1220,22 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption ]; // 60 tokens: a 48-token budget, which the short row fits and the long one does not. const h = await serviceOver(make, rows, source, { maxInputTokens: 60 }); - const first = await h.svc.reindexSource(source.id); + const first = await h.svc.reindexSource(source.name); expect(first).toMatchObject({ ok: true, discovered: 2, indexed: 1, failed: 1 }); - expect(first.failures).toEqual([{ documentId: `${source.id}:r2`, reason: expect.stringContaining("split 'whole'") }]); + expect(first.failures).toEqual([{ documentId: `${source.name}:r2`, reason: expect.stringContaining("split 'whole'") }]); expect(await h.adapter.search('glaciers copper', { source, topK: 5 })).toEqual([]); // A document that fit and then grew past the budget leaves the index too. rows[0].body = `tundra ${longBody}`; - const second = await h.svc.reindexSource(source.id); + const second = await h.svc.reindexSource(source.name); expect(second).toMatchObject({ ok: true, failed: 2 }); expect((await h.adapter.search('tundra', { source, topK: 5 })).map((x) => x.documentId)).toEqual([]); }); - - it('indexDocument refuses caller-supplied chunks', async () => { - const source = splitSource('push'); - const h = await serviceOver(make, [], source); - await expect( - h.svc.indexDocument(source.id, { - id: `${source.id}:x`, - sourceId: source.id, - content: 'pushed', - chunks: [{ id: `${source.id}:x#0`, documentId: `${source.id}:x`, index: 0, content: 'pushed' }], - }), - ).rejects.toThrow(/chunks are cut by the knowledge service/); - expect(h.upserted).toEqual([]); - }); } else { it('receives whole documents, never chunks, whatever the source splits by or the budget', async () => { const source = splitSource('nochunks'); const rows: Row[] = [{ id: 'r1', body: longBody, status: 'published' }]; const h = await serviceOver(make, rows, source, { maxInputTokens: 20 }); - expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, failed: 0 }); + expect(await h.svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1, failed: 0 }); expect(h.received).toHaveLength(1); expect(h.received[0].content).toBe(longBody); expect('chunks' in h.received[0]).toBe(false); From 8b2cabd06db592698f6e9943a3398fdf2174276b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:11:10 +0000 Subject: [PATCH 04/29] feat(rest): two authoring guards for knowledge_source at the metadata write doors Guard one is a row in the existing per-type write capability table: a knowledge_source write through /meta (REST and the dispatcher) and through the MCP draft door needs manage_knowledge_sources beside manage_metadata. Guard two asks the knowledge service to admit an authored source for its author before it is saved: the author must themselves be able to search what the source would index. A verdict that cannot be reached refuses 503; over MCP the human is judged. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/metadata-core/src/index.ts | 1 + .../knowledge-source-save-admission.test.ts | 75 ++++++++++++ .../src/knowledge-source-save-admission.ts | 113 ++++++++++++++++++ packages/rest/src/meta-item-read-gate.ts | 20 +++- packages/rest/src/meta-item-write-routes.ts | 32 ++++- .../src/meta-type-write-capability.test.ts | 87 +++++++++++++- ...-write-door-capability-enumeration.test.ts | 90 ++++++++++++++ ...server-meta-org-scope-url-spelling.test.ts | 3 +- .../rest-server-meta-write-org-scope.test.ts | 5 +- packages/rest/src/rest-server.ts | 28 +++++ .../runtime/src/domains/mcp-authoring.test.ts | 99 +++++++++++++++ packages/runtime/src/domains/mcp-authoring.ts | 45 ++++++- .../domains/meta-save-capability-gate.test.ts | 66 ++++++++++ .../meta-type-write-capability-parity.test.ts | 62 ++++++++++ packages/runtime/src/domains/meta.ts | 22 ++++ .../runtime/src/meta-write-org-scope.test.ts | 4 +- 16 files changed, 739 insertions(+), 13 deletions(-) create mode 100644 packages/metadata-core/src/knowledge-source-save-admission.test.ts create mode 100644 packages/metadata-core/src/knowledge-source-save-admission.ts diff --git a/packages/metadata-core/src/index.ts b/packages/metadata-core/src/index.ts index 261b52a1090..6aa06364f4d 100644 --- a/packages/metadata-core/src/index.ts +++ b/packages/metadata-core/src/index.ts @@ -101,6 +101,7 @@ export * from './item-key-discriminators.js'; // axis. Sunk here because the doors live in `@objectstack/runtime` and // `@objectstack/rest`, which share no other common home. export * from './meta-write-capability.js'; +export * from './knowledge-source-save-admission.js'; // [#27884] The read-side twin: which readers a stored metadata document of a // capability-gated type (datasource, external_catalog) is served to, asked by the // `/meta` type gate (`@objectstack/rest`) and the engine's stored-row read gate diff --git a/packages/metadata-core/src/knowledge-source-save-admission.test.ts b/packages/metadata-core/src/knowledge-source-save-admission.test.ts new file mode 100644 index 00000000000..a3b7c3eeb8d --- /dev/null +++ b/packages/metadata-core/src/knowledge-source-save-admission.test.ts @@ -0,0 +1,75 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4, guard two] `authoredKnowledgeSourceRefusal` — what every save + * door asks before a `knowledge_source` is written: the knowledge service's + * verdict for the AUTHOR. Pinned here: which saves are judged, that the + * service is asked with the item and the author's context, and that the gate + * fails closed. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { authoredKnowledgeSourceRefusal, KNOWLEDGE_SOURCE_ADMISSION_SERVICE } from './knowledge-source-save-admission.js'; + +const ITEM = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; +const AUTHOR = { userId: 'u_author', systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }; +const REFUSED = { admitted: false as const, status: 403, code: 'PERMISSION_DENIED', message: "you may not query field 'salary' of object 'article'" }; + +const serviceAnswering = (verdict: unknown) => ({ admitAuthoredSource: vi.fn(async () => verdict) }); + +describe('authoredKnowledgeSourceRefusal — source admission at save', () => { + it('the service name is the knowledge service\'s', () => { + expect(KNOWLEDGE_SOURCE_ADMISSION_SERVICE).toBe('knowledge'); + }); + + it('asks the knowledge service with the item and the author\'s context, and answers its refusal coded', async () => { + const service = serviceAnswering(REFUSED); + for (const type of ['knowledge_source', 'knowledge_sources']) { + const refusal = await authoredKnowledgeSourceRefusal({ type, item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service }); + expect(refusal, type).toEqual({ status: 403, code: 'PERMISSION_DENIED', message: REFUSED.message }); + } + expect(service.admitAuthoredSource).toHaveBeenCalledWith(ITEM, AUTHOR); + }); + + it('an admitted source saves: no refusal', async () => { + const service = serviceAnswering({ admitted: true }); + expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: async () => service })).toBeUndefined(); + expect(service.admitAuthoredSource).toHaveBeenCalledTimes(1); + }); + + it('another type, and the engine\'s own write, are not judged: the service is never resolved', async () => { + const resolve = vi.fn(() => serviceAnswering(REFUSED)); + expect(await authoredKnowledgeSourceRefusal({ type: 'object', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: resolve })).toBeUndefined(); + expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { isSystem: true }, resolveKnowledgeService: resolve })).toBeUndefined(); + expect(resolve).not.toHaveBeenCalled(); + }); + + it('no knowledge service, or one without the member, judges nothing: nothing loads the item there', async () => { + for (const service of [undefined, null, {}, { search: async () => [] }]) { + expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service })).toBeUndefined(); + } + }); + + it('fails closed, SERVICE_UNAVAILABLE / 503: a service that cannot be resolved, and a verdict that throws', async () => { + const unresolved = await authoredKnowledgeSourceRefusal({ + type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, + resolveKnowledgeService: async () => { throw new Error('factory failed'); }, + }); + expect(unresolved).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(unresolved?.message).toContain('factory failed'); + expect(unresolved?.message).toContain('Nothing was written'); + + const thrown = await authoredKnowledgeSourceRefusal({ + type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, + resolveKnowledgeService: () => ({ admitAuthoredSource: async () => { throw new Error('registry unavailable'); } }), + }); + expect(thrown).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' }); + expect(thrown?.message).toContain('registry unavailable'); + }); + + it('`isSystem: false` is not a bypass', async () => { + const service = serviceAnswering(REFUSED); + const refusal = await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { ...AUTHOR, isSystem: false }, resolveKnowledgeService: () => service }); + expect(refusal?.status).toBe(403); + }); +}); diff --git a/packages/metadata-core/src/knowledge-source-save-admission.ts b/packages/metadata-core/src/knowledge-source-save-admission.ts new file mode 100644 index 00000000000..59987a6c545 --- /dev/null +++ b/packages/metadata-core/src/knowledge-source-save-admission.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4, guard two] Source admission at save: a `knowledge_source` is + * saved only when its AUTHOR may themselves search what it would index. + * + * ## What is asked, and of whom + * + * The knowledge service's search-time gates (`knowledge-source-admission.ts` + * in `@objectstack/service-knowledge`): the object's package is not disabled, + * the API serves the object for `search`, a system object opts into AI reads, + * and the caller may QUERY every field the source would put in its index. At + * search they decide which sources a caller's search reaches. Here the same + * gates are asked once, for the authoring principal, before the item is + * written — so nobody builds an index over an object or a field they could + * not have searched, and has the embedder sent text they may not read. + * + * ## Why the doors ask, through this one function + * + * The verdict needs the author's execution context, and the metadata protocol + * is handed only an actor id. So each door that saves an item asks, right + * after its capability gates and before the protocol writes: `PUT + * /meta/:type/:name` on both transports and the MCP draft save. The gates + * themselves stay with the knowledge service, reached by the duck-typed + * member {@link KnowledgeSourceSaveAdmitter.admitAuthoredSource}; the doors' + * packages do not depend on that package. + * + * ## What is not judged here + * + * - **Any other type**, and **the engine's own write** (`isSystem`: a package + * install, a seed, a migration): the gates that need no principal at + * `os validate` and publish are their own card (topic #37000, row 4). + * - **A deployment with no knowledge service**, or one whose service is not + * the platform's: nothing loads the item there, so nothing is indexed. + * + * ## Fail direction + * + * Access-narrowing, so it fails closed: a knowledge service that cannot be + * resolved, or a verdict that throws, refuses the save `503 + * SERVICE_UNAVAILABLE`. Nothing was written. + */ + +import { canonicalMetaUrlType } from '@objectstack/spec/meta-spelling'; + +/** The kernel service name the knowledge service registers under. */ +export const KNOWLEDGE_SOURCE_ADMISSION_SERVICE = 'knowledge'; + +/** The metadata type judged. */ +const KNOWLEDGE_SOURCE_TYPE = 'knowledge_source'; + +/** An ADR-0112 coded refusal of a save. */ +export interface AuthoredKnowledgeSourceRefusal { + status: number; + code: string; + message: string; +} + +/** The verdict {@link KnowledgeSourceSaveAdmitter.admitAuthoredSource} answers. */ +export type AuthoredKnowledgeSourceVerdict = + | { admitted: true } + | ({ admitted: false } & AuthoredKnowledgeSourceRefusal); + +/** The member of the `knowledge` service the doors ask, reached duck-typed. */ +export interface KnowledgeSourceSaveAdmitter { + admitAuthoredSource(item: unknown, context: unknown): Promise; +} + +function unavailable(why: string): AuthoredKnowledgeSourceRefusal { + return { + status: 503, + code: 'SERVICE_UNAVAILABLE', + message: + `The knowledge source was not saved: whether its author may search what it would index could not be ` + + `judged (${why}). Nothing was written; try again.`, + }; +} + +/** + * The refusal of a `knowledge_source` save, or `undefined` when the save may + * go on (the module doc says what is and is not judged). + * + * `resolveKnowledgeService` answers the request environment's `knowledge` + * service, `undefined` when none is registered, and throws when one is + * registered and cannot be resolved. + */ +export async function authoredKnowledgeSourceRefusal(input: { + /** The metadata type saved, in any URL spelling the protocol accepts. */ + type: string; + /** The item as the door will hand it to the protocol. */ + item: unknown; + /** The author's execution context. */ + executionContext: unknown; + resolveKnowledgeService: () => Promise | unknown; +}): Promise { + if (canonicalMetaUrlType(input.type) !== KNOWLEDGE_SOURCE_TYPE) return undefined; + if ((input.executionContext as { isSystem?: unknown } | null | undefined)?.isSystem === true) return undefined; + let service: unknown; + try { + service = await input.resolveKnowledgeService(); + } catch (err) { + return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`); + } + const admit = (service as Partial | null | undefined)?.admitAuthoredSource; + if (typeof admit !== 'function') return undefined; + let verdict: AuthoredKnowledgeSourceVerdict; + try { + verdict = await admit.call(service, input.item, input.executionContext); + } catch (err) { + return unavailable(err instanceof Error ? err.message : String(err)); + } + if (!verdict || verdict.admitted === true) return undefined; + return { status: verdict.status, code: verdict.code, message: verdict.message }; +} diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index fae5b4840e6..8117fa15bbd 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -2228,7 +2228,7 @@ export function metaTypeReadRefusal( * each transport's `/meta` entry, before any handler resolves the protocol or * writes the store; never per document. * - * ## The row, and why the capability + * ## The rows, and why each capability * * - `datasource` → `manage_platform_settings`. The datasource family's own * write doors — `POST /api/v1/datasources`, `PATCH` and `DELETE @@ -2237,6 +2237,17 @@ export function metaTypeReadRefusal( * create, update and remove the same stored definition a `/meta` write of * this type persists, and admit only this capability. One operation reached * through two mounted doors cannot admit two different sets of callers. + * - `knowledge_source` → `manage_knowledge_sources` (ADR-0161 K4, guard one; + * ruled on #37304, Q2 = B). Saving a knowledge source sends the fields it + * lists, for every record it selects, to the embedding provider and starts + * an index build that may be billed, so authoring one is granted on its + * own: held by default by platform administrators only + * (`ADMIN_FULL_ACCESS_CAPABILITIES`), and asked BESIDE `manage_metadata`, + * which the door itself still asks. A grant on the indexed object's + * records is not read here and implies nothing. This type has no write + * door outside `/meta`, so the capability is the ruling's, and these doors + * are where it is asked: REST and the dispatcher at their `/meta` entry, + * and the MCP draft door (`mcp-authoring.ts`) with the human as the caller. * * ## Why `external_catalog` has no row here * @@ -2246,8 +2257,10 @@ export function metaTypeReadRefusal( * `FEDERATION_WRITE_CAPABILITY` (`manage_metadata`, in * `./external-datasource-routes.ts`), which every `/meta` write door already * demands. ⛔ A row here names the capability the type's own WRITE door - * requires FOR THE WRITE — matched, never minted; a type whose write door asks - * nothing beyond the authoring admission for the write has no row. + * requires FOR THE WRITE — matched, never minted here (a capability no other + * door asks enters by a maintainer's ruling, as `knowledge_source`'s did); a + * type whose write door asks nothing beyond the authoring admission for the + * write has no row. * * That door also requires `manage_platform_settings` (the 2026-11-03 ruling: * seeing a datasource's remote structure needs the read capability on every @@ -2271,6 +2284,7 @@ export function metaTypeReadRefusal( */ export const META_TYPE_WRITE_CAPABILITIES: Readonly> = Object.freeze({ datasource: 'manage_platform_settings', + knowledge_source: 'manage_knowledge_sources', }); /** The verbs {@link metaTypeWriteRefusal} judges. */ diff --git a/packages/rest/src/meta-item-write-routes.ts b/packages/rest/src/meta-item-write-routes.ts index b22c9917970..c49b6546223 100644 --- a/packages/rest/src/meta-item-write-routes.ts +++ b/packages/rest/src/meta-item-write-routes.ts @@ -88,7 +88,10 @@ import { rethrowAuthzStoreUnavailable, userTextLocalesOf } from '@objectstack/core'; // [#12702 · #20156] The `/meta` item write doors' capability predicate — see // `rest-server.ts`' import of the same name for why it is shared. -import { metaWriteCapabilityVerdict } from '@objectstack/metadata-core'; +import { + authoredKnowledgeSourceRefusal, + metaWriteCapabilityVerdict, +} from '@objectstack/metadata-core'; import type { DeleteMetaItemRequest, SaveMetaItemRequest } from '@objectstack/spec/api'; import { handleRouteError } from './error-response.js'; import type { MetaRouteScope, TransportScopedMetaRequest } from './meta-collection-routes.js'; @@ -116,6 +119,7 @@ export interface MetaItemWriteRouteHost { walledCatalogRefusal: RestServer['walledCatalogRefusal']; resolveProtocol: RestServer['resolveProtocol']; resolveMetaWriteActor: RestServer['resolveMetaWriteActor']; + resolveKnowledgeService: RestServer['resolveKnowledgeService']; } /** @@ -246,6 +250,32 @@ export function registerMetaItemWriteRoutes(this: MetaItemWriteRouteHost, scope: ? (body as any).item : body; + // [ADR-0161 K4, guard two] Source admission at save: a + // `knowledge_source` is saved only when its author may + // themselves search what it would index — the knowledge + // service's search-time gates, asked for the author before + // anything is written (`authoredKnowledgeSourceRefusal`). + // Every other type passes untouched. `403` keeps this door's + // `FORBIDDEN` spelling; a verdict that cannot be reached is + // the gate's own `503`. + { + const refused = await authoredKnowledgeSourceRefusal({ + type: req.params.type, + item, + executionContext: ctx, + resolveKnowledgeService: () => this.resolveKnowledgeService(environmentId, req), + }); + if (refused) { + res.status(refused.status).json({ + error: { + code: refused.status === 403 ? 'FORBIDDEN' : refused.code, + message: refused.message, + }, + }); + return; + } + } + // Opt-in OCC under ADR-0008 PR-10d.3: callers (Studio, // CLI) may set `If-Match` to the version token a receipt // served, to enforce that the overlay row has not advanced diff --git a/packages/rest/src/meta-type-write-capability.test.ts b/packages/rest/src/meta-type-write-capability.test.ts index 581373e3f64..5d3bdc92099 100644 --- a/packages/rest/src/meta-type-write-capability.test.ts +++ b/packages/rest/src/meta-type-write-capability.test.ts @@ -164,8 +164,12 @@ const envelope = (res: any) => ({ status: res.statusCode, code: res.body?.code ? // ── 1. The predicate ────────────────────────────────────────────────────────── describe('[#21124] metaTypeWriteRefusal — the type-level write admission', () => { - it('the one row names a declared platform capability (matched, never minted)', () => { - expect(META_TYPE_WRITE_CAPABILITIES).toEqual({ datasource: 'manage_platform_settings' }); + it('each row names a declared platform capability (matched, or a maintainer\'s ruling; never minted here)', () => { + expect(META_TYPE_WRITE_CAPABILITIES).toEqual({ + datasource: 'manage_platform_settings', + // [ADR-0161 K4, guard one] ruled on #37304 (Q2 = B). + knowledge_source: 'manage_knowledge_sources', + }); for (const capability of Object.values(META_TYPE_WRITE_CAPABILITIES)) { expect(PLATFORM_CAPABILITY_NAMES.has(capability)).toBe(true); } @@ -412,3 +416,82 @@ describe('[#21124] no principal writes a datasource through /meta that the datas expect({ status: author.statusCode, code: author.body?.error?.code }).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); }); }); + +// ── 4. `knowledge_source` → `manage_knowledge_sources` ──────────────────────────────── + +/** + * [ADR-0161 K4, guard one; ruled on #37304, Q2 = B] A knowledge source is + * written on the `/meta` surface only by a holder of `manage_knowledge_sources` + * BESIDE `manage_metadata`: saving one sends record content to an embedding + * provider, so the right to author metadata does not include it, and neither + * does a grant on the indexed object's records. Same predicate, same doors and + * same harness as the datasource batteries above. + */ +describe('[ADR-0161 K4] a knowledge_source is written through /meta only beside `manage_knowledge_sources`', () => { + const FAQ = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; + const SPELLINGS = ['knowledge_source', 'knowledge_sources', 'knowledgeSources']; + const BELOW = { + // Every authoring capability `/meta` knows: the doors' own admission admits it. + author: REFUSED.author, + // Another type's row is not this one's. + 'platform-settings': { userId: 'u_settings', systemPermissions: ['manage_metadata', 'manage_platform_settings'] }, + // Full read and write on the indexed object's records, and no capability. + 'record-grant': { userId: 'u_editor', systemPermissions: [] as string[], permissions: ['article_editor'], positions: ['editor'] }, + } as const; + const BOTH = { userId: 'u_admin', systemPermissions: ['manage_knowledge_sources', 'manage_metadata'] }; + + it('the predicate: every write verb on every spelling is refused 403 PERMISSION_DENIED naming the capability; a read verb is not judged', () => { + for (const type of SPELLINGS) { + for (const verb of ['PUT', 'POST', 'PATCH', 'DELETE']) { + const refusal = metaTypeWriteRefusal(verb, type, BELOW.author); + expect(refusal, `${verb} ${type}`).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' }); + expect(refusal?.message).toContain('`manage_knowledge_sources`'); + } + expect(metaTypeWriteRefusal('GET', type, BELOW.author)).toBeUndefined(); + expect(metaTypeWriteRefusal('PUT', type, BOTH)).toBeUndefined(); + } + // Reading a knowledge source asks nothing of its own. + expect(Object.prototype.hasOwnProperty.call(META_TYPE_READ_CAPABILITIES, 'knowledge_source')).toBe(false); + }); + + for (const spelling of SPELLINGS) { + for (const [who, ctx] of Object.entries(BELOW)) { + it(`${spelling} × ${who}: every write shape refuses 403 PERMISSION_DENIED with the store unchanged and no protocol call`, async () => { + const { rest, store, calls } = boot(ctx); + const before = clone(store); + for (const shape of writeShapes(rest)) { + const res = await drive(rest, shape.method, shape.path, spelling, 'faq', shape.query, FAQ); + expect({ shape: shape.label, ...envelope(res) }).toEqual({ shape: shape.label, status: 403, code: 'PERMISSION_DENIED' }); + expect(res.body?.error?.message ?? res.body?.message).toContain('`manage_knowledge_sources`'); + } + expect(store).toEqual(before); + expect(calls()).toBe(0); + }); + } + } + + it('a holder of both saves, publishes, rolls back and resets — each reaching the store', async () => { + const { rest, store, protocol } = boot(BOTH); + const saved = await drive(rest, 'PUT', `${META}/:type/:name`, 'knowledge_source', 'faq', {}, FAQ); + expect(saved.statusCode).toBe(200); + expect(store.knowledge_source.faq).toEqual(FAQ); + await drive(rest, 'POST', `${META}/:type/:name/publish`, 'knowledge_source', 'faq', {}, {}); + expect(protocol.publishMetaItem).toHaveBeenCalledTimes(1); + await drive(rest, 'POST', `${META}/:type/:name/rollback`, 'knowledge_source', 'faq', {}, { version: 1 }); + expect(protocol.rollbackMetaItem).toHaveBeenCalledTimes(1); + const reset = await drive(rest, 'DELETE', `${META}/:type/:name`, 'knowledge_source', 'faq', {}, {}); + expect(reset.statusCode).toBe(200); + expect(store.knowledge_source.faq).toBeUndefined(); + }); + + it('beside, never instead — the capability without `manage_metadata` is refused by the door\'s own admission', async () => { + const { rest, store, calls } = boot({ userId: 'u_half', systemPermissions: ['manage_knowledge_sources'] }); + const before = clone(store); + const res = await drive(rest, 'PUT', `${META}/:type/:name`, 'knowledge_source', 'faq', {}, FAQ); + expect(res.statusCode).toBe(403); + expect(res.body?.error?.code).toBe('FORBIDDEN'); + expect(res.body?.error?.message).toContain('manage_metadata'); + expect(store).toEqual(before); + expect(calls()).toBe(0); + }); +}); diff --git a/packages/rest/src/meta-write-door-capability-enumeration.test.ts b/packages/rest/src/meta-write-door-capability-enumeration.test.ts index ad542bfb511..024abfea01b 100644 --- a/packages/rest/src/meta-write-door-capability-enumeration.test.ts +++ b/packages/rest/src/meta-write-door-capability-enumeration.test.ts @@ -652,6 +652,96 @@ describe('ADR-0131 D6 — `manage_org_presentation` is refused, and no door thre }); }); +/** + * [ADR-0161 K4, guard two] Source admission at save: the save door asks the + * environment's knowledge service whether the AUTHOR may search what the + * source would index (`authoredKnowledgeSourceRefusal`), after its capability + * gates and before the protocol writes. + */ +describe('ADR-0161 K4 — the save door asks the knowledge service to admit the source for its author', () => { + const SAVE = DOORS.find((d) => d.protocolMethod === 'saveMetaItem')!; + const OTHER_ITEM_DOORS = DOORS.filter((d) => !['saveMetaItem', 'migrateStoredMetadata'].includes(d.protocolMethod)); + const SOURCE = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body', 'salary'] } }; + const AUTHOR = { userId: 'u_admin', systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }; + const REFUSAL = { + admitted: false, status: 403, code: 'PERMISSION_DENIED', + message: "The knowledge source 'faq' was not saved: you may not query field 'salary' of object 'article'.", + }; + const asSource = (door: Door, body: unknown = SOURCE): Door => ({ + ...door, params: { ...door.params, type: 'knowledge_source', name: 'faq' }, body, + }); + /** Boot with a `knowledge` service on the request's environment. */ + function bootWith(context: Record, admit: (item: unknown, ctx: unknown) => unknown) { + const stack = boot(context); + const admitAuthoredSource = vi.fn(async (item: unknown, ctx: unknown) => admit(item, ctx)); + (stack.rest as any).kernelServiceProvider = async (name: string) => (name === 'knowledge' ? { admitAuthoredSource } : undefined); + return { ...stack, admitAuthoredSource }; + } + + it('a source its author may not search is refused 403 FORBIDDEN with the gate\'s sentence, and nothing is saved', async () => { + const stack = bootWith(AUTHOR, () => REFUSAL); + const out = await stack.knock(asSource(SAVE)); + expect(out.status).toBe(403); + expect(out.body).toEqual({ error: { code: 'FORBIDDEN', message: REFUSAL.message } }); + expect(stack.calls.saveMetaItem).toBe(0); + // Asked with the item the door would save and the author's own context. + expect(stack.admitAuthoredSource).toHaveBeenCalledWith(SOURCE, AUTHOR); + }); + + it('the item is judged unwrapped: an `{ item }` or `{ metadata }` envelope is the same save', async () => { + for (const body of [{ item: SOURCE }, { metadata: SOURCE }]) { + const stack = bootWith(AUTHOR, () => REFUSAL); + const out = await stack.knock(asSource(SAVE, body)); + expect(out.status).toBe(403); + expect(stack.admitAuthoredSource).toHaveBeenCalledWith(SOURCE, AUTHOR); + expect(stack.calls.saveMetaItem).toBe(0); + } + }); + + it('fails closed: a verdict that throws is 503 SERVICE_UNAVAILABLE, and nothing is saved', async () => { + const stack = bootWith(AUTHOR, () => { throw new Error('registry unavailable'); }); + const out = await stack.knock(asSource(SAVE)); + expect(out.status).toBe(503); + expect(out.body).toMatchObject({ error: { code: 'SERVICE_UNAVAILABLE' } }); + expect(stack.calls.saveMetaItem).toBe(0); + }); + + it('CONTROL: an admitted source is saved; with no knowledge service the save goes on', async () => { + const admitted = bootWith(AUTHOR, () => ({ admitted: true })); + expect((await admitted.knock(asSource(SAVE))).status).not.toBe(403); + expect(admitted.calls.saveMetaItem).toBe(1); + + const none = boot(AUTHOR); + expect((await none.knock(asSource(SAVE))).status).not.toBe(403); + expect(none.calls.saveMetaItem).toBe(1); + }); + + it('the gate is behind the capability gates, and is not asked for another type', async () => { + // `manage_metadata` without `manage_knowledge_sources`, and the reverse. + for (const systemPermissions of [['manage_metadata'], ['manage_knowledge_sources']]) { + const uncapable = bootWith({ userId: 'u_half', systemPermissions }, () => REFUSAL); + expect((await uncapable.knock(asSource(SAVE))).status).toBe(403); + expect(uncapable.admitAuthoredSource).not.toHaveBeenCalled(); + expect(uncapable.calls.saveMetaItem).toBe(0); + } + + const object = bootWith(AUTHOR, () => REFUSAL); + await object.knock(SAVE); // the table's own params: type 'object' + expect(object.admitAuthoredSource).not.toHaveBeenCalled(); + expect(object.calls.saveMetaItem).toBe(1); + }); + + it.each(OTHER_ITEM_DOORS.map((d) => [d.label, d] as const))( + '%s → writes no new item body, so it does not ask', + async (_label, door) => { + const stack = bootWith(AUTHOR, () => REFUSAL); + await stack.knock(asSource(door, door.body)); + expect(stack.admitAuthoredSource).not.toHaveBeenCalled(); + expect(stack.calls[door.protocolMethod]).toBe(1); + }, + ); +}); + /** * [#30675] The data doors' own refusal cases. Booted with NO data engine, so a * caller the gate admits gets `501 NOT_IMPLEMENTED` — the answer that tells the diff --git a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts index 84b3f2c9f79..3aad3e6a1c0 100644 --- a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts +++ b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts @@ -141,7 +141,8 @@ const requestFrom = (fn: any) => fn.mock.calls[0][0]; // [#21124] `manage_platform_settings` too: these suites iterate every registered type, and a // `datasource` write is admitted only with it (`metaTypeWriteRefusal`, the type-level write admission). -const AUTHORIZED = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings'], tenantId: ORG }; +// [ADR-0161 K4] `manage_knowledge_sources` for the same reason: a `knowledge_source` write asks it. +const AUTHORIZED = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings', 'manage_knowledge_sources'], tenantId: ORG }; async function writeWith(type: string) { const b = boot(AUTHORIZED); diff --git a/packages/rest/src/rest-server-meta-write-org-scope.test.ts b/packages/rest/src/rest-server-meta-write-org-scope.test.ts index 826e9b166fc..de6775fa0c2 100644 --- a/packages/rest/src/rest-server-meta-write-org-scope.test.ts +++ b/packages/rest/src/rest-server-meta-write-org-scope.test.ts @@ -114,8 +114,9 @@ const requestFrom = (fn: any) => fn.mock.calls[0][0]; // [#21124] `manage_platform_settings` too: these suites iterate every registered type, and a // `datasource` write is admitted only with it (`metaTypeWriteRefusal`, the type-level write admission). -const AUTHORIZED = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings'], tenantId: ORG }; -const AUTHORIZED_NO_ORG = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings'] }; +// [ADR-0161 K4] `manage_knowledge_sources` for the same reason: a `knowledge_source` write asks it. +const AUTHORIZED = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings', 'manage_knowledge_sources'], tenantId: ORG }; +const AUTHORIZED_NO_ORG = { userId: 'u1', systemPermissions: ['manage_metadata', 'manage_platform_settings', 'manage_knowledge_sources'] }; /** Drive one write door with the given type + execution context. */ async function writeWith(type: string, execCtx: any) { diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 7bdd6cdd687..32c64ab070a 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -102,6 +102,9 @@ import { // read folds the reason into — and [#22639] the list views the read gate // withheld — read only by the item read and its intake-reason helper, moved with // them to `meta-item-read-routes.ts` (#23050 slice 13b). + // [ADR-0161 K4, guard two] The service name the save door's source admission + // resolves (`resolveKnowledgeService`). + KNOWLEDGE_SOURCE_ADMISSION_SERVICE, } from '@objectstack/metadata-core'; import { RouteManager, type RouteEntry } from './route-manager.js'; import { presentedForwardCredential, redeemForwardCredential } from './forward-credential.js'; @@ -5771,6 +5774,7 @@ export class RestServer { walledCatalogRefusal: (...a) => this.walledCatalogRefusal(...a), resolveProtocol: (...a) => this.resolveProtocol(...a), resolveMetaWriteActor: (...a) => this.resolveMetaWriteActor(...a), + resolveKnowledgeService: (...a) => this.resolveKnowledgeService(...a), }; registerMetaItemWriteRoutes.call(itemWriteHost, scope); @@ -6206,6 +6210,30 @@ export class RestServer { } } + /** + * [ADR-0161 K4, guard two] The request environment's `knowledge` service, + * for the save door's source admission (`authoredKnowledgeSourceRefusal`): + * `undefined` when none is registered (nothing loads a knowledge source + * there), a throw when one is registered and cannot be resolved (the door + * then refuses `503`, never proceeds). `unknown`, deliberately: the door + * reads the one member it asks structurally. + */ + private async resolveKnowledgeService( + environmentId?: string, + req?: any, + ): Promise { + if (!this.kernelServiceProvider) return undefined; + try { + return await this.kernelServiceProvider( + KNOWLEDGE_SOURCE_ADMISSION_SERVICE, + await this.resolveRequestEnvironmentId(environmentId, req), + ); + } catch (err) { + if (isServiceNotRegisteredError(err)) return undefined; + throw err; + } + } + /** * [#30955] Resolve the environment's `audit` service — the compliance * ledger's writers, which plugin-audit registers on the kernel that holds diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index cbddf3ef466..7912eee2880 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -195,6 +195,8 @@ async function serve( tenancy?: { posture: string }; /** [#36856] The automation service the door resolves for a flow's switch. */ automation?: unknown; + /** [ADR-0161 K4] The knowledge service the save asks to admit a source for its author. */ + knowledge?: unknown; } = {}, ): Promise { const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); @@ -219,6 +221,7 @@ async function serve( automationAsks.push(scopeId); return opts.automation; } + if (name === 'knowledge') return opts.knowledge; return name === 'mcp' ? mcp : name === 'protocol' ? protocol : name === 'security' ? security : undefined; }, resolveServiceOrLoud: async (_ctx: unknown, name: string) => (name === 'tenancy' ? opts.tenancy : undefined), @@ -941,6 +944,102 @@ describe('save_metadata_draft saves a draft and answers with its publish verdict }); }); +/** + * [ADR-0161 K4, guard one; ruled on #37304, Q2 = B] The draft door asks the + * `/meta` type-level write admission (`metaTypeWriteRefusal`: a + * `knowledge_source` needs `manage_knowledge_sources` beside + * `manage_metadata`) with the HUMAN as the caller. + */ +describe('[ADR-0161 K4] a knowledge_source draft needs the human to hold manage_knowledge_sources too', () => { + const SOURCE = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; + const save = (authoring: OpenAuthoringInjection, type = 'knowledge_source') => + call(authoring, 'save_metadata_draft', { type, name: 'faq', item: SOURCE, package: 'com.acme.crm' }); + const discard = (authoring: OpenAuthoringInjection, type = 'knowledge_source') => + call(authoring, 'delete_metadata_draft', { type, name: 'faq', package: 'com.acme.crm' }); + + it('a human holding manage_metadata without it is refused 403 PERMISSION_DENIED on the save and the discard, naming the capability, before anything is written', async () => { + const { authoring, served } = await authorThroughDomain({ systemPermissions: ['manage_metadata'] }); + for (const type of ['knowledge_source', 'knowledge_sources']) { + const refused = await save(authoring, type); + expect(refused.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(refused.body.error.message, type).toBe('Writing knowledge_source metadata requires the `manage_knowledge_sources` capability.'); + const discarded = await discard(authoring, type); + expect(discarded.body.error, type).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(discarded.body.error.message, type).toContain('`manage_knowledge_sources`'); + } + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem' || c[0] === 'deleteMetaItem')).toEqual([]); + }); + + it("the grant read is the human's: an envelope that carries the capability does not stand in for a human who lacks it", async () => { + // The request envelope is handed carrying both capabilities; the human's + // own permission set, read by the door, carries `manage_metadata` only. + const resolved = await oauthEnvelope(['metadata:write'], ['manage_metadata']); + const envelope = { ...(resolved as object), systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }; + const served = await serve(envelope, { systemPermissions: ['manage_metadata'] }); + const refused = await save(served.authoring!); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403, message: expect.stringContaining('manage_knowledge_sources') }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('CONTROL: a human holding both saves and discards; the same human still saves another type', async () => { + const { authoring, served } = await authorThroughDomain({ systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }); + expect((await save(authoring)).isError).toBe(false); + expect((await discard(authoring)).body).toEqual({ discarded: { type: 'knowledge_source', name: 'faq', package: 'com.acme.crm' } }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem').map((c: any) => c[1].type)).toEqual(['knowledge_source']); + + const author = await authorThroughDomain({ systemPermissions: ['manage_metadata'] }); + const flow = await call(author.authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' }); + expect(flow.isError).toBe(false); + }); +}); + +/** + * [ADR-0161 K4, guard two] The draft save asks the environment's knowledge + * service whether the HUMAN may search what the source would index. + */ +describe('[ADR-0161 K4] save_metadata_draft asks the knowledge service to admit a source for the human', () => { + const SOURCE = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body', 'salary'] } }; + const BOTH = ['manage_metadata', 'manage_knowledge_sources']; + const REFUSAL = { + admitted: false, status: 403, code: 'PERMISSION_DENIED', + message: "The knowledge source 'faq' was not saved: you may not query field 'salary' of object 'article'.", + }; + const save = (authoring: OpenAuthoringInjection, type = 'knowledge_source', item: unknown = SOURCE) => + call(authoring, 'save_metadata_draft', { type, name: 'faq', item, package: 'com.acme.crm' }); + + it('a source the human may not search is refused 403 PERMISSION_DENIED with the gate\'s sentence, before anything is written', async () => { + const admitAuthoredSource = vi.fn(async () => REFUSAL); + const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { admitAuthoredSource } }); + const refused = await save(authoring); + expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403, message: REFUSAL.message }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + // Judged for the admitted human: their id and grants, never a system identity. + const [item, caller] = admitAuthoredSource.mock.calls[0] as unknown as [unknown, any]; + expect(item).toEqual(SOURCE); + expect(caller).toMatchObject({ userId: 'u1', isSystem: false, systemPermissions: BOTH }); + }); + + it('fails closed: a verdict that throws is 503 SERVICE_UNAVAILABLE, and nothing is written', async () => { + const knowledge = { admitAuthoredSource: async () => { throw new Error('registry unavailable'); } }; + const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge }); + const refused = await save(authoring); + expect(refused.body.error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + + it('CONTROL: an admitted source is saved; another type is never asked about; no knowledge service judges nothing', async () => { + const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); + const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { admitAuthoredSource } }); + expect((await save(authoring)).isError).toBe(false); + expect((await call(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' })).isError).toBe(false); + expect(admitAuthoredSource).toHaveBeenCalledTimes(1); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem').map((c: any) => c[1].type)).toEqual(['knowledge_source', 'flow']); + + const none = await authorThroughDomain({ systemPermissions: BOTH }); + expect((await save(none.authoring)).isError).toBe(false); + }); +}); + /** [#34774] `clientSpecVersion` on the save (#34659 ruling D4 = A). */ describe('[#34774] save_metadata_draft judges the client\'s declared spec version', () => { const SERVER = (createRequire(import.meta.url)('@objectstack/spec/package.json') as { version: string }).version; diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index d1ed5192dcd..17b77e42e9f 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -149,7 +149,12 @@ import { createRequire } from 'node:module'; import { resolveUserAuthzGrants, userTextLocalesOf } from '@objectstack/core'; -import { metaWriteCapabilityVerdict, walledCatalogWriteVerdict } from '@objectstack/metadata-core'; +import { + KNOWLEDGE_SOURCE_ADMISSION_SERVICE, + authoredKnowledgeSourceRefusal, + metaWriteCapabilityVerdict, + walledCatalogWriteVerdict, +} from '@objectstack/metadata-core'; import { createMetaItemReadGate, createMetaListReadGate, @@ -405,6 +410,13 @@ export interface OpenAuthoringWriter { userTextLocales: string[]; /** The walled refusal for a write of `type` (`walledCatalogWriteVerdict`). */ writeVerdict(type: string): Promise<{ allowed: true } | { allowed: false; code: ErrorCode; message: string; status: number }>; + /** + * [ADR-0161 K4, guard two] The refusal of a `knowledge_source` save whose + * author may not themselves search what it would index + * (`authoredKnowledgeSourceRefusal`, judged for the admitted human), or + * `undefined` when the save may go on. Every other type answers `undefined`. + */ + itemSaveRefusal(type: string, item: unknown): Promise<{ code: ErrorCode; message: string; status: number } | undefined>; } /** @@ -487,7 +499,7 @@ export async function resolveOpenAuthoringInjection( return undefined; } }, - ...(reader ? { readGate: openReadGateSources(deps, context, reader), writer: openWriter(deps, context, clientId) } : {}), + ...(reader ? { readGate: openReadGateSources(deps, context, reader), writer: openWriter(deps, context, clientId, reader) } : {}), logger: deps.logger, }), principal: { @@ -555,8 +567,17 @@ async function resolveHumanReader( * transport reads; a posture that cannot be read refuses the write `503`, * never a permit. The caller's posture rung is the request envelope's, as the * `/meta` doors and the MCP `import_object` tool read it. + * + * [ADR-0161 K4, guard two] `itemSaveRefusal` judges a `knowledge_source` save + * for the admitted HUMAN (`reader`, the caller `resolveHumanReader` admitted): + * their grants, never the request envelope's. */ -function openWriter(deps: DomainHandlerDeps, context: HttpProtocolContext, clientId: string | undefined): OpenAuthoringWriter { +function openWriter( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + clientId: string | undefined, + reader: MetaReadGateCaller, +): OpenAuthoringWriter { const ec: any = context.executionContext; return { ...(clientId ? { clientId } : {}), @@ -576,6 +597,21 @@ function openWriter(deps: DomainHandlerDeps, context: HttpProtocolContext, clien const walled = walledCatalogWriteVerdict({ type, tenancyPosture, isSystem: ec?.isSystem === true, callerPosture: ec?.posture }); return walled.allowed ? { allowed: true } : { allowed: false, code: PERMISSION_DENIED, message: walled.message, status: 403 }; }, + async itemSaveRefusal(type, item) { + const refused = await authoredKnowledgeSourceRefusal({ + type, + item, + // The human the door admitted: their grants, never the envelope's. + executionContext: reader, + resolveKnowledgeService: () => deps.resolveService(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), + }); + if (!refused) return undefined; + return { + code: refused.status === 403 ? PERMISSION_DENIED : SERVICE_UNAVAILABLE, + message: refused.message, + status: refused.status, + }; + }, }; } @@ -821,6 +857,9 @@ export function createOpenAuthoringRegistry(opts: { if (typeWriteRefused) return refuse(typeWriteRefused.code, typeWriteRefused.message, typeWriteRefused.status); const walled = await writer.writeVerdict(type); if (!walled.allowed) return refuse(walled.code, walled.message, walled.status); + // [ADR-0161 K4, guard two] Source admission at save, for the human. + const itemRefused = await writer.itemSaveRefusal(type, item); + if (itemRefused) return refuse(itemRefused.code, itemRefused.message, itemRefused.status); // Built field by field: `item` is data, never a channel, so no // `force`, `mode` or `writeFace` rides in through it. const saved = await protocol.saveMetaItem({ diff --git a/packages/runtime/src/domains/meta-save-capability-gate.test.ts b/packages/runtime/src/domains/meta-save-capability-gate.test.ts index 0c158d55e44..eb280bb5975 100644 --- a/packages/runtime/src/domains/meta-save-capability-gate.test.ts +++ b/packages/runtime/src/domains/meta-save-capability-gate.test.ts @@ -272,6 +272,72 @@ describe('#7019 — dispatcher PUT /meta/:type/:name: the capability gate', () = * caller without `manage_metadata`; a `manage_metadata` caller's write carries * no organization whatever its active one. */ +/** + * [ADR-0161 K4, guard two] The dispatcher's twin of the REST pins: the save + * asks the environment's knowledge service whether the AUTHOR may search what + * the source would index (`authoredKnowledgeSourceRefusal`). + */ +describe('ADR-0161 K4 — dispatcher PUT asks the knowledge service to admit the source for its author', () => { + const SOURCE = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body', 'salary'] } }; + const AUTHOR = { userId: 'u_admin', systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] }; + const REFUSAL = { + admitted: false, status: 403, code: 'PERMISSION_DENIED', + message: "The knowledge source 'faq' was not saved: you may not query field 'salary' of object 'article'.", + }; + + function bootWith(admit?: (item: unknown, ctx: unknown) => unknown) { + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + const admitAuthoredSource = vi.fn(async (item: unknown, ctx: unknown) => admit!(item, ctx)); + const services: Record = { protocol: { saveMetaItem }, ...(admit ? { knowledge: { admitAuthoredSource } } : {}) }; + const kernel = { context: { getService: (n: string) => services[n] ?? null } } as any; + return { dispatcher: new HttpDispatcher(kernel), saveMetaItem, admitAuthoredSource }; + } + const put = (stack: ReturnType, executionContext: any, path = '/knowledge_source/faq', body: unknown = copy(SOURCE)) => + stack.dispatcher.handleMetadata(path, ctx(executionContext), 'PUT', body); + + it('a source its author may not search is refused 403 PERMISSION_DENIED with the gate\'s sentence, and nothing is saved', async () => { + const stack = bootWith(() => REFUSAL); + const res = await put(stack, AUTHOR); + expect(res.response?.status).toBe(403); + expect(res.response?.body?.error?.code).toBe('PERMISSION_DENIED'); + expect(res.response?.body?.error?.message).toBe(REFUSAL.message); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + expect(stack.admitAuthoredSource).toHaveBeenCalledWith(SOURCE, AUTHOR); + }); + + it('fails closed: a verdict that throws is 503 SERVICE_UNAVAILABLE, and nothing is saved', async () => { + const stack = bootWith(() => { throw new Error('registry unavailable'); }); + const res = await put(stack, AUTHOR); + expect(res.response?.status).toBe(503); + expect(res.response?.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + }); + + it('CONTROL: an admitted source is saved; with no knowledge service the save goes on', async () => { + const admitted = bootWith(() => ({ admitted: true })); + expect((await put(admitted, AUTHOR)).response?.status).toBe(200); + expect(admitted.saveMetaItem).toHaveBeenCalledTimes(1); + + const none = bootWith(); + expect((await put(none, AUTHOR)).response?.status).toBe(200); + expect(none.saveMetaItem).toHaveBeenCalledTimes(1); + }); + + it('the gate is behind the capability gates, and is not asked for another type', async () => { + // `manage_metadata` without `manage_knowledge_sources`, and the reverse. + for (const systemPermissions of [['manage_metadata'], ['manage_knowledge_sources']]) { + const uncapable = bootWith(() => REFUSAL); + expect((await put(uncapable, { userId: 'u_half', systemPermissions })).response?.status).toBe(403); + expect(uncapable.admitAuthoredSource).not.toHaveBeenCalled(); + expect(uncapable.saveMetaItem).not.toHaveBeenCalled(); + } + + const object = bootWith(() => REFUSAL); + expect((await put(object, AUTHOR, '/object/account', { name: 'account', label: 'Account', fields: {} })).response?.status).toBe(200); + expect(object.admitAuthoredSource).not.toHaveBeenCalled(); + }); +}); + describe('ADR-0131 D6 — dispatcher PUT: an organization admin\'s metadata write is refused; writes carry no organization', () => { /** * The `boot()` double above, plus an auth service whose session carries an diff --git a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts index a534cedd866..29688c64af6 100644 --- a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts +++ b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts @@ -33,6 +33,12 @@ const CALLERS = { member: { userId: 'u_member', isSystem: false, systemPermissions: [] as string[] }, author: { userId: 'u_author', isSystem: false, systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'] }, holder: { userId: 'u_settings', isSystem: false, systemPermissions: ['manage_platform_settings', 'manage_metadata'] }, + // [ADR-0161 K4] The knowledge-source rows: full access to the indexed + // object's records and no capability; the capability without + // `manage_metadata`; and both. + 'record-grant': { userId: 'u_editor', isSystem: false, systemPermissions: [] as string[], permissions: ['article_editor'], positions: ['editor'] }, + 'knowledge-only': { userId: 'u_half', isSystem: false, systemPermissions: ['manage_knowledge_sources'] }, + 'knowledge-author': { userId: 'u_admin', isSystem: false, systemPermissions: ['manage_knowledge_sources', 'manage_metadata'] }, } as const; type CallerName = keyof typeof CALLERS; @@ -162,3 +168,59 @@ describe('[#21124] both transports refuse a datasource write below the capabilit expect(disp.store.view.all_leads.label).toBe('Leads (edited)'); }); }); + +/** + * [ADR-0161 K4, guard one; ruled on #37304, Q2 = B] The same parity for the + * table's second row: a `knowledge_source` is written through either transport + * only beside `manage_knowledge_sources`. The MCP draft door asks the same + * predicate with the human as the caller (`mcp-authoring.test.ts`). + */ +describe('[ADR-0161 K4] both transports refuse a knowledge_source write below `manage_knowledge_sources`, alike, writing nothing', () => { + const FAQ = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; + + for (const spelling of ['knowledge_source', 'knowledge_sources', 'knowledgeSources']) { + for (const who of ['author', 'holder', 'record-grant'] as const) { + it(`PUT /meta/${spelling}/faq × ${who}`, async () => { + const rest = bootRest(who); + const disp = bootDispatcher(who); + const restBefore = clone(rest.store); + const dispBefore = clone(disp.store); + const viaRest = await rest.send('PUT', `/meta/${spelling}/faq`, FAQ); + const viaDispatcher = await disp.send('PUT', `/meta/${spelling}/faq`, FAQ); + expect(viaRest).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(viaDispatcher).toEqual(viaRest); + expect(rest.store).toEqual(restBefore); + expect(disp.store).toEqual(dispBefore); + expect(rest.calls()).toBe(0); + expect(disp.calls()).toBe(0); + }); + } + } + + it.each(['POST', 'PATCH', 'DELETE'])('dispatcher: %s on a knowledge_source path is judged at the entry — 403 with no store call', async (verb) => { + for (const path of ['/meta/knowledge_source', '/meta/knowledge_sources', '/meta/knowledge_source/faq']) { + const disp = bootDispatcher('author'); + const answer = await disp.send(verb, path, {}); + expect({ path, ...answer }).toEqual({ path, status: 403, code: 'PERMISSION_DENIED' }); + expect(disp.calls()).toBe(0); + } + }); + + it('beside, never instead — the capability without `manage_metadata` writes nothing through either transport', async () => { + const rest = bootRest('knowledge-only'); + const disp = bootDispatcher('knowledge-only'); + expect((await rest.send('PUT', '/meta/knowledge_source/faq', FAQ)).status).toBe(403); + expect((await disp.send('PUT', '/meta/knowledge_source/faq', FAQ)).status).toBe(403); + expect(rest.store.knowledge_source).toBeUndefined(); + expect(disp.store.knowledge_source).toBeUndefined(); + }); + + it('a holder of both writes through both transports', async () => { + const rest = bootRest('knowledge-author'); + const disp = bootDispatcher('knowledge-author'); + expect((await rest.send('PUT', '/meta/knowledge_source/faq', FAQ)).status).toBe(200); + expect((await disp.send('PUT', '/meta/knowledge_source/faq', FAQ)).status).toBe(200); + expect(rest.store.knowledge_source.faq).toEqual(FAQ); + expect(disp.store.knowledge_source.faq).toEqual(FAQ); + }); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 10da6116133..f97b71fd185 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -33,6 +33,8 @@ import { // `manage_metadata` (or `isSystem`), the one predicate the REST doors run // too. No `/meta` branch here carries an organization into a metadata // write or read: the per-organization overlay axis is retired. + KNOWLEDGE_SOURCE_ADMISSION_SERVICE, + authoredKnowledgeSourceRefusal, metaWriteCapabilityVerdict, // [ADR-0131 D3 · D12 items 7–8] …and, under a wall, the platform operator // alone: the walled refusal every environment-metadata write door asks. @@ -1979,6 +1981,26 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin // means was the actual defect; one answer, from one authority. const item = body ?? {}; + // [ADR-0161 K4, guard two] Source admission at save: a + // `knowledge_source` is saved only when its author may themselves + // search what it would index — the knowledge service's search-time + // gates, asked for the author before anything is written + // (`authoredKnowledgeSourceRefusal`, the predicate `RestServer`'s + // `PUT` and the MCP draft save ask). Every other type passes + // untouched. + { + const refused = await authoredKnowledgeSourceRefusal({ + type, + item, + executionContext: _context.executionContext, + resolveKnowledgeService: () => + deps.resolveService(_context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, _context.environmentId), + }); + if (refused) { + return { handled: true, response: deps.error(refused.message, refused.status) }; + } + } + // Try to get the protocol service directly const protocol = await resolveProtocol(deps, _context); diff --git a/packages/runtime/src/meta-write-org-scope.test.ts b/packages/runtime/src/meta-write-org-scope.test.ts index 4db7a849884..4b901cc6cad 100644 --- a/packages/runtime/src/meta-write-org-scope.test.ts +++ b/packages/runtime/src/meta-write-org-scope.test.ts @@ -298,9 +298,11 @@ const ctx = (activeOrganizationId?: string): any => ({ // [#21124] `manage_platform_settings` too: the URL-contract case below drives // every registered type, and a `datasource` write is admitted only with it // (`metaTypeWriteRefusal`, the type-level write admission). + // [ADR-0161 K4] `manage_knowledge_sources` for the same reason: a + // `knowledge_source` write asks it. executionContext: { userId: 'usr_1', - systemPermissions: ['manage_metadata', 'manage_platform_settings'], + systemPermissions: ['manage_metadata', 'manage_platform_settings', 'manage_knowledge_sources'], ...(activeOrganizationId ? { tenantId: activeOrganizationId } : {}), }, }); From 9c796bbf07af82c19ad6170cf97258987df13ed7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:11:10 +0000 Subject: [PATCH 05/29] feat(service-knowledge): dropSource in the three adapters, source name as the index key knowledge-memory, knowledge-pgvector and knowledge-turso remove every generation of a source, the one under construction included, and what they recorded about the index. An adapter reads the index key from ctx.source.name. os knowledge status prints the holding package and no source kind. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../src/commands/knowledge/knowledge.test.ts | 9 +- .../cli/src/commands/knowledge/rebuild.ts | 2 +- packages/cli/src/commands/knowledge/status.ts | 5 +- packages/cli/src/utils/knowledge-actions.ts | 4 +- .../utils/namespace-co-owner-names.test.ts | 3 + packages/mcp/src/mcp-knowledge-tools.test.ts | 6 +- packages/plugins/knowledge-memory/README.md | 12 +- .../src/__tests__/contract.test.ts | 1 + .../src/__tests__/memory-adapter.test.ts | 4 +- .../plugins/knowledge-memory/src/index.ts | 34 +++-- packages/plugins/knowledge-pgvector/README.md | 10 +- .../acceptance.live-postgres.test.ts | 46 +++--- .../src/__tests__/builder-lock.test.ts | 2 +- .../__tests__/contract.live-postgres.test.ts | 1 + .../generations.live-postgres.test.ts | 52 +++---- .../src/__tests__/not-ready.test.ts | 2 +- .../reindex-real-driver.live-postgres.test.ts | 8 +- .../src/pgvector-adapter.ts | 61 +++++--- packages/plugins/knowledge-turso/README.md | 8 +- .../src/__tests__/acceptance.test.ts | 66 ++++----- .../src/__tests__/contract.test.ts | 1 + .../src/__tests__/plugin.test.ts | 2 +- packages/plugins/knowledge-turso/src/sql.ts | 7 +- .../knowledge-turso/src/turso-adapter.ts | 101 ++++++++----- packages/services/service-knowledge/README.md | 29 ++++ .../knowledge-source-admission.test.ts | 95 ++++++++++++ .../src/knowledge-service.ts | 136 ++++++++++++++++-- 27 files changed, 522 insertions(+), 185 deletions(-) diff --git a/packages/cli/src/commands/knowledge/knowledge.test.ts b/packages/cli/src/commands/knowledge/knowledge.test.ts index 409bbf3e84d..fc9424a1fce 100644 --- a/packages/cli/src/commands/knowledge/knowledge.test.ts +++ b/packages/cli/src/commands/knowledge/knowledge.test.ts @@ -97,7 +97,7 @@ const running = (discovered: number) => ({ const statusOf = (build: unknown) => ok({ ok: true, message: '1 source(s)', - details: { sources: [{ id: 'kb', label: 'KB', adapter: 'pgvector', kind: 'object', index: { state: 'current', due: false, detail: 'current.' }, build }] }, + details: { sources: [{ id: 'kb', label: 'KB', adapter: 'pgvector', index: { state: 'current', due: false, detail: 'current.' }, build }] }, }); const target = ['--url', SERVER, '--token', 'tok']; @@ -170,7 +170,9 @@ describe('os knowledge status', () => { ok: true, details: { sources: [ - { id: 'kb', label: 'KB', adapter: 'pgvector', kind: 'object', index: { state: 'nothing', due: true, detail: 'never built.' }, build: null }, + { id: 'kb', label: 'KB', adapter: 'pgvector', index: { state: 'nothing', due: true, detail: 'never built.' }, build: null }, + // A package's source is listed under its NAMESPACE-NAME, with the package that holds it. + { id: 'crm-faq', label: 'FAQ', adapter: 'turso', packageId: 'com.acme.crm', index: { state: 'current', due: false }, build: null }, ], }, }), @@ -178,7 +180,8 @@ describe('os knowledge status', () => { expect(run.failure).toBeUndefined(); expect(run.requests[0]).toMatchObject({ url: `${SERVER}/api/settings/knowledge/index_status`, body: {} }); const text = run.logs.join('\n'); - expect(text).toContain('kb (KB; adapter pgvector, object source)'); + expect(text).toContain('kb (KB; adapter pgvector)'); + expect(text).toContain('crm-faq (FAQ; adapter turso, package com.acme.crm)'); expect(text).toContain('index: nothing — a build is due — never built.'); expect(text).toContain('last build on this node: none'); }); diff --git a/packages/cli/src/commands/knowledge/rebuild.ts b/packages/cli/src/commands/knowledge/rebuild.ts index 4d3e99def2b..c12ef1d5058 100644 --- a/packages/cli/src/commands/knowledge/rebuild.ts +++ b/packages/cli/src/commands/knowledge/rebuild.ts @@ -37,7 +37,7 @@ export default class KnowledgeRebuild extends Command { ]; static override args = { - source: Args.string({ description: 'The knowledge source id', required: true }), + source: Args.string({ description: 'The knowledge source, by the name `os knowledge status` lists it under (NAMESPACE-NAME for a package\'s source)', required: true }), }; static override flags = { diff --git a/packages/cli/src/commands/knowledge/status.ts b/packages/cli/src/commands/knowledge/status.ts index ae853ab4f01..dd9eac7d0a5 100644 --- a/packages/cli/src/commands/knowledge/status.ts +++ b/packages/cli/src/commands/knowledge/status.ts @@ -28,7 +28,7 @@ export default class KnowledgeStatus extends Command { ]; static override args = { - source: Args.string({ description: 'The knowledge source id; every source when omitted', required: false }), + source: Args.string({ description: 'The knowledge source, by the name this command lists it under (NAMESPACE-NAME for a package\'s source); every source when omitted', required: false }), }; static override flags = { @@ -50,7 +50,8 @@ export default class KnowledgeStatus extends Command { return; } for (const source of sources) { - this.log(`${source.id} (${source.label ?? source.id}; adapter ${source.adapter ?? '?'}, ${source.kind ?? '?'} source)`); + const held = source.packageId ? `, package ${source.packageId}` : ''; + this.log(`${source.id} (${source.label ?? source.id}; adapter ${source.adapter ?? '?'}${held})`); const index = source.index; this.log(` index: ${index?.state ?? 'unknown'}${index?.due ? ' — a build is due' : ''}${index?.detail ? ` — ${index.detail}` : ''}`); this.log(` last build on this node: ${source.build ? describeBuild(source.build) : 'none'}`); diff --git a/packages/cli/src/utils/knowledge-actions.ts b/packages/cli/src/utils/knowledge-actions.ts index c77eb5c02f7..3d2e07d6c3f 100644 --- a/packages/cli/src/utils/knowledge-actions.ts +++ b/packages/cli/src/utils/knowledge-actions.ts @@ -50,10 +50,12 @@ export interface KnowledgeBuildView { /** One source of an `index_status` answer. */ export interface KnowledgeSourceView { + /** The source as `search_knowledge` lists it: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ id: string; label?: string; adapter?: string; - kind?: string; + /** The package that holds the source; absent for a source no package holds. */ + packageId?: string; index?: { state?: string; due?: boolean; detail?: string }; build?: KnowledgeBuildView | null; } diff --git a/packages/cli/src/utils/namespace-co-owner-names.test.ts b/packages/cli/src/utils/namespace-co-owner-names.test.ts index cab86e19755..dd09cbefa64 100644 --- a/packages/cli/src/utils/namespace-co-owner-names.test.ts +++ b/packages/cli/src/utils/namespace-co-owner-names.test.ts @@ -38,6 +38,7 @@ const COLLECTION: Record = { analytics_cube: 'analyticsCubes', tool: 'tools', ai_context: 'aiContexts', + knowledge_source: 'knowledgeSources', }; /** @@ -68,6 +69,8 @@ const item = (type: NamespaceUniqueType, name: string): Record return { name, label: name, description: 'A tool', parameters: {} }; case 'ai_context': return { name, label: name, object: 'crm_account' }; + case 'knowledge_source': + return { name, label: name, adapter: 'memory', source: { kind: 'object', object: 'crm_account', content: ['name'] } }; default: return { name, label: name }; } diff --git a/packages/mcp/src/mcp-knowledge-tools.test.ts b/packages/mcp/src/mcp-knowledge-tools.test.ts index 59eef1f3ccf..544868c418a 100644 --- a/packages/mcp/src/mcp-knowledge-tools.test.ts +++ b/packages/mcp/src/mcp-knowledge-tools.test.ts @@ -258,16 +258,16 @@ describe('[ADR-0161 K9] search_knowledge over the real definition — every tran { id: 'c3', body: 'travel', policy: 'P_travel' }, ]; const SOURCE: KnowledgeSource = { - id: 'clauses', + name: 'clauses', label: 'Clauses', adapter: 'memory', - source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy'] } as ObjectKnowledgeSource, + source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: ['policy'] } as ObjectKnowledgeSource, }; function indexHit(row: Row, n: number, score: number): KnowledgeHit { const doc = recordToDocument(SOURCE, SOURCE.source as ObjectKnowledgeSource, row); return { - chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: SOURCE.id, sourceRecordId: row.id, + chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: SOURCE.name, sourceRecordId: row.id, score, snippet: `${row.body as string} (${n})`, metadata: doc.metadata, docHash: doc.docHash, }; } diff --git a/packages/plugins/knowledge-memory/README.md b/packages/plugins/knowledge-memory/README.md index b7015077512..777f3199de9 100644 --- a/packages/plugins/knowledge-memory/README.md +++ b/packages/plugins/knowledge-memory/README.md @@ -11,12 +11,20 @@ import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; const kernel = new ObjectKernel(); kernel.use(new KnowledgeServicePlugin({ - sources: [{ id: 'task_notes', label: 'Notes', adapter: 'memory', - source: { kind: 'object', object: 'task', contentFields: ['notes'] }}], + sources: [{ name: 'task_notes', label: 'Notes', adapter: 'memory', + source: { kind: 'object', object: 'task', content: ['notes'] }}], })); kernel.use(new KnowledgeMemoryPlugin()); ``` +A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts` +file in an app, or one authored in Studio) that names this adapter with +`adapter: 'memory'`; the `sources` option above registers one from code. + +When a source stops being served (its item was removed, or a package now holds +its name), the knowledge service calls the adapter's `dropSource` and +everything held for that source is discarded. + ## License Apache-2.0. See [LICENSING.md](../../../LICENSING.md). diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index 0cbcab163d9..5eed4419e75 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -19,5 +19,6 @@ runKnowledgeAdapterContract({ refusesOtherFingerprint: true, generations: true, scope: true, + dropSource: true, }, }); diff --git a/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts b/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts index 65d67f9e7bf..685e1e2a408 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts @@ -6,10 +6,10 @@ import type { KnowledgeDocument } from '@objectstack/spec/ai'; import type { KnowledgeSource } from '@objectstack/spec/ai'; const source: KnowledgeSource = { - id: 'src1', + name: 'src1', label: 'Test source', adapter: 'memory', - source: { kind: 'http', urls: ['https://example.com'] } as KnowledgeSource['source'], + source: { kind: 'object', object: 'article', content: ['body'] }, }; const docs: KnowledgeDocument[] = [ diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 1f45903069d..cc3ac9cfc64 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -77,6 +77,9 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; * - `completeBuild` makes the generation it built the active one (the old one * is dropped) and records the recipe hash; `indexStatus` answers both. * + * - `dropSource` (K8, item 4) discards both generations and what was recorded + * about the index; the source then answers as one never seen. + * * It reports no `embedding` descriptor: its vectors are token counts, and its * index does not outlive the process (K7, rule 8). * @@ -87,7 +90,7 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { readonly id: string; readonly capabilities = { chunks: true } as const; - /** source id → its generations. */ + /** A source's index key (`ctx.source.name`) → its generations. */ private readonly store = new Map(); constructor(id = 'memory') { @@ -100,7 +103,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } async delete(documentIds: string[], ctx: AdapterContext): Promise { - const index = this.store.get(ctx.source.id); + const index = this.store.get(ctx.source.name); for (const generation of [index?.active, index?.building]) { if (!generation) continue; const docs: Map = generation.docs; @@ -109,7 +112,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } async indexStatus(ctx: AdapterContext): Promise { - const index = this.store.get(ctx.source.id); + const index = this.store.get(ctx.source.name); const status: AdapterIndexStatus = {}; if (index?.active?.fingerprint !== undefined) status.fingerprint = index.active.fingerprint; if (index?.active?.recipeHash !== undefined) status.recipeHash = index.active.recipeHash; @@ -119,7 +122,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { async beginBuild(ctx: AdapterContext): Promise { const fingerprint = requireIndex(ctx, 'beginBuild').fingerprint; - const index = this.sourceIndex(ctx.source.id); + const index = this.sourceIndex(ctx.source.name); if (index.active === undefined) { index.active = { fingerprint, docs: new Map() }; return; @@ -131,7 +134,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { async completeBuild(ctx: AdapterContext): Promise { const { fingerprint, recipeHash } = requireIndex(ctx, 'completeBuild'); - const index = this.sourceIndex(ctx.source.id); + const index = this.sourceIndex(ctx.source.name); if (index.building?.fingerprint === fingerprint) { index.active = { ...index.building, recipeHash }; index.building = undefined; @@ -142,10 +145,19 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { return; } throw new Error( - `completeBuild: source '${ctx.source.id}' holds no generation for this fingerprint; call beginBuild first.`, + `completeBuild: source '${ctx.source.name}' holds no generation for this fingerprint; call beginBuild first.`, ); } + /** + * Everything held for the source is gone (ADR-0161 K8, item 4): both + * generations and what was recorded about the index. A source it holds + * nothing for is no error. + */ + async dropSource(ctx: AdapterContext): Promise { + this.store.delete(ctx.source.name); + } + private sourceIndex(sourceId: string): SourceIndex { let index = this.store.get(sourceId); if (!index) { @@ -163,7 +175,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { */ private writeTarget(ctx: AdapterContext, create: boolean): Generation | undefined { const fingerprint = ctx.index?.fingerprint; - const index = this.sourceIndex(ctx.source.id); + const index = this.sourceIndex(ctx.source.name); if (index.active === undefined) { if (!create) return undefined; index.active = { fingerprint, docs: new Map() }; @@ -171,7 +183,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } if (fingerprint === undefined || index.active.fingerprint === fingerprint) return index.active; if (index.building?.fingerprint === fingerprint) return index.building; - throw rebuildRequired(ctx.source.id, false); + throw rebuildRequired(ctx.source.name, false); } async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise { @@ -195,12 +207,12 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } async search(query: string, opts: AdapterSearchOptions): Promise { - const index = this.store.get(opts.source.id); + const index = this.store.get(opts.source.name); const active = index?.active; // Vectors of two fingerprints are never ranked against each other // (ADR-0161 K7, rule 5): refused, never answered from the other generation. if (active !== undefined && opts.index !== undefined && active.fingerprint !== opts.index.fingerprint) { - throw rebuildRequired(opts.source.id, index?.building?.fingerprint === opts.index.fingerprint); + throw rebuildRequired(opts.source.name, index?.building?.fingerprint === opts.index.fingerprint); } const chunks = [...(active?.docs.values() ?? [])].flatMap((d) => d.chunks); if (chunks.length === 0) return []; @@ -232,7 +244,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { return top.map(({ chunk, score }) => ({ chunkId: chunk.chunkId, documentId: chunk.documentId, - sourceId: opts.source.id, + sourceId: opts.source.name, sourceRecordId: chunk.sourceRecordId, score, snippet: chunk.content, diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 53e4ed9a5bd..5e35b12d428 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -9,12 +9,14 @@ import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector'; const kernel = new ObjectKernel(); kernel.use(new KnowledgeServicePlugin({ - sources: [{ id: 'task_notes', label: 'Notes', adapter: 'pgvector', - source: { kind: 'object', object: 'task', contentFields: ['notes'] }}], + sources: [{ name: 'task_notes', label: 'Notes', adapter: 'pgvector', + source: { kind: 'object', object: 'task', content: ['notes'] }}], })); kernel.use(new KnowledgePgvectorPlugin()); ``` +A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts` file in an app, or one authored in Studio) that names this adapter with `adapter: 'pgvector'`; the `sources` option above registers one from code. + ## Options | Option | Default | | @@ -36,7 +38,9 @@ Its tables are in their own schema, `os_knowledge` — never the connection's ow - `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model. - `knowledge_vec_d` — one passage table per vector width (`knowledge_vec_d1536`, `knowledge_vec_d3072`, …), created the first time a width is written. -Rows are keyed by source id. Two deployments that share one database — staging and production, say — must each set their own `schema`, or a source id they both use would be one index. +Rows are keyed by the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two indexes). Two deployments that share one database — staging and production, say — must each set their own `schema`, or a source name they both use would be one index. + +When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: every generation of the source is retired in one transaction, so nothing searches or writes it from then on, and its passages are then deleted in batches, the generation rows last. ## Setup when the connection may not create them diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts index 0a98b0a39df..dbf0dd9eadc 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts @@ -25,10 +25,10 @@ const store = liveStore('kpg_accept'); const source = (id: string): KnowledgeSource => ({ - id, + name: id, label: id, adapter: 'under_test', - source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'] }, + source: { kind: 'object', object: 'article', content: ['body'], metadataFields: ['status'] }, }) as KnowledgeSource; const FP_A = { fingerprint: 'fp-test:a', recipeHash: 'rh-test:1' }; @@ -36,10 +36,10 @@ const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; const ctx = (s: KnowledgeSource, index = FP_A): AdapterContext => ({ source: s, reason: 'manual', index }); function doc(s: KnowledgeSource, n: string, content: string, extra: Partial = {}): KnowledgeDocument { - const id = `${s.id}:${n}`; + const id = `${s.name}:${n}`; return { id, - sourceId: s.id, + sourceId: s.name, sourceRecordId: n, content, title: `Title ${n}`, @@ -60,7 +60,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( const s = source('wide'); await adapter.upsert([doc(s, '1', 'glacier valley ice'), doc(s, '2', 'harbour crane night')], ctx(s)); const hits = await adapter.search('glacier ice', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); - expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:1`]); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:1`]); expect(hits[0].score).toBeGreaterThan(0.5); const width = await store.pool().query<{ t: string }>( `SELECT format_type(a.atttypid, a.atttypmod) AS t FROM pg_attribute a @@ -83,9 +83,9 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( ); const search = (organizationIds?: string[]) => adapter.search('alpine meadow', { source: s, topK: 1, index: { fingerprint: FP_A.fingerprint }, ...(organizationIds ? { organizationIds } : {}) }); - expect((await search()).map((h) => h.documentId)).toEqual([`${s.id}:b`]); - expect((await search(['org_a'])).map((h) => h.documentId)).toEqual([`${s.id}:a`]); - expect((await search(['org_b'])).map((h) => h.documentId)).toEqual([`${s.id}:b`]); + expect((await search()).map((h) => h.documentId)).toEqual([`${s.name}:b`]); + expect((await search(['org_a'])).map((h) => h.documentId)).toEqual([`${s.name}:a`]); + expect((await search(['org_b'])).map((h) => h.documentId)).toEqual([`${s.name}:b`]); expect(await search([])).toEqual([]); expect(await search(['org_c'])).toEqual([]); }); @@ -101,7 +101,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( ctx(s), ); const hits = await adapter.search('basalt', { source: s, topK: 1, filter: { status: 'published' }, index: { fingerprint: FP_A.fingerprint } }); - expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:2`]); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:2`]); expect(hits[0].metadata).toEqual({ status: 'published' }); }); @@ -119,8 +119,8 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( const before = embedder.calls; await adapter.upsert( [{ ...doc(s, '1', 'x'), chunks: [ - { id: `${s.id}:1#0`, documentId: `${s.id}:1`, index: 0, content: 'copper wire conducts heat' }, - { id: `${s.id}:1#1`, documentId: `${s.id}:1`, index: 1, content: 'drawn through dies' }, + { id: `${s.name}:1#0`, documentId: `${s.name}:1`, index: 0, content: 'copper wire conducts heat' }, + { id: `${s.name}:1#1`, documentId: `${s.name}:1`, index: 1, content: 'drawn through dies' }, ] }], ctx(s), ); @@ -139,11 +139,11 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( svc.registerAdapter('under_test', adapter); const s = source('svc_same'); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 2 }); const after = embedder.calls; - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 0, skipped: 2 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 0, skipped: 2 }); expect(embedder.calls).toBe(after); - expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.name}:r1`]); }); it('a changed embedding model changes the fingerprint: search is refused by name, and the old rows are not served', async () => { @@ -153,7 +153,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( svc.registerAdapter('under_test', adapter); const s = source('svc_model'); svc.registerSource(s); - await svc.reindexSource(s.id); + await svc.reindexSource(s.name); expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1); embedder.model = 'model-two'; @@ -162,12 +162,12 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( (e: unknown) => e as { code?: string; status?: number; message?: string }, ); expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); - expect(refused?.message).toContain(s.id); + expect(refused?.message).toContain(s.name); // The caller is told the source needs a rebuild, never SQL. expect(refused?.message).not.toContain('DELETE'); // A complete reindex under the new model builds the new generation, and search answers again. const before = embedder.calls; - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1, skipped: 0 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1, skipped: 0 }); expect(embedder.calls).toBe(before + 1); expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1); }); @@ -180,19 +180,19 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( svc.registerAdapter('under_test', adapter); const s = source('svc_leftover'); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1 }); // Same width, another model; an operator deletes only the generation row. embedder.model = 'model-two'; - await store.pool().query(`DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = $1`, [s.id]); + await store.pool().query(`DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = $1`, [s.name]); const before = embedder.calls; - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1, skipped: 0 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1, skipped: 0 }); // The passage was embedded again under the new model: the old vector was not adopted. expect(embedder.calls).toBe(before + 1); expect(embedder.texts.slice(-1)).toEqual(['granite quarry']); const rows = await store.pool().query<{ n: string }>( `SELECT count(*) AS n FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1`, - [s.id], + [s.name], ); expect(Number(rows.rows[0].n)).toBe(1); }); @@ -218,12 +218,12 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( await adapter.upsert([doc(s, '1', 'copper wire conducts heat')], ctx(s)); expect(embedder.calls).toBe(1); interfere = async () => { - await base.query(`DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1`, [s.id]); + await base.query(`DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1`, [s.name]); }; await adapter.upsert([doc(s, '1', 'copper wire conducts heat', { metadata: { status: 'archived' } })], ctx(s)); expect(embedder.calls).toBe(2); const [hit] = await adapter.search('copper', { source: s, topK: 1, index: { fingerprint: FP_A.fingerprint } }); - expect(hit).toMatchObject({ documentId: `${s.id}:1`, metadata: { status: 'archived' } }); + expect(hit).toMatchObject({ documentId: `${s.name}:1`, metadata: { status: 'archived' } }); }); it('beginBuild under its own fingerprint opens nothing; a search under another is refused and never served', async () => { diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts index 4793ae494ec..f117b877836 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts @@ -12,7 +12,7 @@ import type { KnowledgeSource } from '@objectstack/spec/ai'; import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; import { FakeEmbedder } from './live-pg.testkit.js'; -const source = { id: 'locked', label: 'locked', adapter: 'pgvector', source: { kind: 'object', object: 'a', contentFields: ['b'] } } as KnowledgeSource; +const source = { name: 'locked', label: 'locked', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; const index = { fingerprint: 'fp', recipeHash: 'rh' }; /** A store that answers every statement the build's start and end run; the unlock answers `unlocked`. */ diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index 2cfb8e2152a..d1f51dcddcd 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -28,6 +28,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { refusesOtherFingerprint: true, generations: true, scope: true, + dropSource: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts index 7c05d63c09d..0324b8dae87 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts @@ -31,10 +31,10 @@ const FP_C = { fingerprint: 'fp-gen:c', recipeHash: 'rh-gen:1' }; const source = (id: string): KnowledgeSource => ({ - id, + name: id, label: id, adapter: 'under_test', - source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'] }, + source: { kind: 'object', object: 'article', content: ['body'], metadataFields: ['status'] }, }) as KnowledgeSource; const ctx = (s: KnowledgeSource, index: { fingerprint: string; recipeHash: string } = FP_A): AdapterContext => ({ @@ -44,10 +44,10 @@ const ctx = (s: KnowledgeSource, index: { fingerprint: string; recipeHash: strin }); function doc(s: KnowledgeSource, n: string, content: string): KnowledgeDocument { - const id = `${s.id}:${n}`; + const id = `${s.name}:${n}`; return { id, - sourceId: s.id, + sourceId: s.name, sourceRecordId: n, content, docHash: `h:${content}`, @@ -143,24 +143,24 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', svc.registerAdapter('under_test', adapter); const s = source('model_change'); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 2 }); const before = await adapter.indexStatus({ source: s, reason: 'manual' }); - expect(await generationRows(schema, s.id)).toEqual([{ generation: 1, fingerprint: before.fingerprint, state: 'active' }]); + expect(await generationRows(schema, s.name)).toEqual([{ generation: 1, fingerprint: before.fingerprint, state: 'active' }]); // Another model of the same width: the fingerprint moves, and the boot reading says so. embedder.model = 'model-two'; - expect(await svc.readIndexState(s.id)).toMatchObject({ state: 'new-fingerprint', due: true }); + expect(await svc.readIndexState(s.name)).toMatchObject({ state: 'new-fingerprint', due: true }); // The build starts, and its first page's embed call is held. const gate = embedder.holdNext(); - const build = svc.reindexSource(s.id); + const build = svc.reindexSource(s.name); await gate.entered; expect(await adapter.indexStatus({ source: s, reason: 'manual' })).toEqual({ fingerprint: before.fingerprint, recipeHash: before.recipeHash, building: true, }); - expect((await generationRows(schema, s.id)).map((g) => [g.generation, g.state])).toEqual([ + expect((await generationRows(schema, s.name)).map((g) => [g.generation, g.state])).toEqual([ [1, 'active'], [2, 'building'], ]); @@ -177,7 +177,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', const late = { id: 'r0', body: 'basalt columns', status: 'published' }; rows.push(late); await svc.handleRecordUpsert('article', late); - expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 2, 2: 1 }); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 1: 2, 2: 1 }); gate.release(); // The walk wrote both rows, the purge removed nothing written during the build, and the switch ran. @@ -186,12 +186,12 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', const after = await adapter.indexStatus({ source: s, reason: 'manual' }); expect(after.fingerprint).not.toBe(before.fingerprint); expect(after.building).toBeUndefined(); - expect(await generationRows(schema, s.id)).toEqual([{ generation: 2, fingerprint: after.fingerprint, state: 'active' }]); + expect(await generationRows(schema, s.name)).toEqual([{ generation: 2, fingerprint: after.fingerprint, state: 'active' }]); // The old generation is deleted; the write made during the build is there. - expect(await passagesByGeneration(schema, s.id)).toEqual({ 2: 3 }); - expect((await svc.search('basalt', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r0`]); - expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); - expect(await svc.readIndexState(s.id)).toMatchObject({ state: 'current', due: false }); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 2: 3 }); + expect((await svc.search('basalt', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.name}:r0`]); + expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.name}:r1`]); + expect(await svc.readIndexState(s.name)).toMatchObject({ state: 'current', due: false }); }); it('two concurrent builds of one source: one builds, the other is refused LOCK_CONFLICT and walks nothing', async () => { @@ -210,9 +210,9 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', svcB.registerSource(s); const gate = first.holdNext(); - const buildA = svcA.reindexSource(s.id); + const buildA = svcA.reindexSource(s.name); await gate.entered; - const refusedB = await svcB.reindexSource(s.id); + const refusedB = await svcB.reindexSource(s.name); expect(refusedB).toMatchObject({ ok: false, indexed: 0, discovered: 0 }); expect(refusedB.message).toContain('is being built by another process'); expect(second.calls).toBe(0); @@ -221,7 +221,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', gate.release(); expect(await buildA).toMatchObject({ ok: true, indexed: 1 }); // The lock went with the completed build: the other process may build now. - expect(await svcB.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 0, skipped: 1 }); + expect(await svcB.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 0, skipped: 1 }); }); it('a build whose session died is resumed by the next one: what it wrote is kept, and only the rest is written', async () => { @@ -233,7 +233,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_B)); // The process dies: PostgreSQL ends its session, and the advisory lock with it. - const lock = (a as unknown as { builders: Map }).builders.get(s.id)!; + const lock = (a as unknown as { builders: Map }).builders.get(s.name)!; const pid = (await lock.client.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')).rows[0].pid; await store.pool().query('SELECT pg_terminate_backend($1)', [pid]); @@ -241,11 +241,11 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', await expect(b.beginBuild(ctx(s, FP_B))).resolves.toBeUndefined(); // Resumed, not restarted: the generation under construction keeps the passage written before. const listed = await b.listDocuments(ctx(s, FP_B), { limit: 10 }); - expect(listed.documents).toEqual([{ documentId: `${s.id}:1`, docHash: 'h:granite quarry' }]); - expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 2, 2: 1 }); + expect(listed.documents).toEqual([{ documentId: `${s.name}:1`, docHash: 'h:granite quarry' }]); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 1: 2, 2: 1 }); await b.upsert([doc(s, '2', 'marble quarry')], ctx(s, FP_B)); await b.completeBuild(ctx(s, FP_B)); - expect(await passagesByGeneration(schema, s.id)).toEqual({ 2: 2 }); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 2: 2 }); expect(await b.indexStatus(ctx(s))).toEqual({ fingerprint: FP_B.fingerprint, recipeHash: FP_B.recipeHash }); }); @@ -296,11 +296,11 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', await adapter.beginBuild(ctx(s, FP_B)); await adapter.upsert([doc(s, '1', 'stone 1')], ctx(s, FP_B)); await adapter.beginBuild(ctx(s, FP_C)); - expect((await generationRows(schema, s.id)).map((g) => [g.generation, g.fingerprint, g.state])).toEqual([ + expect((await generationRows(schema, s.name)).map((g) => [g.generation, g.fingerprint, g.state])).toEqual([ [1, FP_A.fingerprint, 'active'], [3, FP_C.fingerprint, 'building'], ]); - expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 5 }); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 1: 5 }); // A write under the abandoned fingerprint is refused; nothing reaches the active generation. await expect(adapter.upsert([doc(s, '9', 'stone 9')], ctx(s, FP_B))).rejects.toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED }); @@ -309,7 +309,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', await adapter.completeBuild(ctx(s, FP_C)); // Five passages, two a statement: three statements, all for generation 1. expect(batches).toEqual(['1', '1', '1']); - expect(await generationRows(schema, s.id)).toEqual([{ generation: 3, fingerprint: FP_C.fingerprint, state: 'active' }]); - expect(await passagesByGeneration(schema, s.id)).toEqual({ 3: 1 }); + expect(await generationRows(schema, s.name)).toEqual([{ generation: 3, fingerprint: FP_C.fingerprint, state: 'active' }]); + expect(await passagesByGeneration(schema, s.name)).toEqual({ 3: 1 }); }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts index 022835958db..8eb949c069e 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts @@ -22,7 +22,7 @@ import { } from '../index.js'; import { FakeEmbedder } from './live-pg.testkit.js'; -const source = { id: 's1', label: 's1', adapter: 'pgvector', source: { kind: 'object', object: 'a', contentFields: ['body'] } } as KnowledgeSource; +const source = { name: 's1', label: 's1', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['body'] } } as KnowledgeSource; /** A database without pgvector, where this connection may not create it; `installed` flips that. */ function databaseWithoutVector() { diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts index 63491444851..19411758bed 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts @@ -54,10 +54,10 @@ describe.skipIf(!PG_URL)('knowledge-pgvector — complete reindex over ObjectQL let embedder: FakeEmbedder; const ids = recordIds(); const source = { - id: 'driver_walk', + name: 'driver_walk', label: 'Driver walk', adapter: 'pgvector', - source: { kind: 'object', object: OBJECT, contentFields: ['body'], metadataFields: ['status'] }, + source: { kind: 'object', object: OBJECT, content: ['body'], metadataFields: ['status'] }, } as KnowledgeSource; beforeAll(async () => { @@ -94,7 +94,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector — complete reindex over ObjectQL }); it('indexes every record exactly once, skips none, purges none', async () => { - const first = await svc.reindexSource(source.id); + const first = await svc.reindexSource(source.name); expect(first).toMatchObject({ ok: true, discovered: ids.length, indexed: ids.length, skipped: 0, failed: 0 }); expect(first.purged ?? 0).toBe(0); expect([...upserted].sort()).toEqual([...ids].sort()); @@ -102,7 +102,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector — complete reindex over ObjectQL it('a second complete reindex writes nothing, embeds nothing, and purges nothing', async () => { const before = { upserts: upserted.length, embeds: embedder.calls }; - const second = await svc.reindexSource(source.id); + const second = await svc.reindexSource(source.name); expect(second).toMatchObject({ ok: true, discovered: ids.length, indexed: 0, skipped: ids.length, failed: 0 }); expect(second.purged ?? 0).toBe(0); expect(upserted.length).toBe(before.upserts); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index e303dadf5ae..3c4490066ee 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -306,11 +306,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { for (let attempt = 1; ; attempt++) { const generation = (await this.writeTarget(ctx, embedder, true))!; await this.ensureVectorTable(generation.dim, readiness); - const missing = await this.writePassages(docs, ctx.source.id, generation, readiness, embedder); + const missing = await this.writePassages(docs, ctx.source.name, generation, readiness, embedder); if (missing === undefined) return; if (attempt >= UPSERT_ATTEMPTS) { throw new Error( - `knowledge-pgvector: ${missing} of source '${ctx.source.id}' was removed by a concurrent write ` + + `knowledge-pgvector: ${missing} of source '${ctx.source.name}' was removed by a concurrent write ` + `${UPSERT_ATTEMPTS} times while this write ran; nothing of this batch was written. Retry the write.`, ); } @@ -442,13 +442,13 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // From every generation of the source: a removed document leaves them all. const widths = await pool.query<{ dim: number }>( `SELECT DISTINCT dim FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1`, - [ctx.source.id], + [ctx.source.name], ); for (const { dim } of widths.rows) { if (!(await this.tableExists(Number(dim)))) continue; await pool.query( `DELETE FROM ${qualified(this.schema, vectorTable(Number(dim)))} WHERE source_id = $1 AND document_id = ANY($2::text[])`, - [ctx.source.id, documentIds], + [ctx.source.name, documentIds], ); } } @@ -470,7 +470,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (!generation || !(await this.tableExists(generation.dim))) return { documents: [] }; // In byte order ("C"), both the order and the cursor's comparison, so a // cursor stays valid whatever the database's collation. - const params: unknown[] = [ctx.source.id, generation.generation, opts.limit + 1]; + const params: unknown[] = [ctx.source.name, generation.generation, opts.limit + 1]; const after = opts.cursor === undefined ? '' : `AND document_id COLLATE "C" > $4`; if (opts.cursor !== undefined) params.push(opts.cursor); const page = await pool.query<{ document_id: string; doc_hash: string | null }>( @@ -496,7 +496,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (hits !== undefined) return hits; if (attempt >= SEARCH_ATTEMPTS) { throw new Error( - `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + `knowledge-pgvector: the active generation of source '${opts.source.name}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, ); } } @@ -516,17 +516,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // model or width, and comparing it would refuse a healthy index as one to // rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call. const embedder = this.requireEmbedder(); - const { active: generation, building } = await this.generations(opts.source.id); + const { active: generation, building } = await this.generations(opts.source.name); if (!generation) return []; // Vectors of two fingerprints are never ranked against each other (K7, // rule 5); while the searched fingerprint's generation is being built, the // refusal says so. const searched = opts.index?.fingerprint; if (searched !== undefined && generation.fingerprint !== searched) { - throw rebuildRequired(opts.source.id, building !== undefined && building.fingerprint === searched); + throw rebuildRequired(opts.source.name, building !== undefined && building.fingerprint === searched); } if (embedder.dimensions !== generation.dim) { - throw rebuildRequired(opts.source.id, building !== undefined && building.dim === embedder.dimensions); + throw rebuildRequired(opts.source.name, building !== undefined && building.dim === embedder.dimensions); } if (!(await this.tableExists(generation.dim))) return []; const topK = Math.max(0, Math.floor(opts.topK)); @@ -543,7 +543,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (vector.every((x) => x === 0)) return []; const ext = readiness.extensionSchema; - const params: unknown[] = [opts.source.id, generation.generation, vectorLiteral(vector), topK]; + const params: unknown[] = [opts.source.name, generation.generation, vectorLiteral(vector), topK]; const where = [ 'source_id = $1', 'generation = $2', @@ -610,13 +610,13 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ); if (result.rows.length === 0) { // No hit, or a generation switched out meanwhile: read which. - const now = await this.generations(opts.source.id); + const now = await this.generations(opts.source.name); if (now.active?.generation !== generation.generation) return undefined; } return result.rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, - sourceId: opts.source.id, + sourceId: opts.source.name, ...(r.source_record_id === null ? {} : { sourceRecordId: r.source_record_id }), score: 1 - Number(r.distance), snippet: r.content, @@ -633,7 +633,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { async indexStatus(ctx: AdapterContext): Promise { this.requirePool(); await this.ready(); - const { active, building } = await this.generations(ctx.source.id); + const { active, building } = await this.generations(ctx.source.name); const status: AdapterIndexStatus = {}; if (active?.fingerprint != null) status.fingerprint = active.fingerprint; if (active?.recipe_hash != null) status.recipeHash = active.recipe_hash; @@ -655,7 +655,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.requirePool(); const readiness = await this.ready(); const embedder = this.requireEmbedder(); - const sourceId = ctx.source.id; + const sourceId = ctx.source.name; await this.takeBuilderLock(sourceId); try { const target = await this.inTransaction(async (client) => { @@ -690,7 +690,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const index = requireIndex(ctx, 'completeBuild'); this.requirePool(); await this.ready(); - const sourceId = ctx.source.id; + const sourceId = ctx.source.name; try { await this.inTransaction(async (client) => { const { active, building } = await this.generations(sourceId, client, true); @@ -733,6 +733,33 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } + /** + * Everything held for the source is removed (ADR-0161 K8, item 4). Every + * generation — the active one, and one under construction — is retired in + * one transaction, so from its commit no search and no write finds one; + * then the passages are deleted in batches and each generation row last, as + * a replaced generation's are. A builder lock this adapter holds for the + * source is let go. A source it holds nothing for is no error. A drop that + * stops after the commit leaves retired generations: never searched, and + * deleted by the next drop or the next build of that key. + */ + async dropSource(ctx: AdapterContext): Promise { + this.requirePool(); + await this.ready(); + const sourceId = ctx.source.name; + try { + await this.inTransaction(async (client) => { + const { active, building } = await this.generations(sourceId, client, true); + for (const g of [active, building]) { + if (g !== undefined) await this.retire(client, sourceId, g.generation); + } + }); + await this.sweepRetired(sourceId); + } finally { + await this.releaseBuilderLock(sourceId); + } + } + /** Let go of every builder lock this adapter holds; the plugin calls it before it closes its pool. */ async close(): Promise { for (const sourceId of [...this.builders.keys()]) await this.releaseBuilderLock(sourceId); @@ -983,7 +1010,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { embedder: IEmbedder, create: boolean, ): Promise { - const sourceId = ctx.source.id; + const sourceId = ctx.source.name; const fingerprint = ctx.index?.fingerprint; const { active, building } = await this.generations(sourceId); const checked = (g: GenerationRow): GenerationRow => { @@ -1047,7 +1074,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { */ private touchBuilderLock(ctx: AdapterContext): void { if (ctx.reason !== 'reindex') return; - this.restartIdleTimer(ctx.source.id); + this.restartIdleTimer(ctx.source.name); } private restartIdleTimer(sourceId: string): void { diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 281fb3bf6f8..f65e6ff9283 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -9,12 +9,14 @@ import { KnowledgeTursoPlugin } from '@objectstack/knowledge-turso'; const kernel = new ObjectKernel(); kernel.use(new KnowledgeServicePlugin({ - sources: [{ id: 'task_notes', label: 'Notes', adapter: 'turso', - source: { kind: 'object', object: 'task', contentFields: ['notes'] }}], + sources: [{ name: 'task_notes', label: 'Notes', adapter: 'turso', + source: { kind: 'object', object: 'task', content: ['notes'] }}], })); kernel.use(new KnowledgeTursoPlugin()); // .objectstack/data/knowledge.db ``` +A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts` file in an app, or one authored in Studio) that names this adapter with `adapter: 'turso'`; the `sources` option above registers one from code. + ## Options | Option | Default | | @@ -40,6 +42,8 @@ On a file the store sets WAL and a busy timeout: without them a second process w - `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints. - `knowledge__g` — the passages of one generation of one source, with an `F32_BLOB()` vector column sized for that generation. +`` is the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two tables). When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: the source's generation tables and rows are dropped in one transaction. + ## Search An exact scan by cosine distance (`vector_distance_cos`). The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) run in the same `WHERE`, before ranking — libSQL's DiskANN index (`vector_top_k`) ranks first and filters after, so the store creates none. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. (With a DiskANN index the same 1,000 vectors grew a file to 329 MB, and the index build took 21.8 s.) For larger sources, use `@objectstack/knowledge-pgvector`. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index dcee6d09574..1c6037fdfb4 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -22,20 +22,20 @@ import { FakeEmbedder, storeOf, type StoreKind } from './turso.testkit.js'; const source = (id: string, extra: Record = {}): KnowledgeSource => ({ - id, + name: id, label: id, adapter: 'under_test', - source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'], ...extra }, + source: { kind: 'object', object: 'article', content: ['body'], metadataFields: ['status'], ...extra }, }) as KnowledgeSource; const FP_A = { fingerprint: 'fp-test:a', recipeHash: 'rh-test:1' }; const ctx = (s: KnowledgeSource, index = FP_A): AdapterContext => ({ source: s, reason: 'manual', index }); function doc(s: KnowledgeSource, n: string, content: string, extra: Partial = {}): KnowledgeDocument { - const id = `${s.id}:${n}`; + const id = `${s.name}:${n}`; return { id, - sourceId: s.id, + sourceId: s.name, sourceRecordId: n, content, title: `Title ${n}`, @@ -108,7 +108,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ctx(s), ); const hits = await adapter.search('客户续约提醒', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); - expect(hits[0]).toMatchObject({ documentId: `${s.id}:1`, snippet: '合同到期前三十天提醒客户续约' }); + expect(hits[0]).toMatchObject({ documentId: `${s.name}:1`, snippet: '合同到期前三十天提醒客户续约' }); expect(hits[0].score).toBeGreaterThan(0.3); }); @@ -119,8 +119,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const two = (second: string): KnowledgeDocument => ({ ...doc(s, '1', `granite quarry. ${second}`), chunks: [ - { id: `${s.id}:1#0`, documentId: `${s.id}:1`, index: 0, content: 'granite quarry' }, - { id: `${s.id}:1#1`, documentId: `${s.id}:1`, index: 1, content: second }, + { id: `${s.name}:1#0`, documentId: `${s.name}:1`, index: 0, content: 'granite quarry' }, + { id: `${s.name}:1#1`, documentId: `${s.name}:1`, index: 1, content: second }, ], }); await adapter.upsert([two('marble cliffs')], ctx(s)); @@ -130,7 +130,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.upsert([two('basalt columns')], ctx(s)); expect(embedder.texts.slice(2)).toEqual(['basalt columns']); const hits = await adapter.search('basalt granite', { source: s, topK: 5 }); - expect(hits.map((h) => h.chunkId).sort()).toEqual([`${s.id}:1#0`, `${s.id}:1#1`]); + expect(hits.map((h) => h.chunkId).sort()).toEqual([`${s.name}:1#0`, `${s.name}:1#1`]); }); for (const [label, next] of [ @@ -149,8 +149,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); svc.registerAdapter('under_test', adapter); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); - expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g1`]); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 2 }); + expect(await tables(client, `knowledge_${s.name}_g%`)).toEqual([`knowledge_${s.name}_g1`]); const before = await adapter.indexStatus(ctx(s)); embedder = next(); @@ -159,15 +159,15 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { code: KNOWLEDGE_REBUILD_REQUIRED, status: 409, }); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); - expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g2`]); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + expect(await tables(client, `knowledge_${s.name}_g%`)).toEqual([`knowledge_${s.name}_g2`]); const after = await adapter.indexStatus(ctx(s)); expect(after.fingerprint).toBeDefined(); expect(after.fingerprint).not.toBe(before.fingerprint); const hits = await svc.search('glacier', { topK: 5, executionContext: SYSTEM }); - expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:r1`]); const width = await client.execute( - `SELECT dim, model FROM knowledge_generation WHERE source_id = '${s.id}'`, + `SELECT dim, model FROM knowledge_generation WHERE source_id = '${s.name}'`, ); expect(width.rows.map((r) => [Number(r.dim), r.model])).toEqual([[embedder.dimensions, embedder.model]]); }); @@ -180,14 +180,14 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s)); const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; await adapter.beginBuild(ctx(s, FP_B)); - expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g1`, `knowledge_${s.id}_g2`]); + expect(await tables(client, `knowledge_${s.name}_g%`)).toEqual([`knowledge_${s.name}_g1`, `knowledge_${s.name}_g2`]); const err = await refusal(adapter.search('granite', { source: s, topK: 5, index: { fingerprint: FP_B.fingerprint } })); expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); expect(String(err.message)).toMatch(/is being rebuilt/); // A third fingerprint abandons the unfinished build: one builder per source. const FP_C = { fingerprint: 'fp-test:c', recipeHash: 'rh-test:1' }; await adapter.beginBuild(ctx(s, FP_C)); - const rows = await client.execute(`SELECT generation, fingerprint, state FROM knowledge_generation WHERE source_id = '${s.id}' ORDER BY generation`); + const rows = await client.execute(`SELECT generation, fingerprint, state FROM knowledge_generation WHERE source_id = '${s.name}' ORDER BY generation`); expect(rows.rows.map((r) => [Number(r.generation), r.fingerprint, r.state])).toEqual([ [1, FP_A.fingerprint, 'active'], [2, FP_C.fingerprint, 'building'], @@ -207,9 +207,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ctx(s), ); const asA = await adapter.search('alpine meadow', { source: s, topK: 1, organizationIds: ['org_a'] }); - expect(asA.map((h) => h.documentId)).toEqual([`${s.id}:a`]); + expect(asA.map((h) => h.documentId)).toEqual([`${s.name}:a`]); const asB = await adapter.search('alpine meadow harbour', { source: s, topK: 5, organizationIds: ['org_b'] }); - expect(asB.map((h) => h.documentId)).toEqual([`${s.id}:b`]); + expect(asB.map((h) => h.documentId)).toEqual([`${s.name}:b`]); }); it('the metadata filter runs before ranking, by JSON equality', async () => { @@ -223,8 +223,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ctx(s), ); const top = await adapter.search('tidal pool', { source: s, topK: 1, filter: { status: 'published' } }); - expect(top.map((h) => h.documentId)).toEqual([`${s.id}:2`]); - expect((await adapter.search('tidal', { source: s, topK: 5, filter: { pinned: true } })).map((h) => h.documentId)).toEqual([`${s.id}:1`]); + expect(top.map((h) => h.documentId)).toEqual([`${s.name}:2`]); + expect((await adapter.search('tidal', { source: s, topK: 5, filter: { pinned: true } })).map((h) => h.documentId)).toEqual([`${s.name}:1`]); expect((await adapter.search('tidal', { source: s, topK: 5, filter: { rank: 2 } })).length).toBe(2); expect(await adapter.search('tidal', { source: s, topK: 5, filter: { rank: '2' } })).toEqual([]); }); @@ -243,13 +243,13 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const ids = async (scope: NonNullable[1]['scope']>) => (await adapter.search('harbour rules', { source: s, topK: 5, scope })).map((h) => h.documentId).sort(); // A dotted name is a key, never a JSON path into a nested object. - expect(await ids([{ kind: 'metadata', field: 'policy.id', ids: ['p1'] }])).toEqual([`${s.id}:1`]); + expect(await ids([{ kind: 'metadata', field: 'policy.id', ids: ['p1'] }])).toEqual([`${s.name}:1`]); // A boolean matches no id, by either spelling; the string 'true' does. An object matches nothing. - expect(await ids([{ kind: 'metadata', field: 'flag', ids: ['true'] }])).toEqual([`${s.id}:2`]); + expect(await ids([{ kind: 'metadata', field: 'flag', ids: ['true'] }])).toEqual([`${s.name}:2`]); expect(await ids([{ kind: 'metadata', field: 'flag', ids: ['1'] }])).toEqual([]); expect(await ids([{ kind: 'metadata', field: 'policy', ids: ['{"id":"p1"}'] }])).toEqual([]); // A quote in a name is a value; a number in a list matches its text. - expect(await ids([{ kind: 'metadata', field: "it's", ids: ['7.5'] }])).toEqual([`${s.id}:3`]); + expect(await ids([{ kind: 'metadata', field: "it's", ids: ['7.5'] }])).toEqual([`${s.name}:3`]); expect(await ids([{ kind: 'record', ids: ["1' OR '1'='1"] }])).toEqual([]); }); @@ -275,10 +275,10 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); svc.registerAdapter('under_test', adapter); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1 }); expect(await tables(client, 'knowledge_legacy%')).toEqual(['knowledge_legacy_g1']); const hits = await svc.search('glacier', { topK: 5, executionContext: SYSTEM }); - expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:r1`]); }); it('a generation table of another source is never taken for a legacy table', async () => { @@ -303,10 +303,10 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'amber resin', status: 'published' }]) }); svc.registerAdapter('under_test', adapter); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1 }); expect(await tables(client, 'knowledge_generation')).toEqual(['knowledge_generation']); expect((await adapter.search('amber', { source: other, topK: 5 })).map((h) => h.snippet)).toEqual(['amber lamp']); - expect((await adapter.search('amber', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + expect((await adapter.search('amber', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.name}:r1`]); }); it('a table with the legacy columns but no F32_BLOB vector is not a legacy table', async () => { @@ -352,7 +352,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'slate roof', status: 'published' }]) }); svc.registerAdapter('under_test', adapter); svc.registerSource(s); - expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 1 }); expect((await client.execute('SELECT body FROM knowledge_articles')).rows.map((r) => r.body)).toEqual(['kept']); // Under the name of a generation table it is refused, and left as it is. await client.execute('CREATE TABLE knowledge_notes_g1 (id TEXT PRIMARY KEY, body TEXT)'); @@ -385,9 +385,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); const s = source('fresh'); await adapter.upsert([doc(s, 'old', 'cedar chest')], ctx(s)); - await client.execute({ sql: 'DELETE FROM knowledge_generation WHERE source_id = ?', args: [s.id] }); + await client.execute({ sql: 'DELETE FROM knowledge_generation WHERE source_id = ?', args: [s.name] }); await adapter.upsert([doc(s, 'new', 'cedar fence')], ctx(s)); - expect((await adapter.search('cedar', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.id}:new`]); + expect((await adapter.search('cedar', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.name}:new`]); }); it('concurrent calls on one client are queued, never refused for a held connection', async () => { @@ -508,8 +508,8 @@ describe('knowledge-turso with a request bound (a remote database)', () => { const docs = Array.from({ length: 40 }, (_, i) => doc(s, String(i), `heron ${i}`, { chunks: [0, 1].map((index) => ({ - id: `${s.id}:${i}#${index}`, - documentId: `${s.id}:${i}`, + id: `${s.name}:${i}#${index}`, + documentId: `${s.name}:${i}`, index, content: `heron ${i} ${index === 0 ? 'wading' : 'flying'}`, })), @@ -550,7 +550,7 @@ describe('knowledge-turso with a request bound (a remote database)', () => { const err = await refusal(adapter.upsert([doc(s, 'a', 'otter pup'), doc(s, 'b', 'otter den')], ctx(s))); expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, remedy: expect.stringContaining('requestTimeoutMs') }); await new Promise((r) => setTimeout(r, 100)); - expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.id}:seed`]); + expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.name}:seed`]); // The next write goes through. await adapter.upsert([doc(s, 'a', 'otter pup')], ctx(s)); expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.length).toBe(2); diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 15d9f5bb368..6c0b111351b 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -26,6 +26,7 @@ for (const kind of ['memory', 'file'] as const) { refusesOtherFingerprint: true, generations: true, scope: true, + dropSource: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 411bf6675de..1e04b96d0ac 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -157,7 +157,7 @@ describe('KnowledgeTursoPlugin', () => { await new Fresh({ url: ':memory:', env: {} }).start(ctx); const adapter = adapters.get('turso')!; const err = await adapter - .search('x', { source: { id: 's', label: 's', adapter: 'turso', source: { kind: 'object', object: 'o', contentFields: ['b'] } } as never, topK: 1 }) + .search('x', { source: { name: 's', label: 's', adapter: 'turso', source: { kind: 'object', object: 'o', content: ['b'] } } as never, topK: 1 }) .catch((e: unknown) => e); expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); expect(logs.some(([level, m]) => level === 'warn' && m.includes('@libsql/client could not be loaded'))).toBe(true); diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index 6e42e4c4592..b40a16e5d74 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -9,9 +9,10 @@ */ /** - * A source id this module puts into a table name: the spec's snake_case - * source id (`KnowledgeSource.id`), the spec's own pattern. Anything else is - * refused before it reaches a string. + * A source's index key this module puts into a table name: the string the + * knowledge service hands over as `ctx.source.name` (a source's snake_case + * name, or the service's spelling of a package's source — the same + * alphabet). Anything else is refused before it reaches a string. */ export const SAFE_SOURCE_ID = /^[a-z_][a-z0-9_]*$/; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 453c37090a6..c7a7abfcdf6 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -275,7 +275,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { if (docs.length === 0) return; const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); const embedder = this.requireEmbedder(); await this.ready(); // An unchanged passage is rewritten in place, keeping its vector. When its @@ -284,11 +284,11 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // passage is embedded and inserted rather than lost. for (let attempt = 1; ; attempt++) { const target = await this.queued(client, () => this.writeTarget(ctx, embedder, true)); - const missing = await this.writePassages(docs, ctx.source.id, target!, embedder); + const missing = await this.writePassages(docs, ctx.source.name, target!, embedder); if (missing === undefined) return; if (attempt >= UPSERT_ATTEMPTS) { throw new Error( - `knowledge-turso: a concurrent write to source '${ctx.source.id}' removed passages this write meant to keep, ` + + `knowledge-turso: a concurrent write to source '${ctx.source.name}' removed passages this write meant to keep, ` + `${UPSERT_ATTEMPTS} times while it ran; nothing of this batch was written. Retry the write.`, ); } @@ -413,15 +413,15 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { async delete(documentIds: string[], ctx: AdapterContext): Promise { if (documentIds.length === 0) return; const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); await this.ready(); // From every generation of the source: a removed document leaves them all. await this.queued(client, async () => { - const { active, building } = await this.generations(ctx.source.id); + const { active, building } = await this.generations(ctx.source.name); for (const g of [active, building]) { if (!g) continue; await client.execute({ - sql: `DELETE FROM ${quoted(generationTable(ctx.source.id, g.generation))} WHERE document_id IN (SELECT value FROM json_each(?))`, + sql: `DELETE FROM ${quoted(generationTable(ctx.source.name, g.generation))} WHERE document_id IN (SELECT value FROM json_each(?))`, args: [JSON.stringify(documentIds)], }); } @@ -433,7 +433,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`); } const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); // The embedder first, as on every other call: without one the service's // fingerprint carries no model or width, and comparing it would refuse a // healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE. @@ -443,7 +443,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // The generation the writes go to (ADR-0161 K8, item 1). const target = await this.writeTarget(ctx, embedder, false); if (!target) return { documents: [] }; - const table = quoted(generationTable(ctx.source.id, target.generation)); + const table = quoted(generationTable(ctx.source.name, target.generation)); // SQLite compares TEXT by bytes (BINARY), both the order and the cursor. const page = await client.execute({ sql: `SELECT document_id, max(doc_hash) AS doc_hash FROM ${table} @@ -473,24 +473,24 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17). if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return []; const client = this.requireClient(); - assertSourceId(opts.source.id); + assertSourceId(opts.source.name); // The embedder first: without one the service's fingerprint carries no // model or width, and comparing it would refuse a healthy index as one to // rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call. const embedder = this.requireEmbedder(); await this.ready(); - const { active, building } = await this.queued(client, () => this.generations(opts.source.id)); + const { active, building } = await this.queued(client, () => this.generations(opts.source.name)); if (!active) { - if (await this.queued(client, () => this.hasLegacy(opts.source.id))) { - throw rebuildRequired(opts.source.id, building !== undefined); + if (await this.queued(client, () => this.hasLegacy(opts.source.name))) { + throw rebuildRequired(opts.source.name, building !== undefined); } return []; } // Vectors of two fingerprints are never ranked against each other (K7, rule 5). if (opts.index !== undefined && active.fingerprint !== opts.index.fingerprint) { - throw rebuildRequired(opts.source.id, building?.fingerprint === opts.index.fingerprint); + throw rebuildRequired(opts.source.name, building?.fingerprint === opts.index.fingerprint); } - if (embedder.dimensions !== active.dim) throw rebuildRequired(opts.source.id, false); + if (embedder.dimensions !== active.dim) throw rebuildRequired(opts.source.name, false); const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; @@ -543,10 +543,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); } args.push(topK); - const table = quoted(generationTable(opts.source.id, active.generation)); + const table = quoted(generationTable(opts.source.name, active.generation)); const result = await this.queued(client, async () => { // The generation may have been switched while the query was embedded. - const now = await this.generations(opts.source.id); + const now = await this.generations(opts.source.name); if (now.active?.generation !== active.generation) return undefined; return client.execute({ sql: `SELECT * FROM ( @@ -566,7 +566,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (attempt >= SEARCH_ATTEMPTS) { throw notReady( "its source's index was switched while it searched", - `The active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + `The active generation of source '${opts.source.name}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, ); } return this.searchAttempt(query, opts, attempt + 1); @@ -576,7 +576,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return { chunkId: String(r.chunk_id), documentId: String(r.document_id), - sourceId: opts.source.id, + sourceId: opts.source.name, ...(r.source_record_id === null ? {} : { sourceRecordId: String(r.source_record_id) }), score: 1 - Number(r.distance), snippet: String(r.content), @@ -593,9 +593,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { async indexStatus(ctx: AdapterContext): Promise { const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); await this.ready(); - const { active, building } = await this.queued(client, () => this.generations(ctx.source.id)); + const { active, building } = await this.queued(client, () => this.generations(ctx.source.name)); const status: AdapterIndexStatus = {}; if (active?.fingerprint != null) status.fingerprint = active.fingerprint; if (active?.recipeHash != null) status.recipeHash = active.recipeHash; @@ -606,29 +606,29 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { async beginBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'beginBuild'); const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); const embedder = this.requireEmbedder(); await this.ready(); await this.queued(client, async () => { - const legacy = await this.hasLegacy(ctx.source.id); + const legacy = await this.hasLegacy(ctx.source.name); await this.transaction(async (tx) => { - const { active, building } = await this.generations(ctx.source.id, tx); + const { active, building } = await this.generations(ctx.source.name, tx); const fits = (g: GenerationRow | undefined) => g !== undefined && g.fingerprint === index.fingerprint && g.dim === embedder.dimensions; // Rebuilt inside the active generation, or the build under way taken up. if (fits(active) || fits(building)) return { commit: true, value: undefined }; if (building) { // A build of another fingerprint left unfinished: replaced, one per source. - await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.id, building.generation))}`); + await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.name, building.generation))}`); await tx.execute({ sql: `DELETE FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ?`, - args: [ctx.source.id, building.generation], + args: [ctx.source.name, building.generation], }); } // A source that holds nothing takes the fingerprint as its active one; // beside an active generation, or a legacy table, it is built aside. const state = active === undefined && !legacy ? 'active' : 'building'; - await this.openGeneration(tx, ctx.source.id, index.fingerprint, embedder, state); + await this.openGeneration(tx, ctx.source.name, index.fingerprint, embedder, state); return { commit: true, value: undefined }; }); }); @@ -637,37 +637,64 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { async completeBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'completeBuild'); const client = this.requireClient(); - assertSourceId(ctx.source.id); + assertSourceId(ctx.source.name); await this.ready(); await this.queued(client, async () => { - const legacy = await this.hasLegacy(ctx.source.id); + const legacy = await this.hasLegacy(ctx.source.name); await this.transaction(async (tx) => { - const { active, building } = await this.generations(ctx.source.id, tx); + const { active, building } = await this.generations(ctx.source.name, tx); const t = quoted(GENERATION_TABLE); if (building?.fingerprint === index.fingerprint) { if (active) { - await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.id, active.generation))}`); - await tx.execute({ sql: `DELETE FROM ${t} WHERE source_id = ? AND generation = ?`, args: [ctx.source.id, active.generation] }); + await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.name, active.generation))}`); + await tx.execute({ sql: `DELETE FROM ${t} WHERE source_id = ? AND generation = ?`, args: [ctx.source.name, active.generation] }); } await tx.execute({ sql: `UPDATE ${t} SET state = 'active', recipe_hash = ? WHERE source_id = ? AND generation = ?`, - args: [index.recipeHash, ctx.source.id, building.generation], + args: [index.recipeHash, ctx.source.name, building.generation], }); } else if (active?.fingerprint === index.fingerprint) { await tx.execute({ sql: `UPDATE ${t} SET recipe_hash = ? WHERE source_id = ? AND generation = ?`, - args: [index.recipeHash, ctx.source.id, active.generation], + args: [index.recipeHash, ctx.source.name, active.generation], }); } else { throw new Error( - `completeBuild: source '${ctx.source.id}' holds no generation for this fingerprint; call beginBuild first.`, + `completeBuild: source '${ctx.source.name}' holds no generation for this fingerprint; call beginBuild first.`, ); } // The table of the store's earlier releases goes once a generation is active. - if (legacy) await tx.execute(`DROP TABLE IF EXISTS ${quoted(legacyTable(ctx.source.id))}`); + if (legacy) await tx.execute(`DROP TABLE IF EXISTS ${quoted(legacyTable(ctx.source.name))}`); return { commit: true, value: undefined }; }); - if (legacy) this.noLegacy.add(ctx.source.id); + if (legacy) this.noLegacy.add(ctx.source.name); + }); + } + + /** + * Everything held for the source is removed (ADR-0161 K8, item 4), in one + * write transaction: the table and the row of each generation — the active + * one and one under construction — and the table of the store's earlier + * releases, when the source still has one. A source it holds nothing for is + * no error. + */ + async dropSource(ctx: AdapterContext): Promise { + const client = this.requireClient(); + const sourceId = ctx.source.name; + assertSourceId(sourceId); + await this.ready(); + await this.queued(client, async () => { + const legacy = await this.hasLegacy(sourceId); + await this.transaction(async (tx) => { + const { active, building } = await this.generations(sourceId, tx); + for (const g of [active, building]) { + if (g !== undefined) await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(sourceId, g.generation))}`); + } + await tx.execute({ sql: `DELETE FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ?`, args: [sourceId] }); + if (legacy) await tx.execute(`DROP TABLE IF EXISTS ${quoted(legacyTable(sourceId))}`); + return { commit: true, value: undefined }; + }); + if (legacy) this.noLegacy.add(sourceId); }); } @@ -839,7 +866,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { embedder: IEmbedder, create: boolean, ): Promise { - const sourceId = ctx.source.id; + const sourceId = ctx.source.name; const fingerprint = ctx.index?.fingerprint; const { active, building } = await this.generations(sourceId); const checked = (g: GenerationRow): GenerationRow => { diff --git a/packages/services/service-knowledge/README.md b/packages/services/service-knowledge/README.md index 68af2fab7d6..d6cb2162610 100644 --- a/packages/services/service-knowledge/README.md +++ b/packages/services/service-knowledge/README.md @@ -5,6 +5,35 @@ Orchestrator implementing `IKnowledgeService` over pluggable — that's the job of adapter plugins (`knowledge-memory`, `knowledge-pgvector`, `knowledge-turso`, …). +It loads the `knowledge_source` metadata items of the environment — a +`*.knowledge-source.ts` file in an app's `knowledgeSources` collection, or an +item saved in Studio or through MCP — builds each source's index, keeps it in +step with the records, reloads a source when its item changes and drops its +index when the item is removed. + +```ts +import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; +import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; + +kernel.use(new KnowledgeServicePlugin()); +kernel.use(new KnowledgeMemoryPlugin()); +``` + +```ts +// src/ai/task-notes.knowledge-source.ts +export const TaskNotes: KnowledgeSource = { + name: 'task_notes', + label: 'Task notes', + adapter: 'memory', + source: { kind: 'object', object: 'task', content: ['title', 'notes'] }, +}; +``` + +`new KnowledgeServicePlugin({ sources: [TaskNotes] })` and +`registerSource(TaskNotes)` register the same shape from code. A source +registered in code belongs to no package; a name the other door already holds +is refused. + See [Knowledge Protocol](https://objectstack.ai/docs/protocol/knowledge). ## License diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index 442d35e8028..a948b55d25f 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts @@ -402,3 +402,98 @@ describe('field gate — the title field is the object\'s display field', () => expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); }); }); + +// [ADR-0161 K4, guard two] The same gates, asked once for the AUTHOR when a +// `knowledge_source` item is saved: nobody builds an index over an object or +// a field they could not themselves search. +describe('admitAuthoredSource — source admission at save, as the authoring principal', () => { + const item = (object: string, content: string[], extra: Record = {}) => ({ + name: 'authored', label: 'Authored', adapter: 'memory', source: { kind: 'object', object, content, ...extra }, + }); + const sealed: ObjectDef = { ...TICKET, name: 'sealed', enable: { apiEnabled: false } }; + const getOnly: ObjectDef = { ...TICKET, name: 'get_only', enable: { apiMethods: ['get'] } }; + const sysClosed: ObjectDef = { ...TICKET, name: 'sys_closed_note' }; + const sysOpen: ObjectDef = { ...TICKET, name: 'sys_open_note', enable: { aiReadable: true } }; + + it('a field the author may not query is refused PERMISSION_DENIED / 403, naming the object and the field', async () => { + const { svc } = setup({ sources: [], security: salaryHiddenFromMembers }); + const verdict = await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MEMBER); + expect(verdict).toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, object: 'ticket', field: 'salary_note' }); + const message = (verdict as { message: string }).message; + expect(message).toContain('knowledge source "authored" was not saved'); + expect(message).toContain("field 'salary_note' of object 'ticket'"); + expect(message).toContain('Remove the field from `content` and `metadataFields`'); + // The same source, by an author who may query the field, and by the engine itself. + expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), MANAGER)).toEqual({ admitted: true }); + expect(await svc.admitAuthoredSource(item('ticket', ['body', 'salary_note']), SYSTEM)).toEqual({ admitted: true }); + }); + + it('a `metadataFields` member, and the retired `contentFields` spelling, are judged as the fields they index', async () => { + const { svc } = setup({ sources: [], security: salaryHiddenFromMembers }); + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { metadataFields: ['salary_note'] }), MEMBER)) + .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, field: 'salary_note' }); + const retired = { name: 'authored', label: 'A', adapter: 'memory', source: { kind: 'object', object: 'ticket', contentFields: ['salary_note'] } }; + expect(await svc.admitAuthoredSource(retired, MEMBER)) + .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, field: 'salary_note' }); + }); + + it("the object's display field is indexed as the title: an author who may not query it is refused though the source does not list it", async () => { + const hideTitle = makeSecurity(() => ['id', 'body', 'salary_note', 'status']); + const { svc } = setup({ sources: [], security: hideTitle }); + const verdict = await svc.admitAuthoredSource(item('ticket', ['body']), MEMBER); + expect(verdict).toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, field: 'title' }); + expect((verdict as { message: string }).message).toContain("display field"); + }); + + it.each([ + ['an object of a disabled package', { objects: [TICKET], disabled: ['ticket'] }, 'ticket', 'disabled package'], + ['an object the API does not serve at all', { objects: [sealed] }, 'sealed', 'does not serve object'], + ['an object whose `apiMethods` do not grant `search`', { objects: [getOnly] }, 'get_only', 'does not serve object'], + ['a system object without `enable.aiReadable`', { objects: [sysClosed] }, 'sys_closed_note', 'does not opt into AI reads'], + ])('%s is refused PERMISSION_DENIED / 403, naming the object', async (_label, opts, object, said) => { + const { svc } = setup({ sources: [], ...opts }); + const verdict = await svc.admitAuthoredSource(item(object, ['body']), MANAGER); + expect(verdict).toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, object }); + expect((verdict as { message: string }).message).toContain(`'${object}'`); + expect((verdict as { message: string }).message).toContain(said); + // The engine's own write is admitted: a package install is judged at validate and publish. + expect(await svc.admitAuthoredSource(item(object, ['body']), SYSTEM)).toEqual({ admitted: true }); + }); + + it('CONTROL: a served object, and a system object that opts into AI reads, are admitted', async () => { + const { svc } = setup({ sources: [], objects: [TICKET, sysOpen] }); + expect(await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({ admitted: true }); + expect(await svc.admitAuthoredSource(item('sys_open_note', ['body']), MANAGER)).toEqual({ admitted: true }); + }); + + it('fails closed, SERVICE_UNAVAILABLE / 503: a gate that throws, a security service that answers neither question, no data engine', async () => { + const thrown = setup({ sources: [], schemaThrows: true, logger: { warn: vi.fn(), error: vi.fn() } }); + expect(await thrown.svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)) + .toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503, object: 'ticket' }); + + const mute: KnowledgeFieldSecurity = { getQueryableFields: async () => undefined, getReadableFields: async () => undefined }; + const unanswered = setup({ sources: [], security: mute }); + expect(await unanswered.svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)) + .toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 }); + + const noEngine = new KnowledgeService({}); + expect(await noEngine.admitAuthoredSource(item('ticket', ['body']), MANAGER)) + .toMatchObject({ admitted: false, code: 'SERVICE_UNAVAILABLE', status: 503 }); + }); + + it('a save that carries no identity is refused; an item naming no object is left to the parse', async () => { + const { svc } = setup({ sources: [] }); + expect(await svc.admitAuthoredSource(item('ticket', ['body']), undefined)) + .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403 }); + for (const shapeless of [null, {}, { name: 'x' }, { name: 'x', source: { kind: 'object' } }, { name: 'x', source: 'ticket' }]) { + expect(await svc.admitAuthoredSource(shapeless, MANAGER), JSON.stringify(shapeless)).toEqual({ admitted: true }); + } + }); + + it('registers nothing and searches nothing: the verdict is a read', async () => { + const { svc, adapter } = setup({ sources: [], security: salaryHiddenFromMembers }); + await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER); + expect(svc.listSources()).toEqual([]); + expect(adapter.searchSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 6a92b5b9f59..b3274e58ac5 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -46,6 +46,7 @@ import { admitSourceFields, declaredFields, documentTitleField, + type KnowledgeAdmissionDeps, type KnowledgeFieldSecurity, type KnowledgeSourceAdmission, type ObjectAdmission, @@ -2098,15 +2099,7 @@ export class KnowledgeService implements IKnowledgeService { } return []; } - const deps = { - readSchema: (object: string): unknown => { - const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; - return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; - }, - isObjectPackageDisabled: (object: string): boolean => - registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), - resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), - }; + const deps = this.admissionDeps(engine); const byObject = new Map>(); for (const source of sources) { const object = source.source.object; @@ -2139,6 +2132,131 @@ export class KnowledgeService implements IKnowledgeService { return this.scopeByOrganization(out, ctx); } + /** What the source-admission gates read of the engine and the security service. */ + private admissionDeps(engine: IDataEngine): KnowledgeAdmissionDeps { + return { + readSchema: (object: string): unknown => { + const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; + return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; + }, + isObjectPackageDisabled: (object: string): boolean => + registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), + resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), + }; + } + + /** + * [ADR-0161 K4, guard two] Source admission at save: may `ctx`, the author + * saving this `knowledge_source` item, themselves search what it would + * index? The gates a search asks per caller ({@link admitSources}: the + * object's package is not disabled, the API serves the object for `search`, + * a system object opts into AI reads, every served field is queryable by + * the caller) are asked once for the author, before the item is written. + * Asked by every door that saves an item (`authoredKnowledgeSourceRefusal`, + * `@objectstack/metadata-core`), never by the metadata protocol. + * + * `item` is the body as the door hands it to the protocol, not yet parsed. + * What is read of it is `source.object`, `source.content` and + * `source.metadataFields` (and `source.contentFields`, the spelling the + * ADR-0087 kit renames to `content`, so a converted save is judged on the + * fields it will index). An item with no object to judge is admitted here: + * the protocol's parse refuses it with the schema's own prescription. + * + * A refusal is coded (ADR-0112) and names the object, and the field for the + * field gate: `403 PERMISSION_DENIED`. Fails closed: with no data engine, a + * gate that throws, or a security service that answers neither field + * question, the save is refused `503 SERVICE_UNAVAILABLE`. The system + * context is admitted, as it bypasses the gates at search. + */ + async admitAuthoredSource( + item: unknown, + ctx: ExecutionContext | undefined, + ): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { + if (ctx?.isSystem) return { admitted: true }; + const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; + const declared = body.source as + | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown } + | null + | undefined; + const object = declared && typeof declared === 'object' ? declared.object : undefined; + if (typeof object !== 'string' || object === '') return { admitted: true }; + const names = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; + const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown }; + const objSource: ObjectKnowledgeSource = { + kind: 'object', + object, + content: [...names(listed.content), ...names(listed.contentFields)], + metadataFields: names(listed.metadataFields), + }; + const named = `The knowledge source${describeName(body)} was not saved`; + const refuse = (status: number, code: string, message: string, field?: string) => + ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); + const unavailable = (why: string) => + refuse( + 503, + 'SERVICE_UNAVAILABLE', + `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + + 'allowed to search what their source indexes. Nothing was written; try again.', + ); + if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: the save carries no identity, and a missing identity is not a grant of authority.`); + const engine = this.options.dataEngine; + if (!engine) return unavailable('the knowledge service has no data engine'); + + let admission: ObjectAdmission; + try { + admission = await admitObject(object, ctx, this.admissionDeps(engine)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + const verdict: KnowledgeSourceAdmission = admission.refused + ? { admitted: false, reason: admission.refused, object } + : admitSourceFields(objSource, admission); + if (verdict.admitted) return { admitted: true }; + switch (verdict.reason) { + case 'object-package-disabled': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: its object '${object}' belongs to a disabled package, and a disabled package's records are ` + + 'not indexed or searched. Enable the package, or index another object.', + ); + case 'object-api-not-served': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, or ` + + "its `enable.apiMethods` list does not include `search`), and a knowledge search is a search over the " + + "object's records. Serve the object for `search`, or index another object.", + ); + case 'system-object-not-ai-readable': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: '${object}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), ` + + 'so its records are not indexed for retrieval.', + ); + case 'field-not-queryable': { + const field = verdict.field ?? ''; + const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + + 'to you masked), and the index would hold its text unmasked. ' + + (listedByAuthor + ? 'Remove the field from `content` and `metadataFields`, or have someone who may query it save the source.' + : "The source does not list it: it is the object's display field, which every document carries as its " + + 'title. Have someone who may query it save the source.'), + field, + ); + } + default: + return unavailable(`the security service did not answer which fields of '${object}' you may read`); + } + } + /** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ private reportGateFailure(object: string, err: Error): void { const report = From 008030a9c5c050c76680fb952f0afb5f38f34d85 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:11:11 +0000 Subject: [PATCH 06/29] feat(objectql): say once at boot that knowledge sources have no knowledge service A deployment that holds knowledge_source items and mounts no knowledge service is valid and inert: one warn line names the items. The type joins the package-scoped read types and the namespace co-owner tests. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../src/knowledge-source-unserved.test.ts | 83 ++++++++++++++ .../objectql/src/knowledge-source-unserved.ts | 101 ++++++++++++++++++ ...st-service-residual-namespace-name.test.ts | 2 + .../src/package-scoped-e8-readers.test.ts | 4 +- .../objectql/src/plugin.integration.test.ts | 6 +- packages/objectql/src/plugin.ts | 5 + .../registry-namespace-co-owner-names.test.ts | 5 +- 7 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 packages/objectql/src/knowledge-source-unserved.test.ts create mode 100644 packages/objectql/src/knowledge-source-unserved.ts diff --git a/packages/objectql/src/knowledge-source-unserved.test.ts b/packages/objectql/src/knowledge-source-unserved.test.ts new file mode 100644 index 00000000000..fc722ca8890 --- /dev/null +++ b/packages/objectql/src/knowledge-source-unserved.test.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import { + UNSERVED_KNOWLEDGE_SOURCES_NAMED, + announceUnservedKnowledgeSources, + describeUnservedKnowledgeSources, +} from './knowledge-source-unserved.js'; + +describe('describeUnservedKnowledgeSources — items with no knowledge service (ADR-0161 K4, ADR-0078)', () => { + it('says nothing when a knowledge service is registered, or when no item is held', () => { + expect(describeUnservedKnowledgeSources(['faq'], true)).toBeNull(); + expect(describeUnservedKnowledgeSources([], false)).toBeNull(); + }); + + it('names the item, the missing service and both remedies', () => { + const line = describeUnservedKnowledgeSources(['faq'], false)!; + expect(line).toContain("1 knowledge_source item ('faq')"); + expect(line).toContain("no 'knowledge' service is registered"); + expect(line).toContain('it is loaded, indexed or searched'); + expect(line).toContain('@objectstack/service-knowledge'); + expect(line).toContain('or remove the item.'); + }); + + it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => { + const names = ['g', 'f', 'e', 'd', 'c', 'b', 'a', 'a']; + const line = describeUnservedKnowledgeSources(names, false)!; + expect(line).toContain("8 knowledge_source items ('a', 'b', 'c', 'd', 'e', and 2 more)"); + expect(line).toContain('none is loaded'); + }); +}); + +describe('announceUnservedKnowledgeSources — once, at warn, never a refusal', () => { + const host = (services: Record) => { + const warn = vi.fn(); + return { + warn, + host: { + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no service ${name}`); + }, + logger: { warn }, + }, + }; + }; + const protocolWith = (items: unknown) => ({ getMetaItemsForExecution: vi.fn(async () => items) }); + + it('warns once, naming every published item, when no knowledge service is registered', async () => { + const protocol = protocolWith({ items: [{ name: 'faq' }, { item: { name: 'notes', _packageId: 'com.acme.kb' } }] }); + const h = host({ protocol }); + await announceUnservedKnowledgeSources(h.host); + expect(protocol.getMetaItemsForExecution).toHaveBeenCalledWith({ type: 'knowledge_source' }); + expect(h.warn).toHaveBeenCalledTimes(1); + expect(String(h.warn.mock.calls[0][0])).toContain("2 knowledge_source items ('faq', 'notes')"); + }); + + it('reads nothing and says nothing when a knowledge service is registered', async () => { + const protocol = protocolWith([{ name: 'faq' }]); + const h = host({ protocol, knowledge: {} }); + await announceUnservedKnowledgeSources(h.host); + expect(protocol.getMetaItemsForExecution).not.toHaveBeenCalled(); + expect(h.warn).not.toHaveBeenCalled(); + }); + + it('says nothing when no item is held, when there is no protocol, and when the listing cannot be read', async () => { + const empty = host({ protocol: protocolWith({ items: [] }) }); + await announceUnservedKnowledgeSources(empty.host); + const none = host({}); + await announceUnservedKnowledgeSources(none.host); + const failing = host({ protocol: { getMetaItemsForExecution: async () => { throw new Error('store offline'); } } }); + await expect(announceUnservedKnowledgeSources(failing.host)).resolves.toBeUndefined(); + for (const h of [empty, none, failing]) expect(h.warn).not.toHaveBeenCalled(); + }); + + it('falls back to getMetaItems where the protocol has no execution read', async () => { + const getMetaItems = vi.fn(async () => [{ name: 'faq' }]); + const h = host({ protocol: { getMetaItems } }); + await announceUnservedKnowledgeSources(h.host); + expect(getMetaItems).toHaveBeenCalledWith({ type: 'knowledge_source' }); + expect(h.warn).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/objectql/src/knowledge-source-unserved.ts b/packages/objectql/src/knowledge-source-unserved.ts new file mode 100644 index 00000000000..073c6142ba0 --- /dev/null +++ b/packages/objectql/src/knowledge-source-unserved.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4 · ADR-0078] A deployment that holds `knowledge_source` items + * and mounts no knowledge service says so once at boot. + * + * A `knowledge_source` item is loaded by its one reader, the knowledge + * service's plugin (`@objectstack/service-knowledge`). Where that plugin is + * not in the composition the item still parses, publishes and is listed in + * Studio, and nothing indexes or searches it: the valid-and-inert shape + * ADR-0078 says must be loud. The reader cannot say so itself — it is the + * thing that is missing — so the plugin that serves the metadata protocol + * does, beside the same statement for `queues` and `assignmentRules` + * (`describeMissingOwnershipQueueService`). + * + * A statement at `warn`, never a boot refusal: a package may ship a source to + * a deployment that chose not to run retrieval, and its objects, pages and + * flows must keep serving there. + */ + +import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; + +/** The metadata type of a knowledge source. */ +const KNOWLEDGE_SOURCE_TYPE = 'knowledge_source'; + +/** How many item names the statement spells out before it counts the rest. */ +export const UNSERVED_KNOWLEDGE_SOURCES_NAMED = 5; + +/** + * The statement for `names` (the published `knowledge_source` items), or + * `null` when there is nothing to say: no item, or a knowledge service is + * registered. + */ +export function describeUnservedKnowledgeSources(names: readonly string[], serviceRegistered: boolean): string | null { + if (serviceRegistered || names.length === 0) return null; + const distinct = [...new Set(names)].sort(); + const shown = distinct.slice(0, UNSERVED_KNOWLEDGE_SOURCES_NAMED).map((name) => `'${name}'`).join(', '); + const rest = distinct.length - Math.min(distinct.length, UNSERVED_KNOWLEDGE_SOURCES_NAMED); + const count = names.length; + return ( + `[ObjectQLPlugin] this deployment holds ${count} knowledge_source ${count === 1 ? 'item' : 'items'} ` + + `(${shown}${rest > 0 ? `, and ${rest} more` : ''}), but no '${KNOWLEDGE_SERVICE}' service is registered, so ` + + `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. Add KnowledgeServicePlugin ` + + '(@objectstack/service-knowledge) and a knowledge adapter to the composition, or remove the ' + + `${count === 1 ? 'item' : 'items'}.` + ); +} + +/** What {@link announceUnservedKnowledgeSources} reads of its host. */ +export interface UnservedKnowledgeSourcesHost { + /** Resolve a kernel service by name; throws or answers nothing when none is registered. */ + getService(name: string): unknown; + logger?: { warn?: (message: string) => void }; +} + +/** + * Read the published `knowledge_source` items through the metadata protocol + * and say {@link describeUnservedKnowledgeSources} at `warn`. Called once, at + * `kernel:bootstrapped`: every plugin has registered its services and every + * package of the boot is registered, so "no knowledge service" and the item + * list are both final. Never throws; a listing that cannot be read says + * nothing. + */ +export async function announceUnservedKnowledgeSources(host: UnservedKnowledgeSourcesHost): Promise { + const service = (name: string): unknown => { + try { + return host.getService(name) ?? undefined; + } catch { + return undefined; + } + }; + if (service(KNOWLEDGE_SERVICE) !== undefined) return; + const protocol = service('protocol') as + | { + getMetaItemsForExecution?(request: { type: string }): Promise; + getMetaItems?(request: { type: string }): Promise; + } + | undefined; + const read = typeof protocol?.getMetaItemsForExecution === 'function' + ? protocol.getMetaItemsForExecution.bind(protocol) + : typeof protocol?.getMetaItems === 'function' + ? protocol.getMetaItems.bind(protocol) + : undefined; + if (!read) return; + let raw: unknown; + try { + raw = await read({ type: KNOWLEDGE_SOURCE_TYPE }); + } catch { + return; + } + const list = Array.isArray(raw) ? raw : (raw as { items?: unknown } | null | undefined)?.items; + if (!Array.isArray(list)) return; + const names: string[] = []; + for (const entry of list) { + const doc = entry && typeof entry === 'object' && 'item' in entry ? (entry as { item: unknown }).item : entry; + const name = (doc as { name?: unknown } | null | undefined)?.name; + if (typeof name === 'string' && name !== '') names.push(name); + } + const statement = describeUnservedKnowledgeSources(names, false); + if (statement) host.logger?.warn?.(statement); +} diff --git a/packages/objectql/src/manifest-service-residual-namespace-name.test.ts b/packages/objectql/src/manifest-service-residual-namespace-name.test.ts index b08752c54c3..8893c32e7ba 100644 --- a/packages/objectql/src/manifest-service-residual-namespace-name.test.ts +++ b/packages/objectql/src/manifest-service-residual-namespace-name.test.ts @@ -71,6 +71,8 @@ const item = (type: NamespaceUniqueType, name: string, tag: string): Record !(BARE_NAME_REGISTRY_TYPES as readonly string[]).includes(t)); diff --git a/packages/objectql/src/plugin.integration.test.ts b/packages/objectql/src/plugin.integration.test.ts index c43a66c154d..e9a067a5c6f 100644 --- a/packages/objectql/src/plugin.integration.test.ts +++ b/packages/objectql/src/plugin.integration.test.ts @@ -1115,7 +1115,9 @@ describe('ObjectQLPlugin - Metadata Service Integration', () => { // sys_metadata. The only permitted boot reads are the runtime-authored // re-syncs: hooks (#2588, type='hook') and actions (#2605 — // type='action' plus type='object' rows scanned ONLY to extract their - // embedded `actions[]`). Neither registers objects — the registry + // embedded `actions[]`), and the one read behind the boot notice for + // knowledge sources no knowledge service loads (#37304, + // type='knowledge_source'). None registers objects — the registry // assertion below pins that. const findCalls: Array<{ object: string; query?: any }> = []; await kernel.use({ @@ -1132,7 +1134,7 @@ describe('ObjectQLPlugin - Metadata Service Integration', () => { const metaReads = findCalls.filter((c) => c.object === 'sys_metadata'); for (const read of metaReads) { - expect(read.query?.where?.type).toMatch(/^(hooks?|actions?|object)$/); + expect(read.query?.where?.type).toMatch(/^(hooks?|actions?|object|knowledge_sources?|knowledgeSources)$/); } const registry = (kernel.getService('objectql') as any).registry; expect(registry.getObject('product')).toBeUndefined(); diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 494776b097d..c8717fa8063 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -45,6 +45,7 @@ import { RecordCurrencyFollowRefusedError } from './record-currency-aggregate-do // [#22070] The builtin audit stamps are wrapped like a bound hook but registered in code. import { wrapDeclarativeHook } from './hook-wrappers.js'; import { announceStoredExpressionHoles } from './stored-expression-backfill.js'; +import { announceUnservedKnowledgeSources } from './knowledge-source-unserved.js'; import { announceSummaryHoles } from './summary-hole-announce.js'; import { LifecycleService } from './lifecycle/lifecycle-service.js'; import { WORK_CALENDAR_OBJECT, WorkCalendarService, installWorkCalendarHooks } from './work-calendar-service.js'; @@ -1480,6 +1481,10 @@ export class ObjectQLPlugin implements Plugin { // `os migrate summary-nulls`; a bounded sample read that writes nothing // and never fails the boot (`summary-hole-announce.ts`). if (this.ql) await announceSummaryHoles(this.ql, ctx.logger); + // [ADR-0161 K4 · ADR-0078] `knowledge_source` items with no knowledge + // service to load them are valid and inert: said once, at warn, never + // a boot refusal (`knowledge-source-unserved.ts`). + await announceUnservedKnowledgeSources({ getService: (name) => ctx.getService(name), logger: ctx.logger }); }); ctx.hook('metadata:reloaded', async (payload?: unknown) => { await this.resyncAuthoredHooks(ctx); diff --git a/packages/objectql/src/registry-namespace-co-owner-names.test.ts b/packages/objectql/src/registry-namespace-co-owner-names.test.ts index 24ad92e8d1f..f83f54964df 100644 --- a/packages/objectql/src/registry-namespace-co-owner-names.test.ts +++ b/packages/objectql/src/registry-namespace-co-owner-names.test.ts @@ -52,6 +52,7 @@ const COLLECTION: Record = { analytics_cube: 'analyticsCubes', tool: 'tools', ai_context: 'aiContexts', + knowledge_source: 'knowledgeSources', }; /** A package of namespace `ns` declaring `decl`'s items, each labelled with the package's last id segment. */ @@ -80,11 +81,12 @@ const install = (registry: SchemaRegistry, manifest: unknown, scope?: { packageI const fresh = (collisionPolicy: 'error' | 'warn' = 'error') => new SchemaRegistry({ multiTenant: false, collisionPolicy }); describe('the vocabulary', () => { - it('the twelve types, in ADR-0150 child N\'s order, then the context pack (the 2026-11-25 addendum)', () => { + it('the twelve types, in ADR-0150 child N\'s order, then the context pack and the knowledge source (the two 2026-11-25 addenda)', () => { expect(NAMESPACE_UNIQUE_TYPES).toEqual([ 'sharing_rule', 'queue', 'assignment_rule', 'hook', 'job', 'app', 'page', 'dashboard', 'report', 'book', 'analytics_cube', 'tool', 'ai_context', + 'knowledge_source', ]); }); @@ -118,6 +120,7 @@ describe('the vocabulary', () => { 'hook/hook_one', 'job/job_one', 'app/app_one', 'page/by_id', 'dashboard/dashboard_one', 'report/report_one', 'book/book_one', 'analytics_cube/analytics_cube_one', 'tool/tool_one', 'ai_context/ai_context_one', + 'knowledge_source/knowledge_source_one', 'app/inner', 'tool/inner_tool', ]); expect(spelt).not.toContain('app/nested_apps_entry'); From 6d0b8afe6174f1f860e37cb1d15906f380896265 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:11:11 +0000 Subject: [PATCH 07/29] =?UTF-8?q?docs(knowledge):=20knowledge=5Fsource=20a?= =?UTF-8?q?s=20metadata=20=E2=80=94=20showcase=20source,=20docs,=20skills?= =?UTF-8?q?=20rows,=20changeset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The showcase ships a task-notes source over the memory adapter. The protocol and RAG pages describe the type, its loader, who may author a source and one name per source. Generated references, the liveness ledger row and the changeset with its ADR-0087 registrations ride along. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../37304-knowledge-source-governed-type.md | 52 ++++ content/docs/ai/knowledge-rag.mdx | 68 +++-- .../docs/getting-started/quick-reference.mdx | 3 +- content/docs/protocol/knowledge.mdx | 284 +++++++++++------- content/docs/references/ai/embedding.mdx | 90 ------ content/docs/references/ai/index.mdx | 3 +- .../docs/references/ai/knowledge-document.mdx | 2 +- .../docs/references/ai/knowledge-source.mdx | 173 +++-------- content/docs/references/ai/meta.json | 1 - content/docs/references/api/metadata.mdx | 5 +- .../references/api/package-api-assembled.mdx | 2 + content/docs/references/index.mdx | 11 +- .../references/kernel/metadata-plugin.mdx | 6 +- .../ai.md | 2 +- examples/app-showcase/objectstack.config.ts | 13 +- examples/app-showcase/package.json | 2 + examples/app-showcase/src/ai/index.ts | 1 + .../src/ai/task-notes.knowledge-source.ts | 38 +++ examples/app-showcase/src/coverage.ts | 6 + .../test/expression-conformance.ledger.ts | 14 +- packages/spec/api-surface/ai.json | 12 - packages/spec/declaration-map/ai.json | 14 +- packages/spec/export-origins/ai.json | 12 - packages/spec/liveness/README.md | 3 +- packages/spec/liveness/knowledge_source.json | 150 +++++++++ .../liveness/state-counts/knowledge_source.md | 15 + .../spec/scripts/liveness/check-liveness.mts | 2 +- .../meta-spelling/meta-url-data.generated.ts | 3 + packages/spec/src/shared/expression.zod.ts | 14 +- pnpm-lock.yaml | 6 + skills/objectstack-ai/SKILL.md | 4 +- skills/objectstack-ai/references/_index.md | 3 +- skills/objectstack-platform/SKILL.md | 6 +- 33 files changed, 588 insertions(+), 432 deletions(-) create mode 100644 .changeset/37304-knowledge-source-governed-type.md delete mode 100644 content/docs/references/ai/embedding.mdx create mode 100644 examples/app-showcase/src/ai/task-notes.knowledge-source.ts create mode 100644 packages/spec/liveness/knowledge_source.json create mode 100644 packages/spec/liveness/state-counts/knowledge_source.md diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md new file mode 100644 index 00000000000..cc250dd3cb2 --- /dev/null +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -0,0 +1,52 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/knowledge-memory': minor +'@objectstack/knowledge-pgvector': minor +'@objectstack/knowledge-turso': minor +'@objectstack/metadata-core': minor +'@objectstack/rest': minor +'@objectstack/runtime': minor +'@objectstack/objectql': minor +'@objectstack/core': patch +'@objectstack/metadata': patch +'@objectstack/cli': patch +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +'@object-ui/fields': patch +--- + +feat(spec)!: a knowledge source is a governed metadata type, `knowledge_source`, loaded by the knowledge service + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed +Skills-docs: `skills/objectstack-platform/SKILL.md` lists the new top-level key `knowledgeSources`; `skills/objectstack-ai/SKILL.md`'s compiled `supportKb` example writes `name` and `content`. Teaching the type in `skills/objectstack-ai` is a later change. + + + +ADR-0161 K4, K5, K6 and K8 item 4 (#37304). + +**BREAKING.** A knowledge source written for 18 is refused at parse until it is moved. `os migrate meta --from 18` lists every edit and `--write` applies the ones it can prove. + +| Wrote (18) | Write instead (19) | +|:--|:--| +| `id: 'support_kb'` | `name: 'support_kb'` (the value is unchanged, so the index is found again and nothing is rebuilt) | +| `source.contentFields: ['title', 'body']` | `source.content: ['title', 'body']` | +| `contentFields: ['*']` | `content` with every field named (a hand edit: only the author knows which fields may leave the row store) | +| `embedding`, `vectorStore`, `adapterConfig`, `refresh.cron` | delete the key: nothing read it | +| `source.kind: 'file'` or `'http'`, with `prefix`, `mimeTypes`, `urls`, `userAgent` | a source indexes the records of one object (`kind: 'object'`); a file or URL source has no replacement | +| `knowledge.indexDocument(…)`, `knowledge.deleteDocument(…)` | no call: the service builds every document from the records a source selects; `reindexSource` rebuilds a source | +| `KnowledgeServicePlugin({ sources: [{ id, … }] })`, `registerSource({ id, … })` | the same call with the 19 shape, or the source shipped as metadata in the stack's `knowledgeSources` | + +What changes: + +- **The type.** `knowledge_source` is registered in the metadata type registry with the one schema `KnowledgeSourceSchema`; a stack carries its sources in the new top-level collection `knowledgeSources`, in `*.knowledge-source.ts` or `.yml` files. An item can be created and changed at run time (Studio, MCP); it takes no environment overlay. Studio's menu lists the type. Two packages may each ship a source of one name (ADR-0150, addendum of 2026-11-25): each has its own index, and `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. +- **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. +- **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. +- **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. +- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. +- **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached refuses `503`. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. +- **One name, one source.** `KnowledgeServicePlugin({ sources })` and `registerSource` stay a door for the same schema and parse with it: a retired key is refused with its prescription (`400 VALIDATION_ERROR`), not converted. A source registered in code belongs to no package. It shares one slot with an environment-authored item of the same name, and the second of the two to arrive is refused `409 RESOURCE_CONFLICT`, naming both doors; a metadata item reloading its own earlier version is not a second arrival. +- **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed, with the `file` / `http` branches that served them. They are runtime-interface-only members with no metadata form, so the compiler reports each call (`TS2339`). +- **Removed exports.** `EmbeddingModelSchema`, `VectorStoreSchema` and the rest of `@objectstack/spec/ai`'s `embedding` module leave with `embedding` and `vectorStore`: the knowledge source was their only composer. +- **CLI.** `os knowledge status` prints the package that holds a source and no longer prints a source kind. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 0ae7c592b16..41af9e29141 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -14,41 +14,63 @@ ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable bac ## Wiring +A knowledge source is a metadata item: a `*.knowledge-source.ts` file in your +app, listed under `knowledgeSources`. It says which object's records to +index, which fields become searchable text, and which adapter holds the index. + ```ts -import { ObjectKernel } from '@objectstack/core'; +// src/ai/task-notes.knowledge-source.ts +import type { KnowledgeSource } from '@objectstack/spec/ai'; + +export const TaskNotes: KnowledgeSource = { + name: 'task_notes', + label: 'Task notes', + adapter: 'memory', // 'pgvector' or 'turso' in production + source: { kind: 'object', object: 'task', content: ['title', 'notes'] }, +}; +``` + +```ts +// objectstack.config.ts +import { defineStack } from '@objectstack/spec'; import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; // or, for prod (PostgreSQL + pgvector; a libSQL file is `@objectstack/knowledge-turso`): // import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector'; +import { TaskNotes } from './src/ai/task-notes.knowledge-source.js'; -const kernel = new ObjectKernel(); -kernel.use(new KnowledgeServicePlugin({ - sources: [ - { - id: 'task_notes', - label: 'Task notes', - adapter: 'memory', - source: { kind: 'object', object: 'task', contentFields: ['title', 'notes'] }, - }, - { - id: 'product_docs', - label: 'Product docs', - adapter: 'memory', // 'pgvector' once KnowledgePgvectorPlugin is registered below - source: { kind: 'object', object: 'product_doc', contentFields: ['title', 'body'] }, - }, +export default defineStack({ + plugins: [ + new KnowledgeServicePlugin(), + new KnowledgeMemoryPlugin(), + // new KnowledgePgvectorPlugin(), ], -})); -kernel.use(new KnowledgeMemoryPlugin()); -// kernel.use(new KnowledgePgvectorPlugin()); + knowledgeSources: [TaskNotes], + // … +}); ``` +The knowledge service loads the source when it starts, runs its first build, +and keeps the index in step with the records. There is no registration call +to write. + +- **`content` lists its fields by name.** What is listed is what leaves the row store: the text of those fields is sent to the embedder and kept in the index. `'*'` is refused, and a field added to the object later is not indexed until you add it here. +- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart: a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. +- **Authoring one needs `manage_knowledge_sources`** beside `manage_metadata` — platform administrators hold it by default — and the author must themselves be allowed to search the object and query every listed field, or the save is refused naming what they may not read. +- **Two packages may each ship a source of the same name.** `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. +- **Registering in code still works**: `new KnowledgeServicePlugin({ sources: [TaskNotes] })` or `knowledge.registerSource(TaskNotes)` takes the same shape. A source registered in code and an item saved under the same name are one name: the second to arrive is refused. + + +**Upgrading from 18.** `id` is now `name` and `source.contentFields` is `source.content` (run `os migrate meta --from 18`); a `'*'` member must be replaced with the field names; `embedding`, `vectorStore`, `adapterConfig` and `refresh.cron` are removed, as are the `file` and `http` source kinds and `indexDocument` / `deleteDocument` on the service. Each retired key is refused with what to write instead. + + ## Retrieving knowledge Retrieval is a plain service call — no AI runtime required. Resolve the `knowledge` service and call `search`. Hits are re-checked against the caller's `ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come back. Because the re-check runs after ranking, for a caller other than the -system identity the service asks each object source for more hits than `topK`, +system identity the service asks each source for more hits than `topK`, and asks once more when too few records survive, so a caller who may read few of the matching records still gets up to `topK` hits ([the protocol](/docs/protocol/knowledge) gives the factors and the cap). A @@ -99,7 +121,7 @@ installed ([Connect an MCP Client](/docs/ai/connect-mcp)). ## Searching inside chosen records -Pass `scope` to search only inside some records: the records an object source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`. +Pass `scope` to search only inside some records: the records a source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`. ```ts // Only the clauses of one policy: the clause source lists its `policy` lookup in metadataFields. @@ -162,13 +184,13 @@ const vectors = await embedder.embed(chunks.map((c) => c.content)); ## Splitting documents into passages -The knowledge service cuts each document into passages once, and every adapter that takes passages (`knowledge-memory` does) indexes the same ones. An object source chooses how with `split`: +The knowledge service cuts each document into passages once, and every adapter that takes passages (`knowledge-memory` does) indexes the same ones. A source chooses how with `split`: ```ts source: { kind: 'object', object: 'policy', - contentFields: ['title', 'body'], + content: ['title', 'body'], split: { strategy: 'markdown', maxChars: 600 }, } ``` diff --git a/content/docs/getting-started/quick-reference.mdx b/content/docs/getting-started/quick-reference.mdx index 96f95843456..1410636fa19 100644 --- a/content/docs/getting-started/quick-reference.mdx +++ b/content/docs/getting-started/quick-reference.mdx @@ -117,8 +117,7 @@ AI/ML capabilities - agents, skills, tools, MCP exposure, RAG, and cost tracking | **[MCP](/docs/references/ai/mcp)** | `mcp.zod.ts` | MCPServerRef, MCPToolBinding | MCP server exposure and tool bindings | | **[Model Registry](/docs/references/ai/model-registry)** | `model-registry.zod.ts` | ModelRegistry, ModelProvider | LLM model management | | **[Conversation](/docs/references/ai/conversation)** | `conversation.zod.ts` | ConversationSession | Conversation management | -| **[Embedding](/docs/references/ai/embedding)** | `embedding.zod.ts` | EmbeddingModel, VectorStore | Embedding models and vector stores | -| **[Knowledge Source](/docs/references/ai/knowledge-source)** | `knowledge-source.zod.ts` | KnowledgeSource, KnowledgeRefreshPolicy | RAG ingestion sources | +| **[Knowledge Source](/docs/references/ai/knowledge-source)** | `knowledge-source.zod.ts` | KnowledgeSource, KnowledgeSplit | The `knowledge_source` metadata type: which records and fields the knowledge service indexes | | **[Knowledge Document](/docs/references/ai/knowledge-document)** | `knowledge-document.zod.ts` | KnowledgeDocument, KnowledgeChunk | RAG documents and chunks | | **[Usage](/docs/references/ai/usage)** | `usage.zod.ts` | AIUsageRecord, TokenUsage | AI usage and cost tracking | | **[Solution Blueprint](/docs/references/ai/solution-blueprint)** | `solution-blueprint.zod.ts` | BlueprintObject, BlueprintApp | Blueprint format for AI app generation | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 873a015dc72..fa69a9f4e33 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -106,53 +106,119 @@ any AI consumer.** ## 3. Protocol surface -### 3.1 `KnowledgeSource` (declarative metadata) +### 3.1 `KnowledgeSource` (the `knowledge_source` metadata type) -A `KnowledgeSource` describes *what* to index and *which adapter* to -use. It is stored as metadata (versioned, environment-scoped) just -like a view or a flow. +A knowledge source says *which records* to index, *which of their fields* +become searchable text, and *which adapter* holds the index. It is a governed +metadata type, `knowledge_source` (ADR-0161 K4): a package ships it as a +`*.knowledge-source.ts` (or `.yml`) file under the stack's `knowledgeSources` +collection, and an administrator creates or changes one at run time in Studio +or through MCP. It takes no environment overlay. -Three source kinds: +```typescript +// src/ai/kb-articles.knowledge-source.ts +import type { KnowledgeSource } from '@objectstack/spec/ai'; + +export const KbArticles: KnowledgeSource = { + name: 'kb_articles', // snake_case; with its package, the source's identity + label: 'Knowledge base', + adapter: 'pgvector', // the adapter id a plugin registered + source: { + kind: 'object', // the one kind + object: 'kb_article', + content: ['title', 'body'], // required, at least one, each field named + metadataFields: ['category', 'author'], // optional, carried onto the document + where: { status: 'published' }, // optional ObjectQL filter + split: { strategy: 'markdown', maxChars: 600 }, // optional; see 3.5 + }, +}; -| Kind | Origin | Example use case | -|----------|-----------------------------------------------------|---------------------------------| -| `object` | An ObjectQL object — each record becomes a document | Customer notes, KB articles | -| `file` | A folder in `IStorageService` | Onboarded PDFs, uploads | -| `http` | A list of remote URLs | External docs, RSS, sitemaps | +// objectstack.config.ts +defineStack({ knowledgeSources: [KbArticles], /* … */ }); +``` -`kind` is the discriminator, and each kind carries its own keys — a key from one -kind is rejected on another: +A source indexes the records of one object. Each matching record becomes a +document; `content` lists the fields whose text is the document body, in +order. -```typescript -// object — content comes from the named fields of each matching record -source: { - kind: 'object', - object: 'kb_article', - contentFields: ['title', 'body'], // at least one, required - metadataFields: ['category', 'author'], // optional, carried onto the document - where: { status: 'published' }, // optional ObjectQL filter - split: { strategy: 'markdown', maxChars: 600 }, // optional; see 3.5 -} - -// file — every object under a storage prefix -source: { - kind: 'file', - prefix: 'knowledge/handbook/', - mimeTypes: ['application/pdf', 'text/markdown'], // optional; omit to take all -} +**`content` lists its fields by name.** Embedding is egress: the text of every +listed field is sent to the embedder and kept in an index outside the row +store. So the list is explicit — `'*'` is refused at parse, with the +instruction to list the fields — and a field added to the object later is not +indexed until an author adds it here. Credential-class and `internal` fields +are never indexed, even when named. -// http — an explicit URL list (each must be a valid URL) -source: { - kind: 'http', - urls: ['https://docs.example.com/guide', 'https://docs.example.com/faq'], - userAgent: 'ObjectStack-KnowledgeBot/1.0', // optional -} -``` +**Every key has a reader, and an unknown key is refused**, never dropped. The +keys an earlier release declared and nothing read are refused with what to +write instead, and `os migrate meta --from 18` converts the mechanical ones: -Every source binds to a named **adapter id** (e.g. `'pgvector'`, -`'memory'`). The adapter id is resolved at runtime by the plugin that -registers itself with that name. Adapter config (endpoint, dataset id, -…) is passed through opaquely. +| Before 19 | Now | +|:--|:--| +| `id` | `name` (the value is unchanged, so the index is found again) | +| `source.contentFields` | `source.content` (a `'*'` member is replaced by hand with the field names) | +| `embedding`, `vectorStore` | removed: the embedder and the store are the deployment's, never a source's | +| `adapterConfig` | removed: an adapter takes its settings as options of the plugin that mounts it | +| `refresh.cron` | removed: nothing scheduled it | +| `source.kind: 'file'` / `'http'` with `prefix`, `mimeTypes`, `urls`, `userAgent` | removed: a source indexes an object's records | + +Every source binds to a named **adapter id** (e.g. `'pgvector'`, `'turso'`, +`'memory'`), resolved at run time to the plugin that registered itself under +that name. + +#### How a source is loaded + +The knowledge service reads the published `knowledge_source` items when it +starts and follows the type from then on, with no restart: + +- **Added** — the source is registered, its index status is read, and a build + that is due runs (§3.6). +- **Changed** — the source is registered again and its fingerprint and recipe + hash are read again: a changed `where` or `metadataFields` rebuilds inside + the same generation; a changed `content` list or `split` builds a new one. +- **Removed** — the source is unregistered and its index is dropped through + the adapter's `dropSource` (§3.4). Over an adapter without that member the + index is kept, and the service says so once in its log, naming the source. + +A deployment that holds a `knowledge_source` item but mounts no knowledge +service says so once at boot, naming the items: nothing loads, indexes or +searches them until `KnowledgeServicePlugin` and an adapter are mounted. + +#### Who may author one + +Saving a source starts an egress and, with a paid embedder, a bill. Two guards +stand at every door that writes one — Studio / REST `/meta`, the dispatcher, +and the MCP draft door: + +1. **A capability of its own.** Creating, changing, publishing, rolling back + or deleting a `knowledge_source` needs `manage_knowledge_sources` **beside** + `manage_metadata`. Platform administrators hold it by default; nobody else + does until it is granted. A grant on the indexed object's records does not + imply it. Over MCP it is the human's own grant that is read, never the + agent's. +2. **Source admission at save.** A source is saved only when its author may + themselves search what it would index. The save asks the same gates a + search asks ([Source admission](#source-admission-exposure-and-field-level-rules)) + as the author: an object of a disabled package, an object the API does not + serve for `search`, a system object without `enable.aiReadable`, or a field + the author may not query refuses the save `403`, naming the object or the + field. A verdict that cannot be reached refuses `503`; nothing is written. + +#### One name, one source + +A source is identified by the package that ships it and its `name` +(ADR-0150): two packages may each ship a source of one name, and each has its +own index. Where the name crosses the AI face — the `sources` list +`search_knowledge` answers, its `sourceIds` argument, and the `sourceId` of a +hit — a package's source is spelled `NAMESPACE-NAME` and a source no package +holds keeps its bare name. + +`KnowledgeServicePlugin({ sources })` and `IKnowledgeService.registerSource` +stay a door for the same schema: a registration in code is parsed by it (a +retired key is refused with its prescription, never converted), belongs to no +package, and takes a bare name. A name is one source, whichever door it came +through: a code registration and an environment-authored item of one name are +the same slot, and the second to arrive is refused `409`, naming both doors. A +metadata item reloading its own earlier version is not a second arrival. ### 3.2 `KnowledgeDocument`, `KnowledgeChunk`, `KnowledgeHit` @@ -163,20 +229,18 @@ Canonical shapes shared by every adapter: `organizationId?`, `docHash?`). `organizationId` is the organization of the record the document was assembled from: the service sets it from the record's `organization_id` under a walled tenancy posture (`group` or - `isolated`), and leaves it absent under `single`, for `file` / `http` - sources and for a record with no organization — see + `isolated`), and leaves it absent under `single` and for a record with no + organization — see [Organization scope](#organization-scope). `docHash` is a hash of the assembled document — content, title and metadata, and the organization when the document has one, in a stable key order, behind a version prefix - (`v1:`). The service computes both on every document it hands an adapter, - and `indexDocument` refuses a document that already carries either; the - adapter stores them and returns `docHash` as stored, and never computes or - alters either. + (`v1:`). The service computes both on every document it hands an adapter; + the adapter stores them and returns `docHash` as stored, and never computes + or alters either. - `KnowledgeDocument.chunks?` — the document's passages, cut by the service's splitter (see [3.5 The split](#35-the-split)). Set by the service, and only on a document handed to an adapter that declares - `capabilities.chunks`; `indexDocument` refuses a document that already - carries them. Derived from `content`, so not part of `docHash`. + `capabilities.chunks`. Derived from `content`, so not part of `docHash`. - `KnowledgeChunk` — one passage: `id` (the service sets it to `${documentId}#${index}`, so a hit's `chunkId` is the same on every adapter), `documentId`, `index`, `content` (what the adapter embeds and returns as a @@ -198,16 +262,16 @@ read. **A hit that the user could not have queried directly is never returned.** The re-check runs after ranking, so the service asks for more than it -answers. For a caller who is not the system identity, each `object` -source is asked for `topK × 5` hits. When the hits that survive the +answers. For a caller who is not the system identity, each source is asked +for `topK × 5` hits. When the hits that survive the re-check name fewer than `topK` records (several passages of one record -count once), every `object` source that answered as many hits as it was +count once), every source that answered as many hits as it was asked is asked once more, for `topK × 20`. That is the cap: a caller who may read fewer than `topK` of the rows within the cap gets fewer than `topK` hits. An adapter that answers fewer than it was asked (one that caps `topK`) is not -asked again. A `file` or `http` source is asked for `topK` once, and so is -every source for the system identity. The answer is at most `topK` hits. +asked again. For the system identity every source is asked for `topK` +once. The answer is at most `topK` hits. How many hits the re-check removed is logged at `debug`, never returned to the caller. @@ -219,8 +283,7 @@ passages of one record can take several of the `topK` places. With best-scoring passage, and `topK` counts records. Every source is then asked for `topK × 5` passages, for every caller, and refilled once at `topK × 20` when fewer than `topK` records survive; that is the cap, and fewer records -within it means fewer hits, logged at `debug`. A `file` or `http` hit is -grouped by its document. +within it means fewer hits, logged at `debug`. `groupBy` names a metadata field and groups by its value instead — "which policies", not "which clauses" — with the best hit of each group and the @@ -266,15 +329,13 @@ interface IKnowledgeService { getAdapter(id: string): IKnowledgeAdapter; listAdapters(): string[]; - // Sources + // Sources — registration in code; a metadata item is loaded by the service registerSource(source: KnowledgeSource): void; unregisterSource(sourceId: string): void; listSources(): KnowledgeSource[]; getSource(sourceId: string): KnowledgeSource | undefined; - // Documents - indexDocument(sourceId: string, doc: KnowledgeDocument): Promise; - deleteDocument(sourceId: string, documentId: string): Promise; + // Index reindexSource(sourceId: string, opts?: KnowledgeReindexOptions): Promise; // Search @@ -282,6 +343,14 @@ interface IKnowledgeService { } ``` +A `sourceId` is the name the AI face spells: a bare name for a source no +package holds, `NAMESPACE-NAME` for a package's. A bare name that only +packages hold resolves to the one package's source when one holds it, and is +refused `409`, naming the candidates, when several do. There is no push door: +the service builds every document itself, from the records a source selects — +`indexDocument` and `deleteDocument` left the contract with the `file` and +`http` kinds they served. + `KnowledgeSearchOptions` includes `sourceIds`, `topK`, `filter`, `granularity`, `groupBy`, and the all-important `executionContext` (from the permission-aware tool @@ -312,6 +381,7 @@ interface IKnowledgeAdapter { indexStatus?(ctx: AdapterContext): Promise<{ fingerprint?: string; recipeHash?: string; building?: boolean }>; beginBuild?(ctx: AdapterContext): Promise; // with completeBuild, as a pair completeBuild?(ctx: AdapterContext): Promise; + dropSource?(ctx: AdapterContext): Promise; // everything held for ctx.source healthCheck?(): Promise<{ ok: boolean; message?: string }>; } ``` @@ -344,6 +414,22 @@ from it — the safe direction, since a missing entry is never purged. `indexStatus`, `beginBuild` and `completeBuild` carry the index fingerprint — see [§3.6](#36-the-index-fingerprint). +`dropSource` removes everything the adapter holds for a source (ADR-0161 K8, +item 4): every document, passage and vector of every generation, the one +under construction included, and what it recorded about the index. The +service calls it when a source stops being served — its metadata item was +removed, or a package now holds its name. After it `indexStatus` answers as +for a source never seen, and a source registered again under the same key is +built from nothing. Dropping a source the adapter holds nothing for is not an +error. + +`ctx.source.name` is the source's **index key**: the one string an adapter +keys what it holds by, and the string `KnowledgeDocument.sourceId` carries. +For a source no package holds it is the name as authored; for a package's +source the service spells a key that carries the package too, so two +packages' sources of one name are two keys. An adapter stores and compares +the key; it never derives it, parses it or shows it to a person. + **The contract test suite.** Every adapter package runs the same suite against its own factory: @@ -420,7 +506,7 @@ budget is **removed from the index and reported, never truncated**: `reindexSource` counts it in `failed` and names it in `failures` (`[{ documentId, reason }]`, at most 20; `failed` counts them all), the event sync logs it at `error` with the source, the record id, the estimate and the -limit, and `indexDocument` throws. With no limit known nothing is checked. +limit. With no limit known nothing is checked. The estimate runs high on purpose — on Chinese text about 1.4× a real tokenizer — so a `whole` document's usable length is about **60%** of the model's limit; choose `recursive` or `markdown` for longer documents. @@ -601,9 +687,9 @@ the `embedder` it is given), and answers a search by an exact scan. of each per source, by a unique index — a second build joins the one under way when its fingerprint is the same, and replaces it otherwise, so the first builder's writes are then refused), and one passage table per source and generation, - `knowledge__g`, its vector column sized for that generation. A - source id that is not snake_case is refused before - any SQL. + `knowledge__g`, its vector column sized for that generation + (`` is the source's index key). A key that is not snake_case is + refused before any SQL. - **Search.** An exact scan by cosine distance; the organization filter, the [record scope](#record-scope) and the metadata `filter` (JSON equality per key) run in the same `WHERE`, before ranking. The store creates no DiskANN index: `vector_top_k` ranks @@ -673,9 +759,9 @@ the re-read still decides what is returned. - **At assembly.** Under the `group` and `isolated` tenancy postures, a document built from a record carries the record's `organization_id` as - `organizationId`. Under `single`, for `file` / `http` sources and for a - record with no organization, it carries none. -- **At search.** For each `object` source, the service hands the adapter + `organizationId`. Under `single`, and for a record with no organization, + it carries none. +- **At search.** For each source, the service hands the adapter `organizationIds`, the organizations the tenancy wall gives the caller for that object: under `isolated` the caller's active organization, under `group` every organization the caller holds a membership in. The service @@ -683,7 +769,7 @@ the re-read still decides what is returned. posture. No tool argument or search option supplies it, and `search_knowledge` refuses an `organizationIds` argument. - **No filter** (`organizationIds` absent) under `single`, for the system - identity, for a `file` / `http` source, and for an object outside the wall + identity, and for an object outside the wall (tenancy disabled, or no `organization_id` column). The adapter ranks every document of the source, as before. - **An empty set** (`[]`) is a caller with no organization behind a wall, for @@ -723,8 +809,7 @@ const hits = await knowledge.search('notice period', { field is not reached by the entry, and neither is one that lists two or more of them (logged once at `warn`, naming the fields). A parent two hops away (policy → chapter → clause) is not reached. -- **Several entries** are a union. A source no entry reaches is not searched, - and a `file` / `http` source answers nothing under a scope. +- **Several entries** are a union. A source no entry reaches is not searched. - **Empty.** `scope: []`, or an entry whose `ids` is empty, answers no hits; it never means "no scope". Without `scope`, nothing changes. - **Bounds.** At most 10 entries, each with at most 500 ids; `object` and every @@ -759,9 +844,9 @@ empty result a source withheld from the caller gives. ### Source admission: exposure and field-level rules A passage is built at index time, under a system context, from every -`contentFields` member of its source, the object's display field (the +`content` member of its source, the object's display field (the title) and the source's `metadataFields`. A row re-check alone would therefore serve a caller the text -of a field a field-level rule hides from them. So before an `object` source is +of a field a field-level rule hides from them. So before a source is searched for a non-system caller, the service asks, once per object per search: - **Disabled package** — an object whose owning package is disabled is not @@ -772,8 +857,8 @@ searched for a non-system caller, the service asks, once per object per search: `list` does), keeps the object's sources out of the search. - **System objects** — a `sys_*` object is searched only when it declares `enable.aiReadable: true` (the AI read tools' posture). -- **Field-level rules** — every field the source serves (each `contentFields` - member, `'*'` meaning every field the object declares except `id`; each `metadataFields` +- **Field-level rules** — every field the source serves (each `content` + member; each `metadataFields` member; the display field the title is read from, and a declared `title` field), less the credential-class and `internal: true` fields an index never carries, must be one the caller may **query**, per the `security` @@ -786,14 +871,14 @@ The answer is per **source**, not per field: when one served field is hidden from the caller, that source is not searched for them at all — its passages mix the hidden field's text into one unit that cannot be partially withheld. To keep a source searchable for restricted callers, declare its -`contentFields` / `metadataFields` from fields every intended reader may query, +`content` / `metadataFields` from fields every intended reader may query, and put sensitive fields in a separate source. Every gate fails closed: a lookup that throws — the `security` service lookup included, unless the kernel answers that no `security` service is registered — or a `security` service that answers neither field question, keeps the source out of that caller's search. The system context bypasses these gates as it bypasses the row re-check. A caller with no execution context, or a service with no data engine -bound, is searched no `object` source at all; an `object` source's hit with no +bound, is searched no source at all; a hit with no `sourceRecordId` cannot be re-checked and is dropped; and the service drops a hit whose reported `sourceId` names another source than the one searched. That check sees only the `sourceId` an adapter reports: an adapter that labels @@ -801,16 +886,14 @@ another source's passage with the searched source's id is not caught by it, so two sources must not share one adapter-side store. A restricted caller's empty answer is this narrowing, not a missing index. -For `file` and `http` sources (no underlying ObjectQL record), the -adapter is responsible for honouring an opaque `permissions` field on -each document. Sources that need fine-grained ACLs should be declared -with a `permissions` mapping function at index time. +The same gates are asked once more, of the **author**, when a source is saved +at run time — see [Who may author one](#who-may-author-one). --- ## 6. Sync model -For `object` sources, `KnowledgeService` subscribes to the ObjectQL engine's +`KnowledgeService` subscribes to the ObjectQL engine's `data.record.created`, `data.record.updated`, `data.record.restored` and `data.record.deleted` events. A bare `record.*` event is not part of the vocabulary: no producer emits one, and the subscription ignores it. @@ -886,7 +969,7 @@ published after the restore's own unit has committed. ### Reindex: skip and purge -A `reindexSource` of an `object` source over an adapter that implements +A `reindexSource` over an adapter that implements `listDocuments` first lists what the adapter holds for the source (document id → stored `docHash`), then walks the object's rows page by page: @@ -933,10 +1016,13 @@ their retention window — is the one bulk path that *is* handled, and it is handled at the source rather than after the fact ([#4672](https://github.com/objectstack-ai/objectstack/issues/4672)). -For every object an `object` source projects, the plugin registers an ADR-0057 +For every object a source projects, the plugin registers an ADR-0057 **reap guard** with the lifecycle service. The sweep hands the guard the candidate rows before deleting them; the guard deletes each row's document and -returns the ids it confirms. Rows it does not confirm stay put. +returns the ids it confirms. Rows it does not confirm stay put. The guarded +set follows the sources: a source added after boot for an object with no +guard gets one when it is loaded, so a reaped row of that object is +de-indexed too. - **Failure direction.** If `adapter.delete` fails, the row is *kept* and retried on the next sweep. A row may outlive its index entry; an index entry @@ -958,9 +1044,6 @@ stale documents are removed by the next complete `reindexSource`, over an adapter that implements `listDocuments` ([Reindex: skip and purge](#reindex-skip-and-purge)); nothing runs that reindex on a schedule yet. -`file` / `http` sources rely on explicit `reindexSource` calls -(typically triggered by a cron job, a Console button, or a webhook). - --- ## 7. MVP (Phase 1) scope @@ -973,15 +1056,15 @@ followed (§4.1, §4.2) are the adapters to run in production. | Component | In Phase 1 | Notes | |-----------|-----------:|-------| -| `KnowledgeSourceSchema` | ✅ | object / file / http kinds | +| `KnowledgeSourceSchema` | ✅ | The schema of the `knowledge_source` metadata type; one kind, `object` (the `file` and `http` kinds were retired, ADR-0161 K4) | | `KnowledgeDocument` / `Chunk` / `Hit` | ✅ | Canonical shapes | -| `IKnowledgeService` contract | ✅ | search / index / delete / reindex | -| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments` with a contract test suite (`@objectstack/service-knowledge/testing`) | +| `IKnowledgeService` contract | ✅ | search / reindex / register (the push door, `indexDocument` / `deleteDocument`, was retired) | +| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments`, the index-fingerprint members and `dropSource`, with a contract test suite (`@objectstack/service-knowledge/testing`) | | `service-knowledge` orchestrator | ✅ | Adapter routing, RLS wrapper, sync | | `knowledge-memory` | ✅ | In-process; deterministic fake embedder | | `knowledge-ragflow` | retired | Shipped in Phase 1; its requests did not match the RAGFlow HTTP API, and the package was removed. Use `knowledge-pgvector`, `knowledge-turso` or an adapter of your own | | `search_knowledge` AI tool | ✅ | Threads `ToolExecutionContext` | -| Event-driven sync for `object` sources | ✅ (sync) | MVP synchronous; queue in Phase 2 | +| Event-driven sync | ✅ (sync) | MVP synchronous; queue in Phase 2 | | Console source-management UI | ⏳ Phase 2 | | | Async indexer (queue) | ⏳ Phase 2 | | | Audit + metrics | ⏳ Phase 2 | | @@ -1001,16 +1084,17 @@ followed (§4.1, §4.2) are the adapters to run in production. --- -## 8. Compatibility with existing `Embedding` primitives - -`packages/spec/src/ai/embedding.zod.ts` already defines -`EmbeddingModelSchema` and `VectorStoreSchema`. Those primitives -describe *configuration*; the Knowledge Protocol describes *behaviour*. +## 8. The embedder and the store are the deployment's -Adapters may consume `EmbeddingModel` / `VectorStore` references from a -`KnowledgeSource.embedding` field (when supplied), but they are free to -ignore them when the underlying backend manages embeddings -internally (Dify, Vectara). +A knowledge source names neither a model nor a store. The embedder is +configured once for the deployment and every source is embedded by it; the +store is the adapter the deployment installs, which a source names with +`adapter`. The `embedding` and `vectorStore` keys a source once declared were +never read by a service or an adapter and are retired (ADR-0161 K6), and the +`EmbeddingModelSchema` / `VectorStoreSchema` primitives they composed left the +spec with them. What an adapter's embedder is — model, dimensions, input +limit — is something the adapter **reports** (`IKnowledgeAdapter.embedding`, +§3.4), and the index fingerprint (§3.6) is computed from that report. --- @@ -1036,5 +1120,3 @@ internally (Dify, Vectara). - `actions-as-tools.mdx` — the `ExecutionContext` threading the Knowledge Protocol reuses. - `architecture.mdx` — overall service / plugin layering. -- `packages/spec/src/ai/embedding.zod.ts` — pre-existing embedding / - vector store primitives the protocol composes with. diff --git a/content/docs/references/ai/embedding.mdx b/content/docs/references/ai/embedding.mdx deleted file mode 100644 index aa04d286bc9..00000000000 --- a/content/docs/references/ai/embedding.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Embedding schema — AI Protocol reference -navTitle: Embedding -description: "Embedding & Vector Store Primitives — Platform contract for configuring embedding models and vector stores." ---- - -{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} - -Embedding & Vector Store Primitives - -Platform contract for configuring embedding models and vector stores. - -Scope (intentionally minimal): -- How to reference an embedding model (provider + model name + secret). -- How to reference a vector store (provider + connection). - -NOT in scope (these belong to application code, not the platform): -- Chunking strategies (fixed/semantic/recursive/markdown). -- Retrieval pipelines (rerankers, multi-stage retrieval, filters). -- Document loaders / ingestion DSLs. -- End-to-end RAG pipeline orchestration. - -These were removed in v1 because they describe one specific way to -build a RAG application; the platform's job is to expose the embed + -vector primitives so any RAG strategy can be built on top. - - -**Source:** `packages/spec/src/ai/embedding.zod.ts` - - -## TypeScript Usage - -```typescript -import { EmbeddingModelSchema, VectorStoreSchema, VectorStoreProviderSchema } from '@objectstack/spec/ai'; -import type { EmbeddingModel, VectorStore, VectorStoreProvider } from '@objectstack/spec/ai'; - -// Validate data -const result = EmbeddingModelSchema.parse(data); -``` - ---- - -## EmbeddingModel - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **provider** | `Enum<'openai' \| 'cohere' \| 'azure_openai' \| 'huggingface' \| 'local' \| 'custom'>` | ✅ | | -| **model** | `string` | ✅ | Provider-specific model identifier | -| **dimensions** | `integer` | ✅ | Embedding vector dimensions | -| **endpoint** | `string` | optional | Custom endpoint URL | -| **secretRef** | `string` | optional | Reference to stored API key secret | - - ---- - -## VectorStore - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **provider** | `Enum<'pgvector' \| 'chroma' \| 'qdrant' \| 'pinecone' \| 'weaviate' \| 'milvus' \| 'redis' \| 'opensearch' \| 'elasticsearch' \| 'custom'>` | ✅ | | -| **collection** | `string` | ✅ | Collection / index / namespace name | -| **endpoint** | `string` | optional | Connection string or endpoint URL | -| **secretRef** | `string` | optional | Reference to stored credential secret | -| **dimensions** | `integer` | optional | | - - ---- - -## VectorStoreProvider - -### Allowed Values - -* `pgvector` -* `chroma` -* `qdrant` -* `pinecone` -* `weaviate` -* `milvus` -* `redis` -* `opensearch` -* `elasticsearch` -* `custom` - - ---- - diff --git a/content/docs/references/ai/index.mdx b/content/docs/references/ai/index.mdx index 3930f47124e..8b48e0c5ee6 100644 --- a/content/docs/references/ai/index.mdx +++ b/content/docs/references/ai/index.mdx @@ -1,7 +1,7 @@ --- title: AI Protocol — complete schema reference navTitle: AI Protocol -description: "The ObjectStack AI Protocol in 17 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." +description: "The ObjectStack AI Protocol in 16 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -14,7 +14,6 @@ This section contains all protocol schemas for the ai layer of ObjectStack. - diff --git a/content/docs/references/ai/knowledge-document.mdx b/content/docs/references/ai/knowledge-document.mdx index f0816b275a8..23677c0807e 100644 --- a/content/docs/references/ai/knowledge-document.mdx +++ b/content/docs/references/ai/knowledge-document.mdx @@ -56,7 +56,7 @@ const result = KnowledgeChunkSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **id** | `string` | ✅ | Document id | -| **sourceId** | `string` | ✅ | Owning KnowledgeSource id | +| **sourceId** | `string` | ✅ | Index key of the owning knowledge source | | **sourceRecordId** | `string` | optional | | | **content** | `string` | ✅ | | | **title** | `string` | optional | | diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index d8ea1f587f8..6307d5b9684 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -1,21 +1,20 @@ --- title: Knowledge Source — AI Protocol reference navTitle: Knowledge Source -description: "Knowledge Source — declarative metadata describing what to index and which adapter to use." +description: "Knowledge Source — the governed metadata type knowledge_source: what the knowledge service indexes, from which object, and through which adapter." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} -Knowledge Source — declarative metadata describing what to index and -which adapter to use. +Knowledge Source — the governed metadata type `knowledge_source` +(ADR-0161 K4): what the knowledge service indexes, from which object, and +through which adapter. -A KnowledgeSource is the metadata-level equivalent of an -`IDataEngine` driver binding: it pairs a logical source description -(object/file/http) with the *id* of an `IKnowledgeAdapter` plugin -that will actually do the work. The adapter resolves the id at -runtime via `IKnowledgeService.registerAdapter`. +One schema for every door (ADR-0005, ADR-0161 K4 point 3): a +`*.knowledge-source.ts` file in a package, a save through Studio or MCP, +and a registration in code all parse with `KnowledgeSourceSchema`. -See `content/docs/protocol/knowledge.mdx` for the full design. +See `content/docs/protocol/knowledge.mdx` for the design. **Source:** `packages/spec/src/ai/knowledge-source.zod.ts` @@ -24,39 +23,13 @@ See `content/docs/protocol/knowledge.mdx` for the full design. ## TypeScript Usage ```typescript -import { FileKnowledgeSourceSchema, HttpKnowledgeSourceSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSourceKindSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { FileKnowledgeSource, HttpKnowledgeSource, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSourceKind, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data -const result = FileKnowledgeSourceSchema.parse(data); +const result = KnowledgeRefreshPolicySchema.parse(data); ``` ---- - -## FileKnowledgeSource - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'file'` | ✅ | | -| **prefix** | `string` | ✅ | Storage prefix | -| **mimeTypes** | `string[]` | optional (default: `[]`) | | - - ---- - -## HttpKnowledgeSource - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'http'` | ✅ | | -| **urls** | `string[]` | ✅ | | -| **userAgent** | `string` | optional | | - - --- ## KnowledgeRefreshPolicy @@ -65,8 +38,8 @@ const result = FileKnowledgeSourceSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **onRecordChange** | `boolean` | optional (default: `true`) | | -| **cron** | `string \| { dialect: 'cron'; source?: string; ast?: any; meta?: object }` | optional | Cron-dialect expression for a periodic full reindex. A bare string is shorthand for `{ dialect: 'cron', source }`; the parse enforces a non-empty string or an expression envelope and normalizes to the envelope — cron syntax is not checked here, and no engine evaluates this slot: the verdict belongs to whatever external scheduler you hand the value to. `service-knowledge` does not schedule it: the value is surfaced so an automation flow / external scheduler can trigger `reindexSource`. | +| **onRecordChange** | `boolean` | optional (default: `true`) | Sync the index from record events (default true); false leaves the index to an external indexer | +| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | --- @@ -77,118 +50,43 @@ const result = FileKnowledgeSourceSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **id** | `string` | ✅ | Snake_case source id | +| **name** | `string` | ✅ | Source machine name (snake_case) — what search_knowledge lists and its sourceIds argument names | +| **id** | `never` | optional | [REMOVED] `knowledge_source.id` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — a knowledge source is a metadata item, and an item is identified by `name`; use `name`. Rename the key; the value is unchanged, so the source's index is found again and is not rebuilt. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **label** | `string` | ✅ | | | **description** | `string` | optional | | | **adapter** | `string` | ✅ | Adapter id | -| **adapterConfig** | `Record` | optional (default: `{}`) | | -| **source** | `{ kind: 'object'; object: string; contentFields: string[]; metadataFields?: string[]; … } \| { kind: 'file'; prefix: string; mimeTypes?: string[] } \| { kind: 'http'; urls: string[]; userAgent?: string }` | ✅ | | -| **embedding** | `{ provider: Enum<'openai' \| 'cohere' \| 'azure_openai' \| 'huggingface' \| 'local' \| 'custom'>; model: string; dimensions: integer; endpoint?: string; … }` | optional | | -| **vectorStore** | `{ provider: Enum<'pgvector' \| 'chroma' \| 'qdrant' \| 'pinecone' \| 'weaviate' \| 'milvus' \| 'redis' \| …>; collection: string; endpoint?: string; secretRef?: string; … }` | optional | | -| **refresh** | `{ onRecordChange?: boolean; cron?: string \| object }` | optional | Refresh / sync configuration; omitted parses to `{}` (the runtime default — the published input-shape JSON Schema cannot state it beside `cron`'s transform). | +| **adapterConfig** | `never` | optional | [REMOVED] `knowledge_source.adapterConfig` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — no adapter read it: its one reader was the retired RAGFlow adapter. Delete the key. An adapter takes its settings as options of the plugin that mounts it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **source** | `{ kind: Enum<'object'>; object: string; content: string[]; metadataFields?: string[]; … }` | ✅ | | +| **embedding** | `never` | optional | [REMOVED] `knowledge_source.embedding` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was never read: no service and no adapter chose a model from it. Delete the key. The embedder is configured once for the deployment, and every source is embedded by it. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **vectorStore** | `never` | optional | [REMOVED] `knowledge_source.vectorStore` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was never read: no service and no adapter chose a store from it. Delete the key. The store is the adapter the deployment installs, named by `adapter`. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +| **refresh** | `{ onRecordChange?: boolean }` | optional (default: `{}`) | Refresh / sync configuration; omitted parses to `{}` | | **aiExposed** | `boolean` | optional (default: `true`) | | +| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | +| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | +| **_lockSource** | `Enum<'artifact' \| 'package' \| 'env-forced'>` | optional | Layer that set _lock (artifact \| package \| env-forced). | +| **_provenance** | `Enum<'package' \| 'org' \| 'env-forced' \| 'platform'>` | optional | Origin of the item (package \| org \| env-forced \| platform). | +| **_packageId** | `string` | optional | Owning package machine id. | +| **_packageVersion** | `string` | optional | Owning package version. | +| **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | -### Nested Shape: `KnowledgeSource.source[kind='object']` +### Nested Shape: `KnowledgeSource.source` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **kind** | `'object'` | ✅ | | +| **kind** | `Enum<'object'>` | ✅ | What the source indexes; `object` is the one kind | | **object** | `string` | ✅ | Short object name to index | -| **contentFields** | `string[]` | ✅ | Fields contributing to document content | +| **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | +| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | -### Nested Shape: `KnowledgeSource.source[kind='file']` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'file'` | ✅ | | -| **prefix** | `string` | ✅ | Storage prefix | -| **mimeTypes** | `string[]` | optional (default: `[]`) | | - -### Nested Shape: `KnowledgeSource.embedding` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **provider** | `Enum<'openai' \| 'cohere' \| 'azure_openai' \| 'huggingface' \| 'local' \| 'custom'>` | ✅ | | -| **model** | `string` | ✅ | Provider-specific model identifier | -| **dimensions** | `integer` | ✅ | Embedding vector dimensions | -| **endpoint** | `string` | optional | Custom endpoint URL | -| **secretRef** | `string` | optional | Reference to stored API key secret | - -### Nested Shape: `KnowledgeSource.vectorStore` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **provider** | `Enum<'pgvector' \| 'chroma' \| 'qdrant' \| 'pinecone' \| 'weaviate' \| 'milvus' \| 'redis' \| …>` | ✅ | | -| **collection** | `string` | ✅ | Collection / index / namespace name | -| **endpoint** | `string` | optional | Connection string or endpoint URL | -| **secretRef** | `string` | optional | Reference to stored credential secret | -| **dimensions** | `integer` | optional | | - ### Nested Shape: `KnowledgeSource.refresh` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **onRecordChange** | `boolean` | optional (default: `true`) | | -| **cron** | `string \| { dialect: 'cron'; source?: string; ast?: any; meta?: object }` | optional | Cron-dialect expression for a periodic full reindex. A bare string is shorthand for `{ dialect: 'cron', source }`; the parse enforces a non-empty string or an expression envelope and normalizes to the envelope — cron syntax is not checked here, and no engine evaluates this slot: the verdict belongs to whatever external scheduler you hand the value to. `service-knowledge` does not schedule it: the value is surfaced so an automation flow / external scheduler can trigger `reindexSource`. | - - ---- - -## KnowledgeSourceKind - -### Union Options - -This schema accepts one of the following structures: - -#### Option 1 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'object'` | ✅ | | -| **object** | `string` | ✅ | Short object name to index | -| **contentFields** | `string[]` | ✅ | Fields contributing to document content | -| **metadataFields** | `string[]` | optional (default: `[]`) | | -| **where** | `Record` | optional | | -| **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | - -### Nested Shape: `KnowledgeSourceKind[kind='object'].split` - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | -| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | -| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | - ---- - -#### Option 2 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'file'` | ✅ | | -| **prefix** | `string` | ✅ | Storage prefix | -| **mimeTypes** | `string[]` | optional (default: `[]`) | | - ---- - -#### Option 3 - -### Properties - -| Property | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| **kind** | `'http'` | ✅ | | -| **urls** | `string[]` | ✅ | | -| **userAgent** | `string` | optional | | - ---- +| **onRecordChange** | `boolean` | optional (default: `true`) | Sync the index from record events (default true); false leaves the index to an external indexer | +| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | --- @@ -223,9 +121,10 @@ This schema accepts one of the following structures: | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **kind** | `'object'` | ✅ | | +| **kind** | `Enum<'object'>` | ✅ | What the source indexes; `object` is the one kind | | **object** | `string` | ✅ | Short object name to index | -| **contentFields** | `string[]` | ✅ | Fields contributing to document content | +| **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | +| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | diff --git a/content/docs/references/ai/meta.json b/content/docs/references/ai/meta.json index 00712c3186f..d694cc09b60 100644 --- a/content/docs/references/ai/meta.json +++ b/content/docs/references/ai/meta.json @@ -8,7 +8,6 @@ "solution-blueprint", "tool", "---Knowledge & RAG---", - "embedding", "knowledge-document", "knowledge-source", "---Models & Runtime---", diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 1774d86847e..99045c4f845 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -642,7 +642,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -709,7 +709,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +19 more>` | ✅ | Metadata type | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +20 more>` | ✅ | Metadata type | | **name** | `string` | ✅ | Item name (snake_case) | | **data** | `Record` | ✅ | Metadata payload | | **namespace** | `string` | optional | Optional namespace | @@ -749,6 +749,7 @@ Metadata query with filtering, sorting, and pagination * `tool` * `skill` * `ai_context` +* `knowledge_source` --- diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index 617f7f01e5e..e9931b0933d 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -138,6 +138,7 @@ Installed package row whose manifest is the assembled package body | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | | **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | +| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it where `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | @@ -389,6 +390,7 @@ This schema accepts one of the following structures: | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | | **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | +| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it where `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 2d3540baa02..7249ecf8501 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1735 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1729 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 102 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 16 | 96 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,13 +34,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **222** | **1735** | 14 protocol modules | +| **Total** | **221** | **1729** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 102 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 96 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -51,9 +51,8 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` | | [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` | | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | -| [`embedding.zod.ts`](/docs/references/ai/embedding) | `EmbeddingModel`, `VectorStore`, `VectorStoreProvider` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSourceKind`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index 379e844b085..b57e6e222c3 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -179,7 +179,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -258,6 +258,7 @@ const result = MetadataBulkResultSchema.parse(data); * `tool` * `skill` * `ai_context` +* `knowledge_source` --- @@ -268,7 +269,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +19 more>` | ✅ | Metadata type identifier | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +20 more>` | ✅ | Metadata type identifier | | **label** | `string` | ✅ | Display label for the metadata type | | **description** | `string` | optional | Description of the metadata type | | **filePatterns** | `string[]` | ✅ | Glob patterns to discover files of this type | @@ -317,6 +318,7 @@ const result = MetadataBulkResultSchema.parse(data); * `tool` * `skill` * `ai_context` +* `knowledge_source` ### Nested Shape: `MetadataTypeRegistryEntry.actions[number]` diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 37985ae75bb..8302847ae0a 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 114 | +| `ai/` | 110 | diff --git a/examples/app-showcase/objectstack.config.ts b/examples/app-showcase/objectstack.config.ts index e287de4f62c..767f55bd9cd 100644 --- a/examples/app-showcase/objectstack.config.ts +++ b/examples/app-showcase/objectstack.config.ts @@ -24,8 +24,10 @@ import { ShowcaseApp } from './src/ui/apps/index.js'; import { ChartGalleryDashboard, OpsDashboard, RevenuePulseDashboard } from './src/ui/dashboards/index.js'; import { ShowcaseTaskDataset, ShowcaseProjectDataset, ShowcaseInvoiceDataset, ShowcaseAccountDataset } from './src/ui/datasets/index.js'; import { allReports } from './src/ui/reports/index.js'; -import { ShowcaseProjectBriefContext, ShowcaseTaskNotesContext } from './src/ai/index.js'; +import { ShowcaseProjectBriefContext, ShowcaseTaskNotesContext, ShowcaseTaskNotesKnowledge } from './src/ai/index.js'; import { RecordContextServicePlugin } from '@objectstack/service-record-context'; +import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; +import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; import { allActions } from './src/ui/actions/index.js'; import { CapabilityMapPage, StartHerePage, ComponentGalleryPage, ProjectWorkspacePage, ProjectDetailPage, TaskWorkbenchPage, TaskTriagePage, TaskBoardPage, TaskCalendarPage, TaskGalleryPage, TaskSchedulePage, TaskTimelinePage, TaskMapPage, TaskAllViewsPage, ActiveProjectsPage, TaskDetailPage, InvoiceDocumentPage, ReviewQueuePage, NewProjectWizardPage, MyWorkPage, SettingsPage, StylingGalleryPage, CommandCenterPage, CommandCenterJsxPage, CrmWorkbenchPage, TaskDeskPage, PageVariablesPage, ContactFormPage, RenewalsPipelinePage } from './src/ui/pages/index.js'; import { allFlows } from './src/automation/flows/index.js'; @@ -173,6 +175,14 @@ export default defineStack({ // [ADR-0160] The record-context service: `get_record_context` over MCP // reads the context packs below (`aiContexts`) as the caller. new RecordContextServicePlugin(), + // [ADR-0161 K4] The knowledge service and a store for it: the service + // loads the knowledge sources below (`knowledgeSources`), builds their + // indexes and keeps them in step with the records; `search_knowledge` over + // MCP answers from them as the caller. The in-memory store is the + // reference adapter the source names (`adapter: 'memory'`): no embedder, + // nothing persisted, rebuilt at each boot. + new KnowledgeServicePlugin(), + new KnowledgeMemoryPlugin(), ], // Infrastructure @@ -221,6 +231,7 @@ export default defineStack({ reports: allReports, // [ADR-0160] Context packs read by `get_record_context` (src/ai/). aiContexts: [ShowcaseProjectBriefContext, ShowcaseTaskNotesContext], + knowledgeSources: [ShowcaseTaskNotesKnowledge], actions: allActions, // `themes` retired at #10485 (ADR-0049) — recolour via `app.branding` instead. diff --git a/examples/app-showcase/package.json b/examples/app-showcase/package.json index 52a751dd67f..d118c57cb6f 100644 --- a/examples/app-showcase/package.json +++ b/examples/app-showcase/package.json @@ -30,10 +30,12 @@ "@objectstack/connector-rest": "workspace:*", "@objectstack/connector-slack": "workspace:*", "@objectstack/driver-sql": "workspace:*", + "@objectstack/knowledge-memory": "workspace:*", "@objectstack/organizations": "workspace:*", "@objectstack/runtime": "workspace:*", "@objectstack/service-datasource": "workspace:*", "@objectstack/service-i18n": "workspace:*", + "@objectstack/service-knowledge": "workspace:*", "@objectstack/service-print": "workspace:*", "@objectstack/service-record-context": "workspace:*", "@objectstack/spec": "workspace:*" diff --git a/examples/app-showcase/src/ai/index.ts b/examples/app-showcase/src/ai/index.ts index 8163d085ee9..1871c6aa7e3 100644 --- a/examples/app-showcase/src/ai/index.ts +++ b/examples/app-showcase/src/ai/index.ts @@ -1,3 +1,4 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. export { ShowcaseProjectBriefContext, ShowcaseTaskNotesContext } from './record-context.ai-context.js'; +export { ShowcaseTaskNotesKnowledge } from './task-notes.knowledge-source.js'; diff --git a/examples/app-showcase/src/ai/task-notes.knowledge-source.ts b/examples/app-showcase/src/ai/task-notes.knowledge-source.ts new file mode 100644 index 00000000000..0784a4702e9 --- /dev/null +++ b/examples/app-showcase/src/ai/task-notes.knowledge-source.ts @@ -0,0 +1,38 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { KnowledgeSource } from '@objectstack/spec/ai'; + +/** + * [ADR-0161 K4] A knowledge source — which records the knowledge service + * indexes for retrieval, and which of their fields become searchable text. + * + * `showcase_task_notes` indexes every task that is not done: the text of + * `title` and `notes` is the document body, and `status` and `priority` are + * kept beside each passage so a search can filter on them. The knowledge + * service loads this item at boot, runs its first build, and keeps the index + * in step with the tasks as they change; `search_knowledge` over MCP then + * answers from it, as the caller — a task the caller may not read is not + * returned. + * + * `content` lists its fields by name: what is listed is what leaves the row + * store for the index (and, with a real embedder, for the embedding + * provider). A field added to the task later is not indexed until it is + * added here. + * + * `adapter: 'memory'` names the in-memory reference store mounted in + * objectstack.config.ts — deterministic, no embedder, rebuilt at each boot. + * A real deployment names a persistent store (`'turso'`, `'pgvector'`). + */ +export const ShowcaseTaskNotesKnowledge: KnowledgeSource = { + name: 'showcase_task_notes', + label: 'Task notes', + description: 'Titles and notes of open tasks, searchable by meaning.', + adapter: 'memory', + source: { + kind: 'object', + object: 'showcase_task', + content: ['title', 'notes'], + metadataFields: ['status', 'priority'], + where: { status: { $ne: 'done' } }, + }, +}; diff --git a/examples/app-showcase/src/coverage.ts b/examples/app-showcase/src/coverage.ts index b983ccc0c06..0b0a1670949 100644 --- a/examples/app-showcase/src/coverage.ts +++ b/examples/app-showcase/src/coverage.ts @@ -219,6 +219,12 @@ export const KIND_COVERAGE: Record = { notes: 'Two context packs (ADR-0160): a project brief (own fields, a lookup read through to the account, its open tasks as a related list, filtered, ordered by due date and cut by `where` / `orderBy` / `limit`) and a task with its notes as a body (whole, or an outline read by anchor). Read by `get_record_context` over MCP; the service is wired in objectstack.config.ts plugins.', }, + knowledge_source: { + status: 'demonstrated', + files: ['src/ai/task-notes.knowledge-source.ts'], + notes: + 'One knowledge source (ADR-0161 K4): the titles and notes of open tasks, with `status` and `priority` kept for filtering. `content` lists its fields by name — what is listed is what leaves the row store for the index. Loaded, built and kept in step by the knowledge service; read by `search_knowledge` over MCP as the caller. The service and the in-memory store the source names (`adapter: \'memory\'`) are wired in objectstack.config.ts plugins.', + }, skill: { status: 'waived', reason: diff --git a/packages/qa/dogfood/test/expression-conformance.ledger.ts b/packages/qa/dogfood/test/expression-conformance.ledger.ts index d565753eacd..2a27753fd16 100644 --- a/packages/qa/dogfood/test/expression-conformance.ledger.ts +++ b/packages/qa/dogfood/test/expression-conformance.ledger.ts @@ -608,16 +608,10 @@ export const EXPRESSION_SURFACE: ExprSurface[] = [ proof: 'packages/runtime/src/job-schedule.test.ts', note: 'The ONE cron slot in the spec with a measured evaluator. `@objectstack/formula` cronEngine is NOT on this path — it has zero consumers outside packages/formula, and the five other cron slots once declared beside this one (the former `cron-declared-unwired` row: export schedules, flow schedule state, connector sync, cache warmup, DR backup/test) never reached it either; they were retired under ADR-0049 as declared-but-never-evaluated.', }, - { - // The key and its documented hand-off arrived with #14825. - id: 'cron-knowledge-refresh', - summary: 'knowledge-source periodic reindex cron (KnowledgeRefreshPolicy.cron) — surfaced, deliberately not scheduled', - dialect: 'cron', mode: 'interpret', state: 'experimental', failPolicy: 'unevaluated', - enforcement: - 'PARSE ONLY — `CronExpressionInputSchema` refuses a blank/non-string, non-envelope value and normalizes to `{dialect:"cron",source}`; nothing evaluates the result. service-knowledge/knowledge-service.ts reads `refresh.onRecordChange` and NEVER `refresh.cron` (measured: the only `refresh` reads in that package are the two `onRecordChange` sites)', - covers: ['ai/knowledge-source.zod.ts:KnowledgeRefreshPolicySchema.cron'], - note: 'EXPERIMENTAL by DESIGN — and that is why it survived the ADR-0049 retirement of the other declared-but-unwired cron slots (the former `cron-declared-unwired` row): the key documents its own hand-off — service-knowledge surfaces the value so an automation flow / external scheduler can call `reindexSource`, and the field docblock says so. Nothing in this repo schedules it, which is the intended state rather than an undelivered one. It still has no evaluator, so it is not `enforced`.', - }, + // `cron-knowledge-refresh` sat here until the `knowledge_source` type's + // admission retired its one position, `ai/knowledge-source.zod.ts` + // `KnowledgeRefreshPolicySchema.cron` (ADR-0161 K6, #37304: nothing ever + // scheduled it; the key is a tombstone that names its migration). // `cron-declared-unwired` sat here until #16320 retired every position it // covered under ADR-0049 (the #15954 ruling, decision batch #56, option A — // retire — per family): `api/export.zod.ts` `ScheduledExportSchema.cronExpression` diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 74918bec2bf..7845ae98bbc 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -96,12 +96,8 @@ "DatasetToolCatalogMeasure (type)", "DatasetToolCatalogMeasureSchema (const)", "DatasetToolJsonSchema (interface)", - "EmbeddingModel (type)", - "EmbeddingModelSchema (const)", "FileContent (type)", "FileContentSchema (const)", - "FileKnowledgeSource (type)", - "FileKnowledgeSourceSchema (const)", "FilterCondition (type)", "FunctionCall (type)", "FunctionCallSchema (const)", @@ -111,8 +107,6 @@ "GetRecordContextOutput (type)", "GetRecordContextOutputParsed (type)", "GetRecordContextOutputSchema (const)", - "HttpKnowledgeSource (type)", - "HttpKnowledgeSourceSchema (const)", "ImageContentSchema (const)", "KnowledgeChunk (type)", "KnowledgeChunkSchema (const)", @@ -124,8 +118,6 @@ "KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema (const)", "KnowledgeSource (type)", - "KnowledgeSourceKind (type)", - "KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", "KnowledgeSplit (type)", @@ -284,10 +276,6 @@ "ToolSchema (const)", "TransformPipelineStep (type)", "TransformPipelineStepSchema (const)", - "VectorStore (type)", - "VectorStoreProvider (type)", - "VectorStoreProviderSchema (const)", - "VectorStoreSchema (const)", "agentForm (const)", "aiContextForm (const)", "aiContextWhereFields (function)", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 387c0d02c39..795374643a5 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -66,20 +66,14 @@ "DatasetToolCatalogEntrySchema": "ai/DatasetToolCatalogEntry", "DatasetToolCatalogMeasure": "ai/DatasetToolCatalogMeasure", "DatasetToolCatalogMeasureSchema": "ai/DatasetToolCatalogMeasure", - "EmbeddingModel": "ai/EmbeddingModel", - "EmbeddingModelSchema": "ai/EmbeddingModel", "FileContent": "ai/FileContent", "FileContentSchema": "ai/FileContent", - "FileKnowledgeSource": "ai/FileKnowledgeSource", - "FileKnowledgeSourceSchema": "ai/FileKnowledgeSource", "FunctionCall": "ai/FunctionCall", "FunctionCallSchema": "ai/FunctionCall", "GetRecordContextInput": "ai/GetRecordContextInput", "GetRecordContextInputSchema": "ai/GetRecordContextInput", "GetRecordContextOutput": "ai/GetRecordContextOutput", "GetRecordContextOutputSchema": "ai/GetRecordContextOutput", - "HttpKnowledgeSource": "ai/HttpKnowledgeSource", - "HttpKnowledgeSourceSchema": "ai/HttpKnowledgeSource", "ImageContentSchema": "ai/ImageContent", "KnowledgeChunk": "ai/KnowledgeChunk", "KnowledgeChunkSchema": "ai/KnowledgeChunk", @@ -90,8 +84,6 @@ "KnowledgeRefreshPolicy": "ai/KnowledgeRefreshPolicy", "KnowledgeRefreshPolicySchema": "ai/KnowledgeRefreshPolicy", "KnowledgeSource": "ai/KnowledgeSource", - "KnowledgeSourceKind": "ai/KnowledgeSourceKind", - "KnowledgeSourceKindSchema": "ai/KnowledgeSourceKind", "KnowledgeSourceSchema": "ai/KnowledgeSource", "KnowledgeSplit": "ai/KnowledgeSplit", "KnowledgeSplitSchema": "ai/KnowledgeSplit", @@ -195,11 +187,7 @@ "ToolCallSchema": "ai/ToolCall", "ToolSchema": "ai/Tool", "TransformPipelineStep": "ai/TransformPipelineStep", - "TransformPipelineStepSchema": "ai/TransformPipelineStep", - "VectorStore": "ai/VectorStore", - "VectorStoreProvider": "ai/VectorStoreProvider", - "VectorStoreProviderSchema": "ai/VectorStoreProvider", - "VectorStoreSchema": "ai/VectorStore" + "TransformPipelineStepSchema": "ai/TransformPipelineStep" }, "collisions": [] } diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index cc5f99d983e..4af3c08a963 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -94,12 +94,8 @@ "DatasetToolCatalogMeasure": "src/ai/dataset-tools.zod.ts#DatasetToolCatalogMeasure (type)", "DatasetToolCatalogMeasureSchema": "src/ai/dataset-tools.zod.ts#DatasetToolCatalogMeasureSchema (const)", "DatasetToolJsonSchema": "src/ai/dataset-tools.zod.ts#DatasetToolJsonSchema (interface)", - "EmbeddingModel": "src/ai/embedding.zod.ts#EmbeddingModel (type)", - "EmbeddingModelSchema": "src/ai/embedding.zod.ts#EmbeddingModelSchema (const)", "FileContent": "src/ai/conversation.zod.ts#FileContent (type)", "FileContentSchema": "src/ai/conversation.zod.ts#FileContentSchema (const)", - "FileKnowledgeSource": "src/ai/knowledge-source.zod.ts#FileKnowledgeSource (type)", - "FileKnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#FileKnowledgeSourceSchema (const)", "FilterCondition": "src/data/filter.zod.ts#FilterCondition (type)", "FunctionCall": "src/ai/conversation.zod.ts#FunctionCall (type)", "FunctionCallSchema": "src/ai/conversation.zod.ts#FunctionCallSchema (const)", @@ -109,8 +105,6 @@ "GetRecordContextOutput": "src/ai/record-context-tools.zod.ts#GetRecordContextOutput (type)", "GetRecordContextOutputParsed": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputParsed (type)", "GetRecordContextOutputSchema": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputSchema (const)", - "HttpKnowledgeSource": "src/ai/knowledge-source.zod.ts#HttpKnowledgeSource (type)", - "HttpKnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#HttpKnowledgeSourceSchema (const)", "ImageContentSchema": "src/ai/conversation.zod.ts#ImageContentSchema (const)", "KnowledgeChunk": "src/ai/knowledge-document.zod.ts#KnowledgeChunk (type)", "KnowledgeChunkSchema": "src/ai/knowledge-document.zod.ts#KnowledgeChunkSchema (const)", @@ -122,8 +116,6 @@ "KnowledgeRefreshPolicyParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicySchema (const)", "KnowledgeSource": "src/ai/knowledge-source.zod.ts#KnowledgeSource (type)", - "KnowledgeSourceKind": "src/ai/knowledge-source.zod.ts#KnowledgeSourceKind (type)", - "KnowledgeSourceKindSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", "KnowledgeSplit": "src/ai/knowledge-source.zod.ts#KnowledgeSplit (type)", @@ -281,10 +273,6 @@ "ToolSchema": "src/ai/tool.zod.ts#ToolSchema (const)", "TransformPipelineStep": "src/ai/agent.zod.ts#TransformPipelineStep (type)", "TransformPipelineStepSchema": "src/ai/agent.zod.ts#TransformPipelineStepSchema (const)", - "VectorStore": "src/ai/embedding.zod.ts#VectorStore (type)", - "VectorStoreProvider": "src/ai/embedding.zod.ts#VectorStoreProvider (type)", - "VectorStoreProviderSchema": "src/ai/embedding.zod.ts#VectorStoreProviderSchema (const)", - "VectorStoreSchema": "src/ai/embedding.zod.ts#VectorStoreSchema (const)", "agentForm": "src/ai/agent.form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", diff --git a/packages/spec/liveness/README.md b/packages/spec/liveness/README.md index bbb338affa9..ae0a93ebab4 100644 --- a/packages/spec/liveness/README.md +++ b/packages/spec/liveness/README.md @@ -893,7 +893,7 @@ The governed set is `GOVERNED` at the top of `check-liveness.mts`. To add a type RecordDetailView had been gating the History tab on it the whole time (#2707). 4. Add the type to `GOVERNED`; confirm the gate is green. -## Current state — 45 governed types (complete registry coverage) +## Current state — 46 governed types (complete registry coverage) > **This heading is now checked** (#7257). `check:liveness` reconciles the table > against `GOVERNED` in both directions — a governed type with no row fails, a row @@ -1028,6 +1028,7 @@ marker where the Notes cell goes, never a guess at what belongs there. | assignment_rule | seeded 2026-10-26 with the type itself (#25769, ADR-0142 D5): registered governed. Declared only — organization-authored rules are deferred (ADR-0142 merge question 11) — and read on every insert by the engine's `AssignmentRuleEvaluator`, after every `beforeInsert` hook, for a row whose `owner_id` and `queue` are both still empty. All rows `live`, and `entries.assignTo` is drilled (`type`, `value`) rather than inherited. `name` and `entries.name` key the round-robin cursor (`sys_assignment_cursor`, per rule, entry and organization), so a rename restarts a rotation; `object` gates evaluation to objects carrying the platform `queue` column; `entries.load` is the `least_loaded` count predicate, required with that strategy and refused otherwise. `kernel:ready` refuses a stack that declares rules or queues with no `ownership-queue` service registered, so no row is inert by a missing service. | | template_manifest | seeded 2026-11-06 with the marketplace taxonomy, through `SPEC_ONLY_SCHEMAS` (the sixth category: a package-listing file surface — `objectstack.manifest.json`, read by `os package publish` and create-objectstack, never by a boot). The facet keys `businessFunctions` / `industries` / `maturity` are `planned`: the CLI judges and forwards them, and their consumers are the cloud catalog (objectstack-ai/cloud#3661, which drops them until it lands) and the console marketplace card. `solutionType` is `live` through the publish cross-check. `category` is the tombstone. The other `dead` rows are what entering the denominator measured: `name`, `specVersion`, `skills`, `scaffold` and the warned-and-unsent `visibility` were then retired as tombstones (ADR-0049); `publisher` / `isStarter`, which publish named in a warning and did not send but a first-party publish script did, were then retired too (maintainer ruling: a trust claim does not belong in an author-editable file). | | ai_context | seeded 2026-11-25 with the type itself (#37140, ADR-0160 D1): registered governed, never a `PENDING_GOVERNANCE` debt. Every key is read by the one `get_record_context` executor (`@objectstack/service-record-context`), served over the MCP door on HTTP and stdio; `name`, `object`, `fields`, `related.*` and `body.field` are `live` there, and `label` is the answer's pack header. | +| knowledge_source | seeded 2026-11-26 with the type itself (#37304, ADR-0161 K4): registered governed, never a `PENDING_GOVERNANCE` debt. Every key that parses is read by the knowledge service (`@objectstack/service-knowledge`), whose loader registers the published items: `name` is the source's slot and index key, `label` / `description` / `aiExposed` are read by `search_knowledge`, `adapter`, `source.*` and `refresh.onRecordChange` by the build, the event sync and the reap guard. The 6 `dead` keys are ADR-0161 K6's tombstones, removed in the same PR: `id`, `source.contentFields`, `adapterConfig`, `embedding`, `vectorStore`, `refresh.cron`. | The `dead` set across types is the enforce-or-remove worklist (ADR-0049); a `dead` row warns its authors at compile time by its verdict alone, with no `authorWarn` diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json new file mode 100644 index 00000000000..cac97160911 --- /dev/null +++ b/packages/spec/liveness/knowledge_source.json @@ -0,0 +1,150 @@ +{ + "type": "knowledge_source", + "_note": "KnowledgeSourceSchema (packages/spec/src/ai/knowledge-source.zod.ts) — a knowledge source, the stack's `knowledgeSources` (ADR-0161 K4). Seeded 2026-11-26 with the type itself (#37304): every key that parses is read by the knowledge service (`@objectstack/service-knowledge`), which loads the published items; the keys ADR-0161 K6 retired are tombstones, classified dead. The protection fields (`_lock*`, `_provenance`, `_packageId`) are the framework overlay fields every kind carries and are judged where every kind's are.", + "props": { + "name": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-source-registry.ts#indexKeyOf — the name, with the holding package, is the source's slot and the key its index is held under; packages/services/service-knowledge/src/knowledge-source-registry.ts#resolveSourceRef — how `search_knowledge`'s `sourceIds` and the service's by-name members find it.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Identity: with the package that holds the item, the source's slot (ADR-0150 bucket 3)." + }, + "id": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-id-to-name` (a rename; the value is unchanged, so document ids do not move). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was the source's identity before a source was a metadata item; `name` carries the same value." + }, + "label": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-tools.ts#summarize — carried as `sources[].label`, what the model reads to choose a source; packages/services/service-knowledge/src/knowledge-build-actions.ts#knowledgeIndexStatusActionHandler — the operator's status listing.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "description": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-tools.ts#summarize — carried as `sources[].description` when the source states one.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "adapter": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#reindexWith — the adapter the source's documents are written to and searched in is resolved by this id; packages/services/service-knowledge/src/knowledge-service.ts#dropMetadataSource — the adapter asked to drop the index of a removed item.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Required until row 3b of topic #37000 makes it optional." + }, + "adapterConfig": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-inert-keys-removed` (a strip). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). Its one reader was the RAGFlow adapter, retired by #37004; no adapter in this repository read it after that (ADR-0161 K4: a key no adapter reads does not enter v1)." + }, + "source": { + "children": { + "kind": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#contentRecipe — the kind is part of the source's content recipe; one value, `object` (the `file` and `http` arms retired, ADR-0161 K4 point 1).", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "A discriminator with one arm: kept so a designed arm can return without a rename." + }, + "object": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#objectSourcesFor — a written or deleted record is matched to its sources by this object; packages/services/service-knowledge/src/knowledge-service.ts#walkObjectSource — the object a build walks; packages/services/service-knowledge/src/knowledge-reap-guard.ts#guardedObjectsFor — the object the lifecycle reap guard is registered for.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "content": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#recordToDocument — the listed fields, in order, are the document's text; packages/services/service-knowledge/src/knowledge-source-admission.ts#servedFieldsOf — each is a field the caller must be allowed to query before the source is searched for them.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "A list of field names; the `'*'` member is refused at parse (ADR-0161 K5: embedding is egress)." + }, + "contentFields": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-content-fields-to-content` (a rename; a `'*'` member is reported for a hand edit). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). The key is spelled `content`; the readers above read that." + }, + "metadataFields": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#recordToDocument — each listed field's value is carried in the document's metadata; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a change to the list changes the recipe hash and starts one rebuild; packages/services/service-knowledge/src/knowledge-search-scope.ts — a parent scope and `groupBy` resolve against the listed fields.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "where": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#walkObjectSource — a build indexes only the records the filter selects; packages/services/service-knowledge/src/knowledge-service.ts#syncRecord — a written record is re-read under it, and one that no longer matches is de-indexed; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a changed filter starts one rebuild.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "split": { + "children": { + "strategy": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/split/splitter.ts#resolveSplit — the strategy the service cuts the source's documents by (`recursive` when omitted); packages/services/service-knowledge/src/split/splitter.ts#splitDocument — the cut; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeIndexFingerprint — part of the index fingerprint.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "maxChars": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/split/splitter.ts#resolveSplit — the longest passage; wins over the settings page's `knowledge.chunk_target`, and the embedder's limit can lower it.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "minChars": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/split/splitter.ts#resolveSplit — adjacent pieces shorter than this are merged; never above the effective maxChars.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + } + } + } + } + }, + "embedding": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-inert-keys-removed` (a strip). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was never read: no service and no adapter chose a model from it. The embedder is configured once for the deployment." + }, + "vectorStore": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-inert-keys-removed` (a strip). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was never read: no service and no adapter chose a store from it. The store is the adapter the deployment installs." + }, + "refresh": { + "children": { + "onRecordChange": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#objectSourcesFor — `false` leaves the source out of the event sync and of the reap guard; packages/services/service-knowledge/src/knowledge-service.ts#buildIfDue — and out of the boot and reload builds: an external indexer owns its index.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + }, + "cron": { + "status": "dead", + "verifiedAt": "2026-11-26", + "note": "REMOVED 2026-11-26 (#37304; ADR-0161 K6) — tombstoned at the schema (retiredKey carries the prescription; authoring it is a tsc error and a parse error) and handled for stored rows and existing sources by the protocol-19 conversion `knowledge-source-inert-keys-removed` (a strip). The entry stays because retiredKey keeps the key in the walked shape (the rls.priority precedent). It was parsed and reached no engine: nothing ever scheduled a reindex from it." + } + } + }, + "aiExposed": { + "status": "live", + "verifiedAt": "2026-11-26", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-tools.ts#searchableSources — `false` withholds the source from `search_knowledge`: it is not listed, not searched and cannot be named.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." + } + } +} diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md new file mode 100644 index 00000000000..0f1b3f9d841 --- /dev/null +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -0,0 +1,15 @@ + + + +# `knowledge_source` — liveness counts (generated) + +This type's row of the liveness state table, computed by the gate that enforces +it (`scripts/liveness/check-liveness.mts --json`, `types..byStatus`). Its +Notes prose is the `knowledge_source` row of [the ledger README](../README.md), which +also states the counting method. One file per governed type, and no total is +committed anywhere: `check:liveness` sums the shards when it reads them. +**Never hand-patch a number here** — fix the ledger or the schema and regenerate. + +| Type | live | exp | elsewhere | dead | planned | classified | +|---|---|---|---|---|---|---| +| `knowledge_source` | 21 | 0 | 0 | 6 | 0 | 27 | diff --git a/packages/spec/scripts/liveness/check-liveness.mts b/packages/spec/scripts/liveness/check-liveness.mts index 83bcba14bbe..b1cf23aa284 100644 --- a/packages/spec/scripts/liveness/check-liveness.mts +++ b/packages/spec/scripts/liveness/check-liveness.mts @@ -279,7 +279,7 @@ const ledgerRoot = ledgerRootArg // Governed metadata types, rolled out highest-frequency / highest-risk first. // (`query` is not a metadata type — see SPEC_ONLY_SCHEMAS below.) -const GOVERNED = ['object', 'field', 'flow', 'action', 'hook', 'permission', 'position', 'agent', 'tool', 'skill', 'dataset', 'page', 'view', 'report', 'dashboard', 'webhook', 'query', 'datasource', 'app', 'book', 'doc', 'email_template', 'job', 'mapping', 'picklist', 'seed', 'translation', 'validation', 'api', 'capability', 'qa', 'manifest', 'crud_endpoints', 'metadata_endpoints', 'batch_endpoints', 'route_generation', 'rest_api', 'realtime_subscription', 'sharing_rule', 'connector', 'analytics_cube', 'queue', 'assignment_rule', 'template_manifest', 'ai_context']; +const GOVERNED = ['object', 'field', 'flow', 'action', 'hook', 'permission', 'position', 'agent', 'tool', 'skill', 'dataset', 'page', 'view', 'report', 'dashboard', 'webhook', 'query', 'datasource', 'app', 'book', 'doc', 'email_template', 'job', 'mapping', 'picklist', 'seed', 'translation', 'validation', 'api', 'capability', 'qa', 'manifest', 'crud_endpoints', 'metadata_endpoints', 'batch_endpoints', 'route_generation', 'rest_api', 'realtime_subscription', 'sharing_rule', 'connector', 'analytics_cube', 'queue', 'assignment_rule', 'template_manifest', 'ai_context', 'knowledge_source']; // Authorable metadata types that are NOT yet governed — the coverage ratchet. // diff --git a/packages/spec/src/meta-spelling/meta-url-data.generated.ts b/packages/spec/src/meta-spelling/meta-url-data.generated.ts index 0cb6496a7e5..f8ebc2f8e04 100644 --- a/packages/spec/src/meta-spelling/meta-url-data.generated.ts +++ b/packages/spec/src/meta-spelling/meta-url-data.generated.ts @@ -38,6 +38,7 @@ export const META_URL_TO_SINGULAR: Readonly> = Object.fre "tools": "tool", "skills": "skill", "aiContexts": "ai_context", + "knowledgeSources": "knowledge_source", "hooks": "hook", "mappings": "mapping", "picklists": "picklist", @@ -59,6 +60,7 @@ export const META_URL_TO_SINGULAR: Readonly> = Object.fre "sharing_rules": "sharing_rule", "assignment_rules": "assignment_rule", "ai_contexts": "ai_context", + "knowledge_sources": "knowledge_source", }); /** @@ -99,4 +101,5 @@ export const REGISTRY_DECLARED_META_TYPES: ReadonlyArray = Object.freeze "tool", "skill", "ai_context", + "knowledge_source", ]); diff --git a/packages/spec/src/shared/expression.zod.ts b/packages/spec/src/shared/expression.zod.ts index 8abe29c6a12..c0062d124fa 100644 --- a/packages/spec/src/shared/expression.zod.ts +++ b/packages/spec/src/shared/expression.zod.ts @@ -348,18 +348,18 @@ function typedExpressionRefusals(dialect: TypedExpressionDialect): TypedExpressi * `{ dialect: 'cron', source }`, and an envelope must declare `dialect: 'cron'` * — a `cel` or `template` envelope is refused at the slot, naming the fix * (`TYPED_EXPRESSION_DIALECT_ONLY.cron`), as is a blank string - * (`TYPED_EXPRESSION_SOURCE_REQUIRED.cron`). Two slots carry it: - * `CronSchedule.expression` (`system/job.zod.ts`) and - * `KnowledgeRefreshPolicy.cron` (`ai/knowledge-source.zod.ts`); authors write + * (`TYPED_EXPRESSION_SOURCE_REQUIRED.cron`). One slot carries it: + * `CronSchedule.expression` (`system/job.zod.ts`); authors write * `'0 9 * * 1-5'` without manually wrapping. The seven other cron-typed * positions nothing evaluated were retired by #16320 (ADR-0049 — a slot with - * no engine is declared, not enforced), so a new one needs a reader first. + * no engine is declared, not enforced), and the knowledge source's + * `refresh.cron` with the `knowledge_source` type's admission (ADR-0161 K6), + * so a new one needs a reader first. * * No cron syntax is judged at parse time — `'not a cron'` normalizes like any * other string. `croner` judges the pattern where a schedule is wired - * (`CronSchedule.expression` → `toBoundaryJobSchedule` → `CronJobAdapter`); - * the knowledge-refresh slot is `[EXPERIMENTAL — not enforced]` by design and - * reaches no engine, and no grammar is restated here. + * (`CronSchedule.expression` → `toBoundaryJobSchedule` → `CronJobAdapter`), + * and no grammar is restated here. */ export const CronExpressionInputSchema = cronExpressionInput(ExpressionSchema, typedExpressionRefusals('cron')); export type CronExpressionInput = z.input; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 26d18d25a93..38ef64ba845 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -254,6 +254,9 @@ importers: '@objectstack/driver-sql': specifier: workspace:* version: link:../../packages/drivers/driver-sql + '@objectstack/knowledge-memory': + specifier: workspace:* + version: link:../../packages/plugins/knowledge-memory '@objectstack/organizations': specifier: workspace:* version: link:../../packages/plugins/organizations @@ -266,6 +269,9 @@ importers: '@objectstack/service-i18n': specifier: workspace:* version: link:../../packages/services/service-i18n + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../../packages/services/service-knowledge '@objectstack/service-print': specifier: workspace:* version: link:../../packages/services/service-print diff --git a/skills/objectstack-ai/SKILL.md b/skills/objectstack-ai/SKILL.md index a057470e3e9..d023322a63b 100644 --- a/skills/objectstack-ai/SKILL.md +++ b/skills/objectstack-ai/SKILL.md @@ -290,13 +290,13 @@ dev/test), `@objectstack/knowledge-pgvector` (`'pgvector'`) or `@objectstack/kno import { KnowledgeSourceSchema, type KnowledgeSource } from '@objectstack/spec/ai'; export const supportKb: KnowledgeSource = KnowledgeSourceSchema.parse({ - id: 'support_kb', + name: 'support_kb', label: 'Support Knowledge Base', adapter: 'pgvector', source: { kind: 'object', object: 'kb_article', - contentFields: ['title', 'body'], // concatenated into document content + content: ['title', 'body'], // concatenated into document content metadataFields: ['category', 'owner_id'], // projected for search-time filtering where: { published: true }, // index published articles only }, diff --git a/skills/objectstack-ai/references/_index.md b/skills/objectstack-ai/references/_index.md index 3f51b69e791..0e41003dbe7 100644 --- a/skills/objectstack-ai/references/_index.md +++ b/skills/objectstack-ai/references/_index.md @@ -10,7 +10,7 @@ from `node_modules` — there is no local copy in the skill bundle. ## Core schemas - `node_modules/@objectstack/spec/src/ai/agent.zod.ts` — Exports: AIModelConfigSchema, StructuredOutputFormatSchema, TransformPipelineStepSchema, StructuredOutputConfigSchema, AgentSchema -- `node_modules/@objectstack/spec/src/ai/knowledge-source.zod.ts` — Knowledge Source — declarative metadata describing what to index and +- `node_modules/@objectstack/spec/src/ai/knowledge-source.zod.ts` — Knowledge Source — the governed metadata type `knowledge_source` - `node_modules/@objectstack/spec/src/ai/model-registry.zod.ts` — AI Model Registry Protocol - `node_modules/@objectstack/spec/src/ai/skill.zod.ts` — Skill Trigger Condition Schema - `node_modules/@objectstack/spec/src/ai/solution-blueprint.zod.ts` — Solution Blueprint Schema (ADR-0033 §4 — plan-first authoring) @@ -18,7 +18,6 @@ from `node_modules` — there is no local copy in the skill bundle. ## Transitive dependencies -- `node_modules/@objectstack/spec/src/ai/embedding.zod.ts` — Embedding & Vector Store Primitives - `node_modules/@objectstack/spec/src/data/date-macros.zod.ts` — Date Macro Tokens — the declarative placeholders the UI substitutes - `node_modules/@objectstack/spec/src/data/field-value.zod.ts` — Field runtime VALUE-shape contract (ADR-0104 D1). - `node_modules/@objectstack/spec/src/data/field.zod.ts` — Exports: FieldType, SelectOptionSchema, LocationCoordinatesSchema, CurrencyConfigSchema, UniqueScopeSchema diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index d4ba63f9da9..3dcf5e99f03 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -36,7 +36,7 @@ are `manifest`, `packages`, `objects`, `objectExtensions`, `picklists`, `datasets`, `actions`, `flows`, `jobs`, `emailTemplates`, `docs`, `books`, `positions`, `permissions`, `capabilities`, `sharingRules`, `queues`, `assignmentRules`, `apis`, `webhooks`, `api`, `server`, -`agents`, `tools`, `skills`, `aiContexts`, `hooks`, `functions`, `mappings`, +`agents`, `tools`, `skills`, `aiContexts`, `knowledgeSources`, `hooks`, `functions`, `mappings`, `analyticsCubes`, `connectors`, `data` (seed), `datasources`, `datasourceMapping`, `translations`, `i18n`, `plugins`, `devPlugins`, `devHint`, `devLogins`, `demoStaff`, `requires`, `tiers`, `onEnable`, `appName`, `email`, `sms`, `push`. @@ -103,10 +103,10 @@ Every stack needs a `manifest`: ```typescript import { defineStack } from '@objectstack/spec'; export default defineStack({ manifest: { - id: 'com.example.crm', // Reverse domain unique ID + id: 'com.example.crm', // Reverse-domain ID version: '1.0.0', // Semver type: 'app', // app | plugin | driver | module | ... - name: 'Acme CRM', // Human-readable display name + name: 'Acme CRM', // Display name description: 'CRM system', // Optional engines: { protocol: '^19' }, } }); From f1fc0658e56956947c251eb5ee7583486dfbe215 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:55:46 +0000 Subject: [PATCH 08/29] chore(spec): rosters and bundles follow the knowledge_source type The variant ledger and the empty-state registry drop the entries of the retired file and http source kinds; llms.txt counts one module fewer under ai; the platform checklist waives the new kind with what retires the waiver; the metadata form bundles carry the type's label in every locale. skills/objectstack-platform/SKILL.md keeps only the knowledgeSources row: the two comment trims that made room for it are reverted (ruling A on #32584 allows the row and nothing else). Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .changeset/37304-knowledge-source-governed-type.md | 3 ++- docs/qa/platform-checklist/coverage.json | 3 +++ .../src/apps/translations/ar.metadata-forms.generated.ts | 3 +++ .../src/apps/translations/de.metadata-forms.generated.ts | 3 +++ .../src/apps/translations/en.metadata-forms.generated.ts | 3 +++ .../apps/translations/es-ES.metadata-forms.generated.ts | 3 +++ .../src/apps/translations/fr.metadata-forms.generated.ts | 3 +++ .../apps/translations/ja-JP.metadata-forms.generated.ts | 3 +++ .../src/apps/translations/ko.metadata-forms.generated.ts | 3 +++ .../apps/translations/pt-BR.metadata-forms.generated.ts | 3 +++ .../src/apps/translations/ru.metadata-forms.generated.ts | 3 +++ .../apps/translations/zh-CN.metadata-forms.generated.ts | 3 +++ .../apps/translations/zh-Hant.metadata-forms.generated.ts | 3 +++ packages/spec/llms.txt | 4 ++-- packages/spec/scripts/liveness/empty-state-registry.mts | 7 ------- packages/spec/variant-docs.json | 7 ------- skills/objectstack-platform/SKILL.md | 4 ++-- 17 files changed, 42 insertions(+), 19 deletions(-) diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index cc250dd3cb2..9d1eb426786 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -11,6 +11,7 @@ '@objectstack/core': patch '@objectstack/metadata': patch '@objectstack/cli': patch +'@objectstack/platform-objects': patch '@object-ui/app-shell': minor '@object-ui/i18n': minor '@object-ui/fields': patch @@ -40,7 +41,7 @@ ADR-0161 K4, K5, K6 and K8 item 4 (#37304). What changes: -- **The type.** `knowledge_source` is registered in the metadata type registry with the one schema `KnowledgeSourceSchema`; a stack carries its sources in the new top-level collection `knowledgeSources`, in `*.knowledge-source.ts` or `.yml` files. An item can be created and changed at run time (Studio, MCP); it takes no environment overlay. Studio's menu lists the type. Two packages may each ship a source of one name (ADR-0150, addendum of 2026-11-25): each has its own index, and `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. +- **The type.** `knowledge_source` is registered in the metadata type registry with the one schema `KnowledgeSourceSchema`; a stack carries its sources in the new top-level collection `knowledgeSources`, in `*.knowledge-source.ts` or `.yml` files. An item can be created and changed at run time (Studio, MCP); it takes no environment overlay. Studio's menu lists the type, and the metadata form bundles carry its label in every locale. Two packages may each ship a source of one name (ADR-0150, addendum of 2026-11-25): each has its own index, and `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. - **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. - **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. - **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. diff --git a/docs/qa/platform-checklist/coverage.json b/docs/qa/platform-checklist/coverage.json index 7efe788388d..2bcdca3de74 100644 --- a/docs/qa/platform-checklist/coverage.json +++ b/docs/qa/platform-checklist/coverage.json @@ -215,6 +215,9 @@ "integration-system.job-package-key" ] }, + "knowledge_source": { + "waived": "WAIVED 2026-11-26 — the kind is new (ADR-0161 K4, #37304) and no item has been run against it yet. What exists: the showcase declares one source (examples/app-showcase/src/ai/task-notes.knowledge-source.ts) and mounts the knowledge service with the in-memory store, so a booted showcase indexes its tasks and serves `search_knowledge`; the loader's rules (boot read, add, change, remove with the index dropped) are pinned in packages/services/service-knowledge/src/__tests__/knowledge-source-loader.test.ts, one name per source in knowledge-source-registry.test.ts beside it, and the two authoring guards in packages/rest/src/meta-type-write-capability.test.ts and packages/rest/src/meta-write-door-capability-enumeration.test.ts. WHAT RETIRES THIS WAIVER — the next coverage sweep authors an `ai.` item that boots the showcase, searches the task-notes source as an admin and as a member, saves a second source in Studio with and without `manage_knowledge_sources`, removes it and reads that its index is gone; the same edit replaces this waiver with `items` naming it." + }, "manifest": { "items": [ "platform-core.manifest-install-contract", diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 43316d31730..bd0c7b4dcfa 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const arMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "مصدر معرفة" } }; diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 2418140afd6..363b5502531 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const deMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "Wissensquelle" } }; diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 44c4749a0ef..cf02ba0b543 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const enMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "Knowledge Source" } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 489774cf924..89950cc921a 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const esESMetadataForms: NonNullable = helpText: "Un campo de texto largo del objeto raíz (textarea, markdown, html, richtext). Cualquier otro campo se informa al guardar el paquete, y entonces el paquete no lleva cuerpo." } } + }, + knowledge_source: { + label: "Fuente de conocimiento" } }; diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 06130d95ac2..ecd2916f635 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const frMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "Source de connaissances" } }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index ebb1443b29e..14dff3c4cf5 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const jaJPMetadataForms: NonNullable = helpText: "ルートオブジェクトの長文テキストフィールド(textarea、markdown、html、richtext)。それ以外のフィールドは保存時に報告され、パックは本文を持ちません。" } } + }, + knowledge_source: { + label: "ナレッジソース" } }; diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 700890fea29..c99c9314b82 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const koMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "지식 소스" } }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 473a97654d0..b44cafb643e 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const ptBRMetadataForms: NonNullable = helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "Fonte de conhecimento" } }; diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 62e6b87e23e..f250920c802 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const ruMetadataForms: NonNullable = { helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "Источник знаний" } }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index a560d1b6281..aa8ee8c2f65 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const zhCNMetadataForms: NonNullable = helpText: "根对象的一个长文本字段(textarea、markdown、html、richtext)。选其他字段会在保存时报告,资料包也就不带正文。" } } + }, + knowledge_source: { + label: "知识源" } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index b1851fb0e28..5842c03039c 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3202,5 +3202,8 @@ export const zhHantMetadataForms: NonNullable helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." } } + }, + knowledge_source: { + label: "知識來源" } }; diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index bb4b08b166e..e92bf20d53f 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (231 schemas) +## 3. Schema Inventory by Domain (230 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -92,7 +92,7 @@ here is verifiable from the installed package. | ui | 18 | View, App, Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | | shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) | -| ai | 17 | Agent, AI Context (context pack), Build Progress, Conversation, Dataset Tools, Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Citation, Record Context Tools (`get_record_context`), Skill, Tool | +| ai | 16 | Agent, AI Context (context pack), Build Progress, Conversation, Dataset Tools, Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Citation, Record Context Tools (`get_record_context`), Skill, Tool | | identity | 5 | Identity, Organization, Position, SCIM, Eval User | | marketplace | 5 | Marketplace, Package, Package Version, Template Manifest, Taxonomy | | security | 5 | Permission, RLS, Sharing, Queue, Explain | diff --git a/packages/spec/scripts/liveness/empty-state-registry.mts b/packages/spec/scripts/liveness/empty-state-registry.mts index 1260f4892af..4e0a184a9c1 100644 --- a/packages/spec/scripts/liveness/empty-state-registry.mts +++ b/packages/spec/scripts/liveness/empty-state-registry.mts @@ -215,13 +215,6 @@ export const EMPTY_STATE_REGISTRY: EmptyStateEntry[] = [ rationale: "Which VIEW a proposed app-menu entry opens; absent/null means the object's default list. It is presentation breadth, not authorization — the entry's `target` already fixes WHICH OBJECT is reachable, and record- and field-level security are enforced downstream, so naming a view can only ever change how the same permitted rows are laid out. The empty state is also the pre-existing behaviour every app already has, which is what makes it the safe default here (cloud#2150 added the key precisely because there was no way to say anything ELSE). Note the failure direction is cosmetic and visible: an entry labelled 「工单看板」 that omits this opens the list — wrong-looking, never over-granting.", }, - { - file: 'packages/spec/src/ai/knowledge-source.zod.ts', - property: 'mimeTypes', - semantics: 'scope', - rationale: - 'Which files under a storage prefix get indexed into a knowledge source. Ingestion scope, not read authorization — retrieval is gated separately. NOTE the shape though: it is a vacuous-allow-list ("allow-list" whose empty value admits everything), the same shape as #3896. `storage.zod.ts` models the identical concept the better way — an explicit `mode: "whitelist"` discriminator plus `.min(1)`, so an empty whitelist cannot be expressed at all. Prefer that form for new allow-lists; changing this one is a breaking change to an authorable field and is not in scope here.', - }, { file: 'packages/services/service-messaging/src/objects/notification-preference.object.ts', property: 'user_id', diff --git a/packages/spec/variant-docs.json b/packages/spec/variant-docs.json index 93b370fd587..fdbd42c0278 100644 --- a/packages/spec/variant-docs.json +++ b/packages/spec/variant-docs.json @@ -74,13 +74,6 @@ "content/docs/automation/hook-bodies.mdx" ] }, - { - "key": "kind:file|http|object", - "label": "knowledge source kind", - "docs": [ - "content/docs/protocol/knowledge.mdx" - ] - }, { "key": "type:cron|interval|once", "label": "job schedule", diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index 3dcf5e99f03..7356014b7f8 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -103,10 +103,10 @@ Every stack needs a `manifest`: ```typescript import { defineStack } from '@objectstack/spec'; export default defineStack({ manifest: { - id: 'com.example.crm', // Reverse-domain ID + id: 'com.example.crm', // Reverse domain unique ID version: '1.0.0', // Semver type: 'app', // app | plugin | driver | module | ... - name: 'Acme CRM', // Display name + name: 'Acme CRM', // Human-readable display name description: 'CRM system', // Optional engines: { protocol: '^19' }, } }); From deb49dcde5ed5597fade446eb5131cfd50efb4b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:16:25 +0000 Subject: [PATCH 09/29] test(knowledge): census row, collection-time imports and showcase aliases the gates ask for The system-context page keys the knowledge row to the symbols that hold the elevation reads now, the save admission included. Four edited suites pay their first load of a dynamically imported package at collection, and the showcase aliases the knowledge service and the in-memory store to source. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 6 ++++-- examples/app-showcase/vitest.config.ts | 5 +++++ .../src/rest-server-meta-org-scope-url-spelling.test.ts | 3 +++ packages/rest/src/rest-server-meta-write-org-scope.test.ts | 3 +++ .../runtime/src/domains/meta-save-capability-gate.test.ts | 3 +++ .../src/domains/meta-type-write-capability-parity.test.ts | 3 +++ 6 files changed, 21 insertions(+), 2 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index abe6626504b..d965bbf4025 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -189,7 +189,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources`, `searchWithRefusals` | +| 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -544,6 +544,7 @@ and CI refuses one that differs from what the tree produces. | `packages/core/src/security/tenant-layer0-verdict.ts#isOutsideEveryOrganization` | 1 | 6d | | `packages/mcp/src/stdio-data-bridge.ts#enforceApiExposure` | 1 | 15 | | `packages/mcp/src/tool-call-interceptor.ts#toolCallPrincipalOf` | 2 | 66 | +| `packages/metadata-core/src/knowledge-source-save-admission.ts#authoredKnowledgeSourceRefusal` | 1 | 46 | | `packages/metadata-core/src/meta-write-capability.ts#metaWriteCapabilityVerdict` | 1 | 51 | | `packages/metadata-core/src/meta-write-capability.ts#walledCatalogWriteVerdict` | 1 | 55b | | `packages/metadata-core/src/object-schema-fls.ts#isObjectSchemaMaskExempt` | 1 | 8 | @@ -701,9 +702,10 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b | | `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 | | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | +| `packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | -| `packages/services/service-knowledge/src/knowledge-service.ts#searchWithRefusals` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service.ts#searchByKey` | 1 | 46 | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/examples/app-showcase/vitest.config.ts b/examples/app-showcase/vitest.config.ts index e4826d630af..9ac704eb12d 100644 --- a/examples/app-showcase/vitest.config.ts +++ b/examples/app-showcase/vitest.config.ts @@ -78,12 +78,17 @@ export default defineConfig({ // [ADR-0160] The stack tests load `objectstack.config.ts`, whose plugins // include `RecordContextServicePlugin`: aliased so they boot the executor // in this checkout, not a build of it. + // + // [ADR-0161 K4] The same for `KnowledgeServicePlugin` and the in-memory + // store the showcase's knowledge source names. alias: [ { find: /^@objectstack\/formula$/, replacement: path.resolve(__dirname, '../../packages/formula/src/index.ts') }, { find: /^@objectstack\/plugin-email$/, replacement: path.resolve(__dirname, '../../packages/plugins/plugin-email/src/index.ts') }, { find: /^@objectstack\/lint$/, replacement: path.resolve(__dirname, '../../packages/lint/src/index.ts') }, { find: /^@objectstack\/service-print$/, replacement: path.resolve(__dirname, '../../packages/services/service-print/src/index.ts') }, { find: /^@objectstack\/service-record-context$/, replacement: path.resolve(__dirname, '../../packages/services/service-record-context/src/index.ts') }, + { find: /^@objectstack\/knowledge-memory$/, replacement: path.resolve(__dirname, '../../packages/plugins/knowledge-memory/src/index.ts') }, + { find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../../packages/services/service-knowledge/src/index.ts') }, ], }, test: { diff --git a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts index 3aad3e6a1c0..2edbb2f51ed 100644 --- a/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts +++ b/packages/rest/src/rest-server-meta-org-scope-url-spelling.test.ts @@ -51,6 +51,9 @@ import { describe, it, expect, vi } from 'vitest'; import { META_URL_TO_SINGULAR } from '@objectstack/spec/meta-spelling'; import { RestServer } from './rest-server.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/objectql'; + const META = '/api/v1/meta'; const ORG = 'org_alpha'; diff --git a/packages/rest/src/rest-server-meta-write-org-scope.test.ts b/packages/rest/src/rest-server-meta-write-org-scope.test.ts index de6775fa0c2..5e4375419a4 100644 --- a/packages/rest/src/rest-server-meta-write-org-scope.test.ts +++ b/packages/rest/src/rest-server-meta-write-org-scope.test.ts @@ -27,6 +27,9 @@ import * as metadataCore from '@objectstack/metadata-core'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { RestServer } from './rest-server.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/objectql'; + const META = '/api/v1/meta'; const ORG = 'org_alpha'; diff --git a/packages/runtime/src/domains/meta-save-capability-gate.test.ts b/packages/runtime/src/domains/meta-save-capability-gate.test.ts index eb280bb5975..3c410fb14f3 100644 --- a/packages/runtime/src/domains/meta-save-capability-gate.test.ts +++ b/packages/runtime/src/domains/meta-save-capability-gate.test.ts @@ -42,6 +42,9 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; + /** An object schema carrying a field a restricted caller would never be served. */ const STORED_SCHEMA = { name: 'account', diff --git a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts index 29688c64af6..af357a1e6a0 100644 --- a/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts +++ b/packages/runtime/src/domains/meta-type-write-capability-parity.test.ts @@ -17,6 +17,9 @@ import { describe, it, expect, vi } from 'vitest'; import { RestServer } from '@objectstack/rest'; import { HttpDispatcher } from '../http-dispatcher.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; + const WAREHOUSE = { name: 'warehouse', label: 'Warehouse', driver: 'postgres', config: { host: 'warehouse-db.fixture.internal', port: 5432 } }; const WAREHOUSE_EDIT = { ...WAREHOUSE, label: 'Warehouse (edited)' }; const LEADS_VIEW = { name: 'all_leads', label: 'All leads', object: 'lead', columns: ['name'] }; From aaf309b228ebbfa02ef603ea476df1978ccc3636 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:01:29 +0000 Subject: [PATCH 10/29] =?UTF-8?q?chore(spec):=20after=20the=20merge=20of?= =?UTF-8?q?=20main=20=E2=80=94=20default=20declaration=20under=20major=201?= =?UTF-8?q?9,=20skills=20ceiling=20by=20the=20row's=20delta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spec package reads 19 on main, so the declared default of ai/KnowledgeSource:refresh moves from the major-18 rows to major 19, the only major that authorises it now. skills/objectstack-platform/SKILL.md: the ceiling moves 6151 -> 6156 for the knowledgeSources enumeration row alone (+20 priced bytes), under ruling A on #32584 and #32673 letter A. Nothing else in the file changes. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/scripts/lib/default-changes.ts | 2 ++ scripts/check-skills-token-ratchet.mjs | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/spec/scripts/lib/default-changes.ts b/packages/spec/scripts/lib/default-changes.ts index cc6a335a98b..ab0fb6ed142 100644 --- a/packages/spec/scripts/lib/default-changes.ts +++ b/packages/spec/scripts/lib/default-changes.ts @@ -797,6 +797,8 @@ export const DEFAULT_CHANGES_BY_MAJOR: Readonly 6151 (+2). Pinned AT // the measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 20) / 4) == ceil(24603 / 4) - ['skills/objectstack-platform/SKILL.md', 6151], + // 6151 -> 6156 (card #37304): the enumeration row for the new top-level + // collection `knowledgeSources` — the key joins the list of `defineStack()` + // top-level keys, which `check:skill-top-level-keys` holds exhaustive over + // `ObjectStackDefinitionSchema`. The standing enumeration-row case: ruling A + // on #32584 (record 6819475461), made standing by #32673 letter A (record + // 6840575378). Raised by the row's own measured delta and by no more; + // nothing else in the file is cut and nothing rides along. Arithmetic in + // priced bytes (stamp line excluded): on the base the text is 24603 bytes + // (6151 tokens, headroom 0); the row adds 20 bytes, so the LANDED priced + // text is 24623 bytes -> 6156 tokens: the ceiling moves 6151 -> 6156 (+5). + // Pinned AT the measurement. + ['skills/objectstack-platform/SKILL.md', 6156], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: // the maintainer deleted the published PM skill whole (verbatim: From 15d0855a19d52bc140c9ad5310a966c977de1b2d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:05:26 +0000 Subject: [PATCH 11/29] chore(changeset): name the skills follow-up card The teaching of knowledge_source in skills/objectstack-ai rides #37310. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .changeset/37304-knowledge-source-governed-type.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index 9d1eb426786..ada41dc0477 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -21,7 +21,7 @@ feat(spec)!: a knowledge source is a governed metadata type, `knowledge_source`, Clause-②: yes (narrowing) Metadata-protocol: narrowed -Skills-docs: `skills/objectstack-platform/SKILL.md` lists the new top-level key `knowledgeSources`; `skills/objectstack-ai/SKILL.md`'s compiled `supportKb` example writes `name` and `content`. Teaching the type in `skills/objectstack-ai` is a later change. +Skills-docs: follow-up #37310. Here only the enumeration row: `skills/objectstack-platform/SKILL.md` lists the new top-level key `knowledgeSources`, and `skills/objectstack-ai/SKILL.md`'s compiled `supportKb` example writes `name` and `content`, because the 18 spelling no longer parses. From 2510f5303f22c15c80f5f8e2ef0b422bfd0b04d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:58:21 +0000 Subject: [PATCH 12/29] test(spec): pin the knowledge source's retired keys to their release; drop the embedding row from the protocol map The three conversions admitted with the type join the removal-version pin (every retired key refused from 19 on), and the protocol map no longer links the removed embedding module. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/PROTOCOL_MAP.md | 1 - .../shared/retired-key-removal-version.pin.test.ts | 12 ++++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/spec/PROTOCOL_MAP.md b/packages/spec/PROTOCOL_MAP.md index cb72ba89603..b1bc0e502b7 100644 --- a/packages/spec/PROTOCOL_MAP.md +++ b/packages/spec/PROTOCOL_MAP.md @@ -82,7 +82,6 @@ This document serves as the **Grand Map** of the ObjectStack specification. It l | [`conversation.zod.ts`](src/ai/conversation.zod.ts) | | **Chat Session**. History and context management for AI chats. | | [`knowledge-source.zod.ts`](src/ai/knowledge-source.zod.ts) | | **Knowledge Source**. What to index and which adapter to use (the RAG retrieval binding). | | [`knowledge-document.zod.ts`](src/ai/knowledge-document.zod.ts) | | **Knowledge Document**. Document / chunk / hit shapes shared by every knowledge adapter. | -| [`embedding.zod.ts`](src/ai/embedding.zod.ts) | | **Embeddings**. Embedding model and vector store configuration. | | [`solution-blueprint.zod.ts`](src/ai/solution-blueprint.zod.ts) | | **Solution Blueprint**. Plan-first authoring target for high-level goals (ADR-0033). | | [`usage.zod.ts`](src/ai/usage.zod.ts) | | **Usage**. Token consumption measurement. Was `cost`. | diff --git a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts index 03d9a16cbc4..611a3c45c4b 100644 --- a/packages/spec/src/shared/retired-key-removal-version.pin.test.ts +++ b/packages/spec/src/shared/retired-key-removal-version.pin.test.ts @@ -100,6 +100,7 @@ import { JobSchema } from '../system/job.zod'; import { TranslationBundleSchema, TranslationItemSchema } from '../system/translation.zod'; import { PROTOCOL_MAJOR } from '../kernel/protocol-version'; import { EmailTemplateDefinitionSchema } from '../system/email-template.zod'; +import { KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, ObjectKnowledgeSourceSchema } from '../ai/knowledge-source.zod'; import { ActionButtonPropsSchema, ActionGroupPropsSchema, @@ -649,6 +650,17 @@ const JOIN: Readonly> = { 'cube-sub-day-granularities-removed': [ refusal('a sub-day TimeUpdateInterval member', () => TimeUpdateInterval.safeParse('minute')), ], + // #37304 (ADR-0161 K6): the knowledge source's keys, settled as the type is admitted. + 'knowledge-source-id-to-name': [tombstone(KnowledgeSourceSchema, 'knowledge_source', 'id')], + 'knowledge-source-content-fields-to-content': [ + tombstone(ObjectKnowledgeSourceSchema, 'knowledge_source.source', 'contentFields'), + ], + 'knowledge-source-inert-keys-removed': [ + tombstone(KnowledgeSourceSchema, 'knowledge_source', 'embedding'), + tombstone(KnowledgeSourceSchema, 'knowledge_source', 'vectorStore'), + tombstone(KnowledgeSourceSchema, 'knowledge_source', 'adapterConfig'), + tombstone(KnowledgeRefreshPolicySchema, 'knowledge_source.refresh', 'cron'), + ], }; /** Every major a prescription names as a release: `@objectstack/spec N[.x.y]` or `protocol N`. */ From 33d5511cef6014b96df5bbfcc5069925f799d401 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:54:23 +0000 Subject: [PATCH 13/29] chore(spec): regenerate the ai surfaces after the second merge of main The authorable-surface baseline keeps the knowledge source's retired lines out and takes main's new skill key; api-surface, export-origins and the skills reference index are regenerated from the merged tree. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/api-surface/ai.json | 1 + packages/spec/authorable-surface/ai.json | 1 + packages/spec/export-origins/ai.json | 1 + skills/objectstack-ai/references/_index.md | 1 + 4 files changed, 4 insertions(+) diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 7845ae98bbc..665a787aa23 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -288,6 +288,7 @@ "getRecordContextToolJsonSchemas (function)", "headingsOf (function)", "scopesToAgentPermissionSets (function)", + "skillBindsRecordContextTool (function)", "skillForm (const)", "stripBodyTags (function)", "toolForm (const)" diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 4432b3786e5..9ce11d6cc11 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -461,6 +461,7 @@ "ai/Skill:_packageVersion", "ai/Skill:_provenance", "ai/Skill:active", + "ai/Skill:context", "ai/Skill:description", "ai/Skill:instructions", "ai/Skill:label", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 4af3c08a963..1c61062bafc 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -285,6 +285,7 @@ "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", + "skillBindsRecordContextTool": "src/ai/skill.zod.ts#skillBindsRecordContextTool (function)", "skillForm": "src/ai/skill.form.ts#skillForm (const)", "stripBodyTags": "src/ai/record-body-anchor.ts#stripBodyTags (function)", "toolForm": "src/ai/tool.form.ts#toolForm (const)" diff --git a/skills/objectstack-ai/references/_index.md b/skills/objectstack-ai/references/_index.md index 0e41003dbe7..fa0ae88302c 100644 --- a/skills/objectstack-ai/references/_index.md +++ b/skills/objectstack-ai/references/_index.md @@ -18,6 +18,7 @@ from `node_modules` — there is no local copy in the skill bundle. ## Transitive dependencies +- `node_modules/@objectstack/spec/src/ai/record-context-tools.zod.ts` — Exports: GetRecordContextInputSchema, RecordContextFieldEntrySchema, RecordContextRelatedRowSchema, RecordContextRelatedListSchema, RecordContextOutlineEntrySchema - `node_modules/@objectstack/spec/src/data/date-macros.zod.ts` — Date Macro Tokens — the declarative placeholders the UI substitutes - `node_modules/@objectstack/spec/src/data/field-value.zod.ts` — Field runtime VALUE-shape contract (ADR-0104 D1). - `node_modules/@objectstack/spec/src/data/field.zod.ts` — Exports: FieldType, SelectOptionSchema, LocationCoordinatesSchema, CurrencyConfigSchema, UniqueScopeSchema From 3ea6a22aafec5483985ed82dc3be408417272cca Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:17:05 +0000 Subject: [PATCH 14/29] test(metadata): the owner-stamp boot fixtures carry a knowledge source Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/metadata/src/owner-stamp-residual-build-boot.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts index 4ff53ca2d24..fc7a55972d2 100644 --- a/packages/metadata/src/owner-stamp-residual-build-boot.test.ts +++ b/packages/metadata/src/owner-stamp-residual-build-boot.test.ts @@ -99,6 +99,9 @@ const JUDGED_FIXTURES: Record Date: Thu, 26 Nov 2026 21:43:15 +0000 Subject: [PATCH 15/29] test: the type and tier pins in metadata, metadata-protocol and platform-objects count the knowledge source Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../protocol.legacy-overlay-delete.test.ts | 3 ++- ...metadata-manager-keyed-plural-read.test.ts | 5 +++-- .../bare-type-display-echo-decisions.test.ts | 19 +++++++++++-------- ...ect-lifecycle-panel-echo-decisions.test.ts | 4 +++- 4 files changed, 19 insertions(+), 12 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts b/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts index d1691bdaf66..4a554d34a1c 100644 --- a/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts +++ b/packages/metadata-protocol/src/protocol.legacy-overlay-delete.test.ts @@ -275,8 +275,9 @@ describe('#6960 — the registry is the tier boundary, and it is DATA', () => { */ it('names the rolled-back overlayable tier exactly as the registry declares it', () => { // [ADR-0160 D1] `ai_context` registers like `skill`, overlay allowed, so it joins the tier. + // [ADR-0161 K4] `knowledge_source` registers with `ai_context`'s flags, so it joins too. expect([...ROLLED_BACK_OVERLAYABLE_TYPES]).toEqual([ - 'ai_context', 'app', 'book', 'dataset', 'page', 'permission', 'position', 'skill', 'tool', + 'ai_context', 'app', 'book', 'dataset', 'knowledge_source', 'page', 'permission', 'position', 'skill', 'tool', ]); // The six commit ee58392e1 named, all present. for (const t of ['permission', 'position', 'page', 'app', 'dataset', 'book']) { diff --git a/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts b/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts index 6d092a408ee..8ddd0cc0bec 100644 --- a/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts +++ b/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts @@ -403,8 +403,9 @@ describe('[#32517] the unscoped plural reads answer every package\'s item of an const B = 'com.acme.beta'; // [#31699 PR 2] `webhook` joins the slotted set, and so these plural reads; // [#31985] `tool` joins with its narrowing; [#31699 PR 3] `connector` with its; - // `ai_context` with the ADR-0150 addendum (packs are identified by package + name). - const UNBUNDLED = ['api', 'agent', 'skill', 'action', 'flow', 'permission', 'picklist', 'mapping', 'dataset', 'webhook', 'tool', 'connector', 'ai_context']; + // `ai_context` with the ADR-0150 addendum (packs are identified by package + name); + // `knowledge_source` with ADR-0161 K4 (a source is held by package + name). + const UNBUNDLED = ['api', 'agent', 'skill', 'action', 'flow', 'permission', 'picklist', 'mapping', 'dataset', 'webhook', 'tool', 'connector', 'ai_context', 'knowledge_source']; const NAME = 'shared_item'; const item = (packageId: string | undefined, extra: Record = {}) => ({ name: NAME, diff --git a/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts index 24f0fb9b307..8d1eac9c6b0 100644 --- a/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts @@ -794,7 +794,7 @@ describe('#19403 round 7 — the provenance table agrees these leaves are now au }); describe('#19403 round 7 — the population, DERIVED from the registry and a shape', () => { - it('⭐ the registry and the catalog describe the same 33 metadata types', () => { + it('⭐ the registry and the catalog describe the same 34 metadata types', () => { // The ratchet's anchor. The catalog is GENERATED from this registry, so a // new metadata type arrives in both at once — which is what makes the bare // class below pick up a future unauthored display pair without anybody @@ -807,7 +807,9 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha // description, authored in the three locales on arrival. // 32 → 33: `ai_context` joined it (ADR-0160 D1, #37140), bare with a label // and no description, authored in the three locales on arrival. - expect(REGISTRY_TYPES.length).toBe(33); + // 33 → 34: `knowledge_source` joined it (ADR-0161 K4, #37304), bare with a + // label and no description, authored in every locale on arrival. + expect(REGISTRY_TYPES.length).toBe(34); expect([...REGISTRY_TYPES].sort()).toEqual(Object.keys(enMetadataForms as Record).sort()); }); @@ -815,16 +817,17 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha // Lit. // 16 / 17 → 15 / 18: `ai_context` gained its form (ADR-0160 D1 clause 2, // #37143), so it is a panel type now. - expect(BARE_TYPES.length).toBe(15); + // 15 / 18 → 16 / 18: `knowledge_source` arrives bare (#37304). + expect(BARE_TYPES.length).toBe(16); expect(PANEL_TYPES.length).toBe(18); expect(BARE_TYPES.length + PANEL_TYPES.length).toBe(REGISTRY_TYPES.length); for (const type of ['seed', 'mapping', 'api', 'doc', 'book', 'capability', 'picklist', 'sharing_rule', 'queue', 'assignment_rule', 'object_extension']) { expect(BARE_TYPES, `${type} is bare`).toContain(type); } for (const type of AUTHORED_BARE_TYPES) expect(BARE_TYPES, `${type} is bare`).toContain(type); - // 26 leaves: fifteen labels, and a description on the eleven that carry one. - expect(BARE_LEAVES.length).toBe(26); - expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(15); + // 27 leaves: sixteen labels, and a description on the eleven that carry one. + expect(BARE_LEAVES.length).toBe(27); + expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(16); expect(BARE_LEAVES.filter((l) => l.prop === 'description').length).toBe(11); expect(BARE_LEAVES.every((l) => ['label', 'description'].includes(l.prop))).toBe(true); }); @@ -906,13 +909,13 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha expect(flagged.length).toBe(BARE_LEAVES.length); }); - it('⭐ this class is now DONE — zero of its 26 leaves echoes in all three locales', () => { + it('⭐ this class is now DONE — zero of its 27 leaves echoes in all three locales', () => { const echoing = BARE_LEAVES.filter((l) => TRANSLATED_LOCALES.every(([, forms]) => forms[l.type]?.[l.prop] === l.en), ); expect(echoing.map((l) => `${l.type}.${l.prop}`)).toEqual([]); // Lit — and it really walked the class, which a zero alone would not show. - expect(BARE_LEAVES.length).toBe(26); + expect(BARE_LEAVES.length).toBe(27); }); }); diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 3a2342e7686..ac0dd843869 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1343,7 +1343,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // `uiReadonlyWhen` rows (the hand lock), authored in every locale. // 840 since #37141: the skill form's `context` row (ADR-0160 D8) — one // row label, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(840); + // 841 since #37304: the `knowledge_source` type's own label (ADR-0161 + // K4), authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(841); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From b79a9793518373a20bbefad4145af66be2d4b530 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:43:59 +0000 Subject: [PATCH 16/29] chore(i18n): regenerate zh-Hant from its zh-Hans source for the knowledge source strings Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- ui/packages/i18n/src/locales/zh-Hant.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index b63ed1f4c83..d8de3bdcf4c 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -36,7 +36,7 @@ const zhHant = { manage_metadata: '管理中繼資料', manage_mailboxes: '管理郵箱', manage_connector_connections: '管理聯結器連線', - manage_knowledge_sources: '管理知識來源', + manage_knowledge_sources: '管理知識源', manage_platform_settings: '管理平台設定', setup_access: '訪問 Setup', setup_write: '儲存設定', @@ -4277,9 +4277,9 @@ const zhHant = { ai_context: 'AI 上下文包 {{count}}', ai_context_one: 'AI 上下文包 {{count}}', ai_context_other: 'AI 上下文包 {{count}}', - knowledge_source: '知識來源 {{count}}', - knowledge_source_one: '知識來源 {{count}}', - knowledge_source_other: '知識來源 {{count}}', + knowledge_source: '知識源 {{count}}', + knowledge_source_one: '知識源 {{count}}', + knowledge_source_other: '知識源 {{count}}', datasource: '資料來源 {{count}}', datasource_one: '資料來源 {{count}}', datasource_other: '資料來源 {{count}}', From 7dd6fdcf908c52e166afb3eafba8e5067bdcddb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:45:27 +0000 Subject: [PATCH 17/29] docs(adr): ADR-0084's type table carries the knowledge_source row its item 6 prescribes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One row under AI (order 5, 高级), in the spelling of the ai_context row; the Studio menu placement test reads this table. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- docs/adr/0084-application-builder-information-architecture.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/0084-application-builder-information-architecture.md b/docs/adr/0084-application-builder-information-architecture.md index 881a99bcddd..ca58f881e45 100644 --- a/docs/adr/0084-application-builder-information-architecture.md +++ b/docs/adr/0084-application-builder-information-architecture.md @@ -204,6 +204,7 @@ Every type the spec registers, enumerated at `origin/main` `151e8123` from `pack | **AI** | `ai` | 2 | `tool` 工具 | 常用 | | **AI** | `ai` | 3 | `skill` 技能 | 常用 | | **AI** | `ai` | 4 | `ai_context` *(registered after the ruling — [item 6](#amendment-2026-11-25-silent))* | 高级 | +| **AI** | `ai` | 5 | `knowledge_source` *(registered after the ruling — [item 6](#amendment-2026-11-25-silent))* | 高级 | *(Amended 2026-11-25: the table is redrawn one row per type and gains two columns, **Order** and **Tier** — [Amendment (2026-11-25)](#amendment-2026-11-25). Read again at `origin/main` `a33691e567`: 33 entries — the 32 of the first reading, each in the domain it had, and `ai_context`, registered `ai` on 2026-11-25 ([ADR-0160](./0160-record-scoped-ai-inquiry.md) D1). No type changed group, and the rows count 数据 Data 7 · 界面 UI 7 · 自动化 Automation 2 · 平台 Platform 7 · 访问 Access 6 · AI 4.)* From 45ed21271be3d1302a4e34d0c85e0da86fb8fccc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:10:02 +0000 Subject: [PATCH 18/29] test(plugin-security): platform administrator goldens carry manage_knowledge_sources The platform administrator's built-in grant set now holds the knowledge source capability beside manage_metadata (#37304, ADR-0161), so the four golden lists that pin that set gain the one entry. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../plugin-security/src/builtin-positions.boot.test.ts | 2 ++ .../src/grant-permission-set-name.equivalence.test.ts | 4 ++-- .../plugin-security/src/grant-readers-by-name.golden.test.ts | 2 ++ .../src/resolve-authz-grant-set-by-name.golden.test.ts | 4 ++++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-security/src/builtin-positions.boot.test.ts b/packages/plugins/plugin-security/src/builtin-positions.boot.test.ts index e1a1e98e190..82a30ba87a1 100644 --- a/packages/plugins/plugin-security/src/builtin-positions.boot.test.ts +++ b/packages/plugins/plugin-security/src/builtin-positions.boot.test.ts @@ -690,6 +690,7 @@ const GRANT_GOLDEN: Record<'single' | 'isolated', unknown> = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', @@ -740,6 +741,7 @@ const GRANT_GOLDEN: Record<'single' | 'isolated', unknown> = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', diff --git a/packages/plugins/plugin-security/src/grant-permission-set-name.equivalence.test.ts b/packages/plugins/plugin-security/src/grant-permission-set-name.equivalence.test.ts index 2be42235a68..a3aad8cc1aa 100644 --- a/packages/plugins/plugin-security/src/grant-permission-set-name.equivalence.test.ts +++ b/packages/plugins/plugin-security/src/grant-permission-set-name.equivalence.test.ts @@ -287,7 +287,7 @@ const GOLDEN: Record<'single' | 'isolated', unknown> = { positions: ['everyone', 'platform_admin'], posture: 'PLATFORM_ADMIN', systemPermissions: [ - 'manage_connector_connections', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', 'manage_sharing', 'manage_users', + 'manage_connector_connections', 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', 'manage_sharing', 'manage_users', 'setup.access', 'setup.write', 'studio.access', 'view_all_audit_log', ], }, @@ -326,7 +326,7 @@ const GOLDEN: Record<'single' | 'isolated', unknown> = { positions: ['everyone', 'platform_admin'], posture: 'PLATFORM_ADMIN', systemPermissions: [ - 'manage_connector_connections', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', 'manage_sharing', 'manage_users', + 'manage_connector_connections', 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', 'manage_sharing', 'manage_users', 'setup.access', 'setup.write', 'studio.access', 'view_all_audit_log', ], }, diff --git a/packages/plugins/plugin-security/src/grant-readers-by-name.golden.test.ts b/packages/plugins/plugin-security/src/grant-readers-by-name.golden.test.ts index 87fe02aafc7..8635f4a7ab0 100644 --- a/packages/plugins/plugin-security/src/grant-readers-by-name.golden.test.ts +++ b/packages/plugins/plugin-security/src/grant-readers-by-name.golden.test.ts @@ -384,6 +384,7 @@ const SINGLE: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', @@ -477,6 +478,7 @@ const WALLED: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', diff --git a/packages/plugins/plugin-security/src/resolve-authz-grant-set-by-name.golden.test.ts b/packages/plugins/plugin-security/src/resolve-authz-grant-set-by-name.golden.test.ts index 9ee9f92857a..f7168adc2ca 100644 --- a/packages/plugins/plugin-security/src/resolve-authz-grant-set-by-name.golden.test.ts +++ b/packages/plugins/plugin-security/src/resolve-authz-grant-set-by-name.golden.test.ts @@ -419,6 +419,7 @@ const SINGLE: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', @@ -447,6 +448,7 @@ const SINGLE: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', @@ -610,6 +612,7 @@ const WALLED: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', @@ -638,6 +641,7 @@ const WALLED: unknown = { posture: 'PLATFORM_ADMIN', systemPermissions: [ 'manage_connector_connections', + 'manage_knowledge_sources', 'manage_mailboxes', 'manage_metadata', 'manage_platform_settings', From 1c17182d81b61a4e5362bb33ababdb98d523ff7e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:49:51 +0000 Subject: [PATCH 19/29] fix(spec): a knowledge source's content refuses an empty-string member The member names no field and indexed nothing. The refusal is a length, so the published JSON Schema carries it too; the semantic entry of the contentFields rename says so. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/src/ai/knowledge-source.test.ts | 14 ++++++++++++++ packages/spec/src/ai/knowledge-source.zod.ts | 14 ++++++++++---- .../19.knowledge-source-content-lists-fields.ts | 1 + 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 0d5d578ff97..0acb02d6a0c 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -19,6 +19,7 @@ // is the last case here. import { describe, expect, it } from 'vitest'; +import { z } from 'zod'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '../kernel/metadata-plugin.zod'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { ObjectStackDefinitionSchema } from '../stack.zod'; @@ -202,6 +203,19 @@ describe('KnowledgeSourceSchema — `content` lists fields (ADR-0161 K5)', () => ]); }); + it('refuses an empty-string member at its own path: it names no field and would index nothing', () => { + const issues = issuesOf({ ...SOURCE, source: { ...SOURCE.source, content: ['title', ''] } }); + expect(issues).toHaveLength(1); + const [code, at, message] = issues[0]!; + expect([code, at]).toEqual(['too_small', 'source.content.1']); + expect(message).toContain('an empty string names no field'); + // The published JSON Schema refuses it too: the constraint is a length, not a refinement. + const published = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as unknown as { + properties: { source: { properties: { content: { items: { minLength?: number } } } } }; + }; + expect(published.properties.source.properties.content.items.minLength).toBe(1); + }); + it("a field whose name merely contains `*` is not the wildcard — only the bare `'*'` member is refused here", () => { // Whether such a field exists is the admission gate's question, at save // and at search; the parse refuses the wildcard and nothing else. diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index fcbea5acea6..52cc3af61ae 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -141,10 +141,16 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * fields are never indexed, even when named. */ content: z.array( - // A pattern, not a `.refine()`: the published JSON Schema then refuses - // the member too, so a document validated against the file is not - // refused a release later by the parse. - z.string().regex(/^(?!\*$)/, { + // A length and a pattern, not a `.refine()`: the published JSON Schema + // then refuses the member too, so a document validated against the file + // is not refused a release later by the parse. The length refuses the + // empty string, which names no field and indexed nothing. + z.string().min(1, { + message: + '`knowledge_source.source.content` lists field names: an empty string names no field, so nothing is ' + + 'indexed for that member. Remove the member, or write the name of the field whose text should be ' + + 'indexed, for example `content: [\'title\', \'body\']`.', + }).regex(/^(?!\*$)/, { message: '`knowledge_source.source.content` lists field names: the `\'*\'` member was removed in @objectstack/spec ' + '19.0.0 (ADR-0161 K5) — embedding is egress, and `\'*\'` sent every text field of the record to the ' diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts index 55395ec1a90..313fbf256d7 100644 --- a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-content-lists-fields.ts @@ -23,6 +23,7 @@ export const entry: SemanticMigration = { + 'the source was written included. Each field in `content` is sent, for every record the source selects, ' + 'to the embedding provider the deployment configures, so the list is a statement of what leaves the ' + 'deployment, and a wildcard states nothing. The parse now refuses the member and names the fix; ' + + 'it refuses an empty-string member too, which named no field and indexed nothing: remove it. ' + 'the chain replay renames the key, keeps the member and reports the site as a hand edit. ' + 'Which fields to list is known only to the source\'s author: the ones users search by, and none that ' + 'should not be sent to the provider.', From d15de9a72445831b43ab0087bdce27bfb5ca2b51 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:49:52 +0000 Subject: [PATCH 20/29] fix(service-knowledge): source admission judges the fields a source's where reads The field gate asked about the fields a source serves. It now asks about the fields its where reads as well, by the same rule, at save and at search; a refusal at save names the field and the key to edit. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../knowledge-source-admission.test.ts | 53 ++++++++++++++ .../src/knowledge-service.ts | 22 ++++-- .../src/knowledge-source-admission.ts | 72 ++++++++++++++++--- 3 files changed, 135 insertions(+), 12 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index a948b55d25f..80fa752b14d 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts @@ -126,6 +126,29 @@ describe('field gate — a source serving a field the caller may not query is no expect(searched()).toEqual(['bodies']); // never searched, not searched-then-dropped }); + it('the fields a source\'s `where` reads are judged too: one the caller may not query refuses the source', async () => { + const selecting = (id: string, where: Record): KnowledgeSource => { + const source = objectSource(id, 'ticket', ['body']); + return { ...source, source: { ...source.source, where } as ObjectKnowledgeSource }; + }; + const { svc, searched } = setup({ + sources: [ + selecting('by_key', { salary_note: { $ne: null } }), + selecting('nested', { $and: [{ status: 'open' }, { $or: [{ $not: { salary_note: 'x' } }] }] }), + selecting('dotted', { 'salary_note.grade': 3 }), + selecting('comparand', { body: { $eq: { $field: 'salary_note' } } }), + selecting('open_only', { status: 'open' }), + ], + security: salaryHiddenFromMembers, + }); + expect(ids(await svc.search('raise', { executionContext: MEMBER }))).toEqual(['open_only']); + expect(searched()).toEqual(['open_only']); // never searched, not searched-then-dropped + // Preservation: a caller who may query the field is served every one of them. + expect(ids(await svc.search('raise', { executionContext: MANAGER }))).toEqual( + ['by_key', 'comparand', 'dotted', 'nested', 'open_only'], + ); + }); + it('preservation: a manager who may query every field, and the system context, get the hit', async () => { const { svc } = setup({ sources: [objectSource('notes', 'ticket', ['body', 'salary_note'])], @@ -437,6 +460,36 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, field: 'salary_note' }); }); + it.each([ + ['a condition key', { salary_note: { $ne: null } }], + ['a key under $and / $or / $not', { $and: [{ status: 'open' }, { $or: [{ $not: { salary_note: 'x' } }] }] }], + ['a dotted path, by its first segment', { 'salary_note.grade': 3 }], + ['a cross-field comparand', { body: { $eq: { $field: 'salary_note' } } }], + ])('a field the `where` reads is judged like a served one: %s', async (_label, where) => { + const { svc } = setup({ sources: [], security: salaryHiddenFromMembers }); + const verdict = await svc.admitAuthoredSource(item('ticket', ['body'], { where }), MEMBER); + expect(verdict).toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, object: 'ticket', field: 'salary_note' }); + const message = (verdict as { message: string }).message; + expect(message).toContain("its `where` reads field 'salary_note' of object 'ticket'"); + expect(message).toContain('Remove the field from `where`'); + // The same source, by an author who may query the field, and by the engine itself. + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { where }), MANAGER)).toEqual({ admitted: true }); + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { where }), SYSTEM)).toEqual({ admitted: true }); + }); + + it('CONTROL: a `where` over fields the author may query is admitted, and a `where` that is no condition names no field', async () => { + const { svc } = setup({ sources: [], security: salaryHiddenFromMembers }); + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { where: { status: { $in: ['open', 'new'] } } }), MEMBER)) + .toEqual({ admitted: true }); + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { where: 'status = open' }), MEMBER)).toEqual({ admitted: true }); + }); + + it('a `where` key that is neither a logical key nor a field the author may query is refused: an unknown operator is not a pass', async () => { + const { svc } = setup({ sources: [], security: salaryHiddenFromMembers }); + expect(await svc.admitAuthoredSource(item('ticket', ['body'], { where: { $nor: [{ status: 'open' }] } }), MEMBER)) + .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, field: '$nor' }); + }); + it("the object's display field is indexed as the title: an author who may not query it is refused though the source does not list it", async () => { const hideTitle = makeSecurity(() => ['id', 'body', 'salary_note', 'status']); const { svc } = setup({ sources: [], security: hideTitle }); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index ec4e61f9104..967fc9eb042 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -2289,8 +2289,8 @@ export class KnowledgeService implements IKnowledgeService { * `@objectstack/metadata-core`), never by the metadata protocol. * * `item` is the body as the door hands it to the protocol, not yet parsed. - * What is read of it is `source.object`, `source.content` and - * `source.metadataFields` (and `source.contentFields`, the spelling the + * What is read of it is `source.object`, `source.content`, + * `source.metadataFields` and the fields `source.where` reads (and `source.contentFields`, the spelling the * ADR-0087 kit renames to `content`, so a converted save is judged on the * fields it will index). An item with no object to judge is admitted here: * the protocol's parse refuses it with the schema's own prescription. @@ -2308,19 +2308,23 @@ export class KnowledgeService implements IKnowledgeService { if (ctx?.isSystem) return { admitted: true }; const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; const declared = body.source as - | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown } + | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } | null | undefined; const object = declared && typeof declared === 'object' ? declared.object : undefined; if (typeof object !== 'string' || object === '') return { admitted: true }; const names = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; - const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown }; + const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }; + const where = listed.where; const objSource: ObjectKnowledgeSource = { kind: 'object', object, content: [...names(listed.content), ...names(listed.contentFields)], metadataFields: names(listed.metadataFields), + ...(where !== null && typeof where === 'object' && !Array.isArray(where) + ? { where: where as Record } + : {}), }; const named = `The knowledge source${describeName(body)} was not saved`; const refuse = (status: number, code: string, message: string, field?: string) => @@ -2372,6 +2376,16 @@ export class KnowledgeService implements IKnowledgeService { ); case 'field-not-queryable': { const field = verdict.field ?? ''; + if (verdict.use === 'where') { + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + + 'hidden from you, or served to you masked), and the source would select its records by that field. ' + + 'Remove the field from `where`, or have someone who may query it save the source.', + field, + ); + } const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); return refuse( 403, diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index 95b70a0dd0f..4d77a9ebb04 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -48,6 +48,12 @@ * one unit), and searching it at all would make row presence an oracle on the * hidden value. * + * The fields the source's `where` reads ({@link selectingFieldsOf}) are judged + * by the same rule, at save and at search: the source selects its records by + * them, so they are part of what the source reads of the object. None is + * subtracted for being withheld from the index; the filter reads the field + * whether or not a passage carries it. + * * ## Where the field answer comes from * * The `security` service's `getQueryableFields`; absent that method, or when it @@ -69,6 +75,7 @@ */ import { + FieldReferenceSchema, canServeApiOperation, isAiReadExposed, resolveDisplayField, @@ -105,7 +112,14 @@ export type KnowledgeSourceRefusal = export type KnowledgeSourceAdmission = | { admitted: true } - | { admitted: false; reason: KnowledgeSourceRefusal; object: string; field?: string }; + | { + admitted: false; + reason: KnowledgeSourceRefusal; + object: string; + field?: string; + /** For `field-not-queryable`: how the source uses the field. Absent means it serves it. */ + use?: 'where'; + }; /** What the gates read, handed over by the service. Any member may throw: the caller refuses on a throw. */ export interface KnowledgeAdmissionDeps { @@ -266,6 +280,46 @@ export function servedFieldsOf(objSource: ObjectKnowledgeSource, schema: unknown return served; } +/** Logical keys of the filter grammar: never field names. */ +const WHERE_LOGICAL_KEYS: ReadonlySet = new Set(['$and', '$or', '$not']); + +/** + * The fields a source's `where` reads: every condition key and every + * cross-field comparand (`FieldReferenceSchema`, `{ $field }`), each by its + * first segment, so a dotted path is judged on the local field it starts + * from. It is the reading the engine's own predicate guard takes of a + * caller's filter. A key that is no logical key is a field name, so an + * operator the grammar does not know is judged as a field no caller may query + * and the source is refused: the direction is closed. + */ +export function selectingFieldsOf(objSource: Pick): Set { + const out = new Set(); + const comparands = (operand: unknown): void => { + if (!operand || typeof operand !== 'object') return; + if (Array.isArray(operand)) { + for (const member of operand) comparands(member); + return; + } + const reference = FieldReferenceSchema.safeParse(operand); + if (reference.success) out.add(reference.data.$field.split('.')[0]!); + for (const member of Object.values(operand as Record)) comparands(member); + }; + const walk = (condition: unknown): void => { + if (!condition || typeof condition !== 'object' || Array.isArray(condition)) return; + for (const [key, value] of Object.entries(condition as Record)) { + if (WHERE_LOGICAL_KEYS.has(key)) { + if (Array.isArray(value)) for (const member of value) walk(member); + else walk(value); + continue; + } + out.add(key.split('.')[0]!); + comparands(value); + } + }; + walk(objSource.where); + return out; +} + /** The field gate for one source over an object the object-level gates admitted. */ export function admitSourceFields( objSource: ObjectKnowledgeSource, @@ -276,14 +330,16 @@ export function admitSourceFields( return { admitted: false, reason: 'field-answer-unavailable', object }; } const served = servedFieldsOf(objSource, admission.schema); - if (fields.kind === 'masked-only') { - for (const field of served) { - if (fields.masked.has(field)) return { admitted: false, reason: 'field-not-queryable', object, field }; - } - return { admitted: true }; - } + const selecting = selectingFieldsOf(objSource); + const queryable = + fields.kind === 'masked-only' + ? (field: string) => !fields.masked.has(field) + : (field: string) => fields.queryable.has(field); for (const field of served) { - if (!fields.queryable.has(field)) return { admitted: false, reason: 'field-not-queryable', object, field }; + if (!queryable(field)) return { admitted: false, reason: 'field-not-queryable', object, field }; + } + for (const field of selecting) { + if (!queryable(field)) return { admitted: false, reason: 'field-not-queryable', object, field, use: 'where' }; } return { admitted: true }; } From 150c8543820a63cda47af0b0ada1931ff92c7deb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:49:52 +0000 Subject: [PATCH 21/29] fix(runtime): the authoring guards of a knowledge source cover more doors The dispatcher and the MCP draft door resolve the knowledge service by the classified lookup, so a service that is registered and cannot be resolved refuses the save 503. Every write door of an existing package asks manage_knowledge_sources when the package holds a knowledge source. The changeset names every removed export; the docs and the capability's comment follow. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../37304-knowledge-source-governed-type.md | 8 +- content/docs/ai/knowledge-rag.mdx | 2 +- content/docs/protocol/knowledge.mdx | 21 +- .../runtime/src/domains/mcp-authoring.test.ts | 25 +- packages/runtime/src/domains/mcp-authoring.ts | 5 +- .../domains/meta-save-capability-gate.test.ts | 34 +++ packages/runtime/src/domains/meta.ts | 7 +- .../packages-knowledge-source-gate.test.ts | 244 ++++++++++++++++++ packages/runtime/src/domains/packages.ts | 226 ++++++++++++++++ packages/spec/src/security/capabilities.ts | 6 +- 10 files changed, 562 insertions(+), 16 deletions(-) create mode 100644 packages/runtime/src/domains/packages-knowledge-source-gate.test.ts diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index ada41dc0477..f516d3ef3d4 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -42,12 +42,12 @@ ADR-0161 K4, K5, K6 and K8 item 4 (#37304). What changes: - **The type.** `knowledge_source` is registered in the metadata type registry with the one schema `KnowledgeSourceSchema`; a stack carries its sources in the new top-level collection `knowledgeSources`, in `*.knowledge-source.ts` or `.yml` files. An item can be created and changed at run time (Studio, MCP); it takes no environment overlay. Studio's menu lists the type, and the metadata form bundles carry its label in every locale. Two packages may each ship a source of one name (ADR-0150, addendum of 2026-11-25): each has its own index, and `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. -- **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. +- **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names; an empty-string member is refused, and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. - **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. - **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. -- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. -- **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached refuses `503`. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. +- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, ensure-customization, the manifest update and delete. A package that holds none is written as before, and the install door is not asked. +- **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`. The fields judged are the ones the source serves and the ones its `where` reads, at save and at search: a source whose `where` reads a field a caller may not query is not searched for that caller. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. - **One name, one source.** `KnowledgeServicePlugin({ sources })` and `registerSource` stay a door for the same schema and parse with it: a retired key is refused with its prescription (`400 VALIDATION_ERROR`), not converted. A source registered in code belongs to no package. It shares one slot with an environment-authored item of the same name, and the second of the two to arrive is refused `409 RESOURCE_CONFLICT`, naming both doors; a metadata item reloading its own earlier version is not a second arrival. - **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed, with the `file` / `http` branches that served them. They are runtime-interface-only members with no metadata form, so the compiler reports each call (`TS2339`). -- **Removed exports.** `EmbeddingModelSchema`, `VectorStoreSchema` and the rest of `@objectstack/spec/ai`'s `embedding` module leave with `embedding` and `vectorStore`: the knowledge source was their only composer. +- **Removed exports**, twelve, all from `@objectstack/spec/ai`. The whole `embedding` module leaves with `embedding` and `vectorStore`, because the knowledge source was its only composer: `EmbeddingModelSchema`, `VectorStoreSchema`, `VectorStoreProviderSchema` and the types `EmbeddingModel`, `VectorStore`, `VectorStoreProvider`. The source kinds leave with `file` and `http`: `FileKnowledgeSourceSchema`, `HttpKnowledgeSourceSchema`, `KnowledgeSourceKindSchema` and the types `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeSourceKind`. None has a replacement; an import of one is a compile error. - **CLI.** `os knowledge status` prints the package that holds a source and no longer prints a source kind. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 9183cca3064..4d1335784ab 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -76,7 +76,7 @@ to write. - **`content` lists its fields by name.** What is listed is what leaves the row store: the text of those fields is sent to the embedder and kept in the index. `'*'` is refused, and a field added to the object later is not indexed until you add it here. - **A source can also be created or changed at run time**, in Studio or through MCP, with no restart: a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. -- **Authoring one needs `manage_knowledge_sources`** beside `manage_metadata` — platform administrators hold it by default — and the author must themselves be allowed to search the object and query every listed field, or the save is refused naming what they may not read. +- **Authoring one needs `manage_knowledge_sources`** beside `manage_metadata` — platform administrators hold it by default — and the author must themselves be allowed to search the object and query every listed field and every field `where` reads, or the save is refused naming what they may not read. A write to a package that holds a source (publish its drafts, roll it back, duplicate, disable or delete it) needs the same capability. - **Two packages may each ship a source of the same name.** `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. - **Registering in code still works**: `new KnowledgeServicePlugin({ sources: [TaskNotes] })` or `knowledge.registerSource(TaskNotes)` takes the same shape. A source registered in code and an item saved under the same name are one name: the second to arrive is refused. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index fa69a9f4e33..ea976114c8d 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -194,14 +194,23 @@ and the MCP draft door: `manage_metadata`. Platform administrators hold it by default; nobody else does until it is granted. A grant on the indexed object's records does not imply it. Over MCP it is the human's own grant that is read, never the - agent's. + agent's. The package doors ask it too: every write to an existing package + that holds a knowledge source (enable, disable, publish, publish-drafts, + discard-drafts, the commit revert, rollback, revert, adopt-orphans, + duplicate, ensure-customization, the manifest update and delete) needs the + capability, and is refused `403` naming it otherwise. A package that holds + none is written as before. Installing a package is not asked: a packaged + source arrives by the install door's own admission. 2. **Source admission at save.** A source is saved only when its author may themselves search what it would index. The save asks the same gates a search asks ([Source admission](#source-admission-exposure-and-field-level-rules)) as the author: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the - field. A verdict that cannot be reached refuses `503`; nothing is written. + field. The fields judged are the ones the source serves (`content`, + `metadataFields`, the title field) and the ones its `where` reads. A + verdict that cannot be reached, or a knowledge service that is registered + and cannot be resolved, refuses `503`; nothing is written. #### One name, one source @@ -870,9 +879,11 @@ searched for a non-system caller, the service asks, once per object per search: The answer is per **source**, not per field: when one served field is hidden from the caller, that source is not searched for them at all — its passages mix the hidden field's text into one unit that cannot be partially withheld. -To keep a source searchable for restricted callers, declare its -`content` / `metadataFields` from fields every intended reader may query, -and put sensitive fields in a separate source. Every gate fails closed: a +The fields a source's `where` reads are judged by the same rule: the source +selects its records by them, so a caller who may not query one of them is not +served that source. To keep a source searchable for restricted callers, +declare its `content` / `metadataFields` / `where` from fields every intended +reader may query, and put sensitive fields in a separate source. Every gate fails closed: a lookup that throws — the `security` service lookup included, unless the kernel answers that no `security` service is registered — or a `security` service that answers neither field question, keeps the source out of that caller's diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index ec608a47a9d..24a4fc23558 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -197,6 +197,8 @@ async function serve( automation?: unknown; /** [ADR-0161 K4] The knowledge service the save asks to admit a source for its author. */ knowledge?: unknown; + /** The rejection the classified lookup raises for `knowledge`: registered, and not resolvable. */ + knowledgeFault?: Error; } = {}, ): Promise { const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN); @@ -221,10 +223,18 @@ async function serve( automationAsks.push(scopeId); return opts.automation; } - if (name === 'knowledge') return opts.knowledge; return name === 'mcp' ? mcp : name === 'protocol' ? protocol : name === 'security' ? security : undefined; }, - resolveServiceOrLoud: async (_ctx: unknown, name: string) => (name === 'tenancy' ? opts.tenancy : undefined), + // The classified lookup: `tenancy`, and the knowledge service the draft + // save asks. A `knowledgeFault` is a registered service that cannot be + // resolved, which this lookup re-raises and the quiet probe would absorb. + resolveServiceOrLoud: async (_ctx: unknown, name: string) => { + if (name === 'knowledge') { + if (opts.knowledgeFault) throw opts.knowledgeFault; + return opts.knowledge; + } + return name === 'tenancy' ? opts.tenancy : undefined; + }, getObjectQL: async () => { if (opts.qlThrows) throw new Error('engine lookup failed'); return ql; @@ -1027,6 +1037,17 @@ describe('[ADR-0161 K4] save_metadata_draft asks the knowledge service to admit expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); }); + it('fails closed: a knowledge service that is registered and cannot be resolved is 503 SERVICE_UNAVAILABLE, and nothing is written', async () => { + const { authoring, served } = await authorThroughDomain({ + systemPermissions: BOTH, + knowledgeFault: new Error('knowledge factory: datasource unreachable'), + }); + const refused = await save(authoring); + expect(refused.body.error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(refused.body.error.message).toContain('the knowledge service could not be resolved'); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + it('CONTROL: an admitted source is saved; another type is never asked about; no knowledge service judges nothing', async () => { const admitAuthoredSource = vi.fn(async () => ({ admitted: true })); const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { admitAuthoredSource } }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index f9e1f3968d3..e67f01483d9 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -606,7 +606,10 @@ function openWriter( item, // The human the door admitted: their grants, never the envelope's. executionContext: reader, - resolveKnowledgeService: () => deps.resolveService(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), + // The classified lookup (`resolveServiceOrLoud`): an absent + // service answers `undefined`, a registered one that cannot be + // resolved rejects and the predicate answers `503`. + resolveKnowledgeService: () => deps.resolveServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), }); if (!refused) return undefined; return { diff --git a/packages/runtime/src/domains/meta-save-capability-gate.test.ts b/packages/runtime/src/domains/meta-save-capability-gate.test.ts index 3c410fb14f3..4ea3b20710e 100644 --- a/packages/runtime/src/domains/meta-save-capability-gate.test.ts +++ b/packages/runtime/src/domains/meta-save-capability-gate.test.ts @@ -40,6 +40,7 @@ */ import { describe, it, expect, vi } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; import { HttpDispatcher } from '../http-dispatcher.js'; // Paid at collection, not inside a case's clock (check:test-source-alias). @@ -316,6 +317,39 @@ describe('ADR-0161 K4 — dispatcher PUT asks the knowledge service to admit the expect(stack.saveMetaItem).not.toHaveBeenCalled(); }); + /** + * A real kernel, so the two classes are the plugin loader's own: a name + * nothing registered rejects with the registry's branded miss, and a + * registered factory that throws rejects unbranded. + */ + function bootOnKernel(wiring: 'never-registered' | 'throwing-factory') { + const saveMetaItem = vi.fn(async ({ name }: any) => ({ success: true, name })); + const kernel = new ObjectKernel({ gracefulShutdown: false, skipSystemValidation: true }); + kernel.registerService('protocol', { saveMetaItem }); + if (wiring === 'throwing-factory') { + kernel.registerServiceFactory('knowledge', () => { + throw new Error('knowledge factory: datasource unreachable'); + }); + } + return { dispatcher: new HttpDispatcher(kernel as any), saveMetaItem }; + } + + it('fails closed: a knowledge service that is registered and cannot be resolved is 503 SERVICE_UNAVAILABLE, and nothing is saved', async () => { + const stack = bootOnKernel('throwing-factory'); + const res = await stack.dispatcher.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE)); + expect(res.response?.status).toBe(503); + expect(res.response?.body?.error?.code).toBe('SERVICE_UNAVAILABLE'); + expect(res.response?.body?.error?.message).toContain('the knowledge service could not be resolved'); + expect(stack.saveMetaItem).not.toHaveBeenCalled(); + }); + + it('CONTROL: on the same kernel with no knowledge service registered, the save goes on', async () => { + const stack = bootOnKernel('never-registered'); + const res = await stack.dispatcher.handleMetadata('/knowledge_source/faq', ctx(AUTHOR), 'PUT', copy(SOURCE)); + expect(res.response?.status).toBe(200); + expect(stack.saveMetaItem).toHaveBeenCalledTimes(1); + }); + it('CONTROL: an admitted source is saved; with no knowledge service the save goes on', async () => { const admitted = bootWith(() => ({ admitted: true })); expect((await put(admitted, AUTHOR)).response?.status).toBe(200); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index f97b71fd185..fdbac350b1b 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -1993,8 +1993,13 @@ export async function handleMetadataRequest(deps: DomainHandlerDeps, path: strin type, item, executionContext: _context.executionContext, + // The classified lookup, not the `resolveService` probe: + // a name nothing registered answers `undefined` (no + // knowledge service, nothing to ask), and a service that + // is registered and cannot be resolved rejects, which the + // predicate answers `503`. resolveKnowledgeService: () => - deps.resolveService(_context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, _context.environmentId), + deps.resolveServiceOrLoud(_context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, _context.environmentId), }); if (refused) { return { handled: true, response: deps.error(refused.message, refused.status) }; diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts new file mode 100644 index 00000000000..ef3645cc4ef --- /dev/null +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -0,0 +1,244 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `/packages` — the knowledge source capability at the package write doors + * (ADR-0161 K4, guard one; `refuseKnowledgeSourcePackageWrite`). + * + * A `/meta` write of a `knowledge_source` asks `manage_knowledge_sources` + * beside `manage_metadata`. The package doors write many items at once, so the + * rule is stated on the package: every write door of an existing package that + * holds a knowledge source (an item, a pending draft, or for the verbs that + * rewrite items from the timeline a commit) asks the same capability, and a + * package that holds none answers exactly as before. + * + * Does NOT cover: the `manage_metadata` tier in front of this gate and the + * anonymous floor (`packages-capability-gate.test.ts`), the wall + * (`packages-walled-catalog-write.test.ts`), or the `/meta` doors' own row + * (`meta-type-write-capability-parity.test.ts`). + * + * The driver is the sibling gate tests': `HttpDispatcher` over a fake kernel + * whose services are `vi.fn()` doubles, so "the target never ran" is an + * assertion, and every `/packages` transport converges on the one body driven + * here (`handlePackagesRequest`). + */ + +// Pays `@objectstack/metadata`'s first load at collection, never inside a clocked case. +import '@objectstack/metadata'; +import { describe, it, expect, vi } from 'vitest'; +import { HttpDispatcher } from '../http-dispatcher.js'; + +const ctx = (executionContext: any): any => ({ request: {}, environmentId: 'platform', executionContext }); +const authed = (caps: string[], tenantId?: string) => + ctx({ userId: 'u_builder', isSystem: false, systemPermissions: caps, ...(tenantId ? { tenantId } : {}) }); +const system = (tenantId?: string) => ctx({ isSystem: true, ...(tenantId ? { tenantId } : {}) }); + +const METADATA_ONLY = ['manage_metadata']; +const BOTH = ['manage_metadata', 'manage_knowledge_sources']; + +/** What the package holds, as the three listings the gate reads answer it. */ +interface Holding { + items?: any[]; + drafts?: any[]; + commits?: any[]; + /** A listing that throws, by member name. */ + throws?: 'getMetaItems' | 'listDrafts' | 'listCommits'; +} + +function make(holding: Holding = {}) { + const fail = (member: Holding['throws']) => () => { + if (holding.throws === member) throw new Error('metadata store unreachable'); + }; + const protocol = { + publishPackageDrafts: vi.fn().mockResolvedValue({ success: true, publishedCount: 0, published: [], failed: [] }), + discardPackageDrafts: vi.fn().mockResolvedValue({ success: true, discardedCount: 2 }), + revertCommit: vi.fn().mockResolvedValue({ success: true }), + rollbackToPackageCommit: vi.fn().mockResolvedValue({ success: true }), + reassignOrphanedMetadata: vi.fn().mockResolvedValue({ reassigned: 0 }), + duplicatePackage: vi.fn().mockResolvedValue({ package: { id: 'pkg-b' } }), + ensureCustomizationPackage: vi.fn().mockResolvedValue({ basePackageId: 'pkg-a', packageId: 'pkg-a.custom', namespace: 'pkg_custom', dependencyRange: '^1', created: true, writable: true }), + updatePackage: vi.fn().mockResolvedValue({ package: { manifest: { id: 'com.example.pkg-a' } } }), + deletePackage: vi.fn().mockResolvedValue({ deletedCount: 1 }), + revertStoredPackage: vi.fn().mockResolvedValue({ stored: true }), + // The three listings the gate reads. + getMetaItems: vi.fn(async ({ type }: any) => { + fail('getMetaItems')(); + return { items: type === 'knowledge_source' ? (holding.items ?? []) : [] }; + }), + listDrafts: vi.fn(async ({ type }: any) => { + fail('listDrafts')(); + return { drafts: (holding.drafts ?? []).filter((d) => !type || d.type === type) }; + }), + listCommits: vi.fn(async () => { + fail('listCommits')(); + return holding.commits ?? [{ id: 'c1', operation: 'apply', itemCount: 1, items: [{ type: 'object', name: 'ticket', existedBefore: false, prevVersion: null }] }]; + }), + }; + const metadata = { + publishPackage: vi.fn().mockResolvedValue({ success: true }), + getPackageItems: vi.fn().mockResolvedValue([]), + }; + const registry = { + getAllPackages: vi.fn().mockReturnValue([{ id: 'com.example.pkg-a', status: 'active' }]), + getPackage: vi.fn().mockReturnValue({ id: 'com.example.pkg-a', manifest: { id: 'com.example.pkg-a', name: 'A' } }), + installPackage: vi.fn().mockImplementation((m: any) => ({ id: m.id, manifest: m })), + enablePackage: vi.fn().mockReturnValue({ id: 'com.example.pkg-a' }), + disablePackage: vi.fn().mockReturnValue({ id: 'com.example.pkg-a' }), + uninstallPackage: vi.fn().mockReturnValue(true), + updatePackageManifest: vi.fn().mockReturnValue({ id: 'com.example.pkg-a' }), + }; + const objectql = { registry }; + const kernel: any = { + context: { + getService: (name: string) => + name === 'objectql' ? objectql : name === 'protocol' ? protocol : name === 'metadata' ? metadata : null, + }, + }; + return { dispatcher: new HttpDispatcher(kernel), protocol, metadata, registry }; +} + +type Stack = ReturnType; +interface Door { + name: string; path: string; method: string; body?: any; tenantId?: string; + target: (s: Stack) => any; +} + +/** Every write door of an existing package, each with the writer it must not reach when refused. */ +const DOORS: Door[] = [ + { name: 'PATCH /:id/enable', path: '/pkg-a/enable', method: 'PATCH', target: (s) => s.registry.enablePackage }, + { name: 'PATCH /:id/disable', path: '/pkg-a/disable', method: 'PATCH', target: (s) => s.registry.disablePackage }, + { name: 'POST /:id/publish', path: '/pkg-a/publish', method: 'POST', target: (s) => s.metadata.publishPackage }, + { name: 'POST /:id/publish-drafts', path: '/pkg-a/publish-drafts', method: 'POST', target: (s) => s.protocol.publishPackageDrafts }, + { name: 'POST /:id/discard-drafts', path: '/pkg-a/discard-drafts', method: 'POST', target: (s) => s.protocol.discardPackageDrafts }, + { name: 'POST /:id/commits/:c/revert', path: '/pkg-a/commits/c1/revert', method: 'POST', target: (s) => s.protocol.revertCommit }, + { name: 'POST /:id/rollback', path: '/pkg-a/rollback', method: 'POST', body: { commitId: 'c1' }, target: (s) => s.protocol.rollbackToPackageCommit }, + { name: 'POST /:id/revert', path: '/pkg-a/revert', method: 'POST', target: (s) => s.protocol.revertStoredPackage }, + { name: 'POST /:id/adopt-orphans', path: '/pkg-a/adopt-orphans', method: 'POST', target: (s) => s.protocol.reassignOrphanedMetadata }, + { name: 'POST /:id/duplicate', path: '/pkg-a/duplicate', method: 'POST', body: { targetPackageId: 'pkg-b' }, target: (s) => s.protocol.duplicatePackage }, + { name: 'POST /:id/ensure-customization', path: '/pkg-a/ensure-customization', method: 'POST', target: (s) => s.protocol.ensureCustomizationPackage }, + { name: 'PATCH /:id (manifest)', path: '/pkg-a', method: 'PATCH', body: { name: 'renamed' }, target: (s) => s.protocol.updatePackage }, + { name: 'DELETE /:id', path: '/pkg-a', method: 'DELETE', tenantId: 'org_a', target: (s) => s.protocol.deletePackage }, +]; + +const call = (s: Stack, door: Door, context: any) => + s.dispatcher.handlePackages(door.path, door.method, door.body ?? {}, {}, context); + +const SOURCE_ITEM = { name: 'faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'article', content: ['body'] } }; +const SOURCE_DRAFT = { type: 'knowledge_source', name: 'faq', label: null, packageId: 'pkg-a', updatedAt: null, updatedBy: null }; + +describe('/packages — a package that holds a knowledge source is written by a holder of `manage_knowledge_sources`', () => { + for (const door of DOORS) { + it(`${door.name}: refuses a manage_metadata-only caller when the package holds a knowledge source, and the writer never runs`, async () => { + for (const holding of [{ items: [SOURCE_ITEM] }, { drafts: [SOURCE_DRAFT] }] as Holding[]) { + const s = make(holding); + const r = await call(s, door, authed(METADATA_ONLY, door.tenantId)); + expect(r.response?.status, JSON.stringify(holding)).toBe(403); + const message = r.response?.body?.error?.message as string; + expect(message).toContain('`manage_knowledge_sources`'); + expect(message).toContain('knowledge source "faq"'); + expect(message).toContain('Nothing was changed.'); + expect(door.target(s)).not.toHaveBeenCalled(); + } + }); + + it(`${door.name}: a holder of both capabilities goes on, and the package is not read for it`, async () => { + const s = make({ items: [SOURCE_ITEM], drafts: [SOURCE_DRAFT] }); + const r = await call(s, door, authed(BOTH, door.tenantId)); + expect(r.response?.status).not.toBe(403); + expect(door.target(s)).toHaveBeenCalled(); + expect(s.protocol.listDrafts).not.toHaveBeenCalled(); + }); + + it(`${door.name}: CONTROL — a package that holds no knowledge source answers a manage_metadata caller as before`, async () => { + const s = make({ items: [], drafts: [{ ...SOURCE_DRAFT, type: 'object', name: 'ticket' }] }); + const r = await call(s, door, authed(METADATA_ONLY, door.tenantId)); + expect(r.response?.status).not.toBe(403); + expect(r.response?.status).not.toBe(503); + expect(door.target(s)).toHaveBeenCalled(); + }); + + it(`${door.name}: fails closed — a listing that throws refuses 503, and the writer never runs`, async () => { + const s = make({ throws: 'getMetaItems' }); + const r = await call(s, door, authed(METADATA_ONLY, door.tenantId)); + expect(r.response?.status).toBe(503); + expect(r.response?.body?.error?.message).toContain('could not be read'); + expect(door.target(s)).not.toHaveBeenCalled(); + }); + + it(`${door.name}: the engine's own call is not asked`, async () => { + const s = make({ items: [SOURCE_ITEM] }); + const r = await call(s, door, system(door.tenantId)); + expect(r.response?.status).not.toBe(403); + expect(door.target(s)).toHaveBeenCalled(); + }); + } +}); + +describe('/packages — the verbs that rewrite items from the timeline read the commits too', () => { + const touching = (id: string, type: string) => ({ + id, operation: 'apply', itemCount: 1, items: [{ type, name: type === 'knowledge_source' ? 'faq' : 'ticket', existedBefore: true, prevVersion: 1 }], + }); + const revert = (commitId: string): Door => ({ + name: 'revert', path: `/pkg-a/commits/${commitId}/revert`, method: 'POST', target: (s) => s.protocol.revertCommit, + }); + const rollback: Door = { name: 'rollback', path: '/pkg-a/rollback', method: 'POST', body: { commitId: 'c1' }, target: (s) => s.protocol.rollbackToPackageCommit }; + + it('the per-commit revert is judged on the commit it names: one that touched a knowledge source is refused, another goes on', async () => { + const commits = [touching('c2', 'knowledge_source'), touching('c1', 'object')]; + const refused = make({ commits }); + const r = await call(refused, revert('c2'), authed(METADATA_ONLY)); + expect(r.response?.status).toBe(403); + expect(r.response?.body?.error?.message).toContain('knowledge source "faq" in its commit history'); + expect(refused.protocol.revertCommit).not.toHaveBeenCalled(); + + const other = make({ commits }); + expect((await call(other, revert('c1'), authed(METADATA_ONLY))).response?.status).not.toBe(403); + expect(other.protocol.revertCommit).toHaveBeenCalled(); + }); + + it('a commit the timeline does not list is judged on the whole timeline, never waved through', async () => { + const s = make({ commits: [touching('c2', 'knowledge_source')] }); + expect((await call(s, revert('c_unlisted'), authed(METADATA_ONLY))).response?.status).toBe(403); + expect(s.protocol.revertCommit).not.toHaveBeenCalled(); + }); + + it('the rollback is judged on the whole timeline: a knowledge source a past commit touched refuses it though the package holds none now', async () => { + const s = make({ items: [], drafts: [], commits: [touching('c3', 'object'), touching('c2', 'knowledge_source'), touching('c1', 'object')] }); + const r = await call(s, rollback, authed(METADATA_ONLY)); + expect(r.response?.status).toBe(403); + expect(s.protocol.rollbackToPackageCommit).not.toHaveBeenCalled(); + // A holder rolls the same package back. + const held = make({ commits: [touching('c2', 'knowledge_source')] }); + expect((await call(held, rollback, authed(BOTH))).response?.status).not.toBe(403); + expect(held.protocol.rollbackToPackageCommit).toHaveBeenCalled(); + }); + + it('fails closed: a timeline that cannot be read refuses the rollback 503', async () => { + const s = make({ throws: 'listCommits' }); + expect((await call(s, rollback, authed(METADATA_ONLY))).response?.status).toBe(503); + expect(s.protocol.rollbackToPackageCommit).not.toHaveBeenCalled(); + }); +}); + +describe('/packages — what the gate leaves alone', () => { + it('the draft listing\'s own answer for an id nothing carries is not a fault: the door answers that id as before', async () => { + const s = make(); + s.protocol.listDrafts.mockImplementation(async () => { + const err: any = new Error("'pkg-a' is not an installed package"); + err.code = 'INVALID_REQUEST'; + err.status = 400; + throw err; + }); + const door = DOORS.find((d) => d.name === 'POST /:id/discard-drafts')!; + const r = await call(s, door, authed(METADATA_ONLY)); + expect(r.response?.status).not.toBe(503); + expect(s.protocol.discardPackageDrafts).toHaveBeenCalled(); + }); + + it('the install door is not asked: a packaged source arrives by that door\'s own admission (ADR-0161 K4)', async () => { + const s = make({ items: [SOURCE_ITEM] }); + const manifest = { id: 'com.example.pkg-new', name: 'n', version: '1.0.0', type: 'app' }; + const r = await s.dispatcher.handlePackages('/', 'POST', { manifest }, { overwrite: 'true' }, authed(METADATA_ONLY)); + expect(r.response?.status).not.toBe(403); + expect(s.registry.installPackage).toHaveBeenCalled(); + }); +}); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 5f898d19778..aea70c5900a 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -152,6 +152,9 @@ import { ManifestSchema, SEMVER_2_0_0_VERSION_PATTERN, manifestIdRefusal } from // parameter a door does not read (`packages/rest/src/query-allowlist.ts`), // asked by every write door (`refusePackageWriteDoorQuery`, #26857). import { repeatedQueryParamMessage, unknownQueryParamRefusalMessage } from '@objectstack/rest'; +// [ADR-0161 K4, guard one] The `/meta` type-level write admission, asked by the +// package verbs that reach a `knowledge_source` (`refuseKnowledgeSourcePackageWrite`). +import { metaTypeWriteRefusal } from '@objectstack/rest'; // [commit 0862063ba] The repo's ONE coercion for a query parameter its schema declares // `z.boolean()`, from the module whose header is the authority on the rule // (`packages/runtime/src/query-param.ts`). Imported, never restated: the list @@ -277,6 +280,11 @@ export type PackagesDomainProtocol = * from the producer's own signature. */ getMetaItemForExecution?: ObjectStackProtocolImplementation['getMetaItemForExecution']; + /** + * [ADR-0161 K4, guard one] The pending-draft listing the knowledge + * source gate reads, typed from the producer's own signature. + */ + listDrafts?: ObjectStackProtocolImplementation['listDrafts']; /** ⚠️ Undeclared request shapes — see "Where the ledger honestly ends". */ publishPackageDrafts?(request: any): Promise; discardPackageDrafts?(request: any): Promise; @@ -408,6 +416,146 @@ function requireManageMetadata(deps: DomainHandlerDeps, context: HttpProtocolCon return null; } +/** The governed type {@link refuseKnowledgeSourcePackageWrite} asks about. */ +const KNOWLEDGE_SOURCE_PACKAGE_TYPE = 'knowledge_source'; + +/** + * Where a package can hold a knowledge source, for {@link refuseKnowledgeSourcePackageWrite}: + * + * - `drafts`: its pending drafts; + * - `items`: the items it holds, as the per-package layer lists them; + * - `history`: its commit timeline, read by the verbs that rewrite items from + * it. The per-commit revert reads the one commit named (`commitId`), the + * rollback every commit. + */ +type KnowledgeSourcePackageReach = 'drafts' | 'items' | 'history'; + +/** + * [ADR-0161 K4, guard one, at the package doors] A write to a package that + * holds a `knowledge_source` asks `manage_knowledge_sources` beside + * `manage_metadata`, as the `/meta` doors do for one item. + * + * The package doors act on many items at once: publish-drafts makes every + * pending draft live, discard-drafts and revert drop them, the commit revert + * and the rollback rewrite items from the timeline, duplicate copies a + * package's items into a new one, adopt-orphans binds items to it, and enable, + * disable and delete decide whether its items are served at all. Where one of + * those items is a knowledge source the verb does to it what a `/meta` write + * would. So the rule is stated on the package and is the same at every write + * door of an existing package: one that holds a knowledge source is written by + * a holder of the capability that write asks (`metaTypeWriteRefusal`, the one + * decision). + * + * Asked right after {@link requireManageMetadata} and the wall, and before + * anything is written. A holder of the capability, and the engine's own call + * (`isSystem`), are answered without a read. For anyone else the package is + * read ({@link KnowledgeSourcePackageReach}); one that holds no knowledge + * source is untouched by this gate, so the doors behave as before for it. + * + * Fail direction: closed. A read that throws refuses the verb `503`; nothing + * was changed. A protocol with no such listing cannot hold the items the + * listing would name, so an absent member is not a refusal: it is the + * capability probe every door of this file already asks. + * + * Not asked by the install door (`POST /packages`): a packaged source arrives + * by that door's own admission, as ADR-0161 K4 leaves it. + */ +async function refuseKnowledgeSourcePackageWrite( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + input: { + packageId: string; + /** The refused write, as the message names it, e.g. `Deleting package "x"`. */ + action: string; + reach: readonly KnowledgeSourcePackageReach[]; + /** With `history`: the one commit the verb reverts. Absent: the whole timeline. */ + commitId?: string; + }, +): Promise { + const ec: any = context?.executionContext; + if (ec?.isSystem) return null; + const refusal = metaTypeWriteRefusal('POST', KNOWLEDGE_SOURCE_PACKAGE_TYPE, ec); + if (!refusal) return null; + + const { packageId, action } = input; + let found: string | undefined; + try { + const protocol = await resolveProtocol(deps, context); + found = await knowledgeSourceInPackageReach(protocol, input); + } catch (e) { + return { + handled: true, + response: deps.error( + `${action} is refused: whether package "${packageId}" holds a knowledge source could not be read ` + + `(${clientFacingFailureText(e, 'the listing failed')}), and a change that reaches one requires the ` + + '`manage_knowledge_sources` capability. Nothing was changed; try again.', + 503, + ), + }; + } + if (found === undefined) return null; + return { + handled: true, + response: deps.error( + `${action} is refused: package "${packageId}" holds ${found}, and creating, changing or removing a ` + + 'knowledge source requires the `manage_knowledge_sources` capability beside `manage_metadata`. ' + + 'Nothing was changed. Ask someone who holds that capability to do this.', + refusal.status, + ), + }; +} + +/** + * The first knowledge source a verb's reach holds, as a phrase the refusal + * can name, or `undefined` when the reach holds none. Throws when a listing + * throws; the gate refuses then. + */ +async function knowledgeSourceInPackageReach( + protocol: PackagesDomainProtocol | undefined, + input: { packageId: string; reach: readonly KnowledgeSourcePackageReach[]; commitId?: string }, +): Promise { + if (!protocol) return undefined; + const { packageId, reach } = input; + const isKnowledgeSource = (type: unknown): boolean => + typeof type === 'string' && (PLURAL_TO_SINGULAR[type] ?? type) === KNOWLEDGE_SOURCE_PACKAGE_TYPE; + const named = (name: unknown): string => (typeof name === 'string' && name ? ` "${name}"` : ''); + + if (reach.includes('drafts') && typeof protocol.listDrafts === 'function') { + let drafts: Array<{ type: string; name: string }> = []; + try { + drafts = (await protocol.listDrafts({ packageId, type: KNOWLEDGE_SOURCE_PACKAGE_TYPE }))?.drafts ?? []; + } catch (e: any) { + // The listing's own answer for an id no installed package and no + // draft carries: there is nothing pending to reach, and the door + // answers that id as it always has. + if (e?.code !== 'INVALID_REQUEST') throw e; + } + const draft = drafts.find((d) => isKnowledgeSource(d?.type)); + if (draft) return `a pending draft of the knowledge source${named(draft.name)}`; + } + if (reach.includes('items')) { + const read = typeof protocol.getMetaItemsPerPackage === 'function' + ? protocol.getMetaItemsPerPackage({ type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, packageId }) + : typeof (protocol as any).getMetaItems === 'function' + ? (protocol as any).getMetaItems({ type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, packageId }) + : undefined; + const listed: any = await read; + const items: any[] = Array.isArray(listed?.items) ? listed.items : []; + if (items.length > 0) return `the knowledge source${named(items[0]?.name)}`; + } + if (reach.includes('history') && typeof protocol.listCommits === 'function') { + const commits: any[] = (await protocol.listCommits({ packageId })) ?? []; + const one = input.commitId === undefined ? undefined : commits.find((c) => c?.id === input.commitId); + // A named commit the timeline lists is judged alone; one it does not + // list, and the rollback, are judged on the whole timeline. + for (const commit of one ? [one] : commits) { + const item = (Array.isArray(commit?.items) ? commit.items : []).find((i: any) => isKnowledgeSource(i?.type)); + if (item) return `the knowledge source${named(item.name)} in its commit history`; + } + } + return undefined; +} + /** * The actor a package write door records (ADR-0146 D1): the user id of the * execution context this request was authorized as — the same context @@ -2832,6 +2980,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Enabling package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Enabling package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Enabling package "${id}"`); @@ -2895,6 +3049,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Disabling package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Disabling package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Disabling package "${id}"`); @@ -2970,6 +3130,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Publishing package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Publishing package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; // [#22113] ADR-0070 D2: a code or installed package is read-only, so // this door refuses it BEFORE `publishPackage`, which would otherwise @@ -3012,6 +3178,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Publishing the drafts of package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Publishing the drafts of package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; const protocol = await resolveProtocol(deps, _context); if (protocol && typeof protocol.publishPackageDrafts === 'function') { @@ -3463,6 +3635,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Discarding the drafts of package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Discarding the drafts of package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; const protocol = await resolveProtocol(deps, _context); if (protocol && typeof protocol.discardPackageDrafts === 'function') { @@ -3537,6 +3715,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Reverting commit "${commitId}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Reverting commit "${commitId}"`, reach: ['drafts', 'items', 'history'], commitId, + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; const protocol = await resolveProtocol(deps, _context); if (protocol && typeof protocol.revertCommit === 'function') { @@ -3567,6 +3751,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Rolling back package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Rolling back package "${id}"`, reach: ['drafts', 'items', 'history'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; const protocol = await resolveProtocol(deps, _context); if (protocol && typeof protocol.rollbackToPackageCommit === 'function') { @@ -3598,6 +3788,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Reverting package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Reverting package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; // [#22090] A package's members live in one of two places, and each // is reverted by the service that holds it. A Studio-authored @@ -3724,6 +3920,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Adopting orphaned metadata into package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Adopting orphaned metadata into package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; // [#24813] ADR-0070 D2: a package the deployment ships is not a // base, so nothing is adopted into it. `reassignOrphanedMetadata` @@ -3769,6 +3971,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Duplicating package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Duplicating package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Duplicating package "${id}"`); @@ -3816,6 +4024,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Ensuring the customization package of "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Ensuring the customization package of "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Ensuring the customization package of "${id}"`); @@ -3921,6 +4135,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Updating package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Updating package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Updating package "${id}"`); @@ -4023,6 +4243,12 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Deleting package "${id}"`); if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // where this verb reaches asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Deleting package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Deleting package "${id}"`); diff --git a/packages/spec/src/security/capabilities.ts b/packages/spec/src/security/capabilities.ts index 5145eef2b29..c9efb7004f0 100644 --- a/packages/spec/src/security/capabilities.ts +++ b/packages/spec/src/security/capabilities.ts @@ -116,8 +116,10 @@ export const PLATFORM_CAPABILITIES: readonly PlatformCapability[] = [ // every record it selects, to the embedding provider, and the first build is // billed — an act of another weight than editing a layout. So every door // that creates, changes or removes an item of that type (Studio and REST - // `/meta`, the dispatcher, the MCP draft door) asks this capability BESIDE - // `manage_metadata`, never instead of it. Held by default by platform + // `/meta`, the dispatcher, the MCP draft door), and every write door of an + // existing package that holds one (`/packages/:id/…`), asks this capability + // BESIDE `manage_metadata`, never instead of it. The install door is not + // asked: a packaged source arrives by that door's own admission. Held by default by platform // administrators only (`ADMIN_FULL_ACCESS_CAPABILITIES`); every other // position, organization administrators included, only by explicit grant. // A grant on the indexed object's records does not imply it. `platform`: From a8756eb741ec0e9b043eb93c0ab1d4d750e12086 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:41:30 +0000 Subject: [PATCH 22/29] runtime: duplicate admits each copied knowledge source; the package gate reads per package The duplicate door admits each knowledge source it would copy for the caller before anything is copied. The package gate reads a package's items from the per-package layer only, and a host with no metadata store reads as holding none; any other listing failure still refuses. REST: one JSDoc line on the quiet lookup. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../37304-knowledge-source-governed-type.md | 2 +- content/docs/protocol/knowledge.mdx | 3 +- packages/rest/src/rest-server.ts | 5 + .../packages-knowledge-source-gate.test.ts | 85 ++++++++++- packages/runtime/src/domains/packages.ts | 138 ++++++++++++++++-- 5 files changed, 212 insertions(+), 21 deletions(-) diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index f516d3ef3d4..b0fa4100559 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -45,7 +45,7 @@ What changes: - **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names; an empty-string member is refused, and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. - **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. - **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. -- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, ensure-customization, the manifest update and delete. A package that holds none is written as before, and the install door is not asked. +- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, ensure-customization, the manifest update and delete. A package that holds none is written as before, and the install door is not asked. A duplicate also admits each knowledge source it copies for the caller (source admission, below), and refuses the whole copy when one is refused. - **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`. The fields judged are the ones the source serves and the ones its `where` reads, at save and at search: a source whose `where` reads a field a caller may not query is not searched for that caller. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. - **One name, one source.** `KnowledgeServicePlugin({ sources })` and `registerSource` stay a door for the same schema and parse with it: a retired key is refused with its prescription (`400 VALIDATION_ERROR`), not converted. A source registered in code belongs to no package. It shares one slot with an environment-authored item of the same name, and the second of the two to arrive is refused `409 RESOURCE_CONFLICT`, naming both doors; a metadata item reloading its own earlier version is not a second arrival. - **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed, with the `file` / `http` branches that served them. They are runtime-interface-only members with no metadata form, so the compiler reports each call (`TS2339`). diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index ea976114c8d..857fc6da0a3 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -200,7 +200,8 @@ and the MCP draft door: duplicate, ensure-customization, the manifest update and delete) needs the capability, and is refused `403` naming it otherwise. A package that holds none is written as before. Installing a package is not asked: a packaged - source arrives by the install door's own admission. + source arrives by the install door's own admission. A duplicate also + admits each knowledge source it copies for the caller, by guard two below. 2. **Source admission at save.** A source is saved only when its author may themselves search what it would index. The save asks the same gates a search asks ([Source admission](#source-admission-exposure-and-field-level-rules)) diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 32c64ab070a..95b77910ae0 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -6217,6 +6217,11 @@ export class RestServer { * there), a throw when one is registered and cannot be resolved (the door * then refuses `503`, never proceeds). `unknown`, deliberately: the door * reads the one member it asks structurally. + * + * A server built with no `kernelServiceProvider` answers `undefined`, + * quietly: `RestApiPlugin` always passes one, and a hand-built server + * without it reaches no kernel service at all (its security and audit + * lookups read the same way), so there is no knowledge service to ask. */ private async resolveKnowledgeService( environmentId?: string, diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index ef3645cc4ef..562d7c92709 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -41,10 +41,10 @@ interface Holding { drafts?: any[]; commits?: any[]; /** A listing that throws, by member name. */ - throws?: 'getMetaItems' | 'listDrafts' | 'listCommits'; + throws?: 'getMetaItemsPerPackage' | 'listDrafts' | 'listCommits'; } -function make(holding: Holding = {}) { +function make(holding: Holding = {}, knowledge?: unknown) { const fail = (member: Holding['throws']) => () => { if (holding.throws === member) throw new Error('metadata store unreachable'); }; @@ -60,8 +60,8 @@ function make(holding: Holding = {}) { deletePackage: vi.fn().mockResolvedValue({ deletedCount: 1 }), revertStoredPackage: vi.fn().mockResolvedValue({ stored: true }), // The three listings the gate reads. - getMetaItems: vi.fn(async ({ type }: any) => { - fail('getMetaItems')(); + getMetaItemsPerPackage: vi.fn(async ({ type }: any) => { + fail('getMetaItemsPerPackage')(); return { items: type === 'knowledge_source' ? (holding.items ?? []) : [] }; }), listDrafts: vi.fn(async ({ type }: any) => { @@ -90,7 +90,11 @@ function make(holding: Holding = {}) { const kernel: any = { context: { getService: (name: string) => - name === 'objectql' ? objectql : name === 'protocol' ? protocol : name === 'metadata' ? metadata : null, + name === 'objectql' ? objectql + : name === 'protocol' ? protocol + : name === 'metadata' ? metadata + : name === 'knowledge' ? (knowledge ?? null) + : null, }, }; return { dispatcher: new HttpDispatcher(kernel), protocol, metadata, registry }; @@ -140,7 +144,7 @@ describe('/packages — a package that holds a knowledge source is written by a } }); - it(`${door.name}: a holder of both capabilities goes on, and the package is not read for it`, async () => { + it(`${door.name}: a holder of both capabilities goes on, and the capability gate reads no draft listing for it`, async () => { const s = make({ items: [SOURCE_ITEM], drafts: [SOURCE_DRAFT] }); const r = await call(s, door, authed(BOTH, door.tenantId)); expect(r.response?.status).not.toBe(403); @@ -157,7 +161,7 @@ describe('/packages — a package that holds a knowledge source is written by a }); it(`${door.name}: fails closed — a listing that throws refuses 503, and the writer never runs`, async () => { - const s = make({ throws: 'getMetaItems' }); + const s = make({ throws: 'getMetaItemsPerPackage' }); const r = await call(s, door, authed(METADATA_ONLY, door.tenantId)); expect(r.response?.status).toBe(503); expect(r.response?.body?.error?.message).toContain('could not be read'); @@ -219,6 +223,73 @@ describe('/packages — the verbs that rewrite items from the timeline read the }); }); +describe('/packages — duplicate admits each knowledge source it copies for the caller (guard two)', () => { + const DUPLICATE = DOORS.find((d) => d.name === 'POST /:id/duplicate')!; + const REFUSAL = { + admitted: false, status: 403, code: 'PERMISSION_DENIED', + message: "The knowledge source \"faq\" was not saved: you may not query field 'salary' of object 'article'.", + }; + /** A stack whose kernel also serves a knowledge service answering `admit`. */ + function withKnowledge(holding: Holding, admit: (item: unknown, ctx: unknown) => unknown) { + const admitAuthoredSource = vi.fn(async (item: unknown, c: unknown) => admit(item, c)); + return { ...make(holding, { admitAuthoredSource }), admitAuthoredSource }; + } + + it('a holder of both capabilities who may not search what a source indexes is refused with the gate\'s sentence, and nothing is copied', async () => { + const s = withKnowledge({ items: [SOURCE_ITEM] }, () => REFUSAL); + const caller = authed(BOTH); + const r = await call(s, DUPLICATE, caller); + expect(r.response?.status).toBe(403); + expect(r.response?.body?.error?.message).toContain('nothing was copied'); + expect(r.response?.body?.error?.message).toContain(REFUSAL.message); + expect(s.protocol.duplicatePackage).not.toHaveBeenCalled(); + // Judged as the caller, on the item the package holds. + expect(s.admitAuthoredSource).toHaveBeenCalledWith(SOURCE_ITEM, caller.executionContext); + }); + + it('every source is asked about: the second one refused refuses the duplicate', async () => { + const second = { ...SOURCE_ITEM, name: 'handbook' }; + const s = withKnowledge({ items: [SOURCE_ITEM, second] }, (item: any) => (item.name === 'handbook' ? REFUSAL : { admitted: true })); + expect((await call(s, DUPLICATE, authed(BOTH))).response?.status).toBe(403); + expect(s.admitAuthoredSource).toHaveBeenCalledTimes(2); + expect(s.protocol.duplicatePackage).not.toHaveBeenCalled(); + }); + + it('fails closed: a verdict that throws, and a listing that throws, refuse 503', async () => { + const thrown = withKnowledge({ items: [SOURCE_ITEM] }, () => { throw new Error('registry unavailable'); }); + expect((await call(thrown, DUPLICATE, authed(BOTH))).response?.status).toBe(503); + expect(thrown.protocol.duplicatePackage).not.toHaveBeenCalled(); + + const unread = withKnowledge({ throws: 'getMetaItemsPerPackage' }, () => ({ admitted: true })); + const r = await call(unread, DUPLICATE, authed(BOTH)); + expect(r.response?.status).toBe(503); + expect(r.response?.body?.error?.message).toContain('Nothing was copied'); + expect(unread.protocol.duplicatePackage).not.toHaveBeenCalled(); + }); + + it('CONTROL: admitted sources are copied; a package with none, and a host with no knowledge service, copy as before', async () => { + const admitted = withKnowledge({ items: [SOURCE_ITEM] }, () => ({ admitted: true })); + expect((await call(admitted, DUPLICATE, authed(BOTH))).response?.status).not.toBe(403); + expect(admitted.protocol.duplicatePackage).toHaveBeenCalled(); + + const none = withKnowledge({ items: [] }, () => REFUSAL); + expect((await call(none, DUPLICATE, authed(METADATA_ONLY))).response?.status).not.toBe(403); + expect(none.admitAuthoredSource).not.toHaveBeenCalled(); + expect(none.protocol.duplicatePackage).toHaveBeenCalled(); + + const noService = make({ items: [SOURCE_ITEM] }); + expect((await call(noService, DUPLICATE, authed(BOTH))).response?.status).not.toBe(403); + expect(noService.protocol.duplicatePackage).toHaveBeenCalled(); + }); + + it('the engine\'s own call is not asked', async () => { + const s = withKnowledge({ items: [SOURCE_ITEM] }, () => REFUSAL); + expect((await call(s, DUPLICATE, system())).response?.status).not.toBe(403); + expect(s.admitAuthoredSource).not.toHaveBeenCalled(); + expect(s.protocol.duplicatePackage).toHaveBeenCalled(); + }); +}); + describe('/packages — what the gate leaves alone', () => { it('the draft listing\'s own answer for an id nothing carries is not a fault: the door answers that id as before', async () => { const s = make(); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index aea70c5900a..835f0044ffe 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -47,6 +47,10 @@ import type { GetPackageCustomizationsResponse } from '@objectstack/spec/api'; // [ADR-0131 D3 · D12 items 7–8] The walled refusal's one predicate, asked by // every package write door below, never restated here. import { walledCatalogWriteVerdict } from '@objectstack/metadata-core'; +// [ADR-0161 K4, guard two] Source admission, asked for each knowledge source a +// duplicate would copy (`refuseDuplicatedKnowledgeSources`). +import { KNOWLEDGE_SOURCE_ADMISSION_SERVICE, authoredKnowledgeSourceRefusal } from '@objectstack/metadata-core'; +import { isMissingTableError } from '@objectstack/types'; import { readEffectiveTenancyPosture } from './activation-gate.js'; // [#21727] ADR-0087 D1's protocol handshake and the brand predicate for its // refusal. The install branch asks the predicate ahead of its generic catch, @@ -505,6 +509,48 @@ async function refuseKnowledgeSourcePackageWrite( }; } +/** The metadata store objects the knowledge-source listings read. */ +const KNOWLEDGE_SOURCE_ITEM_STORE = 'sys_metadata'; +const KNOWLEDGE_SOURCE_HISTORY_STORE = 'sys_metadata_commit'; + +/** + * Whether a listing failed because this host has no metadata store to list: + * the store's table was never created (`isMissingTableError`, the predicate the + * protocol's own overlay reads use), or the engine holds no such object + * (`OBJECT_NOT_FOUND` carrying the store's own name). A store that does not + * exist holds no draft, item or commit, so the listing's answer is "none" and + * the door goes on as it does on that host today. + * + * Conservative in the direction the protocol's rule is: only those two + * positively identified shapes read as absent. Every other failure is a + * listing that could not be read, and the gate refuses. + */ +function knowledgeSourceStoreIsAbsent(error: unknown, store: string): boolean { + if (isMissingTableError(error, store)) return true; + for (let node: any = error, depth = 0; node !== null && typeof node === 'object' && depth < 8; node = node.cause, depth += 1) { + if (node.code === 'OBJECT_NOT_FOUND' && node.object === store) return true; + } + return false; +} + +/** + * The knowledge sources a package holds, read from the per-package layer + * (`getMetaItemsPerPackage`): the package's own items, never another + * package's item served under the same name. A protocol with no such layer, + * and a host with no metadata store ({@link knowledgeSourceStoreIsAbsent}), + * answer none. Throws when the listing throws for any other reason. + */ +async function packageKnowledgeSourceItems(protocol: PackagesDomainProtocol, packageId: string): Promise { + if (typeof protocol.getMetaItemsPerPackage !== 'function') return []; + try { + const listed: any = await protocol.getMetaItemsPerPackage({ type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, packageId }); + return Array.isArray(listed?.items) ? listed.items : []; + } catch (e) { + if (knowledgeSourceStoreIsAbsent(e, KNOWLEDGE_SOURCE_ITEM_STORE)) return []; + throw e; + } +} + /** * The first knowledge source a verb's reach holds, as a phrase the refusal * can name, or `undefined` when the reach holds none. Throws when a listing @@ -525,26 +571,26 @@ async function knowledgeSourceInPackageReach( try { drafts = (await protocol.listDrafts({ packageId, type: KNOWLEDGE_SOURCE_PACKAGE_TYPE }))?.drafts ?? []; } catch (e: any) { - // The listing's own answer for an id no installed package and no - // draft carries: there is nothing pending to reach, and the door - // answers that id as it always has. - if (e?.code !== 'INVALID_REQUEST') throw e; + // `INVALID_REQUEST` is the listing's own answer for an id no + // installed package and no draft carries: there is nothing pending + // to reach, and the door answers that id as it always has. A host + // with no metadata store holds no draft either. + if (e?.code !== 'INVALID_REQUEST' && !knowledgeSourceStoreIsAbsent(e, KNOWLEDGE_SOURCE_ITEM_STORE)) throw e; } const draft = drafts.find((d) => isKnowledgeSource(d?.type)); if (draft) return `a pending draft of the knowledge source${named(draft.name)}`; } if (reach.includes('items')) { - const read = typeof protocol.getMetaItemsPerPackage === 'function' - ? protocol.getMetaItemsPerPackage({ type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, packageId }) - : typeof (protocol as any).getMetaItems === 'function' - ? (protocol as any).getMetaItems({ type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, packageId }) - : undefined; - const listed: any = await read; - const items: any[] = Array.isArray(listed?.items) ? listed.items : []; + const items = await packageKnowledgeSourceItems(protocol, packageId); if (items.length > 0) return `the knowledge source${named(items[0]?.name)}`; } if (reach.includes('history') && typeof protocol.listCommits === 'function') { - const commits: any[] = (await protocol.listCommits({ packageId })) ?? []; + let commits: any[] = []; + try { + commits = (await protocol.listCommits({ packageId })) ?? []; + } catch (e) { + if (!knowledgeSourceStoreIsAbsent(e, KNOWLEDGE_SOURCE_HISTORY_STORE)) throw e; + } const one = input.commitId === undefined ? undefined : commits.find((c) => c?.id === input.commitId); // A named commit the timeline lists is judged alone; one it does not // list, and the rollback, are judged on the whole timeline. @@ -556,6 +602,69 @@ async function knowledgeSourceInPackageReach( return undefined; } +/** + * [ADR-0161 K4, guard two, at the duplicate door] A duplicate saves each of + * the source package's knowledge sources again, in the copy, and the caller + * is the author of every one of them. So each is admitted for that caller + * before anything is copied, by the predicate the `/meta` save asks + * (`authoredKnowledgeSourceRefusal`): the caller must themselves be allowed to + * search what the source indexes. The first source refused refuses the whole + * duplicate with the predicate's own status and sentence; nothing was copied. + * + * Asked of every caller but the engine's own call, a holder of + * `manage_knowledge_sources` included: the capability says who may author a + * source, and this says what a given author may index. + * + * The item is judged as the source package holds it. The copy renames the + * package's objects, and the renamed object carries the same fields, so the + * source's own object is the one whose rules the caller can be asked about + * before the copy exists. + * + * Fail direction: closed, as the predicate's is. A listing that throws + * refuses `503`; a protocol with no per-package listing holds nothing to + * judge. + */ +async function refuseDuplicatedKnowledgeSources( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + protocol: PackagesDomainProtocol, + packageId: string, +): Promise { + const ec: any = context?.executionContext; + if (ec?.isSystem) return null; + const action = `Duplicating package "${packageId}"`; + let items: any[] = []; + try { + items = await packageKnowledgeSourceItems(protocol, packageId); + } catch (e) { + return { + handled: true, + response: deps.error( + `${action} is refused: the knowledge sources of the package could not be read ` + + `(${clientFacingFailureText(e, 'the listing failed')}), and each one a duplicate copies is admitted for ` + + 'the caller first. Nothing was copied; try again.', + 503, + ), + }; + } + for (const item of items) { + const refused = await authoredKnowledgeSourceRefusal({ + type: KNOWLEDGE_SOURCE_PACKAGE_TYPE, + item, + executionContext: ec, + resolveKnowledgeService: () => + deps.resolveServiceOrLoud(context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, context.environmentId), + }); + if (refused) { + return { + handled: true, + response: deps.error(`${action} is refused, and nothing was copied. ${refused.message}`, refused.status), + }; + } + } + return null; +} + /** * The actor a package write door records (ADR-0146 D1): the user id of the * execution context this request was authorized as — the same context @@ -3994,6 +4103,11 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // the target package record (`installPackage`) ahead of its copy // loop, so a refusal any later still leaves the empty shell behind. const notABase = requireDuplicableSource(deps, qlService, id); if (notABase) return notABase; + // [ADR-0161 K4, guard two] Each knowledge source the copy would + // hold is admitted for this caller, before the copy's package + // record is minted. + const sourceAdmission = await refuseDuplicatedKnowledgeSources(deps, _context, protocol, id); + if (sourceAdmission) return sourceAdmission; try { const actor = resolvePackageWriteActor(_context); const result = await protocol.duplicatePackage({ From 737f44341d1bc5ce6f1ce3445e53544027d95cff Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:45:36 +0000 Subject: [PATCH 23/29] spec: regenerate authorable-defaults after merging main Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- packages/spec/authorable-defaults/ai.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/spec/authorable-defaults/ai.json b/packages/spec/authorable-defaults/ai.json index ed75da841de..f9509e9bc84 100644 --- a/packages/spec/authorable-defaults/ai.json +++ b/packages/spec/authorable-defaults/ai.json @@ -2,7 +2,6 @@ "description": "Ratchet of the DEFAULT VALUE of every authorable key in one category that has one (#4666) — what a metadata author gets when they omit the key, which for AI-authored metadata is most of the time. Sharded by category like authorable-surface/; the gate reads the whole authorable-defaults/ directory as ONE set. Each line is \": = \". Additions (a NEW key that ships with a default) are auto-recorded — commit the change. CHANGING, ADDING or REMOVING the default of a key that already existed is NOT auto-recorded: it silently alters the behaviour of already-deployed metadata, so it fails check:authorable-surface until it is declared in DEFAULT_CHANGES_BY_MAJOR (scripts/lib/default-changes.ts). Constraints are deliberately NOT recorded here — a tightened bound REJECTS a document loudly, which is a different and self-announcing class (maintainer ruling on #4666, direction B). See #4666, #4661.", "category": "ai", "defaults": [ - "ai/AIModelConfig:provider = \"openai\"", "ai/AIModelConfig:temperature = 0.7", "ai/Agent:active = true", "ai/Agent:surface = \"ask\"", From cf128e59fd446b909083e4ea19214c0176cbc839 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:53:26 +0000 Subject: [PATCH 24/29] runtime: the package gate leaves ensure-customization alone; tests follow the gate's reads The knowledge-source gate is asked by the twelve doors that write an existing package. The ensure-customization door is not asked, as the install door is not: it writes nothing of the base and the pair it creates holds no knowledge source (pinned). Five existing runtime test files are adjusted for the read the gate makes for a caller without the capability; the duplicate pin counts the copy's own reads. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .../37304-knowledge-source-governed-type.md | 2 +- content/docs/protocol/knowledge.mdx | 12 ++-- .../src/domains/error-passthrough.test.ts | 6 +- .../packages-ensure-customization.test.ts | 62 ++++++++++++++++++- .../packages-knowledge-source-gate.test.ts | 41 +++++++++++- ...ublish-drafts-probe-caller-context.test.ts | 4 ++ ...publish-drafts-request-conformance.test.ts | 15 ++++- packages/runtime/src/domains/packages.ts | 22 +++---- .../src/package-state-host-store.test.ts | 6 +- packages/spec/src/security/capabilities.ts | 4 +- 10 files changed, 149 insertions(+), 25 deletions(-) diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index b0fa4100559..083db149b5e 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -45,7 +45,7 @@ What changes: - **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names; an empty-string member is refused, and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. - **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. - **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. -- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, ensure-customization, the manifest update and delete. A package that holds none is written as before, and the install door is not asked. A duplicate also admits each knowledge source it copies for the caller (source admission, below), and refuses the whole copy when one is refused. +- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, the manifest update and delete. A package that holds none is written as before. The install door is not asked, and neither is ensure-customization, which writes nothing of the base and creates an empty pair. A duplicate also admits each knowledge source it copies for the caller (source admission, below), and refuses the whole copy when one is refused. - **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`. The fields judged are the ones the source serves and the ones its `where` reads, at save and at search: a source whose `where` reads a field a caller may not query is not searched for that caller. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. - **One name, one source.** `KnowledgeServicePlugin({ sources })` and `registerSource` stay a door for the same schema and parse with it: a retired key is refused with its prescription (`400 VALIDATION_ERROR`), not converted. A source registered in code belongs to no package. It shares one slot with an environment-authored item of the same name, and the second of the two to arrive is refused `409 RESOURCE_CONFLICT`, naming both doors; a metadata item reloading its own earlier version is not a second arrival. - **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed, with the `file` / `http` branches that served them. They are runtime-interface-only members with no metadata form, so the compiler reports each call (`TS2339`). diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 857fc6da0a3..613349abc3f 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -197,11 +197,13 @@ and the MCP draft door: agent's. The package doors ask it too: every write to an existing package that holds a knowledge source (enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, - duplicate, ensure-customization, the manifest update and delete) needs the - capability, and is refused `403` naming it otherwise. A package that holds - none is written as before. Installing a package is not asked: a packaged - source arrives by the install door's own admission. A duplicate also - admits each knowledge source it copies for the caller, by guard two below. + duplicate, the manifest update and delete) needs the capability, and is + refused `403` naming it otherwise. A package that holds none is written as + before. Two doors are not asked. Installing a package is one: a packaged + source arrives by the install door's own admission. Creating a package's + customization pair (ensure-customization) is the other: it writes nothing + of the base, and the pair it creates is empty. A duplicate also admits + each knowledge source it copies for the caller, by guard two below. 2. **Source admission at save.** A source is saved only when its author may themselves search what it would index. The save asks the same gates a search asks ([Source admission](#source-admission-exposure-and-field-level-rules)) diff --git a/packages/runtime/src/domains/error-passthrough.test.ts b/packages/runtime/src/domains/error-passthrough.test.ts index 1afc305d272..e360b28d301 100644 --- a/packages/runtime/src/domains/error-passthrough.test.ts +++ b/packages/runtime/src/domains/error-passthrough.test.ts @@ -83,8 +83,12 @@ async function dispatchWith(method: string, path: string, err: unknown, body: an // reaching the mapping under test. Only the caller's capabilities are stubbed; // every mechanism and expected status below is unchanged. (The /meta and /ui // routes in the loop need no capability, and holding extra ones never rejects.) + // [#37304] `manage_knowledge_sources` too: for a caller without it the PATCH + // door first reads whether the package holds a knowledge source, and this + // protocol double throws from every member, so the door would answer for + // that read instead of for the `updatePackage` error this pins. (dispatcher as any).timedResolveExecutionContext = async () => ({ - userId: 'u1', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'], + userId: 'u1', systemPermissions: ['manage_metadata', 'manage_knowledge_sources', 'studio.access', 'setup.access'], }); const result: any = await dispatcher.dispatch(method, path, body, {}, {} as any); return result.response; diff --git a/packages/runtime/src/domains/packages-ensure-customization.test.ts b/packages/runtime/src/domains/packages-ensure-customization.test.ts index 9063118739c..943f00eab20 100644 --- a/packages/runtime/src/domains/packages-ensure-customization.test.ts +++ b/packages/runtime/src/domains/packages-ensure-customization.test.ts @@ -24,7 +24,7 @@ // Pays `@objectstack/metadata`'s first load at collection, never inside a clocked case. import '@objectstack/metadata'; -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -391,6 +391,52 @@ describe(`${ENSURE_PATH}: the caller's authority is the install door's`, () => { }); }); +/** + * [#37304, ADR-0161 K4] Why this door is not asked `manage_knowledge_sources`: + * it creates no knowledge source. A base that holds one, as a registered item + * and as a stored row, gets a pair that holds none, and the door writes one + * manifest and no row. + */ +describe(`${ENSURE_PATH}: the pair of a base that holds a knowledge source holds none`, () => { + const SOURCE = { name: 'crm_faq', label: 'FAQ', adapter: 'memory', source: { kind: 'object', object: 'crm_article', content: ['body'] } }; + const STORED = { + id: 'row_crm_faq', type: 'knowledge_source', name: SOURCE.name, package_id: CRM.id, state: 'active', + metadata: JSON.stringify(SOURCE), + }; + + it('201 for a manage_metadata caller, zero knowledge sources in the pair, and no row written', async () => { + const d = withBase(door()); + d.registry.registerItem('knowledge_source', { ...SOURCE }, 'name', CRM.id); + // The base's stored row answers every `sys_metadata` read that does not + // name another package; every engine write is recorded. + const rowWrites: unknown[] = []; + d.engine.find = async (object: string, query: any) => { + if (object !== 'sys_metadata') return []; + const owner = query?.where?.package_id; + return owner === undefined || owner === CRM.id ? [{ ...STORED }] : []; + }; + for (const verb of ['insert', 'update', 'upsert', 'delete', 'bulkInsert', 'bulkUpdate']) { + d.engine[verb] = async (...args: unknown[]) => { rowWrites.push([verb, ...args]); return args[1] ?? null; }; + } + // CONTROL: the base does hold one, by the listing the package gate reads. + expect(d.registry.listItems('knowledge_source', CRM.id)).toHaveLength(1); + + const r = await ensure(d, CRM.id, ADMIN); + expect(r.response.status, JSON.stringify(r.response.body)).toBe(201); + expect(r.response.body.data).toMatchObject({ packageId: PAIR_ID, created: true }); + + expect(d.registry.listItems('knowledge_source', PAIR_ID)).toEqual([]); + const listed = await d.protocol!.getMetaItemsPerPackage({ type: 'knowledge_source', packageId: PAIR_ID }); + expect(listed.items).toEqual([]); + expect(rowWrites).toEqual([]); + // One manifest persisted, and it carries no source. + expect(d.published).toHaveLength(1); + expect(JSON.stringify(d.published[0])).not.toContain('knowledge'); + // The base still holds its own. + expect(d.registry.listItems('knowledge_source', CRM.id)).toHaveLength(1); + }); +}); + describe(`${ENSURE_PATH}: one pair under concurrency`, () => { it('two concurrent calls leave one pair: one 201, one 200, one write', async () => { // Each persist settles a tick later, so both calls are in flight together. @@ -479,12 +525,24 @@ describe('POST /api/v1/packages/:id/duplicate: a copy into a pair id is refused, const d = withBase(door()); const source = { id: 'com.acme.notes', name: 'Notes', version: '1.0.0', type: 'app', namespace: 'notes' }; expect((await install(d, source)).response.status).toBe(201); + // [#37304] Counted inside `duplicatePackage` only. Before the copy + // runs, the door reads the source package's knowledge sources to admit + // them for the caller (`packages-knowledge-source-gate.test.ts`); those + // reads are the door's, and this pins the copy's own order: the target + // id is refused before the copy reads a row. let rowsRead = 0; + let copying = false; const find = d.engine.find; - d.engine.find = async (...args: unknown[]) => { rowsRead++; return find(...args); }; + d.engine.find = async (...args: unknown[]) => { if (copying) rowsRead++; return find(...args); }; + const duplicatePackage = d.protocol!.duplicatePackage.bind(d.protocol); + const copies = vi.spyOn(d.protocol!, 'duplicatePackage').mockImplementation(async (request) => { + copying = true; + try { return await duplicatePackage(request); } finally { copying = false; } + }); const writes = d.published.length; const r = await d.dispatcher.handlePackages(`/${source.id}/duplicate`, 'POST', { targetPackageId: PAIR_ID }, {}, ctx(ADMIN)) as any; expectRefusal(r, 400, 'VALIDATION_ERROR', `Package '${PAIR_ID}' is the paired customization package of '${CRM.id}'`, ENSURE_PATH.replace('POST ', '')); + expect(copies).toHaveBeenCalledTimes(1); expect(rowsRead).toBe(0); expect(d.registry.getPackage(PAIR_ID)).toBeUndefined(); expect(d.published).toHaveLength(writes); diff --git a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts index 562d7c92709..9baf9fcae0e 100644 --- a/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts +++ b/packages/runtime/src/domains/packages-knowledge-source-gate.test.ts @@ -106,7 +106,11 @@ interface Door { target: (s: Stack) => any; } -/** Every write door of an existing package, each with the writer it must not reach when refused. */ +/** + * Every door that writes an existing package, each with the writer it must not + * reach when refused. The install door and the ensure-customization door are + * not here: neither is asked (pinned under "what the gate leaves alone"). + */ const DOORS: Door[] = [ { name: 'PATCH /:id/enable', path: '/pkg-a/enable', method: 'PATCH', target: (s) => s.registry.enablePackage }, { name: 'PATCH /:id/disable', path: '/pkg-a/disable', method: 'PATCH', target: (s) => s.registry.disablePackage }, @@ -118,7 +122,6 @@ const DOORS: Door[] = [ { name: 'POST /:id/revert', path: '/pkg-a/revert', method: 'POST', target: (s) => s.protocol.revertStoredPackage }, { name: 'POST /:id/adopt-orphans', path: '/pkg-a/adopt-orphans', method: 'POST', target: (s) => s.protocol.reassignOrphanedMetadata }, { name: 'POST /:id/duplicate', path: '/pkg-a/duplicate', method: 'POST', body: { targetPackageId: 'pkg-b' }, target: (s) => s.protocol.duplicatePackage }, - { name: 'POST /:id/ensure-customization', path: '/pkg-a/ensure-customization', method: 'POST', target: (s) => s.protocol.ensureCustomizationPackage }, { name: 'PATCH /:id (manifest)', path: '/pkg-a', method: 'PATCH', body: { name: 'renamed' }, target: (s) => s.protocol.updatePackage }, { name: 'DELETE /:id', path: '/pkg-a', method: 'DELETE', tenantId: 'org_a', target: (s) => s.protocol.deletePackage }, ]; @@ -305,6 +308,40 @@ describe('/packages — what the gate leaves alone', () => { expect(s.protocol.discardPackageDrafts).toHaveBeenCalled(); }); + it('a host with no metadata store holds no knowledge source: a missing table, and a store object the engine does not hold, are not faults', async () => { + const absent: Array<() => Error> = [ + () => new Error('no such table: sys_metadata'), + () => Object.assign(new Error("Object 'sys_metadata' not found"), { code: 'OBJECT_NOT_FOUND', status: 404, object: 'sys_metadata' }), + ]; + const door = DOORS.find((d) => d.name === 'PATCH /:id/disable')!; + for (const error of absent) { + const s = make(); + s.protocol.listDrafts.mockImplementation(async () => { throw error(); }); + s.protocol.getMetaItemsPerPackage.mockImplementation(async () => { throw error(); }); + const r = await call(s, door, authed(METADATA_ONLY)); + expect(r.response?.status, error().message).toBe(200); + expect(s.registry.disablePackage).toHaveBeenCalled(); + } + // CONTROL: the same envelope naming another object is a listing that + // could not be read, and refuses. + const s = make(); + s.protocol.listDrafts.mockImplementation(async () => { + throw Object.assign(new Error("Object 'ghost' not found"), { code: 'OBJECT_NOT_FOUND', status: 404, object: 'ghost' }); + }); + const r = await call(s, door, authed(METADATA_ONLY)); + expect(r.response?.status).toBe(503); + expect(s.registry.disablePackage).not.toHaveBeenCalled(); + }); + + it('the ensure-customization door is not asked: it writes nothing of the base, and the pair it creates is empty', async () => { + const s = make({ items: [SOURCE_ITEM], drafts: [SOURCE_DRAFT] }); + const r = await s.dispatcher.handlePackages('/pkg-a/ensure-customization', 'POST', {}, {}, authed(METADATA_ONLY)); + expect(r.response?.status).toBe(201); + expect(s.protocol.ensureCustomizationPackage).toHaveBeenCalledWith({ basePackageId: 'pkg-a' }); + expect(s.protocol.getMetaItemsPerPackage).not.toHaveBeenCalled(); + expect(s.protocol.listDrafts).not.toHaveBeenCalled(); + }); + it('the install door is not asked: a packaged source arrives by that door\'s own admission (ADR-0161 K4)', async () => { const s = make({ items: [SOURCE_ITEM] }); const manifest = { id: 'com.example.pkg-new', name: 'n', version: '1.0.0', type: 'app' }; diff --git a/packages/runtime/src/domains/packages-publish-drafts-probe-caller-context.test.ts b/packages/runtime/src/domains/packages-publish-drafts-probe-caller-context.test.ts index c4e588de4f4..fc9a43397aa 100644 --- a/packages/runtime/src/domains/packages-publish-drafts-probe-caller-context.test.ts +++ b/packages/runtime/src/domains/packages-publish-drafts-probe-caller-context.test.ts @@ -129,6 +129,10 @@ function makeDoor(items: Record = ITEMS) { return { item: items[`${type} ${name}`] }; }; p.getMetaItems = async () => ({ items: [] }); + // [#37304] The door asks whether the package holds a knowledge source for a + // caller without `manage_knowledge_sources`. This double has no registry + // to list from, so it answers as a package that holds none. + p.getMetaItemsPerPackage = async () => ({ items: [] }); const engineFinds: Array<{ object: string; context: unknown }> = []; p.engine = { find: async (object: string, query: any) => { diff --git a/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts b/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts index 4d6555f48c9..9d108a18d36 100644 --- a/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts +++ b/packages/runtime/src/domains/packages-publish-drafts-request-conformance.test.ts @@ -215,6 +215,19 @@ describe('a backfill the schema refuses is refused at the door before anything i return new ObjectStackProtocolImplementation(untouchable as any, undefined, undefined, 'package-author'); } + /** + * [#37304] The caller also holds `manage_knowledge_sources`. The door reads + * whether the package holds a knowledge source for a caller who does not + * (`packages-knowledge-source-gate.test.ts`), which is a read before the + * protocol runs; a holder is answered without one. What this case pins is + * the protocol's own order, the shape judgement before any read. + */ + const SOURCE_ADMIN = () => { + const context = PKG_ADMIN(); + context.executionContext.systemPermissions.push('manage_knowledge_sources'); + return context; + }; + it('answers 400 VALIDATION_ERROR naming the entry, for each malformed shape', async () => { const bodies: Array<{ body: Record; path: string }> = [ { body: { backfill: { object: 'crm_account', field: 'is_key' } }, path: 'backfill' }, @@ -228,7 +241,7 @@ describe('a backfill the schema refuses is refused at the door before anything i const protocol = realProtocol(); const publish = vi.spyOn(protocol, 'publishPackageDrafts'); const { dispatcher } = makeDoor(protocol as unknown as Record); - const result = await dispatcher.handlePackages(`/${PKG}/publish-drafts`, 'POST', body, {}, PKG_ADMIN()); + const result = await dispatcher.handlePackages(`/${PKG}/publish-drafts`, 'POST', body, {}, SOURCE_ADMIN()); const response = result.response as any; expect(response.status, JSON.stringify(body)).toBe(400); expect(response.body?.error?.code, JSON.stringify(body)).toBe('VALIDATION_ERROR'); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 835f0044ffe..3c56bb0ae7f 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -445,10 +445,10 @@ type KnowledgeSourcePackageReach = 'drafts' | 'items' | 'history'; * package's items into a new one, adopt-orphans binds items to it, and enable, * disable and delete decide whether its items are served at all. Where one of * those items is a knowledge source the verb does to it what a `/meta` write - * would. So the rule is stated on the package and is the same at every write - * door of an existing package: one that holds a knowledge source is written by - * a holder of the capability that write asks (`metaTypeWriteRefusal`, the one - * decision). + * would. So the rule is stated on the package and is the same at every door + * that writes an existing package: one that holds a knowledge source is + * written by a holder of the capability that write asks + * (`metaTypeWriteRefusal`, the one decision). * * Asked right after {@link requireManageMetadata} and the wall, and before * anything is written. A holder of the capability, and the engine's own call @@ -462,7 +462,9 @@ type KnowledgeSourcePackageReach = 'drafts' | 'items' | 'history'; * capability probe every door of this file already asks. * * Not asked by the install door (`POST /packages`): a packaged source arrives - * by that door's own admission, as ADR-0161 K4 leaves it. + * by that door's own admission, as ADR-0161 K4 leaves it. Not asked by the + * ensure-customization door either: it writes nothing of the package its path + * names, and the pair it creates is empty. */ async function refuseKnowledgeSourcePackageWrite( deps: DomainHandlerDeps, @@ -4138,12 +4140,10 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Ensuring the customization package of "${id}"`); if (walled) return walled; - // [ADR-0161 K4, guard one] A package that holds a knowledge source - // asks `manage_knowledge_sources` too. - const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { - packageId: id, action: `Ensuring the customization package of "${id}"`, reach: ['drafts', 'items'], - }); - if (sourceGate) return sourceGate; + // [ADR-0161 K4] Not asked `manage_knowledge_sources`, as the install + // door is not: this door writes nothing of the base and creates an + // empty pair, so no knowledge source is created, changed or removed + // by it (pinned in `packages-ensure-customization.test.ts`). // [cloud#3814 D1] Declared replicas on the Redis driver: this change // would reach the serving replica only. Refused before anything is written. const oneReplica = await refuseMultiReplicaPackageChange(deps, _context, `Ensuring the customization package of "${id}"`); diff --git a/packages/runtime/src/package-state-host-store.test.ts b/packages/runtime/src/package-state-host-store.test.ts index 4d99d3b2e54..9748692e499 100644 --- a/packages/runtime/src/package-state-host-store.test.ts +++ b/packages/runtime/src/package-state-host-store.test.ts @@ -47,9 +47,13 @@ import { packageStateFileName, setPackageDisabled } from './package-state-store. const ENVIRONMENT_ID = 'env_host_store'; const PKG = 'com.acme.reporting'; const OTHER = 'com.acme.billing'; +// [#37304] Also a holder of `manage_knowledge_sources`: for anyone else the +// enable and disable doors read whether the package holds a knowledge source, +// and this kernel registers no driver to read with. The cases here are about +// where the package state is written. const ADMIN = { userId: 'u_admin', tenantId: 'org_qa', isSystem: false, - positions: [], permissions: [], systemPermissions: ['manage_metadata'], + positions: [], permissions: [], systemPermissions: ['manage_metadata', 'manage_knowledge_sources'], }; interface Row { enabled?: boolean; status?: string } diff --git a/packages/spec/src/security/capabilities.ts b/packages/spec/src/security/capabilities.ts index c9efb7004f0..1d469a17ed6 100644 --- a/packages/spec/src/security/capabilities.ts +++ b/packages/spec/src/security/capabilities.ts @@ -119,7 +119,9 @@ export const PLATFORM_CAPABILITIES: readonly PlatformCapability[] = [ // `/meta`, the dispatcher, the MCP draft door), and every write door of an // existing package that holds one (`/packages/:id/…`), asks this capability // BESIDE `manage_metadata`, never instead of it. The install door is not - // asked: a packaged source arrives by that door's own admission. Held by default by platform + // asked: a packaged source arrives by that door's own admission. Nor is the + // ensure-customization door, which writes nothing of the package it names + // and creates an empty pair. Held by default by platform // administrators only (`ADMIN_FULL_ACCESS_CAPABILITIES`); every other // position, organization administrators included, only by explicit grant. // A grant on the indexed object's records does not imply it. `platform`: From 20f929970dba273e61cb39ec5364bfda018897b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 02:34:15 +0000 Subject: [PATCH 25/29] docs: census rows name the package-door guards; changeset states the gate's order and its 503 The system-context page's rows 46 and 55 name the two package-door guards, and the site register is regenerated. The changeset says that the package gate reads before the door's own request checks and refuses 503 when the holding cannot be read. One edited test file pays its first load of the metadata package at collection, as the test-source alias gate asks of an edited test. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- .changeset/37304-knowledge-source-governed-type.md | 2 +- content/docs/permissions/system-context.mdx | 6 ++++-- packages/runtime/src/domains/error-passthrough.test.ts | 2 ++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.changeset/37304-knowledge-source-governed-type.md b/.changeset/37304-knowledge-source-governed-type.md index 083db149b5e..2006b148aed 100644 --- a/.changeset/37304-knowledge-source-governed-type.md +++ b/.changeset/37304-knowledge-source-governed-type.md @@ -45,7 +45,7 @@ What changes: - **The schema is strict.** An undeclared key is refused, never dropped. `content` is a non-empty list of field names; an empty-string member is refused, and `'*'` is refused with the instruction to list the fields: embedding is egress, and the wildcard sent every text field of a record to the embedder, including one added to the object later. Credential-class and `internal` fields stay unindexed even when named. - **The loader.** `KnowledgeServicePlugin` reads the published items when it starts and follows the type while it runs: an added source is registered and built when a build is due; a changed one is registered again, and a changed `where` or `metadataFields` rebuilds inside the generation while a changed `content` or `split` builds a new one; a removed one is unregistered and its index dropped. The reap guard now follows the sources, so a retention delete on an object first indexed by a source added after boot de-indexes the row. A deployment that holds an item and mounts no knowledge service says so once at boot, naming the items. - **`IKnowledgeAdapter.dropSource?(ctx)`** removes everything an adapter holds for a source: every generation, the one under construction included, and what it recorded about the index. `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso` implement it, and the contract suite (`@objectstack/service-knowledge/testing`) takes a new `implements.dropSource` declaration. Over an adapter without it, a removed source's index is kept and the service says so once. An adapter is handed the source's index key as `ctx.source.name` (it was `ctx.source.id`): the bare name for a source no package holds, so an existing index is found under the same key. -- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, the manifest update and delete. A package that holds none is written as before. The install door is not asked, and neither is ensure-customization, which writes nothing of the base and creates an empty pair. A duplicate also admits each knowledge source it copies for the caller (source admission, below), and refuses the whole copy when one is refused. +- **A capability of its own.** New platform capability `manage_knowledge_sources`: a write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs it beside `manage_metadata`. Platform administrators hold it by default; a grant on the indexed object's records does not imply it. A caller without it is refused `403 PERMISSION_DENIED`, naming the capability. The package doors ask it too: every write to an existing package that holds a knowledge source (an item, a pending draft, or for the commit revert and the rollback a commit that touched one) needs the capability: enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, the manifest update and delete. A package that holds none is written as before. The install door is not asked, and neither is ensure-customization, which writes nothing of the base and creates an empty pair. For a caller without the capability the doors read the package's holding before their own request checks, so such a caller hears this `403` ahead of a `400`, `404` or `422` the door would have answered for the same request; a holding that cannot be read refuses `503` and changes nothing (a host with no metadata store holds none). A duplicate also admits each knowledge source it copies for the caller (source admission, below), and refuses the whole copy when one is refused. - **Source admission at save.** Those same doors save a source only when its author may themselves search what it would index: an object of a disabled package, an object the API does not serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; a verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`. The fields judged are the ones the source serves and the ones its `where` reads, at save and at search: a source whose `where` reads a field a caller may not query is not searched for that caller. Over MCP it is the human who is judged. Where no knowledge service is mounted there is nothing to ask, and the save goes on. - **One name, one source.** `KnowledgeServicePlugin({ sources })` and `registerSource` stay a door for the same schema and parse with it: a retired key is refused with its prescription (`400 VALIDATION_ERROR`), not converted. A source registered in code belongs to no package. It shares one slot with an environment-authored item of the same name, and the second of the two to arrive is refused `409 RESOURCE_CONFLICT`, naming both doors; a metadata item reloading its own earlier version is not a second arrival. - **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed, with the `file` / `http` branches that served them. They are runtime-interface-only members with no metadata form, so the compiler reports each call (`TS2339`). diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 58b86f2ba50..172e0de5fc1 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -189,7 +189,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal` | +| 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -211,7 +211,7 @@ One of the largest consumers of the flag; | 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `handleActionsRequest`, `dispatchActionRequest`, `resumeActionRunRequest`, `handleAIRequest`, `handleAutomationRequest`, `handleMetadataRequest`, `handleSecurityRequest`, `handlePackagesRequest`, `handleAnalyticsRequest`, `handleI18nRequest`, `registerExternalDatasourceRoutes`, `refusePackageRequest` | | 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `handleMcpRequest` | | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | -| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `requireManageMetadata`, `requireReadCapability` | +| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability; and a write to a package that holds a knowledge source (the twelve doors that write an existing package) without `manage_knowledge_sources` beside it (ADR-0161 K4) | `requireManageMetadata`, `requireReadCapability`, `refuseKnowledgeSourcePackageWrite` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | | 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | @@ -693,6 +693,8 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/mcp.ts#resumeActionRunRequest` | 1 | 52 | | `packages/runtime/src/domains/meta.ts#handleMetadataRequest` | 5 | 50, 52 | | `packages/runtime/src/domains/packages.ts#handlePackagesRequest` | 1 | 52 | +| `packages/runtime/src/domains/packages.ts#refuseDuplicatedKnowledgeSources` | 1 | 46 | +| `packages/runtime/src/domains/packages.ts#refuseKnowledgeSourcePackageWrite` | 1 | 55 | | `packages/runtime/src/domains/packages.ts#refuseWalledCatalogPackageWrite` | 1 | 55b | | `packages/runtime/src/domains/packages.ts#requireCommitTrailReadCapability` | 1 | 8b | | `packages/runtime/src/domains/packages.ts#requireManageMetadata` | 1 | 55 | diff --git a/packages/runtime/src/domains/error-passthrough.test.ts b/packages/runtime/src/domains/error-passthrough.test.ts index e360b28d301..a0c9e5eaea9 100644 --- a/packages/runtime/src/domains/error-passthrough.test.ts +++ b/packages/runtime/src/domains/error-passthrough.test.ts @@ -25,6 +25,8 @@ * underlying error on purpose, because the message could echo row contents. */ +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/metadata'; import { describe, it, expect } from 'vitest'; import { HttpDispatcher } from './../http-dispatcher.js'; From ebc0b7ce8d73163d64f830fb8e24906a59afb3d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 03:37:41 +0000 Subject: [PATCH 26/29] skills: the supportKb example pays for its two renamed keys in the same line After main's own edit the file sat at its ceiling (6801 of 6801), so the two keys this change renames in the example (two bytes longer) put the merged file one token over. The comment on the renamed line is six bytes shorter; the file reads 6800 tokens. No ceiling moves. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- skills/objectstack-ai/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/objectstack-ai/SKILL.md b/skills/objectstack-ai/SKILL.md index 0215dacdd8a..92a2f2d0cd0 100644 --- a/skills/objectstack-ai/SKILL.md +++ b/skills/objectstack-ai/SKILL.md @@ -297,7 +297,7 @@ export const supportKb: KnowledgeSource = KnowledgeSourceSchema.parse({ source: { kind: 'object', object: 'kb_article', - content: ['title', 'body'], // concatenated into document content + content: ['title', 'body'], // joined into document content metadataFields: ['category', 'owner_id'], // projected for search-time filtering where: { published: true }, // index published articles only }, From 2a2218d120a98cd4b69c54ab412c26f0e23ba78a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 04:42:33 +0000 Subject: [PATCH 27/29] skills ratchet: the objectstack-ai row sits at its file's measurement Main's gate now refuses a row above its measurement. The supportKb example on this branch measures 6800 tokens (two bytes added by the two renamed keys, six given back by its comment), so the row is lowered 6801 -> 6800. Shrink-only; no file text moves. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- scripts/check-skills-token-ratchet.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 34c47925a14..c4fb42a320c 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -439,7 +439,9 @@ export const CEILINGS = new Map([ // CEILING_BASIS.strippedInternalIds. `(was N)` is the ceiling this replaced. // Every SKILL.md row was later lowered by exactly 5 when its release-stamp // line left the count (A2′, see STAMP_LINE_REPIN) — its headroom did not move. - ['skills/objectstack-ai/SKILL.md', 6801], // -18 (was 6824), then -5 A2′ (was 6806) + // -1 to the measurement (was 6801, card #37304): the `supportKb` example's + // two renamed keys add two bytes and its comment gives back six. + ['skills/objectstack-ai/SKILL.md', 6800], // -18 (was 6824), then -5 A2′ (was 6806) // -12 (was 6331): the `http.server` decision-table row dropped a trailing // clause that taught `contributes.routes` as a key that "parses but serves // nothing". The key is retired — an authored entry is now REFUSED, carrying From e2949f08100433f8dd6754eafc7347511ebabad5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:06:44 +0000 Subject: [PATCH 28/29] regen: the reference index and the ai authorable surface after merging main The merge of main at 9b50fedbf kept this branch's side of two generated paths both sides had moved. Regenerated on the merged tree: the reference index counts main's new ui page (17 pages, 185 schemas; 222 pages and 1730 schemas in all), and the ai authorable surface carries main's retired marker on AIModelConfig:provider. Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- content/docs/references/index.mdx | 9 +++++---- packages/spec/authorable-surface/ai.json | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 7249ecf8501..97d3503bed5 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1729 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1730 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **221** | **1729** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 17 | 185 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **222** | **1730** | 14 protocol modules | --- @@ -388,7 +388,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 184 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 185 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. @@ -396,6 +396,7 @@ Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI lay | :--- | :--- | | [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionText`, `ActionType`, `InlineAction` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | +| [`ai-chat-nav-params.zod.ts`](/docs/references/ui/ai-chat-nav-params) | `AiChatNavParams` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | | [`bulk-action.zod.ts`](/docs/references/ui/bulk-action) | `BulkActionDef`, `BulkActionExecution`, `BulkActionOperation`, `BulkActionParam`, `BulkActionResult` | | [`chart.zod.ts`](/docs/references/ui/chart) | `ChartAggregate`, `ChartAggregateFunction`, `ChartAnnotation`, `ChartAxis`, `ChartConfig`, `ChartDrillDown`, `ChartGroupBy`, `ChartInteraction`, `ChartSeries`, `ChartType` | diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 9ce11d6cc11..6f4241142ff 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -4,7 +4,7 @@ "keys": [ "ai/AIModelConfig:maxTokens", "ai/AIModelConfig:model", - "ai/AIModelConfig:provider", + "ai/AIModelConfig:provider [RETIRED]", "ai/AIModelConfig:temperature", "ai/AIModelConfig:topP", "ai/AIUsageRecord:costUsd", From dfcdfb8aaa4d4d041d1c5fc59bf8f0dbcc84dcd3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 07:52:17 +0000 Subject: [PATCH 29/29] regen: generated spec artifacts after merging main The merge of main at e69fa46dd took no text merge on six generated paths both sides had moved. Regenerated on the merged tree, so each carries both the form type main admitted and the knowledge source this branch admits: the meta URL spelling data, the ai export origins, and four reference pages (the index, the metadata plugin, the metadata API and the assembled package API). Claude-Session: https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx Co-authored-by: Claude --- content/docs/references/api/metadata.mdx | 5 +++-- content/docs/references/api/package-api-assembled.mdx | 2 ++ content/docs/references/index.mdx | 10 +++++----- content/docs/references/kernel/metadata-plugin.mdx | 6 ++++-- packages/spec/export-origins/ai.json | 8 ++++---- .../spec/src/meta-spelling/meta-url-data.generated.ts | 2 ++ 6 files changed, 20 insertions(+), 13 deletions(-) diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 99045c4f845..5a6df280ec4 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -642,7 +642,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -709,7 +709,7 @@ Metadata query with filtering, sorting, and pagination | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +20 more>` | ✅ | Metadata type | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| … +21 more>` | ✅ | Metadata type | | **name** | `string` | ✅ | Item name (snake_case) | | **data** | `Record` | ✅ | Metadata payload | | **namespace** | `string` | optional | Optional namespace | @@ -724,6 +724,7 @@ Metadata query with filtering, sorting, and pagination * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index e9931b0933d..4a5f6a8ad8f 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -118,6 +118,7 @@ Installed package row whose manifest is the assembled package body | **apps** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Applications | | **views** | `{ name?: string; label?: string \| Record; object?: string; list?: object; … }[]` | optional | List Views | | **viewItems** | `never` | optional | [MACHINE-ASSEMBLED] Non-container view artifacts of a runtime-assembled manifest (standalone ViewItems, flattened overlays) — written by package export and artifact factories, refused in authored stack sources. | +| **forms** | `{ name: string; object: string; label?: string \| Record; type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; … }[]` | optional | Data-entry forms, one object each (ADR-0159): `defineForm` items named `OBJECT.KEY` | | **pages** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Custom Pages | | **dashboards** | `{ name: string; label: string \| Record; description?: string \| Record; header?: object; … }[]` | optional | Dashboards | | **reports** | `{ name: string; label: string \| Record; description?: string \| Record; type?: Enum<'tabular' \| 'summary' \| 'matrix' \| 'joined'>; … }[]` | optional | Analytics Reports | @@ -370,6 +371,7 @@ This schema accepts one of the following structures: | **apps** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Applications | | **views** | `{ name?: string; label?: string \| Record; object?: string; list?: object; … }[]` | optional | List Views | | **viewItems** | `never` | optional | [MACHINE-ASSEMBLED] Non-container view artifacts of a runtime-assembled manifest (standalone ViewItems, flattened overlays) — written by package export and artifact factories, refused in authored stack sources. | +| **forms** | `{ name: string; object: string; label?: string \| Record; type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; … }[]` | optional | Data-entry forms, one object each (ADR-0159): `defineForm` items named `OBJECT.KEY` | | **pages** | `{ name: string; label: string \| Record; description?: string \| Record; icon?: string; … }[]` | optional | Custom Pages | | **dashboards** | `{ name: string; label: string \| Record; description?: string \| Record; header?: object; … }[]` | optional | Dashboards | | **reports** | `{ name: string; label: string \| Record; description?: string \| Record; type?: Enum<'tabular' \| 'summary' \| 'matrix' \| 'joined'>; … }[]` | optional | Analytics Reports | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 97d3503bed5..d303752aca3 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1730 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1731 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 17 | 185 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **222** | **1730** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **222** | **1731** | 14 protocol modules | --- @@ -388,7 +388,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 185 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **17 pages, 186 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. @@ -410,7 +410,7 @@ Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI lay | [`report.zod.ts`](/docs/references/ui/report) | `JoinedReportBlock`, `Report`, `ReportChart`, `ReportSort`, `ReportType` | | [`responsive.zod.ts`](/docs/references/ui/responsive) | `ResponsiveStyles`, `StyleMap` | | [`sharing.zod.ts`](/docs/references/ui/sharing) | `SharingConfig` | -| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `KanbanLaneSummary`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `MetadataListCellType`, `MetadataListColumn`, `MetadataListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | +| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `Form`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `KanbanLaneSummary`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `MetadataListCellType`, `MetadataListColumn`, `MetadataListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | --- diff --git a/content/docs/references/kernel/metadata-plugin.mdx b/content/docs/references/kernel/metadata-plugin.mdx index b57e6e222c3..38293fc8070 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -179,7 +179,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | +| **types** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| 'flow' \| 'job' \| 'datasource' \| 'external_catalog' \| 'translation' \| 'api' \| 'email_template' \| 'doc' \| 'book' \| 'permission' \| 'position' \| 'capability' \| 'sharing_rule' \| 'queue' \| 'assignment_rule' \| 'agent' \| 'tool' \| 'skill' \| 'ai_context' \| 'knowledge_source'>[]` | optional | Filter by metadata types | | **namespaces** | `string[]` | optional | Filter by namespaces | | **packageId** | `string` | optional | Filter by owning package | | **search** | `string` | optional | Full-text search query | @@ -233,6 +233,7 @@ const result = MetadataBulkResultSchema.parse(data); * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` @@ -269,7 +270,7 @@ const result = MetadataBulkResultSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| 'dataset' \| … +20 more>` | ✅ | Metadata type identifier | +| **type** | `Enum<'object' \| 'object_extension' \| 'field' \| 'hook' \| 'seed' \| 'mapping' \| 'picklist' \| 'view' \| 'form' \| 'page' \| 'dashboard' \| 'app' \| 'action' \| 'report' \| … +21 more>` | ✅ | Metadata type identifier | | **label** | `string` | ✅ | Display label for the metadata type | | **description** | `string` | optional | Description of the metadata type | | **filePatterns** | `string[]` | ✅ | Glob patterns to discover files of this type | @@ -293,6 +294,7 @@ const result = MetadataBulkResultSchema.parse(data); * `mapping` * `picklist` * `view` +* `form` * `page` * `dashboard` * `app` diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 1c61062bafc..56c5bbf4c27 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -273,8 +273,8 @@ "ToolSchema": "src/ai/tool.zod.ts#ToolSchema (const)", "TransformPipelineStep": "src/ai/agent.zod.ts#TransformPipelineStep (type)", "TransformPipelineStepSchema": "src/ai/agent.zod.ts#TransformPipelineStepSchema (const)", - "agentForm": "src/ai/agent.form.ts#agentForm (const)", - "aiContextForm": "src/ai/ai-context.form.ts#aiContextForm (const)", + "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", + "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", @@ -286,8 +286,8 @@ "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", "skillBindsRecordContextTool": "src/ai/skill.zod.ts#skillBindsRecordContextTool (function)", - "skillForm": "src/ai/skill.form.ts#skillForm (const)", + "skillForm": "src/ai/skill.metadata-form.ts#skillForm (const)", "stripBodyTags": "src/ai/record-body-anchor.ts#stripBodyTags (function)", - "toolForm": "src/ai/tool.form.ts#toolForm (const)" + "toolForm": "src/ai/tool.metadata-form.ts#toolForm (const)" } } diff --git a/packages/spec/src/meta-spelling/meta-url-data.generated.ts b/packages/spec/src/meta-spelling/meta-url-data.generated.ts index f8ebc2f8e04..c21787bda9a 100644 --- a/packages/spec/src/meta-spelling/meta-url-data.generated.ts +++ b/packages/spec/src/meta-spelling/meta-url-data.generated.ts @@ -19,6 +19,7 @@ export const META_URL_TO_SINGULAR: Readonly> = Object.freeze({ "objects": "object", "apps": "app", + "forms": "form", "pages": "page", "dashboards": "dashboard", "reports": "report", @@ -76,6 +77,7 @@ export const REGISTRY_DECLARED_META_TYPES: ReadonlyArray = Object.freeze "picklist", "mapping", "view", + "form", "page", "dashboard", "app",