Skip to content

Commit a8d84f4

Browse files
committed
fix(spec): the unknown-key refusal names an empty key, and offers no two-edit rename on a short key
An empty key rendered as empty backticks and could be offered a two-letter declared key as its rename. Below six characters the rename budget is the floor of 2, meant for a swap of adjacent letters; it also admitted two unrelated edits, which answered a removed `aria` with `areas`. A short key's guess must now be one edit away counting a swap as one. Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2af25d6 commit a8d84f4

2 files changed

Lines changed: 112 additions & 2 deletions

File tree

‎packages/spec/src/shared/strict-object.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,3 +526,50 @@ describe('eager construction with this module entered first', () => {
526526
).toBe('ok');
527527
}, 60_000);
528528
});
529+
530+
/**
531+
* The rename channel on SHORT keys, and the key that is no spelling at all.
532+
* Below six characters the budget is the floor of 2, which exists for a swap of
533+
* two adjacent letters; two unrelated edits on a four-letter key are half the
534+
* key, and answered a removed `aria` with the app's `areas`.
535+
*/
536+
describe('short and empty unknown keys', () => {
537+
const Nav = lazySchema(() =>
538+
strictObject({ surface: 'this nav', history: 'h' }, {
539+
name: z.string(),
540+
areas: z.array(z.string()).optional(),
541+
label: z.string().optional(),
542+
id: z.string().optional(),
543+
}),
544+
);
545+
const messageFor = (body: Record<string, unknown>) => {
546+
const r = Nav.safeParse({ name: 'x', ...body });
547+
expect(r.success).toBe(false);
548+
const issue = r.error!.issues[0]!;
549+
expect(issue.code).toBe('unrecognized_keys');
550+
return issue.message;
551+
};
552+
553+
it('a four-letter key two unrelated edits from a declared one gets no rename', () => {
554+
const m = messageFor({ aria: { label: 'x' } });
555+
expect(m.startsWith('Unrecognized key(s) on this nav: `aria`.')).toBe(true);
556+
expect(m).not.toContain('Did you mean');
557+
expect(m).not.toContain('`areas`');
558+
});
559+
560+
it('a swap of two adjacent letters on a short key is still answered', () => {
561+
expect(messageFor({ lable: 'x' })).toContain('Did you mean `lable` → `label`?');
562+
expect(messageFor({ aeras: [] })).toContain('Did you mean `aeras` → `areas`?');
563+
});
564+
565+
it('a one-letter slip on a short key is still answered', () => {
566+
expect(messageFor({ labl: 'x' })).toContain('Did you mean `labl` → `label`?');
567+
});
568+
569+
it('an empty key is named as one, and offered no rename', () => {
570+
const m = messageFor({ '': 1 });
571+
expect(m.startsWith('Unrecognized key(s) on this nav: an empty key (`""`).')).toBe(true);
572+
expect(m).not.toContain('``');
573+
expect(m).not.toContain('Did you mean');
574+
});
575+
});

‎packages/spec/src/shared/suggestions.zod.ts‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,65 @@ export function keySetMatches(set: KeySetGuidance, key: string): boolean {
242242
return set.keys instanceof RegExp ? key.search(set.keys) !== -1 : set.keys.includes(key);
243243
}
244244

245+
/**
246+
* One unknown key as the refusal names it: in backticks, the spelling the
247+
* author typed. An EMPTY key is spelled out, because backticks around nothing
248+
* render as an empty code span (or as two stray backticks), and the author is
249+
* left looking for a key the message never shows.
250+
*/
251+
function renderUnknownKey(key: string): string {
252+
return key === '' ? 'an empty key (`""`)' : `\`${key}\``;
253+
}
254+
255+
/**
256+
* Edit distance in which swapping two adjacent letters costs ONE edit (the
257+
* optimal-string-alignment variant of Levenshtein). Used only by
258+
* {@link shortKeyScreenedGuess}; scoring for every other length is
259+
* {@link levenshteinDistance}, unchanged.
260+
*/
261+
function adjacentSwapDistance(a: string, b: string): number {
262+
const rows: number[][] = [];
263+
for (let i = 0; i <= a.length; i++) {
264+
rows.push([i]);
265+
for (let j = 1; j <= b.length; j++) rows[i]![j] = i === 0 ? j : 0;
266+
}
267+
for (let i = 1; i <= a.length; i++) {
268+
for (let j = 1; j <= b.length; j++) {
269+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
270+
let best = Math.min(rows[i - 1]![j]! + 1, rows[i]![j - 1]! + 1, rows[i - 1]![j - 1]! + cost);
271+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
272+
best = Math.min(best, rows[i - 2]![j - 2]! + 1);
273+
}
274+
rows[i]![j] = best;
275+
}
276+
}
277+
return rows[a.length]![b.length]!;
278+
}
279+
280+
/**
281+
* The rename guess for one unknown key, or `undefined`.
282+
*
283+
* Above five characters this is {@link findClosestMatches}' first answer,
284+
* exactly as before. At five characters or fewer the budget is the floor of 2,
285+
* not a third of the key, and the floor exists for one slip: a swap of two
286+
* adjacent letters, which plain Levenshtein charges as two edits (`nmae` →
287+
* `name`). The same 2 also admits two UNRELATED edits, which on a four-letter
288+
* key is half of it — `aria` → `areas` (one substitution, one insertion), a
289+
* removed accessibility key answered with the app's navigation areas. So a
290+
* short key's guess must be one edit away counting a swap as one; the candidates
291+
* are still ranked by {@link findClosestMatches}, and the first that passes wins.
292+
*/
293+
function shortKeyScreenedGuess(
294+
key: string,
295+
knownKeys: readonly string[],
296+
maxDistance: number,
297+
): string | undefined {
298+
if (Math.floor(key.length / 3) >= 2) return findClosestMatches(key, knownKeys, maxDistance, 1)[0];
299+
const folded = foldForScoring(key);
300+
return findClosestMatches(key, knownKeys, maxDistance, knownKeys.length)
301+
.find((candidate) => adjacentSwapDistance(folded, foldForScoring(candidate)) <= 1);
302+
}
303+
245304
/** Options for {@link strictUnknownKeyError}. */
246305
export interface StrictUnknownKeyErrorOptions {
247306
/** Prose name of the authoring surface the key was written on (e.g. `'this permission set'`). */
@@ -410,9 +469,13 @@ export function strictUnknownKeyError(options: StrictUnknownKeyErrorOptions): z.
410469
}
411470
continue;
412471
}
472+
// An empty key names nothing, so nothing is a spelling of it: every
473+
// declared key of two letters or fewer sits inside the budget, and the
474+
// first of them would be offered as the fix.
475+
if (key === '') continue;
413476
const maxDistance = Math.max(2, Math.floor(key.length / 3));
414477
const declared = aliases[aliasProbe(key)];
415-
const guessed = declared ? undefined : findClosestMatches(key, knownKeys, maxDistance, 1)[0];
478+
const guessed = declared ? undefined : shortKeyScreenedGuess(key, knownKeys, maxDistance);
416479
// Screen the GUESS, never the declaration. `findClosestMatches` ranks by
417480
// edit distance and nothing else, so on a shape declaring both ends of a
418481
// range it answers a key that names neither end with whichever end is
@@ -441,7 +504,7 @@ export function strictUnknownKeyError(options: StrictUnknownKeyErrorOptions): z.
441504
// an AI — reads the front of that line and acts on it, so the prescription
442505
// has to be there. Nothing is dropped or made conditional: the sentence is
443506
// still emitted verbatim, once per message, just last (#5955).
444-
let message = `Unrecognized key(s) on ${surface}: ${keys.map((k) => `\`${k}\``).join(', ')}.`;
507+
let message = `Unrecognized key(s) on ${surface}: ${keys.map(renderUnknownKey).join(', ')}.`;
445508
if (renames.length) message += ` Did you mean ${renames.join(', ')}?`;
446509
if (prescriptions.length) message += `\n${prescriptions.map((p) => ` • ${p}`).join('\n')}`;
447510
// The last fix channel, still ahead of `history`: where an aged-out

0 commit comments

Comments
 (0)