diff --git a/.changeset/34718-dataset-member-vocabulary-advisory.md b/.changeset/34718-dataset-member-vocabulary-advisory.md new file mode 100644 index 00000000000..c92941e3422 --- /dev/null +++ b/.changeset/34718-dataset-member-vocabulary-advisory.md @@ -0,0 +1,22 @@ +--- +'@objectstack/lint': patch +'@objectstack/cli': patch +'@objectstack/skills': patch +--- + +feat(lint): a dataset measure or dimension that declares neither `synonyms` nor a `description` is advised + +Clause-②: yes (widening) — @objectstack/lint gains three exports on its "." entry: validateDatasetMemberVocabulary, DATASET_MEMBER_NO_VOCABULARY and the DatasetMemberVocabularyFinding type; nothing accepted before is refused +Metadata-protocol: none + +A dataset member answers a business question through its vocabulary (ADR-0149 D1): `synonyms`, the words a person types for it, and `description`, a short business definition. Both keys are optional, so a dataset that declares neither on a member passes every check, and that member then answers only to its own name and label. A person who asks in other words, or in another language, matches nothing and gets a number from a plain object query instead of the governed metric. + +`@objectstack/lint` adds one advisory rule, `dataset-member-no-vocabulary` (`warning`). It reports once per measure or dimension that has no non-blank `synonyms` entry and no non-blank `description`, names the dataset and the member, and says what is lost. One of the two keys is enough to silence it. It runs at `os validate`, `os build` and `os lint`, and at the metadata publish door for a `dataset` write, where it is an advisory on the save response. Nothing is refused: a dataset that only feeds charts loses nothing by leaving both keys out. `os explain dataset-member-no-vocabulary` prints the full reasoning. + +The author-time rule count the CLI prints (`Running author-time rules (N)`) rises by one, to 70 for `os validate` and `os build`. + +`@objectstack/lint` exports `validateDatasetMemberVocabulary`, `DATASET_MEMBER_NO_VOCABULARY` and the `DatasetMemberVocabularyFinding` type. + +`@objectstack/cli`: `os generate dataset` now writes one `synonyms` entry on each member it scaffolds, seeded from a label the stack already declares (the title field's label on the dimension, the object's plural label on the record count), in whatever language that label is written in, under a comment that says to replace the seed with the words your users type and to add a `description`. A fresh scaffold therefore draws no finding. When a seed would answer to two members (a title field labelled like the object), the scaffold picks the next candidate, so the dataset it writes always parses. + +`@objectstack/skills`: the `objectstack-ui` dashboards rule now says, for every dataset member, to write `synonyms` as the words a person types, in the language of the brief, and a one-sentence business `description`; that one word names one member; and that a member with neither draws the new warning. Its dataset example gives the dimension a synonym too, and the skill's evals gain a case for a dataset authored from a Chinese brief. diff --git a/content/docs/data-modeling/analytics.mdx b/content/docs/data-modeling/analytics.mdx index cbde749655a..4dacb58c98b 100644 --- a/content/docs/data-modeling/analytics.mdx +++ b/content/docs/data-modeling/analytics.mdx @@ -51,21 +51,42 @@ export const SalesDataset = defineDataset({ filter: { is_deleted: { $ne: true } }, // Groupable axes — a base field, or a `relationship.field` path. + // `synonyms` are the words a person types when asking for this member. dimensions: [ - { name: 'stage', field: 'stage', type: 'string' }, - { name: 'region', field: 'account.region', type: 'string' }, - { name: 'close_date', field: 'close_date', type: 'date', dateGranularity: 'month' }, + { name: 'stage', field: 'stage', type: 'string', synonyms: ['pipeline stage', 'phase'] }, + { name: 'region', field: 'account.region', type: 'string', synonyms: ['territory', 'area'] }, + { + name: 'close_date', field: 'close_date', type: 'date', dateGranularity: 'month', + synonyms: ['close month', 'closing date'], + }, ], // Aggregatable values — defined ONCE here; referenced everywhere by name. measures: [ - { name: 'opp_count', aggregate: 'count' }, - { name: 'revenue', aggregate: 'sum', field: 'amount', format: '$0,0' }, - { name: 'won_amount', aggregate: 'sum', field: 'amount', filter: { stage: 'closed_won' } }, + { name: 'opp_count', aggregate: 'count', synonyms: ['deals', 'opportunities', 'number of deals'] }, + { + name: 'revenue', aggregate: 'sum', field: 'amount', format: '$0,0', + synonyms: ['sales', 'pipeline value'], + description: 'The total amount of every opportunity, open or closed.', + }, + { + name: 'won_amount', aggregate: 'sum', field: 'amount', filter: { stage: 'closed_won' }, + synonyms: ['won revenue', 'bookings'], + description: 'The total amount of the opportunities that closed won.', + }, // Derived measure — references OTHER measures by name only (no raw fields/SQL). - { name: 'win_rate', derived: { op: 'ratio', of: ['won_amount', 'revenue'] }, format: '0.0%' }, + { + name: 'win_rate', derived: { op: 'ratio', of: ['won_amount', 'revenue'] }, format: '0.0%', + synonyms: ['close rate', 'conversion rate'], + description: 'Won amount as a share of the total opportunity amount.', + }, // Duration measure — the time between two datetime fields of each record. - { name: 'avg_days_to_close', aggregate: 'avg', duration: { from: 'created_at', to: 'closed_at', unit: 'days' } }, + { + name: 'avg_days_to_close', aggregate: 'avg', + duration: { from: 'created_at', to: 'closed_at', unit: 'days' }, + synonyms: ['sales cycle', 'time to close'], + description: 'The average number of days from creating an opportunity to closing it.', + }, ], }); ``` @@ -88,6 +109,12 @@ export default defineStack({ be omitted) for a count. A SQL expression there is refused at parse: a conditional count or sum is a measure with its own `filter`, and a ratio is a `derived` measure. +- **Give every member its vocabulary.** `synonyms` are the words a person + types, in their own language (a flat list, matched and never translated; one + word names one member), and `description` is a one-sentence business + definition. A measure or dimension with neither answers only to its own name + and label, so a question asked in a user's own words misses the governed + metric; validation and publish warn with `dataset-member-no-vocabulary`. - **Metric certification** — a `certified` flag that marks a measure as a human-blessed governance checkpoint — is a design goal of ADR-0021 but is **not yet implemented**; `DatasetMeasureSchema` has no `certified` field today. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 5a0c9142933..2b7dbac084b 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -887,7 +887,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (69)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 13932548b6f..8a86391d261 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -857,7 +857,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index e8fe83b2be9..b3cdd1858d9 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (70)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index 8d93028432a..7292d590eb3 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -223,12 +223,19 @@ export const salesDataset = defineDataset({ object: 'opportunity', include: ['account'], dimensions: [ - { name: 'region', field: 'account.region', type: 'string' }, - { name: 'close_month', field: 'close_date', type: 'date', dateGranularity: 'month' }, + { name: 'region', field: 'account.region', type: 'string', synonyms: ['territory', 'area'] }, + { + name: 'close_month', field: 'close_date', type: 'date', dateGranularity: 'month', + synonyms: ['closing month', 'month closed'], + }, ], measures: [ - { name: 'revenue', field: 'amount', aggregate: 'sum' }, - { name: 'deal_count', aggregate: 'count' }, + { + name: 'revenue', field: 'amount', aggregate: 'sum', + synonyms: ['sales', 'pipeline value'], + description: 'The total amount of every opportunity, open or closed.', + }, + { name: 'deal_count', aggregate: 'count', synonyms: ['deals', 'number of deals'] }, ], }); @@ -696,14 +703,23 @@ export const projectTasksDataset = defineDataset({ label: 'Project Tasks', object: 'project_task', dimensions: [ - { name: 'status', field: 'status', type: 'string' }, - { name: 'priority', field: 'priority', type: 'string' }, - { name: 'completed_month', field: 'completed_at', type: 'date', dateGranularity: 'month' }, + { name: 'status', field: 'status', type: 'string', synonyms: ['state', 'progress'] }, + { name: 'priority', field: 'priority', type: 'string', synonyms: ['urgency', 'importance'] }, + { + name: 'completed_month', field: 'completed_at', type: 'date', dateGranularity: 'month', + synonyms: ['month completed', 'finish month'], + }, ], measures: [ - { name: 'open_count', aggregate: 'count', filter: { status: { $ne: 'done' } } }, - { name: 'done_count', aggregate: 'count', filter: { status: 'done' } }, - { name: 'task_count', aggregate: 'count' }, + { + name: 'open_count', aggregate: 'count', filter: { status: { $ne: 'done' } }, + synonyms: ['open tasks', 'unfinished tasks'], + }, + { + name: 'done_count', aggregate: 'count', filter: { status: 'done' }, + synonyms: ['done tasks', 'completed tasks'], + }, + { name: 'task_count', aggregate: 'count', synonyms: ['tasks', 'number of tasks'] }, ], }); ``` diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index c39a14544a4..b52c38b01c8 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/examples/app-showcase/src/ui/datasets/chart-gallery.dataset.ts b/examples/app-showcase/src/ui/datasets/chart-gallery.dataset.ts index b245c4df467..ed0e5cd009a 100644 --- a/examples/app-showcase/src/ui/datasets/chart-gallery.dataset.ts +++ b/examples/app-showcase/src/ui/datasets/chart-gallery.dataset.ts @@ -13,17 +13,34 @@ export const ShowcaseTaskDataset = defineDataset({ name: 'showcase_task_metrics', label: 'Task Metrics', object: 'showcase_task', + // Every member carries `synonyms` (ADR-0149 D1): the words a person types in + // a question, every language in the one list; matched, never translated. dimensions: [ - { name: 'status', label: 'Status', field: 'status', type: 'string' }, - { name: 'priority', label: 'Priority', field: 'priority', type: 'string' }, - { name: 'progress', label: 'Progress', field: 'progress', type: 'number' }, - { name: 'created_at', label: 'Created', field: 'created_at', type: 'date', dateGranularity: 'month' }, + { name: 'status', label: 'Status', field: 'status', type: 'string', synonyms: ['task status', '任务状态'] }, + { name: 'priority', label: 'Priority', field: 'priority', type: 'string', synonyms: ['urgency', '优先级'] }, + { + name: 'progress', label: 'Progress', field: 'progress', type: 'number', + synonyms: ['percent complete', 'completion percentage', '进度'], + }, + { + name: 'created_at', label: 'Created', field: 'created_at', type: 'date', dateGranularity: 'month', + synonyms: ['created date', 'creation month', '创建时间', '创建月份'], + }, ], measures: [ - { name: 'task_count', label: 'Tasks', aggregate: 'count' }, - { name: 'est_hours', label: 'Estimated Hours', aggregate: 'sum', field: 'estimate_hours', format: '0.0' }, - { name: 'avg_estimate', label: 'Avg Estimate', aggregate: 'avg', field: 'estimate_hours', format: '0.0' }, - { name: 'avg_progress', label: 'Avg Progress', aggregate: 'avg', field: 'progress', format: '0.0' }, + { name: 'task_count', label: 'Tasks', aggregate: 'count', synonyms: ['number of tasks', '任务数', '任务数量'] }, + { + name: 'est_hours', label: 'Estimated Hours', aggregate: 'sum', field: 'estimate_hours', format: '0.0', + synonyms: ['planned hours', 'estimated effort', '预估工时'], + }, + { + name: 'avg_estimate', label: 'Avg Estimate', aggregate: 'avg', field: 'estimate_hours', format: '0.0', + synonyms: ['average estimate', 'average estimated hours', '平均预估工时'], + }, + { + name: 'avg_progress', label: 'Avg Progress', aggregate: 'avg', field: 'progress', format: '0.0', + synonyms: ['average progress', 'average completion', '平均进度'], + }, // The done rate, moved here from the `showcase_delivery` cube (#20943): a // cube member's `sql` is a column reference, and this is the declared // form of what its CASE expression computed — a count scoped by its own @@ -31,12 +48,16 @@ export const ShowcaseTaskDataset = defineDataset({ // fraction (the cube's expression multiplied by 100), which the `%` // pattern displays as a percentage; the server annotates the column's // scale from the operator, as it does for `paid_rate`. - { name: 'done_count', label: 'Done Tasks', aggregate: 'count', filter: { status: 'done' } }, + { + name: 'done_count', label: 'Done Tasks', aggregate: 'count', filter: { status: 'done' }, + synonyms: ['completed tasks', 'finished tasks', '已完成任务数'], + }, { name: 'done_rate', label: 'Done Rate', derived: { op: 'ratio', of: ['done_count', 'task_count'] }, format: '0.0%', + synonyms: ['completion rate', 'percent done', '完成率'], }, ], }); @@ -46,15 +67,20 @@ export const ShowcaseProjectDataset = defineDataset({ name: 'showcase_project_metrics', label: 'Project Metrics', object: 'showcase_project', + // Every member carries `synonyms` (ADR-0149 D1): the words a person types in + // a question, every language in the one list; matched, never translated. dimensions: [ - { name: 'account', label: 'Account', field: 'account', type: 'lookup' }, + { name: 'account', label: 'Account', field: 'account', type: 'lookup', synonyms: ['customer', 'client', '客户'] }, // status / health added for the Operations dashboard — power the // "by health" chart and the filtered KPI tiles (active / at-risk). - { name: 'status', label: 'Status', field: 'status', type: 'string' }, - { name: 'health', label: 'Health', field: 'health', type: 'string' }, + { name: 'status', label: 'Status', field: 'status', type: 'string', synonyms: ['project status', '项目状态'] }, + { name: 'health', label: 'Health', field: 'health', type: 'string', synonyms: ['project health', '项目健康度'] }, ], measures: [ - { name: 'project_count', label: 'Projects', aggregate: 'count' }, + { + name: 'project_count', label: 'Projects', aggregate: 'count', + synonyms: ['number of projects', '项目数', '项目数量'], + }, // `budget`/`spent` are currency fields with a FIXED currency // (`currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' }`). // The column's currency resolves through the measure's own `currency` → @@ -65,7 +91,13 @@ export const ShowcaseProjectDataset = defineDataset({ // an amount, with two decimals. The Command Center's `cc_k6` tile, which // aggregates `budget` without this dataset, declares the same pattern and // currency, so both dashboards read one total budget alike. - { name: 'budget_sum', label: 'Total Budget', aggregate: 'sum', field: 'budget', format: '0,0.00' }, - { name: 'spent_sum', label: 'Total Spent', aggregate: 'sum', field: 'spent', format: '0,0.00' }, + { + name: 'budget_sum', label: 'Total Budget', aggregate: 'sum', field: 'budget', format: '0,0.00', + synonyms: ['budget', 'planned budget', '预算', '总预算'], + }, + { + name: 'spent_sum', label: 'Total Spent', aggregate: 'sum', field: 'spent', format: '0,0.00', + synonyms: ['spend', 'actual spend', '支出', '已花费'], + }, ], }); diff --git a/examples/app-showcase/src/ui/datasets/revenue-pulse.dataset.ts b/examples/app-showcase/src/ui/datasets/revenue-pulse.dataset.ts index 9a519699dba..d904c5d3a0a 100644 --- a/examples/app-showcase/src/ui/datasets/revenue-pulse.dataset.ts +++ b/examples/app-showcase/src/ui/datasets/revenue-pulse.dataset.ts @@ -15,31 +15,46 @@ export const ShowcaseInvoiceDataset = defineDataset({ name: 'showcase_invoice_metrics', label: 'Invoice Metrics', object: 'showcase_invoice', + // Every member carries `synonyms` (ADR-0149 D1): the words a person types in + // a question, every language in the one list; matched, never translated. dimensions: [ - { name: 'status', label: 'Status', field: 'status', type: 'string' }, - { name: 'region', label: 'Region', field: 'region', type: 'string' }, - { name: 'issued_on', label: 'Issued', field: 'issued_on', type: 'date', dateGranularity: 'month' }, - { name: 'account', label: 'Account', field: 'account', type: 'lookup' }, + { name: 'status', label: 'Status', field: 'status', type: 'string', synonyms: ['invoice status', '发票状态'] }, + { name: 'region', label: 'Region', field: 'region', type: 'string', synonyms: ['billing region', '区域', '地区'] }, + { + name: 'issued_on', label: 'Issued', field: 'issued_on', type: 'date', dateGranularity: 'month', + synonyms: ['issue date', 'invoice month', '开票日期', '开票月份'], + }, + { name: 'account', label: 'Account', field: 'account', type: 'lookup', synonyms: ['customer', 'client', '客户'] }, ], measures: [ - { name: 'invoice_count', label: 'Invoices', aggregate: 'count' }, + { + name: 'invoice_count', label: 'Invoices', aggregate: 'count', + synonyms: ['number of invoices', '发票数', '发票数量'], + }, // Invoices bill in different currencies (`showcase_invoice.currency_code`), // so a sum of their own amounts (or of the line Subtotal, entered in each // invoice's currency) adds euros to yen. The consolidated figure sums the // HOME-currency amount the engine stored at write: one currency, the // organization's, whatever each invoice was billed in. - { name: 'total_home_sum', label: 'Total incl. Tax (Home Currency)', aggregate: 'sum', field: 'amount_home', format: '0,0' }, + { + name: 'total_home_sum', label: 'Total incl. Tax (Home Currency)', aggregate: 'sum', field: 'amount_home', format: '0,0', + synonyms: ['invoiced amount', 'billed amount', '开票金额', '含税总额'], + }, // A RATE — the percent-scale case (objectui#3136). `paid_rate` is a 0–1 // ratio by construction, and grouping by `status` makes the Paid bucket // exactly 1: the value a magnitude-guessing renderer printed as "1.0%" // instead of "100.0%". The server annotates the column's scale from the // `ratio` operator, so display no longer has to infer it. - { name: 'paid_count', label: 'Paid Invoices', aggregate: 'count', filter: { status: 'paid' } }, + { + name: 'paid_count', label: 'Paid Invoices', aggregate: 'count', filter: { status: 'paid' }, + synonyms: ['invoices paid', 'settled invoices', '已付发票数'], + }, { name: 'paid_rate', label: 'Paid Rate', derived: { op: 'ratio', of: ['paid_count', 'invoice_count'] }, format: '0.0%', + synonyms: ['payment rate', 'share of invoices paid', '付款率'], }, ], }); @@ -49,14 +64,31 @@ export const ShowcaseAccountDataset = defineDataset({ name: 'showcase_account_metrics', label: 'Account Metrics', object: 'showcase_account', + // Every member carries `synonyms` (ADR-0149 D1): the words a person types in + // a question, every language in the one list; matched, never translated. dimensions: [ - { name: 'industry', label: 'Industry', field: 'industry', type: 'string' }, - { name: 'status', label: 'Lifecycle', field: 'status', type: 'string' }, - { name: 'sales_region', label: 'Sales Region', field: 'sales_region', type: 'string' }, - { name: 'signed_on', label: 'Customer Since', field: 'signed_on', type: 'date', dateGranularity: 'month' }, + { name: 'industry', label: 'Industry', field: 'industry', type: 'string', synonyms: ['sector', 'vertical', '行业'] }, + { + name: 'status', label: 'Lifecycle', field: 'status', type: 'string', + synonyms: ['account status', 'lifecycle stage', '客户状态', '生命周期'], + }, + { + name: 'sales_region', label: 'Sales Region', field: 'sales_region', type: 'string', + synonyms: ['territory', 'sales territory', '销售区域'], + }, + { + name: 'signed_on', label: 'Customer Since', field: 'signed_on', type: 'date', dateGranularity: 'month', + synonyms: ['signing date', 'signed date', '签约日期', '签约月份'], + }, ], measures: [ - { name: 'account_count', label: 'Accounts', aggregate: 'count' }, - { name: 'revenue_sum', label: 'Annual Revenue', aggregate: 'sum', field: 'annual_revenue', format: '0,0' }, + { + name: 'account_count', label: 'Accounts', aggregate: 'count', + synonyms: ['number of accounts', 'customer count', '客户数', '客户数量'], + }, + { + name: 'revenue_sum', label: 'Annual Revenue', aggregate: 'sum', field: 'annual_revenue', format: '0,0', + synonyms: ['revenue', 'yearly revenue', '年营收', '年收入'], + }, ], }); diff --git a/examples/app-todo/src/datasets/task.dataset.ts b/examples/app-todo/src/datasets/task.dataset.ts index 7ad6af208ad..e01f2eaedda 100644 --- a/examples/app-todo/src/datasets/task.dataset.ts +++ b/examples/app-todo/src/datasets/task.dataset.ts @@ -22,19 +22,77 @@ export const TaskDataset = defineDataset({ object: 'todo_task', // Groupable axes — referenced by report rows/columns and widget dimensions. + // Each member carries `synonyms` (ADR-0149 D1): the words a person types in + // a question, every language in the one list; they are matched, never + // translated. dimensions: [ - { name: 'status', label: 'Status', field: 'status', type: 'string' }, - { name: 'priority', label: 'Priority', field: 'priority', type: 'string' }, - { name: 'category', label: 'Category', field: 'category', type: 'string' }, - { name: 'owner', label: 'Assigned To', field: 'owner', type: 'lookup' }, - { name: 'due_date', label: 'Due Date', field: 'due_date', type: 'date' }, - { name: 'completed_date', label: 'Completed Date', field: 'completed_date', type: 'date' }, + { + name: 'status', + label: 'Status', + field: 'status', + type: 'string', + synonyms: ['task status', 'task state', '任务状态', '状态'], + }, + { + name: 'priority', + label: 'Priority', + field: 'priority', + type: 'string', + synonyms: ['urgency', 'importance', '优先级', '紧急程度'], + }, + { + name: 'category', + label: 'Category', + field: 'category', + type: 'string', + synonyms: ['task type', 'kind of task', '分类', '任务类别'], + }, + { + name: 'owner', + label: 'Assigned To', + field: 'owner', + type: 'lookup', + synonyms: ['assignee', 'responsible person', '负责人', '指派给'], + }, + { + name: 'due_date', + label: 'Due Date', + field: 'due_date', + type: 'date', + synonyms: ['deadline', 'due day', '截止日期', '到期日'], + }, + { + name: 'completed_date', + label: 'Completed Date', + field: 'completed_date', + type: 'date', + synonyms: ['completion date', 'finished date', '完成日期', '完成时间'], + }, ], // Aggregatable values — defined ONCE here; every presentation references by name. measures: [ - { name: 'task_count', label: 'Tasks', aggregate: 'count' }, - { name: 'est_hours', label: 'Estimated Hours', aggregate: 'sum', field: 'estimated_hours', format: '0.0' }, - { name: 'actual_hours', label: 'Actual Hours', aggregate: 'sum', field: 'actual_hours', format: '0.0' }, + { + name: 'task_count', + label: 'Tasks', + aggregate: 'count', + synonyms: ['number of tasks', 'task total', '任务数', '任务数量'], + }, + { + name: 'est_hours', + label: 'Estimated Hours', + aggregate: 'sum', + field: 'estimated_hours', + format: '0.0', + synonyms: ['planned hours', 'estimated effort', '预估工时', '预计工时'], + }, + { + name: 'actual_hours', + label: 'Actual Hours', + aggregate: 'sum', + field: 'actual_hours', + format: '0.0', + synonyms: ['hours spent', 'time spent', '实际工时', '已用工时'], + }, ], }); diff --git a/packages/cli/src/commands/generate-permission-dataset.pin.test.ts b/packages/cli/src/commands/generate-permission-dataset.pin.test.ts index 4ef1e8a5e6f..1546e48fbda 100644 --- a/packages/cli/src/commands/generate-permission-dataset.pin.test.ts +++ b/packages/cli/src/commands/generate-permission-dataset.pin.test.ts @@ -132,8 +132,46 @@ describe('the dataset scaffold is a dataset over the bound object', () => { it('declares a record count, grouped by the record\'s title field', async () => { const dataset = await loadScaffold('dataset', TARGET); - expect(dataset.measures).toEqual([{ name: 'record_count', label: 'Records', aggregate: 'count' }]); - expect(dataset.dimensions).toEqual([{ name: TARGET.displayField, field: TARGET.displayField }]); + // Each member carries one synonym seeded from a label the stack holds (the + // object's label on the count; the title-cased field name where the binding + // carries no field label), so the scaffold draws no + // `dataset-member-no-vocabulary` advisory. + expect(dataset.measures).toEqual([ + { name: 'record_count', label: 'Records', aggregate: 'count', synonyms: ['Account'] }, + ]); + expect(dataset.dimensions).toEqual([ + { name: TARGET.displayField, field: TARGET.displayField, synonyms: ['Name'] }, + ]); + }); + + it('seeds the synonyms from the labels as written, in whatever language they are in', async () => { + const dataset = await loadScaffold('dataset', { + name: 'pin_invoice', + label: '发票', + pluralLabel: '发票', + fields: ['invoice_no', 'amount'], + displayField: 'invoice_no', + displayFieldLabel: '发票号', + }); + expect(DatasetSchema.safeParse(dataset).success).toBe(true); + expect((dataset.measures as Array<{ synonyms?: string[] }>)[0].synonyms).toEqual(['发票']); + expect((dataset.dimensions as Array<{ synonyms?: string[] }>)[0].synonyms).toEqual(['发票号']); + }); + + it.each<[string, ScaffoldObjectBinding, string, string]>([ + // The title field is labelled like the object: one word may name one member. + ['a field labelled like the object', { name: 'pin_tag', label: 'Tag', fields: ['name'], displayField: 'name', displayFieldLabel: 'Tag' }, 'Tag', 'Records'], + // The title field is labelled like the count's own label. + ['a field labelled "Records"', { name: 'pin_log', label: 'Log', fields: ['title'], displayField: 'title', displayFieldLabel: 'Records' }, 'Title', 'Log'], + // The title field is NAMED like the count's label, and its label is too. + ['a field named `records`', { name: 'pin_batch', label: 'Batch', fields: ['records'], displayField: 'records' }, 'Batch Records', 'Batch'], + // A label the schema would refuse as a synonym (over 60 characters) is passed over. + ['an over-long field label', { name: 'pin_note', label: 'Note', fields: ['name'], displayField: 'name', displayFieldLabel: 'x'.repeat(61) }, 'Name', 'Note'], + ])('%s still gets a dataset that parses, one word per member', async (_case, object, dimension, measure) => { + const dataset = await loadScaffold('dataset', object); + expect(DatasetSchema.safeParse(dataset).error?.issues ?? []).toEqual([]); + expect((dataset.dimensions as Array<{ synonyms?: string[] }>)[0].synonyms).toEqual([dimension]); + expect((dataset.measures as Array<{ synonyms?: string[] }>)[0].synonyms).toEqual([measure]); }); it('an object with no title field gets no dimension, and the dataset still parses', async () => { diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index b16e397ad58..cc07b8ecde4 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -57,6 +57,7 @@ import { validateObjectNamespacePrefix } from '@objectstack/spec/kernel'; // derivation the stack schema's own plural keys follow. Imported, not a second // table: `os init` wires, and `os g` looks up, exactly this key. import { singularToPlural } from '@objectstack/spec/shared'; +import { normalizeDatasetTerm } from '@objectstack/spec/ui'; import { printHeader, printSuccess, printError, printInfo, printStep, printWarning, createTimer, isReportedError, CLI_ALIAS } from '../utils/format.js'; import { metadataFileName } from '../utils/metadata-file-name.js'; import { namespacedItemName, readProjectNamespace, type ProjectNamespace } from '../utils/project-namespace.js'; @@ -99,6 +100,8 @@ export interface ScaffoldObjectBinding { fields: readonly string[]; /** The record's title field (`resolveDisplayField`), when it is a declared field. */ displayField?: string; + /** That field's `label`, when the stack declares one as a plain string. */ + displayFieldLabel?: string; } /** What a binding scaffold is rendered against: each reference it writes, resolved. */ @@ -983,6 +986,13 @@ export default ${toCamelCase(name)}PermissionSet; * the record's title field when the object has one, so a widget has a * dimension and a measure to bind from the first build. * + * Each member carries `synonyms` (ADR-0149 D1), the words a question is + * matched against, seeded from the labels the stack already declares + * ({@link datasetScaffoldSynonyms}): a member with neither `synonyms` nor + * a `description` draws `dataset-member-no-vocabulary`, and a scaffold + * adds no finding. The seed is a starting point, in whatever language the + * labels are written in, and the comment above it says to replace it. + * * Declared through `defineDataset`, which types the literal as a * `Dataset`: a bare object literal handed to the stack's `datasets` key * widens `aggregate` to `string` and fails the type check without @@ -993,8 +1003,9 @@ export default ${toCamelCase(name)}PermissionSet; itemName: (name: string, namespace?: string) => itemNameFor(toSnakeCase(name), namespace), generate: (name: string, namespace?: string, bindings?: ScaffoldBindings) => { const object = requireBinding('dataset', bindings, 'object'); - const dimension = object.displayField - ? `\n { name: ${tsString(object.displayField)}, field: ${tsString(object.displayField)} },\n ` + const seeded = datasetScaffoldSynonyms(object); + const dimension = object.displayField && seeded.dimension !== undefined + ? `\n { name: ${tsString(object.displayField)}, field: ${tsString(object.displayField)}, synonyms: [${tsString(seeded.dimension)}] },\n ` : ''; return `import { defineDataset } from '@objectstack/spec/ui'; @@ -1010,6 +1021,11 @@ const ${toCamelCase(name)}Dataset = defineDataset({ label: '${toTitleCase(name)}', object: ${tsString(object.name)}, + // \`synonyms\` are the words people type for a member when they ask a + // question; a question that uses other words does not find it. The ones + // below are seeded from your labels: replace them with the words your users + // type, in their language, and add a one-sentence \`description\`. + // The axes a widget groups by: a field on the object, or a path through a // lookup (\`account.region\`). Declare the fields people group by. dimensions: [${dimension}], @@ -1017,7 +1033,7 @@ const ${toCamelCase(name)}Dataset = defineDataset({ // The values a widget shows. Also: sum, avg, min and max over a numeric // field (\`{ name: 'total', aggregate: 'sum', field: 'amount' }\`). measures: [ - { name: 'record_count', label: 'Records', aggregate: 'count' }, + { name: 'record_count', label: 'Records', aggregate: 'count', synonyms: [${tsString(seeded.measure)}] }, ], }); @@ -1287,11 +1303,62 @@ function tsString(value: string): string { return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\r/g, '\\r').replace(/\n/g, '\\n')}'`; } +/** The title field's `label`, when the stack declares one as a plain string. */ +function displayFieldLabelOf(item: Record, field: string): { displayFieldLabel?: string } { + const declared = (item.fields as Record)[field]; + const label = declared && typeof declared === 'object' ? (declared as { label?: unknown }).label : undefined; + return typeof label === 'string' && label ? { displayFieldLabel: label } : {}; +} + /** The words a scaffold labels a bound object's records with. */ function objectPluralLabel(object: ScaffoldObjectBinding): string { return object.pluralLabel ?? object.label ?? toTitleCase(object.name); } +/** The name and label of the one measure the `dataset` scaffold declares. */ +const DATASET_SCAFFOLD_MEASURE = { name: 'record_count', label: 'Records' } as const; + +/** A word the dataset schema takes as a synonym: trimmed, one line, at most 60 characters. */ +function isDatasetSynonym(word: string): boolean { + return word.length <= 60 && /^\S(?:.*\S)?$/u.test(word); +} + +/** + * The one synonym the `dataset` scaffold seeds on each member (ADR-0149 D1), + * from the labels the stack already declares: the title field's label on the + * dimension, the object's plural label on the record count. A label is in the + * language the author wrote it in, so the seed is too. + * + * Within a dataset one word names one member: the schema refuses a synonym + * that equals another member's name, label or synonym once case, width, + * spacing, `_` and `-` are folded (`normalizeDatasetTerm`). So each seed is + * the first of its candidates that is a valid synonym and answers to no other + * member: a title field labelled like the object, or named `records`, falls + * to the next candidate rather than writing a dataset that does not parse. + * A word equal to its own member's name or label is accepted by the schema. + */ +function datasetScaffoldSynonyms(object: ScaffoldObjectBinding): { dimension?: string; measure: string } { + const pick = (candidates: readonly string[], taken: readonly string[]): string | undefined => { + const folded = new Set(taken.map(normalizeDatasetTerm)); + return candidates.find((word) => isDatasetSynonym(word) && !folded.has(normalizeDatasetTerm(word))); + }; + const objectLabel = object.label ?? toTitleCase(object.name); + const field = object.displayField; + const fieldTitle = field === undefined ? undefined : toTitleCase(field); + const dimension = field === undefined || fieldTitle === undefined + ? undefined + : pick( + [...(object.displayFieldLabel ? [object.displayFieldLabel] : []), fieldTitle, `${objectLabel} ${fieldTitle}`], + [DATASET_SCAFFOLD_MEASURE.name, DATASET_SCAFFOLD_MEASURE.label], + ); + const plural = objectPluralLabel(object); + const measure = pick( + [plural, DATASET_SCAFFOLD_MEASURE.label, `${plural} ${DATASET_SCAFFOLD_MEASURE.label}`], + [...(field === undefined ? [] : [field]), ...(dimension === undefined ? [] : [dimension])], + ) ?? DATASET_SCAFFOLD_MEASURE.label; + return { ...(dimension === undefined ? {} : { dimension }), measure }; +} + /** * The navigation entry that lists the `dashboard` scaffold named `name` * (#32153): one line, the shape an app's `navigation` array takes it in. @@ -1407,6 +1474,7 @@ export function stackBindingCandidates(config: unknown): { ...(typeof item.pluralLabel === 'string' && item.pluralLabel ? { pluralLabel: item.pluralLabel } : {}), fields: declared, ...(title && declared.includes(title) ? { displayField: title } : {}), + ...(title && declared.includes(title) ? displayFieldLabelOf(item, title) : {}), }); } const flows = entries('flows').map(named).filter((name): name is string => !!name); diff --git a/packages/cli/test/generate-binds-from-stack.test.ts b/packages/cli/test/generate-binds-from-stack.test.ts index 0e531794c3c..f1f87cb0068 100644 --- a/packages/cli/test/generate-binds-from-stack.test.ts +++ b/packages/cli/test/generate-binds-from-stack.test.ts @@ -150,6 +150,7 @@ describe('[#21325] the object comes from --object or the stack, never the item n pluralLabel: 'Things', fields: ['title', 'body'], displayField: 'title', + displayFieldLabel: 'Title', }); }); }); diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 55665132f78..02bc371ad93 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -104,6 +104,7 @@ import { validateManagedApiMethods } from './validate-managed-api-methods.js'; import { validateViewContainers } from './validate-view-containers.js'; import { validateWidgetBindings } from './validate-widget-bindings.js'; import { validateDatasetMeasureAggregates } from './validate-dataset-measure-aggregates.js'; +import { validateDatasetMemberVocabulary } from './validate-dataset-member-vocabulary.js'; import { validateDashboardActionRefs } from './validate-dashboard-action-refs.js'; import { validateDashboardWidgetOptions } from './validate-dashboard-widget-options.js'; import { validateFilterTokens } from './validate-filter-tokens.js'; @@ -1075,6 +1076,32 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['dataset'], run: (stack) => validateDatasetMeasureAggregates(stack), }, + // ADR-0149 D1 — a dataset measure or dimension with neither `synonyms` nor a + // `description` answers only to its own name and label, so a question asked + // in a user's own words (or in another language) matches nothing and is + // answered by an ungoverned object query. Advisory: the dataset is valid and + // draws every widget bound to it, and one that only feeds charts loses + // nothing. `parsed`, like the two dataset rules above, because the three read + // the same positions (`datasets[].dimensions[]` / `.measures[]`) and must be + // handed one document; `os lint` judges it on its unparsed stack, which the + // rule tolerates (it reads two optional keys and nothing a default fills). + // + // On the runtime publish door for the type that carries the declaration, + // `dataset`, and nothing else: another type's write would only re-judge a + // STORED dataset, which the differential cancels as a pre-existing + // condition. The rule reads the written dataset's own members and no other + // collection, so the per-write snapshot cannot invent a finding. One finding + // per member that lacks both keys, on the save response, never a refusal. + { + name: 'validateDatasetMemberVocabulary', + tier: 'advisory', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-dataset-member-vocabulary.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['dataset'], + run: (stack) => validateDatasetMemberVocabulary(stack), + }, // ADR-0049 / #3367 — a dashboard header action naming a dead target ships a // button that renders and refuses (or does nothing) on click: a `script` // target must name a defined action, a `modal` target must name a declared diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 31672a7c7f6..321b63564a7 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -73,6 +73,16 @@ export { } from './validate-dataset-measure-aggregates.js'; export type { DatasetMeasureAggregateFinding, GroupKeyClass } from './validate-dataset-measure-aggregates.js'; +// ADR-0149 D1 — a dataset measure or dimension that declares neither +// `synonyms` nor a `description` is advised: a question asked in a user's own +// words will not find it. The rule id is published for `--json` consumers +// (`rule-id-barrel-exports.test.ts`). +export { + validateDatasetMemberVocabulary, + DATASET_MEMBER_NO_VOCABULARY, +} from './validate-dataset-member-vocabulary.js'; +export type { DatasetMemberVocabularyFinding } from './validate-dataset-member-vocabulary.js'; + export { validateStackExpressions, fieldRuleRootIssue, FIELD_RULE_BOUND_ROOTS } from './validate-expressions.js'; export type { ExprIssue } from './validate-expressions.js'; // [#32872] The gate's verdict on one validation rule, formula field or diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index c26e696a936..0933e046f98 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -700,6 +700,37 @@ const DATASET_FILTER_FIELD_UNKNOWN_EXPLANATION: RuleExplanation = { // ── Security posture (`validate-security-posture.ts`) ────────────────────── +const DATASET_MEMBER_NO_VOCABULARY_EXPLANATION: RuleExplanation = { + rule: 'dataset-member-no-vocabulary', + covers: 'what a member with no synonyms and no description loses', + paragraphs: [ + 'A dataset member (a measure or a dimension) carries its business vocabulary in two optional keys: ' + + '`synonyms`, the words a person types for it in a question, and `description`, one or two sentences ' + + 'saying what it is in business terms. When an assistant is asked a business question it matches the ' + + 'words of the question against each member\'s `name`, `label` and `synonyms`, and reads the ' + + '`description` to choose between members and to explain the number it returns.', + 'A member that declares neither answers only to its own name and label. A person who asks for ' + + '"revenue" where the measure is labelled "Total Amount", or who asks in another language, matches ' + + 'nothing, and the assistant falls back to a plain object query: a number no dataset governs, for a ' + + 'metric this dataset does govern. Every check stays green and every dashboard still draws, so nothing ' + + 'else reports the loss.', + 'Reported once per member that has neither key. A `synonyms` list with at least one non-blank word, or a ' + + 'non-blank `description` (a string, or an inline locale map with one non-blank value), is enough to ' + + 'silence it; writing both is the complete form.', + 'To fix it, write the words a person types, in the language your users ask in. Synonyms are matched and ' + + 'never translated, so every language goes in the one list (`synonyms: [\'revenue\', \'sales\', \'营收\']`), ' + + 'and a list is not keyed by locale. Write the `description` as a plain business definition, what the ' + + 'number counts and what it leaves out, never as an instruction to a model; it is display text and is ' + + 'translated like `label`.', + 'One word names one member: within a dataset a synonym may not equal another member\'s name, label or ' + + 'synonym, compared with case, width, spacing, `_` and `-` folded, and the dataset schema refuses one ' + + 'that does. Give the shared word to the member people most often mean by it.', + 'The rule is advisory and stays a warning, at `os validate`, `os build`, `os lint` and on the save ' + + 'response of the metadata publish door. A dataset that only feeds charts, and that nobody asks ' + + 'questions of, loses nothing by leaving both keys out.', + ], +}; + const SECURITY_CBP_AMBIGUOUS_RELATION_EXPLANATION: RuleExplanation = { rule: 'security-controlled-by-parent-ambiguous-relation', covers: 'why a controlled_by_parent object takes exactly one master', @@ -6237,6 +6268,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [DATASET_FIELD_UNKNOWN_EXPLANATION.rule]: DATASET_FIELD_UNKNOWN_EXPLANATION, [DATASET_FIELD_NOT_INCLUDED_EXPLANATION.rule]: DATASET_FIELD_NOT_INCLUDED_EXPLANATION, [DATASET_FILTER_FIELD_UNKNOWN_EXPLANATION.rule]: DATASET_FILTER_FIELD_UNKNOWN_EXPLANATION, + [DATASET_MEMBER_NO_VOCABULARY_EXPLANATION.rule]: DATASET_MEMBER_NO_VOCABULARY_EXPLANATION, [SECURITY_CBP_AMBIGUOUS_RELATION_EXPLANATION.rule]: SECURITY_CBP_AMBIGUOUS_RELATION_EXPLANATION, [SECURITY_CBP_NO_RELATION_EXPLANATION.rule]: SECURITY_CBP_NO_RELATION_EXPLANATION, [SECURITY_CBP_OWNER_POLICY_WITHOUT_OPT_IN_EXPLANATION.rule]: SECURITY_CBP_OWNER_POLICY_WITHOUT_OPT_IN_EXPLANATION, diff --git a/packages/lint/src/runtime-gate.dataset-writes.test.ts b/packages/lint/src/runtime-gate.dataset-writes.test.ts index 4c064e47ec0..bddace2f4a1 100644 --- a/packages/lint/src/runtime-gate.dataset-writes.test.ts +++ b/packages/lint/src/runtime-gate.dataset-writes.test.ts @@ -135,6 +135,7 @@ describe('the dataset write door is wired at all (#19143)', () => { // precisely the drift this pin exists to catch. expect(runtimeAuthoringRulesFor('dataset').map((r) => r.name)).toEqual([ 'validateDatasetMeasureAggregates', + 'validateDatasetMemberVocabulary', 'validateReferenceIntegrity', ]); }); @@ -160,6 +161,7 @@ describe('the dataset write door is wired at all (#19143)', () => { const clean = gateDataset(cleanDataset()); expect(clean.rulesRun).toEqual([ 'validateDatasetMeasureAggregates', + 'validateDatasetMemberVocabulary', 'validateReferenceIntegrity', ]); expect(clean.errors).toEqual([]); @@ -464,15 +466,23 @@ describe('the shipped dataset corpus stays publishable (#19143)', () => { const item = { name: 'opportunity_metrics', object: 'crm_opportunity', + // Each member with the `synonyms` the shipped dataset declares (ADR-0149 + // D1), so the advisory for a member with no vocabulary stays silent on it. dimensions: [ - { name: 'stage', field: 'stage', type: 'string' }, - { name: 'account', field: 'account', type: 'lookup' }, - { name: 'close_date', field: 'close_date', type: 'date', dateGranularity: 'month' }, + { name: 'stage', field: 'stage', type: 'string', synonyms: ['sales stage', 'deal stage', '销售阶段'] }, + { name: 'account', field: 'account', type: 'lookup', synonyms: ['customer', 'client', '客户'] }, + { + name: 'close_date', + field: 'close_date', + type: 'date', + dateGranularity: 'month', + synonyms: ['closing month', '成交日期'], + }, ], measures: [ - { name: 'opp_count', aggregate: 'count' }, - { name: 'total_amount', aggregate: 'sum', field: 'amount' }, - { name: 'avg_amount', aggregate: 'avg', field: 'amount' }, + { name: 'opp_count', aggregate: 'count', synonyms: ['deal count', '商机数'] }, + { name: 'total_amount', aggregate: 'sum', field: 'amount', synonyms: ['deal value', '商机金额'] }, + { name: 'avg_amount', aggregate: 'avg', field: 'amount', synonyms: ['average deal value', '平均商机金额'] }, ], }; diff --git a/packages/lint/src/validate-dataset-member-vocabulary.test.ts b/packages/lint/src/validate-dataset-member-vocabulary.test.ts new file mode 100644 index 00000000000..5e037fe953b --- /dev/null +++ b/packages/lint/src/validate-dataset-member-vocabulary.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// ADR-0149 D1 — a dataset measure or dimension that declares neither +// `synonyms` nor a `description` is advised, once per member, at every +// authoring door: the three CLI commands and the runtime publish door for a +// `dataset` write. Never a refusal. + +import { describe, expect, it } from 'vitest'; + +import { DatasetSchema } from '@objectstack/spec/ui'; + +import { AUTHORING_RULES, runAuthoringRules, type AuthoringCommand } from './authoring-rules.js'; +import { explainRule } from './rule-explanations.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; +import { + DATASET_MEMBER_NO_VOCABULARY, + validateDatasetMemberVocabulary, +} from './validate-dataset-member-vocabulary.js'; + +const OBJECTS = [ + { + name: 'acme_invoice', + label: 'Invoice', + sharingModel: 'private', + fields: { + status: { type: 'select', label: 'Status' }, + issued_on: { type: 'date', label: 'Issued' }, + total: { type: 'currency', label: 'Total' }, + }, + }, +]; + +/** Every member carries both keys: the complete form the reference app ships. */ +const completeDataset = () => ({ + name: 'acme_invoice_metrics', + label: 'Invoice Metrics', + object: 'acme_invoice', + dimensions: [ + { + name: 'status', + label: 'Status', + field: 'status', + type: 'string', + description: 'Where the invoice stands: draft, sent or paid.', + synonyms: ['invoice status', '发票状态'], + }, + { + name: 'issued_on', + label: 'Issued', + field: 'issued_on', + type: 'date', + description: 'The date the invoice was issued, grouped by calendar month.', + synonyms: ['issue date', '开票日期'], + }, + ], + measures: [ + { + name: 'invoice_count', + label: 'Invoices', + aggregate: 'count', + description: 'How many invoices there are, in every status.', + synonyms: ['number of invoices', '发票数'], + }, + { + name: 'total_amount', + label: 'Total Amount', + aggregate: 'sum', + field: 'total', + description: 'The sum of the invoice totals, in every status.', + synonyms: ['revenue', 'billed amount', '开票金额'], + }, + ], +}); + +/** The same dataset with both vocabulary keys removed from every member. */ +const strippedDataset = () => { + const dataset = completeDataset(); + const strip = (member: Record) => { + const { description: _description, synonyms: _synonyms, ...rest } = member; + return rest; + }; + return { ...dataset, dimensions: dataset.dimensions.map(strip), measures: dataset.measures.map(strip) }; +}; + +const run = (...datasets: unknown[]) => validateDatasetMemberVocabulary({ objects: OBJECTS, datasets }); + +describe('dataset member vocabulary · the rule', () => { + it('is silent on a dataset whose every member declares synonyms and a description', () => { + expect(DatasetSchema.safeParse(completeDataset()).success).toBe(true); + expect(run(completeDataset())).toEqual([]); + }); + + it('reports one finding per member of a dataset stripped of both keys, naming the dataset and the member', () => { + expect(DatasetSchema.safeParse(strippedDataset()).success).toBe(true); + const findings = run(strippedDataset()); + expect(findings.map((f) => [f.rule, f.severity, f.path, f.where])).toEqual([ + [DATASET_MEMBER_NO_VOCABULARY, 'warning', 'datasets[0].dimensions[0]', 'dataset "acme_invoice_metrics" dimension "status"'], + [DATASET_MEMBER_NO_VOCABULARY, 'warning', 'datasets[0].dimensions[1]', 'dataset "acme_invoice_metrics" dimension "issued_on"'], + [DATASET_MEMBER_NO_VOCABULARY, 'warning', 'datasets[0].measures[0]', 'dataset "acme_invoice_metrics" measure "invoice_count"'], + [DATASET_MEMBER_NO_VOCABULARY, 'warning', 'datasets[0].measures[1]', 'dataset "acme_invoice_metrics" measure "total_amount"'], + ]); + for (const f of findings) { + // `where` names the dataset and the member (pinned above); the sentence + // and the fix both name the two keys. + expect(f.message).toContain('`synonyms`'); + expect(f.message).toContain('`description`'); + expect(f.hint).toContain('`synonyms`'); + expect(f.hint).toContain('`description`'); + } + }); + + it('is silent on a member with only synonyms, and on a member with only a description', () => { + const dataset = strippedDataset(); + const findings = run({ + ...dataset, + dimensions: [ + { ...dataset.dimensions[0], synonyms: ['invoice status'] }, + { ...dataset.dimensions[1], description: 'The date the invoice was issued.' }, + ], + measures: [ + { ...dataset.measures[0], description: { en: 'How many invoices there are.', 'zh-CN': '发票的数量。' } }, + dataset.measures[1], + ], + }); + // Three members carry one key each; the fourth carries neither. + expect(findings.map((f) => f.path)).toEqual(['datasets[0].measures[1]']); + }); + + it('reads an empty list, a blank string and an empty locale map as not declared', () => { + const dataset = strippedDataset(); + const findings = run({ + ...dataset, + dimensions: [ + { ...dataset.dimensions[0], synonyms: [] }, + { ...dataset.dimensions[1], description: ' ' }, + ], + measures: [ + { ...dataset.measures[0], description: {} }, + { ...dataset.measures[1], synonyms: [], description: { en: '' } }, + ], + }); + expect(findings).toHaveLength(4); + }); + + it('judges each dataset by its own members and locates a map-shaped collection by name', () => { + const complete = completeDataset(); + const stripped = { ...strippedDataset(), name: 'acme_bare_metrics' }; + expect(run(complete, stripped).map((f) => f.path)).toEqual([ + 'datasets[1].dimensions[0]', + 'datasets[1].dimensions[1]', + 'datasets[1].measures[0]', + 'datasets[1].measures[1]', + ]); + const { name: _name, ...keyed } = stripped; + const byName = validateDatasetMemberVocabulary({ datasets: { acme_bare_metrics: keyed } }); + expect(byName.map((f) => f.path)[0]).toBe('datasets.acme_bare_metrics.dimensions[0]'); + expect(byName[0].where).toBe('dataset "acme_bare_metrics" dimension "status"'); + }); + + it('tolerates a stack with no datasets and a dataset with no members', () => { + expect(validateDatasetMemberVocabulary({})).toEqual([]); + expect(run({ name: 'acme_empty', label: 'Empty', object: 'acme_invoice' })).toEqual([]); + expect(run({ name: 'acme_empty', label: 'Empty', object: 'acme_invoice', dimensions: [], measures: [] })).toEqual([]); + }); +}); + +describe('dataset member vocabulary · the doors', () => { + it('is registered advisory, on all three commands and on the publish door for a dataset write', () => { + const entry = AUTHORING_RULES.find((r) => r.name === 'validateDatasetMemberVocabulary'); + expect(entry).toBeDefined(); + expect(entry!.tier).toBe('advisory'); + expect([...entry!.commands].sort()).toEqual(['build', 'lint', 'validate']); + expect(entry!.surfaces).toContain('runtime-publish'); + expect(entry!.runtimeTypes).toEqual(['dataset']); + expect(runtimeAuthoringRulesFor('dataset').map((r) => r.name)).toContain('validateDatasetMemberVocabulary'); + expect(runtimeAuthoringRulesFor('dashboard').map((r) => r.name)).not.toContain('validateDatasetMemberVocabulary'); + }); + + it.each(['validate', 'build', 'lint'])('`os %s` reports it as a warning, one per bare member', (command) => { + const stack = { objects: OBJECTS, datasets: [strippedDataset()] }; + const own = runAuthoringRules(command, { normalized: stack, parsed: stack }).filter( + (f) => f.rule === DATASET_MEMBER_NO_VOCABULARY, + ); + expect(own).toHaveLength(4); + expect(own.every((f) => f.severity === 'warning')).toBe(true); + + const clean = { objects: OBJECTS, datasets: [completeDataset()] }; + expect( + runAuthoringRules(command, { normalized: clean, parsed: clean }).filter((f) => f.rule === DATASET_MEMBER_NO_VOCABULARY), + ).toEqual([]); + }); + + it('the publish door advises a dataset write and never refuses it for this rule', () => { + const gate = (item: unknown, datasets: unknown[] = []) => + runRuntimeAuthoringRules({ type: 'dataset', item, context: { objects: OBJECTS, datasets } }); + + const bare = gate(strippedDataset()); + expect(bare.errors).toEqual([]); + const advised = bare.advisories.filter((f) => f.rule === DATASET_MEMBER_NO_VOCABULARY); + expect(advised.map((f) => f.where)).toEqual([ + 'dataset "acme_invoice_metrics" dimension "status"', + 'dataset "acme_invoice_metrics" dimension "issued_on"', + 'dataset "acme_invoice_metrics" measure "invoice_count"', + 'dataset "acme_invoice_metrics" measure "total_amount"', + ]); + expect(bare.rulesRun).toContain('validateDatasetMemberVocabulary'); + + const complete = gate(completeDataset()); + expect(complete.errors).toEqual([]); + expect(complete.advisories.filter((f) => f.rule === DATASET_MEMBER_NO_VOCABULARY)).toEqual([]); + + // A stored sibling with bare members is somebody else's condition: writing + // a complete dataset beside it reports nothing for the sibling. + const besideBareSibling = gate(completeDataset(), [{ ...strippedDataset(), name: 'acme_other_metrics' }]); + expect(besideBareSibling.advisories.filter((f) => f.rule === DATASET_MEMBER_NO_VOCABULARY)).toEqual([]); + }); + + it('has an `os explain` entry under its own id', () => { + expect(explainRule(DATASET_MEMBER_NO_VOCABULARY)?.rule).toBe(DATASET_MEMBER_NO_VOCABULARY); + }); +}); diff --git a/packages/lint/src/validate-dataset-member-vocabulary.ts b/packages/lint/src/validate-dataset-member-vocabulary.ts new file mode 100644 index 00000000000..31d46e12ed1 --- /dev/null +++ b/packages/lint/src/validate-dataset-member-vocabulary.ts @@ -0,0 +1,122 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A dataset measure or dimension that declares neither `synonyms` nor a + * `description` is advised: a question asked in a user's own words will not + * find it. + * + * ## What the two keys are read for + * + * ADR-0149 D1 gives a dataset member its business vocabulary: `synonyms`, the + * words a person types for it in a question, and `description`, a one- or + * two-sentence business definition. `list_datasets` matches the terms of a + * question against each member's `name`, `label` and `synonyms`, and hands the + * `description` to the assistant to choose a member by and to explain a number + * with. Both keys are optional in the schema, so a dataset that declares + * neither parses, compiles and draws every widget bound to it. What it loses + * is the question: a member with neither answers only to its own name and + * label, a person who asks in other words (or in another language) matches + * nothing, and the assistant falls back to an object query — a number no + * dataset governs, for a metric the app does govern. + * + * ## What counts as declared + * + * - `synonyms`: an array holding at least one non-blank string. + * - `description`: a non-blank string, or an inline locale map + * (`{ en, 'zh-CN' }`) with at least one non-blank value. + * + * One of the two is enough to silence the rule: a member with only synonyms is + * matched, and a member with only a description can still be chosen by its + * definition. The rule reports the member that has NEITHER, one finding per + * member, and names the dataset and the member. + * + * It does not judge the words themselves. That one word names one member (a + * synonym equal to another member's name, label or synonym) is the dataset + * schema's refusal, and whether a synonym is a word anybody types is the + * author's knowledge, not a static reading. + * + * ## Severity and doors + * + * `warning`, never `error`: the dataset is valid and serves every dashboard + * and report bound to it; a dataset that only feeds charts, and that nobody + * asks questions of, loses nothing. It runs on `os validate`, `os build`, + * `os lint` and the runtime publish door for a `dataset` write, where it is an + * advisory on the save response, never a refusal. Reads only the dataset's own + * members, so it is safe on a pre- or post-parse stack and on the per-write + * snapshot. + */ + +import { collectionEntries } from './collection-entries.js'; + +type AnyRec = Record; + +export const DATASET_MEMBER_NO_VOCABULARY = 'dataset-member-no-vocabulary'; + +export interface DatasetMemberVocabularyFinding { + /** Always `warning`: the dataset is valid and renders; see the module note. */ + severity: 'warning'; + rule: typeof DATASET_MEMBER_NO_VOCABULARY; + where: string; + /** Positional config path of the member, e.g. `datasets[0].measures[2]`. */ + path: string; + message: string; + hint: string; +} + +/** The two member groups of a dataset, with the noun a finding names a member by. */ +const MEMBER_GROUPS = [ + { key: 'dimensions', kind: 'dimension' }, + { key: 'measures', kind: 'measure' }, +] as const; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); +const isText = (v: unknown): boolean => typeof v === 'string' && v.trim() !== ''; + +/** At least one non-blank word in the member's `synonyms`. */ +function declaresSynonyms(member: AnyRec): boolean { + return Array.isArray(member.synonyms) && member.synonyms.some(isText); +} + +/** A non-blank `description`: a string, or an inline locale map with one non-blank value. */ +function declaresDescription(member: AnyRec): boolean { + const description = member.description; + if (isText(description)) return true; + return isRec(description) && Object.values(description).some(isText); +} + +/** + * Flag every measure and dimension of every dataset that declares neither + * `synonyms` nor a `description` (module note). Pure `(stack) => Finding[]`; + * safe on pre- or post-parse stacks. + */ +export function validateDatasetMemberVocabulary(stack: AnyRec): DatasetMemberVocabularyFinding[] { + const findings: DatasetMemberVocabularyFinding[] = []; + for (const { rec: dataset, path } of collectionEntries(stack.datasets, 'datasets')) { + const datasetName = typeof dataset.name === 'string' && dataset.name !== '' ? dataset.name : '(unnamed)'; + for (const { key, kind } of MEMBER_GROUPS) { + const members = dataset[key]; + if (!Array.isArray(members)) continue; + members.forEach((member, at) => { + if (!isRec(member)) return; + if (declaresSynonyms(member) || declaresDescription(member)) return; + const memberName = typeof member.name === 'string' && member.name !== '' ? member.name : '(unnamed)'; + findings.push({ + severity: 'warning', + rule: DATASET_MEMBER_NO_VOCABULARY, + where: `dataset "${datasetName}" ${kind} "${memberName}"`, + path: `${path}.${key}[${at}]`, + // `where` names the dataset and the member; every door prints it before this sentence. + message: + 'declares neither `synonyms` nor a `description`, so it answers only to its own name and label: ' + + `a question asked in a user's own words will not find this governed ${kind}, and the answer ` + + 'comes from an ungoverned object query instead.', + hint: + 'Add `synonyms`, the words a person types for it, in the language your users ask in (every ' + + 'language in the one list), and a one-sentence `description` saying what it is in business ' + + 'terms. One word names one member: a synonym may not equal another member\'s name, label or synonym.', + }); + }); + } + } + return findings; +} diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.dataset-writes.test.ts b/packages/metadata-protocol/src/runtime-authoring-gate.dataset-writes.test.ts index 9c4bcfec727..014dc13da3a 100644 --- a/packages/metadata-protocol/src/runtime-authoring-gate.dataset-writes.test.ts +++ b/packages/metadata-protocol/src/runtime-authoring-gate.dataset-writes.test.ts @@ -48,18 +48,22 @@ const OBJECTS = [ }, ]; -/** A dataset every crossed rule passes. */ +/** + * A dataset every crossed rule passes. Each member carries `synonyms` + * (ADR-0149 D1): a member with neither `synonyms` nor a `description` is + * advised (`dataset-member-no-vocabulary`), and "clean" here means no advisory. + */ const cleanDataset = (over: Record = {}) => ({ name: 'acme_invoice_metrics', label: 'Invoice Metrics', object: 'acme_invoice', dimensions: [ - { name: 'region', field: 'region' }, - { name: 'issued_on', field: 'issued_on', dateGranularity: 'month' }, + { name: 'region', field: 'region', synonyms: ['billing region'] }, + { name: 'issued_on', field: 'issued_on', dateGranularity: 'month', synonyms: ['issue date'] }, ], measures: [ - { name: 'invoice_count', aggregate: 'count' }, - { name: 'total_amount', aggregate: 'sum', field: 'total' }, + { name: 'invoice_count', aggregate: 'count', synonyms: ['number of invoices'] }, + { name: 'total_amount', aggregate: 'sum', field: 'total', synonyms: ['billed amount'] }, ], ...over, }); diff --git a/skills/objectstack-ui/evals/README.md b/skills/objectstack-ui/evals/README.md index c17c8d7f7de..304c2d54306 100644 --- a/skills/objectstack-ui/evals/README.md +++ b/skills/objectstack-ui/evals/README.md @@ -7,8 +7,10 @@ view / page / dashboard / report metadata. - `analytics-inline-vs-dataset.json` — dataset-envelope decisions for dashboard/report widgets: when a data need fits a `defineDataset`, when it - must escalate to a stored field or app code, and when an ad-hoc - in-page `` needs no dataset at all. + must escalate to a stored field or app code, when an ad-hoc + in-page `` needs no dataset at all, and a dataset authored + for a Chinese brief, whose members carry Chinese `synonyms` and a + one-sentence `description`. - `record-page.json` — the record page as the object declares it: a child table placed first by `relatedList: 'primary'` (no page file), `navigation: { mode: 'page' }` on the list view with the reader's own diff --git a/skills/objectstack-ui/evals/analytics-inline-vs-dataset.json b/skills/objectstack-ui/evals/analytics-inline-vs-dataset.json index 08295660bd6..dab1c3821a0 100644 --- a/skills/objectstack-ui/evals/analytics-inline-vs-dataset.json +++ b/skills/objectstack-ui/evals/analytics-inline-vs-dataset.json @@ -82,6 +82,16 @@ "must_contain": ["duration", "unit: 'days'", "polarity: 'lower'"], "must_not_contain": ["beforeUpdate"] } + }, + { + "id": 9, + "prompt": "销售总监想在仪表盘上按客户、按月看「回款金额」和「回款笔数」。payment(回款)对象有 amount(金额)、paid_at(回款日期)和 account(客户,lookup)。请写这个数据集。", + "expected_output": "Authors a dataset for a Chinese brief: every measure and dimension carries `synonyms` in the language of the brief, the words a person types (回款金额 / 回款额 / 到账金额 for the amount sum, 回款笔数 for the count, 客户, 回款月份), and a one-sentence business `description` written in Chinese, a definition and not a prompt. Synonyms are one flat list per member, never a locale-keyed map and never English-only words for a Chinese request; one word names one member, so no synonym repeats another member's name, label or synonym. No member is left with neither key (`dataset-member-no-vocabulary`).", + "files": [], + "assertions": { + "must_contain": ["defineDataset", "synonyms", "description", "回款"], + "must_not_contain": ["synonyms: {", "'zh-CN': ["] + } } ] } diff --git a/skills/objectstack-ui/rules/dashboards.md b/skills/objectstack-ui/rules/dashboards.md index 1b98ed26e58..530549890ee 100644 --- a/skills/objectstack-ui/rules/dashboards.md +++ b/skills/objectstack-ui/rules/dashboards.md @@ -293,14 +293,15 @@ import { defineDataset, type DashboardWidget } from '@objectstack/spec/ui'; // In the dataset (Guides → Analytics Datasets): defineDataset({ name: 'crm_contract_metrics', label: 'Contract Metrics', object: 'contract', - dimensions: [{ name: 'signed_date', field: 'signed_date', type: 'date', dateGranularity: 'month' }], + dimensions: [{ name: 'signed_date', field: 'signed_date', type: 'date', dateGranularity: 'month', + synonyms: ['签约月'] }], measures: [{ name: 'signed_count', aggregate: 'count', synonyms: ['签约数', 'deals signed'], description: 'Contracts signed in the period, drafts excluded.' }], }); -// Member `synonyms` (ADR-0149 D1): the words a question uses for it, every -// language in one list; matched, never translated; none may equal another -// member's name, label or synonym. `description`: a business definition, -// never a prompt; translated like `label`. +// Every member: `synonyms`, the words a person types, in the brief's +// language (matched, never translated; one word names one member), and a +// one-sentence business `description`, never a prompt. Neither warns: +// `dataset-member-no-vocabulary`. // A money measure may set `currency` (ISO 4217, e.g. `'USD'`). Chain: // measure `currency` → the field's `defaultCurrency` (`fixed` only) → // tenant `localization.currency`; omit it for counts. A