diff --git a/.changeset/35005-grouping-candidate-no-ask.md b/.changeset/35005-grouping-candidate-no-ask.md new file mode 100644 index 00000000000..76d5d89ab2f --- /dev/null +++ b/.changeset/35005-grouping-candidate-no-ask.md @@ -0,0 +1,15 @@ +--- +'@objectstack/service-analytics': patch +'@objectstack/mcp': patch +--- + +fix(analytics): a grouping or time word with only a near dimension no longer stops a matched measure with a question + +Clause-②: no +Metadata-protocol: none + +A question like 「按行业看销售额」 or "revenue this quarter" sends `list_datasets` a measure word with an exact match (销售额, revenue) and a grouping or time word that matches nothing exactly but is near a dimension (「按行业」 contains 行业, "this quarter" contains `quarter`). The `nextStep` note used to tell the model to ask the user about that word before using it, so an ordinary question got a clarifying question back. Now a word whose candidates are all dimensions is offered as a possible grouping: the note says not to ask about it and that it does not stop the matched measure, which is computed. A word with a measure among its candidates still asks, as before: a bare near-miss measure word (销售 near 销售额) is still `candidates_only` and computes nothing until the user answers, and beside a matched measure it is still asked about. + +What changes is the note only. `decision`, `terms`, `matches` and `candidates` are the same as before for every input: a word with only dimension candidates is still `candidates_only` when it is the reported case, and its candidates are still listed. When such a word is the only word sent, the note offers the grouping and asks which number is meant, as it does for a word that equals a dimension. + +The `list_datasets` tool description and the MCP `initialize` selection rule now state the scoped rule in the same words: "A word whose candidates are all dimensions is at most a possible grouping: never ask about it, and it never stops a matched measure." diff --git a/packages/mcp/src/initialize-selection-rule-34686.test.ts b/packages/mcp/src/initialize-selection-rule-34686.test.ts index eac78046ae5..0bb24c3cc10 100644 --- a/packages/mcp/src/initialize-selection-rule-34686.test.ts +++ b/packages/mcp/src/initialize-selection-rule-34686.test.ts @@ -26,7 +26,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 { DATASET_NEXT_STEP_PRECEDENCE, getDatasetToolDefinitions } 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'; @@ -219,3 +219,28 @@ describe('[#34919] initialize instructions — follow nextStep, cite sourceLine' expect(text).toContain(DATASET_NEXT_STEP_PRECEDENCE.join(', ')); }); }); + +/** + * [#35005] The ask-back is owed only for a word with a measure among its + * candidates; a word whose candidates are all dimensions is at most a possible + * grouping. The rule states it in the same words as `list_datasets`' own + * description (the real one, read from the executor's package), so the two + * doors cannot drift apart. + */ +describe('[#35005] initialize instructions — the ask-back is scoped in the same words as list_datasets', () => { + const SCOPED = + 'A word whose candidates are all dimensions is at most a possible grouping: never ask about it, and it never ' + + 'stops a matched measure.'; + + it('both doors carry the scoped sentence, and the question names a measure among the candidates', async () => { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const text = await instructionsOf(runtime, makeBridge()); + const list = getDatasetToolDefinitions().find((d) => d.name === LIST_DATASETS_TOOL_NAME)!; + expect(text).toContain(SCOPED); + expect(list.description).toContain(SCOPED); + expect(text).toContain('A word with no match and a measure among its candidates in the answer: ask the same way'); + // The unscoped form is gone from both doors. + expect(text).not.toContain('A word with no match but with candidates in the answer'); + expect(list.description).not.toContain('possible readings: ask the same way'); + }); +}); diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index 5a850396411..9296abd6906 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -1811,6 +1811,10 @@ const DEFAULT_HTTP_INSTRUCTIONS = * `list_datasets` `candidates` (the ADR-0149 D3 amendment note): the rule makes * 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; + * [#35005] that question is owed only for a word with a measure among its + * candidates: a word whose candidates are all dimensions is at most a possible + * grouping, never asked about and never a stop for a matched measure, in the + * same words as `list_datasets`' description; * only a word with no match and no candidate falls back to the object tools, * with the answer labelled. [#34919] The answer itself then states the * case (`list_datasets` `nextStep`, composed by the service-analytics @@ -1824,8 +1828,10 @@ const DATASET_SELECTION_RULE = + 'question\'s business words. A word matches only when it equals a measure\'s or dimension\'s name, label or ' + 'synonym, never a similar word. Each word that matches exactly one measure: answer with query_dataset; two ' + 'such words are two metrics, so compute both. One word matching several measures: ask the user which one ' - + '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 ' + + 'they mean; do not pick. A word with no match and a measure among its 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. ' + + 'A word whose candidates are all dimensions is at most a possible grouping: never ask about it, and it never ' + + 'stops a matched measure. No match ' + 'and no candidates: fall back to query_records / aggregate_records and say the answer is not from a governed ' + '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 ' 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 0c9bd25ca13..4d4b4ae03e1 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -61,6 +61,10 @@ const OBJECTS: Record { expect(defs[1].description).toContain('provenance'); }); + it('[#35005] scopes the ask-back to a word with a measure among its candidates', () => { + const [list] = getDatasetToolDefinitions(); + expect(list.description).toContain('A word with a measure among its candidates: ask the same way'); + expect(list.description).toContain( + 'A word whose candidates are all dimensions is at most a possible grouping: never ask about it, and it never ' + + 'stops a matched measure.', + ); + }); + it('[#34919] says follow nextStep and cite sourceLine, and names the precedence the executor applies', () => { const [list, query] = getDatasetToolDefinitions(); expect(list.description).toContain('nextStep'); @@ -1103,6 +1116,140 @@ describe('[#34919] list_datasets nextStep — the precedence among mixed cases', }); }); +/** + * [#35005] An ask-back is owed only for the word being measured. A word whose + * candidates are all dimensions (「按行业」 near 行业, "this quarter" near + * `quarter`) is offered as a possible grouping: no question about it, and no + * stop for a matched measure. A word with a measure among its candidates keeps + * the question. The decision and the answer's `candidates` are unchanged: only + * the sentence is scoped. + */ +describe('[#35005] list_datasets nextStep — a grouping or time word with a candidate does not stop a matched measure', () => { + const SALES_METRICS = { + name: 'sales_metrics', + label: 'Sales Metrics', + object: 'sales_order', + dimensions: [ + { name: 'industry', label: { en: 'Industry', 'zh-CN': '行业' }, field: 'industry', type: 'string' }, + { name: 'quarter', label: { en: 'Quarter', 'zh-CN': '季度' }, field: 'quarter', type: 'string' }, + ], + measures: [ + { name: 'sales_amount', label: { en: 'Revenue', 'zh-CN': '销售额' }, aggregate: 'sum', field: 'amount' }, + { name: 'churn_rate', label: { en: 'Churn Rate', 'zh-CN': '流失率' }, aggregate: 'avg', field: 'churn' }, + ], + }; + /** The sentence that offers a grouping and asks nothing about it, by the locale the context names. */ + const GROUPING_OFFER: Record = { + en: 'A possible grouping is not a question: do not ask the user about it', + 'zh-CN': '可能的分组维度不需要追问:不要就它问用户', + 'zh-TW': '可能的分組維度不需要追問:不要就它問使用者', + 'ja-JP': 'グループ分けの候補は確認の対象ではありません', + }; + /** The reported candidates_only question: compute nothing until the user answers. */ + const ASK_BEFORE_COMPUTING: Record = { + en: 'compute nothing until they answer', + 'zh-CN': '用户回答前不要计算', + 'zh-TW': '使用者回答前不要計算', + 'ja-JP': '回答があるまで計算しないでください', + }; + const loc = (ctx: ExecutionContext) => String(ctx.locale ?? 'en'); + + async function ask(terms: string[], ctx: ExecutionContext = ADMIN) { + const { service } = await bootWired(); + const out = await service.datasetTools({ loadDatasets: async () => [SALES_METRICS] }).listDatasets({ terms }, ctx); + expectNextStepInvariants(out, terms); + return out; + } + + it('「按行业」 + 销售额 ⇒ one_measure, computed with no question back, 行业 offered as a possible grouping', async () => { + for (const ctx of FOUR_LOCALES) { + const out = await ask(['按行业', '销售额'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['销售额'] }); + // The answer's candidates are what they were: the word is still offered its dimension. + expect(out.candidates).toEqual([{ term: '按行业', dataset: 'sales_metrics', member: 'dimensions.industry' }]); + const note = out.nextStep!.note; + expect(note, loc(ctx)).toContain('"sales_amount"'); + expect(note, loc(ctx)).toContain('按行业'); + expect(note, `${loc(ctx)} ⇒ no ask-first`).not.toContain(ASK_FIRST[loc(ctx)]); + expect(note, `${loc(ctx)} ⇒ no ask-before-computing`).not.toContain(ASK_BEFORE_COMPUTING[loc(ctx)]); + expect(note, `${loc(ctx)} ⇒ grouping offered`).toContain(GROUPING_OFFER[loc(ctx)]); + } + const en = (await ask(['按行业', '销售额'])).nextStep!.note; + expect(en).toContain('"按行业" matches no member exactly; it may name a grouping: Industry (dataset: Sales Metrics).'); + expect(en).not.toContain('possible readings'); + }); + + it('"this quarter" + "revenue" ⇒ one_measure, computed with no question back, quarter offered as a possible grouping', async () => { + const out = await ask(['this quarter', 'revenue']); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['revenue'] }); + expect(out.candidates).toEqual([{ term: 'this quarter', dataset: 'sales_metrics', member: 'dimensions.quarter' }]); + const note = out.nextStep!.note; + expect(note).toContain('"this quarter" matches no member exactly; it may name a grouping: Quarter (dataset: Sales Metrics).'); + expect(note).toContain(GROUPING_OFFER.en); + expect(note).not.toContain(ASK_FIRST.en); + // 本季度 contains 季度 the same way. + const zh = await ask(['本季度', '销售额'], { ...ADMIN, locale: 'zh-CN' } as ExecutionContext); + expect(zh.nextStep).toMatchObject({ decision: 'one_measure', terms: ['销售额'] }); + expect(zh.nextStep!.note).toContain(GROUPING_OFFER['zh-CN']); + expect(zh.nextStep!.note).not.toContain(ASK_FIRST['zh-CN']); + }); + + it('a bare near-miss measure word still asks: candidates_only, compute nothing until the user answers', async () => { + for (const ctx of FOUR_LOCALES) { + const out = await ask(['销售'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['销售'] }); + expect(out.candidates).toEqual([{ term: '销售', dataset: 'sales_metrics', member: 'measures.sales_amount' }]); + expect(out.nextStep!.note, loc(ctx)).toContain(ASK_BEFORE_COMPUTING[loc(ctx)]); + expect(out.nextStep!.note, loc(ctx)).not.toContain(GROUPING_OFFER[loc(ctx)]); + } + }); + + it('a matched measure beside a word with a measure candidate still asks about that word (营收 + churn)', async () => { + for (const ctx of FOUR_LOCALES) { + const out = await ask(['revenue', 'churn'], ctx); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['revenue'] }); + expect(out.nextStep!.note, `${loc(ctx)} ⇒ ask first`).toContain(ASK_FIRST[loc(ctx)]); + expect(out.nextStep!.note, loc(ctx)).not.toContain(GROUPING_OFFER[loc(ctx)]); + } + }); + + it('a word with a measure AND a dimension among its candidates keeps the question', async () => { + const out = await ask(['industry revenue', '销售额']); + expect(out.candidates!.map((c) => c.member)).toEqual(['measures.sales_amount', 'dimensions.industry']); + expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['销售额'] }); + expect(out.nextStep!.note).toContain(ASK_FIRST.en); + expect(out.nextStep!.note).not.toContain(GROUPING_OFFER.en); + const alone = await ask(['industry revenue']); + expect(alone.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['industry revenue'] }); + expect(alone.nextStep!.note).toContain(ASK_BEFORE_COMPUTING.en); + }); + + it('both kinds at once: the measure word is asked about and the grouping word is offered', async () => { + const withMeasure = (await ask(['churn', '按行业', '销售额'])).nextStep!; + expect(withMeasure).toMatchObject({ decision: 'one_measure', terms: ['销售额'] }); + expect(withMeasure.note).toContain(ASK_FIRST.en); + expect(withMeasure.note).toContain(GROUPING_OFFER.en); + // The ask-first sentence is about churn's readings and comes before the grouping offer. + expect(withMeasure.note.indexOf(ASK_FIRST.en)).toBeLessThan(withMeasure.note.indexOf('"按行业"')); + const noMeasure = (await ask(['销售', '按行业'])).nextStep!; + expect(noMeasure).toMatchObject({ decision: 'candidates_only', terms: ['销售', '按行业'] }); + expect(noMeasure.note).toContain(ASK_BEFORE_COMPUTING.en); + expect(noMeasure.note).toContain(GROUPING_OFFER.en); + }); + + it('a lone grouping word with a candidate keeps candidates_only and asks which number, never about the grouping', async () => { + for (const ctx of FOUR_LOCALES) { + const out = await ask(['this quarter'], ctx); + // The decision is the spec's: a term with entries in `candidates` is candidates_only. + expect(out.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['this quarter'] }); + const note = out.nextStep!.note; + expect(note, loc(ctx)).toContain(GROUPING_OFFER[loc(ctx)]); + expect(note, loc(ctx)).not.toContain(ASK_BEFORE_COMPUTING[loc(ctx)]); + } + expect((await ask(['this quarter'])).nextStep!.note).toContain('ask the user which number they mean'); + }); +}); + 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(); diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index f428470252f..bfd1844761e 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -46,6 +46,18 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s * * A term sent twice is one term, and a member it equals is counted once. * + * ## Which candidates ask + * + * The decision counts candidates of either kind, as the spec declares + * `candidates_only` ("it matched no member and has entries in `candidates`"). + * The SENTENCE asks back only for a term with a measure among its candidates: + * that is the word being measured, and a possible reading of it is a question + * worth asking. A term whose candidates are all dimensions (「按行业」 near + * 行业, "this quarter" near `quarter`) is at most a possible grouping: the + * sentence offers it as one, never asks about it, and never lets it stop a + * matched measure. What counts as a match does not change (ADR-0149 D3, + * ruling #34691 F1 = B): such a candidate is offered, never selected. + * * ## Precedence among the terms' cases * * One answer carries one `nextStep`, reporting one case, and `terms` names @@ -67,14 +79,19 @@ import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/s * `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; + * `candidates_only` by the seat's L2 S3): under `one_measure`, a word with a + * measure among its candidates together with those candidates, each by its + * label and its dataset's label, and the instruction to ask before using it, + * and a word whose candidates are all dimensions as a possible grouping, asked + * about by nobody; 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 + * measure candidates in one sentence; `["按行业", "销售额"]` computes 销售额's + * measure and offers 行业 as a possible grouping, with no question; * `["库存周转", "金额"]` asks about 金额's candidates and names 库存周转 with - * its fallback. (`several_measures` asks before anything is computed, so its + * its fallback. A reported `candidates_only` word whose candidates are all + * dimensions is offered the same way, and with no measure word beside it the + * note asks which number is meant, as a grouping word does (D3 rule 5). (`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. * @@ -123,12 +140,16 @@ interface DatasetToolCopy { readonly severalTail: string; readonly candidateHit: (term: string, members: string) => string; readonly candidateTail: string; + /** A word with no match whose candidates are all dimensions: offered as a possible grouping. */ + readonly groupingCandidateHit: (term: string, members: string) => string; + /** After the possible groupings: not a question, and no stop for a matched measure. */ + readonly groupingCandidateTail: 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. */ + /** After a `one_measure` note: the left-out words with a measure among their 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; @@ -148,6 +169,8 @@ const COPY: Readonly> = { 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.', + groupingCandidateHit: (t, ms) => `"${t}" matches no member exactly; it may name a grouping: ${ms}.`, + groupingCandidateTail: 'A possible grouping is not a question: do not ask the user about it, and it does not stop a matched measure; group the answer only as the question asks.', 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.', @@ -169,6 +192,8 @@ const COPY: Readonly> = { severalTail: '先问用户指的是哪一个,列出每一个的名称、所属数据集名称和说明;不要替用户选,用户回答前不要计算。', candidateHit: (t, ms) => `「${t}」没有精确匹配任何成员,可能指的是:${ms}。`, candidateTail: '先问用户指的是哪一个,列出每一个的名称、所属数据集名称和说明(只有一个时,问是不是它);不要替用户选,也不要把它当作匹配,用户回答前不要计算。', + groupingCandidateHit: (t, ms) => `「${t}」没有精确匹配任何成员,可能指分组维度:${ms}。`, + groupingCandidateTail: '可能的分组维度不需要追问:不要就它问用户,它也不妨碍计算已匹配的指标;只按问题本身的要求分组。', groupingHit: (t, ms) => `「${t}」是分组维度,不是数字:${ms}。`, unknownHit: (t) => `「${t}」没有匹配任何指标,也没有可能的候选。`, fallbackTail: '改用对象查询工具(query_records、aggregate_records)回答,并在回答中注明未使用治理指标(非指标口径)。', @@ -190,6 +215,8 @@ const COPY: Readonly> = { severalTail: '先問使用者指的是哪一個,列出每一個的名稱、所屬資料集名稱和說明;不要替使用者選,使用者回答前不要計算。', candidateHit: (t, ms) => `「${t}」沒有精確符合任何成員,可能指的是:${ms}。`, candidateTail: '先問使用者指的是哪一個,列出每一個的名稱、所屬資料集名稱和說明(只有一個時,問是不是它);不要替使用者選,也不要把它當作符合,使用者回答前不要計算。', + groupingCandidateHit: (t, ms) => `「${t}」沒有精確符合任何成員,可能指分組維度:${ms}。`, + groupingCandidateTail: '可能的分組維度不需要追問:不要就它問使用者,它也不妨礙計算已符合的指標;只按問題本身的要求分組。', groupingHit: (t, ms) => `「${t}」是分組維度,不是數字:${ms}。`, unknownHit: (t) => `「${t}」沒有符合任何指標,也沒有可能的候選。`, fallbackTail: '改用物件查詢工具(query_records、aggregate_records)回答,並在回答中註明未使用治理指標(非指標口徑)。', @@ -211,6 +238,8 @@ const COPY: Readonly> = { severalTail: 'どれを指しているかユーザーに確認し、それぞれの名前、データセット名、説明を示してください。代わりに選ばず、回答があるまで計算しないでください。', candidateHit: (t, ms) => `「${t}」はどのメンバーにも完全には一致しません。候補:${ms}。`, candidateTail: 'どれを指しているかユーザーに確認し、それぞれの名前、データセット名、説明を示してください(候補が一つなら、それで合っているか確認してください)。代わりに選ばず、候補を一致として扱わず、回答があるまで計算しないでください。', + groupingCandidateHit: (t, ms) => `「${t}」はどのメンバーにも完全には一致しません。グループ分けの候補:${ms}。`, + groupingCandidateTail: 'グループ分けの候補は確認の対象ではありません。ユーザーに確認せず、一致した指標の計算も止めないでください。グループ分けは質問が求めるとおりにしてください。', groupingHit: (t, ms) => `「${t}」は数値ではなくグループ分けです:${ms}。`, unknownHit: (t) => `「${t}」はどの指標にも一致せず、候補もありません。`, fallbackTail: 'オブジェクトのクエリツール(query_records、aggregate_records)で回答し、管理された指標を使っていないことを回答に明記してください。', @@ -271,6 +300,12 @@ interface TermReading { readonly measures: readonly NamedMember[]; readonly dimensions: readonly NamedMember[]; readonly candidates: readonly NamedMember[]; + /** + * A `candidates_only` reading whose candidates are all dimensions: a + * possible grouping, offered and never asked about. `false` for any other + * decision, and for a term with a measure among its candidates. + */ + readonly groupingOnly: boolean; } /** The member a `kind.name` pointer names in `entry`, as the entry lists it, or `undefined`. */ @@ -303,7 +338,7 @@ function readTerm( else if (member?.kind === 'dimensions') dimensions.push(member); } }); - const offered: NamedMember[] = []; + const offered: (NamedMember & { kind: string })[] = []; for (const candidate of candidates) { if (candidate.term !== term) continue; // A candidate points at a member the same answer lists (the shape's invariant). @@ -323,16 +358,34 @@ function readTerm( : offered.length > 0 ? 'candidates_only' : 'no_measure'; - return { term, decision, measures, dimensions, candidates: offered }; + const groupingOnly = decision === 'candidates_only' && offered.every((m) => m.kind === 'dimensions'); + return { term, decision, measures, dimensions, candidates: offered, groupingOnly }; +} + +/** + * The words among `readings` whose candidates are all dimensions, each offered + * as a possible grouping, then the one sentence saying that is no question and + * no stop for a matched measure; nothing when there is none. + */ +function groupingCandidateSentences( + readings: readonly TermReading[], + copy: DatasetToolCopy, + members: (ms: readonly NamedMember[]) => string, +): string[] { + const groupings = readings.filter((r) => r.groupingOnly); + if (groupings.length === 0) return []; + return [...groupings.map((r) => copy.groupingCandidateHit(r.term, members(r.candidates))), copy.groupingCandidateTail]; } /** * 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. + * extended to `candidates_only`): under `one_measure` a word with a measure + * among its candidates with those candidates and the ask-first instruction, + * and a word whose candidates are all dimensions as a possible grouping, never + * asked about; 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, @@ -341,9 +394,11 @@ function leftOutSentences( 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 leftOut = readings.filter((r) => r.decision === 'candidates_only' && r.decision !== decision); + const asked = leftOut.filter((r) => !r.groupingOnly); + for (const r of asked) sentences.push(copy.candidateHit(r.term, members(r.candidates))); + if (asked.length > 0) sentences.push(copy.leftCandidateTail); + sentences.push(...groupingCandidateSentences(leftOut, copy, members)); 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); @@ -396,11 +451,19 @@ export function composeDatasetNextStep(source: DatasetNextStepSource): DatasetNe 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); + case 'candidates_only': { + // A word with a measure among its candidates is asked about; a word + // whose candidates are all dimensions is offered as a grouping, and + // with no such measure word beside it the note asks which number is + // meant, as a grouping word does (D3 rule 5). + const asked = reported.filter((r) => !r.groupingOnly); + for (const r of asked) sentences.push(copy.candidateHit(r.term, members(r.candidates))); + if (asked.length > 0) sentences.push(copy.candidateTail); + sentences.push(...groupingCandidateSentences(reported, copy, members)); + if (asked.length === 0) sentences.push(copy.groupingTail); 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)); diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 17049817834..44de1be177b 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -107,15 +107,17 @@ const LIST_DATASETS_DESCRIPTION = + '`provenance` as its source; two such words are two metrics, so compute both. One word matching several ' + 'measures (in one dataset or two): ask the user which one is meant, listing each candidate\'s label, dataset ' + 'label and description; never pick one. A word that matched nothing may have `candidates`, members offered as ' - + 'possible readings: ask the same way, listing each one\'s label, dataset label and description; never pick one, ' - + 'and never treat a candidate as a match. No match and no candidates: fall back to the object query tools and ' + + 'possible readings. A word with a measure among its candidates: ask the same way, listing each one\'s label, ' + + 'dataset label and description; never pick one, and never treat a candidate as a match. A word whose candidates ' + + 'are all dimensions is at most a possible grouping: never ask about it, and it never stops a matched measure. ' + + 'No match and no candidates: fall back to the object query tools and ' + '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. 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 ' + + 'with one_measure also names the words left out with their candidates or possible groupings, 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.';