Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): person_title_duplicates, preview-only title-prefixed person pairs (#7160)
garrytand0761a41e37b
diff --git a/src/commands/doctor/checks/entity-duplicates.ts b/src/commands/doctor/checks/entity-duplicates.tsnew file mode 100644index 0000000000..14536bb389--- /dev/null+++ b/src/commands/doctor/checks/entity-duplicates.ts@@ -0,0 +1,103 @@+/**+ * person_title_duplicates (#7160): person pages whose slug starts with a title+ * or role ("people/mayor-example", "people/dr-alice-example") next to the+ * unprefixed page of the same person. Links and facts split across the two+ * pages, and a lookup of the titled form lands on the stub.+ *+ * Read-only and preview-first: it lists likely pairs and never merges. A pair+ * qualifies only when the prefixed page's remaining name resolves by the+ * entity card's variant rules (verbs/entity-variants.ts) to exactly one other+ * person page in the same source; a surname two people share pairs with+ * nobody. The owner decides each pair; marking the stub `merged_into:+ * <canonical slug>` makes entity lookup and link resolution follow it.+ *+ * A stub already marked retired (merged_into, superseded_by, canonical:+ * false) is settled and not listed.+ *+ * Bounded: titled candidates come from exact slug-prefix reads+ * (PAIR_SCAN_CAP per brain), one variant read each, one batched link count.+ */+import type { Check } from '../../doctor.ts';+import { NAME_TITLE_TOKENS, parsePersonName } from '../../../core/entities/name-variants.ts';+import { resolveNameVariant } from '../../../core/verbs/entity-variants.ts';+import { retiredPageSql } from '../../../core/entities/resolve.ts';+import { doctorVerify } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export const NAME = 'person_title_duplicates';+/** Titled person pages examined per run; more are reported as not examined. */+export const PAIR_SCAN_CAP = 200;+/** Pairs printed in the message (all are in details, up to the scan cap). */+const SHOWN = 10;++export interface TitleDuplicatePair { source_id: string; stub: string; canonical: string; stub_links: number; canonical_links: number }++const PREFIXES = [...NAME_TITLE_TOKENS].map(t => `people/${t}-%`);++async function runPersonTitleDuplicates(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat(NAME);+ try {+ const sources = ctx.orphanRatioSourceId+ ? [ctx.orphanRatioSourceId]+ : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(r => r.id);+ const pairs: TitleDuplicatePair[] = [];+ let scanned = 0;+ let capped = false;+ for (const sourceId of sources) {+ if (scanned >= PAIR_SCAN_CAP) { capped = true; break; }+ const stubs = await engine.executeRaw<{ slug: string; title: string | null }>(+ `SELECT slug, title FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE ANY($2::text[]) AND NOT ${retiredPageSql('pages')}+ ORDER BY slug LIMIT ${PAIR_SCAN_CAP - scanned + 1}`, [sourceId, PREFIXES]);+ if (stubs.length > PAIR_SCAN_CAP - scanned) capped = true;+ for (const stub of stubs.slice(0, PAIR_SCAN_CAP - scanned)) {+ scanned++;+ const remainder = parsePersonName((stub.slug.split('/').pop() ?? '').replace(/-/g, ' ')).core.join(' ');+ if (!remainder) continue;+ const res = await resolveNameVariant(engine, sourceId, remainder, {+ selectColumns: 'slug, title, type, frontmatter', privatePredicate: '', retirementPrivacy: '', entityTypes: new Set(['person']), exclude: [stub.slug],+ });+ if (res.hit && res.hit.row.slug.startsWith('people/')) pairs.push({ source_id: sourceId, stub: stub.slug, canonical: res.hit.row.slug, stub_links: 0, canonical_links: 0 });+ }+ }+ if (pairs.length) {+ const counts = await engine.executeRaw<{ source_id: string; slug: string; n: number }>(+ `SELECT p.source_id, p.slug, count(DISTINCT l.from_page_id)::int AS n+ FROM pages p JOIN links l ON l.to_page_id = p.id+ WHERE (p.source_id, p.slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))+ GROUP BY p.source_id, p.slug`,+ [pairs.flatMap(p => [p.source_id, p.source_id]), pairs.flatMap(p => [p.stub, p.canonical])]);+ const n = new Map(counts.map(c => [`${c.source_id}:${c.slug}`, Number(c.n)]));+ for (const p of pairs) {+ p.stub_links = n.get(`${p.source_id}:${p.stub}`) ?? 0;+ p.canonical_links = n.get(`${p.source_id}:${p.canonical}`) ?? 0;+ }+ }+ const scope = capped ? ` Examined the first ${PAIR_SCAN_CAP} titled person pages only; rerun with --source <id> to cover the rest.` : '';+ if (!pairs.length) {+ checks.push({ name: 'person_title_duplicates', status: 'ok', message: `No title-prefixed person page pairs with an unprefixed page (${scanned} titled page(s) examined).${scope}`, details: { scanned, capped, pairs: [] } });+ return checks;+ }+ const shown = pairs.slice(0, SHOWN).map(p => `${p.source_id}:${p.stub} (${p.stub_links} inbound) -> ${p.canonical} (${p.canonical_links} inbound)`).join('; ');+ const first = pairs[0]!;+ checks.push({+ name: 'person_title_duplicates',+ status: 'warn',+ message: `${pairs.length} title-prefixed person page(s) likely duplicate an unprefixed page of the same person, so links and lookups split between them. Nothing was changed. ${shown}${pairs.length > SHOWN ? `; ${pairs.length - SHOWN} more in details` : ''}.${scope}`,+ details: { scanned, capped, pairs },+ fix: {+ ask_user: true, actor: 'user', consent: [], requires_exclusive: false, verify: doctorVerify(NAME),+ argv: ['gbrain', 'get', first.stub, '--source', first.source_id],+ why: 'Each pair is a guess from names alone; only the owner can say whether the two pages are one person.',+ user_message: `Review each pair (for example ${first.stub} and ${first.canonical}). Where both pages are the same person, add \`merged_into: ${first.canonical}\` to the titled page's frontmatter (move anything worth keeping first); entity lookup and link resolution then follow it. Leave pairs that are different people as they are.`,+ },+ });+ } catch (err) {+ checks.push({ name: 'person_title_duplicates', status: 'warn', message: `Title-prefixed person pages could not be checked: ${err instanceof Error ? err.message : String(err)}. Health is unknown.` });+ }+ return checks;+}++export const personTitleDuplicatesEntry: DoctorEntry = { name: 'person_title_duplicates', emits: ['person_title_duplicates'], run: runPersonTitleDuplicates };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex f060e60d7f..008533a2d3 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -105,6 +105,7 @@ import { factAdmissionFloorsEntry } from './checks/fact-admission-floors.ts';import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';import { edgeValidityEntry } from './checks/edge-validity.ts';import { coreMemoryEntry } from './checks/core-memory.ts';+import { personTitleDuplicatesEntry } from './checks/entity-duplicates.ts';import { plannerStatsEntry } from './checks/planner-stats.ts';import { revisionBackfillEntry } from './checks/revision-backfill.ts';import { beliefLedgerEntry } from './checks/belief-ledger.ts';@@ -266,6 +267,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [// #6712 PR 4a: the read-only convergence shadow (deep tier: a full level read per source).managedSyncConvergenceEntry,fenceIntegrityEntry,+ // #7160: title-prefixed person pages next to the unprefixed page (read-only, preview-first).+ personTitleDuplicatesEntry,searchModeEntry,];diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 10f5bbeb9c..48484f4785 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -195,6 +195,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).'unlinked_facts',+ // #7160: title-prefixed person pages that likely duplicate an unprefixed page (preview only).+ 'person_title_duplicates','edge_validity','text_projection_readiness','timeline_coverage',diff --git a/test/doctor-person-title-duplicates.test.ts b/test/doctor-person-title-duplicates.test.tsnew file mode 100644index 0000000000..f709b9d614--- /dev/null+++ b/test/doctor-person-title-duplicates.test.ts@@ -0,0 +1,77 @@+/**+ * person_title_duplicates doctor check (#7160): title-prefixed person pages+ * next to the unprefixed page of the same person, reported and never merged.+ * PGLite in-memory, synthetic names.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { personTitleDuplicatesEntry } from '../src/commands/doctor/checks/entity-duplicates.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++const person = (slug: string, title: string) => engine.putPage(slug, { title, type: 'person', compiled_truth: `${title}.` } as never);++beforeEach(async () => {+ await resetPgliteState(engine);+ await person('people/robert-thistlewood', 'Robert Thistlewood');+ await person('people/alice-example', 'Alice Example');+ await person('people/bob-sample', 'Bob Sample');+ await person('people/carol-sample', 'Carol Sample');+});++async function check() {+ const ctx = { engine, orphanRatioSourceId: undefined, progress: { heartbeat() {} } } as unknown as DoctorContext;+ const [c] = await personTitleDuplicatesEntry.run(ctx) as Array<{ name: string; status: string; message: string; details: any; fix?: any }>;+ return c!;+}++describe('person_title_duplicates', () => {+ test('ok when no titled person page exists', async () => {+ const c = await check();+ expect(c).toMatchObject({ name: 'person_title_duplicates', status: 'ok' });+ });++ test('pairs a titled stub with the one person its remaining name resolves to, without changing anything', async () => {+ await person('people/mayor-thistlewood', 'Mayor Thistlewood');+ await person('people/dr-alice-example', 'Dr. Alice Example');+ const c = await check();+ expect(c.status).toBe('warn');+ expect(c.details.pairs.map((p: any) => [p.stub, p.canonical])).toEqual([+ ['people/dr-alice-example', 'people/alice-example'],+ ['people/mayor-thistlewood', 'people/robert-thistlewood'],+ ]);+ expect(c.fix.ask_user).toBe(true);+ expect(c.fix.user_message).toContain('merged_into:');+ const [still] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE slug = 'people/mayor-thistlewood' AND deleted_at IS NULL");+ expect(still!.n).toBe(1);+ });++ test('a surname two people share pairs with nobody', async () => {+ await person('people/mayor-sample', 'Mayor Sample');+ const c = await check();+ expect(c.status).toBe('ok');+ });++ test('a stub the owner already marked merged_into is settled and not listed', async () => {+ await engine.putPage('people/mayor-thistlewood', { title: 'Mayor Thistlewood', type: 'person', compiled_truth: 'x', frontmatter: { merged_into: 'people/robert-thistlewood' } } as never);+ const c = await check();+ expect(c.status).toBe('ok');+ });++ test('is categorized', () => {+ expect(categorizeCheck('person_title_duplicates')).toBeTruthy();+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex fc9e438d91..76169f3a9c 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 252798,- "stdoutSha256": "71b348f0e16ec33eeb7b856a2fa24821a5f971503416d541e00226572381ab56",+ "stdoutBytes": 253109,+ "stdoutSha256": "52884f634d8625753ff796aab76902ff1c4faf428fe04f7a03cc6857f157c24f","toolNames": ["remember","entity",@@ -306,7 +306,8 @@"name": "string?","names": "array?","prefer_source_id": "string?",- "source_id": "string?"+ "source_id": "string?",+ "variants": "boolean?"},"required_scopes": [],"schema": {@@ -329,6 +330,10 @@"source_id": {"description": "Read only this source. Default: your source first, then every source you can read.","type": "string"+ },+ "variants": {+ "description": "Default true: when no exact name matches, resolve one unambiguous name variant (nickname, initial, title, order, surname typo, unique surname; card.match says which). false: exact names only.",+ "type": "boolean"}},"required": [],diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 4f0186f14b..6554ae66b1 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -3072,6 +3072,18 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "capped": false,+ "pairs": [],+ "scanned": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No title-prefixed person page pairs with an unprefixed page (0 titled page(s) examined).",+ "name": "person_title_duplicates",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex c12e5e302a..b013ec2a7e 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -3116,6 +3116,18 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "capped": false,+ "pairs": [],+ "scanned": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No title-prefixed person page pairs with an unprefixed page (0 titled page(s) examined).",+ "name": "person_title_duplicates",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex f3decf8131..7ae918664d 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -925,6 +925,10 @@"category": "brain","name": "fence_integrity"},+ {+ "category": "brain",+ "name": "person_title_duplicates"+ },{"category": "ops","name": "search_mode"