Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): a verb is read at the link's own position; a mention of a typed target adds no second edge

garrytan5baca3c4706f
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index db5899e1ae..fd5b949f29 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle re
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
src/core/minions/worker.ts 1773 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper)
src/commands/sources.ts 2031 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured)
-src/core/link-extraction.ts 2186 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note
+src/core/link-extraction.ts 2200 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge
src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 9a1623d713..be208cb1bb 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -94,10 +94,10 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
// the page is next edited; no fixed watermark can cover code that keeps
// running past it.
// 2026-10-02: hyphen-run basenames resolve (#5623); 2026-10-05: temporal edges derive dated evidence on extraction.
-// 2026-10-05T04: typed relation lines (core/line-grammar.ts) state their link's type; a per-edge verb that
+// 2026-10-05T03: typed relation lines (core/line-grammar.ts) state their link's type; a per-edge verb that
// belongs to another link in the window no longer types this one; "joined [X] as <role>" reads as works_at.
// Re-extract so existing pages pick these up.
-export const LINK_EXTRACTOR_VERSION_TS = '2026-10-05T04:00:00Z';
+export const LINK_EXTRACTOR_VERSION_TS = '2026-10-05T03:00:00Z';
// ─── Entity references ──────────────────────────────────────────
@@ -733,7 +733,7 @@ export async function extractPageLinks(
}
const suppressPrior = idx !== undefined && idx >= 0 && inSuppressedRange(suppressedRanges, idx);
const legacy = inferLinkType(pageType, ctx, suppressPrior ? undefined : content, targetSlug,
- opts.targetType ? targetType ?? null : undefined);
+ opts.targetType ? targetType ?? null : undefined, bodyReference && idx !== undefined && idx >= 0 ? excerptAnchor(content, idx, 240) : undefined);
if (pack?.link_types.some(lt => lt.name === legacy && (lt.inference?.page_type || lt.inference?.target_type))) return { linkType: 'mentions' };
return { linkType: legacy };
};
@@ -954,6 +954,13 @@ export async function extractPageLinks(
frontmatterAttendanceComplete = fm.attendanceComplete;
}
+ const result = dedupeCandidates(candidates);
+ return { candidates: result, unresolved: fmUnresolved,
+ attendanceComplete: [...attendancePending].every(index => attendanceResolved.has(index) && !attendanceAmbiguous.has(index))
+ && frontmatterAttendanceComplete };
+}
+
+function dedupeCandidates(candidates: LinkCandidate[]): LinkCandidate[] {
// Within-page dedup: same (fromSlug, targetSlug, linkType, linkSource)
// collapses to one entry. First occurrence wins.
// Issue #972 (codex P2d, decided): a qualified `[[companies/acme]]` (typed
@@ -962,17 +969,19 @@ export async function extractPageLinks(
// (link_source) and link_type, and the audit trail (which kind of reference
// created the edge) is worth more than collapsing them. graph-query callers
// that want a unique target set dedup on to_slug themselves.
+ // A mention of a target this page also links with a typed verb (same link
+ // source) adds nothing: the typed edge already states the relationship.
+ const edgeKey = (c: LinkCandidate) => `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkSource ?? ''}`;
+ const typed = new Set(candidates.filter(c => c.linkType !== 'mentions').map(edgeKey));
const seen = new Set<string>();
const result: LinkCandidate[] = [];
for (const c of candidates) {
const key = `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? ''}\u0000${c.canonicalAttendance ?? false}`;
- if (seen.has(key)) continue;
+ if (seen.has(key) || (c.linkType === 'mentions' && typed.has(edgeKey(c)))) continue;
seen.add(key);
result.push(c);
}
- return { candidates: result, unresolved: fmUnresolved,
- attendanceComplete: [...attendancePending].every(index => attendanceResolved.has(index) && !attendanceAmbiguous.has(index))
- && frontmatterAttendanceComplete };
+ return result;
}
export function resolvedLinkCandidate(candidate: LinkCandidate, originSlug: string, originSourceId: string,
@@ -1128,6 +1137,11 @@ export function hasAttendanceEvidence(ranges: ReadonlyArray<readonly [number, nu
* entire `extract --stale` run (#2011). `ensureWellFormed` replaces any orphaned
* half with U+FFFD before the slice escapes this function.
*/
+/** Where `idx` lands inside `excerpt(s, idx, width)`: the link's own position, not the first mention of its target. */
+function excerptAnchor(s: string, idx: number, width: number): number {
+ return s.slice(Math.max(0, idx - Math.floor(width / 2)), idx).replace(/\s+/g, ' ').trimStart().length;
+}
+
function excerpt(s: string, idx: number, width: number): string {
const half = Math.floor(width / 2);
const start = Math.max(0, idx - half);
@@ -1243,8 +1257,9 @@ const VERB_RULES: ReadonlyArray<readonly [RegExp, string]> = [
*/
const LINK_MARK_RE = /\]\(|\]\]|\[\[/;
const GLOBAL_VERB_RULES = VERB_RULES.map(([re, verb]) => [new RegExp(re.source, `${re.flags.replace('g', '')}g`), verb] as const);
-function attachedVerb(context: string, targetSlug?: string): string | null | undefined {
- const at = targetSlug ? context.indexOf(targetSlug) : -1;
+function attachedVerb(context: string, targetSlug?: string, anchor?: number): string | null | undefined {
+ const fromAnchor = targetSlug && anchor !== undefined ? context.indexOf(targetSlug, anchor) : -1;
+ const at = fromAnchor >= 0 ? fromAnchor : targetSlug ? context.indexOf(targetSlug) : -1;
if (at < 0) return undefined;
const open = context.lastIndexOf('[', at);
const linkStart = open >= 0 && at - open <= 120 ? (context[open - 1] === '[' ? open - 1 : open) : at;
@@ -1277,7 +1292,7 @@ function attachedVerb(context: string, targetSlug?: string): string | null | und
* lists portfolio companies without repeating the investment verb each time
* ("Her current board seats reflect her portfolio: [Co A], [Co B], [Co C]").
*/
-export function inferLinkType(pageType: PageType, context: string, globalContext?: string, targetSlug?: string, targetType?: string | null): string {
+export function inferLinkType(pageType: PageType, context: string, globalContext?: string, targetSlug?: string, targetType?: string | null, anchor?: number): string {
if (pageType === 'media') {
return 'mentions';
}
@@ -1293,7 +1308,7 @@ export function inferLinkType(pageType: PageType, context: string, globalContext
// Per-edge verb rules, precedence founded > invested_in > advises > works_at
// (then the Chinese rules), over the verbs that belong to this link: in
// "works at [A] and also advises [B]", A is works_at and B advises.
- const attached = attachedVerb(context, targetSlug);
+ const attached = attachedVerb(context, targetSlug, anchor);
if (attached) return attached;
if (attached === undefined) for (const [re, verb] of VERB_RULES) if (re.test(context)) return verb;
// Page-role prior: only fires for person -> company links. Concept pages
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index ff5a8d2f64..78013736b3 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -4573,7 +4573,7 @@
"kind": "variable",
"name": "LINK_EXTRACTOR_VERSION_TS",
"signature": [
- "\"2026-10-05T04:00:00Z\""
+ "\"2026-10-05T03:00:00Z\""
]
},
{
@@ -4749,7 +4749,7 @@
"kind": "function",
"name": "inferLinkType",
"signature": [
- "(pageType: PageType, context: string, globalContext?: string, targetSlug?: string, targetType?: string | null) => string"
+ "(pageType: PageType, context: string, globalContext?: string, targetSlug?: string, targetType?: string | null, anchor?: number) => string"
]
},
{
diff --git a/test/link-extraction-line-grammar.test.ts b/test/link-extraction-line-grammar.test.ts
index b1e88cc213..3709dff590 100644
--- a/test/link-extraction-line-grammar.test.ts
+++ b/test/link-extraction-line-grammar.test.ts
@@ -17,14 +17,19 @@ const pack = (verbs: string[]): LinkExtractionPack => ({ link_types: verbs.map(n
describe('typed relation lines', () => {
test('the stated type wins for the link on its line only', async () => {
- const content = 'Alice mentions [[companies/acme-example]] in passing.\n\n- works_at [[companies/acme-example]] (since 2024)\n- invested_in [[companies/widget-co]]';
+ const content = 'Alice mentions [[companies/beta-example]] in passing.\n\n- works_at [[companies/acme-example]] (since 2024)\n- invested_in [[companies/widget-co]]';
expect(await types(content)).toEqual([
- ['companies/acme-example', 'mentions'],
+ ['companies/beta-example', 'mentions'],
['companies/acme-example', 'works_at'],
['companies/widget-co', 'invested_in'],
]);
});
+ test('a mention of a target the page also links with a typed edge adds no second edge', async () => {
+ const content = 'Alice mentions [[companies/acme-example]] in passing.\n\n- works_at [[companies/acme-example]] (since 2024)';
+ expect(await types(content)).toEqual([['companies/acme-example', 'works_at']]);
+ });
+
test('a sentence line keeps inference', async () => {
expect(await types('- works_at [[companies/acme-example]] since 2024')).toEqual([['companies/acme-example', 'mentions']]);
});
diff --git a/test/link-type-attachment.test.ts b/test/link-type-attachment.test.ts
index 35bb0f3bc2..578380d491 100644
--- a/test/link-type-attachment.test.ts
+++ b/test/link-type-attachment.test.ts
@@ -31,3 +31,16 @@ test('a timeline line "Joined [X] as engineer" is works_at on a page whose prose
test('without a locatable link, plain precedence applies as before', () => {
expect(inferLinkType('person', 'works at Acme and advises Widget')).toBe('advises');
});
+
+test('the verb is read at this link, not at an earlier mention of the same target in the window', () => {
+ const body = [
+ 'Alice is CTO of [Acme](../companies/acme-example).',
+ '- **2025-03-01** | linkedin — Left [Acme](../companies/acme-example) to join [Widget](../companies/widget-co)',
+ '- **2025-03-02** | note — works at [Widget](../companies/widget-co)',
+ ].join('\n');
+ const at = body.lastIndexOf('[Widget]');
+ const window = body.slice(Math.max(0, at - 120), at + 120).replace(/\s+/g, ' ').trim();
+ const anchor = body.slice(Math.max(0, at - 120), at).replace(/\s+/g, ' ').trimStart().length;
+ expect(inferLinkType('person', window, undefined, 'companies/widget-co', undefined, anchor)).toBe('works_at');
+ expect(inferLinkType('person', window, undefined, 'companies/widget-co')).toBe('mentions');
+});