Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): resolve wiki-links to dotted filenames (PRD-7770) (#3430)
Andrew Mikofalvyd28a6ce5574f
diff --git a/.changeset/wikilink-dotted-filename-resolution.md b/.changeset/wikilink-dotted-filename-resolution.mdnew file mode 100644index 000000000..947ae0e24--- /dev/null+++ b/.changeset/wikilink-dotted-filename-resolution.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Wiki-links to notes whose filename contains a dot now open the note. Previously `[[acp.daemon]]` read the text after the dot as a file extension, so the link was treated as a file rather than a document and opened a viewer for a file type that doesn't exist, ending in a 404 — even when the note sat in the same folder. Namespaced and versioned names like `acp.daemon` or `v1.2 release` are common in imported vaults, so this met people on their first click.++The Problems panel and `links({ kind: "dead" })` now agree with what the editor actually opens. A link that resolves by bare name is no longer reported broken, and a wiki-link that genuinely cannot be resolved is no longer silently omitted from the report — previously the two were inverted, flagging working links while staying quiet about broken ones. Write-time `brokenLinks` uses the same resolution, so it can only ever retract a report, never add one. Links naming a real asset, and wiki-embeds, behave exactly as before.++Two documents in different folders that share a filename now always resolve to the same one of them, in the editor and in the dead-link report alike. The tie-break no longer depends on the machine's locale, so a name can no longer resolve to different documents on different computers.++Note: the extension-qualified form `[[acp.daemon.md]]` still does not resolve — it fails for a separate reason and is not covered by this change.diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex bdcaa266e..90922a88d 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -182,8 +182,9 @@ function slugResolve(/*** Bare-name basename fallback. When the target has no path separator,* look up its slug against the basename-keyed index so `[[analysis]]`- * resolves to `andrew-data/project-x/analysis`. Alphabetical-first on- * basename collision is baked into the index build. Targets containing+ * resolves to `andrew-data/project-x/analysis`. The tie-break on basename+ * collision is baked into the index build, so this resolver and the chip's+ * resolver cannot disagree about the winner. Targets containing* `/` skip this branch — a typed path that doesn't exact-match must* not silently rewrite to a same-leaf file in a different folder.*/diff --git a/packages/app/src/components/wiki-link-ordering-contract.test.ts b/packages/app/src/components/wiki-link-ordering-contract.test.tsnew file mode 100644index 000000000..2783c136a--- /dev/null+++ b/packages/app/src/components/wiki-link-ordering-contract.test.ts@@ -0,0 +1,101 @@+import {+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ resolveWikiLinkTargetDocName,+ toWikiLinkSlug,+ type WikiLinkLookupIndex,+} from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { docNameForNavigationTarget, resolveNavigationTarget } from './navigation-targets';++/**+ * Two resolvers answer "which document does this bare name mean": the shared+ * one the server and the chip's resolved-state read, and the navigation+ * resolver the click destination reads. They are deliberately separate — the+ * navigation resolver carries managed-artifact and editable-text branches that+ * cannot move into the shared package — so nothing in the type system stops+ * them drifting apart on WHICH document wins.+ *+ * That drift is the defect this file exists to catch: a bare name resolving one+ * way for navigation and another way for the dead-link verdict is how a link+ * gets reported broken while the reader clicks it and arrives.+ *+ * The contract is a single ordering, and it is enforced structurally — the+ * tie-break happens once, when the basename index is built, so both resolvers+ * consume the same already-decided winner. These tests pin that the two agree+ * AND that the ordering is the runtime-independent one.+ */++function lookupFor(pages: ReadonlySet<string>): WikiLinkLookupIndex {+ return {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+}++/** Resolve through the navigation path the way a click does. */+function viaNavigation(target: string, pages: ReadonlySet<string>): string | null {+ const lookup = lookupFor(pages);+ return docNameForNavigationTarget(+ resolveNavigationTarget(target, {+ pages,+ pagesBySlug: lookup.pagesBySlug,+ pagesByBasename: lookup.pagesByBasename,+ }),+ );+}++/** Resolve through the shared path the dead-link verdict reads. */+function viaShared(target: string, pages: ReadonlySet<string>): string | undefined {+ return resolveWikiLinkTargetDocName(target, lookupFor(pages));+}++describe('bare-name resolution ordering contract', () => {+ test('both resolvers name the same document when a basename collides across folders', () => {+ const pages = new Set(['research/analysis', 'archive/analysis']);++ const navigation = viaNavigation('analysis', pages);+ const shared = viaShared('analysis', pages);++ expect(shared).toBeDefined();+ expect(navigation).toBe(shared);+ });++ test('the winner is code-unit ordered, not locale ordered', () => {+ // 'B' (0x42) sorts before 'a' (0x61) by code unit, but after it under a+ // locale-aware collation. This fixture is the one that tells those two+ // apart, so it fails if the pinned comparator is ever swapped back to+ // `localeCompare` — the state in which two runtimes could disagree.+ const pages = new Set(['B/notes', 'a/notes']);++ expect(viaShared('notes', pages)).toBe('B/notes');+ expect(viaNavigation('notes', pages)).toBe('B/notes');+ });++ test('a dotted basename resolves identically through both resolvers', () => {+ // The reported defect: a dot in the filename used to divert this target+ // into asset classification before either resolver saw it.+ const pages = new Set(['Memory/ACP/entities/acp.daemon', 'sub/plain']);++ expect(viaShared('acp.daemon', pages)).toBe('Memory/ACP/entities/acp.daemon');+ expect(viaNavigation('acp.daemon', pages)).toBe('Memory/ACP/entities/acp.daemon');+ });++ test('the dot-free control resolves identically through both resolvers', () => {+ const pages = new Set(['Memory/ACP/entities/acp.daemon', 'sub/plain']);++ expect(viaShared('plain', pages)).toBe('sub/plain');+ expect(viaNavigation('plain', pages)).toBe('sub/plain');+ });++ test('ordering is stable no matter what order the corpus is enumerated in', () => {+ // Set iteration order follows insertion, so a corpus discovered in a+ // different order must not produce a different winner.+ const forward = new Set(['B/notes', 'a/notes']);+ const reversed = new Set(['a/notes', 'B/notes']);++ expect(viaShared('notes', forward)).toBe(viaShared('notes', reversed));+ expect(viaNavigation('notes', forward)).toBe(viaNavigation('notes', reversed));+ });+});diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.destination.dom.test.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.destination.dom.test.tsxnew file mode 100644index 000000000..2f0d36f0b--- /dev/null+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.destination.dom.test.tsx@@ -0,0 +1,113 @@+/**+ * What destination the wiki-link prop panel reports, and how it labels it.+ *+ * The panel and the chip must agree: whatever the chip navigates to on click is+ * what the panel's destination link points at. They resolve independently, so a+ * document whose filename carries a dot (`notes/acp.daemon`, written+ * `[[acp.daemon]]`) is the case where a syntactic doc-vs-asset split shows up as+ * the panel reading "Asset" and offering an asset href for a document sitting+ * one folder over.+ *+ * The Radix-Popover-based `InteractionPropPanel` is mocked to a passthrough so+ * the panel body renders inline. `usePageList` is mocked at the data boundary+ * with a real corpus — the panel's own resolution runs for real.+ */++import { cleanup, render } from '@testing-library/react';+import type { Editor } from '@tiptap/core';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import { buildPagesByBasenameIndex, buildPagesBySlugIndex } from '../page-list-cache';+import { toWikiLinkSlug } from './wiki-link-helpers';++/** Dotted document, dot-free control in the same folder, and a real asset. */+const PAGES = new Set(['index', 'notes/acp.daemon', 'notes/roadmap']);+const ASSET_PATHS = new Set(['files/meeting.pdf']);++vi.doMock('../link-preview/use-internal-doc-preview.ts', () => ({+ useInternalDocPreview: () => null,+}));++vi.doMock('../../components/InteractionPropPanel', () => ({+ InteractionPropPanel: ({ children }: { children: ReactNode }) => (+ <div data-testid="prop-panel">{children}</div>+ ),+}));++vi.doMock('../../components/PageListContext', () => ({+ usePageList: () => ({+ addPage: () => {},+ assetPaths: ASSET_PATHS,+ filePaths: new Set<string>(),+ folderPaths: new Set<string>(['notes', 'files']),+ pages: PAGES,+ pagesBySlug: buildPagesBySlugIndex(PAGES, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(PAGES, toWikiLinkSlug),+ pageTitles: new Map<string, string>(),+ pageMeta: new Map(),+ loading: false,+ error: null,+ refetch: () => {},+ }),+}));++afterEach(cleanup);++/**+ * Minimal editor + getPos stub. The panel reads node attrs and `editor.view.dom`+ * at render; state mutations only run in callbacks this test never fires.+ */+function makeEditor(target: string): Editor {+ const node = { attrs: { target, alias: null, anchor: null }, nodeSize: 1 };+ return {+ state: { doc: { nodeAt: () => node } },+ view: { dom: document.createElement('div') },+ } as unknown as Editor;+}++async function renderPanel(target: string) {+ const { WikiLinkPropPanel } = await import('./WikiLinkPropPanel');+ const { container } = render(+ <TooltipProvider>+ <WikiLinkPropPanel+ editor={makeEditor(target)}+ getPos={() => 1}+ onClose={() => {}}+ onNavigate={() => true}+ />+ </TooltipProvider>,+ );+ const destination = container.querySelector('[data-slot="wiki-link-prop-panel-text"]');+ return {+ container,+ href: destination?.getAttribute('href') ?? null,+ ariaLabel: container.querySelector('[data-testid="prop-panel"]')?.getAttribute('aria-label'),+ };+}++describe('WikiLinkPropPanel destination', () => {+ test('a target naming a dotted-filename document points at that document', async () => {+ const { href } = await renderPanel('acp.daemon');++ expect(href).toBe('#/notes/acp.daemon');+ });++ test('a dot-free bare name still points at its subfolder document', async () => {+ const { href } = await renderPanel('roadmap');++ expect(href).toBe('#/notes/roadmap');+ });++ test('a target naming a real asset still points at the asset viewer', async () => {+ const { href } = await renderPanel('meeting.pdf');++ expect(href).toBe('#/__asset__/files/meeting.pdf');+ });++ test('a target naming nothing at all still points at the asset viewer', async () => {+ const { href } = await renderPanel('absent.pdf');++ expect(href).toBe('#/__asset__/absent.pdf');+ });+});diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsxindex 9ccb31644..693fcf3f3 100644--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx@@ -16,9 +16,9 @@*/import {- classifyWikiLinkTarget,getWikiLinkText,normalizeNullableString,+ resolveWikiLinkTarget,} from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import type { Editor } from '@tiptap/core';@@ -331,7 +331,15 @@ export function WikiLinkPropPanel({ editor, getPos, onClose, onNavigate }: WikiLpagesByBasename,loading,} = usePageList();- const classifiedTarget = classifyWikiLinkTarget(target, anchor);+ // Resolve against the same corpus the chip uses, so the destination this+ // panel reports is the one a click actually reaches.+ const classifiedTarget = resolveWikiLinkTarget(target, anchor, {+ pages,+ pagesBySlug,+ pagesByBasename,+ assetPaths,+ filePaths,+ });const externalTarget = classifiedTarget?.kind === 'external' ? classifiedTarget : null;// Mirror handlePrimary's asset resolution (wiki-link.ts): when the target// isn't in the known asset paths, fall back to the stripped raw URL so andiff --git a/packages/app/src/editor/extensions/wiki-link-helpers.ts b/packages/app/src/editor/extensions/wiki-link-helpers.tsindex b442944c1..cf5e29e1f 100644--- a/packages/app/src/editor/extensions/wiki-link-helpers.ts+++ b/packages/app/src/editor/extensions/wiki-link-helpers.ts@@ -1,108 +1,23 @@-import { getHeadingSlug, toWikiLinkSlug } from '@inkeep/open-knowledge-core';-import type { PageListCacheSnapshot } from '../page-list-cache';--export { getHeadingSlug, toWikiLinkSlug };--/**- * Input shape accepted by resolution helpers. A bare `Set<string>` works- * for tests and legacy callers — the helper derives the slug index on the- * fly (O(n) per call with a slug computation each). A `PageListCacheSnapshot`- * carries a precomputed `pagesBySlug` map — O(1) lookup. React components- * that consume `usePageList()` typically pass the bare `pages` Set; chip- * PM plugins that read `getPageListCache()` pass the snapshot.- */-type PagesLookupInput = ReadonlySet<string> | PageListCacheSnapshot;--function isSnapshot(input: PagesLookupInput): input is PageListCacheSnapshot {- return 'pagesBySlug' in input;-}--function getPagesSet(input: PagesLookupInput): ReadonlySet<string> {- return isSnapshot(input) ? input.pages : input;-}--function getAssetPathsSet(input: PagesLookupInput, assetPaths?: ReadonlySet<string>) {- return isSnapshot(input) ? (input.assetPaths ?? new Set<string>()) : (assetPaths ?? new Set());-}--/**- * The file-paths set (`kind:'file'` rows from- * `/api/documents` — tracked non-markdown, non-asset files). When the input is- * a snapshot, pull the optional set off it; bare-Set callers can pass it as an- * explicit override. Returns an empty Set on absence so the membership-check- * sites never need to nil-guard.- */-function getFilePathsSet(input: PagesLookupInput, filePaths?: ReadonlySet<string>) {- return isSnapshot(input) ? (input.filePaths ?? new Set<string>()) : (filePaths ?? new Set());-}--/**- * Look up a target by slug against the pages set / snapshot. Returns the- * original docName on match, or undefined when no entry's slug matches- * the target's slug.- *- * `buildUnresolvedWikiLinkAttrs` stores the lowercased slug as the PM- * wikiLink target. The page cache keeps- * case-preserved + non-slug-form docNames (`README`,- * `BA_for_Depression_Research`). Without a slug-based fallback,- * `pages.has('readme')` and `pages.has('ba-for-depression-research')`- * never match, so every dropped `.md` file + hand-typed `[[README]]`- * (via the suggestion-menu fallback path that also slugs) shows- * "Page not found".- *- * `targetSlug` is the slug of `target` — if target is already in slug- * form, it equals the input. Both branches use the slug as the lookup- * key, so `README` and `readme` and `Readme` all resolve to the same- * cache entry.- */-function slugLookup(target: string, input: PagesLookupInput): string | undefined {- const targetSlug = toWikiLinkSlug(target);- if (!targetSlug) return undefined;- if (isSnapshot(input)) {- return input.pagesBySlug.get(targetSlug);- }- // Bare Set — O(n) scan with slug computation per entry. Acceptable for- // PropPanel / non-hot-path callers (tests, one-off resolutions).- for (const page of input) {- if (toWikiLinkSlug(page) === targetSlug) return page;- }- return undefined;-}--/**- * Look up a bare-name target by basename across the pages set / snapshot.- * Returns the original docName on match, or undefined when no entry's- * basename slug matches. Mirrors the basename fallback in- * `resolveNavigationTarget` so the chip's icon + resolved-state classifier- * stays in sync with navigation: `[[analysis]]` chip renders as resolved- * when `andrew-data/.../analysis.md` exists, not as "Page not found".- *- * Targets containing `/` skip this branch (explicit-path intent —- * `[[bar/foo]]` should not silently rewrite to `baz/foo`).- *- * Alphabetical-first tie-break: both the snapshot fast path- * (`pagesByBasename`, built by `buildPagesByBasenameIndex` which sorts- * pages with `localeCompare` before insertion) and the bare-`Set`- * fallback below (linear scan with `localeCompare`-based min-tracking)- * use the same default-locale comparator, so the two branches resolve- * to the same docName for the same input.- */-function basenameLookup(target: string, input: PagesLookupInput): string | undefined {- if (target.includes('/')) return undefined;- const targetSlug = toWikiLinkSlug(target);- if (!targetSlug) return undefined;- if (isSnapshot(input)) {- return input.pagesByBasename?.get(targetSlug);- }- let bestMatch: string | undefined;- for (const page of input) {- const slash = page.lastIndexOf('/');- const basename = slash === -1 ? page : page.slice(slash + 1);- if (toWikiLinkSlug(basename) !== targetSlug) continue;- if (bestMatch === undefined || page.localeCompare(bestMatch) < 0) bestMatch = page;- }- return bestMatch;-}+import {+ getHeadingSlug,+ getWikiLinkResolutionCandidates,+ isResolvedWikiLinkTarget,+ resolveWikiLinkAssetTarget,+ resolveWikiLinkTargetDocName,+ toWikiLinkSlug,+} from '@inkeep/open-knowledge-core';++// The resolution chain moved to core so the server resolves wiki-link targets+// through the same code the editor does. Re-exported here because the chip,+// prop panels, and source-mode plugins all import it from this path.+export {+ getHeadingSlug,+ getWikiLinkResolutionCandidates,+ isResolvedWikiLinkTarget,+ resolveWikiLinkAssetTarget,+ resolveWikiLinkTargetDocName,+ toWikiLinkSlug,+};/*** True when the wiki-link target text can safely be used as a path segment@@ -147,176 +62,3 @@ export function buildUnresolvedWikiLinkAttrs(query: string): {anchor: null,};}--export function getWikiLinkResolutionCandidates(target: string): string[] {- const trimmed = target.trim();- if (!trimmed) return [];- const slug = toWikiLinkSlug(trimmed);- return slug.length > 0 && slug !== trimmed ? [slug] : [];-}--/**- * Resolve a wiki-link `target` attribute to the canonical docName as- * stored in the page-list cache, or `undefined` when no page matches.- *- * Resolution chain — first match wins, intentionally mirrors- * `resolveNavigationTarget` so the icon surface and the click destination- * stay in sync:- * 1. Direct membership: `cache.pages.has(target)`.- * 2. Slug match: `cache.pagesBySlug.get(toWikiLinkSlug(target))` —- * handles dropped-file lowercased slugs (`readme` → `README`)- * and `buildUnresolvedWikiLinkAttrs` slug-form targets.- * 3. Candidate fallback: `getWikiLinkResolutionCandidates(target)`- * against `cache.pages`.- * 4. Canonical folder-index: `${target}/index` in `cache.pages`.- * 5. Legacy folder note: `${target}/${target}` in `cache.pages`.- * 6. Basename fallback: bare-name target → same-leaf file in a- * subfolder via `cache.pagesByBasename`.- *- * Steps 4–5 ensure the chip resolves a folder-target wiki-link to the- * same docName the click destination opens. Without them, a- * `[[reports]]` chip with both `reports/index` AND `other/reports`- * existing would resolve to `other/reports` (basename) for the icon- * while navigation opens `reports/index` — a visible mismatch.- */-export function resolveWikiLinkTargetDocName(- target: string,- input: PagesLookupInput,-): string | undefined {- const trimmed = target.trim();- if (!trimmed) return undefined;- const pages = getPagesSet(input);- if (pages.has(trimmed)) return trimmed;- const viaSlug = slugLookup(trimmed, input);- if (viaSlug) return viaSlug;- for (const candidate of getWikiLinkResolutionCandidates(trimmed)) {- if (pages.has(candidate)) return candidate;- }- const folderIndexDocName = resolveFolderIndexDocName(trimmed, pages);- if (folderIndexDocName) return folderIndexDocName;- return basenameLookup(trimmed, input);-}--/**- * Folder-target → docName for the chip resolver. Mirrors the- * folder-index branches in `resolveNavigationTarget`: prefer a- * canonical `${target}/index` doc, fall back to a legacy- * `${target}/${leaf}` doc. Path-shaped targets (`foo/bar`) keep this- * branch active so `[[foo/bar]]` resolves to `foo/bar/index` when the- * subfolder index exists.- */-function resolveFolderIndexDocName(target: string, pages: ReadonlySet<string>): string | undefined {- const canonical = `${target}/index`;- if (pages.has(canonical)) return canonical;- const slashIndex = target.lastIndexOf('/');- const leaf = slashIndex === -1 ? target : target.slice(slashIndex + 1);- const legacy = leaf ? `${target}/${leaf}` : null;- if (legacy && pages.has(legacy)) return legacy;- return undefined;-}--function normalizeAssetTarget(target: string): string {- const trimmed = target.trim();- const withoutHash = (trimmed.split('#')[0] ?? '').trim();- const withoutQuery = (withoutHash.split('?')[0] ?? '').trim();- return withoutQuery.startsWith('/') ? withoutQuery.slice(1) : withoutQuery;-}--export function resolveWikiLinkAssetTarget(- target: string,- assetPaths: ReadonlySet<string>,- /**- * Optional tracked-files set (`kind:'file'` rows from- * `/api/documents`). When provided, a wiki-link to any tracked non-markdown- * file resolves — not just the renderable-asset subset. The exact + case-- * insensitive + basename branches all extend uniformly so the resolution- * shape stays identical regardless of which partition wins.- */- filePaths?: ReadonlySet<string>,-): string | null {- const normalized = normalizeAssetTarget(target);- if (!normalized) return null;-- const lowerTarget = normalized.toLowerCase();- // The two partitions never overlap in practice (a renderable asset is by- // construction not in the all-files-only set — handleDocumentList suppresses- // `kind:'file'` for any path already emitted as `kind:'asset'`), so check- // them independently. Asset wins on overlap because the renderable set- // carries richer metadata downstream.- const partitions: ReadonlyArray<ReadonlySet<string>> = filePaths- ? [assetPaths, filePaths]- : [assetPaths];-- for (const partition of partitions) {- if (partition.has(normalized)) return normalized;- for (const path of partition) {- if (path.toLowerCase() === lowerTarget) return path;- }- }-- if (normalized.includes('/')) return null;- const matches: string[] = [];- for (const partition of partitions) {- for (const path of partition) {- const slash = path.lastIndexOf('/');- const basename = slash === -1 ? path : path.slice(slash + 1);- if (basename.toLowerCase() === lowerTarget) matches.push(path);- }- }- if (matches.length === 0) return null;- return matches.sort((a, b) => a.localeCompare(b))[0] ?? null;-}--export function isResolvedWikiLinkTarget(- target: string,- pages: PagesLookupInput,- assetPaths?: ReadonlySet<string>,- /**- * Tracked-files set forwarded into- * `resolveWikiLinkAssetTarget`. Lets a wiki-link to an existing non-markdown- * file (e.g. `[[data/example.csv]]`) resolve instead of rendering dead. When- * the input is a snapshot, the set is pulled off it; this explicit override- * is for bare-Set test callers.- */- filePaths?: ReadonlySet<string>,-): boolean {- const trimmed = target.trim();- if (!trimmed) return false;- if (- resolveWikiLinkAssetTarget(- trimmed,- getAssetPathsSet(pages, assetPaths),- getFilePathsSet(pages, filePaths),- )- ) {- return true;- }-- const pagesSet = getPagesSet(pages);- if (pagesSet.has(trimmed)) return true;-- if (getWikiLinkResolutionCandidates(trimmed).some((candidate) => pagesSet.has(candidate))) {- return true;- }-- // Slug-based fallback. Handles dropped `.md`- // (target='readme' from slug) against case-preserved cache entry- // (`README`) AND underscore/space/punctuation cache entries- // (`BA_for_Depression_Research` → slug `ba-for-depression-research`).- // Plus hand-typed `[[README]]` via the suggestion-menu fallback path- // that also runs the slug transform. First-wins on slug collision —- // if both `README` and `ReadMe` exist (different case, same slug), the- // insertion-order-first entry wins (documented in the- // PageListCacheSnapshot JSDoc at `page-list-cache.ts`).- if (slugLookup(trimmed, pages) !== undefined) return true;-- // Folder-index parity with `resolveNavigationTarget` — a `[[reports]]`- // chip is resolved when a `reports/index` (or legacy `reports/reports`)- // doc exists, matching the navigation outcome.- if (resolveFolderIndexDocName(trimmed, pagesSet)) return true;-- // Basename fallback — bare-name target matches a same-basename file in- // a subfolder. Mirrors `resolveNavigationTarget` so the chip's resolved- // class matches the navigation outcome.- return basenameLookup(trimmed, pages) !== undefined;-}diff --git a/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.tsnew file mode 100644index 000000000..1f7e1c702--- /dev/null+++ b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts@@ -0,0 +1,137 @@+/**+ * Where a `[[wikilink]]` chip actually sends you when you activate it.+ *+ * The routing code is real — a mounted Editor with the production `WikiLink`+ * NodeView, activated through the InteractionLayer the way production reaches+ * it (`getRegistration(nodeId).handlePrimary(...)`). The page list is the real+ * module-level cache, populated with a real corpus. Nothing about resolution is+ * doubled; the only observation point is the navigation sink.+ *+ * The case that motivates the file: a document whose filename carries a dot+ * (`notes/acp.daemon.md`, referenced as `[[acp.daemon]]`) reads as a file named+ * `acp` with extension `daemon` to any purely syntactic classifier, so it lands+ * in the asset viewer and 404s. Which document a target names is a question+ * about the corpus, not about the string.+ */++import { Editor } from '@tiptap/core';+import { TextSelection } from '@tiptap/pm/state';+import StarterKit from '@tiptap/starter-kit';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';+import { getInteractionLayer } from '../interaction-layer-host';+import {+ __resetPageListCacheForTests,+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ setPageListCache,+} from '../page-list-cache';+import { installDomGlobals } from '../walk-currency-test-harness';+import { WikiLink } from './wiki-link';+import { toWikiLinkSlug } from './wiki-link-helpers';++let restoreDomGlobals: (() => void) | null = null;++beforeAll(() => {+ restoreDomGlobals = installDomGlobals();+});++afterAll(() => {+ restoreDomGlobals?.();+ restoreDomGlobals = null;+});++const liveEditors = new Set<Editor>();++/**+ * The corpus every case in this file resolves against. `notes/acp.daemon` is+ * the dotted document; `notes/roadmap` is the dot-free control that reaches the+ * same basename step; `meeting.pdf` is a real asset that must keep going to the+ * asset viewer.+ */+const PAGES = new Set(['index', 'notes/acp.daemon', 'notes/roadmap']);+const ASSET_PATHS = new Set(['files/meeting.pdf']);++beforeEach(() => {+ __resetPageListCacheForTests();+ setPageListCache({+ pages: PAGES,+ folderPaths: new Set(['notes', 'files']),+ assetPaths: ASSET_PATHS,+ pagesBySlug: buildPagesBySlugIndex(PAGES, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(PAGES, toWikiLinkSlug),+ });+ globalThis.window.location.hash = '';+});++afterEach(() => {+ for (const editor of liveEditors) editor.destroy();+ liveEditors.clear();+ __resetPageListCacheForTests();+});++/**+ * Mount a real editor holding a single `[[target]]` chip and return an+ * `activate` that runs the production primary-action closure, plus the hash the+ * activation navigated to.+ */+function mountWikiLink(target: string): {+ activate: (newTab?: boolean) => boolean | undefined;+ currentHash: () => string;+} {+ const host = globalThis.document.createElement('div');+ globalThis.document.body.appendChild(host);+ const editor = new Editor({+ element: host,+ content: `<p><span data-wiki-link data-target="${target}"></span></p>`,+ extensions: [StarterKit, WikiLink.configure({ docName: 'index' })],+ });+ liveEditors.add(editor);++ // Force a view update so the NodeView's InteractionLayer registration settles.+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1)));++ const chip = host.querySelector('[data-node-id]');+ const nodeId = chip?.getAttribute('data-node-id') ?? undefined;+ if (nodeId === undefined) {+ throw new Error(`setup: no wiki-link chip parsed for target ${target}`);+ }+ const registration = getInteractionLayer(editor).getRegistration(nodeId);+ if (!registration?.handlePrimary) {+ throw new Error('setup: wiki-link chip did not register a handlePrimary hook');+ }+ return {+ activate: (newTab = false) =>+ registration.handlePrimary?.({ nodeId, type: 'wikiLink', newTab }),+ currentHash: () => globalThis.window.location.hash,+ };+}++describe('WYSIWYG wiki-link activation', () => {+ test('a target naming a dotted-filename document opens that document', () => {+ const { activate, currentHash } = mountWikiLink('acp.daemon');++ expect(activate()).toBe(true);+ expect(currentHash()).toBe('#/notes/acp.daemon');+ });++ test('a dot-free bare name still opens its subfolder document', () => {+ const { activate, currentHash } = mountWikiLink('roadmap');++ expect(activate()).toBe(true);+ expect(currentHash()).toBe('#/notes/roadmap');+ });++ test('a target naming a real asset still opens the asset viewer', () => {+ const { activate, currentHash } = mountWikiLink('meeting.pdf');++ expect(activate()).toBe(true);+ expect(currentHash()).toBe('#/__asset__/files/meeting.pdf');+ });++ test('a target naming nothing at all still routes to the asset viewer', () => {+ const { activate, currentHash } = mountWikiLink('absent.pdf');++ expect(activate()).toBe(true);+ expect(currentHash()).toBe('#/__asset__/absent.pdf');+ });+});diff --git a/packages/app/src/editor/extensions/wiki-link.ts b/packages/app/src/editor/extensions/wiki-link.tsindex 662465044..478ae27c9 100644--- a/packages/app/src/editor/extensions/wiki-link.ts+++ b/packages/app/src/editor/extensions/wiki-link.ts@@ -17,7 +17,7 @@* wikiLink suggestion popover is closed remain orthogonal to the chip* rendering.*/-import { WikiLink as BaseWikiLink, classifyWikiLinkTarget } from '@inkeep/open-knowledge-core';+import { WikiLink as BaseWikiLink, resolveWikiLinkTarget } from '@inkeep/open-knowledge-core';import { createElement } from 'react';import { openExternalUrl } from '@/lib/external-link';import { resolveLinkTargetIntent } from '../../components/link-target-intent';@@ -172,7 +172,10 @@ export function getWikiLinkResolutionState(cache: PageListCacheSnapshot | null,): string | null {if (!target) return null;- const classified = classifyWikiLinkTarget(target, anchor);+ // Same composed resolution the activation path uses, and fed the same cold-+ // cache stand-in, so the colour and the destination cannot disagree about+ // whether a target is a document.+ const classified = resolveWikiLinkTarget(target, anchor, cache ?? new Set<string>());if (!classified) return null;if (classified.kind === 'external') return 'external';if (!cache) return 'loading';@@ -332,10 +335,17 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({const liveTarget = typeof live.target === 'string' ? live.target : '';if (!liveTarget) return false;const liveAnchor = typeof live.anchor === 'string' ? live.anchor : null;- const classified = classifyWikiLinkTarget(liveTarget, liveAnchor);+ // A cold cache resolves nothing, so an asset-shaped target stays an+ // asset until the page list arrives — the same window every bare-name+ // chip already sits in.+ const cache = getPageListCache();+ const classified = resolveWikiLinkTarget(+ liveTarget,+ liveAnchor,+ cache ?? new Set<string>(),+ );if (!classified) return false;if (classified.kind === 'doc') {- const cache = getPageListCache();const intent = resolveLinkTargetIntent(liveTarget, {pages: cache?.pages ?? new Set<string>(),folderPaths: cache?.folderPaths ?? new Set<string>(),@@ -365,7 +375,6 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({// wiki-link to a tracked non-asset file would resolve to the bare// `classified.url.replace(/^\//, '')` and the chip would render as// unresolved — even though the file IS tracked.- const cache = getPageListCache();const assetPath =resolveWikiLinkAssetTarget(classified.url,diff --git a/packages/app/src/editor/page-list-cache.ts b/packages/app/src/editor/page-list-cache.tsindex 36143081c..071a783fc 100644--- a/packages/app/src/editor/page-list-cache.ts+++ b/packages/app/src/editor/page-list-cache.ts@@ -36,6 +36,13 @@* @see packages/app/src/editor/extensions/mark-interaction-bridge.ts*/+import { buildPagesByBasenameIndex, buildPagesBySlugIndex } from '@inkeep/open-knowledge-core';++// The derived-index builders moved to core alongside the resolution chain that+// reads them, so the fast-path index and the resolver's tie-break can't drift.+// Re-exported here because the provider and its tests import them from this path.+export { buildPagesByBasenameIndex, buildPagesBySlugIndex };+export interface PageListCacheSnapshot {readonly pages: ReadonlySet<string>;readonly folderPaths: ReadonlySet<string>;@@ -90,10 +97,12 @@ export interface PageListCacheSnapshot {* backward compatibility — callers fall back to slug + exact match* when the index is absent.*- * Tie-break is alphabetical-first by full docName: if two files- * share a basename (`a/foo.md`, `b/foo.md`), the lexicographically- * smaller path wins (`a/foo`). Matches `resolveWikiLinkAssetTarget`'s- * basename-with-alphabetical-first behavior for assets.+ * Tie-break is code-unit-lowest by full docName: if two files share a+ * basename (`a/foo.md`, `b/foo.md`), the smaller path wins (`a/foo`).+ * Locale-independent on purpose, so the client and the server can't name+ * different documents for one bare name — see `buildPagesByBasenameIndex`+ * in core for why. Note that code-unit order sorts every uppercase letter+ * before every lowercase one.** Consulted only after `pages.has` and `pagesBySlug.get` miss, and* only when the target contains no slash — `[[foo/bar]]` keeps@@ -167,55 +176,6 @@ function pageIconsEqual(return true;}-/**- * Build the slug-keyed index from a pages set. First-wins on slug collision- * (Map insertion order preserved; iteration order of a Set follows insertion- * order per ES spec). Accepts the slug function as a parameter so this- * module stays free of a `@inkeep/open-knowledge-core` import (the actual- * slugger lives there); callers pass `toWikiLinkSlug`.- *- * Tie-break is deliberately insertion-order, not alphabetical — the slug- * key already encodes the full docName, so collisions are rare and- * insertion-order matches the Set's iteration semantics. The sibling- * `buildPagesByBasenameIndex` sorts alphabetically before insertion- * because basename collisions across folders are expected and the- * alphabetical-first tie-break mirrors `resolveWikiLinkAssetTarget`'s- * prior art for assets.- */-export function buildPagesBySlugIndex(- pages: ReadonlySet<string>,- slugFn: (text: string) => string,-): ReadonlyMap<string, string> {- const index = new Map<string, string>();- for (const page of pages) {- const key = slugFn(page);- if (key && !index.has(key)) index.set(key, page);- }- return index;-}--/**- * Build the basename-keyed index from a pages set. Keys by the slug of- * each docName's leaf segment (the part after the last `/`). Sorts- * input alphabetically before insertion so first-wins on basename- * collision becomes alphabetical-first by full docName — matches the- * tie-break in `resolveWikiLinkAssetTarget` for assets.- */-export function buildPagesByBasenameIndex(- pages: ReadonlySet<string>,- slugFn: (text: string) => string,-): ReadonlyMap<string, string> {- const index = new Map<string, string>();- const sorted = [...pages].sort((a, b) => a.localeCompare(b));- for (const page of sorted) {- const slash = page.lastIndexOf('/');- const basename = slash === -1 ? page : page.slice(slash + 1);- const key = slugFn(basename);- if (key && !index.has(key)) index.set(key, page);- }- return index;-}-/*** Project the `icon` field out of a PageMeta-shaped map into a flat* `docName → rawIconValue` map. Skips entries with an absent or blankdiff --git a/packages/app/src/editor/plugins/wiki-link-source.destination.test.ts b/packages/app/src/editor/plugins/wiki-link-source.destination.test.tsnew file mode 100644index 000000000..d3a3c1b61--- /dev/null+++ b/packages/app/src/editor/plugins/wiki-link-source.destination.test.ts@@ -0,0 +1,96 @@+/**+ * Where a source-mode Cmd/Ctrl+click on a `[[wikilink]]` sends you.+ *+ * The destination decision is exercised directly; the surrounding mousedown+ * handler is DOM-layout-bound (`posAtCoords` needs real geometry, which jsdom+ * does not provide) and is covered by Playwright. What is under test here is the+ * part that can be wrong without any geometry: which corpus entry the target+ * names, and therefore which route it opens.+ *+ * Source mode navigates to the raw target and lets the app's hash router run+ * bare-name resolution, so the assertions below pin the route, not the final+ * document — except where the route itself is the defect (an asset route for a+ * document).+ */++import { describe, expect, test } from 'vitest';+import {+ buildSourceWikiLinkLookup,+ type PageItem,+ resolveSourceWikiLinkDestination,+} from './wiki-link-source';++/**+ * The corpus every case resolves against, in the shape `/api/pages` ++ * `/api/documents` actually produce: documents carry `kind:'page'` and no+ * extension, while both referenced assets and tracked files arrive as+ * `kind:'asset'` with a leading slash.+ */+const CORPUS: PageItem[] = [+ { kind: 'page', docName: 'index', title: 'Home' },+ { kind: 'page', docName: 'notes/acp.daemon', title: 'ACP daemon' },+ { kind: 'page', docName: 'notes/roadmap', title: 'Roadmap' },+ { kind: 'asset', docName: '/files/meeting.pdf', title: 'meeting.pdf' },+ { kind: 'folder', docName: 'notes', title: 'notes' },+];++const LOOKUP = buildSourceWikiLinkLookup(CORPUS);++describe('source-mode wiki-link destination', () => {+ test('a target naming a dotted-filename document opens a document route', () => {+ expect(resolveSourceWikiLinkDestination('acp.daemon', null, LOOKUP)).toEqual({+ kind: 'hash',+ href: '#/acp.daemon',+ });+ });++ test('a dot-free bare name opens a document route', () => {+ expect(resolveSourceWikiLinkDestination('roadmap', null, LOOKUP)).toEqual({+ kind: 'hash',+ href: '#/roadmap',+ });+ });++ test('an anchor rides along on a document route', () => {+ expect(resolveSourceWikiLinkDestination('acp.daemon', 'setup', LOOKUP)).toEqual({+ kind: 'hash',+ href: '#/acp.daemon#setup',+ });+ });++ test('a target naming a real asset opens the asset viewer at its indexed path', () => {+ expect(resolveSourceWikiLinkDestination('meeting.pdf', null, LOOKUP)).toEqual({+ kind: 'hash',+ href: '#/__asset__/files/meeting.pdf',+ });+ });++ test('a target naming nothing at all still opens the asset viewer', () => {+ expect(resolveSourceWikiLinkDestination('absent.pdf', null, LOOKUP)).toEqual({+ kind: 'hash',+ href: '#/__asset__/absent.pdf',+ });+ });++ test('an external target is handed to the external opener, not a hash route', () => {+ expect(resolveSourceWikiLinkDestination('https://example.com/docs', null, LOOKUP)).toEqual({+ kind: 'external',+ url: 'https://example.com/docs',+ });+ });++ test('an empty target names nothing to open', () => {+ expect(resolveSourceWikiLinkDestination(' ', null, LOOKUP)).toBeNull();+ });+});++describe('buildSourceWikiLinkLookup', () => {+ test('folders are not documents', () => {+ expect(LOOKUP.pages.has('notes')).toBe(false);+ expect(LOOKUP.pages.has('notes/roadmap')).toBe(true);+ });++ test('asset paths drop the leading slash the documents API adds', () => {+ expect(LOOKUP.assetPaths?.has('files/meeting.pdf')).toBe(true);+ });+});diff --git a/packages/app/src/editor/plugins/wiki-link-source.ts b/packages/app/src/editor/plugins/wiki-link-source.tsindex 30ec07803..e8b12a24f 100644--- a/packages/app/src/editor/plugins/wiki-link-source.ts+++ b/packages/app/src/editor/plugins/wiki-link-source.ts@@ -23,10 +23,16 @@ import {ViewPlugin,type ViewUpdate,} from '@codemirror/view';-import { classifyWikiLinkTarget, type HeadingEntry } from '@inkeep/open-knowledge-core';+import {+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ type HeadingEntry,+ resolveWikiLinkTarget,+ type WikiLinkLookupIndex,+} from '@inkeep/open-knowledge-core';import { openExternalUrl } from '@/lib/external-link';import { hashFromAssetPath, hashFromDocName } from '../../lib/doc-hash';-import { resolveWikiLinkAssetTarget } from '../extensions/wiki-link-helpers';+import { resolveWikiLinkAssetTarget, toWikiLinkSlug } from '../extensions/wiki-link-helpers';import {fetchHeadings,fetchPages,@@ -36,7 +42,7 @@ import {type PageItem,type WikiLinkContext,} from '../extensions/wiki-link-suggestion';-import { openInternalHashHrefInNewTab, shouldOpenInNewTab } from '../internal-link-helpers';+import { openHashHrefInNewTab, shouldOpenInNewTab } from '../internal-link-helpers';import {isLinkValidationVisible,subscribeToLinkValidationPolicy,@@ -54,6 +60,14 @@ const PAGES_CACHE_TTL_MS = 5_000;let pagesCache: PageItem[] | null = null;let pagesCacheTime = 0;let knownTargetSet: Set<string> | null = null;+let wikiLinkLookup: WikiLinkLookupIndex | null = null;++const EMPTY_WIKI_LINK_LOOKUP: WikiLinkLookupIndex = {+ pages: new Set(),+ pagesBySlug: new Map(),+ pagesByBasename: new Map(),+ assetPaths: new Set(),+};const headingsCache = new Map<string, { headings: HeadingEntry[]; time: number }>();// Per-docName link-graph context for autocomplete re-ranking, TTL-cached like// pages so the per-keystroke completion source doesn't refetch backlinks on@@ -76,6 +90,7 @@ async function getPages(): Promise<PageItem[]> {pagesCache = await fetchPages();pagesCacheTime = now;knownTargetSet = buildKnownWikilinkTargetSet(pagesCache);+ wikiLinkLookup = buildSourceWikiLinkLookup(pagesCache);return pagesCache;}@@ -138,6 +153,65 @@ export function buildKnownWikilinkTargetSet(pages: PageItem[]): Set<string> {return s;}+/**+ * Derive the lookup that Cmd/Ctrl+click resolves against. Documents and assets+ * arrive in one `PageItem[]`: documents carry `kind:'page'`, while both+ * referenced assets and tracked files arrive as `kind:'asset'` with a leading+ * slash, and folders are neither.+ *+ * Built once per page-cache refresh rather than per click — the slug and+ * basename maps cost a pass over the corpus plus a slug computation each, which+ * a mousedown handler must not pay.+ *+ * Exported for unit tests — the plugin builds it internally.+ */+export function buildSourceWikiLinkLookup(pages: PageItem[]): WikiLinkLookupIndex {+ const docNames = new Set<string>();+ const assetPaths = new Set<string>();+ for (const page of pages) {+ if (page.kind === 'asset') assetPaths.add(page.docName.replace(/^\//, ''));+ else if (page.kind !== 'folder') docNames.add(page.docName);+ }+ return {+ pages: docNames,+ assetPaths,+ pagesBySlug: buildPagesBySlugIndex(docNames, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(docNames, toWikiLinkSlug),+ };+}++export type SourceWikiLinkDestination =+ | { kind: 'external'; url: string }+ | { kind: 'hash'; href: string };++/**+ * Where a source-mode wiki-link activation goes. Returns null when the target+ * names nothing openable, in which case the click is left to CodeMirror.+ *+ * Documents route to the raw target rather than a resolved docName: the app's+ * hash router runs the same bare-name resolution on the way in, so resolving+ * here would only duplicate it.+ *+ * Exported for unit tests — the mousedown handler around it is layout-bound+ * (`posAtCoords` needs real geometry) and is covered by Playwright.+ */+export function resolveSourceWikiLinkDestination(+ target: string,+ anchor: string | null,+ lookup: WikiLinkLookupIndex,+): SourceWikiLinkDestination | null {+ const classified = resolveWikiLinkTarget(target, anchor, lookup);+ if (!classified) return null;+ if (classified.kind === 'external') return { kind: 'external', url: classified.url };+ if (classified.kind === 'asset') {+ const assetPath =+ resolveWikiLinkAssetTarget(classified.url, lookup.assetPaths ?? new Set<string>()) ??+ classified.url.replace(/^\//, '');+ return { kind: 'hash', href: hashFromAssetPath(assetPath) };+ }+ return { kind: 'hash', href: hashFromDocName(classified.docName, classified.anchor) };+}+/** Extract the target page name from a wikilink's inner text (the part between* `[[` and `]]`). Strips optional `#anchor` and `|alias`, normalizes to lowercase.* Returns the empty string for empty or whitespace-only inner text.@@ -251,36 +325,28 @@ const wikiLinkClickHandler = EditorView.domEventHandlers({const target = m[1]?.trim();const anchor = m[2]?.trim() || null;if (target) {- const classified = classifyWikiLinkTarget(target, anchor);- if (!classified) return false;+ // A cold cache resolves nothing, so an asset-shaped target stays an+ // asset until the page list arrives — the same window every bare-name+ // wikilink already sits in.+ const destination = resolveSourceWikiLinkDestination(+ target,+ anchor,+ wikiLinkLookup ?? EMPTY_WIKI_LINK_LOOKUP,+ );+ if (!destination) return false;event.preventDefault();- if (classified.kind === 'external') {+ if (destination.kind === 'external') {// Route through the desktop bridge so the OS default browser opens// the URL (web falls back to window.open) — symmetric with the- // WYSIWYG wiki-link chip. classifyWikiLinkTarget admits any URI- // scheme via isExternalHref; openExternalUrl refuses unsafe- // schemes internally, so an authored javascript:/data: href is- // dropped there (the event is already consumed via preventDefault).- openExternalUrl(classified.url);- } else if (classified.kind === 'asset') {- const assetPath =- resolveWikiLinkAssetTarget(- classified.url,- new Set(- (pagesCache ?? [])- .filter((item) => item.kind === 'asset')- .map((item) => item.docName.replace(/^\//, '')),- ),- ) ?? classified.url.replace(/^\//, '');- if (shouldOpenInNewTab(event)) {- window.open(hashFromAssetPath(assetPath), '_blank', 'noopener,noreferrer');- } else {- window.location.hash = hashFromAssetPath(assetPath);- }+ // WYSIWYG wiki-link chip. Classification admits any URI scheme via+ // isExternalHref; openExternalUrl refuses unsafe schemes+ // internally, so an authored javascript:/data: href is dropped+ // there (the event is already consumed via preventDefault).+ openExternalUrl(destination.url);} else if (shouldOpenInNewTab(event)) {- openInternalHashHrefInNewTab(classified);+ openHashHrefInNewTab(destination.href);} else {- window.location.hash = hashFromDocName(classified.docName, classified.anchor);+ window.location.hash = destination.href;}}return true;diff --git a/packages/app/tests/integration/link-authoring-contract.test.ts b/packages/app/tests/integration/link-authoring-contract.test.tsindex 0f1e10cf1..f9fc1f451 100644--- a/packages/app/tests/integration/link-authoring-contract.test.ts+++ b/packages/app/tests/integration/link-authoring-contract.test.ts@@ -406,3 +406,48 @@ test('a link to a doc that actually exists is not flagged (admitted-set membershconst doc = docResult(result.structuredContent);expect(doc.brokenLinks).toEqual([]);});++test('bare-name wiki links are validated the way the editor navigates them', async () => {+ const session = await openMcpSession(server.port);+ const suffix = randomUUID().slice(0, 8);+ const folder = `vault-${suffix}`;+ const dotted = `${folder}/acp.daemon`;+ const plain = `${folder}/analysis`;+ const sourceDoc = `notes-${suffix}/index`;++ for (const target of [dotted, plain]) {+ await callTool(+ server.port,+ session,+ 'write',+ { document: { path: target, content: '# Target\n\nBody.\n', position: 'replace' } },+ server.contentDir,+ );+ await awaitFileWatcherIndexed(server, target);+ }++ const result = await callTool(+ server.port,+ session,+ 'write',+ {+ document: {+ path: sourceDoc,+ content: `# Index\n\nSee [[acp.daemon]], [[analysis]], and [[nowhere-${suffix}]].\n`,+ position: 'replace',+ },+ },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);++ // Both targets sit in another folder, so neither matches its written name as+ // a key — yet both are what a reader clicking the link opens. Only the name+ // that resolves to nothing is reported. Before the write response agreed with+ // the editor it named the two working links and said nothing at all about the+ // dotted one, which was read as a file of type `daemon`.+ const doc = docResult(result.structuredContent);+ expect(doc.brokenLinks).toEqual([+ { href: `[[nowhere-${suffix}]]`, resolvedTo: `nowhere-${suffix}`, reason: 'no-such-doc' },+ ]);+});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 8bd1328e0..b79d026b5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1884,3 +1884,14 @@ export {wikiLinkHref,} from './utils/slug.ts';export { expandTagToHierarchy, tagsMatchingPrefix } from './utils/tag-rollup.ts';+export {+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ getWikiLinkResolutionCandidates,+ isResolvedWikiLinkTarget,+ resolveWikiLinkAssetTarget,+ resolveWikiLinkTarget,+ resolveWikiLinkTargetDocName,+ type WikiLinkLookupIndex,+ type WikiLinkPagesInput,+} from './utils/wiki-link-resolve.ts';diff --git a/packages/core/src/utils/wiki-link-resolve.test.ts b/packages/core/src/utils/wiki-link-resolve.test.tsnew file mode 100644index 000000000..5adb0be7e--- /dev/null+++ b/packages/core/src/utils/wiki-link-resolve.test.ts@@ -0,0 +1,455 @@+import { describe, expect, test } from 'vitest';+import { classifyWikiLinkTarget } from './link-targets.ts';+import { toWikiLinkSlug } from './slug.ts';+import {+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,+ isResolvedWikiLinkTarget,+ resolveWikiLinkAssetTarget,+ resolveWikiLinkTarget,+ resolveWikiLinkTargetDocName,+ type WikiLinkLookupIndex,+} from './wiki-link-resolve.ts';++/**+ * Equivalence corpus. Every expectation below was GENERATED by running the+ * resolution chain in its previous home (the app's `wiki-link-helpers.ts` ++ * `page-list-cache.ts`) over these exact fixtures — not hand-written. A+ * mismatch here means relocating the chain changed a resolved docName, which+ * is the one thing the move must not do.+ *+ * Reading the diff cannot confirm equivalence for a resolver: the output is+ * the resolved docName, not the source text. This table is that check.+ */+const PAGES = [+ 'README',+ 'test-doc',+ 'nonexistent-page',+ 'BA_for_Depression_Research',+ 'docs/getting-started',+ 'packages/server/README',+ 'andrew-data/project-x/analysis',+ 'z/foo',+ 'a/foo',+ 'm/foo',+ 'subfolder/Project X',+ 'reports/index',+ 'archive/reports',+ 'docs/api/api',+ 'notes/acp.daemon',+ 'v1.2 release',+ 'meeting.pdf',+ 'Zebra',+ 'apple',+ 'Notes/Summary',+ 'archive/summary',+];++const ASSETS = ['docs/public/Wide.png', 'images/photo.JPG', 'meeting.pdf', 'shared.png'];+const FILES = ['data/example.csv', 'src/components/FileTree.tsx', 'shared.png'];++/**+ * `[target, docNameFromBareSet, docNameFromIndex, assetWithFiles,+ * assetWithoutFiles, isResolvedFromBareSet, isResolvedFromIndex]`.+ *+ * The bare-Set and index columns are separate on purpose: they run different+ * code (linear scan vs precomputed map) and must agree on every row.+ */+type CorpusRow = [+ target: string,+ setDoc: string | null,+ indexDoc: string | null,+ asset: string | null,+ assetNoFiles: string | null,+ setResolved: boolean,+ indexResolved: boolean,+];++const CORPUS: readonly CorpusRow[] = [+ ['', null, null, null, null, false, false],+ [' ', null, null, null, null, false, false],+ ['README', 'README', 'README', null, null, true, true],+ ['readme', 'README', 'README', null, null, true, true],+ ['ReAdMe', 'README', 'README', null, null, true, true],+ ['test-doc', 'test-doc', 'test-doc', null, null, true, true],+ ['Nonexistent Page', 'nonexistent-page', 'nonexistent-page', null, null, true, true],+ ['Missing Page', null, null, null, null, false, false],+ [+ 'ba-for-depression-research',+ 'BA_for_Depression_Research',+ 'BA_for_Depression_Research',+ null,+ null,+ true,+ true,+ ],+ [+ 'BA_for_Depression_Research',+ 'BA_for_Depression_Research',+ 'BA_for_Depression_Research',+ null,+ null,+ true,+ true,+ ],+ ['docs/getting-started', 'docs/getting-started', 'docs/getting-started', null, null, true, true],+ [+ 'packages/server/readme',+ 'packages/server/README',+ 'packages/server/README',+ null,+ null,+ true,+ true,+ ],+ [+ 'analysis',+ 'andrew-data/project-x/analysis',+ 'andrew-data/project-x/analysis',+ null,+ null,+ true,+ true,+ ],+ ['foo', 'a/foo', 'a/foo', null, null, true, true],+ ['project x', 'subfolder/Project X', 'subfolder/Project X', null, null, true, true],+ ['Project X', 'subfolder/Project X', 'subfolder/Project X', null, null, true, true],+ ['sub/foo', null, null, null, null, false, false],+ ['reports', 'reports/index', 'reports/index', null, null, true, true],+ ['docs/api', 'docs/api/api', 'docs/api/api', null, null, true, true],+ ['acp.daemon', 'notes/acp.daemon', 'notes/acp.daemon', null, null, true, true],+ ['ACP.Daemon', 'notes/acp.daemon', 'notes/acp.daemon', null, null, true, true],+ ['notes/acp.daemon', 'notes/acp.daemon', 'notes/acp.daemon', null, null, true, true],+ ['v1.2 release', 'v1.2 release', 'v1.2 release', null, null, true, true],+ ['v1-2-release', 'v1.2 release', 'v1.2 release', null, null, true, true],+ ['meeting.pdf', 'meeting.pdf', 'meeting.pdf', 'meeting.pdf', 'meeting.pdf', true, true],+ ['/meeting.pdf', 'meeting.pdf', 'meeting.pdf', 'meeting.pdf', 'meeting.pdf', true, true],+ ['Wide.png', null, null, 'docs/public/Wide.png', 'docs/public/Wide.png', true, true],+ ['docs/public/wide.png', null, null, 'docs/public/Wide.png', 'docs/public/Wide.png', true, true],+ ['/docs/public/Wide.png', null, null, 'docs/public/Wide.png', 'docs/public/Wide.png', true, true],+ ['other/Wide.png', null, null, null, null, false, false],+ ['Missing.png', null, null, null, null, false, false],+ ['photo.jpg', null, null, 'images/photo.JPG', 'images/photo.JPG', true, true],+ ['data/example.csv', null, null, 'data/example.csv', null, true, true],+ ['/data/example.csv', null, null, 'data/example.csv', null, true, true],+ ['FileTree.tsx', null, null, 'src/components/FileTree.tsx', null, true, true],+ ['filetree.tsx', null, null, 'src/components/FileTree.tsx', null, true, true],+ ['missing.csv', null, null, null, null, false, false],+ ['shared.png', null, null, 'shared.png', 'shared.png', true, true],+ ['Zebra', 'Zebra', 'Zebra', null, null, true, true],+ ['apple', 'apple', 'apple', null, null, true, true],+ // The two rows the comparator pin deliberately changed. `Notes/Summary` and+ // `archive/summary` share the basename slug `summary`; the previous+ // default-locale tie-break picked `archive/summary`, code-unit order picks+ // `Notes/Summary`. Every other row is byte-identical to the pre-move output.+ ['summary', 'Notes/Summary', 'Notes/Summary', null, null, true, true],+ ['Summary', 'Notes/Summary', 'Notes/Summary', null, null, true, true],+ [+ 'docs/public/Wide.png#frag',+ null,+ null,+ 'docs/public/Wide.png',+ 'docs/public/Wide.png',+ true,+ true,+ ],+ ['Wide.png?v=2', null, null, 'docs/public/Wide.png', 'docs/public/Wide.png', true, true],+];++function makeFixtures() {+ const pages = new Set(PAGES);+ const assetPaths = new Set(ASSETS);+ const filePaths = new Set(FILES);+ const index: WikiLinkLookupIndex = {+ pages,+ assetPaths,+ filePaths,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ return { pages, assetPaths, filePaths, index };+}++describe('wiki-link resolution equivalence corpus', () => {+ test('every target resolves to the docName it resolved to before the chain moved', () => {+ const { pages, assetPaths, filePaths, index } = makeFixtures();++ const actual = CORPUS.map(([target]): CorpusRow => {+ return [+ target,+ resolveWikiLinkTargetDocName(target, pages) ?? null,+ resolveWikiLinkTargetDocName(target, index) ?? null,+ resolveWikiLinkAssetTarget(target, assetPaths, filePaths),+ resolveWikiLinkAssetTarget(target, assetPaths),+ isResolvedWikiLinkTarget(target, pages, assetPaths, filePaths),+ isResolvedWikiLinkTarget(target, index),+ ];+ });++ expect(actual).toEqual(CORPUS);+ });++ test('the bare-set scan and the precomputed index name the same document', () => {+ const { pages, index } = makeFixtures();+ for (const [target] of CORPUS) {+ expect(resolveWikiLinkTargetDocName(target, index)).toBe(+ resolveWikiLinkTargetDocName(target, pages),+ );+ }+ });+});++describe('derived index construction', () => {+ test('slug index keys the full docName and keeps the first entry on collision', () => {+ const index = buildPagesBySlugIndex(new Set(['README', 'ReadMe']), toWikiLinkSlug);+ expect(index.get('readme')).toBe('README');+ expect(index.size).toBe(1);+ });++ test('basename index keys the leaf segment so a bare name finds a subfolder doc', () => {+ const index = buildPagesByBasenameIndex(+ new Set(['andrew-data/project-x/analysis', 'notes/acp.daemon']),+ toWikiLinkSlug,+ );+ expect(index.get('analysis')).toBe('andrew-data/project-x/analysis');+ expect(index.get('acp-daemon')).toBe('notes/acp.daemon');+ });+});++describe('ambiguous-basename tie-break', () => {+ const COLLIDING = ['archive/summary', 'Notes/Summary'];++ test('two documents sharing a basename resolve to one winner, whatever the insertion order', () => {+ for (const order of [COLLIDING, [...COLLIDING].reverse()]) {+ const index = buildPagesByBasenameIndex(new Set(order), toWikiLinkSlug);+ expect(index.get('summary')).toBe('Notes/Summary');+ }+ });++ test('the winner is the code-unit minimum, so no runtime locale can change it', () => {+ // Code-unit order is fixed by the language spec — unlike collation, which+ // resolves against whatever locale the runtime defaults to. Deriving the+ // expected winner here with `<` rather than restating a literal is what+ // makes this a check on the ORDERING rather than on one hand-picked pair.+ const pages = new Set([+ 'archive/summary',+ 'Notes/Summary',+ 'z/foo',+ 'a/foo',+ 'M/foo',+ 'README',+ 'packages/server/README',+ ]);+ const index = buildPagesByBasenameIndex(pages, toWikiLinkSlug);++ for (const [key, winner] of index) {+ const bucket = [...pages].filter((page) => {+ const slash = page.lastIndexOf('/');+ return toWikiLinkSlug(slash === -1 ? page : page.slice(slash + 1)) === key;+ });+ const codeUnitMinimum = bucket.reduce((lowest, page) => (page < lowest ? page : lowest));+ expect(winner).toBe(codeUnitMinimum);+ }+ });++ test('the bare-set scan and the index agree on the winner for a mixed-case collision', () => {+ const pages = new Set(COLLIDING);+ const index: WikiLinkLookupIndex = {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ expect(resolveWikiLinkTargetDocName('summary', pages)).toBe('Notes/Summary');+ expect(resolveWikiLinkTargetDocName('summary', index)).toBe('Notes/Summary');+ });++ test('an ambiguous asset basename resolves to one winner too', () => {+ const assets = new Set(['archive/Report.pdf', 'Notes/report.pdf']);+ expect(resolveWikiLinkAssetTarget('report.pdf', assets)).toBe('Notes/report.pdf');+ });+});++describe('resolution chain boundaries', () => {+ test('a document whose filename contains a dot resolves by bare name', () => {+ const { pages, index } = makeFixtures();+ expect(resolveWikiLinkTargetDocName('acp.daemon', pages)).toBe('notes/acp.daemon');+ expect(resolveWikiLinkTargetDocName('acp.daemon', index)).toBe('notes/acp.daemon');+ });++ test('a path-shaped target does not fall back to a same-basename document', () => {+ const pages = new Set(['a/foo']);+ expect(resolveWikiLinkTargetDocName('sub/foo', pages)).toBeUndefined();+ });++ test('an asset that shares a name with a document resolves as the asset', () => {+ // Asset-first precedence. `meeting.pdf` exists both as a document (from a+ // file named `meeting.pdf.md`) and as a real asset; the asset wins, which+ // is the behaviour every wiki-embed in an existing project depends on.+ const pages = new Set(['meeting.pdf']);+ const assets = new Set(['meeting.pdf']);+ expect(resolveWikiLinkAssetTarget('meeting.pdf', assets)).toBe('meeting.pdf');+ expect(isResolvedWikiLinkTarget('meeting.pdf', pages, assets)).toBe(true);+ });+});++describe('composed wiki-link resolution', () => {+ // A project holding a dotted-name document, a real asset, a tracked+ // non-markdown file, and a plain document.+ const PROJECT = (() => {+ const pages = new Set(['notes/acp.daemon', 'v1.2 release', 'guides/install']);+ return {+ pages,+ assetPaths: new Set(['docs/public/Wide.png']),+ filePaths: new Set(['data/example.csv']),+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ } satisfies WikiLinkLookupIndex;+ })();++ test('the bare classifier reads a dotted document name as an asset', () => {+ // The defect, pinned. The classifier is a pure function of the target+ // string and cannot know the corpus — making it corpus-aware would break+ // the backlink index's mtime cache key, so promotion is composition's job+ // rather than a fix applied here.+ expect(classifyWikiLinkTarget('acp.daemon', null)).toEqual({+ kind: 'asset',+ url: 'acp.daemon',+ ext: 'daemon',+ });+ });++ test('a dotted target naming an existing document resolves as a document', () => {+ expect(resolveWikiLinkTarget('acp.daemon', null, PROJECT)).toEqual({+ kind: 'doc',+ docName: 'acp.daemon',+ anchor: null,+ });+ });++ test('promotion carries the anchor through', () => {+ expect(resolveWikiLinkTarget('acp.daemon', ' setup ', PROJECT)).toEqual({+ kind: 'doc',+ docName: 'acp.daemon',+ anchor: 'setup',+ });+ });++ test('a dotted target naming a document with a space and a version resolves too', () => {+ expect(resolveWikiLinkTarget('v1.2 release', null, PROJECT)).toEqual({+ kind: 'doc',+ docName: 'v1.2 release',+ anchor: null,+ });+ });++ test('a target naming a real asset stays an asset', () => {+ expect(resolveWikiLinkTarget('Wide.png', null, PROJECT)).toEqual({+ kind: 'asset',+ url: 'Wide.png',+ ext: 'png',+ });+ });++ test('a target naming a tracked non-markdown file stays an asset', () => {+ expect(resolveWikiLinkTarget('data/example.csv', null, PROJECT)).toEqual({+ kind: 'asset',+ url: 'data/example.csv',+ ext: 'csv',+ });+ });++ test('a target naming neither stays an asset, exactly as before', () => {+ expect(resolveWikiLinkTarget('missing.pdf', null, PROJECT)).toEqual({+ kind: 'asset',+ url: 'missing.pdf',+ ext: 'pdf',+ });+ });++ test('an asset wins over a document of the same name', () => {+ // Asset-first precedence. A project holding the asset `meeting.pdf` and a+ // file `meeting.pdf.md` (docName `meeting.pdf`) keeps pointing wiki-embeds+ // at the asset. Testing membership first would silently flip this, and the+ // flip would land on exactly the dotted-name projects this work targets.+ const pages = new Set(['meeting.pdf']);+ const lookup: WikiLinkLookupIndex = {+ pages,+ assetPaths: new Set(['meeting.pdf']),+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ expect(resolveWikiLinkTarget('meeting.pdf', null, lookup)).toEqual({+ kind: 'asset',+ url: 'meeting.pdf',+ ext: 'pdf',+ });+ });++ test('a tracked non-markdown file wins over a same-basename document', () => {+ // Both candidates are reachable only by basename, so this discriminates+ // whether the tracked-files set is consulted at all: drop it and+ // `archive/data.csv` (a doc from `archive/data.csv.md`) wins instead.+ const pages = new Set(['archive/data.csv']);+ const lookup: WikiLinkLookupIndex = {+ pages,+ filePaths: new Set(['notes/data.csv']),+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ expect(resolveWikiLinkTarget('data.csv', null, lookup)).toEqual({+ kind: 'asset',+ url: 'data.csv',+ ext: 'csv',+ });+ });++ test('a document-classified target passes through untouched', () => {+ expect(resolveWikiLinkTarget('guides/install', 'intro', PROJECT)).toEqual({+ kind: 'doc',+ docName: 'guides/install',+ anchor: 'intro',+ });+ // Including one that names nothing — composition must not start reporting+ // on unresolvable plain names.+ expect(resolveWikiLinkTarget('does-not-exist', null, PROJECT)).toEqual({+ kind: 'doc',+ docName: 'does-not-exist',+ anchor: null,+ });+ });++ test('external and empty targets pass through untouched', () => {+ expect(resolveWikiLinkTarget('https://example.com/a.pdf', 'x', PROJECT)).toEqual({+ kind: 'external',+ url: 'https://example.com/a.pdf#x',+ });+ expect(resolveWikiLinkTarget('', null, PROJECT)).toBeNull();+ expect(resolveWikiLinkTarget(' ', null, PROJECT)).toBeNull();+ });++ test('every target the classifier already resolves is returned unchanged', () => {+ // The promotion must be additive. Anything the classifier does not call an+ // asset, and every asset that really exists, must come back identical.+ for (const target of [+ 'guides/install',+ 'does-not-exist',+ 'Wide.png',+ 'data/example.csv',+ 'missing.pdf',+ 'https://example.com/x',+ '',+ ]) {+ expect(resolveWikiLinkTarget(target, null, PROJECT)).toEqual(+ classifyWikiLinkTarget(target, null),+ );+ }+ });++ test('resolution works from a bare Set with no precomputed index', () => {+ expect(resolveWikiLinkTarget('acp.daemon', null, new Set(['notes/acp.daemon']))).toEqual({+ kind: 'doc',+ docName: 'acp.daemon',+ anchor: null,+ });+ });+});diff --git a/packages/core/src/utils/wiki-link-resolve.ts b/packages/core/src/utils/wiki-link-resolve.tsnew file mode 100644index 000000000..96b24d192--- /dev/null+++ b/packages/core/src/utils/wiki-link-resolve.ts@@ -0,0 +1,447 @@+/**+ * Bare-name wiki-link resolution — the chain that answers "which doc (or+ * asset) does `[[target]]` name?".+ *+ * Lives in core because both the editor and the server must answer that+ * question the same way. When the chain lived only in the client, the server+ * fell back to exact-string existence and reported links dead that the editor+ * navigated fine.+ *+ * Pure string/Set/Map work — no DOM, no `node:*`, no browser globals. Core is+ * reachable from both the Vite bundle and the Node server, so it must stay+ * that way.+ *+ * NOT the same thing as `createBasenameIndex` in `path-resolve.ts`: that one+ * buckets raw-lowercase keys to arrays and tie-breaks relative to the source+ * document, over assets. This one keys slugs to a single winner over+ * documents. The two are deliberately separate — don't assume a shared+ * contract from the similar names.+ */++import {+ type AssetLinkTarget,+ classifyWikiLinkTarget,+ type DocLinkTarget,+ type ExternalLinkTarget,+} from './link-targets.ts';+import { toWikiLinkSlug } from './slug.ts';++/**+ * The lookup surface wiki-link resolution actually reads. Deliberately+ * narrower than the client's page-list snapshot (which also carries+ * `folderPaths` and `pageIcons`): that type stays in the app and satisfies+ * this structurally, while the server can assemble the same shape from its+ * admitted document set without importing anything client-side.+ */+export interface WikiLinkLookupIndex {+ readonly pages: ReadonlySet<string>;+ /** `toWikiLinkSlug(docName) → docName`. Build with {@link buildPagesBySlugIndex}. */+ readonly pagesBySlug: ReadonlyMap<string, string>;+ /** `toWikiLinkSlug(basename(docName)) → docName`. Build with {@link buildPagesByBasenameIndex}. */+ readonly pagesByBasename?: ReadonlyMap<string, string>;+ /** Referenced, renderable assets, contentDir-relative. */+ readonly assetPaths?: ReadonlySet<string>;+ /** Tracked non-markdown, non-asset files, contentDir-relative, extension included. */+ readonly filePaths?: ReadonlySet<string>;+}++/**+ * A bare `Set<string>` works for tests and non-hot-path callers — the helpers+ * derive the slug index on the fly (O(n) per call with a slug computation+ * each). A {@link WikiLinkLookupIndex} carries precomputed maps for O(1)+ * lookup. Both branches must agree on every input; the shared tie-break+ * comparator is what keeps them in sync.+ */+export type WikiLinkPagesInput = ReadonlySet<string> | WikiLinkLookupIndex;++function isLookupIndex(input: WikiLinkPagesInput): input is WikiLinkLookupIndex {+ return 'pagesBySlug' in input;+}++function getPagesSet(input: WikiLinkPagesInput): ReadonlySet<string> {+ return isLookupIndex(input) ? input.pages : input;+}++function getAssetPathsSet(input: WikiLinkPagesInput, assetPaths?: ReadonlySet<string>) {+ return isLookupIndex(input) ? (input.assetPaths ?? new Set<string>()) : (assetPaths ?? new Set());+}++/**+ * The file-paths set (tracked non-markdown, non-asset files). When the input+ * is an index, pull the optional set off it; bare-Set callers can pass it as+ * an explicit override. Returns an empty Set on absence so the+ * membership-check sites never need to nil-guard.+ */+function getFilePathsSet(input: WikiLinkPagesInput, filePaths?: ReadonlySet<string>) {+ return isLookupIndex(input) ? (input.filePaths ?? new Set<string>()) : (filePaths ?? new Set());+}++/**+ * Tie-break comparator for ambiguous basenames. Every index builder and every+ * bare-Set scan fallback sorts through this one function, so the fast path and+ * the slow path always name the same winner.+ *+ * Code-unit order, NOT `localeCompare`. `localeCompare` with no locale+ * argument resolves against the runtime's default locale, so the client and+ * the server can disagree about which document a bare name names — and two+ * clients on different machines can disagree with each other. Code-unit order+ * is fixed by the language spec, so every runtime agrees.+ *+ * This changes the winner for mixed-case collisions. Locale collation sorts+ * case-insensitively (`archive/summary` before `Notes/Summary`); code-unit+ * order puts every uppercase letter before every lowercase one, so+ * `Notes/Summary` now wins. The previous winner was never guaranteed in the+ * first place, which is the reason for the pin.+ */+function compareDocNames(a: string, b: string): number {+ if (a < b) return -1;+ if (a > b) return 1;+ return 0;+}++/**+ * Build the slug-keyed index from a pages set. First-wins on slug collision+ * (Map insertion order preserved; iteration order of a Set follows insertion+ * order per ES spec). Takes the slug function as a parameter so callers can+ * thread the same slugger the resolver uses.+ *+ * Tie-break is deliberately insertion-order, not alphabetical — the slug+ * key already encodes the full docName, so collisions are rare and+ * insertion-order matches the Set's iteration semantics. The sibling+ * {@link buildPagesByBasenameIndex} sorts before insertion because basename+ * collisions across folders are expected.+ */+export function buildPagesBySlugIndex(+ pages: ReadonlySet<string>,+ slugFn: (text: string) => string,+): ReadonlyMap<string, string> {+ const index = new Map<string, string>();+ for (const page of pages) {+ const key = slugFn(page);+ if (key && !index.has(key)) index.set(key, page);+ }+ return index;+}++/**+ * Build the basename-keyed index from a pages set. Keys by the slug of each+ * docName's leaf segment (the part after the last `/`). Sorts input before+ * insertion so first-wins on basename collision becomes+ * lowest-by-{@link compareDocNames} — matching the tie-break in+ * {@link resolveWikiLinkAssetTarget} for assets.+ *+ * The navigation resolver reads this index rather than tie-breaking itself,+ * so the winner picked here is the one the click destination opens.+ */+export function buildPagesByBasenameIndex(+ pages: ReadonlySet<string>,+ slugFn: (text: string) => string,+): ReadonlyMap<string, string> {+ const index = new Map<string, string>();+ const sorted = [...pages].sort(compareDocNames);+ for (const page of sorted) {+ const slash = page.lastIndexOf('/');+ const basename = slash === -1 ? page : page.slice(slash + 1);+ const key = slugFn(basename);+ if (key && !index.has(key)) index.set(key, page);+ }+ return index;+}++/**+ * Look up a target by slug against the pages set / index. Returns the+ * original docName on match, or undefined when no entry's slug matches+ * the target's slug.+ *+ * Unresolved-link attrs store the lowercased slug as the wikiLink target,+ * while the page cache keeps case-preserved + non-slug-form docNames+ * (`README`, `BA_for_Depression_Research`). Without a slug-based fallback,+ * `pages.has('readme')` and `pages.has('ba-for-depression-research')` never+ * match, so every dropped `.md` file + hand-typed `[[README]]` shows+ * "Page not found".+ *+ * `targetSlug` is the slug of `target` — if target is already in slug form,+ * it equals the input. Both branches use the slug as the lookup key, so+ * `README` and `readme` and `Readme` all resolve to the same entry.+ */+function slugLookup(target: string, input: WikiLinkPagesInput): string | undefined {+ const targetSlug = toWikiLinkSlug(target);+ if (!targetSlug) return undefined;+ if (isLookupIndex(input)) {+ return input.pagesBySlug.get(targetSlug);+ }+ // Bare Set — O(n) scan with slug computation per entry. Acceptable for+ // PropPanel / non-hot-path callers (tests, one-off resolutions).+ for (const page of input) {+ if (toWikiLinkSlug(page) === targetSlug) return page;+ }+ return undefined;+}++/**+ * Look up a bare-name target by basename across the pages set / index.+ * Returns the original docName on match, or undefined when no entry's+ * basename slug matches. `[[analysis]]` resolves when+ * `andrew-data/.../analysis.md` exists, so the chip's resolved state and the+ * navigation destination agree.+ *+ * Targets containing `/` skip this branch (explicit-path intent —+ * `[[bar/foo]]` should not silently rewrite to `baz/foo`).+ *+ * Both the index fast path and the bare-Set scan below tie-break through+ * {@link compareDocNames}, so the two branches resolve to the same docName+ * for the same input.+ */+function basenameLookup(target: string, input: WikiLinkPagesInput): string | undefined {+ if (target.includes('/')) return undefined;+ const targetSlug = toWikiLinkSlug(target);+ if (!targetSlug) return undefined;+ if (isLookupIndex(input)) {+ return input.pagesByBasename?.get(targetSlug);+ }+ let bestMatch: string | undefined;+ for (const page of input) {+ const slash = page.lastIndexOf('/');+ const basename = slash === -1 ? page : page.slice(slash + 1);+ if (toWikiLinkSlug(basename) !== targetSlug) continue;+ if (bestMatch === undefined || compareDocNames(page, bestMatch) < 0) bestMatch = page;+ }+ return bestMatch;+}++export function getWikiLinkResolutionCandidates(target: string): string[] {+ const trimmed = target.trim();+ if (!trimmed) return [];+ const slug = toWikiLinkSlug(trimmed);+ return slug.length > 0 && slug !== trimmed ? [slug] : [];+}++/**+ * Resolve a wiki-link `target` attribute to the canonical docName, or+ * `undefined` when no page matches.+ *+ * Resolution chain — first match wins, intentionally mirrors+ * `resolveNavigationTarget` so the icon surface and the click destination+ * stay in sync:+ * 1. Direct membership: `pages.has(target)`.+ * 2. Slug match — handles dropped-file lowercased slugs (`readme` →+ * `README`) and slug-form unresolved-link targets.+ * 3. Candidate fallback: {@link getWikiLinkResolutionCandidates} against+ * `pages`.+ * 4. Canonical folder-index: `${target}/index` in `pages`.+ * 5. Legacy folder note: `${target}/${target}` in `pages`.+ * 6. Basename fallback: bare-name target → same-leaf file in a subfolder.+ *+ * Steps 4-5 ensure the chip resolves a folder-target wiki-link to the+ * same docName the click destination opens. Without them, a `[[reports]]`+ * chip with both `reports/index` AND `other/reports` existing would resolve+ * to `other/reports` (basename) for the icon while navigation opens+ * `reports/index` — a visible mismatch.+ *+ * Dots in the target are not special here: `[[acp.daemon]]` reaches step 6+ * and finds `notes/acp.daemon` like any other bare name. What breaks dotted+ * targets is the classification gate UPSTREAM of this chain, not the chain.+ */+export function resolveWikiLinkTargetDocName(+ target: string,+ input: WikiLinkPagesInput,+): string | undefined {+ const trimmed = target.trim();+ if (!trimmed) return undefined;+ const pages = getPagesSet(input);+ if (pages.has(trimmed)) return trimmed;+ const viaSlug = slugLookup(trimmed, input);+ if (viaSlug) return viaSlug;+ for (const candidate of getWikiLinkResolutionCandidates(trimmed)) {+ if (pages.has(candidate)) return candidate;+ }+ const folderIndexDocName = resolveFolderIndexDocName(trimmed, pages);+ if (folderIndexDocName) return folderIndexDocName;+ return basenameLookup(trimmed, input);+}++/**+ * Folder-target → docName. Mirrors the folder-index branches in+ * `resolveNavigationTarget`: prefer a canonical `${target}/index` doc, fall+ * back to a legacy `${target}/${leaf}` doc. Path-shaped targets (`foo/bar`)+ * keep this branch active so `[[foo/bar]]` resolves to `foo/bar/index` when+ * the subfolder index exists.+ */+function resolveFolderIndexDocName(target: string, pages: ReadonlySet<string>): string | undefined {+ const canonical = `${target}/index`;+ if (pages.has(canonical)) return canonical;+ const slashIndex = target.lastIndexOf('/');+ const leaf = slashIndex === -1 ? target : target.slice(slashIndex + 1);+ const legacy = leaf ? `${target}/${leaf}` : null;+ if (legacy && pages.has(legacy)) return legacy;+ return undefined;+}++function normalizeAssetTarget(target: string): string {+ const trimmed = target.trim();+ const withoutHash = (trimmed.split('#')[0] ?? '').trim();+ const withoutQuery = (withoutHash.split('?')[0] ?? '').trim();+ return withoutQuery.startsWith('/') ? withoutQuery.slice(1) : withoutQuery;+}++export function resolveWikiLinkAssetTarget(+ target: string,+ assetPaths: ReadonlySet<string>,+ /**+ * Optional tracked-files set. When provided, a wiki-link to any tracked+ * non-markdown file resolves — not just the renderable-asset subset. The+ * exact + case-insensitive + basename branches all extend uniformly so the+ * resolution shape stays identical regardless of which partition wins.+ */+ filePaths?: ReadonlySet<string>,+): string | null {+ const normalized = normalizeAssetTarget(target);+ if (!normalized) return null;++ const lowerTarget = normalized.toLowerCase();+ // The two partitions never overlap in practice (a renderable asset is by+ // construction not in the all-files-only set — the document-list handler+ // suppresses `kind:'file'` for any path already emitted as `kind:'asset'`),+ // so check them independently. Asset wins on overlap because the renderable+ // set carries richer metadata downstream.+ const partitions: ReadonlyArray<ReadonlySet<string>> = filePaths+ ? [assetPaths, filePaths]+ : [assetPaths];++ for (const partition of partitions) {+ if (partition.has(normalized)) return normalized;+ for (const path of partition) {+ if (path.toLowerCase() === lowerTarget) return path;+ }+ }++ if (normalized.includes('/')) return null;+ const matches: string[] = [];+ for (const partition of partitions) {+ for (const path of partition) {+ const slash = path.lastIndexOf('/');+ const basename = slash === -1 ? path : path.slice(slash + 1);+ if (basename.toLowerCase() === lowerTarget) matches.push(path);+ }+ }+ if (matches.length === 0) return null;+ return matches.sort(compareDocNames)[0] ?? null;+}++/**+ * Whether a wiki-link target names anything that exists.+ *+ * Asset resolution runs FIRST and document membership only on its miss. That+ * order is the status quo and is load-bearing: flipping it would silently+ * change which thing `[[meeting.pdf]]` names for a project holding both an+ * asset `meeting.pdf` and a document `meeting.pdf.md`.+ */+export function isResolvedWikiLinkTarget(+ target: string,+ pages: WikiLinkPagesInput,+ assetPaths?: ReadonlySet<string>,+ /**+ * Tracked-files set forwarded into {@link resolveWikiLinkAssetTarget}. Lets+ * a wiki-link to an existing non-markdown file (e.g. `[[data/example.csv]]`)+ * resolve instead of rendering dead. When the input is an index, the set is+ * pulled off it; this explicit override is for bare-Set callers.+ */+ filePaths?: ReadonlySet<string>,+): boolean {+ const trimmed = target.trim();+ if (!trimmed) return false;+ if (+ resolveWikiLinkAssetTarget(+ trimmed,+ getAssetPathsSet(pages, assetPaths),+ getFilePathsSet(pages, filePaths),+ )+ ) {+ return true;+ }++ const pagesSet = getPagesSet(pages);+ if (pagesSet.has(trimmed)) return true;++ if (getWikiLinkResolutionCandidates(trimmed).some((candidate) => pagesSet.has(candidate))) {+ return true;+ }++ // Slug-based fallback. Handles dropped `.md` (target='readme' from slug)+ // against case-preserved cache entry (`README`) AND+ // underscore/space/punctuation entries (`BA_for_Depression_Research` → slug+ // `ba-for-depression-research`). First-wins on slug collision — if both+ // `README` and `ReadMe` exist (different case, same slug), the+ // insertion-order-first entry wins.+ if (slugLookup(trimmed, pages) !== undefined) return true;++ // Folder-index parity with `resolveNavigationTarget` — a `[[reports]]`+ // chip is resolved when a `reports/index` (or legacy `reports/reports`)+ // doc exists, matching the navigation outcome.+ if (resolveFolderIndexDocName(trimmed, pagesSet)) return true;++ // Basename fallback — bare-name target matches a same-basename file in+ // a subfolder. Mirrors `resolveNavigationTarget` so the chip's resolved+ // class matches the navigation outcome.+ return basenameLookup(trimmed, pages) !== undefined;+}++/**+ * Decide what a wiki-link target actually names, given the corpus.+ *+ * THIS is the function every wiki-link surface should call — never+ * `classifyWikiLinkTarget` directly. The classifier answers a syntactic+ * question ("does this string end in something extension-shaped?"), so a+ * document named `acp.daemon.md` and referenced as `[[acp.daemon]]` reads+ * `daemon` as a file extension: the target goes to the asset viewer, 404s, and+ * the resolution chain above is never consulted. Only this function answers+ * the real question — does the thing the target names exist, and as what?+ * Authoring that rule per-surface is what let the client and the server drift+ * apart to begin with, so it lives here once and surfaces only apply it.+ *+ * Promotion is decided by index MEMBERSHIP, never by a string heuristic — no+ * extension allowlist, no "does this look like a real extension" test. A+ * heuristic cannot distinguish `[[x.pdf]]` from `![[x.pdf]]` (the extractor+ * drops the embed marker before classification), so it would capture every+ * embed in the corpus. Membership captures only names that collide with a real+ * document.+ *+ * Precedence is ASSET-FIRST, which preserves today's behaviour exactly: a+ * target that resolves to a real asset stays an asset even when a document of+ * the same name exists. Testing membership first would silently flip which+ * thing `[[meeting.pdf]]` names for any project holding both `meeting.pdf` and+ * `meeting.pdf.md` — and a `.md` suffix strip is exactly how that docName+ * arises.+ *+ * A target matching neither stays an asset, which is the deliberate+ * unknown-file-type routing; changing it here would re-render every broken+ * link.+ *+ * `docName` on a promoted target is the RAW target, matching what the+ * classifier's own document branch returns — call sites run their own+ * resolution over it, so `[[acp.daemon]]` and `[[acp daemon]]` travel the same+ * path from here on.+ */+export function resolveWikiLinkTarget(+ target: string,+ anchor: string | null,+ lookup: WikiLinkPagesInput,+): DocLinkTarget | ExternalLinkTarget | AssetLinkTarget | null {+ const classified = classifyWikiLinkTarget(target, anchor);+ if (classified === null || classified.kind !== 'asset') return classified;++ const asset = resolveWikiLinkAssetTarget(+ classified.url,+ getAssetPathsSet(lookup),+ getFilePathsSet(lookup),+ );+ if (asset !== null) return classified;++ if (resolveWikiLinkTargetDocName(target, lookup) === undefined) return classified;++ return {+ kind: 'doc',+ docName: target.trim(),+ anchor: anchor?.trim() || null,+ };+}diff --git a/packages/server/assets/skills/project/references/linking.md b/packages/server/assets/skills/project/references/linking.mdindex 89190ccf2..e52b6355c 100644--- a/packages/server/assets/skills/project/references/linking.md+++ b/packages/server/assets/skills/project/references/linking.md@@ -11,6 +11,6 @@- **Never use HTML anchors** (`<a href="...">`). Markdown link syntax only.- **`brokenLinks` on the write/edit response is your primary check — read it before walking away.** Every `write`/`edit` returns `brokenLinks` in the SAME payload: `[]` means every outbound link resolves; a populated list names each broken `href` with its `resolvedTo` + `reason` (`no-such-doc` = resolved to a doc that doesn't exist; `no-such-file` = resolved to a linked asset / source file that isn't on disk at that path; `unresolvable` = the path escapes the content root, usually one `../` too many). This validates **every** local link, not just doc links: a wrong-depth `[src](../../foo.py)` to a source file is caught too. It is report-only — the write landed regardless; fix or remove every one in a follow-up `edit`.- **`links({ kind: "dead" })` is the authoritative end-state audit.** For a corpus-wide sweep across many docs: `links({ kind: "dead", sourceDocuments: ["your/doc"] })`. Companion `links` kinds: `backlinks` (incoming), `forward` (outgoing), `orphans` (no incoming), `hubs` (high-incoming), `suggest` (untextualized mentions worth linking).-- **The editor's red-underline visual lies.** Its dead-link detection tolerates slug-fallback (e.g., `foo` may appear resolved because `foo.md` exists at root). `links({ kind: "dead" })` is strict-exact — trust the tool, not the visual.+- **The tool and the editor agree.** Both resolve a bare name the same way — exact, then slug, then folder index, then basename — so a link that opens when you click it is never reported dead, and a link reported dead is genuinely unresolvable. A target that names an asset, or names nothing at all, stays silent rather than being reported as a broken doc link.**Note on wiki-link syntax (`[[Page]]`):** the parser still handles it for legacy content, but it's NO LONGER the recommended default. Write new content with standard markdown links per above. Seed-pack templates (`ok seed --pack <name>`) may still emit `[[Page]]` placeholders inside template body text — those are legacy. When you instantiate a seed-pack template, replace the legacy placeholders with standard markdown links during the `{shape}`-fill pass.diff --git a/packages/server/src/api-backlinks.test.ts b/packages/server/src/api-backlinks.test.tsindex 7b843214c..dc957c999 100644--- a/packages/server/src/api-backlinks.test.ts+++ b/packages/server/src/api-backlinks.test.ts@@ -462,6 +462,46 @@ describe('graph endpoints', () => {}});+ test('the dead-link endpoint stays silent for a dotted-name doc link and an asset embed', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-dead-links-dotted-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'notes'), { recursive: true });+ try {+ writeFileSync(+ join(contentDir, 'alpha.md'),+ '# Alpha\n\nSee [[acp.daemon]] and ![[diagram.png]] and [[ghost]].\n',+ 'utf-8',+ );+ writeFileSync(join(contentDir, 'notes', 'acp.daemon.md'), '# Daemon\n\nBody.\n', 'utf-8');++ const backlinkIndex = new BacklinkIndex({ projectDir, contentDir });+ await backlinkIndex.rebuildFromDisk();++ const fileIndex = new Map<string, FileIndexEntry>(+ ['alpha', 'notes/acp.daemon'].map((docName) => [+ docName,+ {+ size: 10,+ modified: new Date(0).toISOString(),+ canonicalPath: '',+ inode: 0,+ aliases: [],+ },+ ]),+ );++ const dead = JSON.parse(+ (await callRoute(contentDir, '/api/dead-links', fileIndex, backlinkIndex)).body,+ ) as { deadLinks: Array<{ target: string }> };++ // The dotted doc link resolves and the asset embed names no document, so+ // neither is reported — while the genuinely-missing target still is.+ expect(dead.deadLinks.map((entry) => entry.target)).toEqual(['ghost']);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('returns 503 when the backlink index is unavailable', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-dead-links-unavailable-'));const contentDir = join(projectDir, 'content');diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex bb8980da3..e2a2d9113 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -483,6 +483,204 @@ describe('BacklinkIndex', () => {}});+ test('a wikilink to a dotted-filename document is recorded and is not reported dead', async () => {+ // `acp.daemon` reads as a file named `acp` with extension `daemon` to the+ // syntactic classifier, so index-time classification cannot tell it from an+ // asset. The raw target is recorded regardless and the corpus decides at+ // query time.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dotted-doc-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'notes'), { recursive: true });+ try {+ writeFileSync(join(contentDir, 'index.md'), '# Index\n\nSee [[acp.daemon]].\n', 'utf-8');+ writeFileSync(join(contentDir, 'notes', 'acp.daemon.md'), '# Daemon\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getForwardLinks('index')).toContain('acp.daemon');+ expect(index.getDeadLinks(['index', 'notes/acp.daemon'])).toEqual([]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('an undecided raw target stays undecided across a cache save/load', async () => {+ // The raw flag is what keeps an asset embed out of the dead-link report,+ // and it is carried in the snapshot rather than recomputed. If it were+ // dropped on the way to disk the report would look right until the first+ // restart, then fill with false positives on every vault that embeds an+ // asset — a failure that unit-level checks of the live index cannot see.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-raw-roundtrip-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'notes'), { recursive: true });+ try {+ writeFileSync(+ join(contentDir, 'index.md'),+ '# Index\n\nSee [[acp.daemon]] and ![[diagram.png]].\n',+ 'utf-8',+ );+ writeFileSync(join(contentDir, 'notes', 'acp.daemon.md'), '# Daemon\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();+ await index.saveToDisk();++ const reloaded = new BacklinkIndex({ projectDir, contentDir });+ expect(await reloaded.loadFromDisk()).toBe(true);+ expect(reloaded.getDeadLinks(['index', 'notes/acp.daemon'])).toEqual([]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a bare wikilink the editor reaches by basename is not reported dead', async () => {+ // The dotted case above is decided by the raw-target filter. This is the+ // undotted one, which classifies as a document at index time and so is+ // never flagged raw — the audit has to resolve it through the same chain+ // the editor uses, or it reports a link the reader can click and reach.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-bare-basename-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'research'), { recursive: true });+ try {+ writeFileSync(join(contentDir, 'index.md'), '# Index\n\nSee [[analysis]].\n', 'utf-8');+ writeFileSync(join(contentDir, 'research', 'analysis.md'), '# A\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getDeadLinks(['index', 'research/analysis'])).toEqual([]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a bare wikilink naming no document is still reported dead', async () => {+ // The guard rail for the test above: leniency comes from membership, so a+ // target the corpus cannot resolve stays reported. A relaxation that+ // silenced this would trade a false positive for a silent broken link.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-bare-missing-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'research'), { recursive: true });+ try {+ writeFileSync(join(contentDir, 'index.md'), '# Index\n\nSee [[nowhere]].\n', 'utf-8');+ writeFileSync(join(contentDir, 'research', 'analysis.md'), '# A\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getDeadLinks(['index', 'research/analysis']).map((e) => e.target)).toEqual([+ 'nowhere',+ ]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('the neighborhood view admits the same documents as the whole graph', async () => {+ // Recording wiki targets verbatim puts asset embeds in the forward index,+ // so every reader of it has to apply the same admission or the two graph+ // views disagree about which documents exist — the neighborhood drawing a+ // node for `diagram.png` that the whole graph omits.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-neighborhood-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'notes'), { recursive: true });+ try {+ writeFileSync(+ join(contentDir, 'index.md'),+ '# Index\n\n![[diagram.png]] and [[acp.daemon]].\n',+ 'utf-8',+ );+ writeFileSync(join(contentDir, 'notes', 'acp.daemon.md'), '# Daemon\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ const neighborhood = index.getLinkGraphNeighborhood('index', 2).nodes.map((n) => n.id);+ const whole = index.getLinkGraph().nodes.map((n) => n.id);++ // The embed is a document in neither view.+ expect(neighborhood).not.toContain('diagram.png');+ expect(whole).not.toContain('diagram.png');+ // The dotted document is present in both.+ expect(neighborhood).toContain('acp.daemon');+ expect(whole).toContain('acp.daemon');+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a markdown href is not basename-resolved by the dead-link audit', async () => {+ // Only wiki targets get the chain. A markdown href is a path, so a wrong+ // one must stay reported even when some other folder holds that basename —+ // otherwise the leniency above would start hiding real mistakes.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-md-exact-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'research'), { recursive: true });+ try {+ writeFileSync(join(contentDir, 'index.md'), '# Index\n\n[A](./analysis.md)\n', 'utf-8');+ writeFileSync(join(contentDir, 'research', 'analysis.md'), '# A\n\nBody.\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getDeadLinks(['index', 'research/analysis']).map((e) => e.target)).toEqual([+ 'analysis',+ ]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a wiki asset embed is neither reported dead nor minted as a graph node', async () => {+ // Recording every wiki target verbatim puts asset embeds into the graph for+ // the first time. Without suppression every vault that embeds an asset+ // would fill with dead links and phantom documents.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-asset-embed-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ writeFileSync(+ join(contentDir, 'notes.md'),+ '# Notes\n\n![[diagram.png]]\n\nSee [[report.pdf]].\n',+ 'utf-8',+ );++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getDeadLinks(['notes'])).toEqual([]);++ const graph = index.getLinkGraph();+ expect(graph.nodes.map((node) => node.id)).toEqual(['notes']);+ expect(graph.links).toEqual([]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('a dotted target becomes a graph node once its document is indexed', () => {+ // The lookup query-time resolution reads is cached against the graph's+ // epoch; a stale cache would leave this target suppressed forever.+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dotted-late-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ const index = new BacklinkIndex({ projectDir, contentDir });+ index.updateDocument('index', [+ { target: 'acp.daemon', anchor: null, snippet: null, rawWikiTarget: true },+ ]);++ expect(index.getLinkGraph().nodes.map((node) => node.id)).toEqual(['index']);++ index.updateDocument('notes/acp.daemon', []);++ expect(index.getLinkGraph().nodes.map((node) => node.id)).toContain('acp.daemon');+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('getIndexedDocNames returns one entry per indexed doc and never a referenced-but-missing target', () => {// The additive existence oracle unions into `collectAdmittedDocNames`.// A doc whose body was indexed is a forward node (even with zero links); a@@ -1881,6 +2079,62 @@ describe('computeBrokenOutboundLinks', () => {>([{ href: '[[people/bob-jones]]', resolvedTo: 'people/bob-jones', reason: 'no-such-doc' }]);});+ test('a bare-name wiki-link resolving to a subfolder doc is not broken; an unresolvable one is', () => {+ // The editor navigates `[[analysis]]` to `research/analysis` by basename,+ // so reporting it broken on write contradicts what the reader sees. The+ // ghost in the same body is the control: leniency must not silence a name+ // that resolves to nothing.+ const md = 'See [[analysis]] and [[nowhere]].';+ const admitted = new Set(['research/analysis', 'notes/a']);+ expect(computeBrokenOutboundLinks(md, 'notes/a', admitted)).toEqual<BrokenOutboundLink[]>([+ { href: '[[nowhere]]', resolvedTo: 'nowhere', reason: 'no-such-doc' },+ ]);+ });++ test('a dotted-filename document target is not reported broken', () => {+ // `acp.daemon` reads as extension `daemon` to the classifier, so the strict+ // check never saw it. Now it promotes to a doc on membership — and the+ // existence question has to be asked of the resolution chain, not of the+ // raw key: `notes/acp.daemon` is what exists, `acp.daemon` is what's written.+ const md = 'See [[acp.daemon]] here.';+ const admitted = new Set(['notes/acp.daemon', 'notes/a']);+ expect(computeBrokenOutboundLinks(md, 'notes/a', admitted)).toEqual([]);+ });++ test('wiki asset embeds and dotted non-doc targets produce no broken links', () => {+ const md = [+ 'Embed ![[diagram.png]] and ![[chart.v2.png]].',+ 'Link [[meeting.pdf]] and [[report.v3.xlsx]].',+ ].join('\n');+ // `meeting.pdf` is the docName a `meeting.pdf.md` file produces, so it+ // promotes and resolves; the other three name nothing. Neither class may+ // enter the response — minting a broken link for an embed that resolves to+ // nothing would fire on every vault that embeds assets.+ const admitted = new Set(['meeting.pdf', 'notes/a']);+ expect(computeBrokenOutboundLinks(md, 'notes/a', admitted)).toEqual([]);+ });++ test('resolving many wiki links scans the corpus a bounded number of times', () => {+ // The slug and basename maps are corpus-wide. Building them per link would+ // be correct and quadratic, and every other test here would still pass.+ class ScanCountingSet extends Set<string> {+ scans = 0;+ [Symbol.iterator](): SetIterator<string> {+ this.scans += 1;+ return super[Symbol.iterator]();+ }+ }+ const admitted = new ScanCountingSet(['research/analysis', 'archive/summary', 'notes/a']);+ const md = Array.from({ length: 12 }, (_, i) => `[[analysis]] [[summary]] [[gone-${i}]]`).join(+ '\n',+ );++ const broken = computeBrokenOutboundLinks(md, 'notes/a', admitted);++ expect(broken).toHaveLength(12);+ expect(admitted.scans).toBeLessThanOrEqual(2);+ });+test('skips external URLs, image embeds, and anchors; file links skipped when no oracle is passed', () => {const md = ['Web [site](https://example.com/missing).',diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex d8c72c544..18f63d65a 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -3,6 +3,8 @@ import { readdir, readFile, stat, writeFile } from 'node:fs/promises';import { dirname, join, relative, resolve } from 'node:path';import {type BrokenLinkReason,+ buildPagesByBasenameIndex,+ buildPagesBySlugIndex,classifyMarkdownHref,classifyWikiLinkTarget,extractSkillRefs,@@ -16,8 +18,12 @@ import {resolveAssetProjectPath,resolveInternalHref,resolveSkillBundleWikiTarget,+ resolveWikiLinkTarget,+ resolveWikiLinkTargetDocName,skillLiveDocName,stripFrontmatter,+ toWikiLinkSlug,+ type WikiLinkLookupIndex,} from '@inkeep/open-knowledge-core';import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';import { getLocalDir } from './config/paths.ts';@@ -36,6 +42,7 @@ interface InlineWikiLinkOccurrence {anchor: string | null;start: number;end: number;+ rawWikiTarget?: boolean;}/**@@ -100,6 +107,23 @@ export interface ExtractedWikiLink {* and leading list/heading prefixes are collapsed before offsets are taken).*/column?: number;+ /**+ * The target was recorded verbatim because index time could not decide what+ * it names. The syntactic classifier reads anything ending in a dot-suffix as+ * a file (`acp.daemon` = an `acp` with extension `daemon`), which is right for+ * `[[diagram.png]]` and wrong for a document literally named `acp.daemon.md`.+ * Telling them apart needs the corpus, and the corpus is only complete at+ * query time — deciding here would make the answer depend on file ordering and+ * would let the mtime-keyed cache persist a stale verdict across restarts.+ *+ * Consumers must treat such a target as UNDECIDED, never as a missing+ * document: it is resolved against the document set at query time, and a+ * target that resolves to nothing stays silent rather than being reported+ * broken. Absent/false means the target is already a resolved docName (a+ * markdown href, or a wiki target the classifier called a document), which+ * keeps its existing report-when-missing behaviour.+ */+ rawWikiTarget?: boolean;}interface ExtractedExternalLink {@@ -174,6 +198,8 @@ interface BackwardLinkMeta {sourceForm?: 'wiki' | 'markdown';line?: number;column?: number;+ /** See {@link ExtractedWikiLink.rawWikiTarget}. */+ rawWikiTarget?: boolean;}interface BranchGraphState {@@ -187,6 +213,19 @@ interface BranchGraphState {* so an edge appears the moment the referenced skill is indexed, without* re-parsing the referencing doc. */skillRefs: Map<string, Set<string>>;+ /**+ * Bumped on every `forward` mutation, which is a superset of the key-set+ * changes the cache below actually depends on — re-indexing a doc whose+ * links changed but whose name did not still invalidates. Conservative in+ * the safe direction: it rebuilds more often than strictly needed, never+ * less. The derived slug/basename+ * lookup query-time resolution reads is O(docs) with a slug computation per+ * doc, so it is cached against this counter rather than rebuilt per query —+ * rebuilding it inside the per-target scan would make that scan O(docs ×+ * targets). Not persisted: a reloaded snapshot is a fresh state object, and+ * the cache is keyed by object identity.+ */+ epoch: number;}/**@@ -202,7 +241,7 @@ const SNAPSHOT_VERSION = 1;interface SerializedBranchGraphState {version?: number;- backward: Record<string, Array<BacklinkEntry>>;+ backward: Record<string, Array<BacklinkEntry & { rawWikiTarget?: boolean }>>;forward: Record<string, string[]>;externalForward: Record<string,@@ -238,9 +277,25 @@ function createEmptyState(): BranchGraphState {externalForward: new Map(),externalBackward: new Map(),skillRefs: new Map(),+ epoch: 0,};}+/**+ * Whether every source that references `target` recorded it as an undecided raw+ * wiki target (see {@link ExtractedWikiLink.rawWikiTarget}). A target reached by+ * even one resolved docName — a markdown href, or a wiki target the classifier+ * called a document — is decided, and keeps its report-when-missing behaviour.+ */+function isUndecidedTarget(state: BranchGraphState, target: string): boolean {+ const sources = state.backward.get(target);+ if (!sources || sources.size === 0) return false;+ for (const meta of sources.values()) {+ if (meta.rawWikiTarget !== true) return false;+ }+ return true;+}+/*** Scope-uniform parse of a skill bundle doc (PROJECT content doc OR GLOBAL* managed-artifact doc) into the three fields the structural-edge logic needs:@@ -295,6 +350,9 @@ function mergeLinkMeta(sourceForm: existing.sourceForm ?? next.sourceForm,line: positioned.line,column: positioned.column,+ // One decided occurrence settles the target for this source: a doc named+ // outright is a doc no matter how many undecided occurrences sit beside it.+ rawWikiTarget: existing.rawWikiTarget === true && next.rawWikiTarget === true,};}@@ -462,6 +520,17 @@ function extractWikiLinksFromLine(start,end: start + label.length,});+ } else if (classified?.kind === 'asset') {+ // Undecidable here — see `ExtractedWikiLink.rawWikiTarget`. Record the+ // target verbatim so a document whose name carries a dot stops being+ // invisible to link reporting, and let the query side resolve it.+ occurrences.push({+ target: classified.url,+ anchor: wikiLink.anchor?.trim() || null,+ start,+ end: start + label.length,+ rawWikiTarget: true,+ });}idx = wikiLink.nextIndex;continue;@@ -815,7 +884,8 @@ export function extractWikiLinksFromMarkdown(} else {const extracted = extractWikiLinksFromLine(line, sourceDocName);links.push(- ...extracted.occurrences.map(({ target, anchor, start, end }) => ({+ ...extracted.occurrences.map(({ target, anchor, start, end, rawWikiTarget }) => ({+ rawWikiTarget,target,anchor,snippet: snippetAround(extracted.text, start, end),@@ -936,9 +1006,21 @@ export interface BrokenOutboundLink {* not by relative path, so the depth footgun doesn't apply and the path-pure* resolver here can't answer them.*+ * Wiki-link doc targets go through the shared composed resolution, so what+ * counts as existing here is what the editor actually navigates to. The report+ * this retracts is the bare name: `[[analysis]]` reaching `research/analysis`+ * by basename was flagged broken while the reader clicked it and arrived. A+ * dotted name now reaches that same chain instead of being read as a file+ * extension, though its verdict here is unchanged either way — a name that+ * promotes has by definition resolved, and one that doesn't stays silent like+ * any other asset. That asymmetry is the safety property: this can only ever+ * retract a report, never add one.+ ** Marginal cost is one doc's extraction + one `Set.has` (docs) or one- * `fileExists` call (files) per distinct outbound link — no corpus scan.- * Duplicate raw hrefs collapse to a single entry.+ * `fileExists` call (files) per distinct outbound link. A wiki target that+ * misses on exact name additionally builds the slug and basename maps — once+ * per call, memoized, never per link. Duplicate raw hrefs collapse to a single+ * entry.** @param markdown the full just-written source (frontmatter is stripped here)* @param sourceDocName the doc being written (relative hrefs resolve against its dir)@@ -1009,15 +1091,43 @@ export function computeBrokenOutboundLinks(// External URLs aren't a local link target — not our concern.};+ // Built on first read, not per call: the two maps cost a pass over the+ // admitted corpus each, and a body with no wiki links — or whose wiki links+ // all name their target exactly — never needs them, because+ // `resolveWikiLinkTargetDocName` tries `pages.has` before any map. Memoized,+ // so a body with many unresolved wiki links still builds each map once+ // rather than once per link.+ let pagesBySlug: ReadonlyMap<string, string> | undefined;+ let pagesByBasename: ReadonlyMap<string, string> | undefined;+ const wikiLookup: WikiLinkLookupIndex = {+ pages: admitted,+ get pagesBySlug() {+ pagesBySlug ??= buildPagesBySlugIndex(admitted, toWikiLinkSlug);+ return pagesBySlug;+ },+ get pagesByBasename() {+ pagesByBasename ??= buildPagesByBasenameIndex(admitted, toWikiLinkSlug);+ return pagesByBasename;+ },+ };+const recordWikiLink = (target: string, anchor: string | null): void => {- const classified = classifyWikiLinkTarget(target, anchor);- // Only doc targets are validated. A wiki-link asset embed (`![[x.pdf]]`)- // resolves by vault-wide basename, not by relative path, so the depth- // footgun doesn't apply and the path-pure resolver here can't answer it —- // unlike a markdown `[text](path.ext)`, which IS file-validated above.- if (!classified || classified.kind !== 'doc') return;- if (!admitted.has(classified.docName)) {- record(`[[${target}${anchor ? `#${anchor}` : ''}]]`, classified.docName, 'no-such-doc');+ const resolved = resolveWikiLinkTarget(target, anchor, wikiLookup);+ // Only doc targets are validated. A target naming an asset — a `![[x.pdf]]`+ // embed, or a link to a tracked non-markdown file — resolves by vault-wide+ // basename rather than by relative path, so the depth footgun doesn't apply+ // and the path-pure resolver here can't answer it (unlike a markdown+ // `[text](path.ext)`, which IS file-validated above). A target naming+ // nothing stays classified as an asset and is therefore silent too, which+ // is what the dead-link query does with a recorded target that resolves to+ // nothing — reporting those would flood every vault that embeds assets.+ if (!resolved || resolved.kind !== 'doc') return;+ // Existence through the chain the editor navigates with, not an exact-key+ // hit. `[[analysis]]` reaching `research/analysis` by basename is a working+ // link, and the strict check reported exactly those as broken while staying+ // silent about the genuinely broken ones.+ if (resolveWikiLinkTargetDocName(resolved.docName, wikiLookup) === undefined) {+ record(`[[${target}${anchor ? `#${anchor}` : ''}]]`, resolved.docName, 'no-such-doc');}};@@ -1085,6 +1195,11 @@ function serializeState(state: BranchGraphState): SerializedBranchGraphState {sourceForm: meta.sourceForm,line: meta.line,column: meta.column,+ // Persisted because it is not recoverable from the target string: a+ // markdown href can resolve to a docName that looks exactly like an+ // undecided wiki target (`notes/report.v2`). Losing it across a+ // restart would turn every asset embed into a dead link.+ ...(meta.rawWikiTarget === true ? { rawWikiTarget: true as const } : {}),})),]),),@@ -1171,6 +1286,7 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {// wire) so a stale/corrupt file degrades to "position unknown".line: cachePosition(entry.line),column: cachePosition(entry.column),+ rawWikiTarget: entry.rawWikiTarget === true,},]),),@@ -1184,6 +1300,7 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {skillRefs: new Map(Object.entries(data.skillRefs ?? {}).map(([source, names]) => [source, new Set(names)]),),+ epoch: 0,};}@@ -1199,6 +1316,16 @@ export class BacklinkIndex {* files whose mtime is unchanged.*/private readonly mtimesByBranch = new Map<string, Map<string, number>>();+ /**+ * Cached slug/basename lookup per graph state, rebuilt only when that state's+ * `epoch` moves. Keyed by state object identity so a branch switch or a+ * snapshot reload (both of which install a fresh state) can never be served a+ * previous state's index.+ */+ private readonly documentLookups = new WeakMap<+ BranchGraphState,+ { epoch: number; lookup: WikiLinkLookupIndex }+ >();private activeBranch = 'main';constructor(options: BacklinkIndexOptions) {@@ -1380,6 +1507,7 @@ export class BacklinkIndex {if (sources.size === 0) state.externalBackward.delete(url);}state.forward.set(docName, new Set());+ state.epoch++;state.externalForward.set(docName, new Map());}@@ -1431,6 +1559,7 @@ export class BacklinkIndex {const nextTargets = new Set<string>();const nextExternalTargets = new Map<string, { label: string | null; snippet: string | null }>();state.forward.set(docName, nextTargets);+ state.epoch++;state.externalForward.set(docName, nextExternalTargets);for (const link of links) {@@ -1449,6 +1578,7 @@ export class BacklinkIndex {sourceForm: link.sourceForm,line: link.line,column: link.column,+ rawWikiTarget: link.rawWikiTarget === true,}),);}@@ -1523,6 +1653,7 @@ export class BacklinkIndex {if (sources.size === 0) state.externalBackward.delete(url);}state.forward.delete(docName);+ state.epoch++;state.externalForward.delete(docName);state.skillRefs.delete(docName);}@@ -1705,6 +1836,31 @@ export class BacklinkIndex {.map(([target, sources]) => ({target,sources: [...sources.entries()]+ // An undecided raw wiki occurrence is never evidence of a broken+ // link. It either names a document the corpus knows under another+ // spelling (`[[acp.daemon]]` → `notes/acp.daemon.md`), or it names+ // nothing the graph can see — an asset embed, a tracked non-markdown+ // file — and then it stays silent exactly as it did when index time+ // discarded it outright. Reporting that second class is the+ // regression this filter exists to avoid: every vault that embeds an+ // asset would fill with dead links. A target left with no decided+ // occurrence drops out below.+ .filter(([, meta]) => meta.rawWikiTarget !== true)+ // The existence test above compares literal names, but a wiki target+ // reaches its document through the whole chain — slug, folder index,+ // basename. Without this, `[[analysis]]` naming `research/analysis`+ // is reported broken while clicking it arrives, which is the+ // contradiction between the audit and the editor that this work+ // exists to remove. Markdown hrefs are deliberately excluded: they+ // are paths, and no surface basename-resolves them, so relaxing them+ // here would hide genuinely wrong ones. Membership is what makes this+ // safe to apply — a target naming nothing still resolves to+ // `undefined` and is still reported.+ .filter(+ ([, meta]) =>+ meta.sourceForm !== 'wiki' ||+ resolveWikiLinkTargetDocName(target, this.documentLookup(branch)) === undefined,+ ).filter(([source]) => !sourceDocSet || sourceDocSet.has(source)).map(([source, meta]) => ({source,@@ -1724,6 +1880,37 @@ export class BacklinkIndex {);}+ /**+ * The document set query-time wiki-link resolution runs against: every doc the+ * graph has indexed. Built once per {@link BranchGraphState.epoch} and reused,+ * so a scan over many targets pays for it once.+ */+ private documentLookup(branch = this.activeBranch): WikiLinkLookupIndex {+ const state = this.getState(branch);+ const cached = this.documentLookups.get(state);+ if (cached?.epoch === state.epoch) return cached.lookup;++ const pages = new Set(state.forward.keys());+ const lookup: WikiLinkLookupIndex = {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ this.documentLookups.set(state, { epoch: state.epoch, lookup });+ return lookup;+ }++ /**+ * Whether an undecided raw wiki target names a real document after all. The+ * shared resolver owns the rule — asset first, document membership only when+ * no asset matches — so the graph and the editor promote the same targets.+ * The graph has no asset oracle, so anything that isn't a document here stays+ * an asset and is dropped rather than minted as a node.+ */+ private undecidedTargetResolves(target: string, branch = this.activeBranch): boolean {+ return resolveWikiLinkTarget(target, null, this.documentLookup(branch))?.kind === 'doc';+ }+getLinkGraph(branch = this.activeBranch): {nodes: GraphNode[];links: Array<{ source: string; target: string }>;@@ -1740,6 +1927,12 @@ export class BacklinkIndex {anchor: getRepresentativeAnchor(state.backward.get(source)),});for (const target of targets) {+ // An asset embed (`![[diagram.png]]`) is recorded like any other wiki+ // target but names no document, and minting a node for it would put a+ // phantom doc in the graph for every asset a vault embeds.+ if (isUndecidedTarget(state, target) && !this.undecidedTargetResolves(target, branch)) {+ continue;+ }nodes.set(target, {kind: 'doc',id: target,@@ -1830,6 +2023,16 @@ export class BacklinkIndex {}} else {for (const target of state.forward.get(current.nodeId) ?? new Set<string>()) {+ // Same admission the whole-graph view applies. Recording every wiki+ // target verbatim means an asset embed reaches here as an ordinary+ // target, and without this the neighborhood mints a document node+ // the whole graph suppresses — two views of one graph disagreeing+ // about which documents exist. Traversal is the right place for it:+ // an unadmitted target never enters `visited`, so it can't return as+ // a node or as an edge endpoint below.+ if (isUndecidedTarget(state, target) && !this.undecidedTargetResolves(target, branch)) {+ continue;+ }neighbors.add(target);}for (const url of state.externalForward.get(current.nodeId)?.keys() ?? []) {@@ -2021,6 +2224,7 @@ export class BacklinkIndex {const targets = new Set<string>();const externalTargets = new Map<string, { label: string | null; snippet: string | null }>();state.forward.set(docName, targets);+ state.epoch++;state.externalForward.set(docName, externalTargets);for (const link of links) {if (!link.target) continue;@@ -2038,6 +2242,7 @@ export class BacklinkIndex {sourceForm: link.sourceForm,line: link.line,column: link.column,+ rawWikiTarget: link.rawWikiTarget === true,}),);}