Skip to content

Commit d59478f

Browse files
feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service (#38013)
repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP Fixes #37983 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: skills/objectstack-ai/SKILL.md § Knowledge Sources (RAG) — the run-time clause now says that where an app ships no source, a run-time save is refused (`503 SERVICE_UNAVAILABLE`, nothing written) until the stack declares `requires: ['knowledge']` and the server restarts (it said such items are never indexed); the matching eval case in `skills/objectstack-ai/evals/skills-tools-knowledge.json` expects the same; the token-ratchet row moves 6893 → 6906 under ruling record 6513306068, letter B ## 维护者速读 - 作者在没装知识服务的部署上,通过工作台、元数据接口或智能体工具保存知识源时,会当场失败并看到原因和修法(先在应用配置里声明需要知识服务并重启,再保存);以前这种保存显示成功却永远不生效。 - 属于知识库检索这条线,执行您选的方案 D:让作者在保存那一刻就知道,而不是只在看不到的服务器日志里。 - 只影响在这类部署上保存知识源的作者;在这类部署上复制一个含知识源的整个应用包也会被拒、什么都不复制(这是裁决点名的三处之外的第四处,请批准前读下方的待定问题一节);装包、种子数据、迁移照常通过;出问题可整单撤回。 - 要你做的:批准这次收窄(按审批流程)。 ## What changes Ruling D (maintainer, recorded on #37983, comment 7220511579) is implemented in the one predicate every save door asks, `authoredKnowledgeSourceRefusal` (`packages/metadata-core/src/knowledge-source-save-admission.ts`): - **No knowledge service registered + a non-system writer ⇒ refused.** `resolveKnowledgeService()` answering `undefined` (or `null`) used to admit the save; it now answers `503 SERVICE_UNAVAILABLE` with a message that names the item, the reason and the remedy in order: add `requires: ['knowledge']` to the stack (or, on a host that composes its own kernel, `KnowledgeServicePlugin` and a knowledge store), restart, then save the source again. Nothing is written. - **Held as ruled:** the engine's own write (`isSystem`: package install, seed, migration) is never refused (the `isSystem` check still runs before the service is resolved); a REGISTERED knowledge service with no `admitAuthoredSource` (not the platform's, for example host-mounted) keeps today's accept. The module doc (`:33-34` on main) now says both, and gains a section on the no-service case. - **Doors.** No door code changed shape: `PUT /meta/:type/:name` in `packages/rest` passes `refused.code` through for a non-403 (`SERVICE_UNAVAILABLE`), the runtime dispatcher `PUT` derives `SERVICE_UNAVAILABLE` from `503`, and the MCP `save_metadata_draft` passes `refused.code` through for a non-403 (on `main` since #37306). Only their comments are updated. Each door is pinned. - **Why `503 SERVICE_UNAVAILABLE`** (ADR-0112 status table, `STATUS_TO_STANDARD_CODE` in `packages/spec/src/api/errors.zod.ts`): the save needs a service this deployment does not run. It is the code this module already answers for a knowledge service that cannot be reached, and the code the knowledge service answers at index and search for a source whose store is not mounted (the same kind of composition fact). It is also the one code all three doors already carry without a door change. Rejected: `400 VALIDATION_ERROR` (the item is valid; a validation code sends the author to fix the item), `403` (not a permission), `501 NOT_IMPLEMENTED` (the meta door's answer for a protocol with no `saveMetaItem`), `409 RESOURCE_CONFLICT` and `428 PRECONDITION_REQUIRED` (no conflicting resource, no missing request precondition), and a new ledger code (a contract change the ruling did not make). The message carries the remedy and does not say "try again". - **ADR-0087:** `Metadata-protocol: narrowed` owes a registered entry: `packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts` (notice only, no D2 conversion: the fix is the deployment's composition, never the item). The changeset carries `registered` with that id. ## Boot line and docs (ruling items 2 and 4), landed after #37306 Held off this branch until #37306 merged (PR #38026, dbe0716); `main` is now merged in (1ca3a31) and the held commit is re-applied as 33acf12. - **Boot line** (`packages/objectql/src/knowledge-source-unserved.ts`): the line for `knowledge_source` items held with no knowledge service now names the same remedy as the save refusal, from the item-4 patch's `UNSERVED_REMEDY`: declare `requires: ['knowledge']` and restart (or, on a host that composes its own kernel, `KnowledgeServicePlugin` and a knowledge store). Before, it said "add `KnowledgeServicePlugin` and a knowledge adapter to the composition". Only the boot-line half of that patch was taken: #37306 did not touch this file, so `main` still carried the old text. - **What #37306 changed, and what that changes here.** A source the app ships in `knowledgeSources` now mounts the service by itself, and `adapter` is optional. So a source saved at run time (Studio, the metadata API, MCP) is never one that mounts the service, and the remedy the maintainer ruled (`requires: ['knowledge']`, restart, then save) is still the one that fixes such a save. The refusal sentence is unchanged. The docs now also say that a source saved at run time does not mount the service. The boot-line module doc says that the items it names are ones the stack does not ship. Main's `knowledge-rag.mdx` already said "the token is for an app that ships none and authors its sources at run time", which matches. - **Docs.** `content/docs/ai/knowledge-rag.mdx`: a bullet beside "Without a source or the token", plus a clause on the run-time-authoring bullet. `content/docs/protocol/knowledge.mdx`: the boot-line paragraph names the remedy (it named the plugin and an adapter), and a paragraph under "Who may author one" covers the refusal, the duplicate and the holds. Rewritten against main's merged text, not patched blindly: `git am --3way` conflicted on `knowledge-rag.mdx`. - **Changeset:** gains the `@objectstack/objectql` and `@objectstack/skills` patch lines and their bullets. - The MCP draft door on `main` now passes `refused.code` through for a non-403 (#37306), so this refusal still arrives there as `SERVICE_UNAVAILABLE`. ## Open question The package **duplicate** door (`POST /packages/:id/duplicate`) asks the same predicate for each knowledge source it copies, so on a deployment with no knowledge service it now refuses a duplicate of a package that holds one, `503`, naming the remedy (pinned in `packages-knowledge-source-gate.test.ts`). The ruling names three doors; this is the fourth door that saves a source as the caller. Keeping it refused is the predicate's own reading and the ruling's principle (the copy would be kept and never served); carving it out needs a new input on an exported function. Recommendation: keep it. ## Tests - `packages/metadata-core/src/knowledge-source-save-admission.test.ts`: refusal with code, status, the reason sentence and the ordered remedy, for both URL spellings and for `undefined`/`null`; an unnamed item; `isSystem` not refused and the service never resolved; a registered service without the member still admits. - REST `PUT` (`packages/rest/src/meta-write-door-capability-enumeration.test.ts`): refused on the kernel's branded "never registered" miss and on a server with no kernel provider; system write saved; host-mounted service saved. - Runtime dispatcher `PUT` (`packages/runtime/src/domains/meta-save-capability-gate.test.ts`): refused on a real `ObjectKernel` with nothing registered; system write saved; host-mounted service saved. - MCP `save_metadata_draft` (`packages/runtime/src/domains/mcp-authoring.test.ts`): refused, nothing written, another type still saves; host-mounted service saved. - Package duplicate (`packages/runtime/src/domains/packages-knowledge-source-gate.test.ts`): refused, nothing copied; a package with no source and the engine's own call copy as before. - Boot line (`packages/objectql/src/knowledge-source-unserved.test.ts`): names `Declare requires: ['knowledge'] in the stack and restart`. Head is now `5bc3ee1a00`. Since `33acf12ec4` it adds only: the test-harness fix `6e4a904ea1` (the MCP `knowledge_source` contract case from #38053 mounts an admitting knowledge service; comment 7232197442), the skills text, eval expectation, ratchet row and changeset line above, the module-doc wording at index and search, and two clean merges of `main` (the second carries #38091). No runtime or rest code moved after `33acf12ec4`, so the dogfood battery below stands. On `5bc3ee1a00`: the skills token ratchet exits 0 (6906, headroom 0; self-test 111 cases pass), `check:skill-docs` and `check:skill-refs` exit 0, and the changeset, ADR-0087, NUL-byte and issue-citation gates exit 0. After the harness fix, runtime reads 12315 passed, 0 failed. Readings at head `33acf12ec4` (main merged in; shared container; every build and test through `scripts/pm/os-verify-lock.sh`, verdict `command-exit 0` each round): <details><summary>Tests and typecheck at 33acf12</summary> - Full build (`turbo run build`, all but docs) exit 0, `packages/runtime/.objectstack` cleared, `@objectstack/spec check:generated` exit 0. - `@objectstack/metadata-core` `pnpm test`: Tests 1113 passed; `typecheck` exit 0. - `@objectstack/objectql` `knowledge-source-unserved.test.ts`: Tests 7 passed; `typecheck` exit 0. - `@objectstack/rest`, 4 files (door enumeration, type-write capability, both org-scope suites): Tests 161 passed; `typecheck` exit 0. - `@objectstack/runtime`, 10 files (dispatcher save gate, MCP authoring, package knowledge gate, error passthrough, capability parity, org scope, ensure-customization, publish-drafts x2, package state store): Tests 304 passed; `typecheck` exit 0. - On the first head, 5 suites that save a `knowledge_source` as a capable author with no knowledge service went red: that is the ruled refusal. Their harnesses now mount a knowledge service that admits every source. Two door-level `isSystem` cases were dropped because inbound HTTP never carries `isSystem` (`metaTypeWriteRefusal` answers 401 first); that hold is tested at the predicate instead. - Narrowed locally: the full rest and runtime suites, `test:repo`, and the derived families not listed under Gates run in CI. </details> <details><summary>Ablations (one per tested behaviour)</summary> - **The save refusal** (at dd50936): `scripts/ablation-replace.mjs` replaced the one new line (anchor 1 -> 0, marker 0 -> 1). `@objectstack/metadata-core` was rebuilt, and `ablation-dist-preflight` found the marker in `dist/index.js` and `dist/index.cjs`. Exactly these went red: the predicate test (1 of 9), REST `PUT` (1 of 81), and dispatcher `PUT`, MCP draft save and package duplicate (3 of 162). Restored with `git checkout HEAD` (blob back to cd26e8f, `git diff HEAD` empty), rebuilt, and preflight `--absent` was clean. - **The boot line** (at 33acf12): the remedy was put back to main's text (anchor 1 -> 0, marker 0 -> 1; the test imports source, so no build was needed). Red: `names the item, the missing service and both remedies` (1 of 7). Restored with `git checkout HEAD` (blob aa50e2e, `git diff HEAD` empty). - The docs pages are not ablated. </details> <details><summary>Live server (REST door, at dd50936)</summary> After a full build I ran `pnpm dev:crm -- --fresh -p 38937`; the CRM stack declares `requires: ['ui', 'automation']` and no knowledge. Signed in as the seeded admin, `PUT /api/v1/meta/knowledge_source/faq` answered `503`, `error.code` `SERVICE_UNAVAILABLE`, with the remedy sentence. A `GET` of the item then answered `404`, so nothing was written. The server was stopped by its recorded pid. A positive control on a stack with `requires: ['knowledge']` was not run (NOT MEASURED); the unit tests cover the admitted path. </details> <details><summary>Gates at 33acf12</summary> Local, exit 0 each: `check-adr-0087-registration` (1 declared-breaking changeset, with its disposition), `check-changeset-no-major`, `check-empty-changeset`, spec `check:upgrade-guide`, `check:spec-changes`, `check:api-surface` (unchanged), `check:nul-bytes`, `check:doc-authoring`, `check-affected-docs`, `check:issue-citations`, `check:dispatcher-error-vocabulary`, `check:startup-registry-verdict`, `check:durability-log-level`. At dd50936 these were also exit 0: `check:authorable-surface`, `check:route-envelope`, `check:error-status-conformance`, `check-closing-keyword-parity`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:adr-anchors`. `overlap-check` before the push: clean against `main` and against #38043, #37982 and #37963. </details> <details><summary>Dogfood battery at 33acf12</summary> The full battery, run as CI runs it (no `OS_TEST_SHARD`, no path), under `scripts/pm/os-verify-lock.sh`. The build was `turbo run build --filter='@objectstack/dogfood^...'` and exited 0. The test was `pnpm --filter @objectstack/dogfood test`. - Verdict: `VERDICT command-exit 0 · held the lock 1727s (28m47s)`, in shared-box seconds. - `Test Files 490 passed | 3 skipped (493)` - `Tests 4144 passed | 68 skipped (4212)` - Failures: none. Recorded in comment 7229739676. CI's `Dogfood Regression Gate` on the PR reads `OS_DOGFOOD_RESULT: skipped` (the shards run in the merge queue), so it is not evidence for this head. </details> ## Acceptance notes - The note on this PR's first head about #37306's `400 VALIDATION_ERROR` arriving at the MCP draft door as `SERVICE_UNAVAILABLE` is obsolete: #37306 merged with the MCP door passing `refused.code` through. - Docs Drift Check (comment 7222797378) is receipted here. `content/docs/ai/knowledge-rag.mdx` and `content/docs/protocol/knowledge.mdx` are updated on this branch. `content/docs/permissions/system-context.mdx` row 46 is re-read and still true: the refusal is not on the `isSystem` path. The other pages match on the `SERVICE_UNAVAILABLE` literal only and say nothing about knowledge sources. The release-owned pages are not edited. - Contract review 7228262724 (PASS) and L1 7228292666 (REWORK: dogfood battery only) are receipted here. The battery is recorded in comment 7229739676: green, and the head is unchanged. The review's nits N1 to N5 are left for a follow-up card; none of them is changed on this head. ## Verification Read first (by risk): `packages/metadata-core/src/knowledge-source-save-admission.ts` (the `service === undefined || null` branch, before the member check), `packages/runtime/src/domains/packages-knowledge-source-gate.test.ts` (the fourth door), `content/docs/protocol/knowledge.mdx` (the two paragraphs rewritten against #37306's text). Two-minute check: `pnpm --filter @objectstack/metadata-core exec vitest run src/knowledge-source-save-admission.test.ts` — expect the "no knowledge service registered" cases green; flip line `if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item);` out and they go red. Body refreshed 2026-11-28T03:15Z at head `5bc3ee1a00`; the readings in the three blocks above were taken at `33acf12ec4`. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 581ae76 commit d59478f

24 files changed

Lines changed: 375 additions & 56 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/metadata-core': minor
3+
'@objectstack/objectql': patch
4+
'@objectstack/spec': patch
5+
'@objectstack/skills': patch
6+
---
7+
8+
feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service
9+
10+
Clause-②: no (narrowing)
11+
Metadata-protocol: narrowed
12+
13+
<!-- adr-0087: registered knowledge-source-save-refused-without-knowledge-service -->
14+
15+
**BREAKING** for an author who saves a `knowledge_source` on a deployment that registers no knowledge service: the save was accepted before and is refused now. Nothing there loads, indexes or searches the source, and the service is mounted when the server starts, never while it runs, so the accepted item was kept and never served; only a boot log line said so, which a Studio, REST or MCP author does not see.
16+
17+
- **`@objectstack/metadata-core`.** `authoredKnowledgeSourceRefusal` answers a refusal, `503 SERVICE_UNAVAILABLE`, when no knowledge service is registered and the writer is not the engine. The message names the item, the reason and the fix: add `requires: ['knowledge']` to the stack (or, on a host that composes its own kernel, `KnowledgeServicePlugin` and a knowledge store), restart, then save the source. Every door that asks it refuses the save with that answer and writes nothing: `PUT /meta/:type/:name` on both transports, the MCP `save_metadata_draft` tool, and a package duplicate that would copy a source.
18+
- **`@objectstack/objectql`.** The boot line for `knowledge_source` items held with no knowledge service names the same fix: `requires: ['knowledge']` and a restart (or `KnowledgeServicePlugin` and a knowledge store on a host that composes its own kernel), where it named the plugin and an adapter.
19+
- **`@objectstack/spec`.** The upgrade guide carries the `knowledge-source-save-refused-without-knowledge-service` entry.
20+
- **`@objectstack/skills`.** The `objectstack-ai` skill's Knowledge Sources section says that on an app that ships no source, a run-time save is refused (`503 SERVICE_UNAVAILABLE`, nothing written) until the stack declares `requires: ['knowledge']` and the server restarts. It used to say such items are never indexed. The eval case for an app that authors its sources at run time expects the same.
21+
22+
Unchanged: the engine's own writes (a package install, a seed, a migration) are not refused; a registered knowledge service that is not the platform's (one with no `admitAuthoredSource`) answers for its own sources and the save goes on; stored items are not rewritten or refused at boot.
23+
24+
## FROM → TO
25+
26+
- A deployment whose stack does not declare `requires: ['knowledge']`, where authors save knowledge sources → add `requires: ['knowledge']` to the stack, restart, then save the source.

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Which store is mounted depends on the platform database:
4040
- **More than one replica** on MySQL, MongoDB or a remote libSQL database: each replica keeps its own local `knowledge.db` and indexes only the record writes that replica itself handles, so replicas answer from indexes that differ. Give them one store: save a shared `libsql://` URL in `turso_url`, or run on PostgreSQL, where the vectors live in the one database.
4141
- **An install without the libSQL client**: `@objectstack/knowledge-turso` is an optional dependency of the CLI, because its client is a native module. Where it could not be installed the server warns at boot that the store was not mounted, and sources naming `turso` answer `SERVICE_UNAVAILABLE`.
4242
- **Without a source or the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you.
43+
- **A source is saved only on a deployment that mounts the knowledge service.** On one without it, saving a source in Studio, the metadata API or MCP is refused `SERVICE_UNAVAILABLE` (503) and nothing is written: nothing there would load, index or search it, and the service is mounted when the server starts, never while it runs. A source saved at run time is not one the app ships, so it does not mount the service either. The refusal names the fix: add `requires: ['knowledge']`, restart, then save the source. A package install, a seed or a migration is not refused; the boot names each source it holds with no service to load it, and the same fix.
4344
- **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.
4445

4546
## Writing a source
@@ -77,7 +78,7 @@ and keeps the index in step with the records. There is no registration call
7778
to write.
7879

7980
- **`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.
80-
- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart where the knowledge service is mounted (above): 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.
81+
- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart where the knowledge service is mounted (above; where it is not, the save is refused, naming the fix): 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.
8182
- **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.
8283
- **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`.
8384
- **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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -198,11 +198,15 @@ starts and follows the type from then on, with no restart:
198198
the adapter's `dropSource` (§3.4). Over an adapter without that member the
199199
index is kept, and the service says so once in its log, naming the source.
200200

201-
A deployment that holds a `knowledge_source` item but mounts no knowledge
202-
service says so once at boot, naming the items: nothing loads, indexes or
203-
searches them until `KnowledgeServicePlugin` and an adapter are mounted. Such
204-
an item is one the stack does not ship — saved at run time or installed in a
205-
package after the boot — since a shipped one mounts the service.
201+
A source is saved only on a deployment that mounts the knowledge service
202+
(see [Who may author one](#who-may-author-one)). A deployment that holds a
203+
`knowledge_source` item but mounts no knowledge service says so once at boot,
204+
naming the items: nothing loads, indexes or searches them until the service is
205+
mounted, by `requires: ['knowledge']` in the stack and a restart (or, on a host
206+
that composes its own kernel, `KnowledgeServicePlugin` and a store). Such an
207+
item is one the stack does not ship, since a shipped one mounts the service:
208+
one a package install, a seed or a migration wrote after the boot, or one
209+
saved before saves were refused there.
206210

207211
#### Who may author one
208212

@@ -236,6 +240,17 @@ and the MCP draft door:
236240
verdict that cannot be reached, or a knowledge service that is registered
237241
and cannot be resolved, refuses `503`; nothing is written.
238242

243+
**A deployment with no knowledge service saves no source.** Nothing there
244+
would load, index or search it, and the service is mounted when the server
245+
starts, never while it runs; a source saved at run time is not one the stack
246+
ships, so it does not mount the service either. So on such a deployment every
247+
door above refuses an author's save `503 SERVICE_UNAVAILABLE`, and a duplicate
248+
that would copy a source is refused the same way; nothing is written. The
249+
refusal names the fix: add `requires: ['knowledge']` to the stack, restart,
250+
then save the source. The engine's own writes (a package install, a seed, a
251+
migration) are not refused, and a knowledge service a host mounts itself
252+
answers for its own sources.
253+
239254
#### One name, one source
240255

241256
A source is identified by the package that ships it and its `name`

‎packages/metadata-core/src/knowledge-source-save-admission.test.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
* [ADR-0161 K4, guard two] `authoredKnowledgeSourceRefusal` — what every save
55
* door asks before a `knowledge_source` is written: the knowledge service's
66
* verdict for the AUTHOR. Pinned here: which saves are judged, that the
7-
* service is asked with the item and the author's context, and that the gate
8-
* fails closed.
7+
* service is asked with the item and the author's context, that a deployment
8+
* with no knowledge service refuses an author's save, and that the gate fails
9+
* closed.
910
*/
1011

1112
import { describe, it, expect, vi } from 'vitest';
@@ -44,8 +45,29 @@ describe('authoredKnowledgeSourceRefusal — source admission at save', () => {
4445
expect(resolve).not.toHaveBeenCalled();
4546
});
4647

47-
it('no knowledge service, or one without the member, judges nothing: nothing loads the item there', async () => {
48-
for (const service of [undefined, null, {}, { search: async () => [] }]) {
48+
it('no knowledge service registered: an author\'s save is refused SERVICE_UNAVAILABLE / 503, naming the reason and the remedy', async () => {
49+
for (const service of [undefined, null]) {
50+
for (const type of ['knowledge_source', 'knowledge_sources']) {
51+
const refusal = await authoredKnowledgeSourceRefusal({ type, item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: async () => service });
52+
expect(refusal, `${type} / ${String(service)}`).toMatchObject({ status: 503, code: 'SERVICE_UNAVAILABLE' });
53+
// The reason, the item, and the remedy in its order: the token, a restart, then the save.
54+
expect(refusal?.message).toMatch(/^The knowledge source 'faq' was not saved: this deployment runs no knowledge service/);
55+
expect(refusal?.message).toMatch(/requires: \['knowledge'\].*restart the server.*then save the source again/);
56+
}
57+
}
58+
// An item with no name is still refused, without a name to quote.
59+
const unnamed = await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: {}, executionContext: AUTHOR, resolveKnowledgeService: () => undefined });
60+
expect(unnamed?.message).toMatch(/^The knowledge source was not saved: /);
61+
});
62+
63+
it('no knowledge service registered: the engine\'s own write is not refused (a package install, a seed, a migration)', async () => {
64+
const resolve = vi.fn(() => undefined);
65+
expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: { isSystem: true }, resolveKnowledgeService: resolve })).toBeUndefined();
66+
expect(resolve).not.toHaveBeenCalled();
67+
});
68+
69+
it('a registered knowledge service without the member (not the platform\'s) judges nothing: the save goes on', async () => {
70+
for (const service of [{}, { search: async () => [] }]) {
4971
expect(await authoredKnowledgeSourceRefusal({ type: 'knowledge_source', item: ITEM, executionContext: AUTHOR, resolveKnowledgeService: () => service })).toBeUndefined();
5072
}
5173
});

‎packages/metadata-core/src/knowledge-source-save-admission.ts‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,27 @@
2929
*
3030
* - **Any other type**, and **the engine's own write** (`isSystem`: a package
3131
* install, a seed, a migration): the gates that need no principal at
32-
* `os validate` and publish are their own card (topic #37000, row 4).
33-
* - **A deployment with no knowledge service**, or one whose service is not
34-
* the platform's: nothing loads the item there, so nothing is indexed.
32+
* `os validate` and publish are their own card (topic #37000, row 4). A
33+
* system write is never refused here, a deployment with no knowledge
34+
* service included: the boot names such an item and its remedy
35+
* (`knowledge-source-unserved.ts` in `@objectstack/objectql`).
36+
* - **A registered knowledge service that is not the platform's** (one with
37+
* no `admitAuthoredSource`, a host-mounted one for example): it answers for
38+
* its own sources, and the save goes on.
39+
*
40+
* ## A deployment with no knowledge service
41+
*
42+
* Refused, not judged (ADR-0078 §1: a declaration that never takes effect is
43+
* an error). Nothing loads, indexes or searches a `knowledge_source` there,
44+
* and nothing mounts the service while the process runs: it is composed at
45+
* boot, from `requires: ['knowledge']` in the stack. So an author's save there
46+
* would be kept and never served, and the Studio, REST or MCP author would
47+
* never see the boot line that says so. The refusal tells them at the save,
48+
* with the remedy: declare the token, restart, then save
49+
* ({@link noKnowledgeServiceRefusal}). `503 SERVICE_UNAVAILABLE`: the save
50+
* needs a service this deployment does not run, the code the knowledge
51+
* service answers at index and search for a store that is not mounted.
52+
* Nothing was written.
3553
*
3654
* ## Fail direction
3755
*
@@ -75,13 +93,35 @@ function unavailable(why: string): AuthoredKnowledgeSourceRefusal {
7593
};
7694
}
7795

96+
/**
97+
* The refusal of an author's `knowledge_source` save on a deployment that
98+
* registers no knowledge service: what is wrong, and what makes the save take
99+
* effect. The service is mounted at boot from the stack's `requires`, never
100+
* while the process runs, so the remedy is ordered: the token, a restart, then
101+
* the save.
102+
*/
103+
function noKnowledgeServiceRefusal(item: unknown): AuthoredKnowledgeSourceRefusal {
104+
const name = (item as { name?: unknown } | null | undefined)?.name;
105+
const source = typeof name === 'string' && name !== '' ? `The knowledge source '${name}'` : 'The knowledge source';
106+
return {
107+
status: 503,
108+
code: 'SERVICE_UNAVAILABLE',
109+
message:
110+
`${source} was not saved: this deployment runs no knowledge service, so nothing would load, index or ` +
111+
"search it. Add requires: ['knowledge'] to the stack (or, on a host that composes its own kernel, " +
112+
'KnowledgeServicePlugin from @objectstack/service-knowledge and a knowledge store), restart the server, ' +
113+
'then save the source again: the service is mounted when the server starts, never while it runs. ' +
114+
'Nothing was written.',
115+
};
116+
}
117+
78118
/**
79119
* The refusal of a `knowledge_source` save, or `undefined` when the save may
80120
* go on (the module doc says what is and is not judged).
81121
*
82122
* `resolveKnowledgeService` answers the request environment's `knowledge`
83-
* service, `undefined` when none is registered, and throws when one is
84-
* registered and cannot be resolved.
123+
* service, `undefined` when none is registered (an author's save is then
124+
* refused), and throws when one is registered and cannot be resolved.
85125
*/
86126
export async function authoredKnowledgeSourceRefusal(input: {
87127
/** The metadata type saved, in any URL spelling the protocol accepts. */
@@ -100,7 +140,8 @@ export async function authoredKnowledgeSourceRefusal(input: {
100140
} catch (err) {
101141
return unavailable(`the knowledge service could not be resolved: ${err instanceof Error ? err.message : String(err)}`);
102142
}
103-
const admit = (service as Partial<KnowledgeSourceSaveAdmitter> | null | undefined)?.admitAuthoredSource;
143+
if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item);
144+
const admit = (service as Partial<KnowledgeSourceSaveAdmitter>).admitAuthoredSource;
104145
if (typeof admit !== 'function') return undefined;
105146
let verdict: AuthoredKnowledgeSourceVerdict;
106147
try {

‎packages/objectql/src/knowledge-source-unserved.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ describe('describeUnservedKnowledgeSources — items with no knowledge service (
2020
expect(line).toContain('it is loaded, indexed or searched');
2121
expect(line).toContain('@objectstack/service-knowledge');
2222
expect(line).toContain('or remove the item.');
23+
// The remedy an author's save on such a deployment is refused with: the token, then a restart.
24+
expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart");
2325
});
2426

2527
it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => {

‎packages/objectql/src/knowledge-source-unserved.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,16 @@
1616
* A statement at `warn`, never a boot refusal: a package may ship a source to
1717
* a deployment that chose not to run retrieval, and its objects, pages and
1818
* flows must keep serving there.
19+
*
20+
* The remedy it names is the one an author's save is refused with on such a
21+
* deployment (`authoredKnowledgeSourceRefusal`, `@objectstack/metadata-core`):
22+
* `requires: ['knowledge']` in the stack, then a restart, since the service is
23+
* composed at boot and never while the process runs. The items this line
24+
* finds are ones the stack does not ship, since a `knowledgeSources` entry
25+
* mounts the service by itself: they arrived by the engine's own write,
26+
* which is never refused (a package
27+
* installed after the boot, a seed, a migration), or were saved before the
28+
* save refused them.
1929
*/
2030

2131
import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
@@ -40,12 +50,21 @@ export function describeUnservedKnowledgeSources(names: readonly string[], servi
4050
return (
4151
`[ObjectQLPlugin] this deployment holds ${count} knowledge_source ${count === 1 ? 'item' : 'items'} ` +
4252
`(${shown}${rest > 0 ? `, and ${rest} more` : ''}), but no '${KNOWLEDGE_SERVICE}' service is registered, so ` +
43-
`${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. Add KnowledgeServicePlugin ` +
44-
'(@objectstack/service-knowledge) and a knowledge adapter to the composition, or remove the ' +
53+
`${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. ${UNSERVED_REMEDY} or remove the ` +
4554
`${count === 1 ? 'item' : 'items'}.`
4655
);
4756
}
4857

58+
/**
59+
* What mounts the service for an item on a deployment that runs none: the
60+
* token (or the plugin, for a host that composes its own kernel), then a
61+
* restart. The same remedy an author's save there is refused with.
62+
*/
63+
const UNSERVED_REMEDY =
64+
"Declare requires: ['knowledge'] in the stack and restart — the service and the deployment's store are mounted " +
65+
'at boot, never while the process runs — or, on a host that composes its own kernel, add KnowledgeServicePlugin ' +
66+
'(@objectstack/service-knowledge) and a knowledge store;';
67+
4968
/** What {@link announceUnservedKnowledgeSources} reads of its host. */
5069
export interface UnservedKnowledgeSourcesHost {
5170
/** Resolve a kernel service by name; throws or answers nothing when none is registered. */

‎packages/rest/src/meta-item-write-routes.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,9 +255,12 @@ export function registerMetaItemWriteRoutes(this: MetaItemWriteRouteHost, scope:
255255
// themselves search what it would index — the knowledge
256256
// service's search-time gates, asked for the author before
257257
// anything is written (`authoredKnowledgeSourceRefusal`).
258-
// Every other type passes untouched. `403` keeps this door's
259-
// `FORBIDDEN` spelling; a verdict that cannot be reached is
260-
// the gate's own `503`.
258+
// On a deployment with no knowledge service the author's save
259+
// is refused `503 SERVICE_UNAVAILABLE`, naming the remedy:
260+
// nothing would load it, and the author never sees the boot
261+
// line. Every other type passes untouched. `403` keeps this
262+
// door's `FORBIDDEN` spelling; a verdict that cannot be
263+
// reached is the gate's own `503`.
261264
{
262265
const refused = await authoredKnowledgeSourceRefusal({
263266
type: req.params.type,

0 commit comments

Comments
 (0)