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
12 changes: 12 additions & 0 deletions .changeset/35420-one-rename-rule.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/spec/export-origins/root.json
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand Down
4 changes: 2 additions & 2 deletions packages/spec/export-origins/shared.json
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand Down
32 changes: 32 additions & 0 deletions packages/spec/src/data/authoring-key-lint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
6 changes: 4 additions & 2 deletions packages/spec/src/data/authoring-key-lint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
22 changes: 22 additions & 0 deletions packages/spec/src/data/default-value-shape.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`?');
});
});
9 changes: 5 additions & 4 deletions packages/spec/src/data/default-value-shape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions packages/spec/src/data/define-seed-record-keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>[] = [{ 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<string, unknown>[] = [{ 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'?");
});
});
25 changes: 25 additions & 0 deletions packages/spec/src/data/field-value.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, unknown>): 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`?');
});
});
8 changes: 5 additions & 3 deletions packages/spec/src/data/field-value.zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
44 changes: 38 additions & 6 deletions packages/spec/src/data/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<string, unknown> as Parameters<typeof ObjectSchema.create>[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`');
});
});
40 changes: 5 additions & 35 deletions packages/spec/src/data/object.zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<number>(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
Expand All @@ -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.`;
Expand Down
Loading
Loading