Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 154 additions & 1 deletion packages/spec/src/shared/retired-key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import { describe, it, expect } from 'vitest';
import { z } from 'zod';

import { acceptRetiredDefaultResidue, retiredKey } from './retired-key';
import { acceptRetiredDefaultResidue, enumWithRetiredValues, retiredKey } from './retired-key';
import { strictObject } from './strict-object';

const GONE_GUIDANCE =
Expand Down Expand Up @@ -135,3 +135,156 @@ describe('acceptRetiredDefaultResidue (#12840)', () => {
expect((def.out as { _zod: { def: { type: string } } })._zod.def.type).toBe('object');
});
});

// ============================================================================
// VALUE-level retirement (#17109)
// ============================================================================

/**
* Contract of `enumWithRetiredValues` — the VALUE-level sibling of the
* tombstones above (#17109; maintainer ruling 2026-09-09, the generic helper
* rather than a refinement on the single enum that exposed the gap).
*
* The class rule under test: a retired enum MEMBER refuses at parse **by
* name**, carrying its own migration prescription, while every other member
* and every unrelated typo is left exactly as `z.enum` had them. Like the
* residue suite above, these run over a SYNTHETIC vocabulary on purpose —
* they prove the judgement is general to any `z.enum` (which is what was
* ruled), not a property of the one enum that will consume it first.
*/

/**
* Two synthetic prescriptions, carrying the house shape — backticked
* fully-qualified name first, the version that removed it, a dash clause
* saying why it went, an imperative fix, and (on the first) the pinned
* `os migrate meta` sentence — with ONE element deliberately absent: the
* `(ADR-NNNN)` reference.
*
* ⛔ Do not "complete the shape" by adding one back. An ADR id is the one
* part of a prescription the repo RESOLVES, and `pnpm check:adr-anchors`
* scans `*.test.ts` too, so a fictional retirement cannot carry one
* honestly: a made-up number is the squat that gate refuses — whoever later
* writes a real record at that number retroactively falsifies every citation
* of it — and a number that DOES resolve would let a fake retirement claim
* governance by a decision that never ruled it.
* What these fixtures pin is that a prescription is retrieved and re-thrown
* byte-for-byte — never which record it cites.
*/
const HEADING_RETIRED =
'`text.variant: "heading"` was removed in @objectstack/spec 99 — a heading is a '
+ 'document level, never a text style, so the renderer had to guess one. Use `h2`, or pick the '
+ 'level you mean. '
+ 'Run `os migrate meta --from 98` to list the mechanical edits for existing sources; apply them by hand.';

/** A second retirement on the SAME enum, and one with no conversion behind it. */
const SUBHEADING_RETIRED =
'`text.variant: "subheading"` was removed in @objectstack/spec 99 — same reason as '
+ '`heading`. Use `h3`, or pick the level you mean.';

const VariantEnum = enumWithRetiredValues(
['body', 'caption', 'h1', 'h2', 'h3'],
{ heading: HEADING_RETIRED, subheading: SUBHEADING_RETIRED },
);

describe('enumWithRetiredValues (#17109)', () => {
it('refuses a retired member with ITS OWN prescription, byte-for-byte', () => {
for (const [member, prescription] of [
['heading', HEADING_RETIRED],
['subheading', SUBHEADING_RETIRED],
] as const) {
const r = VariantEnum.safeParse(member);
expect(r.success).toBe(false);
// The envelope, not merely "it threw": zod's own enum issue, with the
// prescription as the message. A second retired member on one enum is
// the recurrence the ruling named — a hand-rolled ternary does not
// reach it, so it is pinned rather than assumed.
expect(r.error!.issues).toHaveLength(1);
expect(r.error!.issues[0]!.code).toBe('invalid_value');
expect(r.error!.issues[0]!.message).toBe(prescription);
}
});

it('leaves every live member accepted and every other refusal untouched', () => {
for (const live of ['body', 'caption', 'h1', 'h2', 'h3']) {
expect(VariantEnum.parse(live)).toBe(live);
}
// A typo is NOT a retirement: telling the author of `headng` that their
// value "was removed" would misinform, so zod's own message — which lists
// the legal tokens — is what they keep.
const typo = VariantEnum.safeParse('headng');
expect(typo.success).toBe(false);
expect(typo.error!.issues[0]!.message).not.toBe(HEADING_RETIRED);
expect(typo.error!.issues[0]!.message).toContain('Invalid option');
});

it('never hands back an inherited Object.prototype member as the prescription', () => {
// Asked THROUGH zod this assertion is vacuous: zod 4.4.3 ignores a
// non-string error-map return and falls back to its own message, so a bare
// `retired[input]` lookup — which answers `constructor` with a FUNCTION —
// is indistinguishable at the message level. Measured, not assumed: an
// ablation dropping the `hasOwnProperty` guard left all 15 cases green.
// So this asks the helper's OWN error map, where the lookup's answer IS
// the contract — `string` for a retired member, `undefined` for anything
// else — rather than pinning zod's leniency as if it were ours.
const errorMap = (VariantEnum as unknown as {
_zod: { def: { error?: (issue: { code: string; input: unknown }) => unknown } };
})._zod.def.error;
expect(typeof errorMap).toBe('function');
expect(errorMap!({ code: 'invalid_value', input: 'heading' })).toBe(HEADING_RETIRED);
for (const inherited of ['constructor', 'toString', 'hasOwnProperty', '__proto__', 'valueOf']) {
expect(errorMap!({ code: 'invalid_value', input: inherited })).toBeUndefined();
}
// A non-string input reaches the same lookup and must not match either.
for (const nonString of [5, null, {}, ['heading']]) {
expect(errorMap!({ code: 'invalid_value', input: nonString })).toBeUndefined();
}
// End to end, the author of such a typo still meets zod's own message,
// which lists the legal tokens.
const r = VariantEnum.safeParse('constructor');
expect(r.success).toBe(false);
expect(r.error!.issues[0]!.message).toContain('Invalid option');
});

it('composes with `.optional()` — absence is fine, the member still refuses', () => {
const shape = z.object({ variant: VariantEnum.optional() });
expect(shape.safeParse({}).success).toBe(true);
const r = shape.safeParse({ variant: 'heading' });
expect(r.success).toBe(false);
expect(r.error!.issues[0]!.message).toBe(HEADING_RETIRED);
expect(r.error!.issues[0]!.path).toEqual(['variant']);
});

it('composes with `.default(…)` — the default materializes, the member still refuses', () => {
// The sharp case the first consumer presents: the enum carries a default,
// so a document that omits the key never meets the refusal at all, while
// one that WRITES the retired member does. (A retired member that was
// itself the default is a different population — `acceptRetiredDefaultResidue`.)
const shape = z.object({ variant: VariantEnum.default('body') });
expect(shape.parse({})).toEqual({ variant: 'body' });
expect(shape.parse({ variant: 'h3' })).toEqual({ variant: 'h3' });
const r = shape.safeParse({ variant: 'heading' });
expect(r.success).toBe(false);
expect(r.error!.issues[0]!.message).toBe(HEADING_RETIRED);
});

it('excludes the retired member from `z.input` — the tsc channel, same as a key tombstone', () => {
const live: z.input<typeof VariantEnum> = 'h2';
// @ts-expect-error — the retirement removes the member from the input
// union, so an author writing it fails to compile before anything runs.
const retiredMember: z.input<typeof VariantEnum> = 'heading';
expect(live).toBe('h2');
expect(retiredMember).toBe('heading');
});

it('refuses at CONSTRUCTION a retirement that could never fire', () => {
// Still listed: the enum accepts the value, so the prescription is dead
// declaration — the shape this repo refuses (declared ≠ enforced).
expect(() => enumWithRetiredValues(['body', 'heading'], { heading: HEADING_RETIRED }))
.toThrow(/declared retired but still listed/);
// A wrapper with nothing retired, and a prescription that says nothing.
expect(() => enumWithRetiredValues(['body'], {}))
.toThrow(/no retired member declared/);
expect(() => enumWithRetiredValues(['body'], { heading: ' ' }))
.toThrow(/empty prescription/);
});
});
154 changes: 154 additions & 0 deletions packages/spec/src/shared/retired-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
/**
* Tombstones for RETIRED authorable keys (#3855).
*
* This file carries BOTH retirement axes: a retired **key** ({@link retiredKey},
* plus {@link acceptRetiredDefaultResidue} for one that carried a default), and a
* retired **value** — one member of a `z.enum` ({@link enumWithRetiredValues},
* #17109). Everything below is the KEY-level rule; the value-level one is
* documented on its own helper and differs in what it registers, never in how
* the prescription reads.
*
* Removing a key an author can write has one hard requirement: the removal must
* be **audible**. When these tombstones were introduced, none of the schemas
* carrying a deprecated alias was `.strict()`, so deleting the key from the Zod
Expand Down Expand Up @@ -209,3 +216,150 @@ export function acceptRetiredDefaultResidue<S extends z.ZodObject<z.ZodRawShape>
});
return pipe as unknown as z.ZodType<z.output<S>, z.input<S>> & { readonly shape: S['shape'] };
}

// ============================================================================
// VALUE-level retirement — the sibling axis (#17109)
// ============================================================================

/**
* Retired enum MEMBER → the prescription an author who writes it meets.
*
* Free text, exactly like {@link retiredKey}'s `guidance`, and written to the
* same five conventions (the `spec-property-retirement` skill, §2 "guidance
* 字符串怎么写"): the fully-qualified name in backticks first, the version and
* ADR that removed it, a clause saying why it went, an imperative fix, and —
* where an ADR-0087 conversion covers the surface — the house `os migrate
* meta` sentence. That sentence is pinned class-wide by
* `retired-key-migrate-sentence.test.ts`, a plain TEXT scan over string
* literals with no dependency on `retiredKey()` — so a value retirement's
* prescription is judged by the same pin as a key retirement's, for free and
* with no change to the pin. Its walk yields non-test `.ts` only, which is
* the right boundary (a fixture is not a shipped prescription) and is why
* this helper's own test fixture is NOT evidence the pin fires: planting the
* withdrawn spelling there was measured to leave the pin green.
*
* ⛔ Not a structured `{ from, to }` record. The machine-readable channel for
* a retirement already exists one layer out — the ADR-0087 conversion registry
* and the generated upgrade guide — and the message's job is the one thing
* those cannot do: reach the author standing in front of a parse error. A
* second vocabulary for the same fact is how the two drift apart.
*/
export type RetiredValueGuidance = Readonly<Record<string, string>>;

/**
* Declare an enum whose vocabulary has been NARROWED: `z.enum(values)` with a
* named refusal carrying the migration prescription for each member the
* narrowing retired (#17109, maintainer ruling 2026-09-09 — the generic
* helper, ⛔ deliberately not a refinement on the one enum that surfaced it).
*
* ## The gap this closes
*
* {@link retiredKey} retires a **key**. It has no counterpart for a **value**,
* and the three removal routes in the `spec-property-retirement` skill (§2)
* all address keys — none applies to "the def survives, one member leaves".
* Two enums had already reached for the same hand-rolled shape independently
* (`data/hook-body.zod.ts` `HookBodyCapability.crypto.hash`, `data/object.zod.ts`
* `managedBy: 'system'`), each re-deriving the same judgement in its own
* comment; meanwhile `spec-changes.json` twice records the opposite
* conclusion — "a removed ENUM MEMBER cannot carry a retiredKey() fix-it
* error the way an authorable object key can" (`data.field.changed`, #4673;
* `owd-full-alias-removed`) — and those two retirements shipped with no
* prescription at all. One mechanism, so the diagnosis reads the same
* everywhere and the next narrowing does not have to re-decide.
*
* ## Both authoring channels, same as a key tombstone
*
* 1. **`tsc`.** The retired member is absent from `values`, so `z.input` no
* longer admits it and writing it fails to compile at the authoring site.
* This falls out of the shape rather than being added to it — the retired
* member is declared in `retired`, never in `values`, and the helper
* refuses the two lists overlapping.
* 2. **The parse.** A value reaching the runtime raises the prescription
* itself instead of zod's anonymous `Invalid option: expected one of …`.
* Only the retired member gets it: everything else keeps zod's own
* message, which already lists the legal tokens — telling the author of
* `variant: 'headng'` that their value "was removed" would misinform.
*
* ## What composes, and what it does about a default
*
* The return value is a plain `ZodEnum`, so `.describe()`, `.optional()`,
* `.default(…)`, `.meta()` and every schema walker behave exactly as they do
* on `z.enum(…)` — the retirement rides on the enum's own error map and adds
* no wrapper for anything to resolve through. On a **defaulted** enum an
* omitted key still materializes the default untouched (absence never meets
* the refusal); an explicitly authored retired member still refuses. The one
* case this helper does NOT cover is a retired member that WAS the default —
* then every artifact a released toolchain built carries it materialized, and
* the judgement for that population is {@link acceptRetiredDefaultResidue}'s,
* not this one's.
*
* ## Registration
*
* Nothing here registers itself, and the key-level ledgers have no row shape
* for a value: `RETIRED_KEYS_BY_MAJOR` is keyed `'<defKey>:<name>'` (a key),
* and the liveness ledger is walked per schema PROPERTY, which a member is
* not. Per the skill's §2 table, an enum-value narrowing is also byte-invisible
* to all four generated ratchets — the def, its exports and its key are all
* unchanged. So the declaration channels a narrowing owes are its ADR-0087
* conversion and its changeset, and the prescription below is the only one an
* author meets directly. ⚠️ Declaring a member retired here does not narrow
* anything by itself: delete it from `values` in the same edit, which is what
* the construction-time refusal enforces.
*
* @param values - The enum's LIVE vocabulary, retired members already removed.
* @param retired - Retired member → its prescription. Must be non-empty, and
* must not name anything still in `values`.
*
* @example
* ```ts
* export const HookBodyCapability = enumWithRetiredValues(
* ['api.read', 'api.write', 'api.transaction', 'crypto.uuid', 'log'],
* { 'crypto.hash': CRYPTO_HASH_RETIRED },
* );
* ```
*/
export function enumWithRetiredValues<const T extends readonly [string, ...string[]]>(
values: T,
retired: RetiredValueGuidance,
) {
const names = Object.keys(retired);
if (names.length === 0) {
throw new Error(
'enumWithRetiredValues: no retired member declared — a retirement wrapper that can never fire '
+ 'is a declaration with no enforcement; call `z.enum()` directly instead.',
);
}
const live = new Set<string>(values);
const overlap = names.filter((name) => live.has(name));
if (overlap.length > 0) {
throw new Error(
`enumWithRetiredValues: ${overlap.map((n) => `'${n}'`).join(', ')} declared retired but still listed `
+ 'in the enum — the enum accepts the value, so the prescription can never fire. Delete the member '
+ 'from `values`; the retirement is what removes it.',
);
}
const blank = names.filter((name) => retired[name]?.trim() === '' || retired[name] === undefined);
if (blank.length > 0) {
throw new Error(
`enumWithRetiredValues: ${blank.map((n) => `'${n}'`).join(', ')} declared retired with an empty `
+ 'prescription — the prescription IS the migration doc for whoever hits it. State what replaced '
+ 'the member, the version that removed it, and the one-line fix.',
);
}
return z.enum(values, {
// `hasOwnProperty`, never a bare `retired[input]`: a plain object literal
// inherits `constructor`, `toString` and friends from Object.prototype, so
// the bare lookup answers an author's `variant: 'constructor'` with a
// FUNCTION where this map's contract is `string | undefined`. Measured on
// zod 4.4.3: zod ignores a non-string return and falls back to its own
// message, so the guard buys nothing OBSERVABLE today — it keeps the map
// honest instead of resting on that leniency, and the pin for it asks this
// map directly rather than through a parse. `typeof === 'string'` guards
// the same lookup against a non-string input (a number, an object).
error: (issue) =>
(typeof issue.input === 'string'
&& Object.prototype.hasOwnProperty.call(retired, issue.input)
? retired[issue.input]
: undefined),
});
}
Loading