Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(writer): link validator resolves relative links with the extractor's resolver (#6266)
time-attackbda9e49d2597
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex dab22b8667..70f2ab4722 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -104,7 +104,7 @@ rejection of serve-only flags before a brain opens.- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.-- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 falls back to `resolveSlugWithAlias` (rename aliases) for a slug-shaped value with no live page; its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). With `link_resolution.global_basename` on, `extractFrontmatterLinks` passes `resolve(name, dirHint, { globalBasename, selfSlug })`, and a unique basename match (self excluded) resolves right after the exact steps and before the fuzzy and live keyword steps, the exact-name-first precedence of `resolveEntitySlug` (#5749, `test/link-resolution-basename-before-search.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`. #6191: `inferLinkType` applies `link-target-roles.ts` `targetTakesVerb` to every per-edge and fallback verb: `works_at` never types a link to a person, meeting, calendar-event, media, image or transcript target (unknown type: a `people/`, `meetings/`, `calendar/`, `cal/` slug), `founded`/`invested_in` never a temporal or media one; a refused verb keeps scanning lower-precedence rules, then `mentions` (`test/link-type-target-guard.test.ts`).+- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `resolveMarkdownLinkSlug` (one markdown href resolved from a page exactly as `extractPageLinks` resolves it; the writer's link validator, `src/core/output/validators/link.ts`, uses it so its dangling-link verdict matches the graph), `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. In `inferLinkType` a per-edge verb counts only when it belongs to the link being typed (`attachedVerb`: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; `joined [X] as <role>` reads as works_at. `attendanceEvidenceRanges` accepts an `Attendees:`/`Participants:` line (plain or bold) and a `## Attendees`/`## Participants` link-list section (`Participants` since gbrain-evals N12-6, with a `LINK_EXTRACTOR_VERSION_TS` bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver` step 1 falls back to `resolveSlugWithAlias` (rename aliases) for a slug-shaped value with no live page; its fuzzy title step and live keyword step (source-scoped) accept a person/company/fund/organization candidate only under `sameEntityName`, so a near-name stays unresolved instead of linking to a different entity (`test/entity-resolution-near-names.test.ts`). With `link_resolution.global_basename` on, `extractFrontmatterLinks` passes `resolve(name, dirHint, { globalBasename, selfSlug })`, and a unique basename match (self excluded) resolves right after the exact steps and before the fuzzy and live keyword steps, the exact-name-first precedence of `resolveEntitySlug` (#5749, `test/link-resolution-basename-before-search.test.ts`). `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter`. All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`. #6191: `inferLinkType` applies `link-target-roles.ts` `targetTakesVerb` to every per-edge and fallback verb: `works_at` never types a link to a person, meeting, calendar-event, media, image or transcript target (unknown type: a `people/`, `meetings/`, `calendar/`, `cal/` slug), `founded`/`invested_in` never a temporal or media one; a refused verb keeps scanning lower-precedence rules, then `mentions` (`test/link-type-target-guard.test.ts`).- `src/core/timeline-dedup-repair.ts` — schema-drift self-heal for `idx_timeline_dedup`. A master-merge migration renumbering can leave a brain's version counter stamped past the index change while the index keeps an old shape — and every `addTimelineEntry` batch then fails its `ON CONFLICT` inference, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE. Canonical shape is `(page_id, date, md5(summary), source)` — md5-keyed (migration v138) because a raw long/incompressible summary would overflow the btree v4 row cap (~2704 bytes) and abort every timeline insert for that page; both engines' insert sites infer `ON CONFLICT` on the md5 tuple, so `EXPECTED_COLUMNS` MUST carry the md5 form (a raw-shape expectation would make the repair revert v138 on every migrate pass). `checkTimelineDedupIndex(engine)` returns `{tablePresent, indexPresent, columns, needsRepair}` (read-only; powers the `timeline_dedup_index` doctor check; the indexdef column parser is paren-depth-aware so `md5(summary)` — or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) and `repairTimelineDedupIndex(engine)` dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions). `runMigrations` invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches. `gbrain apply-migrations --force-schema` triggers it on demand. Pinned by `test/timeline-dedup-repair.test.ts`.diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex df6790da80..82b45a1155 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -583,6 +583,38 @@ function resolveRelativeSlug(pageSlug: string, ref: EntityRef): string {return [...dirSegs.slice(0, keep), ref.slug].join('/');}+/**+ * A same-directory markdown ref (`sameDir`) resolved against the linking+ * page's directory: `../` / `./../` prefixes (upLevels) and any mid-path+ * `.`/`..` fold the way the FS walker's join() does, slugified through the+ * sync grammar. A run that would climb above the root is a dangling link+ * there too, so it resolves to '' (no candidate).+ */+function resolveSameDirSlug(pageSlug: string, ref: EntityRef): string {+ const segs = pageSlug.includes('/') ? pageSlug.split('/').slice(0, -1) : [];+ for (const seg of ('../'.repeat(ref.upLevels ?? 0) + ref.slug).split('/')) {+ if (seg === '' || seg === '.') continue;+ if (seg !== '..') { segs.push(seg); continue; }+ if (segs.length === 0) return '';+ segs.pop();+ }+ return slugifyPath(segs.join('/'));+}++/**+ * The page slug a markdown link `href` on page `pageSlug` points at, resolved+ * exactly as extractPageLinks resolves it (page-relative `./` and `../`,+ * root-relative dir paths, `.md` and `#anchor` stripped). Null when the+ * extractor would emit no link for it. The writer's link validator calls+ * this, so "the validator accepts it" means "the graph links it".+ */+export function resolveMarkdownLinkSlug(pageSlug: string, href: string): string | null {+ const ref = extractEntityRefs(`[link](${href})`)[0];+ if (!ref) return null;+ const target = ref.sameDir ? resolveSameDirSlug(pageSlug, ref) : resolveRelativeSlug(pageSlug, ref).toLowerCase();+ return target || null;+}+// ─── Link candidates (richer than EntityRef) ────────────────────export interface LinkCandidate {@@ -782,18 +814,7 @@ export async function extractPageLinks(// `[Alice](Alice%20Chen.md)` reaches `people/alice-chen`. Downstream// existence checks drop targets that aren't pages.if (ref.sameDir) {- const segs = slug.includes('/') ? slug.split('/').slice(0, -1) : [];- // `../` / `./../` prefixes (upLevels) and any mid-path `.`/`..` fold- // the way the FS walker's join() does; a run that would climb above- // the root is a dangling link there too, so it yields no candidate.- let climbed = false;- for (const seg of ('../'.repeat(ref.upLevels ?? 0) + ref.slug).split('/')) {- if (seg === '' || seg === '.') continue;- if (seg !== '..') { segs.push(seg); continue; }- if (segs.length === 0) { climbed = true; break; }- segs.pop();- }- const target = climbed ? '' : slugifyPath(segs.join('/'));+ const target = resolveSameDirSlug(slug, ref);if (target && target !== slug) {const idx = ref.index ?? content.indexOf(ref.name);const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;diff --git a/src/core/output/validators/link.ts b/src/core/output/validators/link.tsindex 17cf2e1f52..2ea515b66a 100644--- a/src/core/output/validators/link.ts+++ b/src/core/output/validators/link.ts@@ -9,11 +9,13 @@* Dangling links emit an error.* - Anything else (mailto:, internal anchors) → warning.*- * We strip leading "../" components so a link from a daily file written as- * `../../people/alice.md` resolves to the `people/alice` slug the engine- * knows. This matches how engine.addLink is called downstream.+ * Relative links resolve against the linking page's directory through the+ * link extractor's own resolver (resolveMarkdownLinkSlug), so a link this+ * validator accepts is a link the graph records, and a wrong-depth link is+ * reported with the slug it actually resolves to.*/+import { resolveMarkdownLinkSlug } from '../../link-extraction.ts';import type { PageValidator, PageValidationContext, ValidationFinding } from '../writer.ts';const MD_LINK_RE = /\[([^\]]+)\]\(([^)]+)\)/g;@@ -44,7 +46,7 @@ export const linkValidator: PageValidator = {continue;}- const slug = normalizeToSlug(href);+ const slug = resolveMarkdownLinkSlug(ctx.slug, href.trim());if (!slug) {findings.push({slug: ctx.slug,@@ -78,7 +80,9 @@ export const linkValidator: PageValidator = {validator: 'link',severity: 'error',line: pos.line,- message: `Dangling wikilink to ${slug} (no such page)`,+ message: pos.raw.trim().replace(/\.md$/i, '').toLowerCase() === slug+ ? `Dangling wikilink to ${slug} (no such page)`+ : `Dangling wikilink to ${slug} (no such page; ${truncate(pos.raw, 80)} from ${ctx.slug} resolves there)`,});}}diff --git a/test/writer.test.ts b/test/writer.test.tsindex 8dc143fdee..2358538640 100644--- a/test/writer.test.ts+++ b/test/writer.test.ts@@ -588,6 +588,28 @@ describe('link validator', () => {expect(findings.some(f => f.severity === 'warning')).toBe(true);});+ test('#6266: links resolve against the linking page directory, exactly like the extractor', async () => {+ const put = (slug: string) => engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: 'x', frontmatter: {} });+ await put('wiki/concepts/x');+ await put('wiki/sources/sibling');+ await put('people/alice');+ const check = (slug: string, compiledTruth: string) =>+ linkValidator.validate({ slug, type: 'concept', compiledTruth, timeline: '', frontmatter: {}, engine });++ // A correct nested link: no finding (master strips ../ and looks up concepts/x).+ expect(await check('wiki/sources/foo', 'See [x](../concepts/x.md).')).toEqual([]);+ // Wrong depth: master accepts it; the extractor resolves it to concepts/x, which doesn't exist.+ const wrong = await check('wiki/sources/foo', 'See [x](../../concepts/x.md) and [y](../../wiki/concepts/x.md).');+ expect(wrong).toHaveLength(1);+ expect(wrong[0]!.severity).toBe('error');+ expect(wrong[0]!.message).toContain('Dangling wikilink to concepts/x');+ expect(wrong[0]!.message).toContain('../../concepts/x.md');+ // A ./ sibling resolves in the page's own directory.+ expect(await check('wiki/sources/foo', 'See [s](./sibling.md).')).toEqual([]);+ // Flat brain: one level down, ../ lands at the root.+ expect(await check('meetings/m', 'Met [Alice](../people/alice.md).')).toEqual([]);+ });+test('ignores links inside fenced code', async () => {const compiled = '```\n[link](../people/not-real.md)\n```';const findings = await linkValidator.validate({