Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(context): volunteer the entity page over a same-title meeting (#6725)

garrytanbe4a4ce50edf
diff --git a/docs/architecture/key-files/core-services-1-continued.md b/docs/architecture/key-files/core-services-1-continued.md
index 054781bef1..455e4cc1d9 100644
--- a/docs/architecture/key-files/core-services-1-continued.md
+++ b/docs/architecture/key-files/core-services-1-continued.md
@@ -4,6 +4,8 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The content-repair judgment tier under `src/core/content-repair/`, then the Retrieval Reflex and session-context helpers under `src/core/context/`.
+- `src/core/context/title-matches.ts` — `preferEntityTitleMatches`, the volunteer title arm's one-pointer-per-name-per-source rule: exact-title hits that share a candidate norm within one source collapse to the page the `entity` card would pick (`src/core/entities/exact-match-preference.ts`, shared with `verbs/entity-card.ts`: explicit exact slug, then a linkable type of that source's pack, then any other page), ties broken by slug. Same-title pages in different sources are different entities and all stay. It runs after the privacy and activation gate (a private or withheld entity cannot suppress an eligible fallback) and leaves a norm an alias already resolved alone; the mention policy and packs are read only on a collision. Test: `test/volunteer-title-collision.test.ts`.
+
- `src/core/content-repair/judgment.ts` — #6377 (Lane B3) the content-repair lane's model tier for a slug conflict: `judgeSlugConflict` builds the prompt from both files' frontmatter, headings and first 60 lines of body plus every line that mentions the other's slug anywhere in either body (evidence past line 60 counts), both slugs and paths, the hold's reason and the allowed answers, and parses exactly one JSON object `{"action":"remove_slug"}`, `{"action":"merge_into","canonical":"<one of the two slugs>"}` or `{"action":"needs_human"}` with an optional `why` sentence that reaches the run's output only, never hold metadata. The same failure classes, `thinkingOffControl` and output ceiling as the fence tier; a `canonical` outside the two slugs is `llm_malformed`. Memo key: sha256 of both participants' content + both ids + model + prompt version + rules version. The model is `models.content_repair` (an explicit model always runs), else `models.fence_repair`, else `CONTENT_REPAIR_MEASURED_MODELS` (the eval's qualifiers, best first, ties to the cheaper), else the fence list. Tests: `test/repair-slug-conflicts.test.ts`.
- `src/core/content-repair/llm.ts` — #6377 (Lane B3) the paid call behind `judgment.ts`: one gateway chat under the fence repair's caps and ledger (`FENCE_REPAIR_LEDGER`, so one `fences.repair.max_usd_per_day` covers the whole lane and today's fence spend counts; the per-page cap applies per candidate), `fences.repair.llm=false` and `--no-llm` turn it off, the attempt memo keeps rejected bytes from costing twice, and a transient `llm_unavailable` does not consume the memo. Spend is reported as the item's `llm_usd` and carried into the `content_repair` receipt (`model`, `cost`); prompts never include the rest of either page.
diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.ts
index 93c03ff266..481b9e2eef 100644
--- a/src/core/context/retrieval-reflex.ts
+++ b/src/core/context/retrieval-reflex.ts
@@ -42,6 +42,7 @@ import { redactFindings } from '../secret-scan.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import type { EntityCandidate } from './entity-salience.ts';
import { reflexPointerRationale } from './reflex-rationale.ts';
+import { preferEntityTitleMatches } from './title-matches.ts';
import { logVolunteerEventsFireAndForget, volunteerEventRowsFrom } from './volunteer-events.ts';
import { boundedProjectedPrefix } from '../page-window/document.ts';
import { boundedBodyPrefixSql, boundedRawPrefix, overlaidBoundedRows } from '../page-window/bounded-lead.ts';
@@ -562,7 +563,7 @@ export async function resolveEntitiesToPointers(
const trust = await gatePointerCandidates(engine, resolved, opts); // #5575 gate; then pointers by confidence, suppression + cap
const suppression = opts.suppression ?? 'slug-and-title';
const pointers: ReflexPointer[] = [];
- for (const { slug, source_id, arm, matchedNorm } of resolved) {
+ for (const { slug, source_id, arm, matchedNorm } of await preferEntityTitleMatches(engine, resolved, m => rowByKey.get(keyOf(m.source_id, m.slug)), m => trust.has(pageKey(m)), slugToNorm)) {
const row = rowByKey.get(keyOf(source_id, slug));
if (!row || !trust.has(pageKey({ source_id, slug }))) continue;
// Suppression: already present in PRIOR context. The current turn is
diff --git a/src/core/context/title-matches.ts b/src/core/context/title-matches.ts
new file mode 100644
index 0000000000..c64d64727c
--- /dev/null
+++ b/src/core/context/title-matches.ts
@@ -0,0 +1,57 @@
+/**
+ * #6725: one pointer per name per source in the volunteer title arm.
+ *
+ * Exact-title hits that share a candidate norm WITHIN one source collapse to
+ * the page the `entity` card would pick (entities/exact-match-preference.ts:
+ * explicit exact slug, then linkable entity type, then other), ties broken by
+ * slug. Same-title pages in different sources are different entities and are
+ * never collapsed. Runs after the privacy and activation gate, so a hidden or
+ * withheld entity cannot suppress an eligible fallback. A norm an alias hit
+ * already resolved is left alone (alias precedence). The mention policy and
+ * source packs are read only when a collision exists.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { exactMatchPreference } from '../entities/exact-match-preference.ts';
+
+interface TitleMatch {
+ slug: string;
+ source_id: string;
+ arm: string;
+ matchedNorm?: string;
+}
+
+export async function preferEntityTitleMatches<M extends TitleMatch>(
+ engine: BrainEngine,
+ resolved: readonly M[],
+ rowFor: (match: M) => { slug: string; type?: string | null } | undefined,
+ eligible: (match: M) => boolean,
+ slugToNorm: ReadonlyMap<string, string>,
+): Promise<M[]> {
+ const matches = resolved.filter(m => rowFor(m) !== undefined && eligible(m));
+ const aliasNorms = new Set(matches.filter(m => m.arm === 'alias').map(m => m.matchedNorm));
+ const groupKey = (m: M) => `${m.source_id}\u0000${m.matchedNorm}`;
+ const groups = new Map<string, M[]>();
+ for (const m of matches) {
+ if (m.arm !== 'title' || !m.matchedNorm || aliasNorms.has(m.matchedNorm)) continue;
+ groups.set(groupKey(m), [...(groups.get(groupKey(m)) ?? []), m]);
+ }
+ const collisions = [...groups.values()].filter(group => group.length > 1);
+ if (!collisions.length) return matches;
+
+ const { linkableTypesFor, loadSourcePack, readMentionPolicy } = await import('../mentions/policy.ts');
+ const policy = await readMentionPolicy(engine).catch(() => undefined);
+ const typesBySource = new Map<string, ReadonlySet<string>>();
+ for (const source of new Set(collisions.map(group => group[0].source_id))) {
+ typesBySource.set(source, new Set(policy ? linkableTypesFor(await loadSourcePack(engine, source), policy) : []));
+ }
+ for (const group of collisions) {
+ const exactSlugs = [...slugToNorm].filter(([, norm]) => norm === group[0].matchedNorm).map(([slug]) => slug);
+ const types = typesBySource.get(group[0].source_id)!;
+ group.sort((a, b) => exactMatchPreference(rowFor(a)!, exactSlugs, types) - exactMatchPreference(rowFor(b)!, exactSlugs, types)
+ || a.slug.localeCompare(b.slug));
+ }
+ return matches.filter(m => {
+ const group = m.arm === 'title' && m.matchedNorm ? groups.get(groupKey(m)) : undefined;
+ return !group || group[0] === m;
+ });
+}
diff --git a/src/core/entities/exact-match-preference.ts b/src/core/entities/exact-match-preference.ts
new file mode 100644
index 0000000000..a5093e5575
--- /dev/null
+++ b/src/core/entities/exact-match-preference.ts
@@ -0,0 +1,15 @@
+/**
+ * The exact-match ladder shared by the `entity` card and the volunteer title
+ * arm (#6725): among pages that match a name exactly in one source, an
+ * explicit exact slug ranks first, then a linkable entity type (the source
+ * pack's set, mentions/policy.ts), then any other page (meeting, transcript
+ * or note containers). Lower is better.
+ */
+export function exactMatchPreference(
+ row: { slug: string; type?: string | null },
+ exactSlugs: readonly string[],
+ entityTypes: ReadonlySet<string>,
+): number {
+ if (exactSlugs.includes(row.slug)) return 0;
+ return entityTypes.has(row.type ?? '') ? 1 : 2;
+}
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index e9f61d19b6..504fa8349b 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -30,6 +30,7 @@ import { loadPageTrust } from '../eligibility/stamp.ts';
import { loadRelationshipNotes, relationshipNoteKey } from '../link-relationship-notes.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { slugify } from '../entities/resolve.ts';
+import { exactMatchPreference } from '../entities/exact-match-preference.ts';
import { safeSynopsis } from '../context/retrieval-reflex.ts';
import { stampEvidence, markKeywordHits } from '../search/evidence.ts';
import type { Link, SearchResult } from '../types.ts';
@@ -400,11 +401,6 @@ export async function buildEntityCard(
};
}
-function exactMatchPreference(row: CardPageRow, exactSlugs: string[], entityTypes: ReadonlySet<string>): number {
- if (exactSlugs.includes(row.slug)) return 0;
- return entityTypes.has(row.type ?? '') ? 1 : 2;
-}
-
/**
* The `entity` verb's reference fields: every page linking here (mentions
* included), grouped by pack-canonical type with the continuation for a
diff --git a/test/volunteer-title-collision.test.ts b/test/volunteer-title-collision.test.ts
new file mode 100644
index 0000000000..d9e0165c12
--- /dev/null
+++ b/test/volunteer-title-collision.test.ts
@@ -0,0 +1,103 @@
+/**
+ * #6725: a meeting or transcript page that shares an entity's exact title must
+ * not be volunteered in place of the entity page.
+ *
+ * Protects: among exact-title hits for one name WITHIN one source, the pointer
+ * goes to the explicit exact slug, then a linkable entity type, then anything
+ * else (the same ladder the `entity` card uses), whatever order the rows were
+ * written in; the choice happens after the privacy gate, so a private entity
+ * page falls back to the readable page; same-title pages in different sources
+ * are different entities and both stay. Regression: the title arm pushed every
+ * matching row in SQL row order, so a same-title meeting took the pointer slot.
+ * Synthetic data only.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';
+import { extractCandidates } from '../src/core/context/entity-salience.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+
+let engine: PGLiteEngine;
+const config = { engine: 'pglite' } as never;
+
+async function seed(slug: string, type: string, title: string, body: string, source = 'default', frontmatter: Record<string, unknown> = {}) {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, frontmatter)
+ VALUES ($1, $2, $3, $4, $5, '', $6::text::jsonb)`,
+ [slug, source, type, title, body, JSON.stringify(frontmatter)],
+ );
+}
+
+const pointers = async (text: string, opts: Parameters<typeof resolveEntitiesToPointers>[3] = {}) =>
+ ((await resolveEntitiesToPointers(engine, 'default', extractCandidates(text), opts))?.pointers ?? []).map(p => [p.source_id, p.slug]);
+
+async function call(op: string, args: Record<string, unknown>, ctx: Record<string, unknown>) {
+ const r = await dispatchToolCall(engine, op, args, { config, ...ctx } as never);
+ expect(r.isError).toBeFalsy();
+ return JSON.parse(r.content[0].text);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('wiki', 'wiki', '{}') ON CONFLICT (id) DO NOTHING`);
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM page_aliases').catch(() => {});
+ await engine.executeRaw('DELETE FROM pages');
+});
+
+describe('#6725 same-title collisions in the volunteer title arm', () => {
+ for (const entityFirst of [false, true]) {
+ test(`the entity page wins over a same-title meeting (entity written first: ${entityFirst})`, async () => {
+ const rows: Array<[string, string]> = [['meetings/2026-10-01-alice-sync', 'conversation'], ['people/alice-example', 'person']];
+ if (entityFirst) rows.reverse();
+ for (const [slug, type] of rows) await seed(slug, type, 'Alice Example', `${type} synopsis.`);
+
+ expect(await pointers('about Alice Example', { maxPointers: 1 })).toEqual([['default', 'people/alice-example']]);
+ expect(await pointers('about Alice Example', { maxPointers: 10 })).toEqual([['default', 'people/alice-example']]);
+
+ const volunteered = await call('volunteer_context', { window: 'user: what do we know about Alice Example?' }, { remote: true, sourceId: 'default' });
+ expect(volunteered.pages.map((p: { slug: string }) => p.slug)).toEqual(['people/alice-example']);
+ const card = await call('entity', { name: 'Alice Example' }, { remote: true, sourceId: 'default' });
+ expect(card.card.entity.slug).toBe('people/alice-example');
+ });
+ }
+
+ test('a private entity page falls back to the readable same-title page', async () => {
+ await seed('meetings/2026-10-01-alice-sync', 'conversation', 'Alice Example', 'Public transcript.');
+ await seed('people/alice-example', 'person', 'Alice Example', 'Private entity.', 'default', { visibility: 'private' });
+ expect(await pointers('about Alice Example')).toEqual([['default', 'meetings/2026-10-01-alice-sync']]);
+ });
+
+ test('an explicit exact slug beats an inferred entity type', async () => {
+ await seed('alice-example', 'note', 'Alice Example', 'Explicit page.');
+ await seed('people/alice-example', 'person', 'Alice Example', 'Entity.');
+ expect(await pointers('about Alice Example')).toEqual([['default', 'alice-example']]);
+ });
+
+ test('equal preferences pick the same page whatever the write order', async () => {
+ await seed('people/z-alice', 'person', 'Alice Example', 'Written first.');
+ await seed('people/a-alice', 'person', 'Alice Example', 'Written second.');
+ expect(await pointers('about Alice Example')).toEqual([['default', 'people/a-alice']]);
+ });
+
+ test('same-title pages in different sources are different entities and both stay', async () => {
+ await seed('meetings/2026-10-01-alice-sync', 'conversation', 'Alice Example', 'Default transcript.');
+ await seed('people/alice-example', 'person', 'Alice Example', 'Default person.');
+ await seed('people/alice-example', 'person', 'Alice Example', 'Wiki person.', 'wiki');
+ expect((await pointers('about Alice Example', { sourceIds: ['default', 'wiki'], maxPointers: 10 })).sort())
+ .toEqual([['default', 'people/alice-example'], ['wiki', 'people/alice-example']]);
+ });
+
+ test('a lone container in one source is not displaced by an entity in another source', async () => {
+ await seed('meetings/2026-10-01-alice-sync', 'conversation', 'Alice Example', 'Default transcript.');
+ await seed('people/alice-example', 'person', 'Alice Example', 'Wiki person.', 'wiki');
+ expect((await pointers('about Alice Example', { sourceIds: ['default', 'wiki'], maxPointers: 10 })).sort())
+ .toEqual([['default', 'meetings/2026-10-01-alice-sync'], ['wiki', 'people/alice-example']]);
+ });
+});