Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): resolve child-directory .md links page-relative on the DB path, root-relative fallback (#6983)

garrytana7e1d891ca8c
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 70e4192579..57f9a7f49d 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -103,7 +103,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`, and the rewrite guard (#6385 R12) `assertFenceRewritable` / `FenceRewriteRefusal` that `upsertFactRow`, `upsertTakeRow`, `supersedeRow` and `mergePhantomFenceRows` throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). `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. `escapeFenceCell` also encodes fence-marker text (`gbrain:facts:begin` and the three siblings) by lengthening the ampersand run before `#58;` (`gbrain:X` → `gbrain:X`, a literal `gbrain:X` → `gbrain:X`), and `decodeFenceCell` (the decoder `parseRowCells` and `fence-repair/raw-rows.ts` share) removes exactly one level, so a claim that quotes a marker never becomes a live marker and a literal entity round-trips byte-identically; the lexical fail-closed privacy rule is unchanged. 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`, `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 and the FS resolver try `exactSlugCandidates` (`exact-slug-candidates.ts`: the value, then `slugifyPath`), then `resolveSlugWithAlias` (rename aliases); 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; a `.md` dir link with no `/`/`./`/`../` prefix first tries `pageRelativeMarkdownSlugs`, the page's directory then its ancestors like the FS walker's `resolveSlug`, and the first existing page wins, #6983), `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 and the FS resolver try `exactSlugCandidates` (`exact-slug-candidates.ts`: the value, then `slugifyPath`), then `resolveSlugWithAlias` (rename aliases); 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.ts
index e91c29de2a..2ccc9f0512 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -615,12 +615,42 @@ function resolveSameDirSlug(pageSlug: string, ref: EntityRef): string {
return slugifyPath(segs.join('/'));
}
+/**
+ * #6983: page-relative slugs for a `.md` markdown link with a directory
+ * segment and no `/`, `./` or `../` prefix (`[x](notes/a.md)`), in the FS
+ * walker's resolveSlug order: the linking page's directory, then each
+ * ancestor, stopping before the root. The first one that is a page wins; the
+ * root-relative slug resolveMarkdownLinkSlug returns is the fallback, so
+ * wiki-root-relative authoring keeps resolving. Engine-slug links (no `.md`)
+ * stay root-relative. Empty for a root-level page or any other link shape.
+ */
+export function pageRelativeMarkdownSlugs(pageSlug: string, href: string): string[] {
+ const target = href.trim().replace(/#.*$/, '');
+ if (!/\.md$/i.test(target) || /^[./]/.test(target)) return [];
+ const ref = extractEntityRefs(`[link](${href.trim()})`)[0];
+ if (!ref || ref.sameDir || ref.upLevels) return [];
+ const dirs = pageSlug.split('/').slice(0, -1);
+ const slugs: string[] = [];
+ for (let keep = dirs.length; keep > 0; keep--) slugs.push(`${dirs.slice(0, keep).join('/')}/${ref.slug}`.toLowerCase());
+ return slugs;
+}
+
+/** The raw href of the pass-1 markdown link starting at `index` in `content`. */
+function markdownHrefAt(content: string, index: number): string | null {
+ const re = new RegExp(ENTITY_REF_RE.source, 'y');
+ re.lastIndex = index;
+ const match = re.exec(content);
+ return match ? match[0].slice(match[0].indexOf('](') + 2, -1) : null;
+}
+
/**
* 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".
+ * extractor would emit no link for it. A `.md` dir link first tries
+ * pageRelativeMarkdownSlugs, which needs page existence; this is its
+ * fallback. The writer's link validator calls both, 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];
@@ -991,7 +1021,15 @@ export async function extractBodyLinks(slug: string, content: string, pageType:
// refs) — validateSlug stores every slug lowercase on both engines, so a
// mixed-case candidate could never resolve. NOT slugifyPath: it strips
// characters validateSlug permits and would mangle a legit put_page slug.
- const targetSlug = resolveRelativeSlug(slug, ref).toLowerCase();
+ let targetSlug = resolveRelativeSlug(slug, ref).toLowerCase();
+ // #6983: a `.md` dir link resolves against this page's directory first,
+ // like the FS walker; the root-relative slug stays the fallback.
+ const href = refPass === 0 && resolver.resolveBasenameMatches ? markdownHrefAt(content, idx) : null;
+ const pageRelative = href ? pageRelativeMarkdownSlugs(slug, href) : [];
+ if (pageRelative.length > 0) {
+ const existing = new Set(await resolver.resolveBasenameMatches!(ref.slug.slice(ref.slug.lastIndexOf('/') + 1)));
+ targetSlug = pageRelative.find(s => existing.has(s)) ?? targetSlug;
+ }
candidates.push({
targetSlug,
targetSourceId: ref.sourceId ?? undefined,
diff --git a/src/core/output/validators/link.ts b/src/core/output/validators/link.ts
index 2ea515b66a..2e98ed8f35 100644
--- a/src/core/output/validators/link.ts
+++ b/src/core/output/validators/link.ts
@@ -10,12 +10,13 @@
* - Anything else (mailto:, internal anchors) → warning.
*
* Relative links resolve against the linking page's directory through the
- * link extractor's own resolver (resolveMarkdownLinkSlug), so a link this
+ * link extractor's own resolvers (pageRelativeMarkdownSlugs, then
+ * 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 { pageRelativeMarkdownSlugs, resolveMarkdownLinkSlug } from '../../link-extraction.ts';
import type { PageValidator, PageValidationContext, ValidationFinding } from '../writer.ts';
const MD_LINK_RE = /\[([^\]]+)\]\(([^)]+)\)/g;
@@ -27,6 +28,12 @@ export const linkValidator: PageValidator = {
const findings: ValidationFinding[] = [];
const body = `${ctx.compiledTruth}\n${ctx.timeline}`;
+ const sourceOpts = ctx.sourceIds && ctx.sourceIds.length > 0
+ ? { sourceIds: ctx.sourceIds }
+ : ctx.sourceId
+ ? { sourceId: ctx.sourceId }
+ : undefined;
+
// Collect unique internal targets first to batch engine lookups.
const internalTargets = new Set<string>();
const linkPositions = new Map<string, { display: string; raw: string; line: number }[]>();
@@ -46,7 +53,10 @@ export const linkValidator: PageValidator = {
continue;
}
- const slug = resolveMarkdownLinkSlug(ctx.slug, href.trim());
+ let slug = resolveMarkdownLinkSlug(ctx.slug, href.trim());
+ for (const candidate of pageRelativeMarkdownSlugs(ctx.slug, href)) {
+ if (await ctx.engine.getPage(candidate, sourceOpts)) { slug = candidate; break; }
+ }
if (!slug) {
findings.push({
slug: ctx.slug,
@@ -65,11 +75,6 @@ export const linkValidator: PageValidator = {
}
// Batch-check which targets exist within the validation read scope.
- const sourceOpts = ctx.sourceIds && ctx.sourceIds.length > 0
- ? { sourceIds: ctx.sourceIds }
- : ctx.sourceId
- ? { sourceId: ctx.sourceId }
- : undefined;
for (const slug of internalTargets) {
const page = await ctx.engine.getPage(slug, sourceOpts);
if (page) continue;
diff --git a/test/link-extraction-child-dir-6983.test.ts b/test/link-extraction-child-dir-6983.test.ts
new file mode 100644
index 0000000000..b324e8f7c0
--- /dev/null
+++ b/test/link-extraction-child-dir-6983.test.ts
@@ -0,0 +1,104 @@
+/**
+ * #6983: a `.md` markdown link with a directory segment and no `/`, `./` or
+ * `../` prefix (`[First](notes/008-first.md)` on `library-a/collection/index`)
+ * resolves against the linking page's directory, the way the FS walker
+ * (resolveSlug) and CommonMark readers do. Before the fix the DB path
+ * (`extract links --source db`, backfill_links, put_page auto-link) resolved
+ * it root-relative to `notes/008-first`, which is not a page, so the edge was
+ * dropped while `--source fs` kept it. Root-relative stays the fallback when
+ * no page-relative page exists, so wiki-root-relative authoring still links.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { extractPageLinks, makeResolver, pageRelativeMarkdownSlugs } from '../src/core/link-extraction.ts';
+import { extractLinksFromFile } from '../src/commands/extract.ts';
+import { linkValidator } from '../src/core/output/validators/link.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const PAGES = [
+ 'library-a/collection/index',
+ 'library-a/collection/notes/008-first',
+ 'people/alice-example',
+ 'wiki/concepts/x',
+ 'wiki/a/page',
+ 'meetings/2026/m1',
+];
+
+async function seed(): Promise<Set<string>> {
+ for (const slug of PAGES) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'x', frontmatter: {} });
+ }
+ return new Set(PAGES);
+}
+
+const CASES: Array<{ page: string; body: string; expected: string }> = [
+ { page: 'library-a/collection/index', body: '- [First note](notes/008-first.md)', expected: 'library-a/collection/notes/008-first' },
+ { page: 'meetings/2026/m1', body: 'Met [Alice](people/alice-example.md).', expected: 'people/alice-example' },
+ { page: 'wiki/a/page', body: 'See [X](concepts/x.md).', expected: 'wiki/concepts/x' },
+];
+
+async function dbTargets(page: string, body: string): Promise<string[]> {
+ const resolver = makeResolver(engine, { mode: 'batch', sourceId: 'default' });
+ const { candidates } = await extractPageLinks(page, body, {}, 'note', resolver, { skipFrontmatter: true });
+ return candidates.map(c => c.targetSlug);
+}
+
+describe('#6983 child-directory markdown links', () => {
+ test('DB mode resolves a child-directory .md link against the page directory', async () => {
+ await seed();
+ const targets = await dbTargets(CASES[0].page, CASES[0].body);
+ expect(targets).toContain('library-a/collection/notes/008-first');
+ expect(targets).not.toContain('notes/008-first');
+ });
+
+ test('DB mode falls back to an ancestor, then root-relative, when the page-relative slug is not a page', async () => {
+ await seed();
+ expect(await dbTargets(CASES[1].page, CASES[1].body)).toContain('people/alice-example');
+ expect(await dbTargets(CASES[2].page, CASES[2].body)).toContain('wiki/concepts/x');
+ });
+
+ test('FS and DB modes resolve every case to the same target', async () => {
+ const allSlugs = await seed();
+ for (const { page, body, expected } of CASES) {
+ const fs = (await extractLinksFromFile(body, `${page}.md`, allSlugs)).map(l => l.to_slug);
+ const db = (await dbTargets(page, body)).filter(t => allSlugs.has(t));
+ expect(fs).toEqual([expected]);
+ expect(db).toEqual([expected]);
+ }
+ });
+
+ test('engine-slug links (no .md) and prefixed links keep their resolution', () => {
+ expect(pageRelativeMarkdownSlugs('library-a/collection/index', 'notes/008-first')).toEqual([]);
+ expect(pageRelativeMarkdownSlugs('library-a/collection/index', '/notes/008-first.md')).toEqual([]);
+ expect(pageRelativeMarkdownSlugs('library-a/collection/index', '../notes/008-first.md')).toEqual([]);
+ expect(pageRelativeMarkdownSlugs('index', 'notes/008-first.md')).toEqual([]);
+ expect(pageRelativeMarkdownSlugs('library-a/collection/index', 'notes/008-first.md#top'))
+ .toEqual(['library-a/collection/notes/008-first', 'library-a/notes/008-first']);
+ });
+
+ test('the link validator accepts the child-directory link the graph records', async () => {
+ await seed();
+ const findings = await linkValidator.validate({
+ slug: 'library-a/collection/index', type: 'note', frontmatter: {}, engine,
+ compiledTruth: CASES[0].body, timeline: '',
+ });
+ expect(findings).toEqual([]);
+ });
+});