Skip to content

Commit 27d042f

Browse files
fix(lint)!: os build and the object_extension publish door judge each validation rule an object extension adds by the object's own rule pass (#33205)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao9hFPRZ1WJgvAp5Am1CGguA)_ Fixes #33154 Clause-②: no (narrowing) — `os build`, `os validate`, `os lint` and the runtime `object_extension` publish door (Studio, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuse an extension whose validation rule carries a `condition` or `when` that the same rule declared on the object is refused for. No exported type or signature changes. Measured first-party exposure: 0 extension entries carry a validation rule (`examples/app-showcase` and `packages/plugins/plugin-auth` extensions add fields only; HotCRM `origin/main` 92519d8 has no `objectExtensions` in code), so nothing first-party is newly refused. Two repository test fixtures carried the refused shape and are repaired here (see Acceptance notes). Metadata-protocol: narrowed Skills-docs: none owed — this PR edits `content/docs/deployment/validating-metadata.mdx` (the object extension door paragraph names the rule pass); `skills/objectstack-data` teaches validation rules and `defineObjectExtension({ extend, fields })` without saying an extension's rules are exempt, so the build and the door now give the verdict the object's own rules already get. Precedent followed: #33072 (PR #33119), which declared the same `no (narrowing)` / `narrowed` pair for the computed fields an extension adds. ## 维护者速读 - 改了什么:对象扩展(`objectExtensions` / Studio 发布的 `object_extension`)里的 `validations` 校验规则,现在在 `os build` 和运行时发布口都按对象自身校验规则的同一套检查判定(同一个函数 `judgeValidationRule`、同一条规则 id `expression-invalid`),位置为 `object '对象' · objectExtensions[0] · validation '规则'`。 - 为什么改:注册表会把扩展的校验规则按名字合并到目标对象上,每次保存记录都会执行,但此前两道门都不判定;字段拼错、函数不存在、可空字段没加空值守卫,都要等到最终用户保存记录时才失败(空值情况下会拒绝每次保存)。 - 风险与回滚:收窄;第一方实测 0 处扩展校验规则受影响。仓库测试里有 2 个 fixture 正好是被拒的形状(一个裸字段 `region__c`,一个未加空值守卫的 `record.qx_credit > 5000000`),已在本 PR 修正。草稿保存不受影响,已存的行再次发布时才判。回滚即 revert。 - 先看:`packages/lint/src/validate-expressions.ts`(`judgeValidationRule`、扩展遍历里新增的循环、扩展写入时去掉注入系统列的一行)、`packages/lint/src/runtime-gate.object-formula-writes.test.ts`(#33154 一节)、`packages/runtime/src/domains/meta-object-extension-item.test.ts`(真实发布口 4 条)。 - 两分钟验证:`pnpm --filter @objectstack/lint exec vitest run src/runtime-gate.object-formula-writes.test.ts -t 33154`,预期 9 条全过:拼错字段与未知函数被拒、build 与发布口结论逐条相同(含平台注入的系统列 `created_at`:两边都接受)、合法规则与读同一扩展新增字段的规则通过。 - 需要你做的:无,席位落地。 - 席位意见:落地。契约复审 PASS(评论 6878859677,Head-sha `9d07ffa0`),无 must-fix / should-fix,4 个 nit 记为接受的偏差;上一轮 FAIL(6870963898)的 F1、F2、N2、N3 已在树上核实解决。后续卡 #33216、#33217、#33246。复审由实现本 PR 的同一会话采纳隔离子代理的结论,依据维护者 2026-11-14 14:17Z「你现在可以自己契约复审了」。非受管面,579 行。 ## What changes **Lint: one rule pass, two walks.** - **`packages/lint/src/validate-expressions.ts`.** - The per-rule body of the object walk is hoisted into one closure, `judgeValidationRule(rule, { objectName, locus, rulePath })`. It covers the `condition` and `when` (with the one-hop checks the rule validator serves), every nested `then` / `otherwise` predicate, the `parent` root verdict and the null-guard gate. The object walk's loop now calls it, and its findings, order and key paths are byte for byte what they were. - #32875's extension walk calls the same closure for each `validations[]` rule of each entry that `objectExtensionsByTarget` keeps (the fold already carried them). A `record.FIELD` read resolves against the target's fields as served (`fieldIndex`, over `objectsAsServed`), so a field this extension or a sibling package's extension adds resolves, and a field nothing serves is unknown. An undeclared target is judged on what does not depend on its fields, as its formulas are. The hop checks (`refuseUndeclaredHopField`, `storedMetadataBodyReferencesFor`) read the declared objects, so the leaf of a one-hop read through a reference an extension adds is not judged (see Acceptance notes). - The locator is `object 'TARGET' · objectExtensions[i] · validation 'RULE'`, and the key path is `ENTRY.validations[k].SLOT`. The door's 422 carries that path as is (`objectExtensions[0].validations[0].condition`); only a draft read's `_diagnostics` re-spell it item-relative (`validations.0.condition`). - On an `object_extension` write the door's live objects are read through `stripInjectedSystemColumns` (`@objectstack/metadata-core`), as `authored-site-expression.ts` reads served objects. The registry serves an object with the system columns it injects (`created_at`, `owner_id`, …) declared, `required: false` and no default, so the null-guard gate judged `record.created_at > …` as an unguarded nullable operand and refused at the door what `os build` accepts. Stripped, the indexes re-derive those columns as the build does: known fields, never judged nullable. - On an `object_extension` write the door still runs ONE pass, the extension walk, and returns after it (#33072's `extensionWrite`). The rules join that one pass. - **`packages/lint/src/authoring-rules.ts`.** Comment only (surface amendment 6868654518), on the expression rule's `runtimeTypes`. **Docs, migration and changeset.** - **`content/docs/deployment/validating-metadata.mdx`.** One sentence in the object extension door paragraph. The CEL row's columns do not change: the `ᵒˣ` mark landed with #33072. - **`packages/spec/src/migrations/entries/semantic/18.object-extension-validation-rule-expression-judged.ts`.** The ADR-0087 D3 entry. Its printed guidance carries no tracker id. There is no D2 conversion, because how a refused rule is repaired is a fact only the author holds. - **`.changeset/33154-object-extension-validation-rules-judged.md`.** `@objectstack/lint` minor and `@objectstack/spec` minor, with both declaration lines, a BREAKING banner (Before / Now / Unchanged / Fix) that names the null-guard refusal and its fix, and the ADR-0087 disposition marker. ## Tests 1. **`packages/lint/src/runtime-gate.object-formula-writes.test.ts`**, a new top-level describe `#33154` with 9 cases, at the real gate (`runRuntimeAuthoringRules`) and the build (`runAuthoringRules('build', …)`): - LIT: a misspelt field is refused at the entry, with its key path. - LIT: an unregistered function in a nested `then` branch is refused at the branch. - PARITY: on one shared input set (a typo, `sqrt`, a bare reference), the door's findings deep-equal the build's. - PARITY: with the objects as the registry serves them (`applyInjectedSystemColumns`), an unguarded ordering over `record.created_at` is accepted at the door as at the build, and one over a declared nullable field (`record.amount > 0`) is refused at both, the findings deep-equal. - CONTROL: a valid rule, a rule reading a field the same extension adds, and a gated one-hop read are clean at both doors. - SIBLING: a rule reading a field a sibling package's extension adds resolves at the build, and a misspelling of it is refused at `packages[2].manifest.objectExtensions[0]`. - An undeclared target is judged on what does not depend on its fields. - One pass: the extension write does not judge the target's own broken rule. - CONTROL: the object save door still judges the object's own rule at its own location. 2. **`packages/runtime/src/domains/meta-object-extension-item.test.ts`**, a new describe `[#33154]` with 4 cases, through the real `saveMetaItem` + `publishMetaItem`: - LIT: a rule reading `record.nmae` gets 422 `INVALID_METADATA` with issue `expression-invalid` at the build's location and path. The rule is not served, and the row stays a draft. - CONTROL: a valid rule publishes and is served on the account. - PARITY: `record.created_at > timestamp(…)` with no guard publishes and is served (the account as served declares `created_at`), and `os build` (`runAuthoringRules('build', …)` on the account as authored and the same entry) reports nothing; an unguarded `record.bonus__c > 100` on a field the same entry adds is refused at both, with the same rule, location and path. - LIT (republish, #33072's S1 shape): dropping a field that the extension's own rule still reads is refused, because the stored self lends it nothing. 3. **Repaired by this change** (stale fixtures, each the refused shape): - `meta-object-extension-item.test.ts`: a bare `region__c == null` becomes `record.region__c == null`. - `packages-disable-module-extension-fields.test.ts` (surface amendment 6869487624): an unguarded `record.qx_credit > 5000000` gains `record.qx_credit != null &&`. - `authored-site-expression.test.ts`: the `validate_expression` enumeration's source regions now read the hoisted rule pass. `indexOf` and `isArray` moved out of the region with the object loop's own index, so they leave the member-call table. **Ablation** (one-shot; nothing permanent): `node scripts/ablation-replace.mjs` replaced the extension walk's `for (const rule of rules) {` with an empty loop (anchor x1 → x0, blob a3c3164 → 1bba8602). Then `pnpm --filter @objectstack/lint build` ran, and `ablation-dist-preflight` found the marker in 4 built files. - Lint pins: 5 of 8 red. The 3 controls stayed green. - Runtime pins, read through `dist/`: 2 of 3 red. The control stayed green. - Restore: the blob equals HEAD and `git diff HEAD` is empty. Lint was rebuilt, and `ablation-dist-preflight --absent` passes on all 20 built files with a clean tree. - The mutate leg's tree reading first exited 3, because the source spells the marker `[] as typeof rules`. The dist reading passed on that run, and the restore leg passed `--source-marker`. **Ablation of the strip** (r1, one-shot): `ablation-replace.mjs` replaced `if (extensionWrite) stack = {` with `if (extensionWrite && String('ablated-strip') === 'off') stack = {` (anchor x1 → x0, blob 7295169 → e6b23d5a). Lint was rebuilt, and `ablation-dist-preflight` found the marker in 4 built files. - Lint pins: 1 of 9 red, the injected-column PARITY case (the door reported the null-guard finding on `record.created_at`, the build none). - Runtime door pins: 1 of 4 red, the PARITY case (`422` on `record.created_at`). - Restore: blob equals HEAD and `git diff HEAD` is empty. Lint was rebuilt, and `ablation-dist-preflight --absent` passes on all 20 built files with a clean tree. ## Acceptance notes - **Out of scope, as the seat ruled (filed as #33217):** two rules still judge an object's own rules only. - `validate-rule-compilability` checks a `format` rule's regex. - `validate-rule-schema-formats` checks a `json_schema` rule's formats. - Both read `obj.validations`, so a regex or schema format in an extension's rule is judged at neither door. Neither is an expression pass. The changeset's Unchanged line says so. - **Not judged, at either door:** the leaf of a one-hop read through a reference an extension ADDS. `refuseUndeclaredHopField` and `storedMetadataBodyReferencesFor` read the declared objects, so with `manager__c` (a lookup to staff) added by the extension, `record.manager__c.daly_hours > 12` passes the build and the door alike (measured), while the same misspelling through a reference the target declares is refused. The changeset's Unchanged line says so. Filed as #33216. - **Filed from the contract review (record 6878859677, ③):** the flow and hook publish doors read the same unstripped nullable index, so an unguarded ordering over `record.created_at` in a record-triggered flow or a hook condition is refused at the door while `os build` accepts it. It is out of this card's scope: those walks are not in this diff. Filed as #33246. - A rule an extension adds under the same name as one of the target's own rules replaces it in the registry (merged by name). Both are judged, each where it is authored. - Module packages registered at boot (`defineStack({ objectExtensions })` through `registerApp`) are not gated, as an object's own rules are not. `packages-disable-module-extension-fields.test.ts` still registers unguarded module rules that way, untouched. ## Verification Head `9d07ffa06` (rework r1 on `15d074782`: the strip, its pins, and the prose fixes). `origin/main` was merged twice before r1 (1169d64 before opening, then after #33168 landed on `authored-site-expression.test.ts`); r1 merges nothing, and `git merge-tree` against `origin/main` at push time is clean. Everything below ran at `9d07ffa06` unless it names another head. <details><summary>Package tests</summary> - `@objectstack/lint` at `9d07ffa06`: 208/208 files, 8879/8879 tests. Typecheck exit 0. - Runtime door files at `9d07ffa06` (`meta-object-extension-item.test.ts` + `packages-disable-module-extension-fields.test.ts`): 74/74. - Every other test file that publishes an `object_extension`, at `9d07ffa06`: metadata-protocol `protocol-extension-redeclared-owner-field`, `protocol-stored-item-conversion.notice-name`, `protocol-authoring-gate.extension-write-fold`, `protocol.packaged-base-refusal`, `protocol.unknown-picklist-binding-refusal` (129/129); runtime `meta-picklist-binding-door`, `packages-export-base-showcase-boot.integration`, `meta-object-extension-item-door-fit` (22/22). - At `e4ee8af8e` (before r1; r1 changes only the extension door's object read and prose): `@objectstack/metadata-protocol` 22810 tests passed, `@objectstack/objectql` 12874, `@objectstack/platform-objects` 1955, `@objectstack/mcp` 1145, `@objectstack/cloud-connection` 1206, `@objectstack/plugin-approvals` 1632, `@objectstack/service-mailbox` 152, `@objectstack/rest` 8346 (332 skipped), `@objectstack/cli` unit 5934 and integration `test/migrate-meta-engine-guidance.test.ts` 3/3, `@objectstack/runtime` 597 files after the fixture repair. </details> <details><summary>Gates (dispatch-gates --commands, 109 lines)</summary> The derivation at `9d07ffa06` is the same 109 lines as before r1. Every line ran with stdin closed and its exit code captured before any pipe. 103 exited 0 on the first pass; six `@objectstack/spec` lines (`check:api-surface`, `check:browser-reachable-entries`, `check:dual-source-exports`, `check:entry-nameability`, `check:exported-any`, `check:skill-examples`) exited 3 (refused, nothing measured) because the spec build predated the edited semantic entry. After `pnpm --filter @objectstack/spec build` all six exited 0. `dispatch-gates --ran`: `109 derived, 109 run, 0 NOT-MEASURED`. </details> Dogfood (the title carries `!`), full battery, the CI command, no shard, on head `9d07ffa06`. The closure was built first. Result: `VERDICT command-exit 0`, Test Files 463 passed and 3 skipped (466), Tests 3918 passed and 42 skipped (3960), no failures. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibyToDkPxCjvNiWsv6e)_ <!-- signed: domain:spec#2 · os-tesla · session_01L9qibyToDkPxCjvNiWsv6e --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 47a3b95 commit 27d042f

9 files changed

Lines changed: 490 additions & 89 deletions
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+
fix(lint): `os build` and the runtime `object_extension` publish door judge each validation rule an object extension adds by the object's own rule pass, against the extended object as served
7+
8+
Clause-②: no (narrowing) — `os build`, `os validate`, `os lint` and the `object_extension` publish door (Studio, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuse an extension whose validation rule carries a `condition` or `when` the same rule on the object itself is refused for. No exported type or signature changes. Measured first-party: 0 extension entries carry a validation rule (`examples/app-showcase` one entry, three plain fields; `packages/plugins/plugin-auth` one, a `secret` field; HotCRM none), so nothing first-party is newly refused.
9+
Metadata-protocol: narrowed
10+
Skills-docs: none owed — this PR edits `content/docs/deployment/validating-metadata.mdx` (the object extension door paragraph names the rule pass); `skills/objectstack-data` teaches validation rules on the object and `defineObjectExtension({ extend, fields })` without saying an extension's rules are exempt, so the build and the door now give the verdict the object's own rules already get.
11+
12+
<!-- adr-0087: registered object-extension-validation-rule-expression-judged -->
13+
14+
**BREAKING** accept-set narrowing of `os build`, `os validate`, `os lint` and the runtime `object_extension` publish door.
15+
16+
**Before:** the registry merges an extension's `validations` onto its target object by name, so every save of the target runs them, but the expression rule judged only the rules an object declares. A rule an extension added with a misspelt field (`record.nmae`), an unregistered function (`sqrt(…)`) or an unguarded nullable operand was accepted by `os build`, `os validate` and `os lint` and published with a 200, and failed only when an end user saved a record.
17+
18+
**Now:** each rule an `objectExtensions` entry adds is judged by the object's own rule pass (its `condition` and `when`, every nested `then` / `otherwise` branch, the `parent` root verdict and the null-guard gate), with the same rule id `expression-invalid`, in `os build`, `os validate` and `os lint` as at the door. A `record.FIELD` read resolves against the extended object as served (its own fields and every field an extension adds). The door reads the objects without the system columns the registry injects, as the build does, so a column such as `created_at` is a known field and is not judged nullable at either. A finding is located at the entry: `object 'crm_account' · objectExtensions[0] · validation 'no_blocked__c'`, key path `objectExtensions[0].validations[0].condition`. At the door the refusal is `422 INVALID_METADATA`, the door still runs one pass (the extension walk), and a republish is judged without the package's own stored extension, which the write replaces.
19+
20+
The null-guard gate is part of that pass, and it is the narrowing most likely to meet a working tenant: an extension rule that applies an ordering or arithmetic operator (`>`, `<`, `+`, …) to a nullable field with no guard, such as `record.credit > 5000000` on a declared `number` field with no `required: true` and no `defaultValue`, is now refused. An equality such as `record.credit == null` is not. At runtime that predicate aborts on every save where the field is empty, and the save is refused fail-closed. The repository's own suite carried one such rule and now guards it.
21+
22+
**Unchanged:** the object save door, an object's own rules, a draft save (never gated), a stored row (judged only when it is published again), and the regex and JSON-schema checks of a `format` / `json_schema` rule, which still judge an object's own rules only. The leaf of a one-hop read through a reference an extension adds (`record.manager__c.nmae`) is still not judged, at the build or the door: the hop checks read the declared objects. A hop through a reference the target declares is judged.
23+
24+
**Fix:** before building or publishing again, repair each refused rule the way you would on a rule declared on the same object: read `record.FIELD` for a field the object serves, call only registered functions, guard a nullable operand of an ordering or arithmetic operator with `!= null` (`record.credit != null && record.credit > 5000000`), and read through a reference only in the shape a declared rule may.

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,10 @@ declarations, not words an app adds. The same door runs the build's
610610
field-formula pass on each computed field the written entry adds (#33072),
611611
against the target as served without the package's own stored extension, which
612612
the write replaces, and refuses with the build's rule id (`expression-invalid`).
613+
Each validation rule the entry adds is judged the same way (#33154), by the
614+
object's own rule pass, at the door and in `os build` alike: the registry merges
615+
an extension's `validations` onto the target, so every save of the target runs
616+
them (`object 'TARGET' · objectExtensions[0] · validation 'RULE'`).
613617

614618
**Declared enforcement that cannot run** is two rows for the mirror-image
615619
reason, and #4716 is where it split. That heading covers four rule ids, and

‎packages/lint/src/authored-site-expression.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,6 @@ function walkPushes(code: string): string[] {
103103
const SITE_MEMBER_CALLS: Record<ObjectSite, Record<string, string>> = {
104104
validation: {
105105
get: 'a Map read (the object index, the field definitions)',
106-
indexOf: 'a string offset, reading the slot key',
107-
isArray: '`Array.isArray`',
108106
push: "appends a finding to the walk's list",
109107
},
110108
formula: {
@@ -139,14 +137,17 @@ const CYCLE = {
139137
},
140138
};
141139

142-
/** Where each site's calls are read: the rule loop and the `check` helper it calls; the field-formula pass and what follows the fields loop. */
140+
/** Where each site's calls are read: the rule pass (`judgeValidationRule`) and the `check` helper it calls; the field-formula pass and what follows the fields loop. */
143141
const SITE_REGIONS: Record<ObjectSite, Array<[string, string]>> = {
144142
validation: [
145143
[' const check = (', ' const fieldRuleRootVerdict = ('],
146-
[' for (const rule of recordsOf(validations)) {', ' // Field-level formulas'],
144+
// [#33154] The rule pass, hoisted out of the object walk so the extension
145+
// walk judges an extension's rules by the same body; the object walk's
146+
// loop now calls it and nothing else.
147+
[' const judgeValidationRule = (', ' // ── Object validation-rule'],
147148
],
148149
formula: [
149-
[' const judgeFieldFormula = (', ' // ── Object validation-rule'],
150+
[' const judgeFieldFormula = (', ' const judgeValidationRule = ('],
150151
[
151152
' judgeFieldFormula(fname, f, { objectName, optionFields: optionFieldNames, fieldDefs });\n }',
152153
" // [#26646] A field group's section predicate",

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,13 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
838838
// extension draft is refused, because that batch's pending set carries no
839839
// extension drafts (#33152); publishing the extension first through the
840840
// per-item door works.
841+
//
842+
// [#33154] The same walk judges each `validations[]` rule the written
843+
// extension adds, by the object walk's own rule pass, so a rule the
844+
// registry merges onto the target is refused at this door and in the
845+
// build alike (`object 'TARGET' · objectExtensions[0] · validation 'N'`).
846+
// MEASURED first: 0 first-party `objectExtensions` entries carry a
847+
// validation rule (examples/**, packages/**, HotCRM).
841848
surfaces: CLI_AND_RUNTIME,
842849
runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page', 'object_extension'],
843850
run: (stack, ctx) =>

‎packages/lint/src/runtime-gate.object-formula-writes.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
* the #22019 block of `packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts`.
3939
*/
4040
import { describe, expect, it } from 'vitest';
41+
import { applyInjectedSystemColumns } from '@objectstack/metadata-core';
4142
import { EXPRESSION_INVALID, runAuthoringRules } from './authoring-rules.js';
4243
import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js';
4344
import { runStackExpressionPasses, validateStackExpressions } from './validate-expressions.js';
@@ -452,3 +453,148 @@ describe('#33072 — the object_extension door judges an extension field\'s form
452453
expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('validateStackExpressions');
453454
});
454455
});
456+
457+
describe('#33154 — an extension\'s validation rules are judged at the build and the object_extension door by the object\'s own rule pass', () => {
458+
/** The extended object, as the door's live universe carries it. */
459+
const target = {
460+
name: 'fx_ticket',
461+
label: 'Ticket',
462+
sharingModel: 'private',
463+
fields: {
464+
employee: { type: 'lookup', label: 'Employee', reference: 'fx_staff' },
465+
amount: { type: 'number', label: 'Amount' },
466+
},
467+
};
468+
const staff = {
469+
name: 'fx_staff', label: 'Staff', sharingModel: 'private',
470+
fields: { daily_hours: { type: 'number', label: 'Daily Hours' } },
471+
};
472+
const script = (name: string, condition: string) => ({ name, type: 'script', condition, message: 'Refused.' });
473+
/** One extension of `fx_ticket` adding the given rules (and fields). */
474+
const extension = (validations: unknown[], fields: Record<string, unknown> = {}) => ({ extend: 'fx_ticket', fields, validations });
475+
const RULE_WHERE = (rule: string) => `object 'fx_ticket' · objectExtensions[0] · validation '${rule}'`;
476+
const gateExtension = (item: unknown, objects: unknown[] = [target, staff]) =>
477+
runRuntimeAuthoringRules({ type: 'object_extension', item, context: { objects } });
478+
const buildFindings = (stack: Record<string, unknown>) =>
479+
runAuthoringRules('build', { normalized: stack, parsed: stack }).filter((f) => f.where.includes('objectExtensions'));
480+
481+
it('⭐ LIT — a rule reading a field the extended object does not serve is REFUSED, at the entry, with the slot\'s key path', () => {
482+
const result = gateExtension(extension([script('amount_positive', 'record.amont < 0')]));
483+
484+
const errs = expressionFindings(result.errors);
485+
expect(errs, dump(result)).toHaveLength(1);
486+
expect(errs[0]).toMatchObject({
487+
severity: 'error',
488+
where: RULE_WHERE('amount_positive'),
489+
path: 'objectExtensions[0].validations[0].condition',
490+
});
491+
expect(errs[0]!.message).toContain('amont');
492+
});
493+
494+
it('⭐ LIT — a rule calling an unregistered function (`sqrt`) is REFUSED, and a nested `then` branch is judged too', () => {
495+
const result = gateExtension(extension([
496+
script('first_ok', 'record.amount != null && record.amount < 0'),
497+
{
498+
name: 'big_ticket', type: 'conditional', message: 'Refused.',
499+
when: 'record.amount != null && record.amount > 100',
500+
then: script('root_check', 'record.amount != null && sqrt(record.amount) > 10'),
501+
},
502+
]));
503+
504+
const errs = expressionFindings(result.errors);
505+
expect(errs.map((f) => [f.where, f.path]), dump(result)).toEqual([
506+
[`object 'fx_ticket' · objectExtensions[0] · validation rule 'big_ticket' then → 'root_check'`, 'objectExtensions[0].validations[1].then.condition'],
507+
]);
508+
});
509+
510+
it('⭐ PARITY — on one shared input set, the door\'s findings deep-equal the build\'s', () => {
511+
for (const item of [
512+
extension([script('typo', 'record.amont < 0')]),
513+
extension([script('fn', 'sqrt(record.amount) > 1')]),
514+
extension([script('bare', 'amount < 0')]),
515+
]) {
516+
const atDoor = gateExtension(item);
517+
const atBuild = buildFindings({ objects: [target, staff], objectExtensions: [item] });
518+
519+
expect(atBuild.length, dump(atBuild)).toBeGreaterThan(0);
520+
expect([...atDoor.errors, ...atDoor.advisories]).toEqual(atBuild);
521+
}
522+
});
523+
524+
it('⭐ PARITY — the door reads the objects as served, injected system columns and all: an unguarded ordering over `created_at` is accepted there as at the build, one over a declared nullable field is refused at both', () => {
525+
// As the registry serves them: `created_at`, `owner_id`, … declared.
526+
const served = [applyInjectedSystemColumns(target), applyInjectedSystemColumns(staff)];
527+
expect(Object.keys(served[0]!.fields)).toContain('created_at');
528+
for (const [condition, refused] of [
529+
["record.created_at > timestamp('2020-01-01T00:00:00Z')", false],
530+
['record.amount > 0', true],
531+
] as const) {
532+
const item = extension([script('since', condition)]);
533+
const atDoor = gateExtension(item, served);
534+
const atBuild = buildFindings({ objects: [target, staff], objectExtensions: [item] });
535+
536+
expect([...atDoor.errors, ...atDoor.advisories], condition).toEqual(atBuild);
537+
expect(atBuild.length > 0, `${condition}: ${dump(atBuild)}`).toBe(refused);
538+
}
539+
});
540+
541+
it('⭐ CONTROL — a valid rule, a rule reading a field the same extension adds, and a one-hop read publish clean', () => {
542+
for (const item of [
543+
extension([script('ok', 'record.amount != null && record.amount < 0')]),
544+
extension([script('bonus_ok', 'record.bonus != null && record.amount != null && record.bonus > record.amount')], { bonus: { type: 'number', label: 'Bonus' } }),
545+
// The one-hop read the rule pass serves, in the shape its traversal
546+
// check prescribes: gated on the reference being set.
547+
extension([{
548+
name: 'hop_ok', type: 'conditional', message: 'Refused.',
549+
when: 'record.employee != null',
550+
then: script('long_day', 'record.employee.daily_hours > 12'),
551+
}]),
552+
]) {
553+
const result = gateExtension(item);
554+
expect(result.errors, dump(result)).toEqual([]);
555+
expect(result.advisories, dump(result)).toEqual([]);
556+
expect(buildFindings({ objects: [target, staff], objectExtensions: [item] }), dump(item)).toEqual([]);
557+
}
558+
});
559+
560+
it('a rule reading a field a SIBLING package\'s extension adds resolves at the build; a misspelling of it is refused', () => {
561+
const sibling = { extend: 'fx_ticket', fields: { bonus: { type: 'number', label: 'Bonus' } } };
562+
// An artifact: its top level repeats its bodies' objects, and the fold
563+
// reads each body's extensions.
564+
const stackWith = (item: unknown) => ({
565+
objects: [target, staff],
566+
packages: [
567+
{ manifest: { objects: [target, staff] } },
568+
{ manifest: { objectExtensions: [sibling] } },
569+
{ manifest: { objectExtensions: [item] } },
570+
],
571+
});
572+
573+
expect(buildFindings(stackWith(extension([script('sib', 'record.bonus != null && record.bonus > 0')])))).toEqual([]);
574+
const typo = buildFindings(stackWith(extension([script('sib', 'record.bonsu != null && record.bonsu > 0')])));
575+
expect(typo.map((f) => [f.rule, f.where]), dump(typo)).toEqual([
576+
[EXPRESSION_INVALID, "object 'fx_ticket' · packages[2].manifest.objectExtensions[0] · validation 'sib'"],
577+
]);
578+
});
579+
580+
it('an extension of an object the door does not carry is judged on what does not depend on its fields', () => {
581+
expect(expressionFindings(gateExtension(extension([script('fn', 'sqrt(record.amount) > 1')]), []).errors)).toHaveLength(1);
582+
const read = gateExtension(extension([script('read', 'record.amount != null && record.amount < 0')]), []);
583+
expect(read.errors, dump(read)).toEqual([]);
584+
});
585+
586+
it('on an extension write only the extension walk judges: the target\'s own broken rule is not this write\'s to answer for', () => {
587+
const broken = { ...target, validations: [script('own_typo', 'record.amont < 0')] };
588+
const stack = { objects: [broken, staff], objectExtensions: [extension([script('ok', 'record.amount != null && record.amount < 0')])] };
589+
// The build judges the object's own rule…
590+
expect(validateStackExpressions(stack).map((i) => i.where)).toEqual(["object 'fx_ticket' · validation 'own_typo'"]);
591+
// …the extension door's pass reads only the written entry.
592+
expect(runStackExpressionPasses(stack, { runtimeWriteType: 'object_extension' })).toEqual([]);
593+
});
594+
595+
it('CONTROL — the object save door still judges the object\'s own rule at its own location, and no extension rule', () => {
596+
const own = { ...target, validations: [script('own_typo', 'record.amont < 0')] };
597+
const result = gateObject(own);
598+
expect(expressionFindings(result.errors).map((f) => f.where)).toEqual(["object 'fx_ticket' · validation 'own_typo'"]);
599+
});
600+
});

0 commit comments

Comments
 (0)