diff --git a/.changeset/34761-list-datasets-candidates.md b/.changeset/34761-list-datasets-candidates.md new file mode 100644 index 00000000000..d4934291f90 --- /dev/null +++ b/.changeset/34761-list-datasets-candidates.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): the `list_datasets` output declares `candidates`, the members offered for a clarifying question when a term matched nothing (ADR-0149 D3) + +Clause-②: yes (widening — an optional output field on a published schema) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-ask/SKILL.md (zero-match row reads candidates once #34763 lands) + +`ListDatasetsOutputSchema` (`@objectstack/spec/ai`) gains one optional member, `candidates`, with its entry schema `DatasetTermCandidateSchema` (type `DatasetTermCandidate`) and the per-term cap `LIST_DATASETS_MAX_CANDIDATES_PER_TERM` (5). Nothing is removed or renamed, and an answer without the key parses as it did. + +- **What it is.** For a term the caller sent that matched no member of any listed dataset, the members the platform offers as possible readings. Each entry is a pointer `{ term, dataset, member }` to a member listed in the same answer: `dataset` is a `datasets[].name`, `member` is `measures.` or `dimensions.`. Only members the caller may read are offered. The label, dataset label and description a clarifying question lists are read from that `datasets` entry. +- **What it is not.** A candidate is not a match. `matches`, and what counts as a match (equality after normalization, ADR-0149 D3 rule 1), are unchanged, and an entry carries no `matchedOn`. The platform selects none of them. The list carries no score, and its order is the listing order: terms as sent, datasets as listed, a dataset's measures before its dimensions, at most five per term. +- **When it is present.** Only when `terms` were sent and a term that matched nothing has a candidate. No candidates is the key's absence: an empty list does not parse. A term with a match has none. +- **Who fills it.** This change declares the shape only, and the tool's `outputSchema` (`getDatasetToolJsonSchemas().list_datasets.outputSchema`) lists the member from it. Filling the list is the `list_datasets` executor's change in `@objectstack/service-analytics`, which ships under its own entry; an answer carries `candidates` only from a release that has both. + +ADR-0149 D3 gains an add-only amendment note recording the ruling: a term with no match and with candidates is asked about in rule 3's form and none is acted on; with no candidate, rule 4's fallback is unchanged. + +Level: `minor` for `@objectstack/spec`, the level `Metadata-protocol: added` takes. The `authorable-surface/ai.json` baseline records the new keys: `ai/ListDatasetsOutput:candidates` and the three `ai/DatasetTermCandidate` members. diff --git a/content/docs/references/ai/dataset-tools.mdx b/content/docs/references/ai/dataset-tools.mdx index 4994e344b6c..a69e3632d2f 100644 --- a/content/docs/references/ai/dataset-tools.mdx +++ b/content/docs/references/ai/dataset-tools.mdx @@ -12,7 +12,8 @@ Dataset AI tools — the inputs and outputs of `list_datasets` and The two tools give an AI the business semantic layer a person already reads through dashboards and reports: `list_datasets` returns the catalogue (the datasets the caller may query, their dimensions and measures, each member's -business vocabulary, and which of the caller's words matched which member), +business vocabulary, which of the caller's words matched which member, and, +for a word that matched nothing, the members offered as `candidates`), and `query_dataset` runs a `DatasetSelection` against one saved dataset and answers rows plus a `provenance` block naming the dataset and the measures used. The shapes are declared here once and projected to the JSON Schema an @@ -27,7 +28,8 @@ inline `dataset` and no `previewDrafts` on this tool, because an AI that could author a dataset inline could author its own 口径. Only the shapes are spec. The executor, the catalogue builder with its -admission and member withholding, the term matcher and the row cap +admission and member withholding, the term matcher, the rule that finds a +zero-match term's candidates and the row cap (`selection.limit` held to the bridge's `maxQueryLimit`) belong to `@objectstack/service-analytics` (card #31589); the MCP registration under `data:read` to `@objectstack/mcp` (card #31590). The tool descriptions, which @@ -41,8 +43,8 @@ executor: AI guidance text does not enter the spec (ADR-0149 M1, ruled A). ## TypeScript Usage ```typescript -import { DatasetProvenanceSchema, DatasetTermMatchSchema, DatasetTermMatchedOn, DatasetToolCatalogDimensionSchema, DatasetToolCatalogEntrySchema, DatasetToolCatalogMeasureSchema, ListDatasetsInputSchema, ListDatasetsOutputSchema, QueryDatasetInputSchema, QueryDatasetOutputSchema } from '@objectstack/spec/ai'; -import type { DatasetProvenance, DatasetTermMatch, DatasetTermMatchedOn, DatasetToolCatalogDimension, DatasetToolCatalogEntry, DatasetToolCatalogMeasure, ListDatasetsInput, ListDatasetsOutput, QueryDatasetInput, QueryDatasetOutput } from '@objectstack/spec/ai'; +import { DatasetProvenanceSchema, DatasetTermCandidateSchema, DatasetTermMatchSchema, DatasetTermMatchedOn, DatasetToolCatalogDimensionSchema, DatasetToolCatalogEntrySchema, DatasetToolCatalogMeasureSchema, ListDatasetsInputSchema, ListDatasetsOutputSchema, QueryDatasetInputSchema, QueryDatasetOutputSchema } from '@objectstack/spec/ai'; +import type { DatasetProvenance, DatasetTermCandidate, DatasetTermMatch, DatasetTermMatchedOn, DatasetToolCatalogDimension, DatasetToolCatalogEntry, DatasetToolCatalogMeasure, ListDatasetsInput, ListDatasetsOutput, QueryDatasetInput, QueryDatasetOutput } from '@objectstack/spec/ai'; // Validate data const result = DatasetProvenanceSchema.parse(data); @@ -85,6 +87,19 @@ const result = DatasetProvenanceSchema.parse(data); | **label** | `string` | ✅ | Dimension label at the caller's locale | +--- + +## DatasetTermCandidate + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **term** | `string` | ✅ | The caller's term, as sent in `terms`: one that matched no member of any listed dataset | +| **dataset** | `string` | ✅ | The dataset the offered member belongs to, by name: an entry of `datasets` in the same answer, and what `query_dataset` takes as `datasetName` | +| **member** | `string` | ✅ | The member offered, as `measures.` or `dimensions.`: a member that dataset's entry lists. The term does not equal any of its words after normalization | + + --- ## DatasetTermMatch @@ -211,6 +226,7 @@ const result = DatasetProvenanceSchema.parse(data); | **datasets** | `{ name: string; label: string; description?: string; object: string; … }[]` | ✅ | The datasets this caller may query. A dataset the caller may not query is absent, the same answer as one that does not exist | | **partial** | `true` | optional | Present, and `true`, when the dataset read was degraded and `datasets` may be incomplete; `warning` says why. Absent on a complete answer | | **warning** | `string` | optional | Why the answer is partial; present exactly when `partial` is | +| **candidates** | `{ term: string; dataset: string; member: string }[]` | optional | Members offered as possible readings of a term that matched no member of any listed dataset, for a clarifying question. A candidate is not a match: its term has no entry in any dataset's `matches`. The platform selects none: the list carries no score, and its order is the listing order stated here, not a ranking. Every candidate is a member this caller may read, listed in `datasets`. Terms in the order sent; for one term, datasets in the order listed, and each dataset's measures before its dimensions, as its entry lists them; at most 5 per term, the first in that order. Present only when `terms` were sent and a term that matched nothing has a candidate; absent otherwise, never an empty list. A term with a match has no candidate | ### Nested Shape: `ListDatasetsOutput.datasets[number]` @@ -225,6 +241,14 @@ const result = DatasetProvenanceSchema.parse(data); | **measures** | `{ name: string; label: string; description?: string; aggregate?: Enum<'count' \| 'sum' \| 'avg' \| 'min' \| 'max' \| 'count_distinct'>; … }[]` | ✅ | The measures this caller may read | | **matches** | `{ term: string; member: string; matchedOn: Enum<'name' \| 'label' \| 'synonym'> }[]` | optional | Each of the caller's `terms` that matched a member of this dataset, computed by the platform under the same normalization the dataset's own validation uses. Absent when no `terms` were sent | +### Nested Shape: `ListDatasetsOutput.candidates[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **term** | `string` | ✅ | The caller's term, as sent in `terms`: one that matched no member of any listed dataset | +| **dataset** | `string` | ✅ | The dataset the offered member belongs to, by name: an entry of `datasets` in the same answer, and what `query_dataset` takes as `datasetName` | +| **member** | `string` | ✅ | The member offered, as `measures.` or `dimensions.`: a member that dataset's entry lists. The term does not equal any of its words after normalization | + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index d6c69c93bff..041ab33b738 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1669 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1670 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 14 | 82 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 496 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 188 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,13 +34,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 177 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1669** | 14 protocol modules | +| **Total** | **218** | **1670** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 81 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 82 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -49,7 +49,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`agent.zod.ts`](/docs/references/ai/agent) | `AIModelConfig`, `Agent`, `StructuredOutputConfig`, `StructuredOutputFormat`, `TransformPipelineStep` | | [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` | | [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` | -| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetProvenance`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | +| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`embedding.zod.ts`](/docs/references/ai/embedding) | `EmbeddingModel`, `VectorStore`, `VectorStoreProvider` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | | [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSourceKind`, `ObjectKnowledgeSource` | diff --git a/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md b/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md index e6a4a150c04..8ebae3485f6 100644 --- a/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md +++ b/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md @@ -156,6 +156,17 @@ The rule is stated once here and carried in three places: the tool descriptions Why the platform computes `matches` instead of leaving the whole rule to the model: 防 AI 犯错. The model still decides what the question's terms are; whether a term equals a synonym is a string comparison, and a string comparison belongs where it can be unit-tested and where every consumer gets the same answer. +> **Amendment note (2026-11-17, [#34761](https://github.com/objectstack-ai/objectstack/issues/34761) — this PR): a term with no hit is answered with `candidates`, offered for a question and never selected.** +> Ruled by the maintainer on [#34691](https://github.com/objectstack-ai/objectstack/issues/34691), fork F1, option B, option text verbatim 「B 零命中返回候选」 — 「现在就改服务器,list_datasets 零命中时返回候选数据集。专题席的新推荐。」 (ruling record [`6943126855`](https://github.com/objectstack-ai/objectstack/issues/34691#issuecomment-6943126855), relayed to #34659 as `6943149235`). It re-rules point E2 of #34659's record `6940528935`, where `list_datasets` stayed exact-match with no candidates list on a named premise, to that point's option A. The contract is `packages/spec/src/ai/dataset-tools.zod.ts#ListDatasetsOutputSchema` (its `candidates` member) with `packages/spec/src/ai/dataset-tools.zod.ts#DatasetTermCandidateSchema`; this note points at it without restating every case. +> +> - **What counts as a hit does not change.** This note changes no word of rule 1: equality after normalization is a hit, and a substring, a stem or an embedding neighbour is not. `matches` is computed as before, and rules 2, 3 and 5 read it as before. +> - **A term with no hit in any listed dataset gets `candidates`.** The `list_datasets` output of [D2](#d2--two-tools-one-definition-one-executor-two-transports) gains one optional member beside the ones D2 lists, which stand as written. For such a term it names the members the platform offers as possible readings, each a pointer `{ term, dataset, member }` to a member listed in the same answer, so only a member this caller may read is ever offered. This is rule 1's parenthesis as a platform answer: a non-hit "may be offered in rule 3's question, never acted on". The list carries no score. Its order is the listing order: terms as sent, datasets as listed, a dataset's measures before its dimensions (rule 5: a dimension alone is not an answer), held to `LIST_DATASETS_MAX_CANDIDATES_PER_TERM` per term. A term with a hit has no candidates and an answer with none to offer carries no `candidates` key, so an answer in which every term sent has a hit, like an answer to a call that sent no `terms`, is what it was. Which members are near enough to offer is the executor's rule; this record and the spec say what a candidate is, not how it is found. +> - **With candidates, the AI asks in rule 3's form and acts on none.** The question lists each candidate's label, dataset label and description, as rule 3 lists several hits. The AI does not pick one, does not prefer the first, and does not treat a candidate as a hit under rule 2: the choice is the person's. +> - **With no candidate, rule 4 is unchanged.** No hit and nothing offered is the labelled fallback to the object query, as written; [M2](#m2--what-the-ai-does-when-no-dataset-covers-the-question) stays ruled A. +> - **Rule 4 is named here because its path changes and its matching does not.** A term with no hit used to go straight to the fallback; a clarifying question may now come first. The term still has no hit, so rule 4 still governs it when the question settles nothing. +> - **Why the platform offers them, and not only the client's wording.** A tool result is read by every client that made the call; a tool description is read only after the client chose the tool, and a skill only when it is installed and triggered (the grounds of fork F1 on #34691). It is the reason given above for `matches`: every consumer gets the same answer. +> - **State on `main`.** This PR declares the shape and changes no executor. The executor that fills `candidates`, and the tool descriptions that carry this branch to the model, land with [#34763](https://github.com/objectstack-ai/objectstack/issues/34763); until then no answer carries the key. In [D6](#d6--enforce-or-remove-every-key-names-its-reader-in-its-first-implementation-card)'s terms the pending half is named here, by card, and not hidden. + ### D4 — Permissions: the tools add no gate and bypass none Measured in [Context](#the-executor-and-its-gate-chain-measured-on-originmain). The binding statements: diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 67c86593be3..8e5ab008a41 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 96 | +| `ai/` | 97 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 647ed0dd18d..ccd723b8d1a 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -58,6 +58,8 @@ "ConversationSummarySchema (const)", "DatasetProvenance (type)", "DatasetProvenanceSchema (const)", + "DatasetTermCandidate (type)", + "DatasetTermCandidateSchema (const)", "DatasetTermMatch (type)", "DatasetTermMatchSchema (const)", "DatasetTermMatchedOn (const)", @@ -95,6 +97,7 @@ "KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", + "LIST_DATASETS_MAX_CANDIDATES_PER_TERM (const)", "LIST_DATASETS_TOOL_NAME (const)", "ListDatasetsInput (type)", "ListDatasetsInputSchema (const)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 6ed947a9101..f9c51d0e5ec 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -163,6 +163,9 @@ "ai/DatasetProvenance:kind", "ai/DatasetProvenance:measures", "ai/DatasetProvenance:runtimeFilter", + "ai/DatasetTermCandidate:dataset", + "ai/DatasetTermCandidate:member", + "ai/DatasetTermCandidate:term", "ai/DatasetTermMatch:matchedOn", "ai/DatasetTermMatch:member", "ai/DatasetTermMatch:term", @@ -242,6 +245,7 @@ "ai/KnowledgeSource:source", "ai/KnowledgeSource:vectorStore", "ai/ListDatasetsInput:terms", + "ai/ListDatasetsOutput:candidates", "ai/ListDatasetsOutput:datasets", "ai/ListDatasetsOutput:partial", "ai/ListDatasetsOutput:warning", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 6bbb1f3b553..7bd7960b23f 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -44,6 +44,8 @@ "ConversationSummarySchema": "ai/ConversationSummary", "DatasetProvenance": "ai/DatasetProvenance", "DatasetProvenanceSchema": "ai/DatasetProvenance", + "DatasetTermCandidate": "ai/DatasetTermCandidate", + "DatasetTermCandidateSchema": "ai/DatasetTermCandidate", "DatasetTermMatch": "ai/DatasetTermMatch", "DatasetTermMatchSchema": "ai/DatasetTermMatch", "DatasetTermMatchedOn": "ai/DatasetTermMatchedOn", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index c0c06a0df9d..ec7a0b34718 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -58,6 +58,8 @@ "ConversationSummarySchema": "src/ai/conversation.zod.ts#ConversationSummarySchema (const)", "DatasetProvenance": "src/ai/dataset-tools.zod.ts#DatasetProvenance (type)", "DatasetProvenanceSchema": "src/ai/dataset-tools.zod.ts#DatasetProvenanceSchema (const)", + "DatasetTermCandidate": "src/ai/dataset-tools.zod.ts#DatasetTermCandidate (type)", + "DatasetTermCandidateSchema": "src/ai/dataset-tools.zod.ts#DatasetTermCandidateSchema (const)", "DatasetTermMatch": "src/ai/dataset-tools.zod.ts#DatasetTermMatch (type)", "DatasetTermMatchSchema": "src/ai/dataset-tools.zod.ts#DatasetTermMatchSchema (const)", "DatasetTermMatchedOn": "src/ai/dataset-tools.zod.ts#DatasetTermMatchedOn (type)", @@ -94,6 +96,7 @@ "KnowledgeSourceKindSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", + "LIST_DATASETS_MAX_CANDIDATES_PER_TERM": "src/ai/dataset-tools.zod.ts#LIST_DATASETS_MAX_CANDIDATES_PER_TERM (const)", "LIST_DATASETS_TOOL_NAME": "src/ai/dataset-tools.zod.ts#LIST_DATASETS_TOOL_NAME (const)", "ListDatasetsInput": "src/ai/dataset-tools.zod.ts#ListDatasetsInput (type)", "ListDatasetsInputSchema": "src/ai/dataset-tools.zod.ts#ListDatasetsInputSchema (const)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 6276cf11bd1..0bc9bd67872 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -24,6 +24,7 @@ "ai/ConversationSession", "ai/ConversationSummary", "ai/DatasetProvenance", + "ai/DatasetTermCandidate", "ai/DatasetTermMatch", "ai/DatasetTermMatchedOn", "ai/DatasetToolCatalogDimension", diff --git a/packages/spec/src/ai/dataset-tools.test.ts b/packages/spec/src/ai/dataset-tools.test.ts index 2a4d0a867b1..41a8a38e13c 100644 --- a/packages/spec/src/ai/dataset-tools.test.ts +++ b/packages/spec/src/ai/dataset-tools.test.ts @@ -10,6 +10,10 @@ * selection's own aliases and guidance apply inside it; the query output takes * the dataset answer's members by reference and leaves out `sql`; the * projection is what an `AIToolDefinition` carries, built once. + * + * [ADR-0149 D3, amendment note] `list_datasets` answers a term that matched + * nothing with `candidates`: pointers to listed members, never a match and + * never an empty list, and an answer without the key parses as before. */ import { describe, expect, it } from 'vitest'; @@ -17,7 +21,9 @@ import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/an import { DatasetToolCatalogEntrySchema, DatasetProvenanceSchema, + DatasetTermCandidateSchema, DatasetTermMatchSchema, + LIST_DATASETS_MAX_CANDIDATES_PER_TERM, LIST_DATASETS_TOOL_NAME, ListDatasetsInputSchema, ListDatasetsOutputSchema, @@ -152,6 +158,65 @@ describe('list_datasets output', () => { }); }); +describe('list_datasets candidates', () => { + const entry = { + name: 'billing', + label: '开票', + object: 'invoice', + dimensions: [{ name: 'invoice_status', label: '发票状态', type: 'string' as const }], + measures: [{ name: 'invoice_count', label: '发票数', aggregate: 'count' as const }], + matches: [], + }; + const candidates = [ + { term: 'invoice', dataset: 'billing', member: 'measures.invoice_count' }, + { term: 'invoice', dataset: 'billing', member: 'dimensions.invoice_status' }, + ]; + + it('an answer carries them beside the catalogue, and the parse keeps them', () => { + const parsed = ListDatasetsOutputSchema.parse({ datasets: [entry], candidates }); + expect(parsed.candidates).toEqual(candidates); + }); + + it('an answer without the key parses to the same value as before', () => { + const answer = { datasets: [entry] }; + const parsed = ListDatasetsOutputSchema.parse(answer); + expect(parsed).toEqual(answer); + expect(Object.keys(parsed)).not.toContain('candidates'); + }); + + it('no candidates is the key\'s absence: an empty list is refused', () => { + const parsed = ListDatasetsOutputSchema.safeParse({ datasets: [entry], candidates: [] }); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues[0]?.path).toEqual(['candidates']); + }); + + it('a candidate is a pointer: term, dataset and member, all required, and no `matchedOn`', () => { + expect(Object.keys(DatasetTermCandidateSchema.shape).sort()).toEqual(['dataset', 'member', 'term']); + const [candidate] = candidates; + expect(DatasetTermCandidateSchema.safeParse(candidate).success).toBe(true); + for (const key of ['term', 'dataset', 'member'] as const) { + const { [key]: _omitted, ...rest } = candidate!; + const parsed = DatasetTermCandidateSchema.safeParse(rest); + expect(parsed.success, key).toBe(false); + expect(parsed.error?.issues[0]?.path, key).toEqual([key]); + } + }); + + it('names its member in the format a match does', () => { + const pointer = { term: 'x', dataset: 'billing' }; + for (const member of ['measures.invoice_count', 'dimensions.invoice_status', 'fields.status', 'invoice_count']) { + expect(DatasetTermCandidateSchema.safeParse({ ...pointer, member }).success, member) + .toBe(DatasetTermMatchSchema.safeParse({ term: 'x', matchedOn: 'name', member }).success); + } + expect(DatasetTermCandidateSchema.safeParse({ ...pointer, member: 'fields.status' }).success).toBe(false); + expect(DatasetTermCandidateSchema.safeParse({ ...pointer, member: 'measures.invoice_count' }).success).toBe(true); + }); + + it('the per-term cap is one exported number', () => { + expect(LIST_DATASETS_MAX_CANDIDATES_PER_TERM).toBe(5); + }); +}); + describe('query_dataset output', () => { const answer = { rows: [{ stage: 'Won', total_amount: 1200 }], @@ -219,4 +284,16 @@ describe('JSON Schema projection', () => { const catalogue = getDatasetToolJsonSchemas().list_datasets.outputSchema as { required: string[] }; expect(catalogue.required).toEqual(['datasets']); }); + + it('the `list_datasets` outputSchema carries `candidates`: optional, never empty, three required members', () => { + const outputSchema = getDatasetToolJsonSchemas().list_datasets.outputSchema as unknown as { + required: string[]; + properties: Record; + }; + expect(outputSchema.required).not.toContain('candidates'); + const candidates = outputSchema.properties.candidates; + expect(candidates?.type).toBe('array'); + expect(candidates?.minItems).toBe(1); + expect([...(candidates?.items?.required ?? [])].sort()).toEqual(['dataset', 'member', 'term']); + }); }); diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index 78097169085..bbb4dce7b5b 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -16,7 +16,8 @@ import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/an * The two tools give an AI the business semantic layer a person already reads * through dashboards and reports: `list_datasets` returns the catalogue (the * datasets the caller may query, their dimensions and measures, each member's - * business vocabulary, and which of the caller's words matched which member), + * business vocabulary, which of the caller's words matched which member, and, + * for a word that matched nothing, the members offered as `candidates`), * and `query_dataset` runs a `DatasetSelection` against one saved dataset and * answers rows plus a `provenance` block naming the dataset and the measures * used. The shapes are declared here once and projected to the JSON Schema an @@ -31,7 +32,8 @@ import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/an * author a dataset inline could author its own 口径. * * Only the shapes are spec. The executor, the catalogue builder with its - * admission and member withholding, the term matcher and the row cap + * admission and member withholding, the term matcher, the rule that finds a + * zero-match term's candidates and the row cap * (`selection.limit` held to the bridge's `maxQueryLimit`) belong to * `@objectstack/service-analytics` (card #31589); the MCP registration under * `data:read` to `@objectstack/mcp` (card #31590). The tool descriptions, which @@ -92,6 +94,53 @@ export const DatasetTermMatchSchema = lazySchema(() => z.object({ ), })); +/** + * How many candidates `list_datasets` lists for one term, at most + * ({@link ListDatasetsOutputSchema}'s `candidates`). + * + * Exported so the executor that fills the list and a client that reads it use + * the one number. Declared ahead of the schema on purpose: under + * `OS_EAGER_SCHEMAS=1` (`gen:schema`) the factory runs at module evaluation. + */ +export const LIST_DATASETS_MAX_CANDIDATES_PER_TERM = 5; + +/** + * One member offered as a possible reading of a term that matched nothing: an + * entry of {@link ListDatasetsOutputSchema}'s `candidates` (ADR-0149 D3, the + * amendment note under its rules). + * + * A candidate is NOT a match. A match ({@link DatasetTermMatchSchema}) says + * the term equals one of the member's words after normalization, and D3 rule + * 2 lets one match win. A candidate says only that the platform offers the + * member for a clarifying question; what counts as a match is unchanged, and + * a term has candidates only when it has no match anywhere in the answer. + * + * The entry is a pointer, `{ term, dataset, member }`, and carries no + * `matchedOn`: that key states an equality a candidate does not have. It + * carries no word the term was found near either. D3 rule 1 lets a substring, + * a stem or an embedding neighbour be offered, an embedding neighbour is near + * no single word of the member, and the rule that finds candidates is the + * executor's, so the shape does not presume it. The label, dataset label and + * description a clarifying question lists (D3 rule 3) are read from the + * `datasets` entry the pointer names, in the same answer. + * + * `member` is {@link DatasetTermMatchSchema}'s `member` BY REFERENCE under its + * own description: one member-reference format, declared once. + */ +export const DatasetTermCandidateSchema = lazySchema(() => z.object({ + term: z.string().describe( + 'The caller\'s term, as sent in `terms`: one that matched no member of any listed dataset', + ), + dataset: z.string().describe( + 'The dataset the offered member belongs to, by name: an entry of `datasets` in the same answer, and what ' + + '`query_dataset` takes as `datasetName`', + ), + member: DatasetTermMatchSchema.shape.member.describe( + 'The member offered, as `measures.` or `dimensions.`: a member that dataset\'s entry lists. The ' + + 'term does not equal any of its words after normalization', + ), +})); + /** * A dimension as the catalogue lists it. * @@ -175,6 +224,16 @@ export const ListDatasetsOutputSchema = lazySchema(() => z.object({ + 'why. Absent on a complete answer', ), warning: z.string().optional().describe('Why the answer is partial; present exactly when `partial` is'), + candidates: z.array(DatasetTermCandidateSchema).min(1).optional().describe( + 'Members offered as possible readings of a term that matched no member of any listed dataset, for a ' + + 'clarifying question. A candidate is not a match: its term has no entry in any dataset\'s `matches`. The ' + + 'platform selects none: the list carries no score, and its order is the listing order stated here, not a ' + + 'ranking. Every candidate is a member this caller may read, listed in `datasets`. Terms in the order sent; ' + + 'for one term, datasets in the order listed, and each dataset\'s measures before its dimensions, as its ' + + `entry lists them; at most ${LIST_DATASETS_MAX_CANDIDATES_PER_TERM} per term, the first in that order. ` + + 'Present only when `terms` were sent and a term that matched nothing has a candidate; absent otherwise, ' + + 'never an empty list. A term with a match has no candidate', + ), })); // ========================================== @@ -331,6 +390,7 @@ export function getDatasetToolJsonSchemas(): Readonly< export type ListDatasetsInput = z.input; export type DatasetTermMatchedOn = z.input; export type DatasetTermMatch = z.input; +export type DatasetTermCandidate = z.input; export type DatasetToolCatalogDimension = z.input; export type DatasetToolCatalogMeasure = z.input; export type DatasetToolCatalogEntry = z.input; diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 98d5e5a39d8..e5533095eb0 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -304,7 +304,7 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // --------------------------------------------------------------------------- -// 857 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 858 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -383,6 +383,7 @@ export type Iso_ai_conversation__TokenBudgetStrategySchema = Assert, z.infer< typeof M204.DatasetProvenanceSchema > >>; +export type Iso_ai_datasetTools__DatasetTermCandidateSchema = Assert, z.infer< typeof M204.DatasetTermCandidateSchema > >>; export type Iso_ai_datasetTools__DatasetTermMatchSchema = Assert, z.infer< typeof M204.DatasetTermMatchSchema > >>; export type Iso_ai_datasetTools__DatasetTermMatchedOn = Assert, z.infer< typeof M204.DatasetTermMatchedOn > >>; export type Iso_ai_datasetTools__DatasetToolCatalogDimensionSchema = Assert, z.infer< typeof M204.DatasetToolCatalogDimensionSchema > >>; @@ -1832,7 +1833,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 857 isomorphic pins', () => { + it('still declares all 858 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2909,7 +2910,13 @@ describe('ADR-0122 type-alias convention', () => { // (`data/hook.zod.ts`), closed at `message` / `params` with no default or // transform, pinned here (Iso_data_hook__HookTextSchema) beside its // refusal sibling rather than given a `…Parsed` synonym. +1 added. - expect(pins).toHaveLength(857); + // 857 -> 858 is the ADR-0149 D3 amendment note's candidate entry + // (`ai/dataset-tools.zod.ts` `DatasetTermCandidateSchema`): a plain object + // of two strings and one regex string, no default and no transform + // (Iso_ai_datasetTools__DatasetTermCandidateSchema). +1 added. The + // `candidates` list it fills on `ListDatasetsOutputSchema` is an optional + // array of that object, so that schema's own pin still holds. + expect(pins).toHaveLength(858); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either