Skip to content
Draft
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
11 changes: 11 additions & 0 deletions .changeset/37310-skill-knowledge-source-metadata.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@objectstack/skills': patch
---

docs(skills): `objectstack-ai` teaches `knowledge_source` as a metadata item

Clause-②: no
Metadata-protocol: none

`skills/objectstack-ai` § Knowledge Sources (RAG) now teaches the shape the 19 spec accepts. A source is a `knowledge_source` item shipped in a package (`knowledgeSources`, `*.knowledge-source.ts` / `.yml`) or authored in Studio or over MCP, with registration in code as a second door for the same schema. The key table lists `name`, `label`, `description`, the optional `adapter` (omitted, the source binds to the deployment's store), `source.object`, `source.content` (an explicit, non-empty list: `'*'` is refused because embedding is egress), `source.metadataFields`, `source.where`, `source.split`, `refresh.onRecordChange` and `aiExposed`. An item mounts the knowledge service with no `requires: ['knowledge']`. The section says that a source's first build sends every listed field of every matching record to the embedding provider, and that a run-time save needs `manage_knowledge_sources` and passes save-time admission. It names each key retired in 19 with its fix: `id` → `name`, `contentFields` → `content`, `embedding`, `vectorStore`, `adapterConfig`, `refresh.cron`, and the `file` and `http` arms. `split.strategy` is required once `split` is written. The eval cases for knowledge sources move to the same shape, and a new case asks for a wildcard source.

52 changes: 52 additions & 0 deletions packages/runtime/src/domains/mcp-authoring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,58 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl
expect(missing.body.contract).toBeUndefined();
});

it('[ADR-0161 K4, K5] the knowledge_source contract serves the content rule and no create seed; a source with one object and one content field saves, a wildcard or a retired key is refused', async () => {
const metadata = new MetadataManager({} as never);
metadata.setTypeRegistry(DEFAULT_METADATA_TYPE_REGISTRY);
const protocol = await realProtocol(new Map([['metadata', metadata]]));
const { authoring } = await authorThroughDomain({ protocol, systemPermissions: ['manage_metadata', 'manage_knowledge_sources'] });
const entry = (await protocol.getMetaTypes!()).entries!.find((e) => e.type === 'knowledge_source') as any;

const { contract } = (await call(authoring, 'list_metadata_items', { type: 'knowledge_source', contract: true })).body;
expect(contract.form).toBe('lean');
// No seed is served: the type stays unseeded until the Studio form builds `source` (metadata-create-seeds.test.ts).
expect(getMetadataCreateSeed('knowledge_source')).toBeUndefined();
expect(contract).not.toHaveProperty('createSeed');
expect(Object.keys(contract.schema.properties)).toEqual(Object.keys(entry.schema.properties));

// The content rule, as the served schema states it: a non-empty list, no empty name, no `'*'` member.
const contentPath = '/properties/source/properties/content';
const content = (await call(authoring, 'list_metadata_items', { type: 'knowledge_source', contract: true, contractPath: contentPath })).body.contract;
expect(content).toMatchObject({ form: 'full', path: contentPath });
expect(content.schema).toEqual(entry.schema.properties.source.properties.content);
expect(content.schema.minItems).toBe(1);
expect(content.schema.items).toMatchObject({ minLength: 1 });
expect(new RegExp(content.schema.items.pattern).test('*')).toBe(false);
expect(new RegExp(content.schema.items.pattern).test('body')).toBe(true);

// A tombstone is not served: the served schema publishes what an author MAY write (`{ not: {} }` is
// dropped). Its prescription reaches the author through the save, below.
expect(entry.schema.properties.id).toBeUndefined();
expect(entry.schema.properties.source.properties.contentFields).toBeUndefined();

// A source with one object and one content field saves as a draft; with a wildcard it is refused and nothing is written.
const item = { name: 'crm_opportunity_notes', label: 'Opportunity notes', source: { kind: 'object', object: 'crm_opportunity', content: ['name'] } };
const saved = await call(authoring, 'save_metadata_draft', { type: 'knowledge_source', name: item.name, item, package: STUDIO_BASE });
expect(saved.isError, JSON.stringify(saved.body)).toBe(false);
expect(saved.body.saved).toMatchObject({ type: 'knowledge_source', name: 'crm_opportunity_notes', package: STUDIO_BASE, state: 'draft' });

const wildcard = { ...item, name: 'crm_opportunity_all', source: { ...item.source, content: ['*'] } };
const refused = await call(authoring, 'save_metadata_draft', { type: 'knowledge_source', name: wildcard.name, item: wildcard, package: STUDIO_BASE });
expect(refused.body.error).toMatchObject({ code: 'INVALID_METADATA', status: 422 });
expect(JSON.stringify(refused.body.error.issues)).toContain('content');

// A retired key is refused with its tombstone's prescription, as the describe reads.
for (const [retired, replacement] of [
[{ ...item, name: 'crm_opportunity_id', id: 'crm_opportunity_id' }, '`name`'],
[{ ...item, name: 'crm_opportunity_cf', source: { ...item.source, contentFields: ['name'] } }, '`content`'],
] as const) {
const tomb = await call(authoring, 'save_metadata_draft', { type: 'knowledge_source', name: retired.name, item: retired, package: STUDIO_BASE });
expect(tomb.body.error, replacement).toMatchObject({ code: 'INVALID_METADATA', status: 422 });
expect(JSON.stringify(tomb.body.error.issues), replacement).toContain(`use ${replacement}`);
}
expect((await call(authoring, 'list_drafts', { package: STUDIO_BASE })).body.drafts.map((d: any) => d.name)).toEqual(['crm_opportunity_notes']);
});

it('an inherited member\'s name as `type`, which the fold keeps as sent, is refused and writes nothing', async () => {
const protocol = await realProtocol();
const { authoring } = await authorThroughDomain({ protocol });
Expand Down
14 changes: 9 additions & 5 deletions packages/spec/src/kernel/metadata-create-seeds.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,15 @@ describe('metadata create seeds validate against their spec schemas', () => {
// from `view` until card ③ (#37087), which brings the designer and its
// seed. Deferred work, named here so it is not a silent gap.
'form',
// [ADR-0161 K4] `knowledge_source` is runtime-creatable, and its create
// seed is deferred work with a name: it lands with the Studio form and
// the MCP create seed (rows 5 and 5b of #37000), which are what would
// serve one. Until then a source is created by a `/meta` save or shipped
// in a package, never from a blank form.
// [ADR-0161 K4, K5] `knowledge_source` is runtime-creatable, and its
// create seed is deferred work with a name: it lands with the Studio
// form (row 5 of #37000). The type's object binding and its content list
// sit inside `source`, and K5 makes `content` non-empty, so a seed that
// passes the schema carries a placeholder object AND a placeholder field
// there. The Studio create flow takes placeholder identity out only at
// the top level (objectui#12810), so it would save both into a new
// source. Until the form builds `source` from the author's input, a
// source is created by a `/meta` or MCP save, or shipped in a package.
'knowledge_source',
]);
const seeded = new Set(listMetadataCreateSeedTypes());
Expand Down
17 changes: 16 additions & 1 deletion scripts/check-skills-token-ratchet.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,22 @@ export const CEILINGS = new Map([
// 6791 -> 6609: the section that taught an authored AI button on a record
// page is replaced by one sentence (ADR-0160 D6, "Entry point": the shell's
// entry is the only one); the row follows the measurement down.
['skills/objectstack-ai/SKILL.md', 6609], // -18 (was 6824), then -5 A2′ (was 6806)
// 6609 -> 6639 (2026-11-27, the ADR-0161 K6 item 6 skills follow-up): § Knowledge
// Sources teaches the `knowledge_source` item (`name`, an explicit `content`
// list with `'*'` refused, the optional `adapter`, the item that mounts the
// service), egress and cost with the save-time permission and admission, the
// retired keys with their fixes, and `split.strategy` as required. Raise path
// the standing ruling 「A:先削重复,余额按实测提高」 (ruling record 6513306068,
// letter B). PAID DOWN FIRST: the wiring paragraph's package list, the old key
// table's `source.kind` Hygiene column (folded into the `content` and `where`
// rows), the example's four comments restating those rows and its
// `refresh: { onRecordChange: true }` line restating the default, and the
// split passage's adapter-list aside. Arithmetic in priced bytes (stamp line
// excluded), against `main`'s 26435 (headroom 0): the file is 26462 -> 26581
// bytes, so the LANDED priced text is 26554 -> ceil(26554 / 4) = 6639; the row
// moves +30, the measured remainder only. Pinned AT the measurement.
// ceil(($(wc -c < skills/objectstack-ai/SKILL.md) - 27) / 4) == ceil(26554 / 4)
['skills/objectstack-ai/SKILL.md', 6639], // -18 (was 6824), then -5 A2′ (was 6806)
// -12 (was 6331): the `http.server` decision-table row dropped a trailing
// clause that taught `contributes.routes` as a key that "parses but serves
// nothing". The key is retired — an authored entry is now REFUSED, carrying
Expand Down
89 changes: 47 additions & 42 deletions skills/objectstack-ai/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,35 +233,42 @@ names, a skill's `context` over MCP, `os validate` rules:

## Knowledge Sources (RAG)

The RAG primitive is the **KnowledgeSource** (`KnowledgeSourceSchema` in
`@objectstack/spec/ai`): declarative metadata pairing *what to index* with the id
of an `IKnowledgeAdapter` that does the work. There is no `defineStack`
collection for them — they are registered at runtime, and the ☁️
`search_knowledge` tool exposes registered sources to agents.

**Wiring (open packages).** `KnowledgeServicePlugin({ sources })` from
`@objectstack/service-knowledge` registers `IKnowledgeService` with the kernel and
each source at boot (`service.registerSource` still works later). The `adapter`
id resolves against an adapter plugin — `@objectstack/knowledge-memory` (`'memory'`,
dev/test), `@objectstack/knowledge-pgvector` (`'pgvector'`) or `@objectstack/knowledge-turso` (`'turso'`).

| Property | Purpose |
|:---------|:--------|
| `id` | Snake_case source id |
A RAG source is a **`knowledge_source`** metadata item (`KnowledgeSourceSchema`
in `@objectstack/spec/ai`): which records of one object are indexed, and which
of their fields. Ship it in a package (`knowledgeSources`,
`*.knowledge-source.ts` / `.yml`) or author it in Studio or over MCP;
`KnowledgeServicePlugin({ sources })` and `registerSource` are a second door for
the same schema, and one name is one source. An item mounts the knowledge
service and its store with no `requires: ['knowledge']`, and the ☁️
`search_knowledge` tool serves the sources to agents.

**A source is an egress and cost decision.** Its first build sends every listed
field of every matching record to the embedding provider and keeps the text in
an index. A run-time save needs `manage_knowledge_sources` beside
`manage_metadata`, and is refused, naming the object or field, when you may not
search that object or query a listed field.

| Key | Purpose |
|:----|:--------|
| `name` | Snake_case source name: what `search_knowledge` lists and its `sourceIds` names |
| `label` / `description` | Display metadata |
| `adapter` | Adapter id, resolved via `IKnowledgeService.registerAdapter` |
| `adapterConfig` | Adapter-specific configuration (opaque to the service) |
| `source` | What gets indexed — discriminated on `kind`: `'object'` \| `'file'` \| `'http'` |
| `embedding` | Optional `EmbeddingModelSchema` ref (`provider`, `model`, `dimensions`) — adapters managing embeddings internally may ignore it |
| `vectorStore` | Optional `VectorStoreSchema` ref (`provider`, `collection`) — same caveat |
| `refresh` | `onRecordChange` (default `true` for object sources) + optional `cron` (for an external scheduler; not self-scheduled) |
| `aiExposed` | May `search_knowledge` expose this source to agents (default `true`) — `false` indexes it without making it agent-searchable |

| `source.kind` | Fields | Hygiene |
|:--------------|:-------|:--------|
| `object` | `object`, `contentFields[]` (min 1; `*` = every readable text field), `metadataFields?`, `where?` (ObjectQL `where` syntax), `split?` (below) | `where` keeps drafts and archived rows out of the index; `contentFields` takes meaningful text only (never system fields or ids, `*` sparingly); project what you will filter on at query time (`status`, `owner_id`, `tags`) into `metadataFields` |
| `file` | `prefix` (storage prefix, e.g. `kb/handbooks/`), `mimeTypes?` | narrow the prefix instead of indexing a whole bucket |
| `http` | `urls[]`, `userAgent?` | enumerate URLs explicitly — there is no crawler |
| `adapter` | Optional store id (`pgvector`, `turso`, `memory`). Omitted: the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise), else the only one registered; several and none the deployment's is refused, naming them |
| `source.kind` | `'object'`, the one kind |
| `source.object` | The object whose records are indexed |
| `source.content` | Non-empty list of the fields whose text is indexed, in order. `'*'` is refused: embedding is egress, and a wildcard also sent fields added later. Meaningful text only, never ids or system fields; credential-class and `internal` fields are never indexed |
| `source.metadataFields` | Fields kept for search-time filtering (`status`, `owner_id`, `tags`) |
| `source.where` | ObjectQL `where`: keeps drafts and archived rows out |
| `source.split` | How documents are cut into passages (below) |
| `refresh.onRecordChange` | Sync from record events (default `true`); `false` leaves the index to an external indexer |
| `aiExposed` | May `search_knowledge` expose it (default `true`) |

Retired in 19, each refused with its fix: `id` (use `name`), `contentFields`
(use `content`, listing the fields a `'*'` stood for), `embedding` (the
deployment configures one embedder), `vectorStore` (the store is `adapter`),
`adapterConfig` (an adapter takes plugin options), `refresh.cron` (call
`reindexSource` from a flow or job), and `source.kind: 'file'` / `'http'` with
`prefix`, `mimeTypes`, `urls`, `userAgent` (no form in 19). `os migrate meta
--from 18` lists a stack's edits; edit a registration in code by hand.

<!-- os:check -->
```typescript
Expand All @@ -270,25 +277,23 @@ import { KnowledgeSourceSchema, type KnowledgeSource } from '@objectstack/spec/a
export const supportKb: KnowledgeSource = KnowledgeSourceSchema.parse({
name: 'support_kb',
label: 'Support Knowledge Base',
adapter: 'pgvector',
source: {
source: { // no adapter: the deployment's store
kind: 'object',
object: 'kb_article',
content: ['title', 'body'], // joined into document content
metadataFields: ['category', 'owner_id'], // projected for search-time filtering
where: { published: true }, // index published articles only
content: ['title', 'body'],
metadataFields: ['category', 'owner_id'],
where: { published: true },
},
refresh: { onRecordChange: true }, // re-index on record.* events
});
```

**Splitting (`split`, object sources only).** The knowledge service cuts each
document into passages for an adapter declaring `capabilities.chunks`
(`memory`, `pgvector`, `turso`). Any other adapter receives whole documents;
`split` has no effect on it. `split: { strategy, maxChars?, minChars? }`:
**Splitting (`split`).** The knowledge service cuts each document into passages
for a store declaring `capabilities.chunks`; any other store receives whole
documents. `split: { strategy, maxChars?, minChars? }` — `strategy` is required
once `split` is written; an omitted `split` means `recursive`:

- `recursive` (default): cuts at blank lines, then line breaks, then sentence
ends. For prose.
- `recursive`: cuts at blank lines, then line breaks, then sentence ends. For
prose.
- `markdown`: one section per heading, each passage embedded with its heading
path. For documents with headings.
- `whole`: one passage per document. For short records only: a document over
Expand All @@ -305,8 +310,8 @@ Retired and refused: the `knowledge.chunk_overlap` setting (`400 UNKNOWN_KEY`;
passages never overlap) and `KnowledgeChunk.metadata` (parse error; a passage
takes its document's `metadata`).

Top-K, score thresholds and rerankers are not source metadata: they belong to
the adapter or application code.
`topK` is a `search_knowledge` argument; rerank and hybrid weights are options
of the store's plugin. Neither is source metadata.

---

Expand Down
Loading
Loading