diff --git a/.changeset/37099-knowledge-first-build.md b/.changeset/37099-knowledge-first-build.md
new file mode 100644
index 00000000000..e63932fd5ba
--- /dev/null
+++ b/.changeset/37099-knowledge-first-build.md
@@ -0,0 +1,15 @@
+---
+'@objectstack/service-knowledge': patch
+'@objectstack/cli': patch
+---
+
+feat(service-knowledge): a knowledge source that was never built is built after boot, and an administrator can rebuild one with `os knowledge rebuild`
+
+Clause-②: yes
+Metadata-protocol: none
+
+- **The first build.** After every boot, `KnowledgeServicePlugin` reads what each `object` source's adapter holds (`indexStatus`, else one entry of `listDocuments`) against the index fingerprint and recipe hash the service computes now (ADR-0161 K7, "What starts a rebuild"), and builds — once, in the background, one source at a time — every source the adapter holds nothing for, holds under another fingerprint, or holds under another recipe hash. A source already built is left alone; a source with `refresh.onRecordChange: false` is left to its external indexer; an adapter with neither `indexStatus` nor `listDocuments` is never built automatically, and the boot log says so once. `KnowledgeServicePlugin({ buildAtBoot: false })` turns it off.
+- **One node builds a source.** A build runs under the `cluster` service's lock, key `knowledge:build:SOURCE`, renewed while it runs; a node that gets the lock after another built the source re-reads it and builds nothing, and a lock that does not answer starts no build. With no cluster service the composition is one node. Only a shared cluster lock driver (`redis`) makes this hold across nodes: the default `memory` driver's lock is per process, so with it every node builds.
+- **The administrator's rebuild.** The `knowledge` settings namespace gains two actions, gated like every settings write on `manage_platform_settings`: `rebuild` (`{ "source": "ID" }`) starts one complete build in the background, and `index_status` (`{}` or `{ "source": "ID" }`) answers each source's index state and the last build the answering node ran — its progress while it runs, its result (written, unchanged, purged, cannot be indexed) once it ended. `os knowledge rebuild SOURCE` starts a build and follows its progress to its end (`--no-wait` exits 0 once it has started and reports no outcome; otherwise exit 1 when it did not run or did not finish); `os knowledge status [SOURCE]` prints the state.
+- **What it costs.** A build sends the content fields of every matching row the index does not already hold unchanged to the embedding provider, which bills for them. The line that starts a build says so, the server logs its progress every ten seconds and its result, and `content/docs/ai/knowledge-rag.mdx` states it. The default `memory` adapter holds nothing after a restart, so with it every boot builds the whole source again, on every node.
+- `KnowledgeService` gains `readIndexState`, `rebuildSource`, `buildRecord`, `buildSourcesAtBoot` and `stopBuilds`, and the option `resolveBuildLock`; `IKnowledgeService` is unchanged.
diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx
index d74e41dc18c..aae5f7fc79f 100644
--- a/content/docs/ai/knowledge-rag.mdx
+++ b/content/docs/ai/knowledge-rag.mdx
@@ -218,7 +218,35 @@ Known residual: text made mostly of random hex or base64 — UUIDs, sha256 diges
## When the model or the split changes: rebuild
-Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and carries on every write and every search, and the adapter checks against the index it holds. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint).
+Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and carries on every write and every search, and the adapter checks against the index it holds. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it — which the next boot starts by itself, or `os knowledge rebuild` (below) does now; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint).
+
+## The first build, and rebuilding a source
+
+Event sync keeps an index in step with rows as they are written; it never indexes the rows a source matched before it was mounted. So after every boot the knowledge service reads what each source's adapter holds and builds, once, in the background, every `object` source that needs it — the boot never waits for it:
+
+| What the adapter holds | At boot |
+|:--|:--|
+| nothing for the source (or, for an adapter without an index status, no document) | built |
+| an index under another fingerprint (embedding model, dimensions or split) | built anew, beside the old index where the store keeps generations |
+| the same fingerprint, but the source's `where`, `metadataFields`, title rule or withheld fields changed | rebuilt in place; unchanged documents are skipped |
+| the same fingerprint and recipe | left alone |
+
+A source with `refresh.onRecordChange: false` is left to its external indexer, and an adapter that reports neither an index status nor its documents is never built automatically: the boot log says so, and you rebuild it by hand. With several server nodes sharing a cluster lock driver (`OS_CLUSTER_DRIVER=redis`, [Cluster](/docs/kernel/cluster)), only one builds a source: the build runs under the `cluster` service's lock, and a node that finds the source built when it gets the lock builds nothing. `KnowledgeServicePlugin({ buildAtBoot: false })` turns the boot builds off.
+
+
+**A build costs money.** A complete build reads every row the source's `where` matches and sends the listed content fields of each one the index does not already hold unchanged to your embedding provider, which bills for them. The first build of a large source, or a rebuild after you change the embedding model or the split, sends all of it. The boot log line that starts a build says so.
+
+The default `memory` adapter holds nothing after a restart, so with it **every boot is a first build**: each boot sends the whole source to the embedding provider again, on every node, because each process keeps its own index. Use a persistent adapter (pgvector, Turso, RAGFlow) for a source you do not want re-embedded on each restart. And "only one node builds a source" holds only with a shared cluster lock driver: the default `memory` cluster driver's lock is a per-process mutex, so with it every node builds the source itself.
+
+
+To rebuild a source yourself, as an administrator (an account with `manage_platform_settings`):
+
+```bash
+os knowledge status # each source: built, never built or due a rebuild, and the last build
+os knowledge rebuild support_articles # start a complete build and follow its progress
+```
+
+`os knowledge rebuild` starts the build on the server and prints its progress — rows read, documents written, unchanged, purged, and those that cannot be indexed — until it ends; `--no-wait` returns once it has started. Both commands call the `knowledge` settings actions `rebuild` and `index_status` (`POST /api/settings/knowledge/rebuild` with `{ "source": "ID" }`). The server logs each build's start, its progress every ten seconds, and its result. A build's progress lives on the node that runs it: behind a load balancer, read it from that node.
## Self-hosted vector store: PostgreSQL + pgvector
diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx
index a3452729b6d..d7893458a15 100644
--- a/content/docs/deployment/cli.mdx
+++ b/content/docs/deployment/cli.mdx
@@ -4003,6 +4003,62 @@ the grant, use the environment's console: **Account → Connect an AI Assistant*
| `-s, --server ` | `OS_CLOUD_URL` | Control-plane URL. Default `https://cloud.objectos.ai`, or the URL recorded by `os cloud login` |
| `-t, --token ` | `OS_CLOUD_API_KEY` | Bearer token, used only to find the environment; `$OS_TOKEN` and `~/.objectstack/cloud.json` are the fallbacks |
+### Knowledge
+
+The administrator's view of the server's [knowledge sources](/docs/ai/knowledge-rag#the-first-build-and-rebuilding-a-source):
+what each source's index holds, and one complete rebuild of a source. Both
+commands call the `knowledge` settings actions (`POST /api/settings/knowledge/rebuild`
+and `/index_status`), which answer only an account with
+`manage_platform_settings`; any other caller is refused with `403` and is told
+nothing about the sources.
+
+| Command | Description |
+|---------|-------------|
+| `os knowledge status` | Each source's index state (built, never built, due a rebuild) and the last build the answering node ran |
+| `os knowledge rebuild` | Start one complete build of a source on the server and follow its progress |
+
+#### `os knowledge status`
+
+```bash
+os knowledge status # every source
+os knowledge status support_articles # one source
+```
+
+Prints, per source, its adapter and kind, its index state against what the
+server expects (and whether a build is due), and the last build the node that
+answered ran: its progress while it runs, its counts once it ended. A build's
+record lives on the node that ran it, so behind a load balancer the node that
+answers may not be the one building; the index state is read from the store and
+is the same on every node. Exits `1` with the server's refusal text when the
+action is refused.
+
+#### `os knowledge rebuild`
+
+```bash
+os knowledge rebuild support_articles # start and follow to the end
+os knowledge rebuild support_articles --no-wait # start, and return at once
+```
+
+**A build costs money:** every row the source's `where` matches is read, and the
+content fields of each one the index does not already hold unchanged are sent to
+the embedding provider, which bills for them. The build runs on the server in
+the background; the command reads `index_status` every `--interval` seconds and
+prints the build's progress until it ends. It exits `0` when the build finished,
+and `1` when the server refused the rebuild (an unknown or `file` source, a
+build already running on that node), when the build did not run or did not
+finish, or when the progress was answered by another node than the one
+building (the build continues there). `--no-wait` exits `0` once the build has
+started and reports no outcome: the build can still end without running
+(another node holds the source's lock) or fail, which only `os knowledge status`
+then shows.
+
+| Flag | Commands | Env equivalent | Purpose |
+|---|---|---|---|
+| `-u, --url ` | both | `OS_CLOUD_URL` | Server URL (default `http://localhost:3000`) |
+| `-t, --token ` | both | `OS_TOKEN` | Bearer token of an administrator |
+| `--no-wait` | `rebuild` | — | Return once the build has started; its outcome is not reported |
+| `--interval ` | `rebuild` | — | Seconds between two progress reads (default `2`) |
+
### Skills
The published skills catalog (`@objectstack/skills`, see [AI Skills](/docs/ai/skills))
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 0bb12925cd6..fb6f462274d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -79,6 +79,9 @@
"i18n": {
"description": "Scaffold translation skeletons from a stack, and check translation coverage"
},
+ "knowledge": {
+ "description": "Rebuild a knowledge source's index on the server and read each source's index state and last build"
+ },
"mcp": {
"description": "Connect an MCP client to your environment's MCP server"
},
diff --git a/packages/cli/src/commands/knowledge/knowledge.test.ts b/packages/cli/src/commands/knowledge/knowledge.test.ts
new file mode 100644
index 00000000000..409bbf3e84d
--- /dev/null
+++ b/packages/cli/src/commands/knowledge/knowledge.test.ts
@@ -0,0 +1,191 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * `os knowledge rebuild` and `os knowledge status`, driven against response
+ * bodies built by `sendOk` / `sendError` — the server's one writer of the
+ * declared envelope (see `utils/__tests__/server-body.ts`).
+ *
+ * The settings action door answers an action that reported `ok: false` with
+ * a 400 carrying the action's message, and one that succeeded with a 200
+ * carrying the action's result (`@objectstack/service-settings`,
+ * `settings-routes.ts`). These tests pin what each command makes of both:
+ * the route it calls, the payload it sends, that it follows a started build
+ * to its end, and that a build which did not finish exits 1.
+ *
+ * The oclif `Config` is loaded at module scope, as in
+ * `commands/datasource/envelope-unwrap.test.ts` (whose header says why).
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Config } from '@oclif/core';
+import type { Command } from '@oclif/core';
+import { sendError, sendOk } from '@objectstack/types';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { serverBody } from '../../utils/__tests__/server-body.js';
+import KnowledgeRebuild from './rebuild.js';
+import KnowledgeStatus from './status.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+/** This package's own root — `packages/cli`, never outside it. */
+const CLI_ROOT = resolve(HERE, '../../..');
+const SERVER = 'http://127.0.0.1:39999';
+
+const config = await Config.load({ root: CLI_ROOT });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+interface Request { url: string; body: unknown; auth?: string }
+interface Driven {
+ logs: string[];
+ requests: Request[];
+ failure?: { message: string; exit?: number };
+}
+
+type CommandCtor = new (argv: string[], config: Config) => Command;
+
+/**
+ * Run a command in-process against a queue of responses. `instantTimers`
+ * makes `os knowledge rebuild`'s wait between two progress reads fire at
+ * once; it is off for a command with an optional argument, whose parse reads
+ * piped standard input under a timer of oclif's own.
+ */
+async function drive(
+ Cmd: CommandCtor,
+ argv: string[],
+ responses: Array<{ status: number; body: unknown }>,
+ instantTimers = true,
+): Promise {
+ const logs: string[] = [];
+ const requests: Request[] = [];
+ const queue = [...responses];
+ vi.stubGlobal('fetch', async (input: unknown, init?: { body?: string; headers?: Record }) => {
+ requests.push({
+ url: String(input),
+ body: init?.body ? JSON.parse(init.body) : undefined,
+ ...(init?.headers?.authorization ? { auth: init.headers.authorization } : {}),
+ });
+ const next = queue.shift();
+ if (!next) throw new Error('test: no response left for this request');
+ return { status: next.status, ok: next.status < 400, json: async () => next.body };
+ });
+ if (instantTimers) vi.stubGlobal('setTimeout', (fn: () => void) => { fn(); return 0; });
+ const cmd = new Cmd(argv, config);
+ Object.assign(cmd, { log: (message?: string) => { logs.push(String(message ?? '')); } });
+ try {
+ await cmd.run();
+ return { logs, requests };
+ } catch (err) {
+ const exit = (err as { oclif?: { exit?: number } }).oclif?.exit;
+ return { logs, requests, failure: { message: (err as Error).message, exit } };
+ }
+}
+
+const ok = (result: unknown) => ({ status: 200, body: serverBody((res) => sendOk(res, result)) });
+const refused = (message: string) => ({
+ status: 400,
+ body: serverBody((res) => sendError(res, 400, 'SETTINGS_ACTION_FAILED', message, { details: { ok: false, message } })),
+});
+
+const STARTED_AT = '2026-11-26T05:00:00.000Z';
+const running = (discovered: number) => ({
+ trigger: 'operator', status: 'running', startedAt: STARTED_AT,
+ progress: { pages: 1, discovered, indexed: discovered, skipped: 0, failed: 0 },
+});
+const statusOf = (build: unknown) => ok({
+ ok: true,
+ message: '1 source(s)',
+ details: { sources: [{ id: 'kb', label: 'KB', adapter: 'pgvector', kind: 'object', index: { state: 'current', due: false, detail: 'current.' }, build }] },
+});
+
+const target = ['--url', SERVER, '--token', 'tok'];
+
+describe('os knowledge rebuild', () => {
+ it('starts the rebuild through the settings action door and follows it to its end', async () => {
+ const run = await drive(KnowledgeRebuild, ['kb', ...target], [
+ ok({ ok: true, message: "Rebuild of source 'kb' started.", details: { source: 'kb', build: running(0) } }),
+ statusOf(running(100)),
+ statusOf({
+ ...running(250),
+ status: 'done',
+ finishedAt: '2026-11-26T05:01:00.000Z',
+ progress: { pages: 3, discovered: 250, indexed: 240, skipped: 10, failed: 0 },
+ result: { ok: true, discovered: 250, indexed: 240, skipped: 10, purged: 2, failed: 0 },
+ }),
+ ]);
+
+ expect(run.failure).toBeUndefined();
+ expect(run.requests[0]).toEqual({ url: `${SERVER}/api/settings/knowledge/rebuild`, body: { source: 'kb' }, auth: 'Bearer tok' });
+ expect(run.requests.slice(1).map((r) => [r.url, r.body])).toEqual([
+ [`${SERVER}/api/settings/knowledge/index_status`, { source: 'kb' }],
+ [`${SERVER}/api/settings/knowledge/index_status`, { source: 'kb' }],
+ ]);
+ const text = run.logs.join('\n');
+ expect(text).toContain("Rebuild of source 'kb' started.");
+ expect(text).toContain('running (operator, started 2026-11-26T05:00:00.000Z): 100 row(s) read');
+ expect(text).toContain('done (operator, ended 2026-11-26T05:01:00.000Z): 250 row(s) read, 240 written, 10 unchanged, 2 purged');
+ });
+
+ it('exits 1 when the build did not finish', async () => {
+ const run = await drive(KnowledgeRebuild, ['kb', ...target], [
+ ok({ ok: true, details: { source: 'kb', build: running(0) } }),
+ statusOf({ ...running(10), status: 'failed', finishedAt: STARTED_AT, message: 'the adapter upsert failed: quota' }),
+ ]);
+ expect(run.failure).toMatchObject({ message: 'the adapter upsert failed: quota', exit: 1 });
+ });
+
+ it('exits 1 with the server refusal text, and asks nothing more', async () => {
+ const run = await drive(KnowledgeRebuild, ['kb', ...target], [refused('A build of source \'kb\' is already running on this node.')]);
+ expect(run.failure).toMatchObject({ message: "A build of source 'kb' is already running on this node.", exit: 1 });
+ expect(run.requests).toHaveLength(1);
+ });
+
+ it('says so when the progress is answered by a node that is not running this build', async () => {
+ const run = await drive(KnowledgeRebuild, ['kb', ...target], [
+ ok({ ok: true, details: { source: 'kb', build: running(0) } }),
+ statusOf(null),
+ ]);
+ expect(run.failure?.exit).toBe(1);
+ expect(run.failure?.message).toContain('not running this build');
+ });
+
+ it('--no-wait returns once the build has started, and says its outcome is not reported', async () => {
+ const run = await drive(KnowledgeRebuild, ['kb', '--no-wait', ...target], [
+ ok({ ok: true, message: 'started', details: { source: 'kb', build: running(0) } }),
+ ]);
+ expect(run.failure).toBeUndefined();
+ expect(run.requests).toHaveLength(1);
+ // Exit 0 means "started", not "built": the line pointing at the outcome is
+ // the only thing that tells a script so.
+ expect(run.logs.some((line) => line.includes('os knowledge status'))).toBe(true);
+ });
+});
+
+describe('os knowledge status', () => {
+ it('prints each source with its index state and the last build', async () => {
+ const run = await drive(KnowledgeStatus, target, [
+ ok({
+ ok: true,
+ details: {
+ sources: [
+ { id: 'kb', label: 'KB', adapter: 'pgvector', kind: 'object', index: { state: 'nothing', due: true, detail: 'never built.' }, build: null },
+ ],
+ },
+ }),
+ ], false);
+ expect(run.failure).toBeUndefined();
+ expect(run.requests[0]).toMatchObject({ url: `${SERVER}/api/settings/knowledge/index_status`, body: {} });
+ const text = run.logs.join('\n');
+ expect(text).toContain('kb (KB; adapter pgvector, object source)');
+ expect(text).toContain('index: nothing — a build is due — never built.');
+ expect(text).toContain('last build on this node: none');
+ });
+
+ it('exits 1 with the server refusal text', async () => {
+ const run = await drive(KnowledgeStatus, ['nope', ...target], [refused("No knowledge source 'nope' is registered (kb).")], false);
+ expect(run.failure).toMatchObject({ exit: 1 });
+ expect(run.failure?.message).toContain("No knowledge source 'nope'");
+ });
+});
diff --git a/packages/cli/src/commands/knowledge/rebuild.ts b/packages/cli/src/commands/knowledge/rebuild.ts
new file mode 100644
index 00000000000..4d3e99def2b
--- /dev/null
+++ b/packages/cli/src/commands/knowledge/rebuild.ts
@@ -0,0 +1,106 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import { Args, Command, Flags } from '@oclif/core';
+import {
+ describeBuild,
+ resolveKnowledgeTarget,
+ runKnowledgeAction,
+ type KnowledgeBuildView,
+ type KnowledgeSourceView,
+} from '../../utils/knowledge-actions.js';
+
+/**
+ * `os knowledge rebuild ` — the administrator's rebuild of one
+ * knowledge source (ADR-0161 K7): one complete build, the same walk the
+ * server runs at boot for a source that was never built or needs a rebuild.
+ *
+ * Calls the `knowledge` settings namespace's `rebuild` action, which admits an
+ * administrator only and starts the build in the background on the node that
+ * answers; then, unless `--no-wait`, reads `index_status` every `--interval`
+ * seconds and prints the build's progress until it ends. Exits 0 when the
+ * build finished, 1 when it did not run or did not finish. With `--no-wait`
+ * it exits 0 once the build has started and reports no outcome: the build
+ * may still end `not-run` (another node holds the source's lock) or
+ * `failed`, which only `os knowledge status` then shows.
+ *
+ * A build sends the content fields of every row the source's `where` matches,
+ * except those the index already holds unchanged, to the embedding provider,
+ * which bills for them.
+ */
+export default class KnowledgeRebuild extends Command {
+ static override description =
+ 'Rebuild one knowledge source\'s index on the server and follow its progress (sends the source\'s content to the embedding provider, which bills for it)';
+
+ static override examples = [
+ '$ os knowledge rebuild support_articles',
+ '$ os knowledge rebuild support_articles --no-wait',
+ ];
+
+ static override args = {
+ source: Args.string({ description: 'The knowledge source id', required: true }),
+ };
+
+ static override flags = {
+ url: Flags.string({ char: 'u', description: 'Server URL', env: 'OS_CLOUD_URL' }),
+ token: Flags.string({ char: 't', description: 'Authentication token (an administrator\'s)', env: 'OS_TOKEN' }),
+ wait: Flags.boolean({
+ description:
+ 'Follow the build until it ends (--no-wait exits 0 once it has started and does not report its outcome: read it with os knowledge status)',
+ default: true,
+ allowNo: true,
+ }),
+ interval: Flags.integer({ description: 'Seconds between two progress reads', default: 2, min: 1 }),
+ };
+
+ async run(): Promise {
+ const { args, flags } = await this.parse(KnowledgeRebuild);
+ const target = resolveKnowledgeTarget(flags);
+ const started = await runKnowledgeAction(target, 'rebuild', { source: args.source });
+ if (!started.ok) {
+ this.error(started.message, { exit: 1 });
+ return;
+ }
+ if (started.message) this.log(started.message);
+ const startedBuild = started.details.build as KnowledgeBuildView | null | undefined;
+ if (!flags.wait) {
+ // Exit 0 here says "started", never "built": the build can still end
+ // not-run (another node holds the lock) or failed.
+ this.log('Not followed (--no-wait): the build may still not run or fail. Read its outcome with os knowledge status.');
+ return;
+ }
+ const startedAt = startedBuild?.startedAt;
+
+ let lastLine = '';
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, flags.interval * 1000));
+ const read = await runKnowledgeAction(target, 'index_status', { source: args.source });
+ if (!read.ok) {
+ this.error(`The build's progress could not be read: ${read.message}`, { exit: 1 });
+ return;
+ }
+ const entry = (Array.isArray(read.details.sources) ? (read.details.sources as KnowledgeSourceView[]) : [])[0];
+ const build = entry?.build ?? undefined;
+ if (!build || (startedAt !== undefined && build.startedAt !== startedAt)) {
+ this.error(
+ 'The progress was answered by a server node that is not running this build (behind a load balancer, ' +
+ 'another node may have taken the request). The build continues on the node that started it; read it there ' +
+ 'with os knowledge status.',
+ { exit: 1 },
+ );
+ return;
+ }
+ const line = describeBuild(build);
+ if (line !== lastLine) {
+ this.log(line);
+ lastLine = line;
+ }
+ if (build.status === 'running') continue;
+ if (build.status === 'done') {
+ if (build.message) this.log(build.message);
+ return;
+ }
+ this.error(build.message ?? `The build ended ${build.status ?? 'without a status'}.`, { exit: 1 });
+ return;
+ }
+ }
+}
diff --git a/packages/cli/src/commands/knowledge/status.ts b/packages/cli/src/commands/knowledge/status.ts
new file mode 100644
index 00000000000..ae853ab4f01
--- /dev/null
+++ b/packages/cli/src/commands/knowledge/status.ts
@@ -0,0 +1,61 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import { Args, Command, Flags } from '@oclif/core';
+import {
+ describeBuild,
+ resolveKnowledgeTarget,
+ runKnowledgeAction,
+ type KnowledgeSourceView,
+} from '../../utils/knowledge-actions.js';
+
+/**
+ * `os knowledge status [source]` — what each knowledge source's index holds
+ * against what the server expects of it, and the last build the answering
+ * node ran: its progress while it runs, its result once it ended.
+ *
+ * Calls the `knowledge` settings namespace's `index_status` action, which
+ * admits an administrator only. A build record lives on the node that ran
+ * the build: behind a load balancer, the node that answers may not be the one
+ * building; the index state it reads is the store's own.
+ */
+export default class KnowledgeStatus extends Command {
+ static override description =
+ 'Show each knowledge source\'s index state (built, never built, needs a rebuild) and the last build the server ran, with its progress or result';
+
+ static override examples = [
+ '$ os knowledge status',
+ '$ os knowledge status support_articles',
+ ];
+
+ static override args = {
+ source: Args.string({ description: 'The knowledge source id; every source when omitted', required: false }),
+ };
+
+ static override flags = {
+ url: Flags.string({ char: 'u', description: 'Server URL', env: 'OS_CLOUD_URL' }),
+ token: Flags.string({ char: 't', description: 'Authentication token (an administrator\'s)', env: 'OS_TOKEN' }),
+ };
+
+ async run(): Promise {
+ const { args, flags } = await this.parse(KnowledgeStatus);
+ const target = resolveKnowledgeTarget(flags);
+ const answer = await runKnowledgeAction(target, 'index_status', args.source ? { source: args.source } : {});
+ if (!answer.ok) {
+ this.error(answer.message, { exit: 1 });
+ return;
+ }
+ const sources = Array.isArray(answer.details.sources) ? (answer.details.sources as KnowledgeSourceView[]) : [];
+ if (sources.length === 0) {
+ this.log('No knowledge source is registered on this server.');
+ return;
+ }
+ for (const source of sources) {
+ this.log(`${source.id} (${source.label ?? source.id}; adapter ${source.adapter ?? '?'}, ${source.kind ?? '?'} source)`);
+ const index = source.index;
+ this.log(` index: ${index?.state ?? 'unknown'}${index?.due ? ' — a build is due' : ''}${index?.detail ? ` — ${index.detail}` : ''}`);
+ this.log(` last build on this node: ${source.build ? describeBuild(source.build) : 'none'}`);
+ const note = source.build?.message;
+ if (note) this.log(` ${note}`);
+ }
+ }
+}
diff --git a/packages/cli/src/utils/knowledge-actions.ts b/packages/cli/src/utils/knowledge-actions.ts
new file mode 100644
index 00000000000..c77eb5c02f7
--- /dev/null
+++ b/packages/cli/src/utils/knowledge-actions.ts
@@ -0,0 +1,105 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The client half of `os knowledge rebuild` and `os knowledge status`: the
+ * `knowledge` settings namespace's `rebuild` and `index_status` actions
+ * (`@objectstack/service-knowledge`, `knowledge-build-actions.ts`), reached
+ * through the settings action door, `POST /api/settings/knowledge/ACTION`,
+ * which admits an administrator only (`manage_platform_settings`).
+ *
+ * The shapes below are the fields these commands read of the action's
+ * `details`, not a copy of the service's types: the CLI does not depend on the
+ * knowledge service package, and a field the server stops sending reads as
+ * absent and is printed as such, never guessed.
+ */
+
+import { readEnvelopeFrom } from './response-envelope.js';
+
+/** Where the commands send their request. */
+export interface KnowledgeTarget {
+ url: string;
+ token?: string;
+}
+
+/** Resolve server URL + token from flags, then the environment (mirrors `createApiClient`). */
+export function resolveKnowledgeTarget(flags: { url?: string; token?: string }): KnowledgeTarget {
+ const url = (flags.url || process.env.OS_CLOUD_URL || 'http://localhost:3000').replace(/\/+$/, '');
+ const token = flags.token || process.env.OS_TOKEN;
+ return { url, ...(token ? { token } : {}) };
+}
+
+/** A build's progress, as the server reports it. */
+export interface KnowledgeBuildProgressView {
+ pages?: number;
+ discovered?: number;
+ indexed?: number;
+ skipped?: number;
+ failed?: number;
+}
+
+/** A build record, as the server reports it. */
+export interface KnowledgeBuildView {
+ trigger?: string;
+ status?: 'running' | 'done' | 'failed' | 'not-run';
+ startedAt?: string;
+ finishedAt?: string;
+ progress?: KnowledgeBuildProgressView;
+ result?: { ok?: boolean; discovered?: number; indexed?: number; skipped?: number; purged?: number | null; failed?: number; message?: string };
+ message?: string;
+}
+
+/** One source of an `index_status` answer. */
+export interface KnowledgeSourceView {
+ id: string;
+ label?: string;
+ adapter?: string;
+ kind?: string;
+ index?: { state?: string; due?: boolean; detail?: string };
+ build?: KnowledgeBuildView | null;
+}
+
+/** What one action answered: its result, or the server's refusal text. */
+export type KnowledgeActionAnswer =
+ | { ok: true; message?: string; details: Record }
+ | { ok: false; message: string };
+
+/** Run one `knowledge` settings action. */
+export async function runKnowledgeAction(
+ target: KnowledgeTarget,
+ action: 'rebuild' | 'index_status',
+ payload: Record,
+): Promise {
+ let res: Response;
+ try {
+ res = await fetch(`${target.url}/api/settings/knowledge/${action}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(target.token ? { authorization: `Bearer ${target.token}` } : {}),
+ },
+ body: JSON.stringify(payload),
+ });
+ } catch (err) {
+ return { ok: false, message: `The server at ${target.url} could not be reached (${err instanceof Error ? err.message : String(err)}).` };
+ }
+ const envelope = await readEnvelopeFrom<{ ok?: boolean; message?: string; details?: unknown }>(res);
+ if (!envelope.ok) return { ok: false, message: envelope.message };
+ const details = envelope.data.details;
+ return {
+ ok: true,
+ ...(typeof envelope.data.message === 'string' ? { message: envelope.data.message } : {}),
+ details: typeof details === 'object' && details !== null ? (details as Record) : {},
+ };
+}
+
+/** One line of a build's counts. */
+export function describeBuild(build: KnowledgeBuildView): string {
+ const p = build.progress ?? {};
+ const purged = build.result?.purged;
+ const purgedPart = build.status === 'running' ? '' : `${purged === undefined || purged === null ? 'none' : purged} purged, `;
+ const counts =
+ `${p.discovered ?? 0} row(s) read, ${p.indexed ?? 0} written, ${p.skipped ?? 0} unchanged, ` +
+ `${purgedPart}${p.failed ?? 0} cannot be indexed`;
+ const when = build.status === 'running' ? `started ${build.startedAt ?? '?'}` : `ended ${build.finishedAt ?? '?'}`;
+ return `${build.status ?? 'unknown'} (${build.trigger ?? '?'}, ${when}): ${counts}`;
+}
diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts
new file mode 100644
index 00000000000..c1fa414b8d0
--- /dev/null
+++ b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts
@@ -0,0 +1,535 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The first build of a source and the operator's rebuild (ADR-0161 K7, "What
+ * starts a rebuild"; `knowledge-build.ts`, `knowledge-build-actions.ts`).
+ *
+ * - `readIndexState` reads each state of K7's table from what the adapter
+ * holds, against the fingerprint and recipe hash the service computes.
+ * - `buildSourcesAtBoot` builds a never-built source, so a search finds its
+ * rows with no manual step; leaves a built one alone; and two nodes sharing
+ * a cluster lock build it once.
+ * - The `rebuild` and `index_status` settings actions start a build and
+ * report its progress and result.
+ * - `KnowledgeServicePlugin` runs the boot pass at `kernel:bootstrapped`, in
+ * the background, unless `buildAtBoot: false`.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+import type {
+ AdapterContext,
+ AdapterEmbeddingDescriptor,
+ AdapterIndexStatus,
+ IDataEngine,
+ IKnowledgeAdapter,
+} from '@objectstack/spec/contracts';
+import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource } from '@objectstack/spec/ai';
+import { KnowledgeService } from '../knowledge-service.js';
+import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
+import { buildLockKey, type KnowledgeBuildLock, type KnowledgeBuildLockHandle } from '../knowledge-build.js';
+import { knowledgeIndexStatusActionHandler, knowledgeRebuildActionHandler } from '../knowledge-build-actions.js';
+import type { KnowledgeIndexStatusEntry } from '../knowledge-build-actions.js';
+
+type Row = Record;
+
+const SYSTEM = { executionContext: { positions: [], permissions: [], systemPermissions: [], isSystem: true } };
+
+/** Rows of one object; `find` applies scalar equality, `$and` and `id: { $gt }`, ordered by id. */
+function makeEngine(initial: Row[]) {
+ const rows = new Map(initial.map((r) => [String(r.id), { ...r }]));
+ const matches = (row: Row, where: Record | undefined): boolean => {
+ if (!where) return true;
+ for (const [key, value] of Object.entries(where)) {
+ if (key === '$and') {
+ if (!(value as Array>).every((c) => matches(row, c))) return false;
+ continue;
+ }
+ if (value !== null && typeof value === 'object') {
+ const gt = (value as { $gt?: unknown }).$gt;
+ if (gt === undefined) throw new Error(`engine double: condition on '${key}' is not implemented`);
+ if (!(String(row[key]) > String(gt))) return false;
+ continue;
+ }
+ if (row[key] !== value) return false;
+ }
+ return true;
+ };
+ const select = (where?: Record) =>
+ [...rows.values()].filter((r) => matches(r, where)).sort((a, b) => String(a.id).localeCompare(String(b.id)));
+ const find = vi.fn(async (_object: string, query?: { where?: Record; limit?: number }) => {
+ const all = select(query?.where);
+ return (typeof query?.limit === 'number' ? all.slice(0, query.limit) : all).map((r) => ({ ...r }));
+ });
+ const count = vi.fn(async (_object: string, query?: { where?: Record }) => select(query?.where).length);
+ return { rows, find, engine: { find, count } as unknown as IDataEngine };
+}
+
+/**
+ * An adapter that keeps one generation per source, the way K7 describes: it
+ * holds nothing until a write or `beginBuild`, and `completeBuild` records the
+ * fingerprint and recipe hash. `members` drops the optional members a case
+ * wants absent.
+ */
+function makeAdapter(opts: { embedding?: AdapterEmbeddingDescriptor; omit?: Array<'indexStatus' | 'listDocuments' | 'completeBuild' | 'beginBuild'> } = {}) {
+ const docs = new Map();
+ const held: { fingerprint?: string; recipeHash?: string } = {};
+ const calls = { beginBuild: 0, completeBuild: 0, upserted: 0 };
+ const adapter: IKnowledgeAdapter = {
+ id: 'memory',
+ embedding: opts.embedding ?? { model: 'model-a', dimensions: 3 },
+ async upsert(batch: KnowledgeDocument[], ctx: AdapterContext) {
+ for (const doc of batch) docs.set(doc.id, doc);
+ calls.upserted += batch.length;
+ if (held.fingerprint === undefined && ctx.index) held.fingerprint = ctx.index.fingerprint;
+ },
+ async delete(ids: string[]) {
+ for (const id of ids) docs.delete(id);
+ },
+ async search(query: string): Promise {
+ return [...docs.values()]
+ .filter((doc) => doc.content.includes(query))
+ .map((doc) => ({
+ chunkId: doc.id,
+ documentId: doc.id,
+ sourceId: doc.sourceId,
+ sourceRecordId: doc.sourceRecordId,
+ score: 1,
+ snippet: doc.content,
+ }));
+ },
+ async listDocuments(_ctx: AdapterContext, page: { cursor?: string; limit: number }) {
+ const all = [...docs.values()].map((d) => ({ documentId: d.id, ...(d.docHash ? { docHash: d.docHash } : {}) }));
+ const start = page.cursor === undefined ? 0 : Number(page.cursor);
+ const slice = all.slice(start, start + page.limit);
+ return { documents: slice, ...(start + page.limit < all.length ? { nextCursor: String(start + page.limit) } : {}) };
+ },
+ async indexStatus(): Promise {
+ return { ...held };
+ },
+ async beginBuild(ctx: AdapterContext) {
+ calls.beginBuild += 1;
+ if (held.fingerprint !== ctx.index!.fingerprint) {
+ docs.clear();
+ held.fingerprint = ctx.index!.fingerprint;
+ delete held.recipeHash;
+ }
+ },
+ async completeBuild(ctx: AdapterContext) {
+ calls.completeBuild += 1;
+ held.fingerprint = ctx.index!.fingerprint;
+ held.recipeHash = ctx.index!.recipeHash;
+ },
+ };
+ for (const member of opts.omit ?? []) delete (adapter as unknown as Record)[member];
+ return { adapter, docs, held, calls };
+}
+
+function source(overrides: Partial = {}, where?: Record): KnowledgeSource {
+ return {
+ id: 'kb',
+ label: 'Knowledge base',
+ adapter: 'memory',
+ source: { kind: 'object', object: 'kb_article', contentFields: ['title', 'body'], ...(where ? { where } : {}) },
+ ...overrides,
+ };
+}
+
+const ROWS: Row[] = [
+ { id: 'a1', title: 'Leave policy', body: 'Twenty days of paid leave' },
+ { id: 'a2', title: 'Travel policy', body: 'Economy class under six hours' },
+ { id: 'a3', title: 'Expense policy', body: 'Receipts within thirty days' },
+];
+
+function makeLogger() {
+ return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
+}
+
+function makeService(engine: IDataEngine | undefined, adapter: IKnowledgeAdapter, extra: { lock?: KnowledgeBuildLock; logger?: ReturnType } = {}) {
+ const logger = extra.logger ?? makeLogger();
+ const service = new KnowledgeService({
+ dataEngine: engine,
+ logger,
+ ...(extra.lock ? { resolveBuildLock: () => extra.lock } : {}),
+ });
+ service.registerAdapter('memory', adapter);
+ return { service, logger };
+}
+
+/** A cluster lock shared by every "node" of a test: one holder per key, no wait. */
+function makeSharedLock() {
+ const held = new Set();
+ const asked: string[] = [];
+ const lock: KnowledgeBuildLock = {
+ async acquire(key: string): Promise {
+ asked.push(key);
+ if (held.has(key)) return null;
+ held.add(key);
+ let mine = true;
+ return {
+ async release() { if (mine) { mine = false; held.delete(key); } },
+ async renew() { if (!mine) throw new Error('lease lost'); },
+ isHeld: () => mine,
+ };
+ },
+ };
+ return { lock, held, asked };
+}
+
+describe('readIndexState — the states of ADR-0161 K7 "What starts a rebuild"', () => {
+ it('a source the adapter holds nothing for is due, and current once built', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+
+ const before = await service.readIndexState('kb');
+ expect(before).toMatchObject({ sourceId: 'kb', state: 'nothing', due: true });
+
+ const record = await service.rebuildSource('kb', { trigger: 'operator' });
+ expect(record.status).toBe('done');
+
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'current', due: false });
+ });
+
+ it('another embedding model is a new fingerprint, and is due', async () => {
+ const db = makeEngine(ROWS);
+ const embedding: AdapterEmbeddingDescriptor = { model: 'model-a', dimensions: 3 };
+ const { adapter } = makeAdapter({ embedding });
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ await service.rebuildSource('kb', { trigger: 'operator' });
+
+ embedding.model = 'model-b';
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'new-fingerprint', due: true });
+ });
+
+ it("a changed recipe (the source's where) under the same fingerprint is due", async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ await service.rebuildSource('kb', { trigger: 'operator' });
+
+ service.registerSource(source({}, { title: 'Leave policy' }));
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'recipe-changed', due: true });
+ });
+
+ it('no recorded recipe hash is due when the adapter can record one, and is not when it cannot', async () => {
+ const db = makeEngine(ROWS);
+ const withComplete = makeAdapter();
+ const a = makeService(db.engine, withComplete.adapter);
+ a.service.registerSource(source());
+ await a.service.reindexSource('kb', { limit: 1 }); // a partial walk: writes, records nothing
+ expect(withComplete.held.recipeHash).toBeUndefined();
+ expect(await a.service.readIndexState('kb')).toMatchObject({ state: 'no-recipe-hash', due: true });
+
+ const without = makeAdapter({ omit: ['completeBuild'] });
+ const b = makeService(db.engine, without.adapter);
+ b.service.registerSource(source());
+ await b.service.reindexSource('kb', { limit: 1 });
+ const reading = await b.service.readIndexState('kb');
+ expect(reading).toMatchObject({ state: 'no-recipe-hash', due: false });
+ });
+
+ it('without indexStatus, an empty listing is due and a non-empty one is not', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter({ omit: ['indexStatus'] });
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'listed-empty', due: true });
+ await service.rebuildSource('kb', { trigger: 'operator' });
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'listed-documents', due: false });
+ });
+
+ it('with neither indexStatus nor listDocuments nothing is due, and the operator rebuild is named', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter({ omit: ['indexStatus', 'listDocuments'] });
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ const reading = await service.readIndexState('kb');
+ expect(reading).toMatchObject({ state: 'unknown', due: false });
+ expect(reading.detail).toContain('os knowledge rebuild');
+ });
+
+ it('a failed read is unreadable and not due; a file source is not built here', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ adapter.indexStatus = async () => { throw new Error('store offline'); };
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ service.registerSource({ id: 'files', label: 'Files', adapter: 'memory', source: { kind: 'file', paths: ['docs/*.md'] } } as unknown as KnowledgeSource);
+
+ const reading = await service.readIndexState('kb');
+ expect(reading).toMatchObject({ state: 'unreadable', due: false });
+ expect(reading.detail).toContain('store offline');
+ expect(await service.readIndexState('files')).toMatchObject({ state: 'not-built-here', due: false });
+ });
+
+ it('a first build that opened a generation and never completed it reads as nothing built, not another fingerprint', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ // What a store answers after a builder crashed inside its first build:
+ // a generation under construction, and no active one.
+ adapter.indexStatus = async () => ({ building: true });
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+
+ expect(await service.readIndexState('kb')).toMatchObject({ state: 'nothing', due: true, held: { building: true } });
+ });
+});
+
+describe('buildSourcesAtBoot — the first build', () => {
+ it('resolves, and says so at warn, when the sources cannot even be listed', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const { service, logger } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ vi.spyOn(service, 'listSources').mockImplementation(() => { throw new Error('registry torn down'); });
+
+ await expect(service.buildSourcesAtBoot()).resolves.toBeUndefined();
+ expect(calls.upserted).toBe(0);
+ expect(logger.warn.mock.calls.map((c) => String(c[0])).some((l) => l.includes('registry torn down'))).toBe(true);
+ });
+
+ it('a fresh deployment with one source and existing rows: after the boot pass, search finds them', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const { service, logger } = makeService(db.engine, adapter);
+ service.registerSource(source());
+
+ expect(await service.search('Twenty days', SYSTEM)).toHaveLength(0);
+ await service.buildSourcesAtBoot();
+
+ const hits = await service.search('Twenty days', SYSTEM);
+ expect(hits.map((h) => h.sourceRecordId)).toEqual(['a1']);
+ expect(calls).toMatchObject({ beginBuild: 1, completeBuild: 1, upserted: 3 });
+ expect(service.buildRecord('kb')).toMatchObject({
+ trigger: 'boot',
+ status: 'done',
+ progress: { discovered: 3, indexed: 3, skipped: 0, failed: 0 },
+ result: { ok: true, discovered: 3, indexed: 3 },
+ });
+ // The start line states the cost.
+ const lines = logger.info.mock.calls.map((c) => String(c[0]));
+ expect(lines.some((l) => l.includes("build of source 'kb' (boot) started") && l.includes('embedding provider'))).toBe(true);
+ expect(lines.some((l) => l.includes("build of source 'kb' (boot) finished"))).toBe(true);
+ });
+
+ it('a source already built is not rebuilt at the next boot', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const first = makeService(db.engine, adapter);
+ first.service.registerSource(source());
+ await first.service.buildSourcesAtBoot();
+ expect(calls.beginBuild).toBe(1);
+
+ // The next boot: a new service over the same store.
+ const second = makeService(db.engine, adapter);
+ second.service.registerSource(source());
+ await second.service.buildSourcesAtBoot();
+ expect(calls).toMatchObject({ beginBuild: 1, completeBuild: 1, upserted: 3 });
+ expect(second.service.buildRecord('kb')).toBeUndefined();
+ });
+
+ it('two nodes booting together over one store and one cluster lock build the source once', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const shared = makeSharedLock();
+ const nodeA = makeService(db.engine, adapter, { lock: shared.lock });
+ const nodeB = makeService(db.engine, adapter, { lock: shared.lock });
+ nodeA.service.registerSource(source());
+ nodeB.service.registerSource(source());
+
+ await Promise.all([nodeA.service.buildSourcesAtBoot(), nodeB.service.buildSourcesAtBoot()]);
+
+ expect(calls).toMatchObject({ beginBuild: 1, completeBuild: 1, upserted: 3 });
+ const statuses = [nodeA.service.buildRecord('kb')?.status, nodeB.service.buildRecord('kb')?.status].sort();
+ expect(statuses).toEqual(['done', 'not-run']);
+ expect(shared.asked.every((k) => k === buildLockKey('kb'))).toBe(true);
+ expect(shared.held.size).toBe(0); // released
+ });
+
+ it('a node that takes the lock after another finished re-reads the store and builds nothing', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const shared = makeSharedLock();
+ const nodeA = makeService(db.engine, adapter, { lock: shared.lock });
+ const nodeB = makeService(db.engine, adapter, { lock: shared.lock });
+ nodeA.service.registerSource(source());
+ nodeB.service.registerSource(source());
+
+ await nodeA.service.rebuildSource('kb', { trigger: 'boot' });
+ const late = await nodeB.service.rebuildSource('kb', { trigger: 'boot' });
+ expect(late).toMatchObject({ status: 'not-run' });
+ expect(late.message).toContain('nothing to build');
+ expect(calls.beginBuild).toBe(1);
+ });
+
+ it('a cluster lock that does not answer starts no build, and says so', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const lock: KnowledgeBuildLock = { acquire: async () => { throw new Error('redis unreachable'); } };
+ const { service, logger } = makeService(db.engine, adapter, { lock });
+ service.registerSource(source());
+
+ await service.buildSourcesAtBoot();
+ expect(calls.upserted).toBe(0);
+ expect(service.buildRecord('kb')).toMatchObject({ status: 'not-run' });
+ expect(logger.warn.mock.calls.map((c) => String(c[0])).some((l) => l.includes('redis unreachable'))).toBe(true);
+ });
+
+ it('a source with refresh.onRecordChange: false is left to its external indexer', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source({ refresh: { onRecordChange: false } }));
+ await service.buildSourcesAtBoot();
+ expect(calls.upserted).toBe(0);
+ expect(service.buildRecord('kb')).toBeUndefined();
+ });
+
+ it('a build that does not finish is failed, logged at warn, and leaves the source due', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ adapter.upsert = async () => { throw new Error('provider quota exceeded'); };
+ const { service, logger } = makeService(db.engine, adapter);
+ service.registerSource(source());
+
+ await service.buildSourcesAtBoot();
+ expect(service.buildRecord('kb')).toMatchObject({ status: 'failed', result: { ok: false } });
+ expect(logger.warn.mock.calls.map((c) => String(c[0])).some((l) => l.includes('did not finish') && l.includes('provider quota exceeded'))).toBe(true);
+ expect(await service.readIndexState('kb')).toMatchObject({ due: true });
+ });
+});
+
+describe('the rebuild and index_status settings actions', () => {
+ const run = (handler: ReturnType, payload: unknown) =>
+ handler({ namespace: 'knowledge', actionId: 'x', values: {}, payload, ctx: {} });
+
+ it('rebuild starts a build of the named source; index_status reports its progress and result', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ const rebuild = knowledgeRebuildActionHandler(service);
+ const status = knowledgeIndexStatusActionHandler(service);
+
+ const before = await run(status, {});
+ const beforeEntry = (before.details as { sources: KnowledgeIndexStatusEntry[] }).sources[0];
+ expect(beforeEntry).toMatchObject({ id: 'kb', index: { state: 'nothing', due: true }, build: null });
+
+ const started = await run(rebuild, { source: 'kb' });
+ expect(started).toMatchObject({ ok: true, details: { source: 'kb', build: { trigger: 'operator', status: 'running' } } });
+ expect(started.message).toContain('embedding provider');
+
+ await vi.waitFor(() => expect(service.buildRecord('kb')?.status).toBe('done'));
+ const after = await run(status, { source: 'kb' });
+ const entry = (after.details as { sources: KnowledgeIndexStatusEntry[] }).sources[0];
+ expect(entry).toMatchObject({
+ index: { state: 'current', due: false },
+ build: { status: 'done', progress: { discovered: 3, indexed: 3 }, result: { ok: true, indexed: 3 } },
+ });
+ });
+
+ it('an operator rebuild walks a current source again, and skips what is unchanged', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ await service.rebuildSource('kb', { trigger: 'operator' });
+ const again = await service.rebuildSource('kb', { trigger: 'operator' });
+ expect(again).toMatchObject({ status: 'done', result: { discovered: 3, indexed: 0, skipped: 3 } });
+ expect(calls.beginBuild).toBe(2);
+ });
+
+ it('a build already running on this node is refused, not doubled', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter } = makeAdapter();
+ let release!: () => void;
+ const gate = new Promise((resolve) => { release = resolve; });
+ const upsert = adapter.upsert.bind(adapter);
+ adapter.upsert = async (docs, ctx) => { await gate; return upsert(docs, ctx); };
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ const rebuild = knowledgeRebuildActionHandler(service);
+
+ expect(await run(rebuild, { source: 'kb' })).toMatchObject({ ok: true });
+ const second = await run(rebuild, { source: 'kb' });
+ expect(second).toMatchObject({ ok: false, severity: 'warning' });
+ expect(second.message).toContain('already running');
+ release();
+ await vi.waitFor(() => expect(service.buildRecord('kb')?.status).toBe('done'));
+ });
+
+ it('refuses a payload key other than source, a missing source, an unknown one and a file source', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const { service } = makeService(db.engine, adapter);
+ service.registerSource(source());
+ service.registerSource({ id: 'files', label: 'Files', adapter: 'memory', source: { kind: 'file', paths: ['docs/*.md'] } } as unknown as KnowledgeSource);
+ const rebuild = knowledgeRebuildActionHandler(service);
+ const status = knowledgeIndexStatusActionHandler(service);
+
+ const misspelt = await run(rebuild, { sources: 'kb' });
+ expect(misspelt).toMatchObject({ ok: false });
+ expect(misspelt.message).toContain('sources');
+ expect(await run(status, { sourceId: 'kb' })).toMatchObject({ ok: false });
+ expect(await run(rebuild, {})).toMatchObject({ ok: false });
+ expect(await run(rebuild, { source: 'nope' })).toMatchObject({ ok: false });
+ expect(await run(status, { source: 'nope' })).toMatchObject({ ok: false });
+ expect(await run(rebuild, { source: 'files' })).toMatchObject({ ok: false });
+ expect(calls.upserted).toBe(0);
+ });
+});
+
+describe('KnowledgeServicePlugin — the boot pass', () => {
+ function makeCtx(engine: IDataEngine, adapter: IKnowledgeAdapter) {
+ const hooks = new Map Promise>>();
+ let service: KnowledgeService | undefined;
+ const ctx: any = {
+ logger: makeLogger(),
+ hook: (name: string, fn: () => Promise) => {
+ hooks.set(name, [...(hooks.get(name) ?? []), fn]);
+ },
+ registerService: (name: string, svc: unknown) => {
+ if (name === 'knowledge') service = svc as KnowledgeService;
+ },
+ getService: (name: string) => {
+ if (name === 'objectql') return engine;
+ if (name === 'embedder') return { id: 'test-embedder' };
+ throw new Error(`[Kernel] Service '${name}' not found`);
+ },
+ };
+ return {
+ ctx,
+ async boot(plugin: KnowledgeServicePlugin) {
+ await plugin.init(ctx);
+ service!.registerAdapter('memory', adapter);
+ await plugin.start(ctx);
+ for (const fn of hooks.get('kernel:ready') ?? []) await fn();
+ for (const fn of hooks.get('kernel:bootstrapped') ?? []) await fn();
+ return service!;
+ },
+ };
+ }
+
+ it('builds a never-built source after kernel:bootstrapped, without holding the boot', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const harness = makeCtx(db.engine, adapter);
+ const service = await harness.boot(new KnowledgeServicePlugin({ sources: [source()], enableEventSync: false }));
+ await vi.waitFor(() => expect(service.buildRecord('kb')?.status).toBe('done'));
+ expect(calls.upserted).toBe(3);
+ expect((await service.search('Receipts', SYSTEM)).map((h) => h.sourceRecordId)).toEqual(['a3']);
+ });
+
+ it('buildAtBoot: false builds nothing', async () => {
+ const db = makeEngine(ROWS);
+ const { adapter, calls } = makeAdapter();
+ const harness = makeCtx(db.engine, adapter);
+ const service = await harness.boot(new KnowledgeServicePlugin({ sources: [source()], enableEventSync: false, buildAtBoot: false }));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(calls.upserted).toBe(0);
+ expect(service.buildRecord('kb')).toBeUndefined();
+ });
+});
diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts
index c99ffc41279..590bf432bb0 100644
--- a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts
+++ b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts
@@ -24,6 +24,7 @@ import type { Plugin, PluginContext } from '@objectstack/core';
import { ObjectQL } from '@objectstack/objectql';
import { SETUP_APP, SETUP_NAV_CONTRIBUTIONS } from '@objectstack/platform-objects';
import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
+import type { KnowledgeSource } from '@objectstack/spec/ai';
import type {
IEmbedder,
IHttpRequest,
@@ -205,6 +206,102 @@ describe('[#24769] the two buttons the knowledge service contributes, at the HTT
});
});
+/**
+ * The rebuild entry is an administrator's (ADR-0161 K7, the operator's
+ * rebuild). `rebuild` spends money (it sends a source's content to the
+ * embedding provider) and `index_status` names every source, so both are
+ * refused at the settings action door to any caller without
+ * `manage_platform_settings`, before either handler runs. The gate is not in
+ * this package: it is the `knowledge` manifest's `writePermission`
+ * (`@objectstack/service-settings`), which `SettingsService.runAction` checks
+ * before the handler lookup. These pins drive that real path, so relaxing the
+ * manifest's permission turns them red.
+ */
+describe('the rebuild and index_status actions are administrator-only, at the HTTP door', async () => {
+ // A distinctive source: its id and label must appear in no refusal.
+ const SECRET_SOURCE: KnowledgeSource = {
+ id: 'board_minutes_private',
+ label: 'Board minutes (private)',
+ adapter: 'memory',
+ source: { kind: 'object', object: 'board_minute', contentFields: ['body'] },
+ } as KnowledgeSource;
+ const kernel = new LiteKernel();
+ kernel.use(new FakeManifestPlugin([]));
+ kernel.use(new KnowledgeServicePlugin({ enableEventSync: false, buildAtBoot: false, sources: [SECRET_SOURCE] }));
+ kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false }));
+ await kernel.bootstrap();
+ const settings = kernel.getService('settings');
+ const knowledge = kernel.getService('knowledge');
+
+ const callers = {
+ admin: () => ({ enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }),
+ // An organization member who may read Setup but holds no platform capability.
+ member: () => ({ enforced: true, permissions: ['setup.read', 'setup.write'], userId: 'usr_member' }),
+ // Signed in, no capability at all.
+ bare: () => ({ enforced: true, permissions: [] as string[], userId: 'usr_bare' }),
+ // Not signed in: refused before any manifest is read.
+ anonymous: () => ({ enforced: true, permissions: [] as string[] }),
+ };
+ const door = (who: keyof typeof callers) => {
+ const http = new MockHttp();
+ registerSettingsRoutes(http, settings, { contextFromRequest: callers[who] });
+ return http;
+ };
+ /** Every method the two handlers can call on the service, watched. */
+ const watchService = () =>
+ (['listSources', 'getSource', 'readIndexState', 'rebuildSource', 'buildRecord'] as const).map((m) => vi.spyOn(knowledge, m));
+ afterEach(() => { vi.restoreAllMocks(); });
+
+ it.each([
+ ['member', 'rebuild', { source: SECRET_SOURCE.id }],
+ ['member', 'rebuild', {}],
+ ['member', 'index_status', {}],
+ ['member', 'index_status', { source: SECRET_SOURCE.id }],
+ ['bare', 'rebuild', { source: SECRET_SOURCE.id }],
+ ['bare', 'index_status', {}],
+ ['anonymous', 'rebuild', { source: SECRET_SOURCE.id }],
+ ['anonymous', 'index_status', {}],
+ ] as const)('a %s caller of %s %j is refused, names no source, and reaches no handler', async (who, action, body) => {
+ const watched = watchService();
+ const answer = await post(door(who), 'knowledge', action, body);
+
+ if (who === 'anonymous') {
+ expect(answer.status).toBe(401);
+ expect(answer.body?.error?.code).toBe('UNAUTHENTICATED');
+ } else {
+ expect(answer.status).toBe(403);
+ expect(answer.body?.error?.code).toBe('SETTINGS_FORBIDDEN');
+ }
+ // The refusal names the namespace, never a source the caller may not see.
+ const text = JSON.stringify(answer.body);
+ expect(text).not.toContain(SECRET_SOURCE.id);
+ expect(text).not.toContain(SECRET_SOURCE.label);
+ for (const spy of watched) expect(spy, spy.getMockName()).not.toHaveBeenCalled();
+ });
+
+ it('control: the same door lets an administrator through, and then the source is named', async () => {
+ // Without this, "names no source" above could hold because no answer ever names one.
+ const watched = watchService();
+ const status = await post(door('admin'), 'knowledge', 'index_status', {});
+ expect(status.status).toBe(200);
+ expect(JSON.stringify(status.body)).toContain(SECRET_SOURCE.id);
+
+ // `rebuild` without a source is answered by the handler itself, which lists the ids.
+ const unnamed = await post(door('admin'), 'knowledge', 'rebuild', {});
+ expect(unnamed.status).toBe(400);
+ expect(unnamed.body?.error?.code).toBe('SETTINGS_ACTION_FAILED');
+ expect(JSON.stringify(unnamed.body)).toContain(SECRET_SOURCE.id);
+ expect(watched.some((spy) => spy.mock.calls.length > 0)).toBe(true);
+ });
+
+ it('in process, an enforced caller without the capability is refused by runAction itself', async () => {
+ for (const action of ['rebuild', 'index_status']) {
+ await expect(settings.runAction('knowledge', action, { source: SECRET_SOURCE.id }, callers.member()))
+ .rejects.toMatchObject({ code: 'SETTINGS_FORBIDDEN', namespace: 'knowledge', required: 'manage_platform_settings' });
+ }
+ });
+});
+
// ── The embedder the ai.embedder_* settings configure (#37094) ─────────────
//
// Booted the way a deployment boots: the settings are SAVED through the
diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts
index c7c67ea8e9a..a2419dad168 100644
--- a/packages/services/service-knowledge/src/index.ts
+++ b/packages/services/service-knowledge/src/index.ts
@@ -34,6 +34,27 @@ export type {
SearchKnowledgeSourceSummary,
} from './knowledge-tools.js';
export type { KnowledgeFieldSecurity } from './knowledge-source-admission.js';
+export {
+ BUILD_LEASE_MS,
+ BUILD_PROGRESS_LOG_INTERVAL_MS,
+ buildLockKey,
+} from './knowledge-build.js';
+export type {
+ KnowledgeBuildLock,
+ KnowledgeBuildLockHandle,
+ KnowledgeBuildProgress,
+ KnowledgeBuildRecord,
+ KnowledgeBuildTrigger,
+ KnowledgeIndexReading,
+ KnowledgeIndexState,
+} from './knowledge-build.js';
+export {
+ KNOWLEDGE_INDEX_STATUS_ACTION,
+ KNOWLEDGE_REBUILD_ACTION,
+ knowledgeIndexStatusActionHandler,
+ knowledgeRebuildActionHandler,
+} from './knowledge-build-actions.js';
+export type { KnowledgeIndexStatusEntry } from './knowledge-build-actions.js';
export { KnowledgeServicePlugin } from './knowledge-service-plugin.js';
export type { KnowledgeServicePluginOptions } from './knowledge-service-plugin.js';
export {
diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts
new file mode 100644
index 00000000000..931d8fc35ca
--- /dev/null
+++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts
@@ -0,0 +1,164 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The administrator's rebuild entry (ADR-0161 K7, "What starts a rebuild":
+ * the operator's rebuild), on the `knowledge` settings namespace beside its
+ * `test` action:
+ *
+ * - `rebuild` — payload `{ "source": "ID" }`. Starts one complete build of
+ * that source (`KnowledgeService.rebuildSource`, trigger `operator`) in the
+ * background and answers at once with the build's record; a build of the
+ * source already running on the node that answers is refused, not doubled.
+ * - `index_status` — payload `{}` or `{ "source": "ID" }`. Answers, per
+ * source, what its adapter holds against what the service expects
+ * (`readIndexState`) and the last build this node ran (`buildRecord`):
+ * its progress while it runs, its result once it ended.
+ *
+ * Both run through the settings action door (`POST /api/settings/knowledge/ACTION`),
+ * which gates an HTTP caller on the namespace's write permission,
+ * `manage_platform_settings`: an administrator's. `os knowledge rebuild` and
+ * `os knowledge status` are their command-line callers.
+ *
+ * A payload key other than `source` is refused, so a misspelt key is never
+ * read as "every source". A build record lives on the node that ran the
+ * build; behind a load balancer `index_status` answers for the node that
+ * took the request, while the adapter's state it reads is the store's own.
+ */
+
+import type { SettingsActionHandler } from '@objectstack/service-settings';
+import type { KnowledgeSource } from '@objectstack/spec/ai';
+import type { KnowledgeBuildRecord, KnowledgeIndexReading } from './knowledge-build.js';
+import type { KnowledgeService } from './knowledge-service.js';
+
+/** The `knowledge` settings action that starts a rebuild of one source. */
+export const KNOWLEDGE_REBUILD_ACTION = 'rebuild';
+
+/** The `knowledge` settings action that reads each source's index state and last build. */
+export const KNOWLEDGE_INDEX_STATUS_ACTION = 'index_status';
+
+/** The part of `KnowledgeService` the two actions use. */
+export type KnowledgeBuildActionsService = Pick<
+ KnowledgeService,
+ 'listSources' | 'getSource' | 'readIndexState' | 'rebuildSource' | 'buildRecord'
+>;
+
+/** One source in an `index_status` answer. */
+export interface KnowledgeIndexStatusEntry {
+ id: string;
+ label: string;
+ adapter: string;
+ kind: KnowledgeSource['source']['kind'];
+ /** What the adapter holds against what the service expects. */
+ index: KnowledgeIndexReading;
+ /** The last build this node ran of the source, or `null`. */
+ build: KnowledgeBuildRecord | null;
+}
+
+/** The payload keys both actions read. */
+const PAYLOAD_KEYS: ReadonlySet = new Set(['source']);
+
+/** `{ source? }` from an action payload, or why the payload is refused. */
+function readSourcePayload(payload: unknown): { source?: string } | { refused: string } {
+ if (payload === undefined || payload === null) return {};
+ if (typeof payload !== 'object' || Array.isArray(payload)) {
+ return { refused: 'The payload must be an object: { "source": "ID" }.' };
+ }
+ const unknown = Object.keys(payload).filter((key) => !PAYLOAD_KEYS.has(key));
+ if (unknown.length > 0) {
+ return { refused: `Unknown payload key(s): ${unknown.join(', ')}. The only key is "source".` };
+ }
+ const source = (payload as { source?: unknown }).source;
+ if (source === undefined) return {};
+ if (typeof source !== 'string' || source.trim() === '') {
+ return { refused: '"source" must be a source id: a non-empty string.' };
+ }
+ return { source: source.trim() };
+}
+
+function sourceIds(service: KnowledgeBuildActionsService): string {
+ const ids = service.listSources().map((s) => s.id);
+ return ids.length === 0 ? 'none is registered' : ids.join(', ');
+}
+
+/** The `rebuild` action, bound to `service`. */
+export function knowledgeRebuildActionHandler(service: KnowledgeBuildActionsService): SettingsActionHandler {
+ return async ({ payload }) => {
+ const read = readSourcePayload(payload);
+ if ('refused' in read) return { ok: false, severity: 'error', message: read.refused };
+ if (read.source === undefined) {
+ return { ok: false, severity: 'error', message: `Name the source to rebuild: { "source": "ID" } (${sourceIds(service)}).` };
+ }
+ const source = service.getSource(read.source);
+ if (!source) {
+ return { ok: false, severity: 'error', message: `No knowledge source '${read.source}' is registered (${sourceIds(service)}).` };
+ }
+ if (source.source.kind !== 'object') {
+ return {
+ ok: false,
+ severity: 'error',
+ message: `Source '${source.id}' is a ${source.source.kind} source: its adapter (${source.adapter}) ingests it, and the knowledge service does not build it.`,
+ };
+ }
+ const running = service.buildRecord(source.id);
+ if (running?.status === 'running') {
+ return {
+ ok: false,
+ severity: 'warning',
+ message:
+ `A build of source '${source.id}' is already running on this node (started ${running.startedAt}, ` +
+ `${running.progress.discovered} row(s) read so far); it was not started again.`,
+ details: { source: source.id, build: running },
+ };
+ }
+ // Started, not awaited: a complete build can outlast the request. The
+ // promise answers a record and never rejects for a registered source.
+ void service.rebuildSource(source.id, { trigger: 'operator' }).catch(() => undefined);
+ const build = service.buildRecord(source.id) ?? null;
+ return {
+ ok: true,
+ severity: 'info',
+ message:
+ `Rebuild of source '${source.id}' started. Every row its where matches is read, and the content fields of ` +
+ 'each one the index does not already hold unchanged are sent to the embedding provider, which bills for them. ' +
+ 'Read its progress with os knowledge status.',
+ details: { source: source.id, build },
+ };
+ };
+}
+
+/** The `index_status` action, bound to `service`. */
+export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActionsService): SettingsActionHandler {
+ return async ({ payload }) => {
+ const read = readSourcePayload(payload);
+ if ('refused' in read) return { ok: false, severity: 'error', message: read.refused };
+ let targets: KnowledgeSource[];
+ if (read.source !== undefined) {
+ const source = service.getSource(read.source);
+ if (!source) {
+ return { ok: false, severity: 'error', message: `No knowledge source '${read.source}' is registered (${sourceIds(service)}).` };
+ }
+ targets = [source];
+ } else {
+ targets = service.listSources();
+ }
+ const sources: KnowledgeIndexStatusEntry[] = [];
+ for (const source of targets) {
+ sources.push({
+ id: source.id,
+ label: source.label,
+ adapter: source.adapter,
+ kind: source.source.kind,
+ index: await service.readIndexState(source.id),
+ build: service.buildRecord(source.id) ?? null,
+ });
+ }
+ const due = sources.filter((s) => s.index.due).length;
+ const running = sources.filter((s) => s.build?.status === 'running').length;
+ return {
+ ok: true,
+ severity: 'info',
+ message: `${sources.length} source(s): ${due} need a build, ${running} building on this node.`,
+ details: { sources },
+ };
+ };
+}
diff --git a/packages/services/service-knowledge/src/knowledge-build.ts b/packages/services/service-knowledge/src/knowledge-build.ts
new file mode 100644
index 00000000000..ba44c994343
--- /dev/null
+++ b/packages/services/service-knowledge/src/knowledge-build.ts
@@ -0,0 +1,202 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The first build of a source and the operator's rebuild (ADR-0161 K7, "What
+ * starts a rebuild"; K8, item 8 b).
+ *
+ * The knowledge service reads what a source's adapter holds at boot and
+ * builds the sources that need it, and an administrator can start a rebuild
+ * of one source. This file holds the shapes both answer in and the lease the
+ * build runs under; the reading and the build are
+ * `KnowledgeService.readIndexState` and `KnowledgeService.rebuildSource`.
+ *
+ * ## One node builds a source
+ *
+ * A build runs under the platform's cluster lock (the `cluster` service's
+ * `lock`, the same lease `service-job`'s scheduler elects its leader with),
+ * on the key {@link buildLockKey}: only the node that acquires it builds, and
+ * a boot build re-reads the adapter after acquiring it, so a node that boots
+ * while another has just finished builds nothing. The lease is renewed while
+ * the build runs, so a long build keeps it; a node that dies stops renewing
+ * and the key frees itself. A composition with no cluster service is one
+ * node. A lock that does not answer is no answer at all: no node can prove it
+ * alone builds, so none starts (the boot logs it; the next boot or an
+ * operator rebuild asks again). Beneath the lease, a store that keeps
+ * generations takes its own builder lock in `beginBuild` (K7, rule 2).
+ *
+ * ## What a build costs
+ *
+ * A complete build reads every row its source's `where` matches and sends the
+ * listed content fields of each one the adapter does not already hold
+ * unchanged to the embedding provider. Every line that starts a build says so.
+ */
+
+import type { AdapterIndexStatus, KnowledgeReindexResult } from '@objectstack/spec/contracts';
+
+/**
+ * What a source's adapter holds, against what the service expects of it
+ * (ADR-0161 K7, "What starts a rebuild"):
+ *
+ * - `nothing` — the adapter holds nothing for the source, or only a first
+ * generation `beginBuild` opened and no build completed (no fingerprint is
+ * active yet). Built.
+ * - `new-fingerprint` — the active generation's fingerprint is not the one
+ * the service computes now (another model, dimensions or split). Built as a
+ * new generation.
+ * - `recipe-changed` — same fingerprint, another recipe hash (the source's
+ * `where`, `metadataFields`, the title rule or the withheld fields moved).
+ * Rebuilt inside the generation.
+ * - `no-recipe-hash` — same fingerprint, no recipe hash recorded (an index
+ * built before the adapter recorded one). Rebuilt when the adapter has
+ * `completeBuild`, which records it; left alone, with a warning, when not.
+ * - `current` — same fingerprint, same recipe hash. Nothing to do.
+ * - `listed-empty` — the adapter has no `indexStatus`, and its
+ * `listDocuments` answers no document. Built.
+ * - `listed-documents` — the adapter has no `indexStatus`, and lists a
+ * document. Left alone.
+ * - `unknown` — the adapter has neither method. Nothing is built
+ * automatically; the operator's rebuild is the way.
+ * - `unreadable` — reading the adapter failed. Nothing is built; `detail`
+ * says why.
+ * - `not-built-here` — the service does not build this source: a `file` or
+ * `http` source (its adapter ingests it), or no data engine is bound.
+ */
+export type KnowledgeIndexState =
+ | 'nothing'
+ | 'new-fingerprint'
+ | 'recipe-changed'
+ | 'no-recipe-hash'
+ | 'current'
+ | 'listed-empty'
+ | 'listed-documents'
+ | 'unknown'
+ | 'unreadable'
+ | 'not-built-here';
+
+/** One reading of a source's index (`KnowledgeService.readIndexState`). */
+export interface KnowledgeIndexReading {
+ sourceId: string;
+ state: KnowledgeIndexState;
+ /** Whether a complete build is due for this state. */
+ due: boolean;
+ /** One sentence for the log and the operator. */
+ detail: string;
+ /** What the adapter's `indexStatus` answered, when it has one and answered. */
+ held?: AdapterIndexStatus;
+}
+
+/** Who started a build: the boot's first-build pass, or an administrator. */
+export type KnowledgeBuildTrigger = 'boot' | 'operator';
+
+/** How far a running build has walked; the totals of a finished one. */
+export interface KnowledgeBuildProgress {
+ /** Pages of rows read so far. */
+ pages: number;
+ /** Rows read so far. */
+ discovered: number;
+ /** Documents written to the adapter so far. */
+ indexed: number;
+ /** Documents the adapter already held unchanged, so not written. */
+ skipped: number;
+ /** Documents that cannot be indexed under the source's split, removed. */
+ failed: number;
+}
+
+/**
+ * The last build of a source on this node (`KnowledgeService.buildRecord`).
+ *
+ * - `running` — the walk is under way; `progress` moves.
+ * - `done` — the walk and its purge finished and the adapter recorded the
+ * build; `result` is the reindex result.
+ * - `failed` — the walk ran and did not finish (`result.ok` is `false`), or
+ * threw; the adapter keeps what it held and the next build starts again.
+ * - `not-run` — no walk ran: another node holds the build, the cluster lock
+ * did not answer, or (at boot) the adapter turned out to be current when
+ * the lock was held. `message` says which.
+ *
+ * Kept in memory, one per source, replaced by the next build: a node answers
+ * for the builds it ran, and a restarted node remembers none.
+ */
+export interface KnowledgeBuildRecord {
+ sourceId: string;
+ trigger: KnowledgeBuildTrigger;
+ status: 'running' | 'done' | 'failed' | 'not-run';
+ /** ISO-8601 time the build was asked for. */
+ startedAt: string;
+ /** ISO-8601 time it ended; absent while it runs. */
+ finishedAt?: string;
+ progress: KnowledgeBuildProgress;
+ /** The reindex result, once the walk returned one. */
+ result?: KnowledgeReindexResult;
+ /** One sentence: why it did not run, or the result's own message. */
+ message?: string;
+}
+
+/** A lease on the cluster lock, as the build uses it (`LockHandle`, `@objectstack/spec/contracts`). */
+export interface KnowledgeBuildLockHandle {
+ release(): Promise;
+ /** Extend the lease by `ttlMs`. Throws when the lease was lost. */
+ renew?(ttlMs?: number): Promise;
+ /** True while this handle still owns the lock. */
+ isHeld?(): boolean;
+}
+
+/** The part of the cluster service's `lock` (`ILock`) a build asks. */
+export interface KnowledgeBuildLock {
+ acquire(key: string, opts?: { ttlMs?: number; waitMs?: number }): Promise;
+}
+
+/** The lease a build takes on {@link buildLockKey}; renewed every third of it while the build runs. */
+export const BUILD_LEASE_MS = 60_000;
+
+/** The least time between two progress lines of one running build. */
+export const BUILD_PROGRESS_LOG_INTERVAL_MS = 10_000;
+
+/** The cluster lock key one source's build is held under. */
+export function buildLockKey(sourceId: string): string {
+ return `knowledge:build:${sourceId}`;
+}
+
+/**
+ * Renew `handle`'s lease every `leaseMs / 3` until the returned stop function
+ * is called. A failed renewal never stops the build: `onRenewFailure` is told
+ * once per failure, and renewal stops for good once the handle reports the
+ * lease lost. Each renewal is armed after the previous one settles, and the
+ * timer never holds the process open.
+ */
+export function keepBuildLeaseAlive(
+ handle: KnowledgeBuildLockHandle,
+ leaseMs: number,
+ onRenewFailure: (err: unknown, stillHeld: boolean) => void,
+): () => void {
+ if (typeof handle.renew !== 'function') return () => {};
+ const periodMs = Math.max(1, Math.floor(leaseMs / 3));
+ let stopped = false;
+ let timer: ReturnType | undefined;
+ const beat = async (): Promise => {
+ try {
+ await handle.renew!(leaseMs);
+ } catch (err) {
+ if (stopped) return;
+ const held = handle.isHeld?.() === true;
+ onRenewFailure(err, held);
+ if (!held) return;
+ }
+ arm();
+ };
+ const arm = (): void => {
+ if (stopped) return;
+ timer = setTimeout(() => { void beat(); }, periodMs);
+ (timer as { unref?: () => void } | undefined)?.unref?.();
+ };
+ arm();
+ return () => {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ };
+}
+
+/** A fresh, zeroed progress. */
+export function emptyBuildProgress(): KnowledgeBuildProgress {
+ return { pages: 0, discovered: 0, indexed: 0, skipped: 0, failed: 0 };
+}
diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts
index 119c4be6f64..f6c2c6a3909 100644
--- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts
+++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts
@@ -19,6 +19,7 @@ import { aiTestEmbedderActionHandler } from '@objectstack/service-settings';
import { RECORD_RESTORED_EVENT } from '@objectstack/spec/data';
import { KnowledgeService } from './knowledge-service.js';
import type { KnowledgeLogger } from './knowledge-service.js';
+import type { KnowledgeBuildLock } from './knowledge-build.js';
import type { KnowledgeFieldSecurity } from './knowledge-source-admission.js';
import { createKnowledgeReapGuard, guardedObjectsFor } from './knowledge-reap-guard.js';
import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js';
@@ -336,6 +337,17 @@ export interface KnowledgeServicePluginOptions {
enableEventSync?: boolean;
/** Default top-K when callers omit it. @default 10 */
defaultTopK?: number;
+ /**
+ * Build, after boot and in the background, every source whose adapter
+ * holds nothing for it or marks it as needing a rebuild (ADR-0161 K7,
+ * "What starts a rebuild"; `KnowledgeService.buildSourcesAtBoot`). One node
+ * builds each source, under the `cluster` service's lock. A build sends the
+ * source's content fields to the embedding provider, which bills for them.
+ * `false` leaves every source as it is; an administrator then builds one
+ * with `os knowledge rebuild`.
+ * @default true
+ */
+ buildAtBoot?: boolean;
}
/**
@@ -489,6 +501,20 @@ export class KnowledgeServicePlugin implements Plugin {
throw err;
}
}),
+ // The cluster lock a build runs under, so one node builds a source
+ // (`knowledge-build.ts`). Resolved when a build starts; no `cluster`
+ // service is a one-node composition, and a lookup that throws for any
+ // other reason is the service's to report.
+ resolveBuildLock: () => {
+ let cluster: { lock?: KnowledgeBuildLock } | undefined;
+ try {
+ cluster = ctx.getService<{ lock?: KnowledgeBuildLock } | undefined>('cluster') ?? undefined;
+ } catch (err) {
+ if (isServiceNotRegisteredError(err, 'cluster')) return undefined;
+ throw err;
+ }
+ return cluster?.lock && typeof cluster.lock.acquire === 'function' ? cluster.lock : undefined;
+ },
});
for (const source of this.options.sources ?? []) {
@@ -500,7 +526,7 @@ export class KnowledgeServicePlugin implements Plugin {
// The knowledge settings page, the `ai` embedder section, both test
// actions and the Setup entry are offered only where this service is
// mounted — never by default (`@objectstack/service-settings`).
- contributeKnowledgeSettings(ctx, this.version);
+ contributeKnowledgeSettings(ctx, this.version, this.service);
ctx.logger.info?.(
`KnowledgeServicePlugin: registered '${KNOWLEDGE_SERVICE}' service (eventSync=${
this.options.enableEventSync !== false
@@ -516,6 +542,20 @@ export class KnowledgeServicePlugin implements Plugin {
// `EMBEDDER_SERVICE` where it embeds, not at boot.
ctx.hook('kernel:bootstrapped', async () => {
await this.provideEmbedder(ctx);
+ // [ADR-0161 K7] The first build: every source a build is due for is
+ // built once, in the background — after the embedder is provided,
+ // since a build embeds, and never awaited, so the boot does not wait
+ // for it. `buildAtBoot: false` turns it off.
+ if (this.options.buildAtBoot !== false && this.service) {
+ // `buildSourcesAtBoot` resolves on every failure it can name; the
+ // catch is for one it cannot, so no rejection goes unhandled.
+ void this.service.buildSourcesAtBoot().catch((err: unknown) => {
+ ctx.logger.warn?.(
+ `KnowledgeServicePlugin: the boot build pass stopped (${err instanceof Error ? err.message : String(err)}); ` +
+ 'no further source is built at this boot. Rebuild one with os knowledge rebuild.',
+ );
+ });
+ }
});
if (this.options.enableEventSync === false) return;
@@ -769,6 +809,9 @@ export class KnowledgeServicePlugin implements Plugin {
* the same one either way: a teardown the kernel does not reach.
*/
async destroy(): Promise {
+ // The boot's first-build pass starts no further build; one already
+ // walking runs to its end (a walk cannot be cancelled part-way).
+ this.service?.stopBuilds();
if (!this.subscriptionId) return;
try {
await this.realtime?.unsubscribe(this.subscriptionId);
diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts
index f6725d153a3..079e1b1af8c 100644
--- a/packages/services/service-knowledge/src/knowledge-service.ts
+++ b/packages/services/service-knowledge/src/knowledge-service.ts
@@ -43,6 +43,19 @@ import {
type ObjectAdmission,
} from './knowledge-source-admission.js';
import { readSearchScope, scopeCheck, scopeTermsFor, type SearchScopeEntry } from './knowledge-search-scope.js';
+import {
+ BUILD_LEASE_MS,
+ BUILD_PROGRESS_LOG_INTERVAL_MS,
+ buildLockKey,
+ emptyBuildProgress,
+ keepBuildLeaseAlive,
+ type KnowledgeBuildLock,
+ type KnowledgeBuildLockHandle,
+ type KnowledgeBuildProgress,
+ type KnowledgeBuildRecord,
+ type KnowledgeBuildTrigger,
+ type KnowledgeIndexReading,
+} from './knowledge-build.js';
/**
* Minimal logger shape; falls back to no-op when none is provided.
@@ -100,6 +113,14 @@ export interface KnowledgeServiceOptions {
* service reads as a `single`-posture deployment.
*/
resolveTenancyPosture?: KnowledgeTenancyPostureResolver;
+ /**
+ * The cluster lock a build runs under (`knowledge-build.ts`, "One node
+ * builds a source"), resolved each time a build starts. Answers `undefined`
+ * where no cluster service is composed: the composition is one node and the
+ * build runs without a lease. `KnowledgeServicePlugin` wires it to the
+ * `cluster` service's `lock`.
+ */
+ resolveBuildLock?: () => KnowledgeBuildLock | undefined;
/**
* Default top-K when callers don't specify. The adapter may cap
* further; the service does not enforce an upper bound itself.
@@ -151,6 +172,10 @@ export class KnowledgeService implements IKnowledgeService {
* search finds its hash matching, which clears the entry.
*/
private readonly freshnessRepairs = new Set();
+ /** The last build of each source on this node (`knowledge-build.ts`). */
+ private readonly builds = new Map();
+ /** Set by {@link stopBuilds}: the boot pass starts no further build. */
+ private buildsStopped = false;
constructor(private readonly options: KnowledgeServiceOptions = {}) {
this.defaultTopK = options.defaultTopK ?? 10;
@@ -424,7 +449,15 @@ export class KnowledgeService implements IKnowledgeService {
sourceId: string,
opts: KnowledgeReindexOptions = {},
): Promise {
- const source = this.requireSource(sourceId);
+ return this.reindexWith(this.requireSource(sourceId), opts);
+ }
+
+ /** {@link reindexSource}, with a sink a build's progress is reported to after each page. */
+ private async reindexWith(
+ source: KnowledgeSource,
+ opts: KnowledgeReindexOptions,
+ progress?: (step: KnowledgeBuildProgress) => void,
+ ): Promise {
const adapter = this.getAdapter(source.adapter);
if (source.source.kind !== 'object') {
@@ -458,7 +491,7 @@ export class KnowledgeService implements IKnowledgeService {
}
return chainAfter(this.reindexTails, source.id, () =>
- this.walkObjectSource(source, source.source as ObjectKnowledgeSource, adapter, engine, opts),
+ this.walkObjectSource(source, source.source as ObjectKnowledgeSource, adapter, engine, opts, progress),
);
}
@@ -469,6 +502,7 @@ export class KnowledgeService implements IKnowledgeService {
adapter: IKnowledgeAdapter,
engine: IDataEngine,
opts: KnowledgeReindexOptions,
+ progress?: (step: KnowledgeBuildProgress) => void,
): Promise {
const object = objSource.object;
// `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A
@@ -657,6 +691,7 @@ export class KnowledgeService implements IKnowledgeService {
discovered += rows.length;
indexed += prepared.ready.length;
skipped += docs.length - changed.length;
+ progress?.({ pages: page, discovered, indexed, skipped, failed });
// The next page continues after this page's last id. A last row with no
// id, or one that did not move past the cursor (an engine that ignored
@@ -755,6 +790,303 @@ export class KnowledgeService implements IKnowledgeService {
}
}
+ // ── The first build and the operator's rebuild (ADR-0161 K7) ──────
+
+ /**
+ * What `sourceId`'s adapter holds, against what the service expects of it
+ * now, and whether a complete build is due (ADR-0161 K7, "What starts a
+ * rebuild"; the states are {@link KnowledgeIndexReading}'s). Reads the
+ * adapter's `indexStatus` against the fingerprint and recipe hash
+ * {@link planIndex} computes; an adapter without it is asked for one entry
+ * of `listDocuments`. Never throws for a registered source: a failed read
+ * is the `unreadable` state. Writes nothing.
+ */
+ async readIndexState(sourceId: string): Promise {
+ const source = this.requireSource(sourceId);
+ const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({
+ sourceId,
+ state,
+ due,
+ detail,
+ ...(held === undefined ? {} : { held }),
+ });
+ if (source.source.kind !== 'object') {
+ return reading('not-built-here', false, `a ${source.source.kind} source is ingested by its adapter, not built by the knowledge service.`);
+ }
+ if (!this.options.dataEngine) {
+ return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.');
+ }
+ try {
+ const adapter = this.getAdapter(source.adapter);
+ const plan = await this.planIndex(source, adapter);
+ const ctx = plan.context('reindex');
+ if (typeof adapter.indexStatus === 'function') {
+ const held = await adapter.indexStatus(ctx);
+ const expected = plan.index;
+ if (held.fingerprint === undefined && held.recipeHash === undefined && held.building !== true) {
+ return reading('nothing', true, 'the adapter holds nothing for the source: it has never been built.', held);
+ }
+ // A first build opened a generation and has not completed it (it is
+ // still running on some node, or it stopped part-way): there is no
+ // active generation yet, so no other fingerprint to speak of.
+ if (held.fingerprint === undefined) {
+ return reading(
+ 'nothing',
+ true,
+ 'a first build was started and has not completed (it is still running, or it stopped part-way): the adapter holds no complete index for the source.',
+ held,
+ );
+ }
+ if (held.fingerprint !== expected.fingerprint) {
+ return reading(
+ 'new-fingerprint',
+ true,
+ 'the index was built under another fingerprint (embedding model, dimensions or split): it is built anew.',
+ held,
+ );
+ }
+ if (held.recipeHash === undefined) {
+ return typeof adapter.completeBuild === 'function'
+ ? reading('no-recipe-hash', true, 'the index records no recipe hash: one complete rebuild records it.', held)
+ : reading(
+ 'no-recipe-hash',
+ false,
+ `the adapter '${adapter.id}' records no recipe hash and has no completeBuild, so a changed recipe ` +
+ "(the source's where, metadataFields, title rule or withheld fields) cannot be seen for it; nothing is rebuilt automatically.",
+ held,
+ );
+ }
+ if (held.recipeHash !== expected.recipeHash) {
+ return reading(
+ 'recipe-changed',
+ true,
+ "the source's recipe changed since the last build (its where, metadataFields, title rule or withheld fields): it is rebuilt.",
+ held,
+ );
+ }
+ return reading('current', false, 'the index is current: same fingerprint, same recipe hash.', held);
+ }
+ if (typeof adapter.listDocuments === 'function') {
+ const page = await adapter.listDocuments(ctx, { limit: 1 });
+ const documents = Array.isArray(page?.documents) ? page.documents : undefined;
+ if (documents === undefined) {
+ return reading('unreadable', false, "the adapter's document listing answered no list of documents.");
+ }
+ return documents.length === 0
+ ? reading('listed-empty', true, 'the adapter lists no document for the source: it has never been built.')
+ : reading(
+ 'listed-documents',
+ false,
+ `the adapter '${adapter.id}' holds documents and reports no index status, so whether they are current cannot be read; nothing is rebuilt automatically.`,
+ );
+ }
+ return reading(
+ 'unknown',
+ false,
+ `the adapter '${adapter.id}' has neither indexStatus nor listDocuments, so whether the source was ever built cannot be read; ` +
+ 'nothing is built automatically, and an operator rebuild (os knowledge rebuild) is the way.',
+ );
+ } catch (err) {
+ return reading('unreadable', false, `what the adapter holds could not be read (${operatorText(err)}).`);
+ }
+ }
+
+ /** The last build of `sourceId` on this node, or `undefined` when it ran none. */
+ buildRecord(sourceId: string): KnowledgeBuildRecord | undefined {
+ const record = this.builds.get(sourceId);
+ return record === undefined ? undefined : cloneBuildRecord(record);
+ }
+
+ /**
+ * Build `sourceId` once, completely, under the cluster lock
+ * (`knowledge-build.ts`), and answer the build's record.
+ *
+ * - A build of the source already running on this node is not doubled: its
+ * record is answered.
+ * - The lock held by another node, or not answering, starts nothing
+ * (`not-run`).
+ * - A `boot` build re-reads the adapter once it holds the lock and builds
+ * only when a build is still due; an `operator` build always walks.
+ * - The walk is {@link reindexSource} with no `limit` and no `dryRun`: a
+ * complete build, with `beginBuild` and `completeBuild`.
+ *
+ * Progress is logged at `info` when the build starts (with what it costs),
+ * at most every {@link BUILD_PROGRESS_LOG_INTERVAL_MS} while it walks, and
+ * when it ends; a build that does not finish is logged at `warn` — nothing
+ * claims it finished, the adapter keeps what it held and the next build
+ * starts again. Never rejects for a registered source; throws for an
+ * unknown one, as {@link reindexSource} does.
+ */
+ async rebuildSource(sourceId: string, opts: { trigger: KnowledgeBuildTrigger }): Promise {
+ const source = this.requireSource(sourceId);
+ const running = this.builds.get(sourceId);
+ if (running?.status === 'running') return cloneBuildRecord(running);
+ const record: KnowledgeBuildRecord = {
+ sourceId,
+ trigger: opts.trigger,
+ status: 'running',
+ startedAt: new Date().toISOString(),
+ progress: emptyBuildProgress(),
+ };
+ this.builds.set(sourceId, record);
+ const logger = this.options.logger;
+ const label = `[knowledge] build of source '${sourceId}' (${opts.trigger})`;
+ const finish = (
+ status: Exclude,
+ message: string | undefined,
+ result?: KnowledgeReindexResult,
+ ): KnowledgeBuildRecord => {
+ record.status = status;
+ record.finishedAt = new Date().toISOString();
+ if (message !== undefined) record.message = message;
+ if (result !== undefined) record.result = result;
+ return cloneBuildRecord(record);
+ };
+
+ let lock: KnowledgeBuildLock | undefined;
+ try {
+ lock = this.options.resolveBuildLock?.();
+ } catch (err) {
+ const message = `the cluster service could not be read (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`;
+ logger?.warn(`${label}: ${message}`);
+ return finish('not-run', message);
+ }
+ let handle: KnowledgeBuildLockHandle | null = null;
+ if (lock) {
+ try {
+ handle = await lock.acquire(buildLockKey(sourceId), { ttlMs: BUILD_LEASE_MS, waitMs: 0 });
+ } catch (err) {
+ const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`;
+ logger?.warn(`${label}: ${message}`);
+ return finish('not-run', message);
+ }
+ if (!handle) {
+ const message = 'another node holds the build of this source; this node built nothing.';
+ logger?.info?.(`${label}: ${message}`);
+ return finish('not-run', message);
+ }
+ }
+ const stopLease = handle
+ ? keepBuildLeaseAlive(handle, BUILD_LEASE_MS, (err, held) => {
+ logger?.warn(
+ `${label}: the cluster lease could not be renewed (${errorText(err)}). The build continues; once the lease ` +
+ "lapses another node's boot or an operator rebuild may build the same source. " +
+ (held ? 'Renewal is retried.' : 'The lease is lost; renewal stops for this build.'),
+ );
+ })
+ : () => {};
+ try {
+ if (opts.trigger === 'boot') {
+ const reading = await this.readIndexState(sourceId);
+ if (!reading.due) {
+ const message = `nothing to build once the lock was held: ${reading.detail}`;
+ logger?.info?.(`${label}: ${message}`);
+ return finish('not-run', message);
+ }
+ }
+ logger?.info?.(
+ `${label} started: every row the source's where matches is read, and the content fields of each one the ` +
+ 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.',
+ );
+ let lastLogged = Date.now();
+ const result = await this.reindexWith(source, {}, (step) => {
+ record.progress = { ...step };
+ const now = Date.now();
+ if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return;
+ lastLogged = now;
+ logger?.info?.(
+ `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` +
+ `${step.skipped} unchanged, ${step.failed} cannot be indexed.`,
+ );
+ });
+ record.progress = {
+ pages: record.progress.pages,
+ discovered: result.discovered,
+ indexed: result.indexed,
+ skipped: result.skipped ?? 0,
+ failed: result.failed ?? 0,
+ };
+ const totals =
+ `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` +
+ `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`;
+ if (!result.ok) {
+ logger?.warn(
+ `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` +
+ 'The adapter keeps what it held; the next boot or an operator rebuild builds again.',
+ );
+ return finish('failed', result.message, result);
+ }
+ logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`);
+ return finish('done', result.message, result);
+ } catch (err) {
+ const message = `the build threw: ${operatorText(err)}`;
+ logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next boot or an operator rebuild builds again.`);
+ return finish('failed', message);
+ } finally {
+ stopLease();
+ if (handle) {
+ try {
+ await handle.release();
+ } catch (err) {
+ // The lease still frees itself on its TTL; the build itself ran.
+ logger?.warn(`${label}: the cluster lock could not be released (${errorText(err)}); it frees itself when its lease ends.`);
+ }
+ }
+ }
+ }
+
+ /**
+ * The boot's first-build pass (ADR-0161 K7, "What starts a rebuild"): read
+ * every registered source's index ({@link readIndexState}) and build, one
+ * source at a time, each one a build is due for ({@link rebuildSource},
+ * trigger `boot`). A source with `refresh.onRecordChange: false` is left
+ * alone — an external indexer owns its index — and so is one whose state
+ * builds nothing; a state that cannot be read or seen is logged at `warn`,
+ * once. Resolves when the pass is done; never rejects. Run in the
+ * background by `KnowledgeServicePlugin`, so the boot never waits for it.
+ */
+ async buildSourcesAtBoot(): Promise {
+ const logger = this.options.logger;
+ let sources: KnowledgeSource[];
+ try {
+ sources = this.listSources();
+ } catch (err) {
+ logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`);
+ return;
+ }
+ for (const source of sources) {
+ if (this.buildsStopped) return;
+ try {
+ if (source.source.kind === 'object' && (source.refresh?.onRecordChange ?? true) === false) {
+ logger?.debug?.(`[knowledge] source '${source.id}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built at boot.`);
+ continue;
+ }
+ const reading = await this.readIndexState(source.id);
+ if (reading.due) {
+ logger?.info?.(`[knowledge] source '${source.id}' is built now: ${reading.detail}`);
+ await this.rebuildSource(source.id, { trigger: 'boot' });
+ continue;
+ }
+ const line = `[knowledge] source '${source.id}' is not built at boot: ${reading.detail}`;
+ // What cannot be seen or read is said once, at `warn` (K7: "the
+ // service says so once"); a source that is current, or whose adapter
+ // holds documents it reports no status for, is ordinary.
+ if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') {
+ logger?.warn(line);
+ } else {
+ logger?.info?.(line);
+ }
+ } catch (err) {
+ logger?.warn(`[knowledge] source '${source.id}': the boot build pass failed for it (${operatorText(err)}).`);
+ }
+ }
+ }
+
+ /** Stop the boot pass from starting another build. A build already walking runs to its end. */
+ stopBuilds(): void {
+ this.buildsStopped = true;
+ }
+
// ── The `search_knowledge` AI tool (ADR-0149 D2) ──────────────────
/**
@@ -1876,6 +2208,11 @@ interface IndexPlan {
context(reason: NonNullable): AdapterContext;
}
+/** A copy of a build record, so a caller never holds the live one. */
+function cloneBuildRecord(record: KnowledgeBuildRecord): KnowledgeBuildRecord {
+ return { ...record, progress: { ...record.progress } };
+}
+
/**
* Rows one reindex page reads, and so the most documents one reindex `upsert`
* carries. A memory and request-size bound for the walk, not an embedder
diff --git a/packages/services/service-knowledge/src/knowledge-settings-contribution.ts b/packages/services/service-knowledge/src/knowledge-settings-contribution.ts
index 93a75f8b38c..ae3ac6c3429 100644
--- a/packages/services/service-knowledge/src/knowledge-settings-contribution.ts
+++ b/packages/services/service-knowledge/src/knowledge-settings-contribution.ts
@@ -31,6 +31,13 @@ import {
aiTestEmbedderActionHandler,
type SettingsService,
} from '@objectstack/service-settings';
+import {
+ KNOWLEDGE_INDEX_STATUS_ACTION,
+ KNOWLEDGE_REBUILD_ACTION,
+ knowledgeIndexStatusActionHandler,
+ knowledgeRebuildActionHandler,
+ type KnowledgeBuildActionsService,
+} from './knowledge-build-actions.js';
/** The Setup bundle this contribution registers under. */
export const KNOWLEDGE_SETUP_NAV_BUNDLE_ID = 'com.objectstack.service.knowledge.setup-nav';
@@ -92,8 +99,16 @@ export interface KnowledgeSettingsContribution {
* service, and its Setup entry on the manifest service. A composition with no
* settings service gets none of it, Setup entry included: the entry would open
* a page the server does not serve.
+ *
+ * Given the knowledge service, the namespace also carries the administrator's
+ * rebuild entry, the `rebuild` and `index_status` actions
+ * (`knowledge-build-actions.ts`).
*/
-export function contributeKnowledgeSettings(ctx: PluginContext, version: string): KnowledgeSettingsContribution {
+export function contributeKnowledgeSettings(
+ ctx: PluginContext,
+ version: string,
+ service?: KnowledgeBuildActionsService,
+): KnowledgeSettingsContribution {
const offered: KnowledgeSettingsContribution = { knowledge: false, embedder: false, nav: false };
let settings: SettingsSlot | undefined;
try {
@@ -106,6 +121,10 @@ export function contributeKnowledgeSettings(ctx: PluginContext, version: string)
settings.registerManifest(knowledgeSettingsManifest);
settings.registerAction('knowledge', 'test', knowledgeTestActionHandler);
+ if (service) {
+ settings.registerAction('knowledge', KNOWLEDGE_REBUILD_ACTION, knowledgeRebuildActionHandler(service));
+ settings.registerAction('knowledge', KNOWLEDGE_INDEX_STATUS_ACTION, knowledgeIndexStatusActionHandler(service));
+ }
offered.knowledge = true;
// The embedder section joins the `ai` namespace — the bundled one only,