Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(entities): never resolve facts to retired alias pages; fold alias separators (#6898)

garrytanb2a07bdd77a1
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index d899119586..60f535dc43 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -66,7 +66,7 @@ export async function resolveEntitySlug(
// a row exactly), use it.
if (looksLikeSlug(trimmed)) {
const exact = await tryExactSlug(engine, source_id, trimmed);
- if (exact) return exact;
+ if (exact) return exact.retired ? (await followRetirement(engine, source_id, exact.slug))?.slug ?? null : exact.slug;
}
// 1.25. Exact own name: a live page whose slug basename IS the mention wins
@@ -165,6 +165,110 @@ export function sameEntityName(reference: string, candidateTitle: string | null
return wanted !== '' && (wanted === nameTokens(candidateTitle ?? '') || wanted === nameTokens(candidateSlug.split('/').pop() ?? ''));
}
+/**
+ * #6898: a page that hands its identity to another page. Frontmatter
+ * `canonical: false`, a `superseded_by` or `merged_into` (the concept-merge
+ * record, cycle/concept-redirects.ts) target, or a `status` that names the
+ * page an alias, a redirect, or superseded or merged
+ * (`historical-retired-alias`). A status that describes the entity itself
+ * (`retired`, `archived`, `deprecated`) does not retire the page: a person
+ * who retired is still that person's page.
+ */
+function retiredPageSql(p: string): string {
+ return `(lower(COALESCE(${p}.frontmatter->>'canonical', '')) IN ('false', 'no')
+ OR btrim(COALESCE(${p}.frontmatter->>'superseded_by', '')) <> ''
+ OR btrim(COALESCE(${p}.frontmatter->>'merged_into', '')) <> ''
+ OR lower(COALESCE(${p}.frontmatter->>'status', '')) ~ '(^|[^a-z])(alias|redirect|redirected|superseded|merged)([^a-z]|$)')`;
+}
+
+const MAX_RETIREMENT_HOPS = 5;
+
+/** A frontmatter redirect value as a slug: `[[people/x|X]]`, `people/x.md` and `/people/x` are `people/x`. */
+function redirectSlug(value: string): string | null {
+ const slug = value.trim().replace(/^\[\[/, '').replace(/\]\]$/, '').split('|')[0].trim().replace(/\.md$/i, '').replace(/^\/+/, '');
+ return slug || null;
+}
+
+/**
+ * #6898: the live page that answers for `slug`. A page that is not retired
+ * answers for itself; a retired page hands over to its `superseded_by` (else
+ * `merged_into`) target in the same source, hop by hop up to
+ * MAX_RETIREMENT_HOPS. Null when the chain has no target, reaches a missing,
+ * deleted or (with `privacy`) unreadable page, cycles, or runs too long: the
+ * caller refuses rather than guess.
+ */
+async function followRetirement(
+ engine: BrainEngine,
+ source_id: string,
+ slug: string,
+ privacy = '',
+): Promise<{ slug: string; type: string | null } | null> {
+ const seen = new Set<string>();
+ let current: string | null = slug;
+ while (current && !seen.has(current) && seen.size <= MAX_RETIREMENT_HOPS) {
+ seen.add(current);
+ const [row] = await engine.executeRaw<{ slug: string; type: string | null; retired: boolean; target: string | null }>(
+ `SELECT p.slug, p.type, ${retiredPageSql('p')} AS retired,
+ COALESCE(NULLIF(btrim(p.frontmatter->>'superseded_by'), ''), NULLIF(btrim(p.frontmatter->>'merged_into'), '')) AS target
+ FROM pages p
+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL ${privacy}
+ LIMIT 1`,
+ [source_id, current],
+ );
+ if (!row) return null;
+ if (!row.retired) return { slug: row.slug, type: row.type };
+ current = row.target ? redirectSlug(row.target) : null;
+ }
+ return null;
+}
+
+/** #6898: the distinct live pages that answer for `slugs` (see followRetirement); unfollowable ones drop out. */
+async function canonicalPages(
+ engine: BrainEngine,
+ source_id: string,
+ slugs: string[],
+ privacy = '',
+): Promise<Array<{ slug: string; type: string | null }>> {
+ const out = new Map<string, { slug: string; type: string | null }>();
+ for (const slug of new Set(slugs)) {
+ const page = await followRetirement(engine, source_id, slug, privacy);
+ if (page) out.set(page.slug, page);
+ }
+ return [...out.values()];
+}
+
+/**
+ * #6898: the normalized alias spellings a reference may be stored under.
+ * `/`, `-`, `_` and whitespace separate the same name words, so
+ * `Alice Example`, `alice_example` and `alice-example` meet whichever one
+ * the page declared. A slug-shaped reference (`people/alice-example`) names
+ * its last segment. The literal normalized form comes first.
+ */
+function aliasSpellings(raw: string): { literal: string; folded: string[]; dir: string | null } {
+ const literal = normalizeAlias(raw);
+ const segments = looksLikeSlug(raw.trim()) ? literal.split('/') : [literal];
+ const tokens = segments[segments.length - 1].split(/[\s/_-]+/u).filter(Boolean);
+ const folded = tokens.length ? [...new Set([' ', '-', '_'].map(sep => tokens.join(sep)))].filter(s => s !== literal) : [];
+ return { literal, folded, dir: segments.length > 1 ? segments[segments.length - 2] : null };
+}
+
+/**
+ * Slugs of the pages whose page_aliases row carries the reference: the
+ * literal spelling's hits when it has any, else the separator-folded
+ * spellings'. A folded hit for a slug-shaped reference must sit in the same
+ * directory (`projects/acme-example` never lands on a `companies/` alias).
+ * Throws what resolveAliases throws.
+ */
+async function aliasHitSlugs(engine: BrainEngine, source_id: string, raw: string): Promise<string[]> {
+ const { literal, folded, dir } = aliasSpellings(raw);
+ if (!literal) return [];
+ const hits = await engine.resolveAliases([literal, ...folded], { sourceId: source_id });
+ const exact = (hits.get(literal) ?? []).map(h => h.slug);
+ if (exact.length) return exact;
+ const parentDir = (slug: string) => slug.split('/').slice(-2, -1)[0] ?? null;
+ return folded.flatMap(s => hits.get(s) ?? []).map(h => h.slug).filter(slug => dir === null || parentDir(slug) === dir);
+}
+
/**
* Alias-exact arm (v0.46.15, #3730): unambiguous single-slug page_aliases hit,
* verified against LIVE pages — page_aliases has no FK to pages, so stale
@@ -177,17 +281,11 @@ export function sameEntityName(reference: string, candidateTitle: string | null
*/
let aliasExactWarned = false;
async function tryAliasExact(engine: BrainEngine, source_id: string, raw: string): Promise<string | null> {
- const norm = normalizeAlias(raw);
- if (!norm) return null;
try {
- const hits = (await engine.resolveAliases([norm], { sourceId: source_id })).get(norm) ?? [];
+ const hits = await aliasHitSlugs(engine, source_id, raw);
if (!hits.length) return null;
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])`,
- [source_id, [...new Set(hits.map((h) => h.slug))]],
- );
- const live = [...new Set(rows.map((r) => r.slug))];
- return live.length === 1 ? live[0] : await siblingCanonical(engine, source_id, live);
+ const live = await canonicalPages(engine, source_id, hits);
+ return live.length === 1 ? live[0].slug : await siblingCanonical(engine, source_id, live.map(p => p.slug));
} catch (err) {
if (!isMissingSchemaObject(err, 'table', 'page_aliases') && !aliasExactWarned) {
aliasExactWarned = true;
@@ -231,8 +329,9 @@ async function findExactBasenameCandidates(
): Promise<Array<{ slug: string }>> {
const token = slugify(raw);
if (raw.includes('/') || !token.includes('-')) return [];
+ let rows: Array<{ slug: string }>;
try {
- return await engine.executeRaw<{ slug: string }>(
+ rows = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM pages
WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])
LIMIT 2`,
@@ -241,6 +340,7 @@ async function findExactBasenameCandidates(
} catch {
return [];
}
+ return canonicalPages(engine, source_id, rows.map(r => r.slug));
}
/**
@@ -282,7 +382,10 @@ export async function resolveEntitySlugWithSource(
// Mirror resolveEntitySlug's resolution chain but tag each branch.
if (looksLikeSlug(trimmed)) {
const exact = await tryExactSlug(engine, source_id, trimmed);
- if (exact) return { slug: exact, source: 'exact_page' };
+ if (exact) {
+ const canonical = exact.retired ? (await followRetirement(engine, source_id, exact.slug))?.slug : exact.slug;
+ return canonical ? { slug: canonical, source: 'exact_page' } : null;
+ }
}
const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);
@@ -359,7 +462,11 @@ export async function resolveStrictEntityReference(
linkable ??= new Set((await (await import('../mentions/policy.ts')).loadLinkableTypes(engine, source_id).catch(() => ({ types: [] as string[] }))).types);
return r.type != null && linkable.has(r.type);
};
- const pick = async (rows: Array<{ slug: string; type: string | null }>, arm: StrictResolutionArm): Promise<StrictResolution | null> => {
+ const pick = async (found: Array<{ slug: string; type: string | null }>, arm: StrictResolutionArm): Promise<StrictResolution | null> => {
+ if (found.length === 0) return null;
+ // #6898: a retired page answers through its superseded_by target, which must be readable too.
+ const rows = await canonicalPages(engine, source_id, found.map(r => r.slug), privacy);
+ if (rows.length === 0) return { slug: null, miss: 'not_entity' };
if (rows.length > 1) {
const sibling = await siblingCanonical(engine, source_id, rows.map(r => r.slug), { excludePrivate: opts.excludePrivate });
return sibling ? { slug: sibling, arm } : { slug: null, miss: 'ambiguous' };
@@ -377,21 +484,17 @@ export async function resolveStrictEntityReference(
const basename = await pick(await live([...PREFIX_EXPANSION_DIRS, 'concepts'].map(dir => `${dir}/${token}`)), 'basename');
if (basename) return basename;
}
- const norm = normalizeAlias(trimmed);
- if (norm) {
- try {
- const hits = (await engine.resolveAliases([norm], { sourceId: source_id })).get(norm) ?? [];
- const aliased = await pick(await live(hits.map(h => h.slug)), 'alias_exact');
- if (aliased) return aliased;
- } catch (err) {
- if (!isMissingSchemaObject(err, 'table', 'page_aliases')) throw err;
- }
+ try {
+ const aliased = await pick(await live(await aliasHitSlugs(engine, source_id, trimmed)), 'alias_exact');
+ if (aliased) return aliased;
+ } catch (err) {
+ if (!isMissingSchemaObject(err, 'table', 'page_aliases')) throw err;
}
if (opts.sameName && !isBareName(trimmed)) {
try {
const rows = await engine.executeRaw<{ slug: string; title: string; type: string | null }>(
`SELECT p.slug, p.title, p.type FROM pages p
- WHERE p.source_id = $1 AND p.deleted_at IS NULL ${privacy}
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL ${privacy} AND NOT ${retiredPageSql('p')}
AND (lower(p.title) % $2 OR p.slug ILIKE '%' || $3 || '%')
ORDER BY GREATEST(similarity(lower(p.title), $2), similarity(p.slug, $3)) DESC, p.slug ASC
LIMIT 5`,
@@ -527,6 +630,7 @@ export async function findPrefixCandidates(
FROM pages p
WHERE p.source_id = $1
AND p.deleted_at IS NULL
+ AND NOT ${retiredPageSql('p')}
AND p.slug LIKE ANY($2::text[])
ORDER BY connection_count DESC, p.slug ASC
LIMIT 10`,
@@ -562,14 +666,14 @@ async function tryUnambiguousPrefixExpansion(
try {
const dirs = await engine.executeRaw<{ dir: string }>(
`SELECT DISTINCT split_part(slug, '/', 1) AS dir FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE ANY($2::text[])
+ WHERE source_id = $1 AND deleted_at IS NULL AND NOT ${retiredPageSql('pages')} AND slug LIKE ANY($2::text[])
LIMIT 2`,
[source_id, patterns],
);
if (dirs.length !== 1) return null;
const rows = await engine.executeRaw<{ slug: string; title: string | null }>(
`SELECT slug, title FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL
+ WHERE source_id = $1 AND deleted_at IS NULL AND NOT ${retiredPageSql('pages')}
AND slug LIKE ANY($2::text[]) AND lower(title) = lower($3)
LIMIT 3`,
[source_id, patterns, raw.trim()],
@@ -626,6 +730,7 @@ async function tryPrefixExpansion(
FROM pages p
WHERE p.source_id = $1
AND p.deleted_at IS NULL
+ AND NOT ${retiredPageSql('p')}
AND p.slug LIKE $2
ORDER BY connection_count DESC, p.slug ASC
LIMIT 5`,
@@ -663,14 +768,14 @@ async function tryExactSlug(
engine: BrainEngine,
source_id: string,
candidate: string,
-): Promise<string | null> {
+): Promise<{ slug: string; retired: boolean } | null> {
// A database error propagates: degrading to the fallback slug would
// silently attribute the caller's facts to a different entity.
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,
+ const rows = await engine.executeRaw<{ slug: string; retired: boolean }>(
+ `SELECT slug, ${retiredPageSql('pages')} AS retired FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,
[source_id, candidate],
);
- return rows[0]?.slug ?? null;
+ return rows[0] ?? null;
}
async function tryFuzzyMatch(
@@ -694,6 +799,7 @@ async function tryFuzzyMatch(
FROM pages
WHERE source_id = $1
AND deleted_at IS NULL
+ AND NOT ${retiredPageSql('pages')}
AND (
lower(title) % $2
OR slug ILIKE '%' || $3 || '%'
diff --git a/test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts b/test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts
new file mode 100644
index 0000000000..369c203ae2
--- /dev/null
+++ b/test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts
@@ -0,0 +1,23 @@
+/**
+ * #6898 on Postgres: the retired-alias fixture and cases from
+ * test/helpers/retired-alias-6898.ts against a real Postgres brain (pg_trgm
+ * fuzzy arm, JSONB frontmatter predicates, page_aliases). The PGLite twin is
+ * test/entity-resolve-retired-alias-6898.test.ts. Runs only when
+ * DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { seedRetiredAliasBrain, retiredAliasCases } from '../helpers/retired-alias-6898.ts';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+(hasDatabase() ? describe : describe.skip)('#6898 retired alias pages on Postgres', () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ await setupDB();
+ engine = await getEngine();
+ await seedRetiredAliasBrain(engine);
+ }, 120_000);
+ afterAll(async () => { await teardownDB(); });
+
+ retiredAliasCases(() => engine);
+});
diff --git a/test/entity-resolve-retired-alias-6898.test.ts b/test/entity-resolve-retired-alias-6898.test.ts
new file mode 100644
index 0000000000..e917bdca01
--- /dev/null
+++ b/test/entity-resolve-retired-alias-6898.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #6898: entity resolution attributed facts to a retired alias page.
+ *
+ * The reporter's brain had a canonical person page whose aliases were the
+ * extractor's spellings in slug form (`alice-example`), and a retired page
+ * (`canonical: false`, `superseded_by`, `status: historical-retired-alias`)
+ * whose title carried the same name tokens. The alias arm missed because
+ * `people/alice-example` and `Alice Example` never normalized to
+ * `alice-example`, and the fuzzy arm then took the retired page as the only
+ * same-name candidate. These tests replay that trace: the resolver must reach
+ * the canonical page through the alias, never pick a retired page from a
+ * guessing arm, follow `superseded_by` on an exact hit (bounded, cycle-safe,
+ * visible targets only) and refuse when the redirect cannot be followed.
+ *
+ * Real PGLite; the Postgres twin is
+ * test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts. Placeholder
+ * names only.
+ */
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { seedRetiredAliasBrain, retiredAliasCases } from './helpers/retired-alias-6898.ts';
+import { runFactsBackstop } from '../src/core/facts/backstop.ts';
+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedRetiredAliasBrain(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ __resetFactsQueueForTests();
+});
+
+retiredAliasCases(() => engine);
+
+describe('#6898 facts backstop lands extracted facts on the canonical page', () => {
+ test('entity_slug people/alice-example and Alice Example both attribute to the canonical page', async () => {
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({ facts: [
+ { fact: 'Alice Example moved the launch review to Thursday', kind: 'event', entity: 'people/alice-example', confidence: 1, notability: 'medium' },
+ { fact: 'Alice Example prefers written status updates', kind: 'preference', entity: 'Alice Example', confidence: 1, notability: 'medium' },
+ ] }),
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'test:stub',
+ providerId: 'test',
+ }));
+ const page = { slug: 'mail/thread-6898-example', type: 'note' as const, compiled_truth: 'a mail thread that mentions Alice Example several times. '.repeat(3), frontmatter: {} };
+ const r = await runFactsBackstop(page, { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline' });
+ expect(r.mode).toBe('inline');
+ if (r.mode !== 'inline') return;
+ expect(r.inserted).toBe(2);
+ const rows = await engine.executeRaw<{ entity_slug: string | null }>(
+ 'SELECT entity_slug FROM facts WHERE id = ANY($1::int[]) ORDER BY id', [r.fact_ids]);
+ expect(rows.map(row => row.entity_slug)).toEqual(['people/aliceexample', 'people/aliceexample']);
+ });
+});
diff --git a/test/helpers/retired-alias-6898.ts b/test/helpers/retired-alias-6898.ts
new file mode 100644
index 0000000000..1985a7c994
--- /dev/null
+++ b/test/helpers/retired-alias-6898.ts
@@ -0,0 +1,118 @@
+/**
+ * Shared fixture and cases for #6898 (facts resolved to retired alias pages),
+ * run on PGLite (test/entity-resolve-retired-alias-6898.test.ts) and on
+ * Postgres (test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts).
+ * Placeholder names only.
+ */
+import { describe, test, expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { resolveEntitySlug, resolveEntitySlugWithSource, resolveStrictEntityReference } from '../../src/core/entities/resolve.ts';
+
+function page(frontmatter: Record<string, unknown>, title: string): string {
+ const yaml = Object.entries({ title, ...frontmatter }).map(([k, v]) =>
+ Array.isArray(v) ? `${k}:\n${v.map(item => ` - ${JSON.stringify(item)}`).join('\n')}` : `${k}: ${JSON.stringify(v)}`).join('\n');
+ return `---\n${yaml}\n---\n\n# ${title}\n`;
+}
+
+const PAGES: Array<[string, Record<string, unknown>, string]> = [
+ // The issue's shape: a canonical page whose title is a one-word romanized
+ // name and whose aliases are slug-form spellings, plus a retired page that
+ // carries the same name tokens.
+ ['people/aliceexample', { type: 'person', canonical: true, aliases: ['alice-example', 'aliceexample', 'Alice'] }, 'Aliceexample'],
+ ['root/people/alice-example', { type: 'concept', status: 'historical-retired-alias', canonical: false, superseded_by: 'people/aliceexample' }, 'People Alice Example'],
+ // Retired with nothing to follow: no superseded_by.
+ ['concepts/old-widget-example', { type: 'concept', canonical: false }, 'Old Widget Example'],
+ // Retired, redirect target missing.
+ ['concepts/gone-widget-example', { type: 'concept', superseded_by: 'concepts/never-written-example' }, 'Gone Widget Example'],
+ // A redirect cycle.
+ ['concepts/loop-a-example', { type: 'concept', superseded_by: 'concepts/loop-b-example' }, 'Loop A Example'],
+ ['concepts/loop-b-example', { type: 'concept', superseded_by: '[[concepts/loop-a-example]]' }, 'Loop B Example'],
+ // A two-hop chain ending on a live page, the middle hop via merged_into.
+ ['concepts/chain-one-example', { type: 'concept', superseded_by: 'concepts/chain-two-example.md' }, 'Chain One Example'],
+ ['concepts/chain-two-example', { type: 'concept', merged_into: 'concepts/chain-three-example' }, 'Chain Two Example'],
+ ['concepts/chain-three-example', { type: 'concept' }, 'Chain Three Example'],
+ // A redirect to a private page.
+ ['concepts/public-alias-example', { type: 'concept', canonical: false, superseded_by: 'concepts/private-target-example' }, 'Public Alias Example'],
+ ['concepts/private-target-example', { type: 'concept', visibility: 'private' }, 'Private Target Example'],
+ // A retired same-name page next to nothing else: the fuzzy arm must not take it.
+ ['people/root-copy/bob-example', { type: 'person', status: 'superseded' }, 'Bob Example'],
+ // Separator folding: aliases written with spaces or underscores.
+ ['people/danaexample', { type: 'person', aliases: ['Dana Example'] }, 'Danaexample'],
+ ['companies/acmeco-example', { type: 'company', aliases: ['acme_example'] }, 'Acmeco Example'],
+ // A person whose status is about the person, not the page, stays a candidate.
+ ['people/erin-example', { type: 'person', status: 'retired' }, 'Erin Example'],
+];
+
+export async function seedRetiredAliasBrain(engine: BrainEngine): Promise<void> {
+ for (const [slug, fm, title] of PAGES) await importFromContent(engine, slug, page(fm, title), { noEmbed: true });
+}
+
+export function retiredAliasCases(getEngine: () => BrainEngine): void {
+ const resolve = (raw: string) => resolveEntitySlugWithSource(getEngine(), 'default', raw);
+
+ describe('#6898 alias arm folds name separators', () => {
+ test('the issue trace: people/alice-example resolves to the canonical page through its alias', async () => {
+ expect(await resolve('people/alice-example')).toEqual({ slug: 'people/aliceexample', source: 'alias_exact' });
+ });
+ test('the display spelling Alice Example resolves to the canonical page through its alias', async () => {
+ expect(await resolve('Alice Example')).toEqual({ slug: 'people/aliceexample', source: 'alias_exact' });
+ expect(await resolveEntitySlug(getEngine(), 'default', 'Alice Example')).toBe('people/aliceexample');
+ });
+ test('hyphen, underscore and whitespace spellings meet the stored alias', async () => {
+ expect(await resolve('dana-example')).toEqual({ slug: 'people/danaexample', source: 'alias_exact' });
+ expect(await resolve('dana_example')).toEqual({ slug: 'people/danaexample', source: 'alias_exact' });
+ expect(await resolve('Acme Example')).toEqual({ slug: 'companies/acmeco-example', source: 'alias_exact' });
+ expect(await resolve('companies/acme-example')).toEqual({ slug: 'companies/acmeco-example', source: 'alias_exact' });
+ });
+ test('a slug-shaped reference keeps its directory: projects/acme-example never lands on the company alias', async () => {
+ expect((await resolve('projects/acme-example'))?.slug).not.toBe('companies/acmeco-example');
+ });
+ });
+
+ describe('#6898 exact hits on a retired page follow superseded_by or refuse', () => {
+ test('the retired slug redirects to its canonical page', async () => {
+ expect(await resolve('root/people/alice-example')).toEqual({ slug: 'people/aliceexample', source: 'exact_page' });
+ expect(await resolveEntitySlug(getEngine(), 'default', 'root/people/alice-example')).toBe('people/aliceexample');
+ });
+ test('a chain through superseded_by and merged_into ends on the live page', async () => {
+ expect(await resolve('concepts/chain-one-example')).toEqual({ slug: 'concepts/chain-three-example', source: 'exact_page' });
+ });
+ test('no redirect, a missing target or a cycle refuses instead of guessing', async () => {
+ for (const slug of ['concepts/old-widget-example', 'concepts/gone-widget-example', 'concepts/loop-a-example']) {
+ expect(await resolve(slug)).toBeNull();
+ expect(await resolveEntitySlug(getEngine(), 'default', slug)).toBeNull();
+ }
+ });
+ });
+
+ describe('#6898 guessing arms never pick a retired page', () => {
+ test('fuzzy: a retired page that is the only same-name candidate is not taken', async () => {
+ expect(await resolve('Bob Example')).toEqual({ slug: 'bob-example', source: 'fallback_slugify' });
+ expect(await resolve('Old Widget Example')).toEqual({ slug: 'old-widget-example', source: 'fallback_slugify' });
+ });
+ test('a person page whose status describes the person stays a candidate', async () => {
+ expect((await resolve('Erin Example'))?.slug).toBe('people/erin-example');
+ });
+ });
+
+ describe('#6898 strict resolver', () => {
+ const strict = (raw: string, opts: { sameName?: boolean; excludePrivate?: boolean } = { sameName: true }) =>
+ resolveStrictEntityReference(getEngine(), 'default', raw, opts);
+ test('alias arm folds separators', async () => {
+ expect(await strict('Alice Example')).toEqual({ slug: 'people/aliceexample', arm: 'alias_exact' });
+ expect(await strict('people/alice-example')).toEqual({ slug: 'people/aliceexample', arm: 'alias_exact' });
+ });
+ test('same_name never picks a retired page', async () => {
+ expect(await strict('Bob Example')).toEqual({ slug: null, miss: 'no_page' });
+ });
+ test('an exact retired hit follows superseded_by, or is not a fact entity', async () => {
+ expect(await strict('root/people/alice-example')).toEqual({ slug: 'people/aliceexample', arm: 'exact_page' });
+ expect(await strict('concepts/old-widget-example')).toEqual({ slug: null, miss: 'not_entity' });
+ });
+ test('a redirect is followed only to a page the caller can see', async () => {
+ expect(await strict('concepts/public-alias-example')).toEqual({ slug: 'concepts/private-target-example', arm: 'exact_page' });
+ expect(await strict('concepts/public-alias-example', { excludePrivate: true })).toEqual({ slug: null, miss: 'not_entity' });
+ });
+ });
+}