Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix false missing-file links: NFC/NFD and more (PRD-8896) (#5691)
Andrew Mikofalvy0a736ccda105
diff --git a/.changeset/angle-bracket-link-destinations.md b/.changeset/angle-bracket-link-destinations.mdnew file mode 100644index 000000000..2d494cbbf--- /dev/null+++ b/.changeset/angle-bracket-link-destinations.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Links, images, and reference definitions written with an angle-bracket destination such as `[René](</People/René.md>)` now open the path inside the brackets instead of a literal `<…>` target, and still save byte-for-byte as written.diff --git a/.changeset/cmd-click-non-raw-files.md b/.changeset/cmd-click-non-raw-files.mdnew file mode 100644index 000000000..2f738b606--- /dev/null+++ b/.changeset/cmd-click-non-raw-files.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Cmd-click on a linked code file or extensionless file now opens it in a new app tab instead of a tab showing a 404 or an empty editor.diff --git a/.changeset/excluded-link-target-reason.md b/.changeset/excluded-link-target-reason.mdnew file mode 100644index 000000000..6912f2e15--- /dev/null+++ b/.changeset/excluded-link-target-reason.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": minor+"@inkeep/open-knowledge-core": minor+---++Links to files that exist but are excluded by .gitignore or .okignore now say so in the Problems pane, the Links panel, and agent write results, with the .okignore re-include hint, instead of claiming the file does not exist.diff --git a/.changeset/extensionless-file-links-open.md b/.changeset/extensionless-file-links-open.mdnew file mode 100644index 000000000..8c498308a--- /dev/null+++ b/.changeset/extensionless-file-links-open.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++A link to an existing file with no extension, such as a Makefile, now opens the file preview on click instead of only showing the link popover, and agent write results no longer report it as a missing page.diff --git a/.changeset/nfc-nfd-link-targets.md b/.changeset/nfc-nfd-link-targets.mdnew file mode 100644index 000000000..7f16bb203--- /dev/null+++ b/.changeset/nfc-nfd-link-targets.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": minor+"@inkeep/open-knowledge-core": minor+---++Links, backlinks, and the Problems pane now match documents, files, and folders whose names differ only in Unicode normalization (NFC vs NFD), and such images and files now load on Linux too. In the editor, markdown asset links now match parent folder names case-sensitively; file names stay case-insensitive.diff --git a/.changeset/prd-8896-asset-request-gate.md b/.changeset/prd-8896-asset-request-gate.mdnew file mode 100644index 000000000..24fc138e1--- /dev/null+++ b/.changeset/prd-8896-asset-request-gate.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Raw asset requests whose path contains `#`, an encoded slash, a backslash, or a `.`, `..` or empty segment now return 404 for any file. Ignored files can no longer be reached this way, and files with a backslash in their name are no longer served on macOS or Linux.diff --git a/.changeset/prd-8896-physical-scope-targets.md b/.changeset/prd-8896-physical-scope-targets.mdnew file mode 100644index 000000000..e5fd676da--- /dev/null+++ b/.changeset/prd-8896-physical-scope-targets.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Auditing a single file that has a same-named `.md` or `.mdx` sibling no longer reports links to existing images, files, and folders as missing.diff --git a/.changeset/prd-8896-wiki-asset-problems.md b/.changeset/prd-8896-wiki-asset-problems.mdnew file mode 100644index 000000000..b1c7d14fc--- /dev/null+++ b/.changeset/prd-8896-wiki-asset-problems.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++A `[[file.png]]` or `![[file.png]]` whose file does not exist now appears in the Problems pane and the Links panel's local files, like a missing markdown link does; an existing file, by path or by file name, does not.diff --git a/.changeset/prd-8896-wiki-embed-basename.md b/.changeset/prd-8896-wiki-embed-basename.mdnew file mode 100644index 000000000..c40b45aac--- /dev/null+++ b/.changeset/prd-8896-wiki-embed-basename.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++`![[file.png]]` embeds now resolve by file name anywhere in the project, including folders that hold no markdown document and names that differ only in Unicode normalization.diff --git a/.changeset/prd-8896-wiki-embed-path.md b/.changeset/prd-8896-wiki-embed-path.mdnew file mode 100644index 000000000..5943ec654--- /dev/null+++ b/.changeset/prd-8896-wiki-embed-path.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++`![[folder/file.png]]` embeds now show their file when the embed's letter case or Unicode normalization differs from the file's path, as `[[folder/file.png]]` links already do.diff --git a/docs/content/advanced/content-rules/overview.mdx b/docs/content/advanced/content-rules/overview.mdxindex c5f1ad23f..b70182231 100644--- a/docs/content/advanced/content-rules/overview.mdx+++ b/docs/content/advanced/content-rules/overview.mdx@@ -242,7 +242,7 @@ Every write response carries validation findings for the document it touched, on**`warnings`** carries up to 10 findings across the whole validation plane — lint violations and broken links alike, honoring the project's `validation.links` setting and, for a reserved log, the **Ignore broken links in log.md** switch. Positions are 1-based (`line`/`column`), ready to echo back to a human, and a `links` finding adds `linkTarget`. The field is present only when the write produced findings.-**`brokenLinks`** is the dedicated link channel, and unlike `warnings` it is **always present**. An empty array is the positive "every outbound link resolves" confirmation, which saves a separate `links({ kind: "dead" })` round-trip, as long as no `brokenLinkSuppression` sits beside it and `warnings` carries no `link-check-deferred` entry. That entry means the server was still building its link index after starting, so link checks were skipped. That document's links are checked again only when it is written or edited after startup finishes, or by an `audit`, which waits for startup and can time out until then. Each entry names the href exactly as authored, so an agent can grep for it. `reason` is `no-such-doc` (resolved to a docName that doesn't exist), `no-such-file` (a linked asset or source file missing from disk), or `unresolvable` (an empty href, or a relative path escaping the content root); `resolvedTo` is `null` for `unresolvable`.+**`brokenLinks`** is the dedicated link channel, and unlike `warnings` it is **always present**. An empty array is the positive "every outbound link resolves" confirmation, which saves a separate `links({ kind: "dead" })` round-trip, as long as no `brokenLinkSuppression` sits beside it and `warnings` carries no `link-check-deferred` entry. That entry means the server was still building its link index after starting, so link checks were skipped. That document's links are checked again only when it is written or edited after startup finishes, or by an `audit`, which waits for startup and can time out until then. Each entry names the href exactly as authored, so an agent can grep for it. `reason` is `no-such-doc` (resolved to a docName that doesn't exist), `no-such-file` (a linked asset or source file missing from disk), `excluded` (the file exists on disk but a `.gitignore` or `.okignore` rule keeps it out of the project; a `!` rule in `.okignore`, such as `!ignored/`, re-includes it or its folder), or `unresolvable` (an empty href, or a relative path escaping the content root); `resolvedTo` is `null` for `unresolvable`.**`brokenLinkSuppression`** is present only when the project's reserved-log policy kept findings out of `brokenLinks`, which is what makes an empty array conditional rather than a clean bill of health:diff --git a/docs/content/reference/core-concepts.md b/docs/content/reference/core-concepts.mdindex 40d84fa1b..c2c69ec09 100644--- a/docs/content/reference/core-concepts.md+++ b/docs/content/reference/core-concepts.md@@ -94,6 +94,10 @@ A wiki link such as `[[notes/beta.md]]` first checks for a document whose path iAfter the original exact-path check, OpenKnowledge fully resolves the suffix-stripped spelling: exact path, case- and punctuation-insensitive slug, folder `index` page (or its same-named page), then matching basename when the link has no slash. Only if that finds nothing does it try the original spelling's fuzzy, folder-index, and basename fallbacks. Without a Markdown suffix, those checks run once on the original spelling. If multiple paths have the same fuzzy slug or basename, the path smallest in UTF-16 code-unit order wins. For example, with `reports/index.md` and `reports-md.md`, `[[reports.md]]` opens `reports/index` before trying the fuzzy match for `reports-md`. An exact, case-matching path avoids a fuzzy tie.+Every exact-path check, in every link form except wiki asset links and embeds (see below), compares names with one identity rule. Document and folder names match case-sensitively. File names (images, PDFs, and other non-markdown files) match case-insensitively. Names that differ only in Unicode normalization are the same name for every kind: `é` stored as one character (NFC) or as `e` plus a combining accent (NFD) matches either spelling, so a link typed on Linux opens a file whose name macOS stored decomposed. Characters that only compatibility normalization would merge, such as the `fi` ligature and `fi`, stay distinct. When two stored names are equivalent, an exact spelling wins; otherwise the name smallest in UTF-16 code-unit order wins.++Markdown and wiki asset links treat folder case differently. A Markdown asset link such as `` matches each parent folder case-sensitively and only the file name case-insensitively, so it no longer finds `images/cat.png`. A wiki embed such as `![[Images/cat.png]]` still matches its whole path case-insensitively. On macOS and Windows, whose file systems ignore case, a Markdown asset link whose folder case differs from the folder on disk can show as broken after upgrading; correct the folder spelling in the link.+After upgrading, review existing wiki links and shorthand targets that omit a folder, differ only by case or punctuation, or end in `.md` or `.mdx`. Open each link or use the MCP `links` tool with `kind: "forward"` to inspect its resolved destination. If a valid link now opens a different document, replace its target with the intended document's exact path. Use `audit` to find broken links, but do not rely on it to detect a link that still resolves to the wrong document. For new cross-document links, prefer the explicit relative or root-absolute Markdown paths above.You never write backlinks by hand. They are computed from the links you already write, and together they form the **link graph**: the network of relationships across your knowledge base.diff --git a/packages/app/src/components/LinksPanel.dom.test.tsx b/packages/app/src/components/LinksPanel.dom.test.tsxindex e38a57643..a69bfe274 100644--- a/packages/app/src/components/LinksPanel.dom.test.tsx+++ b/packages/app/src/components/LinksPanel.dom.test.tsx@@ -162,6 +162,27 @@ describe('LinksPanel Local files section', () => {).toBeTruthy();});+ test('an excluded file shows an Excluded status instead of Missing (PRD-8896)', async () => {+ forwardLinksResult.body = forwardLinksBody({+ localTargets: [+ localTarget({+ role: 'image',+ href: 'ignored/ig.png',+ resolvedTarget: 'ignored/ig.png',+ status: 'missing',+ reason: 'excluded',+ }),+ ],+ });+ render(<LinksPanel docName="notes" />);++ expect(await screen.findByText('Excluded')).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'Excluded image ignored/ig.png. Go to reference.' }),+ ).toBeTruthy();+ expect(screen.queryByText('Missing')).toBeNull();+ });+test('a missing row navigates to its authored occurrence and offers no recovery action', async () => {forwardLinksResult.body = forwardLinksBody({localTargets: [diff --git a/packages/app/src/components/LinksPanel.tsx b/packages/app/src/components/LinksPanel.tsxindex 863c69ca3..2e5a5068b 100644--- a/packages/app/src/components/LinksPanel.tsx+++ b/packages/app/src/components/LinksPanel.tsx@@ -567,18 +567,27 @@ function LocalFilesSection({ docName }: { docName: string }) {const isImage = target.role === 'image';const resolved = target.status === 'exact' || target.status === 'fallback';const identity = target.resolvedTarget ?? target.href;- const statusWord = target.status === 'missing' ? t`Missing` : t`Unresolvable`;+ const excluded = target.reason === 'excluded';+ const statusWord = excluded+ ? t`Excluded`+ : target.status === 'missing'+ ? t`Missing`+ : t`Unresolvable`;const ariaLabel = resolved? isImage? t`Image ${identity}. Go to reference.`: t`File ${identity}. Go to reference.`- : target.status === 'missing'+ : excluded? isImage- ? t`Missing image ${identity}. Go to reference.`- : t`Missing file ${identity}. Go to reference.`- : isImage- ? t`Unresolvable image ${identity}. Go to reference.`- : t`Unresolvable file ${identity}. Go to reference.`;+ ? t`Excluded image ${identity}. Go to reference.`+ : t`Excluded file ${identity}. Go to reference.`+ : target.status === 'missing'+ ? isImage+ ? t`Missing image ${identity}. Go to reference.`+ : t`Missing file ${identity}. Go to reference.`+ : isImage+ ? t`Unresolvable image ${identity}. Go to reference.`+ : t`Unresolvable file ${identity}. Go to reference.`;return (<LinkRowkey={`lt:${target.range.start}-${target.range.end}`}diff --git a/packages/app/src/components/PageListContext.identity-targets.dom.test.tsx b/packages/app/src/components/PageListContext.identity-targets.dom.test.tsxnew file mode 100644index 000000000..b62cc9f52--- /dev/null+++ b/packages/app/src/components/PageListContext.identity-targets.dom.test.tsx@@ -0,0 +1,100 @@+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { computeLinkResolutionState } from '@/editor/extensions/link-resolution';+import { __resetPageListCacheForTests, getPageListCache } from '@/editor/page-list-cache';+import { __resetDocumentListInflightForTests } from '@/lib/documents-fetch';+import { resolveNavigationTarget } from './navigation-targets';++vi.doMock('@/lib/documents-events', () => ({+ subscribeToDocumentsChanged: () => () => {},+}));++const NFD_DOC = 'People/René';+const NFC_DOC = 'People/René';+const NFD_FOLDER = 'Archivé';+const NFC_FOLDER = 'Archivé';++let originalFetch: typeof globalThis.fetch;++function jsonRes(body: unknown) {+ return { ok: true, status: 200, json: async () => body } as Response;+}++beforeEach(() => {+ __resetPageListCacheForTests();+ __resetDocumentListInflightForTests();+ originalFetch = globalThis.fetch;+ globalThis.fetch = ((input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes('/api/pages')) {+ return Promise.resolve(+ jsonRes({+ pages: [NFD_DOC, 'README'].map((docName) => ({+ docName,+ title: docName,+ size: 1,+ modified: '2026-01-01T00:00:00.000Z',+ })),+ }),+ );+ }+ if (url.includes('/api/documents')) {+ return Promise.resolve(jsonRes({ documents: [{ kind: 'folder', path: NFD_FOLDER }] }));+ }+ return Promise.reject(new Error(`unexpected fetch: ${url}`));+ }) as typeof globalThis.fetch;+});++afterEach(() => {+ cleanup();+ globalThis.fetch = originalFetch;+ __resetPageListCacheForTests();+});++function NavigationProbe() {+ const { loading, pages, folderPaths } = usePageList();+ if (loading) return null;+ return (+ <div>+ <output data-testid="doc-target">+ {JSON.stringify(resolveNavigationTarget(NFC_DOC, { pages, folderPaths }))}+ </output>+ <output data-testid="folder-target">+ {JSON.stringify(resolveNavigationTarget(NFC_FOLDER, { pages, folderPaths }))}+ </output>+ </div>+ );+}++const { PageListProvider, usePageList } = await import('./PageListContext');++describe('PageListContext resolves canonically equivalent link targets (PRD-8896)', () => {+ test('an NFC link to an NFD-named document or folder resolves and navigates to the stored name', async () => {+ render(+ <PageListProvider>+ <NavigationProbe />+ </PageListProvider>,+ );++ await waitFor(() => {+ expect(screen.getByTestId('doc-target').textContent).not.toBe('');+ expect(getPageListCache()?.pages.has(NFD_DOC)).toBe(true);+ });++ const cache = getPageListCache();+ expect(computeLinkResolutionState(`./${NFC_DOC}.md`, 'README', cache)).toBe('resolved');+ expect(computeLinkResolutionState(`./${NFC_DOC}`, 'README', cache)).toBe('resolved');+ expect(computeLinkResolutionState(`./${NFC_FOLDER}`, 'README', cache)).toBe('folder');++ expect(JSON.parse(screen.getByTestId('doc-target').textContent ?? '')).toEqual({+ kind: 'doc',+ target: NFD_DOC,+ docName: NFD_DOC,+ });+ expect(JSON.parse(screen.getByTestId('folder-target').textContent ?? '')).toEqual({+ kind: 'folder',+ target: NFC_FOLDER,+ folderPath: NFD_FOLDER,+ });+ });+});diff --git a/packages/app/src/components/PageListContext.tsx b/packages/app/src/components/PageListContext.tsxindex 2f6c30db6..5cd8389b4 100644--- a/packages/app/src/components/PageListContext.tsx+++ b/packages/app/src/components/PageListContext.tsx@@ -1,4 +1,8 @@import { toWikiLinkSlug } from '@inkeep/open-knowledge-core/utils/slug';+import {+ asTargetNamespace,+ createTargetNamespace,+} from '@inkeep/open-knowledge-core/utils/target-namespace';import { t } from '@lingui/core/macro';import { createContext, type ReactNode, use, useEffect, useRef, useState } from 'react';import {@@ -28,14 +32,14 @@ export interface PageMeta {}interface PageListContextValue {- pages: Set<string>;+ pages: ReadonlySet<string>;pagesBySlug: ReadonlyMap<string, string>;pagesByBasename: ReadonlyMap<string, string>;pageTitles: ReadonlyMap<string, string>;pageMeta: ReadonlyMap<string, PageMeta>;- folderPaths: Set<string>;- assetPaths: Set<string>;- filePaths: Set<string>;+ folderPaths: ReadonlySet<string>;+ assetPaths: ReadonlySet<string>;+ filePaths: ReadonlySet<string>;loading: boolean;error: string | null;refetch: () => void;@@ -272,12 +276,15 @@ export function PageListProvider({ children }: { children: ReactNode }) {};}, []);- const pages = mergePageSets(serverPages, optimisticPages);+ const pages = asTargetNamespace('document', mergePageSets(serverPages, optimisticPages));const pageTitles = mergePageTitles(serverPageTitles, optimisticPages);const pageMeta: ReadonlyMap<string, PageMeta> = serverPageMeta;- const assetPaths = serverAssetPaths;- const filePaths = serverFilePaths;- const folderPaths = new Set([...deriveKnownFolderPaths(pages), ...serverFolderPaths]);+ const assetPaths = asTargetNamespace('file', serverAssetPaths);+ const filePaths = asTargetNamespace('file', serverFilePaths);+ const folderPaths = createTargetNamespace('folder', [+ ...deriveKnownFolderPaths(pages),+ ...serverFolderPaths,+ ]);const pagesBySlug = buildPagesBySlugIndex(pages, toWikiLinkSlug);const pagesByBasename = buildPagesByBasenameIndex(pages, toWikiLinkSlug);const pageIcons = buildPageIconsIndex(serverPageMeta);diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsxindex 7d6dd9d0d..2c01075e3 100644--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx@@ -419,6 +419,36 @@ describe('ProblemsPanel', () => {expect(screen.queryByText('opaque server fallback')).toBeNull();});+ test('an excluded file target renders the ignore-rule message with the .okignore remedy (PRD-8896)', () => {+ render(+ <ProblemsPanel+ docName="notes"+ diagnostics={[+ diag({+ source: 'links',+ code: 'dead-link',+ message: 'opaque server fallback',+ localTarget: {+ href: 'ignored/ig.png',+ targetKind: 'file',+ role: 'link',+ sourceForm: 'markdown-inline',+ resolvedTarget: 'ignored/ig.png',+ reason: 'excluded',+ resolutionMethod: 'source-relative',+ },+ }),+ ]}+ />,+ );+ expect(+ screen.getByText(+ 'Link target "ignored/ig.png" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.',+ ),+ ).toBeTruthy();+ expect(screen.queryByText('opaque server fallback')).toBeNull();+ });+test('while the lint config has not loaded, the panel makes no plugin claim', () => {projectLintConfigData = null;render(<ProblemsPanel docName="notes" diagnostics={[]} />);diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex 83d2a5dc3..ed593eca5 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -1,4 +1,4 @@-import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';+import { createTargetNamespace, DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {deriveKnownFolderPaths,@@ -866,3 +866,48 @@ describe('markdown-extension normalization preserves document identity', () => {});});});++describe('resolveNavigationTarget across canonically equivalent spellings', () => {+ const NFC = 'people/Ren\u00e9';+ const NFD = 'people/Rene\u0301';++ test('a document requested in NFC navigates to the stored NFD document', () => {+ expect(+ resolveNavigationTarget(NFC, { pages: createTargetNamespace('document', [NFD, 'notes']) }),+ ).toEqual({ kind: 'doc', target: NFD, docName: NFD });+ });++ test('a folder-shaped target resolves its index note under the stored spelling', () => {+ const pages = createTargetNamespace('document', [`${NFD}/index`, 'notes']);+ expect(resolveNavigationTarget(`${NFC}/`, { pages })).toEqual({+ kind: 'folder-index',+ target: NFC,+ folderPath: NFD,+ docName: `${NFD}/index`,+ noteKind: 'canonical-index',+ });+ expect(resolveNavigationTarget(NFC, { pages })).toEqual({+ kind: 'folder-index',+ target: NFC,+ folderPath: NFD,+ docName: `${NFD}/index`,+ noteKind: 'canonical-index',+ });+ });++ test('a folder requested in NFC resolves to the stored NFD folder path', () => {+ expect(+ resolveNavigationTarget(NFC, {+ pages: createTargetNamespace('document', [`${NFD}/notes`]),+ folderPaths: createTargetNamespace('folder', [NFD, 'people']),+ }),+ ).toEqual({ kind: 'folder', target: NFC, folderPath: NFD });+ });++ test('plain sets keep exact matching', () => {+ expect(resolveNavigationTarget(NFC, { pages: new Set([NFD]) })).toEqual({+ kind: 'missing',+ target: NFC,+ });+ });+});diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex 925a06e60..21600ea9c 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -18,6 +18,7 @@ import {mediaKindForSidebarAssetExtension,} from '@inkeep/open-knowledge-core/constants/upload';import type { SkillScope } from '@inkeep/open-knowledge-core/schemas/api';+import { resolveName } from '@inkeep/open-knowledge-core/utils/target-namespace';import { resolveWikiLinkTargetDocName } from '@inkeep/open-knowledge-core/utils/wiki-link-resolve';import type { SkillPreviewFlavor } from '@/lib/doc-hash';import { normalizeDocNameInput } from '@/lib/doc-paths';@@ -109,12 +110,16 @@ function extensionlessTargetPath(target: string): string {return normalizeDocNameInput(target).replace(/\/+$/g, '');}+function folderOfDocName(docName: string): string {+ return docName.slice(0, docName.lastIndexOf('/'));+}+const MARKDOWN_TARGET_EXTENSION = /\.(md|mdx)$/i;function managedArtifactNavigationTarget(target: string, pages: ReadonlySet<string>): string {const { normalizedTarget, expectsFolder } = normalizeTargetPath(target);if (expectsFolder || !MARKDOWN_TARGET_EXTENSION.test(normalizedTarget)) return target;- if (pages.has(normalizedTarget)) return target;+ if (resolveName(pages, normalizedTarget) !== undefined) return target;return normalizedTarget.replace(MARKDOWN_TARGET_EXTENSION, '');}@@ -140,7 +145,7 @@ export function okContentNavigationTarget(): ResolvedContentTarget | null {if (!hasOkPathSegment(docName)) return null;if (parseTemplateContentDocName(docName)) return null;- if (options.pages.has(docName)) return null;+ if (resolveName(options.pages, docName) !== undefined) return null;const assetPath = okReadOnlyAssetPath(docName, options.docExt);return {kind: 'asset',@@ -208,33 +213,32 @@ export function resolveNavigationTarget(? [extensionlessTarget]: [normalizedTarget, extensionlessTarget];for (const folderTarget of folderTargets) {- const canonicalIndexDocName = `${folderTarget}/index`;+ const canonicalIndexDocName = resolveName(options.pages, `${folderTarget}/index`);if (- expectsFolder- ? options.pages.has(canonicalIndexDocName)- : resolvedDocName === canonicalIndexDocName+ canonicalIndexDocName !== undefined &&+ (expectsFolder || resolvedDocName === canonicalIndexDocName)) {return {kind: 'folder-index',target: folderTarget,- folderPath: folderTarget,+ folderPath: folderOfDocName(canonicalIndexDocName),docName: canonicalIndexDocName,noteKind: 'canonical-index',};}const leaf = folderTarget.split('/').pop();- const legacyFolderNoteDocName = leaf ? `${folderTarget}/${leaf}` : null;+ const legacyFolderNoteDocName = leaf+ ? resolveName(options.pages, `${folderTarget}/${leaf}`)+ : undefined;if (- legacyFolderNoteDocName &&- (expectsFolder- ? options.pages.has(legacyFolderNoteDocName)- : resolvedDocName === legacyFolderNoteDocName)+ legacyFolderNoteDocName !== undefined &&+ (expectsFolder || resolvedDocName === legacyFolderNoteDocName)) {return {kind: 'folder-index',target: folderTarget,- folderPath: folderTarget,+ folderPath: folderOfDocName(legacyFolderNoteDocName),docName: legacyFolderNoteDocName,noteKind: 'legacy-folder-note',};@@ -246,11 +250,12 @@ export function resolveNavigationTarget(}const knownFolderPaths = options.folderPaths ?? deriveKnownFolderPaths(options.pages);- if (knownFolderPaths.has(extensionlessTarget)) {+ const folderPath = resolveName(knownFolderPaths, extensionlessTarget);+ if (folderPath !== undefined) {return {kind: 'folder',target: extensionlessTarget,- folderPath: extensionlessTarget,+ folderPath,};}diff --git a/packages/app/src/editor/components/image-target-existence.test.ts b/packages/app/src/editor/components/image-target-existence.test.tsindex cb63967cd..48af94e7f 100644--- a/packages/app/src/editor/components/image-target-existence.test.ts+++ b/packages/app/src/editor/components/image-target-existence.test.ts@@ -1,3 +1,4 @@+import { createTargetNamespace } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { classifyImageTargetExistence } from './image-target-existence';@@ -32,14 +33,21 @@ describe('classifyImageTargetExistence', () => {expect(state).toBe('missing');});- test('existence match is case-insensitive, mirroring link-chip resolution', () => {- const state = classifyImageTargetExistence(- '/Images/Cat.PNG',- '',- new Set(['images/cat.png']),- undefined,+ test('existence matches by NFC and file-name case while parent folder case stays significant', () => {+ const assets = createTargetNamespace('file', ['images/cat.png', 'images/Cafe\u0301.png']);+ expect(classifyImageTargetExistence('/images/Cat.PNG', '', assets, undefined)).toBe('exists');+ expect(classifyImageTargetExistence('/Images/cat.png', '', assets, undefined)).toBe('missing');+ expect(classifyImageTargetExistence('/images/Caf\u00e9.png', '', assets, undefined)).toBe(+ 'exists',);- expect(state).toBe('exists');+ expect(+ classifyImageTargetExistence(+ '/images/Cafe\u0301.png',+ '',+ createTargetNamespace('file', ['images/Caf\u00e9.png']),+ undefined,+ ),+ ).toBe('exists');});test('external URL is unknown — absence from the inventory proves nothing', () => {diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.tsindex 447f38ea5..efa2c8f0b 100644--- a/packages/app/src/editor/editor-tabs.ts+++ b/packages/app/src/editor/editor-tabs.ts@@ -8,6 +8,7 @@ import {} from '@inkeep/open-knowledge-core/constants/cc1';import { isExcalidrawDocFile } from '@inkeep/open-knowledge-core/constants/upload';import type { RenamedAssetMapping, SkillScope } from '@inkeep/open-knowledge-core/schemas/api';+import { resolveName } from '@inkeep/open-knowledge-core/utils/target-namespace';import {decodeSkillPreviewSegments,encodeSkillPreviewSegments,@@ -510,10 +511,16 @@ export function filterOpenTabsForKnownTargets(return normalizeOpenTabs(tabs, Number.MAX_SAFE_INTEGER).filter((tabId) => {const tab = parseEditorTabId(tabId);if (tab.kind === 'folder') {- return folderPaths.has(tab.folderPath) || keepFolderPaths.has(tab.folderPath);+ return (+ resolveName(folderPaths, tab.folderPath) !== undefined ||+ keepFolderPaths.has(tab.folderPath)+ );}if (tab.kind === 'asset') {- return assetPaths.has(tab.assetPath) || filePaths?.has(tab.assetPath) === true;+ return (+ resolveName(assetPaths, tab.assetPath) !== undefined ||+ (filePaths !== undefined && resolveName(filePaths, tab.assetPath) !== undefined)+ );}if (tab.kind === 'skill-file') return true;if (tab.kind === 'skill-preview') return true;diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsxindex d33c2700a..b06b54c09 100644--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx@@ -77,8 +77,8 @@ interface EditMarkdownLinkDialogProps {open: boolean;href: string;text: string;- pages: Set<string>;- folderPaths: Set<string>;+ pages: ReadonlySet<string>;+ folderPaths: ReadonlySet<string>;loading: boolean;onOpenChange: (open: boolean) => void;onSave: (href: string, text: string, labelChanged: boolean) => void;diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsxindex 786450676..32cb23508 100644--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx@@ -60,9 +60,9 @@ interface EditWikiLinkDialogProps {target: string;alias: string | null;anchor: string | null;- pages: Set<string>;- assetPaths: Set<string>;- filePaths: Set<string>;+ pages: ReadonlySet<string>;+ assetPaths: ReadonlySet<string>;+ filePaths: ReadonlySet<string>;loading: boolean;onOpenChange: (open: boolean) => void;onSave: (target: string, alias: string | null, anchor: string | null) => void;diff --git a/packages/app/src/editor/extensions/internal-link.tracked-file-activation.test.ts b/packages/app/src/editor/extensions/internal-link.tracked-file-activation.test.tsnew file mode 100644index 000000000..1dee66a9b--- /dev/null+++ b/packages/app/src/editor/extensions/internal-link.tracked-file-activation.test.ts@@ -0,0 +1,125 @@+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, vi } 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 { InternalLink } from './internal-link';+import { markIdentityKey } from './mark-identity';+import { toWikiLinkSlug } from './wiki-link-helpers';++let restoreDomGlobals: (() => void) | null = null;++beforeAll(() => {+ restoreDomGlobals = installDomGlobals();+});++afterAll(() => {+ restoreDomGlobals?.();+ restoreDomGlobals = null;+});++const liveEditors = new Set<Editor>();++const PAGES = new Set(['NonMd', 'docs/guide']);++beforeEach(() => {+ __resetPageListCacheForTests();+ setPageListCache({+ pages: PAGES,+ folderPaths: new Set(['docs', 'media']),+ assetPaths: new Set(['media/photo.png']),+ filePaths: new Set(['docs/Makefile', 'docs/script.py']),+ pagesBySlug: buildPagesBySlugIndex(PAGES, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(PAGES, toWikiLinkSlug),+ });+ globalThis.window.location.hash = '';+});++afterEach(() => {+ for (const editor of liveEditors) editor.destroy();+ liveEditors.clear();+ __resetPageListCacheForTests();+});++function mountLink(href: 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><a href="${href}">go</a></p>`,+ extensions: [+ StarterKit.configure({ link: false }),+ InternalLink.configure({ docName: 'NonMd' }),+ ],+ });+ liveEditors.add(editor);++ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1)));++ const nodeId = [...(markIdentityKey.getState(editor.state)?.byId.keys() ?? [])][0];+ if (nodeId === undefined) {+ throw new Error(`setup: no link mark id parsed for href ${href}`);+ }+ const registration = getInteractionLayer(editor).getRegistration(nodeId);+ if (!registration?.handlePrimary) {+ throw new Error('setup: link mark did not register a handlePrimary hook');+ }+ return {+ activate: (newTab = false) => registration.handlePrimary?.({ nodeId, type: 'link', newTab }),+ currentHash: () => globalThis.window.location.hash,+ };+}++describe('WYSIWYG markdown link to a tracked file with no page behind it', () => {+ test('a plain click on a link to an extensionless tracked file opens the file preview', () => {+ const { activate, currentHash } = mountLink('docs/Makefile');++ expect(activate(false)).toBe(true);+ expect(currentHash()).toBe('#/__asset__/docs/Makefile');+ });++ test('a Cmd/Ctrl click on a link to an extensionless tracked file opens the preview in a new app tab', async () => {+ const open = vi.fn(() => null);+ const w = globalThis.window as unknown as { open: unknown };+ const originalOpen = w.open;+ w.open = open;+ try {+ const { activate, currentHash } = mountLink('docs/Makefile');++ expect(activate(true)).toBe(true);+ await Promise.resolve();+ expect(open).toHaveBeenCalledWith(+ '#/__asset__/docs/Makefile',+ '_blank',+ 'noopener,noreferrer',+ );+ expect(currentHash()).toBe('');+ } finally {+ w.open = originalOpen;+ }+ });++ test('a link to a missing extensionless path still falls through to create (returns false)', () => {+ const { activate, currentHash } = mountLink('docs/absent');++ expect(activate(false)).toBe(false);+ expect(currentHash()).toBe('');+ });++ test('a link to an existing page keeps opening the page', () => {+ const { activate, currentHash } = mountLink('docs/guide');++ expect(activate(false)).toBe(true);+ expect(currentHash()).toBe('#/docs/guide');+ });+});diff --git a/packages/app/src/editor/extensions/internal-link.tracked-tab.test.ts b/packages/app/src/editor/extensions/internal-link.tracked-tab.test.tsnew file mode 100644index 000000000..9b76f257e--- /dev/null+++ b/packages/app/src/editor/extensions/internal-link.tracked-tab.test.ts@@ -0,0 +1,113 @@+import { createTargetNamespace } from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { assetPathFromHash, hashFromAssetPath } from '@/lib/doc-hash';+import { assetTabId, filterOpenTabsForKnownTargets } from '../editor-tabs';+import { activateAssetLink } from '../internal-link-helpers';+import type { PageListCacheSnapshot } from '../page-list-cache';+import { resolveStoredAssetActivation, resolveTrackedFileActivation } from './internal-link';++const DOC = 'notes/readme';+const CAFE_NFC = 'Café'.normalize('NFC');+const CAFE_NFD = 'Café'.normalize('NFD');++function snapshot(+ assetPaths: readonly string[],+ filePaths: readonly string[],+): PageListCacheSnapshot {+ return {+ pages: createTargetNamespace('document', [DOC]),+ folderPaths: createTargetNamespace('folder', ['notes']),+ assetPaths: createTargetNamespace('file', assetPaths),+ filePaths: createTargetNamespace('file', filePaths),+ pagesBySlug: new Map(),+ };+}++function tabOpenedBy(activation: {+ url: string;+ projectRelPath: string;+ ext: string;+ title: string;+}) {+ let navigatedTo: string | null = null;+ activateAssetLink(+ { ...activation, newTab: false },+ {+ navigate: (assetPath) => {+ navigatedTo = assetPath;+ },+ },+ );+ const assetPath = navigatedTo === null ? null : assetPathFromHash(hashFromAssetPath(navigatedTo));+ return assetPath === null ? null : assetTabId(assetPath);+}++function survivesRefresh(tabId: string, cache: PageListCacheSnapshot): boolean {+ return (+ filterOpenTabsForKnownTargets([tabId], {+ pages: cache.pages,+ folderPaths: cache.folderPaths,+ assetPaths: cache.assetPaths ?? new Set(),+ filePaths: cache.filePaths,+ }).length === 1+ );+}++describe('a tab opened from a differently spelled link to a tracked file', () => {+ test.each([+ ['letter case', './notice', 'notes/NOTICE'],+ ['normalization form', `./${CAFE_NFC}`, `notes/${CAFE_NFD}`],+ ])(+ 'opens under the stored spelling and survives a page-list refresh (%s)',+ (_label, href, stored) => {+ const cache = snapshot([], [stored]);+ const activation = resolveTrackedFileActivation(href, DOC, cache);+ expect(activation?.projectRelPath).toBe(stored);+ expect(activation?.title).toBe(stored.split('/').pop());+ const tabId = activation === null ? null : tabOpenedBy(activation);+ expect(tabId).toBe(assetTabId(stored));+ expect(tabId !== null && survivesRefresh(tabId, cache)).toBe(true);+ },+ );+});++describe('a tab opened from a differently spelled asset link', () => {+ test.each([+ ['letter case', './Photo.PNG', 'notes/photo.png'],+ ['normalization form', `./${CAFE_NFC}.png`, `notes/${CAFE_NFD}.png`],+ ])(+ 'opens under the stored spelling and survives a page-list refresh (%s)',+ (_label, href, stored) => {+ const cache = snapshot([stored], []);+ const activation = resolveStoredAssetActivation(+ { url: href, ext: 'png', literal: false, projectRelPath: `notes/${href.slice(2)}` },+ DOC,+ cache,+ );+ expect(activation?.projectRelPath).toBe(stored);+ const tabId = activation === null ? null : tabOpenedBy(activation);+ expect(tabId).toBe(assetTabId(stored));+ expect(tabId !== null && survivesRefresh(tabId, cache)).toBe(true);+ },+ );++ test('a link naming no tracked file opens nothing', () => {+ expect(+ resolveStoredAssetActivation(+ { url: './ghost.png', ext: 'png', literal: false, projectRelPath: 'notes/ghost.png' },+ DOC,+ snapshot(['notes/photo.png'], []),+ ),+ ).toBeNull();+ });+});++describe('the known-target sync keeps tabs whose spelling is identity-equal to a known target', () => {+ test('asset and file tabs match by the file identity rule', () => {+ const cache = snapshot(['notes/photo.png'], [`notes/${CAFE_NFD}`]);+ expect(survivesRefresh(assetTabId('notes/PHOTO.png'), cache)).toBe(true);+ expect(survivesRefresh(assetTabId(`notes/${CAFE_NFC}`), cache)).toBe(true);+ expect(survivesRefresh(assetTabId('Notes/photo.png'), cache)).toBe(false);+ expect(survivesRefresh(assetTabId('notes/gone.png'), cache)).toBe(false);+ });+});diff --git a/packages/app/src/editor/extensions/internal-link.ts b/packages/app/src/editor/extensions/internal-link.tsindex 562d3cd32..d4f2418e0 100644--- a/packages/app/src/editor/extensions/internal-link.ts+++ b/packages/app/src/editor/extensions/internal-link.ts@@ -16,11 +16,11 @@ import {openInternalHashHrefInNewTab,toInternalHashHref,} from '../internal-link-helpers';-import { getPageListCache } from '../page-list-cache';+import { getPageListCache, type PageListCacheSnapshot } from '../page-list-cache';import { createAssetContextMenuPlugin } from '../plugins/asset-context-menu';import { isSafeNavigationUrl } from '../safe-navigation-url';import { InternalLinkPropPanel } from './InternalLinkPropPanel';-import { isResolvedAssetHref, makeLinkResolutionAttrsComputer } from './link-resolution';+import { makeLinkResolutionAttrsComputer, resolveAssetHrefPath } from './link-resolution';import { linkResolutionDecorationPlugin } from './link-resolution-decoration';import { createMarkInteractionBridgePlugin, getCurrentMarkInfo } from './mark-interaction-bridge';@@ -53,6 +53,41 @@ export function resolveLinkMarkAssetActivation(params: {return { kind: 'asset', url, ext, literal, projectRelPath };}+type AssetLinkActivationTarget = Omit<Parameters<typeof activateAssetLink>[0], 'newTab'>;++function activationTarget(+ url: string,+ projectRelPath: string,+ ext: string,+): AssetLinkActivationTarget {+ return { url, projectRelPath, ext, title: projectRelPath.split('/').pop() ?? url };+}++export function resolveStoredAssetActivation(+ activation: { url: string; ext: string; literal: boolean; projectRelPath: string },+ docName: string,+ cache: PageListCacheSnapshot,+): AssetLinkActivationTarget | null {+ const { url, ext, literal, projectRelPath } = activation;+ if (cache.assetPaths === undefined && cache.filePaths === undefined) {+ return activationTarget(url, projectRelPath, ext);+ }+ const stored = resolveAssetHrefPath(url, docName, cache.assetPaths, cache.filePaths, { literal });+ return stored === null ? null : activationTarget(url, stored, ext);+}++export function resolveTrackedFileActivation(+ href: string,+ docName: string,+ cache: PageListCacheSnapshot | null,+): AssetLinkActivationTarget | null {+ if (cache === null) return null;+ const stored = resolveAssetHrefPath(href, docName, cache.assetPaths, cache.filePaths, {+ literal: false,+ });+ return stored === null ? null : activationTarget(href, stored, extractAssetExtension(href) ?? '');+}+export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({addOptions() {return {@@ -101,21 +136,11 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({});if (activation.kind === 'refused') return false;if (activation.kind === 'asset') {- const { url, ext, literal, projectRelPath } = activation;const cache = getPageListCache();if (cache === null) return false;- if (cache.assetPaths !== undefined || cache.filePaths !== undefined) {- if (!isResolvedAssetHref(url, docName, cache.assetPaths, cache.filePaths, { literal })) {- return false;- }- }- activateAssetLink({- url,- projectRelPath,- ext,- title: projectRelPath.split('/').pop() ?? url,- newTab,- });+ const stored = resolveStoredAssetActivation(activation, docName, cache);+ if (stored === null) return false;+ activateAssetLink({ ...stored, newTab });return true;}@@ -130,7 +155,12 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({pages: cache?.pages ?? new Set<string>(),folderPaths: cache?.folderPaths ?? new Set<string>(),});- if (intent.kind === 'create') return false;+ if (intent.kind === 'create') {+ const trackedFile = resolveTrackedFileActivation(href, docName, cache);+ if (trackedFile === null) return false;+ activateAssetLink({ ...trackedFile, newTab });+ return true;+ }if (newTab) {openInternalHashHrefInNewTab({ docName: target.docName, anchor: target.anchor });} else {diff --git a/packages/app/src/editor/extensions/link-resolution.test.ts b/packages/app/src/editor/extensions/link-resolution.test.tsindex 0aea9ddb5..78cf80612 100644--- a/packages/app/src/editor/extensions/link-resolution.test.ts+++ b/packages/app/src/editor/extensions/link-resolution.test.ts@@ -1,4 +1,4 @@-import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';+import { createTargetNamespace, toWikiLinkSlug } from '@inkeep/open-knowledge-core';import { beforeEach, describe, expect, test } from 'vitest';import {resetLinkValidationPolicyForTest,@@ -20,12 +20,14 @@ function makeCache(opts: {assetPaths?: Iterable<string>;filePaths?: Iterable<string>;}): PageListCacheSnapshot {- const pages = new Set(opts.pages ?? []);+ const pages = createTargetNamespace('document', opts.pages ?? []);return {pages,- folderPaths: new Set(opts.folderPaths ?? []),- assetPaths: opts.assetPaths === undefined ? undefined : new Set(opts.assetPaths),- filePaths: opts.filePaths === undefined ? undefined : new Set(opts.filePaths),+ folderPaths: createTargetNamespace('folder', opts.folderPaths ?? []),+ assetPaths:+ opts.assetPaths === undefined ? undefined : createTargetNamespace('file', opts.assetPaths),+ filePaths:+ opts.filePaths === undefined ? undefined : createTargetNamespace('file', opts.filePaths),pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),};}@@ -109,11 +111,37 @@ describe('computeLinkResolutionState', () => {expect(computeLinkResolutionState('./test/he.png', 'README', cache)).toBe('asset');});- test('relative asset href matches asset index case-insensitively', () => {+ test('relative asset href matches the asset file name case-insensitively', () => {const cache = makeCache({ pages: [], assetPaths: ['docs/Screenshot.PNG'] });expect(computeLinkResolutionState('./docs/screenshot.png', 'README', cache)).toBe('asset');});+ test('relative asset href does not match when a parent folder differs in case', () => {+ const cache = makeCache({ pages: [], assetPaths: ['docs/Screenshot.PNG'] });+ expect(computeLinkResolutionState('./Docs/screenshot.png', 'README', cache)).toBe('unresolved');+ });++ test('asset and file hrefs resolve across canonically equivalent spellings', () => {+ const cache = makeCache({+ pages: [],+ assetPaths: ['images/Rene\u0301.png'],+ filePaths: ['data/Zoe\u0308.csv'],+ });+ expect(computeLinkResolutionState('./images/Ren\u00e9.png', 'README', cache)).toBe('asset');+ expect(computeLinkResolutionState('/data/Zo\u00eb.csv', 'README', cache)).toBe('asset');+ });++ test('a document href spelled in NFC resolves to the NFD page', () => {+ const cache = makeCache({ pages: ['people/Rene\u0301'], folderPaths: ['people'] });+ expect(computeLinkResolutionState('./people/Ren\u00e9.md', 'README', cache)).toBe('resolved');+ expect(computeLinkResolutionState('./people/Ren\u00e9', 'README', cache)).toBe('resolved');+ });++ test('a folder href spelled in NFC resolves to the NFD folder', () => {+ const cache = makeCache({ pages: ['Rene\u0301/notes'], folderPaths: ['Rene\u0301'] });+ expect(computeLinkResolutionState('./Ren\u00e9', 'README', cache)).toBe('folder');+ });+test('relative asset href with cache, asset missing → unresolved', () => {const cache = makeCache({ pages: [], assetPaths: ['test/he.png'] });expect(computeLinkResolutionState('./test/hegggg.png', 'README', cache)).toBe('unresolved');diff --git a/packages/app/src/editor/extensions/link-resolution.ts b/packages/app/src/editor/extensions/link-resolution.tsindex c6b9f4953..1de1b60af 100644--- a/packages/app/src/editor/extensions/link-resolution.ts+++ b/packages/app/src/editor/extensions/link-resolution.ts@@ -2,6 +2,7 @@ import {classifyMarkdownHref,resolveAssetProjectPath,} from '@inkeep/open-knowledge-core/utils/link-targets';+import { resolveName } from '@inkeep/open-knowledge-core/utils/target-namespace';import { resolveLinkTargetIntent } from '../../components/link-target-intent';import { isLinkValidationVisible } from '../link-validation-policy';import type { PageListCacheSnapshot } from '../page-list-cache';@@ -16,13 +17,22 @@ type LinkResolutionState =| 'unresolved'| 'asset';-function setHasPathCaseInsensitive(paths: ReadonlySet<string>, target: string): boolean {- if (paths.has(target)) return true;- const lowerTarget = target.toLowerCase();- for (const path of paths) {- if (path.toLowerCase() === lowerTarget) return true;- }- return false;+export function resolveAssetHrefPath(+ href: string,+ sourceDocName: string,+ assetPaths: ReadonlySet<string> | undefined,+ filePaths: ReadonlySet<string> | undefined,+ options: { literal: boolean },+): string | null {+ const projectRelPath = resolveAssetProjectPath(href, sourceDocName, {+ literal: options.literal,+ });+ if (projectRelPath === null) return null;+ return (+ (assetPaths && resolveName(assetPaths, projectRelPath)) ??+ (filePaths && resolveName(filePaths, projectRelPath)) ??+ null+ );}export function isResolvedAssetHref(@@ -32,13 +42,7 @@ export function isResolvedAssetHref(filePaths: ReadonlySet<string> | undefined,options: { literal: boolean },): boolean {- const projectRelPath = resolveAssetProjectPath(href, sourceDocName, {- literal: options.literal,- });- if (projectRelPath === null) return false;- if (assetPaths && setHasPathCaseInsensitive(assetPaths, projectRelPath)) return true;- if (filePaths && setHasPathCaseInsensitive(filePaths, projectRelPath)) return true;- return false;+ return resolveAssetHrefPath(href, sourceDocName, assetPaths, filePaths, options) !== null;}export function computeLinkResolutionState(diff --git a/packages/app/src/editor/internal-link-helpers.test.ts b/packages/app/src/editor/internal-link-helpers.test.tsindex 992770b0b..19346d737 100644--- a/packages/app/src/editor/internal-link-helpers.test.ts+++ b/packages/app/src/editor/internal-link-helpers.test.ts@@ -117,6 +117,33 @@ describe('activateAssetLink', () => {expect(assign).toHaveBeenCalledWith('#/__asset__/docs/report.html');});+ it.each([+ ['a code file the server never streams raw', 'docs/script.py', 'py'],+ ['an extensionless file', 'docs/Makefile', ''],+ ])(+ 'Cmd/Ctrl/middle-click on %s hands the dispatcher the in-app asset route as its browser URL',+ (_label, projectRelPath, ext) => {+ const navigate = vi.fn((_assetPath: string) => {});+ const dispatch = vi.fn(async () => {});+ const title = projectRelPath.split('/').pop() ?? projectRelPath;++ activateAssetLink(+ { url: projectRelPath, projectRelPath, ext, title, newTab: true },+ { navigate, dispatch },+ );++ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(dispatch).toHaveBeenCalledWith({+ url: `#/__asset__/${projectRelPath}`,+ projectRelPath,+ ext,+ title,+ forceOsDelegation: true,+ });+ expect(navigate).not.toHaveBeenCalled();+ },+ );+it('Cmd/Ctrl/middle-click on an Excalidraw board opens the board in a new app tab, not the OS', () => {const open = vi.fn(() => null);Object.defineProperty(globalThis, 'window', {diff --git a/packages/app/src/editor/internal-link-helpers.ts b/packages/app/src/editor/internal-link-helpers.tsindex 397a0b6bb..5c39bc01a 100644--- a/packages/app/src/editor/internal-link-helpers.ts+++ b/packages/app/src/editor/internal-link-helpers.ts@@ -1,4 +1,7 @@-import { mediaKindForSidebarAssetExtension } from '@inkeep/open-knowledge-core/constants/upload';+import {+ ASSET_EXTENSIONS,+ mediaKindForSidebarAssetExtension,+} from '@inkeep/open-knowledge-core/constants/upload';import {buildRelativeMarkdownHref,type ClassifiedLinkTarget,@@ -75,7 +78,13 @@ export function activateAssetLink(if (mediaKindForSidebarAssetExtension(ext) === 'excalidraw') {openInternalHashHrefInNewTab({ docName: projectRelPath, anchor: null });} else {- void dispatch({ url, projectRelPath, ext, title, forceOsDelegation: true });+ void dispatch({+ url: ASSET_EXTENSIONS.has(ext) ? url : hashFromAssetPath(projectRelPath),+ projectRelPath,+ ext,+ title,+ forceOsDelegation: true,+ });}return;}diff --git a/packages/app/src/editor/localized-validation-message.ts b/packages/app/src/editor/localized-validation-message.tsindex d5d3e1466..a6c72b75a 100644--- a/packages/app/src/editor/localized-validation-message.ts+++ b/packages/app/src/editor/localized-validation-message.ts@@ -13,6 +13,11 @@ export function localizedValidationMessage(diagnostic: Diagnostic): string {? t`Image target "${shown}" could not be resolved to a project-local file.`: t`Link target "${shown}" could not be resolved to a project-local target.`;}+ if (evidence.reason === 'excluded') {+ return evidence.role === 'image'+ ? t`Image target "${shown}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`+ : t`Link target "${shown}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`;+ }if (evidence.targetKind === 'file') {return evidence.role === 'image'? t`Image target "${shown}" does not resolve to an existing file.`diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 81842127f..cd45aa8d8 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -284,6 +284,7 @@"1njn7W": ["فاتح"],"1nke1r": ["فتح ", ["0"], " على GitHub (يفتح في تبويب جديد)"],"1oSHI0": ["تعذّر تثبيت ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["الصورة ", ["identity"], " مستبعدة. انتقل إلى المرجع."],"1pdLQw": ["الصورة غير موجودة"],"1qpGKz": ["تعذّر حفظ التغييرات. حاول تعديل لون مرة أخرى."],"1ruosn": ["OpenKnowledge"],@@ -2091,6 +2092,7 @@"KIIamL": ["سينشئ OpenKnowledge إيداعات ويدفعها إلى مستودعك البعيد تلقائيًا. إن كنت لا تريد إيداعات تلقائية في سجل git لديك، فلا تفعّل المزامنة التلقائية."],+ "KJ_eAL": ["مستبعد"],"KOZud0": ["ابنِ قاعدة معرفة لبحث المنافسين. ابدأ بصفحة نظرة عامة، ثم أضف صفحات مترابطة لكل منافس، ومنتجاته وأسعاره، والمصادر وراء كل ادعاء."],@@ -4655,6 +4657,11 @@"gp3I7-": ["قبل المزامنة، اضبط هويتك لإيداعات git:"],"gpbKxw": ["التحقق من الروابط غير متاح."],"gqk-3R": ["تم نقل ", ["0"], " إلى ", ["destination"], "."],+ "gssxm9": [+ "هدف الرابط \"",+ ["shown"],+ "\" موجود، لكن .gitignore أو .okignore يستبعده. أعد تضمينه، أو مجلده، بقاعدة \"!\" في .okignore."+ ],"gtEbeW": ["تظليل"],"guidance.mcp.managed-file": ["يكتب ملف جسر صغيرًا يحمّله ",@@ -5639,6 +5646,7 @@"phM8Kh": ["عُثر على المستودع لكن تعذّر فتح المشروع. يرجى المحاولة مرة أخرى."],"pha01Y": ["صفحات على مستوى المشروع بلا حواف واردة في الرسم البياني."],"pkAft1": ["فشل البحث."],+ "pkC8Fi": ["الملف ", ["identity"], " مستبعد. انتقل إلى المرجع."],"pkmXTp": [["agentName"], " جاهز"],"pmUArF": ["مساحة العمل"],"poAsUN": ["بدون وكلاء — تُحفظ ولا تُثبَّت في أي مكان"],@@ -5674,6 +5682,11 @@"q63KUv": ["إضافة MCP ومهارة"],"q7F5am": ["العنوان"],"q8aCbb": ["نسختان من «", ["0"], "» — المصدر مقابل ", ["editor"]],+ "qAC6UE": [+ "هدف الصورة \"",+ ["shown"],+ "\" موجود، لكن .gitignore أو .okignore يستبعده. أعد تضمينه، أو مجلده، بقاعدة \"!\" في .okignore."+ ],"qAQVSD": ["لم تكن استجابة عناوين الصفحة بصيغة JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 23b2137ff..81b242264 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -6034,6 +6034,18 @@ msgstr "تعذر تحميل لوحة Excalidraw."msgid "Excalidraw canvas"msgstr "لوحة Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "مستبعد"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "الملف {identity} مستبعد. انتقل إلى المرجع."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "الصورة {identity} مستبعدة. انتقل إلى المرجع."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "سيُسحب الفرع الموجود <0>{trimmed}</0> إلى نافذته الخاصة، تحت <1>.ok/worktrees/</1>."@@ -7536,6 +7548,10 @@ msgstr "تعذّر تحويل هدف الصورة \"{shown}\" إلى ملف محmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "هدف الصورة \"{shown}\" لا يشير إلى ملف موجود."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "هدف الصورة \"{shown}\" موجود، لكن .gitignore أو .okignore يستبعده. أعد تضمينه، أو مجلده، بقاعدة \"!\" في .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "لا تُحجب المعلومات الحساسة في الصور."@@ -8316,6 +8332,10 @@ msgstr "هدف الرابط \"{shown}\" لا يشير إلى مستند موجوmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "هدف الرابط \"{shown}\" لا يشير إلى ملف موجود."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "هدف الرابط \"{shown}\" موجود، لكن .gitignore أو .okignore يستبعده. أعد تضمينه، أو مجلده، بقاعدة \"!\" في .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "اربط النص المحدد، أو حرّر الرابط الواقع تحت المؤشر."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex a0fb40df1..b20c99605 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -227,6 +227,7 @@"1njn7W": ["হালকা"],"1nke1r": [["0"], " GitHub-এ খুলুন (নতুন ট্যাবে খোলে)"],"1oSHI0": [["skillName"], " ইনস্টল করা যায়নি: ", ["0"]],+ "1ouiTz": ["বাদ দেওয়া ছবি ", ["identity"], "। রেফারেন্সে যান।"],"1pdLQw": ["ছবি পাওয়া যায়নি"],"1qpGKz": ["পরিবর্তনগুলি সংরক্ষণ করা যায়নি। একটি রং আবার সম্পাদনা করে দেখুন।"],"1ruosn": ["OpenKnowledge"],@@ -1783,6 +1784,7 @@"KIIamL": ["OpenKnowledge কমিট তৈরি করে নিজে থেকেই আপনার রিমোটে পাঠাবে। আপনি যদি আপনার git ইতিহাসে স্বয়ংক্রিয় কমিট না চান, তবে স্বয়ংক্রিয় সিঙ্ক চালু করা উচিত নয়।"],+ "KJ_eAL": ["বাদ দেওয়া"],"KOZud0": ["প্রতিযোগী গবেষণার একটি জ্ঞানভাণ্ডার গড়ুন। একটি সংক্ষিপ্তসার পাতা দিয়ে শুরু করুন, তারপর প্রতিটি প্রতিযোগী, তাদের পণ্য ও মূল্য, এবং প্রতিটি দাবির পেছনের উৎসের জন্য পরস্পর-যুক্ত পাতা যোগ করুন।"],@@ -3889,6 +3891,11 @@"gp3I7-": ["সিঙ্ক করার আগে git কমিটের জন্য আপনার পরিচয় নির্ধারণ করুন:"],"gpbKxw": ["লিংক যাচাইকরণ উপলভ্য নয়।"],"gqk-3R": [["0"], "-কে ", ["destination"], "-এ সরানো হয়েছে।"],+ "gssxm9": [+ "লিংকের লক্ষ্য \"",+ ["shown"],+ "\" বিদ্যমান, কিন্তু .gitignore বা .okignore সেটিকে বাদ দিয়েছে। .okignore-এ একটি \"!\" নিয়ম দিয়ে সেটিকে, বা তার ফোল্ডারকে, আবার অন্তর্ভুক্ত করুন।"+ ],"gtEbeW": ["হাইলাইট"],"guidance.mcp.managed-file": ["একটি ছোট ব্রিজ ফাইল লেখে, যা ",@@ -4757,6 +4764,7 @@"phM8Kh": ["রিপোজিটরি পাওয়া গেছে কিন্তু প্রকল্পটি খোলা যায়নি। অনুগ্রহ করে আবার চেষ্টা করুন।"],"pha01Y": ["যেসব প্রকল্প-স্তরের পাতার কোনো আগত গ্রাফ প্রান্ত নেই।"],"pkAft1": ["অনুসন্ধান ব্যর্থ।"],+ "pkC8Fi": ["বাদ দেওয়া ফাইল ", ["identity"], "। রেফারেন্সে যান।"],"pkmXTp": [["agentName"], " প্রস্তুত"],"pmUArF": ["ওয়ার্কস্পেস"],"poAsUN": ["কোনো এজেন্ট নেই — সংরক্ষিত, কোথাও ইনস্টল হয়নি"],@@ -4792,6 +4800,11 @@"q63KUv": ["MCP ও স্কিল যোগ করুন"],"q7F5am": ["শিরোনাম"],"q8aCbb": ["\"", ["0"], "\"-এর দুটি সংস্করণ — উৎস বনাম ", ["editor"]],+ "qAC6UE": [+ "ছবির লক্ষ্য \"",+ ["shown"],+ "\" বিদ্যমান, কিন্তু .gitignore বা .okignore সেটিকে বাদ দিয়েছে। .okignore-এ একটি \"!\" নিয়ম দিয়ে সেটিকে, বা তার ফোল্ডারকে, আবার অন্তর্ভুক্ত করুন।"+ ],"qAQVSD": ["পাতার শিরোনামের সাড়া JSON ছিল না"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 257252923..c13df17d5 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -6030,6 +6030,18 @@ msgstr "Excalidraw বোর্ড লোড করা যায়নি।"msgid "Excalidraw canvas"msgstr "Excalidraw ক্যানভাস"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "বাদ দেওয়া"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "বাদ দেওয়া ফাইল {identity}। রেফারেন্সে যান।"++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "বাদ দেওয়া ছবি {identity}। রেফারেন্সে যান।"+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "বিদ্যমান ব্রাঞ্চ <0>{trimmed}</0> <1>.ok/worktrees/</1>-এর নিচে নিজের জানালায় চেক আউট করা হবে।"@@ -7532,6 +7544,10 @@ msgstr "ছবির লক্ষ্য \"{shown}\"-কে প্রকল্পmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "ছবির লক্ষ্য \"{shown}\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "ছবির লক্ষ্য \"{shown}\" বিদ্যমান, কিন্তু .gitignore বা .okignore সেটিকে বাদ দিয়েছে। .okignore-এ একটি \"!\" নিয়ম দিয়ে সেটিকে, বা তার ফোল্ডারকে, আবার অন্তর্ভুক্ত করুন।"+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "ছবির সংবেদনশীল তথ্য আড়াল করা হয় না।"@@ -8312,6 +8328,10 @@ msgstr "লিংকের লক্ষ্য \"{shown}\" কোনো বিদmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "লিংকের লক্ষ্য \"{shown}\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "লিংকের লক্ষ্য \"{shown}\" বিদ্যমান, কিন্তু .gitignore বা .okignore সেটিকে বাদ দিয়েছে। .okignore-এ একটি \"!\" নিয়ম দিয়ে সেটিকে, বা তার ফোল্ডারকে, আবার অন্তর্ভুক্ত করুন।"+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "নির্বাচিত লেখাটি লিংক করুন, বা কার্সরের নিচের লিংকটি সম্পাদনা করুন।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 9e3019c1b..3736c40f9 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -235,6 +235,7 @@"1njn7W": ["Light"],"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],"1oSHI0": ["Couldn't install ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["Excluded image ", ["identity"], ". Go to reference."],"1pdLQw": ["Image not found"],"1qpGKz": ["Couldn’t save changes. Try editing a color again."],"1ruosn": ["OpenKnowledge"],@@ -1846,6 +1847,7 @@"KIIamL": ["OpenKnowledge will create commits and push them to your remote automatically. If you do not want automatic commits in your git history, you should not enable auto-sync."],+ "KJ_eAL": ["Excluded"],"KOZud0": ["Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."],@@ -4017,6 +4019,11 @@"gp3I7-": ["Before syncing, set your identity for git commits:"],"gpbKxw": ["Link validation is unavailable."],"gqk-3R": ["Moved ", ["0"], " to ", ["destination"], "."],+ "gssxm9": [+ "Link target \"",+ ["shown"],+ "\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+ ],"gtEbeW": ["Highlight"],"guidance.mcp.managed-file": ["Writes a small bridge file ",@@ -4918,6 +4925,7 @@"phM8Kh": ["Found the repo but could not open the project. Please try again."],"pha01Y": ["Project-level pages with no incoming graph edges."],"pkAft1": ["Search failed."],+ "pkC8Fi": ["Excluded file ", ["identity"], ". Go to reference."],"pkmXTp": [["agentName"], " is ready"],"pmUArF": ["Workspace"],"poAsUN": ["no agents — saved, not installed anywhere"],@@ -4955,6 +4963,11 @@"q63KUv": ["Add MCP & skill"],"q7F5am": ["title"],"q8aCbb": ["Two versions of \"", ["0"], "\" — source vs ", ["editor"]],+ "qAC6UE": [+ "Image target \"",+ ["shown"],+ "\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+ ],"qAQVSD": ["Page headings response was not JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex fc911662c..5442b6076 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -6034,6 +6034,18 @@ msgstr "Excalidraw board failed to load."msgid "Excalidraw canvas"msgstr "Excalidraw canvas"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Excluded"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "Excluded file {identity}. Go to reference."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "Excluded image {identity}. Go to reference."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."@@ -7536,6 +7548,10 @@ msgstr "Image target \"{shown}\" could not be resolved to a project-local file."msgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "Image target \"{shown}\" does not resolve to an existing file."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "Images aren't redacted."@@ -8316,6 +8332,10 @@ msgstr "Link target \"{shown}\" does not resolve to an existing document."msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "Link target \"{shown}\" does not resolve to an existing file."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Link the selected text, or edit the link under the caret."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 23979526c..842fe6194 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -269,6 +269,7 @@"1njn7W": ["Claro"],"1nke1r": ["Abrir ", ["0"], " en GitHub (se abre en una pestaña nueva)"],"1oSHI0": ["No se pudo instalar ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["Imagen ", ["identity"], " excluida. Ir a la referencia."],"1pdLQw": ["No se encontró la imagen"],"1qpGKz": ["No se pudieron guardar los cambios. Intenta editar un color de nuevo."],"1ruosn": ["OpenKnowledge"],@@ -2142,6 +2143,7 @@"KIIamL": ["OpenKnowledge creará commits y los subirá a tu remoto automáticamente. Si no quieres commits automáticos en tu historial de git, no deberías activar la sincronización automática."],+ "KJ_eAL": ["Excluido"],"KOZud0": ["Crea una base de conocimiento de investigación de la competencia. Empieza con una página general y añade después páginas enlazadas entre sí para cada competidor, sus productos y precios, y las fuentes que respaldan cada afirmación."],@@ -4675,6 +4677,11 @@"gp3I7-": ["Antes de sincronizar, define tu identidad para los commits de git:"],"gpbKxw": ["La validación de enlaces no está disponible."],"gqk-3R": ["Se movió ", ["0"], " a ", ["destination"], "."],+ "gssxm9": [+ "El destino del enlace «",+ ["shown"],+ "» existe, pero .gitignore o .okignore lo excluye. Vuelve a incluirlo, o su carpeta, con una regla «!» en .okignore."+ ],"gtEbeW": ["Resaltado"],"guidance.mcp.managed-file": ["Escribe un pequeño archivo puente que ",@@ -5673,6 +5680,7 @@],"pha01Y": ["Páginas de todo el proyecto sin aristas entrantes en el grafo."],"pkAft1": ["Falló la búsqueda."],+ "pkC8Fi": ["Archivo ", ["identity"], " excluido. Ir a la referencia."],"pkmXTp": [["agentName"], " está listo"],"pmUArF": ["Espacio de trabajo"],"poAsUN": ["sin agentes — guardadas, no instaladas en ningún sitio"],@@ -5712,6 +5720,11 @@"q63KUv": ["Añadir MCP y habilidad"],"q7F5am": ["título"],"q8aCbb": ["Dos versiones de \"", ["0"], "\": el origen frente a ", ["editor"]],+ "qAC6UE": [+ "El destino de la imagen «",+ ["shown"],+ "» existe, pero .gitignore o .okignore lo excluye. Vuelve a incluirlo, o su carpeta, con una regla «!» en .okignore."+ ],"qAQVSD": ["La respuesta de los encabezados de página no era JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex bcabb0b7d..13c5e3a67 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -6034,6 +6034,18 @@ msgstr "No se pudo cargar la pizarra de Excalidraw."msgid "Excalidraw canvas"msgstr "Lienzo de Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Excluido"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "Archivo {identity} excluido. Ir a la referencia."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "Imagen {identity} excluida. Ir a la referencia."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "La rama existente <0>{trimmed}</0> se extraerá en su propia ventana, dentro de <1>.ok/worktrees/</1>."@@ -7536,6 +7548,10 @@ msgstr "El destino de la imagen «{shown}» no se pudo resolver como un archivomsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "El destino de la imagen «{shown}» no corresponde a un archivo existente."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "El destino de la imagen «{shown}» existe, pero .gitignore o .okignore lo excluye. Vuelve a incluirlo, o su carpeta, con una regla «!» en .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "Las imágenes no se censuran."@@ -8316,6 +8332,10 @@ msgstr "El destino del enlace «{shown}» no corresponde a un documento existentmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "El destino del enlace «{shown}» no corresponde a un archivo existente."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "El destino del enlace «{shown}» existe, pero .gitignore o .okignore lo excluye. Vuelve a incluirlo, o su carpeta, con una regla «!» en .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Enlaza el texto seleccionado o edita el enlace bajo el cursor."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 4afd8b2fd..7c6b771cc 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -279,6 +279,7 @@"1njn7W": ["Clair"],"1nke1r": ["Ouvrir ", ["0"], " sur GitHub (s'ouvre dans un nouvel onglet)"],"1oSHI0": ["Impossible d'installer ", ["skillName"], " : ", ["0"]],+ "1ouiTz": ["Image ", ["identity"], " exclue. Accéder à la référence."],"1pdLQw": ["Image introuvable"],"1qpGKz": ["Impossible d’enregistrer les modifications. Essayez à nouveau de modifier une couleur."@@ -2180,6 +2181,7 @@"KIIamL": ["OpenKnowledge créera des commits et les poussera automatiquement vers votre dépôt distant. Si vous ne voulez pas de commits automatiques dans votre historique git, n'activez pas la synchronisation automatique."],+ "KJ_eAL": ["Exclu"],"KOZud0": ["Construis une base de connaissances d'étude concurrentielle. Commence par une page de synthèse, puis ajoute des pages liées entre elles pour chaque concurrent, leurs produits et leurs tarifs, ainsi que les sources derrière chaque affirmation."],@@ -4714,6 +4716,11 @@"gp3I7-": ["Avant de synchroniser, définissez votre identité pour les commits git :"],"gpbKxw": ["La validation des liens est indisponible."],"gqk-3R": [["0"], " déplacé vers ", ["destination"], "."],+ "gssxm9": [+ "La cible du lien « ",+ ["shown"],+ " » existe, mais .gitignore ou .okignore l’exclut. Réincluez-la, ou son dossier, avec une règle « ! » dans .okignore."+ ],"gtEbeW": ["Surlignage"],"guidance.mcp.managed-file": ["Écrit un petit fichier passerelle que ",@@ -5732,6 +5739,7 @@"phM8Kh": ["Dépôt trouvé, mais le projet n'a pas pu être ouvert. Veuillez réessayer."],"pha01Y": ["Pages du projet sans arête entrante dans le graphe."],"pkAft1": ["La recherche a échoué."],+ "pkC8Fi": ["Fichier ", ["identity"], " exclu. Accéder à la référence."],"pkmXTp": [["agentName"], " est prêt"],"pmUArF": ["Espace de travail"],"poAsUN": ["aucun agent — enregistrées, installées nulle part"],@@ -5775,6 +5783,11 @@"q63KUv": ["Ajouter MCP et la compétence"],"q7F5am": ["titre"],"q8aCbb": ["Deux versions de « ", ["0"], " » — source contre ", ["editor"]],+ "qAC6UE": [+ "La cible de l’image « ",+ ["shown"],+ " » existe, mais .gitignore ou .okignore l’exclut. Réincluez-la, ou son dossier, avec une règle « ! » dans .okignore."+ ],"qAQVSD": ["La réponse des titres de page n'était pas du JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex bd50af228..ba9de0d53 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -6034,6 +6034,18 @@ msgstr "Le chargement du tableau Excalidraw a échoué."msgid "Excalidraw canvas"msgstr "Canevas Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Exclu"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "Fichier {identity} exclu. Accéder à la référence."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "Image {identity} exclue. Accéder à la référence."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "La branche existante <0>{trimmed}</0> sera extraite dans sa propre fenêtre, sous <1>.ok/worktrees/</1>."@@ -7536,6 +7548,10 @@ msgstr "La cible de l’image « {shown} » n’a pas pu être résolue en tanmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "La cible de l’image « {shown} » ne correspond à aucun fichier existant."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "La cible de l’image « {shown} » existe, mais .gitignore ou .okignore l’exclut. Réincluez-la, ou son dossier, avec une règle « ! » dans .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "Les images ne sont pas expurgées."@@ -8316,6 +8332,10 @@ msgstr "La cible du lien « {shown} » ne correspond à aucun document existanmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "La cible du lien « {shown} » ne correspond à aucun fichier existant."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "La cible du lien « {shown} » existe, mais .gitignore ou .okignore l’exclut. Réincluez-la, ou son dossier, avec une règle « ! » dans .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Ajoute un lien au texte sélectionné, ou modifie le lien situé sous le curseur."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 1f6755b0b..d5f2e330f 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -229,6 +229,7 @@"1njn7W": ["हल्का"],"1nke1r": [["0"], " को GitHub पर खोलें (नए टैब में खुलता है)"],"1oSHI0": [["skillName"], " इंस्टॉल नहीं की जा सकी: ", ["0"]],+ "1ouiTz": ["बहिष्कृत चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],"1pdLQw": ["छवि नहीं मिली"],"1qpGKz": ["बदलाव सहेजे नहीं जा सके। किसी रंग को फिर से संपादित करें।"],"1ruosn": ["OpenKnowledge"],@@ -1784,6 +1785,7 @@"KIIamL": ["OpenKnowledge कमिट बनाकर उन्हें अपने आप आपके रिमोट पर भेज देगा। यदि आप अपने git इतिहास में स्वचालित कमिट नहीं चाहते, तो आपको स्वत: सिंक सक्षम नहीं करना चाहिए।"],+ "KJ_eAL": ["बहिष्कृत"],"KOZud0": ["प्रतिस्पर्धी शोध का एक ज्ञान आधार बनाएँ। एक सिंहावलोकन पेज से शुरू करें, फिर हर प्रतिस्पर्धी, उनके उत्पादों और मूल्य-निर्धारण, और हर दावे के पीछे के स्रोतों के लिए आपस में जुड़े पेज जोड़ें।"],@@ -3880,6 +3882,11 @@"gp3I7-": ["सिंक करने से पहले, git कमिट के लिए अपनी पहचान सेट करें:"],"gpbKxw": ["लिंक सत्यापन उपलब्ध नहीं है।"],"gqk-3R": [["0"], " को ", ["destination"], " में ले जाया गया।"],+ "gssxm9": [+ "लिंक लक्ष्य \"",+ ["shown"],+ "\" मौजूद है, लेकिन .gitignore या .okignore ने उसे बहिष्कृत किया है। उसे, या उसके फ़ोल्डर को, .okignore में \"!\" नियम से फिर से शामिल करें।"+ ],"gtEbeW": ["उभारें"],"guidance.mcp.managed-file": ["एक छोटी ब्रिज फ़ाइल लिखता है, जिसे ",@@ -4748,6 +4755,7 @@"phM8Kh": ["रिपॉज़िटरी मिल गई पर प्रोजेक्ट नहीं खोला जा सका। कृपया फिर कोशिश करें।"],"pha01Y": ["वे प्रोजेक्ट-स्तर के पेज जिनके कोई आने वाले ग्राफ़ किनारे नहीं हैं।"],"pkAft1": ["खोज विफल।"],+ "pkC8Fi": ["बहिष्कृत फ़ाइल ", ["identity"], "। संदर्भ पर जाएँ।"],"pkmXTp": [["agentName"], " तैयार है"],"pmUArF": ["कार्यक्षेत्र"],"poAsUN": ["कोई एजेंट नहीं — सहेजी गईं, कहीं इंस्टॉल नहीं"],@@ -4783,6 +4791,11 @@"q63KUv": ["MCP और स्किल जोड़ें"],"q7F5am": ["शीर्षक"],"q8aCbb": ["\"", ["0"], "\" के दो संस्करण — स्रोत बनाम ", ["editor"]],+ "qAC6UE": [+ "चित्र लक्ष्य \"",+ ["shown"],+ "\" मौजूद है, लेकिन .gitignore या .okignore ने उसे बहिष्कृत किया है। उसे, या उसके फ़ोल्डर को, .okignore में \"!\" नियम से फिर से शामिल करें।"+ ],"qAQVSD": ["पेज शीर्षकों की प्रतिक्रिया JSON नहीं थी"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex d807da239..1a3516b7f 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -6030,6 +6030,18 @@ msgstr "Excalidraw बोर्ड लोड नहीं हो सका।"msgid "Excalidraw canvas"msgstr "Excalidraw कैनवास"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "बहिष्कृत"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "बहिष्कृत फ़ाइल {identity}। संदर्भ पर जाएँ।"++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "बहिष्कृत चित्र {identity}। संदर्भ पर जाएँ।"+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "मौजूदा ब्रांच <0>{trimmed}</0> को <1>.ok/worktrees/</1> के अंतर्गत उसकी अपनी विंडो में चेक आउट किया जाएगा।"@@ -7532,6 +7544,10 @@ msgstr "चित्र लक्ष्य \"{shown}\" को प्रोजेmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "चित्र लक्ष्य \"{shown}\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "चित्र लक्ष्य \"{shown}\" मौजूद है, लेकिन .gitignore या .okignore ने उसे बहिष्कृत किया है। उसे, या उसके फ़ोल्डर को, .okignore में \"!\" नियम से फिर से शामिल करें।"+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "चित्रों की संवेदनशील जानकारी नहीं छिपाई जाती।"@@ -8312,6 +8328,10 @@ msgstr "लिंक लक्ष्य \"{shown}\" किसी मौजूदmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "लिंक लक्ष्य \"{shown}\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "लिंक लक्ष्य \"{shown}\" मौजूद है, लेकिन .gitignore या .okignore ने उसे बहिष्कृत किया है। उसे, या उसके फ़ोल्डर को, .okignore में \"!\" नियम से फिर से शामिल करें।"+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "चयनित पाठ को लिंक करें, या कर्सर के नीचे वाला लिंक संपादित करें।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 2fc49035f..1fea3ddef 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -231,6 +231,7 @@"1njn7W": ["Terang"],"1nke1r": ["Buka ", ["0"], " di GitHub (terbuka di tab baru)"],"1oSHI0": [["skillName"], " tidak bisa dipasang: ", ["0"]],+ "1ouiTz": ["Gambar ", ["identity"], " dikecualikan. Buka referensi."],"1pdLQw": ["Gambar tidak ditemukan"],"1qpGKz": ["Perubahan tidak dapat disimpan. Coba sunting warna lagi."],"1ruosn": ["OpenKnowledge"],@@ -1875,6 +1876,7 @@"KIIamL": ["OpenKnowledge akan membuat commit dan mengirimkannya ke remote Anda secara otomatis. Jika Anda tidak ingin commit otomatis di riwayat git Anda, sebaiknya jangan aktifkan sinkronisasi otomatis."],+ "KJ_eAL": ["Dikecualikan"],"KOZud0": ["Bangun basis pengetahuan riset pesaing. Mulai dengan halaman ikhtisar, lalu tambahkan halaman yang saling tertaut untuk tiap pesaing, produk dan harganya, serta sumber di balik setiap klaim."],@@ -4020,6 +4022,11 @@"gp3I7-": ["Sebelum menyinkronkan, setel identitas Anda untuk commit git:"],"gpbKxw": ["Validasi tautan tidak tersedia."],"gqk-3R": [["0"], " dipindahkan ke ", ["destination"], "."],+ "gssxm9": [+ "Target tautan \"",+ ["shown"],+ "\" ada, tetapi dikecualikan oleh .gitignore atau .okignore. Sertakan kembali file itu, atau foldernya, dengan aturan \"!\" di .okignore."+ ],"gtEbeW": ["Sorotan"],"guidance.mcp.managed-file": ["Menulis berkas jembatan kecil yang dimuat ",@@ -4934,6 +4941,7 @@"phM8Kh": ["Repo ditemukan tetapi proyeknya tidak dapat dibuka. Silakan coba lagi."],"pha01Y": ["Halaman tingkat proyek yang tidak punya sisi graf masuk."],"pkAft1": ["Pencarian gagal."],+ "pkC8Fi": ["File ", ["identity"], " dikecualikan. Buka referensi."],"pkmXTp": [["agentName"], " siap"],"pmUArF": ["Ruang kerja"],"poAsUN": ["tanpa agen — disimpan, tidak dipasang di mana pun"],@@ -4973,6 +4981,11 @@"q63KUv": ["Tambahkan MCP & keterampilan"],"q7F5am": ["judul"],"q8aCbb": ["Dua versi \"", ["0"], "\" — sumber melawan ", ["editor"]],+ "qAC6UE": [+ "Target gambar \"",+ ["shown"],+ "\" ada, tetapi dikecualikan oleh .gitignore atau .okignore. Sertakan kembali file itu, atau foldernya, dengan aturan \"!\" di .okignore."+ ],"qAQVSD": ["Respons judul halaman bukan JSON"],"qAhFeg": [["userName"], " · ", ["tabCount", "plural", { "other": ["#", " tab"] }]],"qApCYm": ["Tidak disamarkan. Periksa gambar sebelum membagikannya."],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 0aa77dda5..79966b976 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -6030,6 +6030,18 @@ msgstr "Papan Excalidraw gagal dimuat."msgid "Excalidraw canvas"msgstr "Kanvas Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Dikecualikan"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "File {identity} dikecualikan. Buka referensi."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "Gambar {identity} dikecualikan. Buka referensi."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "Cabang yang sudah ada <0>{trimmed}</0> akan diambil ke jendelanya sendiri, di bawah <1>.ok/worktrees/</1>."@@ -7532,6 +7544,10 @@ msgstr "Target gambar \"{shown}\" tidak dapat dicocokkan dengan file lokal proyemsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "Target gambar \"{shown}\" tidak merujuk ke file yang ada."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Target gambar \"{shown}\" ada, tetapi dikecualikan oleh .gitignore atau .okignore. Sertakan kembali file itu, atau foldernya, dengan aturan \"!\" di .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "Gambar tidak disamarkan."@@ -8312,6 +8328,10 @@ msgstr "Target tautan \"{shown}\" tidak merujuk ke dokumen yang ada."msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "Target tautan \"{shown}\" tidak merujuk ke file yang ada."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Target tautan \"{shown}\" ada, tetapi dikecualikan oleh .gitignore atau .okignore. Sertakan kembali file itu, atau foldernya, dengan aturan \"!\" di .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Menautkan teks yang dipilih, atau menyunting tautan di bawah kursor."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 825329949..843724b0b 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -222,6 +222,7 @@"1njn7W": ["밝은 테마"],"1nke1r": ["GitHub에서 ", ["0"], " 열기 (새 탭에서 열림)"],"1oSHI0": [["skillName"], " 설치 실패: ", ["0"]],+ "1ouiTz": ["제외된 이미지 ", ["identity"], ". 참조로 이동합니다."],"1pdLQw": ["이미지를 찾을 수 없음"],"1qpGKz": ["변경사항을 저장하지 못했습니다. 색상을 다시 편집합니다."],"1ruosn": ["OpenKnowledge"],@@ -1794,6 +1795,7 @@"KIIamL": ["OpenKnowledge는 자동으로 커밋을 생성해 원격에 푸시합니다. git 기록에 자동 커밋을 남기고 싶지 않다면 자동 동기화를 사용하지 마세요."],+ "KJ_eAL": ["제외됨"],"KOZud0": ["경쟁사 조사를 위한 지식 베이스를 구축합니다. 개요 페이지로 시작한 다음, 각 경쟁사와 제품 및 가격, 모든 주장에 대한 출처를 서로 연결된 페이지로 추가합니다."],@@ -3859,6 +3861,11 @@"gp3I7-": ["동기화하기 전에 git 커밋에 사용할 사용자 정보를 설정하세요:"],"gpbKxw": ["링크 검증을 사용할 수 없습니다."],"gqk-3R": [["0"], "을 ", ["destination"], "으로 이동했습니다."],+ "gssxm9": [+ "링크 대상 \"",+ ["shown"],+ "\"은 존재하지만 .gitignore 또는 .okignore에 의해 제외되어 있습니다. .okignore에 \"!\" 규칙을 추가해 해당 파일 또는 폴더를 다시 포함하세요."+ ],"gtEbeW": ["강조 표시"],"guidance.mcp.managed-file": [["agent"],@@ -4718,6 +4725,7 @@"phM8Kh": ["저장소를 찾았지만 프로젝트를 열 수 없습니다. 다시 시도하세요."],"pha01Y": ["들어오는 그래프 연결이 없는 프로젝트 수준 페이지입니다."],"pkAft1": ["검색에 실패했습니다."],+ "pkC8Fi": ["제외된 파일 ", ["identity"], ". 참조로 이동합니다."],"pkmXTp": [["agentName"], " 준비 완료"],"pmUArF": ["워크스페이스"],"poAsUN": ["에이전트 없음 — 저장만 되고 어디에도 설치되지 않음"],@@ -4754,6 +4762,11 @@"q63KUv": ["MCP 및 스킬 추가"],"q7F5am": ["제목"],"q8aCbb": ["\"", ["0"], "\"의 두 버전. 소스와 ", ["editor"]],+ "qAC6UE": [+ "이미지 대상 \"",+ ["shown"],+ "\"은 존재하지만 .gitignore 또는 .okignore에 의해 제외되어 있습니다. .okignore에 \"!\" 규칙을 추가해 해당 파일 또는 폴더를 다시 포함하세요."+ ],"qAQVSD": ["페이지 제목 응답이 JSON이 아닙니다"],"qAhFeg": [["userName"], " · ", ["tabCount", "plural", { "other": ["탭 ", "#", "개"] }]],"qApCYm": ["민감 정보가 가려지지 않았습니다. 공유하기 전에 이미지를 확인하세요."],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 990a5214f..85be0e82b 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -6034,6 +6034,18 @@ msgstr "Excalidraw 보드를 불러오지 못했습니다."msgid "Excalidraw canvas"msgstr "Excalidraw 캔버스"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "제외됨"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "제외된 파일 {identity}. 참조로 이동합니다."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "제외된 이미지 {identity}. 참조로 이동합니다."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "기존 브랜치 <0>{trimmed}</0>는 별도 창의 <1>.ok/worktrees/</1> 아래에 체크아웃됩니다."@@ -7536,6 +7548,10 @@ msgstr "이미지 대상 \"{shown}\"을 프로젝트 로컬 파일로 확인할msgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "이미지 대상 \"{shown}\"이 존재하는 파일로 확인되지 않습니다."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "이미지 대상 \"{shown}\"은 존재하지만 .gitignore 또는 .okignore에 의해 제외되어 있습니다. .okignore에 \"!\" 규칙을 추가해 해당 파일 또는 폴더를 다시 포함하세요."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "이미지는 민감 정보가 가려지지 않습니다."@@ -8316,6 +8332,10 @@ msgstr "링크 대상 \"{shown}\"이 존재하는 문서로 확인되지 않습msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "링크 대상 \"{shown}\"이 존재하는 파일로 확인되지 않습니다."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "링크 대상 \"{shown}\"은 존재하지만 .gitignore 또는 .okignore에 의해 제외되어 있습니다. .okignore에 \"!\" 규칙을 추가해 해당 파일 또는 폴더를 다시 포함하세요."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "선택한 텍스트에 링크를 추가하거나 커서 아래의 링크를 편집합니다."diff --git a/packages/app/src/locales/pl/messages.json b/packages/app/src/locales/pl/messages.jsonindex 310245a95..53276ad2c 100644--- a/packages/app/src/locales/pl/messages.json+++ b/packages/app/src/locales/pl/messages.json@@ -288,6 +288,7 @@"1njn7W": ["Jasny"],"1nke1r": ["Otwórz ", ["0"], " na GitHubie (otwiera w nowej karcie)"],"1oSHI0": ["Nie udało się zainstalować ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["Wykluczony obraz ", ["identity"], ". Przejdź do odnośnika."],"1pdLQw": ["Nie znaleziono obrazu"],"1qpGKz": ["Nie udało się zapisać zmian. Spróbuj ponownie edytować kolor."],"1ruosn": ["OpenKnowledge"],@@ -2177,6 +2178,7 @@"KIIamL": ["OpenKnowledge będzie automatycznie tworzyć commity i wysyłać je do zdalnego repozytorium. Jeśli nie chcesz automatycznych commitów w historii git, nie włączaj synchronizacji automatycznej."],+ "KJ_eAL": ["Wykluczone"],"KOZud0": ["Zbuduj bazę wiedzy do badań konkurencji. Zacznij od strony przeglądu, a potem dodaj powiązane linkami strony dla każdej konkurencji, ich produktów i cen oraz źródeł stojących za każdym twierdzeniem."],@@ -4778,6 +4780,11 @@"gp3I7-": ["Przed synchronizacją ustaw swoją tożsamość dla commitów git:"],"gpbKxw": ["Walidacja linków jest niedostępna."],"gqk-3R": ["Przeniesiono ", ["0"], " do ", ["destination"], "."],+ "gssxm9": [+ "Cel linku „",+ ["shown"],+ "” istnieje, ale wyklucza go .gitignore lub .okignore. Dołącz go ponownie, lub jego folder, regułą „!” w .okignore."+ ],"gtEbeW": ["Podświetlenie"],"guidance.mcp.managed-file": ["Zapisuje niewielki plik mostkowy, który ",@@ -5805,6 +5812,7 @@"phM8Kh": ["Znaleziono repozytorium, ale nie udało się otworzyć projektu. Spróbuj ponownie."],"pha01Y": ["Strony projektu bez krawędzi przychodzących w grafie."],"pkAft1": ["Wyszukiwanie nie powiodło się."],+ "pkC8Fi": ["Wykluczony plik ", ["identity"], ". Przejdź do odnośnika."],"pkmXTp": [["agentName"], " jest gotowy"],"pmUArF": ["Obszar roboczy"],"poAsUN": ["brak agentów — zapisano, nie zainstalowano nigdzie"],@@ -5844,6 +5852,11 @@"q63KUv": ["Dodaj MCP i umiejętność"],"q7F5am": ["tytuł"],"q8aCbb": ["Dwie wersje „", ["0"], "” — źródło wobec ", ["editor"]],+ "qAC6UE": [+ "Cel obrazu „",+ ["shown"],+ "” istnieje, ale wyklucza go .gitignore lub .okignore. Dołącz go ponownie, lub jego folder, regułą „!” w .okignore."+ ],"qAQVSD": ["Odpowiedź z nagłówkami strony nie była w formacie JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.poindex 0a718e70b..c133b8a7a 100644--- a/packages/app/src/locales/pl/messages.po+++ b/packages/app/src/locales/pl/messages.po@@ -6034,6 +6034,18 @@ msgstr "Nie udało się wczytać tablicy Excalidraw."msgid "Excalidraw canvas"msgstr "Płótno Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Wykluczone"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "Wykluczony plik {identity}. Przejdź do odnośnika."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "Wykluczony obraz {identity}. Przejdź do odnośnika."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "Istniejąca gałąź <0>{trimmed}</0> zostanie przełączona do własnego okna, w <1>.ok/worktrees/</1>."@@ -7536,6 +7548,10 @@ msgstr "Nie udało się rozwiązać celu obrazu „{shown}” na plik lokalny dlmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "Cel obrazu „{shown}” nie wskazuje na istniejący plik."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Cel obrazu „{shown}” istnieje, ale wyklucza go .gitignore lub .okignore. Dołącz go ponownie, lub jego folder, regułą „!” w .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "Obrazy nie są anonimizowane."@@ -8316,6 +8332,10 @@ msgstr "Cel linku „{shown}” nie wskazuje na istniejący dokument."msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "Cel linku „{shown}” nie wskazuje na istniejący plik."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "Cel linku „{shown}” istnieje, ale wyklucza go .gitignore lub .okignore. Dołącz go ponownie, lub jego folder, regułą „!” w .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Utwórz link z zaznaczonego tekstu lub edytuj link pod kursorem."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 9a7510a80..01701bb85 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -235,6 +235,7 @@"1njn7W": ["Ĺĩĝĥţ"],"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],"1oSHI0": ["Ćōũĺďń'ţ ĩńśţàĺĺ ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["Ēxćĺũďēď ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],"1pdLQw": ["Ĩḿàĝē ńōţ ƒōũńď"],"1qpGKz": ["Ćōũĺďń’ţ śàvē ćĥàńĝēś. Ţŕŷ ēďĩţĩńĝ à ćōĺōŕ àĝàĩń."],"1ruosn": ["ŌƥēńĶńōŵĺēďĝē"],@@ -1846,6 +1847,7 @@"KIIamL": ["ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ćŕēàţē ćōḿḿĩţś àńď ƥũśĥ ţĥēḿ ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ. Ĩƒ ŷōũ ďō ńōţ ŵàńţ àũţōḿàţĩć ćōḿḿĩţś ĩń ŷōũŕ ĝĩţ ĥĩśţōŕŷ, ŷōũ śĥōũĺď ńōţ ēńàƀĺē àũţō-śŷńć."],+ "KJ_eAL": ["Ēxćĺũďēď"],"KOZud0": ["ßũĩĺď à ćōḿƥēţĩţōŕ ŕēśēàŕćĥ ķńōŵĺēďĝē ƀàśē. Śţàŕţ ŵĩţĥ àń ōvēŕvĩēŵ ƥàĝē, ţĥēń àďď ćŕōśś-ĺĩńķēď ƥàĝēś ƒōŕ ēàćĥ ćōḿƥēţĩţōŕ, ţĥēĩŕ ƥŕōďũćţś àńď ƥŕĩćĩńĝ, àńď ţĥē śōũŕćēś ƀēĥĩńď ēvēŕŷ ćĺàĩḿ."],@@ -4017,6 +4019,11 @@"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],"gpbKxw": ["Ĺĩńķ vàĺĩďàţĩōń ĩś ũńàvàĩĺàƀĺē."],"gqk-3R": ["Ḿōvēď ", ["0"], " ţō ", ["destination"], "."],+ "gssxm9": [+ "Ĺĩńķ ţàŕĝēţ \"",+ ["shown"],+ "\" ēxĩśţś ƀũţ ĩś ēxćĺũďēď ƀŷ .ĝĩţĩĝńōŕē ōŕ .ōķĩĝńōŕē. Ŕē-ĩńćĺũďē ĩţ, ōŕ ĩţś ƒōĺďēŕ, ŵĩţĥ à \"!\" ŕũĺē ĩń .ōķĩĝńōŕē."+ ],"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],"guidance.mcp.managed-file": ["Ŵŕĩţēś à śḿàĺĺ ƀŕĩďĝē ƒĩĺē ",@@ -4918,6 +4925,7 @@"phM8Kh": ["Ƒōũńď ţĥē ŕēƥō ƀũţ ćōũĺď ńōţ ōƥēń ţĥē ƥŕōĴēćţ. Ƥĺēàśē ţŕŷ àĝàĩń."],"pha01Y": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ĩńćōḿĩńĝ ĝŕàƥĥ ēďĝēś."],"pkAft1": ["Śēàŕćĥ ƒàĩĺēď."],+ "pkC8Fi": ["Ēxćĺũďēď ƒĩĺē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],"pkmXTp": [["agentName"], " ĩś ŕēàďŷ"],"pmUArF": ["Ŵōŕķśƥàćē"],"poAsUN": ["ńō àĝēńţś — śàvēď, ńōţ ĩńśţàĺĺēď àńŷŵĥēŕē"],@@ -4955,6 +4963,11 @@"q63KUv": ["Àďď ḾĆƤ & śķĩĺĺ"],"q7F5am": ["ţĩţĺē"],"q8aCbb": ["Ţŵō vēŕśĩōńś ōƒ \"", ["0"], "\" — śōũŕćē vś ", ["editor"]],+ "qAC6UE": [+ "Ĩḿàĝē ţàŕĝēţ \"",+ ["shown"],+ "\" ēxĩśţś ƀũţ ĩś ēxćĺũďēď ƀŷ .ĝĩţĩĝńōŕē ōŕ .ōķĩĝńōŕē. Ŕē-ĩńćĺũďē ĩţ, ōŕ ĩţś ƒōĺďēŕ, ŵĩţĥ à \"!\" ŕũĺē ĩń .ōķĩĝńōŕē."+ ],"qAQVSD": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ŵàś ńōţ ĵŚŌŃ"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex d77ca9a30..b8e454439 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -6030,6 +6030,18 @@ msgstr ""msgid "Excalidraw canvas"msgstr ""+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr ""++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr ""++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr ""+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr ""@@ -7532,6 +7544,10 @@ msgstr ""msgid "Image target \"{shown}\" does not resolve to an existing file."msgstr ""+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr ""+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr ""@@ -8312,6 +8328,10 @@ msgstr ""msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr ""+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 98cea777c..d89fe94ec 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -269,6 +269,7 @@"1njn7W": ["Claro"],"1nke1r": ["Abrir ", ["0"], " no GitHub (abre em uma nova aba)"],"1oSHI0": ["Não deu para instalar ", ["skillName"], ": ", ["0"]],+ "1ouiTz": ["A imagem ", ["identity"], " está ignorada. Ir para a referência."],"1pdLQw": ["Imagem não encontrada"],"1qpGKz": ["Não foi possível salvar as alterações. Tente editar uma cor novamente."],"1ruosn": ["OpenKnowledge"],@@ -2115,6 +2116,7 @@"KIIamL": ["O OpenKnowledge vai criar commits e enviá-los ao seu remoto automaticamente. Se você não quer commits automáticos no seu histórico do git, não deve ativar a sincronização automática."],+ "KJ_eAL": ["Ignorado"],"KOZud0": ["Monte uma base de conhecimento sobre a concorrência. Comece com uma página geral e depois acrescente páginas interligadas para cada concorrente, seus produtos e preços, e as fontes por trás de cada afirmação."],@@ -4577,6 +4579,11 @@"gp3I7-": ["Antes de sincronizar, defina sua identidade para os commits do git:"],"gpbKxw": ["A validação de links não está disponível."],"gqk-3R": [["0"], " movido para ", ["destination"], "."],+ "gssxm9": [+ "O destino do link \"",+ ["shown"],+ "\" existe, mas é ignorado por .gitignore ou .okignore. Inclua-o de novo, ou a pasta dele, com uma regra \"!\" em .okignore."+ ],"gtEbeW": ["Destaque"],"guidance.mcp.managed-file": ["Grava um pequeno arquivo de ponte que o ",@@ -5558,6 +5565,7 @@],"pha01Y": ["Páginas de todo o projeto sem arestas de entrada no grafo."],"pkAft1": ["A busca falhou."],+ "pkC8Fi": ["O arquivo ", ["identity"], " está ignorado. Ir para a referência."],"pkmXTp": [["agentName"], " está pronto"],"pmUArF": ["Espaço de trabalho"],"poAsUN": ["nenhum agente — salvas, não instaladas em lugar algum"],@@ -5597,6 +5605,11 @@"q63KUv": ["Adicionar MCP e habilidade"],"q7F5am": ["título"],"q8aCbb": ["Duas versões de \"", ["0"], "\" — a fonte contra ", ["editor"]],+ "qAC6UE": [+ "O destino da imagem \"",+ ["shown"],+ "\" existe, mas é ignorado por .gitignore ou .okignore. Inclua-o de novo, ou a pasta dele, com uma regra \"!\" em .okignore."+ ],"qAQVSD": ["A resposta dos títulos da página não era JSON"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 92c741e07..c104035f1 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -6030,6 +6030,18 @@ msgstr "Falha ao carregar o quadro do Excalidraw."msgid "Excalidraw canvas"msgstr "Tela do Excalidraw"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "Ignorado"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "O arquivo {identity} está ignorado. Ir para a referência."++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "A imagem {identity} está ignorada. Ir para a referência."+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "O ramo existente <0>{trimmed}</0> será extraído em uma janela própria, dentro de <1>.ok/worktrees/</1>."@@ -7532,6 +7544,10 @@ msgstr "O destino da imagem \"{shown}\" não pôde ser resolvido como um arquivomsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "O destino da imagem \"{shown}\" não corresponde a um arquivo existente."+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "O destino da imagem \"{shown}\" existe, mas é ignorado por .gitignore ou .okignore. Inclua-o de novo, ou a pasta dele, com uma regra \"!\" em .okignore."+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "As imagens não são censuradas."@@ -8312,6 +8328,10 @@ msgstr "O destino do link \"{shown}\" não corresponde a um documento existente.msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "O destino do link \"{shown}\" não corresponde a um arquivo existente."+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "O destino do link \"{shown}\" existe, mas é ignorado por .gitignore ou .okignore. Inclua-o de novo, ou a pasta dele, com uma regra \"!\" em .okignore."+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "Cria um link no texto selecionado ou edita o link sob o cursor."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex c3b659349..f17de6f8b 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -234,6 +234,7 @@"1njn7W": ["روشن"],"1nke1r": [["0"], " کو GitHub پر کھولیں (نئے ٹیب میں کھلتا ہے)"],"1oSHI0": [["skillName"], " نصب نہیں ہو سکی: ", ["0"]],+ "1ouiTz": ["خارج شدہ تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],"1pdLQw": ["تصویر نہیں ملی"],"1qpGKz": ["تبدیلیاں محفوظ نہیں ہو سکیں۔ کسی رنگ میں دوبارہ ترمیم کر کے دیکھیں۔"],"1ruosn": ["OpenKnowledge"],@@ -1876,6 +1877,7 @@"KIIamL": ["OpenKnowledge کمٹس بنا کر خودکار طور پر آپ کے ریموٹ پر پُش کرے گا۔ اگر آپ اپنی git تاریخ میں خودکار کمٹس نہیں چاہتے تو خودکار مطابقت پذیری فعال نہ کریں۔"],+ "KJ_eAL": ["خارج شدہ"],"KOZud0": ["حریفوں کی تحقیق کا نالج بیس بنائیں۔ ایک جائزہ صفحے سے شروع کریں، پھر ہر حریف، ان کی مصنوعات اور قیمتوں، اور ہر دعوے کے پیچھے موجود مآخذ کے لیے باہم مربوط صفحات شامل کریں۔"],@@ -4094,6 +4096,11 @@"gp3I7-": ["مطابقت پذیری سے پہلے، git کمٹس کے لیے اپنی شناخت مقرر کریں:"],"gpbKxw": ["لنک کی توثیق دستیاب نہیں ہے۔"],"gqk-3R": [["0"], " کو ", ["destination"], " میں منتقل کر دیا گیا۔"],+ "gssxm9": [+ "لنک کا ہدف \"",+ ["shown"],+ "\" موجود ہے، لیکن .gitignore یا .okignore نے اسے خارج کر رکھا ہے۔ اسے، یا اس کے فولڈر کو، .okignore میں \"!\" اصول کے ذریعے دوبارہ شامل کریں۔"+ ],"gtEbeW": ["نمایاں کریں"],"guidance.mcp.managed-file": ["ایک چھوٹی برج فائل لکھتا ہے جسے ",@@ -5008,6 +5015,7 @@"phM8Kh": ["ریپو مل گیا مگر پروجیکٹ نہیں کھل سکا۔ براہِ کرم دوبارہ کوشش کریں۔"],"pha01Y": ["پروجیکٹ کی سطح کے وہ صفحات جن کے گراف میں آنے والے کنارے نہیں۔"],"pkAft1": ["تلاش ناکام رہی۔"],+ "pkC8Fi": ["خارج شدہ فائل ", ["identity"], "۔ حوالہ پر جائیں۔"],"pkmXTp": [["agentName"], " تیار ہے"],"pmUArF": ["ورک اسپیس"],"poAsUN": ["کوئی ایجنٹ نہیں — محفوظ، کہیں نصب نہیں"],@@ -5047,6 +5055,11 @@"q63KUv": ["MCP اور اسکل شامل کریں"],"q7F5am": ["عنوان"],"q8aCbb": ["«", ["0"], "» کے دو ورژن — ماخذ بمقابلہ ", ["editor"]],+ "qAC6UE": [+ "تصویر کا ہدف \"",+ ["shown"],+ "\" موجود ہے، لیکن .gitignore یا .okignore نے اسے خارج کر رکھا ہے۔ اسے، یا اس کے فولڈر کو، .okignore میں \"!\" اصول کے ذریعے دوبارہ شامل کریں۔"+ ],"qAQVSD": ["صفحے کے عنوانات کا جواب JSON نہیں تھا"],"qAhFeg": [["userName"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 0ed4021c9..57c3ae8ce 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -6034,6 +6034,18 @@ msgstr "Excalidraw بورڈ لوڈ نہیں ہو سکا۔"msgid "Excalidraw canvas"msgstr "Excalidraw کینوس"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "خارج شدہ"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "خارج شدہ فائل {identity}۔ حوالہ پر جائیں۔"++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "خارج شدہ تصویر {identity}۔ حوالہ پر جائیں۔"+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "موجودہ برانچ <0>{trimmed}</0> اپنی الگ ونڈو میں، <1>.ok/worktrees/</1> کے تحت چیک آؤٹ ہو گی۔"@@ -7536,6 +7548,10 @@ msgstr "تصویر کے ہدف \"{shown}\" کو پروجیکٹ کی مقامیmsgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "تصویر کا ہدف \"{shown}\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "تصویر کا ہدف \"{shown}\" موجود ہے، لیکن .gitignore یا .okignore نے اسے خارج کر رکھا ہے۔ اسے، یا اس کے فولڈر کو، .okignore میں \"!\" اصول کے ذریعے دوبارہ شامل کریں۔"+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "تصاویر کی حساس معلومات نہیں چھپائی جاتیں۔"@@ -8316,6 +8332,10 @@ msgstr "لنک کا ہدف \"{shown}\" کسی موجودہ دستاویز کیmsgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "لنک کا ہدف \"{shown}\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "لنک کا ہدف \"{shown}\" موجود ہے، لیکن .gitignore یا .okignore نے اسے خارج کر رکھا ہے۔ اسے، یا اس کے فولڈر کو، .okignore میں \"!\" اصول کے ذریعے دوبارہ شامل کریں۔"+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "منتخب متن کو لنک کریں، یا کرسر کے نیچے موجود لنک میں ترمیم کریں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 8f4b39c79..a2fac9752 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -207,6 +207,7 @@"1njn7W": ["浅色"],"1nke1r": ["在 GitHub 上打开 ", ["0"], "(在新标签页中打开)"],"1oSHI0": ["无法安装 ", ["skillName"], ":", ["0"]],+ "1ouiTz": ["已排除的图片 ", ["identity"], "。转到引用位置。"],"1pdLQw": ["找不到图片"],"1qpGKz": ["无法保存更改。请再次编辑颜色。"],"1ruosn": ["OpenKnowledge"],@@ -1611,6 +1612,7 @@"KIIamL": ["OpenKnowledge 会自动创建提交并推送到你的远程仓库。如果你不希望 git 历史中出现自动提交,就不应该启用自动同步。"],+ "KJ_eAL": ["已排除"],"KOZud0": ["搭建一个竞品调研知识库。先写一页总览,再为每个竞争对手、他们的产品与定价,以及每条论断背后的信息来源添加相互链接的页面。"],@@ -3490,6 +3492,11 @@"gp3I7-": ["同步之前,请设置你用于 git 提交的身份:"],"gpbKxw": ["链接验证不可用。"],"gqk-3R": ["已将 ", ["0"], " 移动到 ", ["destination"], "。"],+ "gssxm9": [+ "链接目标“",+ ["shown"],+ "”存在,但被 .gitignore 或 .okignore 排除。请在 .okignore 中添加“!”规则,重新包含该文件或其文件夹。"+ ],"gtEbeW": ["高亮"],"guidance.mcp.managed-file": ["写入一个小的桥接文件,",@@ -4283,6 +4290,7 @@"phM8Kh": ["找到了仓库,但无法打开项目。请重试。"],"pha01Y": ["没有入链的项目级页面。"],"pkAft1": ["搜索失败。"],+ "pkC8Fi": ["已排除的文件 ", ["identity"], "。转到引用位置。"],"pkmXTp": [["agentName"], " 已就绪"],"pmUArF": ["工作区"],"poAsUN": ["未选择智能体 — 仅保存,不安装到任何位置"],@@ -4318,6 +4326,11 @@"q63KUv": ["添加 MCP 和技能"],"q7F5am": ["标题"],"q8aCbb": ["“", ["0"], "”有两个版本——来源与 ", ["editor"]],+ "qAC6UE": [+ "图片目标“",+ ["shown"],+ "”存在,但被 .gitignore 或 .okignore 排除。请在 .okignore 中添加“!”规则,重新包含该文件或其文件夹。"+ ],"qAQVSD": ["页面标题响应不是 JSON"],"qAhFeg": [["userName"], " · ", ["tabCount", "plural", { "other": ["#", " 个标签页"] }]],"qApCYm": ["未经脱敏。分享前请检查图片。"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 8551b81ed..58828e0d2 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -6034,6 +6034,18 @@ msgstr "Excalidraw 画板加载失败。"msgid "Excalidraw canvas"msgstr "Excalidraw 画布"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "已排除"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "已排除的文件 {identity}。转到引用位置。"++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "已排除的图片 {identity}。转到引用位置。"+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "已有分支 <0>{trimmed}</0> 会被检出到自己的窗口中,位于 <1>.ok/worktrees/</1> 下。"@@ -7536,6 +7548,10 @@ msgstr "无法将图片目标“{shown}”解析为项目本地文件。"msgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "图片目标“{shown}”未指向现有文件。"+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "图片目标“{shown}”存在,但被 .gitignore 或 .okignore 排除。请在 .okignore 中添加“!”规则,重新包含该文件或其文件夹。"+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "图片不会进行脱敏处理。"@@ -8316,6 +8332,10 @@ msgstr "链接目标“{shown}”未指向现有文档。"msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "链接目标“{shown}”未指向现有文件。"+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "链接目标“{shown}”存在,但被 .gitignore 或 .okignore 排除。请在 .okignore 中添加“!”规则,重新包含该文件或其文件夹。"+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "为选中的文本加链接,或编辑光标处的链接。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex e1001d43f..fade19580 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -209,6 +209,7 @@"1njn7W": ["淺色"],"1nke1r": ["在 GitHub 上開啟 ", ["0"], "(在新分頁中開啟)"],"1oSHI0": ["無法安裝 ", ["skillName"], ":", ["0"]],+ "1ouiTz": ["已排除的圖片 ", ["identity"], "。前往引用位置。"],"1pdLQw": ["找不到圖片"],"1qpGKz": ["無法儲存變更。請再編輯一次色彩。"],"1ruosn": ["OpenKnowledge"],@@ -1621,6 +1622,7 @@"KIIamL": ["OpenKnowledge 會自動建立提交並推送到你的遠端。如果你不希望 git 記錄中出現自動提交,就不該啟用自動同步。"],+ "KJ_eAL": ["已排除"],"KOZud0": ["建立一個競品研究知識庫。先寫一頁總覽,再為每個競爭對手、他們的產品與定價,以及每項說法背後的來源,加上互相連結的頁面。"],@@ -3514,6 +3516,11 @@"gp3I7-": ["同步之前,請先設定你用於 git 提交的身分:"],"gpbKxw": ["連結驗證無法使用。"],"gqk-3R": ["已將 ", ["0"], " 移動到 ", ["destination"], "。"],+ "gssxm9": [+ "連結目標「",+ ["shown"],+ "」存在,但被 .gitignore 或 .okignore 排除。請在 .okignore 中加入「!」規則,重新納入該檔案或其資料夾。"+ ],"gtEbeW": ["醒目提示"],"guidance.mcp.managed-file": ["寫入一個小型橋接檔案,",@@ -4305,6 +4312,7 @@"phM8Kh": ["找到儲存庫了,但無法開啟專案。請再試一次。"],"pha01Y": ["沒有連入關係圖邊的專案層級頁面。"],"pkAft1": ["搜尋失敗。"],+ "pkC8Fi": ["已排除的檔案 ", ["identity"], "。前往引用位置。"],"pkmXTp": [["agentName"], " 已就緒"],"pmUArF": ["工作區"],"poAsUN": ["未選擇代理 — 僅保存,不安裝到任何位置"],@@ -4340,6 +4348,11 @@"q63KUv": ["新增 MCP 和技能"],"q7F5am": ["標題"],"q8aCbb": ["「", ["0"], "」有兩個版本——來源與 ", ["editor"]],+ "qAC6UE": [+ "圖片目標「",+ ["shown"],+ "」存在,但被 .gitignore 或 .okignore 排除。請在 .okignore 中加入「!」規則,重新納入該檔案或其資料夾。"+ ],"qAQVSD": ["頁面標題回應不是 JSON"],"qAhFeg": [["userName"], " · ", ["tabCount", "plural", { "other": ["#", " 個分頁"] }]],"qApCYm": ["未遮蔽敏感資訊。分享前請檢查圖片。"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 443ecb70e..71c4909a0 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -6034,6 +6034,18 @@ msgstr "Excalidraw 畫板載入失敗。"msgid "Excalidraw canvas"msgstr "Excalidraw 畫布"+#: src/components/LinksPanel.tsx+msgid "Excluded"+msgstr "已排除"++#: src/components/LinksPanel.tsx+msgid "Excluded file {identity}. Go to reference."+msgstr "已排除的檔案 {identity}。前往引用位置。"++#: src/components/LinksPanel.tsx+msgid "Excluded image {identity}. Go to reference."+msgstr "已排除的圖片 {identity}。前往引用位置。"+#: src/components/NewWorktreeDialog.tsxmsgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."msgstr "既有的分支 <0>{trimmed}</0> 會被簽出到自己的視窗中,位置在 <1>.ok/worktrees/</1> 底下。"@@ -7536,6 +7548,10 @@ msgstr "無法將圖片目標「{shown}」解析為專案本機檔案。"msgid "Image target \"{shown}\" does not resolve to an existing file."msgstr "圖片目標「{shown}」未指向現有檔案。"+#: src/editor/localized-validation-message.ts+msgid "Image target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "圖片目標「{shown}」存在,但被 .gitignore 或 .okignore 排除。請在 .okignore 中加入「!」規則,重新納入該檔案或其資料夾。"+#: src/components/ReportBugDialogBody.tsxmsgid "Images aren't redacted."msgstr "圖片不會遮蔽敏感資訊。"@@ -8316,6 +8332,10 @@ msgstr "連結目標「{shown}」未指向現有文件。"msgid "Link target \"{shown}\" does not resolve to an existing file."msgstr "連結目標「{shown}」未指向現有檔案。"+#: src/editor/localized-validation-message.ts+msgid "Link target \"{shown}\" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a \"!\" rule in .okignore."+msgstr "連結目標「{shown}」存在,但被 .gitignore 或 .okignore 排除。請在 .okignore 中加入「!」規則,重新納入該檔案或其資料夾。"+#: src/lib/keyboard-shortcuts.tsmsgid "Link the selected text, or edit the link under the caret."msgstr "為選取的文字加上連結,或編輯游標處的連結。"diff --git a/packages/app/src/server/hocuspocus-plugin.test.ts b/packages/app/src/server/hocuspocus-plugin.test.tsindex f9ae4673b..af152874f 100644--- a/packages/app/src/server/hocuspocus-plugin.test.ts+++ b/packages/app/src/server/hocuspocus-plugin.test.ts@@ -96,9 +96,11 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {const destroyServer = vi.fn(async () => {teardownOrder.push('server');});+ const resolveTrackedFile = (relativePath: string) => relativePath;const createServerSpy = vi.fn(() => ({lockDir: testContentDir,contentFilter: { isPathIgnored: () => false },+ resolveTrackedFile,hocuspocus: {hooks: async () => {},getConnectionsCount: () => 0,@@ -159,6 +161,9 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {expect(result).toBeUndefined();expect(createAssetServeMiddlewareSpy).toHaveBeenCalledTimes(1);+ expect(createAssetServeMiddlewareSpy).toHaveBeenCalledWith(+ expect.objectContaining({ resolveTrackedFile }),+ );expect(createCollaborationHostSpy).toHaveBeenCalledTimes(1);expect(createCollaborationHostSpy).toHaveBeenCalledWith(expect.objectContaining({diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex e1706e677..62d787a25 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -235,6 +235,7 @@ export function hocuspocusPlugin(): Plugin {assetExtensions: ASSET_EXTENSIONS,blocklistExtensions: EXECUTABLE_BLOCKLIST_EXTENSIONS,ingressPolicy: buildIngressPolicy({}),+ resolveTrackedFile: currentSrv.resolveTrackedFile,});server.middlewares.use((req, res, next) => {const url = req.url ?? '';diff --git a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.tsindex fd23ffbbd..59a7570db 100644--- a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts+++ b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts@@ -18,6 +18,7 @@ const ALLOWLISTED_SITES: ReadonlySet<string> = new Set<string>(['deriveFolderSearchDocuments','handleDocumentList','createLinkedFileExists',+ 'linkedLocalTargetInventory',]);function findEnclosingFn(source: string, offset: number): string {diff --git a/packages/core/package.json b/packages/core/package.jsonindex 7c4702e3b..6a9ea7e8f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -791,6 +791,18 @@"types": "./dist/utils-slug.d.mts","default": "./dist/utils-slug.mjs"},+ "./utils/target-identity": {+ "@inkeep/source": "./src/utils/target-identity.ts",+ "development": "./src/utils/target-identity.ts",+ "types": "./dist/utils-target-identity.d.mts",+ "default": "./dist/utils-target-identity.mjs"+ },+ "./utils/target-namespace": {+ "@inkeep/source": "./src/utils/target-namespace.ts",+ "development": "./src/utils/target-namespace.ts",+ "types": "./dist/utils-target-namespace.d.mts",+ "default": "./dist/utils-target-namespace.mjs"+ },"./utils/vimeo-embed": {"@inkeep/source": "./src/utils/vimeo-embed.ts","development": "./src/utils/vimeo-embed.ts",diff --git a/packages/core/schema-snapshot.json b/packages/core/schema-snapshot.jsonindex b7689e5a6..38c70ffc4 100644--- a/packages/core/schema-snapshot.json+++ b/packages/core/schema-snapshot.json@@ -227,6 +227,10 @@"hasDefault": true,"default": null},+ "sourceUrlForm": {+ "hasDefault": true,+ "default": null+ },"src": {"hasDefault": true,"default": null@@ -363,6 +367,10 @@"hasDefault": true,"default": null},+ "sourceUrlForm": {+ "hasDefault": true,+ "default": null+ },"title": {"hasDefault": true,"default": nulldiff --git a/packages/core/src/extensions/image-src-fidelity.ts b/packages/core/src/extensions/image-src-fidelity.tsindex 44d0832af..700f08566 100644--- a/packages/core/src/extensions/image-src-fidelity.ts+++ b/packages/core/src/extensions/image-src-fidelity.ts@@ -13,6 +13,7 @@ export const ImageSrcFidelity = Image.extend({return {...this.parent?.(),sourceUrl: { default: null, rendered: false },+ sourceUrlForm: { default: null, rendered: false },};},diff --git a/packages/core/src/extensions/link-ref-def-fidelity.ts b/packages/core/src/extensions/link-ref-def-fidelity.tsindex 1ed1572e0..beeaab475 100644--- a/packages/core/src/extensions/link-ref-def-fidelity.ts+++ b/packages/core/src/extensions/link-ref-def-fidelity.ts@@ -13,6 +13,7 @@ export const LinkRefDefFidelity = Node.create({title: { default: null },sourceLayout: { default: null },sourceTitleMarker: { default: null },+ sourceUrlForm: { default: null },};},diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f8c334d6c..3340b78a4 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -2151,6 +2151,26 @@ export {wikiLinkHref,} from './utils/slug.ts';export { expandTagToHierarchy, tagsMatchingPrefix } from './utils/tag-rollup.ts';+export {+ type DependencySlug,+ dependencySlug,+ type IdentityKey,+ identityKey,+ leafKey,+ TARGET_IDENTITY,+ type TargetKind,+ wikiAssetPathKey,+} from './utils/target-identity.ts';+export {+ addDocumentFolders,+ asTargetNamespace,+ createTargetNamespace,+ isTargetNamespace,+ type MutableTargetNamespace,+ resolveName,+ type TargetMatch,+ type TargetNamespace,+} from './utils/target-namespace.ts';export {hasUninstallFeedbackContent,type PostUninstallFeedbackOptions,@@ -2165,6 +2185,7 @@ export {buildPagesByBasenameIndex,buildPagesBySlugIndex,buildWikiLinkAssetTargetKeys,+ createWikiAssetResolver,getWikiLinkResolutionCandidates,isResolvedWikiLinkTarget,resolveWikiLinkAssetTarget,diff --git a/packages/core/src/markdown/angle-destination-escapes.ts b/packages/core/src/markdown/angle-destination-escapes.tsnew file mode 100644index 000000000..7638c9484--- /dev/null+++ b/packages/core/src/markdown/angle-destination-escapes.ts@@ -0,0 +1,17 @@+const ASCII_PUNCTUATION_RE = /^[!-/:-@[-`{-~]$/;++export function isAsciiPunctuation(ch: string | undefined): boolean {+ return ch !== undefined && ASCII_PUNCTUATION_RE.test(ch);+}++export function angleDestinationEscapesBracket(ch: string | undefined): boolean {+ return ch === '<' || ch === '>';+}++export function angleDestinationEscapesBackslashBefore(next: string | undefined): boolean {+ return next === undefined || isAsciiPunctuation(next);+}++export function angleDestinationReproducesEscapeOf(ch: string | undefined): boolean {+ return angleDestinationEscapesBracket(ch) || ch === '\\';+}diff --git a/packages/core/src/markdown/autolink-void-html-guard.ts b/packages/core/src/markdown/autolink-void-html-guard.tsindex 178991863..c1ab5fb96 100644--- a/packages/core/src/markdown/autolink-void-html-guard.ts+++ b/packages/core/src/markdown/autolink-void-html-guard.ts@@ -1,5 +1,11 @@import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';+import {+ angleDestinationEscapesBackslashBefore,+ angleDestinationReproducesEscapeOf,+ isAsciiPunctuation,+} from './angle-destination-escapes.ts';+import { BACKSLASH_ESCAPE_PUA_MARK } from './backslash-escape-guard.ts';import { findFencedRegions, findInlineCodeRegions, isInsideFence } from './fence-regions.ts';const GUARD_OPEN = '\uE000';@@ -46,6 +52,7 @@ function countOpenersBefore(tag: string,offset: number,codeRegions: Array<[number, number]>,+ destinations: AngleDestinationIndex,): number {let count = 0;let from = 0;@@ -54,6 +61,7 @@ function countOpenersBefore(const at = source.indexOf(needle, from);if (at === -1 || at >= offset) break;from = at + needle.length;+ if (isReservedOpen(destinations, at)) continue;const after = source[at + needle.length];if (after !== undefined && after !== '>' && after !== '/' && !/\s/.test(after)) continue;if (isInsideFence(at, codeRegions)) continue;@@ -77,11 +85,18 @@ function lowerBound(arr: number[], target: number): number {return lo;}-function indexUppercaseCloseTagsByName(source: string): Map<string, number[]> {+function indexUppercaseCloseTagsByName(+ source: string,+ destinations: AngleDestinationIndex,+): Map<string, number[]> {const index = new Map<string, number[]>();const re = new RegExp(UPPERCASE_CLOSE_TAG_INDEX_RE.source, 'g');let m = re.exec(source);while (m !== null) {+ if (isReservedOpen(destinations, m.index)) {+ m = re.exec(source);+ continue;+ }const existing = index.get(m[1]);if (existing) existing.push(m.index);else index.set(m[1], [m.index]);@@ -123,53 +138,285 @@ function indexLiteralDoubleNewlines(source: string): number[] {const ANGLE_DEST_SCAN_CAP = 1024;-function isAngleBracketDestinationOpen(offset: number, result: string): boolean {- if (result[offset - 1] !== '(' || result[offset - 2] !== ']') return false;- const labelEnd = offset - 2;+const DEFINITION_LABEL_SIZE_MAX = 999;++const DEFINITION_LINE_START_RE = /(?<![^\n\r]) {0,3}\[/g;++const TABLE_DELIMITER_ROW_RE = /^[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;++interface AngleDestinationIndex {+ readonly opens: ReadonlySet<number>;+ readonly closes: ReadonlySet<number>;+ readonly forced: ReadonlySet<number>;+}++function isReservedOpen(index: AngleDestinationIndex, offset: number): boolean {+ return index.opens.has(offset) || index.forced.has(offset);+}++function isGuardSentinel(ch: string | undefined): boolean {+ return (+ ch === GUARD_OPEN ||+ ch === GUARD_CLOSE ||+ ch === GUARD_COLON ||+ ch === GUARD_AT ||+ ch === GUARD_OPEN_BRACE+ );+}++function isSpaceOrTab(ch: string | undefined): boolean {+ return ch === ' ' || ch === '\t';+}++function isLineEnding(ch: string | undefined): boolean {+ return ch === '\n' || ch === '\r';+}++function skipSpacesAndTabs(offset: number, source: string): number {+ let j = offset;+ while (isSpaceOrTab(source[j])) j++;+ return j;+}++function lineEndingEnd(offset: number, source: string): number {+ return source[offset] === '\r' && source[offset + 1] === '\n' ? offset + 1 : offset;+}++function inlineLabelStart(labelEnd: number, result: string): number {let bs = 0;for (let j = labelEnd - 1; j >= 0 && result[j] === '\\'; j--) bs++;- if (bs % 2 === 1) return false;+ if (bs % 2 === 1) return -1;- let foundLabelStart = false;const scanFloor = Math.max(0, labelEnd - ANGLE_DEST_SCAN_CAP);for (let j = labelEnd - 1; j >= scanFloor; j--) {const ch = result[j];- if (ch === '\n' || ch === '\r' || ch === '`') return false;+ if (isLineEnding(ch) || ch === '`') return -1;if (ch !== '[' && ch !== ']') continue;- let k = 0;- for (let m = j - 1; m >= 0 && result[m] === '\\'; m--) k++;- if (k % 2 === 1) continue;- if (ch === ']') return false;- if (result[j + 1] === '^') return false;- if (result[j - 1] === ']') return false;- foundLabelStart = true;- break;+ if (isBackslashEscaped(j, result)) continue;+ if (ch === ']') return -1;+ if (result[j + 1] === '^') return -1;+ if (result[j - 1] === ']') return -1;+ return j;+ }+ return -1;+}++function isBackslashEscaped(offset: number, source: string): boolean {+ let count = 0;+ for (let j = offset - 1; j >= 0 && source[j] === '\\'; j--) count++;+ return count % 2 === 1;+}++function hasUnescapedPipe(from: number, to: number, source: string): boolean {+ for (let j = from; j < to; j++) {+ if (source[j] === '|' && !isBackslashEscaped(j, source)) return true;}- if (!foundLabelStart) return false;+ return false;+}++function isTableDelimiterRowAfter(offset: number, source: string): boolean {+ let lineStart = offset;+ while (lineStart < source.length && !isLineEnding(source[lineStart])) lineStart++;+ if (lineStart >= source.length) return false;+ lineStart = lineEndingEnd(lineStart, source) + 1;+ let lineEnd = lineStart;+ while (lineEnd < source.length && !isLineEnding(source[lineEnd])) lineEnd++;+ const line = source.slice(lineStart, lineEnd);+ return TABLE_DELIMITER_ROW_RE.test(line) && /[|:]/.test(line);+}++function isSerializableAfterEscapedBackslash(ch: string | undefined): boolean {+ return ch === BACKSLASH_ESCAPE_PUA_MARK || angleDestinationEscapesBackslashBefore(ch);+}- let sawWhitespace = false;- let destClose = -1;+function enclosedDestinationClose(offset: number, result: string, escapedOpens: number[]): number {const scanCeil = Math.min(result.length, offset + 1 + ANGLE_DEST_SCAN_CAP);for (let j = offset + 1; j < scanCeil; j++) {const ch = result[j];- if (ch === '>') {- destClose = j;- break;+ if (ch === '>') return j;+ if (ch === BACKSLASH_ESCAPE_PUA_MARK && result[j + 1] === '<') {+ escapedOpens.push(j + 1);+ j++;+ continue;+ }+ if (ch === '<' || isLineEnding(ch) || isGuardSentinel(ch)) return -1;+ if (ch === '\\') {+ const next = result[j + 1];+ if (next === '\\' && !isSerializableAfterEscapedBackslash(result[j + 2])) return -1;+ if (angleDestinationReproducesEscapeOf(next)) j++;+ else if (isAsciiPunctuation(next)) return -1;}- if (ch === '<' || ch === '\\' || ch === '\n' || ch === '\r') return false;+ }+ return -1;+}++function titleEnd(offset: number, result: string): number {+ const opener = result[offset];+ const marker = opener === '(' ? ')' : opener === '"' || opener === "'" ? opener : null;+ if (marker === null) return -1;+ const scanCeil = Math.min(result.length, offset + 1 + ANGLE_DEST_SCAN_CAP);+ for (let j = offset + 1; j < scanCeil; j++) {+ const ch = result[j];+ if (ch === marker) return j + 1;+ if (isLineEnding(ch) || (marker === ')' && ch === '(')) return -1;+ if (ch === '\\') {+ const next = result[j + 1];+ if (next === marker || next === '\\' || (marker === ')' && next === '(')) j++;+ }+ }+ return -1;+}++function resourceEnd(offset: number, result: string): number {+ if (result[offset] === ')') return offset;+ const titleStart = skipSpacesAndTabs(offset, result);+ if (titleStart === offset) return -1;+ const afterTitle = titleEnd(titleStart, result);+ return afterTitle !== -1 && result[afterTitle] === ')' ? afterTitle : -1;+}++function resourceAngleDestinationClose(+ offset: number,+ result: string,+ escapedOpens: number[],+): number {+ const labelStart = inlineLabelStart(offset - 2, result);+ if (labelStart === -1) return -1;+ const destClose = enclosedDestinationClose(offset, result, escapedOpens);+ if (destClose === -1) return -1;+ const end = resourceEnd(destClose + 1, result);+ if (end === -1 || hasUnescapedPipe(labelStart, end, result)) return -1;+ return destClose;+}++function isBlankLineBefore(lineStart: number, source: string): boolean {+ let j = lineStart - 2;+ if (source[j] === '\r') j--;+ for (; j >= 0 && source[j] !== '\n'; j--) {+ if (!isSpaceOrTab(source[j])) return false;+ }+ return true;+}++function definitionLabelEnd(bracket: number, source: string): number {+ if (source[bracket + 1] === '^') return -1;+ let seenContent = false;+ const scanCeil = Math.min(source.length, bracket + 2 + DEFINITION_LABEL_SIZE_MAX);+ for (let j = bracket + 1; j < scanCeil; j++) {+ const ch = source[j];+ if (ch === ']') return seenContent ? j : -1;+ if (ch === '[' || isLineEnding(ch)) return -1;+ if (ch === '\\') {+ const next = source[j + 1];+ if (next === '[' || next === ']' || next === '\\') j++;+ seenContent = true;+ continue;+ }+ if (!isSpaceOrTab(ch)) seenContent = true;+ }+ return -1;+}++function definitionTitleLineEnd(lineEnd: number, source: string): number {+ const titleStart = skipSpacesAndTabs(lineEnd + 1, source);+ const afterTitle = titleEnd(titleStart, source);+ if (afterTitle === -1) return lineEnd;+ const j = skipSpacesAndTabs(afterTitle, source);+ if (j >= source.length) return source.length;+ return isLineEnding(source[j]) ? lineEndingEnd(j, source) : lineEnd;+}++function definitionEnd(offset: number, source: string): number {+ let j = skipSpacesAndTabs(offset, source);+ if (j >= source.length) return source.length;+ if (isLineEnding(source[j])) return definitionTitleLineEnd(lineEndingEnd(j, source), source);+ if (j === offset) return -1;+ const afterTitle = titleEnd(j, source);+ if (afterTitle === -1) return -1;+ j = skipSpacesAndTabs(afterTitle, source);+ if (j >= source.length) return source.length;+ return isLineEnding(source[j]) ? lineEndingEnd(j, source) : -1;+}++function indexDefinitionAngleDestinations(+ source: string,+ opens: Set<number>,+ closes: Set<number>,+ forced: Set<number>,+): void {+ let lastDefinitionEnd = -1;+ for (const m of source.matchAll(DEFINITION_LINE_START_RE)) {+ const lineStart = m.index;if (- ch === GUARD_OPEN ||- ch === GUARD_CLOSE ||- ch === GUARD_COLON ||- ch === GUARD_AT ||- ch === GUARD_OPEN_BRACE+ lineStart !== 0 &&+ lineStart !== lastDefinitionEnd + 1 &&+ !isBlankLineBefore(lineStart, source)) {- return false;+ continue;+ }+ const labelEnd = definitionLabelEnd(lineStart + m[0].length - 1, source);+ if (labelEnd === -1 || source[labelEnd + 1] !== ':') continue;+ const lt = skipSpacesAndTabs(labelEnd + 2, source);+ if (source[lt] !== '<') continue;+ const escapedOpens: number[] = [];+ const gt = enclosedDestinationClose(lt, source, escapedOpens);+ if (gt === -1) continue;+ const end = definitionEnd(gt + 1, source);+ if (end === -1 || isTableDelimiterRowAfter(gt, source)) continue;+ opens.add(lt);+ closes.add(gt);+ for (const at of escapedOpens) forced.add(at);+ lastDefinitionEnd = end;+ }+}++function indexAngleDestinations(source: string): AngleDestinationIndex {+ const opens = new Set<number>();+ const closes = new Set<number>();+ const forced = new Set<number>();+ let at = source.indexOf('](<');+ while (at !== -1) {+ const escapedOpens: number[] = [];+ const close = resourceAngleDestinationClose(at + 2, source, escapedOpens);+ if (close !== -1) {+ opens.add(at + 2);+ closes.add(close);+ for (const forcedAt of escapedOpens) forced.add(forcedAt);}- if (ch === ' ' || ch === '\t') sawWhitespace = true;+ at = source.indexOf('](<', at + 3);}- if (destClose === -1 || !sawWhitespace) return false;- return result[destClose + 1] === ')';+ indexDefinitionAngleDestinations(source, opens, closes, forced);+ return { opens, closes, forced };+}++function hasLiveCloserAfter(+ source: string,+ tag: string,+ offset: number,+ destinations: AngleDestinationIndex,+): boolean {+ const needle = `</${tag}>`;+ let at = source.indexOf(needle, offset);+ while (at !== -1) {+ if (!isReservedOpen(destinations, at)) return true;+ at = source.indexOf(needle, at + 1);+ }+ return false;+}++function guardAngleBrackets(+ match: string,+ offset: number,+ destinations: AngleDestinationIndex,+): string {+ let out = '';+ for (let i = 0; i < match.length; i++) {+ const ch = match[i];+ if (ch === '<') out += destinations.opens.has(offset + i) ? ch : GUARD_OPEN;+ else if (ch === '>') out += destinations.closes.has(offset + i) ? ch : GUARD_CLOSE;+ else out += ch;+ }+ return out;}function isSelfClosingTagAt(@@ -256,6 +503,7 @@ function isUppercaseJsxSelfClosingAt(scanStart: number,result: string,nextBlankLine: number,+ destinations: AngleDestinationIndex,): boolean {const scanEnd = Math.min(result.length, nextBlankLine);let inDoubleQuote = false;@@ -280,7 +528,7 @@ function isUppercaseJsxSelfClosingAt(continue;}if (braceDepth > 0) continue;- if (ch === '>') {+ if (ch === '>' && !destinations.closes.has(i)) {return i > 0 && result[i - 1] === '/';}}@@ -374,7 +622,11 @@ export function protectFromMdx(source: string): string {return match.replace(/</g, GUARD_OPEN).replace(/>/g, GUARD_CLOSE);});- result = result.replace(AUTOLINK_RE, (_match, uri: string) => {+ const angleDestinations = indexAngleDestinations(result);++ result = result.replace(AUTOLINK_RE, (match, uri: string, offset: number) => {+ if (angleDestinations.opens.has(offset)) return match;+ if (angleDestinations.forced.has(offset)) return `${GUARD_OPEN}${match.slice(1)}`;const safe = uri.replaceAll(':', GUARD_COLON).replaceAll('@', GUARD_AT);return `${GUARD_OPEN}${safe}${GUARD_CLOSE}`;});@@ -382,9 +634,11 @@ export function protectFromMdx(source: string): string {const exemptedClosers = new Map<string, number>();const codeRegions = [...findFencedRegions(result), ...findInlineCodeRegions(result)];result = result.replace(HTML_CLOSE_TAG_RE, (match, tag: string, offset: number) => {+ if (angleDestinations.opens.has(offset)) return match;+ if (angleDestinations.forced.has(offset)) return `${GUARD_OPEN}${match.slice(1)}`;if (LOWERCASE_PAIRED_JSX_TAGS.has(tag)) {const used = exemptedClosers.get(tag) ?? 0;- if (used < countOpenersBefore(result, tag, offset, codeRegions)) {+ if (used < countOpenersBefore(result, tag, offset, codeRegions, angleDestinations)) {exemptedClosers.set(tag, used + 1);return match;}@@ -392,28 +646,40 @@ export function protectFromMdx(source: string): string {return match.replace(/</g, GUARD_OPEN).replace(/>/g, GUARD_CLOSE);});- result = result.replace(LOWERCASE_HTML_TAG_RE, (match, tag: string) => {- if (LOWERCASE_JSX_CANONICAL_TAGS.has(tag) && match.endsWith('/>')) {- return match;- }- if (LOWERCASE_PAIRED_JSX_TAGS.has(tag)) {+ result = result.replace(+ LOWERCASE_HTML_TAG_RE,+ (match, tag: string, _attributes: string | undefined, offset: number) => {+ if (angleDestinations.opens.has(offset)) return match;+ if (angleDestinations.forced.has(offset)) {+ return guardAngleBrackets(match, offset, angleDestinations);+ }+ if (LOWERCASE_JSX_CANONICAL_TAGS.has(tag) && match.endsWith('/>')) {+ return match;+ }+ if (LOWERCASE_PAIRED_JSX_TAGS.has(tag)) {+ return match;+ }+ if (tag[0] === tag[0].toLowerCase() && tag[0] !== tag[0].toUpperCase()) {+ return guardAngleBrackets(match, offset, angleDestinations);+ }return match;- }- if (tag[0] === tag[0].toLowerCase() && tag[0] !== tag[0].toUpperCase()) {- return match.replace(/</g, GUARD_OPEN).replace(/>/g, GUARD_CLOSE);- }- return match;- });+ },+ );- result = result.replace(/<>/g, `${GUARD_OPEN}${GUARD_CLOSE}`);+ result = result.replace(/<>/g, (match, offset: number) =>+ angleDestinations.opens.has(offset)+ ? match+ : guardAngleBrackets(match, offset, angleDestinations),+ );- const closeTagOffsets = indexUppercaseCloseTagsByName(result);+ const closeTagOffsets = indexUppercaseCloseTagsByName(result, angleDestinations);const paragraphBreaks = indexParagraphBreaks(result);const greaterThanOffsets = indexGreaterThan(result);const uppercaseTagSpans = indexUppercaseTagSpans(result);result = result.replace(/</g, (match, offset) => {- if (isAngleBracketDestinationOpen(offset, result)) return match;+ if (angleDestinations.opens.has(offset)) return match;+ if (angleDestinations.forced.has(offset)) return GUARD_OPEN;if (isOffsetInsideAnyRegion(offset, uppercaseTagSpans)) return match;@@ -439,7 +705,7 @@ export function protectFromMdx(source: string): string {if (lookahead.startsWith(`<${pairedTagName}/>`)) {return match;}- if (result.indexOf(`</${pairedTagName}>`, offset) !== -1) {+ if (hasLiveCloserAfter(result, pairedTagName, offset, angleDestinations)) {return match;}return GUARD_OPEN;@@ -456,7 +722,7 @@ export function protectFromMdx(source: string): string {const nextBlankLine = pbIdx < paragraphBreaks.length ? paragraphBreaks[pbIdx] : result.length;const scanStart = offset + 1 + tagName.length;- if (isUppercaseJsxSelfClosingAt(scanStart, result, nextBlankLine)) {+ if (isUppercaseJsxSelfClosingAt(scanStart, result, nextBlankLine, angleDestinations)) {return match;}@@ -498,6 +764,7 @@ export function restoreFromMdx() {rec.value = restoreString(rec.value);}if (typeof rec.url === 'string' && hasSentinels(rec.url)) {+ if (rec.url.startsWith(GUARD_OPEN)) recordGuardedDestinationOpen(node);rec.url = restoreString(rec.url);}if (typeof rec.title === 'string' && hasSentinels(rec.title)) {@@ -516,6 +783,12 @@ export function restoreFromMdx() {};}+function recordGuardedDestinationOpen(node: Nodes): void {+ if (node.type !== 'link' && node.type !== 'image' && node.type !== 'definition') return;+ node.data ??= {};+ node.data.sourceGuardedDestinationOpen = true;+}+function restoreString(s: string): string {let out = s.replaceAll(GUARD_OPEN, '<')diff --git a/packages/core/src/markdown/backslash-escape-guard.ts b/packages/core/src/markdown/backslash-escape-guard.tsindex dbd4923bf..6f921c593 100644--- a/packages/core/src/markdown/backslash-escape-guard.ts+++ b/packages/core/src/markdown/backslash-escape-guard.ts@@ -4,7 +4,7 @@ import { visit } from 'unist-util-visit';import { protectPattern } from './entity-ref-guard.ts';import type { EntityReferenceSpan, EscapeProvenanceEntry } from './mdast-augmentation.ts';-const BACKSLASH_ESCAPE_PUA_MARK = '';+export const BACKSLASH_ESCAPE_PUA_MARK = '';export const BACKSLASH_GUARD_SUBSTITUTIONS: ReadonlyArray<{ from: string; to: string }> = [{ from: '\\', to: BACKSLASH_ESCAPE_PUA_MARK },diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex cc8bd67e6..9f6477013 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -450,6 +450,7 @@ function buildMdastToPmHandlers(alt: node.alt ?? null,title: node.title ?? null,sourceUrl: normalized !== orig ? orig : null,+ sourceUrlForm: node.data?.sourceUrlForm ?? null,});};if (n.imageReference) {@@ -731,6 +732,7 @@ function buildMdastToPmHandlers(const hasIdentifierAttr = !!linkDefNode.spec.attrs?.identifier;const hasSourceLayoutAttr = !!linkDefNode.spec.attrs?.sourceLayout;const hasSourceTitleMarkerAttr = !!linkDefNode.spec.attrs?.sourceTitleMarker;+ const hasSourceUrlFormAttr = !!linkDefNode.spec.attrs?.sourceUrlForm;handlers.definition = (node: Definition) => {const attrs: Record<string, unknown> = {title: node.title ?? null,@@ -745,6 +747,7 @@ function buildMdastToPmHandlers(else if (hasHrefAttr) attrs.href = node.url ?? '';if (hasSourceLayoutAttr) attrs.sourceLayout = node.data?.sourceLayout ?? null;if (hasSourceTitleMarkerAttr) attrs.sourceTitleMarker = node.data?.sourceTitleMarker ?? null;+ if (hasSourceUrlFormAttr) attrs.sourceUrlForm = node.data?.sourceUrlForm ?? null;return linkDefNode.createAndFill(attrs);};}@@ -1324,12 +1327,18 @@ function buildPmToMdastHandlers(buildCellNode(pmNode, state.all(pmNode));if (n.image) {- nodeHandlers.image = (pmNode: PmNode) => ({- type: 'image' as const,- url: (pmNode.attrs.sourceUrl as string | null) ?? pmNode.attrs.src,- alt: pmNode.attrs.alt,- title: pmNode.attrs.title,- });+ nodeHandlers.image = (pmNode: PmNode) => {+ const result: Image = {+ type: 'image' as const,+ url: (pmNode.attrs.sourceUrl as string | null) ?? pmNode.attrs.src,+ alt: pmNode.attrs.alt,+ title: pmNode.attrs.title,+ };+ if (pmNode.attrs.sourceUrlForm === 'angle-bracketed') {+ result.data = { sourceUrlForm: 'angle-bracketed' };+ }+ return result;+ };}if (n.imageReference) {@@ -1367,6 +1376,9 @@ function buildPmToMdastHandlers(if (marker === 'single' || marker === 'double' || marker === 'paren') {data.sourceTitleMarker = marker;}+ if (pmNode.attrs.sourceUrlForm === 'angle-bracketed') {+ data.sourceUrlForm = 'angle-bracketed';+ }const result: Definition = {type: 'definition' as const,identifier: pmNode.attrs.identifier ?? pmNode.attrs.label ?? '',diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 204a8472c..6d6889921 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -46,9 +46,19 @@ export type LocalTargetKind = 'document' | 'file' | 'unknown';export type LocalTargetRole = 'link' | 'image';-export type LocalTargetSourceForm = 'markdown-inline' | 'markdown-reference' | 'html-img';--export type LocalTargetResolutionMethod = 'source-relative' | 'root-relative' | 'tolerant' | 'none';+export type LocalTargetSourceForm =+ | 'markdown-inline'+ | 'markdown-reference'+ | 'html-img'+ | 'wiki-link'+ | 'wiki-embed';++export type LocalTargetResolutionMethod =+ | 'source-relative'+ | 'root-relative'+ | 'tolerant'+ | 'basename'+ | 'none';export interface LocalTargetDiagnosticEvidence extends Record<string, unknown> {href: string;diff --git a/packages/core/src/markdown/mdast-augmentation.ts b/packages/core/src/markdown/mdast-augmentation.tsindex 7548916b7..f03550b99 100644--- a/packages/core/src/markdown/mdast-augmentation.ts+++ b/packages/core/src/markdown/mdast-augmentation.ts@@ -178,6 +178,7 @@ declare module 'mdast' {sourceStyle?: string;sourceRaw?: string;sourceUrlForm?: 'angle-bracketed';+ sourceGuardedDestinationOpen?: true;sourceTitleMarker?: 'single' | 'double' | 'paren';}interface LinkReferenceData {@@ -242,6 +243,12 @@ declare module 'mdast' {interface DefinitionData {sourceLayout?: 'multiline' | 'inline';sourceTitleMarker?: 'single' | 'double' | 'paren';+ sourceUrlForm?: 'angle-bracketed';+ sourceGuardedDestinationOpen?: true;+ }+ interface ImageData {+ sourceUrlForm?: 'angle-bracketed';+ sourceGuardedDestinationOpen?: true;}interface RootContentMap {wikiLink: WikiLinkMdast;diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 5e4455436..480c28077 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -480,7 +480,7 @@ export function applyPositionSliceToNode(while (cursor < slice.length && (slice[cursor] === ' ' || slice[cursor] === '\t')) {cursor++;}- if (slice[cursor] === '<') {+ if (opensEnclosedDestination(slice, cursor, node.data)) {node.data.sourceUrlForm = 'angle-bracketed';}if (@@ -509,9 +509,25 @@ export function applyPositionSliceToNode(break;}+ case 'image': {+ const slice = source.slice(startOff, endOff);+ const closeBracketIdx = slice.lastIndexOf('](');+ if (+ closeBracketIdx !== -1 &&+ destinationStartsWithAngle(slice, closeBracketIdx + 2, node.data)+ ) {+ node.data.sourceUrlForm = 'angle-bracketed';+ }+ break;+ }+case 'definition': {const slice = source.slice(startOff, endOff);node.data.sourceLayout = slice.includes('\n') ? 'multiline' : 'inline';+ const labelCloseIdx = definitionLabelCloseIndex(slice);+ if (labelCloseIdx !== -1 && destinationStartsWithAngle(slice, labelCloseIdx + 2, node.data)) {+ node.data.sourceUrlForm = 'angle-bracketed';+ }if (typeof node.title === 'string' && slice.length > 0) {const lastChar = slice[slice.length - 1];if (lastChar === '"') {@@ -546,6 +562,40 @@ export function applyPositionSliceToNode(}}+interface DestinationSourceData {+ sourceGuardedDestinationOpen?: true;+}++function destinationStartsWithAngle(+ slice: string,+ from: number,+ data: DestinationSourceData,+): boolean {+ let cursor = from;+ while (cursor < slice.length && /[ \t\r\n]/.test(slice[cursor])) cursor++;+ return opensEnclosedDestination(slice, cursor, data);+}++function opensEnclosedDestination(+ slice: string,+ cursor: number,+ data: DestinationSourceData,+): boolean {+ return slice[cursor] === '<' && data.sourceGuardedDestinationOpen !== true;+}++function definitionLabelCloseIndex(slice: string): number {+ for (let i = 1; i < slice.length; i++) {+ const ch = slice[i];+ if (ch === '\\') {+ i++;+ continue;+ }+ if (ch === ']') return slice[i + 1] === ':' ? i : -1;+ }+ return -1;+}+export function positionSlicePlugin() {return (tree: Root, file: VFile) => {const source = typeof file.value === 'string' ? file.value : '';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 168fdcbe5..1075d5ce5 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,8 +1,12 @@-import type { Nodes, Parents } from 'mdast';+import type { Definition, Image, Link, Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';import { classifyCharacter } from 'micromark-util-classify-character';import { isValidSourceLiteralRaw } from '../extensions/source-literal-mark.ts';+import {+ angleDestinationEscapesBackslashBefore,+ angleDestinationEscapesBracket,+} from './angle-destination-escapes.ts';import { scanBraceSpans } from './autolink-void-html-guard.ts';import { widenFenceLength } from './code-fence.ts';import { type RawMdxFallbackMdast, validateEscapeProvenance } from './mdast-augmentation.ts';@@ -196,13 +200,7 @@ export const toMarkdownHandlers = {value += tracker.move('](');subexit();- const urlExit = state.enter('destinationRaw');- const urlRaw = String(node.url ?? '');- const wantAngles = node.data?.sourceUrlForm === 'angle-bracketed';- const alreadyAngled = urlRaw.startsWith('<') && urlRaw.endsWith('>');- const urlOut = wantAngles && !alreadyAngled ? `<${urlRaw}>` : formatLinkUrl(urlRaw);- value += tracker.move(urlOut);- urlExit();+ value += emitDestination(state, tracker, node);if (node.title) {const marker = node.data?.sourceTitleMarker ?? 'double';@@ -228,9 +226,7 @@ export const toMarkdownHandlers = {value += tracker.move('](');subexit();- const urlExit = state.enter('destinationRaw');- value += tracker.move(formatLinkUrl(String(node.url ?? '')));- urlExit();+ value += emitDestination(state, tracker, node);if (node.title) {const titleExit = state.enter('titleQuote');@@ -269,19 +265,7 @@ export const toMarkdownHandlers = {value += tracker.move(sep1);const urlRaw = String(node.url ?? '');- if (!urlRaw || /[\0- ]/.test(urlRaw)) {- const destExit = state.enter('destinationLiteral');- value += tracker.move('<');- value += tracker.move(- state.safe(urlRaw, { before: value, after: '>', ...tracker.current() }),- );- value += tracker.move('>');- destExit();- } else {- const destExit = state.enter('destinationRaw');- value += tracker.move(formatLinkUrl(urlRaw));- destExit();- }+ value += emitDestination(state, tracker, node, !urlRaw || /[\0- ]/.test(urlRaw));if (node.title) {const titleSep = layout === 'multiline' ? '\n ' : ' ';@@ -861,6 +845,46 @@ function emitLinkTitle(return `${separator}"${title.replace(/"/g, '\\"')}"`;}+function emitDestination(+ state: State,+ tracker: ReturnType<State['createTracker']>,+ node: Link | Image | Definition,+ forceAngles = false,+): string {+ const urlRaw = String(node.url ?? '');+ const alreadyAngled = urlRaw.startsWith('<') && urlRaw.endsWith('>');+ const wantAngles = node.data?.sourceUrlForm === 'angle-bracketed' && !alreadyAngled;+ if (wantAngles || forceAngles) {+ const destExit = state.enter('destinationLiteral');+ const out = tracker.move(formatAngleDestination(urlRaw, state.stack.includes('tableCell')));+ destExit();+ return out;+ }+ const destExit = state.enter('destinationRaw');+ const out = tracker.move(formatLinkUrl(urlRaw));+ destExit();+ return out;+}++export function formatAngleDestination(url: string, escapePipes = false): string {+ let out = '<';+ for (let i = 0; i < url.length; i++) {+ const ch = url[i];+ if (angleDestinationEscapesBracket(ch) || (escapePipes && ch === '|')) {+ out += `\\${ch}`;+ } else if (ch === '\n') {+ out += '
';+ } else if (ch === '\r') {+ out += '
';+ } else if (ch === '\\') {+ out += angleDestinationEscapesBackslashBefore(url[i + 1]) ? '\\\\' : '\\';+ } else {+ out += ch;+ }+ }+ return `${out}>`;+}+export function formatLinkUrl(url: string): string {if (!url) return '';diff --git a/packages/core/src/schema-snapshot.json b/packages/core/src/schema-snapshot.jsonindex db569d599..cf8276f82 100644--- a/packages/core/src/schema-snapshot.json+++ b/packages/core/src/schema-snapshot.json@@ -343,6 +343,9 @@},"sourceTitleMarker": {"hasDefault": true+ },+ "sourceUrlForm": {+ "hasDefault": true}},"content": "",@@ -446,6 +449,9 @@},"sourceUrl": {"hasDefault": true+ },+ "sourceUrlForm": {+ "hasDefault": true}},"content": "",diff --git a/packages/core/src/schemas/api/agent-write.test.ts b/packages/core/src/schemas/api/agent-write.test.tsindex ac08c1c50..ae2023386 100644--- a/packages/core/src/schemas/api/agent-write.test.ts+++ b/packages/core/src/schemas/api/agent-write.test.ts@@ -313,6 +313,16 @@ describe('AgentWriteMdSuccessSchema', () => {expect(result.success).toBe(true);});+ test('parses an excluded brokenLink reason (the target exists but ignore rules exclude it)', () => {+ const result = AgentWriteMdSuccessSchema.safeParse({+ timestamp: '2026-04-30T00:00:00.000Z',+ subscriberCount: 0,+ systemSubscriberCount: 0,+ brokenLinks: [{ href: 'ignored/ig.png', resolvedTo: 'ignored/ig.png', reason: 'excluded' }],+ });+ expect(result.success).toBe(true);+ });+test('round-trips a brokenLink carrying additive local-target evidence (image + reference)', () => {const brokenLinks = [{diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.tsindex 6c94dc158..5d5a0214e 100644--- a/packages/core/src/schemas/api/agent-write.ts+++ b/packages/core/src/schemas/api/agent-write.ts@@ -205,7 +205,12 @@ export type AdvisoryWarning = z.infer<typeof AdvisoryWarningSchema>;export const AdvisoryWarningsSchema = z.array(AdvisoryWarningSchema).min(1);-export const BROKEN_LINK_REASONS = ['no-such-doc', 'no-such-file', 'unresolvable'] as const;+export const BROKEN_LINK_REASONS = [+ 'no-such-doc',+ 'no-such-file',+ 'unresolvable',+ 'excluded',+] as const;export type BrokenLinkReason = (typeof BROKEN_LINK_REASONS)[number];export const BrokenLinkSchema = zdiff --git a/packages/core/src/utils/path-resolve.test.ts b/packages/core/src/utils/path-resolve.test.tsindex d7d2c5c94..c4c7cc7d7 100644--- a/packages/core/src/utils/path-resolve.test.ts+++ b/packages/core/src/utils/path-resolve.test.ts@@ -38,6 +38,32 @@ describe('createBasenameIndex — case-insensitive lookup, case-preserving stora});});+describe('createBasenameIndex — canonically equivalent spellings', () => {+ const NFC = 'Café.png';+ const NFD = 'Café.png';++ test('an NFC lookup finds an NFD-stored path', () => {+ const idx = createBasenameIndex();+ idx.add(`media/${NFD}`);+ expect(idx.resolveEmbed(NFC, 'Wiki.md')).toBe(`media/${NFD}`);+ });++ test('an NFD lookup finds an NFC-stored path', () => {+ const idx = createBasenameIndex();+ idx.add(`media/${NFC}`);+ expect(idx.resolveEmbed(NFD, 'Wiki.md')).toBe(`media/${NFC}`);+ });++ test('case folding and normalization compose into one bucket', () => {+ const idx = createBasenameIndex();+ idx.add(`media/CAFÉ.PNG`);+ expect(idx.resolveEmbed(NFC.toLowerCase(), 'Wiki.md')).toBe('media/CAFÉ.PNG');+ idx.remove(`media/CAFÉ.PNG`);+ expect(idx.resolveEmbed(NFC, 'Wiki.md')).toBeNull();+ expect(idx.size()).toBe(0);+ });+});+describe('createBasenameIndex — path normalization', () => {test('./prefix stripped on add', () => {const idx = createBasenameIndex();diff --git a/packages/core/src/utils/path-resolve.ts b/packages/core/src/utils/path-resolve.tsindex aa732f5c5..358a90201 100644--- a/packages/core/src/utils/path-resolve.ts+++ b/packages/core/src/utils/path-resolve.ts@@ -1,3 +1,5 @@+import { leafKey } from './target-identity.ts';+export interface BasenameIndex {add(path: string): void;remove(path: string): void;@@ -65,7 +67,7 @@ export function createBasenameIndex(): BasenameIndex {if (path === '') return;const base = basenameOf(path);if (base === '') return;- const key = base.toLowerCase();+ const key = leafKey('file', base);const bucket = buckets.get(key);if (!bucket) {buckets.set(key, [path]);@@ -76,7 +78,7 @@ export function createBasenameIndex(): BasenameIndex {function remove(rawPath: string): void {const path = normalizePath(rawPath);- const key = basenameOf(path).toLowerCase();+ const key = leafKey('file', basenameOf(path));const bucket = buckets.get(key);if (!bucket) return;const idx = bucket.indexOf(path);@@ -91,7 +93,7 @@ export function createBasenameIndex(): BasenameIndex {}function resolveEmbed(basename: string, sourcePath: string): string | null {- const key = basename.toLowerCase();+ const key = leafKey('file', basename);const bucket = buckets.get(key);if (!bucket || bucket.length === 0) return null;if (bucket.length === 1) return bucket[0];diff --git a/packages/core/src/utils/target-identity.test.ts b/packages/core/src/utils/target-identity.test.tsnew file mode 100644index 000000000..43705dc5a--- /dev/null+++ b/packages/core/src/utils/target-identity.test.ts@@ -0,0 +1,228 @@+import fc from 'fast-check';+import { describe, expect, test } from 'vitest';+import { toWikiLinkSlug } from './slug.ts';+import {+ compareSpellings,+ dependencySlug,+ identityKey,+ leafKey,+ TARGET_IDENTITY,+ type TargetKind,+ wikiAssetPathKey,+} from './target-identity.ts';++const RENE_NFC = 'René';+const RENE_NFD = 'René';+const CAFE_NFC = 'Café';+const CAFE_NFD = 'Café';+const VIET_NFC = 'Việt';+const VIET_PARTIAL = 'Việt';++const KINDS: readonly TargetKind[] = ['document', 'folder', 'file'];++const SPELLING_TOKENS = [+ 'a',+ 'A',+ 'e',+ 'E',+ '0',+ '-',+ ' ',+ '/',+ '.',+ 'é',+ 'é',+ 'É',+ 'É',+ 'ö',+ 'ö',+ 'ß',+ 'ſ',+ 'K',+ 'K',+ 'Å',+ 'Å',+ 'Å',+ 'fi',+ 'fi',+ 'Σ',+ 'σ',+ 'ς',+ 'İ',+ 'ı',+ 'i',+ 'I',+ 'ệ',+ 'ệ',+ 'ệ',+ '́',+ '日',+ '🙂',+];++type Respelling = 'same' | 'nfc' | 'nfd' | 'upper' | 'lower' | 'swapcase';++function respell(spelling: string, how: Respelling): string {+ switch (how) {+ case 'same':+ return spelling;+ case 'nfc':+ return spelling.normalize('NFC');+ case 'nfd':+ return spelling.normalize('NFD');+ case 'upper':+ return spelling.toUpperCase();+ case 'lower':+ return spelling.toLowerCase();+ case 'swapcase':+ return Array.from(spelling, (character) => {+ const upper = character.toUpperCase();+ return upper === character ? character.toLowerCase() : upper;+ }).join('');+ }+}++const spellingArb = fc.string({ unit: fc.constantFrom(...SPELLING_TOKENS), maxLength: 12 });+const graphemeArb = fc.string({ unit: 'grapheme', maxLength: 12 });+const respellingArb = fc.constantFrom<Respelling>(+ 'same',+ 'nfc',+ 'nfd',+ 'upper',+ 'lower',+ 'swapcase',+);++describe('TARGET_IDENTITY', () => {+ test('documents and folders compare case-sensitively, files case-insensitively, all under NFC', () => {+ expect(TARGET_IDENTITY).toEqual({+ document: { unicode: 'NFC', case: 'sensitive' },+ folder: { unicode: 'NFC', case: 'sensitive' },+ file: { unicode: 'NFC', case: 'insensitive' },+ });+ });+});++describe('leafKey', () => {+ test('folds canonically equivalent spellings onto NFC for every kind', () => {+ for (const kind of KINDS) {+ expect(leafKey(kind, RENE_NFD)).toBe(leafKey(kind, RENE_NFC));+ expect(leafKey(kind, VIET_PARTIAL)).toBe(leafKey(kind, VIET_NFC));+ }+ });++ test('keeps case for documents and folders and drops it for files', () => {+ expect(leafKey('document', 'README')).not.toBe(leafKey('document', 'readme'));+ expect(leafKey('folder', 'Assets')).not.toBe(leafKey('folder', 'assets'));+ expect(leafKey('file', `${CAFE_NFD}.PNG`)).toBe(`${CAFE_NFC.toLowerCase()}.png`);+ });++ test('never folds compatibility lookalikes', () => {+ for (const kind of KINDS) {+ expect(leafKey(kind, 'file')).not.toBe(leafKey(kind, 'file'));+ }+ });+});++describe('identityKey', () => {+ test('applies the folder rule to ancestors and the kind rule to the leaf', () => {+ expect(identityKey('file', `assets/${CAFE_NFD}.PNG`)).toBe(+ identityKey('file', `assets/${CAFE_NFC}.png`),+ );+ expect(identityKey('file', `Assets/${CAFE_NFC}.png`)).not.toBe(+ identityKey('file', `assets/${CAFE_NFC}.png`),+ );+ expect(identityKey('document', `People/${RENE_NFD}`)).toBe(+ identityKey('document', `People/${RENE_NFC}`),+ );+ expect(identityKey('document', 'Notes/readme')).not.toBe(+ identityKey('document', 'Notes/README'),+ );+ });++ test('the file key is the coarsest key', () => {+ fc.assert(+ fc.property(spellingArb, respellingArb, (spelling, how) => {+ const other = respell(spelling, how);+ for (const kind of ['document', 'folder'] as const) {+ if (identityKey(kind, spelling) === identityKey(kind, other)) {+ expect(identityKey('file', spelling)).toBe(identityKey('file', other));+ }+ }+ }),+ );+ });+});++describe('wikiAssetPathKey', () => {+ test('folds the whole path, ancestors included, under the file rule', () => {+ expect(wikiAssetPathKey(`Assets/${CAFE_NFD}.PNG`)).toBe(+ wikiAssetPathKey(`assets/${CAFE_NFC}.png`),+ );+ expect(identityKey('file', 'Assets/a.png')).not.toBe(identityKey('file', 'assets/a.png'));+ expect(wikiAssetPathKey('Assets/a.png')).toBe(wikiAssetPathKey('assets/a.png'));+ expect(wikiAssetPathKey('file.png')).not.toBe(wikiAssetPathKey('file.png'));+ });+});++describe('compareSpellings', () => {+ test('orders spellings by UTF-16 code unit', () => {+ expect(compareSpellings('Z', 'a')).toBeLessThan(0);+ expect(compareSpellings('a', 'a')).toBe(0);+ expect(compareSpellings('\u{1F600}', '\uFF21')).toBeLessThan(0);+ expect(['b', 'B', CAFE_NFD, CAFE_NFC].sort(compareSpellings)).toEqual(+ ['B', 'b', CAFE_NFD, CAFE_NFC].sort(),+ );+ });+});++describe('dependencySlug', () => {+ test('agrees across canonically equivalent spellings', () => {+ expect(dependencySlug(`People/${RENE_NFD}`)).toBe(dependencySlug(`People/${RENE_NFC}`));+ });++ test('falls back to the file identity key when the wiki slug is empty', () => {+ expect(toWikiLinkSlug('🙂')).toBe('');+ expect(dependencySlug('🙂')).toBe(identityKey('file', '🙂'));+ expect(dependencySlug('¿?')).toBe(dependencySlug('¿?'.normalize('NFD')));+ });++ test('case variants whose compatibility forms lowercase by context share a dependency slug', () => {+ for (const [a, b] of [+ ['ϲ', 'Ϲ'],+ ['xϲ', 'XϹ'],+ ['ϲ.png', 'Ϲ.PNG'],+ ]) {+ expect(identityKey('file', a)).toBe(identityKey('file', b));+ expect(dependencySlug(a)).toBe(dependencySlug(b));+ }+ });++ test('identity-equal spellings always share a dependency slug (token alphabet)', () => {+ fc.assert(+ fc.property(spellingArb, respellingArb, (spelling, how) => {+ const other = respell(spelling, how);+ for (const kind of KINDS) {+ if (identityKey(kind, spelling) === identityKey(kind, other)) {+ expect(dependencySlug(spelling)).toBe(dependencySlug(other));+ }+ }+ }),+ { numRuns: 2000 },+ );+ });++ test('identity-equal spellings always share a dependency slug (arbitrary graphemes)', () => {+ fc.assert(+ fc.property(graphemeArb, respellingArb, (spelling, how) => {+ const other = respell(spelling, how);+ for (const kind of KINDS) {+ if (identityKey(kind, spelling) === identityKey(kind, other)) {+ expect(dependencySlug(spelling)).toBe(dependencySlug(other));+ }+ }+ }),+ { numRuns: 2000 },+ );+ });+});diff --git a/packages/core/src/utils/target-identity.ts b/packages/core/src/utils/target-identity.tsnew file mode 100644index 000000000..d038bce06--- /dev/null+++ b/packages/core/src/utils/target-identity.ts@@ -0,0 +1,50 @@+import { toWikiLinkSlug } from './slug.ts';++export type TargetKind = 'document' | 'folder' | 'file';++interface IdentityRule {+ readonly unicode: 'NFC';+ readonly case: 'sensitive' | 'insensitive';+}++export const TARGET_IDENTITY = {+ document: { unicode: 'NFC', case: 'sensitive' },+ folder: { unicode: 'NFC', case: 'sensitive' },+ file: { unicode: 'NFC', case: 'insensitive' },+} as const satisfies Record<TargetKind, IdentityRule>;++export type IdentityKey<K extends TargetKind> = string & {+ readonly __brand: 'IdentityKey';+ readonly __kind: K;+};++export type DependencySlug = string & { readonly __brand: 'DependencySlug' };++export function leafKey(kind: TargetKind, segment: string): string {+ const rule = TARGET_IDENTITY[kind];+ const normalized = segment.normalize(rule.unicode);+ return rule.case === 'insensitive' ? normalized.toLowerCase() : normalized;+}++export function wikiAssetPathKey(path: string): string {+ return leafKey('file', path);+}++export function compareSpellings(left: string, right: string): number {+ if (left < right) return -1;+ if (left > right) return 1;+ return 0;+}++export function identityKey<K extends TargetKind>(kind: K, path: string): IdentityKey<K> {+ const segments = path.split('/');+ const last = segments.length - 1;+ return segments+ .map((segment, index) => leafKey(index === last ? kind : 'folder', segment))+ .join('/') as IdentityKey<K>;+}++export function dependencySlug(path: string): DependencySlug {+ const fileKey = identityKey('file', path);+ return (toWikiLinkSlug(fileKey) || fileKey) as DependencySlug;+}diff --git a/packages/core/src/utils/target-namespace.test.ts b/packages/core/src/utils/target-namespace.test.tsnew file mode 100644index 000000000..83a18c37c--- /dev/null+++ b/packages/core/src/utils/target-namespace.test.ts@@ -0,0 +1,216 @@+import fc from 'fast-check';+import { describe, expect, test } from 'vitest';+import {+ addDocumentFolders,+ asTargetNamespace,+ createTargetNamespace,+ isTargetNamespace,+ type MutableTargetNamespace,+ resolveName,+ type TargetMatch,+ type TargetNamespace,+} from './target-namespace.ts';++const RENE_NFC = 'People/René';+const RENE_NFD = 'People/René';+const ZOE_NFC = 'People/Zoë';+const ZOE_NFD = 'People/Zoë';+const CAFE_NFC = 'assets/Café.png';+const CAFE_NFD = 'assets/Café.png';+const VIET_NFC = 'Việt';+const VIET_NFD = 'Việt';+const VIET_PARTIAL = 'Việt';++describe('createTargetNamespace', () => {+ test('an NFC markdown spelling names the NFD document on disk, and vice versa', () => {+ const nfdOnly = createTargetNamespace('document', [RENE_NFD, 'People/Zoë']);+ expect(nfdOnly.resolve(RENE_NFC)).toBe(RENE_NFD);+ expect(nfdOnly.lookup(RENE_NFC)).toEqual<TargetMatch>({ kind: 'equivalent', name: RENE_NFD });+ expect(nfdOnly.resolve(ZOE_NFD)).toBe(ZOE_NFC);+ expect(nfdOnly.resolve('People/Nope')).toBeUndefined();+ expect(nfdOnly.lookup('People/Nope')).toEqual<TargetMatch>({ kind: 'absent' });+ });++ test('an exact spelling always beats an equivalent one', () => {+ const twins = createTargetNamespace('document', [RENE_NFC, RENE_NFD]);+ expect(twins.resolve(RENE_NFC)).toBe(RENE_NFC);+ expect(twins.resolve(RENE_NFD)).toBe(RENE_NFD);+ expect(twins.lookup(RENE_NFC)).toEqual<TargetMatch>({ kind: 'exact', name: RENE_NFC });+ expect(twins.lookup(RENE_NFD)).toEqual<TargetMatch>({ kind: 'exact', name: RENE_NFD });+ });++ test('a third spelling of two twins is ambiguous, still exists, and picks the lowest code points', () => {+ const twins = createTargetNamespace('document', [VIET_NFC, VIET_NFD]);+ expect(twins.lookup(VIET_PARTIAL)).toEqual<TargetMatch>({+ kind: 'ambiguous',+ name: VIET_NFD,+ candidates: [VIET_NFD, VIET_NFC],+ });+ expect(twins.resolve(VIET_PARTIAL)).toBe(VIET_NFD);+ });++ test('add and delete are idempotent and keep resolution in step with membership', () => {+ const names = createTargetNamespace('document', []);+ expect(names.add(RENE_NFC)).toBe(names);+ expect(names.add(RENE_NFC).add(RENE_NFD).size).toBe(2);+ expect(names.delete(RENE_NFC)).toBe(true);+ expect(names.delete(RENE_NFC)).toBe(false);+ expect(names.resolve(RENE_NFC)).toBe(RENE_NFD);+ expect(names.delete(RENE_NFD)).toBe(true);+ expect(names.resolve(RENE_NFC)).toBeUndefined();+ expect(names.size).toBe(0);+ names.add(RENE_NFD);+ names.clear();+ expect(names.resolve(RENE_NFC)).toBeUndefined();+ expect(names.lookup(RENE_NFD)).toEqual<TargetMatch>({ kind: 'absent' });+ });++ test('a compatibility lookalike never matches', () => {+ const names = createTargetNamespace('document', ['file']);+ expect(names.resolve('file')).toBeUndefined();+ expect(createTargetNamespace('file', ['file.txt']).resolve('file.txt')).toBeUndefined();+ });++ test('files ignore leaf case but keep ancestor folder case; documents keep case', () => {+ const files = createTargetNamespace('file', [CAFE_NFD]);+ expect(files.resolve('assets/CAFÉ.PNG')).toBe(CAFE_NFD);+ expect(files.resolve(CAFE_NFC)).toBe(CAFE_NFD);+ expect(files.resolve('Assets/Café.png')).toBeUndefined();+ const documents = createTargetNamespace('document', ['Notes/README']);+ expect(documents.resolve('Notes/readme')).toBeUndefined();+ expect(createTargetNamespace('folder', ['Assets']).resolve('assets')).toBeUndefined();+ });++ test('is a ReadonlySet of the raw names with exact membership', () => {+ const names: ReadonlySet<string> = createTargetNamespace('document', [RENE_NFD]);+ expect(names.has(RENE_NFD)).toBe(true);+ expect(names.has(RENE_NFC)).toBe(false);+ expect(names.size).toBe(1);+ expect([...names]).toEqual([RENE_NFD]);+ expect([...names.keys()]).toEqual([RENE_NFD]);+ expect([...names.values()]).toEqual([RENE_NFD]);+ expect([...names.entries()]).toEqual([[RENE_NFD, RENE_NFD]]);+ const seen: string[] = [];+ names.forEach((value, again, set) => {+ seen.push(value, again);+ expect(set).toBe(names);+ });+ expect(seen).toEqual([RENE_NFD, RENE_NFD]);+ expect(new Set(names)).toEqual(new Set([RENE_NFD]));+ });+});++describe('resolveName', () => {+ test('resolves through a namespace and exactly through a plain set', () => {+ const namespace = createTargetNamespace('document', [RENE_NFD]);+ const plain = new Set([RENE_NFD]);+ expect(isTargetNamespace(namespace)).toBe(true);+ expect(isTargetNamespace(plain)).toBe(false);+ expect(resolveName(namespace, RENE_NFC)).toBe(RENE_NFD);+ expect(resolveName(plain, RENE_NFC)).toBeUndefined();+ expect(resolveName(plain, RENE_NFD)).toBe(RENE_NFD);+ expect(resolveName(namespace, 'People/Nope')).toBeUndefined();+ });+});++describe('addDocumentFolders', () => {+ test('adds every ancestor folder of every document and keeps folders already present', () => {+ const folders = addDocumentFolders(createTargetNamespace('folder', ['empty']), [+ 'root',+ 'a/b/c',+ 'a/d',+ `${RENE_NFD}/notes`,+ ]);+ expect([...folders].sort()).toEqual(['a', 'a/b', 'empty', RENE_NFD, 'People'].sort());+ expect(folders.resolve(RENE_NFC)).toBe(RENE_NFD);+ expect(folders.resolve('A')).toBeUndefined();+ });+});++describe('asTargetNamespace', () => {+ test('reuses a namespace of the same kind and indexes anything else', () => {+ const documents = createTargetNamespace('document', [RENE_NFD]);+ expect(asTargetNamespace('document', documents)).toBe(documents);+ const rebuilt = asTargetNamespace('file', documents);+ expect(rebuilt).not.toBe(documents);+ expect(rebuilt.kind).toBe('file');+ expect(rebuilt.resolve('People/RENÉ')).toBe(RENE_NFD);+ expect(documents.resolve('People/RENÉ')).toBeUndefined();+ const fromArray = asTargetNamespace('document', [RENE_NFD]);+ expect(fromArray.resolve(RENE_NFC)).toBe(RENE_NFD);+ });+});++const NAME_ALPHABET = [+ RENE_NFC,+ RENE_NFD,+ RENE_NFC.toLowerCase(),+ ZOE_NFC,+ ZOE_NFD,+ CAFE_NFC,+ CAFE_NFD,+ 'assets/CAFÉ.PNG',+ VIET_NFC,+ VIET_NFD,+ VIET_PARTIAL,+ 'README',+ 'readme',+ 'a/b',+ 'a-b',+];++type Step = { readonly op: 'add' | 'delete'; readonly name: string };++function describeNamespace(names: TargetNamespace<'document' | 'file'>): string {+ return NAME_ALPHABET.map((spelling) => JSON.stringify(names.lookup(spelling))).join('\n');+}++describe('insertion-order independence', () => {+ test('every permutation of the same names resolves every spelling identically', () => {+ fc.assert(+ fc.property(+ fc.uniqueArray(fc.constantFrom(...NAME_ALPHABET), { maxLength: 8 }),+ fc.constantFrom('document', 'file'),+ (names, kind) => {+ const sorted = createTargetNamespace(kind, [...names].sort());+ const reversed = createTargetNamespace(kind, [...names].sort().reverse());+ expect(describeNamespace(reversed)).toBe(describeNamespace(sorted));+ },+ ),+ );+ });++ test('a namespace mutated by random adds and deletes equals a fresh one over the final set', () => {+ fc.assert(+ fc.property(+ fc.array(+ fc.record<Step>({+ op: fc.constantFrom('add', 'delete'),+ name: fc.constantFrom(...NAME_ALPHABET),+ }),+ { maxLength: 24 },+ ),+ fc.constantFrom('document', 'file'),+ (steps, kind) => {+ const incremental: MutableTargetNamespace<'document' | 'file'> = createTargetNamespace(+ kind,+ [],+ );+ const expected = new Set<string>();+ for (const step of steps) {+ if (step.op === 'add') {+ incremental.add(step.name);+ expected.add(step.name);+ } else {+ expect(incremental.delete(step.name)).toBe(expected.has(step.name));+ expected.delete(step.name);+ }+ }+ const fresh = createTargetNamespace(kind, expected);+ expect(new Set(incremental)).toEqual(expected);+ expect(describeNamespace(incremental)).toBe(describeNamespace(fresh));+ },+ ),+ );+ });+});diff --git a/packages/core/src/utils/target-namespace.ts b/packages/core/src/utils/target-namespace.tsnew file mode 100644index 000000000..303168f59--- /dev/null+++ b/packages/core/src/utils/target-namespace.ts@@ -0,0 +1,135 @@+import {+ compareSpellings,+ type IdentityKey,+ identityKey,+ type TargetKind,+} from './target-identity.ts';++export type TargetMatch =+ | { readonly kind: 'exact'; readonly name: string }+ | { readonly kind: 'equivalent'; readonly name: string }+ | { readonly kind: 'ambiguous'; readonly name: string; readonly candidates: readonly string[] }+ | { readonly kind: 'absent' };++export interface TargetNamespace<K extends TargetKind> extends ReadonlySet<string> {+ readonly kind: K;+ lookup(spelling: string): TargetMatch;+ resolve(spelling: string): string | undefined;+}++export interface MutableTargetNamespace<K extends TargetKind> extends TargetNamespace<K> {+ add(name: string): this;+ delete(name: string): boolean;+ clear(): void;+}++const TARGET_NAMESPACE_BRAND = Symbol.for('@inkeep/open-knowledge-core/target-namespace');++class SpellingIndexedNamespace<K extends TargetKind>+ extends Set<string>+ implements MutableTargetNamespace<K>+{+ readonly kind: K;+ readonly [TARGET_NAMESPACE_BRAND] = true;+ private readonly byKey = new Map<IdentityKey<K>, string[]>();++ constructor(kind: K, names: Iterable<string>) {+ super();+ this.kind = kind;+ for (const name of names) this.add(name);+ }++ override add(name: string): this {+ if (super.has(name)) return this;+ super.add(name);+ const key = identityKey(this.kind, name);+ const bucket = this.byKey.get(key);+ if (bucket === undefined) {+ this.byKey.set(key, [name]);+ return this;+ }+ let index = 0;+ while (index < bucket.length && compareSpellings(bucket[index] as string, name) < 0) index++;+ bucket.splice(index, 0, name);+ return this;+ }++ override delete(name: string): boolean {+ if (!super.delete(name)) return false;+ const key = identityKey(this.kind, name);+ const bucket = this.byKey.get(key);+ if (bucket === undefined) return true;+ bucket.splice(bucket.indexOf(name), 1);+ if (bucket.length === 0) this.byKey.delete(key);+ return true;+ }++ override clear(): void {+ super.clear();+ this.byKey.clear();+ }++ lookup(spelling: string): TargetMatch {+ if (super.has(spelling)) return { kind: 'exact', name: spelling };+ const bucket = this.byKey.get(identityKey(this.kind, spelling));+ if (bucket === undefined) return { kind: 'absent' };+ const name = bucket[0] as string;+ return bucket.length === 1+ ? { kind: 'equivalent', name }+ : { kind: 'ambiguous', name, candidates: [...bucket] };+ }++ resolve(spelling: string): string | undefined {+ if (super.has(spelling)) return spelling;+ return this.byKey.get(identityKey(this.kind, spelling))?.[0];+ }+}++export function createTargetNamespace<K extends TargetKind>(+ kind: K,+ names: Iterable<string> = [],+): MutableTargetNamespace<K> {+ return new SpellingIndexedNamespace(kind, names);+}++export function addDocumentFolders(+ folders: MutableTargetNamespace<'folder'>,+ docNames: Iterable<string>,+): MutableTargetNamespace<'folder'> {+ for (const docName of docNames) {+ for (let slash = docName.indexOf('/'); slash !== -1; slash = docName.indexOf('/', slash + 1)) {+ folders.add(docName.slice(0, slash));+ }+ }+ return folders;+}++export function isTargetNamespace(+ names: ReadonlySet<string>,+): names is TargetNamespace<TargetKind> {+ return (+ (names as { readonly [TARGET_NAMESPACE_BRAND]?: unknown })[TARGET_NAMESPACE_BRAND] === true+ );+}++export function resolveName(names: ReadonlySet<string>, spelling: string): string | undefined {+ if (isTargetNamespace(names)) return names.resolve(spelling);+ return names.has(spelling) ? spelling : undefined;+}++function isNamespaceOfKind<K extends TargetKind>(+ names: Iterable<string>,+ kind: K,+): names is TargetNamespace<K> {+ const candidate = names as Partial<TargetNamespace<K>> & {+ readonly [TARGET_NAMESPACE_BRAND]?: unknown;+ };+ return candidate[TARGET_NAMESPACE_BRAND] === true && candidate.kind === kind;+}++export function asTargetNamespace<K extends TargetKind>(+ kind: K,+ names: Iterable<string>,+): TargetNamespace<K> {+ return isNamespaceOfKind(names, kind) ? names : createTargetNamespace(kind, names);+}diff --git a/packages/core/src/utils/wiki-link-resolve.test.ts b/packages/core/src/utils/wiki-link-resolve.test.tsindex 388136276..05466d677 100644--- a/packages/core/src/utils/wiki-link-resolve.test.ts+++ b/packages/core/src/utils/wiki-link-resolve.test.ts@@ -1,10 +1,12 @@import { describe, expect, test } from 'vitest';import { classifyWikiLinkTarget } from './link-targets.ts';import { toWikiLinkSlug } from './slug.ts';+import { createTargetNamespace } from './target-namespace.ts';import {buildPagesByBasenameIndex,buildPagesBySlugIndex,buildWikiLinkAssetTargetKeys,+ createWikiAssetResolver,isResolvedWikiLinkTarget,resolveWikiLinkAssetTarget,resolveWikiLinkTarget,@@ -199,6 +201,7 @@ describe('indexed asset target keys', () => {['cover.png', true],['/images/cover.png?x#y', true],['IMAGES/COVER.PNG', true],+ ['images/COVER.PNG', true],['guide.pdf#page=2', true],['table.csv', true],['data/table.csv', true],@@ -496,3 +499,90 @@ describe('explicit Markdown suffix precedence', () => {},);});++describe('canonically equivalent spellings', () => {+ const RENE_NFC = 'People/René';+ const RENE_NFD = 'People/René';+ const CAFE_NFC = 'assets/Café.png';+ const CAFE_NFD = 'assets/Café.png';++ function indexOver(pageNames: readonly string[]): WikiLinkLookupIndex {+ const pages = createTargetNamespace('document', pageNames);+ return {+ pages,+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),+ pagesByBasename: buildPagesByBasenameIndex(pages, toWikiLinkSlug),+ };+ }++ test('identity beats the slug bucket: an NFC target lands on the NFD page, not its accent-stripped sibling', () => {+ const lookup = indexOver([RENE_NFD, 'People/Rene']);+ expect(lookup.pagesBySlug.get(toWikiLinkSlug(RENE_NFC))).toBe('People/Rene');+ expect(resolveWikiLinkTargetDocName(RENE_NFC, lookup)).toBe(RENE_NFD);+ expect(resolveWikiLinkTargetDocName(`${RENE_NFC}.md`, lookup)).toBe(RENE_NFD);+ expect(resolveWikiLinkTargetDocName(RENE_NFD, lookup)).toBe(RENE_NFD);+ expect(resolveWikiLinkTargetDocName('People/Rene', lookup)).toBe('People/Rene');+ });++ test('an NFD target lands on the NFC page and folder notes resolve through identity too', () => {+ expect(resolveWikiLinkTargetDocName(RENE_NFD, indexOver([RENE_NFC]))).toBe(RENE_NFC);+ expect(resolveWikiLinkTargetDocName(RENE_NFC, indexOver([`${RENE_NFD}/index`]))).toBe(+ `${RENE_NFD}/index`,+ );+ });++ test('asset targets resolve by NFC and by case across the whole path, folders included', () => {+ const assets = new Set([CAFE_NFD]);+ expect(resolveWikiLinkAssetTarget(CAFE_NFC, assets)).toBe(CAFE_NFD);+ expect(resolveWikiLinkAssetTarget('assets/CAFÉ.PNG', assets)).toBe(CAFE_NFD);+ expect(resolveWikiLinkAssetTarget('/Café.png', assets)).toBe(CAFE_NFD);+ expect(resolveWikiLinkAssetTarget('Assets/Café.png', assets)).toBe(CAFE_NFD);+ expect(resolveWikiLinkAssetTarget('ASSETS/CAFÉ.PNG', assets)).toBe(CAFE_NFD);+ expect(resolveWikiLinkAssetTarget('file.png', new Set(['file.png']))).toBeNull();+ expect(resolveWikiLinkAssetTarget(CAFE_NFC, new Set(), assets)).toBe(CAFE_NFD);+ });++ test('indexed asset keys agree with the asset resolver', () => {+ const lookup: WikiLinkLookupIndex = {+ pages: new Set(),+ pagesBySlug: new Map(),+ assetTargetKeys: buildWikiLinkAssetTargetKeys([CAFE_NFD]),+ };+ expect(isResolvedWikiLinkTarget(CAFE_NFC, lookup)).toBe(true);+ expect(isResolvedWikiLinkTarget('assets/CAFÉ.PNG', lookup)).toBe(true);+ expect(isResolvedWikiLinkTarget('Café.png', lookup)).toBe(true);+ expect(isResolvedWikiLinkTarget('Assets/Café.png', lookup)).toBe(true);+ expect(isResolvedWikiLinkTarget('ASSETS/CAFÉ.PNG', lookup)).toBe(true);+ expect(isResolvedWikiLinkTarget('Other/Café.png', lookup)).toBe(false);+ });++ test('the wiki asset resolver ignores input order and prefers the lowest folded twin', () => {+ const paths = ['assets/a.png', 'Assets/a.png', CAFE_NFD, 'Pics/Deep/x.png', 'data/T.csv'];+ const expected: Array<[string, string | undefined]> = [+ ['assets/A.png', 'assets/a.png'],+ ['ASSETS/a.png', 'Assets/a.png'],+ [CAFE_NFC, CAFE_NFD],+ ['ASSETS/CAFÉ.PNG', CAFE_NFD],+ ['pics/deep/X.PNG', 'Pics/Deep/x.png'],+ ['DATA/t.CSV', 'data/T.csv'],+ ['pics/x.png', undefined],+ ];+ for (const order of [paths, [...paths].reverse()]) {+ const resolver = createWikiAssetResolver(order);+ for (const [target, want] of expected) {+ expect(resolver(target), target).toBe(want);+ expect(resolveWikiLinkAssetTarget(target, new Set(order)) ?? undefined, target).toBe(want);+ }+ }+ });++ test('an identity match beats a folder-case match, and folder-case twins pick one winner', () => {+ const twins = ['assets/a.png', 'Assets/a.png'];+ for (const order of [twins, [...twins].reverse()]) {+ const assets = new Set(order);+ expect(resolveWikiLinkAssetTarget('assets/A.png', assets)).toBe('assets/a.png');+ expect(resolveWikiLinkAssetTarget('Assets/A.png', assets)).toBe('Assets/a.png');+ expect(resolveWikiLinkAssetTarget('ASSETS/a.png', assets)).toBe('Assets/a.png');+ }+ });+});diff --git a/packages/core/src/utils/wiki-link-resolve.ts b/packages/core/src/utils/wiki-link-resolve.tsindex 0c786bfc9..bc4a042ae 100644--- a/packages/core/src/utils/wiki-link-resolve.ts+++ b/packages/core/src/utils/wiki-link-resolve.ts@@ -5,6 +5,8 @@ import {type ExternalLinkTarget,} from './link-targets.ts';import { toWikiLinkSlug } from './slug.ts';+import { compareSpellings, leafKey, wikiAssetPathKey } from './target-identity.ts';+import { asTargetNamespace, resolveName } from './target-namespace.ts';export interface WikiLinkLookupIndex {readonly pages: ReadonlySet<string>;@@ -33,12 +35,6 @@ function getFilePathsSet(input: WikiLinkPagesInput, filePaths?: ReadonlySet<strireturn isLookupIndex(input) ? (input.filePaths ?? new Set<string>()) : (filePaths ?? new Set());}-function compareDocNames(a: string, b: string): number {- if (a < b) return -1;- if (a > b) return 1;- return 0;-}-export function buildPagesBySlugIndex(pages: ReadonlySet<string>,slugFn: (text: string) => string,@@ -47,7 +43,7 @@ export function buildPagesBySlugIndex(for (const page of pages) {const key = slugFn(page);const previous = index.get(key);- if (key && (previous === undefined || compareDocNames(page, previous) < 0)) {+ if (key && (previous === undefined || compareSpellings(page, previous) < 0)) {index.set(key, page);}}@@ -59,7 +55,7 @@ export function buildPagesByBasenameIndex(slugFn: (text: string) => string,): ReadonlyMap<string, string> {const index = new Map<string, string>();- const sorted = [...pages].sort(compareDocNames);+ const sorted = [...pages].sort(compareSpellings);for (const page of sorted) {const slash = page.lastIndexOf('/');const basename = slash === -1 ? page : page.slice(slash + 1);@@ -78,7 +74,7 @@ function slugLookup(target: string, input: WikiLinkPagesInput): string | undefinlet bestMatch: string | undefined;for (const page of input) {if (toWikiLinkSlug(page) !== targetSlug) continue;- if (bestMatch === undefined || compareDocNames(page, bestMatch) < 0) bestMatch = page;+ if (bestMatch === undefined || compareSpellings(page, bestMatch) < 0) bestMatch = page;}return bestMatch;}@@ -95,7 +91,7 @@ function basenameLookup(target: string, input: WikiLinkPagesInput): string | undconst 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;+ if (bestMatch === undefined || compareSpellings(page, bestMatch) < 0) bestMatch = page;}return bestMatch;}@@ -114,7 +110,8 @@ export function resolveWikiLinkTargetDocName(const trimmed = target.trim();if (!trimmed) return undefined;const pages = getPagesSet(input);- if (pages.has(trimmed)) return trimmed;+ const viaIdentity = resolveName(pages, trimmed);+ if (viaIdentity !== undefined) return viaIdentity;const withoutMarkdownSuffix = trimmed.replace(/\.(md|mdx)$/i, '');if (withoutMarkdownSuffix !== trimmed) {const strippedMatch = resolveWikiLinkDocNameWithoutSuffixFallback(withoutMarkdownSuffix, input);@@ -130,11 +127,13 @@ function resolveWikiLinkDocNameWithoutSuffixFallback(const trimmed = target.trim();if (!trimmed) return undefined;const pages = getPagesSet(input);- if (pages.has(trimmed)) return trimmed;+ const viaIdentity = resolveName(pages, trimmed);+ if (viaIdentity !== undefined) return viaIdentity;const viaSlug = slugLookup(trimmed, input);if (viaSlug) return viaSlug;for (const candidate of getWikiLinkResolutionCandidates(trimmed)) {- if (pages.has(candidate)) return candidate;+ const viaCandidate = resolveName(pages, candidate);+ if (viaCandidate !== undefined) return viaCandidate;}const folderIndexDocName = resolveFolderIndexDocName(trimmed, pages);if (folderIndexDocName) return folderIndexDocName;@@ -142,13 +141,11 @@ function resolveWikiLinkDocNameWithoutSuffixFallback(}function resolveFolderIndexDocName(target: string, pages: ReadonlySet<string>): string | undefined {- const canonical = `${target}/index`;- if (pages.has(canonical)) return canonical;+ const canonical = resolveName(pages, `${target}/index`);+ if (canonical !== undefined) 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;+ return leaf ? resolveName(pages, `${target}/${leaf}`) : undefined;}function normalizeAssetTarget(target: string): string {@@ -158,6 +155,29 @@ function normalizeAssetTarget(target: string): string {return withoutQuery.startsWith('/') ? withoutQuery.slice(1) : withoutQuery;}+function foldWikiAssetPaths(paths: Iterable<string>): Map<string, string> {+ const folded = new Map<string, string>();+ for (const path of paths) {+ const key = wikiAssetPathKey(path);+ const current = folded.get(key);+ if (current === undefined || compareSpellings(path, current) < 0) folded.set(key, path);+ }+ return folded;+}++export function createWikiAssetResolver(+ paths: Iterable<string>,+): (spelling: string) => string | undefined {+ const files = asTargetNamespace('file', paths);+ let folded: Map<string, string> | undefined;+ return (spelling) => {+ const resolved = files.resolve(spelling);+ if (resolved !== undefined) return resolved;+ folded ??= foldWikiAssetPaths(files);+ return folded.get(wikiAssetPathKey(spelling));+ };+}+export function resolveWikiLinkAssetTarget(target: string,assetPaths: ReadonlySet<string>,@@ -166,29 +186,27 @@ export function resolveWikiLinkAssetTarget(const normalized = normalizeAssetTarget(target);if (!normalized) return null;- const lowerTarget = normalized.toLowerCase();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;- }+ const resolved = createWikiAssetResolver(partition)(normalized);+ if (resolved !== undefined) return resolved;}if (normalized.includes('/')) return null;+ const targetLeaf = leafKey('file', normalized);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 (leafKey('file', basename) === targetLeaf) matches.push(path);}}if (matches.length === 0) return null;- return matches.sort(compareDocNames)[0] ?? null;+ return matches.sort(compareSpellings)[0] ?? null;}export function buildWikiLinkAssetTargetKeys(@@ -197,9 +215,8 @@ export function buildWikiLinkAssetTargetKeys(const keys = new Set<string>();for (const partition of partitions) {for (const path of partition) {- const lower = path.toLowerCase();- keys.add(`path:${lower}`);- keys.add(`basename:${lower.slice(lower.lastIndexOf('/') + 1)}`);+ keys.add(`path:${wikiAssetPathKey(path)}`);+ keys.add(`basename:${leafKey('file', path.slice(path.lastIndexOf('/') + 1))}`);}}return keys;@@ -213,12 +230,13 @@ export function isResolvedWikiLinkTarget(): boolean {const trimmed = target.trim();if (!trimmed) return false;- const normalizedAsset = normalizeAssetTarget(trimmed).toLowerCase();+ const normalizedAsset = normalizeAssetTarget(trimmed);const indexedAsset = isLookupIndex(pages) ? pages.assetTargetKeys : undefined;if (indexedAsset !== undefined) {if (- indexedAsset.has(`path:${normalizedAsset}`) ||- (!normalizedAsset.includes('/') && indexedAsset.has(`basename:${normalizedAsset}`))+ indexedAsset.has(`path:${wikiAssetPathKey(normalizedAsset)}`) ||+ (!normalizedAsset.includes('/') &&+ indexedAsset.has(`basename:${leafKey('file', normalizedAsset)}`)))return true;} else if (diff --git a/packages/core/tests/contract/module-subpaths.test.ts b/packages/core/tests/contract/module-subpaths.test.tsindex 599d0fafb..050236e43 100644--- a/packages/core/tests/contract/module-subpaths.test.ts+++ b/packages/core/tests/contract/module-subpaths.test.ts@@ -117,6 +117,8 @@ import * as utilsRelativeTimeSubpath from '@inkeep/open-knowledge-core/utils/relimport * as utilsResolveInternalHrefSubpath from '@inkeep/open-knowledge-core/utils/resolve-internal-href';import * as utilsSanitizeFolderNameSubpath from '@inkeep/open-knowledge-core/utils/sanitize-folder-name';import * as utilsSlugSubpath from '@inkeep/open-knowledge-core/utils/slug';+import * as utilsTargetIdentitySubpath from '@inkeep/open-knowledge-core/utils/target-identity';+import * as utilsTargetNamespaceSubpath from '@inkeep/open-knowledge-core/utils/target-namespace';import * as utilsVimeoEmbedSubpath from '@inkeep/open-knowledge-core/utils/vimeo-embed';import * as utilsWikiLinkResolveSubpath from '@inkeep/open-knowledge-core/utils/wiki-link-resolve';import * as utilsYoutubeEmbedSubpath from '@inkeep/open-knowledge-core/utils/youtube-embed';@@ -257,6 +259,8 @@ const MODULE_SUBPATHS: Record<string, object> = {'./utils/resolve-internal-href': utilsResolveInternalHrefSubpath,'./utils/sanitize-folder-name': utilsSanitizeFolderNameSubpath,'./utils/slug': utilsSlugSubpath,+ './utils/target-identity': utilsTargetIdentitySubpath,+ './utils/target-namespace': utilsTargetNamespaceSubpath,'./utils/vimeo-embed': utilsVimeoEmbedSubpath,'./utils/wiki-link-resolve': utilsWikiLinkResolveSubpath,'./utils/youtube-embed': utilsYoutubeEmbedSubpath,diff --git a/packages/core/tests/contract/subpath-types/consumer.ts b/packages/core/tests/contract/subpath-types/consumer.tsindex d1032dd49..78f64d25d 100644--- a/packages/core/tests/contract/subpath-types/consumer.ts+++ b/packages/core/tests/contract/subpath-types/consumer.ts@@ -801,6 +801,24 @@ export type {toWikiLinkSlug,wikiLinkHref,} from '@inkeep/open-knowledge-core/utils/slug';+export type {+ DependencySlug,+ dependencySlug,+ IdentityKey,+ identityKey,+ leafKey,+ TARGET_IDENTITY,+ TargetKind,+} from '@inkeep/open-knowledge-core/utils/target-identity';+export type {+ asTargetNamespace,+ createTargetNamespace,+ isTargetNamespace,+ MutableTargetNamespace,+ resolveName,+ TargetMatch,+ TargetNamespace,+} from '@inkeep/open-knowledge-core/utils/target-namespace';export type { isVimeoUrl } from '@inkeep/open-knowledge-core/utils/vimeo-embed';export type {buildPagesByBasenameIndex,diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex 8add39f69..69eaeb9cb 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -132,6 +132,8 @@ const entry = {'utils-resolve-internal-href': 'src/utils/resolve-internal-href.ts','utils-sanitize-folder-name': 'src/utils/sanitize-folder-name.ts','utils-slug': 'src/utils/slug.ts',+ 'utils-target-identity': 'src/utils/target-identity.ts',+ 'utils-target-namespace': 'src/utils/target-namespace.ts','utils-vimeo-embed': 'src/utils/vimeo-embed.ts','utils-wiki-link-resolve': 'src/utils/wiki-link-resolve.ts','utils-youtube-embed': 'src/utils/youtube-embed.ts',diff --git a/packages/server/assets/skills/project/references/linking.md b/packages/server/assets/skills/project/references/linking.mdindex 0344fe4ac..ee26f8a4a 100644--- a/packages/server/assets/skills/project/references/linking.md+++ b/packages/server/assets/skills/project/references/linking.md@@ -10,7 +10,7 @@- **Every link must resolve to a doc that exists by the time you're done.** Within a single multi-doc authoring pass, linking a page you'll create later in the same pass is fine — `brokenLinks` reports it as `no-such-doc` until the target lands, an expected transient forward-reference rather than a wrong-path error. What's not acceptable is *leaving* a dead link behind: create the target in the same pass, or record it as a tracked task (`TaskCreate`, or your host's task tool — if the host has none, tell the user) and leave the mention as plain prose.- **Never wrap a link in backticks.** `` `[text](./foo.md)` `` is a bug — the backticks make it render as literal code rather than a link.- **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 only when `brokenLinkSuppression` is absent and `warnings` has no `link-check-deferred` entry (that entry means the server was still starting and checked nothing — that doc's links are re-checked only when you write or edit it again after startup, or by an `audit`, which can time out until then); 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`.+- **`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 only when `brokenLinkSuppression` is absent and `warnings` has no `link-check-deferred` entry (that entry means the server was still starting and checked nothing — that doc's links are re-checked only when you write or edit it again after startup, or by an `audit`, which can time out until then); 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; `excluded` = the file is on disk but a `.gitignore` or `.okignore` rule keeps it out of the project, so re-include it or its folder with a `!` rule in `.okignore` (for example `!ignored/`) or link something else; `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`.- **An empty `brokenLinks` alongside a `brokenLinkSuppression` does not mean every link resolves.** That field appears only when the project's reserved-log policy withheld findings, and it carries `{ reason: "reserved-log-policy", count: N }` and nothing else. No href comes back because none of them is repair work: the write landed in a lowercase-stemmed `log.md` or `log.mdx`, an append-only history whose entries deliberately reference pages that moved or were never written. **Never rewrite a reserved log's existing entries to clear a link.** Append new entries instead, and treat `links({ kind: "dead" })` on that file as a deliberate audit of raw state, never as a repair queue. The project can turn the policy off (**Settings ▸ This project ▸ Preferences ▸ Content rules**), in which case those findings come back through the normal channels.- **`audit` is the authoritative end-state link check** — run it once at the end of a multi-doc pass. Read `brokenLinkSuppression` on its result too: when present, the reserved-log policy withheld `count` findings, so a clean result is filtered rather than proof that every raw link resolves. Do not repair those log findings; use `links({ kind: "dead" })` only when deliberately inspecting raw state. Caveat: `audit` reports links only while the project's `validation.links` setting is not `off` (at `off` it returns clean with no warning), so if the project has silenced link validation, fall back to `links({ kind: "dead" })` — the unconditional read of the dead-link graph, which also lists skill-bundle docs excluded from the Problems plane (optionally scoped: `links({ kind: "dead", sourceDocuments: ["your/doc"] })`). Otherwise `links` is the graph-navigation reader, supplemental to `audit`, not a substitute. Companion `links` kinds: `backlinks` (incoming), `forward` (outgoing), `orphans` (no incoming), `hubs` (high-incoming), `suggest` (untextualized mentions worth linking).- **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.diff --git a/packages/server/src/api-asset.test.ts b/packages/server/src/api-asset.test.tsindex ba5d6329e..24194dc1a 100644--- a/packages/server/src/api-asset.test.ts+++ b/packages/server/src/api-asset.test.ts@@ -14,7 +14,11 @@ interface Harness {close: () => Promise<void>;}-async function startHarness(contentDir: string, contentFilter?: ContentFilter): Promise<Harness> {+async function startHarness(+ contentDir: string,+ contentFilter?: ContentFilter,+ resolveTrackedFile?: (relativePath: string) => string | undefined,+): Promise<Harness> {const ext = createApiExtension({hocuspocus: {} as Parameters<typeof createApiExtension>[0]['hocuspocus'],sessionManager: {} as Parameters<typeof createApiExtension>[0]['sessionManager'],@@ -22,6 +26,7 @@ async function startHarness(contentDir: string, contentFilter?: ContentFilter):serverInstanceId: 'test-server',getFileIndex: () => new Map(),contentFilter,+ resolveTrackedFile,});const server: Server = createServer((req, res) => {@@ -220,3 +225,86 @@ describe('GET /api/asset content-filter exclusions', () => {expect(await res.text()).toContain('Asset not found');});});++describe('GET /api/asset tracked-file fallback on an exact miss', () => {+ let tmpDir: string;+ let contentDir: string;+ let harness: Harness;+ const tracked = new Map([+ ['docs/Alias/Photo.png', 'docs/photo.png'],+ ['docs/alias.png', 'docs/scripted.svg'],+ ['docs/link-alias.png', 'docs/escape.png'],+ ['docs/Ignored.png', 'private/secret.png'],+ ['docs/missing.png', 'docs/also-missing.png'],+ ['docs/Chart?.png', 'docs/chart?.png'],+ ['docs/c#.png', 'docs/C#.png'],+ ]);++ beforeEach(async () => {+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-api-asset-tracked-'));+ contentDir = join(tmpDir, 'content');+ mkdirSync(join(contentDir, 'docs'), { recursive: true });+ mkdirSync(join(contentDir, 'private'), { recursive: true });+ writeFileSync(join(contentDir, 'docs', 'photo.png'), 'fake-png-bytes');+ writeFileSync(join(contentDir, 'docs', 'scripted.svg'), '<svg><script>alert(1)</script></svg>');+ writeFileSync(join(contentDir, 'docs', 'chart'), 'chart-prefix-bytes');+ writeFileSync(join(contentDir, 'docs', 'C'), 'c-prefix-bytes');+ writeFileSync(join(contentDir, 'private', 'secret.png'), 'secret-bytes');+ writeFileSync(join(tmpDir, 'outside.png'), 'outside');+ symlinkSync(join(tmpDir, 'outside.png'), join(contentDir, 'docs', 'escape.png'));+ const filter: ContentFilter = {+ isExcluded: (rel) => rel.startsWith('private/'),+ isDirExcluded: (rel) => rel === 'private',+ isPathIgnored: (rel) => rel === 'private' || rel.startsWith('private/'),+ getWatcherIgnoreGlobs: () => ['private'],+ incrementMdDir() {},+ decrementMdDir() {},+ rebuildDirCount() {},+ };+ harness = await startHarness(contentDir, filter, (relativePath) => tracked.get(relativePath));+ });++ afterEach(async () => {+ await harness.close();+ rmSync(tmpDir, { recursive: true, force: true });+ });++ test('serves the tracked file the resolver names when the requested spelling misses', async () => {+ const res = await fetch(assetUrl(harness.baseURL, 'docs/Alias/Photo.png'));+ expect(res.status).toBe(200);+ expect(res.headers.get('content-type')).toBe('image/png');+ expect(res.headers.get('content-disposition')).toBe('inline');+ expect(await res.text()).toBe('fake-png-bytes');+ });++ test('types the response by the resolved file, so an SVG keeps its CSP sandbox', async () => {+ const res = await fetch(assetUrl(harness.baseURL, 'docs/alias.png'));+ expect(res.status).toBe(200);+ expect(res.headers.get('content-type')).toBe('image/svg+xml');+ expect(res.headers.get('content-security-policy')).toBe(+ "sandbox; default-src 'none'; style-src 'unsafe-inline'",+ );+ });++ test('never serves a resolved file that escapes the content directory or is ignored', async () => {+ expect((await fetch(assetUrl(harness.baseURL, 'docs/link-alias.png'))).status).toBe(404);+ expect((await fetch(assetUrl(harness.baseURL, 'docs/Ignored.png'))).status).toBe(404);+ expect((await fetch(assetUrl(harness.baseURL, 'docs/missing.png'))).status).toBe(404);+ });++ test('a tracked name holding ? or # is never answered with the bytes of its prefix', async () => {+ for (const path of ['docs/Chart?.png', 'docs/c#.png']) {+ const res = await fetch(assetUrl(harness.baseURL, path));+ expect(res.status).toBe(404);+ expect(await res.text()).not.toMatch(/prefix-bytes/);+ }+ });++ test('the text view follows the same fallback', async () => {+ const res = await fetch(+ `${harness.baseURL}/api/asset-text?path=${encodeURIComponent('docs/Alias/Photo.png')}`,+ );+ expect(res.status).toBe(200);+ expect(await res.text()).toBe('fake-png-bytes');+ });+});diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 23d46c853..e27897e59 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -27,11 +27,13 @@ import {AgentWriteBatchSuccessSchema,AgentWriteRequestSchema,AgentWriteSuccessSchema,+ asTargetNamespace,type BatchEntryError,type ConfigDiagnosticsReport,changedBlockRange,colorFromSeed,createCodeFenceTracker,+ createWikiAssetResolver,DEFAULT_LINTER_CONFIG,type DiskEditReconciledWarning,type DocumentListEntry,@@ -314,7 +316,13 @@ import {checkLocalOpSecurity as checkLocalOpSecurityBase,createConcurrencyGuard,} from './local-op-security.ts';-import { localTargetInventoryFromIndexes } from './local-target-inventory.ts';+import { isExcludedFileOnDisk } from './local-target-index.ts';+import {+ createFileBasenameResolver,+ createFileExistsOracle,+ localTargetInventoryFromIndexes,+ type WatcherLocalTargetInventory,+} from './local-target-inventory.ts';import { getLogger } from './logger.ts';import {managedArtifactAbsPath,@@ -362,7 +370,7 @@ import { readSkillInstallModeRaw } from './skill-placements.ts';import type { SyncEngine } from './sync-engine.ts';import { getMeter, withSpan, withSpanSync } from './telemetry.ts';-import { computeWriteAdvisoryLinks } from './write-advisory-links.ts';+import { computeWriteAdvisoryLinks, type WriteAdvisoryTargets } from './write-advisory-links.ts';let _renameAttributionCounter: ReturnType<ReturnType<typeof getMeter>['createCounter']> | null =null;@@ -1273,6 +1281,7 @@ interface ApiExtensionBaseOptions {onReferencedAssetsCacheInvalidator?: (invalidate: () => void) => void;getAliasMap?: () => ReadonlyMap<string, string>;getFolderAliasIndex?: () => ReadonlyMap<string, string>;+ resolveTrackedFile?: (relativePath: string) => string | undefined;rescanFiles?: () => void | Promise<void>;localOpConcurrencyGuard?: ReturnType<typeof createConcurrencyGuard>;enableTestRoutes?: boolean;@@ -1464,6 +1473,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {onReferencedAssetsCacheInvalidator,getAliasMap,getFolderAliasIndex,+ resolveTrackedFile,rescanFiles,localOpConcurrencyGuard,enableTestRoutes = false,@@ -1895,18 +1905,20 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {return derivedDocumentIndex?.isReady() ?? true;}- const prepareWriteLinkAdvisory: PrepareWriteLinkAdvisory = async (- writtenDocNames,- { resolveFolderLinks },- ) => {+ const prepareWriteLinkAdvisory: PrepareWriteLinkAdvisory = async (writtenDocNames) => {if (!isDerivedIndexReady()) return deferredWriteLinkAdvisory;const admitted = await collectAdmittedDocNames();for (const docName of writtenDocNames) admitted.add(docName);- const linkedFileExists = createLinkedFileExists();- const linkedFolderExists = resolveFolderLinks ? createLinkedFolderExists() : undefined;+ const targets: WriteAdvisoryTargets = {+ fileExists: createLinkedFileExists(),+ folderExists: createLinkedFolderExists(),+ fileExcluded: createLinkedFileExcluded(),+ resolveWikiFile: createLinkedWikiFileResolver(),+ resolveFileByBasename: createLinkedFileBasenameResolver(),+ };return (source, docName, suppressLogLinkAdvisories) => ({links: projectWriteAdvisoryLinks(- computeWriteAdvisoryLinks(source, docName, admitted, linkedFileExists, linkedFolderExists),+ computeWriteAdvisoryLinks(source, docName, admitted, targets),docName,suppressLogLinkAdvisories,),@@ -2051,7 +2063,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {function createLinkedFolderExists(): (folderPath: string) => boolean {const folderIndex = getFolderIndex?.();if (!folderIndex) return () => false;- return (folderPath) => folderIndex.has(folderPath);+ const folders = asTargetNamespace('folder', folderIndex.keys());+ return (folderPath) => folders.resolve(folderPath) !== undefined;}function createLinkedFileExists(@@ -2062,28 +2075,44 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {getFolderAliasIndex?.() ?? new Map(),contentDir,);- const admittedFiles = new Set(inventory.fileTargets);- const canonicalContentDir = realpathSync(contentDir);+ return createFileExistsOracle(inventory.fileTargets, contentDir, contentFilter);+ }++ function linkedLocalTargetInventory(): WatcherLocalTargetInventory {+ return localTargetInventoryFromIndexes(+ getAllFilesIndex(),+ getFolderAliasIndex?.() ?? new Map(),+ contentDir,+ getFolderIndex?.(),+ );+ }++ function createLinkedWikiFileResolver(): (contentRootRelativePath: string) => string | undefined {+ let resolveWikiFile: ((contentRootRelativePath: string) => string | undefined) | undefined;return (contentRootRelativePath) => {- if (admittedFiles.has(contentRootRelativePath)) return true;- if (contentFilter?.isPathIgnored(contentRootRelativePath)) return false;+ resolveWikiFile ??= createWikiAssetResolver(linkedLocalTargetInventory().fileTargets);+ return resolveWikiFile(contentRootRelativePath);+ };+ }- const candidate = resolve(contentDir, contentRootRelativePath);- if (!isWithinDir(candidate, contentDir) || !existsSync(candidate)) return false;- try {- return isWithinDir(realpathSync(candidate), canonicalContentDir);- } catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {- log.debug(- { err, candidate },- 'linked-file existence fallback could not canonicalize; treating as absent',- );- }- return false;- }+ function createLinkedFileBasenameResolver(): (+ basename: string,+ sourceDocName: string,+ ) => string | undefined {+ let resolveByBasename:+ | ((basename: string, sourceDocName: string) => string | undefined)+ | undefined;+ return (basename, sourceDocName) => {+ resolveByBasename ??= createFileBasenameResolver(linkedLocalTargetInventory().fileTargets);+ return resolveByBasename(basename, sourceDocName);};}+ function createLinkedFileExcluded(): (contentRootRelativePath: string) => boolean {+ return (contentRootRelativePath) =>+ isExcludedFileOnDisk(contentDir, contentFilter, contentRootRelativePath);+ }+/*** Mirrors the watcher's admission gate (precedent #55): a content-scope-excluded doc must* NOT be registered, exactly as the watcher would skip it.@@ -3869,7 +3898,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {const linkAdvisor = await prepareWriteLinkAdvisory(pending.filter((p) => flushErrors.get(p.docName) === undefined).map((p) => p.docName),- { resolveFolderLinks: true },);let lastWrittenDoc: string | undefined;@@ -3949,6 +3977,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {contentDir,isPathIgnored: (relativePath) => contentFilter?.isPathIgnored(relativePath) ?? false,getAttachmentFolderPath,+ resolveTrackedFile,});const fileOpsService = createFileOpsService({contentDir,@@ -4774,6 +4803,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {linkPolicy,admittedDocNames: collectAdmittedDocNames,docFilePathFor: (d) => resolveDocFilePath(contentDir, d),+ localTargetInventory: linkedLocalTargetInventory,}).find((validator) => validator.id === 'links');if (linksValidator) {const run = await linksValidator.run({@@ -4912,6 +4942,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {collectAdmittedDocNames,unmatchedGlobProblems,readAuditGeneration,+ localTargetInventory: linkedLocalTargetInventory,});const lintWriteRoutes = createLintWriteRoutes({conflicts,diff --git a/packages/server/src/api-write-link-policy.test.ts b/packages/server/src/api-write-link-policy.test.tsindex 6ce91cee3..1b5aafdff 100644--- a/packages/server/src/api-write-link-policy.test.ts+++ b/packages/server/src/api-write-link-policy.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import type { IncomingMessage, ServerResponse } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -295,3 +295,118 @@ describe('write-time broken-link advisories under the reserved-log policy', () =expect(body.brokenLinkSuppression).toBeUndefined();});});++describe('write-time advisories for links to folders that hold no document', () => {+ const CAFE_NFC = 'Café'.normalize('NFC');+ const CAFE_NFD = 'Café'.normalize('NFD');++ async function postWithFolders(+ url: string,+ body: Record<string, unknown>,+ folders: string[],+ ): Promise<LinkAdvisoryBody> {+ const ext = createApiExtension({+ hocuspocus,+ sessionManager,+ contentDir,+ getFileIndex: () => new Map(),+ getFolderIndex: () =>+ new Map(+ folders.map((folder) => [+ folder,+ { size: 0 as const, modified: '', canonicalPath: join(contentDir, folder), inode: 0 },+ ]),+ ),+ });+ const req = makeJsonPostReq(url, { ...body, agentId: 'claude-1', agentName: 'Claude' });+ const { res, captured } = makeRes();+ await (+ ext as {+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;+ }+ ).onRequest({ request: req, response: res });+ expect(captured.status).toBe(200);+ return JSON.parse(captured.body) as LinkAdvisoryBody;+ }++ test('a link spelled in the other normalization form names the existing folder', async () => {+ const body = await postWithFolders(+ '/api/agent-write-md',+ {+ docName: 'Probe',+ markdown: `See [dir](${CAFE_NFD}) and [[${CAFE_NFD}]] and [[Nope]].\n`,+ position: 'replace',+ },+ [CAFE_NFC],+ );+ expect((body.brokenLinks ?? []).map((link) => link.href)).toEqual(['[[Nope]]']);+ });++ const LINKS_TO_AN_ASSET_FOLDER = '# Probe\n\nSee [dir](assets) and [[assets]] and [[Nope]].\n';++ test('a frontmatter patch resolves a link to a folder that holds only assets', async () => {+ await seed('Probe', LINKS_TO_AN_ASSET_FOLDER);+ const body = await postWithFolders(+ '/api/frontmatter-patch',+ { docName: 'Probe', patch: { title: 'Probe' } },+ ['assets'],+ );+ expect((body.brokenLinks ?? []).map((link) => link.href)).toEqual(['[[Nope]]']);+ });++ test('an agent patch resolves a link to a folder that holds only assets', async () => {+ await seed('Probe', LINKS_TO_AN_ASSET_FOLDER);+ const body = await postWithFolders(+ '/api/agent-patch',+ { docName: 'Probe', find: 'See', replace: 'Still see' },+ ['assets'],+ );+ expect((body.brokenLinks ?? []).map((link) => link.href)).toEqual(['[[Nope]]']);+ });+});++describe('write-time advisories for slash-free wiki asset embeds', () => {+ test('a basename that names no tracked file is reported, one that names a tracked file is not', async () => {+ mkdirSync(join(contentDir, 'media'), { recursive: true });+ writeFileSync(join(contentDir, 'media', 'photo.png'), 'png');+ const ext = createApiExtension({+ hocuspocus,+ sessionManager,+ contentDir,+ getFileIndex: () => new Map(),+ getAllFilesIndex: () =>+ new Map([+ [+ 'media/photo.png',+ {+ size: 3,+ modified: '',+ canonicalPath: join(contentDir, 'media', 'photo.png'),+ inode: 0,+ aliases: [],+ kind: 'file' as const,+ },+ ],+ ]),+ });+ const req = makeJsonPostReq('/api/agent-write-md', {+ docName: 'notes/Probe',+ markdown: 'See ![[photo.png]], ![[PHOTO.png]], ![[ghost.png]] and ![[media/gone.png]].\n',+ position: 'replace',+ agentId: 'claude-1',+ agentName: 'Claude',+ });+ const { res, captured } = makeRes();+ await (+ ext as {+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;+ }+ ).onRequest({ request: req, response: res });+ expect(captured.status).toBe(200);+ const body = JSON.parse(captured.body) as LinkAdvisoryBody;+ expect((body.brokenLinks ?? []).map((link) => link.href).sort()).toEqual([+ 'ghost.png',+ 'media/gone.png',+ ]);+ });+});diff --git a/packages/server/src/apply-managed-rename.test.ts b/packages/server/src/apply-managed-rename.test.tsindex 60c5e4a89..f6e1f162a 100644--- a/packages/server/src/apply-managed-rename.test.ts+++ b/packages/server/src/apply-managed-rename.test.ts@@ -410,3 +410,18 @@ describe('applyRenameMap — outbound link recomputation when source doc moves',expect(result.rewrites).toBe(1);});});++describe('applyRenameMap across canonically equivalent spellings', () => {+ test('an NFC markdown link to an NFD document is rewritten when that document is renamed', () => {+ const nfd = 'people/Rene\u0301';+ const result = rewriteInCorpus(+ 'See [R](./people/Ren\u00e9.md) and [[people/Ren\u00e9]].\n',+ 'notes',+ new Map([[nfd, 'archive/Rene\u0301']]),+ );+ expect(result).toEqual({+ markdown: 'See [R](./archive/Rene%CC%81.md) and [[archive/Rene\u0301|people/Ren\u00e9]].\n',+ rewrites: 2,+ });+ });+});diff --git a/packages/server/src/apply-managed-rename.ts b/packages/server/src/apply-managed-rename.tsindex ab7342164..ab13efbef 100644--- a/packages/server/src/apply-managed-rename.ts+++ b/packages/server/src/apply-managed-rename.ts@@ -1,6 +1,8 @@import { randomUUID } from 'node:crypto';import { prependFrontmatter, stripFrontmatter } from '@inkeep/open-knowledge-core';import {+ type CanonicalDocName,+ canonicalDocNameBeforeRename,rewriteJsxSrcRefsForDocumentRename,rewriteMarkdownLinksForDocumentRename,rewriteOutboundMarkdownLinksForSourceMove,@@ -130,6 +132,7 @@ function rewriteSupportedLinksForRename(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName,): ManagedRenameRewriteSummary {const { frontmatter, body } = stripFrontmatter(markdown);const markdownRewrite = rewriteMarkdownLinksForDocumentRename(@@ -137,12 +140,14 @@ function rewriteSupportedLinksForRename(sourceDocName,oldDocName,newDocName,+ canonical,);const jsxRewrite = rewriteJsxSrcRefsForDocumentRename(markdownRewrite.markdown,sourceDocName,oldDocName,newDocName,+ canonical,);return {markdown: prependFrontmatter(frontmatter, jsxRewrite.markdown),@@ -157,6 +162,7 @@ export function applyRenameMap(): ManagedRenameRewriteSummary {const { frontmatter, body } = stripFrontmatter(content);const wikiRewrite = rewriteWikiLinksForRenameMap(body, currentDocName, wikiContext);+ const canonical = canonicalDocNameBeforeRename(wikiContext);let markdown = prependFrontmatter(frontmatter, wikiRewrite.markdown);let rewrites = wikiRewrite.rewrites;@@ -177,6 +183,7 @@ export function applyRenameMap(currentDocName,currentDocName,selfRenamedTo,+ canonical,);markdown = selfPass.markdown;rewrites += selfPass.rewrites;@@ -201,6 +208,7 @@ export function applyRenameMap(resolutionSourceName,from,placeholder,+ canonical,);if (phase1.rewrites > 0) {markdown = phase1.markdown;@@ -210,7 +218,13 @@ export function applyRenameMap(}for (const [placeholder, to] of placeholderToFinal) {- const phase2 = rewriteSupportedLinksForRename(markdown, resolutionSourceName, placeholder, to);+ const phase2 = rewriteSupportedLinksForRename(+ markdown,+ resolutionSourceName,+ placeholder,+ to,+ canonical,+ );markdown = phase2.markdown;}diff --git a/packages/server/src/asset-serve-middleware.integration.test.ts b/packages/server/src/asset-serve-middleware.integration.test.tsindex b7b7484ef..55dab7a1c 100644--- a/packages/server/src/asset-serve-middleware.integration.test.ts+++ b/packages/server/src/asset-serve-middleware.integration.test.ts@@ -1,9 +1,11 @@import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { createServer, request as httpRequest, type Server } from 'node:http';+import { connect } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';import {ASSET_EXTENSIONS,+ createTargetNamespace,EXECUTABLE_BLOCKLIST_EXTENSIONS,INLINE_RENDERABLE_EXTENSIONS,} from '@inkeep/open-knowledge-core';@@ -20,7 +22,10 @@ interface Harness {close: () => Promise<void>;}-async function startHarness(contentDir: string): Promise<Harness> {+async function startHarness(+ contentDir: string,+ resolveTrackedFile?: (relativePath: string) => string | undefined,+): Promise<Harness> {const contentFilter = createContentFilter({projectDir: contentDir,contentDir,@@ -33,6 +38,7 @@ async function startHarness(contentDir: string): Promise<Harness> {assetExtensions: ASSET_EXTENSIONS,blocklistExtensions: EXECUTABLE_BLOCKLIST_EXTENSIONS,ingressPolicy: buildIngressPolicy({}),+ resolveTrackedFile,});const server: Server = createServer((req, res) => {@@ -381,4 +387,159 @@ describe('asset-serve middleware (narrow integration)', () => {}});});++ describe('Raw request targets that only an HTTP client can send', () => {+ const SECRET = 'ignored-secret-bytes';++ function rawGet(target: string): Promise<{ statusLine: string; response: string }> {+ const { hostname, port } = new URL(harness.baseURL);+ return new Promise((resolve, reject) => {+ let response = '';+ const socket = connect({ host: hostname, port: Number(port) }, () => {+ socket.write(+ `GET ${target} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`,+ );+ });+ socket.setEncoding('utf8');+ socket.on('data', (chunk: string) => {+ response += chunk;+ });+ socket.on('end', () => resolve({ statusLine: response.split('\r\n')[0] ?? '', response }));+ socket.on('error', reject);+ });+ }++ test('a # in the request line never serves the ignored file its prefix names', async () => {+ writeFileSync(join(contentDir, '.okignore'), '/docs/secret\n');+ writeFileSync(join(contentDir, 'docs', 'secret'), SECRET);+ writeFileSync(join(contentDir, '.env'), SECRET);+ await harness.close();+ harness = await startHarness(contentDir);++ const answers: Array<[string, string, boolean]> = [];+ for (const target of ['/docs/secret#.png', '/.env#.png']) {+ const { statusLine, response } = await rawGet(target);+ answers.push([target, statusLine, response.includes(SECRET)]);+ }+ expect(answers).toEqual([+ ['/docs/secret#.png', 'HTTP/1.1 404 Not Found', false],+ ['/.env#.png', 'HTTP/1.1 404 Not Found', false],+ ]);+ });++ test('an encoded reserved character the gate and sirv decode differently is refused before sirv', async () => {+ writeFileSync(join(contentDir, '.okignore'), 'x%2Fy.png\n');+ writeFileSync(join(contentDir, 'docs', 'x%2Fy.png'), SECRET);+ await harness.close();+ harness = await startHarness(contentDir);++ const { statusLine, response } = await rawGet('/docs/x%2Fy.png');+ expect(statusLine).toBe('HTTP/1.1 404 Not Found');+ expect(response).not.toContain(SECRET);+ });++ test('dot, empty and backslash segments never route around an anchored ignore rule', async () => {+ function bodyOf(response: string): string {+ if (response.includes(SECRET)) return 'secret';+ if (response.includes('spa fallback sentinel')) return 'spa fallback';+ return 'neither';+ }+ writeFileSync(join(contentDir, 'docs', 'secret.png'), SECRET);+ const beforeTheRule = await rawGet('/docs/secret.png');+ writeFileSync(join(contentDir, '.okignore'), '/docs/secret.png\n');+ const backslashSpelling = 'x\\..\\docs\\secret.png';+ writeFileSync(join(contentDir, backslashSpelling), SECRET);+ await harness.close();+ harness = await startHarness(contentDir);++ const answers: Array<[string, string, string]> = [];+ for (const target of [+ '/docs/secret.png',+ '/docs/./secret.png',+ '/docs//secret.png',+ '/x/../docs/secret.png',+ `/${encodeURIComponent(backslashSpelling)}`,+ ]) {+ const { statusLine, response } = await rawGet(target);+ answers.push([target, statusLine, bodyOf(response)]);+ }+ expect([beforeTheRule.statusLine, bodyOf(beforeTheRule.response)]).toEqual([+ 'HTTP/1.1 200 OK',+ 'secret',+ ]);+ expect(answers).toEqual([+ ['/docs/secret.png', 'HTTP/1.1 200 OK', 'spa fallback'],+ ['/docs/./secret.png', 'HTTP/1.1 404 Not Found', 'neither'],+ ['/docs//secret.png', 'HTTP/1.1 404 Not Found', 'neither'],+ ['/x/../docs/secret.png', 'HTTP/1.1 404 Not Found', 'neither'],+ ['/x%5C..%5Cdocs%5Csecret.png', 'HTTP/1.1 404 Not Found', 'neither'],+ ]);+ });++ test('a request line both decoders agree on is still served', async () => {+ const { statusLine, response } = await rawGet('/docs/photo.png?v=1');+ expect(statusLine).toBe('HTTP/1.1 200 OK');+ expect(response).toContain('fake-png-bytes');+ });+ });++ describe('Tracked-file fallback when the requested spelling misses on disk', () => {+ const CAFE_NFD = 'docs/Café.png'.normalize('NFD');+ const SECRET = 'machine-local-secret';++ async function restartWithTracked(trackedFiles: readonly string[]): Promise<void> {+ await harness.close();+ const tracked = createTargetNamespace('file', trackedFiles);+ harness = await startHarness(contentDir, (relativePath) => tracked.resolve(relativePath));+ }++ test('an NFC request serves the NFD-named file on every platform', async () => {+ writeFileSync(join(contentDir, CAFE_NFD), 'nfd-bytes');+ await restartWithTracked([CAFE_NFD]);+ const nfc = encodeURI('/docs/Café.png'.normalize('NFC'));+ const res = await fetch(`${harness.baseURL}${nfc}`);+ expect(res.status).toBe(200);+ expect(res.headers.get('content-type')).toMatch(/^image\/png/);+ expect(res.headers.get('content-disposition')).toBe('inline');+ expect(await res.text()).toBe('nfd-bytes');+ });++ test('a leaf-case request serves the tracked file on every platform', async () => {+ await restartWithTracked(['docs/photo.png']);+ const res = await fetch(`${harness.baseURL}/docs/PHOTO.PNG`);+ expect(res.status).toBe(200);+ expect(await res.text()).toBe('fake-png-bytes');+ });++ test('a tracked symlink into private state is still refused', async () => {+ mkdirSync(join(contentDir, '.git'), { recursive: true });+ writeFileSync(join(contentDir, '.git', 'config'), `[core]\n\t# ${SECRET}\n`);+ symlinkSync('../.git/config', join(contentDir, 'docs', 'cfg.txt'));+ await restartWithTracked(['docs/cfg.txt']);+ const res = await fetch(`${harness.baseURL}/docs/CFG.TXT`);+ expect(res.status).toBe(404);+ expect(await res.text()).not.toContain(SECRET);+ });++ test('a tracked name holding ? never serves the ignored file its prefix names', async () => {+ writeFileSync(join(contentDir, '.okignore'), '/docs/secret\n');+ writeFileSync(join(contentDir, 'docs', 'secret'), SECRET);+ await restartWithTracked(['docs/secret?.png']);+ const res = await fetch(`${harness.baseURL}/docs/SECRET%3F.png`);+ expect(res.status).toBe(404);+ expect(await res.text()).not.toContain(SECRET);+ });++ test('a tracked name holding ? or # is never answered with the bytes of its prefix', async () => {+ writeFileSync(join(contentDir, 'docs', 'chart'), 'chart-prefix-bytes');+ writeFileSync(join(contentDir, 'docs', 'C'), 'c-prefix-bytes');+ await restartWithTracked(['docs/chart?.png', 'docs/C#.png']);+ const answers: string[] = [];+ for (const path of ['/docs/CHART%3F.png', '/docs/c%23.png']) {+ const res = await fetch(`${harness.baseURL}${path}`);+ answers.push(`${path} ${res.status} ${await res.text()}`);+ }+ expect(answers).toEqual(['/docs/CHART%3F.png 404 ', '/docs/c%23.png 404 ']);+ });+ });});diff --git a/packages/server/src/asset-serve-middleware.test.ts b/packages/server/src/asset-serve-middleware.test.tsindex eecb35a38..1905ff3e2 100644--- a/packages/server/src/asset-serve-middleware.test.ts+++ b/packages/server/src/asset-serve-middleware.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import type { IncomingMessage, ServerResponse } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -92,20 +92,30 @@ const SERVABLE_FIXTURES = ['Notes.MD','doc.mdx','my file.m4v',+ 'payload.dmg',];let fixtureDir: string;+let outsideDir: string;beforeAll(() => {fixtureDir = mkdtempSync(join(tmpdir(), 'ok-asset-serve-unit-'));+ outsideDir = mkdtempSync(join(tmpdir(), 'ok-asset-serve-outside-'));for (const name of SERVABLE_FIXTURES) writeFileSync(join(fixtureDir, name), 'fixture');+ writeFileSync(join(outsideDir, 'secret.png'), 'outside');+ symlinkSync(join(outsideDir, 'secret.png'), join(fixtureDir, 'escape.png'));});afterAll(() => {rmSync(fixtureDir, { recursive: true, force: true });+ rmSync(outsideDir, { recursive: true, force: true });});-function buildMiddleware(sirv: SirvLikeMiddleware, filter: AssetServeFilter = admitAll) {+function buildMiddleware(+ sirv: SirvLikeMiddleware,+ filter: AssetServeFilter = admitAll,+ resolveTrackedFile?: (relativePath: string) => string | undefined,+) {return createAssetServeMiddleware({contentDir: fixtureDir,contentFilter: filter,@@ -114,9 +124,22 @@ function buildMiddleware(sirv: SirvLikeMiddleware, filter: AssetServeFilter = adassetExtensions: ASSETS,blocklistExtensions: BLOCKLIST,ingressPolicy: buildIngressPolicy({}),+ resolveTrackedFile,});}+function sirvRecording(urls: string[]): SirvLikeMiddleware {+ return (req, res) => {+ urls.push(req.url ?? '');+ res.writeHead(200);+ res.end();+ };+}++function trackedAlias(alias: string, target: string) {+ return (relativePath: string) => (relativePath === alias ? target : undefined);+}+describe('createAssetServeMiddleware', () => {describe('filter exclusion', () => {test('excluded path falls through to next() immediately without setting headers', () => {@@ -431,4 +454,148 @@ describe('createAssetServeMiddleware', () => {expect(captured.headers['Content-Disposition']).toBeUndefined();});});++ describe('tracked-file fallback on an exact miss', () => {+ test('serves the tracked file the resolver names and keeps the query string', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('Alias/Photo.png', 'photo.png'),+ );+ const { res, captured } = makeRes();+ let nextCalled = false;+ middleware(makeReq('/Alias/Photo.png?v=2'), res, () => {+ nextCalled = true;+ });+ expect(urls).toEqual(['/photo.png?v=2']);+ expect(captured.status).toBe(200);+ expect(captured.headers['Content-Disposition']).toBe('inline');+ expect(nextCalled).toBe(false);+ });++ test('encodes the resolved spelling so the static server looks up its exact bytes', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('alias.m4v', 'my file.m4v'),+ );+ const { res, captured } = makeRes();+ middleware(makeReq('/alias.m4v'), res, () => {});+ expect(urls).toEqual(['/my%20file.m4v']);+ expect(captured.status).toBe(200);+ });++ test('disposition and CSP follow the resolved file rather than the requested spelling', () => {+ const svg = buildMiddleware(sirvServes, admitAll, trackedAlias('alias.png', 'icon.svg'));+ const svgRes = makeRes();+ svg(makeReq('/alias.png'), svgRes.res, () => {});+ expect(svgRes.captured.status).toBe(200);+ expect(svgRes.captured.headers['Content-Security-Policy']).toBe(+ "sandbox; default-src 'none'; style-src 'unsafe-inline'",+ );++ const csv = buildMiddleware(sirvServes, admitAll, trackedAlias('alias.png', 'data.csv'));+ const csvRes = makeRes();+ csv(makeReq('/alias.png'), csvRes.res, () => {});+ expect(csvRes.captured.status).toBe(200);+ expect(csvRes.captured.headers['Content-Disposition']).toBe('attachment');+ });++ test('the resolver is not consulted when the requested spelling exists', () => {+ const asked: string[] = [];+ const middleware = buildMiddleware(sirvServes, admitAll, (relativePath) => {+ asked.push(relativePath);+ return undefined;+ });+ const { res, captured } = makeRes();+ middleware(makeReq('/photo.png'), res, () => {});+ expect(captured.status).toBe(200);+ expect(asked).toEqual([]);+ });++ test('a resolved file the content filter ignores is not served', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ { isPathIgnored: (relativePath) => relativePath === 'photo.png' },+ trackedAlias('alias.png', 'photo.png'),+ );+ const { res, captured } = makeRes();+ middleware(makeReq('/alias.png'), res, () => {});+ expect(urls).toEqual([]);+ expect(captured.status).toBe(404);+ });++ test('a resolved file outside the servable asset extensions is not served', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('alias.png', 'payload.dmg'),+ );+ const { res, captured } = makeRes();+ middleware(makeReq('/alias.png'), res, () => {});+ expect(urls).toEqual([]);+ expect(captured.status).toBe(404);+ });++ test('a resolved symlink that escapes the content directory is not served', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('link-alias.png', 'escape.png'),+ );+ const { res, captured } = makeRes();+ middleware(makeReq('/link-alias.png'), res, () => {});+ expect(urls).toEqual([]);+ expect(captured.status).toBe(404);+ });++ test('a resolved name no URL can spell is refused rather than thrown on', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('alias.png', '\uD800.png'),+ );+ const { res, captured } = makeRes();+ middleware(makeReq('/alias.png'), res, () => {});+ expect(urls).toEqual([]);+ expect(captured.status).toBe(404);+ });++ test('a markdown request never falls back to a tracked file', () => {+ const urls: string[] = [];+ const middleware = buildMiddleware(+ sirvRecording(urls),+ admitAll,+ trackedAlias('missing.md', 'notes.md'),+ );+ const { res } = makeRes();+ let nextCalled = false;+ middleware(makeReq('/missing.md'), res, () => {+ nextCalled = true;+ });+ expect(urls).toEqual([]);+ expect(nextCalled).toBe(true);+ });++ test('an html fall-through after a resolved hit restores the requested URL for the SPA shell', () => {+ const middleware = buildMiddleware(+ sirvFallThrough,+ admitAll,+ trackedAlias('Viewer.html', 'trip-viewer.html'),+ );+ const { res } = makeRes();+ const req = makeReq('/Viewer.html');+ let urlAtNext: string | undefined;+ middleware(req, res, () => {+ urlAtNext = req.url;+ });+ expect(urlAtNext).toBe('/Viewer.html');+ });+ });});diff --git a/packages/server/src/asset-serve-middleware.ts b/packages/server/src/asset-serve-middleware.tsindex 3ac1ec32a..34e0961ca 100644--- a/packages/server/src/asset-serve-middleware.ts+++ b/packages/server/src/asset-serve-middleware.ts@@ -11,6 +11,7 @@ import {isHostAdmitted,isPeerAdmitted,} from './ingress-policy.ts';+import { isValidRelativeContentPath } from './relative-content-path.ts';import { classifyAssetDisposition } from './services/asset-classification.ts';export interface AssetServeFilter {@@ -31,6 +32,7 @@ interface AssetServeMiddlewareDeps {assetExtensions: ReadonlySet<string>;blocklistExtensions: ReadonlySet<string>;ingressPolicy: IngressPolicy;+ resolveTrackedFile?: (relativePath: string) => string | undefined;}function sirvLookupPath(url: string): string {@@ -49,6 +51,18 @@ function sirvLookupPath(url: string): string {}}+function urlLookingUpExactly(relativePath: string, requestUrl: string): string | null {+ let encoded: string;+ try {+ encoded = encodeURI(relativePath);+ } catch {+ return null;+ }+ const query = requestUrl.indexOf('?');+ const url = `/${encoded}${query === -1 ? '' : requestUrl.slice(query)}`;+ return sirvLookupPath(url) === `/${relativePath}` ? url : null;+}+function isServableContentFile(contentDir: string, url: string): boolean {const root = resolve(contentDir);const requested = normalize(join(`${root}${sep}`, sirvLookupPath(url)));@@ -81,18 +95,41 @@ export function createAssetServeMiddleware(assetExtensions,blocklistExtensions,ingressPolicy,+ resolveTrackedFile,} = deps;+ const extensionOf = (relativePath: string): string =>+ extname(relativePath).slice(1).toLowerCase();++ const servableTrackedFile = (+ requested: string,+ requestUrl: string,+ ): { url: string; ext: string } | null => {+ const tracked = resolveTrackedFile?.(requested);+ if (tracked === undefined || tracked === requested) return null;+ const ext = extensionOf(tracked);+ if (contentFilter.isPathIgnored(tracked) || !assetExtensions.has(ext)) return null;+ const url = urlLookingUpExactly(tracked, requestUrl);+ return url !== null && isServableContentFile(contentDir, url) ? { url, ext } : null;+ };+return (req, res, next) => {+ const requestUrl = req.url ?? '';let rel: string;try {- rel = decodeURIComponent(req.url?.split('?')[0]?.replace(/^\//, '') ?? '');+ rel = decodeURIComponent(requestUrl.split('?')[0]?.replace(/^\//, '') ?? '');} catch {return next();}- const ext = extname(rel).slice(1).toLowerCase();- const isDocExt = ext === 'md' || ext === 'mdx';- if (!rel || contentFilter.isPathIgnored(rel) || (!isDocExt && !assetExtensions.has(ext)))+ const sirvLooksUpRel =+ sirvLookupPath(requestUrl) === `/${rel}` && isValidRelativeContentPath(rel);+ const requestedExt = extensionOf(rel);+ const isDocExt = requestedExt === 'md' || requestedExt === 'mdx';+ if (+ !rel ||+ contentFilter.isPathIgnored(rel) ||+ (!isDocExt && !assetExtensions.has(requestedExt))+ )return next();const peerAddress = req.socket?.remoteAddress;if (peerAddress !== undefined && !isPeerAdmitted(peerAddress, ingressPolicy)) {@@ -108,6 +145,10 @@ export function createAssetServeMiddleware(});return;}+ const exactServable = sirvLooksUpRel && isServableContentFile(contentDir, requestUrl);+ const tracked =+ !sirvLooksUpRel || exactServable || isDocExt ? null : servableTrackedFile(rel, requestUrl);+ const ext = tracked?.ext ?? requestedExt;res.setHeader('X-Content-Type-Options', 'nosniff');const classified = classifyAssetDisposition(ext, inlineExtensions);if (!isDocExt) {@@ -121,6 +162,7 @@ export function createAssetServeMiddleware(}const notServed = () => {if (res.headersSent) return;+ req.url = requestUrl;const isHtml = SANDBOXED_HTML_EXTENSIONS.has(ext);if (!isHtml && (assetExtensions.has(ext) || blocklistExtensions.has(ext))) {res.statusCode = 404;@@ -135,10 +177,11 @@ export function createAssetServeMiddleware(}next();};- if (!isServableContentFile(contentDir, req.url ?? '')) {+ if (!exactServable && tracked === null) {notServed();return;}+ if (tracked !== null) req.url = tracked.url;contentSirv(req, res, notServed);};}diff --git a/packages/server/src/asset-walk.test.ts b/packages/server/src/asset-walk.test.tsindex 57ee41488..6f9e9d56c 100644--- a/packages/server/src/asset-walk.test.ts+++ b/packages/server/src/asset-walk.test.ts@@ -62,11 +62,12 @@ describe('seedBasenameIndex — initial walk (no filter)', () => {});});-describe('seedBasenameIndex — initial walk (with ContentFilter sibling-asset admission)', () => {- test('admits assets only in markdown-neighbored directories', async () => {+describe('seedBasenameIndex — initial walk (with ContentFilter)', () => {+ test('admits assets in directories with no markdown document', async () => {write('docs/meeting.md');write('docs/photo.png');write('no-md-here/orphan.png');+ write('no-md-here/deeper/nested.gif');const idx = createBasenameIndex();const contentFilter = createContentFilter({@@ -77,7 +78,8 @@ describe('seedBasenameIndex — initial walk (with ContentFilter sibling-asset aawait seedBasenameIndex({ contentDir, contentFilter, basenameIndex: idx });expect(idx.resolveEmbed('photo.png', 'docs/meeting.md')).toBe('docs/photo.png');- expect(idx.resolveEmbed('orphan.png', 'docs/meeting.md')).toBeNull();+ expect(idx.resolveEmbed('orphan.png', 'docs/meeting.md')).toBe('no-md-here/orphan.png');+ expect(idx.resolveEmbed('nested.gif', 'docs/meeting.md')).toBe('no-md-here/deeper/nested.gif');});test('respects .okignore exclusion patterns', async () => {diff --git a/packages/server/src/asset-walk.ts b/packages/server/src/asset-walk.tsindex 5c74c2e52..75406e580 100644--- a/packages/server/src/asset-walk.ts+++ b/packages/server/src/asset-walk.ts@@ -106,7 +106,7 @@ export async function seedBasenameIndex(opts: SeedOptions): Promise<void> {else if (realStat.isFile() &&isSupportedAssetFile(full, LINKABLE_ASSET_EXTENSIONS) &&- !opts.contentFilter?.isExcluded(rel)+ !opts.contentFilter?.isPathIgnored(rel)) {opts.basenameIndex.add(rel);}@@ -122,7 +122,7 @@ export async function seedBasenameIndex(opts: SeedOptions): Promise<void> {if (entryStat.isFile() &&isSupportedAssetFile(full, LINKABLE_ASSET_EXTENSIONS) &&- !opts.contentFilter?.isExcluded(rel)+ !opts.contentFilter?.isPathIgnored(rel)) {opts.basenameIndex.add(rel);}diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 0dd137b45..7aa38435e 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -9,7 +9,12 @@ import {} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { LOCAL_DIR, skillLiveDocName } from '@inkeep/open-knowledge-core';+import {+ createTargetNamespace,+ encodeHrefPath,+ LOCAL_DIR,+ skillLiveDocName,+} from '@inkeep/open-knowledge-core';import { beforeEach, describe, expect, test, vi } from 'vitest';import {BacklinkIndex,@@ -1738,6 +1743,16 @@ describe('extractMarkdownLinksFromMarkdown', () => {{ target: 'guide', anchor: null, snippet: 'Read the guide.', line: 4, column: 5 },]);});++ test('a .md link with a fragment or query keeps its document edge when a file oracle answers its path', () => {+ const files = new Set(['notes/Guide.md', 'notes/Help.mdx']);+ const md =+ 'See [g](./Guide.md#intro) and [h](./Help.mdx?v=1).\n\n[r][ref]\n\n[ref]: ./Guide.md#ref';+ const edges = extractMarkdownLinksFromMarkdown(md, 'notes/a', 0, {+ hasFile: (path) => files.has(path),+ });+ expect(edges.map((edge) => edge.target)).toEqual(['notes/Guide', 'notes/Help', 'notes/Guide']);+ });});describe('BacklinkIndex with markdown links', () => {@@ -2228,6 +2243,59 @@ describe('computeBrokenOutboundLinks', () => {]);});+ test('a Markdown link naming no document but an existing or ignored file is judged as that file', () => {+ const md = 'See [make](../Makefile), [notice](../ignored/NOTICE) and [gone](../Nope).';+ const excluded = new Set(['ignored/NOTICE']);+ expect(+ computeBrokenOutboundLinks(+ md,+ 'notes/a',+ new Set(),+ fileOracle(['Makefile']),+ () => false,+ (path) => excluded.has(path),+ ),+ ).toEqual<BrokenOutboundLink[]>([+ { href: '../ignored/NOTICE', resolvedTo: 'ignored/NOTICE', reason: 'excluded' },+ { href: '../Nope', resolvedTo: 'Nope', reason: 'no-such-doc' },+ ]);+ });++ test('a Markdown link to a missing document is never satisfied by a file check on its .md path', () => {+ const md = 'See [g](./Guide.md) and [h](./Help.mdx).';+ expect(+ computeBrokenOutboundLinks(+ md,+ 'notes/a',+ new Set(['notes/guide', 'notes/help']),+ fileOracle(['notes/Guide.md', 'notes/Help.mdx']),+ () => false,+ () => false,+ ),+ ).toEqual<BrokenOutboundLink[]>([+ { href: './Guide.md', resolvedTo: 'notes/Guide', reason: 'no-such-doc' },+ { href: './Help.mdx', resolvedTo: 'notes/Help', reason: 'no-such-doc' },+ ]);+ });++ test('a Markdown link to an existing but ignored .md file reports excluded', () => {+ const md = 'See [d](./drafts/plan.md) and [g](./Guide.md).';+ const excluded = new Set(['notes/drafts/plan.md']);+ expect(+ computeBrokenOutboundLinks(+ md,+ 'notes/a',+ new Set(['notes/guide']),+ fileOracle(['notes/Guide.md']),+ () => false,+ (path) => excluded.has(path),+ ),+ ).toEqual<BrokenOutboundLink[]>([+ { href: './drafts/plan.md', resolvedTo: 'notes/drafts/plan.md', reason: 'excluded' },+ { href: './Guide.md', resolvedTo: 'notes/Guide', reason: 'no-such-doc' },+ ]);+ });+test('external URLs and wiki image embeds are not file-validated even with an oracle', () => {const md = ['Web [pdf](https://example.com/x.pdf).',@@ -2471,3 +2539,247 @@ describe('computeBrokenOutboundLinks — JSX src refs', () => {expect(computeBrokenOutboundLinks(md, 'notes/index', new Set(), fileOracle([]))).toEqual([]);});});++describe('link target identity across canonically equivalent spellings', () => {+ const RENE_NFC = 'People/René';+ const RENE_NFD = 'People/René';+ const ZOE_NFC = 'People/Zoë';+ const ZOE_NFD = 'People/Zoë';++ function markdownLinkTo(docName: string): string {+ return `[link](/${encodeHrefPath(docName)}.md)`;+ }++ function createInMemoryIndex(): BacklinkIndex {+ return new BacklinkIndex({ projectDir: '/unused', contentDir: '/unused' });+ }++ test('an NFC markdown link to an NFD document is not dead and its backlink lands on the NFD node', () => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown(RENE_NFD, '# René\n');+ index.updateDocumentFromMarkdown('Probe', `See ${markdownLinkTo(RENE_NFC)}.\n`);++ expect(index.getDeadLinks(['Probe', RENE_NFD])).toEqual([]);+ expect(index.getBacklinks(RENE_NFD).map((entry) => entry.source)).toEqual(['Probe']);+ expect(+ index+ .getLinkGraph()+ .nodes.filter((node) => node.docName.normalize('NFC') === RENE_NFC)+ .map((node) => node.docName),+ ).toEqual([RENE_NFD]);+ });++ test('deleting the document makes the link dead again and re-adding it heals the link', () => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown(RENE_NFD, '# René\n');+ index.updateDocumentFromMarkdown('Probe', `See ${markdownLinkTo(RENE_NFC)}.\n`);+ expect(index.getDeadLinks(['Probe', RENE_NFD])).toEqual([]);++ index.deleteDocument(RENE_NFD);+ expect(index.getDeadLinks(['Probe']).map((entry) => entry.target)).toEqual([RENE_NFC]);+ expect(index.getBacklinks(RENE_NFD)).toEqual([]);++ index.updateDocumentFromMarkdown(RENE_NFD, '# René again\n');+ expect(index.getDeadLinks(['Probe', RENE_NFD])).toEqual([]);+ expect(index.getBacklinks(RENE_NFD).map((entry) => entry.source)).toEqual(['Probe']);+ });++ test('an NFD markdown link to an NFC document resolves the same way', () => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown(ZOE_NFC, '# Zoë\n');+ index.updateDocumentFromMarkdown('Probe', `See ${markdownLinkTo(ZOE_NFD)}.\n`);++ expect(index.getDeadLinks(['Probe', ZOE_NFC])).toEqual([]);+ expect(index.getBacklinks(ZOE_NFC).map((entry) => entry.source)).toEqual(['Probe']);+ });++ test('backlinks requested under an equivalent spelling answer for the stored document', () => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown(RENE_NFD, '# René\n');+ index.updateDocumentFromMarkdown('Probe', `See ${markdownLinkTo(RENE_NFD)}.\n`);++ expect(index.getBacklinks(RENE_NFC)).toEqual(index.getBacklinks(RENE_NFD));+ expect(index.getBacklinks(RENE_NFC).map((entry) => entry.source)).toEqual(['Probe']);+ expect(index.getBacklinkCount(RENE_NFC)).toBe(1);+ expect(index.getBacklinks('People/Ghost')).toEqual([]);+ });++ test('a document that appears after the link was indexed heals the link', () => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown('Probe', `See ${markdownLinkTo(RENE_NFC)}.\n`);+ expect(index.getDeadLinks(['Probe']).map((entry) => entry.target)).toEqual([RENE_NFC]);++ index.updateDocumentFromMarkdown(RENE_NFD, '# René\n');+ expect(index.getDeadLinks(['Probe', RENE_NFD])).toEqual([]);+ expect(index.getBacklinks(RENE_NFD).map((entry) => entry.source)).toEqual(['Probe']);+ });++ test.each([+ [+ 'an NFC wiki link',+ 'an NFD folder index',+ 'Café'.normalize('NFC'),+ `${'Café'.normalize('NFD')}/index`,+ ],+ [+ 'an NFD wiki link',+ 'an NFC folder index',+ 'Café'.normalize('NFD'),+ `${'Café'.normalize('NFC')}/index`,+ ],+ [+ 'an NFC wiki link',+ 'an NFD folder note',+ 'Notes/Café'.normalize('NFC'),+ `${'Notes/Café'.normalize('NFD')}/${'Café'.normalize('NFD')}`,+ ],+ [+ 'an NFC wiki link',+ 'a folder note whose leaf alone is NFD',+ 'Notes/Café'.normalize('NFC'),+ `${'Notes/Café'.normalize('NFC')}/${'Café'.normalize('NFD')}`,+ ],+ ])(+ '%s follows %s added and deleted after the link, without a rebuild',+ (_link, _doc, target, docName) => {+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown('Probe', `See [[${target}]].\n`);+ expect(index.getDeadLinks(['Probe']).map((entry) => entry.target)).toEqual([target]);++ index.updateDocumentFromMarkdown(docName, '# Café\n');+ expect(index.getDeadLinks(['Probe', docName])).toEqual([]);+ expect(index.getBacklinks(docName).map((entry) => entry.source)).toEqual(['Probe']);++ index.deleteDocument(docName);+ expect(index.getDeadLinks(['Probe']).map((entry) => entry.target)).toEqual([target]);+ expect(index.getBacklinks(docName)).toEqual([]);+ },+ );++ test('deleting an NFD folder index that an NFC wiki link already resolved to points the link back at its target', () => {+ const target = 'Café'.normalize('NFC');+ const docName = `${'Café'.normalize('NFD')}/index`;+ const index = createInMemoryIndex();+ index.updateDocumentFromMarkdown(docName, '# Café\n');+ index.updateDocumentFromMarkdown('Probe', `See [[${target}]].\n`);+ expect(index.getBacklinks(docName).map((entry) => entry.source)).toEqual(['Probe']);++ index.deleteDocument(docName);+ expect(index.getDeadLinks(['Probe']).map((entry) => entry.target)).toEqual([target]);+ expect(index.getLinkGraph().links.map((link) => `${link.source} -> ${link.target}`)).toEqual([+ `Probe -> ${target}`,+ ]);+ });++ const DOC_ALPHABET = [+ RENE_NFC,+ RENE_NFD,+ 'People/rené',+ ZOE_NFC,+ ZOE_NFD,+ 'Notes/README',+ 'Notes/readme',+ 'a/b',+ 'a-b',+ 'Café'.normalize('NFC'),+ `${'Café'.normalize('NFD')}/index`,+ `${'Café'.normalize('NFC')}/${'Café'.normalize('NFD')}`,+ ];++ function seededRandom(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+ }++ function pick<T>(random: () => number, items: readonly T[]): T {+ return items[Math.floor(random() * items.length)] as T;+ }++ function randomMarkdown(random: () => number): string {+ const lines: string[] = ['# Doc', ''];+ const linkCount = Math.floor(random() * 4);+ for (let i = 0; i < linkCount; i++) {+ const target = pick(random, DOC_ALPHABET);+ lines.push(random() < 0.5 ? markdownLinkTo(target) : `[[${target}]]`);+ }+ return `${lines.join('\n')}\n`;+ }++ function graphSnapshot(index: BacklinkIndex, liveDocs: ReadonlyMap<string, string>): string {+ const admitted = [...liveDocs.keys()].sort();+ const graph = index.getLinkGraph();+ return JSON.stringify({+ deadLinks: index+ .getDeadLinks(admitted)+ .map((entry) => ({+ target: entry.target,+ sources: entry.sources+ .map((source) => `${source.source}\0${source.sourceForm}\0${source.line}`)+ .sort(),+ }))+ .sort((a, b) => (a.target < b.target ? -1 : a.target > b.target ? 1 : 0)),+ nodes: graph.nodes.map((node) => node.id).sort(),+ links: graph.links.map((link) => `${link.source} -> ${link.target}`).sort(),+ backlinks: admitted.map((docName) => [+ docName,+ index+ .getBacklinks(docName)+ .map((entry) => entry.source)+ .sort(),+ ]),+ });+ }++ test('an incrementally maintained graph equals a fresh rebuild over the same documents', () => {+ for (let seed = 1; seed <= 40; seed++) {+ const random = seededRandom(seed);+ const incremental = createInMemoryIndex();+ const liveDocs = new Map<string, string>();+ for (let step = 0; step < 12; step++) {+ const docName = pick(random, DOC_ALPHABET);+ if (liveDocs.has(docName) && random() < 0.4) {+ liveDocs.delete(docName);+ incremental.deleteDocument(docName);+ } else {+ const markdown = randomMarkdown(random);+ liveDocs.set(docName, markdown);+ incremental.updateDocumentFromMarkdown(docName, markdown);+ }+ const fresh = createInMemoryIndex();+ for (const name of [...liveDocs.keys()].sort()) {+ fresh.updateDocumentFromMarkdown(name, liveDocs.get(name) as string);+ }+ expect(graphSnapshot(incremental, liveDocs), `seed ${seed} step ${step}`).toBe(+ graphSnapshot(fresh, liveDocs),+ );+ }+ }+ });+});++describe('computeBrokenOutboundLinks across canonically equivalent spellings', () => {+ const RENE_NFC = 'People/René';+ const RENE_NFD = 'People/René';++ test('a markdown href in either normalization form names the admitted document', () => {+ const toNfc = `[x](/${encodeHrefPath(RENE_NFC)}.md)\n`;+ const toNfd = `[x](/${encodeHrefPath(RENE_NFD)}.md)\n`;+ expect(computeBrokenOutboundLinks(toNfc, 'Probe', new Set([RENE_NFD]))).toEqual([]);+ expect(computeBrokenOutboundLinks(toNfd, 'Probe', new Set([RENE_NFC]))).toEqual([]);+ expect(+ computeBrokenOutboundLinks(toNfc, 'Probe', createTargetNamespace('document', [RENE_NFD])),+ ).toEqual([]);+ expect(computeBrokenOutboundLinks(`[[${RENE_NFC}]]\n`, 'Probe', new Set([RENE_NFD]))).toEqual(+ [],+ );+ expect(+ computeBrokenOutboundLinks('[x](/People/Nope.md)\n', 'Probe', new Set([RENE_NFD])),+ ).toEqual([{ href: '/People/Nope.md', resolvedTo: 'People/Nope', reason: 'no-such-doc' }]);+ });+});diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex ffe5b74bd..6e8f55ed1 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -2,22 +2,32 @@ import { type Dirent, existsSync, mkdirSync } from 'node:fs';import { readdir, readFile, stat, writeFile } from 'node:fs/promises';import { dirname, join, relative, resolve } from 'node:path';import {+ addDocumentFolders,+ asTargetNamespace,type BrokenLinkReason,classifyMarkdownHref,classifyWikiLinkTarget,+ createTargetNamespace,+ type DependencySlug,+ dependencySlug,extractSkillRefs,getWikiLinkText,+ type IdentityKey,+ identityKey,isExcalidrawDocFile,isExternalHref,isOrphanMode,type JsxSrcRefTagSpec,+ leafKey,MANAGED_ARTIFACT_PREFIX_SKILL,+ type MutableTargetNamespace,ORPHAN_MODES,type OrphanMode,parseGlobalSkillBundleDoc,parseProjectSkillBundleDoc,resolveAssetProjectPath,resolveInternalHref,+ resolveName,resolveSkillBundleWikiTarget,resolveWikiLinkTarget,resolveWikiLinkTargetDocName,@@ -29,7 +39,7 @@ import {import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';import { getLocalDir } from './config/paths.ts';import type { ContentFilter } from './content-filter.ts';-import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';+import { isSupportedDocFile, linkNamesDocumentFile, stripDocExtension } from './doc-extensions.ts';import { instrumentIndexRebuild } from './index-telemetry.ts';import {createJsxSrcAttrRe,@@ -62,7 +72,7 @@ function namesExistingFile(oracle: GraphFileOracle | undefined,): boolean {if (!oracle) return false;- if (isSupportedDocFile(href)) return false;+ if (linkNamesDocumentFile(href, sourceDocName)) return false;const filePath = resolveAssetProjectPath(href, sourceDocName, { literal: false });return filePath !== null && oracle.hasFile(filePath);}@@ -207,18 +217,46 @@ interface ResolvedGraphState {forward: Map<string, Set<string>>;backward: Map<string, Map<string, BackwardLinkMeta>>;sortedBacklinks: Map<string, BacklinkEntry[]>;- wikiSourcesByPathSlug: Map<string, Set<string>>;- wikiSourcesByBasenameSlug: Map<string, Set<string>>;- wikiSourcesByFolder: Map<string, Set<string>>;- wikiKeysBySource: Map<- string,- { paths: Set<string>; basenames: Set<string>; folders: Set<string> }- >;+ sourcesByPathSlug: Map<DependencySlug, Set<string>>;+ wikiSourcesByBasenameSlug: Map<DependencySlug, Set<string>>;+ wikiSourcesByFolder: Map<IdentityKey<'folder'>, Set<string>>;+ keysBySource: Map<string, SourceDependencyKeys>;+}++interface SourceDependencyKeys {+ paths: Set<DependencySlug>;+ basenames: Set<DependencySlug>;+ folders: Set<IdentityKey<'folder'>>;+}++function registerSourceKeys<K extends string>(+ index: Map<K, Set<string>>,+ keys: ReadonlySet<K>,+ source: string,+): void {+ for (const key of keys) {+ const sources = index.get(key) ?? new Set<string>();+ sources.add(source);+ index.set(key, sources);+ }+}++function unregisterSourceKeys<K extends string>(+ index: Map<K, Set<string>>,+ keys: ReadonlySet<K>,+ source: string,+): void {+ for (const key of keys) {+ const sources = index.get(key);+ sources?.delete(source);+ if (sources?.size === 0) index.delete(key);+ }}interface CachedDocumentLookup {epoch: number;lookup: WikiLinkLookupIndex;+ pages: MutableTargetNamespace<'document'>;slugBuckets: Map<string, Set<string>>;basenameBuckets: Map<string, Set<string>>;}@@ -881,8 +919,11 @@ export function computeBrokenOutboundLinks(admittedDocs: Iterable<string>,fileExists?: (contentRootRelativePath: string) => boolean,folderExists?: (folderPath: string) => boolean,+ fileExcluded?: (contentRootRelativePath: string) => boolean,): BrokenOutboundLink[] {- const admitted = admittedDocs instanceof Set ? admittedDocs : new Set(admittedDocs);+ const documents = asTargetNamespace('document', admittedDocs);+ const missingFileReason = (filePath: string): BrokenLinkReason =>+ fileExcluded?.(filePath) === true ? 'excluded' : 'no-such-file';let body: string;try {@@ -923,7 +964,20 @@ export function computeBrokenOutboundLinks(return;}if (classified.kind === 'doc') {- if (!admitted.has(classified.docName) && folderExists?.(classified.docName) !== true) {+ if (documents.resolve(classified.docName) !== undefined) return;+ const filePath = resolveAssetProjectPath(trimmed, sourceDocName, { literal: false });+ if (+ filePath !== null &&+ !linkNamesDocumentFile(trimmed, sourceDocName) &&+ fileExists?.(filePath) === true+ ) {+ return;+ }+ if (filePath !== null && fileExcluded?.(filePath) === true) {+ record(trimmed, filePath, 'excluded');+ return;+ }+ if (folderExists?.(classified.docName) !== true) {record(trimmed, classified.docName, 'no-such-doc');}return;@@ -938,7 +992,7 @@ export function computeBrokenOutboundLinks(return;}if (!fileExists(filePath)) {- record(trimmed, filePath, 'no-such-file');+ record(trimmed, filePath, missingFileReason(filePath));}return;}@@ -957,10 +1011,10 @@ export function computeBrokenOutboundLinks(}if (isExcalidrawDocFile(resolved)) {if (!fileExists) return;- if (!fileExists(resolved)) record(value, resolved, 'no-such-file', 'jsx');+ if (!fileExists(resolved)) record(value, resolved, missingFileReason(resolved), 'jsx');return;}- if (!admitted.has(resolved) && folderExists?.(resolved) !== true) {+ if (documents.resolve(resolved) === undefined && folderExists?.(resolved) !== true) {record(value, resolved, 'no-such-doc', 'jsx');}};@@ -968,7 +1022,7 @@ export function computeBrokenOutboundLinks(let wikiLookup: WikiLinkLookupIndex | undefined;const recordWikiLink = (target: string, anchor: string | null): void => {- wikiLookup ??= buildProjectWikiLinkLookup(admitted);+ wikiLookup ??= buildProjectWikiLinkLookup(documents);const resolved = resolveWikiLinkTarget(target, anchor, wikiLookup);if (resolved?.kind !== 'doc') return;if (@@ -1176,18 +1230,6 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {};}-function deriveFolderPathsFromDocNames(docNames: Iterable<string>): Set<string> {- const folderPaths = new Set<string>();- for (const docName of docNames) {- let slash = docName.indexOf('/');- while (slash !== -1) {- folderPaths.add(docName.slice(0, slash));- slash = docName.indexOf('/', slash + 1);- }- }- return folderPaths;-}-export class BacklinkIndex {private readonly projectDir: string;private readonly contentDir: string;@@ -1500,7 +1542,8 @@ export class BacklinkIndex {this.updateDocumentFromMarkdown(newDocName, markdown, branch);}- getBacklinks(target: string, branch = this.activeBranch): BacklinkEntry[] {+ getBacklinks(requested: string, branch = this.activeBranch): BacklinkEntry[] {+ const target = this.canonicalDocName(requested, branch);const resolved = this.resolvedState(branch);const sources = resolved.backward.get(target);const structural = this.bundleNeighbors(target, branch);@@ -1520,7 +1563,8 @@ export class BacklinkIndex {return [...entries.values()].sort((a, b) => a.source.localeCompare(b.source));}- getBacklinkCount(target: string, branch = this.activeBranch): number {+ getBacklinkCount(requested: string, branch = this.activeBranch): number {+ const target = this.canonicalDocName(requested, branch);const authored = this.resolvedBackward(branch).get(target);const structural = this.bundleNeighbors(target, branch);if (structural.size === 0) return authored?.size ?? 0;@@ -1620,18 +1664,18 @@ export class BacklinkIndex {knownFolderPaths?: Iterable<string>,): DeadLinkEntry[] {const state = this.resolvedGraph(branch);- const admittedDocSet = new Set(admittedDocs);+ const documents = createTargetNamespace('document', admittedDocs);+ for (const indexed of state.forward.keys()) documents.add(indexed);const sourceDocSet = sourceDocNames?.length ? new Set(sourceDocNames) : null;- const folderPathSet = deriveFolderPathsFromDocNames([- ...admittedDocSet,- ...state.forward.keys(),- ]);- for (const folderPath of knownFolderPaths ?? []) folderPathSet.add(folderPath);+ const folders = addDocumentFolders(+ createTargetNamespace('folder', knownFolderPaths ?? []),+ documents,+ );return [...state.backward.entries()].filter(([target, sources]) => {- if (admittedDocSet.has(target) || state.forward.has(target)) return false;- if (folderPathSet.has(target.replace(/\/+$/, ''))) return false;+ if (documents.resolve(target) !== undefined) return false;+ if (folders.resolve(target.replace(/\/+$/, '')) !== undefined) return false;if (!sourceDocSet) return sources.size > 0;for (const source of sources.keys()) {if (sourceDocSet.has(source)) return true;@@ -1671,6 +1715,10 @@ export class BacklinkIndex {);}+ private canonicalDocName(requested: string, branch: string): string {+ return resolveName(this.documentLookup(branch).pages, requested) ?? requested;+ }+private documentLookup(branch = this.activeBranch): WikiLinkLookupIndex {const state = this.getState(branch);const cached = this.documentLookups.get(state);@@ -1693,14 +1741,16 @@ export class BacklinkIndex {basenameBuckets.set(basenameSlug, bucket);}}+ const pages = createTargetNamespace('document', lookup.pages);const mutableLookup: WikiLinkLookupIndex = {- pages: new Set(lookup.pages),+ pages,pagesBySlug: new Map(lookup.pagesBySlug),pagesByBasename: new Map(lookup.pagesByBasename),};this.documentLookups.set(state, {epoch: state.inventoryEpoch,lookup: mutableLookup,+ pages,slugBuckets,basenameBuckets,});@@ -1712,7 +1762,7 @@ export class BacklinkIndex {if (!cached || cached.epoch !== state.inventoryEpoch - 1) return;cached.epoch = state.inventoryEpoch;if (!added && this.fixedDocumentNames.has(docName)) return;- const pages = cached.lookup.pages as Set<string>;+ const pages = cached.pages;if (added ? pages.has(docName) : !pages.has(docName)) return;if (added) pages.add(docName);else pages.delete(docName);@@ -1745,18 +1795,20 @@ export class BacklinkIndex {const resolved = this.resolvedGraphs.get(state);if (!resolved || resolved.inventoryEpoch !== state.inventoryEpoch - 1) return;resolved.inventoryEpoch = state.inventoryEpoch;- const pathSlug = toWikiLinkSlug(docName) || docName;- const basenameSlug = toWikiLinkSlug(docName.slice(docName.lastIndexOf('/') + 1));+ const pathSlug = dependencySlug(docName);+ const basenameSlug = dependencySlug(docName.slice(docName.lastIndexOf('/') + 1));const affected = new Set<string>([- ...(resolved.wikiSourcesByPathSlug.get(pathSlug) ?? []),+ ...(resolved.sourcesByPathSlug.get(pathSlug) ?? []),...(resolved.wikiSourcesByBasenameSlug.get(basenameSlug) ?? []),]);const slash = docName.lastIndexOf('/');if (slash !== -1) {const parent = docName.slice(0, slash);- const leaf = docName.slice(slash + 1);- if (leaf === 'index' || leaf === parent.slice(parent.lastIndexOf('/') + 1)) {- for (const source of resolved.wikiSourcesByFolder.get(parent) ?? []) affected.add(source);+ const leaf = leafKey('document', docName.slice(slash + 1));+ const parentLeaf = leafKey('document', parent.slice(parent.lastIndexOf('/') + 1));+ if (leaf === leafKey('document', 'index') || leaf === parentLeaf) {+ for (const source of resolved.wikiSourcesByFolder.get(identityKey('folder', parent)) ?? [])+ affected.add(source);}}affected.add(docName);@@ -1783,19 +1835,11 @@ export class BacklinkIndex {source: string,lookup: WikiLinkLookupIndex,): Set<string> {- const priorKeys = resolved.wikiKeysBySource.get(source);+ const priorKeys = resolved.keysBySource.get(source);if (priorKeys) {- for (const [keys, index] of [- [priorKeys.paths, resolved.wikiSourcesByPathSlug],- [priorKeys.basenames, resolved.wikiSourcesByBasenameSlug],- [priorKeys.folders, resolved.wikiSourcesByFolder],- ] as const) {- for (const key of keys) {- const sources = index.get(key);- sources?.delete(source);- if (sources?.size === 0) index.delete(key);- }- }+ unregisterSourceKeys(resolved.sourcesByPathSlug, priorKeys.paths, source);+ unregisterSourceKeys(resolved.wikiSourcesByBasenameSlug, priorKeys.basenames, source);+ unregisterSourceKeys(resolved.wikiSourcesByFolder, priorKeys.folders, source);}const changedTargets = new Set(resolved.forward.get(source) ?? []);for (const target of changedTargets) {@@ -1806,27 +1850,30 @@ export class BacklinkIndex {const targets = new Set<string>();if (state.forward.has(source)) resolved.forward.set(source, targets);else resolved.forward.delete(source);- const wikiKeys = {- paths: new Set<string>(),- basenames: new Set<string>(),- folders: new Set<string>(),+ const keys: SourceDependencyKeys = {+ paths: new Set(),+ basenames: new Set(),+ folders: new Set(),};const sourceLinks = state.forward.has(source) ? requireSourceLinks(state, source) : [];for (const meta of sourceLinks) {const rawTarget = meta.target;if (!rawTarget) continue;- let target = rawTarget;+ let target: string;if (meta.sourceForm === 'wiki' || meta.sourceForm === undefined) {const trimmed = rawTarget.trim();for (const form of [trimmed, trimmed.replace(/\.(md|mdx)$/i, '')]) {- const slug = toWikiLinkSlug(form) || form;- wikiKeys.paths.add(slug);- if (!form.includes('/')) wikiKeys.basenames.add(slug);- wikiKeys.folders.add(form);+ const slug = dependencySlug(form);+ keys.paths.add(slug);+ if (!form.includes('/')) keys.basenames.add(slug);+ keys.folders.add(identityKey('folder', form));}const canonical = resolveWikiLinkTargetDocName(rawTarget, lookup);if (meta.rawWikiTarget === true && canonical === undefined) continue;target = canonical ?? rawTarget;+ } else {+ keys.paths.add(dependencySlug(rawTarget));+ target = resolveName(lookup.pages, rawTarget) ?? rawTarget;}targets.add(target);changedTargets.add(target);@@ -1838,20 +1885,12 @@ export class BacklinkIndex {sources.set(source, mergeLinkMeta(sources.get(source), meta));}if (state.forward.has(source)) {- resolved.wikiKeysBySource.set(source, wikiKeys);- for (const [keys, index] of [- [wikiKeys.paths, resolved.wikiSourcesByPathSlug],- [wikiKeys.basenames, resolved.wikiSourcesByBasenameSlug],- [wikiKeys.folders, resolved.wikiSourcesByFolder],- ] as const) {- for (const key of keys) {- const sources = index.get(key) ?? new Set<string>();- sources.add(source);- index.set(key, sources);- }- }+ resolved.keysBySource.set(source, keys);+ registerSourceKeys(resolved.sourcesByPathSlug, keys.paths, source);+ registerSourceKeys(resolved.wikiSourcesByBasenameSlug, keys.basenames, source);+ registerSourceKeys(resolved.wikiSourcesByFolder, keys.folders, source);} else {- resolved.wikiKeysBySource.delete(source);+ resolved.keysBySource.delete(source);}return changedTargets;}@@ -1920,10 +1959,10 @@ export class BacklinkIndex {forward: new Map(),backward: new Map(),sortedBacklinks: new Map(),- wikiSourcesByPathSlug: new Map(),+ sourcesByPathSlug: new Map(),wikiSourcesByBasenameSlug: new Map(),wikiSourcesByFolder: new Map(),- wikiKeysBySource: new Map(),+ keysBySource: new Map(),};const lookup = this.documentLookup(branch);for (const source of state.forward.keys())diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 40f219a76..2727a5d10 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -455,6 +455,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {assetExtensions: ASSET_EXTENSIONS,blocklistExtensions: EXECUTABLE_BLOCKLIST_EXTENSIONS,ingressPolicy,+ resolveTrackedFile: serverInstance.resolveTrackedFile,}): undefined;diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.tsindex 8cfcf5c61..f88201aaa 100644--- a/packages/server/src/content-filter.ts+++ b/packages/server/src/content-filter.ts@@ -632,6 +632,7 @@ export interface ContentFilter {isExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean;isDirExcluded(relativePath: string, opts?: ContentFilterReadOpts): boolean;isPathIgnored(relativePath: string, opts?: ContentFilterPathReadOpts): boolean;+ isExcludedByIgnoreFiles(relativePath: string): boolean;getWatcherIgnoreGlobs(): string[];incrementMdDir(dir: string): void;decrementMdDir(dir: string): void;@@ -924,6 +925,12 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {return isRejectedByConfigurableRules(relativePath);},+ isExcludedByIgnoreFiles(relativePath: string): boolean {+ if (relativePath.split('/').some(isBuiltinSkipDirName)) return false;+ if (contentOutsideProject) return false;+ return isIgnored(relativePath);+ },+getWatcherIgnoreGlobs(): string[] {return watcherIgnoreGlobs;},@@ -1537,6 +1544,12 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Promreturn isRejectedByConfigurableRules(relativePath);},+ isExcludedByIgnoreFiles(relativePath: string): boolean {+ if (relativePath.split('/').some(isBuiltinSkipDirName)) return false;+ if (contentOutsideProject) return false;+ return isIgnored(relativePath);+ },+getWatcherIgnoreGlobs(): string[] {return watcherIgnoreGlobs;},diff --git a/packages/server/src/content/generate-index-literal-metadata.test.ts b/packages/server/src/content/generate-index-literal-metadata.test.tsindex d14ca61ce..15b2787ac 100644--- a/packages/server/src/content/generate-index-literal-metadata.test.ts+++ b/packages/server/src/content/generate-index-literal-metadata.test.ts@@ -390,11 +390,11 @@ const LITERAL_SURFACE_CASES: LiteralSurfaceCase[] = [assert(guides);return {markdown: guides.markdown,- hrefs: [`./${encodeURIComponent(literal)}/index.md`],+ hrefs: [`./${encodeURIComponent(literal.normalize('NFC'))}/index.md`],};},expected: (literal, pathLiteral) =>- `# Index\n\n## Subdirectories\n\n* [${literal}](./${encodeURIComponent(pathLiteral)}/index.md)\n`,+ `# Index\n\n## Subdirectories\n\n* [${literal}](./${encodeURIComponent(pathLiteral.normalize('NFC'))}/index.md)\n`,},];diff --git a/packages/server/src/content/generate-index.test.ts b/packages/server/src/content/generate-index.test.tsindex cf377f393..80ec31ae5 100644--- a/packages/server/src/content/generate-index.test.ts+++ b/packages/server/src/content/generate-index.test.ts@@ -504,6 +504,26 @@ describe('buildIndexMarkdown', () => {expect(resolved.toSorted()).toEqual(names.map((name) => `blogs/drafts/${name}`).toSorted());});+ test('a decomposed entry links in composed form unless a composed sibling owns that spelling', () => {+ const nfd = 'people/Rene\u0301.md';+ const nfc = 'people/Ren\u00e9.md';+ const options = { warningScope: false as const, isRoot: false, directory: 'people' };++ const alone = buildIndexMarkdown([entry({ path: nfd, title: 'Ren\u00e9' })], options);+ expect(alone).toContain('](./Ren%C3%A9.md)');+ expect(resolveInternalHref('./Ren%C3%A9.md', 'people/index')?.docName).toBe('people/Ren\u00e9');++ const twins = buildIndexMarkdown(+ [entry({ path: nfd, title: 'Decomposed' }), entry({ path: nfc, title: 'Composed' })],+ options,+ );+ const hrefs = [...twins.matchAll(/\]\(([^)]+)\)/g)].map((match) => match[1] ?? '');+ expect(hrefs.toSorted()).toEqual(['./Ren%C3%A9.md', './Rene%CC%81.md']);+ expect(+ hrefs.map((href) => resolveInternalHref(href, 'people/index')?.docName).toSorted(),+ ).toEqual(['people/Ren\u00e9', 'people/Rene\u0301'].toSorted());+ });+test('no heading the generator owns collides with a section derived from a document type', () => {const reserved = generatorOwnedHeadings();expect(reserved.toSorted()).toEqual([...GENERATOR_OWNED_HEADINGS].toSorted());diff --git a/packages/server/src/content/generate-index.ts b/packages/server/src/content/generate-index.tsindex dcb4dcbba..945999b51 100644--- a/packages/server/src/content/generate-index.ts+++ b/packages/server/src/content/generate-index.ts@@ -1,4 +1,9 @@-import { encodeHrefPath, isMutatingParserReservation } from '@inkeep/open-knowledge-core';+import {+ createTargetNamespace,+ encodeHrefPath,+ isMutatingParserReservation,+ type TargetNamespace,+} from '@inkeep/open-knowledge-core';import { getLogger } from '../logger.ts';export interface IndexEntry {@@ -248,16 +253,28 @@ function toHref(relativePath: string): string {return `./${encodeHrefPath(normalized)}`;}-function renderLink(link: RenderableLink, directory: string): string {- const anchor = `* [${link.title.source}](${toHref(relativeTo(directory, link.path))})`;+type SiblingPaths = TargetNamespace<'document'>;++function hrefSpelling(relativePath: string, siblings: SiblingPaths): string {+ const composed = relativePath.normalize('NFC');+ return siblings.resolve(composed) === relativePath ? composed : relativePath;+}++function renderLink(link: RenderableLink, directory: string, siblings: SiblingPaths): string {+ const relativePath = hrefSpelling(relativeTo(directory, link.path), siblings);+ const anchor = `* [${link.title.source}](${toHref(relativePath)})`;return link.description?.source ? `${anchor} - ${link.description.source}` : anchor;}-function renderBody(links: readonly RenderableLink[], directory: string): string {+function renderBody(+ links: readonly RenderableLink[],+ directory: string,+ siblings: SiblingPaths,+): string {return links.slice().sort(compareLinks)- .map((link) => renderLink(link, directory))+ .map((link) => renderLink(link, directory, siblings)).join('\n');}@@ -277,6 +294,7 @@ export function buildIndexMarkdown(const titleKey = literalMarkdownText(INDEX_TITLE, { kind: 'generator-owned' }).identity;const grouped = new Map<string, Bucket>();+ const siblings = createTargetNamespace('document');const bucketFor = (heading: LiteralMarkdownText): RenderableLink[] => {const key = heading.identity;@@ -300,20 +318,28 @@ export function buildIndexMarkdown(return existing.links;};+ const sibling = (link: RenderableLink): RenderableLink => {+ siblings.add(relativeTo(directory, link.path));+ return link;+ };+for (const entry of entries) {- bucketFor(sectionOf(entry, warningScope)).push(renderableLink(entry, warningScope));+ bucketFor(sectionOf(entry, warningScope)).push(sibling(renderableLink(entry, warningScope)));}if (subdirectories.length > 0) {bucketFor(literalMarkdownText(SUBDIRECTORY_SECTION, { kind: 'generator-owned' })).push(- ...subdirectories.map((entry) => renderableLink(entry, warningScope)),+ ...subdirectories.map((entry) => sibling(renderableLink(entry, warningScope))),);}const blocks = [...grouped].filter(([key]) => key !== titleKey).sort(([, left], [, right]) => compareSections(left.heading.visible, right.heading.visible))- .map(([, { heading, links }]) => `## ${heading.source}\n\n${renderBody(links, directory)}`);+ .map(+ ([, { heading, links }]) =>+ `## ${heading.source}\n\n${renderBody(links, directory, siblings)}`,+ );const header = options.isRoot ? `---\nokf_version: "${GENERATED_OKF_VERSION}"\n---\n\n` : '';@@ -321,7 +347,7 @@ export function buildIndexMarkdown(const title =titleLinks.length === 0? `# ${INDEX_TITLE}`- : `# ${INDEX_TITLE}\n\n${renderBody(titleLinks, directory)}`;+ : `# ${INDEX_TITLE}\n\n${renderBody(titleLinks, directory, siblings)}`;return `${header}${[title, ...blocks].join('\n\n')}\n`;}diff --git a/packages/server/src/derived-document-index.test.ts b/packages/server/src/derived-document-index.test.tsindex 57de22e2e..0499be871 100644--- a/packages/server/src/derived-document-index.test.ts+++ b/packages/server/src/derived-document-index.test.ts@@ -781,6 +781,23 @@ describe('DerivedDocumentIndex', () => {expect(await rig.index.getBacklinks('assets/NOTICE')).toEqual([]);});+ test('the graph file oracle recognises a file under an equivalent spelling', async () => {+ const stored = 'assets/NOTICE\u0301';+ const linked = 'assets/NOTIC\u00c9';+ let inventory: WatcherLocalTargetInventory | null = null;+ const rig = createRig(() => inventory);+ writeDoc(rig, 'src.md', `See [notice](${linked}).\n`);+ writeDoc(rig, stored, 'plain text\n');++ const startup = rig.index.beginStartup('main');+ await startup.backlinksReady;+ inventory = { documentTargets: ['src'], fileTargets: [stored] };+ await rig.index.settleStartupAfterWatcherSeed();++ expect(await rig.index.getBacklinks(linked)).toEqual([]);+ expect(await rig.index.getDeadLinks(['src'])).toEqual([]);+ });+test('startup settlement re-derives a warm graph cache against the watcher inventory', async () => {let inventory: WatcherLocalTargetInventory | null = null;const rig = createRig(() => inventory);diff --git a/packages/server/src/derived-document-index.ts b/packages/server/src/derived-document-index.tsindex 5a310746d..a960cc916 100644--- a/packages/server/src/derived-document-index.ts+++ b/packages/server/src/derived-document-index.ts@@ -1,5 +1,9 @@import { readFile } from 'node:fs/promises';-import type { DerivedViewChannel } from '@inkeep/open-knowledge-core';+import {+ createTargetNamespace,+ type DerivedViewChannel,+ type TargetNamespace,+} from '@inkeep/open-knowledge-core';import {type BacklinkEntry,BacklinkIndex,@@ -195,7 +199,7 @@ export class DerivedDocumentIndexprivate readonly localTargetFileExistenceTimer: ReturnType<typeof setInterval>;private localTargetRebuildRetryAttempt = 0;private graphFileTargetsSource: readonly string[] | null = null;- private graphFileTargets: Set<string> | null = null;+ private graphFileTargets: TargetNamespace<'file'> | null = null;private startupBranch: string | null = null;private graphBuiltWithoutFileOracle = false;private saveTagsOnNextDebounce = false;@@ -844,10 +848,10 @@ export class DerivedDocumentIndex}if (this.graphFileTargetsSource !== inventory.fileTargets) {this.graphFileTargetsSource = inventory.fileTargets;- this.graphFileTargets = new Set(inventory.fileTargets);+ this.graphFileTargets = createTargetNamespace('file', inventory.fileTargets);}const files = this.graphFileTargets;- return files ? { hasFile: (path) => files.has(path) } : undefined;+ return files ? { hasFile: (path) => files.resolve(path) !== undefined } : undefined;}private async reconcileGraphWithFileInventory(branch: string): Promise<void> {diff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.tsindex 2d37186d4..cbbfa0ac1 100644--- a/packages/server/src/doc-extensions.test.ts+++ b/packages/server/src/doc-extensions.test.ts@@ -6,6 +6,7 @@ import {forgetDocExtension,getDocExtension,isSupportedDocFile,+ linkNamesDocumentFile,registerDocExtension,SUPPORTED_DOC_EXTENSIONS,stripDocExtension,@@ -41,6 +42,16 @@ describe('isSupportedDocFile', () => {});});+describe('linkNamesDocumentFile', () => {+ test('judges the resolved project path, so a fragment or query does not hide the extension', () => {+ expect(linkNamesDocumentFile('./Guide.md', 'notes/a')).toBe(true);+ expect(linkNamesDocumentFile('./Guide.md#intro', 'notes/a')).toBe(true);+ expect(linkNamesDocumentFile('./Help.mdx?v=1', 'notes/a')).toBe(true);+ expect(linkNamesDocumentFile('../Makefile', 'notes/a')).toBe(false);+ expect(linkNamesDocumentFile('./guide', 'notes/a')).toBe(false);+ });+});+describe('stripDocExtension', () => {test('strips .md', () => {expect(stripDocExtension('foo.md')).toBe('foo');diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex 245519cb0..56a79c244 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -5,6 +5,7 @@ import {isEditableTextDocFile,isExcalidrawDocFile,isMermaidDocFile,+ resolveAssetProjectPath,SUPPORTED_DOC_EXTENSIONS,} from '@inkeep/open-knowledge-core';@@ -17,6 +18,11 @@ export function isSupportedDocFile(path: string): boolean {return (SUPPORTED_DOC_EXTENSIONS as readonly string[]).includes(ext);}+export function linkNamesDocumentFile(href: string, sourceDocName: string): boolean {+ const filePath = resolveAssetProjectPath(href, sourceDocName, { literal: false });+ return filePath !== null && isSupportedDocFile(filePath);+}+export function isSupportedAssetFile(path: string, assetExtensions: ReadonlySet<string>): boolean {const ext = extname(path).slice(1).toLowerCase();return ext.length > 0 && assetExtensions.has(ext);diff --git a/packages/server/src/file-watcher.test.ts b/packages/server/src/file-watcher.test.tsindex 3a10f43ef..aebd8c412 100644--- a/packages/server/src/file-watcher.test.ts+++ b/packages/server/src/file-watcher.test.ts@@ -1272,6 +1272,37 @@ describe('file-watcher ContentFilter refcount hooks', () => {expect(filter.isExcluded('fresh/pic.png')).toBe(false);});+ test('asset create in a directory with no markdown document dispatches asset-create', async () => {+ const filter = createContentFilter({+ projectDir: tmpDir,+ contentDir,+ });+ const newDir = resolve(contentDir, 'media');+ mkdirSync(newDir);+ const assetPath = resolve(newDir, 'pic.png');+ writeFileSync(assetPath, 'fake-png-bytes');+ expect(filter.isExcluded('media/pic.png')).toBe(true);++ const collected: DiskEvent[] = [];+ await handleRawEvents(+ [{ type: 'create', path: assetPath }],+ contentDir,+ filter,+ new Map(),+ new Map(),+ async (e) => {+ collected.push(e);+ },+ );++ expect(collected.map((e) => e.kind).sort()).toEqual(['asset-create', 'file-create']);+ const asset = collected.find((e) => e.kind === 'asset-create');+ expect(asset?.kind).toBe('asset-create');+ if (asset?.kind === 'asset-create') {+ expect(asset.relativePath).toBe('media/pic.png');+ }+ });+test('LINKABLE_ASSET_EXTENSIONS: .base file alongside .md dispatches asset-create event', async () => {const filter = createContentFilter({projectDir: tmpDir,diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.tsindex fa7b8b0e2..af8a72172 100644--- a/packages/server/src/file-watcher.ts+++ b/packages/server/src/file-watcher.ts@@ -2673,7 +2673,7 @@ async function handleRawEventsInternal(for (const raw of assetEvents) {if (contentFilter) {const relPath = toPosix(relative(contentDir, raw.path));- if (contentFilter.isExcluded(relPath)) {+ if (contentFilter.isPathIgnored(relPath)) {recordWatcherDecision('drop-filter-excluded', raw.type, raw.path);continue;}diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.tsindex 72fce3b72..920f29422 100644--- a/packages/server/src/http/agent-write-routes.ts+++ b/packages/server/src/http/agent-write-routes.ts@@ -445,9 +445,11 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupconst writtenSource = session.dc.document.getText('source').toString();registerWrittenDocInFileIndex(resolvedDocName, writtenSource);const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);- const linkAdvisory = (- await prepareWriteLinkAdvisory([resolvedDocName], { resolveFolderLinks: true })- )(writtenSource, resolvedDocName, linkPolicy.suppressLogLinkAdvisories);+ const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(+ writtenSource,+ resolvedDocName,+ linkPolicy.suppressLogLinkAdvisories,+ );const subscriberCount = getSubscriberCount(resolvedDocName);const systemSubscriberCount = getSystemSubscriberCount();if (systemSubscriberCount === 0) {@@ -728,9 +730,7 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupresolvedDocName,session.dc.document.getText('source').toString(),);- const linkAdvisory = (- await prepareWriteLinkAdvisory([resolvedDocName], { resolveFolderLinks: false })- )(+ const linkAdvisory = (await prepareWriteLinkAdvisory([resolvedDocName]))(session.dc.document.getText('source').toString(),resolvedDocName,linkPolicy.suppressLogLinkAdvisories,@@ -1042,9 +1042,11 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupconst patchedSource = session.dc.document.getText('source').toString();registerWrittenDocInFileIndex(docName, patchedSource);const renderWarnings = await validateMermaidFences(patchedSource, docName);- const linkAdvisory = (- await prepareWriteLinkAdvisory([docName], { resolveFolderLinks: false })- )(patchedSource, docName, linkPolicy.suppressLogLinkAdvisories);+ const linkAdvisory = (await prepareWriteLinkAdvisory([docName]))(+ patchedSource,+ docName,+ linkPolicy.suppressLogLinkAdvisories,+ );const patchWarning = buildReconcileWarning(patchReconcile);const patchDivergenceEntry =patchDivergence !== undefined ? toContentDivergenceWarning(patchDivergence) : undefined;diff --git a/packages/server/src/http/lint-routes.test.ts b/packages/server/src/http/lint-routes.test.tsindex 0d0c99eb0..8e81b0fd0 100644--- a/packages/server/src/http/lint-routes.test.ts+++ b/packages/server/src/http/lint-routes.test.ts@@ -38,6 +38,7 @@ describe('audit routes with a missing content directory', () => {collectAdmittedDocNames: async () => new Set<string>(),unmatchedGlobProblems: () => [],readAuditGeneration: () => 'initial',+ localTargetInventory: () => ({ documentTargets: [], fileTargets: [], folderTargets: [] }),});const dispatch = group.table.resolve(routePath)?.dispatch;if (dispatch === undefined) throw new Error(`${routePath} was not registered`);diff --git a/packages/server/src/http/lint-routes.ts b/packages/server/src/http/lint-routes.tsindex dec6969cb..fa0c8d5e3 100644--- a/packages/server/src/http/lint-routes.ts+++ b/packages/server/src/http/lint-routes.ts@@ -35,6 +35,7 @@ import {toValidationCountsPlane,type ValidationAuditResult,} from '../lint/validation-audit.ts';+import type { WatcherLocalTargetInventory } from '../local-target-inventory.ts';import { createSingleFlight } from '../single-flight.ts';import type { ApiRouteTable } from './api-pipeline.ts';import { errorResponse } from './error-response.ts';@@ -61,6 +62,7 @@ export interface LintRouteDeps {collectAdmittedDocNames: () => Promise<Set<string>>;unmatchedGlobProblems: (effective: LinterConfig) => string[];readAuditGeneration: () => string;+ localTargetInventory: () => WatcherLocalTargetInventory;}export interface LintRoutes {@@ -84,6 +86,7 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {collectAdmittedDocNames,unmatchedGlobProblems,readAuditGeneration,+ localTargetInventory,} = deps;const liveLintSourceFor = (docRelPath: string): string | null => {@@ -375,6 +378,7 @@ export function createLintRoutes(deps: LintRouteDeps): LintRoutes {docFilePathFor: (docName) => resolveDocFilePath(contentDir, docName),cache: auditCache,auditGeneration: readAuditGeneration,+ localTargetInventory,});const result = await runCoalescedAudit(validators,diff --git a/packages/server/src/link-advisory-policy.ts b/packages/server/src/link-advisory-policy.tsindex 5449998f5..4479ba11b 100644--- a/packages/server/src/link-advisory-policy.ts+++ b/packages/server/src/link-advisory-policy.ts@@ -43,7 +43,6 @@ type WriteLinkAdvisor = (export type PrepareWriteLinkAdvisory = (writtenDocNames: Iterable<string>,- options: { resolveFolderLinks: boolean },) => Promise<WriteLinkAdvisor>;export function deferredWriteLinkAdvisory(): WriteLinkAdvisory {diff --git a/packages/server/src/link-classification-uniformity.test.ts b/packages/server/src/link-classification-uniformity.test.tsindex 3b838aabe..a02d36a19 100644--- a/packages/server/src/link-classification-uniformity.test.ts+++ b/packages/server/src/link-classification-uniformity.test.ts@@ -3,6 +3,7 @@* the equivalent pin for *classification*.*/+import { createTargetNamespace } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {extractMarkdownLinksFromMarkdown,@@ -14,6 +15,7 @@ import {type LocalTargetAssessment,type LocalTargetInventory,} from './local-target-assessment.ts';+import { createFileBasenameResolver } from './local-target-inventory.ts';import {extractLocalTargetOccurrences,type LocalTargetOccurrence,@@ -82,12 +84,13 @@ const DOCUMENTS = ['all-link-types', 'targets/existing-page', 'targets/Case Sensconst FILES = ['assets/NOTICE', 'assets/existing.txt', 'assets/manual.pdf'] as const;function buildInventory(): LocalTargetInventory {- const documents = new Set<string>(DOCUMENTS);- const files = new Set<string>(FILES);+ const documents = createTargetNamespace('document', DOCUMENTS);+ const files = createTargetNamespace('file', FILES);const tolerant = createTolerantDocumentResolver(documents);return {- hasDocument: (docName) => documents.has(docName),- hasFile: (path) => files.has(path),+ resolveDocument: (docName) => documents.resolve(docName),+ resolveFile: (path) => files.resolve(path),+ resolveFileByBasename: createFileBasenameResolver(files),resolveTolerantDocument: (docName) => tolerant(docName),};}diff --git a/packages/server/src/lint/physical-scope-links.ts b/packages/server/src/lint/physical-scope-links.tsindex 921763c27..2f36e3ee6 100644--- a/packages/server/src/lint/physical-scope-links.ts+++ b/packages/server/src/lint/physical-scope-links.ts@@ -1,11 +1,19 @@import { readFileSync, realpathSync } from 'node:fs';import { extname, relative, resolve } from 'node:path';-import { SUPPORTED_DOC_EXTENSIONS } from '@inkeep/open-knowledge-core';+import {+ addDocumentFolders,+ asTargetNamespace,+ createTargetNamespace,+ createWikiAssetResolver,+ SUPPORTED_DOC_EXTENSIONS,+} from '@inkeep/open-knowledge-core';import { BacklinkIndex } from '../backlink-index.ts';import { createContentFilter } from '../content-filter.ts';import { isWithinContentDir } from '../content-path.ts';import { isSupportedDocFile, stripDocExtension } from '../doc-extensions.ts';import { assessLocalTargets, createTolerantDocumentResolver } from '../local-target-assessment.ts';+import { isExcludedFileOnDisk } from '../local-target-index.ts';+import { createFileBasenameResolver } from '../local-target-inventory.ts';import { toPosix } from '../path-utils.ts';import { readScopeEntry } from './audit-scope.ts';import type { ValidationAuditDeps, ValidationScope } from './validation-audit.ts';@@ -54,8 +62,19 @@ export function physicalScopeLinks(if (!isWithinContentDir(realpathSync(full), canonicalContent)) return false;return kind === 'file' ? stat.isFile() : stat.isDirectory();};- const hasFile = (path: string) => targetExists(path, 'file');- const hasFolder = (path: string) => targetExists(path, 'dir');+ const documents = asTargetNamespace('document', admitted);+ const tracked = deps.localTargetInventory?.() ?? null;+ const files = tracked === null ? null : asTargetNamespace('file', tracked.fileTargets);+ const folders =+ tracked === null+ ? null+ : addDocumentFolders(createTargetNamespace('folder', tracked.folderTargets), documents);+ const resolveFile = (path: string): string | undefined =>+ files === null ? (targetExists(path, 'file') ? path : undefined) : files.resolve(path);+ const resolveFolder = (path: string): string | undefined =>+ folders === null ? (targetExists(path, 'dir') ? path : undefined) : folders.resolve(path);+ const hasFile = (path: string) => resolveFile(path) !== undefined;+ const hasFolder = (path: string) => resolveFolder(path) !== undefined;const graph = new BacklinkIndex({projectDir: deps.projectDir,contentDir: deps.contentDir,@@ -63,11 +82,13 @@ export function physicalScopeLinks(getFileOracle: () => ({ hasFile }),});graph.updateDocumentFromMarkdown(source, markdown);- const documents = new Set(admitted);const assessments = assessLocalTargets(markdown, source, {- hasDocument: (name) => documents.has(name),- hasFile,- hasFolder,+ resolveDocument: (name) => documents.resolve(name),+ resolveFile,+ resolveFileByBasename: files === null ? null : createFileBasenameResolver(files),+ ...(files === null ? {} : { resolveWikiFile: createWikiAssetResolver(files) }),+ resolveFolder,+ isExcludedFile: (path) => isExcludedFileOnDisk(deps.contentDir, filter, path),resolveTolerantDocument: createTolerantDocumentResolver(documents),});return {diff --git a/packages/server/src/lint/validation-audit.test.ts b/packages/server/src/lint/validation-audit.test.tsindex b861e245c..657bc14e9 100644--- a/packages/server/src/lint/validation-audit.test.ts+++ b/packages/server/src/lint/validation-audit.test.ts@@ -10,6 +10,7 @@ import {} from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { BacklinkIndex } from '../backlink-index.ts';+import { createContentFilter } from '../content-filter.ts';import type { LinkAdvisoryPolicy } from '../link-advisory-policy.ts';import { LocalTargetIndex } from '../local-target-index.ts';import { resolveAuditScope } from './audit-scope.ts';@@ -517,6 +518,37 @@ describe('local-target findings (files, images, reference-style)', () => {expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);});+ test('a file that exists but is excluded by ignore rules says so and names the .okignore remedy (PRD-8896)', async () => {+ writeFileSync(join(root, '.gitignore'), 'ignored/\n');+ mkdirSync(join(root, 'ignored'));+ writeFileSync(join(root, 'ignored', 'ig.png'), 'png');+ localTargets = new LocalTargetIndex({+ contentDir: root,+ contentFilter: createContentFilter({ projectDir: root, contentDir: root }),+ });+ seedDoc(+ 'doc',+ '# Doc\n\n[d](./ignored/ig.png)\n\n\n\n[m](./ignored/missing.png)\n',+ );++ const result = await runValidationAudit(createProjectValidators(deps()));++ const diagnostics = result.files[0]?.diagnostics ?? [];+ expect(diagnostics.map((d) => [d.message, d.localTarget?.reason])).toEqual([+ [+ 'Link target "ignored/ig.png" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.',+ 'excluded',+ ],+ [+ 'Image target "ignored/ig.png" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.',+ 'excluded',+ ],+ ['Link target "ignored/missing.png" does not resolve to an existing file.', 'no-such-file'],+ ]);+ expect(diagnostics.every((d) => d.linkTarget === undefined)).toBe(true);+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);+ });+test('an existing file target produces no finding', async () => {seedDoc('doc', '# Doc\n\n[report](./report.pdf)\n');seedFile('report.pdf');@@ -527,6 +559,47 @@ describe('local-target findings (files, images, reference-style)', () => {expect(result.warningCount).toBe(0);});+ test('a missing wiki asset target is a dead-link finding like a missing markdown file', async () => {+ seedDoc('doc', '# Doc\n\n![[nothere.gif]] and [[media/nothere.png]]\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files.map((f) => f.file)).toEqual(['doc.md']);+ const diagnostics = result.files[0]?.diagnostics ?? [];+ expect(diagnostics.map((d) => [d.code, d.message])).toEqual([+ ['dead-link', 'Image target "nothere.gif" does not resolve to an existing file.'],+ ['dead-link', 'Link target "media/nothere.png" does not resolve to an existing file.'],+ ]);+ expect(diagnostics[0]?.localTarget).toEqual({+ href: 'nothere.gif',+ targetKind: 'file',+ role: 'image',+ sourceForm: 'wiki-embed',+ resolvedTarget: 'nothere.gif',+ reason: 'no-such-file',+ resolutionMethod: 'root-relative',+ });+ expect(diagnostics[1]?.localTarget).toMatchObject({+ role: 'link',+ sourceForm: 'wiki-link',+ resolvedTarget: 'media/nothere.png',+ reason: 'no-such-file',+ });+ expect(diagnostics.every((d) => d.linkTarget === undefined)).toBe(true);+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);+ });++ test('an existing wiki asset target produces no finding by path, basename, or equivalent spelling', async () => {+ seedFile('media/photo.png');+ seedFile('media/Café.png');+ seedDoc('doc', '# Doc\n\n![[photo.png]] [[media/photo.png]] ![[Café.png]] [[photo.png]]\n');++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files).toEqual([]);+ expect(result.warningCount).toBe(0);+ });+test('an exact file link does not suppress a same-target missing wiki document', async () => {seedDoc('doc', '# Doc\n\n[file](assets/NOTICE) and [[assets/NOTICE]]\n');seedFile('assets/NOTICE');@@ -1291,6 +1364,151 @@ describe('selected physical scope with same-stem document siblings', () => {);});+ test('file and folder targets resolve through the tracked inventory, as on the index path', async () => {+ const links = [+ '[nfc folder](Caf\u00e9/)',+ '[exact file](assets/Cafe\u0301.png)',+ '[nfc file](assets/Caf\u00e9.png)',+ '[nfd file](assets/Zoe\u0308.png)',+ '[leaf case](assets/CAF\u00c9.PNG)',+ '[folder case](Assets/Caf\u00e9.png)',+ '[folder case dir](CAF\u00c9/)',+ '![[shared/pics/pic.png]]',+ ].join('\n\n');+ const fileTargets = ['Shared/Pics/pic.png'];+ for (const dir of ['twin', 'single']) {+ seedDoc(`${dir}/Cafe\u0301/note`, '# note\n');+ fileTargets.push(`${dir}/assets/Cafe\u0301.png`, `${dir}/assets/Zo\u00eb.png`);+ seedDoc(`${dir}/Probe`, `# Probe\n\n${links}\n`);+ }+ for (const file of fileTargets) {+ mkdirSync(join(root, file, '..'), { recursive: true });+ writeFileSync(join(root, file), 'png');+ seedFile(file);+ }+ writeFileSync(join(root, 'twin/Probe.mdx'), '# Probe mdx\n');+ const validators = createProjectValidators(+ deps({+ localTargetInventory: () => ({+ documentTargets: [...admitted],+ fileTargets,+ folderTargets: ['Shared', 'Shared/Pics', 'single/Cafe\u0301', 'twin/Cafe\u0301'],+ }),+ }),+ );+ const findings = async (dir: string): Promise<string[]> => {+ const resolution = resolveAuditScope(`${dir}/Probe.md`, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: `${dir}/Probe.md`,+ resolvedScope: resolution.scope,+ });+ return result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.source === 'links')+ .map((diagnostic) =>+ (diagnostic.localTarget?.href ?? diagnostic.linkTarget ?? '').replace(`${dir}/`, ''),+ )+ .sort();+ };+ expect(await findings('single')).toEqual(['Assets/Caf\u00e9.png', 'CAF\u00c9/']);+ expect(await findings('twin')).toEqual(await findings('single'));+ });++ test('a slash-free wiki asset embed gets the same verdict in the physical scope as on the index path', async () => {+ const fileTargets = ['media/photo.png'];+ mkdirSync(join(root, 'media'), { recursive: true });+ writeFileSync(join(root, 'media/photo.png'), 'png');+ seedFile('media/photo.png');+ for (const dir of ['twin', 'single']) {+ seedDoc(`${dir}/Probe`, '# Probe\n\n![[photo.png]] and ![[ghost.png]]\n');+ }+ writeFileSync(join(root, 'twin/Probe.mdx'), '# Probe mdx\n');+ const validators = createProjectValidators(+ deps({+ localTargetInventory: () => ({+ documentTargets: [...admitted],+ fileTargets,+ folderTargets: ['media'],+ }),+ }),+ );+ const findings = async (dir: string): Promise<string[]> => {+ const resolution = resolveAuditScope(`${dir}/Probe.md`, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: `${dir}/Probe.md`,+ resolvedScope: resolution.scope,+ });+ return result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.source === 'links')+ .map((diagnostic) => diagnostic.localTarget?.href ?? diagnostic.linkTarget ?? '')+ .sort();+ };+ expect(await findings('single')).toEqual(['ghost.png']);+ expect(await findings('twin')).toEqual(['ghost.png']);+ });++ test('without a tracked inventory, a slash-free wiki asset embed in the physical scope gets no verdict', async () => {+ mkdirSync(join(root, 'media'), { recursive: true });+ writeFileSync(join(root, 'media/photo.png'), 'png');+ seedDoc('twin/Probe', '# Probe\n\n![[photo.png]], ![[ghost.png]] and ![[media/gone.png]]\n');+ writeFileSync(join(root, 'twin/Probe.mdx'), '# Probe mdx\n');+ const validators = createProjectValidators(deps({ localTargetInventory: () => null }));+ const resolution = resolveAuditScope('twin/Probe.md', root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: 'twin/Probe.md',+ resolvedScope: resolution.scope,+ });+ const findings = result.files+ .flatMap((file) => file.diagnostics)+ .filter((diagnostic) => diagnostic.source === 'links')+ .map((diagnostic) => diagnostic.localTarget?.href ?? diagnostic.linkTarget ?? '')+ .sort();+ expect(findings).toEqual(['media/gone.png']);+ });++ test('an ignored file target is excluded in the physical scope, as on the index path', async () => {+ writeFileSync(join(root, '.gitignore'), 'ignored/\n');+ mkdirSync(join(root, 'ignored'));+ writeFileSync(join(root, 'ignored', 'ig.png'), 'png');+ localTargets = new LocalTargetIndex({+ contentDir: root,+ contentFilter: createContentFilter({ projectDir: root, contentDir: root }),+ });+ const body = '# Doc\n\n\n\n[m](../ignored/missing.png)\n';+ seedDoc('single/doc', body);+ seedDoc('twin/doc', body);+ writeFileSync(join(root, 'twin/doc.mdx'), '# Doc mdx\n');+ const validators = createProjectValidators(+ deps({+ localTargetInventory: () => ({+ documentTargets: [...admitted],+ fileTargets: [],+ folderTargets: [],+ }),+ }),+ );+ const reasons = async (dir: string): Promise<unknown[]> => {+ const resolution = resolveAuditScope(`${dir}/doc.md`, root);+ if (!resolution.ok) throw new Error(resolution.title);+ const result = await runValidationAudit(validators, {+ targetPath: `${dir}/doc.md`,+ resolvedScope: resolution.scope,+ });+ return result.files+ .flatMap((file) => file.diagnostics)+ .map((d) => [d.localTarget?.resolvedTarget, d.localTarget?.reason]);+ };+ expect(await reasons('single')).toEqual([+ ['ignored/ig.png', 'excluded'],+ ['ignored/missing.png', 'no-such-file'],+ ]);+ expect(await reasons('twin')).toEqual(await reasons('single'));+ });+test('uses live source for the canonical sibling and disk source for the alternate sibling', async () => {seedDoc('dual', '# MD\n\n[[md-disk-ghost]]\n');writeFileSync(join(root, 'dual.mdx'), '# MDX\n\n[[mdx-disk-ghost]]\n');@@ -1316,3 +1534,19 @@ describe('selected physical scope with same-stem document siblings', () => {}});});++describe('canonically equivalent spellings', () => {+ test('NFC links to NFD documents and files are not dead links on either plane', async () => {+ seedDoc('people/Rene\u0301', '# Ren\u00e9\n');+ seedFile('assets/Rene\u0301.png');+ seedDoc(+ 'linker',+ '# Linker\n\nSee [Ren\u00e9](people/Ren\u00e9.md), [[people/Ren\u00e9]] and .\n',+ );++ const result = await runValidationAudit(createProjectValidators(deps()));++ expect(result.files).toEqual([]);+ expect(result.warningCount).toBe(0);+ });+});diff --git a/packages/server/src/lint/validation-audit.ts b/packages/server/src/lint/validation-audit.tsindex 5c7f1095d..b63efd831 100644--- a/packages/server/src/lint/validation-audit.ts+++ b/packages/server/src/lint/validation-audit.ts@@ -20,6 +20,7 @@ import {buildLocalTargetEvidence,type LocalTargetAssessment,} from '../local-target-assessment.ts';+import type { WatcherLocalTargetInventory } from '../local-target-inventory.ts';import { getLogger } from '../logger.ts';import { toPosix } from '../path-utils.ts';import { AuditSupersededError, auditProject, auditScopeWarning, resolveScope } from './audit.ts';@@ -141,6 +142,7 @@ export interface ValidationAuditDeps {docFilePathFor: (docName: string) => string | null;cache?: AuditCache;auditGeneration?: () => string;+ localTargetInventory?: () => WatcherLocalTargetInventory | null;}export function createProjectValidators(deps: ValidationAuditDeps): ProjectValidator[] {@@ -428,6 +430,11 @@ function localTargetMessage(assessment: LocalTargetAssessment, shown: string): s? `Image target "${shown}" could not be resolved to a project-local file.`: `Link target "${shown}" could not be resolved to a project-local target.`;}+ if (assessment.reason === 'excluded') {+ return isImage+ ? `Image target "${shown}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`+ : `Link target "${shown}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`;+ }if (assessment.targetKind === 'file') {return isImage? `Image target "${shown}" does not resolve to an existing file.`diff --git a/packages/server/src/local-target-assessment.test.ts b/packages/server/src/local-target-assessment.test.tsindex a72a102c0..b0f892c46 100644--- a/packages/server/src/local-target-assessment.test.ts+++ b/packages/server/src/local-target-assessment.test.ts@@ -1,7 +1,11 @@+import { createBasenameIndex, createTargetNamespace } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {assessLocalTargetOccurrences,assessLocalTargets,+ buildLocalTargetEvidence,+ createTolerantDocumentResolver,+ isProjectableToLocalTargetSurfaces,type LocalTargetInventory,toForwardLinkLocalTargets,} from './local-target-assessment.ts';@@ -11,13 +15,20 @@ function inventory(opts?: {docs?: Iterable<string>;files?: Iterable<string>;tolerant?: Record<string, string>;+ excluded?: Iterable<string>;}): LocalTargetInventory {- const docs = new Set(opts?.docs ?? []);- const files = new Set(opts?.files ?? []);+ const docs = createTargetNamespace('document', opts?.docs ?? []);+ const files = createTargetNamespace('file', opts?.files ?? []);+ const basenames = createBasenameIndex();+ for (const file of files) basenames.add(file);const tolerant = opts?.tolerant;+ const excluded = opts?.excluded === undefined ? null : new Set(opts.excluded);const base: LocalTargetInventory = {- hasDocument: (docName) => docs.has(docName),- hasFile: (filePath) => files.has(filePath),+ resolveDocument: (docName) => docs.resolve(docName),+ resolveFile: (filePath) => files.resolve(filePath),+ resolveFileByBasename: (basename, sourceDocName) =>+ basenames.resolveEmbed(basename, sourceDocName) ?? undefined,+ ...(excluded === null ? {} : { isExcludedFile: (filePath) => excluded.has(filePath) }),};if (!tolerant) return base;return { ...base, resolveTolerantDocument: (docName) => tolerant[docName] ?? null };@@ -88,6 +99,14 @@ describe('document vs ordinary-file membership', () => {});});+ test('a missing document link with a .md path is never satisfied by a file of that path', () => {+ const a = assessOne(+ '[g](./Guide.md)',+ inventory({ docs: ['notes/guide'], files: ['notes/Guide.md'] }),+ );+ expect(a).toMatchObject({ targetKind: 'document', status: 'missing', reason: 'no-such-doc' });+ });+test('an exact document wins when both extension-less target kinds exist', () => {const a = assessOne('[target](./guide)',@@ -219,11 +238,11 @@ describe('repeated occurrences share existence work while each keeps its range',const md = 'One [a](./x.md) two [b](./x.md) three [c](./y.md).';let docLookups = 0;const inv: LocalTargetInventory = {- hasDocument: (docName) => {+ resolveDocument: (docName) => {docLookups += 1;- return docName === 'notes/x';+ return docName === 'notes/x' ? docName : undefined;},- hasFile: () => false,+ resolveFile: () => undefined,};const assessments = assessLocalTargetOccurrences(extractLocalTargetOccurrences(md),@@ -265,13 +284,114 @@ describe('scope: classification is total across every recognized form', () => {});});- test('an extension-bearing wiki embed stays file-shaped', () => {+ test('an extension-bearing wiki embed stays file-shaped and resolves by vault-wide basename', () => {const a = assessLocalTargets('![[photo.png]]',SOURCE,inventory({ files: ['notes/photo.png'] }),)[0];- expect(a).toMatchObject({ targetKind: 'file', status: 'exact' });+ expect(a).toMatchObject({+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: 'notes/photo.png',+ reason: null,+ resolutionMethod: 'basename',+ });+ });++ test('a basename wiki embed prefers the candidate nearest the source, like the embed renderer', () => {+ const a = assessLocalTargets(+ '![[photo.png]]',+ SOURCE,+ inventory({ files: ['media/photo.png', 'notes/photo.png'] }),+ )[0];+ expect(a).toMatchObject({ status: 'exact', resolvedTarget: 'notes/photo.png' });+ });++ test('a basename wiki embed resolves across canonically equivalent spellings', () => {+ const a = assessLocalTargets(+ '![[Café.png]]',+ SOURCE,+ inventory({ files: ['media/Café.png'] }),+ )[0];+ expect(a).toMatchObject({+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: 'media/Café.png',+ });+ });++ test('a wiki asset path resolves against the vault root, never the source folder', () => {+ const atRoot = assessLocalTargets(+ '[[assets/x.png]]',+ SOURCE,+ inventory({ files: ['assets/x.png'] }),+ )[0];+ expect(atRoot).toMatchObject({+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: 'assets/x.png',+ resolutionMethod: 'root-relative',+ });++ const besideSource = assessLocalTargets(+ '[[assets/x.png]]',+ SOURCE,+ inventory({ files: ['notes/assets/x.png'] }),+ )[0];+ expect(besideSource).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'assets/x.png',+ });+ });++ test('a missing wiki asset target is a missing file, by basename or by path', () => {+ const rows = assessLocalTargets(+ '![[nothere.gif]] and [[media/nothere.png]]',+ SOURCE,+ inventory({ files: ['media/photo.png'] }),+ );+ expect(rows.map((r) => [r.occurrence.sourceForm, r.occurrence.role])).toEqual([+ ['wiki-embed', 'image'],+ ['wiki-link', 'link'],+ ]);+ expect(rows[0]).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'nothere.gif',+ });+ expect(rows[1]).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'media/nothere.png',+ });+ });++ test('a dotted bare wiki name that names a document is assessed as a document link the surfaces leave to the graph', () => {+ const docs = ['vault/acp.daemon'];+ const resolveTolerant = createTolerantDocumentResolver(docs);+ const rows = assessLocalTargets('[[acp.daemon]], ![[ACP.Daemon]] and [[gone.daemon]]', SOURCE, {+ ...inventory({ docs }),+ resolveTolerantDocument: (docName) => resolveTolerant(docName),+ });+ expect(+ rows.map((r) => [+ r.occurrence.href,+ r.targetKind,+ r.status,+ r.reason,+ r.fallbackTarget,+ isProjectableToLocalTargetSurfaces(r),+ ]),+ ).toEqual([+ ['acp.daemon', 'document', 'fallback', 'no-such-doc', 'vault/acp.daemon', false],+ ['ACP.Daemon', 'document', 'fallback', 'no-such-doc', 'vault/acp.daemon', false],+ ['gone.daemon', 'file', 'missing', 'no-such-file', null, true],+ ]);});test('a wiki target resolves entirely against the vault root, fallback included', () => {@@ -298,24 +418,47 @@ describe('scope: classification is total across every recognized form', () => {});describe('toForwardLinkLocalTargets — Links panel Local files projection', () => {- test('projects file and image references but excludes document graph edges and wiki forms', () => {+ test('projects file and image references but excludes document graph edges and document-shaped wiki links', () => {const md = ['[report](./report.pdf)','','<img src="./pic.png">','[other](./other.md)','[[wiki]]',+ '![[missing.png]]',+ '[[docs/spec.pdf]]',].join('\n');const rows = toForwardLinkLocalTargets(assessLocalTargets(md,SOURCE,- inventory({ docs: ['notes/other'], files: ['notes/logo.png'] }),+ inventory({ docs: ['notes/other'], files: ['notes/logo.png', 'docs/spec.pdf'] }),),);- expect(rows.map((r) => r.href).sort()).toEqual(['./logo.png', './pic.png', './report.pdf']);+ expect(rows.map((r) => r.href).sort()).toEqual([+ './logo.png',+ './pic.png',+ './report.pdf',+ 'docs/spec.pdf',+ 'missing.png',+ ]);expect(rows.some((r) => r.targetKind === 'document')).toBe(false);+ expect(rows.find((r) => r.href === 'missing.png')).toMatchObject({+ role: 'image',+ sourceForm: 'wiki-embed',+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'missing.png',+ });+ expect(rows.find((r) => r.href === 'docs/spec.pdf')).toMatchObject({+ role: 'link',+ sourceForm: 'wiki-link',+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: 'docs/spec.pdf',+ });const report = rows.find((r) => r.href === './report.pdf');expect(report).toMatchObject({@@ -384,6 +527,22 @@ describe('toForwardLinkLocalTargets — Links panel Local files projection', ());expect(rows).toEqual([]);});++ test('Problems evidence carries a file-shaped wiki occurrence and still drops a document-shaped one', () => {+ const rows = assessLocalTargets('[[ghost]] and ![[ghost.png]]', SOURCE, inventory({}));+ expect(rows).toHaveLength(2);+ const [doc, file] = rows;+ expect(doc && buildLocalTargetEvidence(doc, 'no-such-doc')).toBeNull();+ expect(file && buildLocalTargetEvidence(file, 'no-such-file')).toEqual({+ href: 'ghost.png',+ targetKind: 'file',+ role: 'image',+ sourceForm: 'wiki-embed',+ resolvedTarget: 'ghost.png',+ reason: 'no-such-file',+ resolutionMethod: 'root-relative',+ });+ });});describe('percent-encoded targets are assessed against the decoded document', () => {@@ -423,3 +582,118 @@ describe('percent-encoded targets are assessed against the decoded document', ()expect(a).toMatchObject({ status: 'missing' });});});++describe('canonically equivalent spellings resolve to the existing raw name', () => {+ const NFC = 'notes/Ren\u00e9';+ const NFD = 'notes/Rene\u0301';++ test.each([+ ['NFC', 'NFD', NFC, NFD],+ ['NFD', 'NFC', NFD, NFC],+ ])(+ 'an %s href to an %s document is exact and names the stored spelling',+ (_h, _d, linked, stored) => {+ const a = assessOne(`[x](/${linked}.md)`, inventory({ docs: [stored] }));+ expect(a).toMatchObject({+ targetKind: 'document',+ status: 'exact',+ resolvedTarget: stored,+ reason: null,+ fallbackTarget: null,+ });+ },+ );++ test('a file href resolves across normalization and leaf case but not ancestor case', () => {+ const stored = 'assets/Rene\u0301.PDF';+ const inv = inventory({ files: [stored] });+ expect(assessOne('[x](/assets/Ren\u00e9.pdf)', inv)).toMatchObject({+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: stored,+ });+ expect(assessOne('[x](/Assets/Ren\u00e9.pdf)', inv)).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ });+ });++ test('the tolerant folder-index tier resolves through an equivalent spelling', () => {+ const resolve = createTolerantDocumentResolver(['guides/Rene\u0301/index']);+ expect(resolve('guides/Ren\u00e9')).toBe('guides/Rene\u0301/index');+ });+});++describe('file targets that exist but are excluded by ignore rules (PRD-8896)', () => {+ const excluded = inventory({ excluded: ['notes/ignored/ig.png'] });++ test('a link to an excluded file reports excluded, not no-such-file', () => {+ const a = assessOne('[d](ignored/ig.png)', excluded);+ expect(a).toMatchObject({+ targetKind: 'file',+ resolvedTarget: 'notes/ignored/ig.png',+ status: 'missing',+ reason: 'excluded',+ resolutionMethod: 'source-relative',+ fallbackTarget: null,+ });+ expect(a?.occurrence.role).toBe('link');+ });++ test('an image embed of an excluded file reports excluded', () => {+ const a = assessOne('', excluded);+ expect(a).toMatchObject({ targetKind: 'file', status: 'missing', reason: 'excluded' });+ expect(a?.occurrence.role).toBe('image');+ });++ test('a wiki embed and a wiki link of an excluded file report excluded', () => {+ for (const markdown of ['![[notes/ignored/ig.png]]', '[[notes/ignored/ig.png]]']) {+ const a = assessOne(markdown, excluded);+ expect(a).toMatchObject({+ targetKind: 'file',+ resolvedTarget: 'notes/ignored/ig.png',+ status: 'missing',+ reason: 'excluded',+ });+ }+ });++ test('a wiki embed of a file the probe does not know stays no-such-file (control)', () => {+ const a = assessOne('![[notes/ignored/missing.png]]', excluded);+ expect(a).toMatchObject({ targetKind: 'file', status: 'missing', reason: 'no-such-file' });+ });++ test('a file the probe does not know stays no-such-file (control)', () => {+ const a = assessOne('[m](ignored/missing.png)', excluded);+ expect(a).toMatchObject({ targetKind: 'file', status: 'missing', reason: 'no-such-file' });+ });++ test('an inventory without the probe keeps reporting no-such-file', () => {+ const a = assessOne('[d](ignored/ig.png)', inventory());+ expect(a).toMatchObject({ targetKind: 'file', status: 'missing', reason: 'no-such-file' });+ });++ test('an extensionless link that falls through to the file plane reports excluded', () => {+ const a = assessOne(+ '[mk](ignored/Makefile)',+ inventory({ excluded: ['notes/ignored/Makefile'] }),+ );+ expect(a).toMatchObject({+ targetKind: 'file',+ resolvedTarget: 'notes/ignored/Makefile',+ status: 'missing',+ reason: 'excluded',+ });+ });++ test('a Markdown link to an existing but ignored .md file reports excluded', () => {+ const a = assessOne('[d](./drafts/plan.md)', inventory({ excluded: ['notes/drafts/plan.md'] }));+ expect(a).toMatchObject({+ targetKind: 'file',+ resolvedTarget: 'notes/drafts/plan.md',+ status: 'missing',+ reason: 'excluded',+ });+ });+});diff --git a/packages/server/src/local-target-assessment.ts b/packages/server/src/local-target-assessment.tsindex 395aca9e1..5969bd7df 100644--- a/packages/server/src/local-target-assessment.ts+++ b/packages/server/src/local-target-assessment.ts@@ -1,5 +1,6 @@import {assertNeverLinkTarget,+ asTargetNamespace,type BrokenLinkReason,classifyMarkdownHref,classifyWikiLinkTarget,@@ -9,6 +10,7 @@ import {resolveAssetProjectPath,toWikiLinkSlug,} from '@inkeep/open-knowledge-core';+import { linkNamesDocumentFile } from './doc-extensions.ts';import {extractLocalTargetOccurrences,type LocalTargetOccurrence,@@ -19,21 +21,29 @@ type LocalTargetKind = 'document' | 'file' | 'unknown';type LocalTargetStatus = 'exact' | 'fallback' | 'missing' | 'unresolvable';-type LocalTargetReason = 'no-such-doc' | 'no-such-file' | 'unresolvable';+type LocalTargetReason = 'no-such-doc' | 'no-such-file' | 'unresolvable' | 'excluded';-type LocalTargetResolutionMethod = 'source-relative' | 'root-relative' | 'tolerant' | 'none';+type LocalTargetResolutionMethod =+ | 'source-relative'+ | 'root-relative'+ | 'tolerant'+ | 'basename'+ | 'none';export interface LocalTargetInventory {- hasDocument(docName: string): boolean;- hasFile(contentRootRelativePath: string): boolean;+ resolveDocument(docName: string): string | undefined;+ resolveFile(contentRootRelativePath: string): string | undefined;+ resolveFileByBasename: ((basename: string, sourceDocName: string) => string | undefined) | null;+ resolveWikiFile?(contentRootRelativePath: string): string | undefined;+ isExcludedFile?(contentRootRelativePath: string): boolean;resolveTolerantDocument?(docName: string, sourceDocName: string): string | null;- hasFolder?(folderPath: string): boolean;+ resolveFolder?(folderPath: string): string | undefined;}export function createTolerantDocumentResolver(documentNames: Iterable<string>,): (docName: string) => string | null {- const documents = new Set(documentNames);+ const documents = asTargetNamespace('document', documentNames);const bySlug = new Map<string, string>();for (const docName of documents) {const slug = toWikiLinkSlug(docName);@@ -49,11 +59,11 @@ export function createTolerantDocumentResolver(const slug = toWikiLinkSlug(docName);const slugMatch = slug ? bySlug.get(slug) : undefined;if (slugMatch) return slugMatch;- const canonicalIndex = `${docName}/index`;- if (documents.has(canonicalIndex)) return canonicalIndex;+ const canonicalIndex = documents.resolve(`${docName}/index`);+ if (canonicalIndex !== undefined) return canonicalIndex;const leaf = docName.slice(docName.lastIndexOf('/') + 1);- const legacyFolderNote = `${docName}/${leaf}`;- if (documents.has(legacyFolderNote)) return legacyFolderNote;+ const legacyFolderNote = documents.resolve(`${docName}/${leaf}`);+ if (legacyFolderNote !== undefined) return legacyFolderNote;if (!docName.includes('/') && slug) return byBasename.get(slug) ?? null;return null;};@@ -89,22 +99,23 @@ function assessDocument(href: string,sourceDocName: string,inventory: LocalTargetInventory,- exactExists?: boolean,+ existingDocument: string | undefined,): SharedAssessment {- if (exactExists ?? inventory.hasDocument(docName)) {+ if (existingDocument !== undefined) {return {targetKind: 'document',- resolvedTarget: docName,+ resolvedTarget: existingDocument,status: 'exact',reason: null,resolutionMethod: methodForHref(href),fallbackTarget: null,};}- if (inventory.hasFolder?.(docName)) {+ const existingFolder = inventory.resolveFolder?.(docName);+ if (existingFolder !== undefined) {return {targetKind: 'document',- resolvedTarget: docName,+ resolvedTarget: existingFolder,status: 'exact',reason: null,resolutionMethod: methodForHref(href),@@ -143,10 +154,11 @@ function assessFile(if (filePath === null) {return { ...UNRESOLVABLE, targetKind: 'file' };}- if (inventory.hasFile(filePath)) {+ const existingFile = inventory.resolveFile(filePath);+ if (existingFile !== undefined) {return {targetKind: 'file',- resolvedTarget: filePath,+ resolvedTarget: existingFile,status: 'exact',reason: null,resolutionMethod: methodForHref(href),@@ -157,13 +169,76 @@ function assessFile(targetKind: 'file',resolvedTarget: filePath,status: 'missing',- reason: 'no-such-file',+ reason: inventory.isExcludedFile?.(filePath) === true ? 'excluded' : 'no-such-file',resolutionMethod: methodForHref(href),fallbackTarget: null,};}-function isWikiForm(sourceForm: OccurrenceSourceForm): boolean {+function assessWikiFile(+ assetUrl: string,+ sourceDocName: string,+ inventory: LocalTargetInventory,+): SharedAssessment | null {+ const filePath = resolveAssetProjectPath(assetUrl, '', { literal: true });+ if (filePath === null) {+ return { ...UNRESOLVABLE, targetKind: 'file' };+ }+ const existingFile = inventory.resolveFile(filePath) ?? inventory.resolveWikiFile?.(filePath);+ if (existingFile !== undefined) {+ return {+ targetKind: 'file',+ resolvedTarget: existingFile,+ status: 'exact',+ reason: null,+ resolutionMethod: 'root-relative',+ fallbackTarget: null,+ };+ }+ if (!filePath.includes('/')) {+ if (inventory.resolveFileByBasename === null) return null;+ const byBasename = inventory.resolveFileByBasename(filePath, sourceDocName);+ if (byBasename !== undefined) {+ return {+ targetKind: 'file',+ resolvedTarget: byBasename,+ status: 'exact',+ reason: null,+ resolutionMethod: 'basename',+ fallbackTarget: null,+ };+ }+ }+ if (inventory.resolveTolerantDocument?.(assetUrl, sourceDocName) != null) {+ return assessDocument(+ assetUrl,+ assetUrl,+ sourceDocName,+ inventory,+ inventory.resolveDocument(assetUrl),+ );+ }+ return {+ targetKind: 'file',+ resolvedTarget: filePath,+ status: 'missing',+ reason: inventory.isExcludedFile?.(filePath) === true ? 'excluded' : 'no-such-file',+ resolutionMethod: 'root-relative',+ fallbackTarget: null,+ };+}++export function wikiFilePath(href: string): string | null {+ return resolveAssetProjectPath(href, '', { literal: true });+}++export function wikiAssetName(occurrence: LocalTargetOccurrence): string | null {+ if (!isWikiForm(occurrence.sourceForm)) return null;+ const classified = classifyWikiLinkTarget(occurrence.href, null);+ return classified?.kind === 'asset' ? classified.url : null;+}++export function isWikiForm(sourceForm: OccurrenceSourceForm): boolean {switch (sourceForm) {case 'wiki-link':case 'wiki-embed':@@ -197,15 +272,18 @@ function assessHref(if (role === 'image' && !isWikiForm(sourceForm)) {return assessFile(href, href, sourceDocName, inventory, false);}- const documentExists = inventory.hasDocument(classified.docName);- if (!documentExists && !isWikiForm(sourceForm)) {+ const existingDocument = inventory.resolveDocument(classified.docName);+ if (existingDocument === undefined && !isWikiForm(sourceForm)) {const file = assessFile(href, href, sourceDocName, inventory, false);- if (file.status === 'exact') return file;+ if (file.reason === 'excluded') return file;+ if (file.status === 'exact' && !linkNamesDocumentFile(href, sourceDocName)) return file;}- return assessDocument(classified.docName, href, sourceDocName, inventory, documentExists);+ return assessDocument(classified.docName, href, sourceDocName, inventory, existingDocument);}case 'asset':- return assessFile(classified.url, href, sourceDocName, inventory, classified.literal);+ return isWikiForm(sourceForm)+ ? assessWikiFile(classified.url, sourceDocName, inventory)+ : assessFile(classified.url, href, sourceDocName, inventory, classified.literal);case 'external':case 'anchor':return null;@@ -252,7 +330,10 @@ export function assessLocalTargets();}-function diagnosticSourceForm(form: OccurrenceSourceForm): LocalTargetSourceForm | null {+type ProjectionSubject = Pick<LocalTargetAssessment, 'occurrence' | 'targetKind'>;++function projectedSourceForm(assessment: ProjectionSubject): LocalTargetSourceForm | null {+ const form = assessment.occurrence.sourceForm;switch (form) {case 'markdown-inline':case 'markdown-reference':@@ -260,7 +341,7 @@ function diagnosticSourceForm(form: OccurrenceSourceForm): LocalTargetSourceFormreturn form;case 'wiki-link':case 'wiki-embed':- return null;+ return assessment.targetKind === 'file' ? form : null;default: {const unreachable: never = form;return unreachable;@@ -268,8 +349,8 @@ function diagnosticSourceForm(form: OccurrenceSourceForm): LocalTargetSourceForm}}-export function isProjectableToLocalTargetSurfaces(occurrence: LocalTargetOccurrence): boolean {- return diagnosticSourceForm(occurrence.sourceForm) !== null;+export function isProjectableToLocalTargetSurfaces(assessment: ProjectionSubject): boolean {+ return projectedSourceForm(assessment) !== null;}export function buildLocalTargetEvidence(@@ -277,7 +358,7 @@ export function buildLocalTargetEvidence(reason: BrokenLinkReason,): LocalTargetDiagnosticEvidence | null {const { occurrence } = assessment;- const sourceForm = diagnosticSourceForm(occurrence.sourceForm);+ const sourceForm = projectedSourceForm(assessment);if (sourceForm === null) return null;return {href: occurrence.href,@@ -305,9 +386,8 @@ export function toForwardLinkLocalTargets(const rows: ForwardLinkLocalTarget[] = [];for (const assessment of assessments) {const { occurrence } = assessment;- if (!isProjectableToLocalTargetSurfaces(occurrence)) continue;if (assessment.targetKind !== 'file' && occurrence.role !== 'image') continue;- const sourceForm = diagnosticSourceForm(occurrence.sourceForm);+ const sourceForm = projectedSourceForm(assessment);if (sourceForm === null) continue;rows.push({role: occurrence.role,diff --git a/packages/server/src/local-target-index.test.ts b/packages/server/src/local-target-index.test.tsindex cb6f48bcc..54d6f8b37 100644--- a/packages/server/src/local-target-index.test.ts+++ b/packages/server/src/local-target-index.test.ts@@ -19,6 +19,7 @@ function createIndex(): LocalTargetIndex {function createDiskRig(overrides: Omit<LocalTargetIndexOptions, 'contentDir' | 'contentFilter'> = {},+ projectFiles: Record<string, string> = {},): {index: LocalTargetIndex;contentDir: string;@@ -27,6 +28,8 @@ function createDiskRig(const projectDir = mkdtempSync(join(tmpdir(), 'ok-lti-'));const contentDir = join(projectDir, 'content');mkdirSync(contentDir, { recursive: true });+ for (const [rel, text] of Object.entries(projectFiles))+ writeFileSync(join(projectDir, rel), text);const contentFilter = createContentFilter({ projectDir, contentDir });const index = new LocalTargetIndex({ contentDir, contentFilter, ...overrides });cleanups.push(() => {@@ -150,10 +153,16 @@ describe('LocalTargetIndex reverse-dependent freshness', () => {});});- test('wiki forms are not projected here, which is what fixes this index on the URI plane', () => {+ test('wiki document links are not projected here; file-shaped wiki embeds are, by their literal spelling', () => {const index = createIndex();index.setSource('src', 'See [[100%20done]] and ![[100%20done.png]].\n');- expect(index.getAssessments('src')).toEqual([]);+ expect(index.getAssessments('src')).toHaveLength(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ resolvedTarget: '100%20done.png',+ });+ expect(index.getFileDependents('100%20done.png')).toEqual(['src']);expect(index.getFileDependents('100 done')).toEqual([]);expect(index.getDocumentDependents('100 done')).toEqual([]);@@ -163,6 +172,77 @@ describe('LocalTargetIndex reverse-dependent freshness', () => {expect(markdownIndex.getFileDependents('100%20done')).toEqual([]);});+ test('a basename wiki embed resolves vault-wide and heals as the file comes and goes', () => {+ const index = createIndex();+ index.setSource('notes/src', 'See ![[photo.png]].\n');+ expect(index.getAssessments('notes/src')[0]).toMatchObject({+ targetKind: 'file',+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'photo.png',+ });++ expect(index.setFileTarget('media/photo.png', true)).toBe(1);+ expect(index.getAssessments('notes/src')[0]).toMatchObject({+ status: 'exact',+ reason: null,+ resolvedTarget: 'media/photo.png',+ resolutionMethod: 'basename',+ });+ expect(index.getFileDependents('media/photo.png')).toEqual(['notes/src']);++ expect(index.setFileTarget('media/photo.png', false)).toBe(1);+ expect(index.getAssessments('notes/src')[0]).toMatchObject({+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'photo.png',+ });+ });++ test('a path-form wiki embed resolves across folder case and heals as the file comes and goes', () => {+ const index = createIndex();+ index.setSource('src', 'See ![[pics/deep/x.png]] and [[PICS/DEEP/X.PNG]].\n');+ expect(statusOf(index, 'src')).toEqual(['missing', 'missing']);++ expect(index.setFileTarget('Pics/Deep/x.png', true)).toBe(1);+ expect(index.getAssessments('src').map((a) => [a.status, a.resolvedTarget])).toEqual([+ ['exact', 'Pics/Deep/x.png'],+ ['exact', 'Pics/Deep/x.png'],+ ]);+ expect(index.getFileDependents('Pics/Deep/x.png')).toEqual(['src']);++ expect(index.setFileTarget('pics/deep/x.png', true)).toBe(1);+ expect(index.getAssessments('src').map((a) => a.resolvedTarget)).toEqual([+ 'pics/deep/x.png',+ 'Pics/Deep/x.png',+ ]);++ expect(index.reconcileFileTargets([])).toBe(1);+ expect(statusOf(index, 'src')).toEqual(['missing', 'missing']);+ });++ test('a markdown asset link keeps ancestor folder case significant', () => {+ const index = createIndex();+ index.setFileTarget('Pics/Deep/x.png', true);+ index.setSource('src', '\n');+ expect(statusOf(index, 'src')).toEqual(['missing']);+ });++ test('a watcher inventory reconcile heals a basename wiki embed across spellings', () => {+ const index = createIndex();+ index.setSource('src', 'See ![[Café.png]].\n');+ expect(statusOf(index, 'src')).toEqual(['missing']);++ expect(index.reconcileFileTargets(['media/Café.png'])).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'media/Café.png',+ });++ expect(index.reconcileFileTargets([])).toBe(1);+ expect(statusOf(index, 'src')).toEqual(['missing']);+ });+test('a content-only file-update event does not flip existence or bump the generation', () => {const index = createIndex();index.setSource('src', 'Download [pdf](assets/report.pdf).\n');@@ -539,3 +619,285 @@ describe('LocalTargetIndex disk lifecycle', () => {});});});++describe('LocalTargetIndex across canonically equivalent spellings', () => {+ const NFC = 'people/Ren\u00e9';+ const NFD = 'people/Rene\u0301';++ test.each([+ ['NFC', 'NFD', NFC, NFD],+ ['NFD', 'NFC', NFD, NFC],+ ])('an %s link heals and breaks with its %s document', (_l, _d, linked, stored) => {+ const index = createIndex();+ index.setSource('src', `See [x](/${linked}).\n`);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: linked,+ });++ index.setSource(stored, '# Target\n');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: stored,+ reason: null,+ });+ expect(index.getDocumentDependents(linked)).toEqual(['src']);+ expect(index.getDocumentDependents(stored)).toEqual(['src']);++ index.removeSource(stored);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: linked,+ reason: 'no-such-doc',+ });+ });++ test('a file target reported in NFD heals an NFC link and is found by either spelling', () => {+ const index = createIndex();+ index.setSource('src', 'See [pdf](assets/Ren\u00e9.pdf).\n');++ expect(index.setFileTarget('assets/Rene\u0301.pdf', true)).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ targetKind: 'file',+ status: 'exact',+ resolvedTarget: 'assets/Rene\u0301.pdf',+ });+ expect(index.getFileDependents('assets/Ren\u00e9.pdf')).toEqual(['src']);+ expect(index.getFileDependents('assets/Rene\u0301.pdf')).toEqual(['src']);++ expect(index.setFileTarget('assets/Rene\u0301.pdf', false)).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ reason: 'no-such-file',+ resolvedTarget: 'assets/Ren\u00e9.pdf',+ });+ });++ test('folder targets resolve across spellings from the watcher and from the docs beneath', () => {+ const index = createIndex();+ index.setSource('src', 'See [folder](Ren\u00e9).\n');++ expect(index.reconcileFolderTargets(['Rene\u0301'])).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'Rene\u0301',+ });+ expect(index.reconcileFolderTargets([])).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({ status: 'missing' });++ index.setSource('Rene\u0301/notes', '# Notes\n');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'Rene\u0301',+ });+ index.removeSource('Rene\u0301/notes');+ expect(index.getAssessments('src')[0]).toMatchObject({ status: 'missing' });+ });++ test('a rebuild resolves NFC links against NFD inventory and a disk sweep stats the raw paths', async () => {+ const rig = createDiskRig();+ rig.write(+ 'source.md',+ 'See [doc](people/Ren\u00e9), [pdf](assets/Ren\u00e9.pdf) and [big](assets/Report.PDF).\n',+ );+ rig.write('people/Rene\u0301.md', '# Ren\u00e9\n');+ rig.write('assets/Rene\u0301.pdf', '%PDF-1.4\n');+ rig.write('assets/Report.PDF', '%PDF-1.4\n');+ await rig.index.rebuildFromDisk({+ documentTargets: ['source', 'people/Rene\u0301'],+ fileTargets: ['assets/Rene\u0301.pdf', 'assets/Report.PDF'],+ });+ expect(+ rig.index+ .getAssessments('source')+ .map(({ status, resolvedTarget }) => [status, resolvedTarget]),+ ).toEqual([+ ['exact', 'people/Rene\u0301'],+ ['exact', 'assets/Rene\u0301.pdf'],+ ['exact', 'assets/Report.PDF'],+ ]);++ expect(await rig.index.reconcileDependentFileTargetsFromDisk()).toBe(0);+ expect(statusOf(rig.index, 'source')).toEqual(['exact', 'exact', 'exact']);++ unlinkSync(join(rig.contentDir, 'assets/Rene\u0301.pdf'));+ expect(await rig.index.reconcileDependentFileTargetsFromDisk()).toBe(1);+ expect(rig.index.getAssessments('source')[1]).toMatchObject({+ status: 'missing',+ reason: 'no-such-file',+ });+ });+});++describe('dotted wiki names that a document can claim (PRD-8896)', () => {+ const SOURCE_MD = 'See [[acp.daemon]], ![[ACP.Daemon]] and [[vault/acp.daemon]].\n';+ const MISSING_ROWS = [+ ['notes/source', 'acp.daemon', 'file', 'missing', 'no-such-file'],+ ['notes/source', 'ACP.Daemon', 'file', 'missing', 'no-such-file'],+ ['notes/source', 'vault/acp.daemon', 'file', 'missing', 'no-such-file'],+ ];++ function rowsOf(index: LocalTargetIndex): Array<Array<string | null>> {+ return index+ .getAssessmentsForSources()+ .flatMap(({ source, assessments }) =>+ assessments.map((a) => [source, a.occurrence.href, a.targetKind, a.status, a.reason]),+ );+ }++ const documentMutations: Array<+ [string, (index: LocalTargetIndex, docNames: string[], created: boolean) => void]+ > = [+ [+ 'a source event',+ (index, _docNames, created) =>+ created+ ? index.setSource('vault/acp.daemon', '# ACP\n')+ : index.removeSource('vault/acp.daemon'),+ ],+ ['a document reconcile', (index, docNames) => index.reconcileDocumentTargets(docNames)],+ ];++ for (const [label, mutate] of documentMutations) {+ test(`creating the document after the link matches a rebuild: ${label}`, async () => {+ const rig = createDiskRig();+ rig.write('notes/source.md', SOURCE_MD);+ await rig.index.rebuildFromDisk({ documentTargets: ['notes/source'], fileTargets: [] });+ expect(rowsOf(rig.index)).toEqual(MISSING_ROWS);++ rig.write('vault/acp.daemon.md', '# ACP\n');+ const docNames = ['notes/source', 'vault/acp.daemon'];+ mutate(rig.index, docNames, true);+ const incremental = rowsOf(rig.index);+ await rig.index.rebuildFromDisk({ documentTargets: docNames, fileTargets: [] });+ expect(incremental).toEqual(rowsOf(rig.index));+ expect(incremental).toEqual([]);+ });++ test(`deleting the document after the link matches a rebuild: ${label}`, async () => {+ const rig = createDiskRig();+ rig.write('notes/source.md', SOURCE_MD);+ rig.write('vault/acp.daemon.md', '# ACP\n');+ await rig.index.rebuildFromDisk({+ documentTargets: ['notes/source', 'vault/acp.daemon'],+ fileTargets: [],+ });+ expect(rowsOf(rig.index)).toEqual([]);++ unlinkSync(join(rig.contentDir, 'vault/acp.daemon.md'));+ const docNames = ['notes/source'];+ mutate(rig.index, docNames, false);+ const incremental = rowsOf(rig.index);+ await rig.index.rebuildFromDisk({ documentTargets: docNames, fileTargets: [] });+ expect(incremental).toEqual(rowsOf(rig.index));+ expect(incremental).toEqual(MISSING_ROWS);+ });+ }+});++describe('rows the index keeps only to track dependencies (PRD-8896)', () => {+ const HIDDEN_ONLY = 'See [[acp.daemon]].\n';++ test('a change to hidden rows alone does not move the generation', () => {+ const index = createIndex();+ index.setSource('vault/acp.daemon', '# ACP\n');+ index.setSource('notes/source', HIDDEN_ONLY);+ expect(index.getAssessmentsForSources()).toEqual([]);+ const generation = index.generation;++ expect(index.setSource('acp.daemon', '# Root\n')).toBe(false);+ expect(index.setSource('notes/source', 'See [[acp.daemon]] and [[acp.daemon]].\n')).toBe(false);+ expect(index.removeSource('notes/source')).toBe(false);+ expect(index.generation).toBe(generation);+ });++ test('a rebuild over hidden rows alone reports nothing and does not move the generation', async () => {+ const rig = createDiskRig();+ rig.write('vault/acp.daemon.md', '# ACP\n');+ rig.write('notes/source.md', HIDDEN_ONLY);+ const inventory = { documentTargets: [], fileTargets: [] };++ expect(await rig.index.rebuildFromDisk(inventory)).toEqual({ sources: 0, occurrences: 0 });+ expect(rig.index.getDocumentDependents('vault/acp.daemon')).toEqual(['notes/source']);+ const generation = rig.index.generation;++ expect(await rig.index.rebuildFromDisk(inventory)).toEqual({ sources: 0, occurrences: 0 });+ expect(rig.index.generation).toBe(generation);+ });++ test('stats count only the rows the index returns', () => {+ const withHidden = createIndex();+ const withoutHidden = createIndex();+ for (const index of [withHidden, withoutHidden]) index.setSource('vault/acp.daemon', '# ACP\n');+ withHidden.setSource('notes/source', 'See [[acp.daemon]] and [x](target).\n');+ withHidden.setSource('notes/other', HIDDEN_ONLY);+ withoutHidden.setSource('notes/source', 'See [x](target).\n');++ const returned = withHidden.getAssessmentsForSources();+ expect(withHidden.getStats()).toEqual(withoutHidden.getStats());+ expect(withHidden.getStats()).toMatchObject({+ sources: returned.length,+ occurrences: returned.flatMap(({ assessments }) => assessments).length,+ });+ });+});++describe('file targets that exist but are excluded by ignore rules (PRD-8896)', () => {+ const IGNORED_SOURCE = [+ '[d](ignored/ig.png)',+ '',+ '[m](ignored/missing.png)',+ '[m2](media/missing.png)',+ ].join('\n');++ function reasonsOf(index: LocalTargetIndex): Array<[string | null, string, string | null]> {+ return index.getAssessments('src').map((a) => [a.resolvedTarget, a.status, a.reason]);+ }++ test('a file on disk under a .gitignore rule reports excluded; missing files stay no-such-file', () => {+ const rig = createDiskRig({}, { '.gitignore': 'ignored/\n' });+ rig.write('ignored/ig.png', 'png');+ rig.index.setSource('src', IGNORED_SOURCE);+ expect(reasonsOf(rig.index)).toEqual([+ ['ignored/ig.png', 'missing', 'excluded'],+ ['ignored/ig.png', 'missing', 'excluded'],+ ['ignored/missing.png', 'missing', 'no-such-file'],+ ['media/missing.png', 'missing', 'no-such-file'],+ ]);+ });++ test('a file on disk under a .okignore rule reports excluded', () => {+ const rig = createDiskRig({}, { '.okignore': 'ignored/\n' });+ rig.write('ignored/ig.png', 'png');+ rig.index.setSource('src', '[d](ignored/ig.png)\n');+ expect(reasonsOf(rig.index)).toEqual([['ignored/ig.png', 'missing', 'excluded']]);+ });++ test('without a content filter the probe is inert and the file stays no-such-file', () => {+ const index = createIndex();+ index.setSource('src', '[d](ignored/ig.png)\n');+ expect(reasonsOf(index)).toEqual([['ignored/ig.png', 'missing', 'no-such-file']]);+ });++ test('a built-in exclusion a "!" rule cannot lift stays no-such-file (control)', () => {+ const rig = createDiskRig();+ rig.write('node_modules/pkg/logo.png', 'png');+ rig.write('.env', 'SECRET=1');+ rig.index.setSource('src', '[n](node_modules/pkg/logo.png)\n[s](.env)\n');+ expect(reasonsOf(rig.index)).toEqual([+ ['node_modules/pkg/logo.png', 'missing', 'no-such-file'],+ ['.env', 'missing', 'no-such-file'],+ ]);+ });++ test('a file under a built-in skip folder stays no-such-file even when an ignore file also matches it', () => {+ const rig = createDiskRig({}, { '.okignore': 'build/\noutput/\n' });+ rig.write('build/diagram.png', 'png');+ rig.write('output/chart.png', 'png');+ rig.index.setSource('src', '[b](build/diagram.png)\n[o](output/chart.png)\n');+ expect(reasonsOf(rig.index)).toEqual([+ ['build/diagram.png', 'missing', 'no-such-file'],+ ['output/chart.png', 'missing', 'no-such-file'],+ ]);+ });+});diff --git a/packages/server/src/local-target-index.ts b/packages/server/src/local-target-index.tsindex 61f15a748..a5d42b186 100644--- a/packages/server/src/local-target-index.ts+++ b/packages/server/src/local-target-index.ts@@ -1,10 +1,20 @@-import { type Dirent, existsSync } from 'node:fs';+import { type Dirent, existsSync, statSync } from 'node:fs';import { readdir, readFile, realpath, stat } from 'node:fs/promises';import { isAbsolute, join, relative, resolve } from 'node:path';import {+ addDocumentFolders,+ type BasenameIndex,classifyMarkdownHref,+ createBasenameIndex,+ createTargetNamespace,+ createWikiAssetResolver,+ type IdentityKey,+ identityKey,+ leafKey,+ type MutableTargetNamespace,resolveAssetProjectPath,toWikiLinkSlug,+ wikiAssetPathKey,} from '@inkeep/open-knowledge-core';import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';import type { ContentFilter } from './content-filter.ts';@@ -17,18 +27,58 @@ import {isProjectableToLocalTargetSurfaces,type LocalTargetAssessment,type LocalTargetInventory,+ wikiAssetName,+ wikiFilePath,} from './local-target-assessment.ts';import { extractLocalTargetOccurrences } from './local-target-occurrences.ts';-import { toPosix } from './path-utils.ts';+import { isWithinDir, toPosix } from './path-utils.ts';function projectableAssessments(assessments: readonly LocalTargetAssessment[],): LocalTargetAssessment[] {- return assessments.filter((assessment) =>- isProjectableToLocalTargetSurfaces(assessment.occurrence),+ return assessments.filter((assessment) => isProjectableToLocalTargetSurfaces(assessment));+}++function maintainedAssessments(+ assessments: readonly LocalTargetAssessment[],+): LocalTargetAssessment[] {+ return assessments.filter(+ (assessment) =>+ isProjectableToLocalTargetSurfaces(assessment) ||+ wikiAssetName(assessment.occurrence) !== null,);}+function basenameIndexOf(files: Iterable<string>): BasenameIndex {+ const index = createBasenameIndex();+ for (const file of files) index.add(file);+ return index;+}++function fileBasenameDependencyKey(relativePath: string): string {+ return `file-basename:${leafKey('file', relativePath.slice(relativePath.lastIndexOf('/') + 1))}`;+}++function wikiFileFoldDependencyKey(relativePath: string): string {+ return `wiki-file:${wikiAssetPathKey(relativePath)}`;+}++function wikiAssetDependencyKeys(assessment: LocalTargetAssessment): string[] {+ const name = wikiAssetName(assessment.occurrence);+ if (name === null) return [];+ const filePath = wikiFilePath(assessment.occurrence.href);+ if (filePath === null) return [];+ const keys = [+ filePath.includes('/')+ ? wikiFileFoldDependencyKey(filePath)+ : fileBasenameDependencyKey(filePath),+ ];+ if (assessment.targetKind === 'file' && assessment.status === 'missing') {+ keys.push(...tolerantDependencyKeys(name));+ }+ return keys;+}+export interface LocalTargetSourceAssessments {source: string;assessments: readonly LocalTargetAssessment[];@@ -59,6 +109,23 @@ export interface LocalTargetRebuildInventory {folderTargets?: Iterable<string>;}+export function isExcludedFileOnDisk(+ contentDir: string,+ contentFilter: ContentFilter | undefined,+ contentRootRelativePath: string,+): boolean {+ if (contentFilter === undefined) return false;+ if (!contentFilter.isExcludedByIgnoreFiles(contentRootRelativePath)) return false;+ if (contentFilter.isPathIgnored(contentRootRelativePath, { bypassFilters: true })) return false;+ const candidate = resolve(contentDir, contentRootRelativePath);+ if (!isWithinDir(candidate, contentDir)) return false;+ try {+ return statSync(candidate).isFile();+ } catch {+ return false;+ }+}+function assessmentTargetDeps(assessment: LocalTargetAssessment,sourceDocName: string,@@ -86,7 +153,11 @@ function assessmentTargetDeps(return { docs, files };}-function addReverseEdge(reverse: Map<string, Set<string>>, target: string, source: string): void {+function addReverseEdge<K extends string>(+ reverse: Map<K, Set<string>>,+ target: K,+ source: string,+): void {let sources = reverse.get(target);if (!sources) {sources = new Set();@@ -95,9 +166,9 @@ function addReverseEdge(reverse: Map<string, Set<string>>, target: string, sourcsources.add(source);}-function removeReverseEdge(- reverse: Map<string, Set<string>>,- target: string,+function removeReverseEdge<K extends string>(+ reverse: Map<K, Set<string>>,+ target: K,source: string,): void {const sources = reverse.get(target);@@ -111,10 +182,14 @@ function tolerantDependencyKeys(docName: string): string[] {const slug = toWikiLinkSlug(docName);if (slug) keys.push(`slug:${slug}`);if (!docName.includes('/') && slug) keys.push(`basename:${slug}`);- keys.push(`folder:${docName}`);+ keys.push(folderDependencyKey(docName));return keys;}+function folderDependencyKey(folderPath: string): string {+ return `folder:${identityKey('folder', folderPath)}`;+}+function documentMutationKeys(docName: string): string[] {const keys: string[] = [];const slug = toWikiLinkSlug(docName);@@ -124,12 +199,28 @@ function documentMutationKeys(docName: string): string[] {if (leafSlug) keys.push(`basename:${leafSlug}`);let slash = docName.indexOf('/');while (slash !== -1) {- keys.push(`folder:${docName.slice(0, slash)}`);+ keys.push(folderDependencyKey(docName.slice(0, slash)));slash = docName.indexOf('/', slash + 1);}return keys;}+function syncReverseEdges<K extends string>(+ reverse: Map<K, Set<string>>,+ previous: ReadonlySet<K> | undefined,+ next: ReadonlySet<K>,+ source: string,+): void {+ if (previous) {+ for (const target of previous) {+ if (!next.has(target)) removeReverseEdge(reverse, target, source);+ }+ }+ for (const target of next) {+ if (!previous?.has(target)) addReverseEdge(reverse, target, source);+ }+}+function assessmentsEqual(left: readonly LocalTargetAssessment[],right: readonly LocalTargetAssessment[],@@ -171,31 +262,42 @@ export class LocalTargetIndex {private readonly readDirectory: (dir: string) => Promise<Dirent[]>;private sourceAssessments = new Map<string, LocalTargetAssessment[]>();- private sourceDocDeps = new Map<string, Set<string>>();+ private sourceDocKeys = new Map<string, Set<IdentityKey<'document'>>>();private sourceFileDeps = new Map<string, Set<string>>();- private reverseByDoc = new Map<string, Set<string>>();- private reverseByFile = new Map<string, Set<string>>();+ private sourceFileKeys = new Map<string, Set<IdentityKey<'file'>>>();+ private reverseByDoc = new Map<IdentityKey<'document'>, Set<string>>();+ private reverseByFile = new Map<IdentityKey<'file'>, Set<string>>();private reverseByTolerant = new Map<string, Set<string>>();private sourceTolerantDeps = new Map<string, Set<string>>();- private documents = new Set<string>();+ private documents: MutableTargetNamespace<'document'> = createTargetNamespace('document');private tolerantDocumentResolver: (docName: string) => string | null = () => null;- private files = new Set<string>();+ private files: MutableTargetNamespace<'file'> = createTargetNamespace('file');+ private fileBasenames: BasenameIndex = createBasenameIndex();+ private wikiFileResolver: ((relativePath: string) => string | undefined) | null = null;private generationValue = 0;private freshnessEpoch = 0;private readyValue = false;private closed = false;- private folderPaths = new Set<string>();- private injectedFolderPaths = new Set<string>();+ private folderPaths: MutableTargetNamespace<'folder'> = createTargetNamespace('folder');+ private injectedFolderPaths: MutableTargetNamespace<'folder'> = createTargetNamespace('folder');private readonly inventory: LocalTargetInventory = {- hasDocument: (docName) => this.documents.has(docName),- hasFile: (relativePath) => this.files.has(relativePath),+ resolveDocument: (docName) => this.documents.resolve(docName),+ resolveFile: (relativePath) => this.files.resolve(relativePath),+ resolveFileByBasename: (basename, sourceDocName) =>+ this.fileBasenames.resolveEmbed(basename, sourceDocName) ?? undefined,+ resolveWikiFile: (relativePath) => {+ this.wikiFileResolver ??= createWikiAssetResolver(this.files);+ return this.wikiFileResolver(relativePath);+ },+ isExcludedFile: (relativePath) =>+ isExcludedFileOnDisk(this.contentDir, this.contentFilter, relativePath),resolveTolerantDocument: (docName) => this.tolerantDocumentResolver(docName),- hasFolder: (folderPath) =>- this.folderPaths.has(folderPath) || this.injectedFolderPaths.has(folderPath),+ resolveFolder: (folderPath) =>+ this.folderPaths.resolve(folderPath) ?? this.injectedFolderPaths.resolve(folderPath),};constructor(options: LocalTargetIndexOptions) {@@ -227,21 +329,22 @@ export class LocalTargetIndex {}getAssessments(docName: string): readonly LocalTargetAssessment[] {- return this.sourceAssessments.get(docName) ?? [];+ return projectableAssessments(this.sourceAssessments.get(docName) ?? []);}getAssessmentsForSources(sourceDocNames?: readonly string[]): LocalTargetSourceAssessments[] {const filter = sourceDocNames && sourceDocNames.length > 0 ? new Set(sourceDocNames) : null;const out: LocalTargetSourceAssessments[] = [];- for (const [source, assessments] of this.sourceAssessments) {+ for (const [source, stored] of this.sourceAssessments) {if (filter && !filter.has(source)) continue;- out.push({ source, assessments });+ const assessments = projectableAssessments(stored);+ if (assessments.length > 0) out.push({ source, assessments });}return out;}getDocumentDependents(docName: string): string[] {- const sources = new Set(this.reverseByDoc.get(docName) ?? []);+ const sources = new Set(this.reverseByDoc.get(identityKey('document', docName)) ?? []);for (const key of documentMutationKeys(docName)) {for (const source of this.reverseByTolerant.get(key) ?? []) sources.add(source);}@@ -249,17 +352,32 @@ export class LocalTargetIndex {}getFileDependents(relativePath: string): string[] {- return [...(this.reverseByFile.get(relativePath) ?? [])].sort((a, b) => a.localeCompare(b));+ return [...(this.reverseByFile.get(identityKey('file', relativePath)) ?? [])].sort((a, b) =>+ a.localeCompare(b),+ );}getStats(): LocalTargetIndexStats {+ let sources = 0;let occurrences = 0;- for (const assessments of this.sourceAssessments.values()) occurrences += assessments.length;+ const documentTargets = new Set<IdentityKey<'document'>>();+ const fileTargets = new Set<IdentityKey<'file'>>();+ for (const [source, stored] of this.sourceAssessments) {+ const assessments = projectableAssessments(stored);+ if (assessments.length === 0) continue;+ sources++;+ occurrences += assessments.length;+ for (const assessment of assessments) {+ const { docs, files } = assessmentTargetDeps(assessment, source);+ for (const doc of docs) documentTargets.add(identityKey('document', doc));+ for (const file of files) fileTargets.add(identityKey('file', file));+ }+ }return {- sources: this.sourceAssessments.size,+ sources,occurrences,- documentTargets: this.reverseByDoc.size,- fileTargets: this.reverseByFile.size,+ documentTargets: documentTargets.size,+ fileTargets: fileTargets.size,};}@@ -279,18 +397,21 @@ export class LocalTargetIndex {if (becameDocument) this.refreshTolerantDocumentIndexes();const occurrences = extractLocalTargetOccurrences(markdown);- const assessments = projectableAssessments(+ const assessments = maintainedAssessments(assessLocalTargetOccurrences(occurrences, docName, this.inventory),);- const sourceChanged = !assessmentsEqual(previous, assessments);- if (sourceChanged) this.applySourceAssessments(docName, assessments);+ if (!assessmentsEqual(previous, assessments)) {+ this.applySourceAssessments(docName, assessments);+ }+ const projectable = projectableAssessments(assessments);+ const sourceChanged = !assessmentsEqual(projectableAssessments(previous), projectable);const healed = becameDocument ? this.reassessDocumentDependents(docName) : 0;const changed = sourceChanged || healed > 0;if (changed) this.generationValue++;return {changed,- occurrences: assessments.length,+ occurrences: projectable.length,affectedSources: healed + (sourceChanged ? 1 : 0),};},@@ -308,7 +429,9 @@ export class LocalTargetIndex {'local-target','document-target',() => {- const occurrences = this.sourceAssessments.get(docName)?.length ?? 0;+ const occurrences = projectableAssessments(+ this.sourceAssessments.get(docName) ?? [],+ ).length;const hadOccurrences = occurrences > 0;const wasDocument = this.documents.delete(docName);if (wasDocument) this.refreshTolerantDocumentIndexes();@@ -342,8 +465,14 @@ export class LocalTargetIndex {'local-target','file-target',() => {- if (exists) this.files.add(relativePath);- else this.files.delete(relativePath);+ if (exists) {+ this.files.add(relativePath);+ this.fileBasenames.add(relativePath);+ } else {+ this.files.delete(relativePath);+ this.fileBasenames.remove(relativePath);+ }+ this.wikiFileResolver = null;const occurrences = this.countFileOccurrences(relativePath);const affected = this.reassessFileDependents(relativePath);if (affected > 0) this.generationValue++;@@ -358,7 +487,7 @@ export class LocalTargetIndex {}reconcileDocumentTargets(documentTargets: Iterable<string>): number {- const next = new Set(documentTargets);+ const next = createTargetNamespace('document', documentTargets);const changedIdentities = new Set<string>();for (const docName of this.documents) {if (!next.has(docName)) changedIdentities.add(docName);@@ -370,7 +499,9 @@ export class LocalTargetIndex {const affected = new Set<string>();for (const docName of changedIdentities) {- for (const source of this.reverseByDoc.get(docName) ?? []) affected.add(source);+ for (const source of this.reverseByDoc.get(identityKey('document', docName)) ?? []) {+ affected.add(source);+ }for (const key of documentMutationKeys(docName)) {for (const source of this.reverseByTolerant.get(key) ?? []) affected.add(source);}@@ -386,7 +517,7 @@ export class LocalTargetIndex {}reconcileFolderTargets(folderTargets: Iterable<string>): number {- const next = new Set(folderTargets);+ const next = createTargetNamespace('folder', folderTargets);const changedFolders = new Set<string>();for (const folderPath of this.injectedFolderPaths) {if (!next.has(folderPath)) changedFolders.add(folderPath);@@ -398,7 +529,7 @@ export class LocalTargetIndex {const affected = new Set<string>();for (const folderPath of changedFolders) {- for (const source of this.reverseByTolerant.get(`folder:${folderPath}`) ?? []) {+ for (const source of this.reverseByTolerant.get(folderDependencyKey(folderPath)) ?? []) {affected.add(source);}}@@ -412,7 +543,7 @@ export class LocalTargetIndex {}reconcileFileTargets(fileTargets: Iterable<string>): number {- const next = new Set(fileTargets);+ const next = createTargetNamespace('file', fileTargets);const changedIdentities = new Set<string>();for (const relativePath of this.files) {if (!next.has(relativePath)) changedIdentities.add(relativePath);@@ -430,9 +561,11 @@ export class LocalTargetIndex {let occurrences = 0;for (const relativePath of changedIdentities) {occurrences += this.countFileOccurrences(relativePath);- for (const source of this.reverseByFile.get(relativePath) ?? []) affected.add(source);+ for (const source of this.fileDependents(relativePath)) affected.add(source);}this.files = next;+ this.fileBasenames = basenameIndexOf(next);+ this.wikiFileResolver = null;let reassessed = 0;for (const source of affected) {if (this.reassessSource(source)) reassessed++;@@ -450,7 +583,11 @@ export class LocalTargetIndex {async reconcileDependentFileTargetsFromDisk(onChange?: (relativePath: string, exists: boolean) => void,): Promise<number> {- const targets = [...this.reverseByFile.keys()];+ const requested = new Set<string>();+ for (const paths of this.sourceFileDeps.values()) {+ for (const relativePath of paths) requested.add(relativePath);+ }+ const targets = [...requested];const existence = await Promise.all(targets.map((relativePath) => this.isAdmittedFileOnDisk(relativePath)),);@@ -484,12 +621,12 @@ export class LocalTargetIndex {}private countFileOccurrences(relativePath: string): number {+ const key = identityKey('file', relativePath);let occurrences = 0;- for (const source of this.reverseByFile.get(relativePath) ?? []) {- for (const assessment of this.sourceAssessments.get(source) ?? []) {- if (assessmentTargetDeps(assessment, source).files.includes(relativePath)) {- occurrences++;- }+ for (const source of this.reverseByFile.get(key) ?? []) {+ for (const assessment of projectableAssessments(this.sourceAssessments.get(source) ?? [])) {+ const { files } = assessmentTargetDeps(assessment, source);+ if (files.some((file) => identityKey('file', file) === key)) occurrences++;}}return occurrences;@@ -511,7 +648,7 @@ export class LocalTargetIndex {private async rebuildOnce(inventory: LocalTargetRebuildInventory,): Promise<LocalTargetRebuildResult> {- const hadContent = this.sourceAssessments.size > 0;+ const hadContent = this.hasProjectableRows();this.freshnessEpoch++;this.readyValue = false;const staged = new LocalTargetIndex({@@ -523,8 +660,9 @@ export class LocalTargetIndex {const result = await staged.populateFromDisk(inventory);this.sourceAssessments = staged.sourceAssessments;- this.sourceDocDeps = staged.sourceDocDeps;+ this.sourceDocKeys = staged.sourceDocKeys;this.sourceFileDeps = staged.sourceFileDeps;+ this.sourceFileKeys = staged.sourceFileKeys;this.reverseByDoc = staged.reverseByDoc;this.reverseByFile = staged.reverseByFile;this.reverseByTolerant = staged.reverseByTolerant;@@ -534,16 +672,28 @@ export class LocalTargetIndex {this.folderPaths = staged.folderPaths;this.injectedFolderPaths = staged.injectedFolderPaths;this.files = staged.files;+ this.fileBasenames = staged.fileBasenames;+ this.wikiFileResolver = null;this.readyValue = true;- if (hadContent || this.sourceAssessments.size > 0) this.generationValue++;+ if (hadContent || this.hasProjectableRows()) this.generationValue++;return result;}+ private hasProjectableRows(): boolean {+ for (const stored of this.sourceAssessments.values()) {+ if (stored.some((assessment) => isProjectableToLocalTargetSurfaces(assessment))) return true;+ }+ return false;+ }+private async populateFromDisk(inventory: LocalTargetRebuildInventory,): Promise<LocalTargetRebuildResult> {for (const docName of inventory.documentTargets) this.documents.add(docName);- for (const relativePath of inventory.fileTargets) this.files.add(relativePath);+ for (const relativePath of inventory.fileTargets) {+ this.files.add(relativePath);+ this.fileBasenames.add(relativePath);+ }for (const folderPath of inventory.folderTargets ?? []) {this.injectedFolderPaths.add(folderPath);}@@ -558,6 +708,7 @@ export class LocalTargetIndex {for (const { docName } of docs) this.documents.add(docName);this.refreshTolerantDocumentIndexes();+ let sourceCount = 0;let occurrenceCount = 0;const BATCH_SIZE = 50;for (let i = 0; i < docs.length && !this.closed; i += BATCH_SIZE) {@@ -571,26 +722,32 @@ export class LocalTargetIndex {for (const result of results) {if (isLinkIndexExcludedDoc(result.docName)) continue;const occurrences = extractLocalTargetOccurrences(result.markdown);- const assessments = projectableAssessments(+ const assessments = maintainedAssessments(assessLocalTargetOccurrences(occurrences, result.docName, this.inventory),);this.applySourceAssessments(result.docName, assessments);- occurrenceCount += assessments.length;+ const projectable = projectableAssessments(assessments).length;+ if (projectable > 0) sourceCount++;+ occurrenceCount += projectable;}}this.readyValue = true;- return { sources: this.sourceAssessments.size, occurrences: occurrenceCount };+ return { sources: sourceCount, occurrences: occurrenceCount };}private applySourceAssessments(docName: string, assessments: LocalTargetAssessment[]): void {- const nextDocDeps = new Set<string>();+ const nextDocKeys = new Set<IdentityKey<'document'>>();const nextFileDeps = new Set<string>();+ const nextFileKeys = new Set<IdentityKey<'file'>>();const nextTolerantDeps = new Set<string>();for (const assessment of assessments) {const { docs, files } = assessmentTargetDeps(assessment, docName);- for (const doc of docs) nextDocDeps.add(doc);- for (const file of files) nextFileDeps.add(file);+ for (const doc of docs) nextDocKeys.add(identityKey('document', doc));+ for (const file of files) {+ nextFileDeps.add(file);+ nextFileKeys.add(identityKey('file', file));+ }if (assessment.targetKind === 'document' &&assessment.resolvedTarget !== null &&@@ -600,48 +757,30 @@ export class LocalTargetIndex {nextTolerantDeps.add(key);}}+ for (const key of wikiAssetDependencyKeys(assessment)) nextTolerantDeps.add(key);}- const prevDocDeps = this.sourceDocDeps.get(docName);- if (prevDocDeps) {- for (const target of prevDocDeps) {- if (!nextDocDeps.has(target)) removeReverseEdge(this.reverseByDoc, target, docName);- }- }- for (const target of nextDocDeps) {- if (!prevDocDeps?.has(target)) addReverseEdge(this.reverseByDoc, target, docName);- }-- const prevFileDeps = this.sourceFileDeps.get(docName);- if (prevFileDeps) {- for (const target of prevFileDeps) {- if (!nextFileDeps.has(target)) removeReverseEdge(this.reverseByFile, target, docName);- }- }- for (const target of nextFileDeps) {- if (!prevFileDeps?.has(target)) addReverseEdge(this.reverseByFile, target, docName);- }-- const prevTolerantDeps = this.sourceTolerantDeps.get(docName);- if (prevTolerantDeps) {- for (const key of prevTolerantDeps) {- if (!nextTolerantDeps.has(key)) removeReverseEdge(this.reverseByTolerant, key, docName);- }- }- for (const key of nextTolerantDeps) {- if (!prevTolerantDeps?.has(key)) addReverseEdge(this.reverseByTolerant, key, docName);- }+ syncReverseEdges(this.reverseByDoc, this.sourceDocKeys.get(docName), nextDocKeys, docName);+ syncReverseEdges(this.reverseByFile, this.sourceFileKeys.get(docName), nextFileKeys, docName);+ syncReverseEdges(+ this.reverseByTolerant,+ this.sourceTolerantDeps.get(docName),+ nextTolerantDeps,+ docName,+ );if (assessments.length === 0) {this.sourceAssessments.delete(docName);- this.sourceDocDeps.delete(docName);+ this.sourceDocKeys.delete(docName);this.sourceFileDeps.delete(docName);+ this.sourceFileKeys.delete(docName);this.sourceTolerantDeps.delete(docName);return;}this.sourceAssessments.set(docName, assessments);- this.sourceDocDeps.set(docName, nextDocDeps);+ this.sourceDocKeys.set(docName, nextDocKeys);this.sourceFileDeps.set(docName, nextFileDeps);+ this.sourceFileKeys.set(docName, nextFileKeys);this.sourceTolerantDeps.set(docName, nextTolerantDeps);}@@ -652,11 +791,11 @@ export class LocalTargetIndex {const next = assessLocalTargetOccurrences(occurrences, docName, this.inventory);if (assessmentsEqual(assessments, next)) return false;this.applySourceAssessments(docName, next);- return true;+ return !assessmentsEqual(projectableAssessments(assessments), projectableAssessments(next));}private reassessDocumentDependents(docName: string): number {- const affected = new Set(this.reverseByDoc.get(docName) ?? []);+ const affected = new Set(this.reverseByDoc.get(identityKey('document', docName)) ?? []);for (const key of documentMutationKeys(docName)) {for (const source of this.reverseByTolerant.get(key) ?? []) affected.add(source);}@@ -667,10 +806,18 @@ export class LocalTargetIndex {return changed;}+ private fileDependents(relativePath: string): Set<string> {+ const sources = new Set(this.reverseByFile.get(identityKey('file', relativePath)) ?? []);+ const byBasename = this.reverseByTolerant.get(fileBasenameDependencyKey(relativePath));+ for (const source of byBasename ?? []) sources.add(source);+ const byWikiFold = this.reverseByTolerant.get(wikiFileFoldDependencyKey(relativePath));+ for (const source of byWikiFold ?? []) sources.add(source);+ return sources;+ }+private reassessFileDependents(relativePath: string): number {- const affected = [...(this.reverseByFile.get(relativePath) ?? [])];let changed = 0;- for (const source of affected) {+ for (const source of this.fileDependents(relativePath)) {if (this.reassessSource(source)) changed += 1;}return changed;@@ -678,15 +825,7 @@ export class LocalTargetIndex {private refreshTolerantDocumentIndexes(): void {this.tolerantDocumentResolver = createTolerantDocumentResolver(this.documents);- const folderPaths = new Set<string>();- for (const docName of this.documents) {- let slash = docName.indexOf('/');- while (slash !== -1) {- folderPaths.add(docName.slice(0, slash));- slash = docName.indexOf('/', slash + 1);- }- }- this.folderPaths = folderPaths;+ this.folderPaths = addDocumentFolders(createTargetNamespace('folder'), this.documents);}private async listDocsWithPaths(): Promise<Array<{ docName: string; filePath: string }>> {diff --git a/packages/server/src/local-target-inventory.test.ts b/packages/server/src/local-target-inventory.test.tsindex 8c54c0f37..8462f6421 100644--- a/packages/server/src/local-target-inventory.test.ts+++ b/packages/server/src/local-target-inventory.test.ts@@ -1,7 +1,11 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test } from 'vitest';import type { AllFileEntries, FileIndexEntry, FolderIndexEntry } from './file-watcher.ts';import {+ createFileExistsOracle,+ createTrackedFileResolver,localTargetInventoryFromIndexes,localTargetInventoryFromWatcher,} from './local-target-inventory.ts';@@ -209,3 +213,109 @@ describe('localTargetInventoryFromIndexes', () => {expect(changed?.documentTargets).toEqual([]);});});++describe('createTrackedFileResolver', () => {+ const contentDir = '/project/content';+ const CAFE_NFD = 'assets/Café.png'.normalize('NFD');+ const CAFE_NFC = 'assets/Café.png'.normalize('NFC');++ function watcherOver(allFiles: Map<string, FileIndexEntry>, generation: () => number) {+ return {+ getAllFilesIndex: () => allFiles,+ getFileIndexGeneration: generation,+ getFolderAliasIndex: () => new Map<string, string>(),+ };+ }++ test('resolves a requested spelling to the tracked raw file under the file identity rule', () => {+ const allFiles = new Map<string, FileIndexEntry>([+ [CAFE_NFD, entry('file', join(contentDir, CAFE_NFD))],+ ['Pics/Deep/x.png', entry('file', join(contentDir, 'Pics/Deep/x.png'))],+ ['notes', entry('markdown', join(contentDir, 'notes.md'))],+ ]);+ const watcher = watcherOver(allFiles, () => 1);+ const resolve = createTrackedFileResolver(() =>+ localTargetInventoryFromWatcher(watcher, contentDir),+ );++ expect(resolve(CAFE_NFC)).toBe(CAFE_NFD);+ expect(resolve(CAFE_NFD)).toBe(CAFE_NFD);+ expect(resolve('assets/CAFÉ.PNG')).toBe(CAFE_NFD);+ expect(resolve('Pics/Deep/X.PNG')).toBe('Pics/Deep/x.png');+ expect(resolve('pics/deep/x.png')).toBeUndefined();+ expect(resolve('notes.md')).toBeUndefined();+ expect(resolve('missing.png')).toBeUndefined();+ });++ test('follows the watcher inventory as its generation changes', () => {+ const allFiles = new Map<string, FileIndexEntry>();+ let generation = 1;+ const watcher = watcherOver(allFiles, () => generation);+ const resolve = createTrackedFileResolver(() =>+ localTargetInventoryFromWatcher(watcher, contentDir),+ );+ expect(resolve(CAFE_NFC)).toBeUndefined();++ allFiles.set(CAFE_NFD, entry('file', join(contentDir, CAFE_NFD)));+ generation++;+ expect(resolve(CAFE_NFC)).toBe(CAFE_NFD);++ allFiles.delete(CAFE_NFD);+ generation++;+ expect(resolve(CAFE_NFC)).toBeUndefined();+ });++ test('resolves nothing while the watcher inventory is unavailable', () => {+ expect(createTrackedFileResolver(() => null)('assets/photo.png')).toBeUndefined();+ });+});++describe('createFileExistsOracle', () => {+ const roots: string[] = [];+ afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+ });++ function project(): string {+ const root = mkdtempSync(join(tmpdir(), 'ok-file-exists-'));+ roots.push(root);+ mkdirSync(join(root, 'Sub'));+ writeFileSync(join(root, 'Sub', 'page.md'), '# Page\n');+ writeFileSync(join(root, 'Makefile'), 'all:\n');+ return root;+ }++ test('accepts a tracked file and an untracked regular file on disk', () => {+ const exists = createFileExistsOracle(['assets/logo.png'], project(), undefined);+ expect(exists('assets/logo.png')).toBe(true);+ expect(exists('Makefile')).toBe(true);+ expect(exists('missing.txt')).toBe(false);+ });++ test('never accepts a directory as an existing file', () => {+ const exists = createFileExistsOracle([], project(), undefined);+ expect(exists('Sub')).toBe(false);+ expect(exists('Sub/')).toBe(false);+ });++ test('refuses an ignored path', () => {+ const exists = createFileExistsOracle([], project(), {+ isPathIgnored: (path) => path === 'Makefile',+ });+ expect(exists('Makefile')).toBe(false);+ });++ test('refuses an existing file outside the content root, directly or through a symlink', () => {+ const outer = mkdtempSync(join(tmpdir(), 'ok-file-exists-outer-'));+ roots.push(outer);+ const root = join(outer, 'content');+ mkdirSync(root);+ writeFileSync(join(outer, 'outside.txt'), 'secret\n');+ symlinkSync(join(outer, 'outside.txt'), join(root, 'escape.txt'));+ const exists = createFileExistsOracle([], root, undefined);+ expect(existsSync(join(root, '..', 'outside.txt'))).toBe(true);+ expect(existsSync(join(root, 'escape.txt'))).toBe(true);+ expect(exists('../outside.txt')).toBe(false);+ expect(exists('escape.txt')).toBe(false);+ });+});diff --git a/packages/server/src/local-target-inventory.ts b/packages/server/src/local-target-inventory.tsindex 93afb85c2..4ee1f3fad 100644--- a/packages/server/src/local-target-inventory.ts+++ b/packages/server/src/local-target-inventory.ts@@ -1,4 +1,12 @@-import { isAbsolute, relative } from 'node:path';+import { realpathSync, statSync } from 'node:fs';+import { isAbsolute, relative, resolve } from 'node:path';+import {+ asTargetNamespace,+ createBasenameIndex,+ createTargetNamespace,+ createWikiAssetResolver,+} from '@inkeep/open-knowledge-core';+import type { ContentFilter } from './content-filter.ts';import { stripDocExtension } from './doc-extensions.ts';import {type AllFileEntries,@@ -6,7 +14,10 @@ import {fileIndexEntryMembers,type WatcherHandle,} from './file-watcher.ts';-import { toPosix } from './path-utils.ts';+import { getLogger } from './logger.ts';+import { isWithinDir, toPosix } from './path-utils.ts';++const log = getLogger('local-target-inventory');export interface WatcherLocalTargetInventory {documentTargets: readonly string[];@@ -110,3 +121,76 @@ export function localTargetInventoryFromIndexes(folderTargets: [...folderTargets],};}++type FileTargetResolver = (relativePath: string) => string | undefined;++function createInventoryFileResolver(+ getInventory: () => WatcherLocalTargetInventory | null,+ build: (fileTargets: readonly string[]) => FileTargetResolver,+): FileTargetResolver {+ let source: readonly string[] | null = null;+ let resolveTarget: FileTargetResolver = () => undefined;+ return (relativePath) => {+ const inventory = getInventory();+ if (inventory === null) return undefined;+ if (inventory.fileTargets !== source) {+ source = inventory.fileTargets;+ resolveTarget = build(source);+ }+ return resolveTarget(relativePath);+ };+}++export function createTrackedFileResolver(+ getInventory: () => WatcherLocalTargetInventory | null,+): FileTargetResolver {+ return createInventoryFileResolver(getInventory, (fileTargets) => {+ const files = createTargetNamespace('file', fileTargets);+ return (relativePath) => files.resolve(relativePath);+ });+}++export function createTrackedWikiFileResolver(+ getInventory: () => WatcherLocalTargetInventory | null,+): FileTargetResolver {+ return createInventoryFileResolver(getInventory, createWikiAssetResolver);+}++export function createFileBasenameResolver(+ fileTargets: Iterable<string>,+): (basename: string, sourceDocName: string) => string | undefined {+ const index = createBasenameIndex();+ for (const file of fileTargets) index.add(file);+ return (basename, sourceDocName) => index.resolveEmbed(basename, sourceDocName) ?? undefined;+}++export function createFileExistsOracle(+ fileTargets: Iterable<string>,+ contentDir: string,+ contentFilter: Pick<ContentFilter, 'isPathIgnored'> | undefined,+): (contentRootRelativePath: string) => boolean {+ const admittedFiles = asTargetNamespace('file', fileTargets);+ const canonicalContentDir = realpathSync(contentDir);+ return (contentRootRelativePath) => {+ if (admittedFiles.resolve(contentRootRelativePath) !== undefined) return true;+ if (contentFilter?.isPathIgnored(contentRootRelativePath)) return false;++ const candidate = resolve(contentDir, contentRootRelativePath);+ if (!isWithinDir(candidate, contentDir)) return false;+ try {+ const canonicalCandidate = realpathSync(candidate);+ return (+ isWithinDir(canonicalCandidate, canonicalContentDir) &&+ statSync(canonicalCandidate).isFile()+ );+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.debug(+ { err, candidate },+ 'linked-file existence fallback could not canonicalize; treating as absent',+ );+ }+ return false;+ }+ };+}diff --git a/packages/server/src/managed-rename-rewrite.test.ts b/packages/server/src/managed-rename-rewrite.test.tsindex 9fbdecc7f..999ed7f19 100644--- a/packages/server/src/managed-rename-rewrite.test.ts+++ b/packages/server/src/managed-rename-rewrite.test.ts@@ -6,6 +6,7 @@ import {} from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {+ canonicalDocNameBeforeRename,createWikiRenameContext,rewriteAssetReferencesForRename,rewriteJsxSrcRefsForDocumentRename,@@ -1213,3 +1214,44 @@ describe('rewriteWikiLinksForDocumentRename — escaped alias separators insideexpect(dataRowCellCount(result.markdown)).toBe(1);});});++describe('rename rewrites across canonically equivalent spellings', () => {+ const NFC = 'people/Ren\u00e9';+ const NFD = 'people/Rene\u0301';++ test('a markdown link spelled in NFC follows the NFD document it resolves to', () => {+ const context = createWikiRenameContext(['notes', NFD], new Map([[NFD, 'archive/Rene\u0301']]));+ const canonical = canonicalDocNameBeforeRename(context);+ expect(+ rewriteMarkdownLinksForDocumentRename(+ `See [R](./${NFC}.md#bio) and [[${NFC}]].\n`,+ 'notes',+ NFD,+ 'archive/Rene\u0301',+ canonical,+ ),+ ).toEqual({+ markdown: `See [R](./archive/Rene%CC%81.md#bio) and [[${NFC}]].\n`,+ rewrites: 1,+ });+ });++ test('without a before-rename lookup the comparison stays exact', () => {+ expect(+ rewriteMarkdownLinksForDocumentRename(`See [R](./${NFC}.md).\n`, 'notes', NFD, 'moved'),+ ).toEqual({ markdown: `See [R](./${NFC}.md).\n`, rewrites: 0 });+ });++ test('a JSX src-ref spelled in NFC follows the NFD board it resolves to', () => {+ const context = createWikiRenameContext(['notes', NFD], new Map([[NFD, 'archive/Rene\u0301']]));+ expect(+ rewriteJsxSrcRefsForDocumentRename(+ `<Excalidraw src="/${NFC}" />\n`,+ 'notes',+ NFD,+ 'archive/Rene\u0301',+ canonicalDocNameBeforeRename(context),+ ),+ ).toEqual({ markdown: '<Excalidraw src="/archive/Rene\u0301" />\n', rewrites: 1 });+ });+});diff --git a/packages/server/src/managed-rename-rewrite.ts b/packages/server/src/managed-rename-rewrite.tsindex 83763c21b..f6b5a7660 100644--- a/packages/server/src/managed-rename-rewrite.ts+++ b/packages/server/src/managed-rename-rewrite.ts@@ -8,6 +8,7 @@ import {rawSegmentOr,resolveAssetProjectPath,resolveInternalHref,+ resolveName,resolveSkillBundleWikiTarget,resolveWikiLinkTargetDocName,type WikiLinkLookupIndex,@@ -403,11 +404,16 @@ function recomputeRelativeMarkdownHref(return `${relativePath}${querySuffix}${hashSuffix}`;}+export type CanonicalDocName = (docName: string) => string;++const exactDocName: CanonicalDocName = (docName) => docName;+function rewriteMarkdownLinksInLine(line: string,sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName,): RenameRewriteResult {let rewritten = '';let rewrites = 0;@@ -470,7 +476,7 @@ function rewriteMarkdownLinksInLine(const markdownLink = readMarkdownLink(line, idx);if (markdownLink) {const resolved = resolveInternalHref(markdownLink.href, sourceDocName);- if (resolved?.docName === oldDocName) {+ if (resolved !== null && canonical(resolved.docName) === oldDocName) {const nextHref = recomputeRelativeMarkdownHref(markdownLink.href,sourceDocName,@@ -685,8 +691,16 @@ function rewriteJsxSrcAttrValue(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName,): string | null {- const next = computeNextJsxSrcAttrValue(spec, value, sourceDocName, oldDocName, newDocName);+ const next = computeNextJsxSrcAttrValue(+ spec,+ value,+ sourceDocName,+ oldDocName,+ newDocName,+ canonical,+ );if (next !== null && /["'<>]/.test(next)) return null;return next;}@@ -697,17 +711,19 @@ function computeNextJsxSrcAttrValue(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName,): string | null {if (spec.resolution === 'bare-doc-name') {- return value === oldDocName ? newDocName : null;+ return canonical(value) === oldDocName ? newDocName : null;}const resolved = resolveJsxSrcRefTarget(spec, value, sourceDocName);if (resolved === null) return null;+ const pointsAtRenamed = canonical(resolved) === oldDocName;const isContainingDocMove = sourceDocName === oldDocName && oldDocName !== newDocName;- if (resolved !== oldDocName && !isContainingDocMove) return null;- const target = resolved === oldDocName ? newDocName : resolved;+ if (!pointsAtRenamed && !isContainingDocMove) return null;+ const target = pointsAtRenamed ? newDocName : resolved;if (value.startsWith('/')) {- return resolved === oldDocName ? `/${target}` : null;+ return pointsAtRenamed ? `/${target}` : null;}const anchorDocName = isContainingDocMove ? newDocName : sourceDocName;const candidate = relativeJsxSrcRef(anchorDocName, target, value);@@ -721,6 +737,7 @@ function rewriteJsxSrcRefsInLine(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName,): RenameRewriteResult {let rewritten = '';let rewrites = 0;@@ -753,6 +770,7 @@ function rewriteJsxSrcRefsInLine(sourceDocName,oldDocName,newDocName,+ canonical,);if (nextValue === null) return whole;rewrites++;@@ -776,6 +794,7 @@ export function rewriteJsxSrcRefsForDocumentRename(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName = exactDocName,): RenameRewriteResult {let fence: FenceState | null = null;let rewrites = 0;@@ -795,7 +814,13 @@ export function rewriteJsxSrcRefsForDocumentRename(return `${line}${ending}`;}- const rewrittenLine = rewriteJsxSrcRefsInLine(line, sourceDocName, oldDocName, newDocName);+ const rewrittenLine = rewriteJsxSrcRefsInLine(+ line,+ sourceDocName,+ oldDocName,+ newDocName,+ canonical,+ );rewrites += rewrittenLine.rewrites;return `${rewrittenLine.markdown}${ending}`;})@@ -822,6 +847,10 @@ export function createWikiRenameContext(return { before, after, renames };}+export function canonicalDocNameBeforeRename(context: WikiRenameContext): CanonicalDocName {+ return (docName) => resolveName(context.before.pages, docName) ?? docName;+}+function resolveRenameWikiTarget(target: string,sourceDocName: string,@@ -922,6 +951,7 @@ export function rewriteMarkdownLinksForDocumentRename(sourceDocName: string,oldDocName: string,newDocName: string,+ canonical: CanonicalDocName = exactDocName,): RenameRewriteResult {let fence: FenceState | null = null;let rewrites = 0;@@ -941,7 +971,13 @@ export function rewriteMarkdownLinksForDocumentRename(return `${line}${ending}`;}- const rewrittenLine = rewriteMarkdownLinksInLine(line, sourceDocName, oldDocName, newDocName);+ const rewrittenLine = rewriteMarkdownLinksInLine(+ line,+ sourceDocName,+ oldDocName,+ newDocName,+ canonical,+ );rewrites += rewrittenLine.rewrites;return `${rewrittenLine.markdown}${ending}`;})diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.tsindex fbe29e731..f7cc2a765 100644--- a/packages/server/src/mcp/tools/shared.ts+++ b/packages/server/src/mcp/tools/shared.ts@@ -94,7 +94,7 @@ export const previewAttachWarningField = zconst brokenLinksOutputField = z.array(BrokenLinkSchema).describe(- 'Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.',+ 'Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.',);const brokenLinkSuppressionOutputField = BrokenLinkSuppressionSchema.optional().describe(diff --git a/packages/server/src/project-wiki-link-lookup.ts b/packages/server/src/project-wiki-link-lookup.tsindex 75a6f21ae..ab931e87f 100644--- a/packages/server/src/project-wiki-link-lookup.ts+++ b/packages/server/src/project-wiki-link-lookup.ts@@ -1,4 +1,5 @@import {+ asTargetNamespace,buildPagesByBasenameIndex,buildPagesBySlugIndex,parseGlobalSkillBundleDoc,@@ -7,7 +8,7 @@ import {} from '@inkeep/open-knowledge-core';export function buildProjectWikiLinkLookup(docNames: Iterable<string>): WikiLinkLookupIndex {- const pages = new Set(docNames);+ const pages = asTargetNamespace('document', docNames);const projectPages = new Set([...pages].filter((page) => !parseGlobalSkillBundleDoc(page)));return {pages,diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 8e142c38c..78a7e1da8 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -292,6 +292,56 @@ describe('createServer() — agent-session cap passthrough', () => {});});+describe('createServer() — wiki embed target resolution', () => {+ let projectDir: string;+ let server: ServerInstance | null;++ beforeEach(() => {+ projectDir = mkdtempSync(resolve(tmpdir(), 'ok-wiki-embed-'));+ server = null;+ });++ afterEach(async () => {+ await server?.destroy();+ rmSync(projectDir, { recursive: true, force: true });+ });++ test('a path-form image embed renders the tracked file it resolves to by wiki rules', async () => {+ const contentDir = mkdtempSync(resolve(projectDir, 'content-'));+ mkdirSync(join(contentDir, 'Pics', 'Deep'), { recursive: true });+ writeFileSync(join(contentDir, 'Pics', 'Deep', 'x.png'), 'png');+ mkdirSync(join(contentDir, 'assets'), { recursive: true });+ writeFileSync(join(contentDir, 'assets', 'Cre\u0300me.png'), 'png');+ writeFileSync(join(contentDir, 'wiki.md'), '# Wiki\n\n![[pics/deep/x.png]]\n');+ server = createServer({ contentDir, projectDir, quiet: true });+ await server.ready;++ expect(server.resolveEmbed('pics/deep/x.png', 'wiki.md')).toBe('Pics/Deep/x.png');+ expect(server.resolveEmbed('PICS/Deep/X.PNG', 'wiki.md')).toBe('Pics/Deep/x.png');+ expect(server.resolveEmbed('assets/CR\u00c8ME.PNG', 'wiki.md')).toBe('assets/Cre\u0300me.png');+ expect(server.resolveEmbed('pics/deep/nope.png', 'wiki.md')).toBeNull();++ const conn = await server.hocuspocus.openDirectConnection('wiki');+ try {+ const embedSrc = (): unknown => {+ const fragment = server?.hocuspocus.documents.get('wiki')?.getXmlFragment('default');+ for (const node of fragment?.toArray() ?? []) {+ if (!(node instanceof Y.XmlElement) || node.nodeName !== 'jsxComponent') continue;+ const props = node.getAttribute('props') as unknown as+ | Record<string, unknown>+ | undefined;+ return props?.src;+ }+ return undefined;+ };+ await vi.waitFor(() => expect(embedSrc()).not.toBeUndefined(), { timeout: 5_000 });+ expect(embedSrc()).toBe('/Pics/Deep/x.png');+ } finally {+ conn.disconnect();+ }+ });+});+describe('createServer() — derived-index branch lifecycle', () => {let projectDir: string;let git: ReturnType<typeof simpleGit>;diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex aef311ac0..c736639b8 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -191,7 +191,12 @@ import {import type { LinkAdvisoryPolicy } from './link-advisory-policy.ts';import { ensureOkfSchemaFiles } from './lint/write-okf-schemas.ts';import { createLiveDerivedIndexExtension } from './live-derived-index.ts';-import { localTargetInventoryFromWatcher } from './local-target-inventory.ts';+import { wikiFilePath } from './local-target-assessment.ts';+import {+ createTrackedFileResolver,+ createTrackedWikiFileResolver,+ localTargetInventoryFromWatcher,+} from './local-target-inventory.ts';import { getLogger } from './logger.ts';import { LossCaptureRing } from './loss-capture.ts';import {@@ -377,6 +382,7 @@ export interface ServerInstance {readonly conflicts: ConflictAuthority;readonly getLinkPreviewsEnabled: () => boolean;readonly resolveEmbed: (basename: string, sourcePath: string) => string | null;+ readonly resolveTrackedFile: (relativePath: string) => string | undefined;readonly acpRegistry: AcpRegistry;readonly acpPermissions: AcpPermissionStore;}@@ -990,11 +996,23 @@ export function createServer(options: ServerOptions): ServerInstance {const basenameIndex: BasenameIndex = createBasenameIndex();- const resolveEmbed = (basename: string, sourcePath: string): string | null =>- basenameIndex.resolveEmbed(basename, sourcePath);+ const resolveTrackedFile = createTrackedFileResolver(() =>+ localTargetInventoryFromWatcher(watcher, contentDir),+ );+ const resolveTrackedWikiFile = createTrackedWikiFileResolver(() =>+ localTargetInventoryFromWatcher(watcher, contentDir),+ );++ const resolveEmbed = (target: string, sourcePath: string): string | null => {+ const wikiPath = wikiFilePath(target);+ if (wikiPath === null || !wikiPath.includes('/')) {+ return basenameIndex.resolveEmbed(target, sourcePath);+ }+ return resolveTrackedWikiFile(wikiPath) ?? null;+ };const resolveSize = (basename: string, sourcePath: string): number | null => {- let candidatePath: string | null = basenameIndex.resolveEmbed(basename, sourcePath);+ let candidatePath: string | null = resolveEmbed(basename, sourcePath);if (!candidatePath && basename.includes('/')) {candidatePath = basename.replace(/^\.?\//, '');}@@ -2179,6 +2197,7 @@ export function createServer(options: ServerOptions): ServerInstance {getFolderIndex: () => (watcher ? watcher.getFolderIndex() : new Map()),getAliasMap: () => (watcher ? watcher.getAliasMap() : new Map()),getFolderAliasIndex: () => (watcher ? watcher.getFolderAliasIndex() : new Map()),+ resolveTrackedFile,rescanFiles: () => watcher?.rescanFromDisk(),enableTestRoutes,shadowRef,@@ -4626,6 +4645,7 @@ export function createServer(options: ServerOptions): ServerInstance {conflicts,getLinkPreviewsEnabled: readLinkPreviewsEnabled,resolveEmbed,+ resolveTrackedFile,acpRegistry,acpPermissions,};diff --git a/packages/server/src/services/assets.ts b/packages/server/src/services/assets.tsindex e8c03b208..35095eeb8 100644--- a/packages/server/src/services/assets.ts+++ b/packages/server/src/services/assets.ts@@ -97,12 +97,20 @@ export interface AssetServiceDeps {contentDir: string;isPathIgnored?: (relativePath: string) => boolean;getAttachmentFolderPath?: () => string;+ resolveTrackedFile?: (relativePath: string) => string | undefined;}type CanonicalResolution =| { ok: true; canonicalPath: string; relativePath: string; size: number }| { ok: false; reason: 'not-found' | 'invalid-path'; cause?: unknown };+function isServableAssetType(path: string): boolean {+ return (+ assetContentTypeForPath(path) !== null &&+ ASSET_EXTENSIONS.has(extname(path).slice(1).toLowerCase())+ );+}+const GENERIC_PASTE_NAMES = /^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;export function resolveUploadDestDir(@@ -227,6 +235,18 @@ export function createAssetService(deps: AssetServiceDeps): AssetService {return { ok: true, canonicalPath, relativePath, size: stat.size };}+ function resolveExactOrTracked(assetPath: string): CanonicalResolution {+ const exact = resolveCanonical(assetPath);+ if (exact.ok || exact.reason !== 'not-found') return exact;+ const requested = assetPath.split('\\').join('/');+ const tracked = deps.resolveTrackedFile?.(requested);+ if (tracked === undefined || tracked === requested || deps.isPathIgnored?.(tracked)) {+ return exact;+ }+ const resolved = resolveCanonical(tracked);+ return resolved.ok ? resolved : exact;+ }+async function storeUpload(input: StoreUploadInput): Promise<StoreUploadOutcome> {const { tempPath, sha, byteLength, filename, parentDocName, placement } = input;@@ -385,16 +405,19 @@ export function createAssetService(deps: AssetServiceDeps): AssetService {if (!requestedPath || requestedPath.includes('\0')) {return { ok: false, reason: 'missing-path' };}- const contentType = assetContentTypeForPath(requestedPath);- const ext = extname(requestedPath).slice(1).toLowerCase();- if (!contentType || !ASSET_EXTENSIONS.has(ext)) {+ if (!isServableAssetType(requestedPath)) {return { ok: false, reason: 'unsupported-type' };}- const core = resolveCanonical(requestedPath);+ const core = resolveExactOrTracked(requestedPath);if (!core.ok) return core;if (deps.isPathIgnored?.(core.relativePath)) {return { ok: false, reason: 'not-found' };}+ const contentType = assetContentTypeForPath(core.relativePath);+ const ext = extname(core.relativePath).slice(1).toLowerCase();+ if (!contentType || !ASSET_EXTENSIONS.has(ext)) {+ return { ok: false, reason: 'unsupported-type' };+ }return {ok: true,asset: {@@ -411,7 +434,7 @@ export function createAssetService(deps: AssetServiceDeps): AssetService {if (!requestedPath || requestedPath.includes('\0')) {return { ok: false, reason: 'missing-path' };}- const core = resolveCanonical(requestedPath);+ const core = resolveExactOrTracked(requestedPath);if (!core.ok) return core;return { ok: true, canonicalPath: core.canonicalPath, size: core.size };},diff --git a/packages/server/src/write-advisory-links.test.ts b/packages/server/src/write-advisory-links.test.tsindex 8923f7a7e..bd2d026fd 100644--- a/packages/server/src/write-advisory-links.test.ts+++ b/packages/server/src/write-advisory-links.test.ts@@ -1,5 +1,25 @@import { describe, expect, test } from 'vitest';-import { computeWriteAdvisoryLinks, type WriteAdvisoryLink } from './write-advisory-links.ts';+import {+ computeWriteAdvisoryLinks,+ type WriteAdvisoryLink,+ type WriteAdvisoryTargets,+} from './write-advisory-links.ts';++const NO_TARGETS: WriteAdvisoryTargets = {+ fileExists: null,+ folderExists: null,+ fileExcluded: null,+ resolveWikiFile: null,+ resolveFileByBasename: null,+};++const NOTHING_TRACKED: WriteAdvisoryTargets = {+ fileExists: () => false,+ folderExists: () => false,+ fileExcluded: () => false,+ resolveWikiFile: () => undefined,+ resolveFileByBasename: () => undefined,+};function fileOracle(...paths: string[]): (rel: string) => boolean {const set = new Set(paths);@@ -9,21 +29,43 @@ function fileOracle(...paths: string[]): (rel: string) => boolean {describe('computeWriteAdvisoryLinks', () => {test('a folder oracle exempts wiki and inline links to existing folders (both planes)', () => {const md = 'See [[assets]] and [dir](./assets) and [[missing-folder]].';+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NO_TARGETS,+ folderExists: (folderPath) => folderPath === 'assets',+ });+ expect(links.map((link) => link.href)).toEqual(['[[missing-folder]]']);+ });++ test('NFC links to NFD documents and folders are not advisory', () => {+ const md = 'See [r](people/Ren\u00e9.md), [[people/Ren\u00e9]] and [dir](Ren\u00e9).';const links = computeWriteAdvisoryLinks(md,'notes',- new Set<string>(),- undefined,- (folderPath) => folderPath === 'assets',+ new Set(['people/Rene\u0301', 'Rene\u0301/inner']),+ { ...NOTHING_TRACKED, fileExists: fileOracle() },);- expect(links.map((link) => link.href)).toEqual(['[[missing-folder]]']);+ expect(links).toEqual([]);+ });++ test('a wiki asset target resolves across folder case through the wiki file resolver', () => {+ const md = 'See ![[pics/deep/x.png]], [[PICS/Deep/X.png]] and ![[pics/deep/nope.png]].\n';+ const tracked: Record<string, string> = { 'pics/deep/x.png': 'Pics/Deep/x.png' };+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle('Pics/Deep/x.png'),+ resolveWikiFile: (rel) => tracked[rel.toLowerCase()],+ });+ expect(links.map((link) => link.href)).toEqual(['pics/deep/nope.png']);});test('reports graph-shaped links (doc, file, wiki) with no evidence, exactly as before', () => {const md = ['See [guide](./guide) and [data](./data.csv).', 'A [[Ghost]] wiki reference.'].join('\n',);- const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([{ href: './guide', resolvedTo: 'guide', reason: 'no-such-doc' },{ href: './data.csv', resolvedTo: 'data.csv', reason: 'no-such-file' },@@ -33,12 +75,10 @@ describe('computeWriteAdvisoryLinks', () => {});test('adds a missing Markdown image as a file finding with local-target evidence', () => {- const links = computeWriteAdvisoryLinks(- '\n',- 'notes',- new Set<string>(),- fileOracle(),- );+ const links = computeWriteAdvisoryLinks('\n', 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([{href: './logo.png',@@ -62,7 +102,7 @@ describe('computeWriteAdvisoryLinks', () => {'<img src="./banner.png" alt="banner">\n','notes',new Set<string>(),- fileOracle(),+ { ...NOTHING_TRACKED, fileExists: fileOracle() },);expect(links).toHaveLength(1);expect(links[0]?.localTarget).toEqual({@@ -78,7 +118,10 @@ describe('computeWriteAdvisoryLinks', () => {test('adds a reference-style target once, pointing at its shared definition', () => {const md = ['See [the spec][spec] and [again][spec].', '', '[spec]: ./spec.pdf'].join('\n');- const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([{href: './spec.pdf',@@ -100,7 +143,10 @@ describe('computeWriteAdvisoryLinks', () => {test('preserves a reference-style document fallback target without blessing it exact', () => {const md = ['See [the guide][guide].', '', '[guide]: guide'].join('\n');- const links = computeWriteAdvisoryLinks(md, 'source', new Set(['Guide']), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'source', new Set(['Guide']), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([{@@ -123,12 +169,10 @@ describe('computeWriteAdvisoryLinks', () => {});test('does not report an image whose target exists', () => {- const links = computeWriteAdvisoryLinks(- '\n',- 'notes',- new Set<string>(),- fileOracle('ok.png'),- );+ const links = computeWriteAdvisoryLinks('\n', 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle('ok.png'),+ });expect(links).toEqual([]);});@@ -137,7 +181,7 @@ describe('computeWriteAdvisoryLinks', () => {'\n','notes',new Set<string>(),- fileOracle('anything'),+ { ...NOTHING_TRACKED, fileExists: fileOracle('anything') },);expect(links).toEqual([{@@ -162,7 +206,7 @@ describe('computeWriteAdvisoryLinks', () => {'[x](./both.png) and \n','notes',new Set<string>(),- fileOracle(),+ { ...NOTHING_TRACKED, fileExists: fileOracle() },);expect(links).toHaveLength(2);expect(links[0]).toEqual({@@ -178,7 +222,7 @@ describe('computeWriteAdvisoryLinks', () => {'[](./target.md)','notes',new Set<string>(),- fileOracle(),+ { ...NOTHING_TRACKED, fileExists: fileOracle() },);expect(links).toHaveLength(2);@@ -195,16 +239,22 @@ describe('computeWriteAdvisoryLinks', () => {'<pre>[raw](./raw.pdf)</pre>',].join('\n');- expect(computeWriteAdvisoryLinks(markdown, 'notes', new Set<string>(), fileOracle())).toEqual(- [],- );+ expect(+ computeWriteAdvisoryLinks(markdown, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ }),+ ).toEqual([]);});test('preserves separate reference definitions that share one missing href', () => {const md = ['[a][one] and [b][two]', '', '[one]: ./missing.pdf', '[two]: ./missing.pdf'].join('\n',);- const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toHaveLength(2);expect(links.map((link) => link.localTarget?.definition)).toEqual([@@ -215,29 +265,34 @@ describe('computeWriteAdvisoryLinks', () => {test('dedups repeated uses of the same shared reference definition', () => {const md = '[a][same] and [b][same]\n\n[same]: ./missing.pdf';- const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toHaveLength(1);expect(links[0]?.localTarget?.definition).toEqual({ line: 2, label: 'same' });});test('does not re-report an inline document link the graph scan already covered', () => {- const links = computeWriteAdvisoryLinks(- '[guide](./guide)\n',- 'notes',- new Set<string>(),- fileOracle(),- );+ const links = computeWriteAdvisoryLinks('[guide](./guide)\n', 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([{ href: './guide', resolvedTo: 'guide', reason: 'no-such-doc' }]);});- test('without a filesystem oracle, skips file/image findings but keeps document findings', () => {+ test('without a filesystem oracle, judges only document links that cannot name a file', () => {const links = computeWriteAdvisoryLinks(- '[g](./g) and \n',+ '[g](./g), [m](./Makefile), [r][g], [[w]], <Mirror src="m" /> and \n\n[g]: ./g\n','notes',new Set<string>(),+ { ...NOTHING_TRACKED, fileExists: null },);- expect(links).toEqual([{ href: './g', resolvedTo: 'g', reason: 'no-such-doc' }]);+ expect(links).toEqual([+ { href: '[[w]]', resolvedTo: 'w', reason: 'no-such-doc' },+ { href: 'm', resolvedTo: 'm', reason: 'no-such-doc', sourceForm: 'jsx' },+ ]);});test('does not report a resolved link/image mix (all targets exist)', () => {@@ -245,7 +300,7 @@ describe('computeWriteAdvisoryLinks', () => {'[home](./home.md) and \n','notes',new Set(['home']),- fileOracle('pic.png'),+ { ...NOTHING_TRACKED, fileExists: fileOracle('pic.png') },);expect(links).toEqual([]);});@@ -255,7 +310,7 @@ describe('computeWriteAdvisoryLinks', () => {'<Excalidraw src="board.excalidraw" />\n','notes/index',new Set<string>(),- fileOracle(),+ { ...NOTHING_TRACKED, fileExists: fileOracle() },);expect(links).toEqual([{@@ -272,7 +327,7 @@ describe('computeWriteAdvisoryLinks', () => {'<Excalidraw src="board.excalidraw" /> and <Mirror src="api-spec" anchor="x" />\n','notes/index',new Set(['api-spec']),- fileOracle('notes/board.excalidraw'),+ { ...NOTHING_TRACKED, fileExists: fileOracle('notes/board.excalidraw') },);expect(links).toEqual([]);});@@ -281,7 +336,10 @@ describe('computeWriteAdvisoryLinks', () => {const md = ['<!-- [b](board.excalidraw) -->', '<Excalidraw src="board.excalidraw" />', ''].join('\n',);- const links = computeWriteAdvisoryLinks(md, 'notes/index', new Set<string>(), fileOracle());+ const links = computeWriteAdvisoryLinks(md, 'notes/index', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExists: fileOracle(),+ });expect(links).toEqual([expect.objectContaining({href: 'board.excalidraw',@@ -292,3 +350,85 @@ describe('computeWriteAdvisoryLinks', () => {]);});});++describe('file targets that exist but are excluded by ignore rules (PRD-8896)', () => {+ test('reports excluded on both the graph plane and the evidence plane; missing stays no-such-file', () => {+ const excluded = new Set(['ig.png']);+ const links = computeWriteAdvisoryLinks(+ '[d](./ig.png)\n\n[m](./missing.png)\n',+ 'notes',+ new Set<string>(),+ { ...NOTHING_TRACKED, fileExists: fileOracle(), fileExcluded: (rel) => excluded.has(rel) },+ );+ expect(links).toEqual([+ { href: './ig.png', resolvedTo: 'ig.png', reason: 'excluded' },+ { href: './missing.png', resolvedTo: 'missing.png', reason: 'no-such-file' },+ {+ href: './ig.png',+ resolvedTo: 'ig.png',+ reason: 'excluded',+ localTarget: {+ href: './ig.png',+ targetKind: 'file',+ role: 'image',+ sourceForm: 'markdown-inline',+ resolvedTarget: 'ig.png',+ reason: 'excluded',+ resolutionMethod: 'source-relative',+ },+ },+ ] satisfies WriteAdvisoryLink[]);+ });++ test('a Markdown link naming no document is judged as the file it names', () => {+ const links = computeWriteAdvisoryLinks(+ '[m](./Makefile), [n](./ignored/NOTICE) and [g](./gone)\n',+ 'notes',+ new Set<string>(),+ {+ ...NOTHING_TRACKED,+ fileExists: fileOracle('Makefile'),+ fileExcluded: (rel) => rel === 'ignored/NOTICE',+ },+ );+ expect(links).toEqual([+ { href: './ignored/NOTICE', resolvedTo: 'ignored/NOTICE', reason: 'excluded' },+ { href: './gone', resolvedTo: 'gone', reason: 'no-such-doc' },+ ] satisfies WriteAdvisoryLink[]);+ });++ test('without the exclusion probe a file missing from the list gets no verdict', () => {+ const links = computeWriteAdvisoryLinks('[d](./ig.png)\n', 'notes', new Set<string>(), {+ ...NOTHING_TRACKED,+ fileExcluded: null,+ });+ expect(links).toEqual([]);+ });+});++describe('a null capability gives the targets it judges no verdict, never missing (PRD-8896)', () => {+ const rows: Array<[keyof WriteAdvisoryTargets, string, string[]]> = [+ ['fileExists', 'See  and [m](./Makefile).\n', ['./Makefile', './i.png']],+ ['folderExists', 'See [dir](./assets) and [[assets]].\n', ['./assets', '[[assets]]']],+ [+ 'fileExcluded',+ 'See [d](./ig.png),  and [m](./Makefile).\n',+ ['./ig.png', './Makefile', './ig.png'],+ ],+ ['resolveWikiFile', 'See ![[Images/cat.png]].\n', ['Images/cat.png']],+ ['resolveFileByBasename', 'See ![[cat.png]].\n', ['cat.png']],+ ];++ test('every capability has a row', () => {+ expect(rows.map(([capability]) => capability).sort()).toEqual(Object.keys(NO_TARGETS).sort());+ });++ for (const [capability, md, reportedWhenNothingIsTracked] of rows) {+ test(`${capability}: null withholds what an oracle that knows nothing would report`, () => {+ const hrefs = (targets: WriteAdvisoryTargets): string[] =>+ computeWriteAdvisoryLinks(md, 'notes', new Set<string>(), targets).map((link) => link.href);+ expect(hrefs(NOTHING_TRACKED)).toEqual(reportedWhenNothingIsTracked);+ expect(hrefs({ ...NOTHING_TRACKED, [capability]: null })).toEqual([]);+ });+ }+});diff --git a/packages/server/src/write-advisory-links.ts b/packages/server/src/write-advisory-links.tsindex f63a920d4..577ea050f 100644--- a/packages/server/src/write-advisory-links.ts+++ b/packages/server/src/write-advisory-links.ts@@ -1,40 +1,81 @@-import type { LocalTargetDiagnosticEvidence } from '@inkeep/open-knowledge-core';+import {+ addDocumentFolders,+ asTargetNamespace,+ createTargetNamespace,+ type LocalTargetDiagnosticEvidence,+} from '@inkeep/open-knowledge-core';import { type BrokenOutboundLink, computeBrokenOutboundLinks } from './backlink-index.ts';import {assessLocalTargets,buildLocalTargetEvidence,createTolerantDocumentResolver,+ isWikiForm,+ type LocalTargetAssessment,type LocalTargetInventory,+ wikiAssetName,} from './local-target-assessment.ts';export interface WriteAdvisoryLink extends BrokenOutboundLink {localTarget?: LocalTargetDiagnosticEvidence;}+export interface WriteAdvisoryTargets {+ fileExists: ((contentRootRelativePath: string) => boolean) | null;+ folderExists: ((folderPath: string) => boolean) | null;+ fileExcluded: ((contentRootRelativePath: string) => boolean) | null;+ resolveWikiFile: ((contentRootRelativePath: string) => string | undefined) | null;+ resolveFileByBasename: ((basename: string, sourceDocName: string) => string | undefined) | null;+}++interface VerdictSubject {+ reason: WriteAdvisoryLink['reason'];+ targetKind: LocalTargetAssessment['targetKind'] | null;+ wikiAsset: boolean;+ mayNameFile: boolean;+}++function hasVerdict(targets: WriteAdvisoryTargets, subject: VerdictSubject): boolean {+ const { reason, targetKind } = subject;+ const filesKnown = targets.fileExists !== null && targets.fileExcluded !== null;+ switch (reason) {+ case 'no-such-doc':+ return targets.folderExists !== null && (!subject.mayNameFile || filesKnown);+ case 'no-such-file':+ return filesKnown && (!subject.wikiAsset || targets.resolveWikiFile !== null);+ case 'excluded':+ return filesKnown;+ case 'unresolvable':+ return targetKind !== 'file' || targets.fileExists !== null;+ default: {+ const unreachable: never = reason;+ return unreachable;+ }+ }+}+export function computeWriteAdvisoryLinks(markdown: string,sourceDocName: string,admittedDocs: Iterable<string>,- fileExists?: (contentRootRelativePath: string) => boolean,- folderExists?: (folderPath: string) => boolean,+ targets: WriteAdvisoryTargets,): WriteAdvisoryLink[] {- const admitted = admittedDocs instanceof Set ? admittedDocs : new Set(admittedDocs);+ const fileExists = targets.fileExists ?? undefined;+ const fileExcluded = targets.fileExcluded ?? undefined;+ const { folderExists, resolveWikiFile, resolveFileByBasename } = targets;+ const documents = asTargetNamespace('document', admittedDocs);- const folderPaths = new Set<string>();- for (const docName of admitted) {- let slash = docName.indexOf('/');- while (slash !== -1) {- folderPaths.add(docName.slice(0, slash));- slash = docName.indexOf('/', slash + 1);- }- }- const hasFolder = (folderPath: string): boolean =>- folderPaths.has(folderPath) || folderExists?.(folderPath) === true;+ const folders = addDocumentFolders(createTargetNamespace('folder'), documents);+ const resolveFolder = (folderPath: string): string | undefined =>+ folders.resolve(folderPath) ?? (folderExists?.(folderPath) === true ? folderPath : undefined);+ const hasFolder = (folderPath: string): boolean => resolveFolder(folderPath) !== undefined;const inventory: LocalTargetInventory = {- hasDocument: (docName) => admitted.has(docName),- hasFile: (relPath) => (fileExists ? fileExists(relPath) : false),- resolveTolerantDocument: createTolerantDocumentResolver(admitted),- hasFolder,+ resolveDocument: (docName) => documents.resolve(docName),+ resolveFile: (relPath) => (fileExists?.(relPath) ? relPath : undefined),+ resolveFileByBasename,+ ...(fileExcluded ? { isExcludedFile: fileExcluded } : {}),+ ...(resolveWikiFile ? { resolveWikiFile } : {}),+ resolveTolerantDocument: createTolerantDocumentResolver(documents),+ resolveFolder,};const assessments = assessLocalTargets(markdown, sourceDocName, inventory);const inlineLinkHrefs = new Set(@@ -45,22 +86,37 @@ export function computeWriteAdvisoryLinks().map(({ occurrence }) => occurrence.href),);- const links: WriteAdvisoryLink[] = computeBrokenOutboundLinks(+ const graphLinks = computeBrokenOutboundLinks(markdown,sourceDocName,- admitted,+ documents,fileExists,hasFolder,+ fileExcluded,).filter((link) =>link.sourceForm === 'jsx' || link.href.startsWith('[[') || inlineLinkHrefs.has(link.href),);- const graphHrefs = new Set(links.map((link) => link.href));+ const graphHrefs = new Set(graphLinks.map((link) => link.href));+ const links: WriteAdvisoryLink[] = graphLinks.filter((link) =>+ hasVerdict(targets, {+ reason: link.reason,+ targetKind: null,+ wikiAsset: false,+ mayNameFile: link.sourceForm !== 'jsx' && !link.href.startsWith('[['),+ }),+ );const seenRepairSites = new Set<string>();for (const assessment of assessments) {if (assessment.reason === null) continue;- if (!fileExists && assessment.targetKind === 'file') continue;+ const verdict = hasVerdict(targets, {+ reason: assessment.reason,+ targetKind: assessment.targetKind,+ wikiAsset: wikiAssetName(assessment.occurrence) !== null,+ mayNameFile: !isWikiForm(assessment.occurrence.sourceForm),+ });+ if (!verdict) continue;const { href, role, sourceForm, range, reference } = assessment.occurrence;if (role === 'link' && sourceForm === 'markdown-inline' && graphHrefs.has(href)) continue;const localTarget = buildLocalTargetEvidence(assessment, assessment.reason);diff --git a/packages/server/src/write-advisory-links.type-tests.ts b/packages/server/src/write-advisory-links.type-tests.tsnew file mode 100644index 000000000..6d5c8e3a3--- /dev/null+++ b/packages/server/src/write-advisory-links.type-tests.ts@@ -0,0 +1,22 @@+import type { WriteAdvisoryTargets } from './write-advisory-links.ts';++const fileCapabilities = {+ fileExists: () => false,+ fileExcluded: () => false,+ resolveWikiFile: () => undefined,+ resolveFileByBasename: () => undefined,+};++// @ts-expect-error — a write route that omits folder resolution must not compile.+const _omitsFolders: WriteAdvisoryTargets = fileCapabilities;+const _optsOutOfFolders: WriteAdvisoryTargets = { ...fileCapabilities, folderExists: null };+const _optsOutOfFiles: WriteAdvisoryTargets = {+ fileExists: null,+ folderExists: () => false,+ fileExcluded: null,+ resolveWikiFile: null,+ resolveFileByBasename: null,+};+void _omitsFolders;+void _optsOutOfFolders;+void _optsOutOfFiles;