Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(enrich): GBRA-130 PR 2 review F8 keep entity identity across escaped and shortened slugs

garrytan6a22c2a0f0da
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 97c21b84db..48775980ee 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -37,7 +37,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy
- `src/core/dry-fix.ts` — `gbrain doctor --fix` engine. `autoFixDryViolations(fixes, {dryRun})` rewrites inlined rules to `> **Convention:** see [path](../path).` callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (`getWorkingTreeStatus()` 3-state `'clean' | 'dirty' | 'not_a_repo'`), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout. `execFileSync` array args (no shell, no injection surface). EOF newline preserved. Safety primitives are in `src/core/skill-fix-gates.ts` (back-compat re-exports preserved). `MISSING_RULE_PATTERNS` INSERT pattern type lives alongside REPLACE patterns — same auto-fix entry point + git-safety gates, but places a canonical callout at a target offset (`after-h1-paragraph` only). First INSERT pattern is `brain_first`, auto-inserting `> **Convention:** see [conventions/brain-first.md](../../conventions/brain-first.md) for the lookup chain (search → query → get_page → external).` on any flagged SKILL.md whose verdict is `missing_brain_first`. Idempotent — re-runs detect the existing callout and skip.
-- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.
+- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. A reserved name is suffixed with the type (`companies/aux-company`) and an over-budget name is cut and tagged with 8 hex digits of its full slug's SHA-256, so long names sharing a prefix keep separate pages (GBRA-130 F8). A page at an escaped slug is reused only when its title maps to the same full slug; when the matching legacy page exists it wins, and when another entity holds the slug (`Aux Company` at `aux-company`, or `Prn` minted at `Prn Company`'s natural slug) the entity takes its hash-tagged slug, skipping with `skipped_reason: 'entity_slug_taken'` if that one names another entity too. Pinned by `test/pathological/b5-enrich-entity-identity.test.ts`. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.
- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. `largePageBodyFilter(alias)` is its SQL twin (`body_bytes` of a segmented page, else the body columns' `octet_length`) and `pageBudgetLimitedFilter(alias)` the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying (PR 2 fix lane J2; test `test/large-pages/held-budget-shrink.test.ts`). The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.
- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation) while they are large (`pageBudgetLimitedFilter`); a page edited down to 1 MiB or under is unmetered and its row is ignored there, in `listBudgetLimitedPages` and in `pageSizeState`, and applies again if the page grows back. `listBudgetLimitedPages` (no row cap with `limit: null`) feeds `gbrain embed --held`; the hold and cap lines `meterPageBatch` prints name a per-page approve with a concrete N (held-embedding-action.ts), and `sizeStateLines` names `gbrain embed --held --dry-run --source <id>`. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.md
index 17fd64d73f..88a210b745 100644
--- a/docs/architecture/key-files/page-identity-and-administration.md
+++ b/docs/architecture/key-files/page-identity-and-administration.md
@@ -81,4 +81,4 @@ upgrade consequence and engine parity respectively.
- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. The same admission refuses a NEW slug with a Windows reserved device segment or a segment over 240 bytes (`slug_not_portable`, suggestion from `portable-slug.ts`); a live page with that slug still updates and gets a `slug_advisory` naming the move. `:` stays valid slug grammar. `validateSlug` and path-derived import slugs are unchanged. Tests: `test/ingestion/put-page-write-through.test.ts`, `test/pathological/b5-export-unsafe-slugs.test.ts`, `test/pathological/b12-slug-segment-bytes.test.ts`.
-- `src/core/portable-slug.ts` — the one slug portability rule (GBRA-130 B-5/B-12): `FILE_NAME_MAX_BYTES` (240, a name's byte budget; a leaf also reserves `.json`), `RESERVED_DEVICE_NAME` (con, prn, aux, nul, com1-9, lpt1-9, alone or before an extension), `truncateUtf8`, `portableSegment` (a reserved name gets `-<suffix>`, an over-budget segment is cut at a code point boundary) and `slugPortabilityProblem` (reason, first segment, suggested slug). Used by `persistence/suffixed-slug.ts` admission and `enrichment-service.ts` `slugifyEntity`, so a reserved entity name mints `people/con-person` or `companies/com1-company`.
+- `src/core/portable-slug.ts` — the one slug portability rule (GBRA-130 B-5/B-12): `FILE_NAME_MAX_BYTES` (240, a name's byte budget; a leaf also reserves `.json`), `RESERVED_DEVICE_NAME` (con, prn, aux, nul, com1-9, lpt1-9, alone or before an extension), `truncateUtf8`, `portableSegment` (a reserved name gets `-<suffix>`, an over-budget segment is cut at a code point boundary) and `slugPortabilityProblem` (reason, first segment, suggested slug). Used by `persistence/suffixed-slug.ts` admission; `enrichment-service.ts` `slugifyEntity` uses its parts, so a reserved entity name mints `people/con-person` or `companies/com1-company` and an over-budget one ends in a hash of the full name.
diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.ts
index b374e518c7..6b323978fb 100644
--- a/src/core/enrichment-service.ts
+++ b/src/core/enrichment-service.ts
@@ -19,7 +19,8 @@ import { OperationError } from './ops/contract.ts';
import { waitForCapacity } from './backoff.ts';
import { quarantineMarkers } from './extraction-review.ts';
import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
-import { portableSegment } from './portable-slug.ts';
+import { createHash } from 'node:crypto';
+import { RESERVED_DEVICE_NAME, segmentByteBudget, truncateUtf8 } from './portable-slug.ts';
// #3994: created stubs route through serializeMarkdown + importFromContent
// (the same parse→chunk→embed pipeline put_page uses) instead of a bare
// engine.putPage, so fresh entity pages land in the retrieval surface
@@ -77,8 +78,11 @@ export interface EnrichmentResult {
action: 'created' | 'updated' | 'skipped';
/** True when the created stub landed in the quarantine lane (issue #160). */
quarantined?: boolean;
- /** Why nothing was written: the page is retired and its superseded_by / merged_into chain has no live target (B-9). */
- skipped_reason?: 'retired_page_unfollowable';
+ /**
+ * Why nothing was written: the page is retired and its superseded_by / merged_into chain has no live target (B-9),
+ * or both this entity's slug and its hash-tagged slug hold pages that name another entity.
+ */
+ skipped_reason?: 'retired_page_unfollowable' | 'entity_slug_taken';
tier: 1 | 2 | 3;
backlinkCreated: boolean;
timelineAdded: boolean;
@@ -108,12 +112,18 @@ const SLUGIFY_ENTITY_KEEP_RE = new RegExp(`[^${SLUG_WORD_CHARS}]`, 'gu');
* as-is (Cyrillic, CJK, Devanagari, …). A name that slugifies to a Windows
* reserved device name gets the entity type as a suffix (`Con` →
* `people/con-person`) and an over-long one is cut to the file-name budget
- * (portable-slug.ts), so a stub is always a page export and write-through can
- * store; a page an older brain created as `people/con` is still found through
- * the legacy-slug lookup in enrichEntity.
+ * and tagged with a hash of its full slug (portable-slug.ts), so a stub is
+ * always a page export and write-through can store and two long names sharing
+ * a prefix keep separate pages; a page an older brain created as `people/con`
+ * is still found through the legacy-slug lookup in enrichEntity.
*/
export function slugifyEntity(name: string, type: 'person' | 'company'): string {
- const slug = name
+ return `${type === 'person' ? 'people' : 'companies'}/${entitySegment(entitySlugBase(name), type, false)}`;
+}
+
+/** The full slug segment a name maps to before portability escaping: the identity two names share when it is equal. */
+function entitySlugBase(name: string): string {
+ return name
.replace(/['‘’]/g, '')
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
@@ -123,9 +133,19 @@ export function slugifyEntity(name: string, type: 'person' | 'company'): string
.replace(SLUGIFY_ENTITY_KEEP_RE, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '');
+}
- const prefix = type === 'person' ? 'people' : 'companies';
- return `${prefix}/${portableSegment(slug, true, type)}`;
+/**
+ * The portable file name for a slug base: a reserved name gets the entity type
+ * as a suffix, and a name over the budget (or any name when `tagged`) ends in
+ * the first 8 hex digits of the base's SHA-256, cut to fit before the tag.
+ */
+function entitySegment(base: string, type: 'person' | 'company', tagged: boolean): string {
+ const renamed = base.replace(RESERVED_DEVICE_NAME, name => `${name}-${type}`);
+ const budget = segmentByteBudget(true);
+ if (!tagged && Buffer.byteLength(renamed) <= budget) return renamed;
+ const tag = createHash('sha256').update(base).digest('hex').slice(0, 8);
+ return `${truncateUtf8(renamed, budget - tag.length - 1).replace(/[-._:]+$/, '')}-${tag}`;
}
/**
@@ -162,7 +182,9 @@ export async function enrichEntity(
request: EnrichmentRequest,
opts?: EnrichmentTrustOptions,
): Promise<EnrichmentResult> {
- const candidateSlug = slugifyEntity(request.entityName, request.entityType);
+ const base = entitySlugBase(request.entityName);
+ const prefix = request.entityType === 'person' ? 'people' : 'companies';
+ const candidateSlug = `${prefix}/${entitySegment(base, request.entityType, false)}`;
const sourceId = opts?.sourceId ?? 'default';
let slug = await engine.resolveSlugWithAlias(candidateSlug, sourceId);
// Fail-closed: only an explicit `trusted: true` writes authoritative pages.
@@ -188,15 +210,35 @@ export async function enrichEntity(
// 3. Check if entity page exists
let existingPage = await engine.getPage(slug, scope);
- if (!existingPage) {
+ // F8: a page whose title maps to this slug base names this entity; any other page at the slug may name another one.
+ const namesEntity = (title: string | undefined) => entitySlugBase(title ?? '') === base;
+ if (!existingPage || !namesEntity(existingPage.title)) {
// A page an older brain created under the ASCII-only slug is the same entity.
const legacy = legacyAsciiEntitySlug(request.entityName, request.entityType);
+ let legacyFound = false;
if (legacy !== candidateSlug && !/^(people|companies)\/$/.test(legacy)) {
const legacySlug = await engine.resolveSlugWithAlias(legacy, sourceId);
const legacyPage = await engine.getPage(legacySlug, { sourceId });
// The legacy slug is lossy (José -> people/jos), so only reuse a page that names this entity.
const same = (t: string) => t.normalize('NFC').trim().toLowerCase();
- if (legacyPage && same(legacyPage.title ?? '') === same(request.entityName)) { slug = legacySlug; existingPage = legacyPage; }
+ if (legacyPage && same(legacyPage.title ?? '') === same(request.entityName)) { slug = legacySlug; existingPage = legacyPage; legacyFound = true; }
+ }
+ // An escaped slug (Aux -> companies/aux-company) can be another entity's natural slug, and a natural slug can be
+ // the escaped slug another entity was minted at (Prn Company's companies/prn-company held by Prn): either way the
+ // page names another entity, so this one takes its hash-tagged slug. A page a person titled differently at this
+ // entity's natural slug stays this entity's page.
+ const heldByOther = !legacyFound && existingPage !== null &&
+ (candidateSlug !== `${prefix}/${base}` || slugifyEntity(existingPage.title ?? '', request.entityType) === candidateSlug);
+ if (heldByOther) {
+ const tagged = `${prefix}/${entitySegment(base, request.entityType, true)}`;
+ const taggedSlug = tagged === candidateSlug ? null : await engine.resolveSlugWithAlias(tagged, sourceId);
+ const taggedPage = taggedSlug === null ? null : await engine.getPage(taggedSlug, scope);
+ if (taggedSlug === null || (taggedPage && !namesEntity(taggedPage.title))) {
+ return { slug, action: 'skipped', skipped_reason: 'entity_slug_taken', tier, backlinkCreated: false, timelineAdded: false,
+ mentionCount, mentionSources, suggestedTier, tierEscalated };
+ }
+ slug = taggedSlug;
+ existingPage = taggedPage;
}
}
// B-9: a retired page (canonical: false, superseded_by) answers through its canonical page, as fact resolution does (#6898).
diff --git a/test/pathological/b5-enrich-entity-identity.test.ts b/test/pathological/b5-enrich-entity-identity.test.ts
new file mode 100644
index 0000000000..1de4aaa140
--- /dev/null
+++ b/test/pathological/b5-enrich-entity-identity.test.ts
@@ -0,0 +1,119 @@
+/**
+ * GBRA-130 PR 2 review F8: an escaped or shortened entity slug kept no
+ * identity of the name it came from.
+ *
+ * slugifyEntity suffixes a Windows reserved name with the entity type (B-5:
+ * `Aux` -> `companies/aux-company`) and cut an over-long name to the file-name
+ * budget (B-12). Both are lossy: `Aux` then shared a slug with a company
+ * really named `Aux Company`, and two long names sharing their first 235 bytes
+ * shared one slug. enrichEntity reused whatever page sat at the slug, so
+ * enriching `Aux` wrote its timeline row and backlink to `Aux Company` and
+ * never looked at the legacy `companies/aux` page that names it. The fix tags
+ * a shortened name with a hash of the full name, checks that a page found at an
+ * escaped slug names this entity, prefers the matching legacy page, and gives
+ * an entity whose slug another entity holds its own hash-tagged page.
+ *
+ * Real PGLite, plus the Postgres arm when DATABASE_URL is set
+ * (test/postgres-unit-arms.txt). Placeholder names only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { enrichEntity, slugifyEntity } from '../../src/core/enrichment-service.ts';
+import { openArm, pathologicalArms } from './_gbra60-shim.ts';
+
+const page = (type: string, title: string) => `---\ntitle: ${JSON.stringify(title)}\ntype: ${type}\n---\n\n# ${title}\n`;
+const PREFIX = 'acme-example-holdings-'.repeat(11);
+const LONG_ONE = `${PREFIX}North`;
+const LONG_TWO = `${PREFIX}South`;
+
+async function seed(engine: BrainEngine): Promise<void> {
+ const pages: Array<[string, string, string]> = [
+ ['companies/aux', 'company', 'Aux'],
+ ['companies/aux-company', 'company', 'Aux Company'],
+ ['people/con-person', 'person', 'Con Person'],
+ ['companies/lpt1-company', 'company', 'Lpt1 Company'],
+ [`companies/lpt1-company-${createHash('sha256').update('lpt1').digest('hex').slice(0, 8)}`, 'company', 'Other Example'],
+ ['notes/source-example', 'note', 'Source Example'],
+ ];
+ for (const [slug, type, title] of pages) await importFromContent(engine, slug, page(type, title), { noEmbed: true });
+}
+
+const counts = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ timeline: number; links: number }>(
+ `SELECT (SELECT count(*)::int FROM timeline_entries t WHERE t.page_id = p.id) AS timeline,
+ (SELECT count(*)::int FROM links l WHERE l.from_page_id = p.id) AS links
+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL`, [slug]))[0] ?? null;
+const title = async (engine: BrainEngine, slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))?.title ?? null;
+
+const arms = pathologicalArms();
+const engines: Array<{ name: string; engine: BrainEngine; close: () => Promise<void> }> = [];
+beforeAll(async () => {
+ for (const arm of arms) {
+ const { engine, close } = await openArm(arm); await seed(engine);
+ engines.push({ name: arm.backend, engine, close });
+ }
+}, 120_000);
+afterAll(async () => { for (const e of engines) await e.close(); });
+
+for (const { backend } of arms) {
+ const engine = () => engines.find(e => e.name === backend)!.engine;
+ const enrich = (entityName: string, entityType: 'person' | 'company') =>
+ enrichEntity(engine(), { entityName, entityType, context: 'named in passing', sourceSlug: 'notes/source-example' }, { trusted: true });
+
+ describe(`F8 enrichment keeps entity identity across escaped and shortened slugs (${backend})`, () => {
+ test('F8: enriching Aux updates the legacy companies/aux page and leaves Aux Company untouched', async () => {
+ const aux = await enrich('Aux', 'company');
+ expect({ slug: aux.slug, action: aux.action }).toEqual({ slug: 'companies/aux', action: 'updated' });
+ expect(await counts(engine(), 'companies/aux-company')).toEqual({ timeline: 0, links: 0 });
+ expect(await counts(engine(), 'companies/aux')).toEqual({ timeline: 1, links: 1 });
+ const company = await enrich('Aux Company', 'company');
+ expect({ slug: company.slug, action: company.action }).toEqual({ slug: 'companies/aux-company', action: 'updated' });
+ expect(await counts(engine(), 'companies/aux')).toEqual({ timeline: 1, links: 1 });
+ });
+
+ test('F8: Con gets its own page when Con Person holds people/con-person, and keeps it on the next mention', async () => {
+ const first = await enrich('Con', 'person');
+ expect({ slug: first.slug, action: first.action }).toEqual({ slug: expect.stringMatching(/^people\/con-person-[0-9a-f]{8}$/), action: 'created' });
+ expect(await title(engine(), first.slug)).toBe('Con');
+ expect(await counts(engine(), 'people/con-person')).toEqual({ timeline: 0, links: 0 });
+ const again = await enrich('Con', 'person');
+ expect({ slug: again.slug, action: again.action }).toEqual({ slug: first.slug, action: 'updated' });
+ expect((await enrich('Con Person', 'person')).slug).toBe('people/con-person');
+ expect(await counts(engine(), first.slug)).toEqual({ timeline: 1, links: 1 });
+ });
+
+ test('F8: a company really named Prn Company does not land on the page minted for Prn', async () => {
+ const prn = await enrich('Prn', 'company');
+ expect({ slug: prn.slug, action: prn.action }).toEqual({ slug: 'companies/prn-company', action: 'created' });
+ const company = await enrich('Prn Company', 'company');
+ expect({ slug: company.slug, action: company.action }).toEqual({ slug: expect.stringMatching(/^companies\/prn-company-[0-9a-f]{8}$/), action: 'created' });
+ expect(await title(engine(), company.slug)).toBe('Prn Company');
+ expect(await counts(engine(), 'companies/prn-company')).toEqual({ timeline: 1, links: 1 });
+ });
+
+ test('F8: when the hash-tagged slug also names another entity, enrichment skips with a reason and writes nothing', async () => {
+ const tagged = `companies/lpt1-company-${createHash('sha256').update('lpt1').digest('hex').slice(0, 8)}`;
+ const result = await enrich('Lpt1', 'company');
+ expect(result).toMatchObject({ action: 'skipped', skipped_reason: 'entity_slug_taken', timelineAdded: false, backlinkCreated: false });
+ for (const slug of ['companies/lpt1-company', tagged]) expect(await counts(engine(), slug)).toEqual({ timeline: 0, links: 0 });
+ expect(await title(engine(), tagged)).toBe('Other Example');
+ });
+
+ test('F8: two long names sharing their first 235 bytes each land on their own portable page', async () => {
+ expect(Buffer.byteLength(PREFIX)).toBeGreaterThan(235);
+ const one = await enrich(LONG_ONE, 'company');
+ const two = await enrich(LONG_TWO, 'company');
+ expect({ one: one.action, two: two.action, distinct: one.slug !== two.slug }).toEqual({ one: 'created', two: 'created', distinct: true });
+ for (const [result, name] of [[one, LONG_ONE], [two, LONG_TWO]] as const) {
+ expect(Buffer.byteLength(result.slug.split('/')[1]!)).toBeLessThanOrEqual(235);
+ expect(result.slug).toBe(slugifyEntity(name, 'company'));
+ expect(await title(engine(), result.slug)).toBe(name);
+ expect(await counts(engine(), result.slug)).toEqual({ timeline: 1, links: 1 });
+ }
+ const again = await enrich(LONG_ONE, 'company');
+ expect({ slug: again.slug, action: again.action }).toEqual({ slug: one.slug, action: 'updated' });
+ expect(await counts(engine(), two.slug)).toEqual({ timeline: 1, links: 1 });
+ });
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 7fb388a371..00ab39edbb 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -256,6 +256,7 @@ test/pathological/b-10-ontology-rekey-collision.test.ts
test/pathological/b-7-facts-pageless-entity.test.ts
test/pathological/b-9-enrich-retired-alias.test.ts
test/pathological/b12-slug-segment-bytes.test.ts
+test/pathological/b5-enrich-entity-identity.test.ts
test/pathological/b5-export-unsafe-slugs.test.ts
test/pathological/b6-triage-verdict-surrogate.test.ts
test/pathological/c-23-override-and-doctor-fixes.test.ts