Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/38369-held-status.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/service-knowledge': patch
'@objectstack/objectql': patch
---

feat(service-knowledge): index_status and rebuild say when the knowledge service is held

Clause-②: yes (widening)
Metadata-protocol: none

While the boot read a knowledge service the runtime composed as not enabled (no embedder, or the deployment's store not mounted), the `knowledge` settings actions say so. `index_status` answers each source's index as the new state `held` (not due) without asking its store, adds `enablement` — `state: 'not-enabled'`, the `reason` naming each missing half and its remedy, `embedder` / `store` for the missing halves, and `heldSources` — and its message leads with the reason and the held count. `rebuild` is refused (`ok: false`, which the settings door answers 400) with the service's own sentence: "Rebuild of source 'X' is refused: … To enable it, save an embedder provider, then restart." `os knowledge rebuild` exits 1 with that sentence. A service a host mounts itself, and an enabled one, answer exactly as before.

The boot line of a deployment that holds `knowledge_source` items and runs no knowledge service now names the embedder step its save refusal already names: declare `requires: ['knowledge']`, restart, then save an embedder provider and restart again.
6 changes: 5 additions & 1 deletion content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,11 @@ no `search_knowledge` definition is handed out; `search`, `rebuildSource` and
`reindexSource` answer `503 SERVICE_UNAVAILABLE` naming the missing half; a
removed source keeps its index, and no store is called. The boot logs one line,
`info` when only a shipped source mounted the service and nothing was saved,
`warn` otherwise, and never refuses to start. A change takes effect at the next
`warn` otherwise, and never refuses to start. The settings `index_status`
action answers each held source's index as `held`, without reading its store,
and adds `enablement`: not enabled, the reason with its remedy, and how many
sources are held. The `rebuild` action refuses the build with the same remedy,
and `os knowledge rebuild` exits 1 with it. A change takes effect at the next
restart. A host-mounted service is not read this way and serves from the start.

#### How a source is loaded
Expand Down
3 changes: 3 additions & 0 deletions packages/objectql/src/knowledge-source-unserved.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ describe('describeUnservedKnowledgeSources — items with no knowledge service (
expect(line).toContain('or remove the item.');
// The remedy an author's save on such a deployment is refused with: the token, then a restart.
expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart");
// [ADR-0161 K8, the dated note on item 12] ...and, as the save's remedy does, the embedder step: the
// service the token mounts is held until a provider is saved and the server restarted once more.
expect(line).toContain("in the stack and restart, then save an embedder provider and restart again");
});

it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => {
Expand Down
19 changes: 12 additions & 7 deletions packages/objectql/src/knowledge-source-unserved.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
* The remedy it names is the one an author's save is refused with on such a
* deployment (`authoredKnowledgeSourceRefusal`, `@objectstack/metadata-core`):
* `requires: ['knowledge']` in the stack, then a restart, since the service is
* composed at boot and never while the process runs. The items this line
* composed at boot and never while the process runs; then an embedder
* provider saved and one more restart, since a service the stack requires is
* enabled only with an embedder, and its embedder settings exist only once
* the service is mounted (ADR-0161 K8, the dated note on item 12). The items this line
* finds are ones the stack does not ship, since a `knowledgeSources` entry
* mounts the service by itself: they arrived by the engine's own write,
* which is never refused (a package
Expand Down Expand Up @@ -56,14 +59,16 @@ export function describeUnservedKnowledgeSources(names: readonly string[], servi
}

/**
* What mounts the service for an item on a deployment that runs none: the
* token (or the plugin, for a host that composes its own kernel), then a
* restart. The same remedy an author's save there is refused with.
* What mounts the service for an item on a deployment that runs none and
* serves the item: the token (or the plugin, for a host that composes its own
* kernel), a restart, then an embedder provider and one more restart. The
* same remedy an author's save there is refused with.
*/
const UNSERVED_REMEDY =
"Declare requires: ['knowledge'] in the stack and restart — the service and the deployment's store are mounted " +
'at boot, never while the process runs — or, on a host that composes its own kernel, add KnowledgeServicePlugin ' +
'(@objectstack/service-knowledge) and a knowledge store;';
"Declare requires: ['knowledge'] in the stack and restart, then save an embedder provider and restart again — " +
"the service and the deployment's store are mounted at boot, never while the process runs, and the service the " +
'stack requires serves only once an embedder is configured — or, on a host that composes its own kernel, add ' +
'KnowledgeServicePlugin (@objectstack/service-knowledge) and a knowledge store;';

/** What {@link announceUnservedKnowledgeSources} reads of its host. */
export interface UnservedKnowledgeSourcesHost {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [ADR-0161 K8, the dated note on item 12] The administrator's two knowledge
* actions say when the service is held. While the boot read a service the
* runtime composed as not enabled (no embedder, or the deployment's store not
* mounted):
*
* - `index_status` answers what it answers otherwise, plus `enablement` — the
* state, the reason with its remedy, the missing halves and how many
* sources are held — and its message leads with the state;
* - `rebuild` is refused (`ok: false`, which the settings door answers 400)
* with the service's own refusal of the build, naming the remedy, and no
* store is called.
*
* A service a host mounts itself, and an enabled one, answer as they always
* did: no `enablement`, the same message. The actions are run the way the
* settings page and `os knowledge status` / `os knowledge rebuild` reach
* them: through the settings service's action door.
*
* While held, `index_status` answers each source's index as `held` without
* asking its store: a held service calls no store, and a reading of the
* store would say a build is due that nothing will run.
*/

import { createHash } from 'node:crypto';
import { describe, it, expect } from 'vitest';
import { LiteKernel } from '@objectstack/core';
import type { Plugin, PluginContext } from '@objectstack/core';
import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
import type { KnowledgeSource } from '@objectstack/spec/ai';
import type { IEmbedder, IKnowledgeAdapter } from '@objectstack/spec/contracts';
import { SettingsServicePlugin, type CryptoAdapter, type SettingsService } from '@objectstack/service-settings';
import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
import { KnowledgeService } from '../knowledge-service.js';
import { knowledgeIndexStatusActionHandler, type KnowledgeIndexStatusEnablement } from '../knowledge-build-actions.js';

/** The settings service stores the embedder key only through an adapter that declares confidentiality. */
class ConfidentialTestAdapter implements CryptoAdapter {
readonly confidential = true;
async encrypt(plaintext: string): Promise<string> {
return 'kms:' + Buffer.from(plaintext, 'utf8').toString('base64');
}
async decrypt(ciphertext: string): Promise<string> {
return Buffer.from(ciphertext.replace(/^kms:/, ''), 'base64').toString('utf8');
}
digest(plaintext: string): string {
return createHash('sha256').update(plaintext).digest('hex');
}
}

/** The deployment's store (`id`), counting every call made to it. */
class CountingStorePlugin implements Plugin {
name = 'test.knowledge.counting-store';
version = '1.0.0';
type = 'standard' as const;
dependencies = ['com.objectstack.service.knowledge'];
constructor(private readonly storeId: string, private readonly calls: string[]) {}
async init(): Promise<void> {}
async start(ctx: PluginContext): Promise<void> {
const calls = this.calls;
const adapter: IKnowledgeAdapter = {
id: this.storeId,
async upsert() {
calls.push('upsert');
},
async search() {
calls.push('search');
return [];
},
async delete() {
calls.push('delete');
},
async dropSource() {
calls.push('dropSource');
},
};
ctx.getService<KnowledgeService>(KNOWLEDGE_SERVICE).registerAdapter(this.storeId, adapter);
}
}

/** A host's own embedder, registered at `init`. */
class HostEmbedderPlugin implements Plugin {
name = 'test.host-embedder';
version = '1.0.0';
type = 'standard' as const;
async init(ctx: PluginContext): Promise<void> {
const embedder: IEmbedder = { id: 'host-own', dimensions: 2, embed: async (t) => t.map(() => [0.6, 0.8]) };
ctx.registerService(EMBEDDER_SERVICE, embedder);
}
}

const SOURCES: KnowledgeSource[] = [
{ name: 'docs', label: 'Docs', source: { kind: 'object', object: 'doc', content: ['body'] } },
{ name: 'faq', label: 'FAQ', source: { kind: 'object', object: 'faq', content: ['answer'] } },
];

async function boot(opts: {
/** Set ⇒ the runtime composed the service (`resolveCapabilityArgument`). */
runtimeComposed?: { declared: boolean };
/** Whether the deployment's store registers its adapter. @default true */
storeMounted?: boolean;
/** Whether a host plugin registers an embedder. @default false */
hostEmbedder?: boolean;
}) {
const calls: string[] = [];
const kernel = new LiteKernel();
if (opts.hostEmbedder) kernel.use(new HostEmbedderPlugin());
kernel.use(new KnowledgeServicePlugin({
enableEventSync: false,
buildAtBoot: false,
reconcile: false,
deploymentAdapter: 'vec',
...(opts.runtimeComposed ? { runtimeComposed: opts.runtimeComposed } : {}),
sources: SOURCES,
}));
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
if (opts.storeMounted !== false) kernel.use(new CountingStorePlugin('vec', calls));
await kernel.bootstrap();
const knowledge = kernel.getService<KnowledgeService>(KNOWLEDGE_SERVICE);
const settings = kernel.getService<SettingsService>('settings');
const run = (action: 'index_status' | 'rebuild', payload: unknown) => settings.runAction('knowledge', action, payload);
return { kernel, knowledge, calls, run };
}

const enablementOf = (details: unknown): KnowledgeIndexStatusEnablement | undefined =>
(details as { enablement?: KnowledgeIndexStatusEnablement }).enablement;

describe('[ADR-0161 K8, note on item 12] index_status states a held service: not enabled, why, how many sources', () => {
it('no embedder: the state, the reason naming the remedy, the embedder half and every held source', async () => {
const { knowledge, run, calls } = await boot({ runtimeComposed: { declared: false } });
expect(knowledge.heldReading()).toBeDefined();

const answer = await run('index_status', {});
expect(answer.ok).toBe(true);
const enablement = enablementOf(answer.details);
expect(enablement).toEqual({
state: 'not-enabled',
reason: expect.stringMatching(/^\[knowledge\] the knowledge service is not enabled on this deployment: no embedder is configured/),
embedder: expect.stringContaining('ai.embedder_provider'),
heldSources: 2,
});
expect(enablement?.reason).toContain('To enable it, save an embedder provider, then restart.');
expect(enablement?.reason).not.toContain('knowledge store');
// The message leads with the state and counts the held sources.
expect(answer.message).toBe(`${enablement?.reason} 2 source(s) held.`);
// Every source is still listed, as on an enabled service.
expect((answer.details as { sources: Array<{ id: string }> }).sources.map((s) => s.id)).toEqual(['docs', 'faq']);

// One source named: its entry alone, and the service's held count all the same.
const one = await run('index_status', { source: 'docs' });
expect((one.details as { sources: Array<{ id: string }> }).sources.map((s) => s.id)).toEqual(['docs']);
expect(enablementOf(one.details)?.heldSources).toBe(2);
expect(calls).toEqual([]);
});

it("the store not mounted as well: both halves, and the reason names the store's remedy", async () => {
const { run } = await boot({ runtimeComposed: { declared: false }, storeMounted: false });
const enablement = enablementOf((await run('index_status', {})).details);
expect(enablement).toMatchObject({ state: 'not-enabled', store: 'vec', embedder: expect.any(String), heldSources: 2 });
expect(enablement?.reason).toContain("the deployment's knowledge store 'vec' is not mounted");
expect(enablement?.reason).toContain("save an embedder provider and mount the deployment's knowledge store, then restart.");
});

it('a host-mounted service with no embedder, and an enabled runtime-composed one, answer no enablement and the same message', async () => {
for (const opts of [{}, { runtimeComposed: { declared: false }, hostEmbedder: true }]) {
const { knowledge, run } = await boot(opts);
expect(knowledge.heldReading(), JSON.stringify(opts)).toBeUndefined();
const answer = await run('index_status', {});
expect(answer.ok).toBe(true);
expect(Object.keys(answer.details as object), JSON.stringify(opts)).not.toContain('enablement');
expect(answer.message, JSON.stringify(opts)).toMatch(/^2 source\(s\): \d+ need a build, 0 building, 0 with failed syncs\.$/);
}
});
});

describe('[ADR-0161 K8, note on item 12] rebuild is refused on a held service, with the remedy', () => {
it("refused (ok: false), the service's own sentence naming the remedy, and no store is called", async () => {
const { run, calls } = await boot({ runtimeComposed: { declared: false } });
const answer = await run('rebuild', { source: 'docs' });
expect(answer).toMatchObject({ ok: false, severity: 'error', details: { source: 'docs', build: null } });
expect(answer.message).toMatch(
/^Rebuild of source 'docs' is refused: \[knowledge\] the knowledge service is not enabled on this deployment: no embedder is configured/,
);
expect(answer.message).toContain('To enable it, save an embedder provider, then restart.');
expect(calls).toEqual([]);
});

it('an enabled runtime-composed service is not refused', async () => {
const { run } = await boot({ runtimeComposed: { declared: false }, hostEmbedder: true });
const answer = await run('rebuild', { source: 'docs' });
expect(answer.message ?? '').not.toContain('is refused');
expect(answer.message ?? '').not.toContain('not enabled');
});
});

describe('[ADR-0161 K8, note on item 12] a held index_status asks no store what it holds', () => {
/** A service with a data engine bound, so its index reading reaches the store; the store counts every call. */
function service(held: boolean) {
const calls: string[] = [];
const dataEngine = { find: async () => [], findOne: async () => null, count: async () => 0 } as never;
const knowledge = new KnowledgeService({ dataEngine, deploymentAdapter: 'vec', enabledByConfiguration: true });
const adapter: IKnowledgeAdapter = {
id: 'vec',
async upsert() { calls.push('upsert'); },
async search() { calls.push('search'); return []; },
async delete() { calls.push('delete'); },
async indexStatus() {
calls.push('indexStatus');
return { fingerprint: 'built-under-another-model', recipeHash: 'r' };
},
};
knowledge.registerAdapter('vec', adapter);
knowledge.registerSource(SOURCES[0]!);
knowledge.settleEnablement(held ? { embedder: 'ai.embedder_provider is not saved' } : undefined);
const status = knowledgeIndexStatusActionHandler(knowledge);
const read = () => status({ namespace: 'knowledge', actionId: 'index_status', values: {}, payload: {}, ctx: {} } as never);
return { calls, read };
}

it('held, the store mounted: the index reads held, not due, and the store is never called', async () => {
const { calls, read } = service(true);
const answer = await read();
const [entry] = (answer.details as { sources: Array<{ index: { state: string; due: boolean; detail: string } }> }).sources;
expect(entry?.index).toMatchObject({ state: 'held', due: false });
expect(entry?.index.detail).toMatch(/^held: the knowledge service is not enabled on this deployment/);
expect(entry?.index.detail).not.toContain('built anew');
expect(calls).toEqual([]);
});

it('control: enabled, the same store is asked once per source, as it always was', async () => {
const { calls, read } = service(false);
const answer = await read();
const [entry] = (answer.details as { sources: Array<{ index: { state: string } }> }).sources;
expect(entry?.index.state).toBe('new-fingerprint');
expect(calls).toEqual(['indexStatus']);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -1012,7 +1012,9 @@ describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is
// The engine's own write (a package install, a seed) is admitted, and nothing calls the store.
expect(await admit(knowledge, SYSTEM)).toEqual({ admitted: true });
// A save with no identity is refused for the held state first: it names the deployment, not the caller.
expect((await admit(knowledge, undefined)).message).toContain(HELD);
// `null`, not `undefined`: `admit`'s default parameter would read `undefined` as the author's identity.
expect(await admit(knowledge, null)).toMatchObject({ admitted: false, status: 503, code: 'SERVICE_UNAVAILABLE' });
expect((await admit(knowledge, null)).message).toContain(HELD);
expect(calls).toEqual([]);
});

Expand Down
Loading
Loading