From fe96c22d8439dd6da22f856272cc1ce548b1faf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:23:29 +0000 Subject: [PATCH 01/11] feat(spec): the dataset tools' output declares nextStep on list_datasets and sourceLine on query_dataset (ADR-0149 M1) ListDatasetsOutputSchema gains optional nextStep: a closed decision enum (one_measure, several_measures, candidates_only, no_measure), the caller's terms it is about, and a note string slot. It holds no member list: the members are read under its terms from the answer's own matches and candidates, so an answer keeps one list of candidates. QueryDatasetOutputSchema gains optional sourceLine, a non-empty string, declared in the tool's own extend so the shared analytics response is not widened. ADR-0149 M1 gains an add-only amendment note: M1 is unchanged, the spec declares two string slots and one closed enum, and the two sentences are written by the executor. Generated artefacts follow in the next commit. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34918-dataset-next-step-source-line.md | 23 +++ ...ions-through-the-dataset-semantic-layer.md | 11 ++ packages/spec/src/ai/dataset-tools.test.ts | 157 ++++++++++++++++++ packages/spec/src/ai/dataset-tools.zod.ts | 101 ++++++++++- .../src/type-alias-convention.pin.test.ts | 16 +- 5 files changed, 303 insertions(+), 5 deletions(-) create mode 100644 .changeset/34918-dataset-next-step-source-line.md diff --git a/.changeset/34918-dataset-next-step-source-line.md b/.changeset/34918-dataset-next-step-source-line.md new file mode 100644 index 00000000000..bc3abdd1179 --- /dev/null +++ b/.changeset/34918-dataset-next-step-source-line.md @@ -0,0 +1,23 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): the dataset tools' output declares `nextStep` on `list_datasets` and `sourceLine` on `query_dataset` (ADR-0149 M1) + +Clause-②: yes (widening: two optional output members on published schemas) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-ask/SKILL.md (follows `nextStep` and cites `sourceLine` once the executor fills them) + +`ListDatasetsOutputSchema` (`@objectstack/spec/ai`) gains one optional member, `nextStep`, with its schema `DatasetNextStepSchema` (type `DatasetNextStep`) and the closed enum `DatasetNextStepDecision`. `QueryDatasetOutputSchema` gains one optional member, `sourceLine`. Nothing is removed or renamed, and an answer without either member parses as it did. + +- **`nextStep`: what it is.** The platform's reading of the caller's `terms` under the ADR-0149 D3 selection rule, as three members: `decision`, `terms` and `note`. +- **`decision` is a closed enum of four cases.** `one_measure` (the term equals exactly one measure), `several_measures` (it equals more than one, in one dataset or in several), `candidates_only` (it matched no member and has entries in `candidates`), `no_measure` (it equals no measure and has no candidate). A dimension the term equals is not counted: the rule selects a measure. Any other value does not parse. The values name what the platform found, not what a reader then does. +- **`terms` is the reference to the members, and there is one list of candidates.** `nextStep` holds no member list. It names the caller's terms the decision is about, and the members are read under those terms from the same answer: a dataset's `matches` for `one_measure` and `several_measures`, `candidates` for `candidates_only`. No `{ dataset, member }` pointer is declared twice. +- **`note` and `sourceLine` are string slots.** `note` is the decision in words; `sourceLine` is a `query_dataset` answer's source as one finished line, the same source `provenance` carries as structure. Each is a non-empty string, and the spec declares no wording for either: the text is the executor's (ADR-0149 M1). +- **`sourceLine` is the tool's member only.** It is declared on `QueryDatasetOutputSchema`; `AnalyticsResultResponseSchema`, the REST door's answer, is not changed. +- **When they are present.** Both are optional. `nextStep` is present only when `terms` were sent. No `sourceLine` is the key's absence: an empty string does not parse. +- **Who fills them.** This change declares the shapes only, and each tool's `outputSchema` (`getDatasetToolJsonSchemas()`) lists its member from it. Filling them is the dataset tools' executor's change in `@objectstack/service-analytics`, which ships under its own entry; an answer carries `nextStep` or `sourceLine` only from a release that has both. + +ADR-0149 M1 gains an add-only amendment note recording the ruling: M1 is unchanged, the spec gains two string slots and one closed enum and no sentence, and the two sentences are written by the executor. + +Level: `minor` for `@objectstack/spec`, the level `Metadata-protocol: added` takes. The `authorable-surface/ai.json` baseline records the new keys: `ai/ListDatasetsOutput:nextStep`, the three `ai/DatasetNextStep` members and `ai/QueryDatasetOutput:sourceLine`. 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 8ebae3485f6..58206891180 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 @@ -253,6 +253,17 @@ Recommendation **A**. 长远合理性: the key the whole industry reads, already 自检行:只看①选 A;②③④ 是否翻转:否。 +> **Amendment note (2026-11-17, [#34918](https://github.com/objectstack-ai/objectstack/issues/34918) — this PR): the two dataset tools' answers may carry a finished sentence each, `nextStep.note` and `sourceLine`; the spec declares a string slot for each and the executor writes the text. M1 stands.** +> Ruled by the maintainer on [#34894](https://github.com/objectstack-ai/objectstack/issues/34894), option A, verbatim 「两件都同意:构建提交进仓库,#34894 选 A」 (ruling record [`6953671481`](https://github.com/objectstack-ai/objectstack/issues/34894#issuecomment-6953671481)). The record states what was ruled: the framework's executor returns `nextStep` (a closed decision, the candidates, a sentence) on `list_datasets` and `sourceLine` on `query_dataset`; the spec declares the shapes; the sentence's text is the executor's and does not enter the spec, so M1 stands. The contract is `packages/spec/src/ai/dataset-tools.zod.ts#ListDatasetsOutputSchema` (its `nextStep` member) with `packages/spec/src/ai/dataset-tools.zod.ts#DatasetNextStepSchema` and `packages/spec/src/ai/dataset-tools.zod.ts#DatasetNextStepDecision`, and `packages/spec/src/ai/dataset-tools.zod.ts#QueryDatasetOutputSchema` (its `sourceLine` member); this note points at them without restating every case. +> +> - **M1 is unchanged.** This note changes no word of M1, of its option table or of its **Ruled A** line. A member `description` is still a plain-language business definition and not a prompt, and AI guidance text still does not enter the spec. +> - **The spec gains two string slots and one closed enum, and no sentence.** `nextStep.note` and `sourceLine` are each a string whose description says what the member is. The spec holds no wording for either, in any language, and no template. The enum is `nextStep.decision`: which case of [D3](#d3--the-selection-rule-and-provenance-the-model-cannot-invent)'s selection rule the caller's terms are in. Its four values name what the platform found (one measure, several measures, candidates only, no measure), not what a reader then does: what follows from each case stays D3's to say, in the three places D3 names. +> - **The sentences are the executor's**, as the tool descriptions are. `@objectstack/service-analytics` composes both, in the caller's locale, from the answer it built: `nextStep.note` from that answer's `matches` and `candidates`, `sourceLine` from its `provenance`. The model types neither. The executor lands with [#34919](https://github.com/objectstack-ai/objectstack/issues/34919). +> - **One list of candidates.** The ruling record's "the candidates" is carried by reference. `nextStep` holds no member list: it names the caller's terms it is about, and the members are read under those terms from the same answer's `matches` and `candidates` (the amendment note under D3). No pointer is declared a second time. +> - **Why a sentence in the result, and not only in a description.** It is the ground given under D3 for `matches` and for `candidates`: a tool result is read by every client that made the call, so the product's agent and an MCP client are handed the same next step and the same source line (#34894, option A). +> - **[D2](#d2--two-tools-one-definition-one-executor-two-transports) and D3 stand as written.** Each tool's output gains one optional member beside the ones D2 lists, and an answer without it parses as before. `provenance` is still the structured source a `query_dataset` answer is rendered from (D3 rule 2); `sourceLine` is that source in words. What counts as a hit, and which rule governs each case, are untouched. +> - **State on `main`.** This PR declares the shapes and changes no executor. Until #34919 lands no answer carries either member. 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. + ### M2 — What the AI does when no dataset covers the question 维护者速读:用户问「营收」,但没有任何数据集定义过它。是退回按对象查(今天的做法,答案标明「非指标口径」),还是不答、请管理员先定义? diff --git a/packages/spec/src/ai/dataset-tools.test.ts b/packages/spec/src/ai/dataset-tools.test.ts index 41a8a38e13c..b9dcb07121c 100644 --- a/packages/spec/src/ai/dataset-tools.test.ts +++ b/packages/spec/src/ai/dataset-tools.test.ts @@ -14,12 +14,21 @@ * [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. + * + * [ADR-0149 M1, amendment note] `list_datasets` may state `nextStep`: a closed + * `decision`, the caller's `terms` it is about and a `note`, with no member + * list of its own, so an answer keeps one list of candidates. `query_dataset` + * may state `sourceLine`, on the tool's answer only. Each is optional, and an + * answer without it parses as before. The two texts are string slots: no + * wording is pinned here, because none is declared. */ import { describe, expect, it } from 'vitest'; import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/analytics.zod'; import { DatasetToolCatalogEntrySchema, + DatasetNextStepDecision, + DatasetNextStepSchema, DatasetProvenanceSchema, DatasetTermCandidateSchema, DatasetTermMatchSchema, @@ -217,6 +226,96 @@ describe('list_datasets candidates', () => { }); }); +describe('list_datasets nextStep', () => { + 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 }, + { name: 'invoice_amount', label: '开票金额', aggregate: 'sum' as const, synonyms: ['金额'] }, + ], + matches: [{ term: '金额', member: 'measures.invoice_amount', matchedOn: 'synonym' as const }], + }; + const candidates = [{ term: 'invoice', dataset: 'billing', member: 'measures.invoice_count' }]; + const nextStep = { decision: 'candidates_only' as const, terms: ['invoice'], note: 'a sentence the executor wrote' }; + + it('the decision is one of four cases, and no other value parses', () => { + expect(DatasetNextStepDecision.options).toEqual(['one_measure', 'several_measures', 'candidates_only', 'no_measure']); + for (const decision of DatasetNextStepDecision.options) { + expect(DatasetNextStepSchema.safeParse({ ...nextStep, decision }).success, decision).toBe(true); + } + for (const decision of ['ask', 'one_match', 'ONE_MEASURE', '', 1, null]) { + const parsed = ListDatasetsOutputSchema.safeParse({ datasets: [entry], nextStep: { ...nextStep, decision } }); + expect(parsed.success, String(decision)).toBe(false); + expect(parsed.error?.issues[0]?.path, String(decision)).toEqual(['nextStep', 'decision']); + } + }); + + it('an answer carries it beside the catalogue and the candidates, and the parse keeps it', () => { + const parsed = ListDatasetsOutputSchema.parse({ datasets: [entry], candidates, nextStep }); + expect(parsed.nextStep).toEqual(nextStep); + expect(parsed.candidates).toEqual(candidates); + }); + + it('an answer without the key parses to the same value as before', () => { + const answer = { datasets: [entry], candidates }; + const parsed = ListDatasetsOutputSchema.parse(answer); + expect(parsed).toEqual(answer); + expect(Object.keys(parsed)).not.toContain('nextStep'); + }); + + it('decision, terms and note are each required, and terms and note are never empty', () => { + for (const key of ['decision', 'terms', 'note'] as const) { + const { [key]: _omitted, ...rest } = nextStep; + const parsed = DatasetNextStepSchema.safeParse(rest); + expect(parsed.success, key).toBe(false); + expect(parsed.error?.issues[0]?.path, key).toEqual([key]); + } + const noTerms = DatasetNextStepSchema.safeParse({ ...nextStep, terms: [] }); + expect(noTerms.success).toBe(false); + expect(noTerms.error?.issues[0]?.path).toEqual(['terms']); + const noNote = DatasetNextStepSchema.safeParse({ ...nextStep, note: '' }); + expect(noNote.success).toBe(false); + expect(noNote.error?.issues[0]?.path).toEqual(['note']); + }); + + it('holds no member list: three keys, and a term is a string, never a pointer', () => { + expect(Object.keys(DatasetNextStepSchema.shape).sort()).toEqual(['decision', 'note', 'terms']); + const pointer = DatasetNextStepSchema.safeParse({ ...nextStep, terms: candidates }); + expect(pointer.success).toBe(false); + expect(pointer.error?.issues[0]?.path).toEqual(['terms', 0]); + }); + + it('an answer has one list of candidates: a list written inside nextStep is not part of the answer', () => { + // The one place a candidate pointer is declared is the answer's `candidates`. + expect(ListDatasetsOutputSchema.shape.candidates.unwrap().element).toBe(DatasetTermCandidateSchema); + const other = [{ term: 'invoice', dataset: 'billing', member: 'dimensions.invoice_status' }]; + const parsed = ListDatasetsOutputSchema.parse({ + datasets: [entry], + candidates, + nextStep: { ...nextStep, candidates: other, matches: entry.matches }, + }); + expect(Object.keys(parsed.nextStep ?? {}).sort()).toEqual(['decision', 'note', 'terms']); + expect(parsed.candidates).toEqual(candidates); + }); + + it('refers to the members by term: they are read from the same answer under `terms`', () => { + const offered = ListDatasetsOutputSchema.parse({ datasets: [entry], candidates, nextStep }); + expect((offered.candidates ?? []).filter((c) => offered.nextStep?.terms.includes(c.term))).toEqual(candidates); + + const matched = ListDatasetsOutputSchema.parse({ + datasets: [entry], + nextStep: { decision: 'one_measure', terms: ['金额'], note: 'a sentence the executor wrote' }, + }); + const measures = matched.datasets.flatMap((d) => (d.matches ?? []) + .filter((m) => matched.nextStep?.terms.includes(m.term) && m.member.startsWith('measures.')) + .map((m) => `${d.name}.${m.member}`)); + expect(measures).toEqual(['billing.measures.invoice_amount']); + }); +}); + describe('query_dataset output', () => { const answer = { rows: [{ stage: 'Won', total_amount: 1200 }], @@ -247,6 +346,31 @@ describe('query_dataset output', () => { expect(QueryDatasetOutputSchema.safeParse(narrowed).success).toBe(true); }); + it('carries `sourceLine`, the source as one line: optional, a string, never empty', () => { + const cited = { ...answer, sourceLine: 'a line the executor wrote' }; + expect(QueryDatasetOutputSchema.parse(cited).sourceLine).toBe('a line the executor wrote'); + + const parsed = QueryDatasetOutputSchema.parse(answer); + expect(parsed).toEqual(answer); + expect(Object.keys(parsed)).not.toContain('sourceLine'); + + for (const sourceLine of ['', 1, null, ['a line']]) { + const refused = QueryDatasetOutputSchema.safeParse({ ...answer, sourceLine }); + expect(refused.success, JSON.stringify(sourceLine)).toBe(false); + expect(refused.error?.issues[0]?.path, JSON.stringify(sourceLine)).toEqual(['sourceLine']); + } + }); + + it('`sourceLine` is the tool\'s member: the REST door\'s answer does not gain it', () => { + expect(Object.keys(QueryDatasetOutputSchema.shape)).toContain('sourceLine'); + expect(Object.keys(AnalyticsResultResponseSchema.shape.data.shape)).not.toContain('sourceLine'); + // The door's `data` is a plain object: a `sourceLine` sent there is not kept. + const door = AnalyticsResultResponseSchema.shape.data.parse({ + rows: answer.rows, fields: answer.fields, sourceLine: 'a line the executor wrote', + }); + expect(Object.keys(door)).not.toContain('sourceLine'); + }); + it('provenance is a dataset source, echoing the caller\'s runtime filter only', () => { expect(DatasetProvenanceSchema.safeParse({ ...provenance, runtimeFilter: { stage: 'won' } }).success).toBe(true); expect(DatasetProvenanceSchema.safeParse({ ...provenance, kind: 'object' }).success).toBe(false); @@ -296,4 +420,37 @@ describe('JSON Schema projection', () => { expect(candidates?.minItems).toBe(1); expect([...(candidates?.items?.required ?? [])].sort()).toEqual(['dataset', 'member', 'term']); }); + + it('the `list_datasets` outputSchema carries `nextStep`: optional, a closed decision, terms by name, a note', () => { + const outputSchema = getDatasetToolJsonSchemas().list_datasets.outputSchema as unknown as { + required: string[]; + properties: Record; + }>; + }; + expect(outputSchema.required).not.toContain('nextStep'); + const nextStep = outputSchema.properties.nextStep; + expect(nextStep?.type).toBe('object'); + expect([...(nextStep?.required ?? [])].sort()).toEqual(['decision', 'note', 'terms']); + expect(nextStep?.additionalProperties).toBe(false); + expect(Object.keys(nextStep?.properties ?? {}).sort()).toEqual(['decision', 'note', 'terms']); + expect(nextStep?.properties?.decision?.enum).toEqual(['one_measure', 'several_measures', 'candidates_only', 'no_measure']); + expect(nextStep?.properties?.terms?.type).toBe('array'); + expect(nextStep?.properties?.terms?.minItems).toBe(1); + expect(nextStep?.properties?.terms?.items?.type).toBe('string'); + expect(nextStep?.properties?.note?.type).toBe('string'); + expect(nextStep?.properties?.note?.minLength).toBe(1); + }); + + it('the `query_dataset` outputSchema carries `sourceLine`: optional, a non-empty string', () => { + const outputSchema = getDatasetToolJsonSchemas().query_dataset.outputSchema as unknown as { + required: string[]; properties: Record; + }; + expect(outputSchema.required).not.toContain('sourceLine'); + expect(outputSchema.properties.sourceLine?.type).toBe('string'); + expect(outputSchema.properties.sourceLine?.minLength).toBe(1); + }); }); diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index bbb4dce7b5b..653aa4288ae 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -17,10 +17,12 @@ import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/an * through dashboards and reports: `list_datasets` returns the catalogue (the * datasets the caller may query, their dimensions and measures, each member's * business vocabulary, which of the caller's words matched which member, and, - * for a word that matched nothing, the members offered as `candidates`), + * for a word that matched nothing, the members offered as `candidates`; with + * them `nextStep`, which case of the selection rule those words are in), * 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 + * used, with `sourceLine`, that source as one finished line. The shapes are + * declared here once and projected to the JSON Schema an * `AIToolDefinition` carries ({@link getDatasetToolJsonSchemas}), so the MCP * registration and the product AI's registration read one definition. * @@ -39,6 +41,9 @@ import { AnalyticsResultResponseSchema, DatasetSelectionSchema } from '../api/an * `data:read` to `@objectstack/mcp` (card #31590). The tool descriptions, which * carry the ADR-0149 D3 selection rule to the model, are written by the * executor: AI guidance text does not enter the spec (ADR-0149 M1, ruled A). + * The two sentences an answer carries, `nextStep.note` and `sourceLine`, are + * the executor's in the same way (card #34919): the spec declares a string + * slot for each and fixes no wording (the amendment note under M1). */ /** The `list_datasets` tool name, in the `list_objects` family's spelling. */ @@ -141,6 +146,79 @@ export const DatasetTermCandidateSchema = lazySchema(() => z.object({ ), })); +/** + * Which case of the ADR-0149 D3 selection rule a term is in: the `decision` + * of {@link DatasetNextStepSchema}. + * + * D3 selects a MEASURE, so the values count measures. A term that equals a + * dimension and no measure is in `no_measure`: a grouping is not a number + * (rule 5). + * + * - `one_measure`: the term equals exactly one measure (rule 2). + * - `several_measures`: it equals more than one measure, in one dataset or in + * several (rule 3). + * - `candidates_only`: it matched no member and has entries in `candidates` + * (the amendment note under the rules). + * - `no_measure`: it equals no measure and has no entry in `candidates` + * (rule 4). + * + * The set is closed: a value outside it does not parse, and a fifth case is a + * change to this enum, never a free string. + * + * Each value names what the platform FOUND, in the words of the members it + * found it in, and none names what a reader then does. What follows from a + * case is D3's to say, and the text that carries it to a model is the + * executor's (M1). Were the rule for a case re-ruled (M2 names its own + * revisits), the four findings would still be these four. + */ +export const DatasetNextStepDecision = z.enum(['one_measure', 'several_measures', 'candidates_only', 'no_measure']); + +/** + * `list_datasets`' reading of the caller's terms under the ADR-0149 D3 + * selection rule: {@link ListDatasetsOutputSchema}'s `nextStep` (ADR-0149 M1, + * the amendment note under it). + * + * Three members: the case (`decision`), the terms it is about (`terms`) and + * the case in words (`note`). + * + * It holds NO member list. The members a decision rests on are already in the + * answer: a match is an entry of a dataset's `matches` + * ({@link DatasetTermMatchSchema}), a candidate is an entry of `candidates` + * ({@link DatasetTermCandidateSchema}), and both carry the caller's `term`. + * `terms` is that same key, so the reference is by term and no + * `{ dataset, member }` pointer is declared a second time: an answer has one + * list of candidates, and `nextStep` holds no second one that could disagree + * with it. + * + * The caller's terms can be in different cases (one equals a measure, another + * has only candidates). Which case one answer reports is the executor's rule; + * the shape says which terms the reported case is about. + * + * What a schema cannot refuse is the executor's to hold, as it is for + * `candidates`: that `decision` is the case the named terms are in, and that + * every term named was sent. + */ +export const DatasetNextStepSchema = lazySchema(() => z.object({ + decision: DatasetNextStepDecision.describe( + 'Which case of the ADR-0149 D3 selection rule each term in `terms` is in, computed by the platform from this ' + + 'answer\'s `matches` and `candidates`. `one_measure`: the term equals exactly one measure. ' + + '`several_measures`: it equals more than one measure, in one dataset or in several. `candidates_only`: it ' + + 'matched no member and has entries in `candidates`. `no_measure`: it equals no measure and has no entry in ' + + '`candidates`. A dimension the term equals is not counted', + ), + terms: z.array(z.string()).min(1).describe( + 'The caller\'s terms the decision is about, each as sent in `terms`. This is the reference to the members the ' + + 'decision rests on, which `nextStep` does not list: they are the entries carrying one of these terms in the ' + + 'same answer, in a dataset\'s `matches` (those whose `member` is a measure) for `one_measure` and ' + + '`several_measures`, and in `candidates` for `candidates_only`. `no_measure` rests on no member', + ), + note: z.string().min(1).describe( + 'The decision in words: finished text in the caller\'s locale, composed by the tool from this answer and never ' + + 'typed by the model. The wording is the executor\'s; the schema declares the slot and fixes no text ' + + '(ADR-0149 M1)', + ), +})); + /** * A dimension as the catalogue lists it. * @@ -234,6 +312,12 @@ export const ListDatasetsOutputSchema = lazySchema(() => z.object({ + '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', ), + nextStep: DatasetNextStepSchema.optional().describe( + 'Which case of the ADR-0149 D3 selection rule the caller\'s `terms` are in, as the platform computed it from ' + + 'this answer\'s own `matches` and `candidates`: the case, the terms it is about and the case in words. It adds ' + + 'no match and no candidate and lists no member: the members it rests on are read from `matches` and ' + + '`candidates` under its `terms`. Present only when `terms` were sent', + ), })); // ========================================== @@ -322,11 +406,22 @@ export const DatasetProvenanceSchema = lazySchema(() => z.object({ * `AnalyticsResultResponseSchema`'s `data`, so a column property the REST door * gains reaches the tool without a second edit. `sql` is left out: the AI is * given no raw SQL (ADR-0021). + * + * `sourceLine` is declared in the `.extend` below, beside `provenance`: a + * member of the tool's answer only. `AnalyticsResultResponseSchema` is not + * edited, so the REST door's answer and every other reader of it are what + * they were. */ export const QueryDatasetOutputSchema = lazySchema(() => AnalyticsResultResponseSchema.shape.data .omit({ sql: true }) .extend({ provenance: DatasetProvenanceSchema.describe('The dataset and members the answer was computed from'), + sourceLine: z.string().min(1).optional().describe( + 'The answer\'s source as one finished line, in the caller\'s locale: composed by the tool from `provenance` ' + + 'after the query ran, never typed by the model. `provenance` stays the structured source and this is the ' + + 'same source in words. The wording is the executor\'s; the schema declares the slot and fixes no text ' + + '(ADR-0149 M1). Absent when the tool composed none, never an empty string', + ), rowCount: z.number().int().nonnegative().describe('How many rows `rows` holds'), truncated: z.boolean().describe( '`true` when more rows existed past the row cap the tool applied and were not returned', @@ -391,6 +486,8 @@ export type ListDatasetsInput = z.input; export type DatasetTermMatchedOn = z.input; export type DatasetTermMatch = z.input; export type DatasetTermCandidate = z.input; +export type DatasetNextStepDecision = z.input; +export type DatasetNextStep = 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 e5533095eb0..15d02f0c037 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'; // --------------------------------------------------------------------------- -// 858 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 860 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 @@ -382,6 +382,8 @@ export type Iso_ai_conversation__TextContentSchema = Assert, z.infer< typeof M1.TokenBudgetStrategySchema > >>; // ai/dataset-tools.zod.ts -- [ADR-0149 D2] plain objects, enums and literals, no default and no transform +export type Iso_ai_datasetTools__DatasetNextStepDecision = Assert, z.infer< typeof M204.DatasetNextStepDecision > >>; +export type Iso_ai_datasetTools__DatasetNextStepSchema = Assert, z.infer< typeof M204.DatasetNextStepSchema > >>; export type Iso_ai_datasetTools__DatasetProvenanceSchema = 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 > >>; @@ -1833,7 +1835,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 858 isomorphic pins', () => { + it('still declares all 860 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 @@ -2916,7 +2918,15 @@ describe('ADR-0122 type-alias convention', () => { // (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); + // 858 -> 860 is the ADR-0149 M1 amendment note's `nextStep` + // (`ai/dataset-tools.zod.ts`): `DatasetNextStepDecision`, a closed enum of + // four values, and `DatasetNextStepSchema`, a plain object of that enum, a + // non-empty array of strings and a non-empty string, no default and no + // transform in either (Iso_ai_datasetTools__DatasetNextStepDecision, + // Iso_ai_datasetTools__DatasetNextStepSchema). +2 added. `nextStep` on + // `ListDatasetsOutputSchema` and `sourceLine` on `QueryDatasetOutputSchema` + // are optional members with no default, so those two pins still hold. + expect(pins).toHaveLength(860); // 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 From d10ea09296e107c40685477e157d64ef8746e1a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:33:44 +0000 Subject: [PATCH 02/11] chore(spec): regenerate the artefacts for nextStep and sourceLine Generator output only, plus one description reworded so the nextStep terms member names the tool's terms input and not itself: api-surface, authorable-surface, declaration-map, export-origins and json-schema.manifest for ai, the dataset-tools reference page, the reference index totals (1670 to 1672, AI 82 to 84) and the strictness ledger count for ai (97 to 98). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- content/docs/references/ai/dataset-tools.mdx | 50 +++++++++++++++++-- content/docs/references/index.mdx | 10 ++-- .../ai.md | 2 +- packages/spec/api-surface/ai.json | 4 ++ packages/spec/authorable-surface/ai.json | 5 ++ packages/spec/declaration-map/ai.json | 3 ++ packages/spec/export-origins/ai.json | 3 ++ packages/spec/json-schema.manifest/ai.json | 2 + packages/spec/src/ai/dataset-tools.zod.ts | 9 ++-- 9 files changed, 73 insertions(+), 15 deletions(-) diff --git a/content/docs/references/ai/dataset-tools.mdx b/content/docs/references/ai/dataset-tools.mdx index a69e3632d2f..efefe0843ae 100644 --- a/content/docs/references/ai/dataset-tools.mdx +++ b/content/docs/references/ai/dataset-tools.mdx @@ -13,10 +13,12 @@ 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, which of the caller's words matched which member, and, -for a word that matched nothing, the members offered as `candidates`), +for a word that matched nothing, the members offered as `candidates`; with +them `nextStep`, which case of the selection rule those words are in), 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 +used, with `sourceLine`, that source as one finished line. The shapes are +declared here once and projected to the JSON Schema an `AIToolDefinition` carries (`getDatasetToolJsonSchemas`), so the MCP registration and the product AI's registration read one definition. @@ -35,6 +37,9 @@ zero-match term's candidates and the row cap `data:read` to `@objectstack/mcp` (card #31590). The tool descriptions, which carry the ADR-0149 D3 selection rule to the model, are written by the executor: AI guidance text does not enter the spec (ADR-0149 M1, ruled A). +The two sentences an answer carries, `nextStep.note` and `sourceLine`, are +the executor's in the same way (card #34919): the spec declares a string +slot for each and fixes no wording (the amendment note under M1). **Source:** `packages/spec/src/ai/dataset-tools.zod.ts` @@ -43,13 +48,38 @@ executor: AI guidance text does not enter the spec (ADR-0149 M1, ruled A). ## TypeScript Usage ```typescript -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'; +import { DatasetNextStepSchema, DatasetNextStepDecision, DatasetProvenanceSchema, DatasetTermCandidateSchema, DatasetTermMatchSchema, DatasetTermMatchedOn, DatasetToolCatalogDimensionSchema, DatasetToolCatalogEntrySchema, DatasetToolCatalogMeasureSchema, ListDatasetsInputSchema, ListDatasetsOutputSchema, QueryDatasetInputSchema, QueryDatasetOutputSchema } from '@objectstack/spec/ai'; +import type { DatasetNextStep, DatasetNextStepDecision, DatasetProvenance, DatasetTermCandidate, DatasetTermMatch, DatasetTermMatchedOn, DatasetToolCatalogDimension, DatasetToolCatalogEntry, DatasetToolCatalogMeasure, ListDatasetsInput, ListDatasetsOutput, QueryDatasetInput, QueryDatasetOutput } from '@objectstack/spec/ai'; // Validate data -const result = DatasetProvenanceSchema.parse(data); +const result = DatasetNextStepSchema.parse(data); ``` +--- + +## DatasetNextStep + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **decision** | `Enum<'one_measure' \| 'several_measures' \| 'candidates_only' \| 'no_measure'>` | ✅ | Which case of the ADR-0149 D3 selection rule each term in `terms` is in, computed by the platform from this answer's `matches` and `candidates`. `one_measure`: the term equals exactly one measure. `several_measures`: it equals more than one measure, in one dataset or in several. `candidates_only`: it matched no member and has entries in `candidates`. `no_measure`: it equals no measure and has no entry in `candidates`. A dimension the term equals is not counted | +| **terms** | `string[]` | ✅ | The caller's terms the decision is about, each as sent in the tool's `terms` input. This is the reference to the members the decision rests on, which `nextStep` does not list: they are the entries carrying one of these terms in the same answer, in a dataset's `matches` (those whose `member` is a measure) for `one_measure` and `several_measures`, and in `candidates` for `candidates_only`. `no_measure` rests on no member | +| **note** | `string` | ✅ | The decision in words: finished text in the caller's locale, composed by the tool from this answer and never typed by the model. The wording is the executor's; the schema declares the slot and fixes no text (ADR-0149 M1) | + + +--- + +## DatasetNextStepDecision + +### Allowed Values + +* `one_measure` +* `several_measures` +* `candidates_only` +* `no_measure` + + --- ## DatasetProvenance @@ -227,6 +257,7 @@ const result = DatasetProvenanceSchema.parse(data); | **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 | +| **nextStep** | `{ decision: Enum<'one_measure' \| 'several_measures' \| 'candidates_only' \| 'no_measure'>; terms: string[]; note: string }` | optional | Which case of the ADR-0149 D3 selection rule the caller's `terms` are in, as the platform computed it from this answer's own `matches` and `candidates`: the case, the terms it is about and the case in words. It adds no match and no candidate and lists no member: the members it rests on are read from `matches` and `candidates` under its `terms`. Present only when `terms` were sent | ### Nested Shape: `ListDatasetsOutput.datasets[number]` @@ -249,6 +280,14 @@ const result = DatasetProvenanceSchema.parse(data); | **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 | +### Nested Shape: `ListDatasetsOutput.nextStep` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **decision** | `Enum<'one_measure' \| 'several_measures' \| 'candidates_only' \| 'no_measure'>` | ✅ | Which case of the ADR-0149 D3 selection rule each term in `terms` is in, computed by the platform from this answer's `matches` and `candidates`. `one_measure`: the term equals exactly one measure. `several_measures`: it equals more than one measure, in one dataset or in several. `candidates_only`: it matched no member and has entries in `candidates`. `no_measure`: it equals no measure and has no entry in `candidates`. A dimension the term equals is not counted | +| **terms** | `string[]` | ✅ | The caller's terms the decision is about, each as sent in the tool's `terms` input. This is the reference to the members the decision rests on, which `nextStep` does not list: they are the entries carrying one of these terms in the same answer, in a dataset's `matches` (those whose `member` is a measure) for `one_measure` and `several_measures`, and in `candidates` for `candidates_only`. `no_measure` rests on no member | +| **note** | `string` | ✅ | The decision in words: finished text in the caller's locale, composed by the tool from this answer and never typed by the model. The wording is the executor's; the schema declares the slot and fixes no text (ADR-0149 M1) | + --- @@ -296,6 +335,7 @@ const result = DatasetProvenanceSchema.parse(data); | **drillRanges** | `Record[]` | optional | Drill-through sidecar for date ranges, aligned to `rows` by index: date dimension name to the half-open range `[gte, lt)` that row's records fall in on that dimension's field. A time bucket gets the span it covers; a `timeDimensions[].dateRange` window gets the window the query filtered by on every row, or narrows the bucket entry on the same field to the part inside the window. Bounds are `YYYY-MM-DD` calendar days, or ISO-8601 instants when the source field is `datetime` (a bucket's at midnight in the reference timezone); a row whose bucket value is null gets no bucket entry, and a window whose end is an instant or the last supported day gets none. Set only on a dataset answer that has rows and groups by at least one `type: 'date'` dimension with a `field` and a granularity, or carries a `dateRange` on a dimension with a `field`; independent of `dimensionFields`. Absent on a cube query answer. | | **drillScopes** | `Record` | optional | Drill-through sidecar per measure: each selected measure name to the list filter, on the answer's `object`, that selects the records that measure aggregates: the dataset's own `filter`, AND the measure's own `filter`, AND, for a measure over a `field`, that field holding a value (`{ "$null": false }`; both instants for a duration measure), with each `{token}` resolved as the query resolved it; `{}` when none of these applies. A drill lists the clicked bucket (`dimensionFields` / `drillRawRows` / `drillRawTotals`, `drillRanges`) AND the widget's own filter AND this scope. A measure is left out when no list filter on `object` selects its records (a derived measure; a scope that names a relationship path such as `account.region`, as a key or as a `$field` reference), and a measure left out offers no drill. Keyed by measure name: a `__compare` column has no entry. Set on every dataset answer (`POST /analytics/dataset/query`) that has rows; absent on a cube query answer and on a draft-preview answer. | | **provenance** | `{ kind: 'dataset'; dataset: object; measures: object[]; dimensions: object[]; … }` | ✅ | The dataset and members the answer was computed from | +| **sourceLine** | `string` | optional | The answer's source as one finished line, in the caller's locale: composed by the tool from `provenance` after the query ran, never typed by the model. `provenance` stays the structured source and this is the same source in words. The wording is the executor's; the schema declares the slot and fixes no text (ADR-0149 M1). Absent when the tool composed none, never an empty string | | **rowCount** | `integer` | ✅ | How many rows `rows` holds | | **truncated** | `boolean` | ✅ | `true` when more rows existed past the row cap the tool applied and were not returned | | **delegationNarrowed** | `true` | optional | Present, and `true`, when the caller acts as an agent whose authority narrows what it may read on the dataset's object; `warning` states the narrowing (ADR-0090 D10) | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 041ab33b738..d84f1198561 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 — 1670 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1672 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 | 82 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 14 | 84 | 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** | **1670** | 14 protocol modules | +| **Total** | **218** | **1672** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 82 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **14 pages, 84 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`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | +| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `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/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 8e5ab008a41..f3c5b4c26d1 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/` | 97 | +| `ai/` | 98 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index ccd723b8d1a..1210460d916 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -56,6 +56,10 @@ "ConversationSessionSchema (const)", "ConversationSummary (type)", "ConversationSummarySchema (const)", + "DatasetNextStep (type)", + "DatasetNextStepDecision (const)", + "DatasetNextStepDecision (type)", + "DatasetNextStepSchema (const)", "DatasetProvenance (type)", "DatasetProvenanceSchema (const)", "DatasetTermCandidate (type)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index f9c51d0e5ec..95b2a780c22 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -158,6 +158,9 @@ "ai/ConversationSummary:summary", "ai/ConversationSummary:summaryTokens", "ai/ConversationSummary:tokensSaved", + "ai/DatasetNextStep:decision", + "ai/DatasetNextStep:note", + "ai/DatasetNextStep:terms", "ai/DatasetProvenance:dataset", "ai/DatasetProvenance:dimensions", "ai/DatasetProvenance:kind", @@ -247,6 +250,7 @@ "ai/ListDatasetsInput:terms", "ai/ListDatasetsOutput:candidates", "ai/ListDatasetsOutput:datasets", + "ai/ListDatasetsOutput:nextStep", "ai/ListDatasetsOutput:partial", "ai/ListDatasetsOutput:warning", "ai/MCPServerRef:active", @@ -369,6 +373,7 @@ "ai/QueryDatasetOutput:provenance", "ai/QueryDatasetOutput:rowCount", "ai/QueryDatasetOutput:rows", + "ai/QueryDatasetOutput:sourceLine", "ai/QueryDatasetOutput:totals", "ai/QueryDatasetOutput:truncated", "ai/QueryDatasetOutput:warning", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 7bd7960b23f..409e0d78f00 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -42,6 +42,9 @@ "ConversationSessionSchema": "ai/ConversationSession", "ConversationSummary": "ai/ConversationSummary", "ConversationSummarySchema": "ai/ConversationSummary", + "DatasetNextStep": "ai/DatasetNextStep", + "DatasetNextStepDecision": "ai/DatasetNextStepDecision", + "DatasetNextStepSchema": "ai/DatasetNextStep", "DatasetProvenance": "ai/DatasetProvenance", "DatasetProvenanceSchema": "ai/DatasetProvenance", "DatasetTermCandidate": "ai/DatasetTermCandidate", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index ec7a0b34718..5aff96e497c 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -56,6 +56,9 @@ "ConversationSessionSchema": "src/ai/conversation.zod.ts#ConversationSessionSchema (const)", "ConversationSummary": "src/ai/conversation.zod.ts#ConversationSummary (type)", "ConversationSummarySchema": "src/ai/conversation.zod.ts#ConversationSummarySchema (const)", + "DatasetNextStep": "src/ai/dataset-tools.zod.ts#DatasetNextStep (type)", + "DatasetNextStepDecision": "src/ai/dataset-tools.zod.ts#DatasetNextStepDecision (type)", + "DatasetNextStepSchema": "src/ai/dataset-tools.zod.ts#DatasetNextStepSchema (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)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 0bc9bd67872..d719571cf46 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -23,6 +23,8 @@ "ai/ConversationMessage", "ai/ConversationSession", "ai/ConversationSummary", + "ai/DatasetNextStep", + "ai/DatasetNextStepDecision", "ai/DatasetProvenance", "ai/DatasetTermCandidate", "ai/DatasetTermMatch", diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index 653aa4288ae..332deaf8eec 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -207,10 +207,11 @@ export const DatasetNextStepSchema = lazySchema(() => z.object({ + '`candidates`. A dimension the term equals is not counted', ), terms: z.array(z.string()).min(1).describe( - 'The caller\'s terms the decision is about, each as sent in `terms`. This is the reference to the members the ' - + 'decision rests on, which `nextStep` does not list: they are the entries carrying one of these terms in the ' - + 'same answer, in a dataset\'s `matches` (those whose `member` is a measure) for `one_measure` and ' - + '`several_measures`, and in `candidates` for `candidates_only`. `no_measure` rests on no member', + 'The caller\'s terms the decision is about, each as sent in the tool\'s `terms` input. This is the reference to ' + + 'the members the decision rests on, which `nextStep` does not list: they are the entries carrying one of ' + + 'these terms in the same answer, in a dataset\'s `matches` (those whose `member` is a measure) for ' + + '`one_measure` and `several_measures`, and in `candidates` for `candidates_only`. `no_measure` rests on no ' + + 'member', ), note: z.string().min(1).describe( 'The decision in words: finished text in the caller\'s locale, composed by the tool from this answer and never ' From d304f1b86183c1a484c72b09b62606e0752da39b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:55:27 +0000 Subject: [PATCH 03/11] docs(spec): one nextStep reports one case, and the ADR-0149 M1 note names its PR DatasetNextStepSchema's doc comment now says it outright: an answer carries one nextStep and it reports one case, also when the terms sent are in several. The precedence among the cases is the executor's, fixed and documented by card #34919; the spec declares no order, and `terms` says which of the terms sent the reported case covers. No describe text changes, so each tool's outputSchema is what it was and no generated artefact moves. The header of the amendment note under ADR-0149 M1 names PR #34982 in place of "this PR". Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- ...usiness-questions-through-the-dataset-semantic-layer.md | 2 +- packages/spec/src/ai/dataset-tools.zod.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) 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 58206891180..0cceca9cf9f 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 @@ -253,7 +253,7 @@ Recommendation **A**. 长远合理性: the key the whole industry reads, already 自检行:只看①选 A;②③④ 是否翻转:否。 -> **Amendment note (2026-11-17, [#34918](https://github.com/objectstack-ai/objectstack/issues/34918) — this PR): the two dataset tools' answers may carry a finished sentence each, `nextStep.note` and `sourceLine`; the spec declares a string slot for each and the executor writes the text. M1 stands.** +> **Amendment note (2026-11-17, [#34918](https://github.com/objectstack-ai/objectstack/issues/34918) — PR #34982): the two dataset tools' answers may carry a finished sentence each, `nextStep.note` and `sourceLine`; the spec declares a string slot for each and the executor writes the text. M1 stands.** > Ruled by the maintainer on [#34894](https://github.com/objectstack-ai/objectstack/issues/34894), option A, verbatim 「两件都同意:构建提交进仓库,#34894 选 A」 (ruling record [`6953671481`](https://github.com/objectstack-ai/objectstack/issues/34894#issuecomment-6953671481)). The record states what was ruled: the framework's executor returns `nextStep` (a closed decision, the candidates, a sentence) on `list_datasets` and `sourceLine` on `query_dataset`; the spec declares the shapes; the sentence's text is the executor's and does not enter the spec, so M1 stands. The contract is `packages/spec/src/ai/dataset-tools.zod.ts#ListDatasetsOutputSchema` (its `nextStep` member) with `packages/spec/src/ai/dataset-tools.zod.ts#DatasetNextStepSchema` and `packages/spec/src/ai/dataset-tools.zod.ts#DatasetNextStepDecision`, and `packages/spec/src/ai/dataset-tools.zod.ts#QueryDatasetOutputSchema` (its `sourceLine` member); this note points at them without restating every case. > > - **M1 is unchanged.** This note changes no word of M1, of its option table or of its **Ruled A** line. A member `description` is still a plain-language business definition and not a prompt, and AI guidance text still does not enter the spec. diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index 332deaf8eec..e9729c3c938 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -191,8 +191,11 @@ export const DatasetNextStepDecision = z.enum(['one_measure', 'several_measures' * with it. * * The caller's terms can be in different cases (one equals a measure, another - * has only candidates). Which case one answer reports is the executor's rule; - * the shape says which terms the reported case is about. + * has only candidates). An answer still carries one `nextStep`, and it reports + * one case. Which case is reported when the terms are in several, the + * precedence among the cases, is the executor's: card #34919 fixes and + * documents it, and the spec declares no order. `terms` says which of the + * terms sent the reported case covers. * * What a schema cannot refuse is the executor's to hold, as it is for * `candidates`: that `decision` is the case the named terms are in, and that From dd86154f7097558fbdedd18fc4c11763e13fa693 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:35:47 +0000 Subject: [PATCH 04/11] feat(analytics): list_datasets answers nextStep and query_dataset answers sourceLine The executor composes both finished sentences from the answer it serves: the per-term decision under the ADR-0149 D3 rule, the precedence among mixed cases (several_measures, one_measure, candidates_only, no_measure), the partial-answer closing sentence, and the source line from provenance, in the caller's language by the user-text ladder. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../src/__tests__/dataset-tools.test.ts | 301 +++++++++++++- .../src/dataset-next-step.ts | 369 ++++++++++++++++++ .../service-analytics/src/dataset-tools.ts | 51 ++- 3 files changed, 706 insertions(+), 15 deletions(-) create mode 100644 packages/services/service-analytics/src/dataset-next-step.ts diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index f0d76468397..f2a6b3f1946 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -18,14 +18,19 @@ * - `query_dataset`: one NOT_FOUND for missing and hidden; `provenance` * composed from what ran, which the model's input cannot set; the row cap * and `truncated`; the delegation statement; no `sql`. + * - [#34919] `nextStep` and `sourceLine` (ADR-0149 M1 note): the decision for + * each term, the precedence among mixed cases, the partial-answer rule, the + * sentence's language, and that neither sentence names a member the caller + * was not admitted to — on a mirror of `examples/app-crm`'s dataset. */ import { describe, it, expect, vi } from 'vitest'; -import { ListDatasetsOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai'; +import { ListDatasetsOutputSchema, QueryDatasetOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { AnalyticsServicePlugin } from '../plugin.js'; import { AnalyticsService } from '../analytics-service.js'; import { createDatasetTools, getDatasetToolDefinitions } from '../dataset-tools.js'; +import { composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js'; const ME = { userId: 'u_me', tenantId: 'org_a', locale: 'zh-CN' } as ExecutionContext; const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; @@ -43,6 +48,19 @@ const OBJECTS: Record[]) { }; } -/** The security double: u_me may not read `crm_locked` nor the `margin` field; u_admin reads everything. */ +/** + * The security double: u_me may not read `crm_locked` nor the `margin` field; + * [#34919] u_rep may not read the `amount` field of app-crm's two objects; + * u_admin reads everything. + */ +function fieldsFor(object: string, ctx?: ExecutionContext): string[] { + const all = Object.keys(OBJECTS[object]?.fields ?? {}); + if (ctx?.userId === 'u_me') return all.filter((f) => f !== 'margin'); + if (ctx?.userId === 'u_rep' && object.startsWith('crm_opportunity')) return all.filter((f) => f !== 'amount'); + return all; +} const security = { getReadFilter: async () => undefined, canReadObject: (object: string, ctx?: ExecutionContext) => !(ctx?.userId === 'u_me' && object === 'crm_locked'), - getReadableFields: async (object: string, ctx?: ExecutionContext) => { - const all = Object.keys(OBJECTS[object]?.fields ?? {}); - return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all; - }, - getQueryableFields: async (object: string, ctx?: ExecutionContext) => { - const all = Object.keys(OBJECTS[object]?.fields ?? {}); - return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all; - }, + getReadableFields: async (object: string, ctx?: ExecutionContext) => fieldsFor(object, ctx), + getQueryableFields: async (object: string, ctx?: ExecutionContext) => fieldsFor(object, ctx), }; async function bootWired(rows: Record[] = [{ stage: 'won', revenue: 100 }]) { @@ -827,3 +849,262 @@ describe('[#34763] list_datasets candidates — only what this caller may read, } }); }); + +/** + * [#34919] `examples/app-crm`'s `crm_opportunity_metrics` + * (`src/datasets/opportunity.dataset.ts`), member for member with its labels + * and synonyms, beside a second dataset over app-crm's line items. app-crm + * declares one dataset, and the D1 rule refuses a word that answers to two + * members of one dataset, so "a word with two matches" needs a second dataset: + * `deal value` is `total_amount`'s synonym there and `line_amount`'s here. + */ +const CRM_OPPORTUNITY_METRICS = { + name: 'crm_opportunity_metrics', + label: 'Opportunity Metrics', + description: 'Semantic layer for sales-pipeline counts and amounts', + object: 'crm_opportunity', + dimensions: [ + { name: 'stage', label: 'Stage', field: 'stage', type: 'string', synonyms: ['sales stage', 'deal stage', 'pipeline stage', '销售阶段', '商机阶段', '漏斗阶段'] }, + { name: 'account', label: 'Account', field: 'account', type: 'string', synonyms: ['customer', 'client', 'company', '客户', '公司', '客户名称'] }, + { name: 'close_date', label: 'Close Date', field: 'close_date', type: 'date', dateGranularity: 'month', synonyms: ['closing month', 'expected close date', '成交日期', '预计成交日期', '成交月份'] }, + ], + measures: [ + { name: 'opp_count', label: 'Opportunities', aggregate: 'count', synonyms: ['deal count', 'number of deals', '商机数', '商机数量', '机会数'] }, + { name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount', format: '0,0', synonyms: ['deal value', 'opportunity amount', '商机金额', '金额合计'] }, + { name: 'avg_amount', label: 'Avg Deal Size', aggregate: 'avg', field: 'amount', format: '0,0', synonyms: ['average deal value', 'average opportunity amount', '平均商机金额'] }, + ], +}; +const CRM_LINE_ITEM_METRICS = { + name: 'crm_line_item_metrics', + label: 'Line Item Metrics', + object: 'crm_opportunity_line_item', + dimensions: [{ name: 'product', label: 'Product', field: 'product', type: 'string' }], + measures: [ + { name: 'line_amount', label: 'Line Amount', aggregate: 'sum', field: 'amount', synonyms: ['deal value', '明细金额'] }, + { name: 'quantity_total', label: 'Quantity', aggregate: 'sum', field: 'quantity' }, + ], +}; +const loadCrm = async () => [CRM_OPPORTUNITY_METRICS, CRM_LINE_ITEM_METRICS]; +const REP = { userId: 'u_rep', tenantId: 'org_a' } as ExecutionContext; +/** The members u_rep may not read (each over `amount`), by every word a sentence could name them with. */ +const WITHHELD_WORDS = ['Total Amount', 'total_amount', 'Avg Deal Size', 'avg_amount', 'Line Amount', 'line_amount']; + +type ListOut = Awaited['listDatasets']>>; + +/** + * The invariants `DatasetNextStepSchema` names and cannot refuse: the answer + * parses; `nextStep` is present exactly when terms were sent; every term it + * names was sent; a `candidates_only` term has entries in `candidates`; a + * measure case's terms have measure entries in `matches`. + */ +function expectNextStepInvariants(out: ListOut, sent: readonly string[] | undefined) { + expect(ListDatasetsOutputSchema.safeParse(out).success).toBe(true); + if (sent === undefined || sent.length === 0) { + expect('nextStep' in out).toBe(false); + return; + } + const step = out.nextStep!; + expect(step).toBeDefined(); + for (const term of step.terms) { + expect(sent).toContain(term); + // Distinct members: a word sent twice repeats its entries in `matches`. + const measureHits = [...new Set(out.datasets.flatMap((d) => (d.matches ?? []) + .filter((m) => m.term === term && m.member.startsWith('measures.')) + .map((m) => `${d.name}.${m.member}`)))]; + const offered = (out.candidates ?? []).filter((c) => c.term === term); + if (step.decision === 'one_measure') expect(measureHits).toHaveLength(1); + if (step.decision === 'several_measures') expect(measureHits.length).toBeGreaterThan(1); + if (step.decision === 'candidates_only') expect([measureHits.length, offered.length > 0]).toEqual([0, true]); + if (step.decision === 'no_measure') expect([measureHits.length, offered.length]).toEqual([0, 0]); + } + expect(new Set(step.terms).size).toBe(step.terms.length); +} + +describe('[#34919] list_datasets nextStep on examples/app-crm — the decision each word gets', () => { + async function ask(terms: string[] | undefined, ctx: ExecutionContext = ADMIN) { + const { service } = await bootWired(); + const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets(terms === undefined ? {} : { terms }, ctx); + expectNextStepInvariants(out, terms); + return out; + } + + it('a word with one match ⇒ one_measure, naming the measure, its dataset and the names to query', async () => { + const out = await ask(['商机数']); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] }); + expect(out.nextStep!.note).toContain('Opportunities (dataset: Opportunity Metrics)'); + expect(out.nextStep!.note).toContain('"crm_opportunity_metrics"'); + expect(out.nextStep!.note).toContain('"opp_count"'); + }); + + it('a word with two matches ⇒ several_measures, the note naming each by its label and its dataset\'s label', async () => { + const out = await ask(['deal value']); + expect(out.nextStep).toMatchObject({ decision: 'several_measures', terms: ['deal value'] }); + expect(out.nextStep!.note).toContain('Total Amount (dataset: Opportunity Metrics)'); + expect(out.nextStep!.note).toContain('Line Amount (dataset: Line Item Metrics)'); + }); + + it('a near-miss word ⇒ candidates_only, the note naming each offered member by its label and its dataset\'s label', async () => { + const out = await ask(['金额']); + expect(out.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['金额'] }); + expect(out.candidates!.map((c) => c.member)).toEqual(['measures.total_amount', 'measures.avg_amount', 'measures.line_amount']); + for (const named of ['Total Amount (dataset: Opportunity Metrics)', 'Avg Deal Size (dataset: Opportunity Metrics)', 'Line Amount (dataset: Line Item Metrics)']) { + expect(out.nextStep!.note).toContain(named); + } + }); + + it('an unknown word ⇒ no_measure, and the note sends the reader to the object tools', async () => { + const out = await ask(['库存周转']); + expect(out.nextStep).toMatchObject({ decision: 'no_measure', terms: ['库存周转'] }); + expect(out.nextStep!.note).toContain('query_records'); + }); + + it('a word equal only to a dimension ⇒ no_measure, naming the grouping, and asks for the number instead of falling back', async () => { + const out = await ask(['销售阶段']); + expect(out.nextStep).toMatchObject({ decision: 'no_measure', terms: ['销售阶段'] }); + expect(out.nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)'); + expect(out.nextStep!.note).not.toContain('query_records'); + }); + + it('no terms, or an empty list, ⇒ no nextStep', async () => { + await ask(undefined); + await ask([]); + }); + + it('a withheld member appears in no decision and no sentence (N5)', async () => { + // u_rep reads no `amount`: total_amount, avg_amount and line_amount are withheld. + for (const terms of [['deal value'], ['金额'], ['商机金额', '销售阶段'], ['商机数', 'deal value', '金额']]) { + const out = await ask(terms, REP); + const text = JSON.stringify(out.nextStep); + for (const word of WITHHELD_WORDS) expect(text, `${terms.join('+')} ⇒ ${word}`).not.toContain(word); + } + // What the same words read as for u_rep: the withheld equalities are gone, so nothing is a measure. + expect((await ask(['deal value'], REP)).nextStep).toMatchObject({ decision: 'no_measure', terms: ['deal value'] }); + expect((await ask(['金额'], REP)).nextStep).toMatchObject({ decision: 'no_measure', terms: ['金额'] }); + // The control: the same words name those members for a caller who reads `amount`. + expect((await ask(['deal value'])).nextStep!.note).toContain('Total Amount'); + }); +}); + +describe('[#34919] list_datasets nextStep — the precedence among mixed cases', () => { + async function decide(terms: string[]) { + const { service } = await bootWired(); + const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms }, ADMIN); + expectNextStepInvariants(out, terms); + return { decision: out.nextStep!.decision, terms: out.nextStep!.terms }; + } + + it('N1: a dimension-matched word never outranks a measure-matched one', async () => { + expect(await decide(['商机金额', '销售阶段'])).toEqual({ decision: 'one_measure', terms: ['商机金额'] }); + expect(await decide(['销售阶段', '商机金额'])).toEqual({ decision: 'one_measure', terms: ['商机金额'] }); + }); + + it('several_measures > one_measure > candidates_only > no_measure, naming every word in the reported case', async () => { + expect(await decide(['商机数', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] }); + expect(await decide(['金额', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] }); + expect(await decide(['金额', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] }); + expect(await decide(['库存周转', '金额'])).toEqual({ decision: 'candidates_only', terms: ['金额'] }); + expect(await decide(['库存周转', '销售阶段'])).toEqual({ decision: 'no_measure', terms: ['库存周转', '销售阶段'] }); + // Two words with one measure each are two metrics: both named, in the order sent. + expect(await decide(['商机金额', '商机数', '销售阶段'])).toEqual({ decision: 'one_measure', terms: ['商机金额', '商机数'] }); + }); + + it('a word sent twice is one word, and the member it equals is counted once', async () => { + expect(await decide(['商机数', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] }); + }); +}); + +describe('[#34919] list_datasets nextStep — an incomplete catalogue says so (N4)', () => { + it('a degraded read keeps nextStep over what it lists and ends the note by saying the catalogue was incomplete', async () => { + const { service } = await bootWired(); + const whole = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms: ['商机数'] }, ADMIN); + const degraded = await service.datasetTools({ + loadDatasets: async () => ({ items: [CRM_OPPORTUNITY_METRICS], partial: true as const, warning: 'one source unavailable' }), + }).listDatasets({ terms: ['商机数'] }, ADMIN); + expectNextStepInvariants(degraded, ['商机数']); + expect(degraded).toMatchObject({ partial: true, nextStep: { decision: 'one_measure', terms: ['商机数'] } }); + // The whole read's sentence, plus one closing sentence naming the warning. + expect(degraded.nextStep!.note.startsWith(whole.nextStep!.note)).toBe(true); + const added = degraded.nextStep!.note.slice(whole.nextStep!.note.length); + expect(added).toContain('incomplete'); + expect(added).toContain('warning'); + expect(whole.nextStep!.note).not.toContain('incomplete'); + }); + + it('a catalogue that could not be read at all answers no_measure for every word, and says the catalogue was incomplete', async () => { + const { service } = await bootWired(); + const failed = await service.datasetTools({ loadDatasets: async () => { throw new Error('metadata loader down'); } }) + .listDatasets({ terms: ['商机数', '销售阶段'] }, ADMIN); + expectNextStepInvariants(failed, ['商机数', '销售阶段']); + expect(failed).toMatchObject({ datasets: [], partial: true, nextStep: { decision: 'no_measure', terms: ['商机数', '销售阶段'] } }); + expect(failed.nextStep!.note).toContain('incomplete'); + }); + + it('an admission that could not be judged is a partial answer too, and its note says so', async () => { + const { service } = await bootWired(); + vi.spyOn(service, 'admitDatasetCatalogEntry').mockImplementation(async () => ({ admitted: false, unresolved: true }) as never); + const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms: ['商机数'] }, ADMIN); + expect(out).toMatchObject({ partial: true, nextStep: { decision: 'no_measure' } }); + expect(out.nextStep!.note).toContain('incomplete'); + }); +}); + +describe('[#34919] the sentences are in the caller\'s language, by the user-text ladder', () => { + it('reads the request locale, then the workspace default, through the platform locale table; en below both', () => { + expect(datasetToolSentenceLocale(['zh-CN'])).toBe('zh-Hans'); + expect(datasetToolSentenceLocale(['zh-TW'])).toBe('zh-Hant'); + expect(datasetToolSentenceLocale(['zh-Hant-HK'])).toBe('zh-Hant'); + expect(datasetToolSentenceLocale(['ja-JP'])).toBe('ja'); + expect(datasetToolSentenceLocale(['en-GB'])).toBe('en'); + // A language with no sentences takes the next rung: the workspace default, then en. + expect(datasetToolSentenceLocale(['fr-FR', 'ja-JP'])).toBe('ja'); + expect(datasetToolSentenceLocale(['fr-FR'])).toBe('en'); + expect(datasetToolSentenceLocale([])).toBe('en'); + }); + + it('the executor writes the note for the context\'s locale, then its workspace default', async () => { + const { service } = await bootWired(); + const tools = service.datasetTools({ loadDatasets: loadCrm }); + const notes: Record = {}; + for (const [key, ctx] of Object.entries({ + en: ADMIN, + zh: { ...ADMIN, locale: 'zh-CN' }, + hant: { ...ADMIN, locale: 'zh-TW' }, + ja: { ...ADMIN, locale: 'ja-JP' }, + frThenJa: { ...ADMIN, locale: 'fr-FR', workspaceLocale: 'ja-JP' }, + } as Record)) { + const out = await tools.listDatasets({ terms: ['deal value'] }, ctx); + expect(out.nextStep!.decision).toBe('several_measures'); + notes[key] = out.nextStep!.note; + } + expect(new Set([notes.en, notes.zh, notes.hant, notes.ja]).size).toBe(4); + expect(notes.frThenJa).toBe(notes.ja); + // Every language still names both members by label and dataset label. + for (const note of Object.values(notes)) { + for (const label of ['Total Amount', 'Opportunity Metrics', 'Line Amount', 'Line Item Metrics']) expect(note).toContain(label); + } + }); +}); + +describe('[#34919] query_dataset sourceLine — the provenance as one finished line', () => { + it('is composed from the answer\'s provenance, in the caller\'s language, and parses', async () => { + const { service } = await bootWired([{ stage: 'won', revenue: 100 }]); + const tools = service.datasetTools({ loadDatasets: loadSaved }); + const out = await tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'] } }, ME); + expect(out.sourceLine).toBe(composeDatasetSourceLine(out.provenance, ['zh-CN'])); + for (const label of ['营收', '销售分析', 'Stage']) expect(out.sourceLine).toContain(label); + const admin = await tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'] } }, ADMIN); + expect(admin.sourceLine).toBe(composeDatasetSourceLine(admin.provenance, [])); + for (const label of ['Revenue', 'Pipeline']) expect(admin.sourceLine).toContain(label); + for (const answer of [out, admin]) expect(QueryDatasetOutputSchema.safeParse(answer).success).toBe(true); + }); + + it('names no member the caller was not admitted to (N5): a withheld measure is refused before any line exists', async () => { + const { service } = await bootWired([{ stage: 'won', opp_count: 3 }]); + const tools = service.datasetTools({ loadDatasets: loadCrm }); + const out = await tools.queryDataset({ datasetName: 'crm_opportunity_metrics', selection: { measures: ['opp_count'], dimensions: ['stage'] } }, REP); + for (const label of ['Opportunities', 'Opportunity Metrics', 'Stage']) expect(out.sourceLine).toContain(label); + for (const word of WITHHELD_WORDS) expect(out.sourceLine).not.toContain(word); + await expect(tools.queryDataset({ datasetName: 'crm_opportunity_metrics', selection: { measures: ['total_amount'] } }, REP)) + .rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + }); +}); diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts new file mode 100644 index 00000000000..a696dd1d13c --- /dev/null +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -0,0 +1,369 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { + DatasetNextStep, + DatasetNextStepDecision, + DatasetProvenance, + DatasetTermCandidate, + DatasetToolCatalogEntry, +} from '@objectstack/spec/ai'; +import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system'; + +/** + * [ADR-0149 M1, the amendment note under it; ruling #34894 = A] The two + * finished sentences the dataset tools hand a caller: `list_datasets`' + * `nextStep` (which case of the D3 selection rule the caller's words are in, + * and that case in words) and `query_dataset`'s `sourceLine` (the answer's + * source as one line to cite). The spec declares the shapes + * (`DatasetNextStepSchema`, `QueryDatasetOutputSchema.sourceLine`) and fixes no + * wording; the wording is this file's. + * + * A model handed a finished string copies it, and one that assembles the same + * sentence from parts often does not: that is why the platform writes the + * sentence instead of leaving `matches`, `candidates` and `provenance` for each + * client to phrase. + * + * ## Only from the admitted answer + * + * Both sentences are composed from the answer the caller is served and from + * nothing else: `nextStep` from that answer's catalogue entries (their + * `matches`, and the labels of the members they list) and its `candidates`, + * `sourceLine` from the answer's `provenance`. A withheld member, an + * `internal`-field member and a dataset the caller may not query are not in + * that answer, so no sentence can name them (ADR-0149 D2, ADR-0100). The + * caller's own terms are quoted back as sent. + * + * ## The decision for one term + * + * A term's case counts MEASURES, as D3 selects a measure: the distinct + * measures, across the listed datasets, whose `matches` entry carries the term. + * + * - exactly one ⇒ `one_measure`; more than one ⇒ `several_measures`; + * - none, and `candidates` holds entries for the term ⇒ `candidates_only` + * (a term with any hit, a dimension hit included, has no candidate); + * - otherwise ⇒ `no_measure`, which is also the case of a term that equals + * only a dimension (a grouping is not a number, D3 rule 5). + * + * A term sent twice is one term, and a member it equals is counted once. + * + * ## Precedence among the terms' cases + * + * One answer carries one `nextStep`, reporting one case, and `terms` names + * every term sent (each once, in the order sent) that is in it. When the terms + * are in different cases, the reported case is the first of: + * + * 1. `several_measures` — a word for a measure is ambiguous. Nothing can be + * computed for it until the user picks, and an answer computed for the + * other words alone would answer a question the user did not ask. + * 2. `one_measure` — every remaining measure word is decided. An exact + * equality outranks a possible reading, and a dimension-matched term never + * outranks a measure-matched one: `["营收", "销售阶段"]` is `one_measure` + * with `terms: ["营收"]`, the grouping left in `matches`. + * 3. `candidates_only` — no word equals a measure, and a possible reading is + * a question worth asking before falling back. + * 4. `no_measure` — no measure and no reading for any word. + * + * The terms of an unreported case keep their entries in `matches` and + * `candidates`; `nextStep` only names which case comes first. + * + * ## An incomplete catalogue + * + * A `partial: true` answer still carries `nextStep`, computed from what it + * lists (every invariant of the shape holds over that answer), and its `note` + * ends by saying that the catalogue was incomplete, that a measure missing from + * it may exist, and that the answer's `warning` is to be repeated. `no_measure` + * on a degraded read is the case most likely to be an artefact of the read, and + * the sentence says so where a bare omission would leave the reader to the + * tool description's rule alone. + * + * ## Language + * + * The caller's locale, read the way every platform-composed sentence reads it + * (`ApiErrorSchema.userMessage`, `@objectstack/spec/api` `contract.zod.ts`): + * the request's locale, else the workspace default, else `en`. Both values are + * the ones the door already put on the caller's `ExecutionContext` (`locale`, + * `workspaceLocale`), the context the executor resolves every label with, so + * the HTTP door and the stdio door get the same sentence for the same caller. + * A code is read through the platform locale table (`platformLocaleTagOf`), + * whole and then one subtag shorter at a time; a language with no sentences + * here takes the next rung. + */ + +/** The languages this file writes, keyed by platform locale tag; `en` is the floor. */ +type NextStepLocale = Extract; + +/** A member as a sentence names it: its label and its dataset's label, both as the answer lists them. */ +interface NamedMember { + readonly label: string; + readonly datasetLabel: string; + readonly datasetName: string; + readonly name: string; +} + +interface DatasetToolCopy { + /** Joins the sentences of one note. */ + readonly sentenceGap: string; + readonly member: (m: NamedMember) => string; + readonly list: (items: readonly string[]) => string; + readonly oneHit: (term: string, m: NamedMember) => string; + readonly oneTail: (count: number) => string; + readonly severalHit: (term: string, members: string) => string; + readonly severalTail: string; + readonly candidateHit: (term: string, members: string) => string; + readonly candidateTail: string; + readonly groupingHit: (term: string, members: string) => string; + readonly unknownHit: (term: string) => string; + readonly fallbackTail: string; + readonly groupingTail: string; + readonly partialTail: string; + readonly source: (measures: readonly string[], dataset: string, dimensions: readonly string[]) => string; +} + +const COPY: Readonly> = { + en: { + sentenceGap: ' ', + member: (m) => `${m.label} (dataset: ${m.datasetLabel})`, + list: (items) => items.join('; '), + oneHit: (t, m) => `"${t}" equals one measure: ${m.label} (dataset: ${m.datasetLabel}), queried as datasetName "${m.datasetName}", measure "${m.name}".`, + oneTail: (n) => (n === 1 + ? 'Answer with query_dataset using that measure, and cite the answer\'s sourceLine as its source.' + : 'Each is its own metric: compute every one with query_dataset, and cite each answer\'s sourceLine as its source.'), + severalHit: (t, ms) => `"${t}" equals several measures: ${ms}.`, + severalTail: 'Ask the user which one they mean, listing each one\'s label, dataset label and description; do not pick one, and compute nothing until they answer.', + candidateHit: (t, ms) => `"${t}" matches no member exactly; possible readings: ${ms}.`, + candidateTail: 'Ask the user which one they mean, listing each one\'s label, dataset label and description (with a single reading, ask whether it is the one meant); do not pick one, never treat a reading as a match, and compute nothing until they answer.', + groupingHit: (t, ms) => `"${t}" equals a grouping, not a number: ${ms}.`, + unknownHit: (t) => `"${t}" equals no measure and has no possible reading.`, + fallbackTail: 'Answer with the object query tools (query_records, aggregate_records) and say in the answer that no governed metric was used.', + groupingTail: 'A grouping alone is no answer: ask the user which number they mean.', + partialTail: 'The catalogue was incomplete (see warning): a measure missing from this answer may still exist, so repeat the warning in the answer.', + source: (ms, ds, dims) => `${ms.length === 1 ? 'Metric' : 'Metrics'}: ${ms.join(', ')} (dataset: ${ds})${dims.length > 0 ? `; grouped by: ${dims.join(', ')}` : ''}`, + }, + 'zh-Hans': { + sentenceGap: '', + member: (m) => `${m.label}(数据集:${m.datasetLabel})`, + list: (items) => items.join('、'), + oneHit: (t, m) => `「${t}」只等于一个指标:${m.label}(数据集:${m.datasetLabel}),查询时 datasetName 为 "${m.datasetName}"、measure 为 "${m.name}"。`, + oneTail: (n) => (n === 1 + ? '用 query_dataset 按这个指标回答,并引用返回的 sourceLine 作为来源。' + : '每个词是一个独立的指标:逐个用 query_dataset 计算,并引用每次返回的 sourceLine 作为来源。'), + severalHit: (t, ms) => `「${t}」等于多个指标:${ms}。`, + severalTail: '先问用户指的是哪一个,列出每一个的名称、所属数据集名称和说明;不要替用户选,用户回答前不要计算。', + candidateHit: (t, ms) => `「${t}」没有精确匹配任何成员,可能指的是:${ms}。`, + candidateTail: '先问用户指的是哪一个,列出每一个的名称、所属数据集名称和说明(只有一个时,问是不是它);不要替用户选,也不要把它当作匹配,用户回答前不要计算。', + groupingHit: (t, ms) => `「${t}」是分组维度,不是数字:${ms}。`, + unknownHit: (t) => `「${t}」没有匹配任何指标,也没有可能的候选。`, + fallbackTail: '改用对象查询工具(query_records、aggregate_records)回答,并在回答中注明未使用治理指标(非指标口径)。', + groupingTail: '只有分组维度还不能回答:问用户想看哪个数字。', + partialTail: '数据集目录不完整(见 warning):这里没有列出的指标仍可能存在,请在回答中转述该警告。', + source: (ms, ds, dims) => `指标:${ms.join('、')}(数据集:${ds})${dims.length > 0 ? `;维度:${dims.join('、')}` : ''}`, + }, + 'zh-Hant': { + sentenceGap: '', + member: (m) => `${m.label}(資料集:${m.datasetLabel})`, + list: (items) => items.join('、'), + oneHit: (t, m) => `「${t}」只等於一個指標:${m.label}(資料集:${m.datasetLabel}),查詢時 datasetName 為 "${m.datasetName}"、measure 為 "${m.name}"。`, + oneTail: (n) => (n === 1 + ? '用 query_dataset 按這個指標回答,並引用回傳的 sourceLine 作為來源。' + : '每個詞是一個獨立的指標:逐一用 query_dataset 計算,並引用每次回傳的 sourceLine 作為來源。'), + severalHit: (t, ms) => `「${t}」等於多個指標:${ms}。`, + severalTail: '先問使用者指的是哪一個,列出每一個的名稱、所屬資料集名稱和說明;不要替使用者選,使用者回答前不要計算。', + candidateHit: (t, ms) => `「${t}」沒有精確符合任何成員,可能指的是:${ms}。`, + candidateTail: '先問使用者指的是哪一個,列出每一個的名稱、所屬資料集名稱和說明(只有一個時,問是不是它);不要替使用者選,也不要把它當作符合,使用者回答前不要計算。', + groupingHit: (t, ms) => `「${t}」是分組維度,不是數字:${ms}。`, + unknownHit: (t) => `「${t}」沒有符合任何指標,也沒有可能的候選。`, + fallbackTail: '改用物件查詢工具(query_records、aggregate_records)回答,並在回答中註明未使用治理指標(非指標口徑)。', + groupingTail: '只有分組維度還不能回答:問使用者想看哪個數字。', + partialTail: '資料集目錄不完整(見 warning):這裡沒有列出的指標仍可能存在,請在回答中轉述該警告。', + source: (ms, ds, dims) => `指標:${ms.join('、')}(資料集:${ds})${dims.length > 0 ? `;維度:${dims.join('、')}` : ''}`, + }, + ja: { + sentenceGap: '', + member: (m) => `${m.label}(データセット:${m.datasetLabel})`, + list: (items) => items.join('、'), + oneHit: (t, m) => `「${t}」は一つの指標だけに一致します:${m.label}(データセット:${m.datasetLabel})。クエリでは datasetName "${m.datasetName}"、measure "${m.name}" です。`, + oneTail: (n) => (n === 1 + ? 'query_dataset でその指標を使って回答し、回答の sourceLine を出典として引用してください。' + : 'それぞれが別の指標です:一つずつ query_dataset で計算し、各回答の sourceLine を出典として引用してください。'), + severalHit: (t, ms) => `「${t}」は複数の指標に一致します:${ms}。`, + severalTail: 'どれを指しているかユーザーに確認し、それぞれの名前、データセット名、説明を示してください。代わりに選ばず、回答があるまで計算しないでください。', + candidateHit: (t, ms) => `「${t}」はどのメンバーにも完全には一致しません。候補:${ms}。`, + candidateTail: 'どれを指しているかユーザーに確認し、それぞれの名前、データセット名、説明を示してください(候補が一つなら、それで合っているか確認してください)。代わりに選ばず、候補を一致として扱わず、回答があるまで計算しないでください。', + groupingHit: (t, ms) => `「${t}」は数値ではなくグループ分けです:${ms}。`, + unknownHit: (t) => `「${t}」はどの指標にも一致せず、候補もありません。`, + fallbackTail: 'オブジェクトのクエリツール(query_records、aggregate_records)で回答し、管理された指標を使っていないことを回答に明記してください。', + groupingTail: 'グループ分けだけでは回答になりません:どの数値を知りたいかユーザーに確認してください。', + partialTail: 'データセットのカタログは不完全です(warning を参照):ここにない指標が存在する可能性があるため、回答でその警告を伝えてください。', + source: (ms, ds, dims) => `指標:${ms.join('、')}(データセット:${ds})${dims.length > 0 ? `;ディメンション:${dims.join('、')}` : ''}`, + }, +}; + +/** + * The platform locale a code names, or `undefined`: the whole code through + * `platformLocaleTagOf`, then each shorter prefix one subtag at a time (RFC + * 4647 lookup: `zh-CN` → `zh-Hans`, `en-GB` → `en`, `zh-Hant-TW` → `zh-Hant`). + * The first prefix the table names decides, so a Traditional Chinese code is + * never handed the Simplified sentence. + */ +function platformLocaleNamedBy(code: string | undefined): PlatformLocaleTag | undefined { + if (typeof code !== 'string' || code.length === 0) return undefined; + const subtags = code.split('-'); + for (let n = subtags.length; n > 0; n -= 1) { + const tag = platformLocaleTagOf(subtags.slice(0, n).join('-')); + if (tag !== undefined) return tag; + } + return undefined; +} + +/** + * The language a sentence is written in for an ordered list of candidate codes + * (the request's locale, then the workspace default): the first that names a + * language this file writes, else `en`. + */ +export function datasetToolSentenceLocale(locales: readonly (string | undefined)[]): NextStepLocale { + for (const code of locales) { + const tag = platformLocaleNamedBy(code); + if (tag !== undefined && Object.prototype.hasOwnProperty.call(COPY, tag)) return tag as NextStepLocale; + } + return 'en'; +} + +/** The decisions in reporting order: the first a term is in is the case `nextStep` reports. */ +const DECISION_PRECEDENCE: readonly DatasetNextStepDecision[] = ['several_measures', 'one_measure', 'candidates_only', 'no_measure']; + +interface TermReading { + readonly term: string; + readonly decision: DatasetNextStepDecision; + readonly measures: readonly NamedMember[]; + readonly dimensions: readonly NamedMember[]; + readonly candidates: readonly NamedMember[]; +} + +/** The member a `kind.name` pointer names in `entry`, as the entry lists it, or `undefined`. */ +function memberOf(entry: DatasetToolCatalogEntry, pointer: string): (NamedMember & { kind: string }) | undefined { + const dot = pointer.indexOf('.'); + const kind = pointer.slice(0, dot); + const name = pointer.slice(dot + 1); + const list = kind === 'measures' ? entry.measures : kind === 'dimensions' ? entry.dimensions : undefined; + const member = list?.find((m) => m.name === name); + if (!member) return undefined; + return { kind, label: member.label, datasetLabel: entry.label, datasetName: entry.name, name: member.name }; +} + +/** How one term reads in this answer ({@link composeDatasetNextStep}). */ +function readTerm( + term: string, + datasets: readonly DatasetToolCatalogEntry[], + candidates: readonly DatasetTermCandidate[], +): TermReading { + const measures: NamedMember[] = []; + const dimensions: NamedMember[] = []; + datasets.forEach((entry) => { + // A term sent twice repeats its entries in `matches`: one member counts once. + const seen = new Set(); + for (const match of entry.matches ?? []) { + if (match.term !== term || seen.has(match.member)) continue; + seen.add(match.member); + const member = memberOf(entry, match.member); + if (member?.kind === 'measures') measures.push(member); + else if (member?.kind === 'dimensions') dimensions.push(member); + } + }); + const offered: NamedMember[] = []; + for (const candidate of candidates) { + if (candidate.term !== term) continue; + // A candidate points at a member the same answer lists (the shape's invariant). + for (const entry of datasets) { + if (entry.name !== candidate.dataset) continue; + const member = memberOf(entry, candidate.member); + if (member) { + offered.push(member); + break; + } + } + } + const decision: DatasetNextStepDecision = measures.length === 1 + ? 'one_measure' + : measures.length > 1 + ? 'several_measures' + : offered.length > 0 + ? 'candidates_only' + : 'no_measure'; + return { term, decision, measures, dimensions, candidates: offered }; +} + +/** What {@link composeDatasetNextStep} reads: the answer `list_datasets` is about to serve, and the caller's locales. */ +export interface DatasetNextStepSource { + /** The caller's terms, as sent. */ + readonly terms: readonly string[]; + /** The answer's catalogue entries, each with its `matches`. */ + readonly datasets: readonly DatasetToolCatalogEntry[]; + /** The answer's `candidates`. */ + readonly candidates: readonly DatasetTermCandidate[]; + /** The answer is `partial: true`. */ + readonly partial: boolean; + /** The request's locale, then the workspace default. */ + readonly locales: readonly (string | undefined)[]; +} + +/** + * [ADR-0149 M1 note] `list_datasets`' `nextStep` for the answer it is about to + * serve: the case the precedence above reports, every term sent that is in it, + * and the sentence. `undefined` when no term was sent. Reads nothing but + * `source`, which is the served answer. + */ +export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNextStep | undefined { + const unique = [...new Set(source.terms)]; + if (unique.length === 0) return undefined; + const readings = unique.map((term) => readTerm(term, source.datasets, source.candidates)); + const decision = DECISION_PRECEDENCE.find((d) => readings.some((r) => r.decision === d))!; + const reported = readings.filter((r) => r.decision === decision); + const copy = COPY[datasetToolSentenceLocale(source.locales)]; + const members = (ms: readonly NamedMember[]) => copy.list(ms.map(copy.member)); + + const sentences: string[] = []; + switch (decision) { + case 'one_measure': + for (const r of reported) sentences.push(copy.oneHit(r.term, r.measures[0])); + sentences.push(copy.oneTail(reported.length)); + break; + case 'several_measures': + for (const r of reported) sentences.push(copy.severalHit(r.term, members(r.measures))); + sentences.push(copy.severalTail); + break; + case 'candidates_only': + for (const r of reported) sentences.push(copy.candidateHit(r.term, members(r.candidates))); + sentences.push(copy.candidateTail); + break; + case 'no_measure': { + for (const r of reported) { + sentences.push(r.dimensions.length > 0 ? copy.groupingHit(r.term, members(r.dimensions)) : copy.unknownHit(r.term)); + } + // A word for a thing measured that names nothing falls back (D3 rule 4); + // a grouping word alone asks which number is meant (rule 5). + sentences.push(reported.some((r) => r.dimensions.length === 0) ? copy.fallbackTail : copy.groupingTail); + break; + } + } + if (source.partial) sentences.push(copy.partialTail); + return { decision, terms: reported.map((r) => r.term), note: sentences.join(copy.sentenceGap) }; +} + +/** + * [ADR-0149 M1 note] `query_dataset`'s `sourceLine`: the answer's + * `provenance` as one line to cite — each measure's label and the dataset's + * label, then each dimension's label — in the caller's language. Composed from + * `provenance` alone, which names only the members the selection asked for and + * the service answered, after the query ran. + */ +export function composeDatasetSourceLine( + provenance: DatasetProvenance, + locales: readonly (string | undefined)[], +): string { + const copy = COPY[datasetToolSentenceLocale(locales)]; + return copy.source( + provenance.measures.map((m) => m.label), + provenance.dataset.label, + (provenance.dimensions ?? []).map((d) => d.label), + ); +} diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 7efcfee5b29..17ab2ec32ad 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -13,7 +13,12 @@ import { type ListDatasetsOutput, type QueryDatasetOutput, } from '@objectstack/spec/ai'; -import { PackageScopedNameRefusedError, packageScopedHolderSource, resolvePackageScopedHolders } from '@objectstack/core'; +import { + PackageScopedNameRefusedError, + packageScopedHolderSource, + resolvePackageScopedHolders, + userTextLocalesOf, +} from '@objectstack/core'; import type { AIToolDefinition, AnalyticsResult, DatasetSelection } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { stripReadDecorations } from '@objectstack/spec/kernel'; @@ -29,6 +34,7 @@ import { usableDeclaredMembers, } from './dataset-declared-members.js'; import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } from './dataset-term-matcher.js'; +import { composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js'; /** * The dataset AI tools — `list_datasets` and `query_dataset` — defined once, @@ -66,6 +72,16 @@ import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } f * then judged) and its `runtimeFilter`, echoed as sent. The input is a * strict object, so a `provenance` (or any other key) the model puts beside * `datasetName` / `selection` is refused, never merged. + * + * ## The next step and the source line, as finished sentences (M1 note) + * + * [Ruling #34894 = A] `list_datasets` answers `nextStep` whenever terms were + * sent: the case of the D3 rule the terms are in, the terms it is about and + * that case in words. `query_dataset` answers `sourceLine`, `provenance` as + * one line to cite. Both are composed in `dataset-next-step.ts` from the + * answer being served and nothing else, in the caller's language; that file + * holds the per-term decision, the precedence among mixed cases and the + * partial-answer rule. */ /** `query_dataset`'s row cap when the host sets none — `query_records`' default. */ @@ -96,7 +112,8 @@ const LIST_DATASETS_DESCRIPTION = + 'say in the answer that no governed metric was used (非指标口径); when the object you fall back to is a listed ' + 'dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone picks a ' + 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this ' - + 'caller may not see.'; + + 'caller may not see. When `terms` were sent the answer carries `nextStep`: the case of this rule your words are ' + + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`.'; const QUERY_DATASET_DESCRIPTION = 'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business ' @@ -104,7 +121,8 @@ const QUERY_DATASET_DESCRIPTION = + 'member names `list_datasets` lists for that dataset; any other name (a raw field, `count`) is refused ' + 'INVALID_FIELD, naming the members you may use. Answers the rows plus ' + '`provenance` naming the dataset and the measures used — render the answer\'s source from `provenance` ' - + '(e.g. 「指标:营收(数据集:销售分析)」), and explain a number with its measure\'s description. A dataset that ' + + '(e.g. 「指标:营收(数据集:销售分析)」); `sourceLine` is that source already written in the caller\'s language, ' + + 'so cite it as given. Explain a number with its measure\'s description. A dataset that ' + 'does not exist and one this caller may not query both answer NOT_FOUND. Rows are capped; `truncated` says ' + 'more existed.'; @@ -400,10 +418,14 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { loaded = await load(service, context); } catch (e) { // The #6504 shape: never a count that is not a fact. + const nextStep = terms !== undefined + ? composeDatasetNextStep({ terms, datasets: [], candidates: [], partial: true, locales: sentenceLocales(context) }) + : undefined; return { datasets: [], partial: true, warning: `The dataset catalogue could not be read: ${e instanceof Error ? e.message : String(e)}`, + ...(nextStep ? { nextStep } : {}), }; } @@ -455,10 +477,16 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { if (unresolved) { warnings.push('Some datasets or members could not be checked against this caller\'s permissions and are left out.'); } + // [ADR-0149 M1 note] Composed last, from this answer alone: the entries + // and candidates above are the admitted members, and nothing else is read. + const nextStep = terms !== undefined + ? composeDatasetNextStep({ terms, datasets: entries, candidates, partial: warnings.length > 0, locales: sentenceLocales(context) }) + : undefined; return { datasets: entries, ...(warnings.length > 0 ? { partial: true as const, warning: warnings.join(' ') } : {}), ...(candidates.length > 0 ? { candidates } : {}), + ...(nextStep ? { nextStep } : {}), }; } @@ -556,11 +584,14 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { narrowing = await deps.diagnoseDelegation(dataset.object, context).catch(() => undefined); } + // Composed last, so nothing the answer carries can stand in for them. + const provenance = composeProvenance(dataset, raw.selection, context?.locale); return { ...rest, rows: served, - // Composed last, so nothing the answer carries can stand in for them. - provenance: composeProvenance(dataset, raw.selection, context?.locale), + provenance, + // [ADR-0149 M1 note] The same source as one line, from `provenance` alone. + sourceLine: composeDatasetSourceLine(provenance, sentenceLocales(context)), rowCount: served.length, truncated, ...(narrowing?.narrowed && narrowing.statement @@ -669,6 +700,16 @@ function composeProvenance( } as DatasetProvenance; } +/** + * The locales a sentence the tools compose is written for: the caller's locale, + * then the workspace default, as the door put them on the context. The user-text + * ladder every platform-composed sentence reads (`userTextLocalesOf`), never a + * second reading; `en` below both. + */ +function sentenceLocales(context: ExecutionContext | undefined): string[] { + return userTextLocalesOf(context); +} + /** A saved item's `name` for the server log, or a placeholder. */ function datasetItemName(item: unknown): string { const name = (item as { name?: unknown } | null | undefined)?.name; From 284c04b2fcf7a79baca52ccc5d3fb331bbfae326 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:38:54 +0000 Subject: [PATCH 05/11] feat(analytics): the tool texts say follow nextStep and cite sourceLine, naming the precedence LIST_DATASETS_DESCRIPTION names the order from the exported DATASET_NEXT_STEP_PRECEDENCE; the MCP initialize rule says the same and is pinned to the constant. The DATASET_SELECTION_RULE docblock drops its stale sentence about the skill's loose-form rows. Both doors are pinned to pass the executor's answer through unchanged, one sentence on HTTP and stdio. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34919-dataset-next-step-executor.md | 20 ++++ .../initialize-selection-rule-34686.test.ts | 17 +++ packages/mcp/src/mcp-dataset-tools.test.ts | 100 +++++++++++++++++- packages/mcp/src/mcp-server-runtime.ts | 11 +- .../src/__tests__/dataset-tools.test.ts | 10 +- .../src/dataset-next-step.ts | 16 ++- .../service-analytics/src/dataset-tools.ts | 6 +- .../services/service-analytics/src/index.ts | 2 + 8 files changed, 172 insertions(+), 10 deletions(-) create mode 100644 .changeset/34919-dataset-next-step-executor.md diff --git a/.changeset/34919-dataset-next-step-executor.md b/.changeset/34919-dataset-next-step-executor.md new file mode 100644 index 00000000000..1fd40dfb55c --- /dev/null +++ b/.changeset/34919-dataset-next-step-executor.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-analytics': patch +'@objectstack/mcp': patch +--- + +feat(analytics): `list_datasets` answers `nextStep` and `query_dataset` answers `sourceLine`, written by the platform in the caller's language + +Clause-②: no +Metadata-protocol: none + +The dataset tools now fill the two members the spec declares (`DatasetNextStepSchema`, `QueryDatasetOutputSchema.sourceLine`, `@objectstack/spec/ai`). Until now the decision "one match answers, several ask, near ones are offered, none falls back" and the citation line were left for each AI client to work out from `matches`, `candidates` and `provenance`; a model handed a finished sentence copies it, and one that builds it from parts often does not. + +- **`nextStep` on `list_datasets`, whenever `terms` were sent.** `decision` is the case of the ADR-0149 D3 rule the words are in, counted in measures: one measure equals the word ⇒ `one_measure`; more than one, in one dataset or several ⇒ `several_measures`; no match but `candidates` ⇒ `candidates_only`; otherwise `no_measure`, which includes a word that equals only a dimension. `terms` names every word sent (once each, in order) that is in the reported case. `note` is that case as a finished sentence: the measure and the names to query for `one_measure`; each member by its label and its dataset's label for `several_measures` and `candidates_only`, with "ask the user, do not pick"; the object query tools for an unknown word, and "ask which number" for a word that is only a grouping. +- **Precedence among mixed cases.** One answer reports one case, the first of `several_measures`, `one_measure`, `candidates_only`, `no_measure`. A word that matches only a dimension never outranks a measure match: `["营收", "销售阶段"]` reports `one_measure` for `营收`. The order is exported as `DATASET_NEXT_STEP_PRECEDENCE` from `@objectstack/service-analytics`, and the tool description and the MCP `initialize` rule name it. +- **A partial answer says so.** With `partial: true` the answer still carries `nextStep`, computed from what it lists, and `note` ends by saying the catalogue was incomplete, that a measure missing from it may exist, and to repeat the `warning`. +- **`sourceLine` on `query_dataset`.** The answer's `provenance` as one line to cite: each measure's label and the dataset's label, then each dimension's label (`指标:营收(数据集:销售分析);维度:阶段`). `provenance` is unchanged and stays the structured source. The REST dataset door's answer is not changed. +- **Only what the caller may see.** Both sentences are composed from the answer being served: a member over a field the caller cannot read, an `internal` member and a dataset the caller may not query never appear in either. +- **Language.** The request's locale, else the workspace default, else English, the ladder every platform-composed sentence follows (`userTextLocalesOf`, read from the caller's execution context). Sentences are written in English, Simplified Chinese, Traditional Chinese and Japanese; another language takes the next rung. The HTTP and stdio MCP doors hand the executor the same context, so one caller reads one sentence on either. + +`@objectstack/mcp`: the `initialize` selection rule now tells the client to follow `nextStep`'s note, names the precedence, and says to cite `sourceLine`. Both tools pass the two members through unchanged. diff --git a/packages/mcp/src/initialize-selection-rule-34686.test.ts b/packages/mcp/src/initialize-selection-rule-34686.test.ts index cf33e7df170..a657030edb7 100644 --- a/packages/mcp/src/initialize-selection-rule-34686.test.ts +++ b/packages/mcp/src/initialize-selection-rule-34686.test.ts @@ -25,6 +25,7 @@ import { MCP_OAUTH_SCOPE_METADATA_WRITE, QUERY_DATASET_TOOL_NAME, } from '@objectstack/spec/ai'; +import { DATASET_NEXT_STEP_PRECEDENCE } from '@objectstack/service-analytics'; import { MCPServerRuntime } from './mcp-server-runtime.js'; import type { McpDataBridge } from './mcp-http-tools.js'; import type { McpAuthoringInjection } from './types.js'; @@ -192,3 +193,19 @@ describe('[#34686] initialize instructions — host and configured texts are lef expect(await instructionsOf(runtime, makeBridge())).toBe(CONFIGURED); }); }); + +/** + * [#34919] The rule tells the client to follow `list_datasets`' `nextStep` + * and cite `query_dataset`'s `sourceLine`, and names the precedence among + * mixed cases in the order the service-analytics executor applies it (its + * exported constant, so a reorder there reds here). + */ +describe('[#34919] initialize instructions — follow nextStep, cite sourceLine', () => { + it('names both members and the executor\'s precedence, in its order', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const text = await instructionsOf(runtime, makeBridge()); + expect(text).toContain('nextStep'); + expect(text).toContain('sourceLine'); + expect(text).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', ')); + }); +}); diff --git a/packages/mcp/src/mcp-dataset-tools.test.ts b/packages/mcp/src/mcp-dataset-tools.test.ts index 63a7fc8a77a..552ef03ae4d 100644 --- a/packages/mcp/src/mcp-dataset-tools.test.ts +++ b/packages/mcp/src/mcp-dataset-tools.test.ts @@ -11,7 +11,9 @@ * the bridge as sent, with the tool's page cap beside them; an undeclared key is * refused before the bridge is asked, in the spec's words; a refusal the bridge * throws comes back as the coded tool error; `list_datasets.candidates` comes - * back exactly as the executor answered it (#34763). + * back exactly as the executor answered it (#34763); `list_datasets.nextStep` + * and `query_dataset.sourceLine` reach the client as the executor wrote them, + * one sentence for one caller on HTTP and on stdio (#34919). */ import { describe, it, expect, beforeEach, vi } from 'vitest'; @@ -29,6 +31,7 @@ import { MCPServerRuntime } from './mcp-server-runtime.js'; import { hasDatasetTools, type McpDataBridge } from './mcp-http-tools.js'; import { createStdioDataBridge, type StdioDatasetToolsService } from './stdio-data-bridge.js'; import { ASK_SECTION_HEADING, renderSkillMarkdown } from './skill-md.js'; +import { AnalyticsServicePlugin, type AnalyticsService } from '@objectstack/service-analytics'; const DATASET_TOOLS = [LIST_DATASETS_TOOL_NAME, QUERY_DATASET_TOOL_NAME].sort(); @@ -443,3 +446,98 @@ describe('[#34763] list_datasets candidates pass through MCP unchanged', () => { expect('candidates' in answer).toBe(false); }); }); + +/** + * [#34919, ADR-0149 M1 note] `list_datasets.nextStep` and + * `query_dataset.sourceLine` are written by the service-analytics executor + * (`dataset-next-step.ts`, pinned there); the MCP door holds no copy of either + * sentence. Here the REAL executor, over a service `AnalyticsServicePlugin` + * wires, answers one caller through the HTTP tool layer and through the stdio + * bridge: both doors serve the executor's answer unchanged, so the caller reads + * the same decision and the same sentence, in its locale, on either transport. + */ +describe('[#34919] nextStep and sourceLine reach the client unchanged, one sentence on HTTP and stdio', () => { + const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1', locale: 'zh-CN' }; + const OBJECTS: Record }> = { + crm_opportunity: { fields: { id: { type: 'text' }, stage: { type: 'text' }, amount: { type: 'number' } } }, + }; + const METRICS = { + name: 'crm_opportunity_metrics', + label: 'Opportunity Metrics', + object: 'crm_opportunity', + dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string', synonyms: ['销售阶段'] }], + measures: [ + { name: 'opp_count', label: 'Opportunities', aggregate: 'count', synonyms: ['商机数'] }, + { name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount', synonyms: ['商机金额'] }, + ], + }; + + async function wiredService(): Promise { + const registered: Record = {}; + const engine = { + execute: async () => ({ rows: [{ stage: 'won', opp_count: 3 }] }), + hasObjectMiddleware: () => false, + getObject: (name: string) => OBJECTS[name], + resolveEffectiveDatasource: () => undefined, + }; + const allFields = async (object: string) => Object.keys(OBJECTS[object]?.fields ?? {}); + const security = { getReadFilter: async () => undefined, canReadObject: () => true, getReadableFields: allFields, getQueryableFields: allFields }; + const ctx = { + getService: (name: string) => (name === 'security' ? security : name === 'data' ? engine : registered[name]), + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + }; + await new AnalyticsServicePlugin({ queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }) }) + .init(ctx as never); + return registered.analytics as AnalyticsService; + } + + /** The HTTP door's bridge members over the executor, as the runtime binds them to the request's principal. */ + function httpBridge(service: AnalyticsService): McpDataBridge { + const executor = () => service.datasetTools({ loadDatasets: async () => [METRICS] }); + const bridge = makeBridge(); + bridge.listDatasets = (input) => executor().listDatasets(input, PRINCIPAL as never); + bridge.queryDataset = (input) => executor().queryDataset(input, PRINCIPAL as never); + bridge.datasetToolDefinitions = () => executor().definitions; + return bridge; + } + + function stdioBridge(service: AnalyticsService) { + return createStdioDataBridge({ + engine: {} as any, + metadataService: { list: async () => [] } as any, + protocol: () => ({ getMetaItems: async () => ({ items: [METRICS] }) }) as any, + resolvePrincipal: async () => PRINCIPAL as any, + datasetTools: service as unknown as StdioDatasetToolsService, + }); + } + + it('list_datasets: the same nextStep on both doors, the executor\'s answer unchanged', async () => { + const service = await wiredService(); + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const input = { terms: ['商机金额', '销售阶段'] }; + const direct = await service.datasetTools({ loadDatasets: async () => [METRICS] }).listDatasets(input, PRINCIPAL as never); + const json = await callTool(runtime, httpBridge(service), LIST_DATASETS_TOOL_NAME, input); + expect(json.result?.isError).toBeFalsy(); + const viaHttp = JSON.parse(json.result!.content[0].text) as ListDatasetsOutput; + const viaStdio = await stdioBridge(service).listDatasets!(input); + expect(viaHttp).toEqual(direct); + expect(direct.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机金额'] }); + expect(viaStdio.nextStep).toEqual(viaHttp.nextStep); + expect(ListDatasetsOutputSchema.safeParse(viaHttp).success).toBe(true); + }); + + it('query_dataset: the same sourceLine on both doors, the executor\'s answer unchanged', async () => { + const service = await wiredService(); + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const input = { datasetName: 'crm_opportunity_metrics', selection: { measures: ['opp_count'], dimensions: ['stage'] } }; + const json = await callTool(runtime, httpBridge(service), QUERY_DATASET_TOOL_NAME, input); + expect(json.result?.isError).toBeFalsy(); + const viaHttp = JSON.parse(json.result!.content[0].text) as QueryDatasetOutput; + const viaStdio = await stdioBridge(service).queryDataset!(input, { maxRows: 50 }); + expect(viaHttp.sourceLine).toEqual(expect.any(String)); + for (const label of ['Opportunities', 'Opportunity Metrics', 'Stage']) expect(viaHttp.sourceLine).toContain(label); + expect(viaStdio.sourceLine).toBe(viaHttp.sourceLine); + }); +}); diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index c11a91bff90..9de8fd9bed0 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1812,8 +1812,11 @@ const DEFAULT_HTTP_INSTRUCTIONS = * that the same question, listing each candidate's label, dataset label and * description, never a pick and never a match, even for a single candidate; * only a word with no match and no candidate falls back to the object tools, - * with the answer labelled. The skill's own loose-form rows predate - * `candidates` and are amended in its lane. + * with the answer labelled. [#34919] The answer itself then states the + * case (`list_datasets` `nextStep`, composed by the service-analytics + * executor, `dataset-next-step.ts`) and the source to cite + * (`query_dataset` `sourceLine`); the rule says to follow the one and cite + * the other, and names the precedence the executor reports mixed cases by. * Sent only where both dataset tools register ({@link datasetToolsServed}). */ const DATASET_SELECTION_RULE = @@ -1824,7 +1827,9 @@ const DATASET_SELECTION_RULE = + 'they mean; do not pick. A word with no match but with candidates in the answer: ask the same way, listing ' + 'each candidate\'s label, dataset label and description; do not pick one or treat it as a match. No match ' + 'and no candidates: fall back to query_records / aggregate_records and say the answer is not from a governed ' - + 'metric.'; + + 'metric. The list_datasets answer states which of these cases your words are in as nextStep: follow its note, ' + + 'which reports the first of several_measures, one_measure, candidates_only, no_measure when words differ. Cite ' + + 'query_dataset\'s sourceLine as the answer\'s source.'; /** * [#34686] The published skills package an open server points a client to diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index f2a6b3f1946..191bfbe897d 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -30,7 +30,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { AnalyticsServicePlugin } from '../plugin.js'; import { AnalyticsService } from '../analytics-service.js'; import { createDatasetTools, getDatasetToolDefinitions } from '../dataset-tools.js'; -import { composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js'; +import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js'; const ME = { userId: 'u_me', tenantId: 'org_a', locale: 'zh-CN' } as ExecutionContext; const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; @@ -178,6 +178,14 @@ describe('the two AIToolDefinitions', () => { expect(defs[0].description).toContain('非指标口径'); expect(defs[1].description).toContain('provenance'); }); + + it('[#34919] says follow nextStep and cite sourceLine, and names the precedence the executor applies', () => { + const [list, query] = getDatasetToolDefinitions(); + expect(list.description).toContain('nextStep'); + expect(list.description).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', ')); + expect(query.description).toContain('sourceLine'); + expect(DATASET_NEXT_STEP_PRECEDENCE).toEqual(['several_measures', 'one_measure', 'candidates_only', 'no_measure']); + }); }); describe('[ADR-0149 D4 caveat] the tools require the plugin-wired service', () => { diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index a696dd1d13c..f162ffd0e2a 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -228,8 +228,18 @@ export function datasetToolSentenceLocale(locales: readonly (string | undefined) return 'en'; } -/** The decisions in reporting order: the first a term is in is the case `nextStep` reports. */ -const DECISION_PRECEDENCE: readonly DatasetNextStepDecision[] = ['several_measures', 'one_measure', 'candidates_only', 'no_measure']; +/** + * The decisions in reporting order: the first a term is in is the case + * `nextStep` reports (the precedence above). `list_datasets`' description names + * this order from this constant, and the MCP `initialize` rule is pinned to it, + * so the order a client is told is the order the executor applies. + */ +export const DATASET_NEXT_STEP_PRECEDENCE: readonly DatasetNextStepDecision[] = Object.freeze([ + 'several_measures', + 'one_measure', + 'candidates_only', + 'no_measure', +]); interface TermReading { readonly term: string; @@ -316,7 +326,7 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe const unique = [...new Set(source.terms)]; if (unique.length === 0) return undefined; const readings = unique.map((term) => readTerm(term, source.datasets, source.candidates)); - const decision = DECISION_PRECEDENCE.find((d) => readings.some((r) => r.decision === d))!; + const decision = DATASET_NEXT_STEP_PRECEDENCE.find((d) => readings.some((r) => r.decision === d))!; const reported = readings.filter((r) => r.decision === decision); const copy = COPY[datasetToolSentenceLocale(source.locales)]; const members = (ms: readonly NamedMember[]) => copy.list(ms.map(copy.member)); diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 17ab2ec32ad..5402e2d168e 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -34,7 +34,7 @@ import { usableDeclaredMembers, } from './dataset-declared-members.js'; import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } from './dataset-term-matcher.js'; -import { composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js'; +import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js'; /** * The dataset AI tools — `list_datasets` and `query_dataset` — defined once, @@ -113,7 +113,9 @@ const LIST_DATASETS_DESCRIPTION = + 'dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone picks a ' + 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this ' + 'caller may not see. When `terms` were sent the answer carries `nextStep`: the case of this rule your words are ' - + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`.'; + + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`. When ' + + `the words are in different cases it reports the first of ${DATASET_NEXT_STEP_PRECEDENCE.join(', ')}, so a word ` + + 'matching only a dimension never outranks a measure match.'; const QUERY_DATASET_DESCRIPTION = 'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business ' diff --git a/packages/services/service-analytics/src/index.ts b/packages/services/service-analytics/src/index.ts index f13ae89496e..e896a35c154 100644 --- a/packages/services/service-analytics/src/index.ts +++ b/packages/services/service-analytics/src/index.ts @@ -55,6 +55,8 @@ export type { } from './dataset-tools.js'; export { matchDatasetTerms } from './dataset-term-matcher.js'; export type { MatchableMember } from './dataset-term-matcher.js'; +// [#34919] The order list_datasets reports mixed cases by (`nextStep`), for the texts that name it. +export { DATASET_NEXT_STEP_PRECEDENCE } from './dataset-next-step.js'; // Strategies export { NativeSQLStrategy } from './strategies/native-sql-strategy.js'; From cfdea828f9056c4d50f6e8bfd5b865a1333651f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:41:31 +0000 Subject: [PATCH 06/11] test(analytics): a word equal to a measure and a dimension reads one_measure Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../service-analytics/src/__tests__/dataset-tools.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 191bfbe897d..8c89721c6cf 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -886,7 +886,8 @@ const CRM_LINE_ITEM_METRICS = { name: 'crm_line_item_metrics', label: 'Line Item Metrics', object: 'crm_opportunity_line_item', - dimensions: [{ name: 'product', label: 'Product', field: 'product', type: 'string' }], + // `deal count` is also `opp_count`'s synonym in the other dataset: a word equal to a measure there and a dimension here. + dimensions: [{ name: 'product', label: 'Product', field: 'product', type: 'string', synonyms: ['deal count'] }], measures: [ { name: 'line_amount', label: 'Line Amount', aggregate: 'sum', field: 'amount', synonyms: ['deal value', '明细金额'] }, { name: 'quantity_total', label: 'Quantity', aggregate: 'sum', field: 'quantity' }, @@ -1016,6 +1017,10 @@ describe('[#34919] list_datasets nextStep — the precedence among mixed cases', expect(await decide(['商机金额', '商机数', '销售阶段'])).toEqual({ decision: 'one_measure', terms: ['商机金额', '商机数'] }); }); + it('a word equal to one measure and to a dimension is one_measure: the dimension is not counted', async () => { + expect(await decide(['deal count'])).toEqual({ decision: 'one_measure', terms: ['deal count'] }); + }); + it('a word sent twice is one word, and the member it equals is counted once', async () => { expect(await decide(['商机数', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] }); }); From d80b2d888ddfd4ce5285e4157f645732e1955173 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:51:22 +0000 Subject: [PATCH 07/11] chore(spec): regenerate the reference index after merging main content/docs/references/index.mdx is generated and was not text-merged in the merge of origin/main. main's side was taken and the page regenerated from the merged tree by `check:generated --fix`: 1673 schemas (main's 1671 plus DatasetNextStep and DatasetNextStepDecision), AI 84, UI 178 with main's ActionRefusal. No other artefact was stale. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- content/docs/references/index.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index d84f1198561..cb2deca35bf 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 — 1672 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1673 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/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [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** | **1672** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 16 | 178 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **218** | **1673** | 14 protocol modules | --- @@ -385,13 +385,13 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 177 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 178 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | File | Schemas | | :--- | :--- | -| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionType`, `InlineAction` | +| [`action.zod.ts`](/docs/references/ui/action) | `Action`, `ActionAi`, `ActionLocation`, `ActionParam`, `ActionRefusal`, `ActionType`, `InlineAction` | | [`action-params.zod.ts`](/docs/references/ui/action-params) | `ActionSession` | | [`app.zod.ts`](/docs/references/ui/app) | `ActionNavItem`, `App`, `AppBranding`, `AppContextSelector`, `AppLandingEntry`, `ComponentNavItem`, `DashboardNavItem`, `DocNavItem`, `GroupNavItem`, `NavigationArea`, `NavigationContribution`, `NavigationItem`, `ObjectNavItem`, `PageNavItem`, `ReportNavItem`, `UrlNavItem` | | [`bulk-action.zod.ts`](/docs/references/ui/bulk-action) | `BulkActionDef`, `BulkActionExecution`, `BulkActionOperation`, `BulkActionParam`, `BulkActionResult` | From 4dd94e3512030d5d71570413d034ea34745c4af8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:10:11 +0000 Subject: [PATCH 08/11] feat(analytics): a one_measure note names the words it leaves out, with their candidates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seat ruling B on the L1-c N1 finding: the order stays; when the reported case is one_measure the note also names each left-out word, a word with candidates together with them, an unknown word with its labelled fallback, a grouping word as the grouping, in all four languages. The changeset declares Clause-② yes (widening). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34919-dataset-next-step-executor.md | 3 +- .../src/__tests__/dataset-tools.test.ts | 23 ++++++++++++ .../src/dataset-next-step.ts | 37 ++++++++++++++++++- .../service-analytics/src/dataset-tools.ts | 3 +- 4 files changed, 62 insertions(+), 4 deletions(-) diff --git a/.changeset/34919-dataset-next-step-executor.md b/.changeset/34919-dataset-next-step-executor.md index 1fd40dfb55c..8109b0d8410 100644 --- a/.changeset/34919-dataset-next-step-executor.md +++ b/.changeset/34919-dataset-next-step-executor.md @@ -5,12 +5,13 @@ feat(analytics): `list_datasets` answers `nextStep` and `query_dataset` answers `sourceLine`, written by the platform in the caller's language -Clause-②: no +Clause-②: yes (widening: the dataset tools' answers now carry `nextStep` and `sourceLine`, `@objectstack/service-analytics` exports `DATASET_NEXT_STEP_PRECEDENCE`, and the `list_datasets` / `query_dataset` descriptions and the MCP `initialize` rule gain the follow-`nextStep`, cite-`sourceLine` instructions) Metadata-protocol: none The dataset tools now fill the two members the spec declares (`DatasetNextStepSchema`, `QueryDatasetOutputSchema.sourceLine`, `@objectstack/spec/ai`). Until now the decision "one match answers, several ask, near ones are offered, none falls back" and the citation line were left for each AI client to work out from `matches`, `candidates` and `provenance`; a model handed a finished sentence copies it, and one that builds it from parts often does not. - **`nextStep` on `list_datasets`, whenever `terms` were sent.** `decision` is the case of the ADR-0149 D3 rule the words are in, counted in measures: one measure equals the word ⇒ `one_measure`; more than one, in one dataset or several ⇒ `several_measures`; no match but `candidates` ⇒ `candidates_only`; otherwise `no_measure`, which includes a word that equals only a dimension. `terms` names every word sent (once each, in order) that is in the reported case. `note` is that case as a finished sentence: the measure and the names to query for `one_measure`; each member by its label and its dataset's label for `several_measures` and `candidates_only`, with "ask the user, do not pick"; the object query tools for an unknown word, and "ask which number" for a word that is only a grouping. +- **Words a `one_measure` answer leaves out are still named.** Its `note` computes the measure word and then names each other word: one with candidates together with those candidates (label and dataset label) and "ask before using it"; an unknown one with its labelled fallback to the object query tools; a grouping word as that grouping. - **Precedence among mixed cases.** One answer reports one case, the first of `several_measures`, `one_measure`, `candidates_only`, `no_measure`. A word that matches only a dimension never outranks a measure match: `["营收", "销售阶段"]` reports `one_measure` for `营收`. The order is exported as `DATASET_NEXT_STEP_PRECEDENCE` from `@objectstack/service-analytics`, and the tool description and the MCP `initialize` rule name it. - **A partial answer says so.** With `partial: true` the answer still carries `nextStep`, computed from what it lists, and `note` ends by saying the catalogue was incomplete, that a measure missing from it may exist, and to repeat the `warning`. - **`sourceLine` on `query_dataset`.** The answer's `provenance` as one line to cite: each measure's label and the dataset's label, then each dimension's label (`指标:营收(数据集:销售分析);维度:阶段`). `provenance` is unchanged and stays the structured source. The REST dataset door's answer is not changed. diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 8c89721c6cf..473c585af06 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -945,6 +945,29 @@ describe('[#34919] list_datasets nextStep on examples/app-crm — the decision e expect(out.nextStep!.note).toContain('"opp_count"'); }); + it('one_measure beside a near-miss word: the measure is computed and the note names the left-out word with its candidates (ruling B)', async () => { + const CANDIDATES = ['Total Amount', 'Avg Deal Size', 'Line Amount']; + for (const ctx of [ADMIN, { ...ADMIN, locale: 'zh-CN' }, { ...ADMIN, locale: 'zh-TW' }, { ...ADMIN, locale: 'ja-JP' }] as ExecutionContext[]) { + const out = await ask(['商机数', '金额'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] }); + const note = out.nextStep!.note; + expect(note, String(ctx.locale)).toContain('"opp_count"'); + expect(note, String(ctx.locale)).toContain('金额'); + for (const label of [...CANDIDATES, 'Line Item Metrics']) expect(note, `${ctx.locale} ⇒ ${label}`).toContain(label); + } + expect((await ask(['商机数', '金额'])).nextStep!.note).toContain('Total Amount (dataset: Opportunity Metrics)'); + }); + + it('one_measure beside an unknown word and a grouping word: the note keeps the unknown word\'s labelled fallback and names the grouping', async () => { + const out = await ask(['商机数', '库存周转', '销售阶段']); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] }); + expect(out.nextStep!.note).toContain('"库存周转"'); + expect(out.nextStep!.note).toContain('query_records'); + expect(out.nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)'); + // The control: alone, the measure word's note sends nobody to the object tools. + expect((await ask(['商机数'])).nextStep!.note).not.toContain('query_records'); + }); + it('a word with two matches ⇒ several_measures, the note naming each by its label and its dataset\'s label', async () => { const out = await ask(['deal value']); expect(out.nextStep).toMatchObject({ decision: 'several_measures', terms: ['deal value'] }); diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index f162ffd0e2a..5ebe676a06b 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -64,7 +64,15 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s * 4. `no_measure` — no measure and no reading for any word. * * The terms of an unreported case keep their entries in `matches` and - * `candidates`; `nextStep` only names which case comes first. + * `candidates`; `decision` and `terms` name only the case that comes first. + * When that case is `one_measure`, `note` still names every word it leaves + * out (seat ruling B on the L1-c N1 finding): a word with candidates + * together with those candidates, each by its label and its dataset's label, + * and the instruction to ask before using it; an unknown word with its + * labelled fallback to the object query tools; a word that equals only a + * dimension as that grouping. `["营收", "churn"]` computes 营收's measure and + * asks about churn's candidates in one sentence. (`several_measures` asks + * before anything is computed, so its note needs no such tail.) * * ## An incomplete catalogue * @@ -116,6 +124,10 @@ interface DatasetToolCopy { readonly fallbackTail: string; readonly groupingTail: string; readonly partialTail: string; + /** After a `one_measure` note: the left-out words that have candidates are asked about before use. */ + readonly leftCandidateTail: string; + /** After a `one_measure` note: the left-out words with no measure and no reading fall back, labelled. */ + readonly leftFallbackTail: string; readonly source: (measures: readonly string[], dataset: string, dimensions: readonly string[]) => string; } @@ -137,6 +149,8 @@ const COPY: Readonly> = { fallbackTail: 'Answer with the object query tools (query_records, aggregate_records) and say in the answer that no governed metric was used.', groupingTail: 'A grouping alone is no answer: ask the user which number they mean.', partialTail: 'The catalogue was incomplete (see warning): a measure missing from this answer may still exist, so repeat the warning in the answer.', + leftCandidateTail: 'For each word above with possible readings, ask the user which one is meant before using it; do not pick one.', + leftFallbackTail: 'For those words, use the object query tools (query_records, aggregate_records) and say in the answer that no governed metric was used for them.', source: (ms, ds, dims) => `${ms.length === 1 ? 'Metric' : 'Metrics'}: ${ms.join(', ')} (dataset: ${ds})${dims.length > 0 ? `; grouped by: ${dims.join(', ')}` : ''}`, }, 'zh-Hans': { @@ -156,6 +170,8 @@ const COPY: Readonly> = { fallbackTail: '改用对象查询工具(query_records、aggregate_records)回答,并在回答中注明未使用治理指标(非指标口径)。', groupingTail: '只有分组维度还不能回答:问用户想看哪个数字。', partialTail: '数据集目录不完整(见 warning):这里没有列出的指标仍可能存在,请在回答中转述该警告。', + leftCandidateTail: '上面有候选的词,先问用户指的是哪一个再使用;不要替用户选。', + leftFallbackTail: '这些词改用对象查询工具(query_records、aggregate_records),并在回答中注明它们未使用治理指标(非指标口径)。', source: (ms, ds, dims) => `指标:${ms.join('、')}(数据集:${ds})${dims.length > 0 ? `;维度:${dims.join('、')}` : ''}`, }, 'zh-Hant': { @@ -175,6 +191,8 @@ const COPY: Readonly> = { fallbackTail: '改用物件查詢工具(query_records、aggregate_records)回答,並在回答中註明未使用治理指標(非指標口徑)。', groupingTail: '只有分組維度還不能回答:問使用者想看哪個數字。', partialTail: '資料集目錄不完整(見 warning):這裡沒有列出的指標仍可能存在,請在回答中轉述該警告。', + leftCandidateTail: '上面有候選的詞,先問使用者指的是哪一個再使用;不要替使用者選。', + leftFallbackTail: '這些詞改用物件查詢工具(query_records、aggregate_records),並在回答中註明它們未使用治理指標(非指標口徑)。', source: (ms, ds, dims) => `指標:${ms.join('、')}(資料集:${ds})${dims.length > 0 ? `;維度:${dims.join('、')}` : ''}`, }, ja: { @@ -194,6 +212,8 @@ const COPY: Readonly> = { fallbackTail: 'オブジェクトのクエリツール(query_records、aggregate_records)で回答し、管理された指標を使っていないことを回答に明記してください。', groupingTail: 'グループ分けだけでは回答になりません:どの数値を知りたいかユーザーに確認してください。', partialTail: 'データセットのカタログは不完全です(warning を参照):ここにない指標が存在する可能性があるため、回答でその警告を伝えてください。', + leftCandidateTail: '候補のある上記の語は、使う前にどれを指しているかユーザーに確認してください。代わりに選ばないでください。', + leftFallbackTail: 'これらの語にはオブジェクトのクエリツール(query_records、aggregate_records)を使い、管理された指標を使っていないことを回答に明記してください。', source: (ms, ds, dims) => `指標:${ms.join('、')}(データセット:${ds})${dims.length > 0 ? `;ディメンション:${dims.join('、')}` : ''}`, }, }; @@ -333,10 +353,23 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe const sentences: string[] = []; switch (decision) { - case 'one_measure': + case 'one_measure': { for (const r of reported) sentences.push(copy.oneHit(r.term, r.measures[0])); sentences.push(copy.oneTail(reported.length)); + // The words this case leaves out are still named (seat ruling B on + // L1-c N1): a word with candidates with those candidates, an unknown + // word with its labelled fallback, a grouping word as the grouping. + const offered = readings.filter((r) => r.decision === 'candidates_only'); + for (const r of offered) sentences.push(copy.candidateHit(r.term, members(r.candidates))); + if (offered.length > 0) sentences.push(copy.leftCandidateTail); + const unknown = readings.filter((r) => r.decision === 'no_measure' && r.dimensions.length === 0); + for (const r of unknown) sentences.push(copy.unknownHit(r.term)); + if (unknown.length > 0) sentences.push(copy.leftFallbackTail); + for (const r of readings) { + if (r.decision === 'no_measure' && r.dimensions.length > 0) sentences.push(copy.groupingHit(r.term, members(r.dimensions))); + } break; + } case 'several_measures': for (const r of reported) sentences.push(copy.severalHit(r.term, members(r.measures))); sentences.push(copy.severalTail); diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 5402e2d168e..04a1393aa1c 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -113,7 +113,8 @@ const LIST_DATASETS_DESCRIPTION = + 'dataset\'s `object`, add one line naming that dataset and its measures. A dimension match alone picks a ' + 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this ' + 'caller may not see. When `terms` were sent the answer carries `nextStep`: the case of this rule your words are ' - + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`. When ' + + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`, which ' + + 'with one_measure also names the words left out and their candidates. When ' + `the words are in different cases it reports the first of ${DATASET_NEXT_STEP_PRECEDENCE.join(', ')}, so a word ` + 'matching only a dimension never outranks a measure match.'; From 50f59442831d701d36875244732d6ccd9f84ace6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:19:12 +0000 Subject: [PATCH 09/11] test(analytics): the left-out unknown word keeps its fallback in all four languages Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../src/__tests__/dataset-tools.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 473c585af06..426e69307c6 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -959,11 +959,15 @@ describe('[#34919] list_datasets nextStep on examples/app-crm — the decision e }); it('one_measure beside an unknown word and a grouping word: the note keeps the unknown word\'s labelled fallback and names the grouping', async () => { - const out = await ask(['商机数', '库存周转', '销售阶段']); - expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] }); - expect(out.nextStep!.note).toContain('"库存周转"'); - expect(out.nextStep!.note).toContain('query_records'); - expect(out.nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)'); + for (const ctx of [ADMIN, { ...ADMIN, locale: 'zh-CN' }, { ...ADMIN, locale: 'zh-TW' }, { ...ADMIN, locale: 'ja-JP' }] as ExecutionContext[]) { + const out = await ask(['商机数', '库存周转', '销售阶段'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] }); + const note = out.nextStep!.note; + expect(note, String(ctx.locale)).toContain('库存周转'); + expect(note, String(ctx.locale)).toContain('query_records'); + expect(note, String(ctx.locale)).toContain('Stage'); + } + expect((await ask(['商机数', '库存周转', '销售阶段'])).nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)'); // The control: alone, the measure word's note sends nobody to the object tools. expect((await ask(['商机数'])).nextStep!.note).not.toContain('query_records'); }); From a95eb068e011c235db2c5d86be490b24cc692259 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:07:56 +0000 Subject: [PATCH 10/11] test(mcp): the degraded stdio list_datasets read with terms carries nextStep main's i18n-throw pin compares the whole answer; with terms sent the unreadable catalogue now also answers nextStep (no_measure, the incomplete-catalogue sentence). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../mcp/src/stdio-data-bridge.dataset-locale.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts index 5a857635285..746735d66a4 100644 --- a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts +++ b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts @@ -242,7 +242,15 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i it.each(CASES)('$read throwing: list_datasets lists nothing, says partial and names the i18n error', async ({ read, message }) => { const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message)); const answer = await bridge.listDatasets!({ terms: TERMS }); - expect(answer).toEqual({ datasets: [], partial: true, warning: expect.stringContaining(message) }); + // [#34919] Terms were sent, so the degraded answer also carries `nextStep`: + // nothing listed reads `no_measure` for every word, and the note says the + // catalogue was incomplete and to repeat the warning. + expect(answer).toEqual({ + datasets: [], + partial: true, + warning: expect.stringContaining(message), + nextStep: { decision: 'no_measure', terms: TERMS, note: expect.stringContaining('warning') }, + }); expect(answer.warning).toMatch(/^The dataset catalogue could not be read: /); }); From 377b2e4c3b364a90495a17e48c07a0607d3d1066 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:20:14 +0000 Subject: [PATCH 11/11] feat(analytics): candidates_only notes name the words they leave out; pin every precedence pair and the ask-first sentence Ruling B, extended to candidates_only by the seat's L2 (S3): the note names each unknown word sent beside the near-miss word with its labelled fallback, and each grouping-only word as that grouping. One helper now writes the left-out tail for both cases. The several_measures beside no_measure pair is pinned (S1), and ruling B's ask-first sentence is pinned in all four languages (S2). Nits: two words that equal one measure are told it is one metric; a mixed no_measure note keeps the grouping word's ask; the changeset says the doors agree only when they carry the same locale. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm --- .../34919-dataset-next-step-executor.md | 6 +- .../src/__tests__/dataset-tools.test.ts | 50 +++++++++++++ .../src/dataset-next-step.ts | 73 +++++++++++++------ .../service-analytics/src/dataset-tools.ts | 3 +- 4 files changed, 104 insertions(+), 28 deletions(-) diff --git a/.changeset/34919-dataset-next-step-executor.md b/.changeset/34919-dataset-next-step-executor.md index 8109b0d8410..c83a95facc7 100644 --- a/.changeset/34919-dataset-next-step-executor.md +++ b/.changeset/34919-dataset-next-step-executor.md @@ -10,12 +10,12 @@ Metadata-protocol: none The dataset tools now fill the two members the spec declares (`DatasetNextStepSchema`, `QueryDatasetOutputSchema.sourceLine`, `@objectstack/spec/ai`). Until now the decision "one match answers, several ask, near ones are offered, none falls back" and the citation line were left for each AI client to work out from `matches`, `candidates` and `provenance`; a model handed a finished sentence copies it, and one that builds it from parts often does not. -- **`nextStep` on `list_datasets`, whenever `terms` were sent.** `decision` is the case of the ADR-0149 D3 rule the words are in, counted in measures: one measure equals the word ⇒ `one_measure`; more than one, in one dataset or several ⇒ `several_measures`; no match but `candidates` ⇒ `candidates_only`; otherwise `no_measure`, which includes a word that equals only a dimension. `terms` names every word sent (once each, in order) that is in the reported case. `note` is that case as a finished sentence: the measure and the names to query for `one_measure`; each member by its label and its dataset's label for `several_measures` and `candidates_only`, with "ask the user, do not pick"; the object query tools for an unknown word, and "ask which number" for a word that is only a grouping. -- **Words a `one_measure` answer leaves out are still named.** Its `note` computes the measure word and then names each other word: one with candidates together with those candidates (label and dataset label) and "ask before using it"; an unknown one with its labelled fallback to the object query tools; a grouping word as that grouping. +- **`nextStep` on `list_datasets`, whenever `terms` were sent.** `decision` is the case of the ADR-0149 D3 rule the words are in, counted in measures: one measure equals the word ⇒ `one_measure`; more than one, in one dataset or several ⇒ `several_measures`; no match but `candidates` ⇒ `candidates_only`; otherwise `no_measure`, which includes a word that equals only a dimension. `terms` names every word sent (once each, in order) that is in the reported case. `note` is that case as a finished sentence: the measure and the names to query for `one_measure`; each member by its label and its dataset's label for `several_measures` and `candidates_only`, with "ask the user, do not pick"; the object query tools for an unknown word, and "ask which number" for a word that is only a grouping (both, when a `no_measure` answer holds one of each). +- **Words a `one_measure` or `candidates_only` answer leaves out are still named.** A `one_measure` `note` gives the measure word's query and then names each other word: one with candidates together with those candidates (label and dataset label) and "ask before using it"; an unknown one with its labelled fallback to the object query tools; a grouping word as that grouping. A `candidates_only` `note` asks about the candidates and names each unknown word with its labelled fallback and each grouping-only word the same way. Two words that equal the same measure are told it is one metric. - **Precedence among mixed cases.** One answer reports one case, the first of `several_measures`, `one_measure`, `candidates_only`, `no_measure`. A word that matches only a dimension never outranks a measure match: `["营收", "销售阶段"]` reports `one_measure` for `营收`. The order is exported as `DATASET_NEXT_STEP_PRECEDENCE` from `@objectstack/service-analytics`, and the tool description and the MCP `initialize` rule name it. - **A partial answer says so.** With `partial: true` the answer still carries `nextStep`, computed from what it lists, and `note` ends by saying the catalogue was incomplete, that a measure missing from it may exist, and to repeat the `warning`. - **`sourceLine` on `query_dataset`.** The answer's `provenance` as one line to cite: each measure's label and the dataset's label, then each dimension's label (`指标:营收(数据集:销售分析);维度:阶段`). `provenance` is unchanged and stays the structured source. The REST dataset door's answer is not changed. - **Only what the caller may see.** Both sentences are composed from the answer being served: a member over a field the caller cannot read, an `internal` member and a dataset the caller may not query never appear in either. -- **Language.** The request's locale, else the workspace default, else English, the ladder every platform-composed sentence follows (`userTextLocalesOf`, read from the caller's execution context). Sentences are written in English, Simplified Chinese, Traditional Chinese and Japanese; another language takes the next rung. The HTTP and stdio MCP doors hand the executor the same context, so one caller reads one sentence on either. +- **Language.** The request's locale, else the workspace default, else English, the ladder every platform-composed sentence follows (`userTextLocalesOf`, read from the caller's execution context). Sentences are written in English, Simplified Chinese, Traditional Chinese and Japanese; another language takes the next rung. The HTTP and stdio MCP doors hand the executor the same execution context, so a caller reads the same sentence on either when both doors carry the same locale (the stdio door has no request locale, so there the workspace default or English decides). `@objectstack/mcp`: the `initialize` selection rule now tells the client to follow `nextStep`'s note, names the precedence, and says to cite `sourceLine`. Both tools pass the two members through unchanged. diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 426e69307c6..0c9bd25ca13 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -897,6 +897,14 @@ const loadCrm = async () => [CRM_OPPORTUNITY_METRICS, CRM_LINE_ITEM_METRICS]; const REP = { userId: 'u_rep', tenantId: 'org_a' } as ExecutionContext; /** The members u_rep may not read (each over `amount`), by every word a sentence could name them with. */ const WITHHELD_WORDS = ['Total Amount', 'total_amount', 'Avg Deal Size', 'avg_amount', 'Line Amount', 'line_amount']; +/** Ruling B's ask-first instruction for a left-out word with candidates, by the locale the context names. */ +const ASK_FIRST: Record = { + en: 'ask the user which one is meant before using it; do not pick one', + 'zh-CN': '先问用户指的是哪一个再使用;不要替用户选', + 'zh-TW': '先問使用者指的是哪一個再使用;不要替使用者選', + 'ja-JP': '使う前にどれを指しているかユーザーに確認してください。代わりに選ばないでください', +}; +const FOUR_LOCALES = [ADMIN, { ...ADMIN, locale: 'zh-CN' }, { ...ADMIN, locale: 'zh-TW' }, { ...ADMIN, locale: 'ja-JP' }] as ExecutionContext[]; type ListOut = Awaited['listDatasets']>>; @@ -954,8 +962,14 @@ describe('[#34919] list_datasets nextStep on examples/app-crm — the decision e expect(note, String(ctx.locale)).toContain('"opp_count"'); expect(note, String(ctx.locale)).toContain('金额'); for (const label of [...CANDIDATES, 'Line Item Metrics']) expect(note, `${ctx.locale} ⇒ ${label}`).toContain(label); + // Ruling B's ask-first sentence, after the candidates it is about. + const ask1st = ASK_FIRST[String(ctx.locale ?? 'en')]; + expect(note, `${ctx.locale} ⇒ ask first`).toContain(ask1st); + expect(note.indexOf(ask1st), String(ctx.locale)).toBeGreaterThan(note.indexOf('Line Item Metrics')); } expect((await ask(['商机数', '金额'])).nextStep!.note).toContain('Total Amount (dataset: Opportunity Metrics)'); + // The control: alone, the measure word's note asks nothing first. + expect((await ask(['商机数'])).nextStep!.note).not.toContain(ASK_FIRST.en); }); it('one_measure beside an unknown word and a grouping word: the note keeps the unknown word\'s labelled fallback and names the grouping', async () => { @@ -972,6 +986,41 @@ describe('[#34919] list_datasets nextStep on examples/app-crm — the decision e expect((await ask(['商机数'])).nextStep!.note).not.toContain('query_records'); }); + it('candidates_only beside an unknown word and a grouping word: the note names both, the unknown one with its labelled fallback (ruling B, seat S3)', async () => { + for (const ctx of FOUR_LOCALES) { + const out = await ask(['库存周转', '金额', '销售阶段'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['金额'] }); + const note = out.nextStep!.note; + for (const label of ['Total Amount', 'Avg Deal Size', 'Line Amount']) expect(note, `${ctx.locale} ⇒ ${label}`).toContain(label); + expect(note, String(ctx.locale)).toContain('库存周转'); + expect(note, String(ctx.locale)).toContain('query_records'); + expect(note, String(ctx.locale)).toContain('Stage'); + } + const two = await ask(['库存周转', '金额']); + expect(two.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['金额'] }); + expect(two.nextStep!.note).toContain('"库存周转" equals no measure and has no possible reading.'); + expect(two.nextStep!.note).toContain('no governed metric was used for them'); + expect((await ask(['金额', '销售阶段'])).nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)'); + // The control: alone, the near-miss word's note sends nobody to the object tools. + expect((await ask(['金额'])).nextStep!.note).not.toContain('query_records'); + }); + + it('two words that equal the same measure are one metric, not "each its own"', async () => { + const out = await ask(['商机数', '商机数量']); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数', '商机数量'] }); + expect(out.nextStep!.note).not.toContain('Each is its own metric'); + expect(out.nextStep!.note).toContain('using that measure'); + // The control: two words with two measures are two metrics. + expect((await ask(['商机数', '商机金额'])).nextStep!.note).toContain('Each is its own metric'); + }); + + it('a mixed no_measure note falls back for the unknown word and still asks which number the grouping word means', async () => { + const out = await ask(['库存周转', '销售阶段']); + expect(out.nextStep).toMatchObject({ decision: 'no_measure', terms: ['库存周转', '销售阶段'] }); + expect(out.nextStep!.note).toContain('query_records'); + expect(out.nextStep!.note).toContain('ask the user which number they mean'); + }); + it('a word with two matches ⇒ several_measures, the note naming each by its label and its dataset\'s label', async () => { const out = await ask(['deal value']); expect(out.nextStep).toMatchObject({ decision: 'several_measures', terms: ['deal value'] }); @@ -1037,6 +1086,7 @@ describe('[#34919] list_datasets nextStep — the precedence among mixed cases', it('several_measures > one_measure > candidates_only > no_measure, naming every word in the reported case', async () => { expect(await decide(['商机数', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] }); expect(await decide(['金额', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] }); + expect(await decide(['deal value', '库存周转'])).toEqual({ decision: 'several_measures', terms: ['deal value'] }); expect(await decide(['金额', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] }); expect(await decide(['库存周转', '金额'])).toEqual({ decision: 'candidates_only', terms: ['金额'] }); expect(await decide(['库存周转', '销售阶段'])).toEqual({ decision: 'no_measure', terms: ['库存周转', '销售阶段'] }); diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index 5ebe676a06b..f428470252f 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -65,14 +65,18 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s * * The terms of an unreported case keep their entries in `matches` and * `candidates`; `decision` and `terms` name only the case that comes first. - * When that case is `one_measure`, `note` still names every word it leaves - * out (seat ruling B on the L1-c N1 finding): a word with candidates - * together with those candidates, each by its label and its dataset's label, - * and the instruction to ask before using it; an unknown word with its - * labelled fallback to the object query tools; a word that equals only a - * dimension as that grouping. `["营收", "churn"]` computes 营收's measure and - * asks about churn's candidates in one sentence. (`several_measures` asks - * before anything is computed, so its note needs no such tail.) + * When that case is `one_measure` or `candidates_only`, `note` still names + * every word it leaves out (seat ruling B on the L1-c N1 finding, extended to + * `candidates_only` by the seat's L2 S3): under `one_measure`, a word with + * candidates together with those candidates, each by its label and its + * dataset's label, and the instruction to ask before using it; under either, + * an unknown word with its labelled fallback to the object query tools and a + * word that equals only a dimension as that grouping. `["营收", "churn"]` + * computes 营收's measure and asks about churn's candidates in one sentence; + * `["库存周转", "金额"]` asks about 金额's candidates and names 库存周转 with + * its fallback. (`several_measures` asks before anything is computed, so its + * note needs no such tail.) Two words that equal the same measure are one + * metric, and the note says so. * * ## An incomplete catalogue * @@ -126,7 +130,7 @@ interface DatasetToolCopy { readonly partialTail: string; /** After a `one_measure` note: the left-out words that have candidates are asked about before use. */ readonly leftCandidateTail: string; - /** After a `one_measure` note: the left-out words with no measure and no reading fall back, labelled. */ + /** After a `one_measure` or `candidates_only` note: the left-out words with no measure and no reading fall back, labelled. */ readonly leftFallbackTail: string; readonly source: (measures: readonly string[], dataset: string, dimensions: readonly string[]) => string; } @@ -322,6 +326,33 @@ function readTerm( return { term, decision, measures, dimensions, candidates: offered }; } +/** + * The sentences naming the words the reported case leaves out (seat ruling B, + * extended to `candidates_only`): under `one_measure` a word with candidates + * with those candidates and the ask-first instruction; under `one_measure` and + * `candidates_only` an unknown word with its labelled fallback, and a word that + * equals only a dimension as that grouping. A `no_measure` word is never the + * reported case here, so every `no_measure` reading is a left-out word. + */ +function leftOutSentences( + decision: DatasetNextStepDecision, + readings: readonly TermReading[], + copy: DatasetToolCopy, + members: (ms: readonly NamedMember[]) => string, +): string[] { + const sentences: string[] = []; + const offered = readings.filter((r) => r.decision === 'candidates_only' && r.decision !== decision); + for (const r of offered) sentences.push(copy.candidateHit(r.term, members(r.candidates))); + if (offered.length > 0) sentences.push(copy.leftCandidateTail); + const unknown = readings.filter((r) => r.decision === 'no_measure' && r.dimensions.length === 0); + for (const r of unknown) sentences.push(copy.unknownHit(r.term)); + if (unknown.length > 0) sentences.push(copy.leftFallbackTail); + for (const r of readings) { + if (r.decision === 'no_measure' && r.dimensions.length > 0) sentences.push(copy.groupingHit(r.term, members(r.dimensions))); + } + return sentences; +} + /** What {@link composeDatasetNextStep} reads: the answer `list_datasets` is about to serve, and the caller's locales. */ export interface DatasetNextStepSource { /** The caller's terms, as sent. */ @@ -355,19 +386,10 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe switch (decision) { case 'one_measure': { for (const r of reported) sentences.push(copy.oneHit(r.term, r.measures[0])); - sentences.push(copy.oneTail(reported.length)); - // The words this case leaves out are still named (seat ruling B on - // L1-c N1): a word with candidates with those candidates, an unknown - // word with its labelled fallback, a grouping word as the grouping. - const offered = readings.filter((r) => r.decision === 'candidates_only'); - for (const r of offered) sentences.push(copy.candidateHit(r.term, members(r.candidates))); - if (offered.length > 0) sentences.push(copy.leftCandidateTail); - const unknown = readings.filter((r) => r.decision === 'no_measure' && r.dimensions.length === 0); - for (const r of unknown) sentences.push(copy.unknownHit(r.term)); - if (unknown.length > 0) sentences.push(copy.leftFallbackTail); - for (const r of readings) { - if (r.decision === 'no_measure' && r.dimensions.length > 0) sentences.push(copy.groupingHit(r.term, members(r.dimensions))); - } + // Two words that equal the same measure are one metric, not two. + const metrics = new Set(reported.map((r) => `${r.measures[0].datasetName}.${r.measures[0].name}`)); + sentences.push(copy.oneTail(metrics.size)); + sentences.push(...leftOutSentences(decision, readings, copy, members)); break; } case 'several_measures': @@ -377,14 +399,17 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe case 'candidates_only': for (const r of reported) sentences.push(copy.candidateHit(r.term, members(r.candidates))); sentences.push(copy.candidateTail); + sentences.push(...leftOutSentences(decision, readings, copy, members)); break; case 'no_measure': { for (const r of reported) { sentences.push(r.dimensions.length > 0 ? copy.groupingHit(r.term, members(r.dimensions)) : copy.unknownHit(r.term)); } // A word for a thing measured that names nothing falls back (D3 rule 4); - // a grouping word alone asks which number is meant (rule 5). - sentences.push(reported.some((r) => r.dimensions.length === 0) ? copy.fallbackTail : copy.groupingTail); + // a grouping word asks which number is meant (rule 5), beside the + // fallback too when the words are mixed. + if (reported.some((r) => r.dimensions.length === 0)) sentences.push(copy.fallbackTail); + if (reported.some((r) => r.dimensions.length > 0)) sentences.push(copy.groupingTail); break; } } diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 04a1393aa1c..17049817834 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -114,7 +114,8 @@ const LIST_DATASETS_DESCRIPTION = + 'grouping, not a number: a measure must still match. `membersWithheld` means some members exist that this ' + 'caller may not see. When `terms` were sent the answer carries `nextStep`: the case of this rule your words are ' + 'in (`decision`), the words it is about (`terms`) and what to do, already written (`note`); follow `note`, which ' - + 'with one_measure also names the words left out and their candidates. When ' + + 'with one_measure also names the words left out and their candidates, and with candidates_only names the ' + + 'unknown and grouping-only words left out. When ' + `the words are in different cases it reports the first of ${DATASET_NEXT_STEP_PRECEDENCE.join(', ')}, so a word ` + 'matching only a dimension never outranks a measure match.';