Skip to content

Commit 97f3420

Browse files
fix(metadata-protocol)!: drop an explained union head from a refused save's issues only when it is zod's bare "Invalid input" (#35520)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgRuogP8Tp8XyFXLc92Bxvo6)_ repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me Fixes #35400 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no skill or doc teaches the order of a refused metadata save's `issues`, or its union entry (searched `skills/` and `content/docs/` for `invalid_union`, "Invalid input", `issues[0]` and "strictly additive"; the hits describe the data API's `fields[]` and the UI CLI's validate report, both unchanged here) ## 维护者速读 1. 设计器、接口或 AI 助手保存元数据被拒时,清单里那句什么都没说的「输入无效」不再排在真正原因前面,第一条直接指出是哪个键错了;自带修法说明的条目照旧保留。 2. 这是巡检发现的「视图或表单保存被拒时,清单第一行是一句空话」的问题,按您两次裁定的范围执行:每一层都去掉,但只去真正空的那句。 3. 出错时,设计器约 25 个字段在保存被拒后少一行「输入无效」红字(多数在作者下次改动后恢复,表单另开一张单改),按第几条读清单的外部调用方会读到另一条;不丢数据也不影响权限,回退代码即可恢复,但发版后回退等于接口再变一次。 4. 无。 ## What changes - **The rule** (`collectMetadataIssues`, `packages/metadata-protocol/src/protocol-metadata-issues.ts`): a union's own entry (the head) is dropped only when BOTH hold: the branch expansion appended at least one entry, and the head's message is exactly zod's default for a failed union. Every other head stays, ahead of what it explains: a head carrying the schema's own sentence (the template slot's sentence telling the author to write a template string, an action's `confirmText` sentence, a view's retirement prescription), a head nothing below explains (every branch a bare kind mismatch, zod's empty `errors`, the depth bound), and every container head (`invalid_key`, `invalid_element`). This narrows the round-1 WIP (`b277779bd0`), which dropped every explained head whatever its message. - **One named constant** for the compared text, `ZOD_UNION_DEFAULT_MESSAGE` (module-level export, not re-exported by `protocol.ts`), pinned against a real zod parse (plain `z.union` and the real view schema), so a zod rewording fails a test instead of silently turning the drop off. - **Texts that became false move here:** the producer's entry-rule docblock (and the WIP's "carries no prescription" line, measured false), the `zodIssuesToMetadataIssues` docblock, and the read-path comment in `metadata-diagnostics.ts` that said the union entry stays first. - **All four callers move together** (save `422 INVALID_METADATA`, read `_diagnostics.errors`, seed-request refusal, unmanaged-import `400`): they share the one producer. - **Changeset** `.changeset/metadata-issues-bare-union-head.md`: `patch`, both declaration lines, BREAKING banner, a was/now table, "read entries by `path` and `code`, not by index", one ADR-0087 marker (`not-required (no-migration-prescription)`; the gate accepted it), what stays, the deliberate asymmetry, and the known regression below. - **The asymmetry, recorded** in `union-branch-policy.cross-package-parity.test.ts`: this envelope drops an explained bare head; the terminal renderer keeps it as its parent row; the data API's `fields[]` keeps it as `invalid_shape` (#35433 tracks it). §2 still compares branch selection across all three walks, with exactly those heads projected out of the two spec walks; §4 asserts the asymmetry itself and that an unexplained bare head is kept by all three. - **Not here:** no `ui/` change (Studio's form rows are #35499) and no change to `packages/spec/src/api/zod-issues-to-fields.ts` (#35433). **Known regression, until #35499 lands.** Studio's metadata form draws a refusal's entry on a field row only when the entry's path equals the row's key. On about 25 top-level keys the dropped head was the only entry at that exact path, so after a refused save that row shows one red line fewer (the "Invalid input" line). On a type with a live validator the author's next edit redraws the row; on the rest (the seat's analysis counted 9 keys) it stays off until #35499. The place is still named by the entries themselves and in the Save button's tooltip. ## Tests Readings are on this branch after its one merge of `origin/main` `5756ae0d75`; the code head was `62387026db`; the final head `692d874e93` adds a merge of `origin/main` `94fb8db2d1` and a changeset-only commit (the Clause-② line reads `no (narrowing)`). The code head's last commit only adds a module-top preload import to four pin files (Verification), so the five pin files and the package typecheck were re-run on it: 122 passed, `VERDICT command-exit 0`. - **Moved pins: 22 tests in the five files** went red on the producer change alone and were rewritten (save-union-issues 7, cross-package parity 8, 422 face inventory 3, container descent 2, diagnostics 2). That is the same 22 the WIP rule moved: every moved pin's head was zod's bare text, so the bare-only condition moved none back. - **New pins** (one `describe` in `protocol.save-union-issues.test.ts`, the file's shared harness): the zod text pin; synthetic bare-vs-authored; a refused view save with a non-locale `label` map answers only the two `label.not_a_locale` entries, container head first; an object `titleFormat` and an action `confirmText` written as formulas keep their authored heads ahead of the `.dialect` cause; CONTROL `label: 42` keeps its unexplained bare head. Plus §4's asymmetry pin in the parity file. <details><summary>Five pin files: red on the producer alone, green after the rewrite</summary> ```text producer commit only (715b42d), 5 files under the verify lock: Test Files 5 failed (5) Tests 22 failed | 93 passed (115) os-verify-lock: VERDICT command-exit 1 after the rewrite: Test Files 5 passed (5) Tests 122 passed (122) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Whole package: test and typecheck</summary> ```text pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 Test Files 360 passed | 9 skipped (369) Tests 23256 passed | 45 skipped (23301) os-verify-lock: VERDICT command-exit 0 pnpm --filter @objectstack/metadata-protocol build && … typecheck check-dts-emitted: @objectstack/metadata-protocol - 2/2 declared declaration file(s) present. os-verify-lock: VERDICT command-exit 0 (tsc --listFiles: 368 test files in the program, all five edited files among them) ``` </details> <details><summary>Ablations (committed first; scripts/ablation-replace.mjs, anchor 1 to 0, restored to the HEAD blob)</summary> The tests import the producer by relative path (`./protocol.js`), so `src` is what runs and no rebuild is involved. ```text A1 · keep every head (main's behaviour): `out.push(entry);` Tests 23 failed | 99 passed (122) VERDICT command-exit 1 red: 20 of the 22 rewritten pins (the other two, in the 422 face inventory, hold under either rule) plus the three new drop pins (bare-vs-authored, the label map, §4's asymmetry); green: the authored-head, unexplained-head and container controls ok restored: blob == HEAD (dccd42f) and `git diff HEAD` is empty A2 · drop every explained head (the WIP rule): `if (below.length === 0) out.push(entry);` Tests 3 failed | 119 passed (122) VERDICT command-exit 1 red: exactly the three authored-head pins (synthetic, titleFormat, confirmText) ok restored: blob == HEAD (dccd42f) and `git diff HEAD` is empty ``` </details> ## Acceptance notes - Studio was measured from source in round 1 and in the seat's scope analysis, not driven in a browser; the form change is #35499. - The data API's `fields[]` keeps its `invalid_shape` head (#35433); the CLI and terminal renderer keep the parent line. Both are pinned as deliberate. - A union head whose message is the schema's own sentence is kept even when its sentence is repeated on an entry below (for example a view's retirement prescription, which also rides on the retired key's own entry). Bare-only was ruled over "drop when repeated below". ## Verification Local subset on the code head `62387026db` (the final head `692d874e93` adds only a merge of main and a changeset line; CI on it: 39 success, 18 skipped, 0 failed): the derived list (`node scripts/pm/dispatch-gates.mjs --commands`, 66 families) all exit 0. `--ran` reconciliation over the recorded exits: "66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN" (a derived zero: all 66 recorded an exit code and none is 3). - One family was red on the head before last and is answered in the diff: `check:test-source-alias` judged the four edited pin files that reach the protocol's lazy lint import inside a clocked case. They now import the package's existing lint preload testkit at module top, as `protocol.save-union-issues.test.ts` already does; the gate then read "the source reach judged 5 test file(s) changed", OK. - `check:dual-build-cjs-loads` and `check:lean-entry-closure` exited 3 (prerequisite, no `dist/`) on the first run; on the final head, after the dogfood closure build, both exit 0. - `node scripts/pm/overlap-check.mjs --branch=claude/issue-35400-drop-explained-union-wrapper` before every push: "VERDICT clean exit 0", 0 PR heads overlapping. - Families CI owns (`Lint & Repo Gates`, `TypeScript Type Check`, `Test Core`, `Build Core`, the UI lanes) are read from this PR's check-runs, not re-run locally. <details><summary>Dogfood battery (narrowing arm)</summary> The full battery (`pnpm --filter @objectstack/dogfood test` under the verify lock, no shard, no path) ran on the final head `692d874e93`: VERDICT command-exit 0; 482 test files passed, 3 skipped; 4092 tests passed, 68 skipped; no failures (os-dev-report 7013769621 on #35400; the same counts as the earlier run on `62387026db`, report 7011455182). </details> ## 席位核对 - Read first: `packages/metadata-protocol/src/protocol-metadata-issues.ts` (the one-line rule in `collectMetadataIssues`, and the constant), then `union-branch-policy.cross-package-parity.test.ts` (`withoutExplainedBareHeads` and §4), then the changeset. - Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run src/protocol.save-union-issues.test.ts` (after building its dependencies) shows 37 passed, including the `#35400` describe. - Line budget: 8 files, +360 / -88 (the changeset +32; production code +72 / -30 in two files; the rest is tests). --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5cd2b54 commit 97f3420

8 files changed

Lines changed: 360 additions & 88 deletions
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol)!: a refused metadata save no longer lists zod's bare "Invalid input" union entry ahead of the entries that explain it
6+
7+
Clause-②: no (narrowing) — narrowed: the `issues[]` of a refused metadata save (`422 INVALID_METADATA`), a stored item's `_diagnostics.errors`, the seed-request refusal's `issues` and the unmanaged-import `400` no longer carry a union's own `invalid_union` entry when its message is zod's bare `Invalid input` and an entry below it explains the failure. `issues[0]` of a refused view save is now the first located cause.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: what moves is which entries a refusal's issues list carries, computed afresh on every refused save and every read. The accept set is unchanged. The one reading instruction is in the body: read entries by path and code, never by index. -->
11+
12+
**BREAKING** for a client that reads a refused metadata save's `issues[]`, or a stored item's `_diagnostics.errors`, by position, or that looks for a root `invalid_union` entry. That entry said only `Invalid input` and named no key; the entries that name the key were always further down the same list, and they are now first. Read entries by `path` and `code`, not by index.
13+
14+
| Refused save | Was | Now |
15+
|:--|:--|:--|
16+
| A list view with a typo in a column's `summary` key | `issues[0]` is `{ path: '', code: 'invalid_union', message: 'Invalid input' }`, then the `unrecognized_keys` entry | `issues[0]` is the `unrecognized_keys` entry naming `type` and `columns` |
17+
| A view whose `label` is a map keyed by something other than a locale | `invalid_union` / `Invalid input` at `''` and again at `label`, then two `label.not_a_locale` entries | only the two `label.not_a_locale` entries: `invalid_key`, then the locale-tag prescription |
18+
| The `meta-envelope` face's headline for the first row | `2 issues — (root) [invalid_union]; (root) [unrecognized_keys]` | `1 issue — (root) [unrecognized_keys]` |
19+
20+
The headline's root locator is the angle-bracketed word `root`; it is spelled `(root)` above only so this changelog renders it.
21+
22+
**What stays.** A union entry is kept, ahead of what it explains, in every other case:
23+
24+
- its message is the schema's own sentence rather than zod's default. An object whose `titleFormat` is written as a formula still gets, first, the template slot's sentence telling the author to write `'{{record.name}}'`; the entry below it says only `expected "template"`, so dropping the first would drop the fix. An action's `confirmText` written as a formula is the same.
25+
- nothing below explains it: every branch only says the value is the wrong kind (a view's `label: 42`), or the nesting bound was reached. Then it is the whole answer for that slot.
26+
- it is a container's entry (`invalid_key`, `invalid_element`): its code is the one place that says the key was refused rather than the value under it.
27+
28+
The comparison is against zod's exact default text, held in one constant in the producer and pinned against a real zod parse, so a zod upgrade that rewords the default fails a test instead of quietly bringing every such entry back.
29+
30+
**Unchanged, on purpose.** The terminal renderer (`formatZodError`, the CLI) still prints the union line as the parent of its indented tree, and the data API's `fields[]` (`zodIssuesToFields`, `400 VALIDATION_ERROR`) still carries it as an `invalid_shape` entry; whether that one follows is #35433. The cross-package parity test records the asymmetry.
31+
32+
**Known regression, until #35499 lands.** Studio's metadata form draws a refusal's entry on a field row only when the entry's path equals that row's key. On about 25 top-level keys (for example a view's `label`, `description`, `columns` and `exportOptions`) the dropped entry was the only one at that exact path, so after a refused save that row shows one red line fewer: the `Invalid input` line. The place is still named by the entries themselves and in the Save button's tooltip, and on a type with a live validator the next edit redraws the row. #35499 makes the form show the located cause on the row it sits under.

‎packages/metadata-protocol/src/metadata-diagnostics.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,9 +330,11 @@ function parseDiagnostics(schema: z.ZodType, candidate: unknown): MetadataDiagno
330330
// KIND, fewest-issues wins, `unrecognized_keys` breaks the tie, ties all
331331
// emitted under a cap, nested unions recursed with absolute paths) is
332332
// defined once, so opening a broken document and saving it give the author
333-
// the same words. The expansion is strictly additive — the union's own
334-
// entry is still first, so any consumer reading `errors[0]` today reads the
335-
// same entry after this change.
333+
// the same words — including which union heads stay: a head that is only
334+
// zod's bare `"Invalid input"` is dropped once an entry below explains it,
335+
// so `errors[0]` is the first located cause, and a head carrying the
336+
// schema's own sentence stays ahead of its causes. Read entries by `path`
337+
// and `code`, never by index.
336338
const errors = zodIssuesToMetadataIssues(parsed.error.issues);
337339

338340
return { valid: false, errors };

‎packages/metadata-protocol/src/metadata-diagnostics.union-issues.test.ts‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
* policy — so the ranking's own behaviour stays pinned where it is defined
2323
* (`protocol.save-union-issues.test.ts`) and is not restated here.
2424
*/
25+
// Pays the lint root's first load at collection, never inside a clocked case.
26+
import './lint-root-preload.testkit.js';
2527
import { describe, expect, it } from 'vitest';
2628
import { getMetadataTypeSchema } from '@objectstack/spec/kernel';
2729
import type { z } from 'zod';
@@ -46,23 +48,16 @@ describe('#5598 computeMetadataDiagnostics — a stored view names the offending
4648
const diag = computeMetadataDiagnostics('view', brokenView);
4749

4850
expect(diag?.valid).toBe(false);
49-
// The defect, stated as a number: this was exactly 1 before the fix.
50-
expect(diag?.errors?.length).toBeGreaterThan(1);
51-
52-
// Additive, not replacing: the union's own entry is still first, so a
53-
// consumer reading `errors[0]` reads the same entry it always did.
54-
expect(diag?.errors?.[0]).toEqual({
55-
path: '',
56-
message: 'Invalid input',
57-
code: 'invalid_union',
58-
});
59-
60-
// ...and the branch behind it is the one that names keys. The #4001
61-
// curated prose itself is spec-owned and deliberately not pinned here —
62-
// what this file guards is that a KEY reaches the consumer at all.
63-
const explained = diag?.errors?.slice(1) ?? [];
64-
expect(explained.some((e) => e.code === 'unrecognized_keys')).toBe(true);
65-
expect(explained.some((e) => e.message.includes('`columns`'))).toBe(true);
51+
// The defect, stated as an entry: before the fix this was the ONLY one.
52+
// [#35400] Since the bare head is dropped once a branch explains it, it
53+
// is now not served at all — the save path's 422 answers the same.
54+
expect(diag?.errors?.some((e) => e.path === '' && e.code === 'invalid_union')).toBe(false);
55+
56+
// ...and the branch that names keys is first. The #4001 curated prose
57+
// itself is spec-owned and deliberately not pinned here — what this file
58+
// guards is that a KEY reaches the consumer at all.
59+
expect(diag?.errors?.[0]?.code).toBe('unrecognized_keys');
60+
expect(diag?.errors?.[0]?.message).toContain('`columns`');
6661
});
6762

6863
it('serves the same verdict the save path serves — one ranking, not two', () => {
@@ -84,7 +79,7 @@ describe('#5598 computeMetadataDiagnostics — a stored view names the offending
8479
_diagnostics?: { valid: boolean; errors?: Array<{ code?: string }> };
8580
};
8681
expect(decorated._diagnostics?.valid).toBe(false);
87-
expect(decorated._diagnostics?.errors?.length).toBeGreaterThan(1);
82+
expect(decorated._diagnostics?.errors?.[0]?.code).toBe('unrecognized_keys');
8883
});
8984

9085
it('re-decorating an already-decorated item is stable — the strip still runs', () => {

‎packages/metadata-protocol/src/protocol-metadata-issues.ts‎

Lines changed: 67 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ const NESTED_EXPANSION_DEPTH_LIMIT = 3;
4848

4949
const UNION_BRANCH_EMIT_LIMIT = 3;
5050

51+
/**
52+
* [#35400] zod's own message for a failed union — the text a union head carries
53+
* when its schema declared no `error` of its own. {@link collectMetadataIssues}
54+
* drops an explained head only when its message is exactly this, so a head
55+
* carrying the schema's own sentence is never mistaken for filler.
56+
*
57+
* A literal, so the rule is only as good as its match with zod's current
58+
* wording: `protocol.save-union-issues.test.ts` pins this value against a real
59+
* failed union parse, so a zod upgrade that rewords the default fails that test
60+
* instead of silently turning the drop off. Exported for that pin only;
61+
* `protocol.ts` does not re-export it.
62+
*/
63+
export const ZOD_UNION_DEFAULT_MESSAGE = 'Invalid input';
64+
5165
/**
5266
* [#5389/#8783] The issue codes that hang their real diagnosis on
5367
* `issue.issues` rather than on `invalid_union`'s `issue.errors`.
@@ -188,34 +202,50 @@ function selectUnionBranches(
188202
/**
189203
* One issue → its `issues[]` entries, appended to `out`.
190204
*
191-
* An ordinary issue is one entry. An `invalid_union` is its own entry (zod's
192-
* bare `"Invalid input"`) FOLLOWED by the entries of the branches that explain
193-
* it, with `path` resolved against the union's own — branch paths are RELATIVE
194-
* to it, which is the trap #5014 paid for: a branch issue's `path` names a slot
195-
* inside the union member, not inside the document.
205+
* An ordinary issue is one entry. An `invalid_union` is followed by the entries
206+
* of the branches that explain it, with `path` resolved against the union's own
207+
* — branch paths are RELATIVE to it, which is the trap #5014 paid for: a branch
208+
* issue's `path` names a slot inside the union member, not inside the document.
209+
*
210+
* [#35400] The union's own entry — the head — is DROPPED when two things hold
211+
* together: the expansion appended at least one entry, and the head's message
212+
* is exactly {@link ZOD_UNION_DEFAULT_MESSAGE}, zod's bare default for a failed
213+
* union. Such a head says nothing the entries below it do not say better, so a
214+
* refused save's `issues[]` holds located causes, read by `path` and `code`,
215+
* never by position — at every depth, so a view's root head and a nested
216+
* `label` head go alike. The head is KEPT, ahead of what it explains, in every
217+
* other case:
218+
*
219+
* - nothing below explains it — every branch a bare kind mismatch, zod's
220+
* "matched multiple" `errors: []`, or the depth bound reached — so it is the
221+
* whole answer;
222+
* - its message is the schema's own sentence (a union declared with an `error`,
223+
* such as the template slot's "write '{{record.name}}' …" or a view's
224+
* retirement prescription). That sentence is a prescription, and it is often
225+
* said nowhere else in the list, so dropping the head would drop the fix.
226+
*
227+
* This reverses the "strictly additive, `issues[0]` unmoved" design #5364
228+
* shipped (released in 17.0.0), by the maintainer's rulings on #35400. Both
229+
* spec walks KEEP every head (`formatZodIssue` prints it as the parent line of
230+
* an indented tree, `zodIssuesToFields` emits it as `invalid_shape`); that
231+
* asymmetry is recorded in `union-branch-policy.cross-package-parity.test.ts`
232+
* §4.
196233
*
197234
* [#8783] A {@link CONTAINER_ISSUE_CODES} issue descends the same way and for
198-
* the same reason, into `issue.issues` instead of `issue.errors`, with two
235+
* the same reason, into `issue.issues` instead of `issue.errors`, with three
199236
* differences: nothing is ranked (a container has one inner schema, so every
200-
* issue it raised is true — see the note on the code set), and the descent is
201-
* only taken when the issue's own code says the payload is a container's. That
202-
* second half is what keeps this targeted: an `issues` array hanging off any
203-
* other code is left alone, so the walk did not become "descend whatever
204-
* nests".
205-
*
206-
* The wrapper's entry is kept rather than replaced — for the union and the
207-
* container alike: it is the only entry naming the slot the client sent,
208-
* existing consumers already read it, and when nothing below is informative it
209-
* is still the whole answer. So the expansion is strictly ADDITIVE — no entry
210-
* that shipped before this changed is gone or renumbered, only newly
211-
* accompanied. Both spec walks were measured to do the same before #8783 copied
212-
* them (`formatZodIssue` prints the wrapper line then the indented detail;
213-
* `zodIssuesToFields` emits the `invalid_shape` wrapper then the detail entry).
237+
* issue it raised is true — see the note on the code set); the descent is only
238+
* taken when the issue's own code says the payload is a container's, so an
239+
* `issues` array hanging off any other code is left alone and the walk did not
240+
* become "descend whatever nests"; and the container's own entry is KEPT ahead
241+
* of what it explains, because its code is the one place that says the KEY was
242+
* refused (`invalid_key`) rather than the value under it.
214243
*
215244
* `seen` de-duplicates entries *within one top-level issue*: two branches that
216-
* reject the same key with the same words say it once. Expanded entries — union
217-
* and container heads alike — are exempt, since two same-path wrapper entries
218-
* can head genuinely different sub-trees.
245+
* reject the same key with the same words say it once. Expanded heads — union
246+
* and container alike — are exempt, since two same-path wrapper entries can
247+
* head genuinely different sub-trees; a union head kept by the rule above stays
248+
* exempt too, exactly as the spec walks treat it.
219249
*
220250
* Deliberate divergence from the spec-side renderer: where it prints a trailing
221251
* "… and N more branches rejected this value", this emits nothing. That line is
@@ -255,19 +285,25 @@ function collectMetadataIssues(
255285
const key = JSON.stringify([entry.path, entry.code, entry.message]);
256286
if (seen.has(key)) return;
257287
seen.add(key);
288+
out.push(entry);
289+
return;
258290
}
259-
out.push(entry);
260-
if (!expandable) return;
261291

262292
if (branches.length > 0) {
293+
const below: MetadataIssueEntry[] = [];
263294
for (const branch of selectUnionBranches(branches)) {
264295
for (const nested of branch) {
265-
collectMetadataIssues(nested, path, depth + 1, seen, out);
296+
collectMetadataIssues(nested, path, depth + 1, seen, below);
266297
}
267298
}
299+
// The head stays ahead of what it explains unless BOTH hold: something
300+
// below explains it, and it says nothing of its own (see the docblock).
301+
if (below.length === 0 || entry.message !== ZOD_UNION_DEFAULT_MESSAGE) out.push(entry);
302+
out.push(...below);
268303
return;
269304
}
270305

306+
out.push(entry);
271307
// Unranked, and every one of them: see {@link CONTAINER_ISSUE_CODES}.
272308
for (const nested of contained) {
273309
collectMetadataIssues(nested, path, depth + 1, seen, out);
@@ -304,7 +340,11 @@ function collectMetadataIssues(
304340
*
305341
* Branch selection is described on {@link selectUnionBranches} and is identical
306342
* to the other copies by construction; the container descent is described on
307-
* {@link CONTAINER_ISSUE_CODES}.
343+
* {@link CONTAINER_ISSUE_CODES}. What this envelope does NOT share with them is
344+
* the union's own entry when it is zod's bare default: it is dropped wherever an
345+
* entry below explains it (#35400, on {@link collectMetadataIssues}), so
346+
* `issues[0]` of a refused view save is the first located cause, not that
347+
* rootless line. Read entries by `path` and `code`, never by index.
308348
*/
309349
export function zodIssuesToMetadataIssues(issues: unknown): MetadataIssueEntry[] {
310350
if (!Array.isArray(issues)) return [];

‎packages/metadata-protocol/src/protocol.container-issue-descent.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@
5050
* expanding exactly as it did, a plain issue still passing through untouched,
5151
* and an `issues` payload on any other code still ignored.
5252
*/
53+
// Pays the lint root's first load at collection, never inside a clocked case.
54+
import './lint-root-preload.testkit.js';
5355
import { describe, expect, it } from 'vitest';
5456
import { z } from 'zod';
5557
// [#5619] The producer's OWN write-verb dispatch decisions, so the fake engine
@@ -275,9 +277,10 @@ describe('#8783 controls — a second descent, not a widened walk', () => {
275277
]);
276278
});
277279

278-
it('an `invalid_union` still expands by the ranking, unchanged', () => {
280+
it('an `invalid_union` still expands by the ranking', () => {
279281
// Verbatim the #5364 pin: fewest issues wins, `unrecognized_keys`
280-
// breaks the tie. Container descent must not have perturbed it.
282+
// breaks the tie. Container descent must not have perturbed it. [#35400]
283+
// The union's bare head is dropped because the branch explains it.
281284
const out = zodIssuesToMetadataIssues([union([
282285
[{ code: 'invalid_value', message: 'wrong discriminator', path: ['kind'] }],
283286
[{ code: 'unrecognized_keys', message: 'Unrecognized key(s): `nmae`', path: [] }],
@@ -288,7 +291,6 @@ describe('#8783 controls — a second descent, not a widened walk', () => {
288291
])]);
289292

290293
expect(out).toEqual([
291-
{ path: '', message: 'Invalid input', code: 'invalid_union' },
292294
{ path: '', message: 'Unrecognized key(s): `nmae`', code: 'unrecognized_keys' },
293295
]);
294296
});
@@ -326,6 +328,9 @@ describe('#8783 controls — a second descent, not a widened walk', () => {
326328
it('a union BELOW a container is expanded by the ranking, not emitted whole', () => {
327329
// The two descents compose, and each level applies its own rule: the
328330
// container emits every issue it has, the union below it selects.
331+
// [#35400] And each keeps its own head rule: the container's head stays
332+
// (its code says the KEY was refused); the union's bare head, explained
333+
// by the branch it selected, goes.
329334
const out = zodIssuesToMetadataIssues([{
330335
code: 'invalid_key',
331336
message: 'Invalid key in record',
@@ -338,7 +343,6 @@ describe('#8783 controls — a second descent, not a widened walk', () => {
338343

339344
expect(out.map((e) => [e.path, e.code])).toEqual([
340345
['m.ab', 'invalid_key'],
341-
['m.ab', 'invalid_union'],
342346
['m.ab', 'unrecognized_keys'],
343347
]);
344348
});

0 commit comments

Comments
 (0)