Skip to content

Commit d58bf7a

Browse files
feat(spec,service-knowledge)!: knowledge_source is a governed metadata type with its loader, its registry and two authoring guards (#37676)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgHittdG1nUD4Ne4ozfqAXgk)_ Fixes #37304 Clause-②: yes (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #37310 ## 维护者速读 - 用户能看到什么变化:知识源成为一种正式的应用配置,可以随应用一起发布,也可以在 Studio 里新建和修改;保存后平台自动建立、更新或清除对应的检索索引。旧写法升级时会被明确拒绝,迁移命令会列出每一处要改的地方。 - 为什么做:属于“知识检索平台化”专题,让应用写一份知识源配置就有可用的检索,并且谁能建知识源、能索引哪些数据都有人管。 - 出错会怎样:只影响用到知识检索的应用。旧配置没迁移时会报出要改的位置,不会悄悄丢数据或建错索引;新增的“管理知识源”权限默认只有平台管理员有;回退本改动即可恢复原状。 - 要你做什么:批准一次。这是一次不兼容的协议收紧,改了两份对外技能文件(各一两行),改动量也超过三千行,按规则要你批准后才能合并。 ## What changes **New metadata type: `knowledge_source`.** Registered in the metadata type registry with the one schema `KnowledgeSourceSchema`; a stack carries its sources in the new top-level collection `knowledgeSources` (`*.knowledge-source.ts` or `.yml`). An item can be created and changed at run time (Studio, MCP) and takes no environment overlay. Studio's menu lists the type under AI, and ADR-0084's type table carries its row. **New platform capability: `manage_knowledge_sources`.** Platform administrators hold it by default. Nothing else grants it. - **The schema is strict.** An undeclared key is refused. `id` becomes `name`, `source.contentFields` becomes `source.content`, a non-empty list of field names; `'*'` is refused with the instruction to list the fields, and an empty-string member is refused too (it names no field). `embedding`, `vectorStore`, `adapterConfig`, `refresh.cron` and the `file` / `http` source kinds are retired with their ADR-0087 entries (three conversions, six retired keys, six retired defs, four semantic entries on protocol 19). `os migrate meta --from 18` lists every edit and `--write` applies the ones it can prove. - **The loader** (`service-knowledge`, `knowledge-source-loader.ts`). `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 (a changed `where` or `metadataFields` rebuilds inside the generation, a changed `content` or `split` builds a new one); a removed one is unregistered and its index dropped. The reap guard's object set follows the sources. - **The registry** (`knowledge-source-registry.ts`), under the maintainer's rulings on this card (record 7192063608, forks 6 and 4d, both A). A source is held by `(package, name)`. 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 package's source of the same name is a second source. Code names a source by its face: the bare name for the package-less one, `NAMESPACE-NAME` for a package's; a bare name several sources answer to is refused `409`, naming the candidates. `search` hits carry the face as `sourceId`. No `IKnowledgeService` signature changes for addressing. - **`IKnowledgeAdapter.dropSource?(ctx)`**, implemented by `knowledge-memory`, `knowledge-pgvector` and `knowledge-turso`; the contract suite (`@objectstack/service-knowledge/testing`) takes `implements.dropSource`. An adapter reads the source's index key from `ctx.source.name` (it was `ctx.source.id`): the bare name for a package-less source, so an existing index is found under the same key and nothing is rebuilt. - **Guard one: the capability.** A write of a `knowledge_source` through `/meta` (REST and the dispatcher: save, publish, rollback, delete) and through the MCP draft door needs `manage_knowledge_sources` beside `manage_metadata`: `403 PERMISSION_DENIED` naming the capability, `401` for an anonymous caller. It is one row in the existing per-type table `META_TYPE_WRITE_CAPABILITIES` (`packages/rest/src/meta-item-read-gate.ts`), so the three doors that already ask that table ask it for this type too. The package doors ask it as well (maintainer's ruling A, record 7207325373 on #37304): each of the twelve doors that write an existing package (enable, disable, publish, publish-drafts, discard-drafts, the commit revert, rollback, revert, adopt-orphans, duplicate, the manifest update, delete) refuses a caller without the capability `403` when the package holds a knowledge source: an item, a pending draft, or, for the commit revert and the rollback, a commit that touched one. A package that holds none is written as before; a holding that cannot be read refuses `503`. Two doors are not asked, see Acceptance notes. - **Guard two: source admission at save.** The 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`. The fields a source's `where` reads are judged with the fields it serves, at save and at search. A knowledge service that is registered and cannot be resolved refuses the save `503` at every door (REST, the dispatcher, MCP). The duplicate door admits each knowledge source it would copy for the caller before anything is copied, and refuses the whole copy when one is refused. Over MCP the human is judged. - **The push door leaves.** `IKnowledgeService.indexDocument` and `deleteDocument` are removed with the `file` / `http` branches that served them. - **Removed exports**, twelve names from `@objectstack/spec/ai`. The `embedding` module: `EmbeddingModelSchema`, `VectorStoreSchema`, `VectorStoreProviderSchema` and the types `EmbeddingModel`, `VectorStore`, `VectorStoreProvider` (the knowledge source was their only composer). The retired source kinds: `FileKnowledgeSourceSchema`, `HttpKnowledgeSourceSchema`, `KnowledgeSourceKindSchema` and the types `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeSourceKind`. The changeset lists the same twelve. - **Boot notice** (`packages/objectql`). A deployment that holds `knowledge_source` items and mounts no knowledge service says so once at boot, at warn, naming the items; it is not a boot refusal. - **CLI.** `os knowledge status` prints the package that holds a source and no longer a source kind. - **Showcase.** `examples/app-showcase` ships `showcase_task_notes` (object `showcase_task`, adapter `memory`) and mounts the knowledge service and the memory store. - **Docs.** `content/docs/protocol/knowledge.mdx` and `content/docs/ai/knowledge-rag.mdx` describe the type, the loader, who may author a source, and one name per source; the generated references follow. - **Skills (Tier H), enumeration row only**, under ruling A on #32584: `knowledgeSources` joins the top-level key list in `skills/objectstack-platform/SKILL.md`. `skills/objectstack-ai/SKILL.md`'s compiled `supportKb` example changes two keys (`id` to `name`, `contentFields` to `content`) because the old spelling is now refused at parse. Teaching the type (prose, tables, evals) rides #37310. - **One ceiling, raised by the row's measured delta and by no more** (`scripts/check-skills-token-ratchet.mjs`): `skills/objectstack-platform/SKILL.md` was at zero headroom (24603 priced bytes, 6151 tokens, after #37442's row); the `knowledgeSources` row adds 20 bytes, so the priced text is 24623 bytes, 6156 tokens, and the ceiling moves 6151 to 6156, pinned at the measurement. Nothing else in the file is cut and nothing rides along. `skills/objectstack-ai/SKILL.md` stays at 6799 tokens under its ceiling of 6801. - **The two rulings the raise path names**, quoted: - Ruling A on #32584 (record 6819475461): "a product PR that adds an authorable `defineStack()` top-level key, or a live member of a schema symbol bound to a registered exhaustive skills section, carries the matching skills enumeration row in the same PR. Only that row; prose, examples and evals still go to the skills sub-card." - #32673 letter A (record 6840575378): "a PR that adds a metadata key and, under ruling A on #32584, carries the matching enumeration row in a published skill may raise that skill file's token cap by the row's measured delta, and by no more. The PR body cites ruling A and this ruling. Nothing else in the file is cut to make room, and no wider raise rides along." ## Tests - `packages/spec/src/ai/knowledge-source.test.ts`: the strict schema, `'*'` refused, an empty-string member refused (and `minLength: 1` in the JSON Schema), every retired key answered with its prescription. - `packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts` (new): the slot rules above, both orders of arrival at each door, face resolution and the `409` with its candidates. - `.../knowledge-source-loader.test.ts` (new): boot read, add, change (each of the two rebuild arms), remove with `dropSource`, an adapter without `dropSource`, the reap guard following the sources. - `.../knowledge-source-admission.test.ts`: each refusal of guard two and its fail-closed `503`; the fields `where` reads (keys, `$and` / `$or` / `$not`, `{ $field }` comparands) judged at save and at search. - The adapter contract suite with `dropSource: true` in `knowledge-memory` and `knowledge-turso`; `knowledge-pgvector` declares it in `contract.live-postgres.test.ts` (see Remaining). - `packages/rest/src/meta-type-write-capability.test.ts`: every write shape of a `knowledge_source` for a caller with `manage_metadata` alone, with `manage_platform_settings`, and with a record grant: `403 PERMISSION_DENIED`, store unchanged, no protocol call; a holder of both saves, publishes, rolls back and resets; the capability without `manage_metadata` is refused by the door's own admission. - `packages/rest/src/meta-write-door-capability-enumeration.test.ts`, `packages/runtime/src/domains/meta-save-capability-gate.test.ts`, `packages/runtime/src/domains/mcp-authoring.test.ts`: guard two at REST, the dispatcher and the MCP save door (the human is judged); on a real kernel, a knowledge service whose factory throws answers `503` at the dispatcher and at MCP, and one never registered is not asked. - `packages/runtime/src/domains/meta-type-write-capability-parity.test.ts`: REST and the dispatcher answer the same for the new row. - `packages/runtime/src/domains/packages-knowledge-source-gate.test.ts` (new): each of the twelve package doors refuses a `manage_metadata`-only caller when the package holds a source (item or draft) and the writer never runs; a holder goes on with no listing read; a package with none answers as before; a listing that throws refuses `503`; the engine's own call is not asked; the commit revert and the rollback read the timeline; the duplicate door's admission of each copied source; a host with no metadata store holds none; the install door and the ensure-customization door are not asked. - `packages/runtime/src/domains/packages-ensure-customization.test.ts`: a base that holds a knowledge source (a registered item and a stored row) gets a pair that holds none, and the door writes one manifest and no row. - `packages/objectql/src/knowledge-source-unserved.test.ts` (new): the boot notice. - `packages/metadata-core/src/knowledge-source-save-admission.test.ts` (new): the admission seam. ## Acceptance notes - **Governed (Tier H) and over 3000 changed lines**: draft until the maintainer's approval. The diff touches `skills/**` and declares a narrowing. - **Rulings this PR implements**: record 7192063608 on #37304 (forks 6 and 4d, both A); earlier on the same card Q1 = B (the type sits in ADR-0150's bucket 3) and Q2 = B (`manage_knowledge_sources` beside `manage_metadata`, platform administrators only); and ruling A of 2026-11-27 (record 7207325373): every write door of an existing package asks the capability when the package holds a knowledge source, and install stays unasked. The ADR-0150 rows ride #37545. One ADR line is edited here, with the zone's approval (claim comment 7203310811 on #37304, amended by 7204020473): ADR-0084's type table gains the `knowledge_source` row its item 6 prescribes for a type registered after the ruling (AI, `ai`, 5, 高级), spelled as the `ai_context` row is. Nothing else under `docs/adr/**` changes. - **The loader's signal** is `protocol.onMetadataMutation` (a save, a publish, a delete, a revert) plus the `metadata:reloaded` hook (a package published, installed or removed, a dev reload), not `metadataService.subscribe`. After either it reads the published set again and reconciles, so a missed event is repaired by the next one. - **Guard two is not asked where no knowledge service is mounted** (there is nothing to ask, and the item is inert there), nor for a system write. - **Two package doors are not asked the new capability (limits).** The install door (`POST /packages`): a package's source arrives by that door's own admission, as the ruling leaves it. The ensure-customization door (`POST /packages/:id/ensure-customization`): it writes nothing of the base and creates an empty pair, so it creates, changes and removes no knowledge source; the seat confirmed this reading on the condition that the pair holds no source, which `packages-ensure-customization.test.ts` pins. - **The package gate reads before it answers.** For a caller without the capability the twelve doors read the package's drafts and items (and its commits, for the two timeline verbs) before the door's own request checks. A host with no metadata store at all (the table was never created, or the engine holds no `sys_metadata` object) reads as holding none, by the same rule the protocol's overlay reads use; any other failed read refuses `503`. - **The read-side author exemption** stays keyed on `manage_metadata`. - **A bare name two sources answer to** is refused `409` at the call that names it (`resolveSourceRef`), listing the candidates; both sources register. Where the host cannot place a package's namespace, the package's face is its bare name, and that name answers `409` for both sources until the package is placed. - **The four narrowings the ADR-0150 addendum asks this card to declare, each counted on this tree**: the install refusal inside a namespace (two packages of one namespace holding a source of one name): 0. The name grammar (a source whose name the grammar refuses): 0. The `409` for a bare name two packages hold: 0. The package-less row under a name a package holds: 0. The tree holds one knowledge source, `showcase_task_notes` (`examples/app-showcase/src/ai/task-notes.knowledge-source.ts`), and no first-party code registers one through the plugin door. - **`KnowledgeIndexStatusEntry.kind` is removed** with the source kinds; `packageId` is added. - **One ADR-0087 marker.** The gate allows exactly one marker per breaking changeset, so the changeset carries `registered …` and names `indexDocument` / `deleteDocument` in prose: they are runtime-interface members with no metadata form, and the compiler reports each call (`TS2339`). - **The boot notice adds one boot read** of `knowledge_source` rows on a kernel that does not hydrate from its database; it registers nothing (`plugin.integration.test.ts` pins the permitted reads and now names this one). - **pgvector `dropSource` and a concurrent build in another process**: the drop retires the active and the building generation in one transaction but does not hold the builder lock across it, so a build already running in another process could still write its generation afterwards. Not changed here; it is a candidate follow-up. - **#37479 (unregistered adapter) is not folded in.** The loader runs after publish, so it is not a refusal point for publish; #37442 adds the coded refusal for an unmounted adapter. - **The showcase mounts the two plugins by hand** rather than declaring `requires: ['knowledge']` (#37442): the token mounts a libSQL or pgvector store, which needs a configured embedder, and the demo runs on the in-memory store with none. A host that mounts the service itself keeps its own, as #37442 specifies. - **Merged with `main` three times** (no rebase). The first merge (at `45ed022b`) followed #37442, #37570 and #37578: four textual conflicts (the migration registry template, the CLI knowledge test fixture, the pgvector adapter's search refusal, the knowledge service's reindex chain and unmounted-adapter refusal). Code and fixtures those PRs wrote against the 18 source shape follow the 19 shape here: `source.id` is `source.name`, `contentFields` is `content`, `reportUnmountedAdapters` names a source by its face, and the unmounted-adapter index test calls `reindexSource` now that `indexDocument` is gone. The second merge (at `c2bfa3ef7`) was forced by a conflict: `main` had gained its own protocol 19 conversion (`permission-view-all-fields-beside-record-bypass`), so the conversion registry, the migration registry template and the retired-key pin now carry both sets, sorted as the registry sorts them; `packages/spec/authorable-surface/ai.json` was merged three ways by hand so that this PR's removals and `main`'s new `ai/Skill:context` both stand; every generated spec surface was regenerated afterwards. The third merge (at `8b9b9d235`) was forced by #37723, which moved the ADR-0150 D3 rule into `packages/metadata-core/src/package-scoped-resolution.ts`: `core`'s file is taken from `main` (a re-export) and the `knowledge_source` row with its comment sits in `metadata-core`'s `PACKAGE_SCOPED_TYPES`; `default-changes.ts` keeps both protocol 19 entries (`main`'s `ai/AIModelConfig:provider` and this PR's `ai/KnowledgeSource:refresh`); the Studio menu placement pin takes `main`'s move of `position` and keeps this PR's row. The merge is its own commit and `packages/spec/authorable-defaults/ai.json` was regenerated in the next one (`737f44341`). - **The declared default of `ai/KnowledgeSource:refresh`** sits under major 19 in `default-changes.ts` (no parsed value changes: the published JSON Schema now states the `{}` the parser always applied). - **Enumeration pins found by CI, not by the first local pass.** The first head was verified on the packages the change edits. CI then failed on tests in packages it does not edit, each a list that counts metadata types or the platform administrator's capabilities: the owner-stamp boot fixture and the unbundled-type list (`packages/metadata`), the tier list (`packages/metadata-protocol`), the type-label counts (`packages/platform-objects`), four golden grant lists (`packages/plugins/plugin-security`), and the generated `zh-Hant` locale. Each gained the one entry; no product code changed for them. The suites of those packages and the workspace type check now run locally as well (see Verification). - **Review round 1.** The contract review on `45ed21271` (comment 7206413701) read PASS with findings, and the seat ordered a rework (7206423476). This head answers it: authoring guards cover more doors and more of what a source reads (the package doors, the duplicate door, the fields `where` reads, the service lookup at the dispatcher and at MCP), the `content` member refuses the empty string, the changeset lists the twelve removed exports, and this body is corrected on the face collision and states the narrowing counts. The findings' detail is with the seat. Two nits are carried by cards the zone files under #37304 (ADR-0084 prose; tombstone wording for code-door registrants). - **Existing tests edited outside the card's first surface** (claim amended by the zone, comment 7207505784 on #37304), each because a package door now reads the package for a caller without the capability: - `packages-publish-drafts-request-conformance.test.ts`: the real-protocol case's caller also holds `manage_knowledge_sources` (its engine is one nothing may touch; the case pins the protocol's own order). Assertions unchanged. - `packages-publish-drafts-probe-caller-context.test.ts`: the protocol double gains a `getMetaItemsPerPackage` stub beside its `getMetaItems` stub. Assertions unchanged. - `package-state-host-store.test.ts` (a kernel with no driver) and `domains/error-passthrough.test.ts` (a protocol double that throws from every member): the caller also holds `manage_knowledge_sources`. Assertions unchanged. - `packages-ensure-customization.test.ts`, "duplicate: 400 before a row is read": **the measure changes.** The door now reads the source package's knowledge sources to admit them before the copy runs, so the case counts the reads made inside `protocol.duplicatePackage` (still 0) instead of every engine read; it also asserts the copy was entered once. - **Open PRs that will conflict with this one** (overlap-check on this head against 12 open PR heads; `main` itself merges cleanly): #37422 (the generated references and `scripts/check-skills-token-ratchet.mjs`: whichever lands second re-measures the row), #37366 (`packages/spec/export-origins/ai.json`). Whichever of each pair lands second merges `main`. ## Verification First files to read, by risk: 1. `packages/services/service-knowledge/src/knowledge-source-registry.ts`: the slot and face rules. 2. `packages/services/service-knowledge/src/knowledge-source-loader.ts`: what each metadata event does to an index. 3. `packages/rest/src/meta-item-read-gate.ts` (`META_TYPE_WRITE_CAPABILITIES`) and `packages/metadata-core/src/knowledge-source-save-admission.ts`: the two guards. 4. `packages/runtime/src/domains/packages.ts` (`refuseKnowledgeSourcePackageWrite`, `refuseDuplicatedKnowledgeSources`): the guards at the package doors. Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/knowledge-source-registry.test.ts src/__tests__/knowledge-source-loader.test.ts`. Head `cf128e59f` (review round 1). Verified so far on this head, locally, every heavy run under `scripts/pm/os-verify-lock.sh`: build exit 0; `@objectstack/runtime` full suite exit 0 (657 files, 13676 passed, 25 skipped); `@objectstack/metadata-core` and `@objectstack/core` exit 0; `tsc --noEmit` on `packages/runtime` exit 0. Running now on the same head, and written here when they end: the other package suites, the workspace type check, the derived gates, the full dogfood battery and the ablations. CI on this head is in progress. The previous head's readings (`45ed21271`: 62 check runs green, 185 gates, the dogfood battery, six ablations) are in the os-dev report, comment 7206197293 on #37304. <details><summary>Skills readings (the diff touches <code>skills/**</code>)</summary> | | Lines before | Lines after | Tokens before | Tokens after | |---|---|---|---|---| | `skills/objectstack-platform/SKILL.md` | 421 | 421 | 6151 | 6156 (ceiling 6156) | | `skills/objectstack-ai/SKILL.md` | 486 | 486 | 6799 | 6799 (ceiling 6801) | | All `SKILL.md` files together | 4961 | 4961 | | | | Ratcheted (authored) bundle | | | 199660 | 199665 (ceiling 204478) | `skills/objectstack-ai/references/_index.md` is generator-owned (53 lines to 52: the embedding module's row leaves, the knowledge source's row is reworded) and is measured, not ratcheted. "Before" is `main` at the third merge (`8b9b9d235`), read with the same script; the bundle's before figure is this tree's reading less the row's 5 tokens. </details> ## Remaining - The same reviewer's read of the round 1 delta (`45ed21271..cf128e5`), then the seat's hand-off. - `knowledge-pgvector`'s `dropSource` contract cases have not run anywhere yet: there is no pgvector in the build container, and the job with a PostgreSQL service does not run on `pull_request`. Their first run is the merge queue. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZe3KTAXogcUJuvYEx --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f7f9345 commit d58bf7a

221 files changed

Lines changed: 6985 additions & 2037 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-knowledge': minor
4+
'@objectstack/knowledge-memory': minor
5+
'@objectstack/knowledge-pgvector': minor
6+
'@objectstack/knowledge-turso': minor
7+
'@objectstack/metadata-core': minor
8+
'@objectstack/rest': minor
9+
'@objectstack/runtime': minor
10+
'@objectstack/objectql': minor
11+
'@objectstack/core': patch
12+
'@objectstack/metadata': patch
13+
'@objectstack/cli': patch
14+
'@objectstack/platform-objects': patch
15+
'@object-ui/app-shell': minor
16+
'@object-ui/i18n': minor
17+
'@object-ui/fields': patch
18+
---
19+
20+
feat(spec)!: a knowledge source is a governed metadata type, `knowledge_source`, loaded by the knowledge service
21+
22+
Clause-②: yes (narrowing)
23+
Metadata-protocol: narrowed
24+
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.
25+
26+
<!-- adr-0087: registered knowledge-source-id-to-name, knowledge-source-content-fields-to-content, knowledge-source-inert-keys-removed, knowledge-source-content-lists-fields, knowledge-source-file-http-kinds-retired, knowledge-source-inert-keys-retired, knowledge-source-registration-governed -->
27+
28+
ADR-0161 K4, K5, K6 and K8 item 4 (#37304).
29+
30+
**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.
31+
32+
| Wrote (18) | Write instead (19) |
33+
|:--|:--|
34+
| `id: 'support_kb'` | `name: 'support_kb'` (the value is unchanged, so the index is found again and nothing is rebuilt) |
35+
| `source.contentFields: ['title', 'body']` | `source.content: ['title', 'body']` |
36+
| `contentFields: ['*']` | `content` with every field named (a hand edit: only the author knows which fields may leave the row store) |
37+
| `embedding`, `vectorStore`, `adapterConfig`, `refresh.cron` | delete the key: nothing read it |
38+
| `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 |
39+
| `knowledge.indexDocument(…)`, `knowledge.deleteDocument(…)` | no call: the service builds every document from the records a source selects; `reindexSource` rebuilds a source |
40+
| `KnowledgeServicePlugin({ sources: [{ id, … }] })`, `registerSource({ id, … })` | the same call with the 19 shape, or the source shipped as metadata in the stack's `knowledgeSources` |
41+
42+
What changes:
43+
44+
- **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`.
45+
- **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.
46+
- **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.
47+
- **`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.
48+
- **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.
49+
- **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.
50+
- **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.
51+
- **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`).
52+
- **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.
53+
- **CLI.** `os knowledge status` prints the package that holds a source and no longer prints a source kind.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 65 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Which store is mounted depends on the platform database:
3030
| PostgreSQL | `@objectstack/knowledge-pgvector` | `pgvector` | the platform database, schema `os_knowledge` ([below](#self-hosted-vector-store-postgresql--pgvector)) |
3131
| anything else (SQLite under `os dev`, libSQL, MySQL, MongoDB) | `@objectstack/knowledge-turso` | `turso` | `knowledge.db` in the directory of the default database and never its file: `.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set ([below](#local-vector-store-a-libsql-file)) |
3232

33-
- **Sources are still written in code**: register them on the `knowledge` service from your own plugin, and name the adapter of the store your database gets (`adapter: 'turso'` or `adapter: 'pgvector'`).
33+
- **Sources are metadata**: list them under `knowledgeSources` ([below](#writing-a-source)), and name the adapter of the store your database gets (`adapter: 'turso'` or `adapter: 'pgvector'`).
3434
- **A source naming a store that is not mounted** does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`.
3535
- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)).
3636
- **Another libSQL store** for the `turso` case: save its URL as `turso_url` (and `turso_auth_token` for a managed `libsql://` database) in Settings → Knowledge, then restart. A `file:` URL saved there must name a file inside that same data directory, and a URL carrying a NUL byte or another control character, written out or percent-encoded (`%00`), is refused, as is a token carrying one (a pasted line break counts); either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on.
@@ -41,34 +41,75 @@ Which store is mounted depends on the platform database:
4141
- **Without the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you.
4242
- **Mounting it yourself** still works: an app whose `plugins` already hold `KnowledgeServicePlugin` keeps its own, and the runtime adds neither a second service nor a store.
4343

44+
## Writing a source
45+
46+
A knowledge source is a metadata item: a `*.knowledge-source.ts` file in your
47+
app, listed under `knowledgeSources`. It says which object's records to
48+
index, which fields become searchable text, and which adapter holds the index.
49+
50+
```ts
51+
// src/ai/task-notes.knowledge-source.ts
52+
import type { KnowledgeSource } from '@objectstack/spec/ai';
53+
54+
export const TaskNotes: KnowledgeSource = {
55+
name: 'task_notes',
56+
label: 'Task notes',
57+
adapter: 'turso', // 'pgvector' when the platform database is PostgreSQL
58+
source: { kind: 'object', object: 'task', content: ['title', 'notes'] },
59+
};
60+
```
61+
62+
```ts
63+
// objectstack.config.ts
64+
import { defineStack } from '@objectstack/spec';
65+
import { TaskNotes } from './src/ai/task-notes.knowledge-source.js';
66+
67+
export default defineStack({
68+
requires: ['knowledge'],
69+
knowledgeSources: [TaskNotes],
70+
// …
71+
});
72+
```
73+
74+
The knowledge service loads the source when it starts, runs its first build,
75+
and keeps the index in step with the records. There is no registration call
76+
to write.
77+
78+
- **`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.
79+
- **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.
80+
- **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.
81+
- **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`.
82+
- **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.
83+
84+
<Callout type="warn">
85+
**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.
86+
</Callout>
87+
4488
## Wiring by hand
4589

90+
An app that mounts the service and a store itself, instead of declaring
91+
`requires: ['knowledge']`, keeps its own: the runtime adds neither a second
92+
service nor a store. This is also how the in-memory store is mounted for a demo
93+
or a test.
94+
4695
```ts
47-
import { ObjectKernel } from '@objectstack/core';
96+
// objectstack.config.ts
97+
import { defineStack } from '@objectstack/spec';
4898
import { KnowledgeServicePlugin } from '@objectstack/service-knowledge';
4999
import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory';
50100
// or, for prod (PostgreSQL + pgvector; a libSQL file is `@objectstack/knowledge-turso`):
51101
// import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector';
102+
import { TaskNotes } from './src/ai/task-notes.knowledge-source.js';
52103

53-
const kernel = new ObjectKernel();
54-
kernel.use(new KnowledgeServicePlugin({
55-
sources: [
56-
{
57-
id: 'task_notes',
58-
label: 'Task notes',
59-
adapter: 'memory',
60-
source: { kind: 'object', object: 'task', contentFields: ['title', 'notes'] },
61-
},
62-
{
63-
id: 'product_docs',
64-
label: 'Product docs',
65-
adapter: 'memory', // 'pgvector' once KnowledgePgvectorPlugin is registered below
66-
source: { kind: 'object', object: 'product_doc', contentFields: ['title', 'body'] },
67-
},
104+
export default defineStack({
105+
plugins: [
106+
new KnowledgeServicePlugin(),
107+
new KnowledgeMemoryPlugin(),
108+
// new KnowledgePgvectorPlugin(),
68109
],
69-
}));
70-
kernel.use(new KnowledgeMemoryPlugin());
71-
// kernel.use(new KnowledgePgvectorPlugin());
110+
knowledgeSources: [TaskNotes], // with `adapter: 'memory'`
111+
// …
112+
});
72113
```
73114

74115
## Retrieving knowledge
@@ -77,7 +118,7 @@ Retrieval is a plain service call — no AI runtime required. Resolve the `knowl
77118
service and call `search`. Hits are re-checked against the caller's
78119
`ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come
79120
back. Because the re-check runs after ranking, for a caller other than the
80-
system identity the service asks each object source for more hits than `topK`,
121+
system identity the service asks each source for more hits than `topK`,
81122
and asks once more when too few records survive, so a caller who may read few of
82123
the matching records still gets up to `topK` hits
83124
([the protocol](/docs/protocol/knowledge) gives the factors and the cap). A
@@ -128,7 +169,7 @@ installed ([Connect an MCP Client](/docs/ai/connect-mcp)).
128169

129170
## Searching inside chosen records
130171

131-
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`.
172+
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`.
132173

133174
```ts
134175
// Only the clauses of one policy: the clause source lists its `policy` lookup in metadataFields.
@@ -191,13 +232,13 @@ const vectors = await embedder.embed(chunks.map((c) => c.content));
191232

192233
## Splitting documents into passages
193234

194-
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`:
235+
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`:
195236

196237
```ts
197238
source: {
198239
kind: 'object',
199240
object: 'policy',
200-
contentFields: ['title', 'body'],
241+
content: ['title', 'body'],
201242
split: { strategy: 'markdown', maxChars: 600 },
202243
}
203244
```

‎content/docs/getting-started/quick-reference.mdx‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,7 @@ AI/ML capabilities - agents, skills, tools, MCP exposure, RAG, and cost tracking
117117
| **[MCP](/docs/references/ai/mcp)** | `mcp.zod.ts` | MCPServerRef, MCPToolBinding | MCP server exposure and tool bindings |
118118
| **[Model Registry](/docs/references/ai/model-registry)** | `model-registry.zod.ts` | ModelRegistry, ModelProvider | LLM model management |
119119
| **[Conversation](/docs/references/ai/conversation)** | `conversation.zod.ts` | ConversationSession | Conversation management |
120-
| **[Embedding](/docs/references/ai/embedding)** | `embedding.zod.ts` | EmbeddingModel, VectorStore | Embedding models and vector stores |
121-
| **[Knowledge Source](/docs/references/ai/knowledge-source)** | `knowledge-source.zod.ts` | KnowledgeSource, KnowledgeRefreshPolicy | RAG ingestion sources |
120+
| **[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 |
122121
| **[Knowledge Document](/docs/references/ai/knowledge-document)** | `knowledge-document.zod.ts` | KnowledgeDocument, KnowledgeChunk | RAG documents and chunks |
123122
| **[Usage](/docs/references/ai/usage)** | `usage.zod.ts` | AIUsageRecord, TokenUsage | AI usage and cost tracking |
124123
| **[Solution Blueprint](/docs/references/ai/solution-blueprint)** | `solution-blueprint.zod.ts` | BlueprintObject, BlueprintApp | Blueprint format for AI app generation |

0 commit comments

Comments
 (0)