diff --git a/.changeset/35420-one-rename-rule.md b/.changeset/35420-one-rename-rule.md new file mode 100644 index 00000000000..49951e6d024 --- /dev/null +++ b/.changeset/35420-one-rename-rule.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +--- + +fix(spec): `ObjectSchema.create()`, `defineSeed` and the `defineStack` / CLI unknown-authoring-key report no longer answer a short unknown key with an unrelated one + +Clause-②: no +Metadata-protocol: none + +The strict unknown-key refusal on every `strictObject` surface stopped offering a key of five characters or fewer a rename that is two unrelated edits away: such a key is answered only by a candidate one edit away, an adjacent swap counted as one. `ObjectSchema.create()` and `defineSeed` carried their own copy of the `max(2, len/3)` budget without that screen, so they went on answering, for example, an object key `page` with `name` and a seed key `kind` with `id`. The unknown-authoring-key report that `defineStack` and the CLI print (`… is not a declared … key, so its value is dropped at load — did you mean …?`) used a flat distance of 3 for every key, so `aria` was answered `areas`, and the budget did not follow the key's length. + +All four now read one rename rule. A genuine one-edit slip is still answered (`nmae` → `name`, `labl` → `label`, `queeu` → `queue`), and keys longer than five characters keep the same `max(2, len/3)` budget (for the authoring-key report that budget replaces the flat 3, so an eight-character key three edits away, `descrptn`, is no longer answered, while a nine-character one, `dfltValue` → `defaultValue`, still is); `ObjectSchema.create()` now also ranks its candidates the way the strict refusal does (case and separators folded on both sides, the author's own capitalisation breaking a tie). Only the "did you mean" text changes: no key is accepted or refused that was not before, and no export is added or removed. diff --git a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts index 358e7aeefc1..44e887c45eb 100644 --- a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts +++ b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts @@ -16,7 +16,8 @@ * action-clone half is not chartered; [#30065] its save names the declared * override from the base's paired `.custom` first (ADR-0146 D9 `action`); * - a PERMISSION SET has its clone (§8 item 3, the "New similar" action, which posts - * to `POST /api/v1/data/sys_permission_set`) and no switch named here. + * to the catalog's clone door `POST /api/v1/security/permission-sets/:name/clone` + * since C3 stage 8 retired the row object's data route) and no switch named here. * * The protocol-side pins are * `packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts`; this diff --git a/packages/spec/export-origins/root.json b/packages/spec/export-origins/root.json index 1c5158ea832..45d0a473375 100644 --- a/packages/spec/export-origins/root.json +++ b/packages/spec/export-origins/root.json @@ -178,7 +178,7 @@ "expandViewContainer": "src/ui/view.zod.ts#expandViewContainer (function)", "expandViewContainerWithDiagnostics": "src/ui/view.zod.ts#expandViewContainerWithDiagnostics (function)", "expression": "src/shared/expression.zod.ts#expression (function)", - "findClosestMatches": "src/shared/suggestions.zod.ts#findClosestMatches (function)", + "findClosestMatches": "src/shared/rename-guess.ts#findClosestMatches (function)", "formatSuggestion": "src/shared/suggestions.zod.ts#formatSuggestion (function)", "formatUnknownAuthoringKey": "src/data/authoring-key-lint.ts#formatUnknownAuthoringKey (function)", "formatZodError": "src/shared/error-map.zod.ts#formatZodError (function)", diff --git a/packages/spec/export-origins/shared.json b/packages/spec/export-origins/shared.json index 45378e39153..ebc1742ab4f 100644 --- a/packages/spec/export-origins/shared.json +++ b/packages/spec/export-origins/shared.json @@ -103,14 +103,14 @@ "cron": "src/shared/expression.zod.ts#cron (function)", "currencyForLocale": "src/shared/region-currency.ts#currencyForLocale (function)", "expression": "src/shared/expression.zod.ts#expression (function)", - "findClosestMatches": "src/shared/suggestions.zod.ts#findClosestMatches (function)", + "findClosestMatches": "src/shared/rename-guess.ts#findClosestMatches (function)", "formatSuggestion": "src/shared/suggestions.zod.ts#formatSuggestion (function)", "formatZodError": "src/shared/error-map.zod.ts#formatZodError (function)", "formatZodIssue": "src/shared/error-map.zod.ts#formatZodIssue (function)", "isValueDomainMember": "src/shared/value-domain.zod.ts#isValueDomainMember (function)", "keySetMatches": "src/shared/suggestions.zod.ts#keySetMatches (function)", "lazySchema": "src/shared/lazy-schema.ts#lazySchema (function)", - "levenshteinDistance": "src/shared/suggestions.zod.ts#levenshteinDistance (function)", + "levenshteinDistance": "src/shared/rename-guess.ts#levenshteinDistance (function)", "metaUrlSpellingRefusal": "src/meta-spelling/metadata-url-spelling.ts#metaUrlSpellingRefusal (function)", "normalizeMetadataCollection": "src/shared/metadata-collection.zod.ts#normalizeMetadataCollection (function)", "normalizePluginMetadata": "src/shared/metadata-collection.zod.ts#normalizePluginMetadata (function)", diff --git a/packages/spec/src/data/authoring-key-lint.test.ts b/packages/spec/src/data/authoring-key-lint.test.ts index 2a3500c53e9..00d7fbb836f 100644 --- a/packages/spec/src/data/authoring-key-lint.test.ts +++ b/packages/spec/src/data/authoring-key-lint.test.ts @@ -213,3 +213,35 @@ describe('a typed list declared on an embedded-JSON field is refused with the ch } }); }); + +/** + * The authoring-key lint (read by `defineStack` and the CLI) answers an unknown + * key with the package's ONE rename rule (`shared/rename-guess.ts`). It used to + * pass a flat distance of 3 to `findClosestMatches`, so a four-letter key was + * offered any declared key three edits away, and the budget did not grow or + * shrink with the key. + */ +describe('lintAuthoredRecordKeys — an unknown key gets the shared rename rule', () => { + const declared = ['description', 'label', 'required', 'areas', 'defaultValue']; + + it('a short key two unrelated edits from a declared key gets no rename', () => { + // `aria` → `areas` is one substitution and one insertion: inside the old + // flat 3, outside the one-edit screen a short key gets. + const [f] = runComparator({ aria: 'x' }, declared); + expect(f).toMatchObject({ path: 'p.aria', key: 'aria' }); + expect(f.suggestion).toBeUndefined(); + expect(formatUnknownAuthoringKey(f)).not.toContain('did you mean'); + }); + + it('a one-edit or adjacent-swap slip on a short key is still answered', () => { + expect(runComparator({ lable: 'x' }, declared)[0]?.suggestion).toBe('label'); + expect(runComparator({ lbael: 'x' }, declared)[0]?.suggestion).toBe('label'); + }); + + it('the budget is length-relative: three edits are too many at eight characters, enough at nine', () => { + // Both are three edits from their declared key. `descrptn` (8 characters) + // gets a budget of 2; `dfltValue` (9 characters) gets 3. + expect(runComparator({ descrptn: 'x' }, declared)[0]?.suggestion).toBeUndefined(); + expect(runComparator({ dfltValue: 'x' }, declared)[0]?.suggestion).toBe('defaultValue'); + }); +}); diff --git a/packages/spec/src/data/authoring-key-lint.ts b/packages/spec/src/data/authoring-key-lint.ts index a2d3a01b682..ebad5a51e87 100644 --- a/packages/spec/src/data/authoring-key-lint.ts +++ b/packages/spec/src/data/authoring-key-lint.ts @@ -43,7 +43,7 @@ * @see ADR-0049 enforce-or-remove · ADR-0104 · #4001 (the strict tiers) */ -import { findClosestMatches } from '../shared/suggestions.zod'; +import { suggestRename } from '../shared/rename-guess'; /** * Which authoring surface a finding came from — a metadata type machine name @@ -267,7 +267,9 @@ export function lintAuthoredRecordKeys( // A retirement (`why`, no `to`) deliberately suppresses the edit-distance // fallback: there IS no successor, and the nearest declared key by spelling // is noise — `pii` is 3 edits from `min`, which would read as real advice. - const suggestion = hint?.to ?? (hint?.why ? undefined : findClosestMatches(key, candidates, 3, 1)[0]); + // The fallback is the package's one rename rule (`shared/rename-guess.ts`): + // a flat distance of 3 answered a short key with anything three edits away. + const suggestion = hint?.to ?? (hint?.why ? undefined : suggestRename(key, candidates)); out.push({ path: `${basePath}.${key}`, surface, diff --git a/packages/spec/src/data/default-value-shape.test.ts b/packages/spec/src/data/default-value-shape.test.ts index 673ca13373b..b7c50cea76c 100644 --- a/packages/spec/src/data/default-value-shape.test.ts +++ b/packages/spec/src/data/default-value-shape.test.ts @@ -219,3 +219,25 @@ describe('suggestDefaultValueToken — Object.prototype fall-through', () => { expect(suggestDefaultValueToken('current_time')).toBe('NOW()'); }); }); + +/** + * A literal default is judged by the value shape's own refusal, so its detail + * carries the package's ONE rename rule (`shared/rename-guess.ts`) — pinned at + * this door because `actionableValueIssueMessage`'s docblock restates it. + */ +describe('checkLiteralDefaultValue — a short unknown key gets the shared rename rule', () => { + it('a short key two unrelated edits from a member is offered nothing', () => { + const v = checkLiteralDefaultValue({ type: 'location' }, { lat: 1, lng: 2, lon: 3 }); + expect(v.ok).toBe(false); + if (v.ok) return; + expect(v.detail).toContain('Unrecognized key(s) on this location value: `lon`.'); + expect(v.detail).not.toContain('Did you mean'); + }); + + it('a genuine one-edit slip on a short key is still answered', () => { + const v = checkLiteralDefaultValue({ type: 'location' }, { lat: 1, lng: 2, lgn: 3 }); + expect(v.ok).toBe(false); + if (v.ok) return; + expect(v.detail).toContain('Did you mean `lgn` → `lng`?'); + }); +}); diff --git a/packages/spec/src/data/default-value-shape.ts b/packages/spec/src/data/default-value-shape.ts index ffc4471cc0e..4b70e376ce8 100644 --- a/packages/spec/src/data/default-value-shape.ts +++ b/packages/spec/src/data/default-value-shape.ts @@ -122,10 +122,11 @@ export interface LiteralDefaultValueVerdict { * The rename IS the prescription. Which channel produced it depends on the * key, and the two cases this function is pinned against are one of each — so * "the curated `aliases` map is what makes the rename possible" is true of only - * half of them. The fallback budget is `Math.max(2, Math.floor(key.length / 3))` - * (`shared/suggestions.zod.ts`), and the lookup is - * `aliases[aliasProbe(key)] ?? findClosestMatches(key, knownKeys, budget, 1)[0]` - * — the table is consulted first and wins outright. + * half of them. The fallback is `suggestRename` (`shared/rename-guess.ts`, the + * package's one rename rule: budget `max(2, floor(len / 3))`, and at five + * characters or fewer one edit counting an adjacent swap as one), and the + * lookup is `aliases[aliasProbe(key)] ?? suggestRename(key, knownKeys)` — the + * table is consulted first and wins outright. * * - `postal_code` -> `postalCode`, the example rendered above, is the * FALLBACK's own answer: scoring folds case and separators on both sides, so diff --git a/packages/spec/src/data/define-seed-record-keys.test.ts b/packages/spec/src/data/define-seed-record-keys.test.ts index c3b0c194c2c..e25718c5ae6 100644 --- a/packages/spec/src/data/define-seed-record-keys.test.ts +++ b/packages/spec/src/data/define-seed-record-keys.test.ts @@ -193,3 +193,26 @@ describe('defineSeed holds a `columns` key to the same column set (#25761)', () expect(error.message).toContain('columns: `stauts` is not a field of `crm_lead`'); }); }); + +/** + * `defineSeed` answers an unknown record key with the package's ONE rename rule + * (`shared/rename-guess.ts`). It used to pass `max(2, len/3)` to + * `findClosestMatches` itself, without the short-key screen, so a short key was + * offered any column two unrelated edits away. + */ +describe('defineSeed — a short unknown key gets the shared rename rule', () => { + it('a short key two unrelated edits from a column is offered nothing', () => { + // `kind` → `id` is two deletions, inside the old budget of 2. + const rows: Record[] = [{ first_name: 'Gil', kind: 'web' }]; + const error = refusalOf(() => defineSeed(Lead, { externalId: 'first_name', records: rows })); + expect(error.message).toContain('records[0]: `kind` is not a field of `crm_lead`.\n'); + expect(error.message).not.toContain('Did you mean'); + }); + + it('a genuine one-edit slip on a short key is still answered', () => { + // An adjacent swap counts as one edit. + const rows: Record[] = [{ first_name: 'Hal', queeu: 'support' }]; + const error = refusalOf(() => defineSeed(Lead, { externalId: 'first_name', records: rows })); + expect(error.message).toContain("records[0]: `queeu` is not a field of `crm_lead`. Did you mean 'queue'?"); + }); +}); diff --git a/packages/spec/src/data/field-value.test.ts b/packages/spec/src/data/field-value.test.ts index db3126475fc..75b0f50f0e1 100644 --- a/packages/spec/src/data/field-value.test.ts +++ b/packages/spec/src/data/field-value.test.ts @@ -547,3 +547,28 @@ describe('valueSchemaFor — stored form (field-zoo reality)', () => { }); }); }); + +/** + * The value shapes answer an unknown key through `strictObject`, so they read + * the package's ONE rename rule (`shared/rename-guess.ts`) — pinned here at + * this door so the comment on `LocationValueSchema` that names the rule cannot + * drift from what the door does. + */ +describe('LocationValueSchema — a short unknown key gets the shared rename rule', () => { + const messageFor = (extra: Record): string => { + const result = LocationValueSchema.safeParse({ lat: 1, lng: 2, ...extra }); + if (result.success) throw new Error('expected LocationValueSchema to refuse the value'); + return result.error.issues.find((i) => i.code === 'unrecognized_keys')?.message ?? ''; + }; + + it('a short key two unrelated edits from a member is offered nothing', () => { + // `lon` is two edits from both `lat` and `lng`, inside the old budget of 2. + const m = messageFor({ lon: 3 }); + expect(m).toContain('Unrecognized key(s) on this location value: `lon`.'); + expect(m).not.toContain('Did you mean'); + }); + + it('a genuine one-edit slip on a short key is still answered', () => { + expect(messageFor({ lgn: 3 })).toContain('Did you mean `lgn` → `lng`?'); + }); +}); diff --git a/packages/spec/src/data/field-value.zod.ts b/packages/spec/src/data/field-value.zod.ts index e91212ba468..a9a9b881e25 100644 --- a/packages/spec/src/data/field-value.zod.ts +++ b/packages/spec/src/data/field-value.zod.ts @@ -430,8 +430,10 @@ export const LocationValueSchema = lazySchema(() => strictObject( + 'dropped — the value parsed green with the key gone, so the mistake surfaced only as a ' + 'blank on screen.', // The retired spec-only spelling (see the module header). The two entries - // play DIFFERENT roles and neither is optional. The fallback budget is - // `Math.max(2, Math.floor(key.length / 3))` (`shared/suggestions.zod.ts`). + // play DIFFERENT roles and neither is optional. The fallback is + // `suggestRename` (`shared/rename-guess.ts`, the package's one rename + // rule): budget `max(2, floor(len / 3))`, and at five characters or fewer + // one edit counting an adjacent swap as one. // // - `longitude` → `lng` is the unreachable case: 6 edits against a budget // of 3, and no other declared member is closer, so without this entry @@ -441,7 +443,7 @@ export const LocationValueSchema = lazySchema(() => strictObject( // a declared member 2 edits away, inside the budget, so the bare // fallback answers `latitude` → `altitude`. This entry OVERRULES a // confident wrong answer rather than filling a gap, which is the other - // job an alias does: `aliases[aliasProbe(key)] ?? findClosestMatches(…)` + // job an alias does: `aliases[aliasProbe(key)] ?? suggestRename(…)` // consults the table first and wins outright. // // The value contract has refused the pair since ADR-0104 D1, so the rename diff --git a/packages/spec/src/data/object.test.ts b/packages/spec/src/data/object.test.ts index 731aecac44c..a072ad12003 100644 --- a/packages/spec/src/data/object.test.ts +++ b/packages/spec/src/data/object.test.ts @@ -1259,12 +1259,12 @@ describe('ObjectSchema.create()', () => { expect(message).toContain('ADR-0032 "no silent failure"'); }); - // #4990 note 1 asked whether this file's own `suggestKey` shares the - // camelCase weakness that `findClosestMatches` had. It does NOT: it already - // lowercases BOTH sides (`editDistance(unknown.toLowerCase(), - // key.toLowerCase())`), so a declared key's capitals were never charged to - // the author here. Pinning it means the two suggesters cannot drift apart - // again — this is the property #4990 fixed in the other one. + // #4990 note 1 asked whether this file's own suggester shares the + // camelCase weakness that `findClosestMatches` had. It did not, and it no + // longer has a suggester of its own: `create()` answers with the shared + // `suggestRename` (`shared/rename-guess.ts`), which folds case on BOTH + // sides, so a declared key's capitals are never charged to the author. + // Pinning it keeps the property #4990 fixed at this door too. it('suggestKey judges a typo identically in either case', () => { const bullet = (key: string): string => { try { @@ -3109,3 +3109,35 @@ describe('ObjectSchema.fields — __proto__ / constructor / prototype key refusa expect(site?.declaredPatterns).toEqual(['banned-keys', 'banned-keys']); }); }); + +/** + * `ObjectSchema.create()` answers an unknown key with the package's ONE rename + * rule (`shared/rename-guess.ts`). It used to carry its own copy of the + * `max(2, len/3)` budget, without the short-key screen the strict refusal + * gained, so a four-letter key was offered any declared key two unrelated + * edits away. + */ +describe('ObjectSchema.create — a short unknown key gets the shared rename rule', () => { + const bulletFor = (key: string): string => { + try { + ObjectSchema.create({ + name: 'demo', + fields: {}, + [key]: 1, + } as Record as Parameters[0]); + } catch (e) { + return ((e as Error).message.split('\n').find((l) => l.trim().startsWith('•')) ?? '').trim(); + } + throw new Error(`expected ObjectSchema.create to reject \`${key}\``); + }; + + it('a short key two unrelated edits from a declared key is offered nothing', () => { + // `page` → `name` is two substitutions, inside the old budget of 2. + expect(bulletFor('page')).toBe('• `page` is not an ObjectSchema field.'); + }); + + it('a genuine one-edit slip on a short key is still answered', () => { + expect(bulletFor('nmae')).toContain('did you mean `name`'); + expect(bulletFor('labl')).toContain('did you mean `label`'); + }); +}); diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index aa4d6db8f86..a4b90474aa4 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -23,6 +23,7 @@ import { MetadataProtectionFields } from '../kernel/metadata-protection.zod'; import { closedObject, strictObject } from '../shared/strict-object'; import { ProtectionSchema } from '../shared/protection.zod'; import { retiredKey } from '../shared/retired-key'; +import { suggestRename } from '../shared/rename-guess'; import { refuseRecordProtoKey } from '../shared/record-proto-key-guard'; import { bannedKeys } from '../shared/refinement-projection'; import { FIELD_GROUP_KEY_PATTERN } from './field-group-layout'; @@ -4887,40 +4888,6 @@ function snakeCaseToLabel(name: string): string { .join(' '); } -/** Levenshtein edit distance — backs the "did you mean" hint for typo'd keys. */ -function editDistance(a: string, b: string): number { - const dp: number[][] = Array.from({ length: a.length + 1 }, () => - new Array(b.length + 1).fill(0), - ); - for (let i = 0; i <= a.length; i++) dp[i][0] = i; - for (let j = 0; j <= b.length; j++) dp[0][j] = j; - for (let i = 1; i <= a.length; i++) { - for (let j = 1; j <= b.length; j++) { - dp[i][j] = a[i - 1] === b[j - 1] - ? dp[i - 1][j - 1] - : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]); - } - } - return dp[a.length][b.length]; -} - -/** Closest known key within a small edit distance, for typo hints (`indexs` → `indexes`). */ -function suggestKey(unknown: string, knownKeys: string[]): string | undefined { - let best: string | undefined; - let bestDist = Infinity; - for (const key of knownKeys) { - const d = editDistance(unknown.toLowerCase(), key.toLowerCase()); - if (d < bestDist) { - bestDist = d; - best = key; - } - } - // Only suggest when the keys are genuinely close (guards against noise). - return best !== undefined && bestDist <= Math.max(2, Math.floor(unknown.length / 3)) - ? best - : undefined; -} - /** * Builds a precise, fixable error for unknown top-level keys on * `ObjectSchema.create()` — the metadata-shape analogue of ADR-0032's "no @@ -4933,7 +4900,10 @@ function unknownKeyError(objectName: unknown, unknownKeys: string[], knownKeys: const lines = unknownKeys.map((key) => { const guidance = UNKNOWN_KEY_GUIDANCE[key]; if (guidance) return ` • ${guidance}`; - const suggestion = suggestKey(key, knownKeys); + // The package's one rename rule (`shared/rename-guess.ts`): the same budget + // and short-key screen every `strictObject` refusal answers with, so a + // short key is never offered an unrelated one here either. + const suggestion = suggestRename(key, knownKeys); return suggestion ? ` • \`${key}\` is not an ObjectSchema field — did you mean \`${suggestion}\`?` : ` • \`${key}\` is not an ObjectSchema field.`; diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index ae3e37548df..908ec97570c 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -11,7 +11,8 @@ import { enumWithRetiredValues } from '../shared/retired-key'; import { strictObject } from '../shared/strict-object'; import { MetadataProtectionFields } from '../kernel/metadata-protection.zod'; import { LocaleSchema } from '../system/translation.zod'; -import { findClosestMatches, formatSuggestion } from '../shared/suggestions.zod'; +import { formatSuggestion } from '../shared/suggestions.zod'; +import { suggestRename } from '../shared/rename-guess'; import { resolveInjectedSystemColumns, type InjectedSystemColumnName } from './injected-system-columns'; import { ColumnApplyOnSchema } from './column-apply-on.zod'; import { dependentRequired } from '../shared/refinement-projection'; @@ -613,9 +614,11 @@ function assertSeedKeysDeclared( if (knownSet.has(key)) return; unknownKeys.add(key); surfaces.add(surface); - const suggestion = formatSuggestion( - findClosestMatches(key, known, Math.max(2, Math.floor(key.length / 3)), 1), - ); + // The package's one rename rule (`shared/rename-guess.ts`), so a short + // key is not offered an unrelated field: `nmae` is one swap from `name` and + // is still offered it, `amt` is two unrelated edits from `name` and is not. + const guess = suggestRename(key, known); + const suggestion = formatSuggestion(guess === undefined ? [] : [guess]); lines.push( ` • ${where}: \`${key}\` is not a field of \`${objectDef.name}\`.` + (suggestion ? ` ${suggestion}` : ''), diff --git a/packages/spec/src/shared/rename-guess.ts b/packages/spec/src/shared/rename-guess.ts new file mode 100644 index 00000000000..0939124b25c --- /dev/null +++ b/packages/spec/src/shared/rename-guess.ts @@ -0,0 +1,188 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The rename guess an unknown key is offered — ONE rule, read by every + * unknown-key suggester in this package. + * + * The doors that answer an unknown key with "did you mean" all call + * {@link suggestRename}: the shared `strictUnknownKeyError` (every + * `strictObject` surface, including the value shapes of + * `data/field-value.zod.ts` that `data/default-value-shape.ts` reads back), + * `ObjectSchema.create()` (`data/object.zod.ts`), `defineSeed` + * (`data/seed.zod.ts`) and the authoring-key lint `defineStack` and the CLI + * report through (`data/authoring-key-lint.ts`). The last three used to spell + * their own budget — two copies of `max(2, len/3)` without the short-key screen + * below, and a flat distance of 3 — so after the screen was settled on the + * first door they kept answering a short key with an unrelated one. This module + * is now the only spelling of the budget and the screen; `suggestions.test.ts` + * fails on a source file that spells either again. + * + * Out of its reach on purpose: suggesters that rank a closed VALUE vocabulary + * rather than guess a key's rename — the enum-value hint in `error-map.zod.ts` + * and `suggestFieldType` — keep `findClosestMatches`' own default. + * + * A leaf module on purpose: it imports nothing, so `suggestions.zod.ts` (which + * `strict-object.ts` imports, which nearly every closed schema imports) can read + * it without joining a cycle, and `data/*.zod.ts` can read it without importing + * the refusal factory. `levenshteinDistance` and `findClosestMatches` are + * re-exported from `suggestions.zod.ts` unchanged, so the published names and + * their import path stay where they were. `suggestRename` and + * {@link renameBudget} are deliberately **not** re-exported from + * `shared/index.ts` — like `alias-probe.ts`, an internal seam, not part of the + * `@objectstack/spec` contract. + */ + +/** + * Compute Levenshtein edit distance between two strings. + * Uses space-optimized two-row approach (O(min(m,n)) space). + */ +export function levenshteinDistance(a: string, b: string): number { + const la = a.length; + const lb = b.length; + + if (la === 0) return lb; + if (lb === 0) return la; + + // Use only two rows for space efficiency + let prev = new Array(lb + 1); + let curr = new Array(lb + 1); + + for (let j = 0; j <= lb; j++) { + prev[j] = j; + } + + for (let i = 1; i <= la; i++) { + curr[0] = i; + for (let j = 1; j <= lb; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + curr[j] = Math.min( + prev[j] + 1, // deletion + curr[j - 1] + 1, // insertion + prev[j - 1] + cost, // substitution + ); + } + [prev, curr] = [curr, prev]; + } + + return prev[lb]; +} + +/** + * Fold away the differences an author is *never* signalling with: letter case + * and the dash/space spellings of an underscore separator. + * + * Applied to BOTH sides of the comparison in {@link findClosestMatches}. Folding + * only the input was a real defect (#4990): candidates are camelCase across most + * of the spec (AGENTS.md Prime Directive #3, "TS config keys → camelCase"), so + * every capital in a declared key charged the author one extra substitution + * against a budget that is only `max(2, len/3)`. The observable symptom was + * inverted quality — `hiddenon` (all-lowercase, plain wrong) resolved to + * `hiddenOn` at distance 1, while `hideOn` (correctly cased, one real typo) + * scored 3 against a budget of 2 and got no suggestion at all. + */ +const foldForScoring = (value: string): string => value.toLowerCase().replace(/[-\s]/g, '_'); + +/** + * Find the closest matches from a list of candidates. + * + * Scoring is case- and separator-insensitive on both sides; the returned + * strings are the candidates' ORIGINAL spelling, because that spelling is what + * the author has to type back. + * + * @param input - The user-provided (possibly invalid) value + * @param candidates - Array of valid values to compare against + * @param maxDistance - Maximum edit distance to consider (default: 3) + * @param maxResults - Maximum number of suggestions to return (default: 3) + * @returns Array of suggested values, sorted by similarity + */ +export function findClosestMatches( + input: string, + candidates: readonly string[], + maxDistance = 3, + maxResults = 3, +): string[] { + const normalized = foldForScoring(input); + + const scored = candidates + .map((candidate) => ({ + value: candidate, + distance: levenshteinDistance(normalized, foldForScoring(candidate)), + // Tie-break only. Folding is right for RANKING (case is not what the + // author meant to signal), but when two declared keys are equidistant + // under the fold the author's own capitalisation is the last piece of + // evidence left about which one they were reaching for — `yxAis` ties + // `yAxis` and `xAxis` at 2 folded, and the capital A picks the intended + // one. Kept strictly secondary so it can never resurrect the #4990 bug + // of case outranking a real edit. + cased: levenshteinDistance(input, candidate), + })) + // Drop only the candidate the author ALREADY typed verbatim — suggesting a + // string back to the author who wrote it is noise. A folded distance of 0 + // on a differently-spelled candidate (`hiddenon` vs `hiddenOn`) is not that + // case: it is the strongest suggestion available, and pre-#4990 the + // `distance > 0` test threw it away together with the true self-match. + .filter((s) => s.distance <= maxDistance && s.value !== input) + .sort((a, b) => a.distance - b.distance || a.cased - b.cased); + + return scored.slice(0, maxResults).map((s) => s.value); +} + +/** + * Edit distance in which swapping two adjacent letters costs ONE edit (the + * optimal-string-alignment variant of Levenshtein). Used only by the short-key + * screen in {@link suggestRename}; scoring for every other length is + * {@link levenshteinDistance}, unchanged. + */ +function adjacentSwapDistance(a: string, b: string): number { + const rows: number[][] = []; + for (let i = 0; i <= a.length; i++) { + rows.push([i]); + for (let j = 1; j <= b.length; j++) rows[i]![j] = i === 0 ? j : 0; + } + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let best = Math.min(rows[i - 1]![j]! + 1, rows[i]![j - 1]! + 1, rows[i - 1]![j - 1]! + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + best = Math.min(best, rows[i - 2]![j - 2]! + 1); + } + rows[i]![j] = best; + } + } + return rows[a.length]![b.length]!; +} + +/** + * The edit budget a rename guess for `key` may spend: a third of the key, never + * less than 2. A flat distance of 3 is noise on a short key, which is why the + * budget is length-relative at all; {@link suggestRename} spends it. + */ +export function renameBudget(key: string): number { + return Math.max(2, Math.floor(key.length / 3)); +} + +/** + * The rename guess for one unknown key, or `undefined`. + * + * Above five characters this is {@link findClosestMatches}' first answer within + * {@link renameBudget}. At five characters or fewer the budget is the floor of + * 2, not a third of the key, and the floor exists for one slip: a swap of two + * adjacent letters, which plain Levenshtein charges as two edits (`nmae` → + * `name`). The same 2 also admits two UNRELATED edits, which on a four-letter + * key is half of it — `aria` → `areas` (one substitution, one insertion), a + * removed accessibility key answered with the app's navigation areas. So a + * short key's guess must be one edit away counting a swap as one; the candidates + * are still ranked by {@link findClosestMatches}, and the first that passes wins. + * + * An empty key names nothing, so nothing is a spelling of it: every candidate + * of one letter sits inside the screen, and the first of them would be offered + * as the fix. + */ +export function suggestRename(key: string, knownKeys: readonly string[]): string | undefined { + if (key === '') return undefined; + const maxDistance = renameBudget(key); + if (Math.floor(key.length / 3) >= 2) return findClosestMatches(key, knownKeys, maxDistance, 1)[0]; + const folded = foldForScoring(key); + return findClosestMatches(key, knownKeys, maxDistance, knownKeys.length) + .find((candidate) => adjacentSwapDistance(folded, foldForScoring(candidate)) <= 1); +} diff --git a/packages/spec/src/shared/suggestions.test.ts b/packages/spec/src/shared/suggestions.test.ts index 4f0f63b8b8c..ac5057167fc 100644 --- a/packages/spec/src/shared/suggestions.test.ts +++ b/packages/spec/src/shared/suggestions.test.ts @@ -8,6 +8,10 @@ import { } from './suggestions.zod'; import { PROTOCOL_UPGRADE_GUIDE_URL, RETIRED_KEY_UPGRADE_GUIDE_SENTENCE } from './protocol-upgrade-guide'; import { suggestFieldType } from './field-type-suggestion'; +import { readdirSync, readFileSync } from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { renameBudget, suggestRename } from './rename-guess'; describe('levenshteinDistance', () => { it('should return 0 for identical strings', () => { @@ -278,3 +282,56 @@ describe('strictUnknownKeyError — retiredKeyUpgradeGuide', () => { ); }); }); + +/** + * The ONE rename rule every unknown-key suggester in `packages/spec` reads. + * Before it was shared, `ObjectSchema.create()` and `defineSeed` each carried a + * copy of the budget without the short-key screen, so they went on answering a + * short key with an unrelated one after the strict refusal had stopped. + */ +describe('suggestRename — the one rename rule', () => { + it('spends a third of the key, never less than 2', () => { + expect(renameBudget('abc')).toBe(2); + expect(renameBudget('abcdef')).toBe(2); + expect(renameBudget('abcdefghi')).toBe(3); + }); + + it('offers a short key only a candidate one edit away, counting an adjacent swap as one', () => { + expect(suggestRename('aria', ['areas', 'label'])).toBeUndefined(); + expect(suggestRename('nmae', ['name', 'label'])).toBe('name'); + expect(suggestRename('labl', ['name', 'label'])).toBe('label'); + }); + + it('spends the full budget above five characters', () => { + expect(suggestRename('lead_sorce', ['lead_source', 'name'])).toBe('lead_source'); + expect(suggestRename('primaryFeild', ['primaryField'])).toBe('primaryField'); + }); + + it('offers nothing for an empty key', () => { + expect(suggestRename('', ['a', 'b'])).toBeUndefined(); + }); + + // The class guard: a suggester that computes its own budget, or hands + // `findClosestMatches` its own distance, is the copy this rule replaced. + // Comments that QUOTE the budget are prose and are skipped. + it('no other source file in the package spells the budget or passes its own distance', () => { + const srcRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); + const offenders: string[] = []; + const walk = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) { walk(path); continue; } + if (!entry.name.endsWith('.ts') || /\.(test|spec)\.ts$/.test(entry.name)) continue; + if (entry.name === 'rename-guess.ts') continue; + readFileSync(path, 'utf8').split('\n').forEach((line, i) => { + const code = line.trim(); + if (code.startsWith('//') || code.startsWith('*') || code.startsWith('/*')) return; + if (/Math\.max\(\s*2\s*,\s*Math\.floor\(/.test(code) + || /findClosestMatches\([^)]*,[^)]*,/.test(code)) offenders.push(`${relative(srcRoot, path)}:${i + 1}`); + }); + } + }; + walk(srcRoot); + expect(offenders).toEqual([]); + }); +}); diff --git a/packages/spec/src/shared/suggestions.zod.ts b/packages/spec/src/shared/suggestions.zod.ts index a4defaac58e..43fee724f7c 100644 --- a/packages/spec/src/shared/suggestions.zod.ts +++ b/packages/spec/src/shared/suggestions.zod.ts @@ -4,6 +4,7 @@ import type { z } from 'zod'; import { RETIRED_KEY_UPGRADE_GUIDE_SENTENCE } from './protocol-upgrade-guide'; import { aliasProbe } from './alias-probe'; +import { suggestRename } from './rename-guess'; import { oppositePoleAmbiguity, oppositePolePrescription, @@ -34,100 +35,10 @@ import { * `eager-entry-import.test.ts` fails on the loop. */ -/** - * Compute Levenshtein edit distance between two strings. - * Uses space-optimized two-row approach (O(min(m,n)) space). - */ -export function levenshteinDistance(a: string, b: string): number { - const la = a.length; - const lb = b.length; - - if (la === 0) return lb; - if (lb === 0) return la; - - // Use only two rows for space efficiency - let prev = new Array(lb + 1); - let curr = new Array(lb + 1); - - for (let j = 0; j <= lb; j++) { - prev[j] = j; - } - - for (let i = 1; i <= la; i++) { - curr[0] = i; - for (let j = 1; j <= lb; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - curr[j] = Math.min( - prev[j] + 1, // deletion - curr[j - 1] + 1, // insertion - prev[j - 1] + cost, // substitution - ); - } - [prev, curr] = [curr, prev]; - } - - return prev[lb]; -} - -/** - * Fold away the differences an author is *never* signalling with: letter case - * and the dash/space spellings of an underscore separator. - * - * Applied to BOTH sides of the comparison in {@link findClosestMatches}. Folding - * only the input was a real defect (#4990): candidates are camelCase across most - * of the spec (AGENTS.md Prime Directive #3, "TS config keys → camelCase"), so - * every capital in a declared key charged the author one extra substitution - * against a budget that is only `max(2, len/3)`. The observable symptom was - * inverted quality — `hiddenon` (all-lowercase, plain wrong) resolved to - * `hiddenOn` at distance 1, while `hideOn` (correctly cased, one real typo) - * scored 3 against a budget of 2 and got no suggestion at all. - */ -const foldForScoring = (value: string): string => value.toLowerCase().replace(/[-\s]/g, '_'); - -/** - * Find the closest matches from a list of candidates. - * - * Scoring is case- and separator-insensitive on both sides; the returned - * strings are the candidates' ORIGINAL spelling, because that spelling is what - * the author has to type back. - * - * @param input - The user-provided (possibly invalid) value - * @param candidates - Array of valid values to compare against - * @param maxDistance - Maximum edit distance to consider (default: 3) - * @param maxResults - Maximum number of suggestions to return (default: 3) - * @returns Array of suggested values, sorted by similarity - */ -export function findClosestMatches( - input: string, - candidates: readonly string[], - maxDistance = 3, - maxResults = 3, -): string[] { - const normalized = foldForScoring(input); - - const scored = candidates - .map((candidate) => ({ - value: candidate, - distance: levenshteinDistance(normalized, foldForScoring(candidate)), - // Tie-break only. Folding is right for RANKING (case is not what the - // author meant to signal), but when two declared keys are equidistant - // under the fold the author's own capitalisation is the last piece of - // evidence left about which one they were reaching for — `yxAis` ties - // `yAxis` and `xAxis` at 2 folded, and the capital A picks the intended - // one. Kept strictly secondary so it can never resurrect the #4990 bug - // of case outranking a real edit. - cased: levenshteinDistance(input, candidate), - })) - // Drop only the candidate the author ALREADY typed verbatim — suggesting a - // string back to the author who wrote it is noise. A folded distance of 0 - // on a differently-spelled candidate (`hiddenon` vs `hiddenOn`) is not that - // case: it is the strongest suggestion available, and pre-#4990 the - // `distance > 0` test threw it away together with the true self-match. - .filter((s) => s.distance <= maxDistance && s.value !== input) - .sort((a, b) => a.distance - b.distance || a.cased - b.cased); - - return scored.slice(0, maxResults).map((s) => s.value); -} +// The scoring primitives live in the leaf `rename-guess.ts` beside the one +// rename rule they serve; their published names and this import path are +// unchanged. +export { levenshteinDistance, findClosestMatches } from './rename-guess'; /** * Format a "Did you mean?" message for display. @@ -252,55 +163,6 @@ function renderUnknownKey(key: string): string { return key === '' ? 'an empty key (`""`)' : `\`${key}\``; } -/** - * Edit distance in which swapping two adjacent letters costs ONE edit (the - * optimal-string-alignment variant of Levenshtein). Used only by - * {@link shortKeyScreenedGuess}; scoring for every other length is - * {@link levenshteinDistance}, unchanged. - */ -function adjacentSwapDistance(a: string, b: string): number { - const rows: number[][] = []; - for (let i = 0; i <= a.length; i++) { - rows.push([i]); - for (let j = 1; j <= b.length; j++) rows[i]![j] = i === 0 ? j : 0; - } - for (let i = 1; i <= a.length; i++) { - for (let j = 1; j <= b.length; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - let best = Math.min(rows[i - 1]![j]! + 1, rows[i]![j - 1]! + 1, rows[i - 1]![j - 1]! + cost); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - best = Math.min(best, rows[i - 2]![j - 2]! + 1); - } - rows[i]![j] = best; - } - } - return rows[a.length]![b.length]!; -} - -/** - * The rename guess for one unknown key, or `undefined`. - * - * Above five characters this is {@link findClosestMatches}' first answer, - * exactly as before. At five characters or fewer the budget is the floor of 2, - * not a third of the key, and the floor exists for one slip: a swap of two - * adjacent letters, which plain Levenshtein charges as two edits (`nmae` → - * `name`). The same 2 also admits two UNRELATED edits, which on a four-letter - * key is half of it — `aria` → `areas` (one substitution, one insertion), a - * removed accessibility key answered with the app's navigation areas. So a - * short key's guess must be one edit away counting a swap as one; the candidates - * are still ranked by {@link findClosestMatches}, and the first that passes wins. - */ -function shortKeyScreenedGuess( - key: string, - knownKeys: readonly string[], - maxDistance: number, -): string | undefined { - if (Math.floor(key.length / 3) >= 2) return findClosestMatches(key, knownKeys, maxDistance, 1)[0]; - const folded = foldForScoring(key); - return findClosestMatches(key, knownKeys, maxDistance, knownKeys.length) - .find((candidate) => adjacentSwapDistance(folded, foldForScoring(candidate)) <= 1); -} - /** Options for {@link strictUnknownKeyError}. */ export interface StrictUnknownKeyErrorOptions { /** Prose name of the authoring surface the key was written on (e.g. `'this permission set'`). */ @@ -370,8 +232,9 @@ export interface StrictUnknownKeyErrorOptions { * loud; this factory makes it *fixable*: the error names the offending key(s) * and, when one is a recognisable spelling of a declared key, points at the * canonical one — alias table first (semantic near-misses), then a - * length-relative edit-distance fallback (matching `suggestKey` in - * `data/object.zod.ts`: a flat distance of 3 is noise on a short key). + * length-relative edit-distance fallback: `suggestRename` in + * `rename-guess.ts`, the one rename rule `ObjectSchema.create()` and + * `defineSeed` answer with too (a flat distance of 3 is noise on a short key). * * The fallback's answer is screened once more before it ships, because a * distance ranking cannot see meaning: on a shape that declares both ends of a @@ -473,9 +336,10 @@ export function strictUnknownKeyError(options: StrictUnknownKeyErrorOptions): z. // declared key of two letters or fewer sits inside the budget, and the // first of them would be offered as the fix. if (key === '') continue; - const maxDistance = Math.max(2, Math.floor(key.length / 3)); const declared = aliases[aliasProbe(key)]; - const guessed = declared ? undefined : shortKeyScreenedGuess(key, knownKeys, maxDistance); + // The one rename rule every suggester in the package shares — budget and + // short-key screen both live in `rename-guess.ts`. + const guessed = declared ? undefined : suggestRename(key, knownKeys); // Screen the GUESS, never the declaration. `findClosestMatches` ranks by // edit distance and nothing else, so on a shape declaring both ends of a // range it answers a key that names neither end with whichever end is