diff --git a/.changeset/35143-data-model-publish-checks.md b/.changeset/35143-data-model-publish-checks.md new file mode 100644 index 00000000000..2e4c39dfd75 --- /dev/null +++ b/.changeset/35143-data-model-publish-checks.md @@ -0,0 +1,34 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +--- + +fix(lint)!: four publish-time checks for data-model metadata that saves and does not work — two refuse the publish, two warn + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #37529 + + + +**BREAKING** for the publish of an object that carries one of the two errors below: it was accepted before and is refused now, with the fix named in the finding. The schema is unchanged and stored objects are not rewritten or refused at boot; the refusal comes at the next publish, and from `os validate` / `lint` / `compile` / `build`. + +Two errors, run by the runtime publish gate and the CLI: + +- `rollup/child-without-parent-reference`: a `summary` field whose child object has no `lookup` / `master_detail` field referencing the parent, or whose `summaryOperations.relationshipField` names no field of the child. With no foreign key the engine's summary index skips the summary with nothing logged; with a `relationshipField` that names no child field the summary is indexed and never recomputed. Either way the field reads 0 or empty on every parent while every child write reports success. Judged once the child resolves (a child the stack does not hold is still not judged), against the child's fields as served (an object extension may add the foreign key) and its injected columns (`owner_id`, `created_by` back to `sys_user`). Reported by `lintSummaryRollups`, beside its aggregand checks. +- `field/reference-on-non-reference-type`: `reference` on a field type that reads none — anything but `lookup`, `master_detail`, `user`, `tree` and `summary`. It links no record, and the record page edits a text, number or date field carrying it with a record picker that writes a record id into it. Judged on objects and on object extensions. + +Two warnings, which refuse nothing and make `os validate --strict` exit 1 as any warning does: + +- `field/count-named-lookup`: a `lookup` / `master_detail` field named like a count or a total (`contact_count`, `total_amount`); a relationship stores the id of one record, never a number. +- `approval-detail-editable-while-pending`: an approval step that locks its record (`lockRecord`, default `true`) on an object whose record page draws a `lookup` child as a table in its own body (`relatedList: 'primary'`); the approval lock covers `master_detail` children only, so those rows stay editable while the record waits. Reported by `validateApprovalApprovers`. + +A formula reading a summary that has no configuration stays covered by `field/summary-without-operations`, which refuses the summary itself. + +## FROM → TO + +- `summaryOperations: { object: 'order_line', function: 'count' }` over an `order_line` with no field pointing at `order` → add `order: { type: 'master_detail', reference: 'order' }` to `order_line`. +- `summaryOperations: { ..., relationshipField: 'order_ref' }` naming no field of the child → name the child field that holds the parent id. +- `account: { type: 'text', reference: 'account' }` → `account: { type: 'lookup', reference: 'account' }`, or drop `reference`. + +No new exports. `@objectstack/spec` adds only the upgrade-guide entry `publish-refuses-data-model-fields-that-save-and-do-not-work`. diff --git a/.changeset/35143-field-designer-drops-stray-reference.md b/.changeset/35143-field-designer-drops-stray-reference.md new file mode 100644 index 00000000000..585617c1f20 --- /dev/null +++ b/.changeset/35143-field-designer-drops-stray-reference.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the field designer removes a relationship target from a field whose type reads none, so the object still publishes + +Clause-②: no +Metadata-protocol: none + +The publish gate now refuses a `reference` on a field type that reads none, anything but `lookup`, `master_detail`, `user`, `tree` and `summary` (`field/reference-on-non-reference-type`). The object designer's field panel kept the key when a field was retyped: a `lookup` retyped to `text` saved as text with the old target still on it, and the Related Object picker, drawn only on `lookup`, `master_detail` and `tree`, offered no way to see or clear it there. A retype to a type that reads none now removes `reference`, as it already removes the picklist binding, option kinds, `referenceNameVisible` and `deleteBehavior` the new type cannot carry. An object saved that way earlier is repaired by its next edit: the designer reads such a field without the key, so the next save writes it without one and the publish goes through. Nothing is lost: on those types the key linked no record. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 4837a98a6eb..af64ea251aa 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (80)... + → Running author-time rules (81)... → 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 ed40bb89b71..72f77750452 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -867,7 +867,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 (80)... + → Running author-time rules (81)... → 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 f36f60fa711..59493acbd77 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -312,7 +312,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (80)... + → Running author-time rules (81)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index d8c8b9be510..6315fde8a9c 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 (80)... + → Running author-time rules (81)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index d37882c6455..d3a7c9883cf 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -179,9 +179,11 @@ import { lintUniqueDeclarations, lintUnscopedDeclaredIndexes, lintLegacyOrganizationComposites, - lintSummaryRollups, lintInlineEditBulk, + lintFieldReferenceShapes, + summaryRollupFindings, } from './data-model-rules.js'; +import { objectExtensionsByTarget, objectsAsServed } from './object-graph.js'; import type { IObjectQLEngine } from '@objectstack/spec/contracts'; import type { UserTextParams } from './finding-user-text.js'; @@ -2594,15 +2596,69 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ source: 'packages/lint/src/data-model-rules.ts', surfaces: CLI_AND_RUNTIME, runtimeTypes: ['object'], - run: (stack) => - lintSummaryRollups(Array.isArray(stack.objects) ? (stack.objects as unknown[]) : []).map((f) => ({ + // [#35143] The relation arm (`rollup/child-without-parent-reference`) + // asks whether the child has a foreign key back to the parent, and an + // object extension may add it, so it reads the child's fields as served: + // on the CLI the stack's own extensions folded in; at the `object` door + // the registry's served objects arriving as `context.objects`, pending + // `object_extension` drafts included (`storedObjectExtensions` is stated + // on `object_extension` writes only, so it is empty here). The aggregand + // arms keep reading the declared child field. + run: (stack, ctx) => { + const served = new Map(); + for (const obj of objectsAsServed(stack, ctx.storedObjectExtensions ?? []).objects) { + if (typeof obj.name !== 'string' || served.has(obj.name)) continue; + const fields = Array.isArray(obj.fields) + ? (obj.fields as AnyRec[]).filter((f) => typeof f?.name === 'string').map((f) => ({ name: f.name as string, def: f })) + : Object.entries((obj.fields ?? {}) as AnyRec).map(([name, def]) => ({ name, def })); + served.set(obj.name, fields); + } + return summaryRollupFindings( + Array.isArray(stack.objects) ? (stack.objects as unknown[]) : [], + (child) => served.get(child), + ).map((f) => ({ severity: f.severity === 'suggestion' ? ('info' as const) : f.severity, rule: f.rule, where: f.where, path: f.path, message: f.message, hint: f.fix ?? '', - })), + })); + }, + }, + // [#35143] Two field shapes that parse and publish and then do not do what + // the key or the name says (`lintFieldReferenceShapes`): `reference` on a + // type that reads none (error — the engine links nothing, and the record + // page's inline editor turns the field into a record picker that writes a + // record id into it), and a `lookup` / `master_detail` named like a count or + // a total (warning — a relationship stores one record's id, never a number). + // GATING on all three commands; on the runtime publish gate's `object` and + // `object_extension` writes, where the written entry's own fields are the + // whole input, so nothing the snapshot lacks can make it fire. The + // differential charges a write only with a finding it creates. + { + name: 'lintFieldReferenceShapes', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/data-model-rules.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['object', 'object_extension'], + run: (stack) => { + const extensions = [...objectExtensionsByTarget(stack).entries()].flatMap(([target, list]) => + list.map((ext) => ({ target, path: ext.path, fields: ext.fields })), + ); + return lintFieldReferenceShapes(Array.isArray(stack.objects) ? (stack.objects as unknown[]) : [], extensions).map( + (f) => ({ + severity: f.severity === 'suggestion' ? ('info' as const) : f.severity, + rule: f.rule, + where: f.where, + path: f.path, + message: f.message, + hint: f.fix ?? '', + }), + ); + }, }, // Two visible fields of one object served under one label // (`field-label-duplicate`): the platform's `owner_id` and an author's diff --git a/packages/lint/src/data-model-rules.field-reference-shapes.test.ts b/packages/lint/src/data-model-rules.field-reference-shapes.test.ts new file mode 100644 index 00000000000..8e790a47e4e --- /dev/null +++ b/packages/lint/src/data-model-rules.field-reference-shapes.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #35143: the second batch of publish-time checks, Data model family, the + * two field-shape rules of `lintFieldReferenceShapes`. Each has a pin that + * fires, a pin that stays silent, and the runtime publish gate's own verdict on + * the write it judges. The family's other lines are pinned in the harness of + * the rule they extend: the summary relation arm in + * `data-model-rules.summary-rollup.test.ts`, the approval detail table in + * `validate-approval-approvers.test.ts`, and the formula-over-a-bare-summary + * line (covered by `field/summary-without-operations`) in + * `validate-functional-completeness.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; +import { lintFieldReferenceShapes } from './data-model-rules.js'; + +type AnyRec = Record; + +const REFERENCE_ON_NON_REFERENCE_TYPE = 'field/reference-on-non-reference-type'; +const COUNT_NAMED_LOOKUP = 'field/count-named-lookup'; + +const rulesOf = (findings: readonly { rule: string }[]) => findings.map((f) => f.rule); + +describe('field/reference-on-non-reference-type', () => { + const object = (fields: AnyRec): AnyRec => ({ name: 'deal', label: 'Deal', fields: { name: { type: 'text', label: 'Name' }, ...fields } }); + + it('refuses reference on a text, number or date field, whose inline editor becomes the record picker', () => { + for (const def of [ + { type: 'text', label: 'Account', reference: 'account' }, + { type: 'number', label: 'Account', reference: 'account' }, + { type: 'date', label: 'Account', reference: 'account' }, + ]) { + const hit = lintFieldReferenceShapes([object({ account: def })]).filter((f) => f.rule === REFERENCE_ON_NON_REFERENCE_TYPE); + expect(hit, def.type).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'error', path: 'objects[0].fields.account.reference' }); + expect(hit[0].message).toContain('record picker'); + expect(hit[0].fix).toContain("{ type: 'lookup', reference: 'account' }"); + } + }); + + it('refuses it on a select too, saying only that it links nothing: the inline editor draws the select first', () => { + const hit = lintFieldReferenceShapes([ + object({ account: { type: 'select', label: 'Account', reference: 'account', options: [{ value: 'a', label: 'A' }] } }), + ]).filter((f) => f.rule === REFERENCE_ON_NON_REFERENCE_TYPE); + expect(hit).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'error', path: 'objects[0].fields.account.reference' }); + expect(hit[0].message).not.toContain('record picker'); + }); + + it('on a formula it says only that the key links nothing: the record page gives a formula no editor', () => { + const hit = lintFieldReferenceShapes([ + object({ account_name: { type: 'formula', label: 'Account', expression: 'record.name', reference: 'account' } }), + ]).filter((f) => f.rule === REFERENCE_ON_NON_REFERENCE_TYPE); + expect(hit).toHaveLength(1); + expect(hit[0].message).not.toContain('record picker'); + }); + + it('is silent on the four reference types, on a summary, and on a blank reference', () => { + const findings = lintFieldReferenceShapes([ + object({ + account: { type: 'lookup', label: 'Account', reference: 'account' }, + parent_deal: { type: 'master_detail', label: 'Parent', reference: 'deal' }, + rep: { type: 'user', label: 'Rep', reference: 'sys_user' }, + parent: { type: 'tree', label: 'Parent', reference: 'deal' }, + lines: { type: 'summary', label: 'Lines', reference: 'deal_line', summaryOperations: { object: 'deal_line', function: 'count' } }, + note: { type: 'text', label: 'Note', reference: '' }, + }), + ]); + expect(rulesOf(findings)).not.toContain(REFERENCE_ON_NON_REFERENCE_TYPE); + }); + + it('judges the fields an object extension adds, located in the extension', () => { + const cli = runAuthoringRules('validate', { + normalized: { objects: [object({})], objectExtensions: [{ extend: 'deal', fields: { region_code: { type: 'text', label: 'Region', reference: 'region' } } }] }, + parsed: { objects: [object({})], objectExtensions: [{ extend: 'deal', fields: { region_code: { type: 'text', label: 'Region', reference: 'region' } } }] }, + } as never); + const hit = cli.filter((f) => f.rule === REFERENCE_ON_NON_REFERENCE_TYPE); + expect(hit).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'error', path: 'objectExtensions[0].fields.region_code.reference' }); + }); + + it('the runtime publish gate refuses the object write and the object_extension write', () => { + const objectVerdict = runRuntimeAuthoringRules({ + type: 'object', + item: object({ account: { type: 'text', label: 'Account', reference: 'account' } }), + context: { objects: [] }, + }); + expect(rulesOf(objectVerdict.errors)).toContain(REFERENCE_ON_NON_REFERENCE_TYPE); + const extensionVerdict = runRuntimeAuthoringRules({ + type: 'object_extension', + item: { extend: 'deal', fields: { account: { type: 'text', label: 'Account', reference: 'account' } } }, + context: { objects: [object({})] }, + }); + expect(rulesOf(extensionVerdict.errors)).toContain(REFERENCE_ON_NON_REFERENCE_TYPE); + const clean = runRuntimeAuthoringRules({ + type: 'object', + item: object({ account: { type: 'lookup', label: 'Account', reference: 'account' } }), + context: { objects: [] }, + }); + expect(rulesOf(clean.errors)).not.toContain(REFERENCE_ON_NON_REFERENCE_TYPE); + }); +}); + +describe('field/count-named-lookup', () => { + const object = (fields: AnyRec): AnyRec => ({ name: 'account', label: 'Account', fields: { name: { type: 'text', label: 'Name' }, ...fields } }); + + it('warns on a lookup or master_detail named like a count or a total', () => { + for (const name of ['contact_count', 'total_amount', 'count', 'deal_totals']) { + const hit = lintFieldReferenceShapes([object({ [name]: { type: 'lookup', label: 'X', reference: 'contact' } })]).filter( + (f) => f.rule === COUNT_NAMED_LOOKUP, + ); + expect(hit, name).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'warning', path: `objects[0].fields.${name}.type` }); + expect(hit[0].fix).toContain("type: 'number'"); + } + }); + + it('is silent on names that only contain the letters (account, discount, country) and on a number named so', () => { + const findings = lintFieldReferenceShapes([ + object({ + account: { type: 'lookup', label: 'Account', reference: 'account' }, + discount: { type: 'lookup', label: 'Discount', reference: 'discount' }, + country: { type: 'lookup', label: 'Country', reference: 'country' }, + contact_count: { type: 'number', label: 'Contacts' }, + }), + ]); + expect(rulesOf(findings)).not.toContain(COUNT_NAMED_LOOKUP); + }); + + it('rides the runtime publish gate as an advisory, never a refusal', () => { + const verdict = runRuntimeAuthoringRules({ + type: 'object', + item: object({ contact_count: { type: 'lookup', label: 'Contacts', reference: 'contact' } }), + context: { objects: [] }, + }); + expect(rulesOf(verdict.errors)).not.toContain(COUNT_NAMED_LOOKUP); + expect(rulesOf(verdict.advisories)).toContain(COUNT_NAMED_LOOKUP); + }); +}); + diff --git a/packages/lint/src/data-model-rules.summary-rollup.test.ts b/packages/lint/src/data-model-rules.summary-rollup.test.ts index 7cd239753f6..0d3701691d4 100644 --- a/packages/lint/src/data-model-rules.summary-rollup.test.ts +++ b/packages/lint/src/data-model-rules.summary-rollup.test.ts @@ -34,6 +34,8 @@ import { ROLLUP_NON_NUMERIC_AGGREGAND, } from './data-model-rules.js'; import { explainRule } from './rule-explanations.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; const RULE = 'rollup/non-numeric-aggregand'; @@ -304,3 +306,136 @@ describe('[#22161] one-line verdicts — rollup/non-numeric-aggregand', () => { }); }); + +// #35143: the relation arm, a child with no reference back to the parent. + +const CHILD_WITHOUT_PARENT_REFERENCE = 'rollup/child-without-parent-reference'; +const rulesOf = (findings: readonly { rule: string }[]) => findings.map((f) => f.rule); +type AnyRec = Record; + +const ORDER = (fields: AnyRec = {}): AnyRec => ({ + name: 'order', + label: 'Order', + fields: { + name: { type: 'text', label: 'Name' }, + line_count: { + type: 'summary', + label: 'Lines', + summaryOperations: { object: 'order_line', function: 'count' }, + }, + ...fields, + }, +}); + +const ORDER_LINE = (fields: AnyRec = {}): AnyRec => ({ + name: 'order_line', + label: 'Order line', + fields: { + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + ...fields, + }, +}); + +const ORDER_FK = { order: { type: 'master_detail', label: 'Order', reference: 'order', required: true } }; + +describe('rollup/child-without-parent-reference', () => { + it('refuses a summary whose child has no lookup or master_detail back to the parent', () => { + const findings = lintSummaryRollups([ORDER(), ORDER_LINE()]); + const hit = findings.filter((f) => f.rule === CHILD_WITHOUT_PARENT_REFERENCE); + expect(hit).toHaveLength(1); + expect(hit[0]).toMatchObject({ + severity: 'error', + path: 'objects[0].fields.line_count.summaryOperations.object', + where: 'object "order" · field \'line_count\'', + }); + expect(hit[0].fix).toContain("reference: 'order'"); + }); + + it('refuses a relationshipField that names no field of the child', () => { + const order = ORDER({ + line_total: { + type: 'summary', + label: 'Total', + summaryOperations: { object: 'order_line', function: 'sum', field: 'amount', relationshipField: 'order_ref' }, + }, + }); + const hit = lintSummaryRollups([order, ORDER_LINE(ORDER_FK)]).filter((f) => f.rule === CHILD_WITHOUT_PARENT_REFERENCE); + expect(hit).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'error', path: 'objects[0].fields.line_total.summaryOperations.relationshipField' }); + }); + + it('is silent when the child points back, by lookup or master_detail, or names a real relationshipField', () => { + expect(rulesOf(lintSummaryRollups([ORDER(), ORDER_LINE(ORDER_FK)]))).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + const viaLookup = ORDER_LINE({ order: { type: 'lookup', label: 'Order', reference: 'order' } }); + expect(rulesOf(lintSummaryRollups([ORDER(), viaLookup]))).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + const named = ORDER({ + line_count: { + type: 'summary', + label: 'Lines', + summaryOperations: { object: 'order_line', function: 'count', relationshipField: 'order_code' }, + }, + }); + const withText = ORDER_LINE({ order_code: { type: 'text', label: 'Order code' } }); + expect(rulesOf(lintSummaryRollups([named, withText]))).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + }); + + it('is silent when the child is not in the walk (an unmanaged install writes the parent first)', () => { + expect(rulesOf(lintSummaryRollups([ORDER()]))).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + }); + + it('reads an injected column as the foreign key, as the engine does (a roll-up onto sys_user)', () => { + const user = { + name: 'sys_user', + label: 'User', + fields: { + name: { type: 'text', label: 'Name' }, + owned_lines: { type: 'summary', label: 'Owned lines', summaryOperations: { object: 'order_line', function: 'count' } }, + }, + }; + expect(rulesOf(lintSummaryRollups([user, ORDER_LINE()]))).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + }); + + it('reads a foreign key an object extension adds to the child, on the CLI', () => { + const extended = { + objects: [ORDER(), ORDER_LINE()], + objectExtensions: [{ extend: 'order_line', fields: { order: ORDER_FK.order } }], + }; + const cli = runAuthoringRules('validate', { normalized: extended, parsed: extended } as never); + expect(rulesOf(cli)).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + const bare = { objects: [ORDER(), ORDER_LINE()] }; + expect(rulesOf(runAuthoringRules('validate', { normalized: bare, parsed: bare } as never))).toContain( + CHILD_WITHOUT_PARENT_REFERENCE, + ); + }); + + it('a served child field whose reference is not a string does not point back, and throws nothing (as the engine\'s scan)', () => { + // At the door the child is the registry's served object, which can hold a + // carrier the parse would refuse. The engine's scan catches it and reads + // on; so does the relation arm, and the aggregand refusal of the same + // write still holds. + const unreadable = { type: 'lookup', label: 'Legacy', reference: { name: 'order' } }; + const order = ORDER({ + latest_line: { type: 'summary', label: 'Latest', summaryOperations: { object: 'order_line', function: 'max', field: 'shipped_at' } }, + }); + const servedChild = ORDER_LINE({ legacy: unreadable, ...ORDER_FK, shipped_at: { type: 'datetime', label: 'Shipped' } }); + const verdict = runRuntimeAuthoringRules({ type: 'object', item: order, context: { objects: [servedChild] } }); + expect(rulesOf(verdict.advisories)).not.toContain('authoring-rule-threw'); + expect(rulesOf(verdict.errors)).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + expect(rulesOf(verdict.errors)).toContain(RULE); + const onlyUnreadable = runRuntimeAuthoringRules({ + type: 'object', + item: ORDER(), + context: { objects: [ORDER_LINE({ legacy: unreadable })] }, + }); + expect(rulesOf(onlyUnreadable.advisories)).not.toContain('authoring-rule-threw'); + expect(rulesOf(onlyUnreadable.errors)).toContain(CHILD_WITHOUT_PARENT_REFERENCE); + }); + + it('the runtime publish gate refuses the object write, and passes it once the child points back', () => { + const refused = runRuntimeAuthoringRules({ type: 'object', item: ORDER(), context: { objects: [ORDER_LINE()] } }); + expect(rulesOf(refused.errors)).toContain(CHILD_WITHOUT_PARENT_REFERENCE); + const passed = runRuntimeAuthoringRules({ type: 'object', item: ORDER(), context: { objects: [ORDER_LINE(ORDER_FK)] } }); + expect(rulesOf(passed.errors)).not.toContain(CHILD_WITHOUT_PARENT_REFERENCE); + }); +}); diff --git a/packages/lint/src/data-model-rules.ts b/packages/lint/src/data-model-rules.ts index f16e42de7f9..4f376f8cc10 100644 --- a/packages/lint/src/data-model-rules.ts +++ b/packages/lint/src/data-model-rules.ts @@ -20,6 +20,7 @@ import { AGGREGATE_FIELD_TYPE_COMPATIBILITY, BOOLEAN_VALUE_TYPES, NUMERIC_VALUE_TYPES, + REFERENCE_VALUE_TYPES, isAggregateCompatibleWithFieldType, isApiOperationAllowed, fieldGroupsPlaceRelationship, @@ -30,6 +31,7 @@ import { type AggregationFunction, } from '@objectstack/spec/data'; import { VALUE_DOMAIN_FIELD_NAMES, type ValueDomain } from '@objectstack/spec/shared'; +import { injectedColumnDefsFor } from './system-fields.js'; export type Severity = 'error' | 'warning' | 'suggestion'; @@ -899,6 +901,26 @@ function acceptedChildTypesOf(fn: AggregationFunction): string { * package's object. A child that never arrives reads nothing — the roll-up * stays 0 / null — but nothing fails. * + * ## The child's reference back to the parent — judged once the child resolves + * + * A child the walk DOES hold is asked one more question first + * ({@link ROLLUP_CHILD_WITHOUT_PARENT_REFERENCE}): does the roll-up have a + * column to match a child row to its parent by? `ObjectQL.buildSummaryIndex` + * (`engine-summaries-and-expansion.ts`) takes `summaryOperations.relationshipField` + * when it is written, and otherwise the first `lookup` / `master_detail` field + * of the child whose `reference` names the parent. With neither, the index + * build `continue`s past the summary with nothing logged: it is never seeded + * and never recomputed, so it reads 0 / null on every parent while every child + * write reports success. Refused at `error`, mirroring that scan exactly — the + * same two types, the same comparison, the child's injected columns included + * (an `owner_id` / `created_by` back to `sys_user` is a real foreign key there) + * and its fields as served (an object extension may add the foreign key). A + * written `relationshipField` naming no field the child has is the same + * defect by another road: the summary is indexed, but no child row yields a + * parent id, so it is never recomputed and reads the same. One naming a field + * that exists is not second-guessed (a text column holding the parent id + * matches by equality all the same). + * * ## Silence, never a guess * * A child field that resolves to no declaration, or declares no type, is not @@ -911,6 +933,45 @@ function acceptedChildTypesOf(fn: AggregationFunction): string { * so `os lint` reports each finding exactly once. */ export function lintSummaryRollups(objects: any[]): LocatedLintIssue[] { + return summaryRollupFindings(objects); +} + +/** + * The rule id the roll-up's relation arm reports under: a summary whose child + * object holds no `lookup` / `master_detail` field naming the parent, or whose + * `summaryOperations.relationshipField` names no field of the child (see + * {@link lintSummaryRollups}, "The child's reference back to the parent"). + */ +const ROLLUP_CHILD_WITHOUT_PARENT_REFERENCE = 'rollup/child-without-parent-reference'; + +/** + * Does the engine's foreign-key scan take this child field as the parent's + * foreign key? A `reference` that is not a string makes `refOf` throw; the + * engine's scan catches exactly that and moves on to the next field, so one + * unreadable sibling hides no readable foreign key, and so does this: such a + * field does not point back. (A served child can carry one — a raw + * registration, or a row stored before the parse tightened.) + */ +function pointsBackTo(def: any, parent: string): boolean { + if (def?.type !== 'master_detail' && def?.type !== 'lookup') return false; + try { + return refOf(def) === parent; + } catch { + return false; + } +} + +/** + * {@link lintSummaryRollups}, with the child's fields AS SERVED when the + * caller holds them: `servedFieldsOf(child)` answers the child's fields with + * every object extension folded in (the registry's merge), or `undefined` to + * read the declaration. Only the relation arm reads it; the aggregand arms + * keep judging the declared child field, as they always did. + */ +export function summaryRollupFindings( + objects: any[], + servedFieldsOf?: (childName: string) => readonly { name: string; def: any }[] | undefined, +): LocatedLintIssue[] { const issues: LocatedLintIssue[] = []; if (!Array.isArray(objects) || objects.length === 0) return issues; @@ -934,6 +995,54 @@ export function lintSummaryRollups(objects: any[]): LocatedLintIssue[] { // Not judged — see the docblock's "The child object" section. if (!child) continue; + // The relation arm — see the docblock's "The child's reference back" + // section. It reports beside the aggregand arms, not instead of them: + // each is a fix of its own. + const childFields = servedFieldsOf?.(childName) ?? fieldEntries(child.fields); + const injected = injectedColumnDefsFor(child); + const relationshipField: unknown = ops?.relationshipField; + if (typeof relationshipField === 'string' && relationshipField !== '') { + const known = + relationshipField === 'id' || + childFields.some((f) => f.name === relationshipField) || + injected.has(relationshipField); + if (!known) { + issues.push({ + severity: 'error', + rule: ROLLUP_CHILD_WITHOUT_PARENT_REFERENCE, + where: fieldWhere(obj, fieldName), + message: + `summary field "${obj.name}.${fieldName}" rolls up ${childName} through ` + + `relationshipField '${relationshipField}', which is not a field of ${childName}: no child row ` + + `is matched to its parent, so the summary is never computed`, + path: `${fieldPath}.summaryOperations.relationshipField`, + fix: + `Name the ${childName} field that holds the ${obj.name} id in summaryOperations.relationshipField, ` + + `or add a lookup or master_detail field to ${childName} with reference: '${obj.name}'.`, + }); + } + } else { + const hasForeignKey = + childFields.some((f) => pointsBackTo(f.def, obj.name)) || + [...injected.values()].some((def) => pointsBackTo(def, obj.name)); + if (!hasForeignKey) { + issues.push({ + severity: 'error', + rule: ROLLUP_CHILD_WITHOUT_PARENT_REFERENCE, + where: fieldWhere(obj, fieldName), + // One verdict: why the engine skips it is the docblock's text. + message: + `summary field "${obj.name}.${fieldName}" rolls up ${childName}, which has no lookup or ` + + `master_detail field referencing ${obj.name}: the engine finds no child rows of a ${obj.name}, ` + + `so the summary is never computed and reads 0 or empty`, + path: `${fieldPath}.summaryOperations.object`, + fix: + `Add a field to ${childName} that points back: { type: 'master_detail', reference: '${obj.name}' } ` + + `(or a lookup), or roll up a child object that already references ${obj.name}.`, + }); + } + } + const childFieldName = ops?.field; if (typeof childFieldName !== 'string' || childFieldName === '') continue; const childType = fieldEntries(child.fields).find((f) => f.name === childFieldName)?.def?.type; @@ -976,6 +1085,157 @@ export function lintSummaryRollups(objects: any[]): LocatedLintIssue[] { return issues; } +// ─── Field shapes that save and do not work ───────────────────────── + +/** The rule id a `reference` on a type that reads none reports under. */ +const FIELD_REFERENCE_ON_NON_REFERENCE_TYPE = 'field/reference-on-non-reference-type'; + +/** The rule id a count- or total-named relationship field reports under. */ +const FIELD_COUNT_NAMED_LOOKUP = 'field/count-named-lookup'; + +/** + * Types whose stray `reference` the record page's inline editor never reads: + * the computed types it hands no editor (`formula`, `autonumber`), and the + * types it routes to their own widget before it looks at `reference` + * (`InlineFieldInput`: a `select` / `multiselect` with options — a `select` + * parses only with options or a picklist, whose options are served onto the + * field — `boolean`, the file-backed types, `markdown` and `textarea`). On + * these the key is merely inert. Every other non-reference type (`text`, + * `number`, `currency`, `percent`, the date types, …) falls through to the + * reference branch (`!!field.reference` routes the field to the record picker). + */ +const TYPES_EDITED_WITHOUT_REFERENCE: ReadonlySet = new Set([ + 'formula', + 'autonumber', + 'select', + 'multiselect', + 'boolean', + 'image', + 'avatar', + 'signature', + 'file', + 'video', + 'audio', + 'markdown', + 'textarea', +]); + +/** + * Non-reference types on which `reference` is still read, so it is not judged + * there: a `summary`'s `reference` names its child object to the roll-up + * nudge of this file (R7 reads `summaryOperations.object` first, then it) and + * to a blueprint builder that derives `summaryOperations` from a bare + * summary's `reference`. The engine reads `summaryOperations.object`. + */ +const REFERENCE_READ_OFF_TYPE: ReadonlySet = new Set(['summary']); + +/** Name tokens that say a field holds a quantity of records, not a link to one. */ +const QUANTITY_NAME_TOKENS: ReadonlySet = new Set(['count', 'counts', 'total', 'totals']); + +/** Is `name` (snake_case) a count or a total — one of its `_`-separated words says so? */ +function isQuantityName(name: string): boolean { + return name.toLowerCase().split('_').some((token) => QUANTITY_NAME_TOKENS.has(token)); +} + +/** One object extension's fields, located, as {@link lintFieldReferenceShapes} reads them. */ +export interface FieldShapeExtension { + /** The object it extends. */ + readonly target: string; + /** Its config path, e.g. `objectExtensions[0]`. */ + readonly path: string; + /** Its field records, each carrying `name`. */ + readonly fields: readonly Record[]; +} + +/** + * Two field shapes that parse, publish and then do not do what the name or the + * key says: + * + * - {@link FIELD_REFERENCE_ON_NON_REFERENCE_TYPE} (`error`): `reference` on a + * type that points at no record. Only `lookup`, `master_detail`, `user` and + * `tree` read it (`REFERENCE_VALUE_TYPES`, the set `referenceTargetOf` — the + * one arbiter `$expand` and the expand gate ask — answers for); the parse + * judges those four (a missing target, a foreign `user` target, a foreign + * `tree` target) and lets the key ride on every other type (`summary` aside, + * see {@link REFERENCE_READ_OFF_TYPE}). There the engine + * links nothing, and on a text, number or date field the record page's + * inline editor still reads it: such a field is edited with the record + * picker, which writes a record id into the column (the types the editor + * routes elsewhere first, see {@link TYPES_EDITED_WITHOUT_REFERENCE}, are + * told only that the key links nothing). One parse-free rule, so the CLI and the save door refuse it alike. + * - {@link FIELD_COUNT_NAMED_LOOKUP} (`warning`): a `lookup` / `master_detail` + * whose name says it holds a count or a total (`contact_count`, + * `total_amount`). A relationship stores the id of ONE record; the author + * (often an AI generator) meant a number or a roll-up. Advisory: a field can + * be named so on purpose, and nothing at run time refuses it. + * + * Reads the objects' own fields and the fields object extensions add, each + * located where it is written. Pure and total: a field with no string type is + * not judged. + */ +export function lintFieldReferenceShapes( + objects: any[], + extensions: readonly FieldShapeExtension[] = [], +): LocatedLintIssue[] { + const issues: LocatedLintIssue[] = []; + const judge = (ownerName: string, fieldName: string, def: any, fieldPath: string, where: string) => { + if (!def || typeof def !== 'object') return; + const type = def.type; + if (typeof type !== 'string') return; + const reference = typeof def.reference === 'string' ? def.reference.trim() : ''; + if (reference !== '' && !REFERENCE_VALUE_TYPES.has(type) && !REFERENCE_READ_OFF_TYPE.has(type)) { + const editor = TYPES_EDITED_WITHOUT_REFERENCE.has(type) + ? '' + : ', and the record page edits it with a record picker that writes a record id into it'; + issues.push({ + severity: 'error', + rule: FIELD_REFERENCE_ON_NON_REFERENCE_TYPE, + where, + message: + `${type} field "${ownerName}.${fieldName}" declares reference: '${reference}', which only lookup, ` + + `master_detail, user and tree fields read: it links no record${editor}`, + path: `${fieldPath}.reference`, + fix: + `To link a ${reference} record, make it { type: 'lookup', reference: '${reference}' }; ` + + `otherwise remove reference.`, + }); + } + if ((type === 'lookup' || type === 'master_detail') && isQuantityName(fieldName)) { + const target = reference !== '' ? reference : 'another object'; + issues.push({ + severity: 'warning', + rule: FIELD_COUNT_NAMED_LOOKUP, + where, + message: + `${type} field "${ownerName}.${fieldName}" is named like a count or a total, but a ${type} stores ` + + `the id of one ${target} record, never a number`, + path: `${fieldPath}.type`, + fix: + `For a quantity use type: 'number', or a summary with summaryOperations ` + + `{ object, function: 'count' | 'sum' } over the child records; if it links one record, rename it ` + + `to say which.`, + }); + } + }; + + if (Array.isArray(objects)) { + objects.forEach((obj, i) => { + if (!obj?.name) return; + for (const { name, def } of fieldEntries(obj.fields)) { + judge(obj.name, name, def, `objects[${i}].fields.${name}`, fieldWhere(obj, name)); + } + }); + } + for (const ext of extensions) { + for (const def of ext.fields) { + const name = typeof def?.name === 'string' ? def.name : ''; + if (!name) continue; + judge(ext.target, name, def, `${ext.path}.fields.${name}`, `object extension of "${ext.target}" · field '${name}'`); + } + } + return issues; +} + // ─── Rule engine ──────────────────────────────────────────────────── /** diff --git a/packages/lint/src/runtime-gate.object-formula-writes.test.ts b/packages/lint/src/runtime-gate.object-formula-writes.test.ts index 4fa252ebe7b..fb2f21e0a12 100644 --- a/packages/lint/src/runtime-gate.object-formula-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-formula-writes.test.ts @@ -364,7 +364,7 @@ describe('#33072 — the object_extension door judges an extension field\'s form it('`validateStackExpressions` is on the object_extension door, beside the vocabulary freeze', () => { // [#33217] And the two validation-rule artifact checks (regex, JSON schema). expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) - .toEqual(['validateStackExpressions', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); }); it('⭐ LIT — an extension formula calling an unregistered function (`sqrt`) is REFUSED, at the entry the build names', () => { @@ -422,7 +422,7 @@ describe('#33072 — the object_extension door judges an extension field\'s form const result = gateExtension(item); expect(result.errors, dump(result)).toEqual([]); expect(result.advisories, dump(result)).toEqual([]); - expect(result.rulesRun).toEqual(['validateStackExpressions', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(result.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); } }); diff --git a/packages/lint/src/runtime-gate.object-writes.test.ts b/packages/lint/src/runtime-gate.object-writes.test.ts index 7844c61232e..cf1a044fa0a 100644 --- a/packages/lint/src/runtime-gate.object-writes.test.ts +++ b/packages/lint/src/runtime-gate.object-writes.test.ts @@ -171,6 +171,10 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () // and its child object against the deployment's names; the door // controls are in the roll-up describe below. 'lintSummaryRollups', + // [#35143] The card names this door for the Data model family: a + // `reference` on a type that reads none (error) and a count-named + // relationship (warning), judged on the written object's own fields. + 'lintFieldReferenceShapes', // Joins as the card's ruling names it (error at the author door): two // visible fields an object serves under one label. The door cases are // in the duplicate-label describe below. @@ -570,6 +574,7 @@ describe('the object write door dispatches at the adjudicated scope (#4716)', () 'validateInertObjectDeclarations', // see the roster pin above 'lintAutonumberFormats', 'lintSummaryRollups', // see the roster pin above + 'lintFieldReferenceShapes', // [#35143] — see the roster pin above 'lintDuplicateFieldLabels', // see the roster pin above 'validateSecurityPosture', 'validateSecurityRoleWord', // [#19370] — see the roster pin above diff --git a/packages/lint/src/validate-approval-approvers.test.ts b/packages/lint/src/validate-approval-approvers.test.ts index 0f1120e8292..01bfc9d9f86 100644 --- a/packages/lint/src/validate-approval-approvers.test.ts +++ b/packages/lint/src/validate-approval-approvers.test.ts @@ -18,6 +18,7 @@ import { APPROVAL_APPROVER_CROSS_ORG_UNSUPPORTED, } from './validate-approval-approvers.js'; import { explainRule } from './rule-explanations.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; // [#22161] Each finding of the two converted ids is one verdict sentence; the // reasoning it used to carry is the id's `os explain` entry. Every call below @@ -1050,3 +1051,70 @@ describe('[#22161] one-line fixes — the expression and membership-tier ids', ( } }); }); + +// #35143: a lookup detail table the approval lock does not cover. + +const DETAIL_EDITABLE_WHILE_PENDING = 'approval-detail-editable-while-pending'; +const ruleIdsOf = (findings: readonly { rule: string }[]) => findings.map((f) => f.rule); + +describe('approval-detail-editable-while-pending', () => { + const EXPENSE = (fieldGroups?: Record[]): Record => ({ + name: 'expense', + label: 'Expense', + fields: { name: { type: 'text', label: 'Name' } }, + ...(fieldGroups ? { fieldGroups } : {}), + }); + const LINE = (fk: Record): Record => ({ + name: 'expense_line', + label: 'Expense line', + fields: { name: { type: 'text', label: 'Name' }, expense: { label: 'Expense', reference: 'expense', ...fk } }, + }); + const approvalFlow = (config: Record = {}): Record => ({ + name: 'expense_approval', + label: 'Expense approval', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'expense' } }, + { + id: 'approve', + type: 'approval', + label: 'Approve', + config: { approvers: [{ type: 'user', value: 'u1' }], ...config }, + }, + ], + edges: [{ id: 'e1', source: 'start', target: 'approve' }], + }); + const stack = (objects: Record[], config: Record = {}): Record => ({ objects, flows: [approvalFlow(config)] }); + + it('warns when a lookup child is a body table of the record under a locking approval', () => { + const primary = validateApprovalApprovers(stack([EXPENSE(), LINE({ type: 'lookup', relatedList: 'primary' })])); + const hit = primary.filter((f) => f.rule === DETAIL_EDITABLE_WHILE_PENDING); + expect(hit).toHaveLength(1); + expect(hit[0]).toMatchObject({ severity: 'warning', path: 'flows[0].nodes[1].config.lockRecord' }); + expect(hit[0].message).toContain('expense_line.expense'); + expect(hit[0].hint).toContain('master_detail'); + }); + + it('is silent for a master_detail child (the lock covers it), a lookup that is no body table, and lockRecord: false', () => { + const md = validateApprovalApprovers( + stack([EXPENSE([{ key: 'lines', label: 'Lines', relatedList: 'expense_line' }]), LINE({ type: 'master_detail', required: true })]), + ); + expect(ruleIdsOf(md)).not.toContain(DETAIL_EDITABLE_WHILE_PENDING); + const plain = validateApprovalApprovers(stack([EXPENSE(), LINE({ type: 'lookup' })])); + expect(ruleIdsOf(plain)).not.toContain(DETAIL_EDITABLE_WHILE_PENDING); + const optedOut = validateApprovalApprovers( + stack([EXPENSE(), LINE({ type: 'lookup', relatedList: 'primary' })], { lockRecord: false }), + ); + expect(ruleIdsOf(optedOut)).not.toContain(DETAIL_EDITABLE_WHILE_PENDING); + }); + + it('rides the runtime publish gate on the flow write as an advisory, never a refusal', () => { + const verdict = runRuntimeAuthoringRules({ + type: 'flow', + item: approvalFlow(), + context: { objects: [EXPENSE(), LINE({ type: 'lookup', relatedList: 'primary' })] }, + }); + expect(ruleIdsOf(verdict.errors)).not.toContain(DETAIL_EDITABLE_WHILE_PENDING); + expect(ruleIdsOf(verdict.advisories)).toContain(DETAIL_EDITABLE_WHILE_PENDING); + }); +}); diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 0b0062c4b96..e9c0e8d8131 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -29,6 +29,7 @@ * | approval-decision-outputs-reserved | error | #3447 P2 resume envelope | * | approval-approver-cross-org-unsupported | error | ADR-0105 D9 targeting | * | approval-approver-platform-admin-authored | error | save door only (see below) | + * | approval-detail-editable-while-pending | warning | detail-row lock follows master_detail only | * * The first two are mutually exclusive by construction — a bad *value* wins, * because its fix (`position`) differs from the deprecation's fix @@ -52,6 +53,7 @@ import { normalizeDecisionOutputs, } from '@objectstack/spec/automation'; import { BUILTIN_MEMBERSHIP_ROLES } from '@objectstack/spec'; +import { fieldGroupsPlaceRelationship, isBodyTableRelationship } from '@objectstack/spec/data'; import { collectCelRootIdentifiers } from '@objectstack/formula'; import { flowDisplayLabel, flowNodeLabel, walkFlowNodes } from './flow-walk.js'; import { recordsOf } from './object-graph.js'; @@ -70,6 +72,56 @@ export const APPROVAL_DECISION_OUTPUTS_RESERVED = 'approval-decision-outputs-res export const APPROVAL_APPROVER_CROSS_ORG_UNSUPPORTED = 'approval-approver-cross-org-unsupported'; export const APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED = 'approval-approver-platform-admin-authored'; +/** + * The rule id of an approval whose record shows a detail table the approval + * lock does not cover (see {@link unlockedDetailTablesOf}). + */ +const APPROVAL_DETAIL_EDITABLE_WHILE_PENDING = 'approval-detail-editable-while-pending'; + +/** The object a flow's runs carry as `record`: its start node's `config.objectName`. */ +function flowStartObjectName(flow: AnyRec): string | undefined { + const nodes = Array.isArray(flow.nodes) ? (flow.nodes as AnyRec[]) : []; + const start = nodes.find((n) => n && typeof n === 'object' && n.type === 'start'); + const config = start && typeof start.config === 'object' && start.config !== null ? (start.config as AnyRec) : {}; + return typeof config.objectName === 'string' && config.objectName.trim() !== '' ? config.objectName : undefined; +} + +/** + * The `lookup` children a record page of `parent` draws as a table in its own + * body — its detail rows — which a pending approval of a `parent` record does + * NOT lock. + * + * A locking approval (`lockRecord`, default `true`) refuses edits of the record + * (`bindRecordLockHook`) and of the rows of every `master_detail` child under + * it (`bindDetailRowLockHook`, whose `masterEdgesOf` reads `master_detail` + * fields only, `plugins/plugin-approvals/src/lifecycle-hooks.ts`). A child + * linked by a `lookup` is outside that lock, yet when it is a body table + * (`relatedList: 'primary'`, or a field group of the parent places it — + * `isBodyTableRelationship`) the approver reads its rows as part of the record + * under approval while anyone may still change them. A `lookup` child that is + * not a body table is a related record, not the record's detail, and is not + * reported; nor is a multi-value lookup, which a body table never draws. + */ +function unlockedDetailTablesOf( + objects: readonly AnyRec[], + parent: AnyRec, +): Array<{ child: string; field: string }> { + const out: Array<{ child: string; field: string }> = []; + const parentName = parent.name; + if (typeof parentName !== 'string') return out; + for (const child of objects) { + if (typeof child.name !== 'string') continue; + for (const field of recordsOf(child.fields)) { + if (field.type !== 'lookup' || field.multiple === true || field.reference !== parentName) continue; + const name = typeof field.name === 'string' ? field.name : ''; + if (!name) continue; + const placedByGroup = fieldGroupsPlaceRelationship(parent.fieldGroups, child.name, name); + if (isBodyTableRelationship(field, { placedByGroup })) out.push({ child: child.name, field: name }); + } + } + return out; +} + /** What {@link validateApprovalApprovers} needs to know about the door that runs it. */ export interface ValidateApprovalApproversOptions { /** @@ -398,6 +450,7 @@ export function validateApprovalApprovers( // Stack-level, so it is read once and every node is judged on the same // evidence — a per-node re-read would let two identical nodes disagree. const managerChainWired = stackWiresManagerChain(stack); + const objects = recordsOf(stack.objects); for (let fi = 0; fi < flows.length; fi++) { const flow = flows[fi]; @@ -409,6 +462,9 @@ export function validateApprovalApprovers( // Every node, INCLUDING those nested in try_catch / loop / parallel regions // — an approval inside a loop body is still an approval (#4380). const walked = walkFlowNodes(flow, `flows[${fi}]`); + // The detail-table advisory is the flow's, not each node's: said once, at + // the first approval step that locks the record. + let detailTablesReported = false; for (let ni = 0; ni < walked.length; ni++) { const { node, path: nodePath } = walked[ni]; @@ -419,6 +475,31 @@ export function validateApprovalApprovers( const approvers = Array.isArray(cfg.approvers) ? (cfg.approvers as AnyRec[]) : []; const where = `flow "${flowName}" · node "${nodeId}"`; + // A locking approval whose record shows a lookup child as its own detail + // table: those rows stay editable while the record waits for approval. + if (!detailTablesReported && cfg.lockRecord !== false) { + const objectName = flowStartObjectName(flow as AnyRec); + const parent = objectName ? objects.find((o) => o.name === objectName) : undefined; + if (parent) { + detailTablesReported = true; + for (const { child, field } of unlockedDetailTablesOf(objects, parent)) { + findings.push({ + severity: 'warning', + rule: APPROVAL_DETAIL_EDITABLE_WHILE_PENDING, + where, + path: `${nodePath}.config.lockRecord`, + message: + `locks a ${objectName} record while it waits for approval, but the ${child} rows its record page ` + + `shows as a table through the lookup "${child}.${field}" stay editable: the lock covers only ` + + `master_detail children`, + hint: + `Make ${child}.${field} a master_detail field so its rows lock with the ${objectName} record, or ` + + `take the ${child} table out of the ${objectName} record body if its rows may change during approval.`, + }); + } + } + } + for (let ai = 0; ai < approvers.length; ai++) { const a = approvers[ai]; if (!a || typeof a !== 'object') continue; diff --git a/packages/lint/src/validate-functional-completeness.test.ts b/packages/lint/src/validate-functional-completeness.test.ts index aea2580ba66..c9daefdaa3d 100644 --- a/packages/lint/src/validate-functional-completeness.test.ts +++ b/packages/lint/src/validate-functional-completeness.test.ts @@ -20,6 +20,7 @@ import { FUNCTIONAL_COMPLETENESS_RULES } from '@objectstack/spec/kernel'; import { runAuthoringRules, splitBySeverity } from './authoring-rules.js'; import { explainRule } from './rule-explanations.js'; import { validateFunctionalCompleteness } from './validate-functional-completeness.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; const bareSummary = { type: 'summary' }; @@ -483,3 +484,24 @@ describe('every completeness rule id has an `os explain` entry carrying what its for (const fact of MOVED[rule]) expect(text, `${rule} explanation names ${fact}`).toContain(fact); }); }); + +// #35143: the Data model family's line "a formula reading a summary field that has no +// configuration" is this rule's. The summary the formula reads is refused at its root. +describe('a formula reading a summary with no configuration — covered by field/summary-without-operations', () => { + it('the gate refuses the bare summary the formula reads, so the formula never ships reading a zero', () => { + const item = { + name: 'venue', + label: 'Venue', + fields: { + name: { type: 'text', label: 'Name' }, + capacity: { type: 'number', label: 'Capacity' }, + booked: { type: 'summary', label: 'Booked' }, + occupancy: { type: 'formula', label: 'Occupancy', expression: 'record.booked / record.capacity' }, + }, + }; + const verdict = runRuntimeAuthoringRules({ type: 'object', item, context: { objects: [] } }); + const hit = verdict.errors.filter((f) => f.rule === 'field/summary-without-operations'); + expect(hit).toHaveLength(1); + expect(hit[0].path).toContain('booked'); + }); +}); diff --git a/packages/lint/src/validate-security-posture.runtime-surface.test.ts b/packages/lint/src/validate-security-posture.runtime-surface.test.ts index 39226eb5871..3a7c2f2d78c 100644 --- a/packages/lint/src/validate-security-posture.runtime-surface.test.ts +++ b/packages/lint/src/validate-security-posture.runtime-surface.test.ts @@ -568,7 +568,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 expect(stackKeyForType('object_extension')).toBe('objectExtensions'); // [#33217] The validation-rule artifact checks (regex, JSON schema) cross on it too. expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name)) - .toEqual(['validateStackExpressions', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + .toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); const roleSelect = { type: 'select', label: 'Group Function', options: [{ value: 'l1', label: 'Tier 1' }] }; const refused = runRuntimeAuthoringRules({ @@ -583,7 +583,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 // positional and names it. expect(refused.errors[0].path).toBe('objectExtensions[0].fields.role.name'); expect(refused.errors[0].where).toBe('field "sd_agent.role"'); - expect(refused.rulesRun).toEqual(['validateStackExpressions', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(refused.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); // The two labels the entry serves, at the same door. const labelled = runRuntimeAuthoringRules({ @@ -603,7 +603,7 @@ describe('validateSecurityPosture at the runtime publish surface (#7576 → #830 }); expect(clean.errors).toEqual([]); expect(clean.advisories).toEqual([]); - expect(clean.rulesRun).toEqual(['validateStackExpressions', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); + expect(clean.rulesRun).toEqual(['validateStackExpressions', 'lintFieldReferenceShapes', 'lintDuplicateFieldLabels', 'validateSecurityRoleWord', 'validateRuleCompilability', 'validateRuleSchemaFormats']); // Not a context row: the baseline carries no `objectExtensions`, and the // candidate holds exactly the written item. diff --git a/packages/objectql/src/protocol-batch-object-registration.test.ts b/packages/objectql/src/protocol-batch-object-registration.test.ts index d03adf90a6d..d4d989cdcaa 100644 --- a/packages/objectql/src/protocol-batch-object-registration.test.ts +++ b/packages/objectql/src/protocol-batch-object-registration.test.ts @@ -169,11 +169,13 @@ const followingLine = (ns: string, name: string, pointer: string) => ({ amount: { name: 'amount', type: 'currency', label: 'Amount', currencyConfig: { currencyMode: 'record', currencyField: pointer } }, }, }); -/** A child line whose amount carries its OWN currency per row. */ +/** A child line whose amount carries its OWN currency per row. It points back to the + * roll-up's parent too, so the roll-up has a foreign key and only D6's door refuses it. */ const ownCurrencyLine = (ns: string) => ({ name: `${ns}_own_line`, label: 'Own line', sharingModel: 'private', fields: { invoice: { name: 'invoice', type: 'master_detail', reference: `${ns}_invoice`, label: 'Invoice' }, + own_total: { name: 'own_total', type: 'lookup', reference: `${ns}_own_total`, label: 'Own total' }, currency_code: { name: 'currency_code', type: 'text', label: 'Currency', ...CODE }, amount: { name: 'amount', type: 'currency', label: 'Amount', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }, }, diff --git a/packages/spec/src/migrations/entries/semantic/18.publish-refuses-data-model-fields-that-save-and-do-not-work.ts b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-data-model-fields-that-save-and-do-not-work.ts new file mode 100644 index 00000000000..93ebb27a1d9 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.publish-refuses-data-model-fields-that-save-and-do-not-work.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the Data model family of the second batch of +// author-time rules (#35143) that refuse, at publish and in `os validate` / +// `build`, an object the schema still accepts but whose roll-up never computes +// or whose field carries a `reference` nothing links through. Notice only: no +// key is removed and no D2 conversion exists, because each fix is a choice only +// the author can make (which child field points back, which type a field is). +export const entry: SemanticMigration = { + id: 'publish-refuses-data-model-fields-that-save-and-do-not-work', + surface: + 'Two author-time object errors, run by the runtime publish gate and by `os validate` / `lint` / `compile` / `build`: ' + + 'a `summary` field whose child object has no `lookup` / `master_detail` field referencing the parent, or whose ' + + '`summaryOperations.relationshipField` names no field of the child (`rollup/child-without-parent-reference`); a ' + + '`reference` on a field type that reads none, anything but `lookup`, `master_detail`, `user`, `tree` and `summary` ' + + '(`field/reference-on-non-reference-type`)', + replacement: + 'Give the child a field that points back (`{ type: \'master_detail\', reference: \'\' }` or a lookup), or name ' + + 'the child field that holds the parent id in `summaryOperations.relationshipField`; make a field that links a record ' + + 'a `lookup` (`{ type: \'lookup\', reference: \'\' }`), or remove `reference` from it', + reason: + 'Each object parses and publishes, then does not work: the engine finds no child rows of a parent for a roll-up with no ' + + 'foreign key, so the summary is never indexed, and one whose `relationshipField` names no child field is indexed and ' + + 'never recomputed; either reads 0 or empty while every child write reports success. A `reference` on a type that ' + + 'reads none links nothing, and on a text, number or date field the record page edits it with a record picker that ' + + 'writes a record id into it. Stored objects are not rewritten or refused at boot. The next ' + + 'publish of an object that carries one of the two errors is refused with the fix named. Two warnings join them ' + + '(`field/count-named-lookup`, a relationship field named like a count or a total; ' + + '`approval-detail-editable-while-pending`, a lookup child drawn as a table in the record body of a record under a ' + + 'locking approval, whose rows the lock does not cover), which refuse nothing and make `os validate --strict` exit 1 ' + + 'as any warning does.', + acceptanceCriteria: + 'os validate reports neither error; a publish of every object the package carries succeeds.', +}; diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.referenceNameVisible-29629.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.referenceNameVisible-29629.test.tsx index 6a1a93e4fc3..0d98d91ecf6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.referenceNameVisible-29629.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.referenceNameVisible-29629.test.tsx @@ -24,6 +24,11 @@ import { render, screen, cleanup, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { FieldSchema } from '@objectstack/spec/data'; import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; +// The inspector loads the CEL lint and formula engines through dynamic +// imports; pull them in at module top so their first load is paid at +// collection, not inside a case's bounded wait. +import '@objectstack/lint'; +import '@objectstack/formula'; const h = vi.hoisted(() => { const CATALOG: Array> = [{ name: 'vendor', label: 'Vendor' }]; @@ -195,3 +200,37 @@ describe('referenceNameVisible in the field inspector', () => { expect(screen.getByRole('checkbox', { name: '不可读时显示名称' })).toBeTruthy(); }); }); + +// The publish gate refuses `reference` on a type that reads none +// (`field/reference-on-non-reference-type`), and the Related Object picker is +// drawn only on lookup / master_detail / tree, so a retype to such a type +// removes the target, as it removes `referenceNameVisible` above. +describe('a retype removes reference on a type that reads none', () => { + it('a retype from lookup to text removes reference, so the save is not refused', async () => { + const { saved } = renderField(LOOKUP); + + await retypeTo('Text'); + + expect(saved().type).toBe('text'); + expect(has(saved(), 'reference')).toBe(false); + expect(rejections(saved())).toEqual([]); + }); + + it('a retype from lookup to master_detail keeps reference (it reads it too)', async () => { + const { saved } = renderField(LOOKUP); + + await retypeTo('Master-Detail'); + + expect(saved().type).toBe('master_detail'); + expect(saved().reference).toBe('vendor'); + }); + + it('a stored text field that still carries reference saves without it on the next edit', async () => { + const { saved } = renderField({ type: 'text', label: 'Vendor', reference: 'vendor' }); + + await retypeTo('Number'); + + expect(saved().type).toBe('number'); + expect(has(saved(), 'reference')).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx index a9c40a53a61..1b32da888f1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx @@ -119,6 +119,7 @@ import { ObjectPicker, useObjectCatalog } from './ObjectPicker.js'; import { useObjectFields } from '../previews/useObjectFields.js'; import { readFields, + readsReference, writeFields, toFieldNameLoose, toFieldNameOrEmpty, @@ -1283,7 +1284,12 @@ export function ObjectFieldInspector({ 'deleteBehavior' in def && (nextDeleteBehaviors.length === 0 || (def.deleteBehavior === 'set_null' && !nextDeleteBehaviors.includes('set_null'))); - if (keepsPicklist && !dropsKinds && !dropsNameVisible && !dropsDeleteBehavior) { + // The publish gate refuses a `reference` on a type that reads none + // (`field/reference-on-non-reference-type`), and the Related Object picker + // is drawn only on `lookup` / `master_detail` / `tree`, so a retype to such + // a type removes the target: the author could not see or clear it there. + const dropsReference = 'reference' in def && !readsReference(nextType); + if (keepsPicklist && !dropsKinds && !dropsNameVisible && !dropsDeleteBehavior && !dropsReference) { patchDef(requireMaster ? { type: nextType, required: true } : { type: nextType }); return; } @@ -1293,6 +1299,7 @@ export function ObjectFieldInspector({ if (dropsKinds) nextDef.options = withoutOptionKinds(def.options as unknown[]); if (dropsNameVisible) delete nextDef.referenceNameVisible; if (dropsDeleteBehavior) delete nextDef.deleteBehavior; + if (dropsReference) delete nextDef.reference; const nextEntries = [...view.entries]; nextEntries[idx] = { ...entry, def: nextDef }; writeView({ shape: view.shape, entries: nextEntries }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.test.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.test.ts index 40c19796b1a..ad10a95582e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.test.ts @@ -24,8 +24,10 @@ import { groupArrangement, groupMembership, diffFields, + readsReference, type FieldsView, } from './object-fields-io'; +import { REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; /* ─────────────── readGroups ─────────────── */ @@ -588,3 +590,43 @@ describe('groupArrangement — the whole arrangement an installed object\'s .cus expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); }); }); + +describe('readFields — a reference on a type that reads none is stripped at the read door', () => { + // A shipped inspector kept `reference` on a retype, and the designer shows + // no control for it on such a type, while the publish gate refuses it + // (`field/reference-on-non-reference-type`). Stripped on read, the next + // edit-and-save writes the field without it. + it('drops it from a text / number / select field, in both draft shapes', () => { + const record = readFields({ + vendor_name: { type: 'text', label: 'Vendor', reference: 'vendor' }, + vendor_no: { type: 'number', label: 'No', reference: 'vendor' }, + tier: { type: 'select', label: 'Tier', reference: 'vendor', options: [{ value: 'a', label: 'A' }] }, + }); + for (const e of record.entries) expect(e.def, e.name).not.toHaveProperty('reference'); + const array = readFields([{ name: 'vendor_name', type: 'text', label: 'Vendor', reference: 'vendor' }]); + expect(array.entries[0].def).toEqual({ type: 'text', label: 'Vendor' }); + expect(writeFields(record)).toMatchObject({ vendor_name: { type: 'text', label: 'Vendor' } }); + }); + + it('keeps it on the types that read it: lookup, master_detail, tree, user and summary', () => { + const view = readFields({ + a: { type: 'lookup', label: 'A', reference: 'vendor' }, + b: { type: 'master_detail', label: 'B', reference: 'vendor' }, + c: { type: 'tree', label: 'C', reference: 'po' }, + d: { type: 'user', label: 'D', reference: 'sys_user' }, + e: { type: 'summary', label: 'E', reference: 'po_line', summaryOperations: { object: 'po_line', function: 'count' } }, + }); + for (const e of view.entries) expect(e.def, e.name).toHaveProperty('reference'); + }); + + it('CONTROL — leaves a type the spec does not declare as it is', () => { + const view = readFields({ legacy: { type: 'not_a_spec_type', label: 'L', reference: 'vendor' } }); + expect(view.entries[0].def).toHaveProperty('reference', 'vendor'); + }); + + it('readsReference is the spec\'s REFERENCE_VALUE_TYPES plus summary', () => { + for (const t of REFERENCE_VALUE_TYPES) expect(readsReference(t), t).toBe(true); + expect(readsReference('summary')).toBe(true); + for (const t of ['text', 'number', 'select', 'formula', 'date', undefined]) expect(readsReference(t), String(t)).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.ts index 7d646795841..e26b086d653 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/object-fields-io.ts @@ -24,6 +24,7 @@ // what widened an unrelated test's partial mock into a suite failure under // the prior shape. A subpath import never pulls the barrel in. import { retiredFieldKeysFor } from '@object-ui/types/internal/retired-field-keys'; +import { FieldType as SpecFieldType, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; import type { FieldTypeId } from './field-types.js'; @@ -167,6 +168,50 @@ function stripRetiredFieldKeys(def: Record): Record = new Set(SpecFieldType.options); + +/** + * Drop a `reference` from a field whose declared type reads none. + * + * A shipped build of the field inspector kept the key on a retype (a `lookup` + * retyped to `text` saved as text with the old target still on it), and the + * designer draws the Related Object picker only on `lookup` / `master_detail` + * / `tree`, so on such a field the key is neither shown nor clearable — while + * the publish gate refuses the object at every later publish, whatever the + * edit, naming a key the designer does not show. Stripping it here, the single + * read door for `draft.fields`, makes the next edit-and-save of such a draft + * come out publishable, as {@link stripRetiredFieldKeys} does for a retired + * key. Nothing is lost: on these types the key linked no record. + * + * Judged only on a type the spec declares: an undeclared or retired type + * string is left as it is (the parse refuses it first, and its `reference` + * may be what a migration needs). + */ +function stripStrayReference(def: Record): Record { + if (!(SPEC_REFERENCE_KEY in def)) return def; + const type = def.type; + if (typeof type !== 'string' || !SPEC_FIELD_TYPES.has(type) || readsReference(type)) return def; + const { [SPEC_REFERENCE_KEY]: _dropped, ...kept } = def; + return kept; +} + +/** Both read-door strips, in order: a retired key first (it may recover a `reference`). */ +function normalizeReadDef(def: Record): Record { + return stripStrayReference(stripRetiredFieldKeys(def)); +} + export interface FieldEntry { /** Canonical snake_case key. */ name: string; @@ -188,7 +233,7 @@ export function readFields(fieldsInput: unknown): FieldsView { const { name, ...rest } = raw ?? {}; return { name: typeof name === 'string' && name ? name : `field_${i + 1}`, - def: stripRetiredFieldKeys(rest as Record), + def: normalizeReadDef(rest as Record), }; }), }; @@ -197,7 +242,7 @@ export function readFields(fieldsInput: unknown): FieldsView { return { shape: 'record', entries: Object.entries(fieldsInput as Record>).map( - ([name, def]) => ({ name, def: stripRetiredFieldKeys({ ...(def ?? {}) }) }), + ([name, def]) => ({ name, def: normalizeReadDef({ ...(def ?? {}) }) }), ), }; }