Skip to content
Closed
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 @@ -9,6 +9,7 @@ import * as dashboards from './src/dashboards/index.js';
import * as datasets from './src/datasets/index.js';
import * as translations from './src/translations/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 @@ -47,6 +48,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' },
},
};
64 changes: 64 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,67 @@ 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([]);
});
});
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
33 changes: 31 additions & 2 deletions packages/create-objectstack/src/templates/blank/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ as source you own:
`src/views/article.view.ts` — a grid of every article.
- `src/apps/main.app.ts` — the menu: Companies, Contacts, Articles, Tasks and
Notes.
- `src/knowledge/articles.knowledge-source.ts` — a knowledge source over the
published help articles, each `##` section one passage: see
[Search the help articles](#search-the-help-articles).

**Tasks and Notes are the platform's own objects** (`sys_task`, `sys_note`),
which every environment carries. This project declares no copy of them: the
Expand All @@ -54,8 +57,9 @@ a note never changes who may see the record it is about.

Change any of it freely: rename a field, add one, or replace both objects with
your own. To remove companies and contacts entirely (help articles go the same
way: their object, view, menu entry, `src/data/articles.ts`, and its entry in
`data` in `objectstack.config.ts`):
way: their object, view, menu entry, `src/data/articles.ts` and its entry in
`data`, and `src/knowledge/articles.knowledge-source.ts` and its entry in
`knowledgeSources`, both in `objectstack.config.ts`):

1. Delete `src/objects/company.object.ts` and `src/objects/contact.object.ts`
and their export lines in `src/objects/index.ts`.
Expand All @@ -68,6 +72,28 @@ way: their object, view, menu entry, `src/data/articles.ts`, and its entry in
do.
4. Run `pnpm validate` and `pnpm test`.

## Search the help articles

`src/knowledge/articles.knowledge-source.ts` makes the published articles
searchable by meaning, through the `search_knowledge` tool AI clients see on
your app's MCP server. It is served only where knowledge retrieval is enabled:
with no embedder configured (as after scaffolding, in `pnpm dev` and in
`pnpm test`) the source is held. Nothing is indexed or sent anywhere, no
`search_knowledge` tool is listed, and the boot says so in one `info` line.

To enable it on a self-hosted deployment:

1. In the Console, open Settings, then **AI → Embedder**, and save a provider
and its API key.
2. Restart the server. The embedder is read when the server starts, so a saved
change takes effect only after a restart.

At that start the published articles are indexed, and each time one changes
afterwards. **The body of every published article is sent to the embedding
provider you saved**, and only the body (which opens with the title): drafts
and the other fields are not. To send another field, list it in the source's
`content`.

## The Console

`pnpm dev` also serves the admin Console at `http://localhost:3000/_console/`,
Expand Down Expand Up @@ -114,6 +140,9 @@ for OAuth, API keys, and which objects/actions become tools.
- `src/apps/` — the app, `main.app.ts`, described in
[The Console](#the-console); `src/views/` — the companies', contacts' and
articles' list views
- `src/knowledge/` — the knowledge source over the help articles, listed by
name in `knowledgeSources`, described in
[Search the help articles](#search-the-help-articles)
- `src/data/` — sample rows, seeded on each boot. `objectstack generate` writes
no seed, so the config lists each one by name in `data`: list a new one there
too
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as picklists from './src/picklists';
import * as permissions from './src/security';
import * as datasets from './src/datasets';
import { articles } from './src/data';
import { ArticlesKnowledge } from './src/knowledge/articles.knowledge-source';

// Every value a barrel exports, as the list a stack key takes: typed by what
// the barrel exports, and an empty list while it exports nothing yet.
Expand Down Expand Up @@ -90,4 +91,11 @@ export default defineStack({
// Sample rows (src/data/): each boot inserts a row that is missing and
// leaves one that exists as it is.
data: [articles],

// The help articles as a knowledge source (src/knowledge/), listed by name
// like the sample rows. It needs no entry in `requires`: the source itself
// brings the knowledge service, which serves it only once an embedder
// provider is saved in Settings and the server restarted. Until then the
// source is held, and nothing is indexed or sent anywhere.
knowledgeSources: [ArticlesKnowledge],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

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

// The help articles, searchable by meaning: a knowledge source tells the
// platform which records to index and which of their fields become
// searchable text. It is the same definition as the platform's Starter app.
//
// It is served only where knowledge retrieval is enabled. With no embedder
// configured (a fresh project, `pnpm dev`, `pnpm test`) the source is held:
// nothing is indexed, nothing is sent anywhere, and AI clients are not offered
// a `search_knowledge` tool. Save an embedder provider in Settings and restart
// the server, and the published articles are indexed and searchable. The
// README's "Search the help articles" says how, and what is sent where.
//
// - `content` lists the fields whose text is indexed, and so sent to the
// embedding provider: only `body`. The body opens with the article's title
// as a `#` heading, so `title` is not listed (it would become a passage
// holding nothing but the title).
// - `split: markdown` makes each `##` section of an article one passage.
// - `where` keeps drafts out: an article is searchable once it is published.
// - `metadataFields` keeps `category` beside each passage, to narrow a search.
// - No `adapter`: the deployment's own store holds the index.
export const ArticlesKnowledge: KnowledgeSource = {
name: 'blank_articles',
label: 'Help articles',
description: 'The published help articles, one passage per section.',
source: {
kind: 'object',
object: 'blank_article',
content: ['body'],
metadataFields: ['category'],
where: { status: 'published' },
split: { strategy: 'markdown' },
},
};
Loading
Loading