diff --git a/.changeset/34919-dataset-next-step-executor.md b/.changeset/34919-dataset-next-step-executor.md new file mode 100644 index 00000000000..c83a95facc7 --- /dev/null +++ b/.changeset/34919-dataset-next-step-executor.md @@ -0,0 +1,21 @@ +--- +'@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-②: 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 (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 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/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 ab04b0c1160..d3d5a150c93 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/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: /); }); 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..0c9bd25ca13 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 { 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; @@ -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 }]) { @@ -156,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', () => { @@ -827,3 +857,344 @@ 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', + // `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' }, + ], +}; +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']>>; + +/** + * 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('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); + // 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 () => { + 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'); + }); + + 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'] }); + 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(['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 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: ['商机数'] }); + }); +}); + +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..f428470252f --- /dev/null +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -0,0 +1,437 @@ +// 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`; `decision` and `terms` name only the case that comes first. + * 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 + * + * 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; + /** After a `one_measure` note: the left-out words that have candidates are asked about before use. */ + readonly leftCandidateTail: string; + /** 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; +} + +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.', + 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': { + 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):这里没有列出的指标仍可能存在,请在回答中转述该警告。', + leftCandidateTail: '上面有候选的词,先问用户指的是哪一个再使用;不要替用户选。', + leftFallbackTail: '这些词改用对象查询工具(query_records、aggregate_records),并在回答中注明它们未使用治理指标(非指标口径)。', + 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):這裡沒有列出的指標仍可能存在,請在回答中轉述該警告。', + leftCandidateTail: '上面有候選的詞,先問使用者指的是哪一個再使用;不要替使用者選。', + leftFallbackTail: '這些詞改用物件查詢工具(query_records、aggregate_records),並在回答中註明它們未使用治理指標(非指標口徑)。', + 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 を参照):ここにない指標が存在する可能性があるため、回答でその警告を伝えてください。', + leftCandidateTail: '候補のある上記の語は、使う前にどれを指しているかユーザーに確認してください。代わりに選ばないでください。', + leftFallbackTail: 'これらの語にはオブジェクトのクエリツール(query_records、aggregate_records)を使い、管理された指標を使っていないことを回答に明記してください。', + 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 (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; + 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 }; +} + +/** + * 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. */ + 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 = 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)); + + const sentences: string[] = []; + switch (decision) { + case 'one_measure': { + for (const r of reported) sentences.push(copy.oneHit(r.term, r.measures[0])); + // 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': + 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); + 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 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; + } + } + 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..17049817834 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 { DATASET_NEXT_STEP_PRECEDENCE, 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,12 @@ 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`, which ' + + '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.'; const QUERY_DATASET_DESCRIPTION = 'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business ' @@ -104,7 +125,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 +422,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 +481,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 +588,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 +704,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; 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';