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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/38374-starter-knowledge-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'create-objectstack': patch
---

feat(create-objectstack): the blank template's help articles are a knowledge source, served only where an embedder is configured

Clause-②: no
Metadata-protocol: none

Who sees it: a developer who scaffolds a project with `npm create objectstack`.

- **New file `src/knowledge/articles.knowledge-source.ts`**, listed in `knowledgeSources` in `objectstack.config.ts`. It indexes the body of each published help article, one passage per `##` section, with the article's category kept beside each passage. Drafts are not indexed. It names no store, so the deployment's own store holds the index, and the stack does not add `requires: ['knowledge']`.
- **With no embedder configured** (a fresh project, `pnpm dev`, `pnpm test`) the source is held: nothing is indexed or sent anywhere, and AI clients connected to the app's MCP server are offered no `search_knowledge` tool.
- **To enable search on a self-hosted deployment**, save an embedder provider in Settings under AI, Embedder, and restart the server. The body of every published article is then sent to that provider. The README's "Search the help articles" section says how.
- `starter.test.ts` gains two cases: with no embedder the boot prints no warning about knowledge and MCP lists no `search_knowledge`; with a small test embedder each published section is found by search.
- To remove the help articles, also delete `src/knowledge/articles.knowledge-source.ts` and its `knowledgeSources` entry; the README's removal steps say so.
17 changes: 17 additions & 0 deletions examples/app-starter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,29 @@ notes in one menu.
- `src/data/` — five sample companies, six sample contacts, and four help
articles (setting up a laptop, a Wi-Fi and printing FAQ, a meeting rooms
reference, and a draft on sharing files).
- `src/knowledge/` — `biz_articles`, a knowledge source over the published
help articles: each `##` section of an article is one passage. See
[Searching the help articles](#searching-the-help-articles).
- `src/translations/` — English and Simplified Chinese.

The API names carry the `biz_` namespace, so a tenant can install this
starter beside a CRM package without a name clash. Uninstalling the package
removes companies, contacts and articles; tasks and notes stay.

## Searching the help articles

The knowledge source is served only where knowledge retrieval is enabled. On a
deployment with no embedder (a fresh self-hosted server, `dev`, `test`) it is
held: nothing is indexed or sent anywhere, AI clients are offered no
`search_knowledge` tool, and the boot says so in one `info` line.

To enable search on a self-hosted deployment, save an embedder provider (and
its API key) in Settings, under **AI → Embedder**, then restart the server. At
the next start the published articles are indexed and `search_knowledge`
answers from them. **The body of every published article is then sent to that
provider** to be embedded (it opens with the title), and again each time an
article changes; drafts and the other fields are not.

## How to run

```bash
Expand Down
7 changes: 7 additions & 0 deletions examples/app-starter/objectstack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as datasets from './src/datasets/index.js';
import * as translations from './src/translations/index.js';
import * as permissionSets from './src/security/index.js';
import { StarterSeedData } from './src/data/index.js';
import { ArticlesKnowledge } from './src/knowledge/articles.knowledge-source.js';

/**
* Starter app — companies and the people at them, and help articles, with the
Expand Down Expand Up @@ -51,6 +52,12 @@ export default defineStack({

data: StarterSeedData,

// The published help articles as a knowledge source. No `requires:
// ['knowledge']`: the source itself mounts the knowledge service, which
// serves it only once the deployment has an embedder; with none, the source
// is held and nothing is indexed or offered to AI clients.
knowledgeSources: [ArticlesKnowledge],

i18n: {
defaultLocale: 'en',
supportedLocales: ['en', 'zh-CN'],
Expand Down
38 changes: 38 additions & 0 deletions examples/app-starter/src/knowledge/articles.knowledge-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import type { KnowledgeSource } from '@objectstack/spec/ai';

/**
* The published help articles, searchable by meaning (ADR-0161 K4).
*
* Served only where knowledge retrieval is enabled. A deployment with no
* embedder holds this source unserved: it builds no index, sends nothing
* anywhere, and lists no `search_knowledge` tool, and the boot says so in one
* `info` line. Once an embedder provider is saved in Settings and the server
* restarts, the source is built and `search_knowledge` answers from it.
*
* - `content: ['body']`: only the body is indexed, and only the body is sent
* to the embedder. The body opens with the article's title as a `#`
* heading, so `title` is not listed: under the `markdown` split a listed
* title would be a passage holding nothing but the title.
* - `split: markdown`: each `##` section of an article is one passage, whose
* heading path is the article's title and the section's.
* - `where`: drafts are not indexed; an article is searchable once it is
* published.
* - `metadataFields: ['category']`: kept beside each passage, so a search can
* be narrowed to how-tos, FAQs or reference pages.
* - No `adapter`: the deployment's own store holds the index.
*/
export const ArticlesKnowledge: KnowledgeSource = {
name: 'biz_articles',
label: 'Help articles',
description: 'The published help articles, one passage per section.',
source: {
kind: 'object',
object: 'biz_article',
content: ['body'],
metadataFields: ['category'],
where: { status: 'published' },
split: { strategy: 'markdown' },
},
};
116 changes: 116 additions & 0 deletions examples/app-starter/test/boot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,119 @@ describe('app-starter — installed as a starter, menu, uninstall', () => {
expect(unwrap(after.note)?.id).toBe(unwrap(note).id);
});
});

/**
* The help-article knowledge source on a host that serves knowledge and has
* no embedder (ADR-0161 K8, item 12): the source is held, and the package
* that carries it still installs and duplicates. A duplicate copies each
* knowledge source again, and while the service is held that door is not
* refused. The host asks for the knowledge service itself
* (`requires: ['knowledge']`): the starter is installed into it, so none of
* the host's own items would mount the service.
*/
describe('app-starter — on a host that serves knowledge with no embedder', () => {
let booted: VerifyStack;
let storageDir: string;
let install: Answer;
let duplicate: Answer;
let copied: Answer;
let held: string[] = [];
let reading: unknown;
let tools: string[] = [];

beforeAll(async () => {
storageDir = mkdtempSync(join(tmpdir(), 'app-starter-knowledge-'));
booted = await bootStack(defineStack({ ...HOST, requires: ['knowledge'] }), {
extraPlugins: [new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir })],
});
const token = await booted.signIn();
const call = async (method: string, path: string, body?: unknown) => json(await booted.apiAs(token, method, path, body));

install = await call('POST', ROUTE, installBody());
const base = install.body?.data?.targetPackageId;
duplicate = await call('POST', `/packages/${base}/duplicate`, { targetPackageId: `${PACKAGE_ID}-second` });
copied = await call('GET', '/meta/knowledge_source');
const knowledge = await booted.kernel.getServiceAsync<any>('knowledge');
held = knowledge.describeSources().map((s: { id: string }) => s.id);
reading = knowledge.heldReading();
tools = knowledge.knowledgeTools().definitions.map((d: { name: string }) => d.name);
}, 180_000);

afterAll(async () => {
await booted?.stop?.();
if (storageDir) rmSync(storageDir, { recursive: true, force: true });
});

it('the package carries the help-article source', () => {
expect((stack.knowledgeSources ?? []).map((s) => s.name)).toEqual(['biz_articles']);
expect(install.status, JSON.stringify(install.body)).toBe(200);
});

it('duplicating the installed starter copies the source, which is not refused while knowledge is held', () => {
expect(duplicate.status, JSON.stringify(duplicate.body)).toBe(200);
const answer = duplicate.body?.data ?? {};
expect(answer.targetPackageId).toBe(`${PACKAGE_ID}-second`);
expect(answer.copied).toContainEqual({ type: 'knowledge_source', name: 'starter_second_articles' });
expect((answer.failed ?? []).filter((f: { type: string }) => f.type === 'knowledge_source')).toEqual([]);
const packages = (copied.body?.items ?? []).map((i: { _packageId?: string }) => i._packageId);
expect(packages, JSON.stringify(copied.body)).toEqual(expect.arrayContaining([`${PACKAGE_ID}-copy`, `${PACKAGE_ID}-second`]));
});

it('both sources are held by the knowledge service, which offers no tool', () => {
expect(held.sort()).toEqual(['biz-biz_articles', 'starter_second-starter_second_articles']);
expect(reading).toMatchObject({ embedder: expect.any(String) });
expect(tools).toEqual([]);
});
});

/**
* The same duplicate on a host that runs no knowledge service: the host asks
* for nothing (no `requires`), and the starter is installed into it, so no
* item of the host's own mounts the service. The source rides along unserved,
* as it does while the service is held (ruling A on #38374, 7380897321): the
* whole package copies, its seeds included, and the copy's source is inert
* like the original's.
*/
describe('app-starter — on a host with no knowledge service', () => {
let booted: VerifyStack;
let storageDir: string;
let install: Answer;
let duplicate: Answer;
let copied: Answer;
let knowledge: unknown;

beforeAll(async () => {
storageDir = mkdtempSync(join(tmpdir(), 'app-starter-no-knowledge-'));
booted = await bootStack(HOST, {
extraPlugins: [new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir })],
});
const token = await booted.signIn();
const call = async (method: string, path: string, body?: unknown) => json(await booted.apiAs(token, method, path, body));

install = await call('POST', ROUTE, installBody());
const base = install.body?.data?.targetPackageId;
duplicate = await call('POST', `/packages/${base}/duplicate`, { targetPackageId: `${PACKAGE_ID}-second` });
copied = await call('GET', '/meta/knowledge_source');
knowledge = await booted.kernel.getServiceAsync('knowledge').catch(() => undefined);
}, 180_000);

afterAll(async () => {
await booted?.stop?.();
if (storageDir) rmSync(storageDir, { recursive: true, force: true });
});

it('precondition: no knowledge service runs on this host', () => {
expect(install.status, JSON.stringify(install.body)).toBe(200);
expect(knowledge).toBeUndefined();
});

it('duplicating the installed starter succeeds, the source copied unserved and no seed refused', () => {
expect(duplicate.status, JSON.stringify(duplicate.body)).toBe(200);
const answer = duplicate.body?.data ?? {};
expect(answer.success, JSON.stringify(answer)).toBe(true);
expect(answer.failed ?? [], JSON.stringify(answer)).toEqual([]);
expect(answer.copied).toContainEqual({ type: 'knowledge_source', name: 'starter_second_articles' });
const packages = (copied.body?.items ?? []).map((i: { _packageId?: string }) => i._packageId);
expect(packages, JSON.stringify(copied.body)).toEqual(expect.arrayContaining([`${PACKAGE_ID}-copy`, `${PACKAGE_ID}-second`]));
});
});
41 changes: 31 additions & 10 deletions packages/cli/src/commands/migrate/meta.relevance-count.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
* The input is the scaffold's own blank template, loaded the way the command
* loads it (`loadConfig(…, { authoredSource: true })`, then the map → array
* pass only) and replayed through the command's own chain
* (`applyMetaMigrationsToPackages`). That template lists no `plugins:`, so
* the chain proves `agents` and `knowledgeSources` absent from it and their
* two protocol-19 notices leave ③. The same stack with a plugin listed — the
* shape the 18.6.0 template had, three connector plugins — proves nothing
* (`applyMetaMigrationsToPackages`). That template lists no `plugins:` and
* no `agents`, so the chain proves `agents` absent and its protocol-19 notice
* leaves ③. It declares one knowledge source (its help articles), so the
* knowledge notice stays listed; the same template with that source removed
* proves `knowledgeSources` absent too. The same stack with a plugin listed —
* the shape the 18.6.0 template had, three connector plugins — proves nothing
* absent, and ④ prints the zero count and the reason instead.
*/

Expand Down Expand Up @@ -103,12 +105,20 @@ function report(

const ids = (todos: MigrationChainResult['todos']) => todos.map((t) => `${t.toMajor}:${t.id}`);

describe('the blank template proves agents and knowledge sources absent (ACCEPTANCE)', () => {
it('lists no `plugins:`, so both notices leave ③ and ④ counts them', async () => {
/** The blank template without its help-article knowledge source. */
async function blankStackWithoutKnowledge(): Promise<Record<string, unknown>> {
const { knowledgeSources: _declared, ...rest } = await blankStack();
return rest;
}

describe('the blank template proves agents absent and keeps its knowledge source listed (ACCEPTANCE)', () => {
it('lists no `plugins:` and no agents: the agent notice leaves ③ and ④ counts it; the knowledge notice stays', async () => {
const stack = await blankStack();
expect(stack.plugins).toBeUndefined();
expect((stack.knowledgeSources as unknown[] | undefined)?.length).toBe(1);
const { result, lines } = report(stack);
expect(ids(result.absentTodos)).toEqual(expect.arrayContaining([AGENT_ENTRY, KNOWLEDGE_ENTRY]));
expect(ids(result.absentTodos)).toContain(AGENT_ENTRY);
expect(ids(result.absentTodos)).not.toContain(KNOWLEDGE_ENTRY);
expect(result.unanswered).toBeUndefined();

const count = lines.find((l) => ABSENT_COUNT_RE.test(l));
Expand All @@ -120,22 +130,33 @@ describe('the blank template proves agents and knowledge sources absent (ACCEPTA
expect(scope).toHaveLength(1);
expect(scope[0]).toContain('metadata a deployment stores');
expect(scope[0]).toContain('`onEnable`');
for (const t of result.absentTodos.filter((u) => [AGENT_ENTRY, KNOWLEDGE_ENTRY].includes(`${u.toMajor}:${u.id}`))) {
for (const t of result.absentTodos.filter((u) => `${u.toMajor}:${u.id}` === AGENT_ENTRY)) {
expect(lines, `${t.id} is counted, not listed`).not.toContain(` ⚠ [protocol ${t.toMajor}] ${t.surface} → ${t.replacement}`);
}
const knowledge = result.todos.filter((u) => `${u.toMajor}:${u.id}` === KNOWLEDGE_ENTRY);
expect(knowledge).toHaveLength(1);
expect(lines, 'the knowledge notice is listed').toContain(
` ⚠ [protocol ${knowledge[0]!.toMajor}] ${knowledge[0]!.surface} → ${knowledge[0]!.replacement}`,
);
});

it('the template without its knowledge source proves both absent (control)', async () => {
const { result } = report(await blankStackWithoutKnowledge());
expect(ids(result.absentTodos)).toEqual(expect.arrayContaining([AGENT_ENTRY, KNOWLEDGE_ENTRY]));
expect(result.unanswered).toBeUndefined();
});

it('a template that declares an agent keeps its notice listed (control)', async () => {
const stack = { ...(await blankStack()), agents: [{ name: 'helper', label: 'Helper' }] };
const { result } = report(stack);
expect(ids(result.absentTodos)).not.toContain(AGENT_ENTRY);
expect(ids(result.absentTodos)).toContain(KNOWLEDGE_ENTRY);
expect(ids(result.absentTodos)).not.toContain(KNOWLEDGE_ENTRY);
});
});

describe('④ prints the zero count, and why a question stayed open (PRINTER)', () => {
it('the template with a plugin listed proves nothing absent: zero, the count of open questions, and why', async () => {
const stack = { ...(await blankStack()), plugins: [new ConnectorLikePlugin(), new ConnectorLikePlugin()] };
const stack = { ...(await blankStackWithoutKnowledge()), plugins: [new ConnectorLikePlugin(), new ConnectorLikePlugin()] };
const { result, lines } = report(stack);
expect(result.absentTodos).toEqual([]);
expect(ids(result.unanswered!.todos)).toEqual(expect.arrayContaining([AGENT_ENTRY, KNOWLEDGE_ENTRY]));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
// articles, and the platform's tasks and notes — without the Starter's
// dashboard entry: the template ships no dashboard. Of the Starter's seed the
// template carries only the help articles: its companies and contacts start
// empty.
// empty. The knowledge source over the help articles
// (`src/knowledge/articles.knowledge-source.ts`) is held equal the same way:
// the exported definition, printed without comments.

import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
Expand Down Expand Up @@ -131,6 +133,18 @@ function seeds(file: string, seeded: string, rename: boolean): string[] {
).map((call) => print(call, sf));
}

/** The printed initializer of every exported `const` in the file, by name. */
function exportedConsts(file: string, rename: boolean): { name: string; text: string }[] {
const sf = parse(file, rename);
return sf.statements
.filter((s): s is ts.VariableStatement => ts.isVariableStatement(s) && !!s.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
.flatMap((s) => s.declarationList.declarations)
.filter((d) => d.initializer !== undefined)
.map((d) => ({ name: d.name.getText(sf), text: print(d.initializer!, sf) }));
}

const KNOWLEDGE_FILE = 'knowledge/articles.knowledge-source.ts';

describe('blank template — the Starter app\'s companies, contacts and articles, as source', () => {
it('reads two real namespaces (vacuity guard)', () => {
expect(BLANK_NAMESPACE).toBe('blank');
Expand Down Expand Up @@ -190,6 +204,33 @@ describe('blank template — the Starter app\'s companies, contacts and articles
expect(mutated).not.toEqual(seeds(path.join(STARTER_SRC, 'data', 'articles.ts'), 'Article', true));
});

it('the help-article knowledge source is the Starter\'s, modulo the namespace', () => {
const starter = exportedConsts(path.join(STARTER_SRC, KNOWLEDGE_FILE), true);
const template = exportedConsts(path.join(BLANK_SRC, KNOWLEDGE_FILE), false);
// Vacuity guard: one source found on each side, naming its object.
expect(starter).toHaveLength(1);
expect(starter[0].text).toMatch(/object: 'blank_article'/);
expect(template).toEqual(starter);
// Both configs list it.
for (const config of [STARTER_CONFIG, path.join(BLANK, 'objectstack.config.ts')]) {
expect(fs.readFileSync(config, 'utf8')).toMatch(/knowledgeSources: \[ArticlesKnowledge\]/);
}
});

it('CONTROL: a one-value change in the template\'s knowledge source is caught', () => {
const file = path.join(BLANK_SRC, KNOWLEDGE_FILE);
const sf = ts.createSourceFile(
file,
fs.readFileSync(file, 'utf8').replace("content: ['body']", "content: ['title', 'body']"),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS,
);
const mutated = sf.statements.filter(ts.isVariableStatement).map((s) => print(s.declarationList.declarations[0].initializer!, sf));
expect(mutated).toHaveLength(1);
expect(mutated).not.toEqual(exportedConsts(path.join(STARTER_SRC, KNOWLEDGE_FILE), true).map((c) => c.text));
});

it('the menu is the Starter\'s five object entries: companies, contacts, articles, and the platform\'s tasks and notes', () => {
const starter = navigation(path.join(STARTER_SRC, 'apps', 'starter.app.ts'), true);
const template = navigation(path.join(BLANK_SRC, 'apps', 'main.app.ts'), false);
Expand Down
Loading
Loading