Skip to content

Commit 3cbf1f2

Browse files
feat(lint)!: refuse an object that shows two visible fields under one label (#33639)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XU2xTyPNgEy5xtAJUJL1GdG)_ Fixes #33545 Part of #33506 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — the authoring half (an AI builder reusing `owner_id` rather than adding a second owner field) is the skills lane's on the parent card; `os explain field-label-duplicate` carries the rule's full text, and four CLI transcripts in `content/docs` move their author-time rule count from 67 to 68 (claim amendment 6887617666). Severity ruling: error at the author door, installed apps unaffected at load (claim 6887573651, Ruling-ref 「开放 p3卡认领」). Measured: no boot or registration path runs the author-time rules, so no fork. ## 维护者速读 - **改了什么**:`@objectstack/lint` 新增一条门禁规则 `field-label-duplicate`:同一对象上两个及以上可见字段(含平台注入的 `owner_id`、创建/修改时间与人)在作者写的标签或任一语言下显示为同一个标签,就报错。`os build` / `os validate` / `os lint` 和元数据发布门(对象写入)都执行它。示例应用里三处中文标签撞了 `owner_id` 的「负责人」,已改名(showcase 的任务「处理人」、团队「组长」,todo 的任务「处理人」),并登记了 ADR-0087 迁移条目。 - **为什么改**:staging 上 AI 搭的工单对象有 `owner_id`(中文「负责人」)和新加的 `assignee`(也叫「负责人」),表格出两列「负责人」、看板卡片显示两次,用户分不清改的是哪个。构建时就拦下,比上线后再发现好。 - **风险与回滚**:今天能构建的元数据如果有同名可见字段会构建失败(这是有意的收紧);已安装的应用启动不受影响。发布门上,已存储对象若带同名字段,再次保存该对象会被拒直到改名;保存别的对象不受影响。回滚即 revert。 - **先看**:`packages/lint/src/lint-duplicate-field-labels.ts`(比较哪些字段、哪些语言),`packages/lint/src/authoring-rules.ts`(新登记项,门禁 + 对象发布门),`examples/app-showcase/src/system/translations/index.ts`(示例改名)。 - **两分钟验证**:`pnpm --filter @objectstack/lint exec vitest run --maxWorkers=2 src/lint-duplicate-field-labels.test.ts`,预期 9 个用例全绿;其中第一个就是 staging 的 `owner_id` + `assignee`「负责人」。 - **需要你做的**:无,席位落地。 ## What changes - **`packages/lint/src/lint-duplicate-field-labels.ts`** (new): `lintDuplicateFieldLabels(stack)`, rule id `FIELD_LABEL_DUPLICATE` = `field-label-duplicate`, `error`. Per object it compares the fields the object SERVES: its own fields with every `objectExtensions` field of the stack folded in (`objectsAsServed`, tied fields left out, as `lintAutonumberFormats` does), plus the columns the registry injects on it (`injectedColumnDefsFor`, the spec tables `applySystemFields` spreads; an authored field of the same name replaces the injected one). `hidden: true` fields are skipped; the injected `organization_id`, `owning_business_unit_id` and `queue` are hidden by their own definitions, so `owner_id` and the four audit columns are compared. Labels are compared trimmed, once as authored and once per locale, through the spec's own read-exit translator `translateObject` (no second copy of its ladder). Locales: every locale a `translations` bundle of the stack carries plus `BUILTIN_SYSTEM_FIELD_LABEL_LOCALES` (`en`, `zh-CN`, `ja-JP`, `es-ES`), the locales a `/meta` read translates the injected columns into with no bundle at all. That second set is what catches the #33506 case: the author's `assignee` keeps 负责人 while `owner_id` is served 负责人 to a `zh-CN` reader. One finding per group of fields sharing a label; it names every field, the label, the locale(s) when only some clash, and the injected column(s) involved; the hint says rename, `hidden: true`, or drop the duplicate and use the platform column. - **`packages/lint/src/authoring-rules.ts`**: one entry, `tier: 'gating'`, `input: 'parsed'`, all three commands, `surfaces: CLI_AND_RUNTIME`, `runtimeTypes: ['object']` (the `lintSummaryRollups` shape). **`index.ts`**: barrel export of the function, the id constant and the finding type. - **`packages/lint/src/rule-explanations.ts`**: `os explain field-label-duplicate` entry (additive, appended after the last entry and at the end of the table; in-flight PR #33517 also edits this file). - **User text:** none. The family's `*.user-text.ts` catalogs hold sentences for door ADVISORIES only (`lint-autonumber-formats.user-text.ts`: "The two errors … refuse the write and have no sentence here"); this rule is an error. - **Tests:** `lint-duplicate-field-labels.test.ts` (new, 9 cases: the #33506 pair red, hidden duplicate clean, distinct labels clean, `ownership: 'none'` clean, a clash only one translated locale creates naming that locale, an authored clash named once with no locale, an authored `owner_id` with its own label replacing the injected one, the registry entry on all three commands, and the explanation naming exactly the built-in locales); `runtime-gate.object-writes.test.ts` (the door roster and `rulesRun` pins gain the entry; a new describe: the write that adds the clash is refused with a name-keyed path, the hidden and relabelled controls publish, a sibling write is not charged with a stored object's clash, and a re-save of the clashing object is judged on its body). - **Shipped metadata the narrowing bit, relabelled (zh-CN bundle only):** `example-showcase` `showcase_task.assignee` 负责人 → 处理人 and `showcase_team.lead` 负责人 → 组长 (plus the `p_assignee` action-param label and its comment, which said it matches `showcase_task.assignee`); `example-todo` `todo_task.owner` 负责人 → 处理人 (and the `todo_tasks_by_owner` report label/description that names the same field). Each of the three was served 负责人 beside `owner_id` to a `zh-CN` reader. - **ADR-0087:** `packages/spec/src/migrations/entries/semantic/18.object-field-label-duplicate-refused.ts` (a structured TODO: which field keeps the label is the author's choice, so no D2 conversion); the changeset carries `registered object-field-label-duplicate-refused`. - **Fixtures the door now refuses, relabelled (claim amendment 6887847864, no assertion changed):** two metadata-protocol test files, both about other rules at the publish door. `protocol.runtime-authoring-gate.test.ts`: four fixture objects declare `owner: { type: 'text', label: 'Owner' }`, which the door now reads as one label with the injected `owner_id` ("Owner"); relabelled `'Owner Name'` (lines 413, 703, 714, 791). `protocol.unknown-picklist-binding-refusal.test.ts`: the `object()` helper gives every bound select field the label `'Tier'`, so a fixture binding `t` and `tier` showed two "Tier" columns; the label is now `` `Tier (${field})` `` (line 187). Neither test is about labels or `owner_id`; 266 of 266 metadata-protocol tests green after the relabel. No other fixture in the swept suites or the dogfood battery was refused. - **Docs:** the four CLI transcripts' `Running author-time rules (67)` → `(68)` (claim amendment 6887617666). - **`.changeset/33545-duplicate-field-labels.md`**: `@objectstack/lint` and `@objectstack/spec` `minor` (`narrowed`), BREAKING banner with FROM → TO lines and fixes. ### Where the rule runs, measured - `os build` / `os validate` / `os lint` and `os verify`'s author-time step: the registry (`authoringRulesFor`). Scaffold validation runs it too (`scaffold-validate.ts`). - The publish door: `saveMetaItem` with `state: 'active'` and the draft→active promotion, through `judgeRuntimeAuthoringRules` / `runtimeAuthoringRulesFor('object')`. Studio, REST `/meta` and MCP/AI authors reach it there. The door snapshot carries no `translations`, so at the door the authored labels and the built-in system-field labels are compared (which is the staging case). - Boot / registration: nothing on that path runs `AUTHORING_RULES` (`git grep` over every non-test consumer: the CLI commands, scaffold validate, `os verify`, the metadata-protocol save/publish gate; `metadata-diagnostics.ts` imports two named lint functions only, not the registry). So an installed app keeps loading — no fork. - "The AI builder's integrity check" (card item 1): not in this repository (no such check under `packages/`; the builder is in cloud). What this repo offers it is the publish door above, which every MCP/REST/Studio object write passes; nothing was done in cloud. ## Tests - `pnpm --filter @objectstack/lint exec vitest run --maxWorkers=2 src/lint-duplicate-field-labels.test.ts src/runtime-gate.object-writes.test.ts`: 53 passed. - **Ablation 1** (rule returns nothing: `if (!isRec(stack)) return findings;` → always return, via `scripts/ablation-replace.mjs`): 6 red, among them the #33506 `owner_id` + `assignee` case, the one-locale clash, the authored clash, the registry entry and both door cases; restored, blob equals HEAD, `git diff HEAD` empty. - **Ablation 2** (hidden fields compared: `if (def.hidden === true) continue;` neutralised): 2 red, the hidden control in the rule test and the hidden/relabelled publish control at the door; restored the same way. - Consumer suites on this branch, each exit 0: rest 8393, runtime 10781, objectql 13028, service-automation 3916, service-datasource 1317, plugin-security 6679, client 812, mcp 1174, cloud-connection 1209, verify 437, example-showcase 545, example-todo 249, example-crm 51, cli unit tier 5966, metadata-protocol 266, plugin-approvals rule-runner tests 24, spec migrations 198. ## Acceptance notes - **Sweep.** Every example and every first-party app under `packages/apps` built through the real CLI (`os build`): only `example-showcase` and `example-todo` were refused, the three fields relabelled above; all 11 build clean now. HotCRM (5 packages, 23 objects, 5 bundles): 0 findings, with a positive control (a duplicate of each object's first visible label) firing on 23 of 23 objects, so the probe reached every object. - **A re-save of a stored object that carries the clash is refused** at the publish door until it is fixed, as for every gating rule there (the door's differential removes the written item's stored self, so its own clash is new to the judgment). A write of any other object is never charged with it. The door test pins both. - **Out of scope, reported:** run over the platform's own objects with their generated translation bundles (98 objects, 111 bundles), the rule finds three clashes no author door judges, because these objects are not built through `os build` and the door snapshot carries no translations: `sys_import_job` `created_at`/`created_count` "Создано" (ru), `sys_oauth_resource` `id`/`identifier` "المعرّف" (ar), `sys_user` `accountable_user_id`/`manager_id` "Responsable" (fr). Each is a reader-facing duplicate column in that locale. Left untouched here (translation pipeline output outside the card); named as a follow-up in the report. - **Where the door compares locales:** the authored labels and the built-in `en`/`zh-CN`/`ja-JP`/`es-ES` system-field labels, which is the staging case; a clash only a stored translation bundle creates is caught by `os build`/`os validate`/`os lint`, not at the object write. ## Verification - Gate list from `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at 274a4bd: 116 commands, every one run, every one exit 0. Three first exited 3 (prerequisite not met, not a finding) and were rerun after the dependency builds: `check-plugin-teardown-shape.mjs --self-test` (pinned commit fetched), `spec check:skill-examples` (client builds), `check:dual-build-cjs-loads` (dist builds). Log: `/mnt/project-files/pm-orders/spec/33545-gates-ran.txt`. - Typecheck: `@objectstack/lint` (including its test typecheck), `@objectstack/metadata-protocol`, `@objectstack/spec` (`tsc --noEmit`), `example-showcase`, `example-todo`: exit 0. - Dogfood battery on 274a4bd (`pnpm --filter @objectstack/dogfood test` under the verify lock, after building `@objectstack/dogfood^...`): command exit 0, 467 files passed and 3 skipped, 3950 tests passed and 42 skipped. No fixture was refused. - Not measured here: the CI-only rows `dispatch-gates` names as having no local invocation (Build Core, the Dogfood Regression Gate's merge-queue run, the type-check lanes over CI's whole-workspace filters). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5mdmzDcF58D1JdRH4y --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5mdmzDcF58D1JdRH4y)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent de5eb08 commit 3cbf1f2

16 files changed

Lines changed: 525 additions & 15 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/lint': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
feat(lint)!: refuse an object that shows two visible fields under one label (`field-label-duplicate`)
7+
8+
Clause-②: no (narrowing) — `os build`, `os validate`, `os lint` and the metadata publish door (an `object` write) now refuse an object whose visible fields, the platform's injected columns included, share one label in the authored text or in any locale a reader is served. Shipped first-party metadata hit: two example apps, relabelled here (`example-showcase`: `showcase_task.assignee` and `showcase_team.lead`, both served 负责人 to a `zh-CN` reader beside `owner_id`; `example-todo`: `todo_task.owner`, likewise); every other example, every first-party app under `packages/apps` and HotCRM build clean.
9+
Metadata-protocol: narrowed
10+
Skills-docs: none — the authoring half (an AI builder reusing `owner_id` instead of adding a second "Owner" field) is the skills lane's on the parent card; `os explain field-label-duplicate` carries the rule's full text, and four CLI transcripts in `content/docs` show the author-time rule count moving from 67 to 68.
11+
12+
<!-- adr-0087: registered object-field-label-duplicate-refused -->
13+
14+
**BREAKING** for metadata that builds today: an object that shows two or more visible fields under one label is now an error. Every surface draws a field under its label (list grid headers, kanban card lines, form captions, export and import columns), so two fields of one label are two columns a person cannot tell apart, and editing one reads as editing the other. The common case is a field added beside the platform's own: a `user` field labelled like `owner_id`, which a `zh-CN` reader is served as "负责人".
15+
16+
What is compared: the fields the object serves (its own plus every `objectExtensions` field of the stack) and the columns the platform injects on it (`owner_id`, `created_at`, `created_by`, `updated_at`, `updated_by`; the organization, business-unit and queue columns are hidden). A field declared under an injected column's name replaces it. `hidden: true` fields are not compared. Labels are compared trimmed, once as authored and once per locale (every locale a `translations` bundle carries, plus `en`, `zh-CN`, `ja-JP` and `es-ES`, the locales the platform translates the injected columns into), through the same `translateObject` the `/meta` read serves them with.
17+
18+
FROM → TO, and the fix:
19+
20+
- FROM an object with `assignee: { type: 'user', label: '负责人' }` beside the injected `owner_id` building clean TO `field-label-duplicate` naming `'assignee' and 'owner_id'`, the label and `locale zh-CN`. Fix: use `owner_id` instead of a second owner field, or label the field apart (for example "处理人"), or set `hidden: true` on it.
21+
- FROM two authored fields labelled "Status" building clean TO the same error, naming both fields and no locale. Fix: give each its own label.
22+
- FROM a translation bundle that gives two fields one label in one locale building clean TO the error naming that locale. Fix: translate them apart in that bundle.
23+
24+
At the publish door a write of another object is never refused for a clash a stored object carries; saving the clashing object itself is refused until the clash is fixed, as for every gating rule at that door. No boot or registration path runs the author-time rules, so an installed app keeps loading and serving its objects as before.

‎content/docs/deployment/cli.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -880,7 +880,7 @@ os compile --json # JSON output for CI pipelines
880880
→ Normalizing stack definition...
881881
→ Lowering inline handlers...
882882
→ Validating protocol compliance...
883-
→ Running author-time rules (67)...
883+
→ Running author-time rules (68)...
884884
→ Checking that every required capability has a provider installable in this edition...
885885
→ Collecting package docs (ADR-0046)... 0 collected
886886
→ Writing artifact...

‎content/docs/deployment/validating-metadata.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -846,7 +846,7 @@ A clean run walks the registry and reports timing:
846846
Config: /path/to/support-desk/objectstack.config.ts
847847
Load time: 21ms
848848
→ Validating against ObjectStack Protocol...
849-
→ Running author-time rules (67)...
849+
→ Running author-time rules (68)...
850850
→ Checking that every required capability has a provider installable in this edition...
851851
→ Checking package docs (ADR-0046)...
852852

‎content/docs/getting-started/build-with-claude-code.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ visible: 'status != "resolved"'
311311
◆ Validate
312312
────────────────────────────────────────
313313
→ Validating against ObjectStack Protocol...
314-
→ Running author-time rules (67)...
314+
→ Running author-time rules (68)...
315315
316316
✗ Author-time rules failed (1 issue)
317317
• stack · action 'resolve_ticket' visible: bare reference `status` — a

‎content/docs/ui/react-pages.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ objectstack validate
404404
────────────────────────────────────────
405405
→ Loading configuration...
406406
→ Validating against ObjectStack Protocol...
407-
→ Running author-time rules (67)...
407+
→ Running author-time rules (68)...
408408
→ Checking that every required capability has a provider installable in this edition...
409409
→ Checking package docs (ADR-0046)...
410410

‎examples/app-showcase/src/system/translations/index.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,10 @@ export const ShowcaseTranslationBundle = {
467467
title: { label: '标题' },
468468
// The project page's Tasks list, titled by this master-detail.
469469
project: { label: '项目', relatedListTitle: '任务' },
470-
assignee: { label: '负责人' },
470+
// Not 负责人: that is what a zh-CN reader is served for the platform's
471+
// `owner_id` on this object, and two columns of one label cannot be
472+
// told apart (`field-label-duplicate`).
473+
assignee: { label: '处理人' },
471474
status: {
472475
label: '状态',
473476
options: { backlog: '待规划', todo: '待办', in_progress: '进行中', in_review: '评审中', done: '已完成' },
@@ -859,7 +862,7 @@ export const ShowcaseTranslationBundle = {
859862
},
860863
showcase_team: {
861864
label: '团队', pluralLabel: '团队',
862-
fields: { name: { label: '团队名称' }, lead: { label: '负责人' }, capacity_hours: { label: '产能(小时)' } },
865+
fields: { name: { label: '团队名称' }, lead: { label: '组长' }, capacity_hours: { label: '产能(小时)' } },
863866
_sections: { team: { label: '团队' } },
864867
},
865868
showcase_project_membership: {
@@ -1002,7 +1005,7 @@ export const ShowcaseTranslationBundle = {
10021005
// because `check-i18n-coverage` ratchets this example at its current
10031006
// untranslated count: a newly declared label that skips zh-CN pushes the
10041007
// count up and fails the gate. (The gallery's older params sit inside
1005-
// that baseline; this one is not allowed to widen it.) `负责人` matches
1008+
// that baseline; this one is not allowed to widen it.) `处理人` matches
10061009
// what the bundle already renders for `showcase_task.assignee`, rather
10071010
// than introducing a second word for the same idea.
10081011
// 动作显隐矩阵(objectui#3492 / #3501)。同上:本示例被
@@ -1013,7 +1016,7 @@ export const ShowcaseTranslationBundle = {
10131016
showcase_action_param_gallery: {
10141017
params: {
10151018
p_assignee: {
1016-
label: '负责人',
1019+
label: '处理人',
10171020
helpText: '指向系统对象的内联查找 —— 可按姓名或邮箱搜索,无需填写 UUID。',
10181021
},
10191022
},

‎examples/app-todo/src/translations/zh-CN.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ export const zhCN: TranslationData = {
5353
days_overdue: { label: '逾期天数', help: '距截止日期已过的整天数;未逾期或未设置截止日期时为 0' },
5454
reminder_date: { label: '提醒日期/时间' },
5555
completed_date: { label: '完成日期' },
56-
owner: { label: '负责人' },
56+
// Not 负责人: a zh-CN reader is served that for the platform's `owner_id`
57+
// on this object too (`field-label-duplicate`).
58+
owner: { label: '处理人' },
5759
tags: {
5860
label: '标签',
5961
options: {
@@ -104,7 +106,7 @@ export const zhCN: TranslationData = {
104106
reports: {
105107
todo_tasks_by_status: { label: '按状态统计任务', description: '按状态分组的任务汇总' },
106108
todo_tasks_by_priority: { label: '按优先级统计任务', description: '按优先级分组的任务汇总' },
107-
todo_tasks_by_owner: { label: '按负责人统计任务', description: '按负责人汇总的任务' },
109+
todo_tasks_by_owner: { label: '按处理人统计任务', description: '按处理人汇总的任务' },
108110
todo_completed_tasks: { label: '已完成任务', description: '所有已完成任务及其工时记录' },
109111
todo_time_tracking: { label: '工时跟踪报表', description: '预计工时与实际工时分析' },
110112
},

‎packages/lint/src/authoring-rules.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ import { lintConnectorCredentialLiterals } from './lint-connector-credential-lit
157157
import { lintLivenessProperties } from './lint-liveness-properties.js';
158158
import { lintAutonumberFormats } from './lint-autonumber-formats.js';
159159
import { lintViewRefs } from './lint-view-refs.js';
160+
import { lintDuplicateFieldLabels } from './lint-duplicate-field-labels.js';
160161
import { validateRetiredPermissionResidue } from './validate-retired-permission-residue.js';
161162
import { validateEmailTemplateHolePlacements } from './validate-email-template-hole-placements.js';
162163
import { validateEmailTemplateHoleGrammar } from './validate-email-template-hole-grammar.js';
@@ -2345,6 +2346,35 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
23452346
hint: f.fix ?? '',
23462347
})),
23472348
},
2349+
// Two visible fields of one object served under one label
2350+
// (`field-label-duplicate`): the platform's `owner_id` and an author's
2351+
// `assignee`, both read as "负责人" by a zh-CN reader, are two columns of one
2352+
// name in every grid, card and form, and editing one reads as editing the
2353+
// other. GATING on all three commands and on the runtime publish gate's
2354+
// `object` writes, the door an AI or Studio author has. The labels compared
2355+
// are the ones `translateObject` serves (see the rule's module note). The
2356+
// gate's differential never charges a stored object's clash to a write of
2357+
// another object; a re-save of that object is judged on its own body, as
2358+
// for every gating rule at this door. No boot or registration path runs
2359+
// this table, so an app already installed keeps loading.
2360+
{
2361+
name: 'lintDuplicateFieldLabels',
2362+
tier: 'gating',
2363+
input: 'parsed',
2364+
commands: ALL,
2365+
source: 'packages/lint/src/lint-duplicate-field-labels.ts',
2366+
surfaces: CLI_AND_RUNTIME,
2367+
runtimeTypes: ['object'],
2368+
run: (stack) =>
2369+
lintDuplicateFieldLabels(stack).map((f) => ({
2370+
severity: f.severity,
2371+
rule: f.rule,
2372+
where: f.where,
2373+
path: f.path,
2374+
message: f.message,
2375+
hint: f.hint,
2376+
})),
2377+
},
23482378
// #3991 / ADR-0120 D5b — a column carrying BOTH a field-level `unique` and a
23492379
// single-column declared unique index states two scopes of which at most one
23502380
// takes effect (`unique/double-declaration`, the four-quadrant matrix).

‎packages/lint/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,6 +1185,9 @@ export {
11851185
AUTONUMBER_LITERAL_TOKEN,
11861186
} from './lint-autonumber-formats.js';
11871187

1188+
export { lintDuplicateFieldLabels, FIELD_LABEL_DUPLICATE } from './lint-duplicate-field-labels.js';
1189+
export type { DuplicateFieldLabelFinding } from './lint-duplicate-field-labels.js';
1190+
11881191
export { lintViewRefs } from './lint-view-refs.js';
11891192
export type { ViewRefFinding } from './lint-view-refs.js';
11901193
export {
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, expect, it } from 'vitest';
4+
5+
import { BUILTIN_SYSTEM_FIELD_LABEL_LOCALES } from '@objectstack/spec/system';
6+
7+
import { AUTHORING_RULES, runAuthoringRules } from './authoring-rules.js';
8+
import { explainRule } from './rule-explanations.js';
9+
import { FIELD_LABEL_DUPLICATE, lintDuplicateFieldLabels } from './lint-duplicate-field-labels.js';
10+
11+
/** The staging object: an AI-added `user` field labelled like the platform's `owner_id` in zh-CN. */
12+
function ticketObject(assignee: Record<string, unknown> = {}): Record<string, unknown> {
13+
return {
14+
name: 'e9gv_ticket',
15+
label: '工单',
16+
fields: {
17+
title: { type: 'text', label: '标题' },
18+
assignee: { type: 'user', label: '负责人', ...assignee },
19+
},
20+
};
21+
}
22+
23+
describe('lintDuplicateFieldLabels', () => {
24+
it('reports the injected owner_id and an authored field the zh-CN reader sees under one label', () => {
25+
const findings = lintDuplicateFieldLabels({ objects: [ticketObject()] });
26+
expect(findings).toHaveLength(1);
27+
const [f] = findings;
28+
expect(f.rule).toBe(FIELD_LABEL_DUPLICATE);
29+
expect(f.severity).toBe('error');
30+
expect(f.where).toBe('object "e9gv_ticket"');
31+
expect(f.path).toBe('objects[0].fields');
32+
expect(f.message).toContain("'assignee' and 'owner_id'");
33+
expect(f.message).toContain('"负责人"');
34+
expect(f.message).toContain('locale zh-CN');
35+
expect(f.hint).toContain("'owner_id'");
36+
});
37+
38+
it('does not compare a hidden field', () => {
39+
expect(lintDuplicateFieldLabels({ objects: [ticketObject({ hidden: true })] })).toEqual([]);
40+
});
41+
42+
it('passes fields whose labels differ in every locale', () => {
43+
expect(lintDuplicateFieldLabels({ objects: [ticketObject({ label: '处理人' })] })).toEqual([]);
44+
});
45+
46+
it('does not compare owner_id where the platform injects none', () => {
47+
const obj = { ...ticketObject(), ownership: 'none' };
48+
expect(lintDuplicateFieldLabels({ objects: [obj] })).toEqual([]);
49+
});
50+
51+
it('reports a clash only a translation bundle creates, naming that locale alone', () => {
52+
const stack = {
53+
objects: [
54+
{ name: 'deal', fields: { amount: { type: 'currency', label: 'Amount' }, total: { type: 'currency', label: 'Total' } } },
55+
],
56+
translations: [
57+
{ 'ja-JP': { objects: { deal: { fields: { amount: { label: '金額' }, total: { label: '金額' } } } } } },
58+
],
59+
};
60+
const findings = lintDuplicateFieldLabels(stack);
61+
expect(findings).toHaveLength(1);
62+
expect(findings[0].message).toContain("'amount' and 'total'");
63+
expect(findings[0].message).toContain('"金額" when read in locale ja-JP,');
64+
});
65+
66+
it('reports an authored clash once, naming no locale', () => {
67+
const stack = {
68+
objects: [
69+
{ name: 'deal', fields: { stage: { type: 'text', label: 'Status' }, status: { type: 'select', label: ' Status ' } } },
70+
],
71+
};
72+
const findings = lintDuplicateFieldLabels(stack);
73+
expect(findings).toHaveLength(1);
74+
expect(findings[0].message).toContain("'stage' and 'status' under one label \"Status\", so");
75+
});
76+
77+
it('reads an authored owner_id with its own label in place of the injected column', () => {
78+
const obj = {
79+
name: 'e9gv_ticket',
80+
fields: { owner_id: { type: 'lookup', reference: 'sys_user', label: '所有者' }, assignee: { type: 'user', label: '负责人' } },
81+
};
82+
expect(lintDuplicateFieldLabels({ objects: [obj] })).toEqual([]);
83+
});
84+
85+
it('is a gating entry the three commands and the object publish door run', () => {
86+
const entry = AUTHORING_RULES.find((r) => r.name === 'lintDuplicateFieldLabels');
87+
expect(entry?.tier).toBe('gating');
88+
expect(entry?.runtimeTypes).toEqual(['object']);
89+
const stack = { objects: [ticketObject()] };
90+
for (const command of ['validate', 'build', 'lint'] as const) {
91+
const rules = runAuthoringRules(command, { normalized: stack, parsed: stack }).filter((f) => f.rule === FIELD_LABEL_DUPLICATE);
92+
expect(rules.map((f) => f.severity), command).toEqual(['error']);
93+
}
94+
});
95+
96+
it('the explanation names exactly the locales the platform translates the injected columns into', () => {
97+
const text = explainRule(FIELD_LABEL_DUPLICATE)!.paragraphs.join(' ');
98+
const named = new Set([...text.matchAll(/`([a-z]{2}(?:-[A-Z]{2})?)`/g)].map((m) => m[1]));
99+
expect([...named].sort()).toEqual([...BUILTIN_SYSTEM_FIELD_LABEL_LOCALES].sort());
100+
});
101+
});

0 commit comments

Comments
 (0)