Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(entities): narrow retired status to alias/redirect, keep unresolved exact hits non-null, skip retired pages in relational title fallback (#6898)

garrytane7afd1afd5f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ae4d8afec..39b83fbb53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,7 +21,8 @@ identifiers and attribution are available in the pre-removal Git revision
| the extractor names `people/alice-example` or `Alice Example`, and the real page has the alias `alice-example` | the alias missed; a retired page with the same name words could win | resolves to the real page through its alias |
| an alias written `Dana Example` or `acme_example`, referenced as `dana-example` or `Acme Example` | no alias match | matches |
| a reference that is exactly a retired page's slug | that retired page | the page its `superseded_by` (or `merged_into`) names, up to 5 hops, same source, readable by the caller |
-| the same, when the retired page names no target, the target is missing or private to the caller, or the chain loops | that retired page | no entity (the fact is saved without one, as for any unknown name) |
+| the same, when the retired page names no target, the target is missing or private to the caller, or the chain loops | that retired page | unresolved, like an unknown name: extracted facts are saved without an entity |
+| `gbrain recall --entity <retired-slug>` when the retired page names a target | the retired page's facts | the target page's facts (the retired page's own facts stay under its slug) |
| a retired page is the only page whose name matches a guess (name match, bare-name prefix, phantom merge) | it could be chosen | it is skipped |
| a person page whose `status` describes the person (`retired`, `archived`) | a candidate | still a candidate |
@@ -31,7 +32,7 @@ Nothing. No migration, nothing is rewritten on upgrade, and stored aliases are r
### Itemized changes
-- `src/core/entities/resolve.ts`: a page is retired when its frontmatter has `canonical: false`, a `superseded_by` or `merged_into` target, or a `status` naming it an alias, a redirect, superseded or merged. The fuzzy and same-name arms of both resolvers, bare-name prefix expansion and the phantom-merge candidate queries exclude retired pages in SQL before uniqueness is counted. The exact-slug, basename and alias arms follow a retired page's `superseded_by` (else `merged_into`; `[[...]]`, `.md` and a leading `/` are stripped) within the same source, at most 5 hops, refusing on a cycle, a missing or deleted target, or (strict resolver with `excludePrivate`) a private one. An exact hit that cannot be followed returns null from `resolveEntitySlug`/`resolveEntitySlugWithSource` and `not_entity` from `resolveStrictEntityReference`.
+- `src/core/entities/resolve.ts`: a page is retired when its frontmatter has `canonical: false`, a `superseded_by` or `merged_into` target, or a `status` naming it an alias or a redirect. The fuzzy and same-name arms of both resolvers, bare-name prefix expansion and the phantom-merge candidate queries exclude retired pages in SQL before uniqueness is counted. The exact-slug, basename and alias arms follow a retired page's `superseded_by` (else `merged_into`; `[[...]]`, `.md` and a leading `/` are stripped) within the same source, at most 5 hops, refusing on a cycle, a missing or deleted target, or (strict resolver with `excludePrivate`) a private one. An exact hit that cannot be followed is reported as `fallback_slugify` (unresolved) by `resolveEntitySlugWithSource` and as `not_entity` by `resolveStrictEntityReference`. Relational recall's exact-title fallback skips retired pages too.
- Alias lookup tries the literal normalized reference first, then its words rejoined with a space, `-` and `_`; a slug-shaped reference uses its last segment, and a folded hit must sit in the same parent directory (`projects/acme-example` never resolves to a `companies/` page's alias). `normalizeAlias` itself is unchanged, so stored `page_aliases` rows, search's alias hop, mentions and CJK handling behave as before.
- Tests: `test/entity-resolve-retired-alias-6898.test.ts` (PGLite, including the facts backstop landing both spellings on the canonical page) and `test/e2e/entity-resolve-retired-alias-6898-postgres.test.ts` share the fixture and cases in `test/helpers/retired-alias-6898.ts`; both fail on the previous resolver.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index c3c4414067..8ae8cfeb3a 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -83,7 +83,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (`slugify`; `slugifySegment` where `slugify` would delete letters; null if empty). Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities. Retired pages (#6898: `canonical: false`, a `superseded_by`/`merged_into` target, or an alias/redirect/superseded/merged `status`) never win a guessing arm; exact, basename and alias hits follow `superseded_by` (5 hops, same source, readable, cycle-safe) or return null. Alias lookup also tries the reference's words joined by space, `-` and `_` (last slug segment, same parent dir). Pinned by `test/entity-resolve-retired-alias-6898.test.ts`.
+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (`slugify`; `slugifySegment` where `slugify` would delete letters; null if empty). Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities. Retired pages (#6898: `canonical: false`, a `superseded_by`/`merged_into` target, or an alias/redirect `status`) never win a guessing arm; exact, basename and alias hits follow `superseded_by` (5 hops, same source, readable, cycle-safe) or stay unresolved. Alias lookup also tries the reference's words joined by space, `-` and `_` (last slug segment, same parent dir). Pinned by `test/entity-resolve-retired-alias-6898.test.ts`.
- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.
- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (`supersession-threshold.ts`; none for an uncalibrated model); capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `wouldDedupSamePage(ctx, existing, score, claim)` (#6333, shadow only, wave 15 [UC2]) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, `source_session` and visibility, sits at or above `SAME_PAGE_REWORDING_THRESHOLD` (0.85) and does not `claimsDiverge`; the backstop counts it as `would_dedup_same_page` on its result, logs the matched id, cosine and session on stderr, and inserts the fact as before. Its measured false positives (Lisbon→Porto, approved→rejected, email→phone are all counted) are pinned in `test/backstop-same-page-shadow-6333.test.ts` and are why no drop path ships. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 610633cf2c..4abd578dc1 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.retired ? (await followRetirement(engine, source_id, exact.slug))?.slug ?? null : exact.slug;
+ if (exact) return exact.retired ? (await followRetirement(engine, source_id, exact.slug))?.slug ?? fallbackSlugify(trimmed) : exact.slug;
}
// 1.25. Exact own name: a live page whose slug basename IS the mention wins
@@ -169,16 +169,17 @@ export function sameEntityName(reference: string, candidateTitle: string | null
* #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.
+ * page an alias or a redirect (`historical-retired-alias`). A status that
+ * describes the entity itself (`retired`, `archived`, `merged`, `superseded`)
+ * does not retire the page: a person who retired is still that person's page,
+ * and a merged company or a superseded decision is still a record of its own
+ * unless it names a target.
*/
-function retiredPageSql(p: string): string {
+export 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]|$)')`;
+ OR lower(COALESCE(${p}.frontmatter->>'status', '')) ~ '(^|[^a-z])(alias|redirect|redirected)([^a-z]|$)')`;
}
const MAX_RETIREMENT_HOPS = 5;
@@ -195,7 +196,9 @@ function redirectSlug(value: string): string | null {
* `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.
+ * caller refuses rather than guess. The target is a human-written redirect,
+ * so it is followed whatever its type; the strict resolver still applies its
+ * fact-entity check to the page it lands on.
*/
async function followRetirement(
engine: BrainEngine,
@@ -384,7 +387,7 @@ export async function resolveEntitySlugWithSource(
const exact = await tryExactSlug(engine, source_id, trimmed);
if (exact) {
const canonical = exact.retired ? (await followRetirement(engine, source_id, exact.slug))?.slug : exact.slug;
- return canonical ? { slug: canonical, source: 'exact_page' } : null;
+ return canonical ? { slug: canonical, source: 'exact_page' } : fallbackResult(trimmed);
}
}
@@ -471,7 +474,6 @@ export async function resolveStrictEntityReference(
const sibling = await siblingCanonical(engine, source_id, rows.map(r => r.slug), { excludePrivate: opts.excludePrivate });
return sibling ? { slug: sibling, arm } : { slug: null, miss: 'ambiguous' };
}
- if (rows.length === 0) return null;
return await isEntity(rows[0]) ? { slug: rows[0].slug, arm } : { slug: null, miss: 'not_entity' };
};
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 7583e13289..7dbc8b08d1 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -29,7 +29,7 @@ import type { SearchResult, PageType, RelationalFanoutRow, PageReadPolicy } from
import { createAuditWriter } from '../audit/audit-writer.ts';
import { listSources } from '../sources-ops.ts';
import { ALL_SOURCES } from '../source-id.ts';
-import { resolveEntitySlugWithSource } from '../entities/resolve.ts';
+import { resolveEntitySlugWithSource, retiredPageSql } from '../entities/resolve.ts';
import { buildVisibilityClause } from './sql-ranking.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
import { boundedProjectedPrefix } from '../page-window/document.ts';
@@ -151,7 +151,7 @@ async function resolveSeedScoped(
if (r?.source === 'fallback_slugify' && titleTypes.length) {
const titled = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
- AND lower(title) = lower($3) LIMIT 2`, [sid, titleTypes, phrase.trim()]);
+ AND lower(title) = lower($3) AND NOT ${retiredPageSql('pages')} LIMIT 2`, [sid, titleTypes, phrase.trim()]);
if (titled.length === 1) r = { slug: titled[0].slug, source: 'exact_page' };
}
if (!r || r.source === 'fallback_slugify') continue;
diff --git a/test/helpers/retired-alias-6898.ts b/test/helpers/retired-alias-6898.ts
index 1985a7c994..b8b8577197 100644
--- a/test/helpers/retired-alias-6898.ts
+++ b/test/helpers/retired-alias-6898.ts
@@ -36,7 +36,9 @@ const PAGES: Array<[string, Record<string, unknown>, string]> = [
['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'],
+ ['people/root-copy/bob-example', { type: 'person', status: 'retired-alias' }, 'Bob Example'],
+ // A merged company that names no target is still a record of its own.
+ ['companies/merged-co-example', { type: 'company', status: 'merged' }, 'Merged Co 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'],
@@ -78,10 +80,10 @@ export function retiredAliasCases(getEngine: () => BrainEngine): void {
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 () => {
+ test('no redirect, a missing target or a cycle is unresolved instead of a guess', 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();
+ expect(await resolve(slug)).toEqual({ slug, source: 'fallback_slugify' });
+ expect(await resolveEntitySlug(getEngine(), 'default', slug)).toBe(slug);
}
});
});
@@ -91,8 +93,10 @@ export function retiredAliasCases(getEngine: () => BrainEngine): void {
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 () => {
+ test('a page whose status describes the entity stays a candidate', async () => {
expect((await resolve('Erin Example'))?.slug).toBe('people/erin-example');
+ expect(await resolve('Merged Co Example')).toEqual({ slug: 'companies/merged-co-example', source: 'fuzzy_match' });
+ expect(await resolve('companies/merged-co-example')).toEqual({ slug: 'companies/merged-co-example', source: 'exact_page' });
});
});