Skip to content

Commit 3e19223

Browse files
fix(lint)!: the object_extension publish door judges a computed field an extension adds by the build's field-formula pass, against the extended object as served (#33119)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoWK5rFW1SUGSkDw9iatZE4f)_ Fixes #33072 Clause-②: no (narrowing) — the runtime `object_extension` publish door (Studio's add-field on a `.custom` pair, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuses an extension whose computed field carries an `expression` `os build` refuses. No exported type or signature changes. Measured first-party exposure: 0 newly refused items. Metadata-protocol: narrowed Skills-docs: none owed — this PR edits `content/docs/deployment/validating-metadata.mdx` (the CEL row's runtime column gains `ᵒˣ`, and the object extension door paragraph names the formula pass); `skills/objectstack-data` teaches `defineObjectExtension({ extend, fields })` and the computed-field rules without saying the runtime door is exempt, so the door now gives the verdict the build already gives. ## 维护者速读 - 改了什么:运行时发布对象扩展(Studio 在 `.custom` 对上加字段、`PUT /api/v1/meta/object_extension/对象`、MCP/AI 作者)时,现在会对扩展新增的计算字段跑和 `os build` 相同的公式检查(同一条规则、同一份遍历,不另写一套)。公式调用不存在的函数、读对象上没有的字段,发布返回 422 `INVALID_METADATA`,规则 id 与 build 相同,位置为 `object '对象' · objectExtensions[0] · field '字段' expression`。重新发布时,按「去掉本包已存扩展后的目标对象」来判(写入会替换它),与 build 看到的一致。 - 为什么改:#33070 之后 build 会拒这类扩展字段,但运行时发布口只跑了保留词检查,build 拒的计算字段经 Studio 仍能发布,之后每行读出 null 或报错。 - 风险与回滚:收窄;第一方实测 0 处受影响(showcase 扩展 3 个普通字段、plugin-auth 扩展 1 个 secret 字段、HotCRM 无对象扩展)。草稿保存不受影响;已存的行再次发布才会被判。已知限制:整包发布草稿(`publishPackageDrafts`)时,若草稿依赖同批的另一个扩展草稿会被拒(#33152),先用单项发布口发布该扩展即可。回滚即 revert。 - 先看:`packages/lint/src/validate-expressions.ts`(`extensionWrite`)、`packages/lint/src/authoring-rules.ts`(`runtimeTypes` 加 `object_extension`)、`packages/metadata-protocol/src/protocol-authoring-gate.ts`(`objectExtensionWriteFold` / `withTargetFoldedWithout`)、`packages/runtime/src/domains/meta-object-extension-item.test.ts`(真实保存+发布口的 #33072 一节,6 条)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/domains/meta-object-extension-item.test.ts -t "33072"`(需先构建 metadata-protocol),预期 6 条全过:坏公式被拒、合法公式发布、重新发布时去掉被引用字段被拒、改指查找字段后按新目标判、目标有已存对象行时同样被拒。 - 需要你做的:无,席位落地。 ## What changes **Lint: the door runs the build's one pass.** - **`packages/lint/src/authoring-rules.ts`.** `validateStackExpressions` declares `object_extension` in `runtimeTypes`, so `runtimeAuthoringRulesFor('object_extension')` answers `validateStackExpressions`, `validateSecurityRoleWord` (registry order). - **`packages/lint/src/validate-expressions.ts`.** On an `object_extension` write (`runtimeWriteType`), `runStackExpressionPasses` runs exactly one pass, by construction: #32875's extension walk (`judgeFieldFormula` over each field of each `objectExtensionsByTarget` entry). The object walk and the flows walk read an empty list under it, and the function returns right after the extension walk. No second field walk and no second fold: the door's snapshot is `{ objects: LIVE_OBJECTS, permissions, books, datasets, objectExtensions: [WRITTEN_ENTRY] }`, and the walk reads the target through the indexes already built over `objectsAsServed`. - **`packages/lint/src/runtime-gate.ts`.** Comment only, on the `object_extension` row of `TYPE_TO_STACK_KEY`. **Metadata-protocol: the target is the one the write will serve.** A package holds one extension per target, so a republish replaces the stored one. The gate used to hand the walk the target as served before the write, with the stored extension still folded in. That was wrong both ways: dropping a field the extension's own formula reads was admitted, and a formula over a lookup the same write re-targets was judged over the old target. - **`packages/metadata-protocol/src/protocol-authoring-gate.ts`.** `objectExtensionWriteFold` names the narrowing for an `object_extension` write that names a package: the registry's existing `withoutExtensionsOf` fold option, on the body's `extend` target. `withTargetFoldedWithout` takes only the target's entry from `listItems('object', undefined, { withoutExtensionsOf })` and keeps every other object as served, because the option is package-wide and the package's extensions of other objects are not being written. The narrowing is keyed on the singular type, so the plural retry narrows the same way. - **`protocol-stored-collection-fold.ts`, `protocol-object-extender-fold.ts`, and the two private wrappers in `protocol.ts`** (amendment 6858898742). There is a new optional trailing argument on each fold: `targetFold` on `foldStoredCollection`, and `withoutExtensionsOf` on `foldObjectExtendersFromRegistry`. They apply the same narrowing to a target that has its own stored `object` row, and only to that row. Every other caller passes nothing and reaches the call it made before. With both `onlyExtensionsOf` and `withoutExtensionsOf` given, both are handed to the registry, which leaves out a contribution either one leaves out; no caller passes both today. Both method docblocks state this. **Docs, migration and changeset.** - **`content/docs/deployment/validating-metadata.mdx`.** The CEL row's runtime column is now `✓ᶠᵃᶜʰᵒˣᵒᵛᵖ`: `ᵒˣ` goes before `ᵒ`, because after `ᵖ` the longest-first reading would take `ᵖᵒ`. One sentence was added to the object extension door paragraph. - **`packages/spec/src/migrations/entries/semantic/18.object-extension-door-computed-field-expression-judged.ts`** is the ADR-0087 D3 entry the narrowing owes. There is no D2 conversion, because how a refused expression is repaired is the author's fact. - **`.changeset/33072-object-extension-door-formula.md`**: `@objectstack/lint` minor, `@objectstack/spec` minor, `@objectstack/metadata-protocol` patch, both declaration lines, BREAKING banner, migration. **Known limit (#33152).** A package-wide draft publish (`publishPackageDrafts`) whose drafts depend on a sibling extension draft is refused, because that batch's pending set carries no extension drafts. Publishing the extension first through the per-item door works. The same gap exists on `main` for object drafts. The changeset, the entry and the `[#33072]` docblocks state it. ## Tests 1. **`packages/lint/src/runtime-gate.object-formula-writes.test.ts`**, new describe `#33072` (10 cases) at the real gate (`runRuntimeAuthoringRules`). Cases: - the roster; - LIT: `sqrt(record.amount)` is refused under `expression-invalid` at the build's location; - LIT: a read of a field the target does not serve is refused; - LIT: a stored field reading another record is an advisory, never a 422; - PARITY: on one shared input, the door's findings deep-equal the build's, for an error and for an advisory; - CONTROL: a valid formula, and a formula reading a field the same extension adds, both publish clean; - an undeclared target is judged on what does not depend on its fields; - the differential; - the narrowing; - CONTROL: the object save door is unchanged. 2. **`packages/runtime/src/domains/meta-object-extension-item.test.ts`**, new describe `[#33072]` (6 cases) through the real `saveMetaItem` + `publishMetaItem` over better-sqlite3 and the real `ObjectQL`/`SchemaRegistry`. Cases: - LIT `sqrt(record.name)` → 422 `expression-invalid` at `object 'crm_account' · objectExtensions[0] · field 'score__c' expression`, the field not served and the row left a draft; - LIT: a misspelt field read is refused; - CONTROL: a valid formula publishes; - and three republish cases, each over a stored self: - lenient direction: dropping `bonus__c` while `total__c` reads it → 422 (was 200); - strict direction: re-targeting lookup `ref__c` from `crm_region` to `crm_account` with `via__c: record.ref__c.name` → 200 (was 422 against `crm_region`). This is also the first hop pinned on the real door; - a target with its own stored `object` row (the pair's runtime-authored `crm_custom_lead`) → 422. 3. **`packages/metadata-protocol/src/protocol-authoring-gate.extension-write-fold.test.ts`** (new, 7 cases): - `objectExtensionWriteFold`: which writes narrow; - `withTargetFoldedWithout`: only the target is replaced; - `foldObjectExtendersFromRegistry`: what each package argument hands the registry, both included. 4. **`packages/lint/src/validate-security-posture.runtime-surface.test.ts`**: the #31998 extension case's roster and `rulesRun` pins now read `['validateStackExpressions', 'validateSecurityRoleWord']`. **Reproduction at `main` `2c98485d`**, with the pins committed first: 8 of the 10 lint door cases were red. The door published `sqrt(record.amount)` with 0 errors while the build refused it. <details><summary>Ablations (fix committed first, mutated through scripts/ablation-replace.mjs, each restore read blob == HEAD and git diff HEAD empty)</summary> | # | Mutation | Expected | Observed | |:--|:--|:--|:--| | 1 | `object_extension` dropped from the rule's `runtimeTypes`, lint rebuilt, dist marker proved absent | lint door pins and runtime LIT pins red, controls green | lint 8 failed / 41 passed; runtime 2 failed (both LIT), CONTROL passed | | 2 | the object-walk fence on an extension write removed | the narrowing pin red | 1 failed (the narrowing pin) | | 3 | host narrowing off (`extensionWrite` forced `undefined`), metadata-protocol rebuilt | the three republish pins red, the r0 pins green | 3 failed / 3 passed | | 4 | stored half off (the target-name match in `foldStoredCollection` broken), metadata-protocol rebuilt | only the stored-object-row pin red | 1 failed / 5 passed | </details> ## Acceptance notes - **Exposure, measured at `2c98485d`:** `examples/app-showcase` has one extension entry with 3 plain fields; `packages/plugins/plugin-auth` has one with a `secret` field; HotCRM (`4f0ffd8`, re-verified at `0009f58`) has none. 0 carry an `expression`, so the door refuses nothing first-party. - **Location agreement is index-exact for a package with one extension entry.** The door's snapshot always holds the written entry at `objectExtensions[0]`. The build of a package with several entries prints that entry's own index, and `packages[j].manifest.objectExtensions[i]` in an artifact stack. Rule id, object, field and message are the same in every case. - **N1.** A served `object_extension` draft's `_diagnostics` now carries the formula verdict, because `draftPublishVerdict` reads the same roster. No prose face names it, and no pin covers it. - **N3.** The real door now pins a hop (the strict republish case). There is still no real-door pin for `label()` or for the draft `_diagnostics`. The lint "(the differential)" case passes by the object-walk fence. - **N4.** An extension of an object outside the written package's closure is refused first by the item gate (`objectExtensionItemRefusal` step 5), so at the door the formula pass never sees it. Only the lint API reaches the "judged on what does not depend on the target's fields" arm. - **N5, N6.** The two folds' docblocks describe their optional arguments and the both-given case. The changeset names `@objectstack/metadata-protocol` (patch), which carries the host half. - **Filed by the seat, out of scope here:** - #33152, batch publish with interdependent extension drafts (the known limit above); - #33153, formula cycles through an extension; - #33154, an extension's `validations` judged at neither door, although the registry registers them on the object. - **Ruling grep** (`ruling|Ruling-ref|maintainer|⛔`) over the surface: the readings that bear on this diff are "the per-write snapshot is not widened for cross-item judgments" (rulings `5791822697` item 3 and `6104584601`) and "⛔ no context row for symmetry" (`runtime-gate.ts`). This diff adds no context collection and no snapshot key; it narrows the existing `objects` list for the target. None is reversed. - **File surface.** Production changes are in `packages/lint`, in `packages/metadata-protocol` (the gate plus the two folds' optional pass-through, amendment 6858898742), in the docs page and in the semantic entry. `packages/runtime` is test only. - **Release:** 18.4.0 shipped before this PR opened, so this rides the next release train. ## Verification Readings at HEAD `f57cc273` unless noted. `f57cc273` is the r2 prose and metadata commit on top of `ac6dd79d`, which merged `origin/main` `bf02d33b` cleanly. main is ahead again and merges clean; it was not merged again. <details><summary>Tests</summary> Each heavy command ran under `scripts/pm/os-verify-lock.sh` (VERDICT command-exit 0). Exit codes were captured before any pipe. - At `f57cc273`, after `pnpm build --concurrency=2` (exit 0): - `@objectstack/metadata-protocol` full suite: Test Files 338 passed | 7 skipped (345), Tests 22810 passed | 36 skipped; - `@objectstack/spec` full suite: Test Files 931 passed (931), Tests 28389 passed | 1 todo; - `meta-object-extension-item.test.ts`: 29 passed (29), the 6 `[#33072]` cases among them. - At `ac6dd79d` (the r1 head; r2 changes comments, the changeset, the entry's text, one fold's option hand-off for a case no caller reaches, and test files only): - `pnpm check:dual-build-cjs-loads` exit 0; - dogfood battery (owed by the `(narrowing)` arm): 460 files and 3874 tests passed, 42 skipped; - `@objectstack/runtime` full suite: 11938 passed, 19 skipped; - `@objectstack/lint` full suite: 8751 passed. - CI at `ac6dd79d`: 68 check runs, every one success or skipped. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `f57cc273` derives 119 families. Each ran with stdin from `/dev/null`: all 119 exited 0. The `--ran` reconciliation read: `119 derived famil(ies) accounted for — 119 run, 0 NOT-MEASURED`. </details> --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibwwiSN1TXWjohzCZN9 <!-- signed: domain:spec#2 · os-tesla · session_01L9qibwwiSN1TXWjohzCZN9 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 68972cd commit 3e19223

14 files changed

Lines changed: 588 additions & 28 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/lint': minor
3+
'@objectstack/spec': minor
4+
'@objectstack/metadata-protocol': patch
5+
---
6+
7+
fix(lint): the runtime `object_extension` publish door judges a computed field an extension adds by the build's field-formula pass, against the extended object as served
8+
9+
Clause-②: no (narrowing) — the `object_extension` publish door (Studio's add-field on a `.custom` pair, `PUT /api/v1/meta/object_extension/TARGET`, the MCP and AI authoring doors) now refuses an extension whose computed field carries an `expression` `os build` refuses. No exported type or signature changes. Measured first-party: 0 extension entries with a computed field (`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.
10+
Metadata-protocol: narrowed
11+
Skills-docs: none owed — this PR edits `content/docs/deployment/validating-metadata.mdx` (the CEL row's runtime column gains `ᵒˣ`, and the object extension door paragraph names the formula pass); `skills/objectstack-data` teaches `defineObjectExtension({ extend, fields })` and the computed-field rules without saying the runtime door is exempt, so the door now gives the verdict the build already gives.
12+
13+
<!-- adr-0087: registered object-extension-door-computed-field-expression-judged -->
14+
15+
**BREAKING** accept-set narrowing of the runtime `object_extension` publish door (`validateStackExpressions` joins its `runtimeTypes`).
16+
17+
`os build` and `os validate` judge each field an `objectExtensions` entry adds with the field-formula pass, but the publish door that writes an extension at runtime ran only the vocabulary freeze, so a computed field the build refuses published with a 200 and then read null, or failed, on every row.
18+
19+
- On an `object_extension` write the expression rule runs exactly one pass: the extension walk over each field the written entry adds, against the door's live objects with the entry folded in (the build's own fold), located as the build locates it for a package with one extension entry: `object 'crm_account' · objectExtensions[0] · field 'score__c' expression` (the door judges the written entry alone, so its index is always `[0]`; a build of a package with several entries names the entry's own index). A refusal is the gate's `422 INVALID_METADATA` with issue rule `expression-invalid`; a stored field that reads another record, the clock or the acting user is an advisory (`stored-expression-cross-record-input`, `stored-expression-volatile-input`), never a refusal.
20+
- A republish is judged against the target without the package's own stored extension, which the write replaces, as the build sees the package's one entry: dropping a field the extension's own formula still reads is refused, and a formula over a lookup the same write re-targets is judged over the new target.
21+
- An extension of an object the door does not carry is judged on what does not depend on that object's fields (grammar, registered functions, bare and unbound references).
22+
- A package-wide draft publish (`publishPackageDrafts`) whose drafts depend on a sibling extension draft is refused, because that batch's pending set carries no extension drafts (#33152); publishing the extension first through the per-item door works.
23+
- Unchanged: the object save door, `os build`, `os validate`, a draft save (never gated), and a stored row, which is judged only when it is published again.
24+
25+
Migration: before publishing an extension again, fix each refused `expression` the way you would on a declared field of the same object: read `record.FIELD` for a field the object serves, call only registered functions, and make a stored field that reads another record, the clock or the acting user a `formula` field.

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ orthogonal to both, and no cell here can carry it; it is written out in
494494
| | `os validate` | `os build` | `os lint` | runtime publish |
495495
|---|---|---|---|---|
496496
| Protocol schema (Zod) | ✓ | ✓ | — | ✓ |
497-
| CEL / predicate validation (ADR-0032) | ✓ | ✓ | ✓ | ✓ᶠᵃᶜʰᵒᵛᵖ |
497+
| CEL / predicate validation (ADR-0032) | ✓ | ✓ | ✓ | ✓ᶠᵃᶜʰᵒˣᵒᵛᵖ |
498498
| List-view navigation modes (ADR-0053) | ✓ | ✓ | ✓ | — |
499499
| Zod-valid but functionally inert declarations — a `summary` with no operations (ADR-0078), a managed object advertising an API method its affordances refuse (#7521) | ✓ | ✓ | ✓ | ✓ᵒ |
500500
| Retired object title template — an object that declares `titleFormat`, retired by ADR-0079 for `nameField` (`title-format-retired`, #29007) | ✓ | ✓ | ✓ | ✓ᵒ |
@@ -606,7 +606,10 @@ located at the entry (`objectExtensions[0].fields.FIELD.name`). The
606606
`object_extension` publish door (Studio's add-field on a customization package,
607607
`/api/v1/meta`) runs the same rule. A field an extension adds to a `sys_*`
608608
object is judged too: the system-object exemption covers the platform's own
609-
declarations, not words an app adds.
609+
declarations, not words an app adds. The same door runs the build's
610+
field-formula pass on each computed field the written entry adds (#33072),
611+
against the target as served without the package's own stored extension, which
612+
the write replaces, and refuses with the build's rule id (`expression-invalid`).
610613

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

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -821,8 +821,25 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
821821
// shipped corpus at `6021b5e837`: 0 findings across examples/**,
822822
// platform-objects and plugin-approvals, against one for a planted unbound
823823
// hole; #25709 re-measured 0 sentences of the holeless `${…}` shape there.
824+
//
825+
// [#33072] `object_extension` joins, for ONE pass: the field-formula pass
826+
// over each field the written extension adds — the extension walk #32875
827+
// gave `os build` / `os validate`, which refuses a computed field there
828+
// that this door published with a 200 (Studio's add-field on a `.custom`
829+
// pair and the `/meta` doors write the item). On an extension write
830+
// `runStackExpressionPasses` runs that walk alone, by construction, over
831+
// the written entry (the sole member of `objectExtensions`) against the
832+
// door's live objects as served, so a refusal carries the build's rule id
833+
// and location (`object 'TARGET' · objectExtensions[0] · field 'F'
834+
// expression`). MEASURED first: 0 first-party `objectExtensions` entries
835+
// carry a computed field (examples/**, packages/**, HotCRM), so the
836+
// crossing refuses nothing the repository ships. A package-wide draft
837+
// publish (`publishPackageDrafts`) whose drafts depend on a sibling
838+
// extension draft is refused, because that batch's pending set carries no
839+
// extension drafts (#33152); publishing the extension first through the
840+
// per-item door works.
824841
surfaces: CLI_AND_RUNTIME,
825-
runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page'],
842+
runtimeTypes: ['flow', 'action', 'hook', 'object', 'view', 'page', 'object_extension'],
826843
run: (stack, ctx) =>
827844
runStackExpressionPasses(stack, { runtimeWriteType: ctx.runtimeWriteType }).map((i) => ({
828845
severity: i.severity ?? 'error',

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

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,3 +336,119 @@ describe('#32529 / #32554 — the object door judges a stored expression\'s inpu
336336
expect(atDoor).toEqual(atBuild);
337337
});
338338
});
339+
340+
describe('#33072 — the object_extension door judges an extension field\'s formula as the build does', () => {
341+
/** The extended object, as the door's live universe carries it. */
342+
const target = {
343+
name: 'fx_ticket',
344+
label: 'Ticket',
345+
sharingModel: 'private',
346+
fields: {
347+
employee: { type: 'lookup', label: 'Employee', reference: 'fx_staff' },
348+
amount: { type: 'number', label: 'Amount' },
349+
},
350+
};
351+
const staff = {
352+
name: 'fx_staff', label: 'Staff', sharingModel: 'private',
353+
fields: { daily_hours: { type: 'number', label: 'Daily Hours' } },
354+
};
355+
/** One extension of `fx_ticket` adding the given fields. */
356+
const extension = (fields: Record<string, unknown>) => ({ extend: 'fx_ticket', fields });
357+
const scoreOf = (expression: string) => extension({ score: { type: 'formula', label: 'Score', expression } });
358+
const EXT_WHERE = (field: string) => `object 'fx_ticket' · objectExtensions[0] · field '${field}' expression`;
359+
const gateExtension = (item: unknown, objects: unknown[] = [target, staff]) =>
360+
runRuntimeAuthoringRules({ type: 'object_extension', item, context: { objects } });
361+
const ofRule = <T extends { rule: string }>(rule: string, fs: readonly T[]): T[] => fs.filter((f) => f.rule === rule);
362+
363+
it('`validateStackExpressions` is on the object_extension door, beside the vocabulary freeze', () => {
364+
expect(runtimeAuthoringRulesFor('object_extension').map((r) => r.name))
365+
.toEqual(['validateStackExpressions', 'validateSecurityRoleWord']);
366+
});
367+
368+
it('⭐ LIT — an extension formula calling an unregistered function (`sqrt`) is REFUSED, at the entry the build names', () => {
369+
const result = gateExtension(scoreOf('sqrt(record.amount)'));
370+
371+
expect(result.rulesRun).toContain('validateStackExpressions');
372+
const errs = expressionFindings(result.errors);
373+
expect(errs, dump(result)).toHaveLength(1);
374+
expect(errs[0]).toMatchObject({ severity: 'error', where: EXT_WHERE('score'), path: EXT_WHERE('score') });
375+
});
376+
377+
it('⭐ LIT — an extension formula reading a field the extended object does not serve is REFUSED', () => {
378+
const result = gateExtension(scoreOf('record.amont * 2'));
379+
380+
const errs = expressionFindings(result.errors);
381+
expect(errs, dump(result)).toHaveLength(1);
382+
expect(errs[0]!.where).toBe(EXT_WHERE('score'));
383+
expect(errs[0]!.message).toContain('amont');
384+
});
385+
386+
it('⭐ LIT — a stored extension field reading another record is an ADVISORY, never a 422', () => {
387+
const result = gateExtension(extension({
388+
hours: { type: 'number', label: 'Hours', expression: 'record.amount * record.employee.daily_hours' },
389+
}));
390+
391+
const advised = ofRule(STORED_EXPRESSION_CROSS_RECORD_INPUT, result.advisories);
392+
expect(advised, dump(result)).toHaveLength(1);
393+
expect(advised[0]).toMatchObject({ severity: 'warning', where: EXT_WHERE('hours') });
394+
expect(result.errors, dump(result)).toEqual([]);
395+
});
396+
397+
it('⭐ PARITY — on one shared input, the door finding IS the build finding', () => {
398+
for (const item of [
399+
scoreOf('sqrt(record.amount)'),
400+
extension({ hours: { type: 'number', label: 'Hours', expression: 'record.amount * record.employee.daily_hours' } }),
401+
]) {
402+
const atDoor = gateExtension(item);
403+
const stack = { objects: [target, staff], objectExtensions: [item] };
404+
const atBuild = runAuthoringRules('build', { normalized: stack, parsed: stack })
405+
.filter((f) => f.where.includes('objectExtensions'));
406+
407+
expect(atBuild.length, dump(atBuild)).toBe(1);
408+
expect([...atDoor.errors, ...atDoor.advisories]).toEqual(atBuild);
409+
}
410+
});
411+
412+
it('⭐ CONTROL — a valid extension formula, and one reading a field the same extension adds, publish clean', () => {
413+
for (const item of [
414+
scoreOf('floor(record.amount)'),
415+
extension({
416+
bonus: { type: 'number', label: 'Bonus' },
417+
total: { type: 'formula', label: 'Total', expression: 'record.amount + record.bonus' },
418+
}),
419+
]) {
420+
const result = gateExtension(item);
421+
expect(result.errors, dump(result)).toEqual([]);
422+
expect(result.advisories, dump(result)).toEqual([]);
423+
expect(result.rulesRun).toEqual(['validateStackExpressions', 'validateSecurityRoleWord']);
424+
}
425+
});
426+
427+
it('an extension of an object the door does not carry is judged on what does not depend on its fields', () => {
428+
expect(expressionFindings(gateExtension(scoreOf('sqrt(record.amount)'), []).errors)).toHaveLength(1);
429+
const read = gateExtension(scoreOf('record.amount * 2'), []);
430+
expect(read.errors, dump(read)).toEqual([]);
431+
});
432+
433+
it('a stored object\'s own broken formula is not the extension write\'s to answer for (the differential)', () => {
434+
const broken = { ...target, fields: { ...target.fields, bad: { type: 'formula', label: 'Bad', expression: 'sqrt(record.amount)' } } };
435+
const result = gateExtension(scoreOf('floor(record.amount)'), [broken, staff]);
436+
437+
expect(result.errors, dump(result)).toEqual([]);
438+
});
439+
440+
it('on an extension write only the extension walk judges: no pass over the objects the door carries', () => {
441+
const broken = { ...target, fields: { ...target.fields, bad: { type: 'formula', label: 'Bad', expression: 'sqrt(record.amount)' } } };
442+
const stack = { objects: [broken, staff], objectExtensions: [scoreOf('floor(record.amount)')] };
443+
// The build judges the declared formula…
444+
expect(validateStackExpressions(stack).map((i) => i.where)).toEqual(["object 'fx_ticket' · field 'bad' expression"]);
445+
// …the extension door's pass reads only the written entry.
446+
expect(runStackExpressionPasses(stack, { runtimeWriteType: 'object_extension' })).toEqual([]);
447+
});
448+
449+
it('CONTROL — the object save door is unchanged: it judges the object\'s own formula and no extension field', () => {
450+
const result = gateObject(fxSqrt('sqrt(record.amount)'));
451+
expect(expressionFindings(result.errors).map((f) => f.where)).toEqual([WHERE]);
452+
expect(runtimeAuthoringRulesFor('object').map((r) => r.name)).toContain('validateStackExpressions');
453+
});
454+
});

‎packages/lint/src/runtime-gate.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,11 @@ const TYPE_TO_STACK_KEY: Readonly<Record<string, string>> = {
289289
// written word on its own, and a write's own collection holds exactly one
290290
// member — its own item (an extension carries `extend` and no `name`, so it is
291291
// never name-keyed).
292+
//
293+
// [#33072] `validateStackExpressions` crosses with this row too, for one
294+
// pass: the extension walk over the written entry's fields. It resolves
295+
// `record.FIELD` into `objects`, which every snapshot already carries, so the
296+
// row still needs no context collection of its own.
292297
object_extension: 'objectExtensions',
293298
};
294299

‎packages/lint/src/validate-expressions.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2262,6 +2262,19 @@ export interface StackExpressionOptions {
22622262
* write. None of them is the object's own body, the object write's snapshot
22632263
* does not carry them, and each is judged at its own type's door; the claim
22642264
* holds by construction rather than by the snapshot's shape.
2265+
*
2266+
* [#33072] On an `object_extension` write exactly ONE pass judges: the
2267+
* field-formula pass over each field the written entry adds (#32875's
2268+
* extension walk, `judgeFieldFormula`), against the extended object as
2269+
* served — the door's live objects with the entry folded in by
2270+
* `objectsAsServed`, the build's own fold — and located at the entry, as the
2271+
* build locates it. The object walk reads an empty list (the carried
2272+
* objects are the universe the field resolves in, not the subject) and so
2273+
* does every other pass; the function returns after the extension walk.
2274+
* A package-wide draft publish (`publishPackageDrafts`) whose drafts depend
2275+
* on a sibling extension draft is refused, because that batch's pending set
2276+
* carries no extension drafts (#33152); publishing the extension first
2277+
* through the per-item door works.
22652278
*/
22662279
runtimeWriteType?: string;
22672280
/**
@@ -2321,6 +2334,13 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
23212334
// an empty list under it, so the claim holds by construction rather than by
23222335
// the shape of the snapshot the gate happens to build today.
23232336
const objectWrite = options.runtimeWriteType === 'object';
2337+
// [#33072] On an `object_extension` write exactly ONE pass judges: the
2338+
// extension-field walk below (#32875), over the written entry, against the
2339+
// extended object as served. Every other loop reads an empty list under it
2340+
// (the object walk and the flows included), and the function returns right
2341+
// after that walk, so the claim holds by construction. See
2342+
// {@link StackExpressionOptions.runtimeWriteType}.
2343+
const extensionWrite = options.runtimeWriteType === 'object_extension';
23242344
// [#32872] See {@link StackExpressionOptions.sharedValidatorRunByCaller}.
23252345
const validatorRunByCaller = options.sharedValidatorRunByCaller === true;
23262346
// [#24798] On a `view` write exactly ONE pass judges — the bulk `confirmText`
@@ -2827,7 +2847,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
28272847
const runtimeGateWrite = options.runtimeWriteType !== undefined;
28282848
const flowEntrances: ReadonlyMap<string, FlowCelEntrance> =
28292849
objectWrite || runtimeGateWrite ? new Map() : flowCelEntrances(stack, fieldIndex);
2830-
for (const flow of objectWrite ? [] : recordsOf(stack.flows)) {
2850+
for (const flow of objectWrite || extensionWrite ? [] : recordsOf(stack.flows)) {
28312851
const flowName = typeof flow.name === 'string' ? flow.name : '(unnamed flow)';
28322852
// [#26858] The flow's index in the authored list, for a finding's key path
28332853
// (`recordsOf` hands an array's own members back). A map-form `flows` has
@@ -3527,7 +3547,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
35273547
// [#32529] The object's position in `objects`, which is its position in
35283548
// `typedObjects` too (the served body the stored-expression member reads).
35293549
let objectPosition = -1;
3530-
for (const obj of objects) {
3550+
// [#33072] Fenced on an extension write: the objects the door carries are
3551+
// the universe the extension field is judged against, not its subject.
3552+
for (const obj of extensionWrite ? [] : objects) {
35313553
objectPosition += 1;
35323554
const objectName = typeof obj.name === 'string' ? obj.name : undefined;
35333555
// [#27643] The object's index in the authored list, for a validation-rule
@@ -4003,6 +4025,12 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
40034025
//
40044026
// Fenced on an object write: an extension is not the written object's
40054027
// body, and an object write's snapshot carries none.
4028+
//
4029+
// [#33072] The `object_extension` publish door runs this walk and nothing
4030+
// else: its snapshot carries the written entry as the sole member of
4031+
// `objectExtensions` and the door's live objects as `objects`, so the field
4032+
// is judged against its target as served and located where the build
4033+
// locates it (`objectExtensions[0]` for a one-entry stack).
40064034
for (const [target, entries] of objectWrite ? [] : objectExtensionsByTarget(stack)) {
40074035
// The target's position in `objects`, which is its position in
40084036
// `typedObjects` too (see `objectPosition` above); -1 when undeclared.
@@ -4044,6 +4072,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
40444072
}
40454073
}
40464074

4075+
// [#33072] An extension write's one pass ends here.
4076+
if (extensionWrite) return issues;
4077+
40474078
// ── Action `visible` / `disabled` / `pressed` predicates ────────────
40484079
// Record-scoped, same as validation rules: a record-header / row action's
40494080
// `visible` is evaluated by ActionEngine against `{ record, recordId,

0 commit comments

Comments
 (0)