Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): read the page-role prior trigger outside machine-written sections (#7882)

garrytanb79fdda881ab
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index e91c29de2a..aa74c4194b 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -739,6 +739,7 @@ function makeTypeFor(content: string, pageType: PageType, opts: ExtractPageLinks
// `content` (stripCodeBlocks and the wikilink mask are length-preserving,
// so indices line up); idx < 0 / undefined keeps the old behavior.
const suppressedRanges = rolePriorSuppressedRanges(stripCodeBlocks(content));
+ const roleText = opts.roleText ?? roleTriggerText(content);
const attendanceRanges = attendanceEvidenceRanges(content);
const statedType = statedRelationTypes(content, { ...opts.lineGrammar, declaredVerbs: pack?.link_types.map(lt => lt.name) });
return (ctx, targetSlug, idx, sourceId, bodyReference = true) => {
@@ -772,7 +773,6 @@ function makeTypeFor(content: string, pageType: PageType, opts: ExtractPageLinks
return decide('mentions', { rule: 'page.meeting' });
}
const suppressPrior = idx !== undefined && idx >= 0 && inSuppressedRange(suppressedRanges, idx);
- const roleText = opts.roleText ?? content;
const trace = traceLinkType(pageType, ctx, suppressPrior ? undefined : roleText, targetSlug,
opts.targetType ? targetType ?? null : undefined, bodyReference && idx !== undefined && idx >= 0 ? excerptAnchor(content, idx, 240) : undefined, roleText, !!explain);
const { type, ...why } = trace;
@@ -1345,6 +1345,23 @@ export function rolePriorPhrases(text: string): Array<string | null> {
return [PARTNER_ROLE_RE, ADVISOR_ROLE_RE, EMPLOYEE_ROLE_RE].map(re => re.exec(text)?.[0] ?? null);
}
+/**
+ * The text the page-role priors read their trigger from (#7882): `text` without its machine-written sections
+ * (rolePriorSuppressedRanges), the sections whose links never receive the prior either. `open` are the headings
+ * still open before `text` (a segmented block, openHeadings), so a section that began in an earlier block still counts.
+ */
+export function roleTriggerText(text: string, open: ReadonlyArray<string | null | undefined> = []): string {
+ const head = open.filter(Boolean).map(h => `${h}\n`).join('');
+ let kept = '';
+ let at = 0;
+ for (const [start, end] of rolePriorSuppressedRanges(stripCodeBlocks(head + text))) {
+ if (end - head.length <= at) continue;
+ if (start - head.length > at) kept += `${text.slice(at, start - head.length)}\n`;
+ at = end - head.length;
+ }
+ return kept + text.slice(at);
+}
+
const EMPLOYEE_ROLE_RE = /\b(?:is an? (?:senior|staff|principal|lead|backend|frontend|full-?stack|ML|data|security|DevOps|platform)? ?engineer at|is an? (?:senior|staff|principal|lead)? ?(?:developer|designer|product manager|engineering manager|director|VP) (?:at|of)|holds? the (?:CTO|CEO|CFO|COO|CMO|CRO|VP) (?:role|position|seat|title) at|is the (?:CTO|CEO|CFO|COO|CMO|CRO) of|employee at|on the team at|works on .{0,30} at)\b/i;
diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.ts
index ff20742393..322f5fc889 100644
--- a/src/core/page-body/segment-derive.ts
+++ b/src/core/page-body/segment-derive.ts
@@ -25,8 +25,8 @@ import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';
import { SEGMENTER_VERSION } from './segmenter.ts';
import type { BodyRegion, ManifestRow } from './types.ts';
-/** Bump a kind's version to re-derive every page's rows of that kind once. fences 2: rows keep fence digests, not fence text. */
-export const SEGMENT_PIPELINE_VERSIONS = { links: 1, mentions: 1, timeline: 1, fences: 2 } as const satisfies Partial<Record<SegmentDerivationKind, number>>;
+/** Bump a kind's version to re-derive every page's rows of that kind once. fences 2: rows keep fence digests, not fence text. links 2: role phrases skip machine sections (#7882). */
+export const SEGMENT_PIPELINE_VERSIONS = { links: 2, mentions: 1, timeline: 1, fences: 2 } as const satisfies Partial<Record<SegmentDerivationKind, number>>;
export type UnpaidDerivationKind = keyof typeof SEGMENT_PIPELINE_VERSIONS;
/**
diff --git a/src/core/page-body/segment-links.ts b/src/core/page-body/segment-links.ts
index 08b7c0cda4..8490bd4e3f 100644
--- a/src/core/page-body/segment-links.ts
+++ b/src/core/page-body/segment-links.ts
@@ -18,7 +18,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import {
- candidateKey, dedupeCandidates, extractBodyLinks, frontmatterLinks, LINK_EXTRACTOR_VERSION_TS, rolePriorPhrases, stripCodeBlocks,
+ candidateKey, dedupeCandidates, extractBodyLinks, frontmatterLinks, LINK_EXTRACTOR_VERSION_TS, rolePriorPhrases, roleTriggerText, stripCodeBlocks,
type BodyLinkCandidate, type ExtractPageLinksOptions, type PageLinksResult, type SlugResolver,
} from '../link-extraction.ts';
import { canonicalJson } from '../belief/keys.ts';
@@ -118,13 +118,15 @@ export async function* bodyWindows(engine: BrainEngine, page: { id: number; slug
yield* cutter.flush();
}
-/** The page-role phrases of a segmented body (rolePriorPhrases over every block), as ExtractPageLinksOptions.roleText. */
+/** The page-role phrases of a segmented body (rolePriorPhrases over every block's roleTriggerText), as ExtractPageLinksOptions.roleText. */
export async function segmentedRoleText(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },
opts: BodyBlockOptions = {}): Promise<string> {
const found: Array<string | null> = [null, null, null];
+ const open: string[] = [];
for await (const block of bodyBlocks(engine, page, opts)) {
- rolePriorPhrases(block.text).forEach((phrase, i) => { found[i] ??= phrase; });
+ rolePriorPhrases(roleTriggerText(block.text, open)).forEach((phrase, i) => { found[i] ??= phrase; });
if (found.every(Boolean)) break;
+ openHeadings(block.text, open);
}
return found.filter(Boolean).join('\n');
}
@@ -271,7 +273,7 @@ export async function openSegmentedLinkSession(engine: BrainEngine, page: Segmen
const r = run && reading;
if (r) {
r.info.chars += block.text.length;
- rolePriorPhrases(block.text).forEach((phrase, i) => { r.info.roles[i] ??= phrase === null ? null : detachedValue(phrase); });
+ rolePriorPhrases(roleTriggerText(block.text, open)).forEach((phrase, i) => { r.info.roles[i] ??= phrase === null ? null : detachedValue(phrase); });
if (r.head.length < CONTEXT_CHARS) r.head += block.text.slice(0, CONTEXT_CHARS - r.head.length);
r.tail.push(block.text);
r.tailChars += block.text.length;
diff --git a/test/link-role-prior-trigger-7882.test.ts b/test/link-role-prior-trigger-7882.test.ts
new file mode 100644
index 0000000000..8220fbc0da
--- /dev/null
+++ b/test/link-role-prior-trigger-7882.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #7882: the page-role prior reads its trigger phrase only from text outside the machine-written sections
+ * (rolePriorSuppressedRanges), the same sections whose links #4977 keeps away from the prior.
+ *
+ * 1. Protects: a "portfolio" written only in ## Facts or ## Timeline leaves a person page's bare company link a
+ * \`mentions\`; the same word in a prose section still types it \`invested_in\`. The segmented full pass, its role text
+ * and the incremental session agree with the inline answer, including a Facts section that spans a segment cut.
+ * 2. Fails when: the prior tests the whole page text (inline) or every block's text (segmented) again.
+ * 3. Why existing coverage misses it: the #4977 tests put the link inside the machine section, not the trigger.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractPageLinks, makeResolver, type SlugResolver } from '../src/core/link-extraction.ts';
+import { extractSegmentedPageLinks, openSegmentedLinkSession, segmentedRoleText } from '../src/core/page-body/segment-links.ts';
+import { SEGMENT_MAX_BYTES } from '../src/core/page-body/limits.ts';
+import { createSegmentedPage } from './helpers/segmented-page.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const SLUG = 'people/alice-example';
+const TARGET = 'companies/acme-cafe';
+const resolver: SlugResolver = { resolve: async () => null } as never;
+const targetType = (s: string) => (s.startsWith('companies/') ? 'company' : 'concept');
+const dining = '# Alice Example\n\n## Dining\n\n- Alice likes the pasta at [[companies/acme-cafe]].\n';
+const variants: Record<string, [string, string]> = {
+ A: [dining, 'mentions'],
+ B: [dining + '\n## Facts\n\n- Alice reviews her portfolio every Sunday.\n', 'mentions'],
+ C: [dining + '\n## Timeline\n\n- **2026-01-02** | Portfolio review completed.\n', 'mentions'],
+ D: [dining + '\n## Money\n\n- Alice keeps a small index-fund portfolio.\n', 'invested_in'],
+};
+
+const typesOf = (candidates: Array<{ targetSlug: string; linkType: string }>) =>
+ candidates.filter(c => c.targetSlug === TARGET).map(c => c.linkType).join(',');
+
+describe('#7882 role-prior trigger outside machine sections (inline)', () => {
+ for (const [name, [body, expected]] of Object.entries(variants)) {
+ test('variant ' + name + ' types the company link ' + expected, async () => {
+ const r = await extractPageLinks(SLUG, body, {}, 'person', resolver, { targetType });
+ expect(typesOf(r.candidates)).toBe(expected);
+ });
+ }
+
+ test('a heading nested under ## Facts stays suppressed; the next prose section reads again', async () => {
+ const nested = dining + '\n## Facts\n\n### Money\n\n- Alice reviews her portfolio.\n';
+ expect(typesOf((await extractPageLinks(SLUG, nested, {}, 'person', resolver, { targetType })).candidates)).toBe('mentions');
+ const after = dining + '\n## Facts\n\n- n/a\n\n## Work\n\n- Alice is a seed investor.\n';
+ expect(typesOf((await extractPageLinks(SLUG, after, {}, 'person', resolver, { targetType })).candidates)).toBe('invested_in');
+ });
+});
+
+describe('#7882 role-prior trigger outside machine sections (segmented)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ });
+
+ // The Facts section opens in the first segment and its trigger sits past the cut, in the second.
+ const filler = Array.from({ length: Math.ceil(SEGMENT_MAX_BYTES / 36) }, (_, i) => '- fact row ' + i + ' about weekly routines\n').join('');
+ const pages: Record<string, [string, string]> = {
+ facts: [dining + '\n## Facts\n\n' + filler + '- Alice reviews her portfolio every Sunday.\n', 'mentions'],
+ prose: [dining + '\n## Facts\n\n' + filler + '\n## Money\n\n- Alice keeps a small index-fund portfolio.\n', 'invested_in'],
+ };
+
+ for (const [name, [truth, expected]] of Object.entries(pages)) {
+ test('a ' + name + ' trigger past a segment cut types the link ' + expected + ', as inline', async () => {
+ const { id } = await createSegmentedPage(engine, { slug: SLUG, truth, meta: { type: 'person' } });
+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [id]);
+ expect(row!.n).toBeGreaterThan(1);
+ const page = { id, slug: SLUG, source_id: 'default', type: 'person' as const, frontmatter: {} };
+ const live = makeResolver(engine, { mode: 'live', sourceId: 'default' });
+ const inline = await extractPageLinks(SLUG, truth + '\n', {}, 'person', live, { targetType });
+ expect(typesOf(inline.candidates)).toBe(expected);
+ const roleText = await segmentedRoleText(engine, page);
+ expect(/portfolio/i.test(roleText)).toBe(expected === 'invested_in');
+ expect(typesOf((await extractSegmentedPageLinks(engine, page, live, { targetType })).candidates)).toBe(expected);
+ const session = await openSegmentedLinkSession(engine, page, live, {});
+ expect(session).not.toBeNull();
+ await session!.targets({});
+ expect(typesOf((await session!.finish({ temporal: true, targetType } as never)).candidates)).toBe(expected);
+ });
+ }
+});