diff --git a/.changeset/39152-qualified-phrase-no-second-reading.md b/.changeset/39152-qualified-phrase-no-second-reading.md new file mode 100644 index 00000000000..9f5b512a1a8 --- /dev/null +++ b/.changeset/39152-qualified-phrase-no-second-reading.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-analytics': patch +--- + +fix(analytics): `list_datasets` no longer reads a qualified phrase by its last word + +Clause-②: no +Metadata-protocol: none + +A phrase sent to `list_datasets` in `terms` that is near no member by itself is read a second time, and that second reading now only takes off the words that do not say which number is meant: total words (`total`, `sum`, `overall`, `合计`), short joining words (`of`, `the`, `our`, `so far`) and what follows `by`, `per`, `for`, `to` and similar words. What remains is tested whole. A phrase that keeps another word beside its noun is no longer read by that noun alone, so it has no entry in `candidates`; sent alone or beside a grouping word, the answer's `nextStep.note` sends it to the object tools, and the assistant gives the figure, says no governed metric was used, and asks nothing. + +Asked "how many sales orders are in each status?" or "what is the overdue balance by owner?", an assistant that sends `sales orders` or `overdue balance` used to get `candidates_only` with an order-count measure or two balance measures, and asked the user which measure was meant instead of giving a figure. Neither measure is the number asked for. + +- This corrects the earlier note for the second reading in this release. A phrase is not read by a "head word", its last word that names what is measured: `sales orders` is not read as `orders`, and `booking count` is not read as a count. Both keep both words and are offered nothing. The same holds for `paid claims`, `hotel spend`, `confirmed orders` and `total booking amount`. +- A phrase that carries only total, joining or `by` words beside its noun is read as before: `booking total`, `total booking`, `booking total by status`, `claimed so far` and `成交合计` are offered the same measure, and the assistant asks about it. +- A bare noun is unchanged: `balance` is still offered both balance measures and `orders` the order count, and the assistant asks. To have a phrase such as `sales orders` select a measure, declare it as one of the measure's `synonyms`. +- What remains after the total word is tested whole in every script: `open invoice total` is read as `open invoice`, as `未结发票合计` is read as `未结发票`. +- What counts as a match is unchanged: only equality after normalization. diff --git a/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md b/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md index 0d752a3a480..4c85c819b75 100644 --- a/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md +++ b/docs/adr/0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md @@ -216,6 +216,18 @@ Why the platform computes `matches` instead of leaving the whole rule to the mod > - **What this note narrows, and the sentences read with it.** It narrows the point ruled on #34691, fork F1, option B, as the note of 2026-11-19 left it: "a measure candidate is still asked about and never selected". For a measure this note takes out, the first half no longer holds: it is not asked about. "Never selected" stands for it. Every sentence above that speaks of a measure candidate, or of a term with a measure among its candidates, stands as written and is read with this scope, the measures it counts being the ones this note leaves: the headline of the note of 2026-11-17 ("offered for a question and never selected") and its third point; the headline and the second point of the note of 2026-11-19, and its "A measure candidate, and every candidate of a term with a measure among its candidates, stays as ruled"; and "a word with a measure among its candidates" in the note of 2026-11-24. The note of 2026-11-17 also says that which members are near enough to offer "is the executor's rule": this note adds one exclusion to it, and that exclusion is the record's, not the executor's. > - **State on `main`.** PR [#38848](https://github.com/objectstack-ai/objectstack/pull/38848) changes the record and nothing else. The executor (`packages/services/service-analytics/src/dataset-term-matcher.ts#findDatasetTermCandidates`, `packages/services/service-analytics/src/dataset-next-step.ts#composeDatasetNextStep`), the two texts that carry the rule to a model (`packages/services/service-analytics/src/dataset-tools.ts#LIST_DATASETS_DESCRIPTION`, `packages/mcp/src/mcp-server-runtime.ts#DATASET_SELECTION_RULE`) and the spec's account of what a candidate is offered for (`packages/spec/src/ai/dataset-tools.zod.ts#ListDatasetsOutputSchema`, `packages/spec/src/ai/dataset-tools.zod.ts#DatasetTermCandidateSchema`) follow in the second PR of #38551. A third text restates the rule: step 2 of the published ask skill (`skills/objectstack-ask/SKILL.md`), the text the note of 2026-11-19 brought to the rule. That step follows on a skills card of its own, which was not filed when this note was written. One more fact stands at this head: `nextStep.note` is declared as "composed by the tool from this answer" (`packages/spec/src/ai/dataset-tools.zod.ts#DatasetNextStepSchema`), and the catalogue lists no `field` for a measure (`packages/spec/src/ai/dataset-tools.zod.ts#DatasetToolCatalogMeasureSchema`), so the field that sentence will name is in no entry of the answer. Until the second PR lands, such a measure is still offered and asked about. In [D6](#d6--enforce-or-remove-every-key-names-its-reader-in-its-first-implementation-card)'s terms what is pending is named here and not hidden: the executor's half by its card, the skill's by the file that owes it until its card exists. +> **Amendment note (2026-12-03, [#39152](https://github.com/objectstack-ai/objectstack/issues/39152) — this PR): the second reading of a phrase takes off only the words that do not say which number is meant; a phrase that keeps another word beside its noun is not read a second time by that noun.** +> Ruled by the maintainer on [#39152](https://github.com/objectstack-ai/objectstack/issues/39152), on the question 「定 #39152:清楚的数字题被反问,问数怎么改?」, option text verbatim 「P 两步都做」 (ruling record [`7363768737`](https://github.com/objectstack-ai/objectstack/issues/39152#issuecomment-7363768737)). This note records the first of the two steps. The second, about a measure candidate whose dataset cannot give the grouping the question asks for, owes a note of its own and is not stated here. Which members are near enough to offer stays the executor's rule (the note of 2026-11-17); this note states the principle that rule follows, and changes no shape. +> +> - **The principle.** A candidate is put in a question, and the question is worth asking only when its answer can lead to the governed figure for what was asked. A measure near one word of a phrase, while the phrase says more than that word, is a wider number than the one asked for: neither "Outstanding balance" nor "Open balance" is the overdue balance. So the second reading offers such a phrase nothing. +> - **This note governs the second reading only.** The first reading, containment either way between the whole phrase and a member's own name, label or synonym, is the executor's rule of the note of 2026-11-17 and is unchanged: it is not ruled on here. A measure one of whose own targets is wholly inside the phrase is still offered and asked about: a measure with the synonym "orders" is still offered for "sales orders", and one labelled "Balance" for "overdue balance". Whether the first reading should follow the same principle is not ruled. +> - **What the executor takes off a phrase, and nothing else.** A phrase near no member by itself is read a second time without its total words ("total", "sum", 合计), its joining words ("of", "our", "so far") and what follows "by", "per" and the like. Those words do not say which number is meant. What remains is tested whole, by the same containment, against measures only. "booking total" is read as "booking" and "claimed so far" as "claimed", and each is offered the measure whose synonym or label carries that word. +> - **Any other word stays, and the phrase is tested with it.** A word that says which records ("overdue", "paid", "sales") or what kind of number ("count", "amount") is part of what was asked. "overdue balance", "sales orders", "paid claims" and "hotel spend" lose nothing, so they have no second reading: where the first reading found no member near them, they have no candidate. A spaced phrase is read as an unspaced one already was: 逾期余额 was never read as 余额. +> - **With no candidate, rule 4 governs, as the notes above say.** The figure comes from the records, labelled 「非指标口径」, and nothing is asked. The example of the note of 2026-11-24, `["sales orders", "status"]`, stands beside an "Order count" measure as it stood without one. +> - **A bare noun is still asked about.** "balance" alone is near both balance measures and "orders" alone is near "Order count": each is offered and asked about, never selected (the note of 2026-11-17). A plain record noun is not read as its count measure by inference; an app that wants "sales orders" to select a measure declares it as a `synonym` ([D1](#d1--business-vocabulary-on-measures-and-dimensions-synonyms-and-description)). +> - **What does not change.** What counts as a hit (rule 1), `matches`, the `candidates` shape, its order and its cap, and the four `nextStep.decision` values. The notes of 2026-11-19, 2026-11-24 and 2026-12-01 stand as written, the cases each lists under "Not covered" included. +> - **State on `main`.** The second reading first landed reading a phrase by its last word that is not a total word, in PR [#39017](https://github.com/objectstack-ai/objectstack/pull/39017), with no note here; no release carried that form. This PR brings the executor (`packages/services/service-analytics/src/dataset-term-matcher.ts#readDatasetTerms`) to the principle above and pins the ruled phrases both ways. + ### D4 — Permissions: the tools add no gate and bypass none Measured in [Context](#the-executor-and-its-gate-chain-measured-on-originmain). The binding statements: diff --git a/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts b/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts index 91d35ce9c08..0900ddd2d6f 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-term-matcher.test.ts @@ -174,9 +174,12 @@ describe('findDatasetTermCandidates', () => { /** * [ADR-0149 D3, the amendment note of 2026-11-17: which members are near * enough to offer is the executor's rule] A phrase near no member by itself is - * read a second time, by its head word: the last word before "by", "per"… - * that is not a total word ("total", "sum", 合计…). A member near the head is - * offered as a CANDIDATE for the phrase, never a hit. + * read a second time, without its total words ("total", "sum", 合计…), its + * joining words and what follows "by", "per"…. A measure near what remains is + * offered as a CANDIDATE for the phrase, never a hit. The rule's first form + * read the phrase by its last such word; the note of 2026-12-03, pinned in the + * suite nested at the end of this one, takes off those words only and tests + * what remains whole. * * The case is the order-to-cash scenario build * (`docs/qa/scenarios/builds/order_to_cash.json`, its three datasets copied @@ -191,21 +194,22 @@ describe('findDatasetTermCandidates', () => { * - rule 1 unchanged: the phrase still matches nothing; * - the second reading never adds to the first: a phrase near a member by * itself keeps exactly those members; - * - total and joining words alone offer nothing, and a phrase whose head - * names nothing ("number of payments") still falls back; - * - the head, not any word: a modifier ("billing orders") offers nothing of - * its own, a kind word ("booking count") stays the head, and what follows - * "by" is not the head; + * - total and joining words alone offer nothing, and a phrase that names + * nothing without them ("number of payments") still falls back; + * - only those words are taken off: a phrase with a modifier ("billing + * orders") or a kind word ("booking count") beside its noun is not read by + * either word, and what follows "by" is not read; * - a phrase written without spaces (成交合计) loses its generic end word, and * 金额 / 合同金额 keep the first reading's answer; * - the per-term cap holds for the second reading; - * - the second reading offers measures only: "balance due", whose head is - * near a dimension alone, has no candidate and falls back (rule 4); + * - the second reading offers measures only: "past due total", near a + * dimension alone without its total word, has no candidate and falls back + * (rule 4); * - the 2026-12-01 field take-out still tests the whole term: "hours total" - * is asked about a filtered measure its head found, "hours" is answered - * from the field. + * is asked about a filtered measure the second reading found, "hours" is + * answered from the field. */ -describe('[#38953] a phrase near nothing by itself is read by its head word', () => { +describe('[#38953] a phrase near nothing by itself is read again without its total words', () => { const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; /** The scenario build's datasets, member by member (names, labels, synonyms, fields). */ @@ -314,18 +318,16 @@ describe('[#38953] a phrase near nothing by itself is read by its head word', () expect(offered(['booking'])).toEqual(['booking → order_book.measures.booked_amount']); }); - it('the head word, not any word: the last that is not a total word, before "by"', () => { + it('only total words, joining words and what follows "by" are taken off; any other word stays and is tested', () => { expect(offered(['total booking'])).toEqual(['total booking → order_book.measures.booked_amount']); expect(offered(['booking total by status'])).toEqual(['booking total by status → order_book.measures.booked_amount']); - // A modifier offers nothing of its own: "billing orders" is read as orders. - expect(offered(['billing orders'])).toEqual(['billing orders → order_book.measures.order_count']); - // A word saying what kind of number stays the head: a count, not the booked amount. - // (The measures "count" is inside, as the single word "count" is offered them.) - expect(offered(['booking count'])).toEqual( - offered(['count']).filter((c) => c.includes('.measures.')).map((c) => c.replace(/^count/, 'booking count')), - ); - expect(offered(['booking count'])).toContain('booking count → order_book.measures.order_count'); - expect(offered(['booking count'])).not.toContain('booking count → order_book.measures.booked_amount'); + // [ADR-0149 D3, note of 2026-12-03] A modifier stays: "billing orders" is not read as "orders". + expect(offered(['billing orders'])).toEqual([]); + // A word saying what kind of number stays too: "booking count" is neither "count" nor "booking". + expect(offered(['booking count'])).toEqual([]); + // The controls: each word alone is still offered what it is near. + expect(offered(['orders'])).toEqual(['orders → order_book.measures.order_count']); + expect(offered(['count'])).toContain('count → order_book.measures.order_count'); }); it('the second reading never adds to the first: a phrase near a member by itself keeps exactly those', () => { @@ -337,7 +339,7 @@ describe('[#38953] a phrase near nothing by itself is read by its head word', () ]); }); - it('total and joining words alone offer nothing, and a head that names nothing still falls back', async () => { + it('total and joining words alone offer nothing, and a phrase that names nothing without them still falls back', async () => { expect(offered(['number of payments', 'the total of all', 'total 合计', 'sum by status'])).toEqual([]); const out = await ask(['number of payments']); expect(out.nextStep!.decision).toBe('no_measure'); @@ -371,24 +373,26 @@ describe('[#38953] a phrase near nothing by itself is read by its head word', () ); }); - it('the head reading offers measures only: a head near a dimension alone leaves the phrase with no candidate (rule 4)', async () => { - // "balance due": its head "due" is near only the dimension labelled "Days past due". - const out = await ask(['balance due']); + it('the second reading offers measures only: a phrase near a dimension alone has no candidate (rule 4)', async () => { + // "past due total": without its total word, "past due" is near only the dimension labelled "Days past due". + const out = await ask(['past due total']); expect(out.nextStep!.decision).toBe('no_measure'); - expect(out.nextStep!.terms).toEqual(['balance due']); + expect(out.nextStep!.terms).toEqual(['past due total']); expect(out.candidates).toBeUndefined(); + expect(offered(['past due total'])).toEqual([]); + // "balance due" loses no word, so it is read once, and it is near nothing. expect(offered(['balance due'])).toEqual([]); - // "order total" keeps the measure its head finds and loses only the dimension; its decision stays candidates_only. + // "order total" keeps the measure "order" finds and loses only the dimension; its decision stays candidates_only. expect(offered(['order total'])).toEqual(['order total → order_book.measures.order_count']); expect((await ask(['order total'])).nextStep!.decision).toBe('candidates_only'); // The first reading keeps both kinds: a term near a dimension by itself still offers it. expect(offered(['past due'])).toEqual(['past due → receivables_aging.dimensions.aging_bucket']); }); - it('a phrase whose head names the field a filtered measure aggregates is asked about, the bare word answered from the field', async () => { + it('a phrase that names the field a filtered measure aggregates only without its total word is asked about, the bare word answered from the field', async () => { // [ADR-0149 D3, note of 2026-12-01] "Named by the term" tests the WHOLE term: // "hours" is inside the field's label, "hours total" is not. So the phrase - // keeps the measure its head found and asks about it (before the second + // keeps the measure the second reading found and asks about it (before the second // reading it was no_measure with no candidate), while the bare word is // answered from the field and asks nothing. const billable = { @@ -405,4 +409,120 @@ describe('[#38953] a phrase near nothing by itself is read by its head word', () expect(word.candidates).toBeUndefined(); expect(word.nextStep!.note).toContain('field "hours"'); }); + + /** + * [ADR-0149 D3, amendment note of 2026-12-03; ruling record 7363768737] The + * second reading takes off total words, joining words and what follows + * "by", "per"…, and nothing else. A phrase that keeps another word beside + * its noun ("overdue balance", "sales orders", "paid claims") is tested + * with that word, so it is never read by its noun alone: it has no + * candidate and takes rule 4's labelled fallback. The first form of the + * rule read such a phrase by its last word, and a plain figure question + * ("sales orders by status", "overdue balance by owner") was answered with + * a question about a wider measure. + * + * The phrases are the ruling's, on the two committed scenario builds + * (`docs/qa/scenarios/builds/order_to_cash.json` above, + * `travel_expense.json` copied below member by member), pinned both ways: + * the phrases that lose their candidate, and the ones that keep it. + */ + describe('[#39152] a phrase that keeps another word beside its noun has no second reading', () => { + const CLAIM_LINES = { + name: 'claim_lines', label: 'Claim lines', object: 'demotravel_claim_line', + measures: [{ name: 'line_amount', label: 'Line amount', aggregate: 'sum', field: 'amount', synonyms: ['line total', '明细金额'] }], + dimensions: [ + { name: 'expense_type', label: 'Expense type', field: 'expense_type', synonyms: ['费用类型'] }, + { name: 'department', label: 'Department', field: 'department', synonyms: ['部门'] }, + ], + }; + const REIMBURSEMENT = { + name: 'reimbursement', label: 'Reimbursement', object: 'demotravel_expense_claim', + measures: [ + { name: 'claimed_amount', label: 'Claimed amount', aggregate: 'sum', field: 'total_amount', synonyms: ['expense claims', 'travel spend', '差旅花费', '报销金额'] }, + { name: 'claim_count', label: 'Claim count', aggregate: 'count', synonyms: ['number of claims', '报销单数'] }, + ], + dimensions: [{ name: 'claim_status', label: 'Claim status', field: 'status' }], + }; + const TRIP_PLAN = { + name: 'trip_plan', label: 'Trip plan', object: 'demotravel_trip_request', + measures: [ + { name: 'estimated_spend', label: 'Estimated spend', aggregate: 'sum', field: 'estimated_cost', synonyms: ['estimated cost', 'trip cost', 'travel spend', '差旅花费', '预计费用'] }, + { name: 'trip_days', label: 'Trip days', aggregate: 'sum', field: 'days', synonyms: ['days on the road', '出差天数'] }, + ], + dimensions: [{ name: 'trip_status', label: 'Trip status', field: 'status', synonyms: ['request status'] }], + }; + const TRAVEL = [CLAIM_LINES, REIMBURSEMENT, TRIP_PLAN]; + + it('a qualified phrase or a compound record noun is offered nothing, on both builds', () => { + for (const phrase of [ + 'sales orders', 'confirmed orders', 'overdue balance', 'overdue invoices', 'total booking amount', + // What follows "by" is taken off, the qualifier before it is not. + 'overdue balance by owner', + ]) { + expect(offered([phrase]), phrase).toEqual([]); + } + for (const phrase of ['hotel spend', 'paid claims', 'approved claims', 'hotel spend on paid claims']) { + expect(offered([phrase], TRAVEL), phrase).toEqual([]); + } + }); + + it('the noun alone, and the noun with only total, joining or "by" words, keeps its candidates', () => { + // The bare nouns of the phrases above still ask. + expect(offered(['orders'])).toEqual(['orders → order_book.measures.order_count']); + const balances = ['billing.measures.open_balance', 'receivables_aging.measures.outstanding_balance']; + expect(offered(['balance'])).toEqual(balances.map((m) => `balance → ${m}`)); + expect(offered(['balance by owner'])).toEqual(balances.map((m) => `balance by owner → ${m}`)); + const claims = ['reimbursement.measures.claimed_amount', 'reimbursement.measures.claim_count']; + expect(offered(['claims'], TRAVEL)).toEqual(claims.map((m) => `claims → ${m}`)); + expect(offered(['total claims'], TRAVEL)).toEqual(claims.map((m) => `total claims → ${m}`)); + // The near-miss questions of the two builds keep the measure they ask about. + expect(offered(['booking total'])).toEqual(['booking total → order_book.measures.booked_amount']); + expect(offered(['what is our booking total'])).toEqual(['what is our booking total → order_book.measures.booked_amount']); + expect(offered(['成交合计'])).toEqual(['成交合计 → order_book.measures.booked_amount']); + expect(offered(['order total'])).toEqual(['order total → order_book.measures.order_count']); + expect(offered(['claimed so far'], TRAVEL)).toEqual(['claimed so far → reimbursement.measures.claimed_amount']); + }); + + it('what remains is tested whole, in a spaced script as in an unspaced one', () => { + // An unspaced phrase was never read by its last word: 逾期余额 is not 余额, 销售订单 is not 订单. + expect(offered(['逾期余额', '销售订单'])).toEqual([]); + expect(offered(['住宿费'], TRAVEL)).toEqual([]); + // Both scripts lose the total word and keep the qualifier, which the measure's own words carry. + expect(offered(['未结发票合计'])).toEqual(['未结发票合计 → receivables_aging.measures.open_invoice_count']); + expect(offered(['open invoice total'])).toEqual(['open invoice total → receivables_aging.measures.open_invoice_count']); + // The same qualifier on a noun whose measure does not carry it finds nothing. + expect(offered(['open order total'])).toEqual([]); + }); + + it('at the door: ["sales orders", "status"] beside an Order count measure falls back and asks nothing', async () => { + const out = await ask(['sales orders', 'status']); + // "status" is near a dimension only; "sales orders" has no candidate, so no measure is offered. + expect(out.candidates).toEqual([{ term: 'status', dataset: 'order_book', member: 'dimensions.order_status' }]); + expect(out.nextStep!.decision).toBe('candidates_only'); + expect(out.nextStep!.terms).toEqual(['status']); + for (const entry of out.datasets) expect(entry.matches).toEqual([]); + // The note sends "sales orders" to the object tools and names no measure to ask about. + expect(out.nextStep!.note).toContain('"sales orders"'); + expect(out.nextStep!.note).toContain('aggregate_records'); + expect(out.nextStep!.note).not.toContain('Order count'); + // The control: the bare noun beside the same grouping is still asked about, with the measure named. + const bare = await ask(['orders', 'status']); + expect(bare.candidates).toContainEqual({ term: 'orders', dataset: 'order_book', member: 'measures.order_count' }); + expect(bare.nextStep!.terms).toContain('orders'); + expect(bare.nextStep!.note).toContain('Order count (dataset: Order book)'); + }); + + it('at the door: "overdue balance" is answered from the records, and "balance" still asks between the two measures', async () => { + const phrase = await ask(['overdue balance']); + expect(phrase.nextStep!.decision).toBe('no_measure'); + expect(phrase.nextStep!.terms).toEqual(['overdue balance']); + expect(phrase.candidates).toBeUndefined(); + const word = await ask(['balance']); + expect(word.nextStep!.decision).toBe('candidates_only'); + expect(word.candidates).toEqual([ + { term: 'balance', dataset: 'billing', member: 'measures.open_balance' }, + { term: 'balance', dataset: 'receivables_aging', member: 'measures.outstanding_balance' }, + ]); + }); + }); }); diff --git a/packages/services/service-analytics/src/dataset-next-step.ts b/packages/services/service-analytics/src/dataset-next-step.ts index 93cfac97cc3..9c97b809264 100644 --- a/packages/services/service-analytics/src/dataset-next-step.ts +++ b/packages/services/service-analytics/src/dataset-next-step.ts @@ -127,9 +127,9 @@ import type { DatasetTermNamedField } from './dataset-term-matcher.js'; * * [#34996] The candidate finder offers a member for any word that contains or * is contained in one of its names, and, for a phrase near no member at all, - * a measure near the phrase's head word (`dataset-term-matcher.ts`, - * `phraseHead`), so a word the client cut out of the - * user's phrase ("claims" out of "number of claims") or put in its own words + * a measure near the phrase without its total and joining words + * (`dataset-term-matcher.ts`, `strippedPhrase`), so a word the client cut out + * of the user's phrase ("claims" out of "number of claims") or put in its own words * comes back with a measure among its candidates, and the question the note * then orders is about a word the user never wrote. Whose word it is, only * the client can tell. So before either question about such a word diff --git a/packages/services/service-analytics/src/dataset-term-matcher.ts b/packages/services/service-analytics/src/dataset-term-matcher.ts index 4ac6f7583c0..731a0fdab37 100644 --- a/packages/services/service-analytics/src/dataset-term-matcher.ts +++ b/packages/services/service-analytics/src/dataset-term-matcher.ts @@ -40,9 +40,11 @@ import { normalizeDatasetTerm } from '@objectstack/spec/ui'; * `list_datasets.candidates`): for a term with no hit anywhere, the members * offered for a clarifying question. It never changes what a hit is. Which * members are near enough to offer is the executor's rule (the note of - * 2026-11-17): containment of the term, and, for a term near nothing, of - * its head word, the last word before "by", "per"… that is not a total word - * such as "total" or 合计, put to measures only. + * 2026-11-17): containment of the term, and, for a term near nothing, of the + * same phrase without its total words ("total", 合计), its joining words and + * what follows "by", "per"…, put to measures only. Nothing else is taken off: + * a phrase that keeps another word beside its noun ("overdue balance") is + * never read by that noun alone (the note of 2026-12-03). * * {@link readDatasetTerms} adds the amendment note of 2026-12-01: a filtered * measure candidate whose aggregated field the term NAMES is taken out of the @@ -216,86 +218,94 @@ function isNear(normalizedTerm: string, member: MatchableMember): boolean { } /** - * The words a phrase's head is never: words that say a number is TOTALLED - * ("booking total", "total revenue") and short joining words. On its own, - * "total" is inside the name of every summed member and says nothing about - * which one. Words that say what KIND of number ("amount", "value", "count", - * "number") are not here: "deal value" and "deal count" are different numbers, - * so such a word stays the head when it is the last one. A closed list, so - * the answer is the same in every consumer and a unit test can pin it, - * written in the form the one normalization gives. + * The words the second reading takes off a phrase: words that say a number is + * TOTALLED ("booking total", "total revenue") and short joining words. On its + * own, "total" is inside the name of every summed member and says nothing + * about which one. Words that say what KIND of number ("amount", "value", + * "count", "number") are not here: "deal value" and "deal count" are + * different numbers, so such a word stays in the phrase. Neither is any word + * that says WHICH records ("overdue", "paid", "sales"): it stays too, and the + * phrase is then tested with it. A closed list, so the answer is the same in + * every consumer and a unit test can pin it, written in the form the one + * normalization gives. */ -const NON_HEAD_WORDS: ReadonlySet = new Set([ +const STRIPPED_WORDS: ReadonlySet = new Set([ 'total', 'totals', 'subtotal', 'sum', 'sums', 'overall', 'grand', 'so', 'far', 'of', 'the', 'an', 'and', 'or', 'our', 'my', 'all', 'this', 'that', 'these', 'those', 'is', 'are', 'what', 'how', 'much', 'many', ]); /** - * Words that end a phrase's head: what follows them qualifies the number - * ("booking total by status", "revenue per region", "bookings to date") and - * is not the thing measured. + * Words that end the phrase the second reading keeps: what follows them + * qualifies the number ("booking total by status", "revenue per region", + * "bookings to date") and is not the thing measured. */ -const HEAD_ENDING_WORDS: ReadonlySet = new Set([ +const PHRASE_ENDING_WORDS: ReadonlySet = new Set([ 'by', 'per', 'for', 'in', 'at', 'on', 'from', 'to', 'during', 'over', 'across', 'vs', 'versus', ]); /** - * The same as {@link NON_HEAD_WORDS}, in scripts written without spaces - * between words (Chinese, Japanese): a phrase there is one token, so such a - * word is cut once from the end, or else the start, of the head token, and - * what remains is the head: `成交合计` gives `成交`. 金额 and 数量 say what kind + * The total words of {@link STRIPPED_WORDS}, in scripts written without + * spaces between words (Chinese, Japanese): a phrase there is one token, so + * such a word is cut once from the end of the phrase, or else from its start, + * and what remains is read: `成交合计` gives `成交`. 金额 and 数量 say what kind * of number, as "amount" does, and are not here. */ -const UNSPACED_NON_HEAD_WORDS: readonly string[] = [ +const UNSPACED_TOTAL_WORDS: readonly string[] = [ '合计', '合計', '总计', '總計', '総計', '总额', '總額', '総額', ]; /** - * The head word of a phrase: the last word that names what it measures. The - * phrase is cut at the first {@link HEAD_ENDING_WORDS} word, and its head is - * the last space-separated word before it that is not one of - * {@link NON_HEAD_WORDS}, with an unspaced total word - * ({@link UNSPACED_NON_HEAD_WORDS}) cut off. `undefined` when that word is - * shorter than {@link DATASET_TERM_NEAR_MIN_CODE_POINTS}, or is the whole - * term (which is tested first, by itself). + * [ADR-0149 D3, amendment note of 2026-12-03] The phrase the second reading + * tests: the term cut at the first {@link PHRASE_ENDING_WORDS} word, without + * its {@link STRIPPED_WORDS}, and with one unspaced total word + * ({@link UNSPACED_TOTAL_WORDS}) cut from its end or else its start. + * `undefined` when what remains is shorter than + * {@link DATASET_TERM_NEAR_MIN_CODE_POINTS}, or is the whole term (nothing + * was taken off, and the term was tested first, by itself). * - * The head, and not any word: "sales orders" counts orders, and "sales" alone - * would offer a sales amount for it. The last word, because an English noun - * phrase and a Chinese compound both end in their head; in "booking total" - * that last word is "total", a total word, so the head is "booking". + * Only those words are taken off, and what remains is tested WHOLE, never by + * its last word. "booking total" gives "booking" and "claimed so far" gives + * "claimed". "overdue balance", "sales orders" and "paid claims" lose nothing, + * so they have no second reading: "overdue" says which balance is meant, and + * a measure near "balance" alone is a wider number than the one asked for. + * "overdue balance by owner" gives "overdue balance", which is tested as + * those two words. A spaced phrase is read as an unspaced one already was: + * `逾期余额` was never read as `余额`, and `未结发票合计` gives `未结发票` as + * "open invoice total" gives "open invoice". */ -function phraseHead(normalizedTerm: string): string | undefined { +function strippedPhrase(normalizedTerm: string): string | undefined { const words = normalizedTerm.split(' '); - const cut = words.findIndex((word) => HEAD_ENDING_WORDS.has(word)); - const headPart = (cut === -1 ? words : words.slice(0, cut)) - .filter((word) => !NON_HEAD_WORDS.has(word) && !UNSPACED_NON_HEAD_WORDS.includes(word)); - let head = headPart[headPart.length - 1]; - if (head === undefined) return undefined; - for (const total of UNSPACED_NON_HEAD_WORDS) { - if (head.endsWith(total)) { head = head.slice(0, head.length - total.length); break; } - if (head.startsWith(total)) { head = head.slice(total.length); break; } + const cut = words.findIndex((word) => PHRASE_ENDING_WORDS.has(word)); + const kept = (cut === -1 ? words : words.slice(0, cut)) + .filter((word) => !STRIPPED_WORDS.has(word) && !UNSPACED_TOTAL_WORDS.includes(word)); + if (kept.length === 0) return undefined; + const last = kept.length - 1; + for (const total of UNSPACED_TOTAL_WORDS) { + if (kept[last].endsWith(total)) { kept[last] = kept[last].slice(0, kept[last].length - total.length); break; } + if (kept[0].startsWith(total)) { kept[0] = kept[0].slice(total.length); break; } } - if (codePoints(head) < DATASET_TERM_NEAR_MIN_CODE_POINTS || head === normalizedTerm) return undefined; - return head; + const stripped = kept.filter((word) => word !== '').join(' '); + if (codePoints(stripped) < DATASET_TERM_NEAR_MIN_CODE_POINTS || stripped === normalizedTerm) return undefined; + return stripped; } /** * Whether `member` may be near `term`, the term normalized here: what a * host-side read is narrowed to before {@link readDatasetTerms} runs (a * measure near no term sent is never a candidate, so its field is never - * tested). It answers for the term and for its head word - * ({@link phraseHead}), because which of the two readings a term takes is + * tested). It answers for the term and for its stripped phrase + * ({@link strippedPhrase}), because which of the two readings a term takes is * decided over every member listed, which one member cannot see: a measure - * near the head only is read and may then go unoffered, and no measure that - * is offered goes unread. + * near the stripped phrase only is read and may then go unoffered, and no + * measure that is offered goes unread. */ export function isNearDatasetTerm(term: string, member: MatchableMember): boolean { const normalized = normalizeDatasetTerm(term); if (codePoints(normalized) < DATASET_TERM_NEAR_MIN_CODE_POINTS) return false; if (isNear(normalized, member)) return true; - const head = phraseHead(normalized); - return head !== undefined && isNear(head, member); + const stripped = strippedPhrase(normalized); + return stripped !== undefined && isNear(stripped, member); } /** @@ -331,12 +341,15 @@ export interface DatasetTermReading { * never a hit, and a term with a hit anywhere has no candidate. * - Near is {@link isNear}: containment either way after normalization, both * sides at least two code points. A term near no member of any dataset - * given is read a second time, by its head word ({@link phraseHead}): a - * MEASURE near the head is near the term. The head names the thing - * measured, so the second reading offers no dimension: a head near no - * measure leaves the term with no candidate (rule 4). "booking total" is near no - * target of a `Booked amount` measure; its head "booking" is inside that - * measure's synonym "bookings", so the measure is offered. + * given is read a second time, as its stripped phrase + * ({@link strippedPhrase}): a MEASURE near that phrase is near the term. + * The phrase names the thing measured, so the second reading offers no + * dimension: a phrase near no measure leaves the term with no candidate + * (rule 4). "booking total" is near no target of a `Booked amount` measure; + * without its total word it is "booking", inside that measure's synonym + * "bookings", so the measure is offered. A phrase from which nothing is + * taken off has no second reading: "overdue balance" is not read as + * "balance", has no candidate and is rule 4's (the note of 2026-12-03). * The second reading never adds to the first: a term near any member by * itself keeps exactly those members. * - Order is the listing order, never a ranking: terms as sent (a term sent @@ -376,9 +389,10 @@ export function readDatasetTerms( [...d.dimensions, ...d.measures].some((m) => matchedOn(normalized, m) !== undefined)); if (hit) continue; // The whole near set, in listing order, uncapped: near the term itself, - // or, when the term is near no member at all, the MEASURES near its head - // word. The head names the thing measured, so a dimension near it is no - // reading of the phrase: a head near no measure leaves the term with no + // or, when the term is near no member at all, the MEASURES near its + // stripped phrase. That phrase names the thing measured, so a dimension + // near it is no reading of the term: a stripped phrase near no measure, + // like a term from which nothing is stripped, leaves the term with no // candidate, rule 4's labelled fallback. const nearSet = (test: (member: MatchableMember) => boolean, dimensions: boolean) => { const near: Array<{ candidate: DatasetTermCandidate; field?: AggregatedField; filtered?: boolean }> = []; @@ -401,8 +415,8 @@ export function readDatasetTerms( }; let near = nearSet((member) => isNear(normalized, member), true); if (near.length === 0) { - const head = phraseHead(normalized); - if (head !== undefined) near = nearSet((member) => isNear(head, member), false); + const stripped = strippedPhrase(normalized); + if (stripped !== undefined) near = nearSet((member) => isNear(stripped, member), false); } // The take-out, over the uncapped set: only when every field the term // names, through any measure candidate, filtered or not, is ONE field; and