Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): unify link audit classification (PRD-7860) (#3418)

serafin-garcia88ef23153828
diff --git a/.changeset/link-classification-uniformity.md b/.changeset/link-classification-uniformity.md
new file mode 100644
index 000000000..5f24f4049
--- /dev/null
+++ b/.changeset/link-classification-uniformity.md
@@ -0,0 +1,11 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Link classification is now uniform across the editor, the audit, and the document graph, so every surface gives the same answer about whether a target exists.
+
+- Reference-style links resolve to their definition's destination in the editor: the link chip, hover card, and open action now work for `[text][label]` forms, and reference-style images render their resolved image.
+- Link syntax inside non-rendering regions (HTML comments, raw `<pre>` and `<code>` elements) is no longer promoted to a live link, removing false dead-link warnings for authored examples.
+- Wiki links and embeds resolve against the same tracked-file inventory the server classifies with, so file-shaped embeds render on their own merits and missing targets are flagged consistently in both editor modes.
+- The hover card no longer offers Create page over an extension-less link whose target file already exists.
+- Image failure placeholders share one design that distinguishes a missing file from an image that could not be displayed, and they stay inside table cells.
diff --git a/.changeset/local-target-link-audit.md b/.changeset/local-target-link-audit.md
new file mode 100644
index 000000000..4f7a71675
--- /dev/null
+++ b/.changeset/local-target-link-audit.md
@@ -0,0 +1,7 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Open Knowledge now checks project-local document, file, and image targets without rewriting authored Markdown. Missing targets appear consistently in write advisories, audits, Problems, Links, and both editor modes, while invalid images keep a visible placeholder that distinguishes a missing file from one that could not be displayed.
+
+The shared target index updates affected references after create, delete, rename, and repair events, fails closed while rebuilding, and retains explicit tolerant-navigation evidence without treating a fallback as a valid authored path.
diff --git a/knip.config.ts b/knip.config.ts
index 78162ec09..f9179f2d4 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,7 +123,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.md
index 76e775bbc..ca047d6fe 100644
--- a/packages/app/BUNDLE-SIZE.md
+++ b/packages/app/BUNDLE-SIZE.md
@@ -60,3 +60,5 @@ Combined-chunks 3.78->4.4 MB when the interface-language preference started acti
Combined-chunks 4.4->4.5 MB once every catalog held real translations rather than English skeletons. Measured 4.41 MB, 6.02 kB over. The entry above predicted this would cost nothing: an untranslated entry compiles to its English source string, so a skeleton already weighs a full catalog, and translating it swaps bytes rather than adding them. That holds for Latin and CJK and does not hold for the Indic and Arabic scripts. Measured per-locale gzipped chunks now span 60,026 B to 78,840 B, where before every one sat at 58,034 B: Devanagari and Bengali are the two largest at ~78 kB, Arabic and Urdu next at ~71 kB, and the Latin and Han catalogs stay near 60-65 kB. Those scripts are 2-3 UTF-8 bytes per character against English's 1, and gzip recovers less of that on an alphabet as large and combining-mark-heavy as Devanagari than it does on Han. The main app bundle is untouched at 395.23 kB against its 485 kB limit and CSS at 8.36 kB against 59 kB, so this is entirely on-demand catalog weight: a reader still downloads one catalog, and the one they download is now the one they can read. No reclamation lever — same as above, the weight is the feature.
Combined-chunks 4.5->4.7 MB merging the ACP-highlighting branch onto the language catalogs: the two lazy features stack — eleven on-demand locale catalogs plus the curated shiki grammar chunk — and measured 4.6 MB locally, ~4.66 MB projected in CI at the ~1.4% local->CI ratio, 104 kB over the 4.5 ceiling that was set before the highlighter existed. The main app bundle and CSS stay under their limits; both features load nothing until used (a catalog on locale switch, the grammar chunk on the first fenced code block). Reclamation levers: trim the grammar list, or the catalog-weight notes above.
+
+Combined-chunks 4.7->4.72 MB for uniform local-target classification and image failure states across the editor, Problems, Links, and source diagnostics. CI measured 4.71 MB, 8.53 kB over the prior ceiling, while the main app bundle remained at 418.08 kB against its 487 kB limit and CSS at 8.36 kB against 59 kB. The increase therefore records the feature's total chunk footprint rather than first-load growth; the pre-existing lazy-load levers above remain the reclamation path.
diff --git a/packages/app/package.json b/packages/app/package.json
index ce10cedac..92099bfa0 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -27,7 +27,7 @@
"measure:stress": "bash scripts/measure-stress.sh",
"measure:sweep": "bash scripts/measure-sweep.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
@@ -53,7 +53,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "4.7 MB",
+ "limit": "4.72 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/AssetPreview.tsx b/packages/app/src/components/AssetPreview.tsx
index 8e614e442..490d2ea9f 100644
--- a/packages/app/src/components/AssetPreview.tsx
+++ b/packages/app/src/components/AssetPreview.tsx
@@ -135,6 +135,10 @@ function AssetPreviewBody({ assetPath, mediaKind }: AssetPreviewProps) {
src={src}
alt={fileName}
draggable={false}
+ // The previewed asset is a real tree entry the user selected, so
+ // it provably exists — a load failure here is a decode/serve
+ // problem ("couldn't be displayed"), never a missing target.
+ targetExistence="exists"
// Slot needs an explicit `h-full` so the `<img>`'s `max-h-full`
// resolves — percentage max-heights against an auto-height
// containing block are treated as `none` per CSS spec.
diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsx
index fb6b9a8e9..2a4a68fd7 100644
--- a/packages/app/src/components/DocPanel.dom.test.tsx
+++ b/packages/app/src/components/DocPanel.dom.test.tsx
@@ -67,7 +67,7 @@ vi.doMock('@/editor/useDocDiagnostics', () => ({
vi.doMock('@/editor/validation-audit-client', () => ({
AUDIT_SUPERSEDED: 'audit-superseded',
runValidationAudit: async () => null,
- useDocLinkFindings: () => [],
+ useDocLinkFindings: () => ({ status: 'loaded', findings: [] }),
}));
// Terminal availability drives the Ask-AI gate — null mirrors the web host.
let terminalLaunchValue: unknown = null;
diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsx
index b2ccaa5a8..9cfc78802 100644
--- a/packages/app/src/components/DocPanel.tsx
+++ b/packages/app/src/components/DocPanel.tsx
@@ -115,7 +115,8 @@ export function DocPanel({
// The doc's broken-link findings ride the SAME scoped audit predicate the
// project audit runs (one canonical determination); lint stays on the live
// CRDT read above, which is fresher than the audit's walk.
- const linkFindings = useDocLinkFindings(docName);
+ const linkFindingsState = useDocLinkFindings(docName);
+ const linkFindings = linkFindingsState.findings;
const diagnostics = [...lintDiagnostics, ...linkFindings];
// Freshness trigger 2: the open doc's shared-store entry tracks its own live
// counts (lint off the CRDT debounce, links off the scoped audit fetch) so
@@ -128,9 +129,9 @@ export function DocPanel({
patchDocValidationSource(docName, 'lint', countsOf(lintDiagnostics));
}, [docName, lintProvider, lintDiagnostics]);
useEffect(() => {
- if (lintProvider === null) return;
+ if (lintProvider === null || linkFindingsState.status !== 'loaded') return;
patchDocValidationSource(docName, 'links', countsOf(linkFindings));
- }, [docName, lintProvider, linkFindings]);
+ }, [docName, lintProvider, linkFindings, linkFindingsState.status]);
// Apply a diagnostic's auto-fix to the source CRDT. `lintProvider` is the
// active provider only when it matches this doc, so a fix always targets the
// document the user is viewing.
@@ -274,6 +275,7 @@ export function DocPanel({
<ProblemsPanel
docName={docName}
diagnostics={diagnostics}
+ linkFindingsStatus={linkFindingsState.status}
onFix={lintProvider !== null ? handleFix : undefined}
onAutoFix={lintProvider !== null ? handleAutoFix : undefined}
onAskAi={lintProvider !== null && terminalLaunch !== null ? handleAskAi : undefined}
diff --git a/packages/app/src/components/LinksPanel.dom.test.tsx b/packages/app/src/components/LinksPanel.dom.test.tsx
new file mode 100644
index 000000000..870cb2638
--- /dev/null
+++ b/packages/app/src/components/LinksPanel.dom.test.tsx
@@ -0,0 +1,321 @@
+/**
+ * Behavioral tests for the LinksPanel Local files section: it renders the local
+ * file and image references a document authors — sourced from the forward-links
+ * `localTargets` sibling — in their own section apart from Outgoing and
+ * Backlinks. Each row identifies file vs image, shows a non-color status cue,
+ * and navigates to the authored occurrence without offering document-only
+ * recovery. Covers mixed resources, repeated occurrences, empty, transport
+ * failure, and the partial (localTargets-absent) response.
+ */
+
+import type { ForwardLinkLocalTarget, ForwardLinksSuccess } from '@inkeep/open-knowledge-core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { cleanup, fireEvent, render as rtlRender, screen } from '@testing-library/react';
+import type { ReactElement, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import type { LintNavDetail } from './ProblemsPanel';
+
+// Both lingui macro specifiers alias to one shim module under the dom config, so
+// register the same superset object for each.
+const linguiMacroMock = {
+ t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
+ Trans: ({ children }: { children: ReactNode }) => children,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+};
+vi.doMock('@lingui/core/macro', () => linguiMacroMock);
+vi.doMock('@lingui/react/macro', () => linguiMacroMock);
+
+// Mirrors the real constant so a dispatch here carries the exact event name
+// SourceEditor listens for; mocking the module keeps the heavy ProblemsPanel
+// tree (and its own audit-client mocks) out of this panel's test.
+const LINT_NAV_EVENT = 'open-knowledge:lint-nav';
+vi.doMock('@/components/ProblemsPanel', () => ({ LINT_NAV_EVENT }));
+
+// A row banks a pending source-navigation intent and fires a live event; capture
+// the banked intents so a test can prove both halves happen.
+const rememberedIntents: { docName: string; detail: LintNavDetail }[] = [];
+vi.doMock('@/editor/source-editor-navigation', () => ({
+ rememberPendingSourceNavigation: (
+ docName: string,
+ intent: { kind: string; detail: LintNavDetail },
+ ) => {
+ rememberedIntents.push({ docName, detail: intent.detail });
+ },
+}));
+
+// The sections gate their query on the doc being known and the page list loaded.
+// A full stub keeps all three enabled without a real provider.
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ pages: new Set(['notes']),
+ folderPaths: new Set<string>(),
+ pagesBySlug: new Map<string, string>(),
+ pagesByBasename: new Map<string, string>(),
+ loading: false,
+ addPage: () => {},
+ }),
+}));
+
+const { LinksPanel } = await import('./LinksPanel');
+
+type FetchResult = { ok: boolean; status: number; body: unknown };
+
+let forwardLinksResult: FetchResult;
+const navEvents: LintNavDetail[] = [];
+
+function onNav(e: Event) {
+ navEvents.push((e as CustomEvent<LintNavDetail>).detail);
+}
+
+function fakeResponse({ ok, status, body }: FetchResult): Response {
+ return { ok, status, json: async () => body } as unknown as Response;
+}
+
+/** One authored local-target occurrence; defaults to a resolved file link. */
+function localTarget(overrides: Partial<ForwardLinkLocalTarget> = {}): ForwardLinkLocalTarget {
+ return {
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: 'assets/data.csv',
+ resolvedTarget: 'assets/data.csv',
+ status: 'exact',
+ reason: null,
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 10, end: 40 },
+ line: 3,
+ column: 5,
+ definition: null,
+ ...overrides,
+ };
+}
+
+function forwardLinksBody(over: Partial<ForwardLinksSuccess> = {}): ForwardLinksSuccess {
+ return { docName: 'notes', forwardLinks: [], localTargets: [], ...over };
+}
+
+function render(ui: ReactElement) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return rtlRender(
+ <QueryClientProvider client={client}>
+ <TooltipProvider>{ui}</TooltipProvider>
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ rememberedIntents.length = 0;
+ navEvents.length = 0;
+ window.addEventListener(LINT_NAV_EVENT, onNav);
+ forwardLinksResult = { ok: true, status: 200, body: forwardLinksBody() };
+ global.fetch = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.startsWith('/api/forward-links')) return fakeResponse(forwardLinksResult);
+ if (url.startsWith('/api/backlinks')) {
+ return fakeResponse({ ok: true, status: 200, body: { docName: 'notes', backlinks: [] } });
+ }
+ return fakeResponse({ ok: false, status: 404, body: null });
+ }) as unknown as typeof fetch;
+});
+
+afterEach(() => {
+ window.removeEventListener(LINT_NAV_EVENT, onNav);
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('LinksPanel Local files section', () => {
+ test('renders local files apart from Outgoing and Backlinks', async () => {
+ forwardLinksResult.body = forwardLinksBody({
+ forwardLinks: [
+ {
+ kind: 'external',
+ url: 'https://example.com',
+ title: 'https://example.com',
+ snippet: null,
+ },
+ ],
+ localTargets: [
+ localTarget({ href: 'assets/data.csv', resolvedTarget: 'assets/data.csv' }),
+ localTarget({ role: 'image', href: 'assets/logo.png', resolvedTarget: 'assets/logo.png' }),
+ ],
+ });
+ render(<LinksPanel docName="notes" />);
+
+ // All three sections are present and distinct.
+ expect(await screen.findByText('Local files')).toBeTruthy();
+ expect(screen.getByText('Outgoing')).toBeTruthy();
+ expect(screen.getByText('Backlinks')).toBeTruthy();
+
+ // The file and image resources render under Local files; the external URL
+ // stays under Outgoing — a resource is never promoted to a graph edge.
+ expect(
+ await screen.findByRole('button', { name: 'File assets/data.csv. Go to reference.' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'Image assets/logo.png. Go to reference.' }),
+ ).toBeTruthy();
+ expect(screen.getByRole('link', { name: /example\.com/ })).toBeTruthy();
+ });
+
+ test('identifies file vs image and shows a non-color missing status as text', async () => {
+ forwardLinksResult.body = forwardLinksBody({
+ localTargets: [
+ localTarget({
+ role: 'image',
+ href: 'assets/missing.png',
+ resolvedTarget: 'assets/missing.png',
+ status: 'missing',
+ reason: 'no-such-file',
+ }),
+ ],
+ });
+ render(<LinksPanel docName="notes" />);
+
+ // The missing status is a text badge, not a color alone.
+ expect(await screen.findByText('Missing')).toBeTruthy();
+ // The kind (image) reaches the accessible name, so the file/image identity
+ // survives with the screen reader, not only through the decorative icon.
+ expect(
+ screen.getByRole('button', {
+ name: 'Missing image assets/missing.png. Go to reference.',
+ }),
+ ).toBeTruthy();
+ });
+
+ test('a missing row navigates to its authored occurrence and offers no recovery action', async () => {
+ forwardLinksResult.body = forwardLinksBody({
+ localTargets: [
+ localTarget({
+ href: 'assets/missing.csv',
+ resolvedTarget: 'assets/missing.csv',
+ status: 'missing',
+ reason: 'no-such-file',
+ line: 7,
+ column: 2,
+ }),
+ ],
+ });
+ render(<LinksPanel docName="notes" />);
+
+ const row = await screen.findByRole('button', {
+ name: 'Missing file assets/missing.csv. Go to reference.',
+ });
+ // The row is a plain button, never a link to the absent target.
+ expect(row.tagName).toBe('BUTTON');
+ fireEvent.click(row);
+
+ // Navigation banks the intent AND fires the live event, at the 1-based
+ // position derived from the 0-based occurrence.
+ expect(navEvents).toEqual([{ docName: 'notes', line: 8, column: 3, source: 'links' }]);
+ expect(rememberedIntents).toEqual([
+ { docName: 'notes', detail: { docName: 'notes', line: 8, column: 3, source: 'links' } },
+ ]);
+
+ // Create page is a document-only recovery; a missing file never offers it.
+ expect(screen.queryByRole('button', { name: /create/i })).toBeNull();
+ expect(screen.queryByText(/create/i)).toBeNull();
+ });
+
+ test('repeated references to one file are separate, individually navigable rows', async () => {
+ forwardLinksResult.body = forwardLinksBody({
+ localTargets: [
+ localTarget({
+ href: 'assets/shared.csv',
+ resolvedTarget: 'assets/shared.csv',
+ status: 'missing',
+ reason: 'no-such-file',
+ range: { start: 10, end: 30 },
+ line: 2,
+ column: 1,
+ }),
+ localTarget({
+ href: 'assets/shared.csv',
+ resolvedTarget: 'assets/shared.csv',
+ status: 'missing',
+ reason: 'no-such-file',
+ range: { start: 80, end: 100 },
+ line: 9,
+ column: 4,
+ }),
+ ],
+ });
+ render(<LinksPanel docName="notes" />);
+
+ const rows = await screen.findAllByRole('button', {
+ name: 'Missing file assets/shared.csv. Go to reference.',
+ });
+ expect(rows).toHaveLength(2);
+
+ fireEvent.click(rows[0]);
+ fireEvent.click(rows[1]);
+ // Each occurrence carries its own source position — the two are not collapsed
+ // to graph cardinality.
+ expect(navEvents.map((e) => `${e.line}:${e.column}`)).toEqual(['3:2', '10:5']);
+ });
+
+ test('shows an empty state when the document references no local files', async () => {
+ forwardLinksResult.body = forwardLinksBody({ localTargets: [] });
+ render(<LinksPanel docName="notes" />);
+ expect(await screen.findByText('This page references no local files or images.')).toBeTruthy();
+ });
+
+ test('surfaces a transport failure in the section', async () => {
+ forwardLinksResult = {
+ ok: false,
+ status: 503,
+ body: {
+ type: 'urn:ok:error:derived-index-unavailable',
+ title: 'Local file index is not ready',
+ status: 503,
+ },
+ };
+ render(<LinksPanel docName="notes" />);
+ // The failing query error message is shown (once per affected section).
+ expect((await screen.findAllByText('Local file index is not ready')).length).toBeGreaterThan(0);
+ });
+
+ test('a partial response (no localTargets) is called out without hiding document relationships', async () => {
+ // A server that predates the localTargets sibling: forwardLinks is present,
+ // localTargets is absent (not `[]`).
+ forwardLinksResult.body = {
+ docName: 'notes',
+ forwardLinks: [
+ {
+ kind: 'external',
+ url: 'https://example.com',
+ title: 'https://example.com',
+ snippet: null,
+ },
+ ],
+ };
+ render(<LinksPanel docName="notes" />);
+
+ expect(await screen.findByText("Local file details aren't available yet.")).toBeTruthy();
+ // Document relationships still render — the partial local-target answer does
+ // not replace the known outgoing links.
+ expect(screen.getByRole('link', { name: /example\.com/ })).toBeTruthy();
+ });
+
+ test('a resolved row carries no status badge and stays keyboard-focusable', async () => {
+ forwardLinksResult.body = forwardLinksBody({
+ localTargets: [localTarget({ href: 'assets/ok.csv', resolvedTarget: 'assets/ok.csv' })],
+ });
+ render(<LinksPanel docName="notes" />);
+
+ const row = await screen.findByRole('button', {
+ name: 'File assets/ok.csv. Go to reference.',
+ });
+ expect(row.tagName).toBe('BUTTON');
+ // A native button is keyboard-focusable and, being enabled, part of the tab
+ // order.
+ expect(row.hasAttribute('disabled')).toBe(false);
+ // Resolved rows carry no failing-status badge.
+ expect(screen.queryByText('Missing')).toBeNull();
+ expect(screen.queryByText('Unresolvable')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/LinksPanel.tsx b/packages/app/src/components/LinksPanel.tsx
index 274120f25..ff6d7ea84 100644
--- a/packages/app/src/components/LinksPanel.tsx
+++ b/packages/app/src/components/LinksPanel.tsx
@@ -4,6 +4,8 @@ import {
type BacklinkEntry,
BacklinksSuccessSchema,
type ForwardLinkEntry,
+ type ForwardLinkLocalTarget,
+ type ForwardLinksSuccess,
ForwardLinksSuccessSchema,
isManagedArtifactDocName,
ProblemDetailsSchema,
@@ -11,12 +13,22 @@ import {
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
import { useQuery } from '@tanstack/react-query';
-import { ArrowUpRight, ChevronDown, ChevronRight, File, Folder, TriangleAlert } from 'lucide-react';
+import {
+ ArrowUpRight,
+ ChevronDown,
+ ChevronRight,
+ File,
+ Folder,
+ Image as ImageIcon,
+ TriangleAlert,
+} from 'lucide-react';
import type { ReactNode } from 'react';
import { useState } from 'react';
import { toast } from 'sonner';
import { resolveLinkTargetIntent } from '@/components/link-target-intent';
import { usePageList } from '@/components/PageListContext';
+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';
+import { Badge } from '@/components/ui/badge';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
Panel,
@@ -29,6 +41,7 @@ import {
import { Separator } from '@/components/ui/separator';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { HttpResponseParseError } from '@/editor/http-client';
+import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';
import { type CreatePageSeed, createPageFromSeedAndUpdate } from '@/lib/create-page';
import { hashFromDocName } from '@/lib/doc-hash';
import { cn } from '@/lib/utils';
@@ -59,7 +72,10 @@ async function fetchBacklinks(docName: string): Promise<BacklinkEntry[]> {
return success.data.backlinks;
}
-async function fetchForwardLinks(docName: string): Promise<ForwardLinkEntry[]> {
+// Returns the whole success body so the Outgoing and Local files sections share
+// one `/api/forward-links` fetch (React Query dedupes on the query key). Outgoing
+// reads `forwardLinks`; Local files reads the additive `localTargets` sibling.
+async function fetchForwardLinks(docName: string): Promise<ForwardLinksSuccess> {
const res = await fetch(`/api/forward-links?docName=${encodeURIComponent(docName)}`);
const body = (await res.json().catch(() => null)) as unknown;
if (!res.ok) {
@@ -79,7 +95,7 @@ async function fetchForwardLinks(docName: string): Promise<ForwardLinkEntry[]> {
status: res.status,
});
}
- return success.data.forwardLinks;
+ return success.data;
}
function compactDocPath(docName: string): string {
@@ -170,6 +186,14 @@ interface LinkRowProps {
* handler unless you intentionally mean to suppress navigation.
*/
onClick?: () => void;
+ /**
+ * Optional right-aligned content (e.g. a status badge). Rendered in normal
+ * flow beneath the primary interactive's hit-area overlay, so it stays visible
+ * but a click on it still triggers the row's primary action. Keep it
+ * non-interactive — an interactive trailing control would need `relative z-10`
+ * to escape the overlay, like the secondary buttons elsewhere in this file.
+ */
+ trailing?: ReactNode;
}
function LinkRow({
@@ -186,6 +210,7 @@ function LinkRow({
external,
disabled,
onClick,
+ trailing,
}: LinkRowProps) {
const showPath = path !== undefined && path !== title;
const iconNode = (
@@ -246,6 +271,7 @@ function LinkRow({
) : null}
{snippet ? <p className="line-clamp-2 text-muted-foreground">{snippet}</p> : null}
</div>
+ {trailing ? <div className="mt-0.5 flex shrink-0 items-center">{trailing}</div> : null}
</div>
);
@@ -345,15 +371,12 @@ function ForwardLinksSection({ docName }: { docName: string }) {
pagesByBasename,
loading: pagesLoading,
} = usePageList();
- const {
- data: links = [],
- isLoading,
- error,
- } = useQuery({
+ const { data, isLoading, error } = useQuery({
queryKey: ['forward-links', docName],
queryFn: () => fetchForwardLinks(docName),
enabled: !pagesLoading && (pages.has(docName) || isManagedArtifactDocName(docName)),
});
+ const links = data?.forwardLinks ?? [];
const [creatingKey, setCreatingKey] = useState<string | null>(null);
const [expanded, setExpanded] = useState(false);
const [prevDocName, setPrevDocName] = useState(docName);
@@ -513,12 +536,141 @@ function ForwardLinksSection({ docName }: { docName: string }) {
);
}
+/**
+ * Local file and image references the document authors, kept in their own
+ * section so a resource is never presented as a document graph edge (Outgoing)
+ * or a backlink. Rows come from the server's local-target assessment — the
+ * additive `localTargets` sibling of the forward-links response — not from
+ * reclassified graph rows. One row per authored occurrence, so two references to
+ * the same file stay individually navigable to their own source position.
+ */
+function LocalFilesSection({ docName }: { docName: string }) {
+ const { t } = useLingui();
+ const { pages, loading: pagesLoading } = usePageList();
+ const { data, isLoading, error } = useQuery({
+ queryKey: ['forward-links', docName],
+ queryFn: () => fetchForwardLinks(docName),
+ enabled: !pagesLoading && (pages.has(docName) || isManagedArtifactDocName(docName)),
+ });
+ const [expanded, setExpanded] = useState(false);
+ const [prevDocName, setPrevDocName] = useState(docName);
+ if (prevDocName !== docName) {
+ setPrevDocName(docName);
+ setExpanded(false);
+ }
+ // Undefined (not `[]`) when the server predates the localTargets sibling: a
+ // partial response whose document relationships are known but whose
+ // local-target assessment is not. Kept distinct from the empty case so the
+ // section says "unavailable" rather than a confident "none".
+ const localTargets = data?.localTargets;
+ const rows = localTargets ?? [];
+ const visible = expanded ? rows : rows.slice(0, INITIAL_VISIBLE);
+
+ function navigateToOccurrence(target: ForwardLinkLocalTarget): void {
+ // Occurrence line/column are 0-based; the source-navigation contract is
+ // 1-based. Bank the intent and fire it live, the same way Problems jumps to a
+ // finding — the visible editor consumes it now, or source mode replays it on
+ // its next activation. The row navigates to where the reference is authored,
+ // never opening the (possibly absent) target itself.
+ const detail: LintNavDetail = {
+ docName,
+ line: target.line + 1,
+ column: target.column + 1,
+ source: 'links',
+ };
+ rememberPendingSourceNavigation(docName, { kind: 'lint', detail });
+ window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail }));
+ }
+
+ function renderLocalTargetRow(target: ForwardLinkLocalTarget) {
+ const isImage = target.role === 'image';
+ const resolved = target.status === 'exact' || target.status === 'fallback';
+ const identity = target.resolvedTarget ?? target.href;
+ // Non-color status cue: a text badge for a failing reference (plus an amber
+ // icon as redundant reinforcement), nothing for a resolved one. A proven
+ // absence reads "Missing"; a reference whose target can't be located in the
+ // project (e.g. an image path escaping the root) reads "Unresolvable".
+ const statusWord = target.status === 'missing' ? t`Missing` : t`Unresolvable`;
+ // Complete messages let translators reorder kind, identity, status, and
+ // action naturally instead of inheriting English concatenation order.
+ const ariaLabel = resolved
+ ? isImage
+ ? t`Image ${identity}. Go to reference.`
+ : t`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 (
+ <LinkRow
+ key={`lt:${target.range.start}-${target.range.end}`}
+ icon={isImage ? <ImageIcon className="size-3.5" /> : <File className="size-3.5" />}
+ iconColorClass={resolved ? undefined : 'text-amber-600 dark:text-amber-400'}
+ title={compactDocPath(identity)}
+ titleHover={identity}
+ ariaLabel={ariaLabel}
+ trailing={
+ resolved ? undefined : (
+ <Badge variant="outline" className="font-normal text-muted-foreground">
+ {statusWord}
+ </Badge>
+ )
+ }
+ onClick={() => navigateToOccurrence(target)}
+ />
+ );
+ }
+
+ return (
+ <Collapsible defaultOpen>
+ <SectionTrigger title={t`Local files`} count={rows.length} isLoading={isLoading} />
+ <CollapsibleContent>
+ <div className="px-2 pb-3" aria-busy={isLoading}>
+ {error ? (
+ <div className="px-3">
+ <PanelError>
+ {error instanceof Error ? error.message : t`Failed to load local files`}
+ </PanelError>
+ </div>
+ ) : localTargets === undefined && !isLoading ? (
+ <div className="px-3">
+ <PanelEmpty>
+ <Trans>Local file details aren't available yet.</Trans>
+ </PanelEmpty>
+ </div>
+ ) : rows.length === 0 && !isLoading ? (
+ <div className="px-3">
+ <PanelEmpty>
+ <Trans>This page references no local files or images.</Trans>
+ </PanelEmpty>
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1">{visible.map(renderLocalTargetRow)}</div>
+ <ShowMoreButton
+ total={rows.length}
+ expanded={expanded}
+ onToggle={() => setExpanded((prev) => !prev)}
+ />
+ </>
+ )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
+
export function LinksPanel({ docName, className = '' }: { docName: string; className?: string }) {
return (
<Panel className={className}>
<PanelBody className="px-0 py-0">
<ForwardLinksSection docName={docName} />
<Separator />
+ <LocalFilesSection docName={docName} />
+ <Separator />
<BacklinksSection docName={docName} />
</PanelBody>
</Panel>
diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsx
index 86a223f6a..dca7df5f3 100644
--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx
+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx
@@ -83,7 +83,7 @@ vi.doMock('@/editor/validation-audit-client', () => ({
auditCalls += 1;
return runLintAuditImpl();
},
- useDocLinkFindings: () => [],
+ useDocLinkFindings: () => ({ status: 'loaded', findings: [] }),
}));
// Page-list context for the dead-link "Create page" one-shot. `addPage` is the
// only member the panel touches.
@@ -171,6 +171,57 @@ function linkDiag(
};
}
+/** Wire-loose local-target evidence (open-enum strings), as the audit projects it. */
+type LocalTargetEvidence = {
+ href: string;
+ targetKind: 'document' | 'file' | 'unknown';
+ role: 'link' | 'image';
+ sourceForm: 'markdown-inline' | 'markdown-reference' | 'html-img';
+ resolvedTarget: string | null;
+ reason: string;
+ resolutionMethod: string;
+ definition?: { line: number; label: string };
+};
+
+/**
+ * A `links` finding carrying local-target evidence — the shape the audit plane
+ * projects for a missing file, image, unresolvable, or reference-style target.
+ * `linkTarget` is threaded only for an eligible missing document (create-page
+ * intent); files, images, and unresolvable targets never carry it in production.
+ */
+function localTargetDiag(args: {
+ line?: number;
+ message: string;
+ role: 'link' | 'image';
+ targetKind: 'document' | 'file' | 'unknown';
+ sourceForm?: LocalTargetEvidence['sourceForm'];
+ resolvedTarget?: string | null;
+ reason?: string;
+ linkTarget?: string;
+ definition?: { line: number; label: string };
+}): LintDiagnostic & { localTarget: LocalTargetEvidence; linkTarget?: string } {
+ return {
+ ...diag({
+ line: args.line ?? 3,
+ severity: 'warning',
+ code: 'dead-link',
+ message: args.message,
+ source: 'links' as LintDiagnostic['source'],
+ }),
+ ...(args.linkTarget !== undefined ? { linkTarget: args.linkTarget } : {}),
+ localTarget: {
+ href: args.resolvedTarget ?? 'assets/x',
+ targetKind: args.targetKind,
+ role: args.role,
+ sourceForm: args.sourceForm ?? 'markdown-inline',
+ resolvedTarget: args.resolvedTarget ?? null,
+ reason: args.reason ?? 'no-such-file',
+ resolutionMethod: 'source-relative',
+ ...(args.definition ? { definition: args.definition } : {}),
+ },
+ };
+}
+
beforeEach(() => {
auditCalls = 0;
runLintAuditImpl = async () => null;
@@ -236,6 +287,30 @@ describe('ProblemsPanel', () => {
expect(screen.getByText('No problems found.')).toBeTruthy();
});
+ test('does not claim the document is clean while link validation is loading', () => {
+ render(<ProblemsPanel docName="notes" diagnostics={[]} linkFindingsStatus="loading" />);
+ expect(screen.getByRole('status').textContent).toContain('Checking links');
+ expect(screen.queryByText('No problems found.')).toBeNull();
+ });
+
+ test('reports an unavailable link plane instead of a clean document', () => {
+ render(<ProblemsPanel docName="notes" diagnostics={[]} linkFindingsStatus="failed" />);
+ expect(screen.getByTestId('problems-links-failed').textContent).toBe(
+ 'Link validation is unavailable.',
+ );
+ expect(screen.queryByText('No problems found.')).toBeNull();
+ });
+
+ test('labels retained problems as last known when a refresh fails', () => {
+ render(
+ <ProblemsPanel docName="notes" diagnostics={[linkDiag()]} linkFindingsStatus="failed" />,
+ );
+ expect(screen.getByTestId('problems-links-failed').textContent).toContain(
+ 'Showing last known problems',
+ );
+ expect(screen.getByText(/does not resolve/)).toBeTruthy();
+ });
+
test('a compact Checked-by line reveals the active plugins in a tooltip', async () => {
projectLintConfigData = lintConfigWith({ markdownlint: true, frontmatter: true });
render(<ProblemsPanel docName="notes" diagnostics={[]} />);
@@ -280,6 +355,34 @@ describe('ProblemsPanel', () => {
expect(screen.getByText(/does not resolve/)).toBeTruthy();
});
+ test('renders local-target prose from structured evidence instead of server English', () => {
+ render(
+ <ProblemsPanel
+ docName="notes"
+ diagnostics={[
+ diag({
+ source: 'links',
+ code: 'dead-link',
+ message: 'opaque server fallback',
+ localTarget: {
+ href: './missing.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'missing.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ }),
+ ]}
+ />,
+ );
+ expect(
+ screen.getByText('Image target "missing.png" does not resolve to an existing file.'),
+ ).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={[]} />);
@@ -1852,3 +1955,202 @@ describe('ProblemsPanel — project scope: sweep-progress live region', () => {
await waitFor(() => expect(sweepLiveRegion()).toBeUndefined());
});
});
+
+/**
+ * Local-target findings (files, images, reference-style, unresolvable) share the
+ * one validation plane with lint and document dead-links. The panel reads their
+ * kind from the assessment evidence — never the message text — so a missing file
+ * or image reads apart from a missing document by glyph, and Create page (a
+ * document-only recovery) never appears on a file, image, or unresolvable row.
+ */
+describe('ProblemsPanel — local-target findings', () => {
+ const fileLink = (line: number) =>
+ localTargetDiag({
+ line,
+ role: 'link',
+ targetKind: 'file',
+ resolvedTarget: 'docs/spec.pdf',
+ message: 'Link target "docs/spec.pdf" does not resolve to an existing file.',
+ });
+ const imageEmbed = (line: number) =>
+ localTargetDiag({
+ line,
+ role: 'image',
+ targetKind: 'file',
+ resolvedTarget: 'assets/logo.png',
+ message: 'Image target "assets/logo.png" does not resolve to an existing file.',
+ });
+ const unresolvableLink = (line: number) =>
+ localTargetDiag({
+ line,
+ role: 'link',
+ targetKind: 'unknown',
+ reason: 'unresolvable',
+ message: 'Link target "../../etc/passwd" could not be resolved to a project-local target.',
+ });
+
+ test('reads file, image, unresolvable, and document kinds apart from the evidence', () => {
+ render(
+ <ProblemsPanel
+ docName="notes"
+ diagnostics={[
+ diag({ line: 1 }),
+ linkDiag({ line: 2 }),
+ fileLink(3),
+ imageEmbed(4),
+ unresolvableLink(5),
+ ]}
+ />,
+ );
+ const tags = screen.getAllByTestId('problems-source-tag');
+ // Every producer keeps its own chip; the links validator owns four of them.
+ expect(tags.map((tag) => tag.textContent)).toEqual([
+ 'markdownlint',
+ 'links',
+ 'links',
+ 'links',
+ 'links',
+ ]);
+ // The kind is a stable, non-color cue read from the assessment, not the text:
+ // a lint finding has none, then document, file, image, and unresolvable.
+ expect(tags.map((tag) => tag.getAttribute('data-target-kind'))).toEqual([
+ null,
+ 'document',
+ 'file',
+ 'image',
+ 'unresolvable',
+ ]);
+ });
+
+ test('never offers Create page for file, image, or unresolvable findings', () => {
+ render(
+ <ProblemsPanel
+ docName="notes"
+ diagnostics={[fileLink(3), imageEmbed(4), unresolvableLink(5), linkDiag({ line: 6 })]}
+ />,
+ );
+ // Only the missing document is eligible; the other three carry no create intent.
+ const created = screen.getAllByTestId('problems-create-page');
+ expect(created).toHaveLength(1);
+ });
+
+ test('offers Create page for a reference-style missing document and creates that doc', async () => {
+ render(
+ <ProblemsPanel
+ docName="notes"
+ diagnostics={[
+ localTargetDiag({
+ line: 3,
+ role: 'link',
+ targetKind: 'document',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'guides/setup',
+ reason: 'no-such-doc',
+ linkTarget: 'guides/setup',
+ message: 'Link target "guides/setup" does not resolve to an existing document.',
+ definition: { line: 20, label: 'setup' },
+ }),
+ ]}
+ />,
+ );
+ expect(screen.getByTestId('problems-source-tag').getAttribute('data-target-kind')).toBe(
+ 'document',
+ );
+ fireEvent.click(screen.getByTestId('problems-create-page'));
+ await waitFor(() =>
+ expect(createPageCalls).toEqual([{ initialDir: '', suggestedName: 'guides/setup' }]),
+ );
+ expect(addPageCalls).toEqual(['guides/setup']);
+ });
+
+ test('a stray create target on an image finding still surfaces no Create page', () => {
+ // The panel enforces the document-only invariant locally: even if the wire
+ // leaked a linkTarget onto an image, the evidence says image, so no Create.
+ render(
+ <ProblemsPanel
+ docName="notes"
+ diagnostics={[
+ localTargetDiag({
+ line: 3,
+ role: 'image',
+ targetKind: 'file',
+ resolvedTarget: 'assets/logo.png',
+ linkTarget: 'assets/logo.png',
+ message: 'Image target "assets/logo.png" does not resolve to an existing file.',
+ }),
+ ]}
+ />,
+ );
+ expect(screen.queryByTestId('problems-create-page')).toBeNull();
+ });
+
+ test('a file finding click-jumps to its authored occurrence', () => {
+ let received: { docName: string; line: number; column: number } | null = null;
+ const listener = (e: Event) => {
+ received = (e as CustomEvent<LintNavDetail>).detail;
+ };
+ window.addEventListener(LINT_NAV_EVENT, listener);
+ try {
+ render(<ProblemsPanel docName="notes" diagnostics={[fileLink(7)]} />);
+ fireEvent.click(screen.getByRole('button', { name: /does not resolve to an existing file/ }));
+ expect(received).toEqual({ docName: 'notes', line: 7, column: 1, source: 'links' });
+ } finally {
+ window.removeEventListener(LINT_NAV_EVENT, listener);
+ }
+ });
+
+ test('keeps the finding message in the row accessible name and hides the kind glyph', () => {
+ render(<ProblemsPanel docName="notes" diagnostics={[imageEmbed(3)]} />);
+ // The kind reads from words, not color: the message is the row's accessible name.
+ expect(
+ screen.getByRole('button', {
+ name: /Image target "assets\/logo.png" does not resolve to an existing file/,
+ }),
+ ).toBeTruthy();
+ // The glyph is decorative, so it never doubles the announcement.
+ const glyph = screen.getByTestId('problems-source-tag').querySelector('svg');
+ expect(glyph?.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ test('project file groups surface file and image findings with gated actions', async () => {
+ runLintAuditImpl = async () =>
+ auditResult({
+ files: [
+ {
+ file: 'guides/setup.md',
+ diagnostics: [linkDiag({ line: 2 }), fileLink(4), imageEmbed(6)],
+ },
+ ],
+ fileCount: 1,
+ warningCount: 3,
+ });
+ render(<ProblemsPanel docName="notes" diagnostics={[]} />);
+ fireEvent.click(screen.getByTestId('panel-scope-project'));
+ await waitFor(() => expect(screen.getByText('guides/setup.md')).toBeTruthy());
+ expandGroup('guides/setup.md');
+
+ const kinds = screen
+ .getAllByTestId('problems-source-tag')
+ .map((tag) => tag.getAttribute('data-target-kind'));
+ expect(kinds).toEqual(['document', 'file', 'image']);
+ // Only the missing document is repairable via Create in the project group.
+ expect(screen.getAllByTestId('problems-create-page')).toHaveLength(1);
+ });
+
+ test('repeated image findings to one target group and never offer Create', () => {
+ render(<ProblemsPanel docName="notes" diagnostics={[imageEmbed(3), imageEmbed(8)]} />);
+ const group = screen.getByTestId('problems-duplicate-group');
+ expect(group.textContent).toContain('2 instances');
+ // The collapsed header still carries the image kind.
+ expect(screen.getByTestId('problems-source-tag').getAttribute('data-target-kind')).toBe(
+ 'image',
+ );
+ expect(screen.queryByTestId('problems-create-page')).toBeNull();
+ fireEvent.click(group.querySelector('button') as HTMLElement);
+ expect(
+ screen.getByTestId('problems-duplicate-instances').querySelectorAll('button'),
+ ).toHaveLength(2);
+ // Neither occurrence gains a Create action on expand.
+ expect(screen.queryByTestId('problems-create-page')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsx
index 4c7e84a4b..24e6e2d35 100644
--- a/packages/app/src/components/ProblemsPanel.tsx
+++ b/packages/app/src/components/ProblemsPanel.tsx
@@ -8,8 +8,11 @@ import {
ChevronRight,
ChevronsDownUp,
ChevronsUpDown,
+ File as FileIcon,
FilePlus2,
+ Image as ImageIcon,
Link2,
+ type LucideIcon,
RefreshCw,
Sparkles,
Wrench,
@@ -38,10 +41,12 @@ import {
subscribeToLintConfigChanged,
useProjectLintConfig,
} from '@/editor/lint-config-client';
+import { localizedValidationMessage } from '@/editor/localized-validation-message';
import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';
import { AUDIT_SUPERSEDED, runValidationAudit } from '@/editor/validation-audit-client';
import { createPageFromSeedAndUpdate } from '@/lib/create-page';
import { filePathToDocName, hashFromDocName } from '@/lib/doc-hash';
+import { invalidatesLocalTargetAudit, subscribeToDocumentsChanged } from '@/lib/documents-events';
import {
cancelProjectFixSweep,
startProjectFixSweep,
@@ -103,6 +108,46 @@ type ProjectAuditState =
| { status: 'loaded'; result: ValidationAuditResponse }
| { status: 'failed' };
+/** What a `links` finding points at: three project-local kinds plus an
+ * unresolvable form. `null` for any other validator. */
+type LinkTargetKind = 'document' | 'file' | 'image' | 'unresolvable';
+
+/**
+ * What a `links` finding points at, read from the assessment evidence rather
+ * than the rendered message. A document dead-link flows from the backlink graph
+ * and carries no `localTarget`, so a `links` finding without evidence is always
+ * a document. Drives both the row's leading glyph and the create-page gate, so a
+ * missing file or image neither reads nor acts like a missing document.
+ */
+function linkTargetKindOf(diagnostic: DiagnosticLike): LinkTargetKind | null {
+ if (diagnostic.source !== 'links') return null;
+ const evidence = diagnostic.localTarget;
+ if (evidence === undefined) return 'document';
+ if (evidence.role === 'image') return 'image';
+ if (evidence.targetKind === 'file') return 'file';
+ if (evidence.targetKind === 'document') return 'document';
+ return 'unresolvable';
+}
+
+const LINK_TARGET_ICON: Record<LinkTargetKind, LucideIcon> = {
+ document: Link2,
+ file: FileIcon,
+ image: ImageIcon,
+ // An unresolvable link has no derivable file identity, so it keeps the link
+ // glyph rather than borrowing the file one.
+ unresolvable: Link2,
+};
+
+/**
+ * Create page is a document-only recovery. The server marks an eligible missing
+ * document with `linkTarget`; the panel additionally requires the evidence to
+ * agree it is a document, so a stray `linkTarget` on a file, image, or
+ * unresolvable finding can never surface the affordance.
+ */
+function canCreateMissingPage(diagnostic: DiagnosticLike): boolean {
+ return diagnostic.linkTarget !== undefined && linkTargetKindOf(diagnostic) === 'document';
+}
+
/** Message line + producer chip + `code · line` subline shared by doc- and project-scope rows. */
function DiagnosticRowBody({
diagnostic,
@@ -115,7 +160,8 @@ function DiagnosticRowBody({
const { t } = useLingui();
const Icon = diagnostic.severity === 'error' ? AlertCircle : AlertTriangle;
const displayLine = diagnostic.range.start.line + 1;
- const isLink = diagnostic.source === 'links';
+ const targetKind = linkTargetKindOf(diagnostic);
+ const KindIcon = targetKind === null ? null : LINK_TARGET_ICON[targetKind];
const grouped = instanceCount !== undefined && instanceCount > 1;
return (
<>
@@ -127,7 +173,9 @@ function DiagnosticRowBody({
diagnostic.severity === 'error' ? 'text-destructive' : 'text-amber-500',
)}
/>
- <span className="min-w-0 flex-1 text-foreground">{diagnostic.message}</span>
+ <span className="min-w-0 flex-1 text-foreground">
+ {localizedValidationMessage(diagnostic)}
+ </span>
{grouped ? (
// Count and disclosure both sit on the right so a grouped row keeps
// the exact left edge of an ungrouped one — a leading chevron indents
@@ -164,12 +212,15 @@ function DiagnosticRowBody({
<Badge
variant="gray"
data-testid="problems-source-tag"
+ // Non-color kind cue: the leading glyph reads a missing file, image,
+ // and document apart at a glance; the message states the same in text.
+ data-target-kind={targetKind ?? undefined}
className={cn(
'h-4 shrink-0 px-1 font-sans text-[10px] uppercase leading-none',
- isLink && 'gap-0.5',
+ KindIcon !== null && 'gap-0.5',
)}
>
- {isLink ? <Link2 aria-hidden="true" className="size-2.5" /> : null}
+ {KindIcon !== null ? <KindIcon aria-hidden="true" className="size-2.5" /> : null}
{diagnostic.source}
</Badge>
{/* A group spans many lines, so only a single finding names one. */}
@@ -231,6 +282,7 @@ function DiagnosticGroupItem({
// `groupDiagnostics` seeds every group with one instance and only ever pushes,
// so the non-empty tuple type guarantees a first element.
const first = group.instances[0];
+ const localizedFirstMessage = localizedValidationMessage(first);
if (group.instances.length === 1) {
const actions = renderActions(first);
@@ -268,13 +320,14 @@ function DiagnosticGroupItem({
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden data-[state=open]:animate-[collapsible-down_150ms_ease-out] data-[state=closed]:animate-[collapsible-up_150ms_ease-in] motion-reduce:animate-none">
<ul
- aria-label={t`Occurrences of ${first.message}`}
+ aria-label={t`Occurrences of ${localizedFirstMessage}`}
className="flex flex-col gap-0.5 pb-1 ps-5"
data-testid="problems-duplicate-instances"
>
{group.instances.map((diagnostic) => {
const actions = renderActions(diagnostic);
const displayLine = diagnostic.range.start.line + 1;
+ const localizedMessage = localizedValidationMessage(diagnostic);
return (
<li
key={diagnosticKey(diagnostic)}
@@ -288,7 +341,7 @@ function DiagnosticGroupItem({
// The visible text is just the line number; the message
// rides the accessible name so the occurrence still reads
// as a whole finding out of list context.
- aria-label={t`${diagnostic.message} at line ${displayLine}`}
+ aria-label={t`${localizedMessage} at line ${displayLine}`}
>
{t`line ${displayLine}`}
</button>
@@ -507,6 +560,7 @@ function FixWithAiButton({
export function ProblemsPanel({
docName,
diagnostics,
+ linkFindingsStatus = 'loaded',
onFix,
onAutoFix,
onAskAi,
@@ -516,6 +570,8 @@ export function ProblemsPanel({
/** Live lint diagnostics for the open doc PLUS its broken-link findings —
* wire-loose so both the in-process lint shape and the audit plane fit. */
diagnostics: DiagnosticLike[];
+ /** Freshness of the asynchronous links slice composed into `diagnostics`. */
+ linkFindingsStatus?: 'idle' | 'loading' | 'loaded' | 'failed';
/** Apply a fixable diagnostic's auto-fix (this-doc scope only). When absent
* (e.g. unit harness), fixable rows render no Fix button. */
onFix?: (diagnostic: DiagnosticLike) => void;
@@ -703,6 +759,13 @@ export function ProblemsPanel({
};
});
useEffect(() => subscribeToLintConfigChanged(() => onLintConfigChangedRef.current()), []);
+ useEffect(
+ () =>
+ subscribeToDocumentsChanged((channels) => {
+ if (invalidatesLocalTargetAudit(channels)) onLintConfigChangedRef.current();
+ }),
+ [],
+ );
// A settled sweep leaves the loaded plane describing problems it just fixed.
// Refresh it in place — but only for a panel that is actually mounted and
@@ -756,7 +819,7 @@ export function ProblemsPanel({
/** Per-occurrence actions in doc scope: create the missing page, fix, ask AI. */
function renderDocActions(diagnostic: DiagnosticLike): ReactElement | null {
const fixable = onFix !== undefined && (diagnostic.fixes?.length ?? 0) > 0;
- const canCreate = diagnostic.linkTarget !== undefined && pageList !== null;
+ const canCreate = canCreateMissingPage(diagnostic) && pageList !== null;
if (!fixable && !canCreate && onAskAi === undefined) return null;
const flatId = `${diagnostic.source}/${diagnostic.code}`;
return (
@@ -828,8 +891,26 @@ export function ProblemsPanel({
<PanelScopeHeader scope={scope} onScopeChange={handleScopeChange} />
{scope === 'doc' ? (
<PanelBody className="px-2 py-2">
+ {linkFindingsStatus === 'idle' || linkFindingsStatus === 'loading' ? (
+ <PanelEmpty
+ className="px-2 pb-2"
+ role="status"
+ aria-live="polite"
+ data-testid="problems-links-loading"
+ >
+ <Trans>Checking links</Trans>
+ </PanelEmpty>
+ ) : linkFindingsStatus === 'failed' ? (
+ <PanelError className="px-2 pb-2" role="status" data-testid="problems-links-failed">
+ {sorted.length > 0 ? (
+ <Trans>Link validation is unavailable. Showing last known problems.</Trans>
+ ) : (
+ <Trans>Link validation is unavailable.</Trans>
+ )}
+ </PanelError>
+ ) : null}
{sorted.length === 0 ? (
- noPluginsEnabled ? (
+ linkFindingsStatus !== 'loaded' ? null : noPluginsEnabled ? (
// Zero lint plugins narrows the plane to link validation alone —
// say so instead of an unqualified "no problems", and point at
// the switch. Only the empty list carries the hint: link
@@ -1255,9 +1336,9 @@ function ProjectFileGroup({
// Same hover-revealed overlay contract as the doc scope, minus
// the fix / ask-AI actions (both are this-doc only).
renderActions={(diagnostic) =>
- diagnostic.linkTarget === undefined || onCreateTarget === undefined ? null : (
+ !canCreateMissingPage(diagnostic) || onCreateTarget === undefined ? null : (
<CreatePageButton
- target={diagnostic.linkTarget}
+ target={diagnostic.linkTarget ?? ''}
creating={creatingTarget === diagnostic.linkTarget}
disabled={creatingTarget !== null}
onCreate={() => onCreateTarget(diagnostic)}
diff --git a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
index 31c7888de..8fb4262bc 100644
--- a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
+++ b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
@@ -12,13 +12,18 @@
*/
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
emitLocalMenuAction,
} from '@/lib/local-menu-action-bus';
import { ReportBugMenuTrigger } from './ReportBugMenuTrigger';
+vi.mock('./ReportBugDialog', () => ({
+ ReportBugDialog: ({ open }: { open: boolean }) =>
+ open ? <div aria-label="Report a bug" role="dialog" /> : null,
+}));
+
// Radix UI primitives (shadcn Dialog) reach for DOM globals at mount. The
// broadly-needed constructors (MutationObserver) live in the shared
// tests/dom/jsdom-preload.ts; NodeFilter (react-focus-scope) and
diff --git a/packages/app/src/components/SystemDocSubscriber.dom.test.tsx b/packages/app/src/components/SystemDocSubscriber.dom.test.tsx
new file mode 100644
index 000000000..c47a7798e
--- /dev/null
+++ b/packages/app/src/components/SystemDocSubscriber.dom.test.tsx
@@ -0,0 +1,84 @@
+import { act, cleanup, render } from '@testing-library/react';
+import { afterEach, expect, test, vi } from 'vitest';
+
+type ProviderHandler = () => void;
+
+let provider: { emitSynced(): void } | null = null;
+const emittedChannels: string[][] = [];
+const setSystemProvider = vi.fn();
+
+vi.doMock('@hocuspocus/provider', () => {
+ class FakeHocuspocusProvider {
+ private readonly handlers = new Map<string, ProviderHandler[]>();
+ awareness = {
+ getStates: () => new Map(),
+ on: () => {},
+ off: () => {},
+ };
+
+ constructor() {
+ provider = this;
+ }
+
+ on(event: string, handler: ProviderHandler) {
+ const handlers = this.handlers.get(event) ?? [];
+ handlers.push(handler);
+ this.handlers.set(event, handlers);
+ }
+
+ emitSynced() {
+ for (const handler of this.handlers.get('synced') ?? []) handler();
+ }
+
+ destroy() {}
+ }
+
+ return { HocuspocusProvider: FakeHocuspocusProvider };
+});
+
+vi.doMock('@tanstack/react-query', () => ({
+ useQueryClient: () => ({ invalidateQueries: () => Promise.resolve() }),
+}));
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ collabUrl: 'ws://localhost:1/collab',
+ setSystemProvider,
+ updateServerInstanceId: () => {},
+ onBranchSwitched: async () => {},
+ observeBranch: async () => {},
+ observeDiskAck: () => {},
+ refreshServerInfo: async () => {},
+ }),
+}));
+
+vi.doMock('@/editor/lint-config-client', () => ({ emitLintConfigChanged: () => {} }));
+vi.doMock('@/lib/config-ignore-nested-error-events', () => ({
+ emitConfigIgnoreNestedError: () => {},
+}));
+vi.doMock('@/lib/config-validation-events', () => ({
+ emitConfigValidationRejected: () => {},
+}));
+vi.doMock('@/lib/documents-events', () => ({
+ emitDocPersisted: () => {},
+ emitDocumentsChanged: (channels: string[]) => emittedChannels.push(channels),
+ subscribeToDocumentsChanged: () => () => {},
+}));
+
+const { SystemDocSubscriber } = await import('./SystemDocSubscriber');
+
+afterEach(() => {
+ cleanup();
+ emittedChannels.length = 0;
+ provider = null;
+ setSystemProvider.mockClear();
+});
+
+test('first system sync recovers local-target invalidations emitted during connection', () => {
+ render(<SystemDocSubscriber />);
+ expect(provider).not.toBeNull();
+
+ act(() => provider?.emitSynced());
+
+ expect(emittedChannels).toContainEqual(['files', 'backlinks', 'graph', 'local-targets']);
+});
diff --git a/packages/app/src/components/SystemDocSubscriber.tsx b/packages/app/src/components/SystemDocSubscriber.tsx
index 48dc5c24a..d832829d5 100644
--- a/packages/app/src/components/SystemDocSubscriber.tsx
+++ b/packages/app/src/components/SystemDocSubscriber.tsx
@@ -107,7 +107,11 @@ export function SystemDocSubscriber() {
});
const unsubscribe = subscribeToDocumentsChanged((channels) => {
- if (channels.includes('files') || channels.includes('backlinks')) {
+ if (
+ channels.includes('files') ||
+ channels.includes('backlinks') ||
+ channels.includes('local-targets')
+ ) {
void queryClient.invalidateQueries({ queryKey: ['backlinks'] });
void queryClient.invalidateQueries({ queryKey: ['forward-links'] });
}
@@ -137,7 +141,11 @@ export function SystemDocSubscriber() {
void handlersRef.current.refreshServerInfo();
});
provider.on('synced', () => {
- emitDocumentsChanged(['files', 'backlinks', 'graph']);
+ // Recover any derived-view frames emitted while this connection was
+ // opening. In particular, a local file can appear or disappear after the
+ // audit's initial fetch but before CC1 is ready, so local targets must be
+ // refreshed on the first sync as well as reconnects.
+ emitDocumentsChanged(['files', 'backlinks', 'graph', 'local-targets']);
onReconnectSynced();
});
diff --git a/packages/app/src/components/ValidationFreshness.dom.test.tsx b/packages/app/src/components/ValidationFreshness.dom.test.tsx
index ab723d9b7..c6faec5b5 100644
--- a/packages/app/src/components/ValidationFreshness.dom.test.tsx
+++ b/packages/app/src/components/ValidationFreshness.dom.test.tsx
@@ -22,7 +22,7 @@ import type {
import { cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { emitLintConfigChanged } from '@/editor/lint-config-client';
-import { emitBranchChanged, emitDocPersisted } from '@/lib/documents-events';
+import { emitBranchChanged, emitDocPersisted, emitDocumentsChanged } from '@/lib/documents-events';
import {
getValidationSnapshot,
resetValidationStoreForTest,
@@ -30,7 +30,9 @@ import {
} from '@/lib/validation-store';
// Config context gates the whole subscriber (`validation.fileTreeIndicators`).
-let mergedConfigValue: { validation?: { fileTreeIndicators?: boolean } } | null = null;
+let mergedConfigValue: {
+ validation?: { fileTreeIndicators?: boolean; links?: 'off' | 'warning' | 'error' };
+} | null = null;
vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ merged: mergedConfigValue }),
}));
@@ -238,6 +240,37 @@ describe('ValidationFreshness', () => {
expect(fetchUrls).toEqual(['/api/audit?counts=1']);
});
+ test.each([
+ 'local-targets',
+ 'files',
+ ] as const)('re-audits when the local-target assessment plane changes via %s', async (channel) => {
+ countsBody = {
+ files: [
+ {
+ file: 'notes.md',
+ lint: { errorCount: 0, warningCount: 0 },
+ links: { errorCount: 0, warningCount: 1 },
+ },
+ ],
+ fileCount: 1,
+ errorCount: 0,
+ warningCount: 1,
+ warnings: [],
+ };
+ render(<ValidationFreshness />);
+ emitDocumentsChanged([channel]);
+
+ await waitFor(
+ () =>
+ expect(getValidationSnapshot().get('notes')).toEqual({
+ errorCount: 0,
+ warningCount: 1,
+ }),
+ { timeout: 3000 },
+ );
+ expect(fetchUrls).toEqual(['/api/audit?counts=1']);
+ });
+
test('docs the new config no longer flags drop out of the snapshot', async () => {
render(<ValidationFreshness />);
countsBody = {
diff --git a/packages/app/src/components/ValidationFreshness.tsx b/packages/app/src/components/ValidationFreshness.tsx
index debb62224..cd408b3fe 100644
--- a/packages/app/src/components/ValidationFreshness.tsx
+++ b/packages/app/src/components/ValidationFreshness.tsx
@@ -10,11 +10,13 @@
* re-validate per doc per burst is enough for a tree tint.
*
* Trigger 4 — when the world every entry was produced against stops holding, the
- * whole plane is re-audited. Two signals qualify. A lint-config change (a plugin
+ * whole plane is re-audited. Three signals qualify. A lint-config change (a plugin
* enabled, a rule toggled, a frontmatter schema edited) invalidates the config
* the counts were computed under; without this, enabling a plugin lights up
* nothing until you open files one at a time, and toggling a rule off leaves its
- * counts standing. A branch switch invalidates the content itself — it replaces
+ * counts standing. A local-targets change invalidates file/image existence
+ * findings without necessarily changing the document graph. A branch switch
+ * invalidates the content itself — it replaces
* the content set wholesale in-window, with no reload to rebuild the plane, so
* the sidebar would otherwise keep showing the previous branch's problems until
* a config change or a per-doc write happened to trip triggers 3/4.
@@ -51,8 +53,9 @@
* not once per launch.
*/
-import { useEffect, useRef } from 'react';
+import { useEffect, useLayoutEffect, useRef } from 'react';
import { useOptionalPageList } from '@/components/PageListContext';
+import { setLinkValidationVisible } from '@/editor/link-validation-policy';
import { subscribeToLintConfigChanged } from '@/editor/lint-config-client';
import {
AUDIT_SUPERSEDED,
@@ -61,7 +64,12 @@ import {
} from '@/editor/validation-audit-client';
import { useConfigContext } from '@/lib/config-provider';
import { filePathToDocName } from '@/lib/doc-hash';
-import { subscribeToBranchChanged, subscribeToDocPersisted } from '@/lib/documents-events';
+import {
+ invalidatesLocalTargetAudit,
+ subscribeToBranchChanged,
+ subscribeToDocPersisted,
+ subscribeToDocumentsChanged,
+} from '@/lib/documents-events';
import { patchDocValidationFromAudit, replaceValidationFromCounts } from '@/lib/validation-store';
const REVALIDATE_DEBOUNCE_MS = 500;
@@ -124,6 +132,10 @@ export function ValidationFreshness() {
// the background work entirely instead of writing to a store nothing reads.
const { merged } = useConfigContext();
const indicatorsEnabled = merged?.validation?.fileTreeIndicators !== false;
+ const linksVisible = merged?.validation?.links !== 'off';
+ // This subscriber mounts before the editors; update before paint so a
+ // project configured with "Don't show" never flashes broken-link styling.
+ useLayoutEffect(() => setLinkValidationVisible(linksVisible), [linksVisible]);
// Doc count for the on-open budget, read off the list the file tree already
// loaded — so deciding whether to audit never costs a walk of its own. Optional
// like the Problems panel's own use: absent provider (bare harness) reads as
@@ -206,6 +218,9 @@ export function ValidationFreshness() {
const unsubscribers = [
subscribeToLintConfigChanged(schedule),
subscribeToBranchChanged(schedule),
+ subscribeToDocumentsChanged((channels) => {
+ if (invalidatesLocalTargetAudit(channels)) schedule();
+ }),
];
return () => {
diff --git a/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx b/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx
index 6cd9e5cd6..00936c0ef 100644
--- a/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx
+++ b/packages/app/src/components/file-tree-problem-indicators.dom.test.tsx
@@ -57,11 +57,16 @@ describe('applyProblemIndicators', () => {
const errorRow = rows.get('a.md');
expect(errorRow?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('error');
- expect(errorRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('3');
+ const errorBadge = errorRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`);
+ expect(errorBadge?.textContent).toBe('3');
+ expect(errorBadge?.getAttribute('aria-label')).toBe('3 problems: 2 errors, 1 warning');
+ expect(errorBadge?.hasAttribute('aria-hidden')).toBe(false);
const warningRow = rows.get('guides/b.md');
expect(warningRow?.getAttribute(OK_PROBLEM_ROW_ATTR)).toBe('warning');
- expect(warningRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`)?.textContent).toBe('4');
+ const warningBadge = warningRow?.querySelector(`[${OK_PROBLEM_BADGE_ATTR}]`);
+ expect(warningBadge?.textContent).toBe('4');
+ expect(warningBadge?.getAttribute('aria-label')).toBe('4 problems: 0 errors, 4 warnings');
const cleanRow = rows.get('clean.md');
expect(cleanRow?.hasAttribute(OK_PROBLEM_ROW_ATTR)).toBe(false);
diff --git a/packages/app/src/components/file-tree-problem-indicators.ts b/packages/app/src/components/file-tree-problem-indicators.ts
index cb67c7880..645258694 100644
--- a/packages/app/src/components/file-tree-problem-indicators.ts
+++ b/packages/app/src/components/file-tree-problem-indicators.ts
@@ -78,7 +78,7 @@ export function applyProblemIndicators(
if (row.getAttribute(OK_PROBLEM_ROW_ATTR) !== severity) {
row.setAttribute(OK_PROBLEM_ROW_ATTR, severity);
}
- upsertProblemBadge(row, entry.errorCount + entry.warningCount);
+ upsertProblemBadge(row, entry);
}
}
@@ -93,13 +93,21 @@ function clearProblemIndicators(row: HTMLElement): void {
* extension badge already in that position so the order reads
* `[label] [decoration?] [EXT?] [count] [action ···]`.
*/
-function upsertProblemBadge(row: HTMLElement, total: number): void {
+function problemBadgeLabel(counts: DocProblemCounts): string {
+ const total = counts.errorCount + counts.warningCount;
+ const problems = total === 1 ? 'problem' : 'problems';
+ const errors = counts.errorCount === 1 ? 'error' : 'errors';
+ const warnings = counts.warningCount === 1 ? 'warning' : 'warnings';
+ return `${total} ${problems}: ${counts.errorCount} ${errors}, ${counts.warningCount} ${warnings}`;
+}
+
+function upsertProblemBadge(row: HTMLElement, counts: DocProblemCounts): void {
+ const total = counts.errorCount + counts.warningCount;
const label = total > 99 ? '99+' : String(total);
let badge = row.querySelector<HTMLSpanElement>(`[${OK_PROBLEM_BADGE_ATTR}]`);
if (!badge) {
badge = row.ownerDocument.createElement('span');
badge.setAttribute(OK_PROBLEM_BADGE_ATTR, '');
- badge.setAttribute('aria-hidden', 'true');
const actionSection = row.querySelector('[data-item-section="action"]');
if (actionSection) {
actionSection.before(badge);
@@ -108,4 +116,8 @@ function upsertProblemBadge(row: HTMLElement, total: number): void {
}
}
if (badge.textContent !== label) badge.textContent = label;
+ const accessibleLabel = problemBadgeLabel(counts);
+ if (badge.getAttribute('aria-label') !== accessibleLabel) {
+ badge.setAttribute('aria-label', accessibleLabel);
+ }
}
diff --git a/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx b/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx
index fd93fef0b..136b37614 100644
--- a/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx
+++ b/packages/app/src/components/settings/ContentRulesSection.dom.test.tsx
@@ -57,6 +57,7 @@ describe('ContentRulesSection', () => {
test('defaults read as links=warning and indicators on, with the plugins pointer', () => {
render(<ContentRulesSection />);
expect(screen.getByTestId('settings-content-rules-links').textContent).toContain('Warning');
+ expect(screen.getByText(/missing project-local documents, files, and images/)).toBeTruthy();
const toggle = screen.getByTestId('settings-content-rules-indicators');
expect(toggle.getAttribute('data-state')).toBe('checked');
expect(screen.getByTestId('settings-content-rules-plugins-note').textContent).toContain(
@@ -76,7 +77,10 @@ describe('ContentRulesSection', () => {
test('both controls are described by their own row description', () => {
render(<ContentRulesSection />);
for (const [testId, expected] of [
- ['settings-content-rules-links', 'How unresolved wiki-links are reported'],
+ [
+ 'settings-content-rules-links',
+ 'How missing project-local documents, files, and images are reported',
+ ],
['settings-content-rules-indicators', 'Tint and badge files'],
] as const) {
expect(describedTextOf(testId)).toContain(expected);
diff --git a/packages/app/src/components/settings/ContentRulesSection.tsx b/packages/app/src/components/settings/ContentRulesSection.tsx
index 649e02bc3..3e2a32b84 100644
--- a/packages/app/src/components/settings/ContentRulesSection.tsx
+++ b/packages/app/src/components/settings/ContentRulesSection.tsx
@@ -71,8 +71,8 @@ export function ContentRulesSection() {
className="text-1sm text-muted-foreground"
>
<Trans>
- How unresolved wiki-links are reported in the Problems panel, audits, and agent
- tools.
+ How missing project-local documents, files, and images are reported in Problems,
+ editor diagnostics, audits, and agent tools.
</Trans>
</p>
</div>
diff --git a/packages/app/src/components/ui/loading-image.dom.test.tsx b/packages/app/src/components/ui/loading-image.dom.test.tsx
new file mode 100644
index 000000000..d69258751
--- /dev/null
+++ b/packages/app/src/components/ui/loading-image.dom.test.tsx
@@ -0,0 +1,149 @@
+/**
+ * Behavioral tests for LoadingImage's target-existence-aware placeholder
+ * contract. Existence is supplied directly via the `targetExistence` prop
+ * (the WYSIWYG oracle wiring is exercised separately in Image.dom.test.tsx),
+ * so every case here is a deterministic pin on the presentation state machine:
+ * proven-absent → "Image not found"; present/unknown display failure → "Image
+ * couldn't be displayed"; heal on target creation; break on target deletion;
+ * clipboard/DOM fidelity of the hidden authored <img>.
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { LoadingImage } from './loading-image';
+
+describe('LoadingImage — truthful placeholders', () => {
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ consoleErrorSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test('proven-missing target shows "Image not found" without a load attempt', () => {
+ render(<LoadingImage src="/images/ghost.png" alt="" targetExistence="missing" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error')).toBe('true');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('not-found');
+ // No load event fired — the placeholder is authoritative from the oracle,
+ // and the skeleton is not left announcing forever.
+ expect(screen.queryByTestId('image-loading-skeleton')).toBeNull();
+
+ const overlay = slot.querySelector('[role="img"]');
+ expect(overlay).not.toBeNull();
+ expect(overlay?.classList.contains('ok-image-error-placeholder')).toBe(true);
+ expect(overlay?.getAttribute('aria-label')).toBe('Image not found: /images/ghost.png');
+ expect(overlay?.textContent).toContain('Image not found');
+ expect(overlay?.querySelector('.ok-image-error-target')?.textContent).toBe('/images/ghost.png');
+ // Non-color cue: an icon accompanies the text (aria-hidden so it isn't
+ // announced twice), so the state is not conveyed by color alone.
+ expect(overlay?.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+ });
+
+ test('present target that fails to display says "couldn\'t be displayed", not absent', () => {
+ const { container } = render(
+ <LoadingImage src="/images/corrupt.png" alt="" targetExistence="exists" />,
+ );
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ const overlay = slot.querySelector('[role="img"]');
+ expect(overlay?.classList.contains('ok-image-error-placeholder')).toBe(true);
+ expect(overlay?.getAttribute('aria-label')).toBe(
+ "Image couldn't be displayed: /images/corrupt.png",
+ );
+ expect(overlay?.querySelector('.ok-image-error-target')?.textContent).toBe(
+ '/images/corrupt.png',
+ );
+ expect(overlay?.textContent).toContain("Image couldn't be displayed");
+ expect(overlay?.textContent).not.toContain('not found');
+ });
+
+ test('unknown existence never claims absence on a load failure', () => {
+ // Default targetExistence is 'unknown' (no oracle / off-project src). A
+ // failure must read as "couldn't be displayed", not "not found".
+ const { container } = render(<LoadingImage src="https://cdn.example.com/x.png" alt="" />);
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.textContent).toContain("couldn't be displayed");
+ });
+
+ test('present target that loads renders the image with no placeholder', () => {
+ const { container } = render(
+ <LoadingImage src="/images/cat.png" alt="a cat" targetExistence="exists" />,
+ );
+ fireEvent.load(container.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error')).toBeNull();
+ expect(slot.querySelector('[role="img"]')).toBeNull();
+ const img = slot.querySelector('img');
+ expect(img?.hasAttribute('hidden')).toBe(false);
+ expect(img?.getAttribute('src')).toBe('/images/cat.png');
+ });
+
+ test('creating the target heals "not found" back to a fresh load', () => {
+ const { rerender } = render(
+ <LoadingImage src="/images/created.png" alt="" targetExistence="missing" />,
+ );
+ expect(screen.getByTestId('image-slot').getAttribute('data-image-error')).toBe('true');
+
+ // Target created on disk → oracle flips missing → exists.
+ rerender(<LoadingImage src="/images/created.png" alt="" targetExistence="exists" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error')).toBeNull();
+ // Remounted to re-request: skeleton returns until the fresh load resolves,
+ // and the img is visible again (not hidden).
+ expect(screen.queryByTestId('image-loading-skeleton')).not.toBeNull();
+ expect(slot.querySelector('img')?.hasAttribute('hidden')).toBe(false);
+ });
+
+ test('deleting the target after a successful load breaks to "Image not found"', () => {
+ const { container, rerender } = render(
+ <LoadingImage src="/images/live.png" alt="" targetExistence="exists" />,
+ );
+ fireEvent.load(container.querySelector('img') as HTMLImageElement);
+ expect(screen.getByTestId('image-slot').getAttribute('data-image-error')).toBeNull();
+
+ // Target deleted on disk → oracle flips exists → missing, over the loaded
+ // bitmap.
+ rerender(<LoadingImage src="/images/live.png" alt="" targetExistence="missing" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('not-found');
+ expect(slot.querySelector('[role="img"]')?.textContent).toContain('Image not found');
+ expect(slot.querySelector('img')?.hasAttribute('hidden')).toBe(true);
+ });
+
+ test('placeholder chrome is clipboard-opt-out while the hidden <img> keeps the authored src', () => {
+ render(<LoadingImage src="/images/ghost.png" alt="" targetExistence="missing" />);
+ const slot = screen.getByTestId('image-slot');
+
+ const optOut = slot.querySelector('[data-clipboard-omit="true"]');
+ expect(optOut).not.toBeNull();
+ expect(optOut?.textContent).toContain('Image not found');
+ const img = slot.querySelector('img');
+ expect(img?.getAttribute('data-clipboard-omit')).toBeNull();
+ expect(img?.hasAttribute('hidden')).toBe(true);
+ expect(img?.getAttribute('src')).toBe('/images/ghost.png');
+ });
+
+ test('a non-decorative alt is used as the accessible target context', () => {
+ render(<LoadingImage src="/images/ghost.png" alt="team photo" targetExistence="missing" />);
+ expect(
+ screen.getByTestId('image-slot').querySelector('[role="img"]')?.getAttribute('aria-label'),
+ ).toBe('Image not found: team photo');
+ });
+});
diff --git a/packages/app/src/components/ui/loading-image.tsx b/packages/app/src/components/ui/loading-image.tsx
index 1a03b02b3..d8d4c3c20 100644
--- a/packages/app/src/components/ui/loading-image.tsx
+++ b/packages/app/src/components/ui/loading-image.tsx
@@ -1,8 +1,9 @@
import { useLingui } from '@lingui/react/macro';
import { ImageOff } from 'lucide-react';
import type { CSSProperties, ImgHTMLAttributes } from 'react';
-import { useLayoutEffect, useRef, useState } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { OPT_OUT_ATTR } from '@/editor/clipboard/clipboard-sanitize';
+import type { ImageTargetExistence } from '@/editor/components/image-target-existence';
import { cn } from '@/lib/utils';
type LoadingImageProps = ImgHTMLAttributes<HTMLImageElement> & {
@@ -11,8 +12,21 @@ type LoadingImageProps = ImgHTMLAttributes<HTMLImageElement> & {
loadingTestId?: string;
slotTestId?: string;
slotClassName?: string;
+ /**
+ * Server/inventory-known existence of the target the src points at, kept
+ * distinct from whether the `<img>` decoded. `'missing'` (proven absent)
+ * renders the "Image not found" placeholder authoritatively — even before a
+ * load attempt and even over a stale cached bitmap — so a deleted target
+ * heals to the truthful state. `'exists'` / `'unknown'` never claim absence:
+ * a decode/permission/serving failure there reads "Image couldn't be
+ * displayed". Defaults to `'unknown'`.
+ */
+ targetExistence?: ImageTargetExistence;
};
+/** Which truthful placeholder to show, or none. */
+type ImageErrorKind = 'not-found' | 'undisplayable' | null;
+
function hasIntrinsicDimensions(
width: number | string | undefined,
height: number | string | undefined,
@@ -47,55 +61,102 @@ export function LoadingImage({
src,
style,
alt = '',
+ targetExistence = 'unknown',
...imgProps
}: LoadingImageProps) {
const { t } = useLingui();
const imgRef = useRef<HTMLImageElement>(null);
const [loaded, setLoaded] = useState(false);
const [hasError, setHasError] = useState(false);
+ // Bumped when a proven-missing target becomes present, to remount the
+ // cached-failed <img> and force a fresh request (see the healing effect).
+ const [reloadNonce, setReloadNonce] = useState(0);
const intrinsic = hasIntrinsicDimensions(width, height);
const slotStyle = computeSlotStyle(width, height, style);
// Cached or preloaded images may be `complete` at mount and never fire
- // onLoad after React commits — the skeleton would otherwise persist
+ // onLoad/onError after React commits — the skeleton would otherwise persist
// forever and the <img> stay stuck at opacity-0. Treating `complete` as
// the terminal-state signal dismisses the skeleton in that case.
- // Re-running on src change resets both flags when the same instance is
- // reused with a new src (e.g. AssetPreview switching assets).
- // biome-ignore lint/correctness/useExhaustiveDependencies: src drives the reactive trigger only; the effect body reads imgRef.current so biome flags src as unused.
+ // Re-running on src / reloadNonce change resets both flags when the same
+ // instance is reused with a new src (AssetPreview switching assets) or
+ // remounted to re-request a now-present target.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: src + reloadNonce drive the reactive trigger; the effect body reads imgRef.current so biome flags them as unused.
useLayoutEffect(() => {
const img = imgRef.current;
if (img?.complete) {
+ // `complete && naturalWidth === 0` is NOT read as failure: per the HTML
+ // spec that shape is also a successful load of a dimensionless resource
+ // (SVG with only a viewBox, images sized by CSS). Treat complete as
+ // loaded and let decode() — the only unambiguous cached signal — flip to
+ // error when the bytes genuinely can't be decoded.
setLoaded(true);
+ setHasError(false);
+ // R7/R10 boundary: HTMLImageElement.decode() is a browser API; a real
+ // EncodingError rejection is the cached decode/serve failure this handler
+ // exists for (fresh loads take the onError path instead). Absent in
+ // jsdom (feature-detected out), covered for real by the browser e2e.
+ if (typeof img.decode === 'function') {
+ let cancelled = false;
+ void img.decode().then(
+ () => {},
+ () => {
+ if (!cancelled) setHasError(true);
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }
} else {
setLoaded(false);
+ setHasError(false);
}
- // NOTE: don't try to infer error from `complete && naturalWidth === 0`
- // — per the HTML spec that shape is also produced by a successful
- // load of a dimensionless resource (SVG with only a viewBox, images
- // sized by CSS). onError is the only unambiguous signal.
- setHasError(false);
- }, [src]);
+ }, [src, reloadNonce]);
+
+ // Heal a proven-missing target that becomes present (created / renamed on
+ // disk — the CC1 `files` push flips `targetExistence`). The cached <img>
+ // still holds its failed fetch, so reset and bump the remount nonce to
+ // re-request the now-existing bytes rather than sit on "not found".
+ const prevExistenceRef = useRef(targetExistence);
+ useEffect(() => {
+ const prev = prevExistenceRef.current;
+ prevExistenceRef.current = targetExistence;
+ if (prev === 'missing' && targetExistence !== 'missing') {
+ setLoaded(false);
+ setHasError(false);
+ setReloadNonce((n) => n + 1);
+ }
+ }, [targetExistence]);
+
+ // Target-existence truth is authoritative over image-render truth: a proven-
+ // absent target says "not found" regardless of any cached bitmap; only when
+ // the target is present or unknown does a decode/serve failure say
+ // "couldn't be displayed" (never claiming absence it can't prove).
+ const errorKind: ImageErrorKind =
+ targetExistence === 'missing' ? 'not-found' : hasError ? 'undisplayable' : null;
- // A visible placeholder overlay replaces the browser's default 16x16
- // broken-image glyph so the reader can tell the asset is missing instead
- // of assuming the block rendered empty. The <img> stays mounted (hidden
- // via CSS) so consumers that inspect the DOM — clipboard walker, prop
- // panel, e2e tests reading img.src — still find it with the authored
- // src, matching the storage-layer fidelity contract (bytes land verbatim
- // in the CRDT even when the render layer shows a fallback).
- //
- // Always announce on error: `alt` at this layer conflates "author opted
- // in to decorative" with "no alt was authored" (Image.tsx coerces
- // `props.alt ?? ''`, and `![](/x.png)` markdown reaches here with
- // alt=''). Silencing the pill for alt='' would silence broken
- // no-alt-authored images too.
+ // Always announce on error: `alt` at this layer conflates "author opted in to
+ // decorative" with "no alt was authored" (Image.tsx coerces `props.alt ?? ''`,
+ // and `![](/x.png)` reaches here with alt=''). Silencing for alt='' would
+ // silence broken no-alt-authored images too. The label carries target context.
const errorLabel = alt && alt.length > 0 ? alt : (src ?? '');
+ const errorMessage =
+ errorKind === 'not-found' ? t`Image not found` : t`Image couldn't be displayed`;
+ const errorAriaLabel =
+ errorKind === 'not-found'
+ ? t`Image not found: ${errorLabel}`
+ : t`Image couldn't be displayed: ${errorLabel}`;
return (
<span
data-testid={slotTestId}
- data-image-error={hasError ? 'true' : undefined}
+ // `data-image-error="true"` stays the exact marker the clipboard walker's
+ // `unhideErrorSlotImages` scopes its hidden-<img> un-hide to — both
+ // placeholder kinds carry it so a broken-but-portable image still pastes
+ // as a plain <img> with its authored src.
+ data-image-error={errorKind ? 'true' : undefined}
+ data-image-error-kind={errorKind ?? undefined}
className={cn(
'relative inline-block overflow-hidden',
// Pre-load only: reserve a 16:9 slot to prevent the "0x0 box → reflow"
@@ -103,12 +164,12 @@ export function LoadingImage({
// object-contain / max-h-full styling can govern the image's
// natural shape — otherwise sidebar previews would be locked at 16:9
// forever, letterboxing portrait assets.
- !intrinsic && !loaded && !hasError && 'aspect-[16/9] w-full max-w-full',
+ !intrinsic && !loaded && !errorKind && 'aspect-[16/9] w-full max-w-full',
slotClassName,
)}
style={slotStyle}
>
- {!loaded && !hasError && (
+ {!loaded && !errorKind && (
// Inline-content the skeleton element directly rather than reaching for
// shadcn `<Skeleton>` (which is a `<div>`). The slot is a `<span>`
// because `Image.tsx`'s `<Zoom wrapElement="span">` constrains its
@@ -126,15 +187,19 @@ export function LoadingImage({
)}
<img
{...imgProps}
+ // Remount on heal so a cached-failed request is re-issued for a
+ // now-present target. Same authored src is preserved (no cache-busting
+ // query), keeping clipboard / DOM-inspection fidelity intact.
+ key={reloadNonce}
ref={imgRef}
src={src}
alt={alt}
width={width}
height={height}
// `hidden` keeps the img in the DOM (queryable by tests + the
- // clipboard walker) but out of the visual + a11y trees when the
- // error placeholder is showing.
- hidden={hasError || undefined}
+ // clipboard walker) but out of the visual + a11y trees when a
+ // placeholder is showing.
+ hidden={errorKind ? true : undefined}
className={cn(
'block max-w-full transition-opacity motion-reduce:transition-none',
loaded ? 'opacity-100' : 'opacity-0',
@@ -154,25 +219,30 @@ export function LoadingImage({
onError?.(event);
}}
/>
- {hasError && (
+ {errorKind && (
<span
role="img"
- aria-label={t`Image failed to load: ${errorLabel}`}
+ aria-label={errorAriaLabel}
// Render-layer chrome only: the clipboard walker strips opt-out
// children from cross-app copies, so the pill text never pastes
// as if it were document content. The hidden <img> sibling stays
// in the clone and carries the authored src (the walker's
// error-slot un-hide pass drops the hidden attr from the clone).
{...{ [OPT_OUT_ATTR]: 'true' }}
- className="inline-flex max-w-full items-center gap-2 rounded-md border border-dashed border-border bg-muted/40 px-2 py-1 text-muted-foreground"
+ className="ok-image-error-placeholder box-border inline-grid max-w-full grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2 rounded-md border border-dashed px-2 py-1 text-foreground"
>
- <ImageOff aria-hidden="true" className="size-3.5 shrink-0 opacity-70" />
- <span className="text-xs font-medium">{t`Image failed to load`}</span>
- {src ? (
- <span className="max-w-[24ch] truncate font-mono text-xs opacity-70" title={src}>
- {src}
- </span>
- ) : null}
+ <ImageOff aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <span className="min-w-0">
+ <span className="ok-image-error-message block text-xs font-medium">{errorMessage}</span>
+ {src ? (
+ <span
+ className="ok-image-error-target block max-w-[24ch] truncate font-mono text-xs"
+ title={src}
+ >
+ {src}
+ </span>
+ ) : null}
+ </span>
</span>
)}
</span>
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index 054590545..80af004dc 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -45,6 +45,7 @@ import {
} from './source-editor-navigation';
import { sourceHeadingLines } from './source-heading-lines';
import { sourceLineDirection } from './source-line-direction';
+import { createLocalTargetDiagnosticsExtension } from './source-lint/local-target-diagnostics';
import { createMarkdownLintExtension } from './source-lint/markdown-lint-source';
import { sourceModeSetup } from './source-mode-setup';
import { createSourcePolishExtension } from './source-polish';
@@ -309,6 +310,12 @@ export function SourceEditor({
// Transient highlight for a mode-switch jump that lands in source.
landingFlashSource(),
lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),
+ // Server-authoritative target-existence diagnostics (missing local
+ // files/images/documents + reference-style targets). Separate from
+ // the markdownlint compartment above: it follows `validation.links`
+ // server-side, not the markdownlint enabled flag, and fetches its
+ // own findings rather than re-linting off the doc text.
+ createLocalTargetDiagnosticsExtension(docName),
sourceClipboard,
// A user edit promotes this doc's preview tab to permanent. Safe to
// capture `resolvedDocName` in the closure even though the view
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index beb0d8211..02d18387c 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -56,6 +56,7 @@ import {
createHandlePaste,
} from './clipboard/index.ts';
import { useDocumentContext } from './DocumentContext';
+import { createBareHtmlImageDecoration } from './extensions/bare-html-image-decoration';
import { setEditorDocName } from './extensions/doc-context.ts';
import { setEditorSourceMode } from './extensions/editor-mode-context.ts';
import { FrozenTableHeaders } from './extensions/frozen-table-headers.ts';
@@ -385,14 +386,21 @@ export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[]
const { collaboration, guard } = buildPrewarmBoundCollaboration(provider, prebuiltMapping);
return [
// Configure docName-aware extensions before construction. Link extensions
- // use it for resolved/folder/unresolved states; jsxComponent uses it to
- // normalize doc-relative media src values while rendering raw JSX/MDX.
+ // use it for resolved/folder/unresolved states; render-time media nodes use
+ // it to normalize doc-relative src values on their initial render.
...sharedExtensions.map((ext) => {
- if (ext.name === 'link' || ext.name === 'wikiLink' || ext.name === 'jsxComponent') {
+ if (
+ ext.name === 'link' ||
+ ext.name === 'wikiLink' ||
+ ext.name === 'jsxComponent' ||
+ ext.name === 'jsxInline' ||
+ ext.name === 'imageReference'
+ ) {
return ext.configure({ docName: provider.configuration.name ?? '' });
}
return ext;
}),
+ createBareHtmlImageDecoration(provider.configuration.name ?? ''),
Placeholder.configure({
// A getter, not a string: extensions are built once at editor
// construction, so a resolved string would pin the placeholder to
diff --git a/packages/app/src/editor/clipboard/clipboard-walker.test.ts b/packages/app/src/editor/clipboard/clipboard-walker.test.ts
index f72f5c0de..54a068580 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker.test.ts
@@ -1318,15 +1318,21 @@ function wrapUnhideNode(node: UnhideFakeNode): Element {
}
describe('unhideErrorSlotImages — error-render-state normalization', () => {
- test('strips hidden from the img inside an error slot and drops the slot marker', () => {
+ test('strips hidden from the img inside an error slot and drops the slot markers', () => {
const img = makeUnhideNode('img', { src: 'https://example.com/x.png', hidden: '' });
- const slot = makeUnhideNode('span', { 'data-image-error': 'true' }, [img]);
+ const slot = makeUnhideNode(
+ 'span',
+ { 'data-image-error': 'true', 'data-image-error-kind': 'not-found' },
+ [img],
+ );
const root = makeUnhideNode('div', {}, [slot]);
unhideErrorSlotImages(wrapUnhideNode(root));
expect('hidden' in img.attrs).toBe(false);
expect('data-image-error' in slot.attrs).toBe(false);
+ // The error-kind marker is render-layer state too and must not survive.
+ expect('data-image-error-kind' in slot.attrs).toBe(false);
expect(img.attrs.src).toBe('https://example.com/x.png');
});
diff --git a/packages/app/src/editor/clipboard/clipboard-walker.ts b/packages/app/src/editor/clipboard/clipboard-walker.ts
index ee3390312..fc44eedc9 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker.ts
@@ -649,7 +649,12 @@ function replaceLucideIconsWithGlyphs(root: Element): void {
*/
export function unhideErrorSlotImages(clone: Element, inErrorSlot = false): void {
const isErrorSlot = clone.getAttribute('data-image-error') === 'true';
- if (isErrorSlot) clone.removeAttribute('data-image-error');
+ if (isErrorSlot) {
+ clone.removeAttribute('data-image-error');
+ // Sibling render-state marker (missing vs undisplayable) — strip it with
+ // the same scoping so no placeholder chrome bleeds into the clone.
+ clone.removeAttribute('data-image-error-kind');
+ }
const active = inErrorSlot || isErrorSlot;
if (active && clone.tagName.toLowerCase() === 'img') {
clone.removeAttribute('hidden');
diff --git a/packages/app/src/editor/components/Image.dom.test.tsx b/packages/app/src/editor/components/Image.dom.test.tsx
index 19d3cf917..299d03e4c 100644
--- a/packages/app/src/editor/components/Image.dom.test.tsx
+++ b/packages/app/src/editor/components/Image.dom.test.tsx
@@ -38,6 +38,25 @@ vi.doMock('react-medium-image-zoom', () => ({
default: ({ children }: { children: React.ReactNode }) => children,
}));
+// The project inventory that feeds target-existence classification is a
+// fetched-from-`/api/documents` boundary; stub it here (null = no provider, the
+// same "unknown" state a portal/renderToString render sees). Only the fields
+// the classifier reads are supplied.
+type StubPageList = { assetPaths: Set<string>; filePaths: Set<string>; loading: boolean };
+let currentPageList: StubPageList | null = null;
+vi.doMock('@/components/PageListContext', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/components/PageListContext')>();
+ return {
+ ...actual,
+ useOptionalPageList: () =>
+ currentPageList as unknown as ReturnType<typeof actual.useOptionalPageList>,
+ };
+});
+
+beforeEach(() => {
+ currentPageList = null;
+});
+
const { Image } = await import('./Image');
describe('Image — loading-state placeholder (PRD-6638)', () => {
@@ -161,7 +180,9 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
// DOM (hidden) so consumers can still inspect src.
const overlay = slot.querySelector('[role="img"]');
expect(overlay).not.toBeNull();
- expect(overlay?.getAttribute('aria-label')).toBe('Image failed to load: /missing.png');
+ // No project inventory (currentPageList = null) → 'unknown' existence → a
+ // load failure reads as undisplayable, never claiming the target is absent.
+ expect(overlay?.getAttribute('aria-label')).toBe("Image couldn't be displayed: /missing.png");
expect(slot.getAttribute('aria-hidden')).toBeNull();
// Img stays mounted (hidden) so tests + walkers can still find its src.
const img = slot.querySelector('img');
@@ -180,7 +201,7 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
fireEvent.error(container.querySelector('img') as HTMLImageElement);
const slot = screen.getByTestId('image-slot');
const overlay = slot.querySelector('[role="img"]');
- expect(overlay?.getAttribute('aria-label')).toBe('Image failed to load: a cat photo');
+ expect(overlay?.getAttribute('aria-label')).toBe("Image couldn't be displayed: a cat photo");
expect(slot.getAttribute('aria-hidden')).toBeNull();
// Img stays mounted (hidden) in the alt-provided branch too, so DOM
// inspectors can still find src regardless of alt shape.
@@ -211,7 +232,7 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
expect(screen.queryByTestId('image-loading-skeleton')).toBeNull();
const slot = screen.getByTestId('image-slot');
expect(slot.getAttribute('data-image-error')).toBe('true');
- expect(slot.textContent).toContain('Image failed to load');
+ expect(slot.textContent).toContain("Image couldn't be displayed");
expect(slot.textContent).toContain('/missing-asset.png');
// Stays inline for phrasing-content compatibility with <p>.
expect(slot.tagName).toBe('SPAN');
@@ -237,7 +258,7 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
const slot = screen.getByTestId('image-slot');
const optOut = slot.querySelector('[data-clipboard-omit="true"]');
expect(optOut).not.toBeNull();
- expect(optOut?.textContent).toContain('Image failed to load');
+ expect(optOut?.textContent).toContain("Image couldn't be displayed");
const img = slot.querySelector('img');
expect(img?.getAttribute('data-clipboard-omit')).toBeNull();
});
@@ -284,3 +305,79 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
expect(imgAfterRecovery?.hasAttribute('hidden')).toBe(false);
});
});
+
+describe('Image — target-existence wiring (PRD-7860)', () => {
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ consoleErrorSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ function seedInventory(assetPaths: string[], filePaths: string[] = []) {
+ currentPageList = {
+ assetPaths: new Set(assetPaths),
+ filePaths: new Set(filePaths),
+ loading: false,
+ };
+ }
+
+ test('a src the inventory does not contain renders "Image not found" with no load attempt', () => {
+ seedInventory(['images/present.png']);
+ render(<Image src="/images/ghost.png" alt="" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('not-found');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ 'Image not found: /images/ghost.png',
+ );
+ // The authored src is still queryable on the hidden <img> for clipboard.
+ const img = slot.querySelector('img');
+ expect(img?.hasAttribute('hidden')).toBe(true);
+ expect(img?.getAttribute('src')).toBe('/images/ghost.png');
+ });
+
+ test('a tracked src that loads shows the image with no placeholder', () => {
+ seedInventory(['images/cat.png']);
+ const { container } = render(<Image src="/images/cat.png" alt="" />);
+ fireEvent.load(container.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error')).toBeNull();
+ expect(slot.querySelector('[role="img"]')).toBeNull();
+ });
+
+ test('a tracked src that fails to display says "couldn\'t be displayed", not missing', () => {
+ seedInventory(['images/cat.png']);
+ const { container } = render(<Image src="/images/cat.png" alt="" />);
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.textContent).toContain("couldn't be displayed");
+ });
+
+ test('creating the target on disk heals "not found" to a fresh load', () => {
+ seedInventory([]);
+ const { rerender } = render(<Image src="/images/created.png" alt="" />);
+ expect(screen.getByTestId('image-slot').getAttribute('data-image-error-kind')).toBe(
+ 'not-found',
+ );
+
+ // Target lands on disk → the next `/api/documents` snapshot lists it →
+ // the oracle flips missing → exists on re-render.
+ seedInventory(['images/created.png']);
+ rerender(<Image src="/images/created.png" alt="" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error')).toBeNull();
+ expect(screen.queryByTestId('image-loading-skeleton')).not.toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/components/Image.tsx b/packages/app/src/editor/components/Image.tsx
index 77470012f..89db35322 100644
--- a/packages/app/src/editor/components/Image.tsx
+++ b/packages/app/src/editor/components/Image.tsx
@@ -37,8 +37,9 @@ import { toDesktopAssetHref } from '@inkeep/open-knowledge-core';
import type { ImgHTMLAttributes } from 'react';
import Zoom from 'react-medium-image-zoom';
import { LoadingImage } from '@/components/ui/loading-image';
+import { useImageTargetExistence } from './image-target-existence';
-interface ImageProps {
+export interface ImageProps {
src?: string;
alt?: string;
width?: number | string;
@@ -71,7 +72,12 @@ function coerceDimension(value: number | string | undefined): number | string |
* without document reflow. Translates lowercase HTML-attr names to React's
* camelCase at this JSX boundary.
*/
-function BareImg(props: ImageProps) {
+export function BareImg(props: ImageProps) {
+ // Classify against the project inventory on the pre-desktop-href src (the
+ // normalized server-absolute form) so a proven-absent target renders "Image
+ // not found" while a present one that fails to decode reads "couldn't be
+ // displayed" — and either heals as the target is created/deleted on disk.
+ const targetExistence = useImageTargetExistence(props.src);
return (
<LoadingImage
src={props.src === undefined ? undefined : toDesktopAssetHref(props.src)}
@@ -86,6 +92,7 @@ function BareImg(props: ImageProps) {
fetchPriority={props.fetchpriority}
crossOrigin={props.crossorigin}
referrerPolicy={props.referrerpolicy}
+ targetExistence={targetExistence}
/>
);
}
diff --git a/packages/app/src/editor/components/image-target-existence.test.ts b/packages/app/src/editor/components/image-target-existence.test.ts
new file mode 100644
index 000000000..d0005ce6c
--- /dev/null
+++ b/packages/app/src/editor/components/image-target-existence.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, test } from 'vitest';
+import { classifyImageTargetExistence } from './image-target-existence';
+
+describe('classifyImageTargetExistence', () => {
+ test('server-absolute src present in the referenced-asset set is exists', () => {
+ const state = classifyImageTargetExistence(
+ '/images/cat.png',
+ '',
+ new Set(['images/cat.png']),
+ undefined,
+ );
+ expect(state).toBe('exists');
+ });
+
+ test('server-absolute src present only in the tracked-file set is exists', () => {
+ // An unreferenced image on disk surfaces as a `kind:'file'` row, not a
+ // referenced asset — the union of both partitions is the existence oracle.
+ const state = classifyImageTargetExistence(
+ '/pics/loose.png',
+ '',
+ new Set(),
+ new Set(['pics/loose.png']),
+ );
+ expect(state).toBe('exists');
+ });
+
+ test('project-local src in neither partition is missing', () => {
+ const state = classifyImageTargetExistence(
+ '/images/ghost.png',
+ '',
+ new Set(['images/cat.png']),
+ new Set(['data/example.csv']),
+ );
+ 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,
+ );
+ expect(state).toBe('exists');
+ });
+
+ test('external URL is unknown — absence from the inventory proves nothing', () => {
+ expect(
+ classifyImageTargetExistence('https://cdn.example.com/a.png', '', new Set(), new Set()),
+ ).toBe('unknown');
+ });
+
+ test('protocol-relative src is unknown', () => {
+ expect(classifyImageTargetExistence('//host/a.png', '', new Set(), new Set())).toBe('unknown');
+ });
+
+ test('anchor-only src is unknown', () => {
+ expect(classifyImageTargetExistence('#section', '', new Set(), new Set())).toBe('unknown');
+ });
+
+ test('traversal escape past the content root is unknown, not missing', () => {
+ // A `..` that pops above the root resolves to no project path, so it must
+ // not be reported as a missing project-local file.
+ expect(classifyImageTargetExistence('../../../etc/passwd.png', '', new Set(), new Set())).toBe(
+ 'unknown',
+ );
+ });
+
+ test('a doc-relative src resolves against the source doc directory', () => {
+ // The rare un-normalized relative form still classifies correctly when a
+ // source doc is supplied.
+ expect(
+ classifyImageTargetExistence(
+ './cat.png',
+ 'folder/note',
+ new Set(['folder/cat.png']),
+ undefined,
+ ),
+ ).toBe('exists');
+ expect(
+ classifyImageTargetExistence(
+ './ghost.png',
+ 'folder/note',
+ new Set(['folder/cat.png']),
+ undefined,
+ ),
+ ).toBe('missing');
+ });
+
+ test('undefined inventory partitions classify a resolvable src as missing', () => {
+ // Both partitions absent (cold/legacy snapshot) — a resolvable project path
+ // with no inventory to confirm it is treated as missing by this pure
+ // function; the hook layer suppresses this during the cold load.
+ expect(classifyImageTargetExistence('/images/cat.png', '', undefined, undefined)).toBe(
+ 'missing',
+ );
+ });
+});
diff --git a/packages/app/src/editor/components/image-target-existence.ts b/packages/app/src/editor/components/image-target-existence.ts
new file mode 100644
index 000000000..e5ae53b27
--- /dev/null
+++ b/packages/app/src/editor/components/image-target-existence.ts
@@ -0,0 +1,64 @@
+/**
+ * Existence signal for a rendered image, resolved against the same
+ * project-local asset/file inventory the link chips use
+ * (`isResolvedAssetHref` + the page-list cache). Separates *target-existence
+ * truth* (does the file the src points at exist in the project?) from
+ * *image-render truth* (did the `<img>` decode?) so the renderer can say
+ * "Image not found" for a proven-absent target and "Image couldn't be
+ * displayed" for a present-but-undecodable one, rather than conflating both
+ * into a single broken state.
+ *
+ * `'unknown'` is the deliberate non-claiming answer: an off-project src
+ * (external URL, traversal escape), an anchor, or a not-yet-loaded inventory
+ * cannot prove absence, so the renderer must not assert "not found".
+ */
+
+import { resolveAssetProjectPath } from '@inkeep/open-knowledge-core';
+import { useOptionalPageList } from '../../components/PageListContext';
+import { isResolvedAssetHref } from '../extensions/link-resolution';
+
+export type ImageTargetExistence = 'exists' | 'missing' | 'unknown';
+
+/**
+ * Pure existence classification for an image src against a project inventory.
+ *
+ * - src that resolves to no project-relative path (external scheme, `//host`,
+ * `#anchor`, or a `..` escape past the content root) → `'unknown'`: it is
+ * not a project-local target, so its absence from the inventory is not
+ * evidence of a missing file.
+ * - project-relative src present in `assetPaths` or `filePaths` (the referenced-
+ * asset and tracked-file partitions of `/api/documents`) → `'exists'`.
+ * - project-relative src in neither partition → `'missing'` (proven absent
+ * under the same ContentFilter admission the server assessment uses).
+ */
+export function classifyImageTargetExistence(
+ src: string,
+ sourceDocName: string,
+ assetPaths: ReadonlySet<string> | undefined,
+ filePaths: ReadonlySet<string> | undefined,
+): ImageTargetExistence {
+ const projectRelPath = resolveAssetProjectPath(src, sourceDocName);
+ if (projectRelPath === null) return 'unknown';
+ return isResolvedAssetHref(src, sourceDocName, assetPaths, filePaths) ? 'exists' : 'missing';
+}
+
+/**
+ * React hook: current existence signal for an image src, reactive to the
+ * page-list cache (which refreshes on the CC1 `files` push, so a target
+ * created/deleted on disk flips this without a reload).
+ *
+ * Server-absolute srcs (the normalized `/contentDir-relative` form the
+ * markdown image path emits) resolve without a source doc, so `''` is passed.
+ * An absent or empty src is invalid and returns `'missing'` immediately.
+ *
+ * For a non-empty src, returns `'unknown'` while no provider is mounted
+ * (portal/test renders) or during the cold page-list load, so an image never
+ * flashes "not found" before the inventory is known.
+ */
+export function useImageTargetExistence(src: string | undefined): ImageTargetExistence {
+ const pageList = useOptionalPageList();
+ if (src === undefined || src === '') return 'missing';
+ if (pageList === null) return 'unknown';
+ if (pageList.loading) return 'unknown';
+ return classifyImageTargetExistence(src, '', pageList.assetPaths, pageList.filePaths);
+}
diff --git a/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx b/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
index b263bfabb..f187be461 100644
--- a/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
@@ -14,7 +14,7 @@
* `render()` — the inline-`<span>` choice IS the assertion.
*/
-import { cleanup, render } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';
vi.doMock('react-medium-image-zoom', () => ({
@@ -127,6 +127,21 @@ describe('ImageInlineZoomView — inline-image lightbox wrap', () => {
expect(img?.getAttribute('title')).toBe('Hover');
});
+ test('an inline Markdown image load failure uses the shared image placeholder', () => {
+ render(
+ <ImageInlineZoomView
+ {...makeNode({ src: '/assets/broken.png', alt: 'Broken inline image' })}
+ />,
+ );
+ fireEvent.error(document.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ "Image couldn't be displayed: Broken inline image",
+ );
+ });
+
test('alt defaults to empty string when PM attrs has no alt — matches descriptor `Image.tsx` decorative-image contract', () => {
render(<ImageInlineZoomView {...makeNode({ src: '/a.png' })} />);
const img = document.querySelector('img');
diff --git a/packages/app/src/editor/extensions/ImageInlineZoomView.tsx b/packages/app/src/editor/extensions/ImageInlineZoomView.tsx
index 9ac4cca23..740ac6710 100644
--- a/packages/app/src/editor/extensions/ImageInlineZoomView.tsx
+++ b/packages/app/src/editor/extensions/ImageInlineZoomView.tsx
@@ -32,10 +32,11 @@
* non-server-baked path).
*/
-import { normalizeDocRelativeAssetUrl, toDesktopAssetHref } from '@inkeep/open-knowledge-core';
+import { normalizeDocRelativeAssetUrl } from '@inkeep/open-knowledge-core';
import type { NodeViewProps } from '@tiptap/core';
import { NodeViewWrapper } from '@tiptap/react';
import Zoom from 'react-medium-image-zoom';
+import { BareImg } from '../components/Image';
import { getEditorDocName } from './doc-context.ts';
export function ImageInlineZoomView({ node, editor }: NodeViewProps) {
@@ -54,15 +55,13 @@ export function ImageInlineZoomView({ node, editor }: NodeViewProps) {
// prior behavior rather than emitting a wrong base.
const sourceDocName = editor ? (getEditorDocName(editor) ?? undefined) : undefined;
const src =
- typeof rawSrc === 'string'
- ? toDesktopAssetHref(normalizeDocRelativeAssetUrl(rawSrc, sourceDocName))
- : undefined;
+ typeof rawSrc === 'string' ? normalizeDocRelativeAssetUrl(rawSrc, sourceDocName) : undefined;
const alt = typeof rawAlt === 'string' ? rawAlt : '';
const title = typeof rawTitle === 'string' ? rawTitle : undefined;
return (
<NodeViewWrapper as="span" data-image-inline-zoom data-clipboard-inline-leaf="image">
<Zoom wrapElement="span" zoomMargin={20} zoomImg={{ sizes: undefined }}>
- <img src={src} alt={alt} title={title} />
+ <BareImg src={src} alt={alt} title={title} />
</Zoom>
</NodeViewWrapper>
);
diff --git a/packages/app/src/editor/extensions/ImageReferenceView.dom.test.tsx b/packages/app/src/editor/extensions/ImageReferenceView.dom.test.tsx
new file mode 100644
index 000000000..fdad2a561
--- /dev/null
+++ b/packages/app/src/editor/extensions/ImageReferenceView.dom.test.tsx
@@ -0,0 +1,107 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { EditorContent, useEditor } from '@tiptap/react';
+import { useEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { afterEach, describe, expect, test } from 'vitest';
+import { ImageReferenceLeaf } from './ImageReferenceView';
+import { sharedExtensions } from './shared';
+
+function Host({ content }: { content: object }) {
+ const editor = useEditor({
+ extensions: sharedExtensions.map((extension) =>
+ extension.name === 'imageReference'
+ ? extension.configure({ docName: 'all-link-types' })
+ : extension,
+ ),
+ content,
+ immediatelyRender: true,
+ });
+ const [portalTarget] = useState(() => document.createElement('div'));
+
+ useEffect(() => {
+ document.body.appendChild(portalTarget);
+ return () => portalTarget.remove();
+ }, [portalTarget]);
+
+ return createPortal(
+ // biome-ignore lint/plugin/no-unportaled-editor-content: portalled per the H6 contract — this IS the sanctioned createPortal shape, in a test harness with a per-render exclusive target
+ <EditorContent editor={editor} />,
+ portalTarget,
+ );
+}
+
+function referenceImageDoc() {
+ return {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'imageReference',
+ attrs: {
+ alt: 'Working reference image',
+ label: 'valid-image',
+ identifier: 'valid-image',
+ referenceType: 'full',
+ },
+ },
+ ],
+ },
+ {
+ type: 'linkRefDef',
+ attrs: { label: 'valid-image', href: 'assets/working.png' },
+ },
+ ],
+ };
+}
+
+describe('ImageReferenceLeaf', () => {
+ afterEach(cleanup);
+
+ test('a reference-style Markdown image failure uses the shared image placeholder', () => {
+ render(<ImageReferenceLeaf src="/assets/missing.png" alt="Missing reference image" />);
+ fireEvent.error(document.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ "Image couldn't be displayed: Missing reference image",
+ );
+ });
+
+ test('a reference-style image without a matching definition renders a not-found placeholder', () => {
+ render(<ImageReferenceLeaf alt="Undefined reference image" />);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('not-found');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ 'Image not found: Undefined reference image',
+ );
+ });
+});
+
+describe('ImageReferenceView', () => {
+ afterEach(cleanup);
+
+ test('normalizes a local definition href against the configured document on initial render', async () => {
+ const desktopWindow = window as typeof window & {
+ okDesktop?: { config: { apiOrigin: string } };
+ };
+ desktopWindow.okDesktop = { config: { apiOrigin: 'http://localhost:53351' } };
+
+ try {
+ render(<Host content={referenceImageDoc()} />);
+
+ await waitFor(() => {
+ expect(
+ document
+ .querySelector<HTMLImageElement>('span[data-image-reference-view] img')
+ ?.getAttribute('src'),
+ ).toBe('http://localhost:53351/assets/working.png');
+ });
+ } finally {
+ delete desktopWindow.okDesktop;
+ }
+ });
+});
diff --git a/packages/app/src/editor/extensions/ImageReferenceView.test.ts b/packages/app/src/editor/extensions/ImageReferenceView.test.ts
new file mode 100644
index 000000000..47eb3a3a3
--- /dev/null
+++ b/packages/app/src/editor/extensions/ImageReferenceView.test.ts
@@ -0,0 +1,37 @@
+import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
+import { resolveImageReferenceHref } from './ImageReferenceView';
+import { sharedExtensions } from './shared';
+
+const schema = getSchema(sharedExtensions);
+
+function makeDoc(...definitions: Array<{ label: string; href: string }>) {
+ return schema.node('doc', undefined, [
+ schema.node('paragraph'),
+ ...definitions.map(({ label, href }) => schema.node('linkRefDef', { label, href })),
+ ]);
+}
+
+describe('resolveImageReferenceHref', () => {
+ test('matches the normalized image identifier to its definition label', () => {
+ const doc = makeDoc({ label: ' Product Shot ', href: './assets/product.png' });
+ expect(resolveImageReferenceHref(doc, 'product shot')).toBe('./assets/product.png');
+ });
+
+ test('uses the first matching definition, like CommonMark reference resolution', () => {
+ const doc = makeDoc(
+ { label: 'photo', href: '/assets/first.png' },
+ { label: 'PHOTO', href: '/assets/second.png' },
+ );
+ expect(resolveImageReferenceHref(doc, 'photo')).toBe('/assets/first.png');
+ });
+
+ test('matches labels with CommonMark Unicode case folding', () => {
+ const doc = makeDoc({ label: 'SS', href: '/assets/unicode.png' });
+ expect(resolveImageReferenceHref(doc, 'ẞ')).toBe('/assets/unicode.png');
+ });
+
+ test('returns undefined when no definition resolves the image reference', () => {
+ expect(resolveImageReferenceHref(makeDoc(), 'missing')).toBeUndefined();
+ });
+});
diff --git a/packages/app/src/editor/extensions/ImageReferenceView.tsx b/packages/app/src/editor/extensions/ImageReferenceView.tsx
new file mode 100644
index 000000000..c2a43522b
--- /dev/null
+++ b/packages/app/src/editor/extensions/ImageReferenceView.tsx
@@ -0,0 +1,83 @@
+import { normalizeDocRelativeAssetUrl, normalizeReferenceLabel } from '@inkeep/open-knowledge-core';
+import type { NodeViewProps } from '@tiptap/core';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { NodeViewWrapper, useEditorState } from '@tiptap/react';
+import Zoom from 'react-medium-image-zoom';
+import { BareImg } from '../components/Image';
+import { getEditorDocName } from './doc-context.ts';
+
+/**
+ * CommonMark label matching collapses internal markdown whitespace
+ * (`[\t\n\r ]`, not `\s`) and folds case. The shared core helper keeps the
+ * editor aligned with the parser and server.
+ */
+export function resolveImageReferenceHref(
+ doc: ProseMirrorNode,
+ identifier: string,
+): string | undefined {
+ const normalizedIdentifier = normalizeReferenceLabel(identifier);
+ let href: string | undefined;
+
+ doc.descendants((candidate) => {
+ // Once resolved, prune the rest of the walk (`false` stops descent).
+ if (href !== undefined) return false;
+ if (candidate.type.name !== 'linkRefDef') return;
+ const label = candidate.attrs.label;
+ const candidateHref = candidate.attrs.href;
+ if (
+ typeof label === 'string' &&
+ typeof candidateHref === 'string' &&
+ normalizeReferenceLabel(label) === normalizedIdentifier
+ ) {
+ href = candidateHref;
+ }
+ });
+
+ return href;
+}
+
+export interface ImageReferenceLeafProps {
+ /** Absent when no definition resolves the reference; the failure placeholder renders instead. */
+ src?: string;
+ alt: string;
+}
+
+export function ImageReferenceLeaf({ src, alt }: ImageReferenceLeafProps) {
+ return <BareImg src={src} alt={alt} />;
+}
+
+export function ImageReferenceView({ node, editor, extension }: NodeViewProps) {
+ const rawIdentifier = node.attrs.identifier;
+ const identifier = typeof rawIdentifier === 'string' ? rawIdentifier : '';
+ const rawAlt = node.attrs.alt;
+ const rawLabel = node.attrs.label;
+ const alt =
+ typeof rawAlt === 'string' && rawAlt.length > 0
+ ? rawAlt
+ : typeof rawLabel === 'string'
+ ? rawLabel
+ : '';
+ const href = useEditorState({
+ editor,
+ selector: ({ editor: currentEditor }) =>
+ resolveImageReferenceHref(currentEditor.state.doc, identifier),
+ });
+ const configuredDocName = (extension.options as { docName?: unknown }).docName;
+ const sourceDocName =
+ typeof configuredDocName === 'string' && configuredDocName
+ ? configuredDocName
+ : (getEditorDocName(editor) ?? undefined);
+ const src = href === undefined ? undefined : normalizeDocRelativeAssetUrl(href, sourceDocName);
+
+ return (
+ <NodeViewWrapper
+ as="span"
+ data-image-reference-view
+ data-clipboard-inline-leaf="imageReference"
+ >
+ <Zoom wrapElement="span" zoomMargin={20} zoomImg={{ sizes: undefined }}>
+ <ImageReferenceLeaf src={src} alt={alt} />
+ </Zoom>
+ </NodeViewWrapper>
+ );
+}
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
index 580fc0231..0cdc36b5f 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
@@ -24,7 +24,7 @@ if (typeof globalThis.DOMRect === 'undefined') {
type CurrentMarkInfo = {
id: string;
markType: string;
- attrs: { href: string };
+ attrs: { href: string; linkStyle?: string };
from: number;
to: number;
};
@@ -37,12 +37,22 @@ let currentMarkInfo: CurrentMarkInfo | null = {
to: 4,
};
+const pageListHarness = {
+ pages: new Set<string>(),
+ pagesBySlug: new Map<string, string>(),
+ pagesByBasename: new Map<string, string>(),
+};
+
vi.doMock('../../components/PageListContext', () => ({
usePageList: () => ({
addPage: () => {},
+ assetPaths: new Set<string>(),
+ filePaths: new Set<string>(),
folderPaths: new Set<string>(),
loading: false,
- pages: new Set<string>(),
+ pageMeta: new Map(),
+ pageTitles: new Map(),
+ ...pageListHarness,
}),
}));
@@ -134,6 +144,9 @@ afterEach(() => {
loadHarness.calls = 0;
loadHarness.result = null;
configHarness.enabled = false;
+ pageListHarness.pages = new Set<string>();
+ pageListHarness.pagesBySlug = new Map<string, string>();
+ pageListHarness.pagesByBasename = new Map<string, string>();
});
describe('InternalLinkPropPanel', () => {
@@ -265,6 +278,68 @@ describe('InternalLinkPropPanel', () => {
});
expect(deleteRange).not.toHaveBeenCalled();
});
+
+ test('navigates a tolerant-case fallback without offering Create page', () => {
+ currentMarkInfo = {
+ id: 'm1',
+ markType: 'link',
+ attrs: { href: 'targets/case-sensitive' },
+ from: 0,
+ to: 4,
+ };
+ pageListHarness.pages = new Set(['targets/Case Sensitive']);
+ pageListHarness.pagesBySlug = new Map([['targets-case-sensitive', 'targets/Case Sensitive']]);
+
+ const { container } = render(
+ <TooltipProvider>
+ <InternalLinkPropPanel
+ editor={makeEditor()}
+ nodeId="m1"
+ sourceDocName="all-link-types"
+ onClose={() => {}}
+ onNavigate={() => true}
+ />
+ </TooltipProvider>,
+ );
+
+ expect(container.querySelector('[data-slot="internal-link-prop-panel-create"]')).toBeNull();
+ expect(
+ container.querySelector('[data-slot="internal-link-prop-panel-text"]')?.getAttribute('href'),
+ ).toBe('#/targets/Case Sensitive');
+ });
+
+ test('reference-style links preserve navigation without offering a lossy destination edit', () => {
+ currentMarkInfo = {
+ id: 'm1',
+ markType: 'link',
+ attrs: { href: '/targets/reference', linkStyle: 'full' },
+ from: 0,
+ to: 4,
+ };
+ pageListHarness.pages = new Set(['targets/reference']);
+ const onNavigate = vi.fn(() => true);
+ const onClose = vi.fn(() => {});
+
+ const { container } = render(
+ <TooltipProvider>
+ <InternalLinkPropPanel
+ editor={makeEditor()}
+ nodeId="m1"
+ sourceDocName="notes/source"
+ onClose={onClose}
+ onNavigate={onNavigate}
+ />
+ </TooltipProvider>,
+ );
+
+ expect(container.querySelector('[data-slot="internal-link-prop-panel-edit"]')).toBeNull();
+ const destination = screen.getByRole('link', { name: 'targets/reference' });
+ expect(destination.getAttribute('href')).toBe('#/targets/reference');
+
+ fireEvent.click(destination);
+ expect(onNavigate).toHaveBeenCalledWith(false);
+ expect(onClose).toHaveBeenCalled();
+ });
});
const EXTERNAL_URL = 'https://example.com/some/page';
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
index c2876f6df..939b9fa77 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
@@ -72,6 +72,7 @@ import { useInternalDocPreview } from '../link-preview/use-internal-doc-preview.
import { isSafeNavigationUrl } from '../safe-navigation-url';
import { CopyButton } from './LinkPropPanelCopy';
import { consumePendingLinkEdit } from './link-edit-autoopen';
+import { isResolvedAssetHref } from './link-resolution';
import { getCurrentMarkInfo } from './mark-interaction-bridge';
import { useHeadings } from './use-headings';
import { isResolvedWikiLinkTarget } from './wiki-link-helpers';
@@ -353,6 +354,9 @@ export function InternalLinkPropPanel({
}: InternalLinkPropPanelProps) {
const info = getCurrentMarkInfo(editor.state, nodeId);
const href = (info?.attrs?.href as string | undefined) ?? '';
+ const linkStyle = info?.attrs?.linkStyle;
+ const canEditDestination =
+ linkStyle !== 'full' && linkStyle !== 'collapsed' && linkStyle !== 'shortcut';
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [isCreating, setIsCreating] = useState(false);
@@ -367,21 +371,44 @@ export function InternalLinkPropPanel({
if (consumePendingLinkEdit(nodeId)) setEditDialogOpen(true);
}, [nodeId]);
- const { addPage, folderPaths, pages, loading } = usePageList();
+ const {
+ addPage,
+ assetPaths,
+ filePaths,
+ folderPaths,
+ pages,
+ pagesBySlug,
+ pagesByBasename,
+ loading,
+ } = usePageList();
const { t } = useLingui();
// Classify + resolve the target before the early-return guards so the
// doc-preview hook is called unconditionally (Rules of Hooks). The card only
// renders for a resolved doc target; every other kind leaves the pill as-is.
const target = href ? classifyMarkdownHref(href, sourceDocName) : null;
+ // An extension-less href with no document identity can still name an existing
+ // ordinary file, and the server's classifier settles that with exact
+ // inventory membership. Without the same check the card offers Create page
+ // over a file that is right there on disk — and the chip beside it, which
+ // does consult the tracked-file sets, renders resolved at the same moment.
+ const namesTrackedFile =
+ target?.kind === 'doc' && isResolvedAssetHref(href, sourceDocName, assetPaths, filePaths);
const docIntent =
- target?.kind === 'doc' ? resolveLinkTargetIntent(target.docName, { pages, folderPaths }) : null;
+ target?.kind === 'doc' && !namesTrackedFile
+ ? resolveLinkTargetIntent(target.docName, {
+ pages,
+ folderPaths,
+ pagesBySlug,
+ pagesByBasename,
+ })
+ : null;
const docPreview = useInternalDocPreview({
docName:
target?.kind === 'doc' &&
docIntent?.kind === 'navigate' &&
docIntent.displayState === 'resolved'
- ? target.docName
+ ? docIntent.hashDocName
: null,
anchor: target?.kind === 'doc' ? target.anchor : null,
enabled: true,
@@ -459,7 +486,7 @@ export function InternalLinkPropPanel({
onClose();
}
- const editDialog = (
+ const editDialog = canEditDestination ? (
<EditMarkdownLinkDialog
open={editDialogOpen}
href={href}
@@ -470,7 +497,7 @@ export function InternalLinkPropPanel({
onOpenChange={href ? setEditDialogOpen : handleEmptyHrefDialogOpenChange}
onSave={handleSave}
/>
- );
+ ) : null;
if (!href) {
return <>{editDialog}</>;
@@ -577,7 +604,10 @@ export function InternalLinkPropPanel({
const isExternalLink = target?.kind === 'external';
const linkHref =
target?.kind === 'doc'
- ? toInternalHashHref({ docName: target.docName, anchor: target.anchor })
+ ? toInternalHashHref({
+ docName: docIntent?.kind === 'navigate' ? docIntent.hashDocName : target.docName,
+ anchor: target.anchor,
+ })
: target?.kind === 'anchor'
? toInternalHashHref({ docName: sourceDocName, anchor: target.anchor })
: target?.kind === 'external' && isSafeNavigationUrl(target.url)
@@ -704,23 +734,25 @@ export function InternalLinkPropPanel({
{isCreating ? <Trans>Creating...</Trans> : <Trans>Create page</Trans>}
</Button>
) : null}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- aria-label={t`Edit`}
- onClick={() => setEditDialogOpen(true)}
- data-slot="internal-link-prop-panel-edit"
- >
- <Pencil className="size-3.5" aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <Trans>Edit</Trans>
- </TooltipContent>
- </Tooltip>
+ {canEditDestination ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t`Edit`}
+ onClick={() => setEditDialogOpen(true)}
+ data-slot="internal-link-prop-panel-edit"
+ >
+ <Pencil className="size-3.5" aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <Trans>Edit</Trans>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
<CopyButton copyContent={href} />
<Tooltip>
<TooltipTrigger asChild>
diff --git a/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx b/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx
index f6642b9d3..f7886c704 100644
--- a/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/JsxInlineView.dom.test.tsx
@@ -23,7 +23,11 @@ import { sharedExtensions } from './shared';
// Portalled per the H6 cross-doc DOM bleed contract (no-unportaled-editor-content).
function Host({ content, onEditor }: { content: object; onEditor: (e: Editor) => void }) {
const editor = useEditor({
- extensions: sharedExtensions,
+ extensions: sharedExtensions.map((extension) =>
+ extension.name === 'jsxInline'
+ ? extension.configure({ docName: 'all-link-types' })
+ : extension,
+ ),
editable: true,
content,
immediatelyRender: true,
@@ -86,6 +90,36 @@ function docWithInline(attrs: Record<string, unknown>, text?: string) {
afterEach(cleanup);
describe('JsxInlineView', () => {
+ test('normalizes a local inline img src against its document before rendering', async () => {
+ const desktopWindow = window as typeof window & {
+ okDesktop?: { config: { apiOrigin: string } };
+ };
+ desktopWindow.okDesktop = { config: { apiOrigin: 'http://localhost:53351' } };
+
+ try {
+ mountEditor(
+ docWithInline({
+ componentName: 'img',
+ sourceRaw: '<img src="assets/space image.png" alt="Working self-closing HTML image" />',
+ props: {
+ src: 'assets/space image.png',
+ alt: 'Working self-closing HTML image',
+ },
+ }),
+ );
+
+ await waitFor(() => {
+ expect(
+ document
+ .querySelector<HTMLImageElement>('img[alt="Working self-closing HTML image"]')
+ ?.getAttribute('src'),
+ ).toBe('http://localhost:53351/assets/space image.png');
+ });
+ } finally {
+ delete desktopWindow.okDesktop;
+ }
+ });
+
test('a registered componentName renders the descriptor widget', async () => {
mountEditor(
docWithInline({
diff --git a/packages/app/src/editor/extensions/JsxInlineView.tsx b/packages/app/src/editor/extensions/JsxInlineView.tsx
index 82e02b84b..4a9a9bfcf 100644
--- a/packages/app/src/editor/extensions/JsxInlineView.tsx
+++ b/packages/app/src/editor/extensions/JsxInlineView.tsx
@@ -28,7 +28,9 @@ import { Button } from '../../components/ui/button.tsx';
import { Popover, PopoverContent, PopoverTrigger } from '../../components/ui/popover.tsx';
import { PropPanel } from '../components/PropPanel.tsx';
import { getDescriptor } from '../registry/index.ts';
+import { getEditorDocName } from './doc-context.ts';
import { extractPrimitiveProps, stableHash } from './JsxComponentView.tsx';
+import { normalizeDocRelativeMediaRenderProps } from './media-render-props.ts';
export function JsxInlineView(viewProps: NodeViewProps) {
const { node } = viewProps;
@@ -50,6 +52,7 @@ function RegisteredInlineView({
selected,
editor,
getPos,
+ extension,
name,
}: NodeViewProps & { name: string }) {
const descriptor = getDescriptor(name);
@@ -69,6 +72,16 @@ function RegisteredInlineView({
if (typeof bodyText === 'string' && bodyText !== '') {
(primitiveProps as Record<string, unknown>).children = bodyText;
}
+ const configuredDocName = (extension.options as { docName?: unknown }).docName;
+ const sourceDocName =
+ typeof configuredDocName === 'string' && configuredDocName
+ ? configuredDocName
+ : getEditorDocName(editor);
+ const renderProps = normalizeDocRelativeMediaRenderProps(
+ descriptor.name,
+ primitiveProps,
+ sourceDocName,
+ );
// `stableHash` sorts keys recursively so a props re-serialization that
// reorders insertion order doesn't remount the ErrorBoundary mid-render.
const resetKey = `${descriptor.name}::${stableHash(primitiveProps)}`;
@@ -136,7 +149,7 @@ function RegisteredInlineView({
<span className="text-xs font-mono text-destructive">[{name}]</span>
)}
>
- <Component {...primitiveProps} />
+ <Component {...renderProps} />
</ErrorBoundary>
</span>
</PopoverTrigger>
diff --git a/packages/app/src/editor/extensions/WikiLinkEmbedImageView.dom.test.tsx b/packages/app/src/editor/extensions/WikiLinkEmbedImageView.dom.test.tsx
new file mode 100644
index 000000000..b3e934015
--- /dev/null
+++ b/packages/app/src/editor/extensions/WikiLinkEmbedImageView.dom.test.tsx
@@ -0,0 +1,96 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { EditorContent, useEditor } from '@tiptap/react';
+import { useEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { afterEach, describe, expect, test } from 'vitest';
+import { sharedExtensions } from './shared';
+import { WikiLinkEmbedImageView } from './WikiLinkEmbedImageView';
+
+function WikiImageHost() {
+ const editor = useEditor({
+ extensions: sharedExtensions,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'wikiLinkEmbed',
+ attrs: {
+ target: 'attachments/broken.png',
+ alias: 'Broken production wiki image',
+ anchor: null,
+ resolvedSrc: '/attachments/broken.png',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ immediatelyRender: true,
+ });
+ const [portalTarget] = useState(() => document.createElement('div'));
+
+ useEffect(() => {
+ document.body.appendChild(portalTarget);
+ return () => portalTarget.remove();
+ }, [portalTarget]);
+
+ return createPortal(
+ // biome-ignore lint/plugin/no-unportaled-editor-content: portalled per the H6 contract — this IS the sanctioned createPortal shape, in a test harness with a per-render exclusive target
+ <EditorContent editor={editor} />,
+ portalTarget,
+ );
+}
+
+describe('WikiLinkEmbedImageView', () => {
+ afterEach(() => {
+ cleanup();
+ delete (window as typeof window & { okDesktop?: unknown }).okDesktop;
+ });
+
+ test('a wiki image embed load failure uses the shared image placeholder', () => {
+ render(<WikiLinkEmbedImageView src="/attachments/broken.png" alt="Broken wiki image" />);
+ fireEvent.error(document.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ "Image couldn't be displayed: Broken wiki image",
+ );
+ });
+
+ test('the shared leaf keeps the Electron asset-origin rewrite', () => {
+ const windowWithDesktop = window as typeof window & {
+ okDesktop?: { config: { apiOrigin: string } };
+ };
+ windowWithDesktop.okDesktop = {
+ config: { apiOrigin: 'http://127.0.0.1:54321' },
+ };
+
+ render(<WikiLinkEmbedImageView src="/attachments/photo.png" alt="Photo" />);
+ expect(document.querySelector('img')?.getAttribute('src')).toBe(
+ 'http://127.0.0.1:54321/attachments/photo.png',
+ );
+ });
+
+ test('the production WikiLinkEmbed image NodeView wires the shared placeholder', async () => {
+ render(<WikiImageHost />);
+
+ const wrapper = await waitFor(() => {
+ const element = document.querySelector(
+ '[data-wiki-embed][data-target="attachments/broken.png"]',
+ );
+ expect(element?.querySelector('img')).not.toBeNull();
+ return element;
+ });
+ fireEvent.error(wrapper.querySelector('img') as HTMLImageElement);
+
+ const slot = screen.getByTestId('image-slot');
+ expect(slot.getAttribute('data-image-error-kind')).toBe('undisplayable');
+ expect(slot.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(
+ "Image couldn't be displayed: Broken production wiki image",
+ );
+ });
+});
diff --git a/packages/app/src/editor/extensions/WikiLinkEmbedImageView.tsx b/packages/app/src/editor/extensions/WikiLinkEmbedImageView.tsx
new file mode 100644
index 000000000..976c3628e
--- /dev/null
+++ b/packages/app/src/editor/extensions/WikiLinkEmbedImageView.tsx
@@ -0,0 +1,11 @@
+import { BareImg } from '../components/Image';
+
+export interface WikiLinkEmbedImageViewProps {
+ src: string;
+ alt: string;
+}
+
+/** Shared image leaf for the transient, drop-time wiki-embed NodeView. */
+export function WikiLinkEmbedImageView({ src, alt }: WikiLinkEmbedImageViewProps) {
+ return <BareImg src={src} alt={alt} />;
+}
diff --git a/packages/app/src/editor/extensions/bare-html-image-decoration.test.tsx b/packages/app/src/editor/extensions/bare-html-image-decoration.test.tsx
new file mode 100644
index 000000000..0ff11d284
--- /dev/null
+++ b/packages/app/src/editor/extensions/bare-html-image-decoration.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+
+import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
+import {
+ findBareHtmlImageTags,
+ findRenderableBareHtmlImages,
+ parseBareHtmlImage,
+} from './bare-html-image-decoration';
+
+const markdown = new MarkdownManager({ extensions: sharedExtensions });
+const schema = getSchema(sharedExtensions);
+
+function parse(source: string) {
+ return schema.nodeFromJSON(markdown.parse(source));
+}
+
+describe('bare HTML image decoration', () => {
+ test('promotes a local HTML void image while leaving its PM bytes literal', () => {
+ const source = '<img src="./missing.png" alt="team photo">\n';
+ const doc = parse(source);
+ const [image] = findRenderableBareHtmlImages(doc, 'notes/today');
+ expect(image?.raw).toBe('<img src="./missing.png" alt="team photo">');
+ expect(image?.props).toMatchObject({ src: '/notes/missing.png', alt: 'team photo' });
+ expect(markdown.serialize(doc.toJSON())).toBe(source);
+ });
+
+ test('the scanner accepts a closing bracket inside a quoted attribute', () => {
+ expect(findBareHtmlImageTags('<img src="./x.png" alt=">">')).toEqual([
+ { index: 0, raw: '<img src="./x.png" alt=">">' },
+ ]);
+ expect(parseBareHtmlImage('<img src="./x.png" alt=">">', 'README')?.alt).toBe('>');
+ });
+
+ test.each([
+ ['inline code', '`<img src="./x.png">`'],
+ ['fenced code', '```html\n<img src="./x.png">\n```'],
+ ['indented code', ' <img src="./x.png">'],
+ ['escaped literal', '\\<img src="./x.png">'],
+ ['entity-authored literal', '&lt;img src="./x.png"&gt;'],
+ ])('does not promote %s', (_label, source) => {
+ expect(findRenderableBareHtmlImages(parse(source), 'README')).toEqual([]);
+ });
+
+ test('leaves self-closing and external images to their existing render paths', () => {
+ expect(parseBareHtmlImage('<img src="./x.png" />', 'README')).toBeNull();
+ expect(parseBareHtmlImage('<img src="https://example.com/x.png">', 'README')).toBeNull();
+ });
+
+ test('keeps only valid HTML referrer policies', () => {
+ expect(
+ parseBareHtmlImage(
+ '<img src="./x.png" referrerpolicy="strict-origin-when-cross-origin">',
+ 'README',
+ )?.referrerpolicy,
+ ).toBe('strict-origin-when-cross-origin');
+ expect(
+ parseBareHtmlImage('<img src="./x.png" referrerpolicy="not-a-policy">', 'README')
+ ?.referrerpolicy,
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/app/src/editor/extensions/bare-html-image-decoration.tsx b/packages/app/src/editor/extensions/bare-html-image-decoration.tsx
new file mode 100644
index 000000000..9e02f85e1
--- /dev/null
+++ b/packages/app/src/editor/extensions/bare-html-image-decoration.tsx
@@ -0,0 +1,203 @@
+/**
+ * Render valid HTML-void `<img ...>` source as an image without rewriting it.
+ *
+ * Core intentionally preserves the no-slash HTML form as literal text. This
+ * app decoration hides only that rendered text range and inserts the same
+ * target-aware image leaf used by canonical images; the ProseMirror document
+ * and Y.Text keep the exact authored bytes.
+ */
+
+import { normalizeDocRelativeAssetUrl, resolveAssetProjectPath } from '@inkeep/open-knowledge-core';
+import { type Editor, Extension } from '@tiptap/core';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { ReactRenderer } from '@tiptap/react';
+import { BareImg, type ImageProps } from '../components/Image';
+
+const pluginKey = new PluginKey<DecorationSet>('bareHtmlImageDecoration');
+
+interface BareTagMatch {
+ index: number;
+ raw: string;
+}
+
+export interface RenderableBareHtmlImage extends BareTagMatch {
+ from: number;
+ to: number;
+ props: ImageProps;
+}
+
+/** Find closing `>` outside quoted attributes; `alt="a > b"` stays valid. */
+export function findBareHtmlImageTags(text: string): BareTagMatch[] {
+ const matches: BareTagMatch[] = [];
+ let cursor = 0;
+ while (cursor < text.length) {
+ const index = text.indexOf('<img', cursor);
+ if (index === -1) break;
+ const afterName = text[index + 4];
+ if (afterName !== '>' && afterName !== undefined && !/\s/.test(afterName)) {
+ cursor = index + 4;
+ continue;
+ }
+ let quote: '"' | "'" | null = null;
+ let end = index + 4;
+ for (; end < text.length; end += 1) {
+ const character = text[end];
+ if (quote !== null) {
+ if (character === quote) quote = null;
+ } else if (character === '"' || character === "'") {
+ quote = character;
+ } else if (character === '>') {
+ break;
+ } else if (character === '<') {
+ break;
+ }
+ }
+ if (text[end] === '>') matches.push({ index, raw: text.slice(index, end + 1) });
+ cursor = Math.max(index + 4, end + 1);
+ }
+ return matches;
+}
+
+function imagePropsFromElement(image: HTMLImageElement, sourceDocName: string): ImageProps | null {
+ const src = image.getAttribute('src');
+ if (src === null || resolveAssetProjectPath(src, sourceDocName) === null) return null;
+
+ const loading = image.getAttribute('loading');
+ const decoding = image.getAttribute('decoding');
+ const fetchpriority = image.getAttribute('fetchpriority');
+ const crossorigin = image.getAttribute('crossorigin');
+ const referrerpolicy = image.getAttribute('referrerpolicy');
+ return {
+ src: normalizeDocRelativeAssetUrl(src, sourceDocName),
+ alt: image.getAttribute('alt') ?? '',
+ width: image.getAttribute('width') ?? undefined,
+ height: image.getAttribute('height') ?? undefined,
+ title: image.getAttribute('title') ?? undefined,
+ srcset: image.getAttribute('srcset') ?? undefined,
+ sizes: image.getAttribute('sizes') ?? undefined,
+ loading: loading === 'eager' || loading === 'lazy' ? loading : undefined,
+ decoding:
+ decoding === 'sync' || decoding === 'async' || decoding === 'auto' ? decoding : undefined,
+ fetchpriority:
+ fetchpriority === 'high' || fetchpriority === 'low' || fetchpriority === 'auto'
+ ? fetchpriority
+ : undefined,
+ crossorigin:
+ crossorigin === '' || crossorigin === 'anonymous' || crossorigin === 'use-credentials'
+ ? crossorigin
+ : undefined,
+ referrerpolicy:
+ referrerpolicy === '' ||
+ referrerpolicy === 'no-referrer' ||
+ referrerpolicy === 'no-referrer-when-downgrade' ||
+ referrerpolicy === 'origin' ||
+ referrerpolicy === 'origin-when-cross-origin' ||
+ referrerpolicy === 'same-origin' ||
+ referrerpolicy === 'strict-origin' ||
+ referrerpolicy === 'strict-origin-when-cross-origin' ||
+ referrerpolicy === 'unsafe-url'
+ ? referrerpolicy
+ : undefined,
+ };
+}
+
+/** Parse one complete, lowercase, non-self-closing local HTML image tag. */
+export function parseBareHtmlImage(raw: string, sourceDocName: string): ImageProps | null {
+ if (!raw.startsWith('<img') || raw.endsWith('/>')) return null;
+ const template = document.createElement('template');
+ template.innerHTML = raw;
+ if (template.content.childNodes.length !== 1) return null;
+ const image = template.content.firstElementChild;
+ if (!(image instanceof HTMLImageElement)) return null;
+ return imagePropsFromElement(image, sourceDocName);
+}
+
+function isLiteralOnlyContext(node: ProseMirrorNode, parent: ProseMirrorNode | null): boolean {
+ if (parent?.type.spec.code === true || parent?.type.name.toLowerCase().includes('codeblock')) {
+ return true;
+ }
+ return node.marks.some((mark) =>
+ ['code', 'escapeMark', 'sourceLiteral'].includes(mark.type.name),
+ );
+}
+
+/** Locate only raw-HTML-origin text, excluding escaped and code-shaped literals. */
+export function findRenderableBareHtmlImages(
+ doc: ProseMirrorNode,
+ sourceDocName: string,
+): RenderableBareHtmlImage[] {
+ const images: RenderableBareHtmlImage[] = [];
+ doc.descendants((node, pos, parent) => {
+ if (!node.isText || node.text === undefined || isLiteralOnlyContext(node, parent)) return;
+ for (const match of findBareHtmlImageTags(node.text)) {
+ const props = parseBareHtmlImage(match.raw, sourceDocName);
+ if (props === null) continue;
+ const from = pos + match.index;
+ images.push({ ...match, from, to: from + match.raw.length, props });
+ }
+ });
+ return images;
+}
+
+function buildDecorations(
+ doc: ProseMirrorNode,
+ editor: Editor,
+ sourceDocName: string,
+): DecorationSet {
+ const decorations: Decoration[] = [];
+ for (const match of findRenderableBareHtmlImages(doc, sourceDocName)) {
+ const { from, to, props } = match;
+ let renderer: ReactRenderer<typeof BareImg> | null = null;
+ decorations.push(
+ Decoration.inline(from, to, {
+ 'aria-hidden': 'true',
+ class: 'hidden ok-bare-html-image-source',
+ }),
+ Decoration.widget(
+ from,
+ () => {
+ renderer = new ReactRenderer(BareImg, {
+ editor,
+ props,
+ as: 'span',
+ className: 'ok-bare-html-image-render',
+ });
+ renderer.element.setAttribute('contenteditable', 'false');
+ return renderer.element;
+ },
+ {
+ side: -1,
+ key: `${from}:${match.raw}`,
+ destroy: () => renderer?.destroy(),
+ },
+ ),
+ );
+ }
+ return DecorationSet.create(doc, decorations);
+}
+
+export function createBareHtmlImageDecoration(sourceDocName: string): Extension {
+ return Extension.create({
+ name: 'bareHtmlImageDecoration',
+ addProseMirrorPlugins() {
+ const editor = this.editor;
+ return [
+ new Plugin<DecorationSet>({
+ key: pluginKey,
+ state: {
+ init: (_, state) => buildDecorations(state.doc, editor, sourceDocName),
+ apply: (transaction, previous) =>
+ transaction.docChanged
+ ? buildDecorations(transaction.doc, editor, sourceDocName)
+ : previous.map(transaction.mapping, transaction.doc),
+ },
+ props: {
+ decorations: (state) => pluginKey.getState(state) ?? DecorationSet.empty,
+ },
+ }),
+ ];
+ },
+ });
+}
diff --git a/packages/app/src/editor/extensions/image-reference.ts b/packages/app/src/editor/extensions/image-reference.ts
new file mode 100644
index 000000000..28cd2ede8
--- /dev/null
+++ b/packages/app/src/editor/extensions/image-reference.ts
@@ -0,0 +1,16 @@
+import { ImageReferenceFidelity } from '@inkeep/open-knowledge-core';
+import { ReactNodeViewRenderer } from '@tiptap/react';
+import { ImageReferenceView } from './ImageReferenceView';
+
+export const ImageReference = ImageReferenceFidelity.extend<{ docName: string }>({
+ addOptions() {
+ return {
+ ...this.parent?.(),
+ docName: '',
+ };
+ },
+
+ addNodeView() {
+ return ReactNodeViewRenderer(ImageReferenceView);
+ },
+});
diff --git a/packages/app/src/editor/extensions/link-resolution-decoration.ts b/packages/app/src/editor/extensions/link-resolution-decoration.ts
index e4f088f07..7b14c3543 100644
--- a/packages/app/src/editor/extensions/link-resolution-decoration.ts
+++ b/packages/app/src/editor/extensions/link-resolution-decoration.ts
@@ -53,6 +53,7 @@ import type { Node as PmNode } from '@tiptap/pm/model';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { mark } from '@/lib/perf';
+import { subscribeToLinkValidationPolicy } from '../link-validation-policy';
import {
getPageListCache,
type PageListCacheSnapshot,
@@ -197,12 +198,15 @@ export function linkResolutionDecorationPlugin(
{ markTypes: Array.from(markTypeSet).join(',') },
{ startTime: performance.now(), duration: 0 },
);
- const unsubscribe = subscribePageListCache(() => {
+ const refresh = () => {
view.dispatch(view.state.tr.setMeta(linkResolutionDecorationKey, { refresh: true }));
- });
+ };
+ const unsubscribePageList = subscribePageListCache(refresh);
+ const unsubscribePolicy = subscribeToLinkValidationPolicy(refresh);
return {
destroy() {
- unsubscribe();
+ unsubscribePageList();
+ unsubscribePolicy();
},
};
},
diff --git a/packages/app/src/editor/extensions/link-resolution-uniformity.test.ts b/packages/app/src/editor/extensions/link-resolution-uniformity.test.ts
new file mode 100644
index 000000000..0fb610081
--- /dev/null
+++ b/packages/app/src/editor/extensions/link-resolution-uniformity.test.ts
@@ -0,0 +1,197 @@
+/**
+ * Editor-side half of link-classification uniformity.
+ *
+ * The server already computes a canonical classification for every authored
+ * occurrence — `{targetKind, resolvedTarget, status, reason, resolutionMethod}`
+ * — against the full inventory (documents AND files). The editor decoration is a
+ * CONSUMER of that answer, so for any given occurrence its rendered state must
+ * agree with what the server concluded. Where it re-derives existence from a
+ * narrower view of the same inventory, it disagrees, and the user sees a blue
+ * chip on a dead target or a redlink on a file that is right there on disk.
+ *
+ * The cross-plane server pin lives in
+ * `packages/server/src/link-classification-uniformity.test.ts`. This file pins
+ * the client half of the same invariant.
+ *
+ * Deliberately out of scope, because they are not classification disagreements:
+ * external schemes (already uniformly `external` on every plane) and the wiki
+ * escaped-pipe (`\|`) trailing-backslash defect, which every surface reports
+ * identically and which is fixed separately.
+ */
+
+import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
+import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
+import {
+ computeLinkResolutionAttrs,
+ computeLinkResolutionState,
+ isResolvedAssetHref,
+} from './link-resolution';
+import type { MarkInfo } from './mark-identity';
+import { getWikiLinkResolutionState } from './wiki-link';
+
+beforeEach(() => resetLinkValidationPolicyForTest());
+
+const SOURCE_DOC = 'all-link-types';
+
+/**
+ * The same fixture inventory the server-side uniformity pin uses, in the shape
+ * `/api/documents` hands the client. `assets/NOTICE` is the load-bearing entry:
+ * an EXISTING extensionless ordinary file.
+ */
+function fixtureCache(): PageListCacheSnapshot {
+ const pages = new Set(['all-link-types', 'targets/existing-page', 'targets/Case Sensitive']);
+ return {
+ pages,
+ folderPaths: new Set(['targets', 'assets']),
+ assetPaths: new Set(['assets/existing.txt', 'assets/manual.pdf']),
+ filePaths: new Set(['assets/NOTICE']),
+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),
+ };
+}
+
+function makeMarkInfo(attrs: Record<string, unknown>, overrides?: Partial<MarkInfo>): MarkInfo {
+ return { id: 'm1', markType: 'link', attrs, from: 0, to: 5, ...overrides };
+}
+
+/** States that render as "this target is fine" rather than as a redlink. */
+const RESOLVED_STATES = ['resolved', 'folder', 'asset', 'external', 'anchor'];
+
+describe('editor resolution state agrees with the canonical server classification', () => {
+ test('an existing extensionless ordinary file does not render as a dead link', () => {
+ // The server proves `assets/NOTICE` exists (`targetKind: 'file'`,
+ // `status: 'exact'`). The client classifies the extensionless href as a
+ // DOCUMENT and then resolves it against `pages` + `folderPaths` only —
+ // `filePaths` never enters the document branch — so the same occurrence the
+ // server called an existing file renders unresolved and offers Create page.
+ setLinkValidationVisible(true);
+ const state = computeLinkResolutionState('assets/NOTICE', SOURCE_DOC, fixtureCache());
+ expect(RESOLVED_STATES).toContain(state);
+ });
+
+ test('a wiki embed of a missing document carries a resolution state', () => {
+ // `computeLinkResolutionAttrs` returns null for every `sourceForm:
+ // 'wikiembed'` mark, so a document-shaped embed naming a target the server
+ // reports as missing gets no decoration at all and renders resolved-blue.
+ setLinkValidationVisible(true);
+ const attrs = computeLinkResolutionAttrs(
+ makeMarkInfo({ href: 'targets/missing-embed', sourceForm: 'wikiembed' }),
+ fixtureCache(),
+ SOURCE_DOC,
+ );
+ expect(attrs).not.toBeNull();
+ expect(attrs?.['data-resolution-state']).toBe('unresolved');
+ });
+
+ test('a wiki embed of an existing tracked file renders as an asset, not a dead link', () => {
+ // The mirror of the case above: skipping every wiki embed also means an
+ // embed pointing at a file the server tracks gets no state, so the editor
+ // cannot distinguish it from the missing one.
+ setLinkValidationVisible(true);
+ const attrs = computeLinkResolutionAttrs(
+ makeMarkInfo({ href: 'assets/manual.pdf', sourceForm: 'wikiembed' }),
+ fixtureCache(),
+ SOURCE_DOC,
+ );
+ expect(attrs).not.toBeNull();
+ expect(RESOLVED_STATES).toContain(attrs?.['data-resolution-state']);
+ });
+
+ test('a full reference mark reaches the same decoration path as an inline link', () => {
+ setLinkValidationVisible(true);
+ const attrs = computeLinkResolutionAttrs(
+ makeMarkInfo({
+ href: 'targets/missing-reference',
+ linkStyle: 'full',
+ refLabel: 'missing-ref',
+ }),
+ fixtureCache(),
+ SOURCE_DOC,
+ );
+
+ expect(attrs).toEqual({ 'data-resolution-state': 'unresolved' });
+ });
+
+ test('control: a missing document still renders unresolved', () => {
+ // Guard, not a RED assertion. The uniformity fix must not reach agreement by
+ // making the editor optimistic about everything.
+ setLinkValidationVisible(true);
+ expect(computeLinkResolutionState('targets/missing-wiki', SOURCE_DOC, fixtureCache())).toBe(
+ 'unresolved',
+ );
+ });
+
+ test('a wiki-link chip carries the resolution state its target deserves', () => {
+ // Wiki-link chips are NODES, and the decoration plugin is registered for
+ // `markTypes: ['link']`, so nothing ever reached them: a missing target
+ // rendered in resolved-blue while Problems reported it missing and the
+ // hover card offered Create page.
+ const cache = fixtureCache();
+ expect(getWikiLinkResolutionState('targets/existing-page', null, cache)).toBe('resolved');
+ expect(getWikiLinkResolutionState('targets/missing-wiki', null, cache)).toBe('unresolved');
+ expect(getWikiLinkResolutionState('assets/manual.pdf', null, cache)).toBe('asset');
+ expect(getWikiLinkResolutionState('https://inkeep.com', null, cache)).toBe('external');
+ });
+
+ test('a wiki-link asset stays optimistic when both file inventories are absent', () => {
+ const cache = fixtureCache();
+ const legacyCache: PageListCacheSnapshot = {
+ pages: cache.pages,
+ folderPaths: cache.folderPaths,
+ pagesBySlug: cache.pagesBySlug,
+ };
+
+ expect(getWikiLinkResolutionState('assets/manual.pdf', null, legacyCache)).toBe('asset');
+ });
+
+ test('an extensionless wiki-link target remains a document target', () => {
+ expect(getWikiLinkResolutionState('assets/NOTICE', null, fixtureCache())).toBe('unresolved');
+ });
+
+ test('the hover panel and the chip agree about an existing extensionless file', () => {
+ // The hover card decides its Create-page affordance from
+ // `resolveLinkTargetIntent(docName, {pages, folderPaths})`, which cannot see
+ // tracked files. Left alone it offers Create page for `assets/NOTICE` while
+ // the chip beside it renders resolved — the same occurrence, two verdicts,
+ // one of them offering to create a document over a file that exists.
+ //
+ // `isResolvedAssetHref` is the shared predicate both surfaces consult; this
+ // pins that it answers yes here, so the panel's guard short-circuits before
+ // the doc-intent resolver ever runs.
+ const cache = fixtureCache();
+ expect(
+ isResolvedAssetHref('assets/NOTICE', SOURCE_DOC, cache.assetPaths, cache.filePaths),
+ ).toBe(true);
+ setLinkValidationVisible(true);
+ expect(RESOLVED_STATES).toContain(
+ computeLinkResolutionState('assets/NOTICE', SOURCE_DOC, cache),
+ );
+ });
+
+ test('control: a genuinely missing document still reaches the Create-page path', () => {
+ // The guard must not swallow the affordance for a target that really is a
+ // missing document — that is the row the matrix expects Create page on.
+ const cache = fixtureCache();
+ expect(
+ isResolvedAssetHref('targets/missing-wiki', SOURCE_DOC, cache.assetPaths, cache.filePaths),
+ ).toBe(false);
+ });
+
+ test('control: external schemes stay uniformly external', () => {
+ // Guard, not a RED assertion. External handling is already uniform across
+ // every plane and is explicitly out of scope for this fix.
+ const cache = fixtureCache();
+ for (const href of [
+ 'https://example.com/docs',
+ 'mailto:[email protected]',
+ 'tel:+15551234567',
+ '//cdn.example.com/file.pdf',
+ ]) {
+ expect(computeLinkResolutionState(href, SOURCE_DOC, cache)).toBe('external');
+ }
+ });
+});
diff --git a/packages/app/src/editor/extensions/link-resolution.test.ts b/packages/app/src/editor/extensions/link-resolution.test.ts
index 54536b22d..d9050628b 100644
--- a/packages/app/src/editor/extensions/link-resolution.test.ts
+++ b/packages/app/src/editor/extensions/link-resolution.test.ts
@@ -13,7 +13,11 @@
*/
import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
-import { describe, expect, test } from 'vitest';
+import { beforeEach, describe, expect, test } from 'vitest';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
import {
computeLinkResolutionAttrs,
@@ -22,6 +26,8 @@ import {
} from './link-resolution';
import type { MarkInfo } from './mark-identity';
+beforeEach(() => resetLinkValidationPolicyForTest());
+
function makeCache(opts: {
pages?: Iterable<string>;
folderPaths?: Iterable<string>;
@@ -217,6 +223,12 @@ describe('computeLinkResolutionAttrs', () => {
expect(result).toEqual({ 'data-resolution-state': 'resolved' });
});
+ test('validation.links off omits the unresolved decoration attribute', () => {
+ setLinkValidationVisible(false);
+ const mark = makeMarkInfo({ href: './MISSING.md' });
+ expect(computeLinkResolutionAttrs(mark, makeCache({ pages: [] }), 'README')).toBeNull();
+ });
+
test('returns null when href attr missing', () => {
const mark = makeMarkInfo({});
expect(computeLinkResolutionAttrs(mark, null, 'README')).toBeNull();
@@ -258,19 +270,24 @@ describe('computeLinkResolutionAttrs', () => {
});
});
- test('wikiembed-sourced link → no decoration (skip classification)', () => {
+ test('wikiembed-sourced media link → asset, not broken-link styling', () => {
// Asset-embed links (`![[foo.pdf]]` → link mark with sourceForm='wikiembed')
- // must NOT be classified against the pages cache — the cache is markdown-
- // only, so PDF/video/audio hrefs would always resolve 'unresolved' and
- // paint the link with broken-link styling.
+ // must not be painted with broken-link styling. They used to be skipped
+ // wholesale to achieve that, because resolving a PDF/video/audio href
+ // against the markdown-only pages cache always came back 'unresolved'. The
+ // href is classified as an asset on its own merits now, so the embed
+ // resolves rather than being silenced — which also lets a document-shaped
+ // embed report the missing target the skip used to swallow.
const cache = makeCache({ pages: ['README'] });
const mark = makeMarkInfo({ href: 'docs/foo.pdf', sourceForm: 'wikiembed' });
- expect(computeLinkResolutionAttrs(mark, cache, 'README')).toBeNull();
+ expect(computeLinkResolutionAttrs(mark, cache, 'README')).toEqual({
+ 'data-resolution-state': 'asset',
+ });
});
test('plain link mark (sourceForm=null) still gets decoration', () => {
- // Regression guard: the skip-for-wikiembed rule must NOT affect normal
- // markdown links `[text](./foo.md)` — those still need resolution state.
+ // Regression guard: wiki-embed handling must NOT affect normal markdown
+ // links `[text](./foo.md)` — those still need resolution state.
const cache = makeCache({ pages: ['OTHER'] });
const mark = makeMarkInfo({ href: './OTHER.md', sourceForm: null });
expect(computeLinkResolutionAttrs(mark, cache, 'README')).toEqual({
diff --git a/packages/app/src/editor/extensions/link-resolution.ts b/packages/app/src/editor/extensions/link-resolution.ts
index 2d1e6479c..b27c917ab 100644
--- a/packages/app/src/editor/extensions/link-resolution.ts
+++ b/packages/app/src/editor/extensions/link-resolution.ts
@@ -31,6 +31,7 @@
import { classifyMarkdownHref, resolveAssetProjectPath } from '@inkeep/open-knowledge-core';
import { resolveLinkTargetIntent } from '../../components/link-target-intent';
+import { isLinkValidationVisible } from '../link-validation-policy';
import type { PageListCacheSnapshot } from '../page-list-cache';
import type { MarkInfo } from './mark-identity';
@@ -114,8 +115,16 @@ export function computeLinkResolutionState(
pages: cache.pages,
folderPaths: cache.folderPaths,
});
- if (intent.kind === 'create') return 'unresolved';
- return intent.displayState;
+ if (intent.kind !== 'create') return intent.displayState;
+
+ // An extension-less href is syntactically ambiguous — it usually names a
+ // document, but it can name an ordinary file (`assets/NOTICE`). The server's
+ // canonical classifier settles that with exact inventory membership: document
+ // identity first, then an exact file hit. Resolving only against `pages` +
+ // `folderPaths` here means the editor paints a redlink, and offers Create
+ // page, over a file the server has already proven exists.
+ if (isResolvedAssetHref(href, sourceDocName, cache.assetPaths, cache.filePaths)) return 'asset';
+ return 'unresolved';
}
/**
@@ -133,12 +142,15 @@ export function computeLinkResolutionAttrs(
): Record<string, string> | null {
const href = markInfo.attrs?.href;
if (typeof href !== 'string' || href.length === 0) return null;
- // Wiki-embed asset links are not doc-links — the pages cache is markdown-
- // only, so running the doc-link intent classifier against a PDF/video/
- // audio href always returns 'unresolved' and paints the link as broken.
- // Skip the decoration; asset links get default <a> styling.
- if (markInfo.attrs?.sourceForm === 'wikiembed') return null;
+ // Wiki embeds resolve like every other form, never skipped: the document
+ // branch consults the tracked-file sets the way the server's classifier
+ // does, so a PDF/video/audio embed resolves as an asset on its own merits
+ // instead of coming back 'unresolved' against the markdown-only page cache.
+ // Skipping would not be a conservative default but a silence — it would also
+ // swallow document-shaped embeds like `![[targets/missing-embed]]`, which
+ // the server reports as a missing document.
const state = computeLinkResolutionState(href, sourceDocName, cache);
+ if (state === 'unresolved' && !isLinkValidationVisible()) return null;
return { 'data-resolution-state': state };
}
diff --git a/packages/app/src/editor/extensions/shared.ts b/packages/app/src/editor/extensions/shared.ts
index 94ae1b21b..0c0ecf898 100644
--- a/packages/app/src/editor/extensions/shared.ts
+++ b/packages/app/src/editor/extensions/shared.ts
@@ -34,6 +34,7 @@ import { FootnoteAnchorScroll } from './footnote-anchor-scroll';
import { FormattingShortcuts } from './formatting-shortcuts';
import { HeadingAnchors } from './heading-anchors';
import { ImageInlineZoom } from './image-inline-zoom';
+import { ImageReference } from './image-reference';
import { InternalLink } from './internal-link';
import { JsxComponent } from './jsx-component';
import { JsxInline } from './jsx-inline';
@@ -87,6 +88,7 @@ export const sharedExtensions = [
const coreOptions = (ext as unknown as { options?: Record<string, unknown> }).options ?? {};
return ImageInlineZoom.configure({ ...coreOptions, inline: true });
}
+ if (ext.name === 'imageReference') return ImageReference;
if (ext.name === 'rawMdxFallback') return RawMdxFallback;
if (ext.name === 'wikiLink') return WikiLink;
if (ext.name === 'wikiLinkEmbed') return WikiLinkEmbed;
diff --git a/packages/app/src/editor/extensions/wiki-link-embed.test.ts b/packages/app/src/editor/extensions/wiki-link-embed.test.ts
index ceecbce85..b5d4c05be 100644
--- a/packages/app/src/editor/extensions/wiki-link-embed.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link-embed.test.ts
@@ -1,90 +1,53 @@
-/**
- * Unit tests for the WikiLinkEmbed image NodeView DOM builder. Pins the
- * desktop-origin rewrite: `dom.setAttribute('src',
- * …)` must route through `toDesktopAssetHref` so server-absolute paths land
- * on the utility-process API origin in Electron. Without this, `![[photo.png]]`
- * embeds break under `file://` page contexts the same way plain-markdown
- * images did before this rewrite.
- *
- * Pattern: bare-Bun (no happy-dom). The DOM-builder accepts an injectable
- * `doc: Pick<Document, 'createElement'>` for exactly this purpose; we feed a
- * stub element that records `setAttribute` calls.
- */
-import { afterEach, describe, expect, test } from 'vitest';
-import { buildWikiLinkEmbedImageDom } from './wiki-link-embed.ts';
+import { describe, expect, test } from 'vitest';
+import { applyWikiLinkEmbedImageDomAttributes } from './wiki-link-embed.ts';
interface RecordingElement {
attrs: Map<string, string>;
- setAttribute: (k: string, v: string) => void;
+ setAttribute: (key: string, value: string) => void;
}
-function makeStubDoc(): {
- doc: { createElement: () => RecordingElement };
- lastEl: () => RecordingElement | null;
-} {
- let last: RecordingElement | null = null;
+function makeElement(): RecordingElement {
+ const attrs = new Map<string, string>();
return {
- doc: {
- createElement: () => {
- const attrs = new Map<string, string>();
- const el: RecordingElement = {
- attrs,
- setAttribute: (k, v) => {
- attrs.set(k, v);
- },
- };
- last = el;
- return el;
- },
- },
- lastEl: () => last,
+ attrs,
+ setAttribute: (key, value) => attrs.set(key, value),
};
}
-const g = globalThis as { window?: unknown };
-
-afterEach(() => {
- delete g.window;
-});
-
-describe('buildWikiLinkEmbedImageDom — desktop-origin rewrite', () => {
- test('without window.okDesktop, src stays server-absolute', () => {
- const { doc, lastEl } = makeStubDoc();
- buildWikiLinkEmbedImageDom({
+describe('applyWikiLinkEmbedImageDomAttributes', () => {
+ test('marks the React-rendered image wrapper as a non-editable wiki embed', () => {
+ const dom = makeElement();
+ applyWikiLinkEmbedImageDomAttributes(dom as unknown as HTMLElement, {
nodeId: 'wle-1',
target: 'photo.png',
alias: null,
- src: '/attachments/photo.png',
- doc: doc as unknown as Pick<Document, 'createElement'>,
});
- expect(lastEl()?.attrs.get('src')).toBe('/attachments/photo.png');
+
+ expect(dom.attrs.get('data-wiki-embed')).toBe('');
+ expect(dom.attrs.get('data-node-id')).toBe('wle-1');
+ expect(dom.attrs.get('data-target')).toBe('photo.png');
+ expect(dom.attrs.get('contenteditable')).toBe('false');
});
- test('with window.okDesktop.config.apiOrigin, src is prefixed onto the origin', () => {
- g.window = { okDesktop: { config: { apiOrigin: 'http://127.0.0.1:54321' } } };
- const { doc, lastEl } = makeStubDoc();
- buildWikiLinkEmbedImageDom({
+ test('keeps the authored alias on the outer NodeView wrapper', () => {
+ const dom = makeElement();
+ applyWikiLinkEmbedImageDomAttributes(dom as unknown as HTMLElement, {
nodeId: 'wle-2',
target: 'photo.png',
- alias: null,
- src: '/attachments/photo.png',
- doc: doc as unknown as Pick<Document, 'createElement'>,
+ alias: 'Team photo',
});
- expect(lastEl()?.attrs.get('src')).toBe('http://127.0.0.1:54321/attachments/photo.png');
+
+ expect(dom.attrs.get('data-alias')).toBe('Team photo');
});
- test('non-server-absolute src (relative) passes through untouched even under desktop', () => {
- g.window = { okDesktop: { config: { apiOrigin: 'http://127.0.0.1:54321' } } };
- const { doc, lastEl } = makeStubDoc();
- buildWikiLinkEmbedImageDom({
+ test('normalizes a missing alias to the empty data attribute', () => {
+ const dom = makeElement();
+ applyWikiLinkEmbedImageDomAttributes(dom as unknown as HTMLElement, {
nodeId: 'wle-3',
target: 'photo.png',
alias: null,
- src: 'photo.png',
- doc: doc as unknown as Pick<Document, 'createElement'>,
});
- // toDesktopAssetHref short-circuits on non-`/`-prefixed input — the chip
- // should carry the bare target without an origin prefix.
- expect(lastEl()?.attrs.get('src')).toBe('photo.png');
+
+ expect(dom.attrs.get('data-alias')).toBe('');
});
});
diff --git a/packages/app/src/editor/extensions/wiki-link-embed.ts b/packages/app/src/editor/extensions/wiki-link-embed.ts
index a3e2f9f0b..0c4d5ca63 100644
--- a/packages/app/src/editor/extensions/wiki-link-embed.ts
+++ b/packages/app/src/editor/extensions/wiki-link-embed.ts
@@ -1,10 +1,11 @@
/**
- * App-layer WikiLinkEmbed extension — plain-DOM NodeView routed via the
- * shared InteractionLayer.
+ * App-layer WikiLinkEmbed extension. Asset chips use a plain-DOM NodeView
+ * routed via the shared InteractionLayer; image embeds use the shared React
+ * image leaf so all image failures report consistently.
*
* Mirrors the `wiki-link.ts` pattern (atom-node + module-level counter +
* InteractionLayer registration + in-place DOM update). Image extensions
- * render as `<img>` (matching the core `renderHTML` output) and do NOT
+ * render a React-owned `<img>` (matching the core `renderHTML` output) and do NOT
* register with the layer — clicking an inline image is a PM-selection
* operation, not an asset dispatch. Non-image extensions render as a
* clickable `<a>` chip + register `handlePrimary` → `activateAssetLink`:
@@ -27,10 +28,11 @@ import {
extractAssetExtension,
IMAGE_EXTENSIONS,
resolveAssetProjectPath,
- toDesktopAssetHref,
} from '@inkeep/open-knowledge-core';
+import { ReactRenderer } from '@tiptap/react';
import { getInteractionLayer } from '../interaction-layer-host';
import { activateAssetLink } from '../internal-link-helpers';
+import { WikiLinkEmbedImageView } from './WikiLinkEmbedImageView';
// Module-level monotonic counter — drives the stable `data-node-id`
// attribute used by InteractionLayer's event delegation.
@@ -97,37 +99,21 @@ function buildWikiLinkEmbedChipDom(params: {
}
/**
- * Build the plain-DOM `<img>` for image-ext WikiLinkEmbed NodeViews.
- * No InteractionLayer registration — inline images don't have an asset-
- * dispatch click story (clicking selects, same as before this amendment).
- *
- * Exported (internal) for unit testing — the DOM layout + `toDesktopAssetHref`
- * application can be exercised without constructing a full TipTap Editor.
+ * Apply the stable NodeView metadata around the shared React image leaf.
*/
-export function buildWikiLinkEmbedImageDom(params: {
- nodeId: string;
- target: string;
- alias: string | null;
- src: string;
- doc?: Pick<Document, 'createElement'>;
-}): BuildChipDomResult {
- const docImpl: Pick<Document, 'createElement'> =
- params.doc ??
- (typeof document !== 'undefined' ? document : ({ createElement: null as never } as never));
-
- const dom = docImpl.createElement('img') as HTMLElement;
+export function applyWikiLinkEmbedImageDomAttributes(
+ dom: HTMLElement,
+ params: {
+ nodeId: string;
+ target: string;
+ alias: string | null;
+ },
+): void {
dom.setAttribute('data-wiki-embed', '');
dom.setAttribute('data-node-id', params.nodeId);
dom.setAttribute('data-target', params.target);
dom.setAttribute('data-alias', params.alias ?? '');
- // `resolvedSrc` is server-absolute (`/<contentDir-relative>`); in Electron
- // the page may be at `file://` or a Vite dev URL with no asset middleware,
- // so `/...` resolves against the wrong base. Mirror the rewrite the
- // canonical media components apply (Image.tsx, Video.tsx, Audio.tsx,
- // Pdf.tsx, File.tsx + ImageSrcFidelity.renderHTML).
- dom.setAttribute('src', toDesktopAssetHref(params.src));
- dom.setAttribute('alt', params.alias ?? params.target);
- return { dom };
+ dom.setAttribute('contenteditable', 'false');
}
function isImageExtension(target: string): boolean {
@@ -152,7 +138,14 @@ export const WikiLinkEmbed = BaseWikiLinkEmbed.extend({
// dispatch — the click is a PM-selection concern).
if (isImage) {
const src = resolvedSrc ?? target;
- const { dom } = buildWikiLinkEmbedImageDom({ nodeId, target, alias, src });
+ const renderer = new ReactRenderer(WikiLinkEmbedImageView, {
+ editor,
+ props: { src, alt: alias ?? target },
+ as: 'span',
+ className: 'wiki-link-embed-image',
+ });
+ const dom = renderer.element;
+ applyWikiLinkEmbedImageDomAttributes(dom, { nodeId, target, alias });
return {
dom,
ignoreMutation: () => true,
@@ -170,12 +163,15 @@ export const WikiLinkEmbed = BaseWikiLinkEmbed.extend({
// `false` if the new target isn't an image so PM rebuilds.
if (!isImageExtension(newTarget)) return false;
const newSrc = newResolvedSrc ?? newTarget;
- dom.setAttribute('data-target', newTarget);
- dom.setAttribute('data-alias', newAlias ?? '');
- dom.setAttribute('src', toDesktopAssetHref(newSrc));
- dom.setAttribute('alt', newAlias ?? newTarget);
+ applyWikiLinkEmbedImageDomAttributes(dom, {
+ nodeId,
+ target: newTarget,
+ alias: newAlias,
+ });
+ renderer.updateProps({ src: newSrc, alt: newAlias ?? newTarget });
return true;
},
+ destroy: () => renderer.destroy(),
};
}
diff --git a/packages/app/src/editor/extensions/wiki-link.external-open.test.ts b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
index b874a4bfa..0581ca1ea 100644
--- a/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
@@ -14,11 +14,21 @@
* `window.open`).
*/
+import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
import { Editor } from '@tiptap/core';
import { TextSelection } from '@tiptap/pm/state';
import StarterKit from '@tiptap/starter-kit';
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { getInteractionLayer } from '../interaction-layer-host';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
+import {
+ __resetPageListCacheForTests,
+ buildPagesBySlugIndex,
+ setPageListCache,
+} from '../page-list-cache';
import { installDomGlobals } from '../walk-currency-test-harness';
import { WikiLink } from './wiki-link';
@@ -49,6 +59,8 @@ const liveEditors = new Set<Editor>();
afterEach(() => {
for (const editor of liveEditors) editor.destroy();
liveEditors.clear();
+ __resetPageListCacheForTests();
+ resetLinkValidationPolicyForTest();
delete testWindow().okDesktop;
});
@@ -91,6 +103,20 @@ function mountWithExternalWikiLink(url: string): {
};
}
+function mountWikiLink(target: string): { editor: Editor; chip: HTMLElement } {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content: `<p><span data-wiki-link data-target="${target}"></span></p>`,
+ extensions: [StarterKit, WikiLink.configure({ docName: 'notes/test' })],
+ });
+ liveEditors.add(editor);
+ const chip = host.querySelector<HTMLElement>('[data-wiki-link]');
+ if (!chip) throw new Error('setup: no wiki-link chip');
+ return { editor, chip };
+}
+
describe('WYSIWYG wiki-link external activation — desktop (bridge present)', () => {
test('bare click routes to the OS browser via okDesktop.shell.openExternal, NOT window.open', () => {
const url = 'https://youtube.com/watch?v=abc';
@@ -126,3 +152,23 @@ describe('WYSIWYG wiki-link external activation — web (no bridge)', () => {
expect(openWindow).toHaveBeenCalledWith(url, '_blank', 'noopener,noreferrer');
});
});
+
+describe('WYSIWYG wiki-link validation visibility', () => {
+ test('a missing chip repaints when validation visibility changes at runtime', () => {
+ const pages = new Set<string>();
+ setPageListCache({
+ pages,
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ filePaths: new Set(),
+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),
+ });
+ const { chip } = mountWikiLink('missing-page');
+
+ expect(chip.getAttribute('data-resolution-state')).toBe('unresolved');
+ setLinkValidationVisible(false);
+ expect(chip.hasAttribute('data-resolution-state')).toBe(false);
+ setLinkValidationVisible(true);
+ expect(chip.getAttribute('data-resolution-state')).toBe('unresolved');
+ });
+});
diff --git a/packages/app/src/editor/extensions/wiki-link.ts b/packages/app/src/editor/extensions/wiki-link.ts
index 9608299ef..662465044 100644
--- a/packages/app/src/editor/extensions/wiki-link.ts
+++ b/packages/app/src/editor/extensions/wiki-link.ts
@@ -29,6 +29,10 @@ import {
openInternalHashHrefInNewTab,
toInternalHashHref,
} from '../internal-link-helpers';
+import {
+ isLinkValidationVisible,
+ subscribeToLinkValidationPolicy,
+} from '../link-validation-policy';
import {
getPageListCache,
type PageListCacheSnapshot,
@@ -149,6 +153,67 @@ export function getWikiLinkIcon(
return resolved;
}
+/**
+ * Pure helper — the chip's resolution state for one wiki-link target, in the
+ * same vocabulary the link-mark decoration uses (`data-resolution-state`).
+ * Exported for unit testing.
+ *
+ * Wiki-link chips are NODES, not link marks, so the decoration plugin — wired
+ * for `markTypes: ['link']` — never reaches them. Without this the chip carried
+ * no resolution state at all and a missing target rendered resolved-blue, while
+ * the server reported it missing and the hover card offered Create page.
+ *
+ * Resolution mirrors `handlePrimary` exactly, including its tolerant inputs, so
+ * a chip's colour can never disagree with where clicking it goes.
+ */
+export function getWikiLinkResolutionState(
+ target: string,
+ anchor: string | null,
+ cache: PageListCacheSnapshot | null,
+): string | null {
+ if (!target) return null;
+ const classified = classifyWikiLinkTarget(target, anchor);
+ if (!classified) return null;
+ if (classified.kind === 'external') return 'external';
+ if (!cache) return 'loading';
+ if (classified.kind === 'asset') {
+ if (cache.assetPaths === undefined && cache.filePaths === undefined) return 'asset';
+ return resolveWikiLinkAssetTarget(
+ classified.url,
+ cache.assetPaths ?? new Set(),
+ cache.filePaths,
+ )
+ ? 'asset'
+ : isLinkValidationVisible()
+ ? 'unresolved'
+ : null;
+ }
+ const intent = resolveLinkTargetIntent(target, {
+ pages: cache.pages,
+ folderPaths: cache.folderPaths,
+ pagesBySlug: cache.pagesBySlug,
+ pagesByBasename: cache.pagesByBasename,
+ fallbackTargets: getWikiLinkResolutionCandidates(target),
+ });
+ if (intent.kind !== 'create') return intent.displayState;
+ return isLinkValidationVisible() ? 'unresolved' : null;
+}
+
+/**
+ * Mutate the chip's resolution-state attribute in-place. Idempotent, and
+ * mirrors `syncWikiLinkIconSlot`'s equality short-circuit so a repaint that
+ * resolves the same way costs one attribute comparison.
+ */
+function syncWikiLinkResolutionState(dom: HTMLElement, state: string | null): void {
+ const next = state ?? '';
+ if (dom.getAttribute('data-resolution-state') === next) return;
+ if (!next) {
+ dom.removeAttribute('data-resolution-state');
+ return;
+ }
+ dom.setAttribute('data-resolution-state', next);
+}
+
/**
* Mutate the icon slot in-place to match `icon`. Idempotent — re-running
* with the same `(kind, value)` is a no-op (cheap equality check on the
@@ -232,11 +297,18 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({
// a single attr comparison, no DOM writes.
const refreshIconSlot = () => {
const liveTarget = String(currentNode.attrs.target ?? '');
- const icon = getWikiLinkIcon(liveTarget, getPageListCache());
- syncWikiLinkIconSlot(iconSpan, icon);
+ const liveAnchor =
+ currentNode.attrs.anchor != null ? String(currentNode.attrs.anchor) : null;
+ const snapshot = getPageListCache();
+ syncWikiLinkIconSlot(iconSpan, getWikiLinkIcon(liveTarget, snapshot));
+ syncWikiLinkResolutionState(
+ dom,
+ getWikiLinkResolutionState(liveTarget, liveAnchor, snapshot),
+ );
};
refreshIconSlot();
const unsubscribePageListCache = subscribePageListCache(refreshIconSlot);
+ const unsubscribePolicy = subscribeToLinkValidationPolicy(refreshIconSlot);
const safeGetPos = (): number | undefined => {
const pos = getPos();
@@ -378,6 +450,7 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({
destroy: () => {
layer.deregister(nodeId);
unsubscribePageListCache();
+ unsubscribePolicy();
},
};
};
diff --git a/packages/app/src/editor/link-validation-policy.ts b/packages/app/src/editor/link-validation-policy.ts
new file mode 100644
index 000000000..e53e1d208
--- /dev/null
+++ b/packages/app/src/editor/link-validation-policy.ts
@@ -0,0 +1,26 @@
+/** Live client policy for whether unresolved-link decorations are visible. */
+
+type Listener = () => void;
+
+let enabled = true;
+const listeners = new Set<Listener>();
+
+export function isLinkValidationVisible(): boolean {
+ return enabled;
+}
+
+export function setLinkValidationVisible(next: boolean): void {
+ if (enabled === next) return;
+ enabled = next;
+ for (const listener of listeners) listener();
+}
+
+export function subscribeToLinkValidationPolicy(listener: Listener): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function resetLinkValidationPolicyForTest(): void {
+ enabled = true;
+ listeners.clear();
+}
diff --git a/packages/app/src/editor/localized-validation-message.ts b/packages/app/src/editor/localized-validation-message.ts
new file mode 100644
index 000000000..b665e2915
--- /dev/null
+++ b/packages/app/src/editor/localized-validation-message.ts
@@ -0,0 +1,23 @@
+import type { ValidationDocResult } from '@inkeep/open-knowledge-core';
+import { t } from '@lingui/core/macro';
+
+type Diagnostic = ValidationDocResult['diagnostics'][number];
+
+/** Localize structured local-target findings without parsing server prose. */
+export function localizedValidationMessage(diagnostic: Diagnostic): string {
+ const evidence = diagnostic.localTarget;
+ if (diagnostic.source !== 'links' || evidence === undefined) return diagnostic.message;
+
+ const shown = evidence.resolvedTarget ?? evidence.href;
+ if (evidence.reason === 'unresolvable') {
+ return evidence.role === 'image'
+ ? 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.targetKind === 'file') {
+ return evidence.role === 'image'
+ ? t`Image target "${shown}" does not resolve to an existing file.`
+ : t`Link target "${shown}" does not resolve to an existing file.`;
+ }
+ return t`Link target "${shown}" does not resolve to an existing document.`;
+}
diff --git a/packages/app/src/editor/plugins/md-link-source.test.ts b/packages/app/src/editor/plugins/md-link-source.test.ts
index be005593d..dd95b79c8 100644
--- a/packages/app/src/editor/plugins/md-link-source.test.ts
+++ b/packages/app/src/editor/plugins/md-link-source.test.ts
@@ -1,5 +1,9 @@
import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
-import { describe, expect, test } from 'vitest';
+import { beforeEach, describe, expect, test } from 'vitest';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
import { markdownSourceLinkClass } from './md-link-source';
@@ -18,6 +22,8 @@ function makeCache(opts: {
}
describe('markdownSourceLinkClass', () => {
+ beforeEach(() => resetLinkValidationPolicyForTest());
+
test('external URLs are not source-mode internal links', () => {
expect(markdownSourceLinkClass('https://example.com', 'README', makeCache({}))).toBeNull();
expect(markdownSourceLinkClass('//example.com/page', 'README', makeCache({}))).toBeNull();
@@ -33,6 +39,13 @@ describe('markdownSourceLinkClass', () => {
);
});
+ test('validation.links off keeps a missing target navigable without broken styling', () => {
+ setLinkValidationVisible(false);
+ expect(markdownSourceLinkClass('/not-existing', 'README', makeCache({ pages: [] }))).toBe(
+ 'cm-md-internal-link',
+ );
+ });
+
test('existing root-absolute docs keep the normal internal class', () => {
expect(
markdownSourceLinkClass('/docs/page.md', 'README', makeCache({ pages: ['docs/page'] })),
diff --git a/packages/app/src/editor/plugins/md-link-source.ts b/packages/app/src/editor/plugins/md-link-source.ts
index c2c22bfea..91c0d94ed 100644
--- a/packages/app/src/editor/plugins/md-link-source.ts
+++ b/packages/app/src/editor/plugins/md-link-source.ts
@@ -26,6 +26,10 @@ import {
openInternalHashHrefInNewTab,
shouldOpenInNewTab,
} from '../internal-link-helpers';
+import {
+ isLinkValidationVisible,
+ subscribeToLinkValidationPolicy,
+} from '../link-validation-policy';
import type { PageListCacheSnapshot } from '../page-list-cache';
import { getPageListCache, subscribePageListCache } from '../page-list-cache';
@@ -48,7 +52,9 @@ export function markdownSourceLinkClass(
): string | null {
const state = computeLinkResolutionState(href, sourceDocName, cache);
if (state === 'external') return null;
- return state === 'unresolved' ? 'cm-md-internal-link cm-md-link-broken' : 'cm-md-internal-link';
+ return state === 'unresolved' && isLinkValidationVisible()
+ ? 'cm-md-internal-link cm-md-link-broken'
+ : 'cm-md-internal-link';
}
function markdownSourceLinkMark(
@@ -95,12 +101,15 @@ const mdLinkDecorations = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
private cacheAtBuild: PageListCacheSnapshot | null;
- private readonly unsubscribe: () => void;
+ private validationVisibleAtBuild: boolean;
+ private readonly unsubscribePageList: () => void;
+ private readonly unsubscribePolicy: () => void;
constructor(view: EditorView) {
this.cacheAtBuild = getPageListCache();
+ this.validationVisibleAtBuild = isLinkValidationVisible();
this.decorations = buildDecorations(view);
- this.unsubscribe = subscribePageListCache((snapshot) => {
+ this.unsubscribePageList = subscribePageListCache((snapshot) => {
if (this.cacheAtBuild === snapshot) return;
queueMicrotask(() => {
try {
@@ -110,16 +119,31 @@ const mdLinkDecorations = ViewPlugin.fromClass(
}
});
});
+ this.unsubscribePolicy = subscribeToLinkValidationPolicy(() => {
+ try {
+ view.dispatch({});
+ } catch {
+ /* view destroyed before policy refresh */
+ }
+ });
}
update(update: ViewUpdate) {
const cache = getPageListCache();
- if (update.docChanged || update.viewportChanged || this.cacheAtBuild !== cache) {
+ const validationVisible = isLinkValidationVisible();
+ if (
+ update.docChanged ||
+ update.viewportChanged ||
+ this.cacheAtBuild !== cache ||
+ this.validationVisibleAtBuild !== validationVisible
+ ) {
this.cacheAtBuild = cache;
+ this.validationVisibleAtBuild = validationVisible;
this.decorations = buildDecorations(update.view);
}
}
destroy() {
- this.unsubscribe();
+ this.unsubscribePageList();
+ this.unsubscribePolicy();
}
},
{ decorations: (v) => v.decorations },
diff --git a/packages/app/src/editor/plugins/wiki-link-source.test.ts b/packages/app/src/editor/plugins/wiki-link-source.test.ts
index 54e1c3181..b3d718a46 100644
--- a/packages/app/src/editor/plugins/wiki-link-source.test.ts
+++ b/packages/app/src/editor/plugins/wiki-link-source.test.ts
@@ -1,10 +1,17 @@
-import { describe, expect, test } from 'vitest';
+import { beforeEach, describe, expect, test } from 'vitest';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
import {
buildKnownWikilinkTargetSet,
buildPageNameSet,
extractWikilinkTarget,
+ wikiLinkSourceClass,
} from './wiki-link-source';
+beforeEach(() => resetLinkValidationPolicyForTest());
+
/**
* Unit tests for the wikilink broken-detection primitives.
*
@@ -132,6 +139,15 @@ describe('extractWikilinkTarget', () => {
});
});
+describe('wikiLinkSourceClass', () => {
+ test('validation.links off suppresses the broken wikilink decoration', () => {
+ const targets = new Set(['known']);
+ expect(wikiLinkSourceClass('missing', targets)).toBe('cm-wiki-link cm-wiki-link-broken');
+ setLinkValidationVisible(false);
+ expect(wikiLinkSourceClass('missing', targets)).toBe('cm-wiki-link');
+ });
+});
+
describe('end-to-end target matching', () => {
test('valid wikilink resolves — target lookups succeed', () => {
const pageSet = buildPageNameSet([{ docName: 'existing-page', title: 'Existing' }]);
diff --git a/packages/app/src/editor/plugins/wiki-link-source.ts b/packages/app/src/editor/plugins/wiki-link-source.ts
index 511e21d2a..30ec07803 100644
--- a/packages/app/src/editor/plugins/wiki-link-source.ts
+++ b/packages/app/src/editor/plugins/wiki-link-source.ts
@@ -37,6 +37,10 @@ import {
type WikiLinkContext,
} from '../extensions/wiki-link-suggestion';
import { openInternalHashHrefInNewTab, shouldOpenInNewTab } from '../internal-link-helpers';
+import {
+ isLinkValidationVisible,
+ subscribeToLinkValidationPolicy,
+} from '../link-validation-policy';
// ── Data fetching (module-level TTL cache wrapping shared fetchers) ──────────
//
@@ -142,6 +146,14 @@ export function extractWikilinkTarget(inner: string): string {
return inner.split(/[#|]/)[0].trim().toLowerCase();
}
+export function wikiLinkSourceClass(inner: string, targetSet: ReadonlySet<string> | null): string {
+ if (targetSet === null) return 'cm-wiki-link';
+ const target = extractWikilinkTarget(inner);
+ return target && !targetSet.has(target) && isLinkValidationVisible()
+ ? 'cm-wiki-link cm-wiki-link-broken'
+ : 'cm-wiki-link';
+}
+
function buildDecorations(view: EditorView): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
// Cache-cold → all wikilinks get plain mark (no false-positive broken flash)
@@ -153,13 +165,8 @@ function buildDecorations(view: EditorView): DecorationSet {
WIKI_LINK_RE.lastIndex = 0;
let m = WIKI_LINK_RE.exec(text);
while (m !== null) {
- let mark = wikiLinkMark;
- if (targetSet) {
- const target = extractWikilinkTarget(m[0].slice(2, -2)); // strip [[ and ]]
- if (target && !targetSet.has(target)) {
- mark = wikiLinkBrokenMark;
- }
- }
+ const className = wikiLinkSourceClass(m[0].slice(2, -2), targetSet);
+ const mark = className.includes('cm-wiki-link-broken') ? wikiLinkBrokenMark : wikiLinkMark;
builder.add(from + m.index, from + m.index + m[0].length, mark);
m = WIKI_LINK_RE.exec(text);
}
@@ -171,17 +178,34 @@ const wikiLinkDecorations = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
private cacheWarmAtBuild: boolean;
+ private validationVisibleAtBuild: boolean;
+ private readonly unsubscribePolicy: () => void;
constructor(view: EditorView) {
this.cacheWarmAtBuild = pagesCache !== null;
+ this.validationVisibleAtBuild = isLinkValidationVisible();
this.decorations = buildDecorations(view);
+ this.unsubscribePolicy = subscribeToLinkValidationPolicy(() => {
+ try {
+ view.dispatch({});
+ } catch {
+ /* view destroyed before policy refresh */
+ }
+ });
if (!this.cacheWarmAtBuild) this.warmCache(view);
}
update(update: ViewUpdate) {
const cacheNowWarm = pagesCache !== null;
- if (update.docChanged || update.viewportChanged || (!this.cacheWarmAtBuild && cacheNowWarm)) {
+ const validationVisible = isLinkValidationVisible();
+ if (
+ update.docChanged ||
+ update.viewportChanged ||
+ (!this.cacheWarmAtBuild && cacheNowWarm) ||
+ this.validationVisibleAtBuild !== validationVisible
+ ) {
this.cacheWarmAtBuild = cacheNowWarm;
+ this.validationVisibleAtBuild = validationVisible;
this.decorations = buildDecorations(update.view);
}
}
@@ -199,6 +223,10 @@ const wikiLinkDecorations = ViewPlugin.fromClass(
console.warn('[wiki-link-source] warmCache fetch failed:', err);
});
}
+
+ destroy() {
+ this.unsubscribePolicy();
+ }
},
{ decorations: (v) => v.decorations },
);
diff --git a/packages/app/src/editor/source-lint/local-target-diagnostics.test.ts b/packages/app/src/editor/source-lint/local-target-diagnostics.test.ts
new file mode 100644
index 000000000..4aa1bcc6d
--- /dev/null
+++ b/packages/app/src/editor/source-lint/local-target-diagnostics.test.ts
@@ -0,0 +1,204 @@
+/**
+ * Unit tests for the pure server-assessment → CodeMirror diagnostic mapping.
+ *
+ * The source-mode target-existence layer takes the server's authoritative
+ * `source: 'links'` findings (already policy-gated by `validation.links`) and
+ * projects them onto CodeMirror lint diagnostics, widening each collapsed
+ * occurrence point to the enclosing link/image span via the Lezer tree so the
+ * squiggle covers the whole authored occurrence. Tested headless with an
+ * `EditorState` carrying the markdown language (for the syntax tree) — no DOM,
+ * matching the sibling `markdown-lint-source` + `source-polish` conventions.
+ */
+
+import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+import { EditorState } from '@codemirror/state';
+import type { ValidationDocResult } from '@inkeep/open-knowledge-core';
+import { GFM } from '@lezer/markdown';
+import { describe, expect, test } from 'vitest';
+import { mapLocalTargetDiagnostics } from './local-target-diagnostics.ts';
+
+type LinkFinding = ValidationDocResult['diagnostics'][number];
+
+function stateOf(doc: string): EditorState {
+ return EditorState.create({
+ doc,
+ extensions: [markdown({ base: markdownLanguage, extensions: [GFM] })],
+ });
+}
+
+/** A collapsed server finding: point range at (line, column), like the wire. */
+function finding(over: Partial<LinkFinding> & { line: number; column: number }): LinkFinding {
+ const { line, column, ...rest } = over;
+ return {
+ range: { start: { line, character: column }, end: { line, character: column } },
+ severity: 'warning',
+ source: 'links',
+ code: 'dead-link',
+ message: 'Link target "./x" does not resolve to an existing file.',
+ ...rest,
+ } as LinkFinding;
+}
+
+describe('mapLocalTargetDiagnostics', () => {
+ test('widens a missing-file link finding to span the whole authored link', () => {
+ const doc = 'See [the report](./missing.pdf) now.\n';
+ const state = stateOf(doc);
+ const linkStart = doc.indexOf('[the report]');
+ const linkEnd = doc.indexOf(')') + 1;
+ const [d] = mapLocalTargetDiagnostics(state, [
+ finding({
+ line: 0,
+ column: linkStart,
+ severity: 'error',
+ message: 'Link target "./missing.pdf" does not resolve to an existing file.',
+ }),
+ ]);
+ // The server collapses the range to the occurrence start; the source layer
+ // widens it to the enclosing Link node so the squiggle covers `[..](..)`.
+ expect(d?.from).toBe(linkStart);
+ expect(d?.to).toBe(linkEnd);
+ expect(d?.severity).toBe('error');
+ expect(d?.message).toBe('Link target "./missing.pdf" does not resolve to an existing file.');
+ expect(d?.source).toBe('links/dead-link');
+ });
+
+ test('widens a markdown image finding to span the whole authored image', () => {
+ const doc = 'A ![alt text](./missing.png) here.\n';
+ const state = stateOf(doc);
+ const imgStart = doc.indexOf('![alt text]');
+ const imgEnd = doc.indexOf(')') + 1;
+ const [d] = mapLocalTargetDiagnostics(state, [
+ finding({
+ line: 0,
+ column: imgStart,
+ message: 'Image target "./missing.png" does not resolve to an existing file.',
+ }),
+ ]);
+ expect(d?.from).toBe(imgStart);
+ expect(d?.to).toBe(imgEnd);
+ });
+
+ test('widens a bare HTML img finding to span the whole tag', () => {
+ const doc = 'Inline <img src="./missing.png"> image.\n';
+ const state = stateOf(doc);
+ const tagStart = doc.indexOf('<img');
+ const tagEnd = doc.indexOf('>') + 1;
+ const [d] = mapLocalTargetDiagnostics(state, [
+ finding({
+ line: 0,
+ column: tagStart,
+ message: 'Image target "./missing.png" does not resolve to an existing file.',
+ }),
+ ]);
+ // HTML img must land a real span, not a point — it is the form the ticket
+ // names and the one no prior source-mode treatment covered.
+ expect(d?.from).toBe(tagStart);
+ expect(d?.to).toBeGreaterThan(tagStart);
+ expect(d?.to).toBe(tagEnd);
+ });
+
+ test('positions every reference-style use independently over the same label', () => {
+ const doc = 'First [one][r] and second [two][r].\n\n[r]: ./missing.pdf\n';
+ const state = stateOf(doc);
+ const firstUse = doc.indexOf('[one][r]');
+ const secondUse = doc.indexOf('[two][r]');
+ const diagnostics = mapLocalTargetDiagnostics(state, [
+ finding({
+ line: 0,
+ column: firstUse,
+ message: 'Link target "./missing.pdf" does not resolve to an existing file.',
+ localTarget: {
+ href: './missing.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'missing.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ definition: { line: 2, label: 'r' },
+ },
+ }),
+ finding({
+ line: 0,
+ column: secondUse,
+ message: 'Link target "./missing.pdf" does not resolve to an existing file.',
+ localTarget: {
+ href: './missing.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'missing.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ definition: { line: 2, label: 'r' },
+ },
+ }),
+ ]);
+ expect(diagnostics).toHaveLength(2);
+ expect(diagnostics[0]?.from).toBe(firstUse);
+ expect(diagnostics[1]?.from).toBe(secondUse);
+ // Two distinct positioned diagnostics — the two uses never collapse to one.
+ expect(diagnostics[0]?.from).not.toBe(diagnostics[1]?.from);
+ });
+
+ test('widens a graph document dead-link (no local-target evidence) to its link span', () => {
+ const doc = 'See [the page](./gone) here.\n';
+ const state = stateOf(doc);
+ const linkStart = doc.indexOf('[the page]');
+ const [d] = mapLocalTargetDiagnostics(state, [
+ finding({
+ line: 0,
+ column: linkStart,
+ message: 'Link target "gone" does not resolve to an existing document.',
+ }),
+ ]);
+ expect(d?.from).toBe(linkStart);
+ expect(d?.to).toBe(doc.indexOf(')') + 1);
+ });
+
+ test('falls back to a positioned point when no link/image node encloses the occurrence', () => {
+ const doc = 'A [[Wiki Target]] embed.\n';
+ const state = stateOf(doc);
+ const wikiStart = doc.indexOf('[[Wiki Target]]');
+ const [d] = mapLocalTargetDiagnostics(state, [
+ finding({ line: 0, column: wikiStart, message: 'x' }),
+ ]);
+ // Wiki forms have no Lezer Link node; the diagnostic stays positioned at the
+ // occurrence rather than mis-widening onto unrelated text.
+ expect(d?.from).toBe(wikiStart);
+ expect(d?.to).toBe(wikiStart);
+ });
+
+ test('skips non-links findings (they belong to their own surfaces)', () => {
+ const doc = 'plain text\n';
+ const state = stateOf(doc);
+ expect(
+ mapLocalTargetDiagnostics(state, [
+ finding({ line: 0, column: 0, source: 'markdownlint', code: 'MD010' }),
+ finding({ line: 0, column: 0, source: 'frontmatter', code: 'required' }),
+ ]),
+ ).toHaveLength(0);
+ });
+
+ test('clamps an out-of-range occurrence instead of throwing', () => {
+ const doc = 'one line\n';
+ const state = stateOf(doc);
+ expect(() =>
+ mapLocalTargetDiagnostics(state, [finding({ line: 998, column: 40, message: 'x' })]),
+ ).not.toThrow();
+ expect(
+ mapLocalTargetDiagnostics(state, [finding({ line: 998, column: 40, message: 'x' })]),
+ ).toHaveLength(1);
+ });
+
+ test('maps severities: error, warning, and info', () => {
+ const doc = '[a](./x) [b](./y) [c](./z)\n';
+ const state = stateOf(doc);
+ const diagnostics = mapLocalTargetDiagnostics(state, [
+ finding({ line: 0, column: 0, severity: 'error' }),
+ finding({ line: 0, column: doc.indexOf('[b]'), severity: 'warning' }),
+ finding({ line: 0, column: doc.indexOf('[c]'), severity: 'info' }),
+ ]);
+ expect(diagnostics.map((d) => d.severity)).toEqual(['error', 'warning', 'info']);
+ });
+});
diff --git a/packages/app/src/editor/source-lint/local-target-diagnostics.test.tsx b/packages/app/src/editor/source-lint/local-target-diagnostics.test.tsx
new file mode 100644
index 000000000..a2c89edb7
--- /dev/null
+++ b/packages/app/src/editor/source-lint/local-target-diagnostics.test.tsx
@@ -0,0 +1,132 @@
+// @vitest-environment jsdom
+/**
+ * Narrow integration for the source-mode target-existence layer: a real
+ * `EditorView` with the extension installed, the audit fetch and CC1 push mocked
+ * at its subscription boundary, proving the wiring the pure mapping test cannot
+ * — settled findings render, a later settled plane heals them, and authored
+ * bytes never change.
+ */
+
+import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+import { EditorState } from '@codemirror/state';
+import { EditorView } from '@codemirror/view';
+import type { ValidationDocResult } from '@inkeep/open-knowledge-core';
+import { GFM } from '@lezer/markdown';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ resetLinkValidationPolicyForTest,
+ setLinkValidationVisible,
+} from '../link-validation-policy';
+
+type LinkFinding = ValidationDocResult['diagnostics'][number];
+
+let findingsListener:
+ | ((state: { status: 'loading' | 'loaded' | 'failed'; findings: readonly LinkFinding[] }) => void)
+ | null = null;
+
+vi.mock('../validation-audit-client', () => ({
+ subscribeToDocLinkFindings: (
+ _docName: string,
+ cb: (state: {
+ status: 'loading' | 'loaded' | 'failed';
+ findings: readonly LinkFinding[];
+ }) => void,
+ ) => {
+ findingsListener = cb;
+ cb({ status: 'loading', findings: [] });
+ return () => {
+ findingsListener = null;
+ };
+ },
+}));
+
+// Imported after the mocks are registered.
+const { createLocalTargetDiagnosticsExtension } = await import('./local-target-diagnostics.ts');
+
+const DOC = 'See [the report](./missing.pdf) now.\n';
+
+function missingFileFinding(): LinkFinding {
+ const column = DOC.indexOf('[the report]');
+ return {
+ range: { start: { line: 0, character: column }, end: { line: 0, character: column } },
+ severity: 'error',
+ source: 'links',
+ code: 'dead-link',
+ message: 'Link target "./missing.pdf" does not resolve to an existing file.',
+ } as LinkFinding;
+}
+
+let view: EditorView | null = null;
+
+function mount(): EditorView {
+ const parent = document.createElement('div');
+ document.body.appendChild(parent);
+ return new EditorView({
+ parent,
+ state: EditorState.create({
+ doc: DOC,
+ extensions: [
+ markdown({ base: markdownLanguage, extensions: [GFM] }),
+ createLocalTargetDiagnosticsExtension('doc'),
+ ],
+ }),
+ });
+}
+
+beforeEach(() => {
+ findingsListener = null;
+ resetLinkValidationPolicyForTest();
+});
+
+afterEach(() => {
+ view?.destroy();
+ view = null;
+ document.body.innerHTML = '';
+});
+
+describe('source-mode local-target diagnostics wiring', () => {
+ test('renders a fetched target-existence finding as a lint diagnostic', async () => {
+ view = mount();
+ findingsListener?.({ status: 'loaded', findings: [missingFileFinding()] });
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).not.toBeNull();
+ });
+ // Severity survives end-to-end: an `error` finding paints the error range.
+ expect(view?.dom.querySelector('.cm-lintRange-error')).not.toBeNull();
+ });
+
+ test('never mutates the authored source bytes', async () => {
+ view = mount();
+ findingsListener?.({ status: 'loaded', findings: [missingFileFinding()] });
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).not.toBeNull();
+ });
+ expect(view?.state.doc.toString()).toBe(DOC);
+ });
+
+ test('heals the diagnostic after the target subscription settles present', async () => {
+ view = mount();
+ findingsListener?.({ status: 'loaded', findings: [missingFileFinding()] });
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).not.toBeNull();
+ });
+ findingsListener?.({ status: 'loaded', findings: [] });
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).toBeNull();
+ });
+ expect(view?.state.doc.toString()).toBe(DOC);
+ });
+
+ test('clears a settled diagnostic immediately when validation.links turns off', async () => {
+ view = mount();
+ findingsListener?.({ status: 'loaded', findings: [missingFileFinding()] });
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).not.toBeNull();
+ });
+
+ setLinkValidationVisible(false);
+ await vi.waitFor(() => {
+ expect(view?.dom.querySelector('.cm-lint-local-target')).toBeNull();
+ });
+ });
+});
diff --git a/packages/app/src/editor/source-lint/local-target-diagnostics.ts b/packages/app/src/editor/source-lint/local-target-diagnostics.ts
new file mode 100644
index 000000000..a1d8675ad
--- /dev/null
+++ b/packages/app/src/editor/source-lint/local-target-diagnostics.ts
@@ -0,0 +1,177 @@
+/**
+ * Source-mode target-existence diagnostics.
+ *
+ * The server owns the authoritative local-target assessment (documents,
+ * ordinary files, images, and reference-style uses) and projects unresolved
+ * occurrences onto the unified validation plane as `source: 'links'` findings,
+ * already gated by the `validation.links` policy. This CodeMirror layer surfaces
+ * those findings as `@codemirror/lint` diagnostics — the accessible source-mode
+ * surface (gutter marker, hover message, keyboard-reachable lint panel) — one
+ * per authored occurrence, at the occurrence position.
+ *
+ * Two source-mode concerns stay distinct: a **missing reference definition**
+ * (`[text][ref]` with no `[ref]:` line) is a client-side syntax fact handled by
+ * `source-polish/broken-ref-field`; a **definition whose destination is missing**
+ * (`[ref]: ./missing.pdf`) is a target-existence fact the server assesses and
+ * this layer reports at the use. They never fire on the same occurrence — an
+ * unresolved reference use has no server occurrence to assess.
+ *
+ * The server collapses each finding's range to the occurrence start (the byte
+ * offset every consumer navigates to). Here the point is widened to the
+ * enclosing link/image span via the Lezer tree so the squiggle covers the whole
+ * authored occurrence; the span is the client's responsive rendering while the
+ * server remains the sole authority on whether the target exists (the client
+ * cache never contradicts a settled assessment because this layer reads the
+ * assessment, not the cache). No authored bytes are touched — diagnostics are
+ * decorations over the raw source.
+ */
+
+import { ensureSyntaxTree } from '@codemirror/language';
+import { type Diagnostic, forceLinting, linter } from '@codemirror/lint';
+import { type EditorState, type Extension, StateEffect, type Text } from '@codemirror/state';
+import { ViewPlugin } from '@codemirror/view';
+import type { LintPosition, ValidationDocResult } from '@inkeep/open-knowledge-core';
+import {
+ isLinkValidationVisible,
+ subscribeToLinkValidationPolicy,
+} from '../link-validation-policy';
+import { localizedValidationMessage } from '../localized-validation-message';
+import { subscribeToDocLinkFindings } from '../validation-audit-client';
+
+/** Wire-loose diagnostic (schema `source`/`severity` are strings, by design). */
+type LinkFinding = ValidationDocResult['diagnostics'][number];
+
+/**
+ * Lezer markdown node names whose span is the authored occurrence to underline.
+ * `Link`/`Image` cover inline and reference-style markdown; `HTMLTag`/`HTMLBlock`
+ * cover the bare and self-closing HTML `img` forms. Anything else (a wiki-link
+ * node, or a position the parser has not reached) falls back to the point.
+ */
+const OCCURRENCE_NODE_NAMES = new Set(['Link', 'Image', 'HTMLTag', 'HTMLBlock']);
+
+/** Selector hook so tests + any future styling can target this layer's ranges
+ * distinctly from markdownlint ranges (the severity class drives the visual). */
+const LOCAL_TARGET_MARK_CLASS = 'cm-lint-local-target';
+
+/**
+ * Absolute CM offset for a 0-based LSP position, clamped: the doc can shift
+ * between the async audit fetch and this mapping, so an out-of-range line/column
+ * degrades to the nearest valid offset rather than throwing.
+ */
+function offsetOf(doc: Text, position: LintPosition): number {
+ const lineNumber = Math.min(Math.max(position.line + 1, 1), doc.lines);
+ const line = doc.line(lineNumber);
+ return Math.min(line.from + Math.max(0, position.character), line.to);
+}
+
+/**
+ * Widen the occurrence start to the enclosing link/image node's span. Returns a
+ * zero-width span at `start` when no recognized node encloses it (wiki forms, or
+ * a stale position after an edit) — still a positioned, accessible diagnostic.
+ */
+function occurrenceSpan(state: EditorState, start: number): { from: number; to: number } {
+ const tree = ensureSyntaxTree(state, start + 1, 100);
+ if (tree) {
+ // `SyntaxNode` is declared but not exported by @codemirror/language, so the
+ // walk type is taken from `resolveInner`'s own return rather than a named
+ // import (avoids adding @lezer/common as a direct dependency).
+ let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(start, 1);
+ while (node) {
+ if (OCCURRENCE_NODE_NAMES.has(node.name)) {
+ return { from: node.from, to: node.to };
+ }
+ node = node.parent;
+ }
+ }
+ return { from: start, to: start };
+}
+
+/** CodeMirror's severity scale admits `hint` too; the wire only ever carries
+ * these three. An unknown value degrades to `warning` rather than dropping. */
+function toCmSeverity(severity: string): Diagnostic['severity'] {
+ return severity === 'error' ? 'error' : severity === 'info' ? 'info' : 'warning';
+}
+
+/**
+ * Project the server's `source: 'links'` findings onto CodeMirror diagnostics,
+ * one per authored occurrence, each widened to its link/image span. Pure over
+ * `(state, findings)` so it runs headless in tests.
+ */
+export function mapLocalTargetDiagnostics(
+ state: EditorState,
+ findings: readonly LinkFinding[],
+): Diagnostic[] {
+ const doc = state.doc;
+ const diagnostics: Diagnostic[] = [];
+ for (const finding of findings) {
+ // Only link-plane findings carry a source occurrence; lint/frontmatter
+ // findings belong to their own surfaces and are skipped here.
+ if (finding.source !== 'links') continue;
+ const start = offsetOf(doc, finding.range.start);
+ const span = occurrenceSpan(state, start);
+ diagnostics.push({
+ from: span.from,
+ to: Math.max(span.to, span.from),
+ severity: toCmSeverity(finding.severity),
+ message: localizedValidationMessage(finding),
+ source: `${finding.source}/${finding.code}`,
+ markClass: LOCAL_TARGET_MARK_CLASS,
+ });
+ }
+ return diagnostics;
+}
+
+/**
+ * `needsRefresh` marker: findings arrive asynchronously (audit fetch + CC1
+ * `backlinks` pushes), not on doc edits, so a dispatched effect tells the lint
+ * plugin to re-run this source when the doc is otherwise unchanged.
+ */
+const refreshLocalTargetsEffect = StateEffect.define<null>();
+
+/**
+ * Source-mode extension: a lint source reading the latest server findings, plus
+ * a view plugin that fetches them for `docName` and re-fetches on every CC1
+ * `backlinks` push (a target create/delete/rename ripples through the link
+ * index). Composes with the markdownlint linter — `@codemirror/lint` merges all
+ * lint sources into one diagnostic plane.
+ */
+export function createLocalTargetDiagnosticsExtension(docName: string): Extension {
+ // Lives with the (cached, reparented) view rather than a React component, so
+ // findings survive an Activity park/remount — mirrors the self-contained
+ // markdown-lint-decorations pattern.
+ const holder: { findings: readonly LinkFinding[] } = { findings: [] };
+ return [
+ linter(
+ (view) =>
+ isLinkValidationVisible() ? mapLocalTargetDiagnostics(view.state, holder.findings) : [],
+ {
+ delay: 300,
+ needsRefresh: (update) =>
+ update.transactions.some((tr) =>
+ tr.effects.some((effect) => effect.is(refreshLocalTargetsEffect)),
+ ),
+ },
+ ),
+ ViewPlugin.define((view) => {
+ const apply = (findings: readonly LinkFinding[]): void => {
+ holder.findings = findings;
+ // Schedule (needsRefresh) then force it to run now: `forceLinting` alone
+ // no-ops while the plugin is idle, so the dispatch primes it first.
+ view.dispatch({ effects: refreshLocalTargetsEffect.of(null) });
+ forceLinting(view);
+ };
+ const unsubscribe = subscribeToDocLinkFindings(docName, (state) => {
+ // Preserve the last settled decorations while refreshing or degraded;
+ // an empty/unavailable request must never paint a falsely-clean source.
+ if (state.status === 'loaded') apply(state.findings);
+ });
+ const unsubscribePolicy = subscribeToLinkValidationPolicy(() => apply(holder.findings));
+ return {
+ destroy() {
+ unsubscribe();
+ unsubscribePolicy();
+ },
+ };
+ }),
+ ];
+}
diff --git a/packages/app/src/editor/source-lint/local-target-parity.test.ts b/packages/app/src/editor/source-lint/local-target-parity.test.ts
new file mode 100644
index 000000000..ac961f9f6
--- /dev/null
+++ b/packages/app/src/editor/source-lint/local-target-parity.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Cross-surface parity: the same authored local-link occurrence that produces a
+ * source-mode CodeMirror diagnostic also produces the WYSIWYG unresolved chip
+ * treatment, and neither surface relies on color alone (source: a lint range with
+ * its own selector hook + wavy severity underline; WYSIWYG: the `unresolved`
+ * resolution state, a wavy underline distinct from a resolved link's solid one).
+ *
+ * The two surfaces read different inputs — source reads the server's
+ * authoritative assessment (a `source: 'links'` finding), WYSIWYG reads the
+ * client page-list cache — so this pins that when both are told a target is
+ * missing they agree, the cross-surface parity contract a composed fixture
+ * exercises end-to-end.
+ */
+
+import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
+import { EditorState } from '@codemirror/state';
+import { toWikiLinkSlug, type ValidationDocResult } from '@inkeep/open-knowledge-core';
+import { GFM } from '@lezer/markdown';
+import { describe, expect, test } from 'vitest';
+import { computeLinkResolutionState } from '../extensions/link-resolution';
+import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
+import { mapLocalTargetDiagnostics } from './local-target-diagnostics.ts';
+
+type LinkFinding = ValidationDocResult['diagnostics'][number];
+
+function stateOf(doc: string): EditorState {
+ return EditorState.create({
+ doc,
+ extensions: [markdown({ base: markdownLanguage, extensions: [GFM] })],
+ });
+}
+
+/** A page-list cache that knows the project but not the target — the WYSIWYG
+ * equivalent of the server assessing the target as missing. */
+function cacheWithout(): PageListCacheSnapshot {
+ const pages = new Set<string>(['README']);
+ return {
+ pages,
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ filePaths: new Set(),
+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),
+ };
+}
+
+function serverFinding(doc: string, occurrence: string, message: string): LinkFinding {
+ const column = doc.indexOf(occurrence);
+ return {
+ range: { start: { line: 0, character: column }, end: { line: 0, character: column } },
+ severity: 'warning',
+ source: 'links',
+ code: 'dead-link',
+ message,
+ } as LinkFinding;
+}
+
+describe('source ⇄ WYSIWYG parity for an unresolved local link', () => {
+ test('a missing file link is flagged in both editor modes', () => {
+ const doc = 'See [the report](./missing.pdf) now.\n';
+ const href = './missing.pdf';
+
+ // Source mode: the server finding projects to one positioned lint diagnostic.
+ const [sourceDiag] = mapLocalTargetDiagnostics(stateOf(doc), [
+ serverFinding(
+ doc,
+ '[the report]',
+ `Link target "${href}" does not resolve to an existing file.`,
+ ),
+ ]);
+ expect(sourceDiag).toBeDefined();
+ expect(sourceDiag?.markClass).toBe('cm-lint-local-target');
+
+ // WYSIWYG: the chip resolves to `unresolved` (wavy, non-color-only).
+ expect(computeLinkResolutionState(href, 'README', cacheWithout())).toBe('unresolved');
+ });
+
+ test('a missing document link is flagged in both editor modes', () => {
+ const doc = 'See [the page](./gone.md) now.\n';
+ const href = './gone.md';
+
+ const [sourceDiag] = mapLocalTargetDiagnostics(stateOf(doc), [
+ serverFinding(
+ doc,
+ '[the page]',
+ `Link target "gone" does not resolve to an existing document.`,
+ ),
+ ]);
+ expect(sourceDiag).toBeDefined();
+
+ expect(computeLinkResolutionState(href, 'README', cacheWithout())).toBe('unresolved');
+ });
+
+ test('a resolved link is flagged in neither editor mode', () => {
+ const doc = 'See [the page](./OTHER.md) now.\n';
+ // No server finding for a resolved target → no source diagnostic.
+ expect(mapLocalTargetDiagnostics(stateOf(doc), [])).toHaveLength(0);
+ // Cache that knows the target → WYSIWYG resolves it.
+ const pages = new Set(['README', 'OTHER']);
+ const cache: PageListCacheSnapshot = {
+ pages,
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ filePaths: new Set(),
+ pagesBySlug: buildPagesBySlugIndex(pages, toWikiLinkSlug),
+ };
+ expect(computeLinkResolutionState('./OTHER.md', 'README', cache)).toBe('resolved');
+ });
+});
diff --git a/packages/app/src/editor/validation-audit-client.dom.test.tsx b/packages/app/src/editor/validation-audit-client.dom.test.tsx
index 38be676fc..55884b9ad 100644
--- a/packages/app/src/editor/validation-audit-client.dom.test.tsx
+++ b/packages/app/src/editor/validation-audit-client.dom.test.tsx
@@ -3,7 +3,7 @@
* `GET /api/audit` with the right scoping query, and `useDocLinkFindings`
* serves the doc's links-plane findings via the SAME endpoint (canonical
* predicate — no divergent doc-scope determination), refreshing on the CC1
- * `backlinks` push relay.
+ * `backlinks`, `local-targets`, and file-inventory push relays.
*/
import type { ValidationAuditResponse } from '@inkeep/open-knowledge-core';
@@ -83,8 +83,9 @@ describe('useDocLinkFindings', () => {
warnings: [],
};
const { result } = renderHook(() => useDocLinkFindings('notes'));
- await waitFor(() => expect(result.current).toHaveLength(1));
- expect(result.current[0]?.code).toBe('dead-link');
+ await waitFor(() => expect(result.current.status).toBe('loaded'));
+ expect(result.current.findings).toHaveLength(1);
+ expect(result.current.findings[0]?.code).toBe('dead-link');
expect(fetchUrls).toEqual(['/api/audit?doc=notes']);
});
@@ -97,22 +98,31 @@ describe('useDocLinkFindings', () => {
warnings: [],
};
const { result } = renderHook(() => useDocLinkFindings('notes'));
- await waitFor(() => expect(result.current).toHaveLength(1));
+ await waitFor(() => expect(result.current.findings).toHaveLength(1));
// The link target gets created elsewhere — the index push heals this doc.
fetchBody = { files: [], fileCount: 1, errorCount: 0, warningCount: 0, warnings: [] };
act(() => emitDocumentsChanged(['backlinks']));
- await waitFor(() => expect(result.current).toHaveLength(0));
+ await waitFor(() => expect(result.current.status).toBe('loaded'));
+ expect(result.current.findings).toHaveLength(0);
expect(fetchUrls).toEqual(['/api/audit?doc=notes', '/api/audit?doc=notes']);
- // Unrelated channels do not refetch.
+ act(() => emitDocumentsChanged(['local-targets']));
+ await waitFor(() => expect(fetchUrls).toHaveLength(3));
+
+ // The broad inventory signal is a correctness backstop for existence
+ // changes whose narrower local-target generation signal is missed.
act(() => emitDocumentsChanged(['files']));
- expect(fetchUrls).toHaveLength(2);
+ await waitFor(() => expect(fetchUrls).toHaveLength(4));
+
+ // Unrelated channels do not refetch.
+ act(() => emitDocumentsChanged(['tags']));
+ expect(fetchUrls).toHaveLength(4);
});
test('null docName serves no findings and never fetches', () => {
const { result } = renderHook(() => useDocLinkFindings(null));
- expect(result.current).toEqual([]);
+ expect(result.current).toEqual({ status: 'idle', findings: [] });
expect(fetchUrls).toEqual([]);
});
@@ -124,10 +134,16 @@ describe('useDocLinkFindings', () => {
warningCount: 0,
warnings: [],
};
- const { result, rerender } = renderHook(({ doc }: { doc: string }) => useDocLinkFindings(doc), {
- initialProps: { doc: 'a' },
- });
- await waitFor(() => expect(result.current).toHaveLength(1));
+ const renders: Array<{ doc: string; state: ReturnType<typeof useDocLinkFindings> }> = [];
+ const { result, rerender } = renderHook(
+ ({ doc }: { doc: string }) => {
+ const state = useDocLinkFindings(doc);
+ renders.push({ doc, state });
+ return state;
+ },
+ { initialProps: { doc: 'a' } },
+ );
+ await waitFor(() => expect(result.current.findings).toHaveLength(1));
// Park the next fetch unresolved: doc B's findings must read EMPTY during
// the in-flight window, never doc A's stale list (which would render A's
@@ -135,7 +151,11 @@ describe('useDocLinkFindings', () => {
let resolveNext: (r: Response) => void = () => {};
globalThis.fetch = (() => new Promise<Response>((r) => (resolveNext = r))) as typeof fetch;
rerender({ doc: 'b' });
- expect(result.current).toEqual([]);
+ expect(renders.find((render) => render.doc === 'b')?.state).toEqual({
+ status: 'loading',
+ findings: [],
+ });
+ expect(result.current).toEqual({ status: 'loading', findings: [] });
resolveNext(
new Response(
@@ -143,6 +163,66 @@ describe('useDocLinkFindings', () => {
{ status: 200, headers: { 'content-type': 'application/json' } },
),
);
- await waitFor(() => expect(result.current).toEqual([]));
+ await waitFor(() => expect(result.current).toEqual({ status: 'loaded', findings: [] }));
+ });
+
+ test('an invalidation during a walk queues one post-settle refresh', async () => {
+ let resolveFirst: (response: Response) => void = () => {};
+ let resolveSecond: (response: Response) => void = () => {};
+ let call = 0;
+ globalThis.fetch = ((url: RequestInfo | URL) => {
+ fetchUrls.push(String(url));
+ call += 1;
+ if (call === 1) return new Promise<Response>((resolve) => (resolveFirst = resolve));
+ return new Promise<Response>((resolve) => (resolveSecond = resolve));
+ }) as typeof fetch;
+
+ const { result } = renderHook(() => useDocLinkFindings('notes'));
+ act(() => {
+ emitDocumentsChanged(['local-targets']);
+ emitDocumentsChanged(['backlinks']);
+ });
+ expect(fetchUrls).toHaveLength(1);
+
+ resolveFirst(
+ new Response(
+ JSON.stringify({
+ files: [{ file: 'notes.md', diagnostics: [deadLink] }],
+ fileCount: 1,
+ errorCount: 1,
+ warningCount: 0,
+ warnings: [],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ );
+ await waitFor(() => expect(fetchUrls).toHaveLength(2));
+ expect(result.current).toEqual({ status: 'loading', findings: [] });
+
+ resolveSecond(
+ new Response(
+ JSON.stringify({ files: [], fileCount: 1, errorCount: 0, warningCount: 0, warnings: [] }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ );
+ await waitFor(() => expect(result.current.status).toBe('loaded'));
+ expect(result.current.findings).toEqual([]);
+ });
+
+ test('a failed refresh preserves findings and reports failure', async () => {
+ fetchBody = {
+ files: [{ file: 'notes.md', diagnostics: [deadLink] }],
+ fileCount: 1,
+ errorCount: 1,
+ warningCount: 0,
+ warnings: [],
+ };
+ const { result } = renderHook(() => useDocLinkFindings('notes'));
+ await waitFor(() => expect(result.current.findings).toHaveLength(1));
+
+ globalThis.fetch = (async () => new Response('{}', { status: 500 })) as typeof fetch;
+ act(() => emitDocumentsChanged(['local-targets']));
+ await waitFor(() => expect(result.current.status).toBe('failed'));
+ expect(result.current.findings).toHaveLength(1);
});
});
diff --git a/packages/app/src/editor/validation-audit-client.ts b/packages/app/src/editor/validation-audit-client.ts
index 0d1690011..3b5c99d46 100644
--- a/packages/app/src/editor/validation-audit-client.ts
+++ b/packages/app/src/editor/validation-audit-client.ts
@@ -15,7 +15,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { useEffect, useState } from 'react';
import type { z } from 'zod';
-import { subscribeToDocumentsChanged } from '@/lib/documents-events';
+import { invalidatesLocalTargetAudit, subscribeToDocumentsChanged } from '@/lib/documents-events';
/** Wire-loose diagnostic (schema `source` is any string, by design). */
type WireDiagnostic = ValidationDocResult['diagnostics'][number];
@@ -41,8 +41,9 @@ export const AUDIT_SUPERSEDED = 'audit-superseded' as const;
*/
export async function runValidationAudit(
scope: AuditScope = { kind: 'project' },
+ signal?: AbortSignal,
): Promise<ValidationAuditResponse | null | typeof AUDIT_SUPERSEDED> {
- return fetchAudit(scope, ValidationAuditResponseSchema, false);
+ return fetchAudit(scope, ValidationAuditResponseSchema, false, signal);
}
/**
@@ -130,37 +131,98 @@ async function fetchAudit<T>(
* both this doc's own edits and cross-doc ripples (a deleted target turning
* this doc's link dead).
*/
-export function useDocLinkFindings(docName: string | null): WireDiagnostic[] {
- const [findings, setFindings] = useState<WireDiagnostic[]>([]);
+export type DocLinkFindingsState =
+ | { status: 'idle'; findings: readonly WireDiagnostic[] }
+ | { status: 'loading'; findings: readonly WireDiagnostic[] }
+ | { status: 'loaded'; findings: readonly WireDiagnostic[] }
+ | { status: 'failed'; findings: readonly WireDiagnostic[] };
+
+/**
+ * One serialized scoped-audit subscription. Invalidations received during a
+ * walk mark it dirty instead of starting a competing request; once that walk
+ * settles, exactly one fresh request runs against the new local-target world.
+ * This is stronger than abort-only cancellation because the server may
+ * coalesce an invalidating request onto the same already-running audit.
+ */
+export function subscribeToDocLinkFindings(
+ docName: string,
+ onState: (state: DocLinkFindingsState) => void,
+): () => void {
+ let disposed = false;
+ let inFlight = false;
+ let dirty = false;
+ let findings: readonly WireDiagnostic[] = [];
+ let controller: AbortController | null = null;
+
+ const load = (): void => {
+ if (inFlight) {
+ dirty = true;
+ return;
+ }
+ inFlight = true;
+ controller = new AbortController();
+ onState({ status: 'loading', findings });
+ void runValidationAudit({ kind: 'doc', docName }, controller.signal)
+ .then((result) => {
+ if (disposed || controller?.signal.aborted === true) return;
+ if (result === null) {
+ onState({ status: 'failed', findings });
+ return;
+ }
+ if (result === AUDIT_SUPERSEDED) {
+ dirty = true;
+ return;
+ }
+ // An invalidation proves this completion describes an older world.
+ // Keep the current visible state until the queued replacement settles.
+ if (dirty) return;
+ findings = result.files
+ .flatMap((file) => file.diagnostics)
+ .filter((diagnostic) => diagnostic.source === 'links');
+ onState({ status: 'loaded', findings });
+ })
+ .finally(() => {
+ if (disposed) return;
+ inFlight = false;
+ controller = null;
+ if (dirty) {
+ dirty = false;
+ load();
+ }
+ });
+ };
+
+ load();
+ const unsubscribe = subscribeToDocumentsChanged((channels) => {
+ if (channels.includes('backlinks') || invalidatesLocalTargetAudit(channels)) load();
+ });
+ return () => {
+ disposed = true;
+ controller?.abort();
+ unsubscribe();
+ };
+}
+
+export function useDocLinkFindings(docName: string | null): DocLinkFindingsState {
+ const [owned, setOwned] = useState<{
+ docName: string | null;
+ state: DocLinkFindingsState;
+ }>({ docName: null, state: { status: 'idle', findings: [] } });
useEffect(() => {
- // Reset on every doc change, not just null: the previous doc's findings
- // must never survive into the new doc's render window — a stale carryover
- // would show doc A's dead links under doc B (panel rows AND store counts)
- // until the scoped fetch resolves.
- setFindings((prev) => (prev.length === 0 ? prev : []));
if (docName === null) {
+ setOwned({ docName: null, state: { status: 'idle', findings: [] } });
return;
}
- let cancelled = false;
- const load = () => {
- void runValidationAudit({ kind: 'doc', docName }).then((result) => {
- if (cancelled || result === null || result === AUDIT_SUPERSEDED) return;
- const linkFindings = result.files
- .flatMap((f) => f.diagnostics)
- .filter((d) => d.source === 'links');
- setFindings((prev) =>
- prev.length === 0 && linkFindings.length === 0 ? prev : linkFindings,
- );
- });
- };
- load();
- const unsub = subscribeToDocumentsChanged((channels) => {
- if (channels.includes('backlinks')) load();
- });
- return () => {
- cancelled = true;
- unsub();
- };
+ // A new document starts unsettled with no carryover from the prior doc.
+ setOwned({ docName, state: { status: 'loading', findings: [] } });
+ return subscribeToDocLinkFindings(docName, (state) => setOwned({ docName, state }));
}, [docName]);
- return findings;
+ // Effects run after render. Owner-gating prevents the previous document's
+ // findings and counts from painting during the first render of a new one.
+ if (owned.docName !== docName) {
+ return docName === null
+ ? { status: 'idle', findings: [] }
+ : { status: 'loading', findings: [] };
+ }
+ return owned.state;
}
diff --git a/packages/app/src/editor/walk-currency-extension.test.ts b/packages/app/src/editor/walk-currency-extension.test.ts
index 8f4f18af3..a46cda016 100644
--- a/packages/app/src/editor/walk-currency-extension.test.ts
+++ b/packages/app/src/editor/walk-currency-extension.test.ts
@@ -335,6 +335,42 @@ describe('non-stale fast path', () => {
// ---------------------------------------------------------------------------
describe('wiring arms', () => {
+ test('docName-aware render extensions receive the provider document name synchronously', () => {
+ const docName = `nested/image-matrix-${randomUUID()}`;
+ const { provider, cleanup } = makeProvider(docName);
+ try {
+ const extensions = buildExtensionList({
+ provider,
+ clipboard: fakeClipboard,
+ ctorStart: 0,
+ });
+ const configured = new Map(
+ extensions
+ .filter((extension) =>
+ ['link', 'wikiLink', 'jsxComponent', 'jsxInline', 'imageReference'].includes(
+ extension.name,
+ ),
+ )
+ .map((extension) => [
+ extension.name,
+ (extension.options as { docName?: unknown }).docName,
+ ]),
+ );
+
+ expect(configured).toEqual(
+ new Map([
+ ['link', docName],
+ ['wikiLink', docName],
+ ['jsxComponent', docName],
+ ['jsxInline', docName],
+ ['imageReference', docName],
+ ]),
+ );
+ } finally {
+ cleanup();
+ }
+ });
+
test('no prebuiltMapping → walk-currency extension absent from the extension list', () => {
const { provider, cleanup } = makeProvider(`wiring-negative-${randomUUID()}`);
try {
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 89848b9a0..e823ffb53 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -5547,6 +5547,43 @@ html.electron-mode [data-slot="sidebar-inner"] {
.ProseMirror .ok-lint-block-atom.ok-lint-block-error {
outline-color: var(--lint-error-color);
}
+
+/* Image failures use the same warning/error language as link audit and source
+ diagnostics. A present target that the browser cannot decode is a warning;
+ a target proven absent by the project inventory is an error. The labeled
+ placeholder and ImageOff icon remain the non-color channels, while the
+ authored target gets the familiar audit squiggle. */
+.ok-image-error-placeholder {
+ --ok-image-error-accent: color-mix(in oklch, var(--lint-warning-color) 82%, var(--foreground));
+
+ border-color: var(--ok-image-error-accent);
+ background: color-mix(in oklch, var(--lint-warning-color) 9%, transparent);
+}
+[data-image-error-kind="not-found"] > .ok-image-error-placeholder {
+ --ok-image-error-accent: color-mix(in oklch, var(--lint-error-color) 82%, var(--foreground));
+
+ border-color: var(--ok-image-error-accent);
+ background: color-mix(in oklch, var(--lint-error-color) 8%, transparent);
+}
+.ok-image-error-placeholder > svg {
+ color: var(--ok-image-error-accent);
+}
+.ok-image-error-target {
+ text-decoration: underline wavy var(--ok-image-error-accent);
+ text-underline-offset: 0.2em;
+}
+
+/* Percentage max-width is indefinite for shrink-to-fit inline content inside
+ an auto-layout table cell. Give the error slot a definite cell-relative
+ width there, then let the target grid item shrink and truncate within it. */
+.ProseMirror td [data-image-error="true"],
+.ProseMirror td .ok-image-error-placeholder {
+ width: 100%;
+ min-width: 0;
+}
+.ProseMirror td [data-image-error="true"] {
+ display: block;
+}
/* Hover tooltip for a decorated lint block (markdown-lint-decorations.ts). A
styled, instant alternative to the native `title` — OK popover tokens,
one diagnostic per line, never intercepts pointer events. */
diff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.ts
index 6cca5ece8..3c121c370 100644
--- a/packages/app/src/lib/documents-events.ts
+++ b/packages/app/src/lib/documents-events.ts
@@ -42,6 +42,15 @@ export function subscribeToDocumentsChanged(
return () => window.removeEventListener(DOCUMENTS_CHANGED_EVENT, listener);
}
+/**
+ * Local-target existence follows the workspace file inventory. The dedicated
+ * channel is the precise signal, while `files` is its correctness backstop when
+ * a watcher batch changes inventory but produces no assessment-generation edge.
+ */
+export function invalidatesLocalTargetAudit(channels: readonly DerivedViewChannel[]): boolean {
+ return channels.includes('local-targets') || channels.includes('files');
+}
+
// Doc-persisted relays the CC1 `disk-ack` frame's docName — the one per-doc
// push channel — for consumers that react to "this document's bytes just
// reached disk" (the validation-freshness per-doc re-audit). Kept separate
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 4a8c1be30..cc3f2b5e4 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -179,11 +179,13 @@
"1njn7W": ["فاتح"],
"1nke1r": ["فتح ", ["0"], " على GitHub (يفتح في تبويب جديد)"],
"1oSHI0": ["تعذّر تثبيت ", ["skillName"], ": ", ["0"]],
+ "1pdLQw": ["الصورة غير موجودة"],
"1qpGKz": ["تعذّر حفظ التغييرات. حاول تعديل لون مرة أخرى."],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["رفض"],
"1u-mAI": ["تعذّر بدء المزامنة. تحقق من اتصالك، ثم أعد المحاولة."],
"1vn0CI": ["استجابة الخادم غير صالحة"],
+ "1xui0Q": ["فشل تحميل الملفات المحلية"],
"2277Tu": ["طيّ الرسم البياني"],
"237hSL": ["انتهت"],
"253MN6": ["تعذّر إرسال تعليقاتك — يرجى المحاولة مرة أخرى."],
@@ -497,6 +499,7 @@
"6HCOwA": ["فشل الفتح."],
"6KCH4m": ["الملفات المخفية"],
"6KXnz5": ["يمكنك استعادة هذا الملف من المهملات."],
+ "6LJJ1v": ["الملف ", ["identity"], ". انتقل إلى المرجع."],
"6LbUG7": ["المستودع خاص وحساب GitHub الخاص بك لا يملك صلاحية الوصول إليه."],
"6Mbe-P": [
"صِف ما ينبغي أن تفعله، أو أضف واحدة بنفسك. يحفظ OpenKnowledge مهاراتك في مكان واحد، ويؤرشف إصداراتها، ويثبّتها في وكلاء مثل Claude وCodex وCursor."
@@ -1130,7 +1133,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " رمز مستخدَم"],
"EQXPXf": ["التمرير إلى النهاية"],
"ETyvvg": ["لا توجد لغة مطابقة."],
- "EUiJEM": ["تكرارات ", ["0"]],
"EWCJFu": ["تم إنشاء ", ["target"]],
"EWPtMO": ["كود"],
"EWX92Z": ["طيّ «اسأل الذكاء الاصطناعي»"],
@@ -1458,6 +1460,7 @@
"IgN3LY": ["على النص المحدد في <0>", ["address"], "</0>"],
"IgTwLt": ["افتح هذا المستند في المحرر واطوِ الرسم البياني."],
"Ik-gP0": ["العنوان H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["التحقق من الروابط غير متاح. جارٍ عرض آخر المشكلات المعروفة."],
"Iq8zdU": ["إغلاق الطرفية"],
"IrB5AK": [
"فشل التنظيف من جانب الخادم لـ ",
@@ -1667,6 +1670,7 @@
"Lm3r51": ["تعذّر على Slidev عرض هذا المستند."],
"LnVIW4": ["فشل بدء تسجيل الدخول — أعد المحاولة"],
"LpB85N": ["عادي"],
+ "Lrsl_h": ["الملف ", ["identity"], " مفقود. انتقل إلى المرجع."],
"LtI9AS": ["المالك"],
"LtSYdi": ["الكشف في Finder"],
"LtiJ5c": ["مهارة المشروع"],
@@ -1789,7 +1793,6 @@
"عند تمرير المؤشر فوق رابط خارجي، يُرسل رابطه إلى الموقع الوجهة لجلب بيانات معاينة الصفحة — طلب واحد لكل رابط معاين."
],
"MysZUL": ["يجري الاتصال بـ ", ["agentName"], "…"],
- "N-IonL": ["كيف يُبلَّغ عن روابط الويكي غير المحلولة في لوحة المشكلات والمراجعات وأدوات الوكلاء."],
"N1KkEO": ["الانتقال إلى آخر تبويب"],
"N1YYa7": ["يجري تحميل الصورة"],
"N1mdmS": ["لا يمكن فتح هذا الملف في محرر النصوص."],
@@ -2251,6 +2254,7 @@
"U2Kx6T": ["إغلاق كل غير المثبّت"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["الدليل الكامل"],
+ "U3RIJu": ["الملفات المحلية"],
"U4nTfu": ["تفعيل المتابعة"],
"U5Spo9": ["يجب أن يكون مجلد المحتوى داخل المشروع"],
"U6wmNc": ["المزامنة موقوفة مؤقتًا"],
@@ -2375,12 +2379,14 @@
"VNNRfN": ["جعله المصدر"],
"VNgKZz": ["إعدادات متقدمة"],
"VTulZj": ["الفتح في شجرة عمل"],
+ "VU3Nrn": ["مفقود"],
"VUijjF": ["ضمّن صورة مع نص بديل اختياري."],
"VVRrPk": [["0"], " لا يوفر أي إعدادات للضبط"],
"VXGFMg": ["تراجع أو إعادة في حقل الكود"],
"VYd_YA": ["افتح مجلد مشروع موجودًا من القرص."],
"VZGh8G": ["اطوِ نطاقات المصدر أو ابسطها، أو اطوِ الكل أو ابسط الكل."],
"VZSBXL": ["يُفعَّل الترتيب الدلالي أول مرة يشغّل فيها وكيل بحثًا."],
+ "VZg6Gn": ["تعذّر إظهار الصورة: ", ["errorLabel"]],
"V_6bJ4": ["لم تُحمَّل إعدادات الطرفية بعد — أعد المحاولة بعد قليل."],
"V_DjMe": ["خطأ في العرض"],
"V_wltx": ["أدخل عنوانًا لهذا القالب."],
@@ -2433,12 +2439,14 @@
"W1qRuM": ["هذا المستند نشط بالفعل في المحرر. استخدم «فتح» لطي الرسم البياني."],
"W3Tsgy": ["مكتشف في ", ["0"]],
"W5A0Ly": ["حدث خطأ غير متوقع."],
+ "W5qdI_": ["تعذّر تحويل هدف الصورة \"", ["shown"], "\" إلى ملف محلي في المشروع."],
"W7XJN4": [
"لا يمكن تداخل المشاريع. يوجد بالفعل مشروع OpenKnowledge في <0>",
["rootPath"],
"</0>. اختر موقعًا خارجه، أو افتح ذلك المشروع بدلًا من ذلك."
],
"W8vpBM": ["حزمة بداية"],
+ "W9NSe0": ["جارٍ التحقق من الروابط"],
"W9_Bub": ["تتداخل التغييرات المحلية مع المزامنة الواردة"],
"WBNpt9": ["تعذّرت قراءة هذه السمة (", ["0"], ")"],
"WFEbV1": ["أشِر إلى مشكلات Markdown الشائعة في المحرر. مدعوم بـ <0>markdownlint<1/></0>."],
@@ -2499,11 +2507,13 @@
"X8kjQX": ["أعد المصادقة مع GitHub"],
"X9VpsP": ["يجري تحميل محتويات المجلد"],
"XAyxsa": ["سحب فرع بعيد"],
+ "XBBZnv": ["هدف الرابط \"", ["shown"], "\" لا يشير إلى مستند موجود."],
"XBgr2S": ["النسخ إلى هنا"],
"XDzAnp": ["يفتح في تبويب جديد"],
"XFpEgc": [
"اختر الوكلاء الذين يظهرون في قوائم الوكلاء في التطبيق، مثل Ask AI وOpen with AI وزر + لمحادثة جديدة. أوقف وكيلاً لإخفائه منها جميعاً."
],
+ "XGKy1z": ["تعذّر إظهار الصورة"],
"XH30C4": ["مستند"],
"XIltnd": ["توجد بالفعل مهارة باسم «", ["trimmed"], "» هنا"],
"XJOV1Y": ["النشاط"],
@@ -2521,6 +2531,7 @@
"XW18jo": ["لم تطابق استجابة عناوين الصفحة مخطط النجاح"],
"XWEqQj": [["days"], "ي"],
"XXA1b_": [["componentLabel"], " (فارغ)"],
+ "XYZ7tp": ["غير قابل للحل"],
"XYlJJT": ["يجري الإعداد"],
"XZkdtg": ["تبديل الفرع"],
"XcGbim": ["إظهار الملفات المخفية"],
@@ -2630,6 +2641,7 @@
"YW7Q86": ["لم تُحمَّل إعدادات البحث بعد — أعد المحاولة بعد قليل"],
"Y_GpJd": ["انتهت مهلة طلب تنزيل ", ["0"], "."],
"Y_ZQ6l": ["يجري تثبيت ", ["agentName"], "…"],
+ "Y_iImT": ["تعذّر حل الملف ", ["identity"], ". انتقل إلى المرجع."],
"Y_kL7X": ["خصّص مظهر المحرر وسلوكه."],
"Ya3PlJ": ["الإذن مطلوب"],
"YaeyFh": ["قد تستبدل عمليات السحب تعديلات غير مودعة في ملفاتك المحلية."],
@@ -2768,6 +2780,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["مواضع ظهور ", ["localizedFirstMessage"]],
"_DwR-n": ["جارٍ الإنشاء…"],
"_FLBbi": [["sizeText"], " · تم إخفاء الأسرار · لم يُخفَ تفريغ الأعطال"],
"_GRWOJ": ["هل تريد تغيير مزوّد التضمينات؟"],
@@ -2926,6 +2939,7 @@
"blFttG": ["البحث في المشاريع"],
"bmC18N": ["يجري مسح بيانات التعاون المحلية لـ «", ["docName"], "» قبل إعادة الاتصال."],
"bnOTEz": ["يجري الاسترجاع…"],
+ "bpMVIA": ["تعذّر تحويل هدف الرابط \"", ["shown"], "\" إلى هدف محلي في المشروع."],
"bpytj4": ["النقل إلى ", ["0"]],
"brCtGB": ["السجل غير متاح"],
"buNXgr": ["بدّل بين المحرر المرئي ومحرر المصدر مع الاحتفاظ بموضعك."],
@@ -3207,6 +3221,7 @@
"fJgQHX": ["فشل إنشاء الملف"],
"fMsFdZ": ["تعذّر حفظ إعداد التحديث التلقائي: ", ["0"]],
"fNr-MX": ["تعطيل البحث الدلالي"],
+ "fOzzSV": ["هدف الرابط \"", ["shown"], "\" لا يشير إلى ملف موجود."],
"fR-Kdc": ["(على مستوى المشروع فقط)"],
"fRVBiq": [
"يضيف بيانات القياس وحالة الخادم ومعلومات وقت التشغيل عند توفرها. تُزال بيانات الاعتماد دائمًا؛ وتظهر أسماء المستندات، إن أُدرجت، كنص صريح (غير مخفي)."
@@ -3255,6 +3270,7 @@
"fwrPh4": ["يرجى إدخال بريد إلكتروني صالح."],
"fxJk_6": ["<0>هل لديك المزيد لتضيفه؟</0> راسلنا على <1/> واذكر رقم مرجعك."],
"fxbCNQ": ["تمت المزامنة. الرابط محدَّث."],
+ "g-dkjJ": ["تفاصيل الملفات المحلية غير متاحة بعد."],
"g12y1g": ["YAML غير صالح"],
"g1ZTh_": [
[
@@ -3345,6 +3361,7 @@
"gmJ0An": ["فشل فتح المجلد."],
"goO4Ll": ["شريط حالة المحرر"],
"gp3I7-": ["قبل المزامنة، اضبط هويتك لإيداعات git:"],
+ "gpbKxw": ["التحقق من الروابط غير متاح."],
"gqk-3R": ["تم نقل ", ["0"], " إلى ", ["destination"], "."],
"gtEbeW": ["تظليل"],
"gtGQ9S": ["تشغيل ", ["agentName"], "، ", ["hint"]],
@@ -3453,6 +3470,7 @@
"iRdfLr": ["نسخة التطوير: ", ["label"]],
"iSLIjg": ["اتصال"],
"iSQTsg": ["قائمة مرتّبة"],
+ "iSWh95": ["هدف الصورة \"", ["shown"], "\" لا يشير إلى ملف موجود."],
"iSnkwB": ["فشل فتح المشروع المستنسخ."],
"iTylMl": ["القوالب"],
"iUwpZI": ["بلا مسافات — استخدم <0>-</0> بدلًا منها."],
@@ -3502,6 +3520,9 @@
"الـ <0>type</0> الذي يحصل عليه كل مستند يُنشأ من هذا القالب (مثل <1>research-note</1>). يبقي المستندات الجديدة متوافقة مع Open Knowledge Format."
],
"iqIDv4": ["حالة المزامنة غير متاحة"],
+ "iqr14Z": [
+ "كيفية الإبلاغ عن مستندات المشروع المحلية والملفات والصور المفقودة في المشكلات وتشخيصات المحرر وعمليات التدقيق وأدوات الوكيل."
+ ],
"iqugog": ["فشلت التهيئة: ", ["errorDetail"]],
"irFGwu": ["قائمة القوالب"],
"irrm_E": ["إزالة التحديد"],
@@ -3597,6 +3618,7 @@
"kCqCyf": ["افتح لوحة تشخيصات الفحص في CodeMirror."],
"kFLlsI": ["أدرج مرجع حاشية مع بذرة تعريف مطابقة."],
"kGp168": ["تعذّر تجهيز هذا المشروع للنشر."],
+ "kI5pWt": ["الصورة غير موجودة: ", ["errorLabel"]],
"kKw0H3": [
"حرّرت هذه المهارة محليًا وللمصدر تغييرات جديدة. أخذ نسخة المستودع البعيد يستبدل نسختك؛ وتبقى تعديلاتك قابلة للاستعادة في سجل النسخ."
],
@@ -3869,7 +3891,6 @@
"nCzR-G": ["نسخ الرمز ", ["userCode"]],
"nDT8qt": ["تمت تهيئة ", ["0"], " لكن تعذّر فتحه."],
"nG-XA9": ["اختفى النص المرتبط. يمكنك إعادة وضعه على نص محدد."],
- "nL-HHD": ["تعذّر تحميل الصورة"],
"nMSYz5": [
"هذا المسار على وحدة تخزين خارجية (/Volumes/...). سيفقد OpenKnowledge تتبّع الملفات عند إخراج القرص."
],
@@ -4005,6 +4026,7 @@
"pFRz_E": ["استبعد هذه التعليقات من هذه الرسالة"],
"pFagOn": ["تحرير المصدر"],
"pHYP6v": ["افتح <0>تخصيص</0> في الشريط الجانبي <1/> <2>المهارات</2>."],
+ "pJ7XCo": ["لا تشير هذه الصفحة إلى أي ملفات أو صور محلية."],
"pOo4Aa": ["نص عادي"],
"pSimwP": ["اسم جديد لنسخة ", ["editor"]],
"pTPqMK": ["بدّل كتلة الكود المحصورة."],
@@ -4164,7 +4186,6 @@
"qjHMHf": ["فشل تعطيل المزامنة — ", ["detail"]],
"qkqG0b": ["أخذ نسخة المستودع البعيد"],
"qlAIQ1": ["بعيد"],
- "qlnfTD": ["تعذّر تحميل الصورة: ", ["errorLabel"]],
"qmL1UG": ["يجري الرفع بأمان"],
"qo4zCg": ["لا يمكن أن يحتوي المسار على شرطات مائلة عكسية"],
"qpQwGC": ["صِف ما تعمل عليه ويتولى الوكيل إعداده لك."],
@@ -4197,6 +4218,7 @@
"rXz97P": ["قائمة عناصر مرقّمة."],
"rZ9HZq": ["للقيام به"],
"rZVMkf": ["حقل استبدال المحرر المرئي مركَّز عليه"],
+ "radOpL": ["الصورة ", ["identity"], ". انتقل إلى المرجع."],
"rageVb": ["HTML مخصص مع لوحة معاينة حية (إطار معزول)."],
"rbrHTd": ["موافق عليه — ", ["optionName"]],
"rcJmK8": ["تحويل المواقع إلى نسخ"],
@@ -4375,6 +4397,7 @@
["trashNoun"],
". هل تريد الحذف نهائيًا بدلاً من ذلك؟"
],
+ "txUHO8": [["localizedMessage"], " في السطر ", ["displayLine"]],
"tzGWeg": ["يجري التحضير لإلغاء تثبيت OpenKnowledge"],
"tzZ6ha": ["الاتصال بخادم GitHub Enterprise"],
"u-9fWA": ["راجع <0>Architecture</0> للاطلاع على نظرة عامة على النظام."],
@@ -4402,7 +4425,6 @@
"uA_jXp": ["تبديل الفرع وتحديثه"],
"uBAxNB": ["المحرر"],
"uCaIdy": ["تسجيل الدخول إلى GitHub مفقود أو منتهي الصلاحية. أعد الاتصال لاستئناف المزامنة."],
- "uCe4AX": [["0"], " في السطر ", ["displayLine"]],
"uDlyqd": [
"وثّق بنية هذا المستودع: أنشئ صفحة نظرة عامة ترتبط بصفحة لكل وحدة رئيسية تصف مسؤولياتها ونقاط دخولها."
],
@@ -4524,6 +4546,7 @@
"vPEyDz": ["نص جلسة الوكيل"],
"vPF04k": ["بدء محادثة جديدة"],
"vPKX2i": ["داخل التطبيق (بيتا)"],
+ "vPLUCm": ["الصورة ", ["identity"], " مفقودة. انتقل إلى المرجع."],
"vPXOUw": ["تبديل عرض المصدر"],
"vQIVHc": ["خصائص المجلد"],
"vWc9a0": ["اكتب للتحرير؛ <0>⌘ Enter</0> يحفظ، و<1>Esc</1> يلغي."],
@@ -4695,6 +4718,7 @@
"xxRpzT": ["تم العثور على Slidev على نظامك."],
"xzAmL_": ["موافق عليه تلقائيًا"],
"xzktOa": ["تحرير رابط الويكي"],
+ "y-LQPF": ["تعذّر حل الصورة ", ["identity"], ". انتقل إلى المرجع."],
"y1eoq1": ["نسخ الرابط"],
"y1t8bQ": ["أقسام الإعدادات"],
"y3aU20": ["حفظ التغييرات"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index bdbec900b..663511c47 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} يتصرف دون سؤال — لا يمكن لـ OpenKnowledge إض
msgid "{0} added, {1} removed"
msgstr "تمت إضافة {0}، وإزالة {1}"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} في السطر {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, zero {# رابط} one {رابط واحد} two {را
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} في السطر {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, zero {قبل # دقيقة} one {قبل # دقيقة} two {قبل # دقيقة} few {قبل # دقائق} many {قبل # دقيقة} other {قبل # دقيقة}}"
@@ -2208,6 +2207,10 @@ msgstr "يجري التحقق من التحديثات على GitHub"
msgid "Checking GitHub connection..."
msgstr "يجري التحقق من الاتصال بـ GitHub..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "جارٍ التحقق من الروابط"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "يجري سحب الملفات"
@@ -5057,6 +5060,10 @@ msgstr "فشل تحميل العناوين"
msgid "Failed to load hub pages"
msgstr "فشل تحميل الصفحات المحورية"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "فشل تحميل الملفات المحلية"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "فشل تحميل الصفحات اليتيمة"
@@ -5284,6 +5291,10 @@ msgstr "الحقول"
msgid "File"
msgstr "ملف"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "الملف {identity}. انتقل إلى المرجع."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "الملف موجود بالفعل"
@@ -6034,6 +6045,10 @@ msgstr "ما رأيك في OpenKnowledge؟"
msgid "How does sharing work?"
msgstr "كيف تعمل المشاركة؟"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "كيفية الإبلاغ عن مستندات المشروع المحلية والملفات والصور المفقودة في المشكلات وتشخيصات المحرر وعمليات التدقيق وأدوات الوكيل."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "كيفية الدفع يدويًا"
@@ -6051,10 +6066,6 @@ msgstr "كيفية الإعداد"
msgid "How to set up {0} (opens in browser)"
msgstr "كيفية إعداد {0} (يفتح في المتصفح)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "كيف يُبلَّغ عن روابط الويكي غير المحلولة في لوحة المشكلات والمراجعات وأدوات الوكلاء."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "كيف تظهر نتائج التحقق عبر المشروع. تُودَع هذه الخيارات في config.yml وتُشارك مع كل متعاون عبر git."
@@ -6110,13 +6121,33 @@ msgstr "أنماط التجاهل"
msgid "Ignore patterns (raw text)"
msgstr "أنماط التجاهل (نص خام)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "الصورة {identity}. انتقل إلى المرجع."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "تعذّر إظهار الصورة"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "تعذّر تحميل الصورة"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "تعذّر إظهار الصورة: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "تعذّر تحميل الصورة: {errorLabel}"
+msgid "Image not found"
+msgstr "الصورة غير موجودة"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "الصورة غير موجودة: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "تعذّر تحويل هدف الصورة \"{shown}\" إلى ملف محلي في المشروع."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "هدف الصورة \"{shown}\" لا يشير إلى ملف موجود."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "الرابط جاهز، لكن تعذّر نسخه إلى الحافظة
msgid "Link target"
msgstr "وجهة الرابط"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "تعذّر تحويل هدف الرابط \"{shown}\" إلى هدف محلي في المشروع."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "هدف الرابط \"{shown}\" لا يشير إلى مستند موجود."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "هدف الرابط \"{shown}\" لا يشير إلى ملف موجود."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "اربط النص المحدد، أو حرّر الرابط الواقع تحت المؤشر."
@@ -6729,6 +6772,14 @@ msgstr "اربط بصفحة أو رابط خارجي."
msgid "Link URL"
msgstr "رابط الوجهة"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "التحقق من الروابط غير متاح."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "التحقق من الروابط غير متاح. جارٍ عرض آخر المشكلات المعروفة."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "لم تطابق استجابة رسم الروابط الشكل المتوقع."
@@ -6925,6 +6976,14 @@ msgstr "تعذّر مسح بيانات التعاون المحلية لـ «{doc
msgid "Local commits are keeping this copy from updating"
msgstr "تمنع الإيداعات المحلية هذه النسخة من التحديث"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "تفاصيل الملفات المحلية غير متاحة بعد."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "الملفات المحلية"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "مسار محلي"
@@ -7101,10 +7160,22 @@ msgstr "مصدر المرآة <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "مصدر المرآة <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "مفقود"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "ينقصه ميزة"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "الملف {identity} مفقود. انتقل إلى المرجع."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "الصورة {identity} مفقودة. انتقل إلى المرجع."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "صفحة مفقودة — انقر لإنشائها"
@@ -8021,10 +8092,9 @@ msgstr "قائمة عناصر مرقّمة."
msgid "Object"
msgstr "كائن"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "تكرارات {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "مواضع ظهور {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "هذه الصفحة غير موجودة بعد. افتحها لإنشا
msgid "This page doesn't link to anything yet."
msgstr "هذه الصفحة لا ترتبط بشيء بعد."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "لا تشير هذه الصفحة إلى أي ملفات أو صور محلية."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "هذا المسار على وحدة تخزين خارجية (/Volumes/...). سيفقد OpenKnowledge تتبّع الملفات عند إخراج القرص."
@@ -12868,6 +12942,18 @@ msgstr "رابط غير معروف"
msgid "Unrecognized wiki link"
msgstr "رابط ويكي غير معروف"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "غير قابل للحل"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "تعذّر حل الملف {identity}. انتقل إلى المرجع."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "تعذّر حل الصورة {identity}. انتقل إلى المرجع."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "محدَّث"
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 5cfed6e6b..aaf8164a9 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -156,11 +156,13 @@
"1njn7W": ["হালকা"],
"1nke1r": [["0"], " GitHub-এ খুলুন (নতুন ট্যাবে খোলে)"],
"1oSHI0": [["skillName"], " ইনস্টল করা যায়নি: ", ["0"]],
+ "1pdLQw": ["ছবি পাওয়া যায়নি"],
"1qpGKz": ["পরিবর্তনগুলি সংরক্ষণ করা যায়নি। একটি রং আবার সম্পাদনা করে দেখুন।"],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["প্রত্যাখ্যান করুন"],
"1u-mAI": ["সিঙ্ক শুরু করা যায়নি। আপনার সংযোগ দেখুন, তারপর আবার চেষ্টা করুন।"],
"1vn0CI": ["সার্ভারের প্রতিক্রিয়া অবৈধ"],
+ "1xui0Q": ["স্থানীয় ফাইল লোড করতে ব্যর্থ"],
"2277Tu": ["গ্রাফ গুটিয়ে নিন"],
"237hSL": ["শেষ হয়েছে"],
"253MN6": ["আপনার মন্তব্য পাঠানো যায়নি — অনুগ্রহ করে আবার চেষ্টা করুন।"],
@@ -434,6 +436,7 @@
"6HCOwA": ["খুলতে ব্যর্থ।"],
"6KCH4m": ["লুকানো ফাইল"],
"6KXnz5": ["আপনি এই ফাইলটি ট্র্যাশ থেকে পুনরুদ্ধার করতে পারেন।"],
+ "6LJJ1v": ["ফাইল ", ["identity"], "। রেফারেন্সে যান।"],
"6LbUG7": ["রিপোজিটরিটি ব্যক্তিগত এবং আপনার GitHub অ্যাকাউন্টের সেখানে প্রবেশাধিকার নেই।"],
"6Mbe-P": [
"এটি কী করবে তার বর্ণনা দিন, নয়তো নিজেই একটি যোগ করুন। OpenKnowledge আপনার স্কিলগুলো এক জায়গায় রাখে, সেগুলোর সংস্করণ রাখে, এবং Claude, Codex ও Cursor-এর মতো এজেন্টে ইনস্টল করে।"
@@ -948,7 +951,6 @@
"EPwuTC": [["sizeLabel"], "-এর মধ্যে ", ["usedLabel"], " টোকেন ব্যবহৃত"],
"EQXPXf": ["শেষে স্ক্রল করুন"],
"ETyvvg": ["কোনো ভাষা মেলে না।"],
- "EUiJEM": [["0"], "-এর উপস্থিতি"],
"EWCJFu": [["target"], " তৈরি হয়েছে"],
"EWPtMO": ["কোড"],
"EWX92Z": ["Ask AI গুটিয়ে নিন"],
@@ -1237,6 +1239,7 @@
"IgN3LY": ["<0>", ["address"], "</0>-এ নির্বাচিত লেখার উপর"],
"IgTwLt": ["এই নথিটি সম্পাদকে খুলুন এবং গ্রাফ গুটিয়ে নিন।"],
"Ik-gP0": ["শিরোনাম H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["লিংক যাচাইকরণ উপলভ্য নয়। সর্বশেষ জানা সমস্যাগুলি দেখানো হচ্ছে।"],
"Iq8zdU": ["টার্মিনাল বন্ধ করুন"],
"IrB5AK": [
["failedCount", "plural", { "one": ["#", " আইটেমের"], "other": ["#", " আইটেমের"] }],
@@ -1420,6 +1423,7 @@
"Lm3r51": ["Slidev এই নথিটি রেন্ডার করতে পারেনি।"],
"LnVIW4": ["সাইন-ইন শুরু করতে ব্যর্থ — আবার চেষ্টা করুন"],
"LpB85N": ["সাদামাটা"],
+ "Lrsl_h": ["অনুপস্থিত ফাইল ", ["identity"], "। রেফারেন্সে যান।"],
"LtI9AS": ["মালিক"],
"LtSYdi": ["Finder-এ দেখান"],
"LtiJ5c": ["প্রকল্প স্কিল"],
@@ -1517,7 +1521,6 @@
"আপনি কোনো বাইরের লিংকের উপর মাউস নিলে পাতার প্রাকদর্শনের মেটাডেটা আনতে তার URL গন্তব্য সাইটে পাঠানো হয় — প্রতি প্রাকদর্শিত লিংকে একটি অনুরোধ।"
],
"MysZUL": [["agentName"], "-এর সঙ্গে যুক্ত হচ্ছে…"],
- "N-IonL": ["Problems প্যানেল, নিরীক্ষা ও এজেন্ট টুলে অমীমাংসিত উইকি লিংক কীভাবে জানানো হয়।"],
"N1KkEO": ["শেষ ট্যাবে যান"],
"N1YYa7": ["ছবি লোড হচ্ছে"],
"N1mdmS": ["এই ফাইলটি টেক্সট সম্পাদকে খোলা যায় না।"],
@@ -1952,6 +1955,7 @@
"U2Kx6T": ["সব আনপিন করা বন্ধ করুন"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["পূর্ণ নির্দেশিকা"],
+ "U3RIJu": ["স্থানীয় ফাইল"],
"U4nTfu": ["Follow চালু করুন"],
"U5Spo9": ["বিষয়বস্তুর ডিরেক্টরি প্রকল্পের ভেতরে হতে হবে"],
"U6wmNc": ["সিঙ্ক থেমে আছে"],
@@ -2067,12 +2071,14 @@
"VNNRfN": ["উৎস বানান"],
"VNgKZz": ["উন্নত সেটিং"],
"VTulZj": ["ওয়ার্কট্রিতে খুলুন"],
+ "VU3Nrn": ["অনুপস্থিত"],
"VUijjF": ["ঐচ্ছিক বিকল্প-লেখাসহ একটি ছবি এমবেড করুন।"],
"VVRrPk": [["0"], " সমন্বয় করার মতো কোনো সেটিং দেয় না"],
"VXGFMg": ["কোড ফিল্ডে পূর্বাবস্থা বা পুনরায়"],
"VYd_YA": ["ডিস্ক থেকে একটি বিদ্যমান প্রকল্প ফোল্ডার খুলুন।"],
"VZGh8G": ["সোর্সের পরিসর ভাঁজ করুন, খুলুন, সব ভাঁজ করুন, বা সব খুলুন।"],
"VZSBXL": ["কোনো এজেন্ট প্রথমবার অনুসন্ধান চালালেই অর্থভিত্তিক ক্রম সক্রিয় হয়।"],
+ "VZg6Gn": ["ছবি দেখানো যায়নি: ", ["errorLabel"]],
"V_6bJ4": ["টার্মিনালের সেটিং এখনও লোড হয়নি — একটু পরে আবার চেষ্টা করুন।"],
"V_DjMe": ["রেন্ডার ত্রুটি"],
"V_wltx": ["এই টেমপ্লেটের জন্য একটি শিরোনাম দিন।"],
@@ -2097,12 +2103,14 @@
"W1qRuM": ["এই নথিটি সম্পাদকে আগে থেকেই সক্রিয়। গ্রাফ গুটিয়ে নিতে Open ব্যবহার করুন।"],
"W3Tsgy": [["0"], "-এ শনাক্ত হয়েছে"],
"W5A0Ly": ["একটি অপ্রত্যাশিত ত্রুটি ঘটেছে।"],
+ "W5qdI_": ["ছবির লক্ষ্য \"", ["shown"], "\"-কে প্রকল্পের স্থানীয় ফাইল হিসেবে নির্ণয় করা যায়নি।"],
"W7XJN4": [
"প্রকল্পের ভেতরে প্রকল্প রাখা যায় না। <0>",
["rootPath"],
"</0>-এ আগে থেকেই একটি OpenKnowledge প্রকল্প আছে। এর বাইরে কোনো জায়গা বাছুন, নয়তো সেই প্রকল্পটিই খুলুন।"
],
"W8vpBM": ["স্টার্টার প্যাক"],
+ "W9NSe0": ["লিংক যাচাই করা হচ্ছে"],
"W9_Bub": ["স্থানীয় পরিবর্তন আগত সিঙ্কের সঙ্গে মিলে যাচ্ছে"],
"WBNpt9": ["এই থিমটি পড়া যায়নি (", ["0"], ")"],
"WFEbV1": ["সম্পাদকে সাধারণ markdown সমস্যা চিহ্নিত করুন। <0>markdownlint<1/></0> দ্বারা চালিত।"],
@@ -2163,11 +2171,13 @@
"X8kjQX": ["GitHub-এর সঙ্গে আবার প্রমাণীকরণ করুন"],
"X9VpsP": ["ফোল্ডারের বিষয়বস্তু লোড হচ্ছে"],
"XAyxsa": ["রিমোট ব্রাঞ্চ চেক আউট করুন"],
+ "XBBZnv": ["লিংকের লক্ষ্য \"", ["shown"], "\" কোনো বিদ্যমান নথিকে নির্দেশ করে না।"],
"XBgr2S": ["এখানে কপি করুন"],
"XDzAnp": ["নতুন ট্যাবে খোলে"],
"XFpEgc": [
"অ্যাপ জুড়ে এজেন্ট মেনুতে কোন এজেন্টগুলি দেখা যাবে তা বেছে নিন, যেমন Ask AI, Open with AI এবং + নতুন চ্যাট বোতাম। কোনো এজেন্ট বন্ধ করলে সেটি এই সবগুলি থেকে লুকিয়ে যাবে।"
],
+ "XGKy1z": ["ছবি দেখানো যায়নি"],
"XH30C4": ["নথি"],
"XIltnd": ["\"", ["trimmed"], "\" নামের একটি স্কিল এখানে আগে থেকেই আছে"],
"XJOV1Y": ["কার্যকলাপ"],
@@ -2185,6 +2195,7 @@
"XW18jo": ["পাতার শিরোনামের সাড়া সাফল্য স্কিমার সঙ্গে মেলেনি"],
"XWEqQj": [["days"], "দি"],
"XXA1b_": [["componentLabel"], " (খালি)"],
+ "XYZ7tp": ["সমাধান অযোগ্য"],
"XYlJJT": ["সেট আপ করা হচ্ছে"],
"XZkdtg": ["ব্রাঞ্চ বদলান"],
"XcGbim": ["লুকানো ফাইল দেখান"],
@@ -2276,6 +2287,7 @@
"YW7Q86": ["অনুসন্ধানের সেটিং এখনও লোড হয়নি — একটু পরে আবার চেষ্টা করুন"],
"Y_GpJd": [["0"], "-এর ডাউনলোড অনুরোধের সময় শেষ হয়ে গেছে।"],
"Y_ZQ6l": [["agentName"], " ইনস্টল করা হচ্ছে…"],
+ "Y_iImT": ["সমাধান করা যায় না এমন ফাইল ", ["identity"], "। রেফারেন্সে যান।"],
"Y_kL7X": ["সম্পাদক কেমন দেখাবে ও কেমন আচরণ করবে তা নিজের মতো সাজান।"],
"Ya3PlJ": ["অনুমতি প্রয়োজন"],
"YaeyFh": ["টানলে আপনার স্থানীয় ফাইলের কমিট না করা সম্পাদনা মুছে যেতে পারে।"],
@@ -2389,6 +2401,7 @@
["currentLabel"],
"</1>-এ আছেন।"
],
+ "_Bix3-": [["localizedFirstMessage"], "-এর উপস্থিতিগুলি"],
"_DwR-n": ["তৈরি হচ্ছে…"],
"_FLBbi": [["sizeText"], " · গোপন তথ্য সরানো হয়েছে · ক্র্যাশ ডাম্প থেকে সরানো হয়নি"],
"_GRWOJ": ["এমবেডিং সরবরাহকারী বদলাবেন?"],
@@ -2534,6 +2547,7 @@
"blFttG": ["প্রকল্প খুঁজুন"],
"bmC18N": ["পুনরায় যুক্ত হওয়ার আগে \"", ["docName"], "\"-এর স্থানীয় সহযোগিতা তথ্য মুছে ফেলা হচ্ছে।"],
"bnOTEz": ["আনা হচ্ছে…"],
+ "bpMVIA": ["লিংকের লক্ষ্য \"", ["shown"], "\"-কে প্রকল্পের স্থানীয় লক্ষ্য হিসেবে নির্ণয় করা যায়নি।"],
"bpytj4": [["0"], "-এ সরান"],
"brCtGB": ["ইতিহাস অনুপলব্ধ"],
"buNXgr": ["নিজের জায়গা ধরে রেখে দৃশ্য ও সোর্স সম্পাদকের মধ্যে বদলান।"],
@@ -2750,6 +2764,7 @@
"fJgQHX": ["ফাইল তৈরি করতে ব্যর্থ"],
"fMsFdZ": ["স্বয়ংক্রিয় হালনাগাদের সেটিং সংরক্ষণ করা যায়নি: ", ["0"]],
"fNr-MX": ["অর্থভিত্তিক অনুসন্ধান নিষ্ক্রিয় করুন"],
+ "fOzzSV": ["লিংকের লক্ষ্য \"", ["shown"], "\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"],
"fR-Kdc": ["(শুধু প্রকল্প স্তরে)"],
"fRVBiq": [
"পাওয়া গেলে টেলিমেট্রি, সার্ভারের অবস্থা ও রানটাইম তথ্য যোগ করে। ক্রেডেনশিয়াল সবসময় সরিয়ে ফেলা হয়; নথির নাম, যদি অন্তর্ভুক্ত থাকে, সাদা লেখায় দেখা যায় (সরানো হয় না)।"
@@ -2787,6 +2802,7 @@
"fwrPh4": ["অনুগ্রহ করে একটি বৈধ ইমেইল দিন।"],
"fxJk_6": ["<0>আরও কিছু যোগ করার আছে?</0> <1/>-এ লিখুন এবং আপনার রেফারেন্স উল্লেখ করুন।"],
"fxbCNQ": ["সিঙ্ক হয়েছে। লিংকটি হালনাগাদ।"],
+ "g-dkjJ": ["স্থানীয় ফাইলের বিবরণ এখনও উপলব্ধ নয়।"],
"g12y1g": ["অবৈধ YAML"],
"g1ZTh_": [
[
@@ -2857,6 +2873,7 @@
"gmJ0An": ["ফোল্ডার খুলতে ব্যর্থ।"],
"goO4Ll": ["সম্পাদকের অবস্থা বার"],
"gp3I7-": ["সিঙ্ক করার আগে git কমিটের জন্য আপনার পরিচয় নির্ধারণ করুন:"],
+ "gpbKxw": ["লিংক যাচাইকরণ উপলভ্য নয়।"],
"gqk-3R": [["0"], "-কে ", ["destination"], "-এ সরানো হয়েছে।"],
"gtEbeW": ["হাইলাইট"],
"gtGQ9S": [["agentName"], " শুরু করুন, ", ["hint"]],
@@ -2974,6 +2991,7 @@
"iRdfLr": ["ডেভ ইনস্ট্যান্স: ", ["label"]],
"iSLIjg": ["যুক্ত করুন"],
"iSQTsg": ["ক্রমিক তালিকা"],
+ "iSWh95": ["ছবির লক্ষ্য \"", ["shown"], "\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"],
"iSnkwB": ["ক্লোন করা প্রকল্প খুলতে ব্যর্থ।"],
"iTylMl": ["টেমপ্লেট"],
"iUwpZI": ["ফাঁকা জায়গা নয় — বদলে <0>-</0> ব্যবহার করুন।"],
@@ -3011,6 +3029,9 @@
"এই টেমপ্লেট থেকে তৈরি প্রতিটি নথি যে <0>type</0> পায় (যেমন <1>research-note</1>)। নতুন নথিগুলোকে Open Knowledge Format-সঙ্গতিপূর্ণ রাখে।"
],
"iqIDv4": ["সিঙ্কের অবস্থা পাওয়া যাচ্ছে না"],
+ "iqr14Z": [
+ "অনুপস্থিত প্রজেক্ট-লোকাল ডকুমেন্ট, ফাইল ও ছবিগুলো সমস্যা, এডিটর ডায়াগনস্টিকস, অডিট এবং এজেন্ট টুলে কীভাবে রিপোর্ট করা হয়।"
+ ],
"iqugog": ["চালু করা ব্যর্থ: ", ["errorDetail"]],
"irFGwu": ["টেমপ্লেট তালিকা"],
"irrm_E": ["নির্বাচন সরান"],
@@ -3110,6 +3131,7 @@
"kCqCyf": ["CodeMirror-এর lint নির্ণয় প্যানেল খুলুন।"],
"kFLlsI": ["একটি পাদটীকা রেফারেন্স + মিলে যাওয়া সংজ্ঞার কাঠামো ঢোকান।"],
"kGp168": ["এই প্রকল্পটি প্রকাশের জন্য প্রস্তুত করা যায়নি।"],
+ "kI5pWt": ["ছবি পাওয়া যায়নি: ", ["errorLabel"]],
"kKw0H3": [
"আপনি এই স্কিলটি স্থানীয়ভাবে সম্পাদনা করেছেন এবং উৎসে নতুন পরিবর্তন আছে। আপস্ট্রিমেরটি নিলে আপনার সংস্করণের জায়গা নেয়; আপনার সম্পাদনা সংস্করণ ইতিহাসে পুনরুদ্ধারযোগ্য থাকে।"
],
@@ -3344,7 +3366,6 @@
"nCzR-G": ["কোড ", ["userCode"], " কপি করুন"],
"nDT8qt": [["0"], " চালু করা হয়েছে কিন্তু সেটি খোলা যায়নি।"],
"nG-XA9": ["অ্যাংকর করা লেখাটি আর নেই। আপনি এটি নির্বাচিত লেখার উপর আবার বসাতে পারেন।"],
- "nL-HHD": ["ছবি লোড করা যায়নি"],
"nMSYz5": [
"এই পথটি একটি বাইরের ভলিউমে (/Volumes/…)। ড্রাইভটি বের করে নিলে OpenKnowledge ফাইলগুলোর হদিস হারিয়ে ফেলবে।"
],
@@ -3475,6 +3496,7 @@
"pFRz_E": ["এই মন্তব্যগুলো এই বার্তার বাইরে রাখুন"],
"pFagOn": ["সোর্স সম্পাদনা"],
"pHYP6v": ["সাইডবারে <0>Customize</0> <1/> <2>Skills</2> খুলুন।"],
+ "pJ7XCo": ["এই পাতাটি কোনো স্থানীয় ফাইল বা ছবি উল্লেখ করে না।"],
"pOo4Aa": ["সাধারণ টেক্সট"],
"pSimwP": [["editor"], " সংস্করণের জন্য নতুন নাম"],
"pTPqMK": ["বেড়া দেওয়া কোড ব্লক চালু বা বন্ধ করুন।"],
@@ -3579,7 +3601,6 @@
"qjHMHf": ["সিঙ্ক নিষ্ক্রিয় করতে ব্যর্থ — ", ["detail"]],
"qkqG0b": ["আপস্ট্রিমেরটি নিন"],
"qlAIQ1": ["রিমোট"],
- "qlnfTD": ["ছবি লোড করা যায়নি: ", ["errorLabel"]],
"qmL1UG": ["নিরাপদে আপলোড করা হচ্ছে"],
"qo4zCg": ["পথে ব্যাকস্ল্যাশ থাকতে পারে না"],
"qpQwGC": ["আপনি কী নিয়ে কাজ করছেন তার বর্ণনা দিন, এজেন্ট আপনার জন্য সেটি সাজিয়ে দেবে।"],
@@ -3612,6 +3633,7 @@
"rXz97P": ["আইটেমের সংখ্যায়িত তালিকা।"],
"rZ9HZq": ["করণীয়"],
"rZVMkf": ["দৃশ্য সম্পাদকের বদলানোর ইনপুট ফোকাসে"],
+ "radOpL": ["ছবি ", ["identity"], "। রেফারেন্সে যান।"],
"rageVb": ["সরাসরি প্রাকদর্শন প্যানেলসহ কাস্টম HTML (স্যান্ডবক্স করা iframe)।"],
"rbrHTd": ["অনুমোদিত — ", ["optionName"]],
"rcJmK8": ["জায়গাগুলোকে অনুলিপিতে রূপান্তর করুন"],
@@ -3770,6 +3792,7 @@
["trashNoun"],
"-এ পাঠানো যায়নি। এর বদলে কি স্থায়ীভাবে মুছে ফেলতে চান?"
],
+ "txUHO8": [["displayLine"], " নম্বর লাইনে ", ["localizedMessage"]],
"tzGWeg": ["OpenKnowledge সরানোর প্রস্তুতি নেওয়া হচ্ছে"],
"tzZ6ha": ["GitHub Enterprise Server-এর সঙ্গে যুক্ত করুন"],
"u-9fWA": ["সিস্টেমের সংক্ষিপ্তসারের জন্য <0>Architecture</0> দেখুন।"],
@@ -3784,7 +3807,6 @@
"uA_jXp": ["ব্রাঞ্চ বদলে হালনাগাদ করুন"],
"uBAxNB": ["সম্পাদক"],
"uCaIdy": ["GitHub সাইন-ইন অনুপস্থিত বা এর মেয়াদ শেষ। সিঙ্ক আবার শুরু করতে পুনরায় যুক্ত হোন।"],
- "uCe4AX": [["displayLine"], " নম্বর লাইনে ", ["0"]],
"uDlyqd": [
"এই রিপোজিটরির স্থাপত্য নথিভুক্ত করুন: একটি সংক্ষিপ্তসার পাতা তৈরি করুন যা প্রতিটি প্রধান মডিউলের পাতার সঙ্গে যুক্ত থাকে এবং তার দায়িত্ব ও প্রবেশবিন্দু বর্ণনা করে।"
],
@@ -3873,6 +3895,7 @@
"vPEyDz": ["এজেন্ট প্রতিলিপি"],
"vPF04k": ["একটি নতুন আলাপ শুরু করুন"],
"vPKX2i": ["অ্যাপে (বিটা)"],
+ "vPLUCm": ["অনুপস্থিত ছবি ", ["identity"], "। রেফারেন্সে যান।"],
"vPXOUw": ["সোর্স দৃশ্য চালু বা বন্ধ করুন"],
"vQIVHc": ["ফোল্ডার প্রপার্টি"],
"vWc9a0": ["সম্পাদনা করতে লিখুন; <0>⌘ Enter</0> সংরক্ষণ করে, <1>Esc</1> বাতিল করে।"],
@@ -4026,6 +4049,7 @@
"xxRpzT": ["আপনার সিস্টেমে Slidev পাওয়া গেছে।"],
"xzAmL_": ["স্বয়ংক্রিয়ভাবে অনুমোদিত"],
"xzktOa": ["উইকি লিংক সম্পাদনা করুন"],
+ "y-LQPF": ["সমাধান করা যায় না এমন ছবি ", ["identity"], "। রেফারেন্সে যান।"],
"y1eoq1": ["লিংক কপি করুন"],
"y1t8bQ": ["সেটিং-এর বিভাগ"],
"y3aU20": ["পরিবর্তন সংরক্ষণ করুন"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index 698ff98a4..cadce3459 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} জিজ্ঞাসা না করেই কাজ করে —
msgid "{0} added, {1} removed"
msgstr "{0} যোগ হয়েছে, {1} সরানো হয়েছে"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{displayLine} নম্বর লাইনে {0}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# লিংক} other {# লিংক}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{displayLine} নম্বর লাইনে {localizedMessage}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {# মিনিট আগে} other {# মিনিট আগে}}"
@@ -2204,6 +2203,10 @@ msgstr "GitHub-এ হালনাগাদ দেখা হচ্ছে"
msgid "Checking GitHub connection..."
msgstr "GitHub সংযোগ পরীক্ষা করা হচ্ছে…"
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "লিংক যাচাই করা হচ্ছে"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "ফাইল চেক আউট করা হচ্ছে"
@@ -5053,6 +5056,10 @@ msgstr "শিরোনাম লোড করতে ব্যর্থ"
msgid "Failed to load hub pages"
msgstr "হাব পাতা লোড করতে ব্যর্থ"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "স্থানীয় ফাইল লোড করতে ব্যর্থ"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "অনাথ পাতা লোড করতে ব্যর্থ"
@@ -5280,6 +5287,10 @@ msgstr "ফিল্ড"
msgid "File"
msgstr "ফাইল"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "ফাইল {identity}। রেফারেন্সে যান।"
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "ফাইলটি আগে থেকেই আছে"
@@ -6030,6 +6041,10 @@ msgstr "OpenKnowledge আপনার কেমন লাগছে?"
msgid "How does sharing work?"
msgstr "ভাগাভাগি কীভাবে কাজ করে?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "অনুপস্থিত প্রজেক্ট-লোকাল ডকুমেন্ট, ফাইল ও ছবিগুলো সমস্যা, এডিটর ডায়াগনস্টিকস, অডিট এবং এজেন্ট টুলে কীভাবে রিপোর্ট করা হয়।"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "হাতে কীভাবে পাঠাবেন"
@@ -6047,10 +6062,6 @@ msgstr "কীভাবে সেট আপ করবেন"
msgid "How to set up {0} (opens in browser)"
msgstr "{0} কীভাবে সেট আপ করবেন (ব্রাউজারে খোলে)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Problems প্যানেল, নিরীক্ষা ও এজেন্ট টুলে অমীমাংসিত উইকি লিংক কীভাবে জানানো হয়।"
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "যাচাইয়ের ফলাফল প্রকল্প জুড়ে কীভাবে সামনে আসে। এই বাছাইগুলো config.yml-এ কমিট হয় এবং git-এর মাধ্যমে প্রতিটি সহযোগীর সঙ্গে ভাগ করা হয়।"
@@ -6106,13 +6117,33 @@ msgstr "উপেক্ষার প্যাটার্ন"
msgid "Ignore patterns (raw text)"
msgstr "উপেক্ষার প্যাটার্ন (কাঁচা লেখা)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "ছবি {identity}। রেফারেন্সে যান।"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "ছবি দেখানো যায়নি"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "ছবি লোড করা যায়নি"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "ছবি দেখানো যায়নি: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "ছবি লোড করা যায়নি: {errorLabel}"
+msgid "Image not found"
+msgstr "ছবি পাওয়া যায়নি"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "ছবি পাওয়া যায়নি: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "ছবির লক্ষ্য \"{shown}\"-কে প্রকল্পের স্থানীয় ফাইল হিসেবে নির্ণয় করা যায়নি।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "ছবির লক্ষ্য \"{shown}\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6713,6 +6744,18 @@ msgstr "লিংক প্রস্তুত, কিন্তু ক্লি
msgid "Link target"
msgstr "লিংকের লক্ষ্য"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "লিংকের লক্ষ্য \"{shown}\"-কে প্রকল্পের স্থানীয় লক্ষ্য হিসেবে নির্ণয় করা যায়নি।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "লিংকের লক্ষ্য \"{shown}\" কোনো বিদ্যমান নথিকে নির্দেশ করে না।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "লিংকের লক্ষ্য \"{shown}\" কোনো বিদ্যমান ফাইলকে নির্দেশ করে না।"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "নির্বাচিত লেখাটি লিংক করুন, বা কার্সরের নিচের লিংকটি সম্পাদনা করুন।"
@@ -6725,6 +6768,14 @@ msgstr "একটি পাতা বা বাইরের URL-এ লিংক
msgid "Link URL"
msgstr "লিংক URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "লিংক যাচাইকরণ উপলভ্য নয়।"
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "লিংক যাচাইকরণ উপলভ্য নয়। সর্বশেষ জানা সমস্যাগুলি দেখানো হচ্ছে।"
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "লিংক-গ্রাফের সাড়া প্রত্যাশিত আকারের সঙ্গে মেলেনি।"
@@ -6921,6 +6972,14 @@ msgstr "\"{docName}\"-এর স্থানীয় সহযোগিতা
msgid "Local commits are keeping this copy from updating"
msgstr "স্থানীয় কমিটগুলো এই অনুলিপিকে হালনাগাদ হতে দিচ্ছে না"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "স্থানীয় ফাইলের বিবরণ এখনও উপলব্ধ নয়।"
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "স্থানীয় ফাইল"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "স্থানীয় পথ"
@@ -7097,10 +7156,22 @@ msgstr "মিরর উৎস <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "মিরর উৎস <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "অনুপস্থিত"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "একটি বৈশিষ্ট্য অনুপস্থিত"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "অনুপস্থিত ফাইল {identity}। রেফারেন্সে যান।"
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "অনুপস্থিত ছবি {identity}। রেফারেন্সে যান।"
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "অনুপস্থিত পাতা — তৈরি করতে ক্লিক করুন"
@@ -8017,10 +8088,9 @@ msgstr "আইটেমের সংখ্যায়িত তালিকা
msgid "Object"
msgstr "অবজেক্ট"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "{0}-এর উপস্থিতি"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "{localizedFirstMessage}-এর উপস্থিতিগুলি"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12325,6 +12395,10 @@ msgstr "এই পাতাটি এখনও নেই। সম্পাদ
msgid "This page doesn't link to anything yet."
msgstr "এই পাতাটি এখনও কোনো কিছুর সঙ্গে লিংক করে না।"
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "এই পাতাটি কোনো স্থানীয় ফাইল বা ছবি উল্লেখ করে না।"
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "এই পথটি একটি বাইরের ভলিউমে (/Volumes/…)। ড্রাইভটি বের করে নিলে OpenKnowledge ফাইলগুলোর হদিস হারিয়ে ফেলবে।"
@@ -12864,6 +12938,18 @@ msgstr "অচেনা লিংক"
msgid "Unrecognized wiki link"
msgstr "অচেনা উইকি লিংক"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "সমাধান অযোগ্য"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "সমাধান করা যায় না এমন ফাইল {identity}। রেফারেন্সে যান।"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "সমাধান করা যায় না এমন ছবি {identity}। রেফারেন্সে যান।"
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "হালনাগাদ"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 46c3f2c28..92133359e 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -160,11 +160,13 @@
"1njn7W": ["Light"],
"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],
"1oSHI0": ["Couldn't install ", ["skillName"], ": ", ["0"]],
+ "1pdLQw": ["Image not found"],
"1qpGKz": ["Couldn’t save changes. Try editing a color again."],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["Reject"],
"1u-mAI": ["Couldn't start the sync. Check your connection, then retry."],
"1vn0CI": ["Invalid server response"],
+ "1xui0Q": ["Failed to load local files"],
"2277Tu": ["Collapse graph"],
"237hSL": ["Ended"],
"253MN6": ["Couldn't send your comments — please try again."],
@@ -443,6 +445,7 @@
"6HCOwA": ["Failed to open."],
"6KCH4m": ["Hidden files"],
"6KXnz5": ["You can restore this file from the Trash."],
+ "6LJJ1v": ["File ", ["identity"], ". Go to reference."],
"6LbUG7": ["The repository is private and your GitHub account doesn't have access to it."],
"6Mbe-P": [
"Describe what it should do, or add one yourself. OpenKnowledge keeps your skills in one place, versions them, and installs them into agents like Claude, Codex, and Cursor."
@@ -982,7 +985,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens used"],
"EQXPXf": ["Scroll to end"],
"ETyvvg": ["No language match."],
- "EUiJEM": ["Occurrences of ", ["0"]],
"EWCJFu": ["Created ", ["target"]],
"EWPtMO": ["Code"],
"EWX92Z": ["Collapse Ask AI"],
@@ -1278,6 +1280,7 @@
"IgN3LY": ["On selected text in <0>", ["address"], "</0>"],
"IgTwLt": ["Open this document in the editor and collapse the graph."],
"Ik-gP0": ["Heading H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["Link validation is unavailable. Showing last known problems."],
"Iq8zdU": ["Close terminal"],
"IrB5AK": [
"Server-side cleanup failed for ",
@@ -1463,6 +1466,7 @@
"Lm3r51": ["Slidev couldn't render this document."],
"LnVIW4": ["Failed to start sign-in — try again"],
"LpB85N": ["Plain"],
+ "Lrsl_h": ["Missing file ", ["identity"], ". Go to reference."],
"LtI9AS": ["Owner"],
"LtSYdi": ["Reveal in Finder"],
"LtiJ5c": ["Project skill"],
@@ -1567,9 +1571,6 @@
"When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
],
"MysZUL": ["Connecting to ", ["agentName"], "…"],
- "N-IonL": [
- "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
- ],
"N1KkEO": ["Jump to last tab"],
"N1YYa7": ["Loading image"],
"N1mdmS": ["This file can't be opened in the text editor."],
@@ -2001,6 +2002,7 @@
"U2Kx6T": ["Close all unpinned"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["Full guide"],
+ "U3RIJu": ["Local files"],
"U4nTfu": ["Enable Follow"],
"U5Spo9": ["Content directory must be inside the project"],
"U6wmNc": ["Sync paused"],
@@ -2120,12 +2122,14 @@
"VNNRfN": ["make source"],
"VNgKZz": ["Advanced settings"],
"VTulZj": ["Open in worktree"],
+ "VU3Nrn": ["Missing"],
"VUijjF": ["Embed an image with optional alt text."],
"VVRrPk": [["0"], " doesn't offer any settings to adjust"],
"VXGFMg": ["Code field undo or redo"],
"VYd_YA": ["Open an existing project folder from disk."],
"VZGh8G": ["Fold, unfold, fold all, or unfold all source ranges."],
"VZSBXL": ["Semantic ranking activates the first time an agent runs a search."],
+ "VZg6Gn": ["Image couldn't be displayed: ", ["errorLabel"]],
"V_6bJ4": ["Terminal settings not loaded yet — try again in a moment."],
"V_DjMe": ["render error"],
"V_wltx": ["Enter a title for this template."],
@@ -2150,12 +2154,14 @@
"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],
"W3Tsgy": ["Detected in ", ["0"]],
"W5A0Ly": ["An unexpected error occurred."],
+ "W5qdI_": ["Image target \"", ["shown"], "\" could not be resolved to a project-local file."],
"W7XJN4": [
"Can't nest projects. An OpenKnowledge project already exists at <0>",
["rootPath"],
"</0>. Choose a location outside it, or open that project instead."
],
"W8vpBM": ["starter pack"],
+ "W9NSe0": ["Checking links"],
"W9_Bub": ["Local changes overlap with incoming sync"],
"WBNpt9": ["Couldn’t read this theme (", ["0"], ")"],
"WFEbV1": ["Flag common markdown issues in the editor. Powered by <0>markdownlint<1/></0>."],
@@ -2216,11 +2222,13 @@
"X8kjQX": ["Re-authenticate with GitHub"],
"X9VpsP": ["Loading folder contents"],
"XAyxsa": ["Check out remote branch"],
+ "XBBZnv": ["Link target \"", ["shown"], "\" does not resolve to an existing document."],
"XBgr2S": ["Copy in"],
"XDzAnp": ["Opens in a new tab"],
"XFpEgc": [
"Choose which agents appear in agent menus across the app, such as Ask AI, Open with AI, and the + new chat button. Turn an agent off to hide it from all of them."
],
+ "XGKy1z": ["Image couldn't be displayed"],
"XH30C4": ["document"],
"XIltnd": ["A skill named \"", ["trimmed"], "\" already exists here"],
"XJOV1Y": ["Activity"],
@@ -2238,6 +2246,7 @@
"XW18jo": ["Page headings response did not match success schema"],
"XWEqQj": [["days"], "d"],
"XXA1b_": [["componentLabel"], " (empty)"],
+ "XYZ7tp": ["Unresolvable"],
"XYlJJT": ["Setting up"],
"XZkdtg": ["Switch branch"],
"XcGbim": ["Show hidden files"],
@@ -2329,6 +2338,7 @@
"YW7Q86": ["Search settings not yet loaded — try again in a moment"],
"Y_GpJd": ["The ", ["0"], " download request timed out."],
"Y_ZQ6l": ["Installing ", ["agentName"], "…"],
+ "Y_iImT": ["Unresolvable file ", ["identity"], ". Go to reference."],
"Y_kL7X": ["Customize how the editor looks and behaves."],
"Ya3PlJ": ["Permission required"],
"YaeyFh": ["Pulls may overwrite uncommitted edits in your local files."],
@@ -2443,6 +2453,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Occurrences of ", ["localizedFirstMessage"]],
"_DwR-n": ["Creating…"],
"_FLBbi": [["sizeText"], " · secrets redacted · crash dump not redacted"],
"_GRWOJ": ["Change the embeddings provider?"],
@@ -2590,6 +2601,7 @@
"blFttG": ["Search projects"],
"bmC18N": ["Clearing local collaboration data for \"", ["docName"], "\" before reconnecting."],
"bnOTEz": ["Retrieving…"],
+ "bpMVIA": ["Link target \"", ["shown"], "\" could not be resolved to a project-local target."],
"bpytj4": ["Move to ", ["0"]],
"brCtGB": ["History unavailable"],
"buNXgr": ["Switch between the visual and source editors, keeping your place."],
@@ -2826,6 +2838,7 @@
"fJgQHX": ["Failed to create file"],
"fMsFdZ": ["Couldn't save the auto-update setting: ", ["0"]],
"fNr-MX": ["Disable semantic search"],
+ "fOzzSV": ["Link target \"", ["shown"], "\" does not resolve to an existing file."],
"fR-Kdc": ["(project-level only)"],
"fRVBiq": [
"Adds telemetry, server state, and runtime info when available. Credentials are always removed; document names, if included, appear in cleartext (not redacted)."
@@ -2861,6 +2874,7 @@
"fwrPh4": ["Please enter a valid email."],
"fxJk_6": ["<0>Have more to add?</0> Write to <1/> and mention your reference."],
"fxbCNQ": ["Synced. The link is up to date."],
+ "g-dkjJ": ["Local file details aren't available yet."],
"g12y1g": ["Invalid YAML"],
"g1ZTh_": [
[
@@ -2948,6 +2962,7 @@
"gmJ0An": ["Failed to open folder."],
"goO4Ll": ["Editor status bar"],
"gp3I7-": ["Before syncing, set your identity for git commits:"],
+ "gpbKxw": ["Link validation is unavailable."],
"gqk-3R": ["Moved ", ["0"], " to ", ["destination"], "."],
"gtEbeW": ["Highlight"],
"gtGQ9S": ["Start ", ["agentName"], ", ", ["hint"]],
@@ -3066,6 +3081,7 @@
"iRdfLr": ["Dev instance: ", ["label"]],
"iSLIjg": ["Connect"],
"iSQTsg": ["Ordered list"],
+ "iSWh95": ["Image target \"", ["shown"], "\" does not resolve to an existing file."],
"iSnkwB": ["Failed to open cloned project."],
"iTylMl": ["Templates"],
"iUwpZI": ["No spaces — use <0>-</0> instead."],
@@ -3104,6 +3120,9 @@
"The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."
],
"iqIDv4": ["Sync status unavailable"],
+ "iqr14Z": [
+ "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+ ],
"iqugog": ["Initialize failed: ", ["errorDetail"]],
"irFGwu": ["Template list"],
"irrm_E": ["Remove selection"],
@@ -3205,6 +3224,7 @@
"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],
"kFLlsI": ["Insert a footnote reference + matching definition stub."],
"kGp168": ["Couldn't prepare this project for publish."],
+ "kI5pWt": ["Image not found: ", ["errorLabel"]],
"kKw0H3": [
"You edited this skill locally and the source has new changes. Taking upstream replaces your version; your edits stay recoverable in version history."
],
@@ -3449,7 +3469,6 @@
"nCzR-G": ["Copy code ", ["userCode"]],
"nDT8qt": ["Initialized ", ["0"], " but could not open it."],
"nG-XA9": ["The anchored text is gone. You can re-place it on selected text."],
- "nL-HHD": ["Image failed to load"],
"nMSYz5": [
"This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
],
@@ -3585,6 +3604,7 @@
"pFRz_E": ["Leave these comments out of this message"],
"pFagOn": ["Source editing"],
"pHYP6v": ["Open <0>Customize</0> in the sidebar <1/> <2>Skills</2>."],
+ "pJ7XCo": ["This page references no local files or images."],
"pOo4Aa": ["Plain text"],
"pSimwP": ["New name for the ", ["editor"], " version"],
"pTPqMK": ["Toggle a fenced code block."],
@@ -3698,7 +3718,6 @@
"qjHMHf": ["Failed to disable sync — ", ["detail"]],
"qkqG0b": ["Take upstream"],
"qlAIQ1": ["Remote"],
- "qlnfTD": ["Image failed to load: ", ["errorLabel"]],
"qmL1UG": ["Uploading securely"],
"qo4zCg": ["Path cannot contain backslashes"],
"qpQwGC": ["Describe what you're working on and the agent sets it up for you."],
@@ -3739,6 +3758,7 @@
"rXz97P": ["Numbered list of items."],
"rZ9HZq": ["To do"],
"rZVMkf": ["Visual editor replace input focused"],
+ "radOpL": ["Image ", ["identity"], ". Go to reference."],
"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],
"rbrHTd": ["Approved — ", ["optionName"]],
"rcJmK8": ["Convert locations to copies"],
@@ -3903,6 +3923,7 @@
["trashNoun"],
". Do you want to permanently delete instead?"
],
+ "txUHO8": [["localizedMessage"], " at line ", ["displayLine"]],
"tzGWeg": ["Preparing to uninstall OpenKnowledge"],
"tzZ6ha": ["Connect to GitHub Enterprise Server"],
"u-9fWA": ["See <0>Architecture</0> for the system overview."],
@@ -3917,7 +3938,6 @@
"uA_jXp": ["Switch and update branch"],
"uBAxNB": ["Editor"],
"uCaIdy": ["GitHub sign-in is missing or expired. Reconnect to resume syncing."],
- "uCe4AX": [["0"], " at line ", ["displayLine"]],
"uDlyqd": [
"Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."
],
@@ -4008,6 +4028,7 @@
"vPEyDz": ["Agent transcript"],
"vPF04k": ["Start a new chat"],
"vPKX2i": ["In app (beta)"],
+ "vPLUCm": ["Missing image ", ["identity"], ". Go to reference."],
"vPXOUw": ["Toggle source view"],
"vQIVHc": ["Folder properties"],
"vWc9a0": ["Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."],
@@ -4173,6 +4194,7 @@
"xxRpzT": ["Slidev found on your system."],
"xzAmL_": ["Auto-approved"],
"xzktOa": ["Edit wiki link"],
+ "y-LQPF": ["Unresolvable image ", ["identity"], ". Go to reference."],
"y1eoq1": ["Copy link"],
"y1t8bQ": ["Settings sections"],
"y3aU20": ["Save changes"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 37c68985e..37defb5b2 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} acts without asking — OpenKnowledge can't add permission prompts f
msgid "{0} added, {1} removed"
msgstr "{0} added, {1} removed"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} at line {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# link} other {# links}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} at line {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {# min ago} other {# min ago}}"
@@ -2208,6 +2207,10 @@ msgstr "Checking for updates on GitHub"
msgid "Checking GitHub connection..."
msgstr "Checking GitHub connection..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "Checking links"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "Checking out files"
@@ -5057,6 +5060,10 @@ msgstr "Failed to load headings"
msgid "Failed to load hub pages"
msgstr "Failed to load hub pages"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "Failed to load local files"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "Failed to load orphan pages"
@@ -5284,6 +5291,10 @@ msgstr "Fields"
msgid "File"
msgstr "File"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "File {identity}. Go to reference."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "File already exists"
@@ -6034,6 +6045,10 @@ msgstr "How do you like OpenKnowledge?"
msgid "How does sharing work?"
msgstr "How does sharing work?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "How to push manually"
@@ -6051,10 +6066,6 @@ msgstr "How to set up"
msgid "How to set up {0} (opens in browser)"
msgstr "How to set up {0} (opens in browser)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
@@ -6110,13 +6121,33 @@ msgstr "Ignore patterns"
msgid "Ignore patterns (raw text)"
msgstr "Ignore patterns (raw text)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "Image {identity}. Go to reference."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "Image couldn't be displayed"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "Image failed to load"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "Image couldn't be displayed: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "Image failed to load: {errorLabel}"
+msgid "Image not found"
+msgstr "Image not found"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "Image not found: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "Image target \"{shown}\" could not be resolved to a project-local file."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "Image target \"{shown}\" does not resolve to an existing file."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "Link ready but could not copy to clipboard."
msgid "Link target"
msgstr "Link target"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "Link target \"{shown}\" could not be resolved to a project-local target."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "Link target \"{shown}\" does not resolve to an existing document."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "Link target \"{shown}\" does not resolve to an existing file."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "Link the selected text, or edit the link under the caret."
@@ -6729,6 +6772,14 @@ msgstr "Link to a page or external URL."
msgid "Link URL"
msgstr "Link URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "Link validation is unavailable."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "Link validation is unavailable. Showing last known problems."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "Link-graph response did not match expected shape."
@@ -6925,6 +6976,14 @@ msgstr "Local collaboration data for \"{docName}\" could not be cleared. Reload
msgid "Local commits are keeping this copy from updating"
msgstr "Local commits are keeping this copy from updating"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "Local file details aren't available yet."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "Local files"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "Local path"
@@ -7101,10 +7160,22 @@ msgstr "Mirror source <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "Mirror source <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "Missing"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "Missing a feature"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "Missing file {identity}. Go to reference."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "Missing image {identity}. Go to reference."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "Missing page — click to create"
@@ -8021,10 +8092,9 @@ msgstr "Numbered list of items."
msgid "Object"
msgstr "Object"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "Occurrences of {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "Occurrences of {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "This page doesn't exist yet. Open it to create the page in the editor an
msgid "This page doesn't link to anything yet."
msgstr "This page doesn't link to anything yet."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "This page references no local files or images."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
@@ -12868,6 +12942,18 @@ msgstr "Unrecognized link"
msgid "Unrecognized wiki link"
msgstr "Unrecognized wiki link"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "Unresolvable"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "Unresolvable file {identity}. Go to reference."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "Unresolvable image {identity}. Go to reference."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "Up to date"
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index a7b82524d..ae6e5fe33 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -180,11 +180,13 @@
"1njn7W": ["Claro"],
"1nke1r": ["Abrir ", ["0"], " en GitHub (se abre en una pestaña nueva)"],
"1oSHI0": ["No se pudo instalar ", ["skillName"], ": ", ["0"]],
+ "1pdLQw": ["No se encontró la imagen"],
"1qpGKz": ["No se pudieron guardar los cambios. Intenta editar un color de nuevo."],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["Rechazar"],
"1u-mAI": ["No se pudo iniciar la sincronización. Revisa tu conexión y vuelve a intentarlo."],
"1vn0CI": ["Respuesta del servidor no válida"],
+ "1xui0Q": ["No se pudieron cargar los archivos locales"],
"2277Tu": ["Contraer el grafo"],
"237hSL": ["Terminado"],
"253MN6": ["No se pudieron enviar tus comentarios; inténtalo de nuevo."],
@@ -512,6 +514,7 @@
"6HCOwA": ["No se pudo abrir."],
"6KCH4m": ["Archivos ocultos"],
"6KXnz5": ["Puedes restaurar este archivo desde la Papelera."],
+ "6LJJ1v": ["Archivo ", ["identity"], ". Ir a la referencia."],
"6LbUG7": ["El repositorio es privado y tu cuenta de GitHub no tiene acceso."],
"6Mbe-P": [
"Describe lo que debería hacer, o añade una tú. OpenKnowledge guarda tus habilidades en un solo sitio, las versiona y las instala en agentes como Claude, Codex y Cursor."
@@ -1134,7 +1137,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens usados"],
"EQXPXf": ["Desplazar hasta el final"],
"ETyvvg": ["Ningún idioma coincide."],
- "EUiJEM": ["Apariciones de ", ["0"]],
"EWCJFu": ["Se creó ", ["target"]],
"EWPtMO": ["Código"],
"EWX92Z": ["Contraer Preguntar a la IA"],
@@ -1484,6 +1486,9 @@
"IgN3LY": ["Sobre el texto seleccionado en <0>", ["address"], "</0>"],
"IgTwLt": ["Abre este documento en el editor y contrae el grafo."],
"Ik-gP0": ["Encabezado H", ["level"], ": ", ["text"]],
+ "IoHQYP": [
+ "La validación de enlaces no está disponible. Se muestran los últimos problemas conocidos."
+ ],
"Iq8zdU": ["Cerrar terminal"],
"IrB5AK": [
"Falló la limpieza en el servidor de ",
@@ -1696,6 +1701,7 @@
"Lm3r51": ["Slidev no pudo renderizar este documento."],
"LnVIW4": ["No se pudo iniciar la sesión: inténtalo de nuevo"],
"LpB85N": ["Sencillo"],
+ "Lrsl_h": ["Falta el archivo ", ["identity"], ". Ir a la referencia."],
"LtI9AS": ["Propietario"],
"LtSYdi": ["Mostrar en el Finder"],
"LtiJ5c": ["Habilidad del proyecto"],
@@ -1812,9 +1818,6 @@
"Al pasar el cursor por un enlace externo, su URL se envía al sitio de destino para obtener los metadatos de vista previa de la página: una solicitud por cada enlace previsualizado."
],
"MysZUL": ["Conectando con ", ["agentName"], "…"],
- "N-IonL": [
- "Cómo se informa de los enlaces wiki sin resolver en el panel Problemas, en las auditorías y en las herramientas de agente."
- ],
"N1KkEO": ["Ir a la última pestaña"],
"N1YYa7": ["Cargando la imagen"],
"N1mdmS": ["Este archivo no se puede abrir en el editor de texto."],
@@ -2285,6 +2288,7 @@
"U2Kx6T": ["Cerrar todas las no fijadas"],
"U2pMtf": ["nombre-de-etiqueta"],
"U3IvM5": ["Guía completa"],
+ "U3RIJu": ["Archivos locales"],
"U4nTfu": ["Activar Seguir"],
"U5Spo9": ["El directorio de contenido debe estar dentro del proyecto"],
"U6wmNc": ["Sincronización en pausa"],
@@ -2416,6 +2420,7 @@
"VNNRfN": ["convertir en origen"],
"VNgKZz": ["Ajustes avanzados"],
"VTulZj": ["Abrir en un worktree"],
+ "VU3Nrn": ["Ausente"],
"VUijjF": ["Incrusta una imagen con texto alternativo opcional."],
"VVRrPk": [["0"], " no ofrece ajustes que configurar"],
"VXGFMg": ["Deshacer o rehacer en el campo de código"],
@@ -2424,6 +2429,7 @@
"VZSBXL": [
"La clasificación semántica se activa la primera vez que un agente ejecuta una búsqueda."
],
+ "VZg6Gn": ["No se pudo mostrar la imagen: ", ["errorLabel"]],
"V_6bJ4": [
"Los ajustes de la terminal aún no se han cargado; inténtalo de nuevo en un momento."
],
@@ -2466,12 +2472,18 @@
"W1qRuM": ["Este documento ya está activo en el editor. Usa Abrir para contraer el grafo."],
"W3Tsgy": ["Detectado en ", ["0"]],
"W5A0Ly": ["Se produjo un error inesperado."],
+ "W5qdI_": [
+ "El destino de la imagen «",
+ ["shown"],
+ "» no se pudo resolver como un archivo local del proyecto."
+ ],
"W7XJN4": [
"No se pueden anidar proyectos. Ya existe un proyecto de OpenKnowledge en <0>",
["rootPath"],
"</0>. Elige una ubicación fuera de él o abre ese proyecto."
],
"W8vpBM": ["paquete inicial"],
+ "W9NSe0": ["Comprobando enlaces"],
"W9_Bub": ["Los cambios locales se solapan con la sincronización entrante"],
"WBNpt9": ["No se pudo leer este tema (", ["0"], ")"],
"WFEbV1": [
@@ -2534,11 +2546,13 @@
"X8kjQX": ["Volver a autenticarse con GitHub"],
"X9VpsP": ["Cargando el contenido de la carpeta"],
"XAyxsa": ["Extraer rama remota"],
+ "XBBZnv": ["El destino del enlace «", ["shown"], "» no corresponde a un documento existente."],
"XBgr2S": ["Copiar aquí"],
"XDzAnp": ["Se abre en una pestaña nueva"],
"XFpEgc": [
"Elige qué agentes aparecen en los menús de agentes de la aplicación, como Ask AI, Open with AI y el botón + de nuevo chat. Desactiva un agente para ocultarlo de todos ellos."
],
+ "XGKy1z": ["No se pudo mostrar la imagen"],
"XH30C4": ["documento"],
"XIltnd": ["Ya existe aquí una habilidad llamada \"", ["trimmed"], "\""],
"XJOV1Y": ["Actividad"],
@@ -2556,6 +2570,7 @@
"XW18jo": ["La respuesta de los encabezados de página no coincide con el esquema de éxito"],
"XWEqQj": [["days"], "d"],
"XXA1b_": [["componentLabel"], " (vacío)"],
+ "XYZ7tp": ["Sin resolver"],
"XYlJJT": ["Configurando"],
"XZkdtg": ["Cambiar de rama"],
"XcGbim": ["Mostrar los archivos ocultos"],
@@ -2673,6 +2688,7 @@
"YW7Q86": ["Los ajustes de búsqueda aún no se han cargado; inténtalo de nuevo en un momento"],
"Y_GpJd": ["Se agotó el tiempo de la solicitud de descarga de ", ["0"], "."],
"Y_ZQ6l": ["Instalando ", ["agentName"], "…"],
+ "Y_iImT": ["No se puede resolver el archivo ", ["identity"], ". Ir a la referencia."],
"Y_kL7X": ["Personaliza el aspecto y el comportamiento del editor."],
"Ya3PlJ": ["Se requiere permiso"],
"YaeyFh": ["El pull puede sobrescribir ediciones sin confirmar en tus archivos locales."],
@@ -2803,6 +2819,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Apariciones de ", ["localizedFirstMessage"]],
"_DwR-n": ["Creando…"],
"_FLBbi": [["sizeText"], " · secretos ocultos · volcado de fallo sin ocultar"],
"_GRWOJ": ["¿Cambiar el proveedor de embeddings?"],
@@ -2983,6 +3000,11 @@
"\" antes de reconectar."
],
"bnOTEz": ["Recuperando…"],
+ "bpMVIA": [
+ "El destino del enlace «",
+ ["shown"],
+ "» no se pudo resolver como un destino local del proyecto."
+ ],
"bpytj4": ["Mover a ", ["0"]],
"brCtGB": ["El historial no está disponible"],
"buNXgr": ["Cambia entre el editor visual y el de código sin perder tu sitio."],
@@ -3266,6 +3288,7 @@
"fJgQHX": ["No se pudo crear el archivo"],
"fMsFdZ": ["No se pudo guardar el ajuste de actualización automática: ", ["0"]],
"fNr-MX": ["Desactivar la búsqueda semántica"],
+ "fOzzSV": ["El destino del enlace «", ["shown"], "» no corresponde a un archivo existente."],
"fR-Kdc": ["(solo a nivel de proyecto)"],
"fRVBiq": [
"Añade telemetría, estado del servidor e información de ejecución cuando está disponible. Las credenciales siempre se eliminan; los nombres de documento, si se incluyen, aparecen en texto plano (sin ocultar)."
@@ -3313,6 +3336,7 @@
"fwrPh4": ["Escribe un correo válido."],
"fxJk_6": ["<0>¿Tienes algo más que añadir?</0> Escribe a <1/> y menciona tu referencia."],
"fxbCNQ": ["Sincronizado. El enlace está al día."],
+ "g-dkjJ": ["Los detalles de los archivos locales aún no están disponibles."],
"g12y1g": ["YAML no válido"],
"g1ZTh_": [
[
@@ -3411,6 +3435,7 @@
"gmJ0An": ["No se pudo abrir la carpeta."],
"goO4Ll": ["Barra de estado del editor"],
"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"], "."],
"gtEbeW": ["Resaltado"],
"gtGQ9S": ["Iniciar ", ["agentName"], ", ", ["hint"]],
@@ -3543,6 +3568,7 @@
"iRdfLr": ["Instancia de desarrollo: ", ["label"]],
"iSLIjg": ["Conectar"],
"iSQTsg": ["Lista numerada"],
+ "iSWh95": ["El destino de la imagen «", ["shown"], "» no corresponde a un archivo existente."],
"iSnkwB": ["No se pudo abrir el proyecto clonado."],
"iTylMl": ["Plantillas"],
"iUwpZI": ["Sin espacios: usa <0>-</0> en su lugar."],
@@ -3585,6 +3611,9 @@
"El <0>type</0> que recibe cada documento creado a partir de esta plantilla (p. ej. <1>research-note</1>). Mantiene los documentos nuevos conformes al Open Knowledge Format."
],
"iqIDv4": ["Estado de sincronización no disponible"],
+ "iqr14Z": [
+ "Cómo se notifican los documentos, archivos e imágenes locales del proyecto que faltan en Problemas, los diagnósticos del editor, las auditorías y las herramientas de agentes."
+ ],
"iqugog": ["Falló la inicialización: ", ["errorDetail"]],
"irFGwu": ["Lista de plantillas"],
"irrm_E": ["Quitar la selección"],
@@ -3692,6 +3721,7 @@
"kCqCyf": ["Abre el panel de diagnóstico de análisis de CodeMirror."],
"kFLlsI": ["Inserta una referencia a nota al pie y su definición correspondiente."],
"kGp168": ["No se pudo preparar este proyecto para publicarlo."],
+ "kI5pWt": ["No se encontró la imagen: ", ["errorLabel"]],
"kKw0H3": [
"Editaste esta habilidad en local y el origen tiene cambios nuevos. Aceptar la versión remota reemplaza la tuya; tus ediciones siguen recuperables en el historial de versiones."
],
@@ -3968,7 +3998,6 @@
"nG-XA9": [
"El texto anclado ha desaparecido. Puedes volver a colocarlo sobre el texto seleccionado."
],
- "nL-HHD": ["No se pudo cargar la imagen"],
"nMSYz5": [
"Esta ruta está en un volumen externo (/Volumes/...). OpenKnowledge perderá la pista de los archivos cuando se expulse la unidad."
],
@@ -4111,6 +4140,7 @@
"pFRz_E": ["Dejar estos comentarios fuera de este mensaje"],
"pFagOn": ["Edición de código"],
"pHYP6v": ["Abre <0>Personalizar</0> en la barra lateral <1/> <2>Habilidades</2>."],
+ "pJ7XCo": ["Esta página no hace referencia a ningún archivo o imagen local."],
"pOo4Aa": ["Texto sin formato"],
"pSimwP": ["Nombre nuevo para la versión de ", ["editor"]],
"pTPqMK": ["Activa o desactiva un bloque de código delimitado."],
@@ -4247,7 +4277,6 @@
"qjHMHf": ["No se pudo desactivar la sincronización — ", ["detail"]],
"qkqG0b": ["Aceptar la versión remota"],
"qlAIQ1": ["Remoto"],
- "qlnfTD": ["No se pudo cargar la imagen: ", ["errorLabel"]],
"qmL1UG": ["Subiendo de forma segura"],
"qo4zCg": ["La ruta no puede contener barras invertidas"],
"qpQwGC": ["Describe en qué estás trabajando y el agente te lo prepara."],
@@ -4288,6 +4317,7 @@
"rXz97P": ["Lista numerada de elementos."],
"rZ9HZq": ["Por hacer"],
"rZVMkf": ["Campo de reemplazo del editor visual enfocado"],
+ "radOpL": ["Imagen ", ["identity"], ". Ir a la referencia."],
"rageVb": ["HTML personalizado con panel de vista previa en vivo (iframe aislado)."],
"rbrHTd": ["Aprobado — ", ["optionName"]],
"rcJmK8": ["Convertir las ubicaciones en copias"],
@@ -4468,6 +4498,7 @@
["trashNoun"],
". ¿Quieres eliminarlo permanentemente?"
],
+ "txUHO8": [["localizedMessage"], " en la línea ", ["displayLine"]],
"tzGWeg": ["Preparando la desinstalación de OpenKnowledge"],
"tzZ6ha": ["Conectar con GitHub Enterprise Server"],
"u-9fWA": ["Consulta <0>Arquitectura</0> para ver una visión general del sistema."],
@@ -4490,7 +4521,6 @@
"uCaIdy": [
"Falta la sesión de GitHub o ha caducado. Vuelve a conectarte para reanudar la sincronización."
],
- "uCe4AX": [["0"], " en la línea ", ["displayLine"]],
"uDlyqd": [
"Documenta la arquitectura de este repositorio: crea una página general que enlace a una página por cada módulo principal describiendo sus responsabilidades y sus puntos de entrada."
],
@@ -4592,6 +4622,7 @@
"vPEyDz": ["Transcripción del agente"],
"vPF04k": ["Empezar un chat nuevo"],
"vPKX2i": ["En la aplicación (beta)"],
+ "vPLUCm": ["Falta la imagen ", ["identity"], ". Ir a la referencia."],
"vPXOUw": ["Mostrar u ocultar la vista de código"],
"vQIVHc": ["Propiedades de la carpeta"],
"vWc9a0": ["Escribe para editar; <0>⌘ Intro</0> guarda, <1>Esc</1> cancela."],
@@ -4785,6 +4816,7 @@
"xxRpzT": ["Slidev encontrado en tu sistema."],
"xzAmL_": ["Aprobado automáticamente"],
"xzktOa": ["Editar el enlace wiki"],
+ "y-LQPF": ["No se puede resolver la imagen ", ["identity"], ". Ir a la referencia."],
"y1eoq1": ["Copiar enlace"],
"y1t8bQ": ["Secciones de ajustes"],
"y3aU20": ["Guardar los cambios"],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 2b3845cba..44b368325 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} actúa sin preguntar — OpenKnowledge no puede añadirle solicitude
msgid "{0} added, {1} removed"
msgstr "{0} añadidos, {1} eliminados"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} en la línea {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# enlace} many {# enlaces} other {# enlaces}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} en la línea {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {hace # min} many {hace # min} other {hace # min}}"
@@ -2208,6 +2207,10 @@ msgstr "Buscando actualizaciones en GitHub"
msgid "Checking GitHub connection..."
msgstr "Comprobando la conexión con GitHub..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "Comprobando enlaces"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "Extrayendo archivos"
@@ -5057,6 +5060,10 @@ msgstr "No se pudieron cargar los encabezados"
msgid "Failed to load hub pages"
msgstr "No se pudieron cargar las páginas índice"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "No se pudieron cargar los archivos locales"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "No se pudieron cargar las páginas huérfanas"
@@ -5284,6 +5291,10 @@ msgstr "Campos"
msgid "File"
msgstr "Archivo"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "Archivo {identity}. Ir a la referencia."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "El archivo ya existe"
@@ -6034,6 +6045,10 @@ msgstr "¿Qué te parece OpenKnowledge?"
msgid "How does sharing work?"
msgstr "¿Cómo funciona compartir?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "Cómo se notifican los documentos, archivos e imágenes locales del proyecto que faltan en Problemas, los diagnósticos del editor, las auditorías y las herramientas de agentes."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "Cómo hacer push manualmente"
@@ -6051,10 +6066,6 @@ msgstr "Cómo configurarlo"
msgid "How to set up {0} (opens in browser)"
msgstr "Cómo configurar {0} (se abre en el navegador)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Cómo se informa de los enlaces wiki sin resolver en el panel Problemas, en las auditorías y en las herramientas de agente."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "Cómo aparecen los hallazgos de validación en el proyecto. Estas opciones se guardan en config.yml y se comparten con todos los colaboradores mediante git."
@@ -6110,13 +6121,33 @@ msgstr "Patrones de exclusión"
msgid "Ignore patterns (raw text)"
msgstr "Patrones de exclusión (texto sin formato)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "Imagen {identity}. Ir a la referencia."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "No se pudo mostrar la imagen"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "No se pudo cargar la imagen"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "No se pudo mostrar la imagen: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "No se pudo cargar la imagen: {errorLabel}"
+msgid "Image not found"
+msgstr "No se encontró la imagen"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "No se encontró la imagen: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "El destino de la imagen «{shown}» no se pudo resolver como un archivo local del proyecto."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "El destino de la imagen «{shown}» no corresponde a un archivo existente."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "El enlace está listo, pero no se pudo copiar al portapapeles."
msgid "Link target"
msgstr "Destino del enlace"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "El destino del enlace «{shown}» no se pudo resolver como un destino local del proyecto."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "El destino del enlace «{shown}» no corresponde a un documento existente."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "El destino del enlace «{shown}» no corresponde a un archivo existente."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "Enlaza el texto seleccionado o edita el enlace bajo el cursor."
@@ -6729,6 +6772,14 @@ msgstr "Enlaza a una página o a una URL externa."
msgid "Link URL"
msgstr "URL del enlace"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "La validación de enlaces no está disponible."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "La validación de enlaces no está disponible. Se muestran los últimos problemas conocidos."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "La respuesta del grafo de enlaces no tenía la forma esperada."
@@ -6925,6 +6976,14 @@ msgstr "No se pudieron borrar los datos locales de colaboración de \"{docName}\
msgid "Local commits are keeping this copy from updating"
msgstr "Hay commits locales que impiden actualizar esta copia"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "Los detalles de los archivos locales aún no están disponibles."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "Archivos locales"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "Ruta local"
@@ -7101,10 +7160,22 @@ msgstr "Origen del espejo <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "Origen del espejo <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "Ausente"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "Faltaba una función"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "Falta el archivo {identity}. Ir a la referencia."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "Falta la imagen {identity}. Ir a la referencia."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "Página inexistente: haz clic para crearla"
@@ -8021,10 +8092,9 @@ msgstr "Lista numerada de elementos."
msgid "Object"
msgstr "Objeto"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "Apariciones de {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "Apariciones de {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "Esta página todavía no existe. Ábrela para crearla en el editor y con
msgid "This page doesn't link to anything yet."
msgstr "Esta página todavía no enlaza a nada."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "Esta página no hace referencia a ningún archivo o imagen local."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "Esta ruta está en un volumen externo (/Volumes/...). OpenKnowledge perderá la pista de los archivos cuando se expulse la unidad."
@@ -12868,6 +12942,18 @@ msgstr "Enlace no reconocido"
msgid "Unrecognized wiki link"
msgstr "Enlace wiki no reconocido"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "Sin resolver"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "No se puede resolver el archivo {identity}. Ir a la referencia."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "No se puede resolver la imagen {identity}. Ir a la referencia."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "Al día"
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 5bc78f2cb..556699cac 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -188,6 +188,7 @@
"1njn7W": ["Clair"],
"1nke1r": ["Ouvrir ", ["0"], " sur GitHub (s'ouvre dans un nouvel onglet)"],
"1oSHI0": ["Impossible d'installer ", ["skillName"], " : ", ["0"]],
+ "1pdLQw": ["Image introuvable"],
"1qpGKz": [
"Impossible d’enregistrer les modifications. Essayez à nouveau de modifier une couleur."
],
@@ -197,6 +198,7 @@
"Impossible de démarrer la synchronisation. Vérifiez votre connexion, puis réessayez."
],
"1vn0CI": ["Réponse du serveur invalide"],
+ "1xui0Q": ["Échec du chargement des fichiers locaux"],
"2277Tu": ["Réduire le graphe"],
"237hSL": ["Terminé"],
"253MN6": ["Impossible d'envoyer vos commentaires — veuillez réessayer."],
@@ -534,6 +536,7 @@
"6HCOwA": ["Échec de l'ouverture."],
"6KCH4m": ["Fichiers masqués"],
"6KXnz5": ["Vous pouvez restaurer ce fichier depuis la corbeille."],
+ "6LJJ1v": ["Fichier ", ["identity"], ". Accéder à la référence."],
"6LbUG7": ["Le dépôt est privé et votre compte GitHub n'y a pas accès."],
"6Mbe-P": [
"Décrivez ce qu'elle doit faire, ou ajoutez-en une vous-même. OpenKnowledge regroupe vos compétences au même endroit, les versionne, et les installe dans des agents comme Claude, Codex et Cursor."
@@ -1166,7 +1169,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens utilisés"],
"EQXPXf": ["Défiler jusqu'à la fin"],
"ETyvvg": ["Aucune langue correspondante."],
- "EUiJEM": ["Occurrences de ", ["0"]],
"EWCJFu": [["target"], " créé"],
"EWPtMO": ["Code"],
"EWX92Z": ["Réduire Demander à l'IA"],
@@ -1511,6 +1513,9 @@
"IgN3LY": ["Sur le texte sélectionné dans <0>", ["address"], "</0>"],
"IgTwLt": ["Ouvre ce document dans l'éditeur et réduit le graphe."],
"Ik-gP0": ["Titre de niveau ", ["level"], " : ", ["text"]],
+ "IoHQYP": [
+ "La validation des liens est indisponible. Affichage des derniers problèmes connus."
+ ],
"Iq8zdU": ["Fermer le terminal"],
"IrB5AK": [
"Le nettoyage côté serveur a échoué pour ",
@@ -1727,6 +1732,7 @@
"Lm3r51": ["Slidev n'a pas pu afficher ce document."],
"LnVIW4": ["Échec du démarrage de la connexion — réessayez"],
"LpB85N": ["Simple"],
+ "Lrsl_h": ["Fichier ", ["identity"], " manquant. Accéder à la référence."],
"LtI9AS": ["Propriétaire"],
"LtSYdi": ["Afficher dans le Finder"],
"LtiJ5c": ["Compétence de projet"],
@@ -1841,9 +1847,6 @@
"Quand vous survolez un lien externe, son URL est envoyée au site de destination pour récupérer les métadonnées d'aperçu de la page — une requête par lien prévisualisé."
],
"MysZUL": ["Connexion à ", ["agentName"], "…"],
- "N-IonL": [
- "Comment les liens wiki non résolus sont signalés dans le panneau Problèmes, les audits et les outils d'agent."
- ],
"N1KkEO": ["Aller au dernier onglet"],
"N1YYa7": ["Chargement de l'image"],
"N1mdmS": ["Ce fichier ne peut pas être ouvert dans l'éditeur de texte."],
@@ -2322,6 +2325,7 @@
"U2Kx6T": ["Fermer tous les onglets non épinglés"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["Guide complet"],
+ "U3RIJu": ["Fichiers locaux"],
"U4nTfu": ["Activer Suivre"],
"U5Spo9": ["Le répertoire de contenu doit se trouver dans le projet"],
"U6wmNc": ["Synchronisation en pause"],
@@ -2457,6 +2461,7 @@
"VNNRfN": ["définir comme source"],
"VNgKZz": ["Paramètres avancés"],
"VTulZj": ["Ouvrir dans un worktree"],
+ "VU3Nrn": ["Manquant"],
"VUijjF": ["Intègre une image avec un texte alternatif facultatif."],
"VVRrPk": [["0"], " ne propose aucun paramètre à ajuster"],
"VXGFMg": ["Annuler ou rétablir dans un champ de code"],
@@ -2465,6 +2470,7 @@
"VZSBXL": [
"Le classement sémantique s'active la première fois qu'un agent lance une recherche."
],
+ "VZg6Gn": ["Impossible d'afficher l'image : ", ["errorLabel"]],
"V_6bJ4": [
"Les paramètres du terminal ne sont pas encore chargés — réessayez dans un instant."
],
@@ -2509,12 +2515,18 @@
],
"W3Tsgy": ["Détecté dans ", ["0"]],
"W5A0Ly": ["Une erreur inattendue s'est produite."],
+ "W5qdI_": [
+ "La cible de l’image « ",
+ ["shown"],
+ " » n’a pas pu être résolue en tant que fichier local au projet."
+ ],
"W7XJN4": [
"Impossible d'imbriquer les projets. Un projet OpenKnowledge existe déjà dans <0>",
["rootPath"],
"</0>. Choisissez un emplacement en dehors, ou ouvrez plutôt ce projet."
],
"W8vpBM": ["pack de démarrage"],
+ "W9NSe0": ["Vérification des liens"],
"W9_Bub": ["Les modifications locales chevauchent la synchronisation entrante"],
"WBNpt9": ["Impossible de lire ce thème (", ["0"], ")"],
"WFEbV1": [
@@ -2577,11 +2589,13 @@
"X8kjQX": ["Se réauthentifier auprès de GitHub"],
"X9VpsP": ["Chargement du contenu du dossier"],
"XAyxsa": ["Extraire une branche distante"],
+ "XBBZnv": ["La cible du lien « ", ["shown"], " » ne correspond à aucun document existant."],
"XBgr2S": ["Copier ici"],
"XDzAnp": ["S'ouvre dans un nouvel onglet"],
"XFpEgc": [
"Choisissez quels agents apparaissent dans les menus d'agents de l'application, comme Ask AI, Open with AI et le bouton + de nouveau chat. Désactivez un agent pour le masquer de tous ces menus."
],
+ "XGKy1z": ["Impossible d'afficher l'image"],
"XH30C4": ["document"],
"XIltnd": ["Une compétence nommée « ", ["trimmed"], " » existe déjà ici"],
"XJOV1Y": ["Activité"],
@@ -2599,6 +2613,7 @@
"XW18jo": ["La réponse des titres de page ne correspond pas au schéma de succès"],
"XWEqQj": [["days"], "j"],
"XXA1b_": [["componentLabel"], " (vide)"],
+ "XYZ7tp": ["Non résolu"],
"XYlJJT": ["Configuration en cours"],
"XZkdtg": ["Changer de branche"],
"XcGbim": ["Afficher les fichiers masqués"],
@@ -2713,6 +2728,7 @@
],
"Y_GpJd": ["La demande de téléchargement de ", ["0"], " a expiré."],
"Y_ZQ6l": ["Installation de ", ["agentName"], "…"],
+ "Y_iImT": ["Fichier ", ["identity"], " impossible à résoudre. Accéder à la référence."],
"Y_kL7X": ["Personnalisez l'apparence et le comportement de l'éditeur."],
"Ya3PlJ": ["Autorisation requise"],
"YaeyFh": [
@@ -2843,6 +2859,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Occurrences de ", ["localizedFirstMessage"]],
"_DwR-n": ["Création…"],
"_FLBbi": [["sizeText"], " · secrets masqués · vidage de plantage non masqué"],
"_GRWOJ": ["Changer de fournisseur d'embeddings ?"],
@@ -3017,6 +3034,11 @@
" » avant la reconnexion."
],
"bnOTEz": ["Récupération…"],
+ "bpMVIA": [
+ "La cible du lien « ",
+ ["shown"],
+ " » n’a pas pu être résolue en tant que cible locale au projet."
+ ],
"bpytj4": ["Déplacer vers ", ["0"]],
"brCtGB": ["Historique indisponible"],
"buNXgr": [
@@ -3303,6 +3325,7 @@
"fJgQHX": ["Échec de la création du fichier"],
"fMsFdZ": ["Impossible d'enregistrer le réglage de mise à jour automatique : ", ["0"]],
"fNr-MX": ["Désactiver la recherche sémantique"],
+ "fOzzSV": ["La cible du lien « ", ["shown"], " » ne correspond à aucun fichier existant."],
"fR-Kdc": ["(niveau projet uniquement)"],
"fRVBiq": [
"Ajoute la télémétrie, l'état du serveur et les informations d'exécution lorsqu'elles sont disponibles. Les identifiants sont toujours supprimés ; les noms de documents, s'ils sont inclus, apparaissent en clair (non masqués)."
@@ -3352,6 +3375,7 @@
"<0>Vous avez autre chose à ajouter ?</0> Écrivez à <1/> en mentionnant votre référence."
],
"fxbCNQ": ["Synchronisé. Le lien est à jour."],
+ "g-dkjJ": ["Les détails des fichiers locaux ne sont pas encore disponibles."],
"g12y1g": ["YAML non valide"],
"g1ZTh_": [
[
@@ -3446,6 +3470,7 @@
"gmJ0An": ["Échec de l'ouverture du dossier."],
"goO4Ll": ["Barre d'état de l'éditeur"],
"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"], "."],
"gtEbeW": ["Surlignage"],
"gtGQ9S": ["Démarrer ", ["agentName"], ", ", ["hint"]],
@@ -3580,6 +3605,7 @@
"iRdfLr": ["Instance de développement : ", ["label"]],
"iSLIjg": ["Connecter"],
"iSQTsg": ["Liste numérotée"],
+ "iSWh95": ["La cible de l’image « ", ["shown"], " » ne correspond à aucun fichier existant."],
"iSnkwB": ["Échec de l'ouverture du projet cloné."],
"iTylMl": ["Modèles"],
"iUwpZI": ["Pas d'espaces — utilisez <0>-</0> à la place."],
@@ -3622,6 +3648,9 @@
"Le <0>type</0> que reçoit chaque document créé à partir de ce modèle (par ex. <1>research-note</1>). Garde les nouveaux documents conformes à l'Open Knowledge Format."
],
"iqIDv4": ["État de synchronisation indisponible"],
+ "iqr14Z": [
+ "Comment les documents, fichiers et images locaux au projet manquants sont signalés dans Problèmes, les diagnostics de l’éditeur, les audits et les outils d’agent."
+ ],
"iqugog": ["Échec de l'initialisation : ", ["errorDetail"]],
"irFGwu": ["Liste des modèles"],
"irrm_E": ["Retirer la sélection"],
@@ -3731,6 +3760,7 @@
"Insère une référence de note de bas de page et l'ébauche de définition correspondante."
],
"kGp168": ["Impossible de préparer ce projet pour la publication."],
+ "kI5pWt": ["Image introuvable : ", ["errorLabel"]],
"kKw0H3": [
"Vous avez modifié cette compétence en local et la source a de nouveaux changements. Prendre la version amont remplace la vôtre ; vos modifications restent récupérables dans l'historique des versions."
],
@@ -4007,7 +4037,6 @@
"nCzR-G": ["Copier le code ", ["userCode"]],
"nDT8qt": [["0"], " initialisé mais impossible à ouvrir."],
"nG-XA9": ["Le texte ancré a disparu. Vous pouvez le replacer sur un texte sélectionné."],
- "nL-HHD": ["Échec du chargement de l’image"],
"nMSYz5": [
"Ce chemin se trouve sur un volume externe (/Volumes/...). OpenKnowledge perdra la trace des fichiers lorsque le disque sera éjecté."
],
@@ -4150,6 +4179,7 @@
"pFRz_E": ["Ne pas inclure ces commentaires dans ce message"],
"pFagOn": ["Édition de la source"],
"pHYP6v": ["Ouvrez <0>Personnaliser</0> dans la barre latérale <1/> <2>Compétences</2>."],
+ "pJ7XCo": ["Cette page ne référence aucun fichier ou image local."],
"pOo4Aa": ["Texte brut"],
"pSimwP": ["Nouveau nom pour la version ", ["editor"]],
"pTPqMK": ["Bascule un bloc de code délimité."],
@@ -4302,7 +4332,6 @@
"qjHMHf": ["Échec de la désactivation de la synchronisation — ", ["detail"]],
"qkqG0b": ["Prendre la version amont"],
"qlAIQ1": ["Distant"],
- "qlnfTD": ["Échec du chargement de l’image : ", ["errorLabel"]],
"qmL1UG": ["Envoi sécurisé"],
"qo4zCg": ["Le chemin ne peut pas contenir d'antislash"],
"qpQwGC": ["Décrivez ce sur quoi vous travaillez et l'agent le met en place pour vous."],
@@ -4347,6 +4376,7 @@
"rXz97P": ["Liste numérotée d'éléments."],
"rZ9HZq": ["À faire"],
"rZVMkf": ["Champ de remplacement de l'éditeur visuel actif"],
+ "radOpL": ["Image ", ["identity"], ". Accéder à la référence."],
"rageVb": ["HTML personnalisé avec un volet d'aperçu en direct (iframe en bac à sable)."],
"rbrHTd": ["Approuvé — ", ["optionName"]],
"rcJmK8": ["Convertir les emplacements en copies"],
@@ -4526,6 +4556,7 @@
["trashNoun"],
". Voulez-vous le supprimer définitivement ?"
],
+ "txUHO8": [["localizedMessage"], " à la ligne ", ["displayLine"]],
"tzGWeg": ["Préparation de la désinstallation d'OpenKnowledge"],
"tzZ6ha": ["Se connecter à GitHub Enterprise Server"],
"u-9fWA": ["Voir <0>Architecture</0> pour la vue d'ensemble du système."],
@@ -4548,7 +4579,6 @@
"uCaIdy": [
"La connexion GitHub est absente ou expirée. Reconnectez-vous pour reprendre la synchronisation."
],
- "uCe4AX": [["0"], " à la ligne ", ["displayLine"]],
"uDlyqd": [
"Documente l'architecture de ce dépôt : crée une page de synthèse qui renvoie vers une page par module principal décrivant ses responsabilités et ses points d'entrée."
],
@@ -4650,6 +4680,7 @@
"vPEyDz": ["Transcription de l'agent"],
"vPF04k": ["Démarrer une nouvelle discussion"],
"vPKX2i": ["Dans l'application (bêta)"],
+ "vPLUCm": ["Image ", ["identity"], " manquante. Accéder à la référence."],
"vPXOUw": ["Basculer l'affichage de la source"],
"vQIVHc": ["Propriétés du dossier"],
"vWc9a0": ["Saisissez pour modifier ; <0>⌘ Entrée</0> enregistre, <1>Échap</1> annule."],
@@ -4843,6 +4874,7 @@
"xxRpzT": ["Slidev trouvé sur votre système."],
"xzAmL_": ["Approuvé automatiquement"],
"xzktOa": ["Modifier le lien wiki"],
+ "y-LQPF": ["Image ", ["identity"], " impossible à résoudre. Accéder à la référence."],
"y1eoq1": ["Copier le lien"],
"y1t8bQ": ["Sections des paramètres"],
"y3aU20": ["Enregistrer les modifications"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 63f8df6c0..3b0ac12f2 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} agit sans demander — OpenKnowledge ne peut pas lui ajouter de dema
msgid "{0} added, {1} removed"
msgstr "{0} ajouté(s), {1} retiré(s)"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} à la ligne {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# lien} many {# liens} other {# liens}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle} : {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} à la ligne {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {il y a # min} many {il y a # min} other {il y a # min}}"
@@ -2208,6 +2207,10 @@ msgstr "Recherche de mises à jour sur GitHub"
msgid "Checking GitHub connection..."
msgstr "Vérification de la connexion GitHub…"
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "Vérification des liens"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "Extraction des fichiers"
@@ -5057,6 +5060,10 @@ msgstr "Échec du chargement des titres"
msgid "Failed to load hub pages"
msgstr "Échec du chargement des pages pivots"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "Échec du chargement des fichiers locaux"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "Échec du chargement des pages orphelines"
@@ -5284,6 +5291,10 @@ msgstr "Champs"
msgid "File"
msgstr "Fichier"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "Fichier {identity}. Accéder à la référence."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "Le fichier existe déjà"
@@ -6034,6 +6045,10 @@ msgstr "Que pensez-vous d'OpenKnowledge ?"
msgid "How does sharing work?"
msgstr "Comment fonctionne le partage ?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "Comment les documents, fichiers et images locaux au projet manquants sont signalés dans Problèmes, les diagnostics de l’éditeur, les audits et les outils d’agent."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "Comment pousser manuellement"
@@ -6051,10 +6066,6 @@ msgstr "Comment configurer"
msgid "How to set up {0} (opens in browser)"
msgstr "Comment configurer {0} (s'ouvre dans le navigateur)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Comment les liens wiki non résolus sont signalés dans le panneau Problèmes, les audits et les outils d'agent."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "Comment les résultats de validation apparaissent dans le projet. Ces choix sont validés dans config.yml et partagés avec tous les collaborateurs via git."
@@ -6110,13 +6121,33 @@ msgstr "Motifs d'exclusion"
msgid "Ignore patterns (raw text)"
msgstr "Motifs d'exclusion (texte brut)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "Image {identity}. Accéder à la référence."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "Impossible d'afficher l'image"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "Échec du chargement de l’image"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "Impossible d'afficher l'image : {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "Échec du chargement de l’image : {errorLabel}"
+msgid "Image not found"
+msgstr "Image introuvable"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "Image introuvable : {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "La cible de l’image « {shown} » n’a pas pu être résolue en tant que fichier local au projet."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "La cible de l’image « {shown} » ne correspond à aucun fichier existant."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "Le lien est prêt, mais n'a pas pu être copié dans le presse-papiers."
msgid "Link target"
msgstr "Cible du lien"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "La cible du lien « {shown} » n’a pas pu être résolue en tant que cible locale au projet."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "La cible du lien « {shown} » ne correspond à aucun document existant."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "La cible du lien « {shown} » ne correspond à aucun fichier existant."
+
#: src/lib/keyboard-shortcuts.ts
msgid "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."
@@ -6729,6 +6772,14 @@ msgstr "Lien vers une page ou une URL externe."
msgid "Link URL"
msgstr "URL du lien"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "La validation des liens est indisponible."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "La validation des liens est indisponible. Affichage des derniers problèmes connus."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "La réponse du graphe de liens ne correspond pas à la forme attendue."
@@ -6925,6 +6976,14 @@ msgstr "Les données de collaboration locales de « {docName} » n'ont pas pu ê
msgid "Local commits are keeping this copy from updating"
msgstr "Des commits locaux empêchent cette copie de se mettre à jour"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "Les détails des fichiers locaux ne sont pas encore disponibles."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "Fichiers locaux"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "Chemin local"
@@ -7101,10 +7160,22 @@ msgstr "Source du miroir <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "Source du miroir <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "Manquant"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "Une fonctionnalité manquante"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "Fichier {identity} manquant. Accéder à la référence."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "Image {identity} manquante. Accéder à la référence."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "Page manquante — cliquez pour la créer"
@@ -8021,10 +8092,9 @@ msgstr "Liste numérotée d'éléments."
msgid "Object"
msgstr "Objet"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "Occurrences de {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "Occurrences de {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "Cette page n'existe pas encore. Ouvrez-la pour la créer dans l'éditeur
msgid "This page doesn't link to anything yet."
msgstr "Cette page ne renvoie encore vers rien."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "Cette page ne référence aucun fichier ou image local."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "Ce chemin se trouve sur un volume externe (/Volumes/...). OpenKnowledge perdra la trace des fichiers lorsque le disque sera éjecté."
@@ -12868,6 +12942,18 @@ msgstr "Lien non reconnu"
msgid "Unrecognized wiki link"
msgstr "Lien wiki non reconnu"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "Non résolu"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "Fichier {identity} impossible à résoudre. Accéder à la référence."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "Image {identity} impossible à résoudre. Accéder à la référence."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "À jour"
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 7ecf03acc..1496384b4 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -158,11 +158,13 @@
"1njn7W": ["हल्का"],
"1nke1r": [["0"], " को GitHub पर खोलें (नए टैब में खुलता है)"],
"1oSHI0": [["skillName"], " इंस्टॉल नहीं की जा सकी: ", ["0"]],
+ "1pdLQw": ["छवि नहीं मिली"],
"1qpGKz": ["बदलाव सहेजे नहीं जा सके। किसी रंग को फिर से संपादित करें।"],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["अस्वीकारें"],
"1u-mAI": ["सिंक शुरू नहीं किया जा सका। अपना कनेक्शन जाँचें, फिर कोशिश करें।"],
"1vn0CI": ["सर्वर की प्रतिक्रिया अमान्य है"],
+ "1xui0Q": ["स्थानीय फ़ाइलें लोड करने में विफल"],
"2277Tu": ["ग्राफ़ समेटें"],
"237hSL": ["समाप्त"],
"253MN6": ["आपकी टिप्पणियाँ नहीं भेजी जा सकीं — कृपया फिर कोशिश करें।"],
@@ -432,6 +434,7 @@
"6HCOwA": ["खोलने में विफल।"],
"6KCH4m": ["छिपी हुई फ़ाइलें"],
"6KXnz5": ["आप इस फ़ाइल को ट्रैश से पुनर्स्थापित कर सकते हैं।"],
+ "6LJJ1v": ["फ़ाइल ", ["identity"], "। संदर्भ पर जाएँ।"],
"6LbUG7": ["रिपॉज़िटरी निजी है और आपके GitHub खाते की उस तक पहुँच नहीं है।"],
"6Mbe-P": [
"बताएँ कि इसे क्या करना चाहिए, या ख़ुद एक जोड़ें। OpenKnowledge आपकी स्किल एक ही जगह रखता है, उनके संस्करण सँभालता है, और उन्हें Claude, Codex और Cursor जैसे एजेंट में इंस्टॉल करता है।"
@@ -947,7 +950,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " टोकन उपयोग में"],
"EQXPXf": ["अंत तक स्क्रॉल करें"],
"ETyvvg": ["कोई भाषा मेल नहीं खाती।"],
- "EUiJEM": [["0"], " की घटनाएँ"],
"EWCJFu": [["target"], " बनाया गया"],
"EWPtMO": ["कोड"],
"EWX92Z": ["Ask AI समेटें"],
@@ -1228,6 +1230,7 @@
"IgN3LY": ["<0>", ["address"], "</0> में चयनित पाठ पर"],
"IgTwLt": ["इस दस्तावेज़ को संपादक में खोलें और ग्राफ़ समेटें।"],
"Ik-gP0": ["शीर्षक H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["लिंक सत्यापन उपलब्ध नहीं है। पिछली ज्ञात समस्याएँ दिखाई जा रही हैं।"],
"Iq8zdU": ["टर्मिनल बंद करें"],
"IrB5AK": [
["failedCount", "plural", { "one": ["#", " आइटम"], "other": ["#", " आइटम"] }],
@@ -1415,6 +1418,7 @@
"Lm3r51": ["Slidev इस दस्तावेज़ को रेंडर नहीं कर सका।"],
"LnVIW4": ["साइन-इन शुरू करने में विफल — फिर कोशिश करें"],
"LpB85N": ["सादा"],
+ "Lrsl_h": ["गुम फ़ाइल ", ["identity"], "। संदर्भ पर जाएँ।"],
"LtI9AS": ["स्वामी"],
"LtSYdi": ["Finder में दिखाएँ"],
"LtiJ5c": ["प्रोजेक्ट स्किल"],
@@ -1513,7 +1517,6 @@
"जब आप किसी बाहरी लिंक पर माउस ले जाते हैं, तो पेज के पूर्वावलोकन का मेटाडेटा लाने के लिए उसका URL गंतव्य साइट को भेजा जाता है — हर पूर्वावलोकित लिंक के लिए एक अनुरोध।"
],
"MysZUL": [["agentName"], " से जोड़ा जा रहा है…"],
- "N-IonL": ["Problems पैनल, ऑडिट और एजेंट टूल में अनसुलझे विकी लिंक कैसे बताए जाते हैं।"],
"N1KkEO": ["अंतिम टैब पर जाएँ"],
"N1YYa7": ["छवि लोड हो रही है"],
"N1mdmS": ["यह फ़ाइल पाठ संपादक में नहीं खोली जा सकती।"],
@@ -1936,6 +1939,7 @@
"U2Kx6T": ["सभी अनपिन किए हुए बंद करें"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["पूरी मार्गदर्शिका"],
+ "U3RIJu": ["स्थानीय फ़ाइलें"],
"U4nTfu": ["Follow सक्षम करें"],
"U5Spo9": ["सामग्री निर्देशिका प्रोजेक्ट के भीतर होनी चाहिए"],
"U6wmNc": ["सिंक रुका हुआ"],
@@ -2049,12 +2053,14 @@
"VNNRfN": ["स्रोत बनाएँ"],
"VNgKZz": ["उन्नत सेटिंग"],
"VTulZj": ["वर्कट्री में खोलें"],
+ "VU3Nrn": ["अनुपस्थित"],
"VUijjF": ["वैकल्पिक वैकल्पिक-पाठ के साथ एक छवि एम्बेड करें।"],
"VVRrPk": [["0"], " समायोजित करने के लिए कोई सेटिंग नहीं देता"],
"VXGFMg": ["कोड फ़ील्ड में पूर्ववत या पुनः करें"],
"VYd_YA": ["डिस्क से कोई मौजूदा प्रोजेक्ट फ़ोल्डर खोलें।"],
"VZGh8G": ["स्रोत की श्रेणियाँ मोड़ें, खोलें, सब मोड़ें, या सब खोलें।"],
"VZSBXL": ["अर्थ-आधारित क्रम पहली बार तब सक्रिय होता है जब कोई एजेंट खोज चलाता है।"],
+ "VZg6Gn": ["छवि दिखाई नहीं जा सकी: ", ["errorLabel"]],
"V_6bJ4": ["टर्मिनल सेटिंग अभी लोड नहीं हुईं — कुछ देर बाद फिर कोशिश करें।"],
"V_DjMe": ["रेंडर त्रुटि"],
"V_wltx": ["इस टेम्पलेट के लिए एक शीर्षक डालें।"],
@@ -2079,12 +2085,14 @@
"W1qRuM": ["यह दस्तावेज़ पहले से ही संपादक में सक्रिय है। ग्राफ़ समेटने के लिए Open का उपयोग करें।"],
"W3Tsgy": [["0"], " में पाया गया"],
"W5A0Ly": ["एक अप्रत्याशित त्रुटि हुई।"],
+ "W5qdI_": ["चित्र लक्ष्य \"", ["shown"], "\" को प्रोजेक्ट की स्थानीय फ़ाइल के रूप में हल नहीं किया जा सका।"],
"W7XJN4": [
"प्रोजेक्ट नेस्ट नहीं कर सकते। <0>",
["rootPath"],
"</0> पर पहले से एक OpenKnowledge प्रोजेक्ट मौजूद है। उसके बाहर कोई स्थान चुनें, या उसी प्रोजेक्ट को खोलें।"
],
"W8vpBM": ["स्टार्टर पैक"],
+ "W9NSe0": ["लिंक की जाँच की जा रही है"],
"W9_Bub": ["स्थानीय बदलाव आने वाले सिंक से टकराते हैं"],
"WBNpt9": ["यह थीम पढ़ी नहीं जा सकी (", ["0"], ")"],
"WFEbV1": ["संपादक में सामान्य markdown समस्याएँ चिह्नित करें। <0>markdownlint<1/></0> द्वारा संचालित।"],
@@ -2145,11 +2153,13 @@
"X8kjQX": ["GitHub के साथ फिर से प्रमाणित करें"],
"X9VpsP": ["फ़ोल्डर की सामग्री लोड हो रही है"],
"XAyxsa": ["रिमोट ब्रांच चेक आउट करें"],
+ "XBBZnv": ["लिंक लक्ष्य \"", ["shown"], "\" किसी मौजूदा दस्तावेज़ पर हल नहीं होता।"],
"XBgr2S": ["यहाँ कॉपी करें"],
"XDzAnp": ["नए टैब में खुलता है"],
"XFpEgc": [
"चुनें कि ऐप के एजेंट मेनू में कौन से एजेंट दिखें, जैसे Ask AI, Open with AI और + नई चैट बटन। किसी एजेंट को बंद करने पर वह इन सभी से छिप जाएगा।"
],
+ "XGKy1z": ["छवि दिखाई नहीं जा सकी"],
"XH30C4": ["दस्तावेज़"],
"XIltnd": ["\"", ["trimmed"], "\" नाम की एक स्किल यहाँ पहले से मौजूद है"],
"XJOV1Y": ["गतिविधि"],
@@ -2167,6 +2177,7 @@
"XW18jo": ["पेज शीर्षकों की प्रतिक्रिया सफलता स्कीमा से मेल नहीं खाई"],
"XWEqQj": [["days"], "दि"],
"XXA1b_": [["componentLabel"], " (खाली)"],
+ "XYZ7tp": ["अनसुलझा"],
"XYlJJT": ["सेट अप किया जा रहा है"],
"XZkdtg": ["ब्रांच बदलें"],
"XcGbim": ["छिपी हुई फ़ाइलें दिखाएँ"],
@@ -2258,6 +2269,7 @@
"YW7Q86": ["खोज सेटिंग अभी लोड नहीं हुई — कुछ देर बाद फिर कोशिश करें"],
"Y_GpJd": [["0"], " के डाउनलोड अनुरोध का समय समाप्त हो गया।"],
"Y_ZQ6l": [["agentName"], " इंस्टॉल किया जा रहा है…"],
+ "Y_iImT": ["हल न की जा सकने वाली फ़ाइल ", ["identity"], "। संदर्भ पर जाएँ।"],
"Y_kL7X": ["संपादक कैसा दिखे और कैसे काम करे यह अपने अनुसार तय करें।"],
"Ya3PlJ": ["अनुमति आवश्यक है"],
"YaeyFh": ["खींचने पर आपकी स्थानीय फ़ाइलों के बिना कमिट किए संपादन मिट सकते हैं।"],
@@ -2369,6 +2381,7 @@
["currentLabel"],
"</1> पर हैं।"
],
+ "_Bix3-": [["localizedFirstMessage"], " की घटनाएँ"],
"_DwR-n": ["बनाया जा रहा है…"],
"_FLBbi": [["sizeText"], " · गोपनीय जानकारी हटाई गई · क्रैश डंप से नहीं हटाई गई"],
"_GRWOJ": ["एम्बेडिंग प्रदाता बदलें?"],
@@ -2519,6 +2532,7 @@
"blFttG": ["प्रोजेक्ट खोजें"],
"bmC18N": ["फिर से जुड़ने से पहले \"", ["docName"], "\" का स्थानीय सहयोग डेटा साफ़ किया जा रहा है।"],
"bnOTEz": ["लाया जा रहा है…"],
+ "bpMVIA": ["लिंक लक्ष्य \"", ["shown"], "\" को प्रोजेक्ट के स्थानीय लक्ष्य के रूप में हल नहीं किया जा सका।"],
"bpytj4": [["0"], " में ले जाएँ"],
"brCtGB": ["इतिहास अनुपलब्ध"],
"buNXgr": ["अपनी जगह बनाए रखते हुए दृश्य और स्रोत संपादकों के बीच बदलें।"],
@@ -2735,6 +2749,7 @@
"fJgQHX": ["फ़ाइल बनाने में विफल"],
"fMsFdZ": ["स्वत: अपडेट सेटिंग नहीं सहेजी जा सकी: ", ["0"]],
"fNr-MX": ["अर्थ-आधारित खोज अक्षम करें"],
+ "fOzzSV": ["लिंक लक्ष्य \"", ["shown"], "\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"],
"fR-Kdc": ["(केवल प्रोजेक्ट स्तर)"],
"fRVBiq": [
"उपलब्ध होने पर टेलीमेट्री, सर्वर स्थिति और रनटाइम जानकारी जोड़ता है। क्रेडेंशियल हमेशा हटा दिए जाते हैं; दस्तावेज़ों के नाम, यदि शामिल हों, सादे पाठ में दिखते हैं (हटाए नहीं जाते)।"
@@ -2772,6 +2787,7 @@
"fwrPh4": ["कृपया एक मान्य ईमेल डालें।"],
"fxJk_6": ["<0>और कुछ जोड़ना है?</0> <1/> पर लिखें और अपने संदर्भ का उल्लेख करें।"],
"fxbCNQ": ["सिंक हो गया। लिंक अद्यतित है।"],
+ "g-dkjJ": ["स्थानीय फ़ाइल विवरण अभी उपलब्ध नहीं हैं।"],
"g12y1g": ["अमान्य YAML"],
"g1ZTh_": [
[
@@ -2843,6 +2859,7 @@
"gmJ0An": ["फ़ोल्डर खोलने में विफल।"],
"goO4Ll": ["संपादक स्थिति पट्टी"],
"gp3I7-": ["सिंक करने से पहले, git कमिट के लिए अपनी पहचान सेट करें:"],
+ "gpbKxw": ["लिंक सत्यापन उपलब्ध नहीं है।"],
"gqk-3R": [["0"], " को ", ["destination"], " में ले जाया गया।"],
"gtEbeW": ["उभारें"],
"gtGQ9S": [["agentName"], " शुरू करें, ", ["hint"]],
@@ -2960,6 +2977,7 @@
"iRdfLr": ["डेव इंस्टेंस: ", ["label"]],
"iSLIjg": ["जोड़ें"],
"iSQTsg": ["क्रमित सूची"],
+ "iSWh95": ["चित्र लक्ष्य \"", ["shown"], "\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"],
"iSnkwB": ["क्लोन किया गया प्रोजेक्ट खोलने में विफल।"],
"iTylMl": ["टेम्पलेट"],
"iUwpZI": ["कोई रिक्त स्थान नहीं — इसके बजाय <0>-</0> का उपयोग करें।"],
@@ -2995,6 +3013,9 @@
"वह <0>type</0> जो इस टेम्पलेट से बने हर दस्तावेज़ को मिलता है (जैसे <1>research-note</1>)। नए दस्तावेज़ों को Open Knowledge Format के अनुरूप रखता है।"
],
"iqIDv4": ["सिंक स्थिति अनुपलब्ध"],
+ "iqr14Z": [
+ "गायब प्रोजेक्ट-स्थानीय दस्तावेज़ों, फ़ाइलों और इमेज को समस्याएँ, एडिटर डायग्नोस्टिक्स, ऑडिट और एजेंट टूल में कैसे रिपोर्ट किया जाता है।"
+ ],
"iqugog": ["आरंभ विफल: ", ["errorDetail"]],
"irFGwu": ["टेम्पलेट सूची"],
"irrm_E": ["चयन हटाएँ"],
@@ -3098,6 +3119,7 @@
"kCqCyf": ["CodeMirror का lint निदान पैनल खोलें।"],
"kFLlsI": ["एक फ़ुटनोट संदर्भ + उससे मेल खाती परिभाषा का ढाँचा डालें।"],
"kGp168": ["इस प्रोजेक्ट को प्रकाशन के लिए तैयार नहीं किया जा सका।"],
+ "kI5pWt": ["छवि नहीं मिली: ", ["errorLabel"]],
"kKw0H3": [
"आपने इस स्किल को स्थानीय रूप से संपादित किया है और स्रोत में नए बदलाव हैं। अपस्ट्रीम वाला लेने पर आपका संस्करण बदल जाता है; आपके संपादन संस्करण इतिहास में पुनर्प्राप्त किए जा सकते हैं।"
],
@@ -3329,7 +3351,6 @@
"nCzR-G": ["कोड ", ["userCode"], " कॉपी करें"],
"nDT8qt": [["0"], " आरंभ किया गया पर उसे खोला नहीं जा सका।"],
"nG-XA9": ["एंकर किया गया पाठ चला गया है। आप इसे चयनित पाठ पर फिर से रख सकते हैं।"],
- "nL-HHD": ["छवि लोड नहीं हो सकी"],
"nMSYz5": [
"यह पथ किसी बाहरी वॉल्यूम (/Volumes/…) पर है। ड्राइव निकलने पर OpenKnowledge फ़ाइलों का पता खो देगा।"
],
@@ -3463,6 +3484,7 @@
"pFRz_E": ["इन टिप्पणियों को इस संदेश से बाहर रखें"],
"pFagOn": ["स्रोत संपादन"],
"pHYP6v": ["साइडबार में <0>Customize</0> <1/> <2>Skills</2> खोलें।"],
+ "pJ7XCo": ["यह पेज किसी स्थानीय फ़ाइल या छवि को संदर्भित नहीं करता।"],
"pOo4Aa": ["सादा टेक्स्ट"],
"pSimwP": [["editor"], " संस्करण के लिए नया नाम"],
"pTPqMK": ["बाड़बंद कोड ब्लॉक चालू या बंद करें।"],
@@ -3567,7 +3589,6 @@
"qjHMHf": ["सिंक अक्षम करने में विफल — ", ["detail"]],
"qkqG0b": ["अपस्ट्रीम वाला लें"],
"qlAIQ1": ["रिमोट"],
- "qlnfTD": ["छवि लोड नहीं हो सकी: ", ["errorLabel"]],
"qmL1UG": ["सुरक्षित रूप से अपलोड किया जा रहा है"],
"qo4zCg": ["पथ में बैकस्लैश नहीं हो सकते"],
"qpQwGC": ["बताएँ कि आप किस पर काम कर रहे हैं और एजेंट आपके लिए इसे सेट अप कर देगा।"],
@@ -3602,6 +3623,7 @@
"rXz97P": ["आइटम की क्रमांकित सूची।"],
"rZ9HZq": ["करना है"],
"rZVMkf": ["दृश्य संपादक का बदलें इनपुट फ़ोकस में"],
+ "radOpL": ["चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],
"rageVb": ["लाइव पूर्वावलोकन पैनल वाला कस्टम HTML (सैंडबॉक्स किया गया iframe)।"],
"rbrHTd": ["स्वीकृत — ", ["optionName"]],
"rcJmK8": ["स्थानों को प्रतियों में बदलें"],
@@ -3758,6 +3780,7 @@
["trashNoun"],
" में नहीं ले जाया जा सका। क्या आप इसके बजाय स्थायी रूप से हटाना चाहते हैं?"
],
+ "txUHO8": [["displayLine"], " पंक्ति पर ", ["localizedMessage"]],
"tzGWeg": ["OpenKnowledge हटाने की तैयारी"],
"tzZ6ha": ["GitHub Enterprise Server से जोड़ें"],
"u-9fWA": ["सिस्टम के सिंहावलोकन के लिए <0>Architecture</0> देखें।"],
@@ -3774,7 +3797,6 @@
"uCaIdy": [
"GitHub साइन-इन अनुपस्थित है या उसकी अवधि समाप्त हो चुकी है। सिंक फिर से शुरू करने के लिए दोबारा जुड़ें।"
],
- "uCe4AX": ["पंक्ति ", ["displayLine"], " पर ", ["0"]],
"uDlyqd": [
"इस रिपॉज़िटरी की संरचना का दस्तावेज़ीकरण करें: एक सिंहावलोकन पेज बनाएँ जो हर प्रमुख मॉड्यूल के पेज से जुड़ता हो और उसकी ज़िम्मेदारियाँ तथा प्रवेश बिंदु बताता हो।"
],
@@ -3861,6 +3883,7 @@
"vPEyDz": ["एजेंट प्रतिलेख"],
"vPF04k": ["नई चैट शुरू करें"],
"vPKX2i": ["ऐप में (बीटा)"],
+ "vPLUCm": ["गुम चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],
"vPXOUw": ["स्रोत दृश्य चालू या बंद करें"],
"vQIVHc": ["फ़ोल्डर प्रॉपर्टी"],
"vWc9a0": ["संपादित करने के लिए लिखें; <0>⌘ Enter</0> सहेजता है, <1>Esc</1> रद्द करता है।"],
@@ -4020,6 +4043,7 @@
"xxRpzT": ["आपके सिस्टम पर Slidev मिला।"],
"xzAmL_": ["स्वत: स्वीकृत"],
"xzktOa": ["विकी लिंक संपादित करें"],
+ "y-LQPF": ["हल न की जा सकने वाला चित्र ", ["identity"], "। संदर्भ पर जाएँ।"],
"y1eoq1": ["लिंक कॉपी करें"],
"y1t8bQ": ["सेटिंग अनुभाग"],
"y3aU20": ["बदलाव सहेजें"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 4bdcbf798..945a78444 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} बिना पूछे काम करता है — OpenKnow
msgid "{0} added, {1} removed"
msgstr "{0} जोड़े गए, {1} हटाए गए"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "पंक्ति {displayLine} पर {0}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# लिंक} other {# लिंक}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{displayLine} पंक्ति पर {localizedMessage}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {# मिनट पहले} other {# मिनट पहले}}"
@@ -2204,6 +2203,10 @@ msgstr "GitHub पर अपडेट देखे जा रहे हैं"
msgid "Checking GitHub connection..."
msgstr "GitHub कनेक्शन जाँचा जा रहा है…"
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "लिंक की जाँच की जा रही है"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "फ़ाइलें चेक आउट की जा रही हैं"
@@ -5053,6 +5056,10 @@ msgstr "शीर्षक लोड करने में विफल"
msgid "Failed to load hub pages"
msgstr "हब पेज लोड करने में विफल"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "स्थानीय फ़ाइलें लोड करने में विफल"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "अनाथ पेज लोड करने में विफल"
@@ -5280,6 +5287,10 @@ msgstr "फ़ील्ड"
msgid "File"
msgstr "फ़ाइल"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "फ़ाइल {identity}। संदर्भ पर जाएँ।"
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "फ़ाइल पहले से मौजूद है"
@@ -6030,6 +6041,10 @@ msgstr "आपको OpenKnowledge कैसा लगा?"
msgid "How does sharing work?"
msgstr "साझाकरण कैसे काम करता है?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "गायब प्रोजेक्ट-स्थानीय दस्तावेज़ों, फ़ाइलों और इमेज को समस्याएँ, एडिटर डायग्नोस्टिक्स, ऑडिट और एजेंट टूल में कैसे रिपोर्ट किया जाता है।"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "हाथ से कैसे भेजें"
@@ -6047,10 +6062,6 @@ msgstr "सेट अप कैसे करें"
msgid "How to set up {0} (opens in browser)"
msgstr "{0} कैसे सेट अप करें (ब्राउज़र में खुलता है)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Problems पैनल, ऑडिट और एजेंट टूल में अनसुलझे विकी लिंक कैसे बताए जाते हैं।"
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "सत्यापन के निष्कर्ष पूरे प्रोजेक्ट में कैसे सामने आते हैं। ये चुनाव config.yml में कमिट होते हैं और git के ज़रिए हर सहयोगी के साथ साझा किए जाते हैं।"
@@ -6106,13 +6117,33 @@ msgstr "अनदेखा करने के पैटर्न"
msgid "Ignore patterns (raw text)"
msgstr "अनदेखा करने के पैटर्न (कच्चा पाठ)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "चित्र {identity}। संदर्भ पर जाएँ।"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "छवि दिखाई नहीं जा सकी"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "छवि लोड नहीं हो सकी"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "छवि दिखाई नहीं जा सकी: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "छवि लोड नहीं हो सकी: {errorLabel}"
+msgid "Image not found"
+msgstr "छवि नहीं मिली"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "छवि नहीं मिली: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "चित्र लक्ष्य \"{shown}\" को प्रोजेक्ट की स्थानीय फ़ाइल के रूप में हल नहीं किया जा सका।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "चित्र लक्ष्य \"{shown}\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6713,6 +6744,18 @@ msgstr "लिंक तैयार है, लेकिन क्लिपब
msgid "Link target"
msgstr "लिंक लक्ष्य"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "लिंक लक्ष्य \"{shown}\" को प्रोजेक्ट के स्थानीय लक्ष्य के रूप में हल नहीं किया जा सका।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "लिंक लक्ष्य \"{shown}\" किसी मौजूदा दस्तावेज़ पर हल नहीं होता।"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "लिंक लक्ष्य \"{shown}\" किसी मौजूदा फ़ाइल पर हल नहीं होता।"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "चयनित पाठ को लिंक करें, या कर्सर के नीचे वाला लिंक संपादित करें।"
@@ -6725,6 +6768,14 @@ msgstr "किसी पेज या बाहरी URL से लिंक
msgid "Link URL"
msgstr "लिंक URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "लिंक सत्यापन उपलब्ध नहीं है।"
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "लिंक सत्यापन उपलब्ध नहीं है। पिछली ज्ञात समस्याएँ दिखाई जा रही हैं।"
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "लिंक-ग्राफ़ की प्रतिक्रिया अपेक्षित आकार से मेल नहीं खाई।"
@@ -6921,6 +6972,14 @@ msgstr "\"{docName}\" का स्थानीय सहयोग डेटा
msgid "Local commits are keeping this copy from updating"
msgstr "स्थानीय कमिट इस प्रति को अद्यतित होने से रोक रहे हैं"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "स्थानीय फ़ाइल विवरण अभी उपलब्ध नहीं हैं।"
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "स्थानीय फ़ाइलें"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "स्थानीय पथ"
@@ -7097,10 +7156,22 @@ msgstr "मिरर स्रोत <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "मिरर स्रोत <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "अनुपस्थित"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "एक सुविधा अनुपस्थित"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "गुम फ़ाइल {identity}। संदर्भ पर जाएँ।"
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "गुम चित्र {identity}। संदर्भ पर जाएँ।"
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "अनुपस्थित पेज — बनाने के लिए क्लिक करें"
@@ -8017,10 +8088,9 @@ msgstr "आइटम की क्रमांकित सूची।"
msgid "Object"
msgstr "ऑब्जेक्ट"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "{0} की घटनाएँ"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "{localizedFirstMessage} की घटनाएँ"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12325,6 +12395,10 @@ msgstr "यह पेज अभी मौजूद नहीं है। सं
msgid "This page doesn't link to anything yet."
msgstr "यह पेज अभी किसी से लिंक नहीं करता।"
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "यह पेज किसी स्थानीय फ़ाइल या छवि को संदर्भित नहीं करता।"
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "यह पथ किसी बाहरी वॉल्यूम (/Volumes/…) पर है। ड्राइव निकलने पर OpenKnowledge फ़ाइलों का पता खो देगा।"
@@ -12864,6 +12938,18 @@ msgstr "अपरिचित लिंक"
msgid "Unrecognized wiki link"
msgstr "अपरिचित विकी लिंक"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "अनसुलझा"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "हल न की जा सकने वाली फ़ाइल {identity}। संदर्भ पर जाएँ।"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "हल न की जा सकने वाला चित्र {identity}। संदर्भ पर जाएँ।"
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "अद्यतित"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 5365510d5..4e44d162a 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -158,11 +158,13 @@
"1njn7W": ["Terang"],
"1nke1r": ["Buka ", ["0"], " di GitHub (terbuka di tab baru)"],
"1oSHI0": [["skillName"], " tidak bisa dipasang: ", ["0"]],
+ "1pdLQw": ["Gambar tidak ditemukan"],
"1qpGKz": ["Perubahan tidak dapat disimpan. Coba sunting warna lagi."],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["Tolak"],
"1u-mAI": ["Sinkronisasinya tidak bisa dimulai. Periksa koneksi Anda, lalu coba lagi."],
"1vn0CI": ["Respons server tidak valid"],
+ "1xui0Q": ["Gagal memuat berkas lokal"],
"2277Tu": ["Ciutkan graf"],
"237hSL": ["Berakhir"],
"253MN6": ["Komentar Anda tidak bisa dikirim — silakan coba lagi."],
@@ -446,6 +448,7 @@
"6HCOwA": ["Gagal membuka."],
"6KCH4m": ["Berkas tersembunyi"],
"6KXnz5": ["Anda dapat memulihkan berkas ini dari Tempat Sampah."],
+ "6LJJ1v": ["File ", ["identity"], ". Buka referensi."],
"6LbUG7": ["Repositorinya bersifat pribadi dan akun GitHub Anda tidak punya akses ke sana."],
"6Mbe-P": [
"Jelaskan apa yang harus dilakukannya, atau tambahkan sendiri. OpenKnowledge menyimpan keterampilan Anda di satu tempat, memberinya versi, dan memasangnya ke agen seperti Claude, Codex, dan Cursor."
@@ -969,7 +972,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " token terpakai"],
"EQXPXf": ["Gulir ke akhir"],
"ETyvvg": ["Tidak ada bahasa yang cocok."],
- "EUiJEM": ["Kemunculan ", ["0"]],
"EWCJFu": [["target"], " dibuat"],
"EWPtMO": ["Kode"],
"EWX92Z": ["Ciutkan Tanya AI"],
@@ -1284,6 +1286,7 @@
"IgN3LY": ["Pada teks terpilih di <0>", ["address"], "</0>"],
"IgTwLt": ["Membuka dokumen ini di penyunting dan menciutkan graf."],
"Ik-gP0": ["Judul H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["Validasi tautan tidak tersedia. Menampilkan masalah terakhir yang diketahui."],
"Iq8zdU": ["Tutup terminal"],
"IrB5AK": [
"Pembersihan di sisi server gagal untuk ",
@@ -1476,6 +1479,7 @@
"Lm3r51": ["Slidev tidak dapat merender dokumen ini."],
"LnVIW4": ["Gagal memulai proses masuk — coba lagi"],
"LpB85N": ["Polos"],
+ "Lrsl_h": ["File ", ["identity"], " tidak ditemukan. Buka referensi."],
"LtI9AS": ["Pemilik"],
"LtSYdi": ["Tampilkan di Finder"],
"LtiJ5c": ["Keterampilan proyek"],
@@ -1572,9 +1576,6 @@
"Ketika Anda mengarahkan kursor ke tautan eksternal, URL-nya dikirim ke situs tujuan untuk mengambil metadata pratinjau halaman itu — satu permintaan per tautan yang dipratinjau."
],
"MysZUL": ["Menghubungkan ke ", ["agentName"], "…"],
- "N-IonL": [
- "Bagaimana tautan wiki yang tidak terselesaikan dilaporkan di panel Masalah, audit, dan alat agen."
- ],
"N1KkEO": ["Lompat ke tab terakhir"],
"N1YYa7": ["Memuat gambar"],
"N1mdmS": ["Berkas ini tidak bisa dibuka di penyunting teks."],
@@ -2009,6 +2010,7 @@
"U2Kx6T": ["Tutup semua yang tidak disematkan"],
"U2pMtf": ["nama-tag"],
"U3IvM5": ["Panduan lengkap"],
+ "U3RIJu": ["Berkas lokal"],
"U4nTfu": ["Aktifkan Ikuti"],
"U5Spo9": ["Direktori konten harus berada di dalam proyek"],
"U6wmNc": ["Sinkronisasi dijeda"],
@@ -2128,6 +2130,7 @@
"VNNRfN": ["jadikan sumber"],
"VNgKZz": ["Pengaturan lanjutan"],
"VTulZj": ["Buka di worktree"],
+ "VU3Nrn": ["Hilang"],
"VUijjF": ["Menyematkan gambar dengan teks alternatif opsional."],
"VVRrPk": [["0"], " tidak menawarkan pengaturan untuk disesuaikan"],
"VXGFMg": ["Batalkan atau ulangi di bidang kode"],
@@ -2138,6 +2141,7 @@
"VZSBXL": [
"Pemeringkatan semantik aktif pertama kali ketika sebuah agen menjalankan pencarian."
],
+ "VZg6Gn": ["Gambar tidak dapat ditampilkan: ", ["errorLabel"]],
"V_6bJ4": ["Pengaturan terminal belum dimuat — coba lagi sebentar."],
"V_DjMe": ["galat render"],
"V_wltx": ["Masukkan judul untuk templat ini."],
@@ -2166,12 +2170,18 @@
"W1qRuM": ["Dokumen ini sudah aktif di penyunting. Gunakan Buka untuk menciutkan graf."],
"W3Tsgy": ["Terdeteksi di ", ["0"]],
"W5A0Ly": ["Terjadi galat yang tidak terduga."],
+ "W5qdI_": [
+ "Target gambar \"",
+ ["shown"],
+ "\" tidak dapat dicocokkan dengan file lokal proyek."
+ ],
"W7XJN4": [
"Proyek tidak bisa disarangkan. Sudah ada proyek OpenKnowledge di <0>",
["rootPath"],
"</0>. Pilih lokasi di luarnya, atau buka proyek itu saja."
],
"W8vpBM": ["paket awal"],
+ "W9NSe0": ["Memeriksa tautan"],
"W9_Bub": ["Perubahan lokal bertumpang tindih dengan sinkronisasi yang masuk"],
"WBNpt9": ["Tema ini tidak dapat dibaca (", ["0"], ")"],
"WFEbV1": [
@@ -2234,11 +2244,13 @@
"X8kjQX": ["Autentikasi ulang dengan GitHub"],
"X9VpsP": ["Memuat isi folder"],
"XAyxsa": ["Ambil cabang remote"],
+ "XBBZnv": ["Target tautan \"", ["shown"], "\" tidak merujuk ke dokumen yang ada."],
"XBgr2S": ["Salin ke sini"],
"XDzAnp": ["Terbuka di tab baru"],
"XFpEgc": [
"Pilih agen mana yang muncul di menu agen di seluruh aplikasi, seperti Ask AI, Open with AI, dan tombol + obrolan baru. Nonaktifkan agen untuk menyembunyikannya dari semuanya."
],
+ "XGKy1z": ["Gambar tidak dapat ditampilkan"],
"XH30C4": ["dokumen"],
"XIltnd": ["Keterampilan bernama \"", ["trimmed"], "\" sudah ada di sini"],
"XJOV1Y": ["Aktivitas"],
@@ -2256,6 +2268,7 @@
"XW18jo": ["Respons judul halaman tidak sesuai skema sukses"],
"XWEqQj": [["days"], "h"],
"XXA1b_": [["componentLabel"], " (kosong)"],
+ "XYZ7tp": ["Tidak terselesaikan"],
"XYlJJT": ["Menyiapkan"],
"XZkdtg": ["Ganti cabang"],
"XcGbim": ["Tampilkan berkas tersembunyi"],
@@ -2343,6 +2356,7 @@
"YW7Q86": ["Pengaturan pencarian belum dimuat — coba lagi sebentar"],
"Y_GpJd": ["Permintaan unduhan ", ["0"], " kehabisan waktu."],
"Y_ZQ6l": ["Memasang ", ["agentName"], "…"],
+ "Y_iImT": ["File ", ["identity"], " tidak dapat ditentukan. Buka referensi."],
"Y_kL7X": ["Sesuaikan tampilan dan perilaku penyunting."],
"Ya3PlJ": ["Perlu izin"],
"YaeyFh": ["Pull bisa menimpa suntingan yang belum di-commit di berkas lokal Anda."],
@@ -2457,6 +2471,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Kemunculan ", ["localizedFirstMessage"]],
"_DwR-n": ["Membuat…"],
"_FLBbi": [["sizeText"], " · rahasia disunting · crash dump tidak disunting"],
"_GRWOJ": ["Ganti penyedia embedding?"],
@@ -2619,6 +2634,11 @@
"\" sebelum menyambung ulang."
],
"bnOTEz": ["Mengambil…"],
+ "bpMVIA": [
+ "Target tautan \"",
+ ["shown"],
+ "\" tidak dapat dicocokkan dengan target lokal proyek."
+ ],
"bpytj4": ["Pindahkan ke ", ["0"]],
"brCtGB": ["Riwayat tidak tersedia"],
"buNXgr": ["Beralih antara penyunting visual dan sumber, tanpa kehilangan posisi Anda."],
@@ -2851,6 +2871,7 @@
"fJgQHX": ["Gagal membuat berkas"],
"fMsFdZ": ["Pengaturan pembaruan otomatis tidak bisa disimpan: ", ["0"]],
"fNr-MX": ["Nonaktifkan pencarian semantik"],
+ "fOzzSV": ["Target tautan \"", ["shown"], "\" tidak merujuk ke file yang ada."],
"fR-Kdc": ["(hanya tingkat proyek)"],
"fRVBiq": [
"Menambahkan telemetri, keadaan server, dan info runtime bila tersedia. Kredensial selalu dihapus; nama dokumen, jika disertakan, muncul sebagai teks biasa (tidak disunting)."
@@ -2888,6 +2909,7 @@
"fwrPh4": ["Silakan masukkan surel yang valid."],
"fxJk_6": ["<0>Ada yang ingin ditambahkan?</0> Tulis ke <1/> dan sebutkan referensi Anda."],
"fxbCNQ": ["Tersinkron. Tautannya sudah mutakhir."],
+ "g-dkjJ": ["Detail berkas lokal belum tersedia."],
"g12y1g": ["YAML tidak valid"],
"g1ZTh_": [
[
@@ -2966,6 +2988,7 @@
"gmJ0An": ["Gagal membuka folder."],
"goO4Ll": ["Bilah status penyunting"],
"gp3I7-": ["Sebelum menyinkronkan, setel identitas Anda untuk commit git:"],
+ "gpbKxw": ["Validasi tautan tidak tersedia."],
"gqk-3R": [["0"], " dipindahkan ke ", ["destination"], "."],
"gtEbeW": ["Sorotan"],
"gtGQ9S": ["Mulai ", ["agentName"], ", ", ["hint"]],
@@ -3099,6 +3122,7 @@
"iRdfLr": ["Instans pengembangan: ", ["label"]],
"iSLIjg": ["Hubungkan"],
"iSQTsg": ["Daftar berurut"],
+ "iSWh95": ["Target gambar \"", ["shown"], "\" tidak merujuk ke file yang ada."],
"iSnkwB": ["Gagal membuka proyek hasil kloning."],
"iTylMl": ["Templat"],
"iUwpZI": ["Tanpa spasi — gunakan <0>-</0> saja."],
@@ -3135,6 +3159,9 @@
"<0>type</0> yang didapat setiap dokumen yang dibuat dari templat ini (mis. <1>research-note</1>). Menjaga dokumen baru tetap sesuai Open Knowledge Format."
],
"iqIDv4": ["Status sinkronisasi tidak tersedia"],
+ "iqr14Z": [
+ "Cara dokumen, file, dan gambar lokal proyek yang hilang dilaporkan di Masalah, diagnostik editor, audit, dan alat agen."
+ ],
"iqugog": ["Inisialisasi gagal: ", ["errorDetail"]],
"irFGwu": ["Daftar templat"],
"irrm_E": ["Hapus pilihan"],
@@ -3242,6 +3269,7 @@
"kCqCyf": ["Membuka panel diagnostik lint CodeMirror."],
"kFLlsI": ["Menyisipkan rujukan catatan kaki + kerangka definisi yang sesuai."],
"kGp168": ["Tidak dapat menyiapkan proyek ini untuk diterbitkan."],
+ "kI5pWt": ["Gambar tidak ditemukan: ", ["errorLabel"]],
"kKw0H3": [
"Anda menyunting keterampilan ini secara lokal dan sumbernya punya perubahan baru. Mengambil versi remote akan menggantikan versi Anda; suntingan Anda tetap bisa dipulihkan lewat riwayat versi."
],
@@ -3487,7 +3515,6 @@
"nG-XA9": [
"Teks berjangkarnya sudah hilang. Anda bisa menempatkannya ulang pada teks yang dipilih."
],
- "nL-HHD": ["Gambar gagal dimuat"],
"nMSYz5": [
"Jalur ini berada di volume eksternal (/Volumes/...). OpenKnowledge akan kehilangan jejak berkasnya ketika drive itu dicabut."
],
@@ -3620,6 +3647,7 @@
"pFRz_E": ["Jangan sertakan komentar ini dalam pesan ini"],
"pFagOn": ["Penyuntingan sumber"],
"pHYP6v": ["Buka <0>Sesuaikan</0> di bilah sisi <1/> <2>Keterampilan</2>."],
+ "pJ7XCo": ["Halaman ini tidak merujuk ke berkas atau gambar lokal apa pun."],
"pOo4Aa": ["Teks biasa"],
"pSimwP": ["Nama baru untuk versi ", ["editor"]],
"pTPqMK": ["Menyalakan atau mematikan blok kode berpagar."],
@@ -3722,7 +3750,6 @@
"qjHMHf": ["Gagal menonaktifkan sinkronisasi — ", ["detail"]],
"qkqG0b": ["Ambil versi remote"],
"qlAIQ1": ["Remote"],
- "qlnfTD": ["Gambar gagal dimuat: ", ["errorLabel"]],
"qmL1UG": ["Mengunggah dengan aman"],
"qo4zCg": ["Jalur tidak boleh memuat garis miring terbalik"],
"qpQwGC": ["Jelaskan apa yang sedang Anda kerjakan dan agennya akan menyiapkannya untuk Anda."],
@@ -3763,6 +3790,7 @@
"rXz97P": ["Daftar item bernomor."],
"rZ9HZq": ["Akan dikerjakan"],
"rZVMkf": ["Bidang penggantian penyunting visual sedang difokus"],
+ "radOpL": ["Gambar ", ["identity"], ". Buka referensi."],
"rageVb": ["HTML khusus dengan panel pratinjau langsung (iframe tersekat)."],
"rbrHTd": ["Disetujui — ", ["optionName"]],
"rcJmK8": ["Ubah lokasi menjadi salinan"],
@@ -3929,6 +3957,7 @@
["trashNoun"],
". Apakah Anda ingin menghapus permanen saja?"
],
+ "txUHO8": [["localizedMessage"], " pada baris ", ["displayLine"]],
"tzGWeg": ["Bersiap mencopot OpenKnowledge"],
"tzZ6ha": ["Hubungkan ke GitHub Enterprise Server"],
"u-9fWA": ["Lihat <0>Arsitektur</0> untuk ikhtisar sistemnya."],
@@ -3945,7 +3974,6 @@
"uCaIdy": [
"Status masuk GitHub tidak ada atau kedaluwarsa. Sambungkan ulang untuk melanjutkan sinkronisasi."
],
- "uCe4AX": [["0"], " di baris ", ["displayLine"]],
"uDlyqd": [
"Dokumentasikan arsitektur repo ini: buat halaman ikhtisar yang menaut ke satu halaman per modul utama yang menjelaskan tanggung jawab dan titik masuknya."
],
@@ -4019,6 +4047,7 @@
"vPEyDz": ["Transkrip agen"],
"vPF04k": ["Mulai obrolan baru"],
"vPKX2i": ["Di aplikasi (beta)"],
+ "vPLUCm": ["Gambar ", ["identity"], " tidak ditemukan. Buka referensi."],
"vPXOUw": ["Tampilkan atau sembunyikan tampilan sumber"],
"vQIVHc": ["Properti folder"],
"vWc9a0": ["Ketik untuk menyunting; <0>⌘ Enter</0> menyimpan, <1>Esc</1> membatalkan."],
@@ -4192,6 +4221,7 @@
"xxRpzT": ["Slidev ditemukan di sistem Anda."],
"xzAmL_": ["Disetujui otomatis"],
"xzktOa": ["Sunting tautan wiki"],
+ "y-LQPF": ["Gambar ", ["identity"], " tidak dapat ditentukan. Buka referensi."],
"y1eoq1": ["Salin tautan"],
"y1t8bQ": ["Bagian pengaturan"],
"y3aU20": ["Simpan perubahan"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index cdb60bb13..86c386c21 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} bertindak tanpa bertanya — OpenKnowledge tidak dapat menambahkan p
msgid "{0} added, {1} removed"
msgstr "{0} ditambahkan, {1} dihapus"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} di baris {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, other {# tautan}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} pada baris {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, other {# mnt lalu}}"
@@ -2204,6 +2203,10 @@ msgstr "Memeriksa pembaruan di GitHub"
msgid "Checking GitHub connection..."
msgstr "Memeriksa koneksi GitHub..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "Memeriksa tautan"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "Mengambil berkas"
@@ -5053,6 +5056,10 @@ msgstr "Gagal memuat judul"
msgid "Failed to load hub pages"
msgstr "Gagal memuat halaman pusat"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "Gagal memuat berkas lokal"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "Gagal memuat halaman yatim"
@@ -5280,6 +5287,10 @@ msgstr "Bidang"
msgid "File"
msgstr "Berkas"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "File {identity}. Buka referensi."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "Berkas sudah ada"
@@ -6030,6 +6041,10 @@ msgstr "Bagaimana pendapat Anda tentang OpenKnowledge?"
msgid "How does sharing work?"
msgstr "Bagaimana cara kerja berbagi?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "Cara dokumen, file, dan gambar lokal proyek yang hilang dilaporkan di Masalah, diagnostik editor, audit, dan alat agen."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "Cara push manual"
@@ -6047,10 +6062,6 @@ msgstr "Cara menyiapkan"
msgid "How to set up {0} (opens in browser)"
msgstr "Cara menyiapkan {0} (terbuka di peramban)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Bagaimana tautan wiki yang tidak terselesaikan dilaporkan di panel Masalah, audit, dan alat agen."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "Bagaimana temuan validasi muncul di seluruh proyek. Pilihan ini disimpan di config.yml dan dibagikan ke setiap kolaborator lewat git."
@@ -6106,13 +6117,33 @@ msgstr "Pola abaikan"
msgid "Ignore patterns (raw text)"
msgstr "Pola abaikan (teks mentah)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "Gambar {identity}. Buka referensi."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "Gambar tidak dapat ditampilkan"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "Gambar gagal dimuat"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "Gambar tidak dapat ditampilkan: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "Gambar gagal dimuat: {errorLabel}"
+msgid "Image not found"
+msgstr "Gambar tidak ditemukan"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "Gambar tidak ditemukan: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "Target gambar \"{shown}\" tidak dapat dicocokkan dengan file lokal proyek."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "Target gambar \"{shown}\" tidak merujuk ke file yang ada."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6713,6 +6744,18 @@ msgstr "Tautan siap, tetapi tidak dapat disalin ke papan klip."
msgid "Link target"
msgstr "Tujuan tautan"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "Target tautan \"{shown}\" tidak dapat dicocokkan dengan target lokal proyek."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "Target tautan \"{shown}\" tidak merujuk ke dokumen yang ada."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "Target tautan \"{shown}\" tidak merujuk ke file yang ada."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "Menautkan teks yang dipilih, atau menyunting tautan di bawah kursor."
@@ -6725,6 +6768,14 @@ msgstr "Menaut ke sebuah halaman atau URL eksternal."
msgid "Link URL"
msgstr "URL tautan"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "Validasi tautan tidak tersedia."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "Validasi tautan tidak tersedia. Menampilkan masalah terakhir yang diketahui."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "Respons graf tautan tidak sesuai bentuk yang diharapkan."
@@ -6921,6 +6972,14 @@ msgstr "Data kolaborasi lokal untuk \"{docName}\" tidak dapat dibersihkan. Muat
msgid "Local commits are keeping this copy from updating"
msgstr "Commit lokal menghalangi salinan ini diperbarui"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "Detail berkas lokal belum tersedia."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "Berkas lokal"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "Jalur lokal"
@@ -7097,10 +7156,22 @@ msgstr "Sumber cermin <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "Sumber cermin <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "Hilang"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "Ada fitur yang kurang"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "File {identity} tidak ditemukan. Buka referensi."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "Gambar {identity} tidak ditemukan. Buka referensi."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "Halaman belum ada — klik untuk membuat"
@@ -8017,10 +8088,9 @@ msgstr "Daftar item bernomor."
msgid "Object"
msgstr "Objek"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "Kemunculan {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "Kemunculan {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12325,6 +12395,10 @@ msgstr "Halaman ini belum ada. Buka untuk membuat halamannya di penyunting dan m
msgid "This page doesn't link to anything yet."
msgstr "Halaman ini belum menaut ke apa pun."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "Halaman ini tidak merujuk ke berkas atau gambar lokal apa pun."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "Jalur ini berada di volume eksternal (/Volumes/...). OpenKnowledge akan kehilangan jejak berkasnya ketika drive itu dicabut."
@@ -12864,6 +12938,18 @@ msgstr "Tautan tidak dikenali"
msgid "Unrecognized wiki link"
msgstr "Tautan wiki tidak dikenali"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "Tidak terselesaikan"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "File {identity} tidak dapat ditentukan. Buka referensi."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "Gambar {identity} tidak dapat ditentukan. Buka referensi."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "Sudah mutakhir"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 4917a2c37..7dc7ee4d4 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -160,11 +160,13 @@
"1njn7W": ["Ĺĩĝĥţ"],
"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],
"1oSHI0": ["Ćōũĺďń'ţ ĩńśţàĺĺ ", ["skillName"], ": ", ["0"]],
+ "1pdLQw": ["Ĩḿàĝē ńōţ ƒōũńď"],
"1qpGKz": ["Ćōũĺďń’ţ śàvē ćĥàńĝēś. Ţŕŷ ēďĩţĩńĝ à ćōĺōŕ àĝàĩń."],
"1ruosn": ["ŌƥēńĶńōŵĺēďĝē"],
"1t_NnN": ["ŔēĴēćţ"],
"1u-mAI": ["Ćōũĺďń'ţ śţàŕţ ţĥē śŷńć. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń, ţĥēń ŕēţŕŷ."],
"1vn0CI": ["Ĩńvàĺĩď śēŕvēŕ ŕēśƥōńśē"],
+ "1xui0Q": ["Ƒàĩĺēď ţō ĺōàď ĺōćàĺ ƒĩĺēś"],
"2277Tu": ["Ćōĺĺàƥśē ĝŕàƥĥ"],
"237hSL": ["Ēńďēď"],
"253MN6": ["Ćōũĺďń'ţ śēńď ŷōũŕ ćōḿḿēńţś — ƥĺēàśē ţŕŷ àĝàĩń."],
@@ -443,6 +445,7 @@
"6HCOwA": ["Ƒàĩĺēď ţō ōƥēń."],
"6KCH4m": ["Ĥĩďďēń ƒĩĺēś"],
"6KXnz5": ["Ŷōũ ćàń ŕēśţōŕē ţĥĩś ƒĩĺē ƒŕōḿ ţĥē Ţŕàśĥ."],
+ "6LJJ1v": ["Ƒĩĺē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"6LbUG7": ["Ţĥē ŕēƥōśĩţōŕŷ ĩś ƥŕĩvàţē àńď ŷōũŕ ĜĩţĤũƀ àććōũńţ ďōēśń'ţ ĥàvē àććēśś ţō ĩţ."],
"6Mbe-P": [
"Ďēśćŕĩƀē ŵĥàţ ĩţ śĥōũĺď ďō, ōŕ àďď ōńē ŷōũŕśēĺƒ. ŌƥēńĶńōŵĺēďĝē ķēēƥś ŷōũŕ śķĩĺĺś ĩń ōńē ƥĺàćē, vēŕśĩōńś ţĥēḿ, àńď ĩńśţàĺĺś ţĥēḿ ĩńţō àĝēńţś ĺĩķē Ćĺàũďē, Ćōďēx, àńď Ćũŕśōŕ."
@@ -982,7 +985,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " ţōķēńś ũśēď"],
"EQXPXf": ["Śćŕōĺĺ ţō ēńď"],
"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],
- "EUiJEM": ["Ōććũŕŕēńćēś ōƒ ", ["0"]],
"EWCJFu": ["Ćŕēàţēď ", ["target"]],
"EWPtMO": ["Ćōďē"],
"EWX92Z": ["Ćōĺĺàƥśē Àśķ ÀĨ"],
@@ -1278,6 +1280,7 @@
"IgN3LY": ["Ōń śēĺēćţēď ţēxţ ĩń <0>", ["address"], "</0>"],
"IgTwLt": ["Ōƥēń ţĥĩś ďōćũḿēńţ ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"Ik-gP0": ["Ĥēàďĩńĝ Ĥ", ["level"], ": ", ["text"]],
+ "IoHQYP": ["Ĺĩńķ vàĺĩďàţĩōń ĩś ũńàvàĩĺàƀĺē. Śĥōŵĩńĝ ĺàśţ ķńōŵń ƥŕōƀĺēḿś."],
"Iq8zdU": ["Ćĺōśē ţēŕḿĩńàĺ"],
"IrB5AK": [
"Śēŕvēŕ-śĩďē ćĺēàńũƥ ƒàĩĺēď ƒōŕ ",
@@ -1463,6 +1466,7 @@
"Lm3r51": ["Śĺĩďēv ćōũĺďń'ţ ŕēńďēŕ ţĥĩś ďōćũḿēńţ."],
"LnVIW4": ["Ƒàĩĺēď ţō śţàŕţ śĩĝń-ĩń — ţŕŷ àĝàĩń"],
"LpB85N": ["Ƥĺàĩń"],
+ "Lrsl_h": ["Ḿĩśśĩńĝ ƒĩĺē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"LtI9AS": ["Ōŵńēŕ"],
"LtSYdi": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ"],
"LtiJ5c": ["ƤŕōĴēćţ śķĩĺĺ"],
@@ -1567,9 +1571,6 @@
"Ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ, ĩţś ŨŔĹ ĩś śēńţ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ ţĥē ƥàĝē'ś ƥŕēvĩēŵ ḿēţàďàţà — ōńē ŕēǫũēśţ ƥēŕ ƥŕēvĩēŵēď ĺĩńķ."
],
"MysZUL": ["Ćōńńēćţĩńĝ ţō ", ["agentName"], "…"],
- "N-IonL": [
- "Ĥōŵ ũńŕēśōĺvēď ŵĩķĩ-ĺĩńķś àŕē ŕēƥōŕţēď ĩń ţĥē Ƥŕōƀĺēḿś ƥàńēĺ, àũďĩţś, àńď àĝēńţ ţōōĺś."
- ],
"N1KkEO": ["ĵũḿƥ ţō ĺàśţ ţàƀ"],
"N1YYa7": ["Ĺōàďĩńĝ ĩḿàĝē"],
"N1mdmS": ["Ţĥĩś ƒĩĺē ćàń'ţ ƀē ōƥēńēď ĩń ţĥē ţēxţ ēďĩţōŕ."],
@@ -2001,6 +2002,7 @@
"U2Kx6T": ["Ćĺōśē àĺĺ ũńƥĩńńēď"],
"U2pMtf": ["ţàĝ-ńàḿē"],
"U3IvM5": ["Ƒũĺĺ ĝũĩďē"],
+ "U3RIJu": ["Ĺōćàĺ ƒĩĺēś"],
"U4nTfu": ["Ēńàƀĺē Ƒōĺĺōŵ"],
"U5Spo9": ["Ćōńţēńţ ďĩŕēćţōŕŷ ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
"U6wmNc": ["Śŷńć ƥàũśēď"],
@@ -2120,12 +2122,14 @@
"VNNRfN": ["ḿàķē śōũŕćē"],
"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],
"VTulZj": ["Ōƥēń ĩń ŵōŕķţŕēē"],
+ "VU3Nrn": ["Ḿĩśśĩńĝ"],
"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],
"VVRrPk": [["0"], " ďōēśń'ţ ōƒƒēŕ àńŷ śēţţĩńĝś ţō àďĴũśţ"],
"VXGFMg": ["Ćōďē ƒĩēĺď ũńďō ōŕ ŕēďō"],
"VYd_YA": ["Ōƥēń àń ēxĩśţĩńĝ ƥŕōĴēćţ ƒōĺďēŕ ƒŕōḿ ďĩśķ."],
"VZGh8G": ["Ƒōĺď, ũńƒōĺď, ƒōĺď àĺĺ, ōŕ ũńƒōĺď àĺĺ śōũŕćē ŕàńĝēś."],
"VZSBXL": ["Śēḿàńţĩć ŕàńķĩńĝ àćţĩvàţēś ţĥē ƒĩŕśţ ţĩḿē àń àĝēńţ ŕũńś à śēàŕćĥ."],
+ "VZg6Gn": ["Ĩḿàĝē ćōũĺďń'ţ ƀē ďĩśƥĺàŷēď: ", ["errorLabel"]],
"V_6bJ4": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ĺōàďēď ŷēţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],
"V_DjMe": ["ŕēńďēŕ ēŕŕōŕ"],
"V_wltx": ["Ēńţēŕ à ţĩţĺē ƒōŕ ţĥĩś ţēḿƥĺàţē."],
@@ -2150,12 +2154,14 @@
"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"W3Tsgy": ["Ďēţēćţēď ĩń ", ["0"]],
"W5A0Ly": ["Àń ũńēxƥēćţēď ēŕŕōŕ ōććũŕŕēď."],
+ "W5qdI_": ["Ĩḿàĝē ţàŕĝēţ \"", ["shown"], "\" ćōũĺď ńōţ ƀē ŕēśōĺvēď ţō à ƥŕōĴēćţ-ĺōćàĺ ƒĩĺē."],
"W7XJN4": [
"Ćàń'ţ ńēśţ ƥŕōĴēćţś. Àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ àĺŕēàďŷ ēxĩśţś àţ <0>",
["rootPath"],
"</0>. Ćĥōōśē à ĺōćàţĩōń ōũţśĩďē ĩţ, ōŕ ōƥēń ţĥàţ ƥŕōĴēćţ ĩńśţēàď."
],
"W8vpBM": ["śţàŕţēŕ ƥàćķ"],
+ "W9NSe0": ["Ćĥēćķĩńĝ ĺĩńķś"],
"W9_Bub": ["Ĺōćàĺ ćĥàńĝēś ōvēŕĺàƥ ŵĩţĥ ĩńćōḿĩńĝ śŷńć"],
"WBNpt9": ["Ćōũĺďń’ţ ŕēàď ţĥĩś ţĥēḿē (", ["0"], ")"],
"WFEbV1": ["Ƒĺàĝ ćōḿḿōń ḿàŕķďōŵń ĩśśũēś ĩń ţĥē ēďĩţōŕ. Ƥōŵēŕēď ƀŷ <0>ḿàŕķďōŵńĺĩńţ<1/></0>."],
@@ -2216,11 +2222,13 @@
"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],
"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],
"XAyxsa": ["Ćĥēćķ ōũţ ŕēḿōţē ƀŕàńćĥ"],
+ "XBBZnv": ["Ĺĩńķ ţàŕĝēţ \"", ["shown"], "\" ďōēś ńōţ ŕēśōĺvē ţō àń ēxĩśţĩńĝ ďōćũḿēńţ."],
"XBgr2S": ["Ćōƥŷ ĩń"],
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XFpEgc": [
"Ćĥōōśē ŵĥĩćĥ àĝēńţś àƥƥēàŕ ĩń àĝēńţ ḿēńũś àćŕōśś ţĥē àƥƥ, śũćĥ àś Àśķ ÀĨ, Ōƥēń ŵĩţĥ ÀĨ, àńď ţĥē + ńēŵ ćĥàţ ƀũţţōń. Ţũŕń àń àĝēńţ ōƒƒ ţō ĥĩďē ĩţ ƒŕōḿ àĺĺ ōƒ ţĥēḿ."
],
+ "XGKy1z": ["Ĩḿàĝē ćōũĺďń'ţ ƀē ďĩśƥĺàŷēď"],
"XH30C4": ["ďōćũḿēńţ"],
"XIltnd": ["À śķĩĺĺ ńàḿēď \"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś ĥēŕē"],
"XJOV1Y": ["Àćţĩvĩţŷ"],
@@ -2238,6 +2246,7 @@
"XW18jo": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ śũććēśś śćĥēḿà"],
"XWEqQj": [["days"], "ď"],
"XXA1b_": [["componentLabel"], " (ēḿƥţŷ)"],
+ "XYZ7tp": ["Ũńŕēśōĺvàƀĺē"],
"XYlJJT": ["Śēţţĩńĝ ũƥ"],
"XZkdtg": ["Śŵĩţćĥ ƀŕàńćĥ"],
"XcGbim": ["Śĥōŵ ĥĩďďēń ƒĩĺēś"],
@@ -2329,6 +2338,7 @@
"YW7Q86": ["Śēàŕćĥ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"Y_GpJd": ["Ţĥē ", ["0"], " ďōŵńĺōàď ŕēǫũēśţ ţĩḿēď ōũţ."],
"Y_ZQ6l": ["Ĩńśţàĺĺĩńĝ ", ["agentName"], "…"],
+ "Y_iImT": ["Ũńŕēśōĺvàƀĺē ƒĩĺē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"Y_kL7X": ["Ćũśţōḿĩźē ĥōŵ ţĥē ēďĩţōŕ ĺōōķś àńď ƀēĥàvēś."],
"Ya3PlJ": ["Ƥēŕḿĩśśĩōń ŕēǫũĩŕēď"],
"YaeyFh": ["Ƥũĺĺś ḿàŷ ōvēŕŵŕĩţē ũńćōḿḿĩţţēď ēďĩţś ĩń ŷōũŕ ĺōćàĺ ƒĩĺēś."],
@@ -2443,6 +2453,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Ōććũŕŕēńćēś ōƒ ", ["localizedFirstMessage"]],
"_DwR-n": ["Ćŕēàţĩńĝ…"],
"_FLBbi": [["sizeText"], " · śēćŕēţś ŕēďàćţēď · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"],
"_GRWOJ": ["Ćĥàńĝē ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ?"],
@@ -2590,6 +2601,7 @@
"blFttG": ["Śēàŕćĥ ƥŕōĴēćţś"],
"bmC18N": ["Ćĺēàŕĩńĝ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"", ["docName"], "\" ƀēƒōŕē ŕēćōńńēćţĩńĝ."],
"bnOTEz": ["Ŕēţŕĩēvĩńĝ…"],
+ "bpMVIA": ["Ĺĩńķ ţàŕĝēţ \"", ["shown"], "\" ćōũĺď ńōţ ƀē ŕēśōĺvēď ţō à ƥŕōĴēćţ-ĺōćàĺ ţàŕĝēţ."],
"bpytj4": ["Ḿōvē ţō ", ["0"]],
"brCtGB": ["Ĥĩśţōŕŷ ũńàvàĩĺàƀĺē"],
"buNXgr": ["Śŵĩţćĥ ƀēţŵēēń ţĥē vĩśũàĺ àńď śōũŕćē ēďĩţōŕś, ķēēƥĩńĝ ŷōũŕ ƥĺàćē."],
@@ -2826,6 +2838,7 @@
"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],
"fMsFdZ": ["Ćōũĺďń'ţ śàvē ţĥē àũţō-ũƥďàţē śēţţĩńĝ: ", ["0"]],
"fNr-MX": ["Ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ"],
+ "fOzzSV": ["Ĺĩńķ ţàŕĝēţ \"", ["shown"], "\" ďōēś ńōţ ŕēśōĺvē ţō àń ēxĩśţĩńĝ ƒĩĺē."],
"fR-Kdc": ["(ƥŕōĴēćţ-ĺēvēĺ ōńĺŷ)"],
"fRVBiq": [
"Àďďś ţēĺēḿēţŕŷ, śēŕvēŕ śţàţē, àńď ŕũńţĩḿē ĩńƒō ŵĥēń àvàĩĺàƀĺē. Ćŕēďēńţĩàĺś àŕē àĺŵàŷś ŕēḿōvēď; ďōćũḿēńţ ńàḿēś, ĩƒ ĩńćĺũďēď, àƥƥēàŕ ĩń ćĺēàŕţēxţ (ńōţ ŕēďàćţēď)."
@@ -2861,6 +2874,7 @@
"fwrPh4": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ."],
"fxJk_6": ["<0>Ĥàvē ḿōŕē ţō àďď?</0> Ŵŕĩţē ţō <1/> àńď ḿēńţĩōń ŷōũŕ ŕēƒēŕēńćē."],
"fxbCNQ": ["Śŷńćēď. Ţĥē ĺĩńķ ĩś ũƥ ţō ďàţē."],
+ "g-dkjJ": ["Ĺōćàĺ ƒĩĺē ďēţàĩĺś àŕēń'ţ àvàĩĺàƀĺē ŷēţ."],
"g12y1g": ["Ĩńvàĺĩď ŶÀḾĹ"],
"g1ZTh_": [
[
@@ -2948,6 +2962,7 @@
"gmJ0An": ["Ƒàĩĺēď ţō ōƥēń ƒōĺďēŕ."],
"goO4Ll": ["Ēďĩţōŕ śţàţũś ƀàŕ"],
"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],
+ "gpbKxw": ["Ĺĩńķ vàĺĩďàţĩōń ĩś ũńàvàĩĺàƀĺē."],
"gqk-3R": ["Ḿōvēď ", ["0"], " ţō ", ["destination"], "."],
"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],
"gtGQ9S": ["Śţàŕţ ", ["agentName"], ", ", ["hint"]],
@@ -3066,6 +3081,7 @@
"iRdfLr": ["Ďēv ĩńśţàńćē: ", ["label"]],
"iSLIjg": ["Ćōńńēćţ"],
"iSQTsg": ["Ōŕďēŕēď ĺĩśţ"],
+ "iSWh95": ["Ĩḿàĝē ţàŕĝēţ \"", ["shown"], "\" ďōēś ńōţ ŕēśōĺvē ţō àń ēxĩśţĩńĝ ƒĩĺē."],
"iSnkwB": ["Ƒàĩĺēď ţō ōƥēń ćĺōńēď ƥŕōĴēćţ."],
"iTylMl": ["Ţēḿƥĺàţēś"],
"iUwpZI": ["Ńō śƥàćēś — ũśē <0>-</0> ĩńśţēàď."],
@@ -3104,6 +3120,9 @@
"Ţĥē <0>ţŷƥē</0> ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē ĝēţś (ē.ĝ. <1>ŕēśēàŕćĥ-ńōţē</1>). Ķēēƥś ńēŵ ďōćś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ–ćōńƒōŕḿàńţ."
],
"iqIDv4": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē"],
+ "iqr14Z": [
+ "Ĥōŵ ḿĩśśĩńĝ ƥŕōĴēćţ-ĺōćàĺ ďōćũḿēńţś, ƒĩĺēś, àńď ĩḿàĝēś àŕē ŕēƥōŕţēď ĩń Ƥŕōƀĺēḿś, ēďĩţōŕ ďĩàĝńōśţĩćś, àũďĩţś, àńď àĝēńţ ţōōĺś."
+ ],
"iqugog": ["Ĩńĩţĩàĺĩźē ƒàĩĺēď: ", ["errorDetail"]],
"irFGwu": ["Ţēḿƥĺàţē ĺĩśţ"],
"irrm_E": ["Ŕēḿōvē śēĺēćţĩōń"],
@@ -3205,6 +3224,7 @@
"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],
"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],
"kGp168": ["Ćōũĺďń'ţ ƥŕēƥàŕē ţĥĩś ƥŕōĴēćţ ƒōŕ ƥũƀĺĩśĥ."],
+ "kI5pWt": ["Ĩḿàĝē ńōţ ƒōũńď: ", ["errorLabel"]],
"kKw0H3": [
"Ŷōũ ēďĩţēď ţĥĩś śķĩĺĺ ĺōćàĺĺŷ àńď ţĥē śōũŕćē ĥàś ńēŵ ćĥàńĝēś. Ţàķĩńĝ ũƥśţŕēàḿ ŕēƥĺàćēś ŷōũŕ vēŕśĩōń; ŷōũŕ ēďĩţś śţàŷ ŕēćōvēŕàƀĺē ĩń vēŕśĩōń ĥĩśţōŕŷ."
],
@@ -3449,7 +3469,6 @@
"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
"nG-XA9": ["Ţĥē àńćĥōŕēď ţēxţ ĩś ĝōńē. Ŷōũ ćàń ŕē-ƥĺàćē ĩţ ōń śēĺēćţēď ţēxţ."],
- "nL-HHD": ["Ĩḿàĝē ƒàĩĺēď ţō ĺōàď"],
"nMSYz5": [
"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."
],
@@ -3585,6 +3604,7 @@
"pFRz_E": ["Ĺēàvē ţĥēśē ćōḿḿēńţś ōũţ ōƒ ţĥĩś ḿēśśàĝē"],
"pFagOn": ["Śōũŕćē ēďĩţĩńĝ"],
"pHYP6v": ["Ōƥēń <0>Ćũśţōḿĩźē</0> ĩń ţĥē śĩďēƀàŕ <1/> <2>Śķĩĺĺś</2>."],
+ "pJ7XCo": ["Ţĥĩś ƥàĝē ŕēƒēŕēńćēś ńō ĺōćàĺ ƒĩĺēś ōŕ ĩḿàĝēś."],
"pOo4Aa": ["Ƥĺàĩń ţēxţ"],
"pSimwP": ["Ńēŵ ńàḿē ƒōŕ ţĥē ", ["editor"], " vēŕśĩōń"],
"pTPqMK": ["Ţōĝĝĺē à ƒēńćēď ćōďē ƀĺōćķ."],
@@ -3698,7 +3718,6 @@
"qjHMHf": ["Ƒàĩĺēď ţō ďĩśàƀĺē śŷńć — ", ["detail"]],
"qkqG0b": ["Ţàķē ũƥśţŕēàḿ"],
"qlAIQ1": ["Ŕēḿōţē"],
- "qlnfTD": ["Ĩḿàĝē ƒàĩĺēď ţō ĺōàď: ", ["errorLabel"]],
"qmL1UG": ["Ũƥĺōàďĩńĝ śēćũŕēĺŷ"],
"qo4zCg": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ƀàćķśĺàśĥēś"],
"qpQwGC": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ'ŕē ŵōŕķĩńĝ ōń àńď ţĥē àĝēńţ śēţś ĩţ ũƥ ƒōŕ ŷōũ."],
@@ -3739,6 +3758,7 @@
"rXz97P": ["Ńũḿƀēŕēď ĺĩśţ ōƒ ĩţēḿś."],
"rZ9HZq": ["Ţō ďō"],
"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],
+ "radOpL": ["Ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],
"rbrHTd": ["Àƥƥŕōvēď — ", ["optionName"]],
"rcJmK8": ["Ćōńvēŕţ ĺōćàţĩōńś ţō ćōƥĩēś"],
@@ -3903,6 +3923,7 @@
["trashNoun"],
". Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"
],
+ "txUHO8": [["localizedMessage"], " àţ ĺĩńē ", ["displayLine"]],
"tzGWeg": ["Ƥŕēƥàŕĩńĝ ţō ũńĩńśţàĺĺ ŌƥēńĶńōŵĺēďĝē"],
"tzZ6ha": ["Ćōńńēćţ ţō ĜĩţĤũƀ Ēńţēŕƥŕĩśē Śēŕvēŕ"],
"u-9fWA": ["Śēē <0>Àŕćĥĩţēćţũŕē</0> ƒōŕ ţĥē śŷśţēḿ ōvēŕvĩēŵ."],
@@ -3917,7 +3938,6 @@
"uA_jXp": ["Śŵĩţćĥ àńď ũƥďàţē ƀŕàńćĥ"],
"uBAxNB": ["Ēďĩţōŕ"],
"uCaIdy": ["ĜĩţĤũƀ śĩĝń-ĩń ĩś ḿĩśśĩńĝ ōŕ ēxƥĩŕēď. Ŕēćōńńēćţ ţō ŕēśũḿē śŷńćĩńĝ."],
- "uCe4AX": [["0"], " àţ ĺĩńē ", ["displayLine"]],
"uDlyqd": [
"Ďōćũḿēńţ ţĥē àŕćĥĩţēćţũŕē ōƒ ţĥĩś ŕēƥō: ćŕēàţē àń ōvēŕvĩēŵ ƥàĝē ţĥàţ ĺĩńķś ţō à ƥàĝē ƥēŕ ḿàĴōŕ ḿōďũĺē ďēśćŕĩƀĩńĝ ĩţś ŕēśƥōńśĩƀĩĺĩţĩēś àńď ēńţŕŷ ƥōĩńţś."
],
@@ -4008,6 +4028,7 @@
"vPEyDz": ["Àĝēńţ ţŕàńśćŕĩƥţ"],
"vPF04k": ["Śţàŕţ à ńēŵ ćĥàţ"],
"vPKX2i": ["Ĩń àƥƥ (ƀēţà)"],
+ "vPLUCm": ["Ḿĩśśĩńĝ ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"vPXOUw": ["Ţōĝĝĺē śōũŕćē vĩēŵ"],
"vQIVHc": ["Ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"vWc9a0": ["Ţŷƥē ţō ēďĩţ; <0>⌘ Ēńţēŕ</0> śàvēś, <1>Ēść</1> ćàńćēĺś."],
@@ -4173,6 +4194,7 @@
"xxRpzT": ["Śĺĩďēv ƒōũńď ōń ŷōũŕ śŷśţēḿ."],
"xzAmL_": ["Àũţō-àƥƥŕōvēď"],
"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],
+ "y-LQPF": ["Ũńŕēśōĺvàƀĺē ĩḿàĝē ", ["identity"], ". Ĝō ţō ŕēƒēŕēńćē."],
"y1eoq1": ["Ćōƥŷ ĺĩńķ"],
"y1t8bQ": ["Śēţţĩńĝś śēćţĩōńś"],
"y3aU20": ["Śàvē ćĥàńĝēś"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index f05b9616c..0d6a2d4e1 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -265,11 +265,6 @@ msgstr ""
msgid "{0} added, {1} removed"
msgstr ""
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr ""
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr ""
msgid "{loadErrorTitle}: {message}"
msgstr ""
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr ""
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr ""
@@ -2204,6 +2203,10 @@ msgstr ""
msgid "Checking GitHub connection..."
msgstr ""
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr ""
@@ -5053,6 +5056,10 @@ msgstr ""
msgid "Failed to load hub pages"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr ""
@@ -5280,6 +5287,10 @@ msgstr ""
msgid "File"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr ""
@@ -6030,6 +6041,10 @@ msgstr ""
msgid "How does sharing work?"
msgstr ""
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr ""
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr ""
@@ -6047,10 +6062,6 @@ msgstr ""
msgid "How to set up {0} (opens in browser)"
msgstr ""
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr ""
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr ""
@@ -6106,12 +6117,32 @@ msgstr ""
msgid "Ignore patterns (raw text)"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr ""
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr ""
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr ""
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
+msgid "Image not found"
msgstr ""
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
+msgid "Image not found: {errorLabel}"
+msgstr ""
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr ""
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
msgstr ""
#: src/components/ImportSkillForm.tsx
@@ -6713,6 +6744,18 @@ msgstr ""
msgid "Link target"
msgstr ""
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr ""
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr ""
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr ""
@@ -6725,6 +6768,14 @@ msgstr ""
msgid "Link URL"
msgstr ""
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr ""
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr ""
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr ""
@@ -6921,6 +6972,14 @@ msgstr ""
msgid "Local commits are keeping this copy from updating"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr ""
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr ""
@@ -7097,10 +7156,22 @@ msgstr ""
msgid "Mirror source <0>api-spec</0>"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr ""
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr ""
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr ""
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr ""
@@ -8017,9 +8088,8 @@ msgstr ""
msgid "Object"
msgstr ""
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
+msgid "Occurrences of {localizedFirstMessage}"
msgstr ""
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
@@ -12325,6 +12395,10 @@ msgstr ""
msgid "This page doesn't link to anything yet."
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr ""
@@ -12864,6 +12938,18 @@ msgstr ""
msgid "Unrecognized wiki link"
msgstr ""
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr ""
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr ""
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 7bcc997f5..cb8780382 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -176,11 +176,13 @@
"1njn7W": ["Claro"],
"1nke1r": ["Abrir ", ["0"], " no GitHub (abre em uma nova aba)"],
"1oSHI0": ["Não deu para instalar ", ["skillName"], ": ", ["0"]],
+ "1pdLQw": ["Imagem não encontrada"],
"1qpGKz": ["Não foi possível salvar as alterações. Tente editar uma cor novamente."],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["Rejeitar"],
"1u-mAI": ["Não deu para iniciar a sincronização. Verifique sua conexão e tente de novo."],
"1vn0CI": ["Resposta do servidor inválida"],
+ "1xui0Q": ["Falha ao carregar os arquivos locais"],
"2277Tu": ["Recolher o grafo"],
"237hSL": ["Encerrado"],
"253MN6": ["Não deu para enviar seus comentários — tente de novo."],
@@ -510,6 +512,7 @@
"6HCOwA": ["Falha ao abrir."],
"6KCH4m": ["Arquivos ocultos"],
"6KXnz5": ["Você pode restaurar este arquivo do Lixo."],
+ "6LJJ1v": ["Arquivo ", ["identity"], ". Ir para a referência."],
"6LbUG7": ["O repositório é privado e sua conta do GitHub não tem acesso a ele."],
"6Mbe-P": [
"Descreva o que ela deve fazer, ou acrescente uma você mesmo. O OpenKnowledge guarda suas habilidades em um só lugar, versiona-as e instala-as em agentes como Claude, Codex e Cursor."
@@ -1122,7 +1125,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens usados"],
"EQXPXf": ["Rolar até o fim"],
"ETyvvg": ["Nenhum idioma corresponde."],
- "EUiJEM": ["Ocorrências de ", ["0"]],
"EWCJFu": [["target"], " criado"],
"EWPtMO": ["Código"],
"EWX92Z": ["Recolher Perguntar à IA"],
@@ -1468,6 +1470,9 @@
"IgN3LY": ["Sobre o texto selecionado em <0>", ["address"], "</0>"],
"IgTwLt": ["Abre este documento no editor e recolhe o grafo."],
"Ik-gP0": ["Título H", ["level"], ": ", ["text"]],
+ "IoHQYP": [
+ "A validação de links não está disponível. Exibindo os últimos problemas conhecidos."
+ ],
"Iq8zdU": ["Fechar terminal"],
"IrB5AK": [
"A limpeza no servidor falhou para ",
@@ -1676,6 +1681,7 @@
"Lm3r51": ["O Slidev não conseguiu renderizar este documento."],
"LnVIW4": ["Falha ao iniciar o login — tente de novo"],
"LpB85N": ["Simples"],
+ "Lrsl_h": ["O arquivo ", ["identity"], " está ausente. Ir para a referência."],
"LtI9AS": ["Dono"],
"LtSYdi": ["Mostrar no Finder"],
"LtiJ5c": ["Habilidade do projeto"],
@@ -1790,9 +1796,6 @@
"Quando você passa o cursor sobre um link externo, a URL dele é enviada ao site de destino para buscar os metadados de pré-visualização da página — uma requisição por link pré-visualizado."
],
"MysZUL": ["Conectando ao ", ["agentName"], "…"],
- "N-IonL": [
- "Como os links wiki não resolvidos são reportados no painel Problemas, nas auditorias e nas ferramentas de agente."
- ],
"N1KkEO": ["Ir para a última aba"],
"N1YYa7": ["Carregando a imagem"],
"N1mdmS": ["Não dá para abrir este arquivo no editor de texto."],
@@ -2259,6 +2262,7 @@
"U2Kx6T": ["Fechar todas as não fixadas"],
"U2pMtf": ["nome-da-tag"],
"U3IvM5": ["Guia completo"],
+ "U3RIJu": ["Arquivos locais"],
"U4nTfu": ["Ativar Acompanhar"],
"U5Spo9": ["O diretório de conteúdo precisa ficar dentro do projeto"],
"U6wmNc": ["Sincronização pausada"],
@@ -2390,12 +2394,14 @@
"VNNRfN": ["tornar fonte"],
"VNgKZz": ["Configurações avançadas"],
"VTulZj": ["Abrir em um worktree"],
+ "VU3Nrn": ["Ausente"],
"VUijjF": ["Incorpora uma imagem com texto alternativo opcional."],
"VVRrPk": [["0"], " não oferece configurações para ajustar"],
"VXGFMg": ["Desfazer ou refazer no campo de código"],
"VYd_YA": ["Abre do disco uma pasta de projeto existente."],
"VZGh8G": ["Dobra, desdobra, dobra tudo ou desdobra todos os trechos do código."],
"VZSBXL": ["A classificação semântica é ativada na primeira vez que um agente roda uma busca."],
+ "VZg6Gn": ["Não foi possível mostrar a imagem: ", ["errorLabel"]],
"V_6bJ4": ["As configurações do terminal ainda não carregaram — tente de novo em instantes."],
"V_DjMe": ["erro de renderização"],
"V_wltx": ["Digite um título para este modelo."],
@@ -2432,12 +2438,18 @@
"W1qRuM": ["Este documento já está ativo no editor. Use Abrir para recolher o grafo."],
"W3Tsgy": ["Detectado em ", ["0"]],
"W5A0Ly": ["Ocorreu um erro inesperado."],
+ "W5qdI_": [
+ "O destino da imagem \"",
+ ["shown"],
+ "\" não pôde ser resolvido como um arquivo local do projeto."
+ ],
"W7XJN4": [
"Não dá para aninhar projetos. Já existe um projeto do OpenKnowledge em <0>",
["rootPath"],
"</0>. Escolha um local fora dele ou abra aquele projeto."
],
"W8vpBM": ["pacote inicial"],
+ "W9NSe0": ["Verificando links"],
"W9_Bub": ["As alterações locais se sobrepõem à sincronização que está chegando"],
"WBNpt9": ["Não foi possível ler este tema (", ["0"], ")"],
"WFEbV1": [
@@ -2500,11 +2512,13 @@
"X8kjQX": ["Autenticar de novo no GitHub"],
"X9VpsP": ["Carregando o conteúdo da pasta"],
"XAyxsa": ["Extrair ramo remoto"],
+ "XBBZnv": ["O destino do link \"", ["shown"], "\" não corresponde a um documento existente."],
"XBgr2S": ["Copiar para cá"],
"XDzAnp": ["Abre em uma nova aba"],
"XFpEgc": [
"Escolha quais agentes aparecem nos menus de agentes do aplicativo, como Ask AI, Open with AI e o botão + de novo chat. Desative um agente para ocultá-lo de todos eles."
],
+ "XGKy1z": ["Não foi possível mostrar a imagem"],
"XH30C4": ["documento"],
"XIltnd": ["Já existe aqui uma habilidade chamada \"", ["trimmed"], "\""],
"XJOV1Y": ["Atividade"],
@@ -2522,6 +2536,7 @@
"XW18jo": ["A resposta dos títulos da página não corresponde ao esquema de sucesso"],
"XWEqQj": [["days"], "d"],
"XXA1b_": [["componentLabel"], " (vazio)"],
+ "XYZ7tp": ["Não resolvido"],
"XYlJJT": ["Configurando"],
"XZkdtg": ["Trocar de ramo"],
"XcGbim": ["Mostrar os arquivos ocultos"],
@@ -2624,6 +2639,7 @@
"YW7Q86": ["As configurações de busca ainda não carregaram — tente de novo em instantes"],
"Y_GpJd": ["A requisição de download de ", ["0"], " expirou."],
"Y_ZQ6l": ["Instalando ", ["agentName"], "…"],
+ "Y_iImT": ["Não foi possível resolver o arquivo ", ["identity"], ". Ir para a referência."],
"Y_kL7X": ["Personalize a aparência e o comportamento do editor."],
"Ya3PlJ": ["Permissão necessária"],
"YaeyFh": ["O pull pode sobrescrever edições sem commit nos seus arquivos locais."],
@@ -2752,6 +2768,7 @@
["currentLabel"],
"</1>."
],
+ "_Bix3-": ["Ocorrências de ", ["localizedFirstMessage"]],
"_DwR-n": ["Criando…"],
"_FLBbi": [["sizeText"], " · segredos ocultados · despejo de falha sem ocultação"],
"_GRWOJ": ["Trocar o provedor de embeddings?"],
@@ -2922,6 +2939,11 @@
"\" antes de reconectar."
],
"bnOTEz": ["Recuperando…"],
+ "bpMVIA": [
+ "O destino do link \"",
+ ["shown"],
+ "\" não pôde ser resolvido como um destino local do projeto."
+ ],
"bpytj4": ["Mover para ", ["0"]],
"brCtGB": ["Histórico indisponível"],
"buNXgr": ["Alterna entre o editor visual e o de código, mantendo seu lugar."],
@@ -3198,6 +3220,7 @@
"fJgQHX": ["Falha ao criar o arquivo"],
"fMsFdZ": ["Não deu para salvar a configuração de atualização automática: ", ["0"]],
"fNr-MX": ["Desativar a busca semântica"],
+ "fOzzSV": ["O destino do link \"", ["shown"], "\" não corresponde a um arquivo existente."],
"fR-Kdc": ["(somente no nível do projeto)"],
"fRVBiq": [
"Adiciona telemetria, estado do servidor e informações de execução quando disponíveis. As credenciais são sempre removidas; os nomes de documento, se incluídos, aparecem em texto simples (sem ocultação)."
@@ -3245,6 +3268,7 @@
"fwrPh4": ["Digite um e-mail válido."],
"fxJk_6": ["<0>Tem mais a acrescentar?</0> Escreva para <1/> e mencione sua referência."],
"fxbCNQ": ["Sincronizado. O link está atualizado."],
+ "g-dkjJ": ["Os detalhes dos arquivos locais ainda não estão disponíveis."],
"g12y1g": ["YAML inválido"],
"g1ZTh_": [
[
@@ -3339,6 +3363,7 @@
"gmJ0An": ["Falha ao abrir a pasta."],
"goO4Ll": ["Barra de status do editor"],
"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"], "."],
"gtEbeW": ["Destaque"],
"gtGQ9S": ["Iniciar ", ["agentName"], ", ", ["hint"]],
@@ -3471,6 +3496,7 @@
"iRdfLr": ["Instância de desenvolvimento: ", ["label"]],
"iSLIjg": ["Conectar"],
"iSQTsg": ["Lista ordenada"],
+ "iSWh95": ["O destino da imagem \"", ["shown"], "\" não corresponde a um arquivo existente."],
"iSnkwB": ["Falha ao abrir o projeto clonado."],
"iTylMl": ["Modelos"],
"iUwpZI": ["Sem espaços — use <0>-</0> no lugar."],
@@ -3513,6 +3539,9 @@
"O <0>type</0> que cada documento criado a partir deste modelo recebe (ex.: <1>research-note</1>). Mantém os novos documentos em conformidade com o Open Knowledge Format."
],
"iqIDv4": ["Status de sincronização indisponível"],
+ "iqr14Z": [
+ "Como documentos, arquivos e imagens locais do projeto ausentes são informados em Problemas, diagnósticos do editor, auditorias e ferramentas de agente."
+ ],
"iqugog": ["Falha na inicialização: ", ["errorDetail"]],
"irFGwu": ["Lista de modelos"],
"irrm_E": ["Remover a seleção"],
@@ -3618,6 +3647,7 @@
"kCqCyf": ["Abre o painel de diagnósticos de análise do CodeMirror."],
"kFLlsI": ["Insere uma referência de nota de rodapé e a definição correspondente."],
"kGp168": ["Não foi possível preparar este projeto para publicação."],
+ "kI5pWt": ["Imagem não encontrada: ", ["errorLabel"]],
"kKw0H3": [
"Você editou esta habilidade localmente e a fonte tem mudanças novas. Aceitar a versão remota substitui a sua; suas edições continuam recuperáveis no histórico de versões."
],
@@ -3890,7 +3920,6 @@
"nCzR-G": ["Copiar o código ", ["userCode"]],
"nDT8qt": [["0"], " inicializado, mas não foi possível abri-lo."],
"nG-XA9": ["O texto ancorado sumiu. Você pode reposicioná-lo em um texto selecionado."],
- "nL-HHD": ["Falha ao carregar a imagem"],
"nMSYz5": [
"Este caminho está em um volume externo (/Volumes/...). O OpenKnowledge vai perder os arquivos de vista quando a unidade for ejetada."
],
@@ -4027,6 +4056,7 @@
"pFRz_E": ["Deixar estes comentários fora desta mensagem"],
"pFagOn": ["Edição de código"],
"pHYP6v": ["Abra <0>Personalizar</0> na barra lateral <1/> <2>Habilidades</2>."],
+ "pJ7XCo": ["Esta página não faz referência a nenhum arquivo ou imagem local."],
"pOo4Aa": ["Texto simples"],
"pSimwP": ["Novo nome para a versão do ", ["editor"]],
"pTPqMK": ["Liga ou desliga um bloco de código delimitado."],
@@ -4159,7 +4189,6 @@
"qjHMHf": ["Falha ao desativar a sincronização — ", ["detail"]],
"qkqG0b": ["Aceitar a versão remota"],
"qlAIQ1": ["Remoto"],
- "qlnfTD": ["Falha ao carregar a imagem: ", ["errorLabel"]],
"qmL1UG": ["Enviando com segurança"],
"qo4zCg": ["O caminho não pode conter barras invertidas"],
"qpQwGC": ["Descreva no que você está trabalhando e o agente prepara tudo para você."],
@@ -4200,6 +4229,7 @@
"rXz97P": ["Lista numerada de itens."],
"rZ9HZq": ["A fazer"],
"rZVMkf": ["Campo de substituição do editor visual em foco"],
+ "radOpL": ["Imagem ", ["identity"], ". Ir para a referência."],
"rageVb": ["HTML personalizado com painel de pré-visualização ao vivo (iframe isolado)."],
"rbrHTd": ["Aprovado — ", ["optionName"]],
"rcJmK8": ["Converter os locais em cópias"],
@@ -4381,6 +4411,7 @@
["trashNoun"],
". Deseja excluir permanentemente?"
],
+ "txUHO8": [["localizedMessage"], " na linha ", ["displayLine"]],
"tzGWeg": ["Preparando a desinstalação do OpenKnowledge"],
"tzZ6ha": ["Conectar ao GitHub Enterprise Server"],
"u-9fWA": ["Veja <0>Arquitetura</0> para uma visão geral do sistema."],
@@ -4403,7 +4434,6 @@
"uCaIdy": [
"O login do GitHub está ausente ou expirou. Reconecte para retomar a sincronização."
],
- "uCe4AX": [["0"], " na linha ", ["displayLine"]],
"uDlyqd": [
"Documente a arquitetura deste repositório: crie uma página geral que aponte para uma página por módulo principal descrevendo suas responsabilidades e seus pontos de entrada."
],
@@ -4505,6 +4535,7 @@
"vPEyDz": ["Transcrição do agente"],
"vPF04k": ["Começar um novo chat"],
"vPKX2i": ["No app (beta)"],
+ "vPLUCm": ["A imagem ", ["identity"], " está ausente. Ir para a referência."],
"vPXOUw": ["Mostrar ou ocultar a visualização de código"],
"vQIVHc": ["Propriedades da pasta"],
"vWc9a0": ["Digite para editar; <0>⌘ Enter</0> salva, <1>Esc</1> cancela."],
@@ -4677,6 +4708,7 @@
"xxRpzT": ["Slidev encontrado no seu sistema."],
"xzAmL_": ["Aprovado automaticamente"],
"xzktOa": ["Editar o link wiki"],
+ "y-LQPF": ["Não foi possível resolver a imagem ", ["identity"], ". Ir para a referência."],
"y1eoq1": ["Copiar link"],
"y1t8bQ": ["Seções das configurações"],
"y3aU20": ["Salvar as alterações"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index c62cb87d2..50cf6975f 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} age sem perguntar — o OpenKnowledge não consegue adicionar pedido
msgid "{0} added, {1} removed"
msgstr "{0} adicionados, {1} removidos"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} na linha {displayLine}"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# link} many {# links} other {# links}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "{localizedMessage} na linha {displayLine}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {há # min} many {há # min} other {há # min}}"
@@ -2204,6 +2203,10 @@ msgstr "Buscando atualizações no GitHub"
msgid "Checking GitHub connection..."
msgstr "Verificando a conexão com o GitHub..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "Verificando links"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "Extraindo arquivos"
@@ -5053,6 +5056,10 @@ msgstr "Falha ao carregar os títulos"
msgid "Failed to load hub pages"
msgstr "Falha ao carregar as páginas de índice"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "Falha ao carregar os arquivos locais"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "Falha ao carregar as páginas órfãs"
@@ -5280,6 +5287,10 @@ msgstr "Campos"
msgid "File"
msgstr "Arquivo"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "Arquivo {identity}. Ir para a referência."
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "O arquivo já existe"
@@ -6030,6 +6041,10 @@ msgstr "O que você acha do OpenKnowledge?"
msgid "How does sharing work?"
msgstr "Como funciona o compartilhamento?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "Como documentos, arquivos e imagens locais do projeto ausentes são informados em Problemas, diagnósticos do editor, auditorias e ferramentas de agente."
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "Como enviar manualmente"
@@ -6047,10 +6062,6 @@ msgstr "Como configurar"
msgid "How to set up {0} (opens in browser)"
msgstr "Como configurar {0} (abre no navegador)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "Como os links wiki não resolvidos são reportados no painel Problemas, nas auditorias e nas ferramentas de agente."
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "Como os achados de validação aparecem no projeto. Estas escolhas ficam salvas no config.yml e são compartilhadas com todos os colaboradores pelo git."
@@ -6106,13 +6117,33 @@ msgstr "Padrões de exclusão"
msgid "Ignore patterns (raw text)"
msgstr "Padrões de exclusão (texto puro)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "Imagem {identity}. Ir para a referência."
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "Não foi possível mostrar a imagem"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "Falha ao carregar a imagem"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "Não foi possível mostrar a imagem: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "Falha ao carregar a imagem: {errorLabel}"
+msgid "Image not found"
+msgstr "Imagem não encontrada"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "Imagem não encontrada: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "O destino da imagem \"{shown}\" não pôde ser resolvido como um arquivo local do projeto."
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "O destino da imagem \"{shown}\" não corresponde a um arquivo existente."
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6713,6 +6744,18 @@ msgstr "O link está pronto, mas não foi possível copiá-lo para a área de tr
msgid "Link target"
msgstr "Destino do link"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "O destino do link \"{shown}\" não pôde ser resolvido como um destino local do projeto."
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "O destino do link \"{shown}\" não corresponde a um documento existente."
+
+#: src/editor/localized-validation-message.ts
+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/lib/keyboard-shortcuts.ts
msgid "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."
@@ -6725,6 +6768,14 @@ msgstr "Aponta para uma página ou uma URL externa."
msgid "Link URL"
msgstr "URL do link"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "A validação de links não está disponível."
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "A validação de links não está disponível. Exibindo os últimos problemas conhecidos."
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "A resposta do grafo de links não tinha o formato esperado."
@@ -6921,6 +6972,14 @@ msgstr "Não foi possível limpar os dados locais de colaboração de \"{docName
msgid "Local commits are keeping this copy from updating"
msgstr "Commits locais estão impedindo esta cópia de atualizar"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "Os detalhes dos arquivos locais ainda não estão disponíveis."
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "Arquivos locais"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "Caminho local"
@@ -7097,10 +7156,22 @@ msgstr "Fonte do espelho <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "Fonte do espelho <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "Ausente"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "Faltava um recurso"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "O arquivo {identity} está ausente. Ir para a referência."
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "A imagem {identity} está ausente. Ir para a referência."
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "Página inexistente — clique para criar"
@@ -8017,10 +8088,9 @@ msgstr "Lista numerada de itens."
msgid "Object"
msgstr "Objeto"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "Ocorrências de {0}"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "Ocorrências de {localizedFirstMessage}"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12325,6 +12395,10 @@ msgstr "Esta página ainda não existe. Abra para criá-la no editor e recolher
msgid "This page doesn't link to anything yet."
msgstr "Esta página ainda não aponta para nada."
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "Esta página não faz referência a nenhum arquivo ou imagem local."
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "Este caminho está em um volume externo (/Volumes/...). O OpenKnowledge vai perder os arquivos de vista quando a unidade for ejetada."
@@ -12864,6 +12938,18 @@ msgstr "Link não reconhecido"
msgid "Unrecognized wiki link"
msgstr "Link wiki não reconhecido"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "Não resolvido"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "Não foi possível resolver o arquivo {identity}. Ir para a referência."
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "Não foi possível resolver a imagem {identity}. Ir para a referência."
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "Atualizado"
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 29847d84c..c6ecf1a06 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -160,11 +160,13 @@
"1njn7W": ["روشن"],
"1nke1r": [["0"], " کو GitHub پر کھولیں (نئے ٹیب میں کھلتا ہے)"],
"1oSHI0": [["skillName"], " نصب نہیں ہو سکی: ", ["0"]],
+ "1pdLQw": ["تصویر نہیں ملی"],
"1qpGKz": ["تبدیلیاں محفوظ نہیں ہو سکیں۔ کسی رنگ میں دوبارہ ترمیم کر کے دیکھیں۔"],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["مسترد کریں"],
"1u-mAI": ["مطابقت پذیری شروع نہیں ہو سکی۔ اپنا کنکشن دیکھیں، پھر دوبارہ کوشش کریں۔"],
"1vn0CI": ["سرور کا جواب غیر درست ہے"],
+ "1xui0Q": ["مقامی فائلیں لوڈ نہیں ہو سکیں"],
"2277Tu": ["گراف سکیڑیں"],
"237hSL": ["ختم ہو گیا"],
"253MN6": ["آپ کے تبصرے نہیں بھیجے جا سکے — براہِ کرم دوبارہ کوشش کریں۔"],
@@ -450,6 +452,7 @@
"6HCOwA": ["نہیں کھل سکا۔"],
"6KCH4m": ["چھپی ہوئی فائلیں"],
"6KXnz5": ["آپ اس فائل کو ردی سے بحال کر سکتے ہیں۔"],
+ "6LJJ1v": ["فائل ", ["identity"], "۔ حوالہ پر جائیں۔"],
"6LbUG7": ["ریپازٹری نجی ہے اور آپ کے GitHub اکاؤنٹ کو اس تک رسائی نہیں۔"],
"6Mbe-P": [
"بیان کریں کہ اسے کیا کرنا چاہیے، یا خود ایک شامل کریں۔ OpenKnowledge آپ کی مہارتیں ایک جگہ رکھتا ہے، ان کے ورژن سنبھالتا ہے، اور انہیں Claude، Codex اور Cursor جیسے ایجنٹس میں نصب کرتا ہے۔"
@@ -985,7 +988,6 @@
"EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " ٹوکنز استعمال شدہ"],
"EQXPXf": ["آخر تک سکرول کریں"],
"ETyvvg": ["کوئی زبان مماثل نہیں۔"],
- "EUiJEM": [["0"], " کے مواقع"],
"EWCJFu": [["target"], " بن گیا"],
"EWPtMO": ["کوڈ"],
"EWX92Z": ["«AI سے پوچھیں» سکیڑیں"],
@@ -1295,6 +1297,7 @@
"IgN3LY": ["<0>", ["address"], "</0> میں منتخب متن پر"],
"IgTwLt": ["یہ دستاویز ایڈیٹر میں کھولیں اور گراف سکیڑ دیں۔"],
"Ik-gP0": ["عنوان H", ["level"], ": ", ["text"]],
+ "IoHQYP": ["لنک کی توثیق دستیاب نہیں ہے۔ آخری معلوم مسائل دکھائے جا رہے ہیں۔"],
"Iq8zdU": ["ٹرمینل بند کریں"],
"IrB5AK": [
["failedCount", "plural", { "one": ["#", " آئٹم"], "other": ["#", " آئٹمز"] }],
@@ -1494,6 +1497,7 @@
"Lm3r51": ["Slidev اس دستاویز کو رینڈر نہیں کر سکا۔"],
"LnVIW4": ["سائن اِن شروع نہیں ہو سکا — دوبارہ کوشش کریں"],
"LpB85N": ["سادہ"],
+ "Lrsl_h": ["غائب فائل ", ["identity"], "۔ حوالہ پر جائیں۔"],
"LtI9AS": ["مالک"],
"LtSYdi": ["Finder میں دکھائیں"],
"LtiJ5c": ["پروجیکٹ کی مہارت"],
@@ -1600,7 +1604,6 @@
"جب آپ کسی بیرونی لنک پر ماؤس لے جاتے ہیں تو صفحے کا پیش منظر ڈیٹا لانے کے لیے اس کا URL منزل کی سائٹ کو بھیجا جاتا ہے — ہر پیش منظر والے لنک کے لیے ایک درخواست۔"
],
"MysZUL": [["agentName"], " سے منسلک ہو رہا ہے…"],
- "N-IonL": ["غیر حل شدہ وکی لنکس مسائل کے پینل، آڈٹس اور ایجنٹ ٹولز میں کیسے رپورٹ ہوتے ہیں۔"],
"N1KkEO": ["آخری ٹیب پر جائیں"],
"N1YYa7": ["تصویر لوڈ ہو رہی ہے"],
"N1mdmS": ["یہ فائل ٹیکسٹ ایڈیٹر میں نہیں کھل سکتی۔"],
@@ -2050,6 +2053,7 @@
"U2Kx6T": ["تمام غیر پن شدہ بند کریں"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["مکمل رہنما"],
+ "U3RIJu": ["مقامی فائلیں"],
"U4nTfu": ["پیروی فعال کریں"],
"U5Spo9": ["مواد کی ڈائریکٹری پروجیکٹ کے اندر ہونی چاہیے"],
"U6wmNc": ["مطابقت پذیری روکی ہوئی"],
@@ -2171,12 +2175,14 @@
"VNNRfN": ["ماخذ بنائیں"],
"VNgKZz": ["اعلیٰ ترتیبات"],
"VTulZj": ["ورک ٹری میں کھولیں"],
+ "VU3Nrn": ["غائب"],
"VUijjF": ["اختیاری متبادل متن کے ساتھ تصویر شامل کریں۔"],
"VVRrPk": [["0"], " ایڈجسٹ کرنے کے لیے کوئی ترتیبات فراہم نہیں کرتا"],
"VXGFMg": ["کوڈ فیلڈ میں واپسی یا دوبارہ"],
"VYd_YA": ["ڈسک سے موجودہ پروجیکٹ کا فولڈر کھولیں۔"],
"VZGh8G": ["سورس کے حصے تہ کریں، کھولیں، سب تہ کریں، یا سب کھولیں۔"],
"VZSBXL": ["معنوی درجہ بندی پہلی بار اسی وقت فعال ہوتی ہے جب کوئی ایجنٹ تلاش چلائے۔"],
+ "VZg6Gn": ["تصویر دکھائی نہیں جا سکی: ", ["errorLabel"]],
"V_6bJ4": ["ٹرمینل کی ترتیبات ابھی لوڈ نہیں ہوئیں — تھوڑی دیر بعد دوبارہ کوشش کریں۔"],
"V_DjMe": ["رینڈر کی خرابی"],
"V_wltx": ["اس ٹیمپلیٹ کے لیے عنوان درج کریں۔"],
@@ -2203,12 +2209,18 @@
"W1qRuM": ["یہ دستاویز ایڈیٹر میں پہلے ہی فعال ہے۔ گراف سکیڑنے کے لیے «کھولیں» استعمال کریں۔"],
"W3Tsgy": [["0"], " میں پایا گیا"],
"W5A0Ly": ["ایک غیر متوقع خرابی پیش آئی۔"],
+ "W5qdI_": [
+ "تصویر کے ہدف \"",
+ ["shown"],
+ "\" کو پروجیکٹ کی مقامی فائل کے طور پر حل نہیں کیا جا سکا۔"
+ ],
"W7XJN4": [
"پروجیکٹس ایک دوسرے کے اندر نہیں ہو سکتے۔ <0>",
["rootPath"],
"</0> پر پہلے سے ایک OpenKnowledge پروجیکٹ موجود ہے۔ اس سے باہر کوئی مقام منتخب کریں، یا اس کے بجائے وہی پروجیکٹ کھولیں۔"
],
"W8vpBM": ["ابتدائی پیک"],
+ "W9NSe0": ["لنکس کی جانچ ہو رہی ہے"],
"W9_Bub": ["مقامی تبدیلیاں آنے والی مطابقت پذیری سے ٹکراتی ہیں"],
"WBNpt9": ["یہ تھیم پڑھی نہیں جا سکی (", ["0"], ")"],
"WFEbV1": [
@@ -2271,11 +2283,13 @@
"X8kjQX": ["GitHub سے دوبارہ توثیق کریں"],
"X9VpsP": ["فولڈر کا مواد لوڈ ہو رہا ہے"],
"XAyxsa": ["ریموٹ برانچ چیک آؤٹ کریں"],
+ "XBBZnv": ["لنک کا ہدف \"", ["shown"], "\" کسی موجودہ دستاویز کی طرف اشارہ نہیں کرتا۔"],
"XBgr2S": ["یہاں کاپی کریں"],
"XDzAnp": ["نئے ٹیب میں کھلتا ہے"],
"XFpEgc": [
"منتخب کریں کہ ایپ کے ایجنٹ مینیوز میں کون سے ایجنٹ نظر آئیں، جیسے Ask AI، Open with AI اور + نئی چیٹ کا بٹن۔ کسی ایجنٹ کو بند کرنے سے وہ ان سب سے چھپ جائے گا۔"
],
+ "XGKy1z": ["تصویر دکھائی نہیں جا سکی"],
"XH30C4": ["دستاویز"],
"XIltnd": ["«", ["trimmed"], "» نام کی مہارت یہاں پہلے سے موجود ہے"],
"XJOV1Y": ["سرگرمی"],
@@ -2293,6 +2307,7 @@
"XW18jo": ["صفحے کے عنوانات کا جواب کامیابی کے اسکیما سے میل نہیں کھایا"],
"XWEqQj": [["days"], "دن"],
"XXA1b_": [["componentLabel"], " (خالی)"],
+ "XYZ7tp": ["ناقابلِ حل"],
"XYlJJT": ["ترتیب دیا جا رہا ہے"],
"XZkdtg": ["برانچ بدلیں"],
"XcGbim": ["چھپی ہوئی فائلیں دکھائیں"],
@@ -2384,6 +2399,7 @@
"YW7Q86": ["تلاش کی ترتیبات ابھی لوڈ نہیں ہوئیں — تھوڑی دیر بعد دوبارہ کوشش کریں"],
"Y_GpJd": [["0"], " کی ڈاؤن لوڈ درخواست کا وقت ختم ہو گیا۔"],
"Y_ZQ6l": [["agentName"], " نصب کیا جا رہا ہے…"],
+ "Y_iImT": ["ناقابلِ حل فائل ", ["identity"], "۔ حوالہ پر جائیں۔"],
"Y_kL7X": ["ایڈیٹر کی شکل اور رویہ اپنی مرضی کے مطابق بنائیں۔"],
"Ya3PlJ": ["اجازت درکار ہے"],
"YaeyFh": ["کھینچنے سے آپ کی مقامی فائلوں میں غیر کمٹ شدہ ترامیم مٹ سکتی ہیں۔"],
@@ -2497,6 +2513,7 @@
["currentLabel"],
"</1> پر ہیں۔"
],
+ "_Bix3-": [["localizedFirstMessage"], " کے واقعات"],
"_DwR-n": ["بنائی جا رہی ہے…"],
"_FLBbi": [["sizeText"], " · رازداری کی معلومات چھپا دی گئیں · کریش ڈمپ نہیں چھپایا گیا"],
"_GRWOJ": ["ایمبیڈنگز فراہم کنندہ بدلیں؟"],
@@ -2654,6 +2671,11 @@
"» کا مقامی اشتراکی ڈیٹا صاف کیا جا رہا ہے۔"
],
"bnOTEz": ["حاصل کیا جا رہا ہے…"],
+ "bpMVIA": [
+ "لنک کے ہدف \"",
+ ["shown"],
+ "\" کو پروجیکٹ کے مقامی ہدف کے طور پر حل نہیں کیا جا سکا۔"
+ ],
"bpytj4": [["0"], " پر منتقل کریں"],
"brCtGB": ["تاریخ دستیاب نہیں"],
"buNXgr": ["اپنی جگہ برقرار رکھتے ہوئے بصری اور سورس ایڈیٹر کے درمیان بدلیں۔"],
@@ -2888,6 +2910,7 @@
"fJgQHX": ["فائل نہیں بن سکی"],
"fMsFdZ": ["خودکار اپ ڈیٹ کی ترتیب محفوظ نہیں ہو سکی: ", ["0"]],
"fNr-MX": ["معنوی تلاش بند کریں"],
+ "fOzzSV": ["لنک کا ہدف \"", ["shown"], "\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"],
"fR-Kdc": ["(صرف پروجیکٹ کی سطح پر)"],
"fRVBiq": [
"دستیاب ہونے پر ٹیلی میٹری، سرور کی حالت اور رن ٹائم معلومات شامل کرتا ہے۔ اسناد ہمیشہ ہٹا دی جاتی ہیں؛ دستاویزات کے نام، اگر شامل ہوں، سادہ متن میں ظاہر ہوتے ہیں (چھپائے نہیں جاتے)۔"
@@ -2925,6 +2948,7 @@
"fwrPh4": ["براہِ کرم درست ای میل درج کریں۔"],
"fxJk_6": ["<0>مزید کچھ کہنا ہے؟</0> <1/> پر لکھیں اور اپنا حوالہ ذکر کریں۔"],
"fxbCNQ": ["مطابق ہو گیا۔ لنک تازہ ترین ہے۔"],
+ "g-dkjJ": ["مقامی فائل کی تفصیلات ابھی دستیاب نہیں ہیں۔"],
"g12y1g": ["YAML درست نہیں"],
"g1ZTh_": [
[
@@ -3005,6 +3029,7 @@
"gmJ0An": ["فولڈر نہیں کھل سکا۔"],
"goO4Ll": ["ایڈیٹر کی حالت کا بار"],
"gp3I7-": ["مطابقت پذیری سے پہلے، git کمٹس کے لیے اپنی شناخت مقرر کریں:"],
+ "gpbKxw": ["لنک کی توثیق دستیاب نہیں ہے۔"],
"gqk-3R": [["0"], " کو ", ["destination"], " میں منتقل کر دیا گیا۔"],
"gtEbeW": ["نمایاں کریں"],
"gtGQ9S": [["agentName"], " شروع کریں، ", ["hint"]],
@@ -3129,6 +3154,7 @@
"iRdfLr": ["ڈیو انسٹینس: ", ["label"]],
"iSLIjg": ["منسلک کریں"],
"iSQTsg": ["مرتب فہرست"],
+ "iSWh95": ["تصویر کا ہدف \"", ["shown"], "\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"],
"iSnkwB": ["کلون شدہ پروجیکٹ نہیں کھل سکا۔"],
"iTylMl": ["ٹیمپلیٹس"],
"iUwpZI": ["کوئی خالی جگہ نہیں — اس کے بجائے <0>-</0> استعمال کریں۔"],
@@ -3165,6 +3191,9 @@
"وہ <0>type</0> جو اس ٹیمپلیٹ سے بننے والی ہر دستاویز کو ملتا ہے (مثلاً <1>research-note</1>)۔ نئی دستاویزات کو Open Knowledge Format سے ہم آہنگ رکھتا ہے۔"
],
"iqIDv4": ["مطابقت پذیری کی حالت دستیاب نہیں"],
+ "iqr14Z": [
+ "گم شدہ پروجیکٹ-لوکل دستاویزات، فائلوں اور تصاویر کو مسائل، ایڈیٹر تشخیصات، آڈٹس اور ایجنٹ ٹولز میں کیسے رپورٹ کیا جاتا ہے۔"
+ ],
"iqugog": ["ابتدائیہ ناکام: ", ["errorDetail"]],
"irFGwu": ["ٹیمپلیٹس کی فہرست"],
"irrm_E": ["انتخاب ہٹائیں"],
@@ -3272,6 +3301,7 @@
"kCqCyf": ["CodeMirror کا لِنٹ تشخیصی پینل کھولیں۔"],
"kFLlsI": ["فٹ نوٹ کا حوالہ + اس سے مماثل تعریف کا خاکہ داخل کریں۔"],
"kGp168": ["اس پروجیکٹ کو اشاعت کے لیے تیار نہیں کیا جا سکا۔"],
+ "kI5pWt": ["تصویر نہیں ملی: ", ["errorLabel"]],
"kKw0H3": [
"آپ نے یہ مہارت مقامی طور پر بدلی اور ماخذ میں نئی تبدیلیاں ہیں۔ اپ سٹریم لینا آپ کے ورژن کی جگہ لے لیتا ہے؛ آپ کی ترامیم ورژن کی تاریخ میں بحالی کے قابل رہتی ہیں۔"
],
@@ -3523,7 +3553,6 @@
"nCzR-G": ["کوڈ ", ["userCode"], " نقل کریں"],
"nDT8qt": [["0"], " کا ابتدائیہ ہو گیا مگر یہ کھل نہیں سکا۔"],
"nG-XA9": ["لنگر انداز متن غائب ہو گیا۔ آپ اسے منتخب متن پر دوبارہ رکھ سکتے ہیں۔"],
- "nL-HHD": ["تصویر لوڈ نہیں ہو سکی"],
"nMSYz5": [
"یہ راستہ بیرونی والیوم پر ہے (/Volumes/...)۔ ڈرائیو نکالنے پر OpenKnowledge فائلوں کا سراغ کھو دے گا۔"
],
@@ -3657,6 +3686,7 @@
"pFRz_E": ["ان تبصروں کو اس پیغام سے باہر رکھیں"],
"pFagOn": ["سورس کی ترمیم"],
"pHYP6v": ["سائیڈ بار میں <0>حسبِ ضرورت بنائیں</0> <1/> <2>مہارتیں</2> کھولیں۔"],
+ "pJ7XCo": ["یہ صفحہ کسی مقامی فائل یا تصویر کا حوالہ نہیں دیتا۔"],
"pOo4Aa": ["سادہ متن"],
"pSimwP": [["editor"], " ورژن کے لیے نیا نام"],
"pTPqMK": ["باڑ والا کوڈ بلاک بدلیں۔"],
@@ -3761,7 +3791,6 @@
"qjHMHf": ["مطابقت پذیری بند نہیں ہو سکی — ", ["detail"]],
"qkqG0b": ["اپ سٹریم والا لیں"],
"qlAIQ1": ["ریموٹ"],
- "qlnfTD": ["تصویر لوڈ نہیں ہو سکی: ", ["errorLabel"]],
"qmL1UG": ["محفوظ طریقے سے اپ لوڈ ہو رہا ہے"],
"qo4zCg": ["راستے میں الٹی سلیش نہیں ہو سکتی"],
"qpQwGC": ["بیان کریں کہ آپ کس چیز پر کام کر رہے ہیں اور ایجنٹ اسے آپ کے لیے ترتیب دے دے گا۔"],
@@ -3796,6 +3825,7 @@
"rXz97P": ["آئٹمز کی نمبر شدہ فہرست۔"],
"rZ9HZq": ["کرنا ہے"],
"rZVMkf": ["بصری ایڈیٹر کا تبدیلی اِن پٹ فوکس میں ہے"],
+ "radOpL": ["تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],
"rageVb": ["براہِ راست پیش منظر کے پین کے ساتھ حسبِ ضرورت HTML (سینڈ باکسڈ iframe)۔"],
"rbrHTd": ["منظور شدہ — ", ["optionName"]],
"rcJmK8": ["مقامات کو نقول میں بدلیں"],
@@ -3956,6 +3986,7 @@
["trashNoun"],
" میں منتقل نہیں کیا جا سکا۔ کیا آپ اس کے بجائے مستقل طور پر حذف کرنا چاہتے ہیں؟"
],
+ "txUHO8": ["سطر ", ["displayLine"], " پر ", ["localizedMessage"]],
"tzGWeg": ["OpenKnowledge کی تنصیب ختم کرنے کی تیاری"],
"tzZ6ha": ["GitHub Enterprise Server سے منسلک ہوں"],
"u-9fWA": ["نظام کے جائزے کے لیے <0>Architecture</0> دیکھیں۔"],
@@ -3972,7 +4003,6 @@
"uCaIdy": [
"GitHub کا سائن اِن غائب یا میعاد ختم ہے۔ مطابقت پذیری جاری رکھنے کے لیے دوبارہ منسلک ہوں۔"
],
- "uCe4AX": [["0"], " سطر ", ["displayLine"], " پر"],
"uDlyqd": [
"اس ریپو کے ڈھانچے کی دستاویز بنائیں: ایک جائزہ صفحہ بنائیں جو ہر بڑے ماڈیول کے صفحے سے جڑا ہو اور اس کی ذمہ داریاں اور داخلی نقاط بیان کرے۔"
],
@@ -4064,6 +4094,7 @@
"vPEyDz": ["ایجنٹ کا ٹرانسکرپٹ"],
"vPF04k": ["نئی گفتگو شروع کریں"],
"vPKX2i": ["ایپ میں (بیٹا)"],
+ "vPLUCm": ["غائب تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],
"vPXOUw": ["سورس کا منظر بدلیں"],
"vQIVHc": ["فولڈر کی خصوصیات"],
"vWc9a0": ["ترمیم کے لیے لکھیں؛ <0>⌘ Enter</0> محفوظ کرتا ہے، <1>Esc</1> منسوخ کرتا ہے۔"],
@@ -4236,6 +4267,7 @@
"xxRpzT": ["آپ کے سسٹم پر Slidev مل گیا۔"],
"xzAmL_": ["خودکار منظور شدہ"],
"xzktOa": ["وکی لنک میں ترمیم کریں"],
+ "y-LQPF": ["ناقابلِ حل تصویر ", ["identity"], "۔ حوالہ پر جائیں۔"],
"y1eoq1": ["لنک کاپی کریں"],
"y1t8bQ": ["ترتیبات کے سیکشنز"],
"y3aU20": ["تبدیلیاں محفوظ کریں"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index f405980f3..d7a2722b4 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} پوچھے بغیر عمل کرتا ہے — OpenKnowledge اس کے
msgid "{0} added, {1} removed"
msgstr "{0} شامل، {1} ہٹائے گئے"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0} سطر {displayLine} پر"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, one {# لنک} other {# لنکس}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}: {message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "سطر {displayLine} پر {localizedMessage}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, one {# منٹ پہلے} other {# منٹ پہلے}}"
@@ -2208,6 +2207,10 @@ msgstr "GitHub پر اپ ڈیٹس دیکھے جا رہے ہیں"
msgid "Checking GitHub connection..."
msgstr "GitHub کنکشن جانچا جا رہا ہے..."
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "لنکس کی جانچ ہو رہی ہے"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "فائلیں چیک آؤٹ کی جا رہی ہیں"
@@ -5057,6 +5060,10 @@ msgstr "عنوانات لوڈ نہیں ہو سکے"
msgid "Failed to load hub pages"
msgstr "مرکزی صفحات لوڈ نہیں ہو سکے"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "مقامی فائلیں لوڈ نہیں ہو سکیں"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "یتیم صفحات لوڈ نہیں ہو سکے"
@@ -5284,6 +5291,10 @@ msgstr "فیلڈز"
msgid "File"
msgstr "فائل"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "فائل {identity}۔ حوالہ پر جائیں۔"
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "فائل پہلے سے موجود ہے"
@@ -6034,6 +6045,10 @@ msgstr "OpenKnowledge آپ کو کیسا لگا؟"
msgid "How does sharing work?"
msgstr "اشتراک کیسے کام کرتا ہے؟"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "گم شدہ پروجیکٹ-لوکل دستاویزات، فائلوں اور تصاویر کو مسائل، ایڈیٹر تشخیصات، آڈٹس اور ایجنٹ ٹولز میں کیسے رپورٹ کیا جاتا ہے۔"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "دستی طور پر پُش کیسے کریں"
@@ -6051,10 +6066,6 @@ msgstr "ترتیب کیسے دیں"
msgid "How to set up {0} (opens in browser)"
msgstr "{0} کیسے ترتیب دیں (براؤزر میں کھلتا ہے)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "غیر حل شدہ وکی لنکس مسائل کے پینل، آڈٹس اور ایجنٹ ٹولز میں کیسے رپورٹ ہوتے ہیں۔"
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "توثیق کے نتائج پورے پروجیکٹ میں کیسے ظاہر ہوتے ہیں۔ یہ انتخاب config.yml میں کمٹ ہوتے ہیں اور git کے ذریعے ہر ساتھی کے ساتھ مشترک ہوتے ہیں۔"
@@ -6110,13 +6121,33 @@ msgstr "نظر انداز کرنے کے پیٹرنز"
msgid "Ignore patterns (raw text)"
msgstr "نظر انداز کرنے کے پیٹرنز (خام متن)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "تصویر {identity}۔ حوالہ پر جائیں۔"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "تصویر دکھائی نہیں جا سکی"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "تصویر لوڈ نہیں ہو سکی"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "تصویر دکھائی نہیں جا سکی: {errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "تصویر لوڈ نہیں ہو سکی: {errorLabel}"
+msgid "Image not found"
+msgstr "تصویر نہیں ملی"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "تصویر نہیں ملی: {errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "تصویر کے ہدف \"{shown}\" کو پروجیکٹ کی مقامی فائل کے طور پر حل نہیں کیا جا سکا۔"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "تصویر کا ہدف \"{shown}\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "لنک تیار ہے، مگر کلپ بورڈ پر کاپی نہیں ہ
msgid "Link target"
msgstr "لنک کا ہدف"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "لنک کے ہدف \"{shown}\" کو پروجیکٹ کے مقامی ہدف کے طور پر حل نہیں کیا جا سکا۔"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "لنک کا ہدف \"{shown}\" کسی موجودہ دستاویز کی طرف اشارہ نہیں کرتا۔"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "لنک کا ہدف \"{shown}\" کسی موجودہ فائل کی طرف اشارہ نہیں کرتا۔"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "منتخب متن کو لنک کریں، یا کرسر کے نیچے موجود لنک میں ترمیم کریں۔"
@@ -6729,6 +6772,14 @@ msgstr "کسی صفحے یا بیرونی URL سے لنک کریں۔"
msgid "Link URL"
msgstr "لنک کا URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "لنک کی توثیق دستیاب نہیں ہے۔"
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "لنک کی توثیق دستیاب نہیں ہے۔ آخری معلوم مسائل دکھائے جا رہے ہیں۔"
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "لنک گراف کا جواب متوقع ساخت سے میل نہیں کھایا۔"
@@ -6925,6 +6976,14 @@ msgstr "«{docName}» کا مقامی اشتراکی ڈیٹا صاف نہیں ہ
msgid "Local commits are keeping this copy from updating"
msgstr "مقامی کمٹس اس نقل کو تازہ ہونے سے روک رہے ہیں"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "مقامی فائل کی تفصیلات ابھی دستیاب نہیں ہیں۔"
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "مقامی فائلیں"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "مقامی راستہ"
@@ -7101,10 +7160,22 @@ msgstr "مرر کا ماخذ <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "مرر کا ماخذ <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "غائب"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "ایک خصوصیت غائب ہے"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "غائب فائل {identity}۔ حوالہ پر جائیں۔"
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "غائب تصویر {identity}۔ حوالہ پر جائیں۔"
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "غائب صفحہ — بنانے کے لیے کلک کریں"
@@ -8021,10 +8092,9 @@ msgstr "آئٹمز کی نمبر شدہ فہرست۔"
msgid "Object"
msgstr "آبجیکٹ"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "{0} کے مواقع"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "{localizedFirstMessage} کے واقعات"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "یہ صفحہ ابھی موجود نہیں۔ ایڈیٹر میں صفح
msgid "This page doesn't link to anything yet."
msgstr "یہ صفحہ ابھی کسی چیز سے لنک نہیں کرتا۔"
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "یہ صفحہ کسی مقامی فائل یا تصویر کا حوالہ نہیں دیتا۔"
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "یہ راستہ بیرونی والیوم پر ہے (/Volumes/...)۔ ڈرائیو نکالنے پر OpenKnowledge فائلوں کا سراغ کھو دے گا۔"
@@ -12868,6 +12942,18 @@ msgstr "ناقابلِ شناخت لنک"
msgid "Unrecognized wiki link"
msgstr "ناقابلِ شناخت وکی لنک"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "ناقابلِ حل"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "ناقابلِ حل فائل {identity}۔ حوالہ پر جائیں۔"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "ناقابلِ حل تصویر {identity}۔ حوالہ پر جائیں۔"
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "تازہ ترین"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 5e260097f..70834d042 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -147,11 +147,13 @@
"1njn7W": ["浅色"],
"1nke1r": ["在 GitHub 上打开 ", ["0"], "(在新标签页中打开)"],
"1oSHI0": ["无法安装 ", ["skillName"], ":", ["0"]],
+ "1pdLQw": ["找不到图片"],
"1qpGKz": ["无法保存更改。请再次编辑颜色。"],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["拒绝"],
"1u-mAI": ["无法开始同步。请检查你的网络连接,然后重试。"],
"1vn0CI": ["服务器响应无效"],
+ "1xui0Q": ["加载本地文件失败"],
"2277Tu": ["折叠关系图"],
"237hSL": ["已结束"],
"253MN6": ["无法发送你的评论——请重试。"],
@@ -407,6 +409,7 @@
"6HCOwA": ["打开失败。"],
"6KCH4m": ["隐藏文件"],
"6KXnz5": ["你可以从废纸篓中恢复此文件。"],
+ "6LJJ1v": ["文件 ", ["identity"], "。转到引用位置。"],
"6LbUG7": ["这个仓库是私有的,你的 GitHub 账户没有访问权限。"],
"6Mbe-P": [
"描述它该做什么,或者自己添加一个。OpenKnowledge 会把你的技能集中保存、做版本管理,并安装到 Claude、Codex、Cursor 等智能体中。"
@@ -876,7 +879,6 @@
"EPwuTC": ["已使用 ", ["usedLabel"], " / ", ["sizeLabel"], " 个 token"],
"EQXPXf": ["滚动到末尾"],
"ETyvvg": ["没有匹配的语言。"],
- "EUiJEM": [["0"], " 的出现位置"],
"EWCJFu": ["已创建 ", ["target"]],
"EWPtMO": ["代码"],
"EWX92Z": ["折叠「问 AI」"],
@@ -1131,6 +1133,7 @@
"IgN3LY": ["在 <0>", ["address"], "</0> 中选中的文本上"],
"IgTwLt": ["在编辑器中打开这个文档并折叠关系图。"],
"Ik-gP0": [["level"], " 级标题:", ["text"]],
+ "IoHQYP": ["链接验证不可用。正在显示上次已知的问题。"],
"Iq8zdU": ["关闭终端"],
"IrB5AK": [["failedCount", "plural", { "other": ["#", " 个项目"] }], "的服务器端清理失败"],
"IrC12v": ["应用程序"],
@@ -1290,6 +1293,7 @@
"Lm3r51": ["Slidev 无法渲染此文档。"],
"LnVIW4": ["启动登录失败——请重试"],
"LpB85N": ["纯文本"],
+ "Lrsl_h": ["文件 ", ["identity"], " 不存在。转到引用位置。"],
"LtI9AS": ["所有者"],
"LtSYdi": ["在访达中显示"],
"LtiJ5c": ["项目技能"],
@@ -1378,7 +1382,6 @@
"把鼠标悬停在外部链接上时,它的 URL 会发送到目标站点以获取页面的预览元数据——每个被预览的链接一次请求。"
],
"MysZUL": ["正在连接 ", ["agentName"], "…"],
- "N-IonL": ["未解析的维基链接在「问题」面板、审查结果和智能体工具中如何呈现。"],
"N1KkEO": ["跳到最后一个标签页"],
"N1YYa7": ["正在加载图片"],
"N1mdmS": ["这个文件无法在文本编辑器中打开。"],
@@ -1770,6 +1773,7 @@
"U2Kx6T": ["关闭所有未固定的"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["完整指南"],
+ "U3RIJu": ["本地文件"],
"U4nTfu": ["启用「跟随」"],
"U5Spo9": ["内容目录必须位于项目内部"],
"U6wmNc": ["同步已暂停"],
@@ -1879,12 +1883,14 @@
"VNNRfN": ["设为来源"],
"VNgKZz": ["高级设置"],
"VTulZj": ["在 worktree 中打开"],
+ "VU3Nrn": ["缺失"],
"VUijjF": ["嵌入一张图片,可选填替代文本。"],
"VVRrPk": [["0"], " 没有可调整的设置"],
"VXGFMg": ["代码字段的撤销或重做"],
"VYd_YA": ["从磁盘打开一个已有的项目文件夹。"],
"VZGh8G": ["折叠、展开、全部折叠或全部展开源码区域。"],
"VZSBXL": ["语义排序会在智能体第一次执行搜索时启用。"],
+ "VZg6Gn": ["无法显示图片:", ["errorLabel"]],
"V_6bJ4": ["终端设置尚未加载——请稍后再试。"],
"V_DjMe": ["渲染错误"],
"V_wltx": ["请为这个模板输入标题。"],
@@ -1909,12 +1915,14 @@
"W1qRuM": ["这个文档已经在编辑器中打开了。请用「打开」来折叠关系图。"],
"W3Tsgy": ["在 ", ["0"], " 中检测到"],
"W5A0Ly": ["发生了意外错误。"],
+ "W5qdI_": ["无法将图片目标“", ["shown"], "”解析为项目本地文件。"],
"W7XJN4": [
"项目不能嵌套。<0>",
["rootPath"],
"</0> 处已存在一个 OpenKnowledge 项目。请选择它之外的位置,或者直接打开那个项目。"
],
"W8vpBM": ["入门包"],
+ "W9NSe0": ["正在检查链接"],
"W9_Bub": ["本地改动与传入的同步内容重叠"],
"WBNpt9": ["无法读取此主题(", ["0"], ")"],
"WFEbV1": ["在编辑器中标出常见的 markdown 问题。由 <0>markdownlint<1/></0> 提供支持。"],
@@ -1975,11 +1983,13 @@
"X8kjQX": ["重新通过 GitHub 认证"],
"X9VpsP": ["正在加载文件夹内容"],
"XAyxsa": ["检出远程分支"],
+ "XBBZnv": ["链接目标“", ["shown"], "”未指向现有文档。"],
"XBgr2S": ["复制进来"],
"XDzAnp": ["在新标签页中打开"],
"XFpEgc": [
"选择哪些智能体显示在应用的智能体菜单中,例如 Ask AI、Open with AI 和 + 新对话按钮。关闭某个智能体即可在所有菜单中隐藏它。"
],
+ "XGKy1z": ["无法显示图片"],
"XH30C4": ["文档"],
"XIltnd": ["这里已存在名为“", ["trimmed"], "”的技能"],
"XJOV1Y": ["动态"],
@@ -1997,6 +2007,7 @@
"XW18jo": ["页面标题响应不符合成功时的架构"],
"XWEqQj": [["days"], "天"],
"XXA1b_": [["componentLabel"], "(空)"],
+ "XYZ7tp": ["无法解析"],
"XYlJJT": ["正在设置"],
"XZkdtg": ["切换分支"],
"XcGbim": ["显示隐藏文件"],
@@ -2073,6 +2084,7 @@
"YW7Q86": ["搜索设置尚未加载——请稍后再试"],
"Y_GpJd": [["0"], " 的下载请求超时。"],
"Y_ZQ6l": ["正在安装 ", ["agentName"], "…"],
+ "Y_iImT": ["无法解析文件 ", ["identity"], "。转到引用位置。"],
"Y_kL7X": ["自定义编辑器的外观和行为。"],
"Ya3PlJ": ["需要授权"],
"YaeyFh": ["拉取可能会覆盖你本地文件中未提交的编辑。"],
@@ -2179,6 +2191,7 @@
["currentLabel"],
"</1> 上。"
],
+ "_Bix3-": [["localizedFirstMessage"], " 的出现位置"],
"_DwR-n": ["正在创建…"],
"_FLBbi": [["sizeText"], " · 已隐去机密信息 · 崩溃转储未隐去"],
"_GRWOJ": ["要更换嵌入服务提供方吗?"],
@@ -2316,6 +2329,7 @@
"blFttG": ["搜索项目"],
"bmC18N": ["正在重新连接前清除“", ["docName"], "”的本地协作数据。"],
"bnOTEz": ["正在检索…"],
+ "bpMVIA": ["无法将链接目标“", ["shown"], "”解析为项目本地目标。"],
"bpytj4": ["移动到 ", ["0"]],
"brCtGB": ["历史记录不可用"],
"buNXgr": ["在可视化编辑器和源码编辑器之间切换,并保持当前位置。"],
@@ -2524,6 +2538,7 @@
"fJgQHX": ["创建文件失败"],
"fMsFdZ": ["无法保存自动更新设置:", ["0"]],
"fNr-MX": ["关闭语义搜索"],
+ "fOzzSV": ["链接目标“", ["shown"], "”未指向现有文件。"],
"fR-Kdc": ["(仅项目级)"],
"fRVBiq": [
"在可用时附上遥测数据、服务器状态和运行时信息。凭据始终会被移除;如果包含文档名,它们会以明文出现(不做隐去)。"
@@ -2559,6 +2574,7 @@
"fwrPh4": ["请输入有效的邮箱。"],
"fxJk_6": ["<0>还有想补充的吗?</0>请写信到 <1/> 并附上你的编号。"],
"fxbCNQ": ["已同步。链接是最新的。"],
+ "g-dkjJ": ["本地文件详情尚不可用。"],
"g12y1g": ["无效的 YAML"],
"g1ZTh_": [
["count", "plural", { "other": ["确定要删除以下 ", "#", " 个文件/文件夹及其内容吗?"] }]
@@ -2619,6 +2635,7 @@
"gmJ0An": ["打开文件夹失败。"],
"goO4Ll": ["编辑器状态栏"],
"gp3I7-": ["同步之前,请设置你用于 git 提交的身份:"],
+ "gpbKxw": ["链接验证不可用。"],
"gqk-3R": ["已将 ", ["0"], " 移动到 ", ["destination"], "。"],
"gtEbeW": ["高亮"],
"gtGQ9S": ["启动 ", ["agentName"], ",", ["hint"]],
@@ -2727,6 +2744,7 @@
"iRdfLr": ["开发实例:", ["label"]],
"iSLIjg": ["连接"],
"iSQTsg": ["有序列表"],
+ "iSWh95": ["图片目标“", ["shown"], "”未指向现有文件。"],
"iSnkwB": ["打开克隆的项目失败。"],
"iTylMl": ["模板"],
"iUwpZI": ["不能有空格——请改用 <0>-</0>。"],
@@ -2763,6 +2781,7 @@
"用这个模板创建的每个文档所获得的 <0>type</0>(例如 <1>research-note</1>)。让新文档符合 Open Knowledge Format。"
],
"iqIDv4": ["同步状态不可用"],
+ "iqr14Z": ["如何在“问题”、编辑器诊断、审计和代理工具中报告缺失的项目本地文档、文件和图像。"],
"iqugog": ["初始化失败:", ["errorDetail"]],
"irFGwu": ["模板列表"],
"irrm_E": ["移除选区"],
@@ -2860,6 +2879,7 @@
"kCqCyf": ["打开 CodeMirror 的检查诊断面板。"],
"kFLlsI": ["插入一个脚注引用及其对应的定义占位。"],
"kGp168": ["无法为发布准备此项目。"],
+ "kI5pWt": ["找不到图片:", ["errorLabel"]],
"kKw0H3": [
"你在本地编辑过这个技能,而来源有了新改动。采用远程版本会替换你的版本;你的编辑仍可在版本历史中找回。"
],
@@ -3069,7 +3089,6 @@
"nCzR-G": ["复制验证码 ", ["userCode"]],
"nDT8qt": ["已初始化 ", ["0"], ",但无法打开它。"],
"nG-XA9": ["锚定的文本已经不见了。你可以把它重新定位到选中的文本上。"],
- "nL-HHD": ["图片加载失败"],
"nMSYz5": ["这个路径位于外置卷(/Volumes/...)。驱动器弹出后,OpenKnowledge 会跟丢这些文件。"],
"nNYV3Y": ["另外还有 ", ["remaining"], " 个"],
"nOEDQs": ["更新同步模式失败——", ["detail"]],
@@ -3184,6 +3203,7 @@
"pFRz_E": ["不要把这些评论放进这条消息"],
"pFagOn": ["源码编辑"],
"pHYP6v": ["在侧边栏中打开<0>自定义</0> <1/> <2>技能</2>。"],
+ "pJ7XCo": ["此页面未引用任何本地文件或图片。"],
"pOo4Aa": ["纯文本"],
"pSimwP": [["editor"], " 版本的新名称"],
"pTPqMK": ["切换围栏代码块。"],
@@ -3276,7 +3296,6 @@
"qjHMHf": ["关闭同步失败——", ["detail"]],
"qkqG0b": ["采用远程版本"],
"qlAIQ1": ["远程"],
- "qlnfTD": ["图片加载失败:", ["errorLabel"]],
"qmL1UG": ["正在安全上传"],
"qo4zCg": ["路径不能包含反斜杠"],
"qpQwGC": ["描述一下你在做什么,智能体会为你搭建好。"],
@@ -3315,6 +3334,7 @@
"rXz97P": ["带编号的项目列表。"],
"rZ9HZq": ["待办"],
"rZVMkf": ["可视化编辑器替换输入框已聚焦"],
+ "radOpL": ["图片 ", ["identity"], "。转到引用位置。"],
"rageVb": ["带实时预览面板的自定义 HTML(沙箱 iframe)。"],
"rbrHTd": ["已批准 — ", ["optionName"]],
"rcJmK8": ["把这些位置改为副本"],
@@ -3459,6 +3479,7 @@
"tsiTqO": ["粘贴你的 API 密钥"],
"tsyExA": ["把你的 AI 工具连接到 OpenKnowledge"],
"tvMvze": ["无法将“", ["targetName"], "”移到", ["trashNoun"], "。是否要改为永久删除?"],
+ "txUHO8": ["第 ", ["displayLine"], " 行:", ["localizedMessage"]],
"tzGWeg": ["正在准备卸载 OpenKnowledge"],
"tzZ6ha": ["连接到 GitHub Enterprise Server"],
"u-9fWA": ["系统总览见<0>架构</0>。"],
@@ -3473,7 +3494,6 @@
"uA_jXp": ["切换并更新分支"],
"uBAxNB": ["编辑器"],
"uCaIdy": ["GitHub 登录缺失或已过期。请重新连接以继续同步。"],
- "uCe4AX": [["0"], ",第 ", ["displayLine"], " 行"],
"uDlyqd": [
"记录这个仓库的架构:创建一页总览,链接到每个主要模块的页面,说明各自的职责和入口。"
],
@@ -3537,6 +3557,7 @@
"vPEyDz": ["智能体记录"],
"vPF04k": ["开始新对话"],
"vPKX2i": ["在应用内(beta)"],
+ "vPLUCm": ["图片 ", ["identity"], " 不存在。转到引用位置。"],
"vPXOUw": ["切换源码视图"],
"vQIVHc": ["文件夹属性"],
"vWc9a0": ["输入即可编辑;<0>⌘ Enter</0> 保存,<1>Esc</1> 取消。"],
@@ -3675,6 +3696,7 @@
"xxRpzT": ["在你的系统中找到 Slidev。"],
"xzAmL_": ["已自动批准"],
"xzktOa": ["编辑维基链接"],
+ "y-LQPF": ["无法解析图片 ", ["identity"], "。转到引用位置。"],
"y1eoq1": ["复制链接"],
"y1t8bQ": ["设置分区"],
"y3aU20": ["保存更改"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index dec5639c9..2ac840169 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} 不经询问即执行操作 — OpenKnowledge 无法为其添加权
msgid "{0} added, {1} removed"
msgstr "新增 {0} 项,移除 {1} 项"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0},第 {displayLine} 行"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, other {# 个链接}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}:{message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "第 {displayLine} 行:{localizedMessage}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, other {# 分钟前}}"
@@ -2208,6 +2207,10 @@ msgstr "正在 GitHub 上检查更新"
msgid "Checking GitHub connection..."
msgstr "正在检查 GitHub 连接…"
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "正在检查链接"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "正在检出文件"
@@ -5057,6 +5060,10 @@ msgstr "加载标题失败"
msgid "Failed to load hub pages"
msgstr "加载中枢页面失败"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "加载本地文件失败"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "加载孤立页面失败"
@@ -5284,6 +5291,10 @@ msgstr "字段"
msgid "File"
msgstr "文件"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "文件 {identity}。转到引用位置。"
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "文件已存在"
@@ -6034,6 +6045,10 @@ msgstr "你觉得 OpenKnowledge 怎么样?"
msgid "How does sharing work?"
msgstr "共享是怎么运作的?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "如何在“问题”、编辑器诊断、审计和代理工具中报告缺失的项目本地文档、文件和图像。"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "如何手动推送"
@@ -6051,10 +6066,6 @@ msgstr "如何设置"
msgid "How to set up {0} (opens in browser)"
msgstr "如何设置 {0}(在浏览器中打开)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "未解析的维基链接在「问题」面板、审查结果和智能体工具中如何呈现。"
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "校验结果在项目中如何呈现。这些选项会写入 config.yml,并通过 git 与所有协作者共享。"
@@ -6110,13 +6121,33 @@ msgstr "忽略模式"
msgid "Ignore patterns (raw text)"
msgstr "忽略模式(纯文本)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "图片 {identity}。转到引用位置。"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "无法显示图片"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "图片加载失败"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "无法显示图片:{errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "图片加载失败:{errorLabel}"
+msgid "Image not found"
+msgstr "找不到图片"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "找不到图片:{errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "无法将图片目标“{shown}”解析为项目本地文件。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "图片目标“{shown}”未指向现有文件。"
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "链接已生成,但无法复制到剪贴板。"
msgid "Link target"
msgstr "链接目标"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "无法将链接目标“{shown}”解析为项目本地目标。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "链接目标“{shown}”未指向现有文档。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "链接目标“{shown}”未指向现有文件。"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "为选中的文本加链接,或编辑光标处的链接。"
@@ -6729,6 +6772,14 @@ msgstr "链接到某个页面或外部 URL。"
msgid "Link URL"
msgstr "链接 URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "链接验证不可用。"
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "链接验证不可用。正在显示上次已知的问题。"
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "链接关系图响应的结构与预期不符。"
@@ -6925,6 +6976,14 @@ msgstr "无法清除“{docName}”的本地协作数据。请重新加载后重
msgid "Local commits are keeping this copy from updating"
msgstr "本地提交使这份副本无法更新"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "本地文件详情尚不可用。"
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "本地文件"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "本地路径"
@@ -7101,10 +7160,22 @@ msgstr "镜像来源 <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "镜像来源 <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "缺失"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "缺少某个功能"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "文件 {identity} 不存在。转到引用位置。"
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "图片 {identity} 不存在。转到引用位置。"
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "页面不存在——点击可创建"
@@ -8021,10 +8092,9 @@ msgstr "带编号的项目列表。"
msgid "Object"
msgstr "对象"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "{0} 的出现位置"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "{localizedFirstMessage} 的出现位置"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "这个页面还不存在。打开它即可在编辑器中创建该页面
msgid "This page doesn't link to anything yet."
msgstr "这个页面还没有链接到任何地方。"
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "此页面未引用任何本地文件或图片。"
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "这个路径位于外置卷(/Volumes/...)。驱动器弹出后,OpenKnowledge 会跟丢这些文件。"
@@ -12868,6 +12942,18 @@ msgstr "无法识别的链接"
msgid "Unrecognized wiki link"
msgstr "无法识别的维基链接"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "无法解析"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "无法解析文件 {identity}。转到引用位置。"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "无法解析图片 {identity}。转到引用位置。"
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "已是最新"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 1f123476d..5456b7d95 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -147,11 +147,13 @@
"1njn7W": ["淺色"],
"1nke1r": ["在 GitHub 上開啟 ", ["0"], "(在新分頁中開啟)"],
"1oSHI0": ["無法安裝 ", ["skillName"], ":", ["0"]],
+ "1pdLQw": ["找不到圖片"],
"1qpGKz": ["無法儲存變更。請再編輯一次色彩。"],
"1ruosn": ["OpenKnowledge"],
"1t_NnN": ["拒絕"],
"1u-mAI": ["無法開始同步。請檢查你的網路連線,然後再試一次。"],
"1vn0CI": ["伺服器回應無效"],
+ "1xui0Q": ["載入本機檔案失敗"],
"2277Tu": ["摺疊關係圖"],
"237hSL": ["已結束"],
"253MN6": ["無法傳送你的註解——請再試一次。"],
@@ -409,6 +411,7 @@
"6HCOwA": ["開啟失敗。"],
"6KCH4m": ["隱藏檔案"],
"6KXnz5": ["你可以從垃圾桶還原此檔案。"],
+ "6LJJ1v": ["檔案 ", ["identity"], "。前往引用位置。"],
"6LbUG7": ["這個儲存庫是私人的,你的 GitHub 帳戶沒有存取權。"],
"6Mbe-P": [
"描述它該做什麼,或者自己加一個。OpenKnowledge 會把你的技能集中保存、做版本管理,並安裝到 Claude、Codex、Cursor 等代理裡。"
@@ -882,7 +885,6 @@
"EPwuTC": ["已使用 ", ["usedLabel"], " / ", ["sizeLabel"], " 個 token"],
"EQXPXf": ["捲動到結尾"],
"ETyvvg": ["沒有相符的語言。"],
- "EUiJEM": [["0"], " 出現的位置"],
"EWCJFu": ["已建立 ", ["target"]],
"EWPtMO": ["程式碼"],
"EWX92Z": ["摺疊「問 AI」"],
@@ -1139,6 +1141,7 @@
"IgN3LY": ["在 <0>", ["address"], "</0> 中選取的文字上"],
"IgTwLt": ["在編輯器中開啟這份文件並摺疊關係圖。"],
"Ik-gP0": ["第 ", ["level"], " 級標題:", ["text"]],
+ "IoHQYP": ["連結驗證無法使用。正在顯示上次已知的問題。"],
"Iq8zdU": ["關閉終端機"],
"IrB5AK": [["failedCount", "plural", { "other": ["#", " 個項目"] }], "的伺服器端清理失敗"],
"IrC12v": ["應用程式"],
@@ -1308,6 +1311,7 @@
"Lm3r51": ["Slidev 無法算繪此文件。"],
"LnVIW4": ["啟動登入失敗——請再試一次"],
"LpB85N": ["純文字"],
+ "Lrsl_h": ["檔案 ", ["identity"], " 不存在。前往引用位置。"],
"LtI9AS": ["擁有者"],
"LtSYdi": ["在 Finder 中顯示"],
"LtiJ5c": ["專案技能"],
@@ -1396,7 +1400,6 @@
"把游標停在外部連結上時,它的 URL 會送到目標網站,以取得那個頁面的預覽中繼資料——每個被預覽的連結送一次要求。"
],
"MysZUL": ["正在連線到 ", ["agentName"], "…"],
- "N-IonL": ["未解析的維基連結會如何呈現在「問題」面板、稽核結果和代理工具中。"],
"N1KkEO": ["跳到最後一個分頁"],
"N1YYa7": ["正在載入圖片"],
"N1mdmS": ["這個檔案無法在文字編輯器中開啟。"],
@@ -1790,6 +1793,7 @@
"U2Kx6T": ["關閉所有未釘選的"],
"U2pMtf": ["tag-name"],
"U3IvM5": ["完整指南"],
+ "U3RIJu": ["本機檔案"],
"U4nTfu": ["啟用「跟隨」"],
"U5Spo9": ["內容目錄必須在專案裡面"],
"U6wmNc": ["同步已暫停"],
@@ -1901,12 +1905,14 @@
"VNNRfN": ["設為來源"],
"VNgKZz": ["進階設定"],
"VTulZj": ["在 worktree 中開啟"],
+ "VU3Nrn": ["缺失"],
"VUijjF": ["嵌入一張圖片,可選填替代文字。"],
"VVRrPk": [["0"], " 沒有可調整的設定"],
"VXGFMg": ["程式碼欄位的復原或重做"],
"VYd_YA": ["從磁碟開啟一個既有的專案資料夾。"],
"VZGh8G": ["摺疊、展開、全部摺疊或全部展開原始碼範圍。"],
"VZSBXL": ["語意排序會在代理第一次執行搜尋時啟用。"],
+ "VZg6Gn": ["無法顯示圖片:", ["errorLabel"]],
"V_6bJ4": ["終端機設定尚未載入——請稍候再試。"],
"V_DjMe": ["算繪錯誤"],
"V_wltx": ["請為這個範本輸入標題。"],
@@ -1931,12 +1937,14 @@
"W1qRuM": ["這份文件已經在編輯器中開啟了。請用「開啟」來摺疊關係圖。"],
"W3Tsgy": ["在 ", ["0"], " 中偵測到"],
"W5A0Ly": ["發生了非預期的錯誤。"],
+ "W5qdI_": ["無法將圖片目標「", ["shown"], "」解析為專案本機檔案。"],
"W7XJN4": [
"專案不能巢狀。<0>",
["rootPath"],
"</0> 已經有一個 OpenKnowledge 專案了。請選它以外的位置,或者直接開啟那個專案。"
],
"W8vpBM": ["入門套件"],
+ "W9NSe0": ["正在檢查連結"],
"W9_Bub": ["本機變更和傳入的同步內容重疊"],
"WBNpt9": ["無法讀取這個主題(", ["0"], ")"],
"WFEbV1": ["在編輯器中標出常見的 markdown 問題。由 <0>markdownlint<1/></0> 提供。"],
@@ -1997,11 +2005,13 @@
"X8kjQX": ["重新用 GitHub 驗證"],
"X9VpsP": ["正在載入資料夾內容"],
"XAyxsa": ["簽出遠端分支"],
+ "XBBZnv": ["連結目標「", ["shown"], "」未指向現有文件。"],
"XBgr2S": ["複製進來"],
"XDzAnp": ["在新分頁中開啟"],
"XFpEgc": [
"選擇哪些智慧代理顯示在應用程式的代理選單中,例如 Ask AI、Open with AI 和 + 新對話按鈕。關閉某個智慧代理即可在所有選單中隱藏它。"
],
+ "XGKy1z": ["無法顯示圖片"],
"XH30C4": ["文件"],
"XIltnd": ["這裡已存在名為「", ["trimmed"], "」的技能"],
"XJOV1Y": ["動態"],
@@ -2019,6 +2029,7 @@
"XW18jo": ["頁面標題回應不符合成功時的結構描述"],
"XWEqQj": [["days"], "天"],
"XXA1b_": [["componentLabel"], "(空的)"],
+ "XYZ7tp": ["無法解析"],
"XYlJJT": ["正在設定"],
"XZkdtg": ["切換分支"],
"XcGbim": ["顯示隱藏的檔案"],
@@ -2095,6 +2106,7 @@
"YW7Q86": ["搜尋設定尚未載入——請稍候再試"],
"Y_GpJd": [["0"], " 的下載要求逾時。"],
"Y_ZQ6l": ["正在安裝 ", ["agentName"], "…"],
+ "Y_iImT": ["無法解析檔案 ", ["identity"], "。前往引用位置。"],
"Y_kL7X": ["自訂編輯器的外觀和行為。"],
"Ya3PlJ": ["需要授權"],
"YaeyFh": ["拉取可能會覆蓋你本機檔案中尚未提交的編輯。"],
@@ -2199,6 +2211,7 @@
["currentLabel"],
"</1> 上。"
],
+ "_Bix3-": [["localizedFirstMessage"], " 的出現位置"],
"_DwR-n": ["正在建立…"],
"_FLBbi": [["sizeText"], " · 已遮蔽機密資訊 · 當機傾印未遮蔽"],
"_GRWOJ": ["要更換嵌入服務供應商嗎?"],
@@ -2336,6 +2349,7 @@
"blFttG": ["搜尋專案"],
"bmC18N": ["正在重新連線前清除「", ["docName"], "」的本機協作資料。"],
"bnOTEz": ["擷取中…"],
+ "bpMVIA": ["無法將連結目標「", ["shown"], "」解析為專案本機目標。"],
"bpytj4": ["移動到 ", ["0"]],
"brCtGB": ["無法取得記錄"],
"buNXgr": ["在視覺化編輯器和原始碼編輯器之間切換,並保持目前的位置。"],
@@ -2544,6 +2558,7 @@
"fJgQHX": ["建立檔案失敗"],
"fMsFdZ": ["無法儲存自動更新設定:", ["0"]],
"fNr-MX": ["關閉語意搜尋"],
+ "fOzzSV": ["連結目標「", ["shown"], "」未指向現有檔案。"],
"fR-Kdc": ["(僅專案層級)"],
"fRVBiq": [
"在可取得時附上遙測資料、伺服器狀態和執行階段資訊。憑證一律會移除;如果包含文件名稱,它們會以明文出現(不做遮蔽)。"
@@ -2579,6 +2594,7 @@
"fwrPh4": ["請輸入有效的電子郵件。"],
"fxJk_6": ["<0>還有想補充的嗎?</0>請寫信到 <1/> 並附上你的編號。"],
"fxbCNQ": ["已同步。連結是最新的。"],
+ "g-dkjJ": ["本機檔案詳情尚無法使用。"],
"g12y1g": ["無效的 YAML"],
"g1ZTh_": [
["count", "plural", { "other": ["確定要刪除以下 ", "#", " 個檔案/資料夾及其內容嗎?"] }]
@@ -2643,6 +2659,7 @@
"gmJ0An": ["開啟資料夾失敗。"],
"goO4Ll": ["編輯器狀態列"],
"gp3I7-": ["同步之前,請先設定你用於 git 提交的身分:"],
+ "gpbKxw": ["連結驗證無法使用。"],
"gqk-3R": ["已將 ", ["0"], " 移動到 ", ["destination"], "。"],
"gtEbeW": ["醒目提示"],
"gtGQ9S": ["啟動 ", ["agentName"], ",", ["hint"]],
@@ -2751,6 +2768,7 @@
"iRdfLr": ["開發執行個體:", ["label"]],
"iSLIjg": ["連接"],
"iSQTsg": ["編號清單"],
+ "iSWh95": ["圖片目標「", ["shown"], "」未指向現有檔案。"],
"iSnkwB": ["開啟複製下來的專案失敗。"],
"iTylMl": ["範本"],
"iUwpZI": ["不能有空格——請改用 <0>-</0>。"],
@@ -2787,6 +2805,7 @@
"用這個範本建立的每份文件會得到的 <0>type</0>(例如 <1>research-note</1>)。讓新文件符合 Open Knowledge Format。"
],
"iqIDv4": ["無法取得同步狀態"],
+ "iqr14Z": ["如何在「問題」、編輯器診斷、稽核和代理工具中報告缺少的專案本機文件、檔案和影像。"],
"iqugog": ["初始化失敗:", ["errorDetail"]],
"irFGwu": ["範本清單"],
"irrm_E": ["移除選取範圍"],
@@ -2884,6 +2903,7 @@
"kCqCyf": ["開啟 CodeMirror 的檢查診斷面板。"],
"kFLlsI": ["插入一個註腳參照,以及對應的定義草稿。"],
"kGp168": ["無法為發布準備這個專案。"],
+ "kI5pWt": ["找不到圖片:", ["errorLabel"]],
"kKw0H3": [
"你在本機編輯過這個技能,而來源又有了新的變更。採用上游版本會取代你的版本;你的編輯仍然可以在版本記錄中找回。"
],
@@ -3093,7 +3113,6 @@
"nCzR-G": ["複製驗證碼 ", ["userCode"]],
"nDT8qt": ["已初始化 ", ["0"], ",但無法開啟它。"],
"nG-XA9": ["錨定的文字已經不見了。你可以把它重新定位到選取的文字上。"],
- "nL-HHD": ["圖片載入失敗"],
"nMSYz5": [
"這個路徑在外接磁碟區(/Volumes/...)上。磁碟退出後,OpenKnowledge 會找不到這些檔案。"
],
@@ -3210,6 +3229,7 @@
"pFRz_E": ["不要把這些註解放進這則訊息"],
"pFagOn": ["原始碼編輯"],
"pHYP6v": ["在側邊欄中開啟<0>自訂</0> <1/> <2>技能</2>。"],
+ "pJ7XCo": ["此頁面未引用任何本機檔案或圖片。"],
"pOo4Aa": ["純文字"],
"pSimwP": [["editor"], " 版本的新名稱"],
"pTPqMK": ["切換圍欄程式碼區塊。"],
@@ -3302,7 +3322,6 @@
"qjHMHf": ["關閉同步失敗——", ["detail"]],
"qkqG0b": ["採用上游版本"],
"qlAIQ1": ["遠端"],
- "qlnfTD": ["圖片載入失敗:", ["errorLabel"]],
"qmL1UG": ["正在安全上傳"],
"qo4zCg": ["路徑不能包含反斜線"],
"qpQwGC": ["描述一下你正在做的事,代理就會幫你設定好。"],
@@ -3341,6 +3360,7 @@
"rXz97P": ["有編號的項目清單。"],
"rZ9HZq": ["待辦"],
"rZVMkf": ["視覺化編輯器取代輸入框已聚焦"],
+ "radOpL": ["圖片 ", ["identity"], "。前往引用位置。"],
"rageVb": ["帶即時預覽窗格的自訂 HTML(沙箱 iframe)。"],
"rbrHTd": ["已核准 — ", ["optionName"]],
"rcJmK8": ["把這些位置改成副本"],
@@ -3485,6 +3505,7 @@
"tsiTqO": ["貼上你的 API 金鑰"],
"tsyExA": ["把你的 AI 工具連接到 OpenKnowledge"],
"tvMvze": ["無法將「", ["targetName"], "」移到", ["trashNoun"], "。是否要改為永久刪除?"],
+ "txUHO8": ["第 ", ["displayLine"], " 行:", ["localizedMessage"]],
"tzGWeg": ["正在準備解除安裝 OpenKnowledge"],
"tzZ6ha": ["連接到 GitHub Enterprise Server"],
"u-9fWA": ["系統總覽見<0>架構</0>。"],
@@ -3499,7 +3520,6 @@
"uA_jXp": ["切換並更新分支"],
"uBAxNB": ["編輯器"],
"uCaIdy": ["GitHub 登入不存在或已過期。請重新連接以繼續同步。"],
- "uCe4AX": [["0"], ",第 ", ["displayLine"], " 行"],
"uDlyqd": [
"記錄這個儲存庫的架構:建立一頁總覽,連到每個主要模組的頁面,說明各自的職責和進入點。"
],
@@ -3565,6 +3585,7 @@
"vPEyDz": ["代理記錄"],
"vPF04k": ["開始新的對話"],
"vPKX2i": ["在應用程式內(beta)"],
+ "vPLUCm": ["圖片 ", ["identity"], " 不存在。前往引用位置。"],
"vPXOUw": ["切換原始碼檢視"],
"vQIVHc": ["資料夾屬性"],
"vWc9a0": ["輸入即可編輯;<0>⌘ Enter</0> 儲存,<1>Esc</1> 取消。"],
@@ -3703,6 +3724,7 @@
"xxRpzT": ["在你的系統中找到 Slidev。"],
"xzAmL_": ["已自動核准"],
"xzktOa": ["編輯維基連結"],
+ "y-LQPF": ["無法解析圖片 ", ["identity"], "。前往引用位置。"],
"y1eoq1": ["複製連結"],
"y1t8bQ": ["設定分區"],
"y3aU20": ["儲存變更"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 5b11b475c..93dd6f373 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -265,11 +265,6 @@ msgstr "{0} 不經詢問即執行操作 — OpenKnowledge 無法為其加入權
msgid "{0} added, {1} removed"
msgstr "新增 {0} 項,移除 {1} 項"
-#. placeholder {0}: diagnostic.message
-#: src/components/ProblemsPanel.tsx
-msgid "{0} at line {displayLine}"
-msgstr "{0},第 {displayLine} 行"
-
#. placeholder {0}: info.agent.name
#: src/components/acp/ThreadView.tsx
msgid "{0} can't continue this chat — the transcript is kept, but the agent session is gone."
@@ -689,6 +684,10 @@ msgstr "{linkCount, plural, other {# 個連結}}"
msgid "{loadErrorTitle}: {message}"
msgstr "{loadErrorTitle}:{message}"
+#: src/components/ProblemsPanel.tsx
+msgid "{localizedMessage} at line {displayLine}"
+msgstr "第 {displayLine} 行:{localizedMessage}"
+
#: src/components/TimelinePanel.tsx
msgid "{mins, plural, one {# min ago} other {# min ago}}"
msgstr "{mins, plural, other {# 分鐘前}}"
@@ -2208,6 +2207,10 @@ msgstr "正在 GitHub 上檢查更新"
msgid "Checking GitHub connection..."
msgstr "正在檢查 GitHub 連線…"
+#: src/components/ProblemsPanel.tsx
+msgid "Checking links"
+msgstr "正在檢查連結"
+
#: src/components/CloneDialog.tsx
msgid "Checking out files"
msgstr "正在簽出檔案"
@@ -5057,6 +5060,10 @@ msgstr "載入標題失敗"
msgid "Failed to load hub pages"
msgstr "載入樞紐頁面失敗"
+#: src/components/LinksPanel.tsx
+msgid "Failed to load local files"
+msgstr "載入本機檔案失敗"
+
#: src/components/GraphPanel.tsx
msgid "Failed to load orphan pages"
msgstr "載入孤立頁面失敗"
@@ -5284,6 +5291,10 @@ msgstr "欄位"
msgid "File"
msgstr "檔案"
+#: src/components/LinksPanel.tsx
+msgid "File {identity}. Go to reference."
+msgstr "檔案 {identity}。前往引用位置。"
+
#: src/components/FileTree.tsx
msgid "File already exists"
msgstr "檔案已存在"
@@ -6034,6 +6045,10 @@ msgstr "你覺得 OpenKnowledge 如何?"
msgid "How does sharing work?"
msgstr "分享是怎麼運作的?"
+#: src/components/settings/ContentRulesSection.tsx
+msgid "How missing project-local documents, files, and images are reported in Problems, editor diagnostics, audits, and agent tools."
+msgstr "如何在「問題」、編輯器診斷、稽核和代理工具中報告缺少的專案本機文件、檔案和影像。"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "How to push manually"
msgstr "如何手動推送"
@@ -6051,10 +6066,6 @@ msgstr "如何設定"
msgid "How to set up {0} (opens in browser)"
msgstr "如何設定 {0}(在瀏覽器中開啟)"
-#: src/components/settings/ContentRulesSection.tsx
-msgid "How unresolved wiki-links are reported in the Problems panel, audits, and agent tools."
-msgstr "未解析的維基連結會如何呈現在「問題」面板、稽核結果和代理工具中。"
-
#: src/components/settings/ContentRulesSection.tsx
msgid "How validation findings surface across the project. These choices are committed to config.yml and shared with every collaborator via git."
msgstr "驗證結果會如何呈現在專案各處。這些選擇會寫進 config.yml,並透過 git 分享給每位協作者。"
@@ -6110,13 +6121,33 @@ msgstr "忽略模式"
msgid "Ignore patterns (raw text)"
msgstr "忽略模式(純文字)"
+#: src/components/LinksPanel.tsx
+msgid "Image {identity}. Go to reference."
+msgstr "圖片 {identity}。前往引用位置。"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image couldn't be displayed"
+msgstr "無法顯示圖片"
+
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load"
-msgstr "圖片載入失敗"
+msgid "Image couldn't be displayed: {errorLabel}"
+msgstr "無法顯示圖片:{errorLabel}"
#: src/components/ui/loading-image.tsx
-msgid "Image failed to load: {errorLabel}"
-msgstr "圖片載入失敗:{errorLabel}"
+msgid "Image not found"
+msgstr "找不到圖片"
+
+#: src/components/ui/loading-image.tsx
+msgid "Image not found: {errorLabel}"
+msgstr "找不到圖片:{errorLabel}"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" could not be resolved to a project-local file."
+msgstr "無法將圖片目標「{shown}」解析為專案本機檔案。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Image target \"{shown}\" does not resolve to an existing file."
+msgstr "圖片目標「{shown}」未指向現有檔案。"
#: src/components/ImportSkillForm.tsx
msgid "Import"
@@ -6717,6 +6748,18 @@ msgstr "連結已備妥,但無法複製到剪貼簿。"
msgid "Link target"
msgstr "連結目標"
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" could not be resolved to a project-local target."
+msgstr "無法將連結目標「{shown}」解析為專案本機目標。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing document."
+msgstr "連結目標「{shown}」未指向現有文件。"
+
+#: src/editor/localized-validation-message.ts
+msgid "Link target \"{shown}\" does not resolve to an existing file."
+msgstr "連結目標「{shown}」未指向現有檔案。"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Link the selected text, or edit the link under the caret."
msgstr "為選取的文字加上連結,或編輯游標處的連結。"
@@ -6729,6 +6772,14 @@ msgstr "連到某個頁面或外部 URL。"
msgid "Link URL"
msgstr "連結 URL"
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable."
+msgstr "連結驗證無法使用。"
+
+#: src/components/ProblemsPanel.tsx
+msgid "Link validation is unavailable. Showing last known problems."
+msgstr "連結驗證無法使用。正在顯示上次已知的問題。"
+
#: src/components/GraphView.tsx
msgid "Link-graph response did not match expected shape."
msgstr "連結關係圖回應的結構與預期不符。"
@@ -6925,6 +6976,14 @@ msgstr "無法清除「{docName}」的本機協作資料。請重新載入後再
msgid "Local commits are keeping this copy from updating"
msgstr "本機的提交讓這份副本無法更新"
+#: src/components/LinksPanel.tsx
+msgid "Local file details aren't available yet."
+msgstr "本機檔案詳情尚無法使用。"
+
+#: src/components/LinksPanel.tsx
+msgid "Local files"
+msgstr "本機檔案"
+
#: src/components/CloneDialog.tsx
msgid "Local path"
msgstr "本機路徑"
@@ -7101,10 +7160,22 @@ msgstr "鏡像來源 <0>{label}</0>"
msgid "Mirror source <0>api-spec</0>"
msgstr "鏡像來源 <0>api-spec</0>"
+#: src/components/LinksPanel.tsx
+msgid "Missing"
+msgstr "缺失"
+
#: src/components/FeedbackForm.tsx
msgid "Missing a feature"
msgstr "缺少某個功能"
+#: src/components/LinksPanel.tsx
+msgid "Missing file {identity}. Go to reference."
+msgstr "檔案 {identity} 不存在。前往引用位置。"
+
+#: src/components/LinksPanel.tsx
+msgid "Missing image {identity}. Go to reference."
+msgstr "圖片 {identity} 不存在。前往引用位置。"
+
#: src/components/LinksPanel.tsx
msgid "Missing page — click to create"
msgstr "頁面不存在——點一下可建立"
@@ -8021,10 +8092,9 @@ msgstr "有編號的項目清單。"
msgid "Object"
msgstr "物件"
-#. placeholder {0}: first.message
#: src/components/ProblemsPanel.tsx
-msgid "Occurrences of {0}"
-msgstr "{0} 出現的位置"
+msgid "Occurrences of {localizedFirstMessage}"
+msgstr "{localizedFirstMessage} 的出現位置"
#. placeholder {0}: basenameOf(project.mainRoot ?? '')
#: src/components/NavigatorApp.tsx
@@ -12329,6 +12399,10 @@ msgstr "這個頁面還不存在。開啟它就能在編輯器中建立這個頁
msgid "This page doesn't link to anything yet."
msgstr "這個頁面還沒有連到任何地方。"
+#: src/components/LinksPanel.tsx
+msgid "This page references no local files or images."
+msgstr "此頁面未引用任何本機檔案或圖片。"
+
#: src/components/ConsentDialogBody.tsx
msgid "This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."
msgstr "這個路徑在外接磁碟區(/Volumes/...)上。磁碟退出後,OpenKnowledge 會找不到這些檔案。"
@@ -12868,6 +12942,18 @@ msgstr "無法辨識的連結"
msgid "Unrecognized wiki link"
msgstr "無法辨識的維基連結"
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable"
+msgstr "無法解析"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable file {identity}. Go to reference."
+msgstr "無法解析檔案 {identity}。前往引用位置。"
+
+#: src/components/LinksPanel.tsx
+msgid "Unresolvable image {identity}. Go to reference."
+msgstr "無法解析圖片 {identity}。前往引用位置。"
+
#: src/components/SyncStatusBadge.tsx
msgid "Up to date"
msgstr "已是最新"
diff --git a/packages/app/src/server/hocuspocus-plugin.test.ts b/packages/app/src/server/hocuspocus-plugin.test.ts
index dd90f39f2..199e4bc01 100644
--- a/packages/app/src/server/hocuspocus-plugin.test.ts
+++ b/packages/app/src/server/hocuspocus-plugin.test.ts
@@ -128,29 +128,30 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {
const destroyServer = vi.fn(async () => {
teardownOrder.push('server');
});
+ const createServerSpy = vi.fn(() => ({
+ lockDir: testContentDir,
+ contentFilter: { isPathIgnored: () => false },
+ hocuspocus: {
+ hooks: async () => {},
+ getConnectionsCount: () => 0,
+ handleConnection: () => ({
+ handleMessage: () => {},
+ handleClose: () => {},
+ }),
+ },
+ sessionManager: { closeAllForAgent: async () => {} },
+ agentFocusBroadcaster: { clearFocus: () => {} },
+ agentPresenceBroadcaster: { clearPresence: () => {}, bumpPresenceTs: () => {} },
+ maintenanceCoordinator: {},
+ destroy: destroyServer,
+ }));
vi.doMock('@inkeep/open-knowledge-server', () => ({
...actualServerPkg,
AcpThreadManager: FakeAcpThreadManager,
createAssetServeMiddleware: createAssetServeMiddlewareSpy,
createCollaborationHost: createCollaborationHostSpy,
- createServer: () => ({
- lockDir: testContentDir,
- contentFilter: { isPathIgnored: () => false },
- hocuspocus: {
- hooks: async () => {},
- getConnectionsCount: () => 0,
- handleConnection: () => ({
- handleMessage: () => {},
- handleClose: () => {},
- }),
- },
- sessionManager: { closeAllForAgent: async () => {} },
- agentFocusBroadcaster: { clearFocus: () => {} },
- agentPresenceBroadcaster: { clearPresence: () => {}, bumpPresenceTs: () => {} },
- maintenanceCoordinator: {},
- destroy: destroyServer,
- }),
+ createServer: createServerSpy,
handleCollabSocketError: () => false,
parseKeepaliveConnectionId: () => null,
releaseServerLock: () => {},
@@ -187,6 +188,9 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {
// biome-ignore lint/suspicious/noExplicitAny: minimal Vite ViteDevServer stub for the structural assertion
const result = await (plugin.configureServer as any).call(plugin, viteServerStub);
+ const createServerOptions = createServerSpy.mock.calls[0]?.[0];
+ expect(createServerOptions?.configHomedirOverride).toBe(createServerOptions?.contentDir);
+
// No post-hook returned — both middlewares are registered synchronously.
// (Returning a function would defer registration to AFTER Vite's internal
// middlewares, which would let `spaFallbackMiddleware` win for asset URLs.)
diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.ts
index deb090c40..1e3a69056 100644
--- a/packages/app/src/server/hocuspocus-plugin.ts
+++ b/packages/app/src/server/hocuspocus-plugin.ts
@@ -185,6 +185,7 @@ export function hocuspocusPlugin(): Plugin {
contentDir: CONTENT_DIR,
projectDir: TEST_PROJECT_DIR ?? (isTestIsolated ? CONTENT_DIR : PROJECT_ROOT),
contentRoot: isTestIsolated ? '' : CONTENT_ROOT,
+ ...(isTestIsolated ? { configHomedirOverride: CONTENT_DIR } : {}),
// Ephemeral single-file mode forces git off (no shadow repo) regardless
// of OK_TEST_GIT_ENABLED, matching the real ephemeral boot.
gitEnabled: isEphemeralTest ? false : !isTestIsolated || gitEnabledForTest,
diff --git a/packages/app/tests/integration/link-authoring-contract.test.ts b/packages/app/tests/integration/link-authoring-contract.test.ts
index a993a9fea..0f1e10cf1 100644
--- a/packages/app/tests/integration/link-authoring-contract.test.ts
+++ b/packages/app/tests/integration/link-authoring-contract.test.ts
@@ -28,10 +28,21 @@ interface InitializedSession {
// declared core types. Importing the core type would let a silent type↔wire
// drift pass unnoticed — the literal expectations below are the contract, not
// the TypeScript declarations.
+interface LocalTargetEvidence {
+ href: string;
+ targetKind: string;
+ role: string;
+ sourceForm: string;
+ resolvedTarget: string | null;
+ reason: string;
+ resolutionMethod: string;
+ definition?: { line: number; label: string };
+}
interface BrokenLink {
href: string;
resolvedTo: string | null;
reason: 'no-such-doc' | 'no-such-file' | 'unresolvable';
+ localTarget?: LocalTargetEvidence;
}
async function openMcpSession(port: number): Promise<InitializedSession> {
@@ -286,6 +297,82 @@ test('the HTTP /api/agent-write-md response carries brokenLinks directly', async
]);
});
+test('write surfaces missing image + reference-style targets with local-target evidence', async () => {
+ const session = await openMcpSession(server.port);
+ const docName = `pics-${randomUUID().slice(0, 8)}`;
+ const content = [
+ '# Pics',
+ '',
+ '![logo](./logo.png)',
+ '',
+ 'See [the spec][spec].',
+ '',
+ '[spec]: ./spec.pdf',
+ '',
+ ].join('\n');
+
+ const result = await callTool(
+ server.port,
+ session,
+ 'write',
+ { document: { path: docName, content, position: 'replace' } },
+ server.contentDir,
+ );
+ expect(result.isError ?? false).toBe(false);
+ const doc = docResult(result.structuredContent);
+ const broken = doc.brokenLinks as BrokenLink[];
+
+ // The Markdown image — a form the graph-only triple never reached — is now a
+ // file finding carrying the same evidence scoped audit reports.
+ expect(broken.find((l) => l.href === './logo.png')).toEqual({
+ href: './logo.png',
+ resolvedTo: 'logo.png',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ });
+ // The reference-style use points at its shared definition for repair.
+ expect(broken.find((l) => l.href === './spec.pdf')).toEqual({
+ href: './spec.pdf',
+ resolvedTo: 'spec.pdf',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './spec.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'spec.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ definition: { line: 6, label: 'spec' },
+ },
+ });
+
+ // The same evidence rides the unified advisory (warnings) channel: the image
+ // is a lint-violation carrying localTarget, so an agent reading either channel
+ // derives one target identity.
+ const warnings = (doc.warnings ?? []) as Array<{
+ kind: string;
+ localTarget?: LocalTargetEvidence;
+ }>;
+ const imageViolation = warnings.find(
+ (w) => w.kind === 'lint-violation' && w.localTarget?.role === 'image',
+ );
+ expect(imageViolation?.localTarget?.resolvedTarget).toBe('logo.png');
+
+ // Report-only: the write landed byte-for-byte, images and reference syntax intact.
+ const stored = readFileSync(join(server.contentDir, `${docName}.md`), 'utf-8');
+ expect(stored).toContain('![logo](./logo.png)');
+ expect(stored).toContain('[spec]: ./spec.pdf');
+});
+
test('a link to a doc that actually exists is not flagged (admitted-set membership)', async () => {
const session = await openMcpSession(server.port);
const suffix = randomUUID().slice(0, 8);
diff --git a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
index f152f0ed8..0de3c32cb 100644
--- a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
+++ b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
@@ -38,6 +38,9 @@ const SERVER_FACTORY_PATH = join(SERVER_SRC_ROOT, 'server-factory.ts');
// api-extension wires the accessor into `createSearchService({ getAllFilesIndex })`
// the same way server-factory wires it into createApiExtension.
const SEARCH_SERVICE_PATH = join(SERVER_SRC_ROOT, 'services/search.ts');
+// The inventory adapter deliberately partitions every all-files entry by
+// `kind` before exposing separate document and file target sets.
+const LOCAL_TARGET_INVENTORY_PATH = join(SERVER_SRC_ROOT, 'local-target-inventory.ts');
// The native document/pages route group: hosts `handleDocumentList` (the
// `/api/documents` payload site) after its Wave 2 lift out of
// api-extension.ts. api-extension wires the accessor into
@@ -73,6 +76,9 @@ const ALLOWLISTED_SITES: ReadonlySet<string> = new Set<string>([
// Future `/api/documents` payload site. The exact handler is
// `handleDocumentList`; pre-allowlisted for the same reason as above.
'handleDocumentList',
+ // Write advisories consume the all-files index through the canonical local
+ // target inventory, so both entry kinds are partitioned before membership.
+ 'createLinkedFileExists',
]);
/**
@@ -205,6 +211,7 @@ describe('PRD-7117 US-002 — getAllFilesIndex caller coverage (D12 §13-A)', ()
API_EXT_PATH,
SERVER_FACTORY_PATH,
SEARCH_SERVICE_PATH,
+ LOCAL_TARGET_INVENTORY_PATH,
DOCUMENT_ROUTES_PATH,
]);
const offenders: string[] = [];
diff --git a/packages/app/tests/meta/link-audit-seams-coverage.test.ts b/packages/app/tests/meta/link-audit-seams-coverage.test.ts
new file mode 100644
index 000000000..791b4f52f
--- /dev/null
+++ b/packages/app/tests/meta/link-audit-seams-coverage.test.ts
@@ -0,0 +1,107 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import {
+ LINK_AUDIT_COMPOSITION_ROOTS,
+ LINK_AUDIT_SEAMS,
+ type LinkAuditCompositionRoot,
+ type LinkAuditSeam,
+} from './link-audit-seams.manifest.ts';
+
+const workspaceRoot = fileURLToPath(new URL('../../../../', import.meta.url));
+
+interface ValidationDeps {
+ exists(path: string): boolean;
+ read(path: string): string;
+}
+
+function validateLinkAuditSubstrate(
+ seams: readonly LinkAuditSeam[],
+ roots: readonly LinkAuditCompositionRoot[],
+ deps: ValidationDeps,
+): string[] {
+ const violations: string[] = [];
+ const ids = new Set<string>();
+
+ for (const seam of seams) {
+ if (ids.has(seam.id)) violations.push(`duplicate seam id: ${seam.id}`);
+ ids.add(seam.id);
+ for (const path of [...seam.modules, ...seam.tests.map((entry) => entry.path)]) {
+ if (!deps.exists(path)) violations.push(`${seam.id}: missing path ${path}`);
+ }
+ const presentTiers = new Set(seam.tests.map((entry) => entry.tier));
+ for (const tier of seam.requiredTiers) {
+ if (!presentTiers.has(tier)) violations.push(`${seam.id}: missing ${tier} coverage`);
+ }
+ }
+
+ const packageJson = deps.read('packages/app/package.json');
+ for (const testPath of new Set(
+ seams.flatMap((seam) =>
+ seam.tests.filter((entry) => entry.tier === 'browser-e2e').map((entry) => entry.path),
+ ),
+ )) {
+ const appRelative = testPath.replace(/^packages\/app\//, '');
+ if (!packageJson.includes(appRelative)) {
+ violations.push(`browser E2E is not in the blocking app test:e2e script: ${testPath}`);
+ }
+ }
+
+ for (const root of roots) {
+ if (!deps.exists(root.path)) {
+ violations.push(`missing composition root: ${root.path}`);
+ continue;
+ }
+ const source = deps.read(root.path);
+ if (!source.includes(root.requiredText)) {
+ violations.push(`composition root lost real wiring: ${root.path}`);
+ }
+ if (root.maskingText !== undefined && source.includes(root.maskingText)) {
+ violations.push(`composition root contains masking path: ${root.path}`);
+ }
+ }
+ return violations;
+}
+
+const realDeps: ValidationDeps = {
+ exists: (path) => existsSync(fileURLToPath(new URL(path, `file://${workspaceRoot}/`))),
+ read: (path) => readFileSync(fileURLToPath(new URL(path, `file://${workspaceRoot}/`)), 'utf-8'),
+};
+
+describe('local-target link-audit seam substrate', () => {
+ test('every declared seam carries its required rung and every composition root stays real', () => {
+ expect(
+ validateLinkAuditSubstrate(LINK_AUDIT_SEAMS, LINK_AUDIT_COMPOSITION_ROOTS, realDeps),
+ ).toEqual([]);
+ });
+
+ test('the checker fires on one planted missing test without flagging adjacent valid paths', () => {
+ const planted = LINK_AUDIT_SEAMS[0]?.tests[0]?.path;
+ expect(planted).toBeDefined();
+ const violations = validateLinkAuditSubstrate(LINK_AUDIT_SEAMS, [], {
+ ...realDeps,
+ exists: (path) => path !== planted && realDeps.exists(path),
+ });
+ expect(violations).toEqual([
+ `canonical-occurrence-classification: missing path ${planted as string}`,
+ ]);
+ });
+
+ test('the checker distinguishes missing real wiring from an adjacent masking path', () => {
+ const [root] = LINK_AUDIT_COMPOSITION_ROOTS.filter((entry) => entry.maskingText !== undefined);
+ expect(root).toBeDefined();
+ const missingReal = validateLinkAuditSubstrate([], [root as LinkAuditCompositionRoot], {
+ exists: () => true,
+ read: () => 'const localTargets = toForwardLinkLocalTargets([]);',
+ });
+ expect(missingReal).toEqual([
+ `composition root contains masking path: ${(root as LinkAuditCompositionRoot).path}`,
+ ]);
+
+ const adjacentValid = validateLinkAuditSubstrate([], [root as LinkAuditCompositionRoot], {
+ exists: () => true,
+ read: () => 'const localTargets = toForwardLinkLocalTargets(realAssessments);',
+ });
+ expect(adjacentValid).toEqual([]);
+ });
+});
diff --git a/packages/app/tests/meta/link-audit-seams.manifest.ts b/packages/app/tests/meta/link-audit-seams.manifest.ts
new file mode 100644
index 000000000..38949e0bb
--- /dev/null
+++ b/packages/app/tests/meta/link-audit-seams.manifest.ts
@@ -0,0 +1,198 @@
+export type LinkAuditTestTier = 'unit' | 'dom' | 'integration' | 'browser-e2e';
+
+export interface LinkAuditSeamTest {
+ path: string;
+ tier: LinkAuditTestTier;
+}
+
+export interface LinkAuditSeam {
+ id: string;
+ priority: 'P0' | 'P1';
+ owner: string;
+ failureClass: string;
+ modules: readonly string[];
+ tests: readonly LinkAuditSeamTest[];
+ requiredTiers: readonly LinkAuditTestTier[];
+}
+
+/**
+ * Product seams introduced or materially changed by the local-target audit.
+ * Paths are relative to the Open Knowledge workspace root. This is a closed
+ * inventory of this feature's contracts, not a claim to discover every future
+ * boundary in the repository.
+ */
+export const LINK_AUDIT_SEAMS: readonly LinkAuditSeam[] = [
+ {
+ id: 'canonical-occurrence-classification',
+ priority: 'P0',
+ owner: 'core markdown + server indexes',
+ failureClass: 'authored forms disagree across graph and audit planes',
+ modules: [
+ 'packages/core/src/markdown/link-reference-destination.ts',
+ 'packages/core/src/markdown/non-rendering-contexts.ts',
+ 'packages/server/src/link-syntax.ts',
+ 'packages/server/src/local-target-occurrences.ts',
+ 'packages/server/src/local-target-assessment.ts',
+ ],
+ tests: [
+ {
+ path: 'packages/server/src/link-classification-uniformity.test.ts',
+ tier: 'integration',
+ },
+ {
+ path: 'packages/server/src/link-syntax.test.ts',
+ tier: 'unit',
+ },
+ {
+ path: 'packages/server/src/local-target-occurrences.test.ts',
+ tier: 'unit',
+ },
+ ],
+ requiredTiers: ['unit', 'integration'],
+ },
+ {
+ id: 'watcher-backed-target-inventory',
+ priority: 'P0',
+ owner: 'server factory + derived document index',
+ failureClass: 'real files are absent from classification or fail to heal after disk events',
+ modules: [
+ 'packages/server/src/server-factory.ts',
+ 'packages/server/src/local-target-inventory.ts',
+ 'packages/server/src/local-target-index.ts',
+ 'packages/server/src/derived-document-index.ts',
+ ],
+ tests: [
+ {
+ path: 'packages/server/src/local-target-watcher-integration.test.ts',
+ tier: 'integration',
+ },
+ {
+ path: 'packages/app/tests/stress/local-target-audit.e2e.ts',
+ tier: 'browser-e2e',
+ },
+ ],
+ requiredTiers: ['integration', 'browser-e2e'],
+ },
+ {
+ id: 'write-time-agent-advisory',
+ priority: 'P0',
+ owner: 'server write API + MCP transport',
+ failureClass: 'the write succeeds but the agent receives stale or misclassified link evidence',
+ modules: [
+ 'packages/server/src/write-advisory-links.ts',
+ 'packages/server/src/api-extension.ts',
+ 'packages/core/src/schemas/api/agent-write.ts',
+ ],
+ tests: [
+ {
+ path: 'packages/app/tests/integration/link-authoring-contract.test.ts',
+ tier: 'integration',
+ },
+ { path: 'packages/server/src/write-advisory-links.test.ts', tier: 'unit' },
+ ],
+ requiredTiers: ['unit', 'integration'],
+ },
+ {
+ id: 'links-and-problems-projection',
+ priority: 'P0',
+ owner: 'forward-links route + document side panel',
+ failureClass: 'one target is reported as different kinds or offers an unsafe recovery action',
+ modules: [
+ 'packages/server/src/http/link-graph-routes.ts',
+ 'packages/app/src/components/LinksPanel.tsx',
+ 'packages/app/src/components/ProblemsPanel.tsx',
+ ],
+ tests: [
+ { path: 'packages/app/src/components/LinksPanel.dom.test.tsx', tier: 'dom' },
+ { path: 'packages/app/src/components/ProblemsPanel.dom.test.tsx', tier: 'dom' },
+ {
+ path: 'packages/app/tests/stress/local-target-audit.e2e.ts',
+ tier: 'browser-e2e',
+ },
+ {
+ path: 'packages/app/tests/stress/unified-problems.e2e.ts',
+ tier: 'browser-e2e',
+ },
+ ],
+ requiredTiers: ['dom', 'browser-e2e'],
+ },
+ {
+ id: 'source-and-wysiwyg-parity',
+ priority: 'P0',
+ owner: 'server audit client + CodeMirror + TipTap',
+ failureClass: 'editor modes disagree or a healed target remains visibly broken',
+ modules: [
+ 'packages/app/src/editor/SourceEditor.tsx',
+ 'packages/app/src/editor/source-lint/local-target-diagnostics.ts',
+ 'packages/app/src/editor/extensions/link-resolution.ts',
+ 'packages/app/src/editor/validation-audit-client.ts',
+ ],
+ tests: [
+ {
+ path: 'packages/app/src/editor/source-lint/local-target-parity.test.ts',
+ tier: 'integration',
+ },
+ {
+ path: 'packages/app/src/editor/source-lint/local-target-diagnostics.test.tsx',
+ tier: 'dom',
+ },
+ {
+ path: 'packages/app/tests/stress/local-target-audit.e2e.ts',
+ tier: 'browser-e2e',
+ },
+ ],
+ requiredTiers: ['dom', 'integration', 'browser-e2e'],
+ },
+ {
+ id: 'image-error-state-rendering',
+ priority: 'P0',
+ owner: 'TipTap image node views + browser asset loader',
+ failureClass: 'missing and undecodable images report the wrong severity or escape their layout',
+ modules: [
+ 'packages/app/src/components/ui/loading-image.tsx',
+ 'packages/app/src/editor/components/image-target-existence.ts',
+ 'packages/app/src/editor/extensions/bare-html-image-decoration.tsx',
+ 'packages/app/src/editor/extensions/ImageReferenceView.tsx',
+ 'packages/app/src/editor/extensions/WikiLinkEmbedImageView.tsx',
+ ],
+ tests: [
+ {
+ path: 'packages/app/src/components/ui/loading-image.dom.test.tsx',
+ tier: 'dom',
+ },
+ {
+ path: 'packages/app/tests/stress/image-invalid-placeholder.e2e.ts',
+ tier: 'browser-e2e',
+ },
+ ],
+ requiredTiers: ['dom', 'browser-e2e'],
+ },
+];
+
+export interface LinkAuditCompositionRoot {
+ path: string;
+ requiredText: string;
+ maskingText?: string;
+}
+
+/** Structural liveness checks for the real composition roots the behavioral
+ * tests above mutation-pin. These are enforcement, not behavioral evidence. */
+export const LINK_AUDIT_COMPOSITION_ROOTS: readonly LinkAuditCompositionRoot[] = [
+ {
+ path: 'packages/server/src/server-factory.ts',
+ requiredText: 'localTargetInventoryFromWatcher(watcher, contentDir)',
+ },
+ {
+ path: 'packages/server/src/http/link-graph-routes.ts',
+ requiredText: 'toForwardLinkLocalTargets(',
+ maskingText: 'toForwardLinkLocalTargets([])',
+ },
+ {
+ path: 'packages/app/src/editor/SourceEditor.tsx',
+ requiredText: 'createLocalTargetDiagnosticsExtension(docName)',
+ },
+ {
+ path: 'packages/app/src/editor/TiptapEditor.tsx',
+ requiredText: "ext.name === 'imageReference'",
+ },
+];
diff --git a/packages/app/tests/stress/image-invalid-placeholder.e2e.ts b/packages/app/tests/stress/image-invalid-placeholder.e2e.ts
new file mode 100644
index 000000000..73680444f
--- /dev/null
+++ b/packages/app/tests/stress/image-invalid-placeholder.e2e.ts
@@ -0,0 +1,278 @@
+/**
+ * Real-browser coverage for the truthful invalid-image placeholder
+ * (LoadingImage + the target-existence oracle). jsdom can drive the state
+ * machine but cannot load bytes, decode, cache, or run the watcher → oracle
+ * push; this exercises all of those against real Chromium + a real asset
+ * server:
+ *
+ * - a proven-absent target renders "Image not found" (markdown + HTML forms)
+ * without rewriting the authored source bytes;
+ * - an existing target whose bytes can't decode renders "Image couldn't be
+ * displayed", never claiming absence;
+ * - a page reload keeps the undecodable placeholder (cached-failure path:
+ * the <img> is `complete` at mount, so decode() is the only signal);
+ * - creating the target on disk heals "Image not found" to a loaded image
+ * without a reload (watcher → CC1 files push → oracle flip → remount).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';
+
+const FIXTURES_DIR = join(dirname(fileURLToPath(import.meta.url)), '_fixtures');
+
+async function getSourceText(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const provider = window.__activeProvider;
+ return provider?.document?.getText('source')?.toString() ?? '';
+ });
+}
+
+async function openDocWithBody(
+ page: Page,
+ api: { createPage(p: string): Promise<void>; replaceDoc(d: string, md: string): Promise<void> },
+ body: string,
+ docName = `img-${randomUUID().slice(0, 8)}`,
+): Promise<string> {
+ await api.createPage(`${docName}.md`);
+ await api.replaceDoc(docName, body);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+ return docName;
+}
+
+test.describe('invalid-image placeholder (PRD-7860)', () => {
+ test('a proven-missing markdown image renders "Image not found" and does not rewrite the source', async ({
+ page,
+ api,
+ }) => {
+ const missing = `/no-such-${randomUUID().slice(0, 8)}.png`;
+ const body = `# Missing\n\n![a missing photo](${missing})\n`;
+ await openDocWithBody(page, api, body);
+
+ // The oracle settles to "missing" once /api/documents (which omits the
+ // absent file) has loaded; a proven-absent target is authoritative.
+ await expect(page.getByRole('img', { name: /Image not found/i })).toBeVisible({
+ timeout: 15_000,
+ });
+ const slot = page.locator('[data-testid="image-slot"][data-image-error-kind="not-found"]');
+ await expect(slot).toHaveCount(1);
+
+ // Byte-sacred: the authored markdown is untouched by the placeholder.
+ expect(await getSourceText(page)).toContain(`![a missing photo](${missing})`);
+ });
+
+ test('a proven-missing bare HTML <img> also renders "Image not found"', async ({ page, api }) => {
+ const missing = `/no-html-${randomUUID().slice(0, 8)}.png`;
+ const bareImage = `<img src="${missing}" alt="html photo">`;
+ const body = `# Missing HTML\n\n${bareImage}\n`;
+ await openDocWithBody(page, api, body);
+
+ await expect(page.getByRole('img', { name: /Image not found/i })).toBeVisible({
+ timeout: 15_000,
+ });
+ expect(await getSourceText(page)).toBe(body);
+ });
+
+ test('an existing image whose bytes cannot decode renders "Image couldn\'t be displayed"', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `corrupt-${randomUUID().slice(0, 8)}.png`;
+ // A real file exists (so the oracle reports it present), but the bytes are
+ // not a decodable image → the browser fires `error` → undisplayable, never
+ // "not found".
+ writeFileSync(join(workerServer.contentDir, name), 'this is definitely not a PNG', 'utf-8');
+ await openDocWithBody(page, api, `# Corrupt\n\n![corrupt](/${name})\n`);
+
+ await expect(page.getByRole('img', { name: /couldn't be displayed/i })).toBeVisible({
+ timeout: 15_000,
+ });
+ // It must not read as absent.
+ await expect(page.locator('[data-image-error-kind="not-found"]')).toHaveCount(0);
+ });
+
+ test('error placeholders stay inside narrow table cells with readable text', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const corrupt = `corrupt-table-${randomUUID().slice(0, 8)}.png`;
+ const missing = `/missing-table-${randomUUID().slice(0, 8)}.png`;
+ writeFileSync(join(workerServer.contentDir, corrupt), 'not a PNG', 'utf-8');
+ await openDocWithBody(
+ page,
+ api,
+ [
+ '| State | Example | Probe | Expected behavior | Why | Comments |',
+ '| --- | --- | --- | --- | --- | --- |',
+ `| Broken | ![missing table image](${missing}) | Missing image | Show an error without covering this text. | Target is absent. | Persistent state. |`,
+ `| Display failure | ![corrupt table image](/${corrupt}) | Existing invalid image | Show a warning without covering this text. | Bytes cannot decode. | Persistent state. |`,
+ '',
+ ].join('\n'),
+ );
+
+ const placeholders = page.locator('.ok-image-error-placeholder');
+ await expect(placeholders).toHaveCount(2, { timeout: 15_000 });
+
+ for (const placeholder of await placeholders.all()) {
+ const geometry = await placeholder.evaluate((element) => {
+ const cell = element.closest('td');
+ if (!cell) return null;
+ const elementRect = element.getBoundingClientRect();
+ const cellRect = cell.getBoundingClientRect();
+ return {
+ elementRight: elementRect.right,
+ cellRight: cellRect.right,
+ elementLeft: elementRect.left,
+ cellLeft: cellRect.left,
+ };
+ });
+ expect(geometry).not.toBeNull();
+ expect(geometry?.elementLeft).toBeGreaterThanOrEqual((geometry?.cellLeft ?? 0) - 0.5);
+ expect(geometry?.elementRight).toBeLessThanOrEqual((geometry?.cellRight ?? 0) + 0.5);
+
+ const textStyles = await placeholder.evaluate((element) => {
+ const message = element.querySelector('.ok-image-error-message');
+ const target = element.querySelector('.ok-image-error-target');
+ const rootStyle = getComputedStyle(document.documentElement);
+ return {
+ messageColor: message ? getComputedStyle(message).color : null,
+ targetColor: target ? getComputedStyle(target).color : null,
+ targetOpacity: target ? getComputedStyle(target).opacity : null,
+ foreground: rootStyle.getPropertyValue('--foreground').trim(),
+ };
+ });
+ expect(textStyles.messageColor).toBe(textStyles.foreground);
+ expect(textStyles.targetColor).toBe(textStyles.foreground);
+ expect(textStyles.targetOpacity).toBe('1');
+ }
+ });
+
+ test('all stable authored image forms share the same valid, missing, and undecodable states', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const runId = randomUUID().slice(0, 8);
+ const folder = `image-forms-${runId}`;
+ const docName = `${folder}/matrix`;
+ const assetDir = join(workerServer.contentDir, folder, 'assets');
+ mkdirSync(assetDir, { recursive: true });
+ writeFileSync(join(assetDir, 'valid.png'), readFileSync(join(FIXTURES_DIR, 'real-shot.png')));
+ writeFileSync(join(assetDir, 'corrupt.png'), 'not a PNG', 'utf-8');
+
+ const body = [
+ '# Image forms',
+ '',
+ '## Markdown',
+ '![Markdown valid](assets/valid.png)',
+ '![Markdown missing](assets/missing.png)',
+ '![Markdown corrupt](assets/corrupt.png)',
+ '',
+ '## Bare HTML',
+ '<img src="assets/valid.png" alt="Bare HTML valid">',
+ '<img src="assets/missing.png" alt="Bare HTML missing">',
+ '<img src="assets/corrupt.png" alt="Bare HTML corrupt">',
+ '',
+ '## JSX-style HTML',
+ '<img src="assets/valid.png" alt="JSX valid" />',
+ '<img src="assets/missing.png" alt="JSX missing" />',
+ '<img src="assets/corrupt.png" alt="JSX corrupt" />',
+ '',
+ '## Reference style',
+ '![Reference valid][image-valid]',
+ '![Reference missing][image-missing]',
+ '![Reference corrupt][image-corrupt]',
+ '',
+ '[image-valid]: assets/valid.png',
+ '[image-missing]: assets/missing.png',
+ '[image-corrupt]: assets/corrupt.png',
+ '',
+ ].join('\n');
+ await openDocWithBody(page, api, body, docName);
+
+ const forms = ['Markdown', 'Bare HTML', 'JSX', 'Reference'];
+ for (const form of forms) {
+ const valid = page.getByRole('img', { name: `${form} valid`, exact: true });
+ await valid.scrollIntoViewIfNeeded();
+ await expect(valid).toBeVisible({ timeout: 15_000 });
+
+ const missing = page.getByRole('img', {
+ name: `Image not found: ${form} missing`,
+ exact: true,
+ });
+ await missing.scrollIntoViewIfNeeded();
+ await expect(missing).toBeVisible({ timeout: 15_000 });
+
+ const corrupt = page.getByRole('img', {
+ name: `Image couldn't be displayed: ${form} corrupt`,
+ exact: true,
+ });
+ await corrupt.scrollIntoViewIfNeeded();
+ await expect(corrupt).toBeVisible({ timeout: 15_000 });
+ }
+
+ await expect(page.locator('[data-image-error-kind="not-found"]')).toHaveCount(4);
+ await expect(page.locator('[data-image-error-kind="undisplayable"]')).toHaveCount(4);
+ await expect(
+ page.locator(
+ `[data-image-reference-view] img[alt="Reference valid"][src$="/${folder}/assets/valid.png"]`,
+ ),
+ ).toBeVisible();
+ expect((await getSourceText(page)).trimEnd()).toBe(body.trimEnd());
+ });
+
+ test('reloading keeps the undecodable placeholder (cached-failure decode path)', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `cached-${randomUUID().slice(0, 8)}.png`;
+ writeFileSync(join(workerServer.contentDir, name), 'still not a PNG', 'utf-8');
+ const docName = await openDocWithBody(page, api, `# Cached\n\n![cached](/${name})\n`);
+ await expect(page.getByRole('img', { name: /couldn't be displayed/i })).toBeVisible({
+ timeout: 15_000,
+ });
+
+ // On reload the <img> is `complete` at first mount and `error` will not
+ // re-fire; decode() must reclassify the cached failure.
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await expect(page.getByRole('img', { name: /couldn't be displayed/i })).toBeVisible({
+ timeout: 15_000,
+ });
+ });
+
+ test('creating the target on disk heals "Image not found" to a loaded image without reload', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const name = `created-${randomUUID().slice(0, 8)}.png`;
+ await openDocWithBody(page, api, `# Heal\n\n![created](/${name})\n`);
+
+ await expect(page.getByRole('img', { name: /Image not found/i })).toBeVisible({
+ timeout: 15_000,
+ });
+
+ // Land real, decodable PNG bytes at the target path. The watcher indexes
+ // it → CC1 `files` push → page-list refetch → oracle flips exists →
+ // LoadingImage remounts and re-requests the now-present bytes.
+ const png = readFileSync(join(FIXTURES_DIR, 'real-shot.png'));
+ writeFileSync(join(workerServer.contentDir, name), png);
+
+ // Placeholder clears without a reload and the real <img> loads.
+ await expect(page.getByRole('img', { name: /Image not found/i })).toHaveCount(0, {
+ timeout: 25_000,
+ });
+ await expect(page.locator('[data-testid="image-slot"][data-image-error]')).toHaveCount(0);
+ const img = page.locator(`.ProseMirror:not(.composer-prosemirror) img[src$="/${name}"]`);
+ await expect(img).toBeVisible({ timeout: 25_000 });
+ });
+});
diff --git a/packages/app/tests/stress/local-target-audit.e2e.ts b/packages/app/tests/stress/local-target-audit.e2e.ts
new file mode 100644
index 000000000..b3a370b0f
--- /dev/null
+++ b/packages/app/tests/stress/local-target-audit.e2e.ts
@@ -0,0 +1,194 @@
+/**
+ * Real-browser composition coverage for the local-target audit plane.
+ *
+ * The lower tiers exercise classification and each UI projection independently.
+ * This file proves the production wiring they cannot: real disk events feed the
+ * server's watcher-backed inventory, the derived index projects one assessment
+ * through HTTP + CC1, and the browser renders the same result in WYSIWYG,
+ * source mode, Links, and Problems.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Page } from '@playwright/test';
+import {
+ expect,
+ filterCriticalErrors,
+ type LogEntry,
+ test,
+ waitForActiveProviderSynced as waitForProvider,
+} from './_helpers';
+
+const errors: LogEntry[] = [];
+
+async function openDoc(
+ page: Page,
+ api: {
+ createPage(path: string): Promise<void>;
+ replaceDoc(docName: string, md: string): Promise<void>;
+ },
+ docName: string,
+ body: string,
+): Promise<void> {
+ await api.createPage(`${docName}.md`);
+ await api.replaceDoc(docName, body);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+}
+
+async function switchToSource(page: Page): Promise<void> {
+ await page.getByRole('radio', { name: 'Markdown source' }).click();
+ await page.waitForSelector('.cm-content');
+}
+
+test.beforeEach(async ({ page }) => {
+ errors.length = 0;
+ page.on('pageerror', (err) => errors.push({ type: 'uncaught', text: err.message }));
+ page.on('console', (msg) => {
+ if (msg.type() !== 'error') return;
+ const location = msg.location();
+ errors.push({
+ type: 'error',
+ text: msg.text(),
+ url: location.url,
+ line: location.lineNumber,
+ });
+ });
+});
+
+test.afterEach(() => {
+ expect(filterCriticalErrors(errors), 'Expected zero critical console errors').toEqual([]);
+});
+
+test.describe('local-target audit composition', () => {
+ test('one classification projects uniformly into Links and Problems', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const folder = `local-target-matrix-${randomUUID().slice(0, 8)}`;
+ const docName = `${folder}/matrix`;
+ const assetsDir = join(workerServer.contentDir, folder, 'assets');
+ mkdirSync(assetsDir, { recursive: true });
+ writeFileSync(join(assetsDir, 'NOTICE'), 'existing extensionless file\n', 'utf-8');
+
+ await openDoc(
+ page,
+ api,
+ docName,
+ [
+ '# Local target matrix',
+ '',
+ '[existing file](assets/NOTICE)',
+ '[missing file](assets/missing.pdf)',
+ '[missing document](missing.md)',
+ '',
+ ].join('\n'),
+ );
+
+ await page.locator('#tab-links').click();
+ await expect(page.getByText('Local files', { exact: true })).toBeVisible();
+
+ const existingFile = `${folder}/assets/NOTICE`;
+ const missingFile = `${folder}/assets/missing.pdf`;
+ await expect(
+ page.getByRole('button', { name: `File ${existingFile}. Go to reference.` }),
+ ).toBeVisible({ timeout: 15_000 });
+ await expect(
+ page.getByRole('button', { name: `Missing file ${missingFile}. Go to reference.` }),
+ ).toBeVisible();
+ // An existing extensionless file must never leak into the document graph's
+ // recovery path, while the genuinely missing document still may be created.
+ await expect(page.getByRole('button', { name: /Missing page: existing file/i })).toHaveCount(0);
+ await expect(
+ page.getByRole('button', {
+ name: /Missing page: .*missing.*\. Click to create\./i,
+ }),
+ ).toBeVisible();
+
+ await page.locator('#tab-problems').click();
+ const problems = page.locator('ul[aria-label="Problems"]');
+ await expect(problems).toBeVisible({ timeout: 15_000 });
+ await expect(
+ problems.getByTestId('problems-source-tag').filter({ hasText: 'links' }),
+ ).toHaveCount(2);
+ // The file failure reports, but only the document finding offers Create.
+ await expect(problems.getByTestId('problems-create-page')).toHaveCount(1);
+ await expect(
+ problems.getByRole('button', { name: `Create missing page ${folder}/missing` }),
+ ).toBeVisible();
+ });
+
+ test('creating a missing file heals WYSIWYG and source diagnostics without reload', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const folder = `local-target-heal-${randomUUID().slice(0, 8)}`;
+ const docName = `${folder}/matrix`;
+ const relativeTarget = 'assets/report.pdf';
+ const targetPath = join(workerServer.contentDir, folder, relativeTarget);
+ mkdirSync(join(workerServer.contentDir, folder, 'assets'), { recursive: true });
+
+ await openDoc(page, api, docName, `# Healing\n\n[the report](${relativeTarget})\n`);
+
+ await expect(
+ page.locator('.ProseMirror:not(.composer-prosemirror) [data-resolution-state="unresolved"]'),
+ ).toHaveCount(1, { timeout: 15_000 });
+
+ await switchToSource(page);
+ const diagnostic = page.locator('.cm-lint-local-target');
+ await expect(diagnostic).toHaveCount(1, { timeout: 15_000 });
+ await expect
+ .poll(() => diagnostic.evaluate((element) => getComputedStyle(element).textDecorationStyle))
+ .toBe('wavy');
+
+ writeFileSync(targetPath, '%PDF-1.4 real watcher target\n', 'utf-8');
+
+ // Real watcher → local-target index → CC1 local-targets → scoped audit
+ // refresh. No page reload or test-only event injection participates.
+ await expect(diagnostic).toHaveCount(0, { timeout: 25_000 });
+
+ await page.getByRole('radio', { name: 'Visual editor' }).click();
+ await expect(
+ page.locator('.ProseMirror:not(.composer-prosemirror) [data-resolution-state="asset"]'),
+ ).toHaveCount(1, { timeout: 15_000 });
+ });
+
+ test('deleting a referenced file breaks WYSIWYG and source diagnostics without reload', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const folder = `local-target-break-${randomUUID().slice(0, 8)}`;
+ const docName = `${folder}/matrix`;
+ const relativeTarget = 'assets/report.pdf';
+ const targetPath = join(workerServer.contentDir, folder, relativeTarget);
+ mkdirSync(join(workerServer.contentDir, folder, 'assets'), { recursive: true });
+ writeFileSync(targetPath, '%PDF-1.4 real watcher target\n', 'utf-8');
+
+ await openDoc(page, api, docName, `# Breaking\n\n[the report](${relativeTarget})\n`);
+
+ await expect(
+ page.locator('.ProseMirror:not(.composer-prosemirror) [data-resolution-state="asset"]'),
+ ).toHaveCount(1, { timeout: 15_000 });
+
+ await switchToSource(page);
+ const diagnostic = page.locator('.cm-lint-local-target');
+ await expect(diagnostic).toHaveCount(0);
+
+ unlinkSync(targetPath);
+
+ // The unlink direction of the same wiring the heal test drives: real
+ // watcher delete → local-target index → CC1 local-targets → scoped audit
+ // refresh surfaces the now-missing target.
+ await expect(diagnostic).toHaveCount(1, { timeout: 25_000 });
+
+ await page.getByRole('radio', { name: 'Visual editor' }).click();
+ await expect(
+ page.locator('.ProseMirror:not(.composer-prosemirror) [data-resolution-state="unresolved"]'),
+ ).toHaveCount(1, { timeout: 15_000 });
+ });
+});
diff --git a/packages/cli/src/commands/audit.test.ts b/packages/cli/src/commands/audit.test.ts
index 0d5634b3e..f7f865dd7 100644
--- a/packages/cli/src/commands/audit.test.ts
+++ b/packages/cli/src/commands/audit.test.ts
@@ -38,6 +38,26 @@ function diagnostic(over: Record<string, unknown> = {}) {
};
}
+// A links/dead-link finding for a missing local image, carrying the additive
+// evidence the audit plane attaches, positioned at the image occurrence.
+function imageDiagnostic() {
+ return diagnostic({
+ range: { start: { line: 5, character: 2 }, end: { line: 5, character: 2 } },
+ source: 'links',
+ code: 'dead-link',
+ message: 'Image target "./logo.png" does not resolve to an existing file.',
+ localTarget: {
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'assets/logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ });
+}
+
function collectIo() {
const out: string[] = [];
const err: string[] = [];
@@ -201,6 +221,43 @@ describe('runAudit', () => {
expect(JSON.parse(out.join('\n'))).toEqual(body);
});
+ test('--json preserves local-target evidence verbatim', async () => {
+ const body = payload({
+ fileCount: 1,
+ warningCount: 1,
+ files: [{ file: 'pics.md', diagnostics: [imageDiagnostic()] }],
+ });
+ stubFetch(body);
+ const { io, out } = collectIo();
+
+ const code = await runAudit(undefined, { json: true }, minimalConfig, dir, dir, io);
+
+ expect(code).toBe(1);
+ // The whole plane round-trips through the parse, evidence included.
+ expect(JSON.parse(out.join('\n'))).toEqual(body);
+ });
+
+ test('formatted output points at the occurrence and reads as an image break', async () => {
+ stubFetch(
+ payload({
+ fileCount: 1,
+ warningCount: 1,
+ files: [{ file: 'pics.md', diagnostics: [imageDiagnostic()] }],
+ }),
+ );
+ const { io, out } = collectIo();
+
+ const code = await runAudit(undefined, {}, minimalConfig, dir, dir, io);
+
+ expect(code).toBe(1);
+ const text = out.join('\n');
+ // 1-based location from the 0-based occurrence range — the row points at the
+ // authored image, not the top of the doc.
+ expect(text).toContain('6:3');
+ expect(text).toContain('links/dead-link');
+ expect(text).toContain('Image target "./logo.png" does not resolve to an existing file');
+ });
+
test('surfaces engine degradation warnings in the report', async () => {
stubFetch(
payload({ warnings: ['links validation unavailable: backlink index is not configured'] }),
diff --git a/packages/cli/tests/integration/multi-project-locks.test.ts b/packages/cli/tests/integration/multi-project-locks.test.ts
index 650b264ec..40c2fb910 100644
--- a/packages/cli/tests/integration/multi-project-locks.test.ts
+++ b/packages/cli/tests/integration/multi-project-locks.test.ts
@@ -158,7 +158,10 @@ describe('multi-project lock isolation (A1)', () => {
// ---------------------------------------------------------------------------
const LOCK_WORKER_PATH = resolve(__dirname, '_helpers', 'lock-worker.ts');
-const WORKER_READY_TIMEOUT_MS = 5_000;
+// `node --import tsx` startup competes with the repository's fully parallel
+// package matrix. The isolated path is ~2s, but five seconds is below the
+// observed scheduler budget under that supported topology.
+const WORKER_READY_TIMEOUT_MS = 20_000;
const WORKER_EXIT_TIMEOUT_MS = 3_000;
interface WorkerHandle {
@@ -193,6 +196,7 @@ function spawnLockWorker(
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
if (proc.pid === undefined || !proc.stdout || !proc.stderr) {
+ proc.kill('SIGKILL');
reject(new Error('lock-worker spawn did not return a pid + pipes'));
return;
}
@@ -224,11 +228,22 @@ function spawnLockWorker(
});
} catch (err) {
clearTimeout(timeoutHandle);
+ proc.kill('SIGKILL');
reject(new Error(`lock-worker READY parse failed: ${(err as Error).message} :: ${line}`));
}
};
proc.stdout.on('data', onData);
+ proc.once('exit', (code, signal) => {
+ if (resolved) return;
+ clearTimeout(timeoutHandle);
+ reject(
+ new Error(
+ `lock-worker exited before READY (code=${String(code)}, signal=${String(signal)}, lockDir=${lockDir}, stderr=${stderrBuffer || '(empty)'})`,
+ ),
+ );
+ });
+
const timeoutHandle = setTimeout(() => {
if (!resolved) {
try {
@@ -248,6 +263,7 @@ function spawnLockWorker(
/** SIGTERM the worker and await its exit. Falls back to SIGKILL on timeout. */
function stopLockWorker(handle: WorkerHandle): Promise<void> {
+ if (handle.proc.exitCode !== null || handle.proc.signalCode !== null) return Promise.resolve();
return new Promise((resolveStop) => {
let settled = false;
const onExit = (): void => {
@@ -303,11 +319,18 @@ function stopLockWorker(handle: WorkerHandle): Promise<void> {
return { i, lockDir, serverPort: 52100 + i, uiPort: 3100 + i };
});
- workers = await Promise.all(
+ const spawnResults = await Promise.allSettled(
lockDirs.map(({ lockDir, serverPort, uiPort }) =>
spawnLockWorker(lockDir, serverPort, uiPort),
),
);
+ workers = spawnResults.flatMap((result) =>
+ result.status === 'fulfilled' ? [result.value] : [],
+ );
+ const failedSpawn = spawnResults.find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
+ if (failedSpawn) throw failedSpawn.reason;
// Every worker is alive on this host.
for (const w of workers) {
diff --git a/packages/core/schema-snapshot.json b/packages/core/schema-snapshot.json
index fe321347c..a507ba31b 100644
--- a/packages/core/schema-snapshot.json
+++ b/packages/core/schema-snapshot.json
@@ -984,6 +984,16 @@
"version": null,
"hasOptions": false
},
+ {
+ "name": "link-reference-destination",
+ "version": null,
+ "hasOptions": false
+ },
+ {
+ "name": "non-rendering-context-demote",
+ "version": null,
+ "hasOptions": false
+ },
{
"name": "ensure-non-empty-doc",
"version": null,
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 01ac80099..dcc5b0690 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 04e1dcd16..d44a02bf0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -469,6 +469,7 @@ export {
export { HardBreakFidelity } from './extensions/hard-break-fidelity.ts';
export { HeadingFidelity } from './extensions/heading-fidelity.ts';
export { HtmlBlockFidelity } from './extensions/html-block-fidelity.ts';
+export { ImageReferenceFidelity } from './extensions/image-reference-fidelity.ts';
export { ImageSrcFidelity } from './extensions/image-src-fidelity.ts';
export { JsxComponent } from './extensions/jsx-component.ts';
export { JsxInline } from './extensions/jsx-inline.ts';
@@ -676,6 +677,11 @@ export {
type LintRange,
type LintSeverity,
type LintTextEdit,
+ type LocalTargetDiagnosticEvidence,
+ type LocalTargetKind,
+ type LocalTargetResolutionMethod,
+ type LocalTargetRole,
+ type LocalTargetSourceForm,
lintDocument,
MARKDOWNLINT_RULE_CATALOG,
type MarkdownlintRuleSetting,
@@ -716,6 +722,14 @@ export {
ZERO_SOURCE_COUNTS,
} from './markdown/lint/index.ts';
export { markdownToHtml, mdastToHtml } from './markdown/mdast-to-html.ts';
+export {
+ isNonRenderingRange,
+ type MaskableLine,
+ maskNonRenderingContextLines,
+ maskNonRenderingContexts,
+ skipInlineCode,
+} from './markdown/non-rendering-contexts.ts';
+export { normalizeReferenceLabel } from './markdown/reference-label.ts';
export { normalizeDocRelativeAssetUrl } from './markdown/resolve-image-url.ts';
export {
isRelativeUrl,
@@ -924,6 +938,8 @@ export {
ForwardLinkEntrySchema,
type ForwardLinkExternalEntry,
ForwardLinkExternalEntrySchema,
+ type ForwardLinkLocalTarget,
+ ForwardLinkLocalTargetSchema,
type ForwardLinksSuccess,
ForwardLinksSuccessSchema,
type FrontmatterPatchRequest,
@@ -1002,6 +1018,8 @@ export {
LocalOpOkInitRequestSchema,
type LocalOpOkInitResponse,
LocalOpOkInitResponseSchema,
+ LocalTargetDiagnosticEvidenceSchema,
+ type LocalTargetDiagnosticEvidenceWire,
type MetricsAgentEffectsSuccess,
MetricsAgentEffectsSuccessSchema,
type MetricsAgentPresenceSuccess,
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 7415c474a..34704165b 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index da0a81d23..5d1000cc4 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 9075aa7f1..ec1ac1b7e 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,6 +207,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -254,6 +256,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -714,8 +721,8 @@ function buildMdastToPmHandlers(
}
const children = state.all(node).flat();
const mark = m.link.create({
- href: '',
- title: null,
+ href: node.data?.resolvedUrl ?? '',
+ title: node.data?.resolvedTitle ?? null,
linkStyle: node.referenceType ?? 'shortcut',
refLabel: node.label ?? node.identifier ?? null,
});
@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/link-reference-destination.ts b/packages/core/src/markdown/link-reference-destination.ts
new file mode 100644
index 000000000..62d0b95dd
--- /dev/null
+++ b/packages/core/src/markdown/link-reference-destination.ts
@@ -0,0 +1,37 @@
+import type { Definition, LinkReference, Root } from 'mdast';
+import { visit } from 'unist-util-visit';
+import { normalizeReferenceLabel } from './reference-label.ts';
+
+function labelKey(node: Definition | LinkReference): string | null {
+ const raw = node.identifier ?? node.label;
+ if (typeof raw !== 'string') return null;
+ const key = normalizeReferenceLabel(raw);
+ return key.length > 0 ? key : null;
+}
+
+function collectDefinitions(tree: Root): Map<string, Definition> {
+ const byLabel = new Map<string, Definition>();
+ visit(tree, 'definition', (node: Definition) => {
+ const key = labelKey(node);
+ if (key && !byLabel.has(key)) byLabel.set(key, node);
+ });
+ return byLabel;
+}
+
+export function linkReferenceDestinationPlugin() {
+ return (tree: Root) => {
+ const definitions = collectDefinitions(tree);
+ if (definitions.size === 0) return;
+ visit(tree, 'linkReference', (node: LinkReference) => {
+ const key = labelKey(node);
+ if (!key) return;
+ const definition = definitions.get(key);
+ if (!definition) return;
+ node.data = {
+ ...node.data,
+ resolvedUrl: definition.url,
+ resolvedTitle: definition.title ?? null,
+ };
+ });
+ };
+}
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 0ba33b7d8..1e3ad29c6 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { agentIdentityFields, safeDocNameField, summaryField } from '../../schemas/api/_shared.ts';
+import { LocalTargetDiagnosticEvidenceSchema } from '../../schemas/api/agent-write.ts';
import { DEFAULT_MARKDOWNLINT_CONFIG } from './default-config.ts';
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { FrontmatterSchemaMapping, MarkdownlintRuleSetting } from './types.ts';
@@ -38,6 +39,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
@@ -168,6 +170,7 @@ export type LintAuditResponse = z.infer<typeof LintAuditResponseSchema>;
const ValidationDiagnosticSchema = LintDiagnosticSchema.extend({
linkTarget: z.string().optional(),
+ localTarget: LocalTargetDiagnosticEvidenceSchema.optional(),
});
export const ValidationDocResultSchema = z.object({
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 0d4c9a0df..b96d19182 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 00d08265a..1ca263610 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
@@ -111,6 +112,11 @@ export type {
LintRange,
LintSeverity,
LintTextEdit,
+ LocalTargetDiagnosticEvidence,
+ LocalTargetKind,
+ LocalTargetResolutionMethod,
+ LocalTargetRole,
+ LocalTargetSourceForm,
MarkdownlintRuleSetting,
MarkdownlintRuleSeverity,
MarkdownlintRuleWriteValue,
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 5e832aa19..be5871ed9 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -13,6 +14,7 @@ import {
type MarkdownlintSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 3918e657c..3dae5c031 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,6 @@
+
+import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
+
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -32,9 +35,34 @@ export interface LintDiagnostic {
const VALIDATION_SOURCES = [...LINT_PLUGIN_IDS, 'links'] as const;
export type ValidationSource = (typeof VALIDATION_SOURCES)[number];
+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 interface LocalTargetDiagnosticEvidence extends Record<string, unknown> {
+ href: string;
+ targetKind: LocalTargetKind;
+ role: LocalTargetRole;
+ sourceForm: LocalTargetSourceForm;
+ resolvedTarget: string | null;
+ reason: BrokenLinkReason;
+ resolutionMethod: LocalTargetResolutionMethod;
+ fallbackTarget?: string;
+ definition?: {
+ [key: string]: unknown;
+ line: number;
+ label: string;
+ };
+}
+
export interface ValidationDiagnostic extends Omit<LintDiagnostic, 'source'> {
source: ValidationSource;
linkTarget?: string;
+ localTarget?: LocalTargetDiagnosticEvidence;
}
export const LINKS_VALIDATION_SETTINGS = ['off', 'warning', 'error'] as const;
@@ -71,6 +99,7 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-augmentation.ts b/packages/core/src/markdown/mdast-augmentation.ts
index 087f3caf9..721c1c7f1 100644
--- a/packages/core/src/markdown/mdast-augmentation.ts
+++ b/packages/core/src/markdown/mdast-augmentation.ts
@@ -142,6 +142,8 @@ declare module 'mdast' {
}
interface LinkReferenceData {
sourceRaw?: string;
+ resolvedUrl?: string;
+ resolvedTitle?: string | null;
}
interface ThematicBreakData {
sourceRaw?: string;
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/non-rendering-context-demote.ts b/packages/core/src/markdown/non-rendering-context-demote.ts
new file mode 100644
index 000000000..9ed992373
--- /dev/null
+++ b/packages/core/src/markdown/non-rendering-context-demote.ts
@@ -0,0 +1,53 @@
+import type { Link, LinkReference, Nodes, Parent, Root, Text } from 'mdast';
+import type { VFile } from 'vfile';
+import { isNonRenderingRange, maskNonRenderingContexts } from './non-rendering-contexts.ts';
+
+function isLinkShaped(node: Nodes): node is Link | LinkReference {
+ return node.type === 'link' || node.type === 'linkReference';
+}
+
+function demoteInPlace(
+ parent: Parent,
+ index: number,
+ node: Link | LinkReference,
+ source: string,
+): void {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start === undefined || end === undefined) return;
+ const raw = source.slice(start, end);
+ const text: Text = {
+ type: 'text',
+ value: raw,
+ data: { sourceRaw: raw },
+ position: node.position,
+ };
+ parent.children.splice(index, 1, text);
+}
+
+export function nonRenderingContextDemotePlugin() {
+ return (tree: Root, file: VFile): void => {
+ const source = typeof file.value === 'string' ? file.value : String(file.value ?? '');
+ if (source.length === 0) return;
+ if (!source.includes('<!--') && !/<(pre|code)[\s/>]/i.test(source)) return;
+
+ const masked = maskNonRenderingContexts(source);
+
+ const visit = (parent: Parent): void => {
+ for (let index = parent.children.length - 1; index >= 0; index--) {
+ const child = parent.children[index];
+ if (!child) continue;
+ if ('children' in child && Array.isArray(child.children)) {
+ visit(child as Parent);
+ }
+ if (!isLinkShaped(child)) continue;
+ const start = child.position?.start.offset;
+ const end = child.position?.end.offset;
+ if (start === undefined || end === undefined) continue;
+ if (!isNonRenderingRange(source, masked, start, end)) continue;
+ demoteInPlace(parent, index, child, source);
+ }
+ };
+ visit(tree);
+ };
+}
diff --git a/packages/core/src/markdown/non-rendering-contexts.ts b/packages/core/src/markdown/non-rendering-contexts.ts
new file mode 100644
index 000000000..a98861796
--- /dev/null
+++ b/packages/core/src/markdown/non-rendering-contexts.ts
@@ -0,0 +1,178 @@
+import { createCodeFenceTracker } from '../utils/code-fence-tracker.ts';
+
+export interface MaskableLine {
+ text: string;
+ start: number;
+}
+
+function maskRange(chars: string[], start: number, end: number): void {
+ for (let i = start; i < end; i++) chars[i] = ' ';
+}
+
+function rawTagAt(line: string, start: number): 'pre' | 'code' | null {
+ if (line[start] !== '<') return null;
+ const lower = line.slice(start).toLowerCase();
+ for (const tag of ['pre', 'code'] as const) {
+ if (!lower.startsWith(`<${tag}`)) continue;
+ const boundary = line[start + tag.length + 1];
+ if (boundary === '>' || boundary === '/' || boundary === ' ' || boundary === '\t') return tag;
+ }
+ return null;
+}
+
+function htmlTagEnd(line: string, start: number): number | null {
+ let quote: '"' | "'" | null = null;
+ for (let i = start; i < line.length; i++) {
+ const char = line[i];
+ if (quote !== null) {
+ if (char === quote) quote = null;
+ } else if (char === '"' || char === "'") {
+ quote = char;
+ } else if (char === '>') {
+ return i + 1;
+ }
+ }
+ return null;
+}
+
+function rawClosingTagEnd(line: string, start: number, tag: 'pre' | 'code'): number | null {
+ const match = new RegExp(`</${tag}\\s*>`, 'i').exec(line.slice(start));
+ return match?.index === undefined ? null : start + match.index + match[0].length;
+}
+
+export function skipInlineCode(line: string, start: number): number | null {
+ let runLength = 0;
+ while (line[start + runLength] === '`') runLength += 1;
+ if (runLength === 0) return null;
+ const openEnd = start + runLength;
+ let i = openEnd;
+ while (i < line.length) {
+ if (line[i] !== '`') {
+ i += 1;
+ continue;
+ }
+ let closeLen = 0;
+ while (line[i + closeLen] === '`') closeLen += 1;
+ if (closeLen === runLength) return i + runLength;
+ i += closeLen;
+ }
+ return openEnd;
+}
+
+export function maskNonRenderingContextLines(lines: MaskableLine[]): MaskableLine[] {
+ const inFence = createCodeFenceTracker();
+ let inComment = false;
+ let rawTag: 'pre' | 'code' | null = null;
+
+ return lines.map(({ text, start }) => {
+ if (rawTag === null && !inComment) {
+ const fenced = inFence(text);
+ if (fenced) {
+ return { text: ' '.repeat(text.length), start };
+ }
+ }
+
+ const chars = text.split('');
+ let cursor = 0;
+ while (cursor < text.length) {
+ if (inComment) {
+ const close = text.indexOf('-->', cursor);
+ const end = close < 0 ? text.length : close + 3;
+ maskRange(chars, cursor, end);
+ cursor = end;
+ if (close < 0) break;
+ inComment = false;
+ continue;
+ }
+ if (rawTag !== null) {
+ const end = rawClosingTagEnd(text, cursor, rawTag);
+ maskRange(chars, cursor, end ?? text.length);
+ if (end === null) break;
+ cursor = end;
+ rawTag = null;
+ continue;
+ }
+
+ const commentStart = text.indexOf('<!--', cursor);
+ let rawStart = -1;
+ let nextRawTag: 'pre' | 'code' | null = null;
+ for (let i = cursor; i < text.length; i++) {
+ const found = rawTagAt(text, i);
+ if (found !== null) {
+ rawStart = i;
+ nextRawTag = found;
+ break;
+ }
+ }
+ const inlineCodeStart = text.indexOf('`', cursor);
+ const firstHtmlStart =
+ commentStart < 0
+ ? rawStart
+ : rawStart < 0
+ ? commentStart
+ : Math.min(commentStart, rawStart);
+ if (inlineCodeStart >= 0 && (firstHtmlStart < 0 || inlineCodeStart < firstHtmlStart)) {
+ cursor = skipInlineCode(text, inlineCodeStart) ?? inlineCodeStart + 1;
+ continue;
+ }
+ if (commentStart < 0 && rawStart < 0) break;
+ if (commentStart >= 0 && (rawStart < 0 || commentStart < rawStart)) {
+ const close = text.indexOf('-->', commentStart + 4);
+ const end = close < 0 ? text.length : close + 3;
+ maskRange(chars, commentStart, end);
+ cursor = end;
+ inComment = close < 0;
+ if (inComment) break;
+ continue;
+ }
+
+ const openEnd = htmlTagEnd(text, rawStart);
+ if (openEnd === null || nextRawTag === null) break;
+ const closeEnd = rawClosingTagEnd(text, openEnd, nextRawTag);
+ const end = closeEnd ?? text.length;
+ maskRange(chars, rawStart, end);
+ cursor = end;
+ rawTag = closeEnd === null ? nextRawTag : null;
+ if (rawTag !== null) break;
+ }
+ return { text: chars.join(''), start };
+ });
+}
+
+export function maskNonRenderingContexts(source: string): string {
+ const lines: MaskableLine[] = [];
+ let start = 0;
+ for (let i = 0; i < source.length; i++) {
+ const ch = source[i];
+ if (ch === '\n') {
+ lines.push({ text: source.slice(start, i), start });
+ start = i + 1;
+ } else if (ch === '\r') {
+ lines.push({ text: source.slice(start, i), start });
+ if (source[i + 1] === '\n') i += 1;
+ start = i + 1;
+ }
+ }
+ lines.push({ text: source.slice(start), start });
+
+ const masked = maskNonRenderingContextLines(lines);
+ const out = source.split('');
+ for (const line of masked) {
+ for (let i = 0; i < line.text.length; i++) {
+ out[line.start + i] = line.text[i] as string;
+ }
+ }
+ return out.join('');
+}
+
+export function isNonRenderingRange(
+ source: string,
+ maskedSource: string,
+ start: number,
+ end: number,
+): boolean {
+ if (end <= start) return false;
+ const original = source.slice(start, end);
+ if (original.trim().length === 0) return false;
+ return maskedSource.slice(start, end).trim().length === 0;
+}
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index d988f4b8b..4aa0490c4 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 449e6f12f..55736041c 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
@@ -30,10 +31,12 @@ import { highlightPromoterPlugin } from './highlight-promoter.ts';
import { imagePromoterPlugin } from './image-promoter.ts';
import { indentedCodePromoterPlugin } from './indented-code-promoter.ts';
import { insertInteriorBlankRunParagraphs } from './interior-blank-runs.ts';
+import { linkReferenceDestinationPlugin } from './link-reference-destination.ts';
import { mathPromoterPlugin } from './math-promoter.ts';
import type { SourceDocBoundary } from './mdast-augmentation.ts';
import { mergedPostParseWalkerPlugin } from './merged-walker.ts';
import { mermaidPromoterPlugin } from './mermaid-promoter.ts';
+import { nonRenderingContextDemotePlugin } from './non-rendering-context-demote.ts';
import { positionAwareBlankLineJoin } from './position-aware-join.ts';
import { remarkMdxAgnostic } from './remark-mdx-agnostic.ts';
import { singleDollarMathPromoterPlugin } from './single-dollar-math-promoter.ts';
@@ -101,6 +104,8 @@ export const ACTIVE_MDAST_PLUGINS = [
{ name: 'comment-promoter', plugin: commentPromoterPlugin },
{ name: 'merged-post-parse-walker', plugin: mergedPostParseWalkerPlugin },
{ name: 'empty-task-item-unmint', plugin: emptyTaskItemUnmintPlugin },
+ { name: 'link-reference-destination', plugin: linkReferenceDestinationPlugin },
+ { name: 'non-rendering-context-demote', plugin: nonRenderingContextDemotePlugin },
{ name: 'ensure-non-empty-doc', plugin: () => ensureNonEmptyDoc },
] as const;
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/reference-label.ts b/packages/core/src/markdown/reference-label.ts
new file mode 100644
index 000000000..812925a5d
--- /dev/null
+++ b/packages/core/src/markdown/reference-label.ts
@@ -0,0 +1,7 @@
+export function normalizeReferenceLabel(value: string): string {
+ return value
+ .replace(/[\t\n\r ]+/g, ' ')
+ .replace(/^ | $/g, '')
+ .toLowerCase()
+ .toUpperCase();
+}
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 7cac5b042..93798cf83 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 3e79f8cb6..959cc0bd2 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/core/src/schemas/api/agent-write.test.ts b/packages/core/src/schemas/api/agent-write.test.ts
index 96d8130b9..42e584c23 100644
--- a/packages/core/src/schemas/api/agent-write.test.ts
+++ b/packages/core/src/schemas/api/agent-write.test.ts
@@ -8,6 +8,8 @@ import {
AgentWriteMdSuccessSchema,
AgentWriteRequestSchema,
AgentWriteSuccessSchema,
+ LintViolationWarningSchema,
+ LocalTargetDiagnosticEvidenceSchema,
ProblemTypeSchema,
SummaryResponseFieldSchema,
} from './index.ts';
@@ -318,6 +320,92 @@ describe('AgentWriteMdSuccessSchema', () => {
expect(result.success).toBe(true);
});
+ test('round-trips a brokenLink carrying additive local-target evidence (image + reference)', () => {
+ const brokenLinks = [
+ {
+ href: './diagram.png',
+ resolvedTo: 'assets/diagram.png',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './diagram.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'assets/diagram.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ },
+ {
+ href: 'guide',
+ resolvedTo: 'guide',
+ reason: 'no-such-doc',
+ localTarget: {
+ href: 'guide',
+ targetKind: 'document',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'guide',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ fallbackTarget: 'Guide',
+ definition: { line: 12, label: 'guide' },
+ },
+ },
+ ];
+ const result = AgentWriteMdSuccessSchema.safeParse({
+ timestamp: '2026-04-30T00:00:00.000Z',
+ subscriberCount: 0,
+ systemSubscriberCount: 0,
+ brokenLinks,
+ });
+ expect(result.success).toBe(true);
+ // The evidence survives the round trip — a consumer reads it back verbatim.
+ expect(result.success && result.data.brokenLinks).toEqual(brokenLinks);
+ });
+
+ test('preserves additive fields in local-target evidence and its definition', () => {
+ const evidence = {
+ href: './guide',
+ targetKind: 'document',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'guide',
+ reason: 'no-such-doc',
+ resolutionMethod: 'source-relative',
+ futureEvidence: 'kept',
+ definition: { line: 4, label: 'guide', futureDefinition: 'kept' },
+ };
+
+ expect(LocalTargetDiagnosticEvidenceSchema.parse(evidence)).toEqual(evidence);
+ });
+
+ test.each([-1, 1.5])('rejects invalid local-target definition line %s', (line) => {
+ const result = LocalTargetDiagnosticEvidenceSchema.safeParse({
+ href: './guide',
+ targetKind: 'document',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'guide',
+ reason: 'no-such-doc',
+ resolutionMethod: 'source-relative',
+ definition: { line, label: 'guide' },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ test('a legacy brokenLink with no localTarget still parses (back-compat)', () => {
+ const result = AgentWriteMdSuccessSchema.safeParse({
+ timestamp: '2026-04-30T00:00:00.000Z',
+ subscriberCount: 0,
+ systemSubscriberCount: 0,
+ brokenLinks: [{ href: './old.md', resolvedTo: 'old', reason: 'no-such-doc' }],
+ });
+ expect(result.success).toBe(true);
+ expect(result.success && result.data.brokenLinks[0]?.localTarget).toBeUndefined();
+ });
+
test('requires brokenLinks (always-present confirmation field)', () => {
const result = AgentWriteMdSuccessSchema.safeParse({
timestamp: '2026-04-30T00:00:00.000Z',
@@ -359,6 +447,46 @@ describe('AgentWriteMdSuccessSchema', () => {
});
});
+describe('LintViolationWarningSchema', () => {
+ test('round-trips a links violation carrying local-target evidence', () => {
+ const warning = {
+ kind: 'lint-violation',
+ source: 'links',
+ code: 'dead-link',
+ message: 'Image target "./logo.png" does not resolve to an existing file.',
+ severity: 'warning',
+ line: 3,
+ column: 1,
+ localTarget: {
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'html-img',
+ resolvedTarget: 'logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ };
+ const result = LintViolationWarningSchema.safeParse(warning);
+ expect(result.success).toBe(true);
+ expect(result.success && result.data.localTarget).toEqual(warning.localTarget);
+ });
+
+ test('a markdownlint violation with no localTarget still parses (back-compat)', () => {
+ const result = LintViolationWarningSchema.safeParse({
+ kind: 'lint-violation',
+ source: 'markdownlint',
+ code: 'MD010',
+ message: 'Hard tabs',
+ severity: 'warning',
+ line: 1,
+ column: 1,
+ });
+ expect(result.success).toBe(true);
+ expect(result.success && result.data.localTarget).toBeUndefined();
+ });
+});
+
describe('AgentPatchSuccessSchema', () => {
test('parses with required fields', () => {
const result = AgentPatchSuccessSchema.safeParse({
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index d7758a76d..41b938dd5 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -274,6 +274,38 @@ export const RenderWarningSchema = z
.loose() satisfies StandardSchemaV1;
export type RenderWarning = z.infer<typeof RenderWarningSchema>;
+/**
+ * Wire mirror of core's `LocalTargetDiagnosticEvidence` (markdown/lint/types.ts):
+ * additive evidence carried on a broken local-target finding — the authored
+ * href, what it resolves to, the target kind (document/file/unknown), occurrence
+ * role (link/image), authored syntax family, failure reason, resolution method,
+ * and a reference-style definition pointer. One schema so write advisories, the
+ * audit plane, and lint-violation advisories describe a local target identically.
+ *
+ * Enum-shaped fields are `z.string()` (open enums), not `z.enum`, deliberately:
+ * a server that learns a new kind/reason/form must not fail an older client's
+ * parse. The runtime object carries the precise union value; the loose wire
+ * passes it through. `reason` reuses the `no-such-doc | no-such-file |
+ * unresolvable` vocabulary above without pinning the wire to it.
+ */
+export const LocalTargetDiagnosticEvidenceSchema = z
+ .object({
+ href: z.string(),
+ targetKind: z.string(),
+ role: z.string(),
+ sourceForm: z.string(),
+ resolvedTarget: z.string().nullable(),
+ reason: z.string(),
+ resolutionMethod: z.string(),
+ fallbackTarget: z.string().nullable().optional(),
+ definition: z
+ .object({ line: z.number().int().nonnegative(), label: z.string() })
+ .loose()
+ .optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type LocalTargetDiagnosticEvidenceWire = z.infer<typeof LocalTargetDiagnosticEvidenceSchema>;
+
/**
* A content-rule violation on the post-write document — the full validation
* plane: markdown-lint findings AND broken internal links. Strictly advisory —
@@ -298,6 +330,12 @@ export const LintViolationWarningSchema = z
column: z.number().int().positive(),
/** `links` findings only: the unresolved target docName, verbatim. */
linkTarget: z.string().optional(),
+ /**
+ * `links` findings on a project-local file/image/reference target: the same
+ * additive evidence the audit plane carries. Absent on markdownlint findings
+ * and on document dead-links that flow from the graph.
+ */
+ localTarget: LocalTargetDiagnosticEvidenceSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type LintViolationWarning = z.infer<typeof LintViolationWarningSchema>;
@@ -370,6 +408,13 @@ export const BrokenLinkSchema = z
href: z.string(),
resolvedTo: z.string().nullable(),
reason: z.enum(BROKEN_LINK_REASONS),
+ /**
+ * Additive local-target evidence, matching what scoped audit reports for the
+ * same occurrence — carried for the forms the graph-only `{href, resolvedTo,
+ * reason}` triple cannot describe (images, reference-style targets). Absent
+ * on plain document/wiki links, whose triple already fully describes them.
+ */
+ localTarget: LocalTargetDiagnosticEvidenceSchema.optional(),
})
.loose() satisfies StandardSchemaV1;
export type BrokenLink = z.infer<typeof BrokenLinkSchema>;
diff --git a/packages/core/src/schemas/api/document-read.test.ts b/packages/core/src/schemas/api/document-read.test.ts
index 7007319e7..d7cf15aef 100644
--- a/packages/core/src/schemas/api/document-read.test.ts
+++ b/packages/core/src/schemas/api/document-read.test.ts
@@ -9,6 +9,7 @@ import {
ForwardLinkDocEntrySchema,
ForwardLinkEntrySchema,
ForwardLinkExternalEntrySchema,
+ ForwardLinkLocalTargetSchema,
ForwardLinksSuccessSchema,
LinkGraphDocNodeSchema,
LinkGraphEdgeSchema,
@@ -507,6 +508,140 @@ describe('ForwardLinkEntrySchema', () => {
});
});
+describe('ForwardLinkLocalTargetSchema', () => {
+ test('parses a missing-file row (link to an absent local file)', () => {
+ expect(
+ ForwardLinkLocalTargetSchema.safeParse({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: './report.pdf',
+ resolvedTarget: 'report.pdf',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 10, end: 32 },
+ line: 2,
+ column: 4,
+ definition: null,
+ }).success,
+ ).toBe(true);
+ });
+ test('parses a missing-image row (HTML img to an absent local image)', () => {
+ expect(
+ ForwardLinkLocalTargetSchema.safeParse({
+ role: 'image',
+ sourceForm: 'html-img',
+ targetKind: 'file',
+ href: './pic.png',
+ resolvedTarget: 'pic.png',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 0, end: 24 },
+ line: 0,
+ column: 0,
+ definition: null,
+ }).success,
+ ).toBe(true);
+ });
+ test('parses an exact (resolved) image row with a null reason', () => {
+ const result = ForwardLinkLocalTargetSchema.safeParse({
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: './logo.svg',
+ resolvedTarget: 'logo.svg',
+ status: 'exact',
+ reason: null,
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 5, end: 20 },
+ line: 1,
+ column: 5,
+ definition: null,
+ });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.reason).toBeNull();
+ });
+ test('parses a reference-style row carrying the shared definition pointer', () => {
+ const result = ForwardLinkLocalTargetSchema.safeParse({
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ targetKind: 'file',
+ href: './data.csv',
+ resolvedTarget: 'data.csv',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 40, end: 49 },
+ line: 3,
+ column: 0,
+ definition: { label: 'data', line: 9 },
+ });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.definition).toEqual({ label: 'data', line: 9 });
+ });
+ test('defaults fallbackTarget and definition to null when omitted', () => {
+ const result = ForwardLinkLocalTargetSchema.safeParse({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: './a.pdf',
+ resolvedTarget: 'a.pdf',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ range: { start: 0, end: 8 },
+ line: 0,
+ column: 0,
+ });
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.fallbackTarget).toBeNull();
+ expect(result.data.definition).toBeNull();
+ }
+ });
+ test('tolerates an unknown status/targetKind value (open enums — forward-compat)', () => {
+ // A client on an older schema must still parse a row whose server added a
+ // new status token later; the enums are deliberately open `z.string()`.
+ expect(
+ ForwardLinkLocalTargetSchema.safeParse({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'future-kind',
+ href: './x',
+ resolvedTarget: null,
+ status: 'future-status',
+ reason: null,
+ resolutionMethod: 'none',
+ range: { start: 0, end: 2 },
+ line: 0,
+ column: 0,
+ }).success,
+ ).toBe(true);
+ });
+ test('rejects a row missing its source range', () => {
+ expect(
+ ForwardLinkLocalTargetSchema.safeParse({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: './x.pdf',
+ resolvedTarget: 'x.pdf',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ line: 0,
+ column: 0,
+ }).success,
+ ).toBe(false);
+ });
+});
+
describe('ForwardLinksSuccessSchema', () => {
test('parses success body', () => {
expect(
@@ -524,6 +659,45 @@ describe('ForwardLinksSuccessSchema', () => {
}).success,
).toBe(true);
});
+ test('a legacy response without localTargets stays valid; the field is undefined', () => {
+ // Version skew: an older server omits the sibling collection entirely. The
+ // document/external union is untouched, so the response must still parse.
+ const result = ForwardLinksSuccessSchema.safeParse({
+ docName: 'alpha',
+ forwardLinks: [{ kind: 'doc', docName: 'beta', anchor: null, title: 'Beta', snippet: null }],
+ });
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.localTargets).toBeUndefined();
+ });
+ test('a current response carries localTargets alongside the forwardLinks union', () => {
+ const body = {
+ docName: 'alpha',
+ forwardLinks: [{ kind: 'doc', docName: 'beta', anchor: null, title: 'Beta', snippet: null }],
+ localTargets: [
+ {
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ href: './missing.png',
+ resolvedTarget: 'missing.png',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ range: { start: 12, end: 40 },
+ line: 2,
+ column: 0,
+ definition: null,
+ },
+ ],
+ };
+ const result = ForwardLinksSuccessSchema.safeParse(body);
+ expect(result.success).toBe(true);
+ if (result.success) {
+ // Fully-specified rows round-trip unchanged (defaults already applied).
+ expect(result.data).toEqual(body);
+ }
+ });
});
describe('LinkGraphNodeSchema', () => {
diff --git a/packages/core/src/schemas/api/document-read.ts b/packages/core/src/schemas/api/document-read.ts
index c002da03f..056134d56 100644
--- a/packages/core/src/schemas/api/document-read.ts
+++ b/packages/core/src/schemas/api/document-read.ts
@@ -262,11 +262,74 @@ export const ForwardLinkEntrySchema = z.discriminatedUnion('kind', [
]) satisfies StandardSchemaV1;
export type ForwardLinkEntry = z.infer<typeof ForwardLinkEntrySchema>;
-/** Success body for `GET /api/forward-links?docName=...`. */
+/**
+ * One local file or image reference a document authors, carried in the optional
+ * `localTargets` sibling of the forward-links response and rendered in the Links
+ * panel's Local files section. It is NOT a member of the `forwardLinks`
+ * document/external union — files and images are resources, not document graph
+ * edges — and it comes from the server's local-target assessment index, not from
+ * reclassified graph rows.
+ *
+ * One row per authored occurrence: two references to the same file produce two
+ * rows, each with its own `range`, so repeated uses stay individually navigable
+ * rather than collapsing to graph cardinality.
+ *
+ * Value domains (kept as open `z.string()` enums so a client on an older schema
+ * tolerates a value the server adds later, exactly like the `source` field on
+ * validation diagnostics):
+ * - `role`: `'link' | 'image'`
+ * - `sourceForm`: `'markdown-inline' | 'markdown-reference' | 'html-img'`
+ * - `targetKind`: `'file'` for a resolvable file/image, `'unknown'` for an image
+ * whose path escapes the content root (documents are excluded from this list)
+ * - `status`: `'exact' | 'fallback' | 'missing' | 'unresolvable'`
+ * - `reason`: `'no-such-file' | 'unresolvable'`, or null when the target exists
+ * - `resolutionMethod`: `'source-relative' | 'root-relative' | 'tolerant' | 'none'`
+ */
+export const ForwardLinkLocalTargetSchema = z
+ .object({
+ role: z.string().min(1),
+ sourceForm: z.string().min(1),
+ targetKind: z.string().min(1),
+ href: z.string(),
+ // Content-root-relative identity the authored href resolves to, or null when
+ // unresolvable. For a `missing` target this is the identity that is absent.
+ resolvedTarget: z.string().nullable(),
+ status: z.string().min(1),
+ reason: z.string().nullable(),
+ resolutionMethod: z.string().min(1),
+ // Present only for `status: 'fallback'` — the existing target tolerant
+ // navigation reaches; files never carry one. Null otherwise.
+ fallbackTarget: z.string().nullable().default(null),
+ // Exact source range of the authored occurrence; `source.slice(start, end)`
+ // reproduces it verbatim and the editor scrolls here to navigate to it.
+ range: z.object({
+ start: z.number().int().nonnegative(),
+ end: z.number().int().nonnegative(),
+ }),
+ line: z.number().int().nonnegative(),
+ column: z.number().int().nonnegative(),
+ // Reference-style repair pointer: the shared `[label]` definition every use
+ // points at. Null for inline / HTML forms.
+ definition: z
+ .object({ label: z.string(), line: z.number().int().nonnegative() })
+ .nullable()
+ .default(null),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type ForwardLinkLocalTarget = z.infer<typeof ForwardLinkLocalTargetSchema>;
+
+/**
+ * Success body for `GET /api/forward-links?docName=...`. `localTargets` is an
+ * additive sibling collection kept OUT of the `forwardLinks` document/external
+ * union so document relationship semantics stay pure. Absent on legacy responses
+ * (an older server omits it); a current server always sends it, possibly empty.
+ * Separately versionable from `forwardLinks`.
+ */
export const ForwardLinksSuccessSchema = z
.object({
docName: z.string().min(1),
forwardLinks: z.array(ForwardLinkEntrySchema),
+ localTargets: z.array(ForwardLinkLocalTargetSchema).optional(),
})
.loose() satisfies StandardSchemaV1;
export type ForwardLinksSuccess = z.infer<typeof ForwardLinksSuccessSchema>;
diff --git a/packages/core/src/schemas/cc1.ts b/packages/core/src/schemas/cc1.ts
index 62d584f09..ba4747024 100644
--- a/packages/core/src/schemas/cc1.ts
+++ b/packages/core/src/schemas/cc1.ts
@@ -96,6 +96,13 @@ export const CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR = 'config-ignore-nested-erro
* `.ok/config.yml` + native/schema files fresh from disk, so clients must
* refetch when the persisted bytes change — a moment the config CRDT
* observers fire BEFORE (persistence debounce), not at.
+ *
+ * `local-targets` invalidates project-local file/image target assessments:
+ * a source edit or a document/ordinary-file create/delete/rename reassessed
+ * some sources' local-target findings, so consumers refetch the assessment
+ * projection. Distinct from `backlinks` (document relationship graph) and
+ * `files` (raw file list) so a file mutation that only heals a `[x](y.pdf)`
+ * finding does not force a graph or listing refetch.
*/
export const DerivedViewChannelSchema = z.enum([
'files',
@@ -106,6 +113,7 @@ export const DerivedViewChannelSchema = z.enum([
'tags',
'comments',
'lint-config',
+ 'local-targets',
]);
export type DerivedViewChannel = z.infer<typeof DerivedViewChannelSchema>;
diff --git a/packages/server/src/api-backlinks.test.ts b/packages/server/src/api-backlinks.test.ts
index 5c237dff3..7b843214c 100644
--- a/packages/server/src/api-backlinks.test.ts
+++ b/packages/server/src/api-backlinks.test.ts
@@ -563,6 +563,37 @@ describe('graph endpoints', () => {
}
});
+ test('keeps forward links available while the local-target projection is not ready', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-forward-links-partial-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ const unavailableIndex = new DerivedDocumentIndex({
+ projectDir,
+ contentDir,
+ contentFilter: createContentFilter({ projectDir, contentDir }),
+ getGlobalSkillRoots: () => [],
+ getLocalTargetInventory: () => null,
+ signalChannel: () => {},
+ });
+ unavailableIndex.beginStartup('main');
+ await unavailableIndex.settleStartupAfterWatcherSeed();
+
+ try {
+ const response = await callRoute(
+ contentDir,
+ '/api/forward-links?docName=doc',
+ new Map(),
+ undefined,
+ { derivedDocumentIndex: unavailableIndex },
+ );
+ expect(response.status).toBe(200);
+ expect(JSON.parse(response.body)).toEqual({ docName: 'doc', forwardLinks: [] });
+ } finally {
+ await unavailableIndex.close();
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
test('forward-links / hubs / link-graph fall back to docName for excluded targets', async () => {
// Wiki-link targets parsed from indexed docs may name a doc that is
// itself excluded from the content scope (e.g. by `.gitignore` /
diff --git a/packages/server/src/api-extension.test-helper.ts b/packages/server/src/api-extension.test-helper.ts
index a34a6177c..3e4ad3ae2 100644
--- a/packages/server/src/api-extension.test-helper.ts
+++ b/packages/server/src/api-extension.test-helper.ts
@@ -56,6 +56,9 @@ export function createDerivedDocumentIndexApiPortStub(
async getDeadLinks() {
return [];
},
+ async getLocalTargetAssessmentsForSources() {
+ return [];
+ },
async getIndexedDocNames() {
return [];
},
@@ -200,6 +203,11 @@ function createLegacyDerivedIndexPort(
async getDeadLinks(admittedDocuments, sourceDocumentNames) {
return backlinkIndex?.getDeadLinks(admittedDocuments, sourceDocumentNames) ?? [];
},
+ // This legacy port wraps only the backlink + tag indexes; the local-target
+ // assessment index is not part of it, so there are no local-target findings.
+ async getLocalTargetAssessmentsForSources() {
+ return [];
+ },
async getIndexedDocNames() {
return backlinkIndex?.getIndexedDocNames() ?? [];
},
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index c168602c5..902830b01 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -525,7 +525,6 @@ import {
ManagedRenameSourceTypeMismatchError,
SymlinkEscapeError,
} from './apply-managed-rename.ts';
-import { computeBrokenOutboundLinks } from './backlink-index.ts';
import { getBootTimings } from './boot-timings.ts';
import { composeAndWriteRawBody, type PrecomputedParse, replaceRawBody } from './bridge-intake.ts';
import type { BridgeDeriveLossReporter } from './bridge-loss-detector.ts';
@@ -646,6 +645,7 @@ import {
runGhDeviceLoginSubprocess,
runPatSubprocess,
} from './local-ops/index.ts';
+import { localTargetInventoryFromIndexes } from './local-target-inventory.ts';
import { getLogger } from './logger.ts';
import {
managedArtifactAbsPath,
@@ -726,6 +726,7 @@ import type { SyncEngine } from './sync-engine.ts';
import { getMeter, withSpan, withSpanSync } from './telemetry.ts';
import { getDocumentHistory, getFolderTimeline } from './timeline-query.ts';
import { recordTimelineCoalesced } from './timeline-telemetry.ts';
+import { computeWriteAdvisoryLinks } from './write-advisory-links.ts';
// Lazy-init so the counter registers against a real meter post-initTelemetry
// (not the pre-init no-op). Matches the httpDurationHist pattern in
@@ -3519,14 +3520,43 @@ export function createApiExtension(
);
}
- // On-disk existence oracle for non-doc outbound link targets (linked assets
- // and source files) used by `computeBrokenOutboundLinks`. Doc links resolve
- // against the admitted set above; file links have no CRDT presence, so a
- // just-written `[x](../src/foo.py)` is validated against the filesystem. The
- // path is already content-root-confined by `resolveAssetProjectPath`, so
- // `resolve(contentDir, …)` cannot escape the tree.
- const linkedFileExists = (contentRootRelativePath: string): boolean =>
- existsSync(resolve(contentDir, contentRootRelativePath));
+ // Content-scoped existence oracle for non-doc outbound targets. The watcher
+ // inventory is authoritative once an entry is indexed. The confined disk
+ // fallback preserves immediate write advisories during the short window
+ // between a native file creation and its watcher event, while applying the
+ // same ignore and realpath-escape gates before admitting that file.
+ function createLinkedFileExists(
+ allFiles = getAllFilesIndex(),
+ ): (contentRootRelativePath: string) => boolean {
+ const inventory = localTargetInventoryFromIndexes(
+ allFiles,
+ getFolderAliasIndex?.() ?? new Map(),
+ contentDir,
+ );
+ const admittedFiles = new Set(inventory.fileTargets);
+ const canonicalContentDir = realpathSync(contentDir);
+ return (contentRootRelativePath) => {
+ if (admittedFiles.has(contentRootRelativePath)) return true;
+ if (contentFilter?.isPathIgnored(contentRootRelativePath)) return false;
+
+ const candidate = resolve(contentDir, contentRootRelativePath);
+ if (!isWithinDir(candidate, contentDir) || !existsSync(candidate)) return false;
+ try {
+ return isWithinDir(realpathSync(candidate), canonicalContentDir);
+ } catch (err) {
+ // ENOENT is the expected TOCTOU race (deleted between existsSync and
+ // realpathSync) and needs no note; anything else (EACCES, ELOOP) would
+ // otherwise report a persistently absent file with no diagnostic.
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.debug(
+ { err, candidate },
+ 'linked-file existence fallback could not canonicalize; treating as absent',
+ );
+ }
+ return false;
+ }
+ };
+ }
// Synchronously register a just-persisted agent-write doc into the file index,
// mirroring `/api/create-page`. The file-watcher normally adds it on the next
@@ -5510,11 +5540,11 @@ export function createApiExtension(
// isn't falsely flagged before the file-watcher indexes it on disk.
const admittedForLinks = await collectAdmittedDocNames();
admittedForLinks.add(resolvedDocName);
- const brokenLinks = computeBrokenOutboundLinks(
+ const brokenLinks = computeWriteAdvisoryLinks(
writtenSource,
resolvedDocName,
admittedForLinks,
- linkedFileExists,
+ createLinkedFileExists(),
);
const subscriberCount = getSubscriberCount(resolvedDocName);
@@ -5673,7 +5703,7 @@ export function createApiExtension(
docName: string;
summary?: SummaryResponse;
warnings?: AdvisoryWarning[];
- brokenLinks: ReturnType<typeof computeBrokenOutboundLinks>;
+ brokenLinks: ReturnType<typeof computeWriteAdvisoryLinks>;
}
type BatchResult = BatchWrittenResult | BatchErrorResult;
@@ -5936,6 +5966,7 @@ export function createApiExtension(
for (const p of pending) {
if (flushErrors.get(p.docName) === undefined) admittedForLinks.add(p.docName);
}
+ const linkedFileExists = createLinkedFileExists();
let lastWrittenDoc: string | undefined;
for (const p of pending) {
@@ -5946,7 +5977,7 @@ export function createApiExtension(
}
const writtenSource = p.session.dc.document.getText('source').toString();
registerWrittenDocInFileIndex(p.docName, writtenSource);
- const brokenLinks = computeBrokenOutboundLinks(
+ const brokenLinks = computeWriteAdvisoryLinks(
writtenSource,
p.docName,
admittedForLinks,
@@ -6299,11 +6330,11 @@ export function createApiExtension(
// the contract uniform rather than returning a misleading empty `[]`.
const admittedForLinks = await collectAdmittedDocNames();
admittedForLinks.add(resolvedDocName);
- const brokenLinks = computeBrokenOutboundLinks(
+ const brokenLinks = computeWriteAdvisoryLinks(
session.dc.document.getText('source').toString(),
resolvedDocName,
admittedForLinks,
- linkedFileExists,
+ createLinkedFileExists(),
);
successResponse(
@@ -6839,11 +6870,11 @@ export function createApiExtension(
// just-edited source bytes; see handleAgentWriteMd for the full why.
const admittedForLinks = await collectAdmittedDocNames();
admittedForLinks.add(docName);
- const brokenLinks = computeBrokenOutboundLinks(
+ const brokenLinks = computeWriteAdvisoryLinks(
patchedSource,
docName,
admittedForLinks,
- linkedFileExists,
+ createLinkedFileExists(),
);
// Success body is flat — no `{ ok: true }` wrapper.
@@ -20503,10 +20534,10 @@ export function createApiExtension(
}
/**
- * The world an audit plane would be true of: the lint configuration in force
- * plus the branch whose content is on disk. The audit's coalescing key and
- * its in-flight walks both rest on this one reader, so the two stay in step
- * by construction.
+ * The world an audit plane would be true of: the lint configuration in force,
+ * the branch whose content is on disk, and the local-target inventory
+ * generation. The audit's coalescing key and its in-flight walks both rest on
+ * this one reader, so the three stay in step by construction.
*
* Branch belongs here for the same reason the config epoch does, one layer
* down: a switch replaces the content set wholesale, so a request issued
@@ -20518,7 +20549,9 @@ export function createApiExtension(
* a git branch name (refnames admit no spaces) or a `detached-<oid>` literal.
*/
const readAuditGeneration = (): string =>
- `${lintConfigEpoch} ${durabilityState.getActiveBranch()}`;
+ `${lintConfigEpoch} ${durabilityState.getActiveBranch()} ${
+ derivedDocumentIndex?.readLocalTargetGeneration?.() ?? 0
+ }`;
// Content-rule violations on a post-write document, for the agent write/edit
// advisory channel — the full validation plane, not just lint: every enabled
@@ -20589,6 +20622,9 @@ export function createApiExtension(
line: d.range.start.line + 1,
column: d.range.start.character + 1,
...('linkTarget' in d && d.linkTarget !== undefined ? { linkTarget: d.linkTarget } : {}),
+ ...('localTarget' in d && d.localTarget !== undefined
+ ? { localTarget: d.localTarget }
+ : {}),
}));
} catch (err) {
log.warn(
diff --git a/packages/server/src/api-forward-links-local-targets.test.ts b/packages/server/src/api-forward-links-local-targets.test.ts
new file mode 100644
index 000000000..564ce3a6a
--- /dev/null
+++ b/packages/server/src/api-forward-links-local-targets.test.ts
@@ -0,0 +1,119 @@
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { ForwardLinksSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig } from './composition-rig.test-helper.ts';
+
+/**
+ * The forward-links response projects local file/image references from the REAL
+ * assessment index over the composed `bootServer` stack (real watcher seed →
+ * DerivedDocumentIndex → LocalTargetIndex → HTTP). This is the composition
+ * boundary the local-target sibling collection introduces: a mocked index would
+ * leave the seam UNKNOWN, so the test boots the real server against on-disk
+ * fixtures and reads the wire body through the shared core schema.
+ */
+
+const NOTES = [
+ '# Notes',
+ '',
+ '![logo](./logo.png)',
+ '',
+ '![gone](./gone.png)',
+ '',
+ '![gone](./gone.png)',
+ '',
+ '[report](./report.pdf)',
+ '',
+ '[peer](./peer.md)',
+ '',
+ 'Reference to [grab][data].',
+ '',
+ '[data]: ./data.csv',
+ '',
+].join('\n');
+
+let tmpRoot: string;
+let server: BootedServer;
+
+beforeAll(async () => {
+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-fwdlinks-localtargets-'));
+ const dir = mkdtempSync(resolve(tmpRoot, 'content-'));
+ writeFileSync(resolve(dir, 'notes.md'), NOTES, 'utf-8');
+ // peer.md is an admitted document; logo.png an admitted ordinary file. The
+ // other three targets (gone.png, report.pdf, data.csv) are deliberately absent.
+ writeFileSync(resolve(dir, 'peer.md'), '# Peer\n\nBody.\n', 'utf-8');
+ writeFileSync(resolve(dir, 'logo.png'), 'not-a-real-png-just-needs-to-exist', 'utf-8');
+ server = await bootCompositionRig(dir);
+ await server.ready;
+}, 60_000);
+
+afterAll(async () => {
+ await server?.destroy();
+ await rm(tmpRoot, { recursive: true, force: true });
+});
+
+describe('GET /api/forward-links — local-target sibling collection', () => {
+ test('projects file/image references with exact/missing status and preserves the forwardLinks union', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/forward-links?docName=notes`);
+ expect(res.status).toBe(200);
+
+ // New payloads survive the HTTP schema round trip through the real contract.
+ const body = ForwardLinksSuccessSchema.parse(await res.json());
+ const localTargets = body.localTargets ?? [];
+
+ // logo (exact image), gone ×2 (missing image), report.pdf (missing file
+ // link), data.csv (missing reference-style file). peer.md is a document, so
+ // it is absent here and present in forwardLinks instead.
+ expect(localTargets.map((r) => r.href).sort()).toEqual([
+ './data.csv',
+ './gone.png',
+ './gone.png',
+ './logo.png',
+ './report.pdf',
+ ]);
+ expect(localTargets.some((r) => r.targetKind === 'document')).toBe(false);
+ expect(localTargets.some((r) => r.href === './peer.md')).toBe(false);
+
+ expect(localTargets.find((r) => r.href === './logo.png')).toMatchObject({
+ role: 'image',
+ targetKind: 'file',
+ status: 'exact',
+ reason: null,
+ resolvedTarget: 'logo.png',
+ });
+ expect(localTargets.find((r) => r.href === './report.pdf')).toMatchObject({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolvedTarget: 'report.pdf',
+ });
+
+ const dataRow = localTargets.find((r) => r.href === './data.csv');
+ expect(dataRow).toMatchObject({
+ sourceForm: 'markdown-reference',
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ expect(dataRow?.definition?.label).toBe('data');
+
+ // The document link stays a graph edge in the forwardLinks union.
+ expect(body.forwardLinks).toContainEqual(
+ expect.objectContaining({ kind: 'doc', docName: 'peer' }),
+ );
+ });
+
+ test('repeated references to one missing image keep distinct navigable occurrences', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/forward-links?docName=notes`);
+ const body = ForwardLinksSuccessSchema.parse(await res.json());
+ const goneRows = (body.localTargets ?? []).filter((r) => r.href === './gone.png');
+ expect(goneRows).toHaveLength(2);
+ // Each occurrence carries its own source range — not one collapsed edge.
+ expect(goneRows[0]?.range).not.toEqual(goneRows[1]?.range);
+ expect(goneRows.every((r) => r.status === 'missing' && r.role === 'image')).toBe(true);
+ });
+});
diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.ts
index e2c890948..bb8980da3 100644
--- a/packages/server/src/backlink-index.test.ts
+++ b/packages/server/src/backlink-index.test.ts
@@ -233,6 +233,34 @@ describe('extractWikiLinksFromMarkdown', () => {
});
describe('BacklinkIndex', () => {
+ test('indexes full, collapsed, and shortcut reference links across graph queries', () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-reference-links-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ try {
+ const index = new BacklinkIndex({ projectDir, contentDir });
+ index.updateDocumentFromMarkdown(
+ 'source',
+ [
+ 'See [full label][full-ref], [collapsed-ref][], and [shortcut-ref].',
+ '',
+ '[full-ref]: ./full-target.md',
+ '[collapsed-ref]: ./collapsed-target.md',
+ '[shortcut-ref]: ./shortcut-target.md',
+ ].join('\n'),
+ );
+
+ const targets = ['collapsed-target', 'full-target', 'shortcut-target'];
+ expect(index.getForwardLinks('source')).toEqual(targets);
+ for (const target of targets) {
+ expect(index.getBacklinks(target)).toEqual([expect.objectContaining({ source: 'source' })]);
+ }
+ expect(index.getDeadLinks(['source']).map((entry) => entry.target)).toEqual(targets);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
test('deleteDocument removes outbound links and incoming backlinks', () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-del-'));
const contentDir = join(projectDir, 'content');
@@ -1564,6 +1592,38 @@ describe('BacklinkIndex with markdown links', () => {
}
});
+ test('rebuildFromDisk indexes full, collapsed, and shortcut reference links', async () => {
+ const tmpDir = mkdtempSync(join(tmpdir(), 'backlinks-reference-rebuild-'));
+ try {
+ writeFileSync(
+ join(tmpDir, 'source.md'),
+ [
+ 'See [full label][full-ref], [collapsed-ref][], and [shortcut-ref].',
+ '',
+ '[full-ref]: ./full-target.md',
+ '[collapsed-ref]: ./collapsed-target.md',
+ '[shortcut-ref]: ./shortcut-target.md',
+ '',
+ ].join('\n'),
+ 'utf-8',
+ );
+ for (const target of ['full-target', 'collapsed-target', 'shortcut-target']) {
+ writeFileSync(join(tmpDir, `${target}.md`), `# ${target}\n`, 'utf-8');
+ }
+
+ const index = new BacklinkIndex({ projectDir: tmpDir, contentDir: tmpDir });
+ await index.rebuildFromDisk();
+
+ const targets = ['collapsed-target', 'full-target', 'shortcut-target'];
+ expect(index.getForwardLinks('source')).toEqual(targets);
+ for (const target of targets) {
+ expect(index.getBacklinks(target)).toEqual([expect.objectContaining({ source: 'source' })]);
+ }
+ } finally {
+ rmSync(tmpDir, { recursive: true, force: true });
+ }
+ });
+
test('wiki link wins for same target when both syntaxes link to the same page', () => {
const tmpDir = mkdtempSync(join(tmpdir(), 'backlinks-dedup-'));
try {
diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.ts
index 59fc1df08..d8c72c544 100644
--- a/packages/server/src/backlink-index.ts
+++ b/packages/server/src/backlink-index.ts
@@ -25,6 +25,7 @@ import type { ContentFilter } from './content-filter.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
import { instrumentIndexRebuild } from './index-telemetry.ts';
import { readMarkdownLinkAt, readWikiLinkAt } from './link-syntax.ts';
+import { extractLocalTargetOccurrences } from './local-target-occurrences.ts';
import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
@@ -37,6 +38,46 @@ interface InlineWikiLinkOccurrence {
end: number;
}
+/**
+ * The one inventory question the graph plane has to ask before it can decide
+ * whether an extension-less href names a document.
+ *
+ * Without it this plane has no file inventory at all, so it reads
+ * `assets/NOTICE` as a document and emits a dead-document edge for a file that
+ * is right there on disk — while the local-target plane, which does see the
+ * files, calls the same occurrence an existing file. Structurally satisfied by
+ * `LocalTargetInventory`, so the two planes share one oracle rather than each
+ * growing their own.
+ *
+ * Optional at every entry point: a caller with no inventory (a rebuild before
+ * the file index has seeded, a test exercising graph shape alone) keeps the
+ * document-shaped reading, which is the safe default when existence is unknown.
+ */
+export interface GraphFileOracle {
+ /** Whether a content-root-relative path names an admitted ordinary file. */
+ hasFile(contentRootRelativePath: string): boolean;
+}
+
+/**
+ * Whether an extension-less doc-shaped href actually names an existing ordinary
+ * file, which makes it NOT a document edge.
+ *
+ * Mirrors the local-target plane's disambiguation: document identity is decided
+ * by the caller, and an exact file hit is what overrides it. An href carrying a
+ * document extension is never re-read as a file, so `notes/guide.md` stays a
+ * document even if some file of that name is tracked.
+ */
+function namesExistingFile(
+ href: string,
+ sourceDocName: string,
+ oracle: GraphFileOracle | undefined,
+): boolean {
+ if (!oracle) return false;
+ if (isSupportedDocFile(href)) return false;
+ const filePath = resolveAssetProjectPath(href, sourceDocName);
+ return filePath !== null && oracle.hasFile(filePath);
+}
+
interface FenceState {
char: '`' | '~';
length: number;
@@ -46,6 +87,8 @@ export interface ExtractedWikiLink {
target: string;
anchor: string | null;
snippet: string | null;
+ /** Authored syntax that produced this graph edge. */
+ sourceForm?: 'wiki' | 'markdown';
/**
* 0-based source line of the occurrence (the extractor's `lineOffset` param
* folds a stripped-frontmatter prefix back in, keeping this full-doc exact).
@@ -69,6 +112,8 @@ export interface BacklinkEntry {
source: string;
anchor: string | null;
snippet: string | null;
+ /** Authored syntax retained for cross-plane audit reconciliation. */
+ sourceForm?: 'wiki' | 'markdown';
/**
* 0-based full-doc position of the link occurrence in the source doc (line
* exact, column approximate — see `ExtractedWikiLink`). Absent on entries
@@ -126,6 +171,7 @@ export { isOrphanMode, ORPHAN_MODES, type OrphanMode };
interface BackwardLinkMeta {
anchor: string | null;
snippet: string | null;
+ sourceForm?: 'wiki' | 'markdown';
line?: number;
column?: number;
}
@@ -176,6 +222,13 @@ interface BacklinkIndexOptions {
projectDir: string;
contentDir: string;
contentFilter?: ContentFilter;
+ /**
+ * Existence oracle for ordinary files, so an extension-less href naming a
+ * tracked file is not read as a document edge. Supplied as a getter because
+ * the file inventory seeds asynchronously and lives in a sibling index — the
+ * graph must read it live, not capture it at construction.
+ */
+ getFileOracle?: () => GraphFileOracle | undefined;
}
function createEmptyState(): BranchGraphState {
@@ -239,6 +292,7 @@ function mergeLinkMeta(
return {
anchor: existing.anchor ?? next.anchor,
snippet: existing.snippet ?? next.snippet,
+ sourceForm: existing.sourceForm ?? next.sourceForm,
line: positioned.line,
column: positioned.column,
};
@@ -499,6 +553,7 @@ function readMarkdownLink(
function extractMarkdownLinksFromLine(
line: string,
sourceDocName: string,
+ fileOracle?: GraphFileOracle,
): { text: string; occurrences: InlineWikiLinkOccurrence[] } {
let flatText = '';
const occurrences: InlineWikiLinkOccurrence[] = [];
@@ -534,7 +589,10 @@ function extractMarkdownLinksFromLine(
const mdLink = readMarkdownLink(line, idx);
if (mdLink) {
const classified = classifyMarkdownHref(mdLink.href, sourceDocName);
- if (classified?.kind === 'doc') {
+ if (
+ classified?.kind === 'doc' &&
+ !namesExistingFile(mdLink.href, sourceDocName, fileOracle)
+ ) {
const start = flatText.length;
flatText += mdLink.text;
occurrences.push({
@@ -642,6 +700,7 @@ export function extractMarkdownLinksFromMarkdown(
markdown: string,
sourceDocName: string,
lineOffset = 0,
+ fileOracle?: GraphFileOracle,
): ExtractedWikiLink[] {
const source = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
const lines = source.split('\n');
@@ -658,7 +717,7 @@ export function extractMarkdownLinksFromMarkdown(
if (nextFence) {
fence = nextFence;
} else {
- const extracted = extractMarkdownLinksFromLine(line, sourceDocName);
+ const extracted = extractMarkdownLinksFromLine(line, sourceDocName, fileOracle);
links.push(
...extracted.occurrences.map(({ target, anchor, start, end }) => ({
target,
@@ -672,6 +731,65 @@ export function extractMarkdownLinksFromMarkdown(
}
}
+ links.push(...extractReferenceLinksFromMarkdown(source, sourceDocName, lineOffset, fileOracle));
+
+ return links;
+}
+
+/**
+ * A line-initial `[label]:` — CommonMark's reference-definition opener, allowing
+ * the up-to-three-space indent it permits and backslash-escaped brackets inside
+ * the label (`[foo\]bar]:`). Permissive by design: a false positive just runs
+ * the real extractor, which decides for itself.
+ */
+const HAS_REFERENCE_DEFINITION = /^ {0,3}\[(?:\\.|[^\\\]])*\]:/m;
+
+/**
+ * Document edges authored as reference-style links (`[text][label]`,
+ * `[label][]`, `[label]`), whose destination lives in a separate definition.
+ *
+ * The line scanner above reads only inline destinations, so this pass is what
+ * makes a reference-style document link visible to the graph. Without it,
+ * Problems still warns (the local-target plane reads the definition straight
+ * from source) while Outgoing, backlinks, orphans, hubs, and dead-links all
+ * under-report by the same amount.
+ *
+ * Recognition is not re-implemented here. `extractLocalTargetOccurrences` is the
+ * consolidated reader for every authored form, including reference resolution
+ * and the full non-rendering-context masking, so this reuses it and keeps only
+ * the graph-shaped projection: document-kind link occurrences, minus any that
+ * name an existing ordinary file.
+ */
+function extractReferenceLinksFromMarkdown(
+ source: string,
+ sourceDocName: string,
+ lineOffset: number,
+ fileOracle: GraphFileOracle | undefined,
+): ExtractedWikiLink[] {
+ // The full occurrence extractor is the price of not re-implementing reference
+ // resolution, and this runs per document on every rebuild and every write. A
+ // reference use needs a matching definition to be a link at all, and a
+ // definition is a line-initial `[label]:`, so a body without one cannot
+ // contain a reference edge. Most documents have none, and they skip the pass.
+ if (!HAS_REFERENCE_DEFINITION.test(source)) return [];
+
+ const links: ExtractedWikiLink[] = [];
+ for (const occurrence of extractLocalTargetOccurrences(source)) {
+ if (occurrence.sourceForm !== 'markdown-reference' || occurrence.role !== 'link') continue;
+ const classified = classifyMarkdownHref(occurrence.href, sourceDocName);
+ if (classified?.kind !== 'doc') continue;
+ if (namesExistingFile(occurrence.href, sourceDocName, fileOracle)) continue;
+ links.push({
+ target: classified.docName,
+ anchor: classified.anchor,
+ // The reference's visible text is its label, not its destination, and the
+ // occurrence range covers the whole authored use — enough for a snippet
+ // without re-flattening the line the way the inline scanner does.
+ snippet: source.slice(occurrence.range.start, occurrence.range.end) || null,
+ line: lineOffset + occurrence.line,
+ column: occurrence.column,
+ });
+ }
return links;
}
@@ -964,6 +1082,7 @@ function serializeState(state: BranchGraphState): SerializedBranchGraphState {
source,
anchor: meta.anchor,
snippet: meta.snippet,
+ sourceForm: meta.sourceForm,
line: meta.line,
column: meta.column,
})),
@@ -1042,6 +1161,10 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {
{
anchor: entry.anchor ?? null,
snippet: entry.snippet ?? null,
+ sourceForm:
+ entry.sourceForm === 'wiki' || entry.sourceForm === 'markdown'
+ ? entry.sourceForm
+ : undefined,
// Cache files predating position indexing lack these fields, and
// the cache is read without schema validation — admit non-negative
// integers only (typeof alone lets -2 / 1.5 / NaN through to the
@@ -1068,6 +1191,7 @@ export class BacklinkIndex {
private readonly projectDir: string;
private readonly contentDir: string;
private readonly contentFilter?: ContentFilter;
+ private readonly getFileOracle: () => GraphFileOracle | undefined;
private readonly states = new Map<string, BranchGraphState>();
/**
* Per-branch mtime snapshots. Populated by rebuildFromDisk / reconcileWithDisk
@@ -1081,6 +1205,7 @@ export class BacklinkIndex {
this.projectDir = options.projectDir;
this.contentDir = options.contentDir;
this.contentFilter = options.contentFilter;
+ this.getFileOracle = options.getFileOracle ?? (() => undefined);
this.states.set(this.activeBranch, createEmptyState());
}
@@ -1321,6 +1446,7 @@ export class BacklinkIndex {
mergeLinkMeta(sources.get(docName), {
anchor: link.anchor,
snippet: link.snippet,
+ sourceForm: link.sourceForm,
line: link.line,
column: link.column,
}),
@@ -1351,8 +1477,16 @@ export class BacklinkIndex {
try {
const { frontmatter, body } = stripFrontmatter(markdown);
const lineOffset = frontmatterLineCount(frontmatter);
- const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset);
- const mdLinks = extractMarkdownLinksFromMarkdown(body, docName, lineOffset);
+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset).map((link) => ({
+ ...link,
+ sourceForm: 'wiki' as const,
+ }));
+ const mdLinks = extractMarkdownLinksFromMarkdown(
+ body,
+ docName,
+ lineOffset,
+ this.getFileOracle(),
+ ).map((link) => ({ ...link, sourceForm: 'markdown' as const }));
const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);
const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);
// Merge: wiki links take precedence for duplicate targets (they have richer snippet context)
@@ -1576,6 +1710,7 @@ export class BacklinkIndex {
source,
anchor: meta.anchor,
snippet: meta.snippet,
+ sourceForm: meta.sourceForm,
line: meta.line,
column: meta.column,
}))
@@ -1864,8 +1999,16 @@ export class BacklinkIndex {
mtimes.set(docName, mtimeMs);
const { frontmatter, body } = stripFrontmatter(markdown);
const lineOffset = frontmatterLineCount(frontmatter);
- const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset);
- const mdLinks = extractMarkdownLinksFromMarkdown(body, docName, lineOffset);
+ const wikiLinks = extractWikiLinksFromMarkdown(body, docName, lineOffset).map((link) => ({
+ ...link,
+ sourceForm: 'wiki' as const,
+ }));
+ const mdLinks = extractMarkdownLinksFromMarkdown(
+ body,
+ docName,
+ lineOffset,
+ this.getFileOracle(),
+ ).map((link) => ({ ...link, sourceForm: 'markdown' as const }));
const wikiExternalLinks = extractExternalWikiLinksFromMarkdown(body);
const mdExternalLinks = extractExternalMarkdownLinksFromMarkdown(body, docName);
const seen = new Set(wikiLinks.map((l) => l.target));
@@ -1892,6 +2035,7 @@ export class BacklinkIndex {
mergeLinkMeta(sources.get(docName), {
anchor: link.anchor,
snippet: link.snippet,
+ sourceForm: link.sourceForm,
line: link.line,
column: link.column,
}),
diff --git a/packages/server/src/derived-document-index.test.ts b/packages/server/src/derived-document-index.test.ts
index 7fd409941..cd47cfffa 100644
--- a/packages/server/src/derived-document-index.test.ts
+++ b/packages/server/src/derived-document-index.test.ts
@@ -8,6 +8,8 @@ import {
DerivedDocumentIndex,
isDerivedDocumentIndexClosedError,
} from './derived-document-index.ts';
+import { LocalTargetIndex } from './local-target-index.ts';
+import type { WatcherLocalTargetInventory } from './local-target-inventory.ts';
import { getLogger } from './logger.ts';
import { TagIndex } from './tag-index.ts';
@@ -34,7 +36,10 @@ function createDeferred(): Deferred {
return { promise, resolve };
}
-function createRig(): Rig {
+function createRig(
+ getLocalTargetInventory?: () => WatcherLocalTargetInventory | null,
+ onRecoveredFileTarget?: (relativePath: string, exists: boolean) => void,
+): Rig {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-derived-index-'));
const contentDir = join(projectDir, 'content');
mkdirSync(contentDir, { recursive: true });
@@ -46,6 +51,8 @@ function createRig(): Rig {
contentFilter,
getGlobalSkillRoots: () => [],
signalChannel: (channel) => signals.push(channel),
+ ...(getLocalTargetInventory ? { getLocalTargetInventory } : {}),
+ ...(onRecoveredFileTarget ? { onRecoveredFileTarget } : {}),
});
cleanups.push(async () => {
await index.close();
@@ -693,6 +700,67 @@ describe('DerivedDocumentIndex', () => {
);
});
+ test('a startup graph pass with no file inventory keeps extension-less file hrefs as document edges', async () => {
+ // The watcher never seeds (factory stays null), as when it fails outright:
+ // the settlement reconcile has no inventory to consult either, so the
+ // startup pass's document-shaped reading of `assets/NOTICE` persists.
+ const rig = createRig(() => null);
+ writeDoc(rig, 'src.md', 'See [notice](assets/NOTICE).\n');
+ writeDoc(rig, 'assets/NOTICE', 'plain text\n');
+
+ const startup = rig.index.beginStartup('main');
+ await startup.backlinksReady;
+ await rig.index.settleStartupAfterWatcherSeed();
+
+ expect((await rig.index.getBacklinks('assets/NOTICE')).map((entry) => entry.source)).toEqual([
+ 'src',
+ ]);
+ });
+
+ test('startup settlement re-derives the graph once the watcher inventory arrives', async () => {
+ let inventory: WatcherLocalTargetInventory | null = null;
+ const rig = createRig(() => inventory);
+ writeDoc(rig, 'src.md', 'See [notice](assets/NOTICE).\n');
+ writeDoc(rig, 'assets/NOTICE', 'plain text\n');
+
+ const startup = rig.index.beginStartup('main');
+ await startup.backlinksReady;
+ // The real cold-boot ordering: the graph builds before the watcher seeds,
+ // then the inventory exists by the time startup settles.
+ inventory = { documentTargets: ['src'], fileTargets: ['assets/NOTICE'] };
+ await rig.index.settleStartupAfterWatcherSeed();
+
+ // The reconcile re-derived the graph against the inventory: the
+ // extension-less href names an existing ordinary file, not a document.
+ expect(await rig.index.getBacklinks('assets/NOTICE')).toEqual([]);
+ });
+
+ test('startup settlement re-derives a warm graph cache against the watcher inventory', async () => {
+ let inventory: WatcherLocalTargetInventory | null = null;
+ const rig = createRig(() => inventory);
+ writeDoc(rig, 'src.md', 'See [notice](assets/NOTICE).\n');
+ writeDoc(rig, 'assets/NOTICE', 'plain text\n');
+
+ // Seed the persisted cache in the pre-inventory shape an older build or a
+ // prior cold startup would have written. Its mtime snapshot is current, so
+ // the warm reconcile legitimately has no changed document to re-parse.
+ const cached = new BacklinkIndex({
+ projectDir: rig.projectDir,
+ contentDir: rig.contentDir,
+ contentFilter: rig.contentFilter,
+ });
+ await cached.rebuildFromDisk('main');
+ await cached.saveToDisk('main');
+ expect(cached.getBacklinks('assets/NOTICE', 'main')).toHaveLength(1);
+
+ const startup = rig.index.beginStartup('main');
+ await startup.backlinksReady;
+ inventory = { documentTargets: ['src'], fileTargets: ['assets/NOTICE'] };
+ await rig.index.settleStartupAfterWatcherSeed();
+
+ expect(await rig.index.getBacklinks('assets/NOTICE')).toEqual([]);
+ });
+
test('close flushes a pending paired save and rejects future commands', async () => {
vi.useFakeTimers();
const backlinkSave = vi.spyOn(BacklinkIndex.prototype, 'saveToDisk');
@@ -816,3 +884,292 @@ describe('DerivedDocumentIndex', () => {
expect(backlinkSave).toHaveBeenCalledTimes(2);
});
});
+
+describe('DerivedDocumentIndex local-target projection', () => {
+ test('a source edit assesses local targets and signals local-targets alongside relations', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+
+ await rig.index.recordDirectDocument('src', 'See [x](target) and [pdf](assets/f.pdf).\n');
+
+ const assessments = await rig.index.getLocalTargetAssessments('src');
+ expect(assessments.map((a) => [a.targetKind, a.resolvedTarget, a.status])).toEqual([
+ ['document', 'target', 'missing'],
+ ['file', 'assets/f.pdf', 'missing'],
+ ]);
+ // local-targets rides the relation signal set only because an assessment moved.
+ expect(rig.signals).toEqual(['backlinks', 'graph', 'local-targets', 'tags']);
+ });
+
+ test('the batch source query returns every source, or a scoped subset, through the ready gate', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+ await rig.index.recordDirectDocument('a', 'Download [pdf](assets/a.pdf).\n');
+ await rig.index.recordDirectDocument('b', 'Download [pdf](assets/b.pdf).\n');
+
+ const all = await rig.index.getLocalTargetAssessmentsForSources();
+ expect(all.map((entry) => entry.source).sort()).toEqual(['a', 'b']);
+ expect(all.flatMap((entry) => entry.assessments).every((a) => a.status === 'missing')).toBe(
+ true,
+ );
+
+ // A source filter narrows enumeration to just those sources — the path a
+ // folder/doc scope drives.
+ const scoped = await rig.index.getLocalTargetAssessmentsForSources(['a']);
+ expect(scoped.map((entry) => entry.source)).toEqual(['a']);
+ });
+
+ test('wiki-only and occurrence-free edits never signal local-targets or move its generation', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+ const generation = await rig.index.getLocalTargetGeneration();
+
+ await rig.index.recordDirectDocument('wiki', 'See [[target]]. #tagged\n');
+
+ expect(rig.signals).toEqual(['backlinks', 'graph', 'tags']);
+ expect(await rig.index.getLocalTargetGeneration()).toBe(generation);
+ expect(await rig.index.getLocalTargetAssessments('wiki')).toEqual([]);
+ });
+
+ test('creating the target document heals the reference and re-signals', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+ await rig.index.recordDirectDocument('src', 'See [x](target).\n');
+ rig.signals.length = 0;
+
+ await rig.index.recordDirectDocument('target', '# Target\n');
+
+ expect((await rig.index.getLocalTargetAssessments('src'))[0]).toMatchObject({
+ status: 'exact',
+ });
+ expect(rig.signals).toContain('local-targets');
+ expect(await rig.index.getLocalTargetDocumentDependents('target')).toEqual(['src']);
+ });
+
+ test('ordinary-file target events heal and break references and signal only when a dependent moves', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+ await rig.index.recordDirectDocument('src', 'Download [pdf](assets/report.pdf).\n');
+ rig.signals.length = 0;
+
+ await rig.index.recordFileTargetUpsert('assets/report.pdf');
+ expect((await rig.index.getLocalTargetAssessments('src'))[0]).toMatchObject({
+ status: 'exact',
+ });
+ expect(rig.signals).toEqual(['local-targets']);
+
+ rig.signals.length = 0;
+ await rig.index.recordFileTargetDelete('assets/report.pdf');
+ expect((await rig.index.getLocalTargetAssessments('src'))[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ expect(rig.signals).toEqual(['local-targets']);
+
+ // An unreferenced file create moves nothing and stays silent.
+ rig.signals.length = 0;
+ await rig.index.recordFileTargetUpsert('assets/unreferenced.pdf');
+ expect(rig.signals).toEqual([]);
+ });
+
+ test('the dependency-only sweep repairs file inventory in both missed-watcher directions', async () => {
+ vi.useFakeTimers();
+ const inventory: WatcherLocalTargetInventory = {
+ documentTargets: ['source'],
+ fileTargets: ['assets/report.pdf'],
+ };
+ const recovered: Array<{ relativePath: string; exists: boolean }> = [];
+ const rig = createRig(
+ () => inventory,
+ (relativePath, exists) => recovered.push({ relativePath, exists }),
+ );
+ writeDoc(rig, 'source.md', 'Download [pdf](assets/report.pdf).\n');
+ writeDoc(rig, 'assets/report.pdf', '%PDF-1.4\n');
+ await settleStartup(rig);
+ expect((await rig.index.getLocalTargetAssessments('source'))[0]).toMatchObject({
+ status: 'exact',
+ });
+
+ unlinkSync(join(rig.contentDir, 'assets/report.pdf'));
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect((await rig.index.getLocalTargetAssessments('source'))[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ expect(rig.signals).toEqual(['local-targets', 'files']);
+ expect(recovered).toEqual([{ relativePath: 'assets/report.pdf', exists: false }]);
+
+ rig.signals.length = 0;
+ writeDoc(rig, 'assets/report.pdf', '%PDF-1.4 restored\n');
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect((await rig.index.getLocalTargetAssessments('source'))[0]).toMatchObject({
+ status: 'exact',
+ });
+ expect(rig.signals).toEqual(['local-targets', 'files']);
+ expect(recovered).toEqual([
+ { relativePath: 'assets/report.pdf', exists: false },
+ { relativePath: 'assets/report.pdf', exists: true },
+ ]);
+ });
+
+ test('a canonical document rename invalidates old aliases and admits new aliases', async () => {
+ let inventory: WatcherLocalTargetInventory = {
+ documentTargets: ['source', 'canonical-old', 'old-alias'],
+ fileTargets: [],
+ };
+ const rig = createRig(() => inventory);
+ writeDoc(rig, 'source.md', 'See [old](old-alias) and [new](new-alias).\n');
+ writeDoc(rig, 'canonical-old.md', '# Old\n');
+ await settleStartup(rig);
+ expect((await rig.index.getLocalTargetAssessments('source')).map((a) => a.status)).toEqual([
+ 'exact',
+ 'missing',
+ ]);
+
+ inventory = {
+ documentTargets: ['source', 'canonical-new', 'new-alias'],
+ fileTargets: [],
+ };
+ await rig.index.recordDirectRename('canonical-old', 'canonical-new', '# New\n');
+
+ expect((await rig.index.getLocalTargetAssessments('source')).map((a) => a.status)).toEqual([
+ 'missing',
+ 'exact',
+ ]);
+ });
+
+ test('an ordinary-file delete invalidates direct and directory-alias identities together', async () => {
+ let inventory: WatcherLocalTargetInventory = {
+ documentTargets: ['source'],
+ fileTargets: ['canonical/data.csv', 'direct.csv', 'folder-alias/data.csv'],
+ };
+ const rig = createRig(() => inventory);
+ writeDoc(
+ rig,
+ 'source.md',
+ '[canonical](canonical/data.csv) [direct](direct.csv) [folder](folder-alias/data.csv)\n',
+ );
+ await settleStartup(rig);
+ expect(
+ (await rig.index.getLocalTargetAssessments('source')).every((a) => a.status === 'exact'),
+ ).toBe(true);
+
+ inventory = { documentTargets: ['source'], fileTargets: [] };
+ await rig.index.recordFileTargetDelete('canonical/data.csv');
+
+ expect((await rig.index.getLocalTargetAssessments('source')).map((a) => a.status)).toEqual([
+ 'missing',
+ 'missing',
+ 'missing',
+ ]);
+ });
+
+ test('a direct batch coalesces high-fanout source assessments into one local-targets signal', async () => {
+ const rig = createRig();
+ await settleStartup(rig);
+
+ await rig.index.recordDirectMutations(
+ Array.from({ length: 12 }, (_, i) => ({
+ kind: 'upsert' as const,
+ documentName: `dep-${i}`,
+ markdown: 'Download [pdf](assets/shared.pdf).\n',
+ })),
+ );
+
+ expect(rig.signals.filter((channel) => channel === 'local-targets')).toHaveLength(1);
+ // One file create heals every dependent in the batch.
+ expect(await rig.index.getLocalTargetFileDependents('assets/shared.pdf')).toHaveLength(12);
+ expect(await rig.index.recordFileTargetUpsert('assets/shared.pdf')).toBeUndefined();
+ for (let i = 0; i < 12; i++) {
+ expect((await rig.index.getLocalTargetAssessments(`dep-${i}`))[0]).toMatchObject({
+ status: 'exact',
+ });
+ }
+ });
+
+ test('local-target queries wait for post-watcher settlement rather than return a falsely clean result', async () => {
+ const rig = createRig();
+ writeDoc(rig, 'src.md', 'See [x](target).\n');
+ const startup = rig.index.beginStartup('main');
+
+ const pending = rig.index.getLocalTargetAssessments('src');
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+
+ await startup.backlinksReady;
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ await rig.index.settleStartupAfterWatcherSeed();
+ const assessments = await pending;
+ expect(settled).toBe(true);
+ // Seeded from disk: `target` does not exist, so the reference is missing, not absent.
+ expect(assessments[0]).toMatchObject({ resolvedTarget: 'target', status: 'missing' });
+ });
+
+ test('local-target queries fail closed when the startup rebuild fails', async () => {
+ const rig = createRig();
+ writeDoc(rig, 'src.md', 'See [x](target).\n');
+ vi.spyOn(LocalTargetIndex.prototype, 'rebuildFromDisk').mockRejectedValueOnce(
+ new Error('forced local-target rebuild failure'),
+ );
+
+ const startup = rig.index.beginStartup('main');
+ await startup.backlinksReady;
+ await rig.index.settleStartupAfterWatcherSeed();
+
+ await expect(rig.index.getIndexedDocNames()).resolves.toContain('src');
+ await expect(rig.index.getLocalTargetAssessments('src')).rejects.toThrow(
+ 'Local-target index is not ready',
+ );
+ await expect(rig.index.getLocalTargetAssessmentsForSources()).rejects.toThrow(
+ 'Local-target index is not ready',
+ );
+ });
+
+ test('a transient startup rebuild failure recovers on the scheduled retry', async () => {
+ vi.useFakeTimers();
+ const rig = createRig();
+ writeDoc(rig, 'src.md', 'See [x](target).\n');
+ vi.spyOn(LocalTargetIndex.prototype, 'rebuildFromDisk').mockRejectedValueOnce(
+ new Error('transient rebuild failure'),
+ );
+
+ const startup = rig.index.beginStartup('main');
+ await startup.backlinksReady;
+ await rig.index.settleStartupAfterWatcherSeed();
+ await expect(rig.index.getLocalTargetAssessments('src')).rejects.toThrow(
+ 'Local-target index is not ready',
+ );
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(rig.index.getLocalTargetAssessments('src')).resolves.toEqual([
+ expect.objectContaining({ resolvedTarget: 'target', status: 'missing' }),
+ ]);
+ expect(rig.signals).toContain('local-targets');
+ });
+
+ test('a branch switch reassesses against the new branch inventory', async () => {
+ const rig = createRig();
+ writeDoc(rig, 'src.md', 'See [x](target).\n');
+ writeDoc(rig, 'target.md', '# Target\n');
+ await settleStartup(rig);
+ expect((await rig.index.getLocalTargetAssessments('src'))[0]).toMatchObject({
+ status: 'exact',
+ });
+
+ // The new branch no longer has the target on disk.
+ unlinkSync(join(rig.contentDir, 'target.md'));
+ const transition = await rig.index.beginBranchSwitch('feature');
+ await rig.index.settleBranchFromDisk(transition);
+
+ expect((await rig.index.getLocalTargetAssessments('src'))[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-doc',
+ });
+ });
+});
diff --git a/packages/server/src/derived-document-index.ts b/packages/server/src/derived-document-index.ts
index 6955b535c..fceea8685 100644
--- a/packages/server/src/derived-document-index.ts
+++ b/packages/server/src/derived-document-index.ts
@@ -10,16 +10,28 @@ import {
import { isLinkIndexExcludedDoc, isManagedArtifactDoc } from './cc1-broadcast.ts';
import type { ContentFilter } from './content-filter.ts';
import { docNameToRelativePath } from './doc-extensions.ts';
+import { recordIndexGenerationLag } from './index-telemetry.ts';
+import type { LocalTargetAssessment } from './local-target-assessment.ts';
+import {
+ LocalTargetIndex,
+ type LocalTargetIndexStats,
+ type LocalTargetRebuildInventory,
+ type LocalTargetSourceAssessments,
+} from './local-target-index.ts';
+import type { WatcherLocalTargetInventory } from './local-target-inventory.ts';
import { getLogger } from './logger.ts';
import { TagIndex, type TagSummaryEntry } from './tag-index.ts';
const log = getLogger('derived-document-index');
const DERIVED_INDEX_SAVE_DEBOUNCE_MS = 2000;
+const LOCAL_TARGET_REBUILD_RETRY_BASE_MS = 1000;
+const LOCAL_TARGET_REBUILD_RETRY_MAX_MS = 30_000;
+const LOCAL_TARGET_FILE_EXISTENCE_SWEEP_MS = 5000;
export type DerivedDocumentRelationChannel = Extract<
DerivedViewChannel,
- 'backlinks' | 'graph' | 'tags'
+ 'files' | 'backlinks' | 'graph' | 'tags' | 'local-targets'
>;
type ForwardLinkEntry = ReturnType<BacklinkIndex['getForwardLinkEntries']>[number];
@@ -95,6 +107,17 @@ export interface DerivedDocumentIndexApiPort {
admittedDocuments: Iterable<string>,
sourceDocumentNames?: readonly string[],
): Promise<DeadLinkEntry[]>;
+ /**
+ * Assessed local-target occurrences per source, optionally scoped to a source
+ * set — the project/folder-scope enumeration the links validator projects into
+ * the unified validation plane. Exposed on the API port (a query, not a raw
+ * index handle) so the validator reads assessment truth without owning the index.
+ */
+ getLocalTargetAssessmentsForSources(
+ sourceDocumentNames?: readonly string[],
+ ): Promise<LocalTargetSourceAssessments[]>;
+ /** Synchronous equality token for request coalescing/supersession. */
+ readLocalTargetGeneration?(): string | number;
getIndexedDocNames(): Promise<string[]>;
getAllTags(): Promise<TagSummaryEntry[]>;
getDocsForTagWithMatches(tag: string): Promise<TagDocMatch[]>;
@@ -106,6 +129,9 @@ export interface DerivedDocumentIndexOptions {
contentFilter: ContentFilter;
getGlobalSkillRoots: () => string[];
signalChannel: (channel: DerivedDocumentRelationChannel) => void;
+ /** Late-bound watcher inventory. Null means unavailable, not authoritatively empty. */
+ getLocalTargetInventory?: () => WatcherLocalTargetInventory | null;
+ onRecoveredFileTarget?: (relativePath: string, exists: boolean) => void;
}
interface Deferred {
@@ -136,6 +162,17 @@ export function isDerivedDocumentIndexClosedError(err: unknown): boolean {
return err instanceof DerivedDocumentIndexClosedError;
}
+class LocalTargetIndexNotReadyError extends Error {
+ constructor() {
+ super('Local-target index is not ready');
+ this.name = 'LocalTargetIndexNotReadyError';
+ }
+}
+
+export function isLocalTargetIndexNotReadyError(err: unknown): boolean {
+ return err instanceof LocalTargetIndexNotReadyError;
+}
+
export class DerivedDocumentIndex
implements
DerivedDocumentIndexApiPort,
@@ -146,18 +183,35 @@ export class DerivedDocumentIndex
private readonly backlinkIndex: BacklinkIndex;
private readonly tagIndex: TagIndex;
+ private readonly localTargetIndex: LocalTargetIndex;
private readonly contentFilter: ContentFilter;
private readonly getGlobalSkillRoots: () => string[];
+ private readonly getLocalTargetInventory: () => WatcherLocalTargetInventory | null;
private readonly signalChannel: (channel: DerivedDocumentRelationChannel) => void;
+ private readonly onRecoveredFileTarget?: (relativePath: string, exists: boolean) => void;
private readonly startupAdmission = createDeferred();
private readonly readyBarrier = createDeferred();
private tail: Promise<void> = Promise.resolve();
private saveTimer: ReturnType<typeof setTimeout> | null = null;
+ private localTargetRebuildRetryTimer: ReturnType<typeof setTimeout> | null = null;
+ private readonly localTargetFileExistenceTimer: ReturnType<typeof setInterval>;
+ private localTargetRebuildRetryAttempt = 0;
+ /** Identity of the watcher `fileTargets` array the graph oracle was built from. */
+ private graphFileTargetsSource: readonly string[] | null = null;
+ private graphFileTargets: Set<string> | null = null;
+ /** Branch the startup graph pass ran against, for the file-inventory reconcile. */
+ private startupBranch: string | null = null;
+ /**
+ * Whether any graph extraction ran while the watcher inventory was still
+ * unavailable, and therefore read every extension-less href as a document.
+ */
+ private graphBuiltWithoutFileOracle = false;
private saveTagsOnNextDebounce = false;
private branchTransition: BranchTransition | null = null;
private startupBegun = false;
private startupSettled = false;
private liveUpdateToken = 0;
+ private lastSignaledLocalTargetGeneration = 0;
private closed = false;
private closePromise: Promise<void> | null = null;
@@ -166,19 +220,48 @@ export class DerivedDocumentIndex
projectDir: options.projectDir,
contentDir: options.contentDir,
contentFilter: options.contentFilter,
+ // Sourced from the WATCHER inventory, not from `localTargetIndex`. The
+ // local-target rebuild consumes `backlinkIndex.getIndexedDocNames()`, so
+ // taking the oracle from that index would make the two indexes mutually
+ // dependent and the graph would build against an empty file set. The
+ // watcher is the actual source of truth for which files exist, and both
+ // indexes read it, so there is no cycle and no ordering to get wrong.
+ getFileOracle: () => this.graphFileOracle(),
});
this.tagIndex = new TagIndex({
projectDir: options.projectDir,
contentDir: options.contentDir,
contentFilter: options.contentFilter,
});
+ this.localTargetIndex = new LocalTargetIndex({
+ contentDir: options.contentDir,
+ contentFilter: options.contentFilter,
+ });
this.contentFilter = options.contentFilter;
this.getGlobalSkillRoots = options.getGlobalSkillRoots;
+ this.getLocalTargetInventory =
+ options.getLocalTargetInventory ?? (() => ({ documentTargets: [], fileTargets: [] }));
this.signalChannel = options.signalChannel;
+ this.onRecoveredFileTarget = options.onRecoveredFileTarget;
this.testOnly = {
resetDocumentForTest: (documentName) => this.resetDocumentForTest(documentName),
rescanBacklinksForTest: () => this.rescanBacklinksForTest(),
};
+ this.localTargetFileExistenceTimer = setInterval(() => {
+ if (this.closed || !this.startupSettled || !this.localTargetIndex.isReady()) return;
+ void this.runCommand(async () => {
+ const affected = await this.localTargetIndex.reconcileDependentFileTargetsFromDisk(
+ this.onRecoveredFileTarget,
+ );
+ this.maybeSignalLocalTargets();
+ if (affected > 0) this.signalChannel('files');
+ }).catch((err) => {
+ if (!this.closed) {
+ log.warn({ err }, '[local-target] dependent file-existence sweep failed');
+ }
+ });
+ }, LOCAL_TARGET_FILE_EXISTENCE_SWEEP_MS);
+ this.localTargetFileExistenceTimer.unref?.();
}
beginStartup(branch: string): { backlinksReady: Promise<DerivedIndexStartupBacklinksResult> } {
@@ -187,6 +270,7 @@ export class DerivedDocumentIndex
throw new Error('Derived document index startup has already begun');
}
this.startupBegun = true;
+ this.startupBranch = branch;
this.backlinkIndex.switchBranch(branch);
const backlinksReady = this.initializeBacklinks(branch);
@@ -208,20 +292,28 @@ export class DerivedDocumentIndex
try {
return await this.enqueueInternal(async () => {
+ let tagIndexDegraded = false;
try {
const diff = await this.tagIndex.reconcileWithDisk();
if (diff.added > 0 || diff.updated > 0 || diff.deleted > 0) {
log.info(diff, '[tag-index] startup reconcile: offline changes applied');
}
await this.saveTagsLogOnly('startup');
- return { tagIndexDegraded: false };
} catch (err) {
log.error(
{ err },
'[tag-index] startup reconcile failed; tag index updates incrementally via watcher events',
);
- return { tagIndexDegraded: true };
+ tagIndexDegraded = true;
+ }
+ if (await this.rebuildLocalTargets('startup')) this.syncLocalTargetBaseline();
+ // The startup graph pass ran before the watcher existed, so it had no
+ // way to tell an extension-less file target from a document. The
+ // inventory is available now.
+ if (this.startupBranch !== null) {
+ await this.reconcileGraphWithFileInventory(this.startupBranch);
}
+ return { tagIndexDegraded };
});
} finally {
this.readyBarrier.resolve();
@@ -293,6 +385,7 @@ export class DerivedDocumentIndex
await this.tagIndex.init();
}
await this.saveTagsLogOnly('branch-switch');
+ if (await this.rebuildLocalTargets('branch-switch')) this.syncLocalTargetBaseline();
if (globalIngestFailed) throw globalIngestFailure;
});
} finally {
@@ -330,6 +423,7 @@ export class DerivedDocumentIndex
recordDiskUpsert(documentName: string, markdown: string): Promise<void> {
return this.runCommand(async () => {
this.updateBoth(documentName, markdown);
+ this.reconcileLocalTargetInventory();
this.scheduleSave();
this.signalAllRelations();
});
@@ -338,6 +432,7 @@ export class DerivedDocumentIndex
recordDiskDelete(documentName: string): Promise<void> {
return this.runCommand(async () => {
this.deleteBoth(documentName);
+ this.reconcileLocalTargetInventory();
this.scheduleSave();
this.signalAllRelations();
});
@@ -350,11 +445,40 @@ export class DerivedDocumentIndex
): Promise<void> {
return this.runCommand(async () => {
this.renameBoth(oldDocumentName, newDocumentName, markdown);
+ this.reconcileLocalTargetInventory();
this.scheduleSave();
this.signalAllRelations();
});
}
+ /**
+ * An ordinary (non-markdown) file target appeared or its content changed.
+ * Only its reverse-dependent sources reassess, and the local-targets signal
+ * fires only if one actually healed — an unreferenced file create is silent.
+ * Ordinary-file renames arrive as delete + upsert (the watcher has no rename
+ * variant for them), settling to the union of both identities' dependents.
+ */
+ recordFileTargetUpsert(relativePath: string): Promise<void> {
+ return this.runCommand(async () => {
+ const inventory = this.reconcileLocalTargetInventory();
+ if (inventory === null || !inventory.fileTargets.includes(relativePath)) {
+ this.localTargetIndex.setFileTarget(relativePath, true);
+ }
+ this.maybeSignalLocalTargets();
+ });
+ }
+
+ /** An ordinary file target was removed; its reverse dependents break. */
+ recordFileTargetDelete(relativePath: string): Promise<void> {
+ return this.runCommand(async () => {
+ const inventory = this.reconcileLocalTargetInventory();
+ if (inventory === null || inventory.fileTargets.includes(relativePath)) {
+ this.localTargetIndex.setFileTarget(relativePath, false);
+ }
+ this.maybeSignalLocalTargets();
+ });
+ }
+
recordDirectDocument(documentName: string, markdown: string): Promise<void> {
return this.recordDirectMutations([{ kind: 'upsert', documentName, markdown }]);
}
@@ -402,6 +526,7 @@ export class DerivedDocumentIndex
}
if (tagsChanged) {
+ this.reconcileLocalTargetInventory();
await this.saveBothLogOnly('direct-batch');
this.signalAllRelations();
} else {
@@ -414,6 +539,7 @@ export class DerivedDocumentIndex
refreshGlobalSkillNodes(): Promise<void> {
return this.runCommand(async () => {
await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots());
+ this.reconcileLocalTargetInventory();
this.signalBacklinks();
});
}
@@ -431,7 +557,10 @@ export class DerivedDocumentIndex
globalIngestFailure = err;
}
await this.tagIndex.init();
+ await this.rebuildLocalTargets('content-filter');
await this.saveBothLogOnly('content-filter', branch);
+ // Content scope changed wholesale; signalAllRelations() -> maybeSignalLocalTargets
+ // emits `local-targets` off the rebuild's generation jump (no baseline sync).
this.signalAllRelations();
if (globalIngestFailed) throw globalIngestFailure;
});
@@ -503,6 +632,57 @@ export class DerivedDocumentIndex
return this.runQuery(() => this.tagIndex.getDocsForTagWithMatches(tag));
}
+ /**
+ * Assessed local-target occurrences for one source. Gated behind the ready
+ * barrier like every query, so it never returns a falsely clean empty result
+ * against a half-seeded inventory. The occurrence range travels on each
+ * assessment for positioned diagnostics.
+ */
+ getLocalTargetAssessments(documentName: string): Promise<readonly LocalTargetAssessment[]> {
+ return this.runLocalTargetQuery(() => this.localTargetIndex.getAssessments(documentName));
+ }
+
+ /**
+ * Assessed local-target occurrences per source (all sources, or a scoped set),
+ * for project/folder-scope validation enumeration. Gated behind the ready
+ * barrier like every query, so it never publishes a falsely clean empty result
+ * against a half-seeded inventory.
+ */
+ getLocalTargetAssessmentsForSources(
+ sourceDocumentNames?: readonly string[],
+ ): Promise<LocalTargetSourceAssessments[]> {
+ return this.runLocalTargetQuery(() =>
+ this.localTargetIndex.getAssessmentsForSources(sourceDocumentNames),
+ );
+ }
+
+ /** Monotonic generation of the local-target index — consumers diff it to detect staleness. */
+ getLocalTargetGeneration(): Promise<number> {
+ return this.runLocalTargetQuery(() => this.localTargetIndex.generation);
+ }
+
+ /** Read-only freshness token; unlike assessment queries it never publishes index contents. */
+ readLocalTargetGeneration(): string {
+ return this.localTargetIndex.freshnessToken;
+ }
+
+ /** Bounded-cardinality counts for the local-target index (no paths). */
+ getLocalTargetStats(): Promise<LocalTargetIndexStats> {
+ return this.runLocalTargetQuery(() => this.localTargetIndex.getStats());
+ }
+
+ /** Sources whose local-target assessment depends on a document identity's existence. */
+ getLocalTargetDocumentDependents(documentName: string): Promise<string[]> {
+ return this.runLocalTargetQuery(() =>
+ this.localTargetIndex.getDocumentDependents(documentName),
+ );
+ }
+
+ /** Sources whose local-target assessment depends on an ordinary-file identity's existence. */
+ getLocalTargetFileDependents(relativePath: string): Promise<string[]> {
+ return this.runLocalTargetQuery(() => this.localTargetIndex.getFileDependents(relativePath));
+ }
+
close(): Promise<void> {
if (this.closePromise) return this.closePromise;
const pendingSave = this.cancelScheduledSave();
@@ -510,6 +690,9 @@ export class DerivedDocumentIndex
void this.enqueueInternal(() => this.saveScheduledCache(pendingSave, 'close-flush'));
}
this.closed = true;
+ clearInterval(this.localTargetFileExistenceTimer);
+ this.cancelLocalTargetRebuildRetry();
+ this.localTargetIndex.close();
this.startupAdmission.resolve();
this.readyBarrier.resolve();
this.releaseBranchTransition(this.branchTransition);
@@ -535,6 +718,7 @@ export class DerivedDocumentIndex
const branch = this.backlinkIndex.getActiveBranch();
await this.backlinkIndex.rebuildFromDisk(branch);
await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(), branch);
+ this.reconcileLocalTargetInventory();
await this.saveBacklinksLogOnly('test-rescan', branch);
this.signalBacklinks();
});
@@ -543,6 +727,11 @@ export class DerivedDocumentIndex
private async initializeBacklinks(branch: string): Promise<DerivedIndexStartupBacklinksResult> {
try {
let deletedDocNames: readonly string[] = [];
+ // Startup graph extraction runs before the watcher inventory exists.
+ // Even a warm cache must be checked after watcher seed: ordinary files
+ // can appear or disappear while the app is offline without changing a
+ // Markdown mtime, which can change an extension-less target's identity.
+ this.graphFileOracle();
if (await this.backlinkIndex.loadFromDisk(branch)) {
const diff = await this.backlinkIndex.reconcileWithDisk(branch);
deletedDocNames = diff.deletedDocNames;
@@ -594,25 +783,31 @@ export class DerivedDocumentIndex
private updateBacklinks(documentName: string, markdown: string): void {
if (this.isAdmitted(documentName)) {
this.backlinkIndex.updateDocumentFromMarkdown(documentName, markdown);
+ this.localTargetIndex.setSource(documentName, markdown);
} else {
this.backlinkIndex.deleteDocument(documentName);
+ this.localTargetIndex.removeSource(documentName);
}
}
private deleteBoth(documentName: string): void {
this.backlinkIndex.deleteDocument(documentName);
this.tagIndex.deleteDocument(documentName);
+ this.localTargetIndex.removeSource(documentName);
}
private renameBoth(oldDocumentName: string, newDocumentName: string, markdown: string): void {
if (this.isAdmitted(newDocumentName)) {
this.backlinkIndex.renameDocument(oldDocumentName, newDocumentName, markdown);
this.tagIndex.renameDocument(oldDocumentName, newDocumentName, markdown);
+ this.localTargetIndex.renameSource(oldDocumentName, newDocumentName, markdown);
} else {
this.backlinkIndex.deleteDocument(oldDocumentName);
this.backlinkIndex.deleteDocument(newDocumentName);
this.tagIndex.deleteDocument(oldDocumentName);
this.tagIndex.deleteDocument(newDocumentName);
+ this.localTargetIndex.removeSource(oldDocumentName);
+ this.localTargetIndex.removeSource(newDocumentName);
}
}
@@ -625,6 +820,7 @@ export class DerivedDocumentIndex
private signalBacklinks(): void {
this.signalChannel('backlinks');
this.signalChannel('graph');
+ this.maybeSignalLocalTargets();
}
private signalAllRelations(): void {
@@ -632,6 +828,159 @@ export class DerivedDocumentIndex
this.signalChannel('tags');
}
+ /**
+ * Emit `local-targets` only when an assessment actually moved since the last
+ * emission — a wiki-only or occurrence-free edit leaves the generation
+ * untouched and stays silent, so document/backlink surfaces don't refetch the
+ * local-target projection for nothing. The baseline is re-synced after the
+ * startup and branch reconciles (whose wholesale generation jump is covered by
+ * mount-driven load and the `branch-switched` channel), so it is not mistaken
+ * for a delta on the next ordinary command.
+ */
+ private maybeSignalLocalTargets(): void {
+ const generation = this.localTargetIndex.generation;
+ const lag = generation - this.lastSignaledLocalTargetGeneration;
+ if (lag === 0) return;
+ recordIndexGenerationLag('local-target', 'signal', lag);
+ this.lastSignaledLocalTargetGeneration = generation;
+ this.signalChannel('local-targets');
+ }
+
+ /**
+ * File-existence oracle handed to the document graph, memoized against the
+ * watcher's own `fileTargets` array so a whole-document link scan does not
+ * rebuild the set per link. The watcher hands back a fresh array whenever the
+ * inventory changes, so identity is a sound cache key.
+ */
+ private graphFileOracle(): { hasFile(path: string): boolean } | undefined {
+ const inventory = this.getLocalTargetInventory();
+ if (!inventory) {
+ // The watcher is not up during the startup graph build, so this is the
+ // normal first-boot path, not an error. Remember it: every extension-less
+ // href in that pass was read as a document, and the graph has to be
+ // re-derived once the inventory exists or `assets/NOTICE` keeps its
+ // dead-document edge until the file happens to change.
+ this.graphBuiltWithoutFileOracle = true;
+ return undefined;
+ }
+ if (this.graphFileTargetsSource !== inventory.fileTargets) {
+ this.graphFileTargetsSource = inventory.fileTargets;
+ this.graphFileTargets = new Set(inventory.fileTargets);
+ }
+ const files = this.graphFileTargets;
+ return files ? { hasFile: (path) => files.has(path) } : undefined;
+ }
+
+ /**
+ * Re-derive the graph once the file inventory first becomes available, so the
+ * document/file disambiguation the startup pass could not make is applied.
+ *
+ * Bounded: the flag clears on the first successful pass, so this is at most
+ * one extra rebuild per boot, and only when a graph pass actually ran without
+ * the oracle.
+ */
+ private async reconcileGraphWithFileInventory(branch: string): Promise<void> {
+ if (!this.graphBuiltWithoutFileOracle) return;
+ if (!this.graphFileOracle()) return;
+ // Cleared before the rebuild rather than after, so the rebuild itself can
+ // legitimately re-set it: the oracle is polled per extraction, and a pass
+ // that loses the inventory mid-rebuild has again built without it.
+ this.graphBuiltWithoutFileOracle = false;
+ try {
+ await this.backlinkIndex.rebuildFromDisk(branch);
+ await this.saveBacklinksLogOnly('file-inventory-reconcile', branch);
+ this.signalChannel('backlinks');
+ this.signalChannel('graph');
+ } catch (err) {
+ // The reconcile did not land, so the flag must keep saying the graph was
+ // built without the oracle. Nothing retries it this boot — the one call
+ // site runs once, at startup settlement — and the audit plane still
+ // suppresses a dead-link claim the canonical classifier contradicts.
+ this.graphBuiltWithoutFileOracle = true;
+ log.warn(
+ { err, branch },
+ '[backlinks] file-inventory reconciliation failed; graph retains its startup extraction',
+ );
+ }
+ }
+
+ private async rebuildLocalTargets(reason: string): Promise<boolean> {
+ try {
+ const watcherInventory = this.getLocalTargetInventory();
+ if (watcherInventory === null) {
+ this.localTargetIndex.markUnavailable();
+ log.warn(
+ { reason },
+ '[local-target] watcher inventory unavailable; index remains not ready',
+ );
+ return false;
+ }
+ const inventory: LocalTargetRebuildInventory = {
+ documentTargets: new Set([
+ ...this.backlinkIndex.getIndexedDocNames(),
+ ...watcherInventory.documentTargets,
+ ]),
+ fileTargets: watcherInventory.fileTargets,
+ };
+ await this.localTargetIndex.rebuildFromDisk(inventory);
+ this.localTargetRebuildRetryAttempt = 0;
+ this.cancelLocalTargetRebuildRetry();
+ return true;
+ } catch (err) {
+ log.warn(
+ { err, reason },
+ '[local-target] rebuild failed; retaining the last complete snapshot and scheduling recovery',
+ );
+ this.scheduleLocalTargetRebuildRetry(reason);
+ return false;
+ }
+ }
+
+ private reconcileLocalTargetInventory(): WatcherLocalTargetInventory | null {
+ const watcherInventory = this.getLocalTargetInventory();
+ if (watcherInventory === null) {
+ this.localTargetIndex.markUnavailable();
+ return null;
+ }
+ this.localTargetIndex.reconcileDocumentTargets(
+ new Set([...this.backlinkIndex.getIndexedDocNames(), ...watcherInventory.documentTargets]),
+ );
+ this.localTargetIndex.reconcileFileTargets(watcherInventory.fileTargets);
+ return watcherInventory;
+ }
+
+ private syncLocalTargetBaseline(): void {
+ const generation = this.localTargetIndex.generation;
+ const lag = generation - this.lastSignaledLocalTargetGeneration;
+ if (lag > 0) recordIndexGenerationLag('local-target', 'baseline', lag);
+ this.lastSignaledLocalTargetGeneration = generation;
+ }
+
+ private scheduleLocalTargetRebuildRetry(reason: string): void {
+ if (this.closed || this.localTargetRebuildRetryTimer !== null) return;
+ const delay = Math.min(
+ LOCAL_TARGET_REBUILD_RETRY_BASE_MS * 2 ** this.localTargetRebuildRetryAttempt,
+ LOCAL_TARGET_REBUILD_RETRY_MAX_MS,
+ );
+ this.localTargetRebuildRetryAttempt++;
+ this.localTargetRebuildRetryTimer = setTimeout(() => {
+ this.localTargetRebuildRetryTimer = null;
+ void this.runCommand(async () => {
+ if (await this.rebuildLocalTargets(`retry:${reason}`)) this.maybeSignalLocalTargets();
+ }).catch((err) => {
+ if (!this.closed) log.warn({ err, reason }, '[local-target] recovery enqueue failed');
+ });
+ }, delay);
+ this.localTargetRebuildRetryTimer.unref?.();
+ }
+
+ private cancelLocalTargetRebuildRetry(): void {
+ if (this.localTargetRebuildRetryTimer !== null) {
+ clearTimeout(this.localTargetRebuildRetryTimer);
+ this.localTargetRebuildRetryTimer = null;
+ }
+ }
+
private scheduleSave(includeTags = true): void {
const saveTags = this.saveTagsOnNextDebounce || includeTags;
this.cancelScheduledSave();
@@ -713,6 +1062,13 @@ export class DerivedDocumentIndex
return this.enqueueAfterBranchAdmission(query);
}
+ private runLocalTargetQuery<T>(query: () => Promise<T> | T): Promise<T> {
+ return this.runQuery(() => {
+ if (!this.localTargetIndex.isReady()) throw new LocalTargetIndexNotReadyError();
+ return query();
+ });
+ }
+
private async enqueueAfterBranchAdmission<T>(operation: () => Promise<T> | T): Promise<T> {
while (true) {
const transition = this.branchTransition;
diff --git a/packages/server/src/http/link-graph-routes.ts b/packages/server/src/http/link-graph-routes.ts
index b1d4e7c9b..bd38d871f 100644
--- a/packages/server/src/http/link-graph-routes.ts
+++ b/packages/server/src/http/link-graph-routes.ts
@@ -34,8 +34,10 @@ import {
type DerivedDocumentIndexApiPort,
type DerivedGraphNode,
isDerivedOrphanMode,
+ isLocalTargetIndexNotReadyError,
} from '../derived-document-index.ts';
import type { FileIndexEntry } from '../file-watcher.ts';
+import { toForwardLinkLocalTargets } from '../local-target-assessment.ts';
import type { FrontmatterMetadata } from '../page-identity.ts';
import { SuggestLinksTargetNotFoundError, suggestLinks } from '../suggest-links.ts';
import type { ApiRouteTable } from './api-pipeline.ts';
@@ -216,30 +218,42 @@ export function createLinkGraphRoutes(deps: LinkGraphRouteDeps): LinkGraphRoutes
return;
}
const admitted = await collectAdmittedDocNames();
+ const forwardLinks = (await derivedDocumentIndex.getForwardLinkEntries(docName)).map(
+ (entry) =>
+ entry.kind === 'doc'
+ ? {
+ kind: 'doc' as const,
+ docName: entry.target,
+ anchor: entry.anchor,
+ title: readPageTitleForLinkedDocName(entry.target, admitted),
+ snippet: entry.snippet,
+ }
+ : {
+ kind: 'external' as const,
+ url: entry.url,
+ title: entry.label ?? entry.url,
+ snippet: entry.snippet,
+ },
+ );
+ // Local file/image references ride an additive sibling collection sourced
+ // from the assessment index — never reclassified from the graph rows above,
+ // so document relationship semantics stay pure.
+ let localTargets: ReturnType<typeof toForwardLinkLocalTargets> | undefined;
+ try {
+ const localTargetSources = await derivedDocumentIndex.getLocalTargetAssessmentsForSources(
+ [docName],
+ );
+ localTargets = toForwardLinkLocalTargets(
+ localTargetSources.flatMap((entry) => entry.assessments),
+ );
+ } catch (error) {
+ if (!isLocalTargetIndexNotReadyError(error)) throw error;
+ }
successResponse(
res,
200,
ForwardLinksSuccessSchema,
- {
- docName,
- forwardLinks: (await derivedDocumentIndex.getForwardLinkEntries(docName)).map(
- (entry) =>
- entry.kind === 'doc'
- ? {
- kind: 'doc' as const,
- docName: entry.target,
- anchor: entry.anchor,
- title: readPageTitleForLinkedDocName(entry.target, admitted),
- snippet: entry.snippet,
- }
- : {
- kind: 'external' as const,
- url: entry.url,
- title: entry.label ?? entry.url,
- snippet: entry.snippet,
- },
- ),
- },
+ { docName, forwardLinks, ...(localTargets ? { localTargets } : {}) },
{ handler: 'forward-links' },
);
} catch (e) {
diff --git a/packages/server/src/index-telemetry.test.ts b/packages/server/src/index-telemetry.test.ts
index 04e531719..bd2c1a623 100644
--- a/packages/server/src/index-telemetry.test.ts
+++ b/packages/server/src/index-telemetry.test.ts
@@ -7,7 +7,12 @@ import {
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { __resetIndexTelemetryForTests, instrumentIndexRebuild } from './index-telemetry.ts';
+import {
+ __resetIndexTelemetryForTests,
+ instrumentIndexRebuild,
+ instrumentIndexUpdate,
+ recordIndexGenerationLag,
+} from './index-telemetry.ts';
let exporter: InMemorySpanExporter;
let provider: BasicTracerProvider;
@@ -81,3 +86,31 @@ describe('instrumentIndexRebuild', () => {
await expect(instrumentIndexRebuild('tag', 'reconcile', async () => 1)).resolves.toBe(1);
});
});
+
+describe('instrumentIndexUpdate', () => {
+ test('emits only bounded operation and numeric measurement attributes', () => {
+ const result = instrumentIndexUpdate(
+ 'local-target',
+ 'source',
+ () => ({ changed: true, occurrences: 4, affectedSources: 2 }),
+ (update) => ({
+ 'index.occurrences': update.occurrences,
+ 'index.affected_sources': update.affectedSources,
+ }),
+ );
+
+ expect(result.changed).toBe(true);
+ const span = requireSpan('ok.index.update');
+ expect(span.attributes).toEqual({
+ 'index.name': 'local-target',
+ 'index.mode': 'source',
+ 'index.occurrences': 4,
+ 'index.affected_sources': 2,
+ });
+ expect(Object.keys(span.attributes).some((key) => /path|href|content/.test(key))).toBe(false);
+ });
+
+ test('records generation lag only at a real publication boundary', () => {
+ expect(() => recordIndexGenerationLag('local-target', 'signal', 3)).not.toThrow();
+ });
+});
diff --git a/packages/server/src/index-telemetry.ts b/packages/server/src/index-telemetry.ts
index d8c8d801f..0e474b35b 100644
--- a/packages/server/src/index-telemetry.ts
+++ b/packages/server/src/index-telemetry.ts
@@ -8,19 +8,25 @@
* cardinality flat regardless of corpus size — NEVER add per-doc labels.
*/
import type { Attributes, Counter, Histogram } from '@opentelemetry/api';
-import { getMeter, withSpan } from './telemetry.ts';
+import { getMeter, withSpan, withSpanSync } from './telemetry.ts';
/** Bounded label set — extend only for a NEW derived index, never per-doc. */
-export type IndexName = 'backlink' | 'tag';
+export type IndexName = 'backlink' | 'tag' | 'local-target';
/** `full` = whole-corpus re-parse; `reconcile` = mtime-gated incremental pass. */
export type IndexRebuildMode = 'full' | 'reconcile';
+/** Incremental mutation class. Bounded: never derive this value from a path or event name. */
+export type IndexUpdateMode = 'source' | 'document-target' | 'file-target';
+
+/** Bounded publication path for generation-lag observations. */
+export type IndexPublicationMode = 'signal' | 'baseline';
+
let _rebuildCounter: Counter | null = null;
function rebuildCounter(): Counter {
_rebuildCounter ||= getMeter().createCounter('ok.index.rebuild_total', {
description:
- 'Count of derived-index rebuild passes. Bounded labels: index.name ∈ {backlink, tag}, index.mode ∈ {full, reconcile}.',
+ 'Count of derived-index rebuild passes. Bounded labels: index.name ∈ {backlink, tag, local-target}, index.mode ∈ {full, reconcile}.',
});
return _rebuildCounter;
}
@@ -35,6 +41,69 @@ function rebuildDurationHist(): Histogram {
return _rebuildDurationHist;
}
+let _updateCounter: Counter | null = null;
+function updateCounter(): Counter {
+ _updateCounter ||= getMeter().createCounter('ok.index.update_total', {
+ description:
+ 'Count of incremental derived-index updates. Bounded labels: index.name and index.mode.',
+ });
+ return _updateCounter;
+}
+
+let _updateDurationHist: Histogram | null = null;
+function updateDurationHist(): Histogram {
+ _updateDurationHist ||= getMeter().createHistogram('ok.index.update_duration_ms', {
+ description: 'Duration of incremental derived-index updates in milliseconds.',
+ unit: 'ms',
+ });
+ return _updateDurationHist;
+}
+
+let _occurrenceCountHist: Histogram | null = null;
+function occurrenceCountHist(): Histogram {
+ _occurrenceCountHist ||= getMeter().createHistogram('ok.index.occurrence_count', {
+ description: 'Local-target occurrences processed by an index operation.',
+ unit: '{occurrence}',
+ });
+ return _occurrenceCountHist;
+}
+
+let _affectedSourceCountHist: Histogram | null = null;
+function affectedSourceCountHist(): Histogram {
+ _affectedSourceCountHist ||= getMeter().createHistogram('ok.index.affected_source_count', {
+ description: 'Source documents whose assessment changed during an index operation.',
+ unit: '{source}',
+ });
+ return _affectedSourceCountHist;
+}
+
+let _generationLagHist: Histogram | null = null;
+function generationLagHist(): Histogram {
+ _generationLagHist ||= getMeter().createHistogram('ok.index.generation_lag', {
+ description: 'Index generations accumulated between consumer publications.',
+ unit: '{generation}',
+ });
+ return _generationLagHist;
+}
+
+function recordBoundedMeasurements(attrs: Attributes, labels: Attributes): void {
+ const occurrences = attrs['index.occurrences'];
+ if (typeof occurrences === 'number') occurrenceCountHist().record(occurrences, labels);
+ const affectedSources = attrs['index.affected_sources'];
+ if (typeof affectedSources === 'number') {
+ affectedSourceCountHist().record(affectedSources, labels);
+ }
+}
+
+/** Record real publication lag, never a per-operation placeholder. */
+export function recordIndexGenerationLag(
+ name: IndexName,
+ publication: IndexPublicationMode,
+ lag: number,
+): void {
+ generationLagHist().record(lag, { 'index.name': name, 'index.publication': publication });
+}
+
/**
* Run a rebuild/reconcile pass inside an `ok.index.rebuild` span and record
* the counter + duration histogram. The duration lands even when `fn` throws
@@ -58,7 +127,11 @@ export async function instrumentIndexRebuild<T>(
const start = performance.now();
try {
const result = await fn();
- if (resultAttrs) span.setAttributes(resultAttrs(result));
+ if (resultAttrs) {
+ const attrs = resultAttrs(result);
+ span.setAttributes(attrs);
+ recordBoundedMeasurements(attrs, { 'index.name': name, 'index.mode': mode });
+ }
return result;
} finally {
const attrs = { 'index.name': name, 'index.mode': mode };
@@ -69,6 +142,32 @@ export async function instrumentIndexRebuild<T>(
);
}
+/**
+ * Instrument one synchronous incremental update. Result attributes are numeric,
+ * bounded measurements only; callers must never attach paths, hrefs, or content.
+ */
+export function instrumentIndexUpdate<T>(
+ name: IndexName,
+ mode: IndexUpdateMode,
+ fn: () => T,
+ resultAttrs: (result: T) => Attributes,
+): T {
+ const labels = { 'index.name': name, 'index.mode': mode };
+ return withSpanSync('ok.index.update', { attributes: labels }, (span) => {
+ const start = performance.now();
+ try {
+ const result = fn();
+ const attrs = resultAttrs(result);
+ span.setAttributes(attrs);
+ recordBoundedMeasurements(attrs, labels);
+ return result;
+ } finally {
+ updateCounter().add(1, labels);
+ updateDurationHist().record(performance.now() - start, labels);
+ }
+ });
+}
+
/**
* Drop the cached lazy-init instruments so the next call rebinds against the
* currently-registered global MeterProvider. Test-only — production code
@@ -78,4 +177,9 @@ export async function instrumentIndexRebuild<T>(
export function __resetIndexTelemetryForTests(): void {
_rebuildCounter = null;
_rebuildDurationHist = null;
+ _updateCounter = null;
+ _updateDurationHist = null;
+ _occurrenceCountHist = null;
+ _affectedSourceCountHist = null;
+ _generationLagHist = null;
}
diff --git a/packages/server/src/link-classification-uniformity.test.ts b/packages/server/src/link-classification-uniformity.test.ts
new file mode 100644
index 000000000..a97e8d074
--- /dev/null
+++ b/packages/server/src/link-classification-uniformity.test.ts
@@ -0,0 +1,297 @@
+/**
+ * Cross-plane link-classification uniformity.
+ *
+ * Every authored link occurrence must have exactly ONE canonical
+ * classification — `{targetKind, resolvedTarget, status, reason,
+ * resolutionMethod}` — computed once against the complete inventory
+ * (documents AND files) over the complete form set (wiki, inline, reference,
+ * html-img), and consumed verbatim by every reporting surface.
+ *
+ * Each classification plane already has its own unit tests and each one passes.
+ * That is precisely the gap this file closes: the planes are only ever exercised
+ * in isolation, so a disagreement between them is invisible until they are
+ * COMPARED over the same document and the same inventory. `link-syntax.ts` cites
+ * precedent #56 and is pinned by divergence tests for *recognition*; this is the
+ * equivalent pin for *classification*.
+ *
+ * The two planes under comparison:
+ *
+ * - **A — document graph** (`backlink-index.ts`): feeds Links ▸ Outgoing and the
+ * Problems rows that carry `linkTarget`.
+ * - **B — local-target assessment** (`local-target-assessment.ts`): feeds
+ * Links ▸ Local files and the Problems rows that carry `localTarget`.
+ *
+ * The inventory below is a boundary fake, not a mock of either plane: both
+ * planes run their real production classifiers over it, and the assertions check
+ * what those classifiers conclude. A fake reporting the wrong membership would
+ * fail these tests rather than hide a bug.
+ */
+
+import { describe, expect, test } from 'vitest';
+import {
+ extractMarkdownLinksFromMarkdown,
+ extractWikiLinksFromMarkdown,
+} from './backlink-index.ts';
+import {
+ assessLocalTargets,
+ createTolerantDocumentResolver,
+ type LocalTargetAssessment,
+ type LocalTargetInventory,
+} from './local-target-assessment.ts';
+import {
+ extractLocalTargetOccurrences,
+ type LocalTargetOccurrence,
+} from './local-target-occurrences.ts';
+
+const SOURCE_DOC = 'all-link-types';
+
+/**
+ * Faithful reduction of the `all-link-types.md` QA matrix, carrying one row per
+ * in-scope failing cluster plus the passing rows that make each disagreement
+ * legible. Deliberately EXCLUDED, because they are not classification
+ * disagreements and are fixed separately:
+ * - external schemes (https / mailto / tel / protocol-relative), which every
+ * plane already treats identically as external;
+ * - the wiki escaped-pipe (`\|`) trailing-backslash defect.
+ */
+const MATRIX = [
+ '---',
+ 'title: All link types matrix',
+ 'ignored_example: "[Ignored frontmatter](assets/frontmatter-missing.txt)"',
+ '---',
+ '',
+ '# Matrix',
+ '',
+ '## Documents (control rows — these already agree)',
+ '',
+ '- [Relative Markdown document](targets/existing-page.md)',
+ '- [Missing Markdown document](targets/missing-markdown.md)',
+ '',
+ '## Cluster 1 — wiki forms',
+ '',
+ '- [[targets/existing-page]]',
+ '- [[targets/missing-wiki]]',
+ '- ![[targets/missing-embed]]',
+ '',
+ '## Cluster 2 — reference-style links',
+ '',
+ '- [Missing reference document][missing-doc-ref]',
+ '- [Tolerant case fallback][case-doc]',
+ '- [Existing reference PDF][valid-pdf]',
+ '- [Missing full reference][missing-spec]',
+ '- [missing-spec][]',
+ '- [missing-spec]',
+ '',
+ '## Cluster 3 — extensionless ordinary file',
+ '',
+ '- [Extensionless ordinary file](assets/NOTICE)',
+ '- ![Existing extensionless image target](assets/NOTICE)',
+ '',
+ '## Files (control rows — these already agree)',
+ '',
+ '- [Existing text file](assets/existing.txt)',
+ '- [Missing JSON file](assets/missing.json)',
+ '',
+ '## Cluster 4 — non-rendering contexts (must be inert everywhere)',
+ '',
+ 'Invisible by design <!-- [HTML comment](assets/comment-missing.txt) -->',
+ '',
+ '<pre>[Raw pre block](assets/pre-missing.txt)</pre>',
+ '',
+ '```markdown',
+ '[Fenced code](assets/fenced-missing.txt)',
+ '[[targets/fenced-wiki-missing]]',
+ '```',
+ '',
+ '[missing-doc-ref]: targets/missing-reference',
+ '[case-doc]: targets/case-sensitive',
+ '[valid-pdf]: assets/manual.pdf',
+ '[missing-spec]: assets/missing-spec.pdf',
+ '',
+].join('\n');
+
+/** Documents the fixture project admits. */
+const DOCUMENTS = ['all-link-types', 'targets/existing-page', 'targets/Case Sensitive'] as const;
+
+/**
+ * Ordinary files the fixture project admits. `assets/NOTICE` is the load-bearing
+ * one: an EXISTING extensionless ordinary file, which plane B can prove exists
+ * and plane A — having no file inventory — guesses is a document.
+ */
+const 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 tolerant = createTolerantDocumentResolver(documents);
+ return {
+ hasDocument: (docName) => documents.has(docName),
+ hasFile: (path) => files.has(path),
+ resolveTolerantDocument: (docName) => tolerant(docName),
+ };
+}
+
+/** Stable identity for one authored occurrence, shared across planes. */
+function occurrenceKey(o: Pick<LocalTargetOccurrence, 'line' | 'column' | 'href'>): string {
+ return `${o.line}:${o.column}:${o.href}`;
+}
+
+/**
+ * Plane A: every document target the graph extractors emit for this document.
+ *
+ * Both planes are handed the SAME inventory — that is the whole point. Plane A
+ * takes only the file half, because document membership is already implicit in
+ * the graph's admitted set, while file membership is what it had no way to see.
+ */
+function planeADocumentTargets(markdown: string): Set<string> {
+ const files = new Set<string>(FILES);
+ const fileOracle = { hasFile: (path: string) => files.has(path) };
+ const targets = new Set<string>();
+ for (const edge of [
+ ...extractMarkdownLinksFromMarkdown(markdown, SOURCE_DOC, 0, fileOracle),
+ ...extractWikiLinksFromMarkdown(markdown, SOURCE_DOC),
+ ]) {
+ if (typeof edge.target === 'string' && edge.target.length > 0) targets.add(edge.target);
+ }
+ return targets;
+}
+
+interface Planes {
+ occurrences: LocalTargetOccurrence[];
+ assessmentByKey: Map<string, LocalTargetAssessment>;
+ graphDocumentTargets: Set<string>;
+}
+
+function runPlanes(): Planes {
+ const inventory = buildInventory();
+ const occurrences = extractLocalTargetOccurrences(MATRIX);
+ const assessments = assessLocalTargets(MATRIX, SOURCE_DOC, inventory);
+ return {
+ occurrences,
+ assessmentByKey: new Map(assessments.map((a) => [occurrenceKey(a.occurrence), a])),
+ graphDocumentTargets: planeADocumentTargets(MATRIX),
+ };
+}
+
+/** A graph edge exists for this authored href (root-relative forms are equivalent). */
+function graphHasEdgeFor(href: string, graphDocumentTargets: Set<string>): boolean {
+ return (
+ graphDocumentTargets.has(href) ||
+ graphDocumentTargets.has(href.replace(/^\//, '')) ||
+ graphDocumentTargets.has(href.replace(/\.mdx?$/, ''))
+ );
+}
+
+/** Human-readable occurrence label for assertion failure messages. */
+function describeOccurrence(o: LocalTargetOccurrence): string {
+ return `line ${o.line} ${o.sourceForm} ${o.role} "${o.href}"`;
+}
+
+describe('link classification uniformity across the document-graph and local-target planes', () => {
+ test('every recognized occurrence receives a canonical classification', () => {
+ const { occurrences, assessmentByKey } = runPlanes();
+
+ // Recognition is already consolidated behind one grammar, so an occurrence
+ // the extractor SEES is an occurrence some surface will report on. Anything
+ // the classifier refuses to answer for is a hole a surface fills by guessing.
+ const unclassified = occurrences
+ .filter((o) => !assessmentByKey.has(occurrenceKey(o)))
+ .map(describeOccurrence);
+
+ expect(unclassified).toEqual([]);
+ });
+
+ test('an occurrence is never both an existing file and a document edge', () => {
+ const { occurrences, assessmentByKey, graphDocumentTargets } = runPlanes();
+
+ // `assets/NOTICE` is the case that walks straight through the hole: plane B
+ // proves the extensionless file exists, while plane A — with no file
+ // inventory — emits a document edge for the same authored href, so Problems
+ // shows a missing-document warning for a file that is right there on disk.
+ const contradictions = occurrences
+ .filter((o) => {
+ const assessment = assessmentByKey.get(occurrenceKey(o));
+ return (
+ assessment?.targetKind === 'file' &&
+ assessment.status === 'exact' &&
+ graphHasEdgeFor(o.href, graphDocumentTargets)
+ );
+ })
+ .map(describeOccurrence);
+
+ expect(contradictions).toEqual([]);
+ });
+
+ test('document links are represented in the graph regardless of authored form', () => {
+ const { occurrences, assessmentByKey, graphDocumentTargets } = runPlanes();
+
+ // Reference-style links reach the assessment plane but no reference reader
+ // exists in the graph plane, so `targets/missing-reference` warns in Problems
+ // while never appearing under Outgoing — and backlinks / orphans / hubs /
+ // dead-links all under-report by the same amount.
+ const missingFromGraph = occurrences
+ .filter((o) => {
+ const assessment = assessmentByKey.get(occurrenceKey(o));
+ return (
+ assessment?.targetKind === 'document' &&
+ o.role === 'link' &&
+ !graphHasEdgeFor(o.href, graphDocumentTargets)
+ );
+ })
+ .map(describeOccurrence);
+
+ expect(missingFromGraph).toEqual([]);
+ });
+
+ test('both planes resolve a wiki target to the same identity from a nested source', () => {
+ // Wiki targets are vault-root-relative: `[[targets/x]]` authored in
+ // `notes/index` names `targets/x`, not `notes/targets/x`. From a ROOT-level
+ // source the source-relative and root-relative readings coincide, so this
+ // has to be asserted from a nested doc or the divergence is invisible.
+ const nestedSource = 'notes/index';
+ const markdown = '[[targets/existing-page]]\n\n![[targets/missing-embed]]\n';
+ const inventory = buildInventory();
+
+ const planeA = new Set(
+ extractWikiLinksFromMarkdown(markdown, nestedSource).map((edge) => edge.target),
+ );
+ const planeB = assessLocalTargets(markdown, nestedSource, inventory);
+
+ expect(planeB.map((a) => a.resolvedTarget)).toEqual([
+ 'targets/existing-page',
+ 'targets/missing-embed',
+ ]);
+ for (const assessment of planeB) {
+ expect(planeA).toContain(assessment.resolvedTarget);
+ }
+ });
+
+ test('a body with no reference definition still yields its inline document edges', () => {
+ // The graph skips the reference pass when no `[label]:` definition line
+ // exists, because that pass costs a full second extraction per document on
+ // every rebuild and every write. The skip must not take inline edges with
+ // it — this is the guard on that shortcut.
+ const inlineOnly =
+ '# Doc\n\n[a](targets/existing-page.md)\n\n[b](targets/missing-markdown.md)\n';
+ expect(planeADocumentTargets(inlineOnly)).toEqual(
+ new Set(['targets/existing-page', 'targets/missing-markdown']),
+ );
+ });
+
+ test('non-rendering contexts are inert in both planes', () => {
+ const { occurrences, graphDocumentTargets } = runPlanes();
+
+ // Guard, not a RED assertion: both server planes already exclude these. It
+ // is pinned here so the uniformity fix cannot reach agreement by teaching a
+ // plane to START reporting comment / pre / fenced content.
+ const inertHrefs = [
+ 'assets/comment-missing.txt',
+ 'assets/pre-missing.txt',
+ 'assets/fenced-missing.txt',
+ ];
+ for (const href of inertHrefs) {
+ expect(occurrences.map((o) => o.href)).not.toContain(href);
+ }
+ expect(graphDocumentTargets).not.toContain('targets/fenced-wiki-missing');
+ });
+});
diff --git a/packages/server/src/link-syntax.test.ts b/packages/server/src/link-syntax.test.ts
index 06093d8d9..d7e002474 100644
--- a/packages/server/src/link-syntax.test.ts
+++ b/packages/server/src/link-syntax.test.ts
@@ -5,9 +5,13 @@ import {
extractWikiLinksFromMarkdown,
} from './backlink-index.ts';
import {
+ matchHtmlImgs,
matchMarkdownLinks,
matchWikiLinks,
+ readHtmlImgAt,
readMarkdownLinkAt,
+ readMarkdownReferenceAt,
+ readReferenceDefinition,
readWikiLinkAt,
} from './link-syntax.ts';
import { rewriteWikiLinksForDocumentRename } from './managed-rename-rewrite.ts';
@@ -230,6 +234,157 @@ describe('matchMarkdownLinks', () => {
});
});
+describe('readMarkdownReferenceAt', () => {
+ test('full reference carries the second-bracket label', () => {
+ expect(readMarkdownReferenceAt('[text][ref]', 0)).toMatchObject({
+ image: false,
+ label: 'text',
+ form: 'full',
+ referenceLabelRaw: 'ref',
+ start: 0,
+ end: 11,
+ labelEnd: 6,
+ });
+ });
+
+ test('collapsed reference reuses the label', () => {
+ expect(readMarkdownReferenceAt('[text][]', 0)).toMatchObject({
+ form: 'collapsed',
+ label: 'text',
+ referenceLabelRaw: 'text',
+ end: 8,
+ labelEnd: 6,
+ });
+ });
+
+ test('shortcut reference ends at the label', () => {
+ expect(readMarkdownReferenceAt('[text]', 0)).toMatchObject({
+ form: 'shortcut',
+ referenceLabelRaw: 'text',
+ end: 6,
+ labelEnd: 6,
+ });
+ });
+
+ test('image form at the ! position', () => {
+ expect(readMarkdownReferenceAt('![alt][ref]', 0)).toMatchObject({
+ image: true,
+ label: 'alt',
+ form: 'full',
+ referenceLabelRaw: 'ref',
+ labelEnd: 6,
+ });
+ });
+
+ test('a space between the brackets is a shortcut, not a full reference', () => {
+ expect(readMarkdownReferenceAt('[text] [ref]', 0)).toMatchObject({
+ form: 'shortcut',
+ end: 6,
+ });
+ });
+
+ test('unterminated label does not match', () => {
+ expect(readMarkdownReferenceAt('[text', 0)).toBeNull();
+ });
+
+ test('end always equals start + matched length (range fidelity)', () => {
+ for (const [input, matched] of [
+ ['[text][ref]', '[text][ref]'],
+ ['![alt][ref]', '![alt][ref]'],
+ ['[text][]', '[text][]'],
+ ['[text]', '[text]'],
+ ] as const) {
+ const m = readMarkdownReferenceAt(input, 0);
+ expect(m).not.toBeNull();
+ expect(input.slice(m?.start, m?.end)).toBe(matched);
+ }
+ });
+});
+
+describe('readReferenceDefinition', () => {
+ test('bare destination with the repair range bounding the destination token', () => {
+ const line = '[ref]: ./file.pdf';
+ const def = readReferenceDefinition(line);
+ expect(def).toMatchObject({ label: 'ref', destination: './file.pdf', titleSuffix: '' });
+ expect(line.slice(def?.destinationStart, def?.destinationEnd)).toBe('./file.pdf');
+ });
+
+ test('angle-wrapped destination admits spaces and unwraps', () => {
+ const line = '[ref]: <./my file.pdf> "title"';
+ const def = readReferenceDefinition(line);
+ expect(def).toMatchObject({ destination: './my file.pdf', titleSuffix: ' "title"' });
+ expect(line.slice(def?.destinationStart, def?.destinationEnd)).toBe('<./my file.pdf>');
+ });
+
+ test('up to three leading spaces are tolerated; the repair range still lands on the destination', () => {
+ const line = ' [ref]: ./file.pdf';
+ const def = readReferenceDefinition(line);
+ expect(line.slice(def?.destinationStart, def?.destinationEnd)).toBe('./file.pdf');
+ });
+
+ test('four leading spaces disqualify the definition (indented code)', () => {
+ expect(readReferenceDefinition(' [ref]: ./file.pdf')).toBeNull();
+ });
+
+ test('a non-definition line does not match', () => {
+ expect(readReferenceDefinition('see [ref] here')).toBeNull();
+ expect(readReferenceDefinition('[ref]: ./a ./b')).toBeNull();
+ });
+});
+
+describe('readHtmlImgAt / matchHtmlImgs', () => {
+ test('bare void form with a double-quoted src', () => {
+ expect(readHtmlImgAt('<img src="./photo.png">', 0)).toMatchObject({
+ src: './photo.png',
+ selfClosing: false,
+ start: 0,
+ end: 23,
+ });
+ });
+
+ test('self-closing form is flagged', () => {
+ expect(readHtmlImgAt('<img src="./photo.png" />', 0)).toMatchObject({
+ src: './photo.png',
+ selfClosing: true,
+ });
+ });
+
+ test('quoted attributes may contain src-like text and greater-than signs', () => {
+ expect(
+ readHtmlImgAt('<img alt="fake src=\'./wrong.png\' > still alt" src="./right.png">', 0),
+ ).toMatchObject({ src: './right.png' });
+ });
+
+ test('does not treat data-src, srcset, or quoted text as src', () => {
+ expect(readHtmlImgAt('<img data-src="./wrong.png" srcset="./also.png 2x">', 0)).toBeNull();
+ });
+
+ test('single-quoted and unquoted src values', () => {
+ expect(readHtmlImgAt("<img src='./a.png'>", 0)).toMatchObject({ src: './a.png' });
+ expect(readHtmlImgAt('<img src=./a.png>', 0)).toMatchObject({ src: './a.png' });
+ });
+
+ test('src after other attributes; data-src / srcset are not read as the source', () => {
+ expect(readHtmlImgAt('<img alt="x" src="./a.png">', 0)).toMatchObject({ src: './a.png' });
+ expect(readHtmlImgAt('<img data-src="./decoy.png" src="./real.png">', 0)).toMatchObject({
+ src: './real.png',
+ });
+ expect(readHtmlImgAt('<img srcset="./a.png 1x">', 0)).toBeNull();
+ });
+
+ test('non-img tags and img without src do not match', () => {
+ expect(readHtmlImgAt('<a href="./a.png">', 0)).toBeNull();
+ expect(readHtmlImgAt('<img alt="no source">', 0)).toBeNull();
+ });
+
+ test('scans every img on a line and preserves exact spans', () => {
+ const line = 'a <img src="./a.png"> b <img src="./b.png"/> c';
+ const matches = matchHtmlImgs(line);
+ expect(matches.map((m) => m.src)).toEqual(['./a.png', './b.png']);
+ for (const m of matches) expect(line.slice(m.start, m.end).startsWith('<img')).toBe(true);
+ });
+});
+
/**
* Characterization ledger for the pre-consolidation recognizer divergences.
* Each entry pins how the shared grammar decided a case where the four
diff --git a/packages/server/src/link-syntax.ts b/packages/server/src/link-syntax.ts
index dd59b3361..1003c6582 100644
--- a/packages/server/src/link-syntax.ts
+++ b/packages/server/src/link-syntax.ts
@@ -53,6 +53,7 @@ const markdownPattern = (label: string, flags: string) =>
const WIKI_AT_RE = wikiPattern('y');
const WIKI_SCAN_RE = wikiPattern('g');
const MD_AT_RE = markdownPattern(LABEL_STRICT_SOURCE, 'y');
+const MD_AT_NESTED_RE = markdownPattern(LABEL_NESTED_SOURCE, 'y');
const MD_SCAN_STRICT_RE = markdownPattern(LABEL_STRICT_SOURCE, 'g');
const MD_SCAN_NESTED_RE = markdownPattern(LABEL_NESTED_SOURCE, 'g');
@@ -142,9 +143,14 @@ export function readWikiLinkAt(line: string, start: number): WikiLinkMatch | nul
* `![…](…)` at `start` is an image; `[…](…)` is a link — dispatch on
* `.image` when the two forms need different handling.
*/
-export function readMarkdownLinkAt(line: string, start: number): MarkdownLinkMatch | null {
- MD_AT_RE.lastIndex = start;
- const match = MD_AT_RE.exec(line);
+export function readMarkdownLinkAt(
+ line: string,
+ start: number,
+ options?: MatchMarkdownLinksOptions,
+): MarkdownLinkMatch | null {
+ const pattern = options?.nestedBracketLabels ? MD_AT_NESTED_RE : MD_AT_RE;
+ pattern.lastIndex = start;
+ const match = pattern.exec(line);
if (!match) return null;
return toMarkdownLinkMatch(match, start);
}
@@ -189,3 +195,228 @@ export function matchMarkdownLinks(
}
return matches;
}
+
+// Reference-style label: `[text][ref]` (full), `[text][]` (collapsed),
+// `[text]` (shortcut). Label + optional second bracket use the same strict
+// `[^\]]*` class as the inline label above, so recognition stays observationally
+// aligned with `readMarkdownLinkAt`. Whether a shortcut/collapsed form is a real
+// reference depends on a matching definition, which only the caller (holding the
+// whole-document definition table) can decide — this recognizer reports the
+// authored shape and leaves resolution to the caller.
+const MD_REFERENCE_SOURCE = String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;
+const MD_REFERENCE_AT_RE = new RegExp(MD_REFERENCE_SOURCE, 'y');
+
+// A link reference definition line: up to 3 leading spaces, `[label]:`, a
+// destination (`<…>` admits spaces; the bare form runs to the first whitespace),
+// and an optional CommonMark title. Anchored to the whole line — definitions are
+// block-level and carry no other content. Group 1 captures the prefix so the
+// destination's offset is `prefix.length` without needing match indices.
+const REFERENCE_DEFINITION_RE =
+ /^( {0,3}\[([^\]\n]+)\]:[ \t]*)(<[^>\n]*>|[^\s\n]+)((?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?[ \t]*)$/;
+
+type MarkdownReferenceForm = 'full' | 'collapsed' | 'shortcut';
+
+export interface MarkdownReferenceMatch {
+ /** True for the `![…][…]` image form. */
+ image: boolean;
+ /** Link text as authored (the first bracket's contents). */
+ label: string;
+ form: MarkdownReferenceForm;
+ /**
+ * Label to resolve against the definition table: the second bracket's
+ * contents for `full`, otherwise `label` (collapsed and shortcut reuse the
+ * text as the reference).
+ */
+ referenceLabelRaw: string;
+ start: number;
+ /** Index just past the whole form (through the second bracket for full/collapsed). */
+ end: number;
+ /** Index just past the label's closing `]` — where a shortcut form ends. */
+ labelEnd: number;
+}
+
+export interface ReferenceDefinitionMatch {
+ /** Definition label as authored (untrimmed, not case-folded). */
+ label: string;
+ /** Destination as authored, including any `<…>` wrapper. */
+ destinationRaw: string;
+ /** Destination with a `<…>` wrapper removed. */
+ destination: string;
+ /** Offset of the destination token within the line — the repair-range start. */
+ destinationStart: number;
+ /** Index just past the destination token — the repair-range end. */
+ destinationEnd: number;
+ /** Authored whitespace+title suffix, '' when no title. */
+ titleSuffix: string;
+}
+
+export interface HtmlImgMatch {
+ /** The `src` value as authored (quotes removed, not URL-decoded). */
+ src: string;
+ /** True when the tag closes with `/>` rather than a bare `>`. */
+ selfClosing: boolean;
+ start: number;
+ /** Index just past the closing `>`. */
+ end: number;
+}
+
+function toMarkdownReferenceMatch(match: RegExpExecArray, start: number): MarkdownReferenceMatch {
+ const image = match[1] === '!';
+ const label = match[2] ?? '';
+ const secondBracket = match[3];
+ const labelEnd = start + (image ? 2 : 1) + label.length + 1;
+ const end = start + match[0].length;
+ if (secondBracket === undefined) {
+ return { image, label, form: 'shortcut', referenceLabelRaw: label, start, end, labelEnd };
+ }
+ if (secondBracket === '') {
+ return { image, label, form: 'collapsed', referenceLabelRaw: label, start, end, labelEnd };
+ }
+ return { image, label, form: 'full', referenceLabelRaw: secondBracket, start, end, labelEnd };
+}
+
+/**
+ * Match a reference-style markdown link or image starting exactly at `start`.
+ * `![…]` at `start` is an image; `[…]` is a link. Returns the authored shape
+ * ({@link MarkdownReferenceForm}); the caller decides whether a matching
+ * definition exists. Returns null when the label is unterminated.
+ */
+export function readMarkdownReferenceAt(
+ line: string,
+ start: number,
+): MarkdownReferenceMatch | null {
+ MD_REFERENCE_AT_RE.lastIndex = start;
+ const match = MD_REFERENCE_AT_RE.exec(line);
+ if (!match) return null;
+ return toMarkdownReferenceMatch(match, start);
+}
+
+/**
+ * Parse a whole line as a link reference definition (`[label]: dest "title"`).
+ * Returns null when the line is not a definition. `destinationStart` /
+ * `destinationEnd` bound the destination token so a rewriter can replace just
+ * that span (the definition repair range).
+ */
+export function readReferenceDefinition(line: string): ReferenceDefinitionMatch | null {
+ const match = REFERENCE_DEFINITION_RE.exec(line);
+ if (!match) return null;
+ const prefix = match[1] ?? '';
+ const destinationRaw = match[3] ?? '';
+ return {
+ label: match[2] ?? '',
+ destinationRaw,
+ destination: unwrapAngleHref(destinationRaw),
+ destinationStart: prefix.length,
+ destinationEnd: prefix.length + destinationRaw.length,
+ titleSuffix: match[4] ?? '',
+ };
+}
+
+function isHtmlSpace(char: string | undefined): boolean {
+ return char === ' ' || char === '\t' || char === '\r' || char === '\n' || char === '\f';
+}
+
+/** Find the closing `>` without letting one inside a quoted attribute terminate the tag. */
+function findHtmlTagEnd(line: string, start: number): number | null {
+ let quote: '"' | "'" | null = null;
+ for (let i = start; i < line.length; i++) {
+ const char = line[i];
+ if (quote !== null) {
+ if (char === quote) quote = null;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '>') return i;
+ }
+ return null;
+}
+
+/** Read the first exact `src` attribute from a bounded `<img ...>` tag. */
+function readImgSrcAttribute(line: string, attributesStart: number, tagEnd: number): string | null {
+ let cursor = attributesStart;
+ while (cursor < tagEnd) {
+ while (isHtmlSpace(line[cursor]) || line[cursor] === '/') cursor += 1;
+ if (cursor >= tagEnd) break;
+
+ const nameStart = cursor;
+ while (
+ cursor < tagEnd &&
+ !isHtmlSpace(line[cursor]) &&
+ line[cursor] !== '=' &&
+ line[cursor] !== '/' &&
+ line[cursor] !== '>'
+ ) {
+ cursor += 1;
+ }
+ const name = line.slice(nameStart, cursor).toLowerCase();
+ if (!name) {
+ cursor += 1;
+ continue;
+ }
+ while (isHtmlSpace(line[cursor])) cursor += 1;
+ if (line[cursor] !== '=') continue;
+ cursor += 1;
+ while (isHtmlSpace(line[cursor])) cursor += 1;
+ if (cursor >= tagEnd) return null;
+
+ const quote = line[cursor];
+ let value: string;
+ if (quote === '"' || quote === "'") {
+ const valueStart = cursor + 1;
+ const valueEnd = line.indexOf(quote, valueStart);
+ if (valueEnd < 0 || valueEnd > tagEnd) return null;
+ value = line.slice(valueStart, valueEnd);
+ cursor = valueEnd + 1;
+ } else {
+ const valueStart = cursor;
+ while (cursor < tagEnd && !isHtmlSpace(line[cursor]) && line[cursor] !== '>') cursor += 1;
+ value = line.slice(valueStart, cursor);
+ }
+ if (name === 'src') return value;
+ }
+ return null;
+}
+
+/**
+ * Match an HTML `<img>` starting exactly at `start`, reading its `src`. Covers
+ * the bare void form and the self-closing form. Returns null when `start` is not
+ * an `<img>` with a `src`.
+ */
+export function readHtmlImgAt(line: string, start: number): HtmlImgMatch | null {
+ if (line.slice(start, start + 4).toLowerCase() !== '<img') return null;
+ const boundary = line[start + 4];
+ if (boundary !== '>' && boundary !== '/' && !isHtmlSpace(boundary)) return null;
+ const tagEnd = findHtmlTagEnd(line, start + 4);
+ if (tagEnd === null) return null;
+ const src = readImgSrcAttribute(line, start + 4, tagEnd);
+ if (src === null) return null;
+ let beforeClose = tagEnd - 1;
+ while (beforeClose >= start && isHtmlSpace(line[beforeClose])) beforeClose -= 1;
+ return {
+ src,
+ selfClosing: line[beforeClose] === '/',
+ start,
+ end: tagEnd + 1,
+ };
+}
+
+/** Every HTML `<img src>` on a line, left to right, non-overlapping. */
+export function matchHtmlImgs(line: string): HtmlImgMatch[] {
+ const matches: HtmlImgMatch[] = [];
+ const lower = line.toLowerCase();
+ for (let cursor = 0; cursor < line.length; ) {
+ const start = lower.indexOf('<img', cursor);
+ if (start < 0) break;
+ const match = readHtmlImgAt(line, start);
+ if (match) {
+ matches.push(match);
+ cursor = match.end;
+ } else {
+ cursor = start + 1;
+ }
+ }
+ return matches;
+}
diff --git a/packages/server/src/lint/audit-yield.test.ts b/packages/server/src/lint/audit-yield.test.ts
index 3fdef6b4d..1cdb3696c 100644
--- a/packages/server/src/lint/audit-yield.test.ts
+++ b/packages/server/src/lint/audit-yield.test.ts
@@ -103,6 +103,20 @@ describe('auditProject generation supersession', () => {
expect(generation).toBe('1 main');
});
+ test('abandons a one-file walk when generation changes without a time-slice yield', async () => {
+ let reads = 0;
+ await expect(
+ auditProject({
+ projectDir: root,
+ contentDir: root,
+ baseConfig: base,
+ targetPath: 'folder-0/doc-0.md',
+ auditGeneration: () => (reads++ === 0 ? '0 main 1' : '0 main 2'),
+ }),
+ ).rejects.toBeInstanceOf(AuditSupersededError);
+ expect(reads).toBe(2);
+ });
+
test('completes normally when the generation holds', async () => {
const result = await auditProject({
projectDir: root,
diff --git a/packages/server/src/lint/audit.ts b/packages/server/src/lint/audit.ts
index 3d8345b8b..de0d4e0bf 100644
--- a/packages/server/src/lint/audit.ts
+++ b/packages/server/src/lint/audit.ts
@@ -343,6 +343,12 @@ export async function auditProject(
if (result.diagnostics.length > 0) files.push(result);
}
+ // Small corpora may finish without crossing the time-slice yield above. The
+ // final equality check keeps every audit size supersession-safe.
+ if (auditGeneration !== undefined && auditGeneration() !== startGeneration) {
+ throw new AuditSupersededError();
+ }
+
return { files, fileCount: docFiles.length, errorCount, warningCount, warnings };
}
diff --git a/packages/server/src/lint/validation-audit.test.ts b/packages/server/src/lint/validation-audit.test.ts
index 45babd7fb..6846acfc4 100644
--- a/packages/server/src/lint/validation-audit.test.ts
+++ b/packages/server/src/lint/validation-audit.test.ts
@@ -1,8 +1,8 @@
/**
* Unit tests for the unified validation audit: the validator registry fanning
* out to the real lint walk (`auditProject`) and a real in-memory
- * `BacklinkIndex` over a temp content tree, merged into one source-tagged
- * diagnostic plane.
+ * `BacklinkIndex` and `LocalTargetIndex` over a temp content tree, merged into
+ * one source-tagged diagnostic plane.
*/
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
@@ -17,6 +17,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { BacklinkIndex } from '../backlink-index.ts';
+import { LocalTargetIndex } from '../local-target-index.ts';
import {
createProjectValidators,
runValidationAudit,
@@ -26,6 +27,7 @@ import {
let root: string;
let index: BacklinkIndex;
+let localTargets: LocalTargetIndex;
let admitted: Set<string>;
const lintOn: LinterConfig = {
@@ -42,21 +44,36 @@ const DOC_WITH_TAB = '# Title\n\n\tindented with a tab\n';
beforeEach(() => {
root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-validation-audit-')));
index = new BacklinkIndex({ projectDir: root, contentDir: root });
+ localTargets = new LocalTargetIndex({ contentDir: root });
admitted = new Set();
});
afterEach(() => {
rmSync(root, { recursive: true, force: true });
});
-/** Write the doc to disk AND index it — the two views production keeps in sync. */
+/**
+ * Write the doc to disk AND index it into both derived indexes — the three views
+ * production keeps in sync (disk for the lint walk, the graph for wiki/inline-md
+ * document dead-links, the local-target index for file/image/reference targets).
+ */
function seedDoc(docName: string, markdown: string): void {
const abs = join(root, `${docName}.md`);
mkdirSync(join(abs, '..'), { recursive: true });
writeFileSync(abs, markdown, 'utf-8');
index.updateDocumentFromMarkdown(docName, markdown);
+ localTargets.setSource(docName, markdown);
admitted.add(docName);
}
+/**
+ * Mark an ordinary-file target as present in the local-target inventory — what
+ * the watcher's all-files snapshot does in production. Order-independent: the
+ * index reassesses any source already pointing at this path.
+ */
+function seedFile(contentRootRelativePath: string): void {
+ localTargets.setFileTarget(contentRootRelativePath, true);
+}
+
function docFilePathFor(docName: string): string | null {
for (const ext of SUPPORTED_DOC_EXTENSIONS) {
if (existsSync(join(root, `${docName}${ext}`))) return `${docName}${ext}`;
@@ -69,7 +86,14 @@ function deps(overrides: Partial<ValidationAuditDeps> = {}): ValidationAuditDeps
projectDir: root,
contentDir: root,
baseConfig: lintOn,
- derivedDocumentIndex: index,
+ // The reader composes the two real derived indexes the way
+ // DerivedDocumentIndex does — the graph for document dead-links, the
+ // local-target index for file/image/reference targets — so the projection
+ // is tested against real assessment data, not a stand-in.
+ derivedDocumentIndex: {
+ getDeadLinks: (a, s) => index.getDeadLinks(a, s),
+ getLocalTargetAssessmentsForSources: (s) => localTargets.getAssessmentsForSources(s),
+ },
admittedDocNames: () => admitted,
docFilePathFor,
...overrides,
@@ -294,13 +318,14 @@ describe('runValidationAudit', () => {
test('a dead link from an admitted-but-unsaved source still names a file', async () => {
// Admitted in the index but not on disk yet: docFilePathFor returns null, so
// the finding falls back to the default extension rather than emitting null.
- const fakeIndex: Pick<BacklinkIndex, 'getDeadLinks'> = {
+ const fakeIndex = {
getDeadLinks: () => [
{
target: 'ghost',
sources: [{ source: 'unsaved', anchor: null, snippet: null, line: 3, column: 2 }],
},
],
+ getLocalTargetAssessmentsForSources: () => [],
};
const result = await runValidationAudit(
@@ -323,10 +348,11 @@ describe('runValidationAudit', () => {
test('a dead link from a pre-position cache degrades to the start of the doc', async () => {
// Entries deserialized from a cache written before positions were indexed
// carry no line/column; the finding degrades to the doc start, not undefined.
- const fakeIndex: Pick<BacklinkIndex, 'getDeadLinks'> = {
+ const fakeIndex = {
getDeadLinks: () => [
{ target: 'ghost', sources: [{ source: 'legacy', anchor: null, snippet: null }] },
],
+ getLocalTargetAssessmentsForSources: () => [],
};
const result = await runValidationAudit(
@@ -347,6 +373,272 @@ describe('runValidationAudit', () => {
// An undefined position would fail the wire schema and 500 the route.
expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);
});
+
+ test('graph findings survive when the local-target index is unavailable', async () => {
+ const fakeIndex = {
+ getDeadLinks: () => [
+ {
+ target: 'ghost',
+ sources: [{ source: 'source', anchor: null, snippet: null, line: 1, column: 2 }],
+ },
+ ],
+ getLocalTargetAssessmentsForSources: () => {
+ throw new Error('Local-target index is not ready');
+ },
+ };
+
+ const result = await runValidationAudit(
+ createProjectValidators(
+ deps({
+ derivedDocumentIndex: fakeIndex,
+ admittedDocNames: () => ['source'],
+ docFilePathFor: () => 'source.md',
+ }),
+ ),
+ );
+
+ expect(result.files[0]?.diagnostics).toEqual([
+ expect.objectContaining({ code: 'dead-link', linkTarget: 'ghost' }),
+ ]);
+ expect(result.warnings).toContain(
+ 'local-target validation unavailable: Local-target index is not ready',
+ );
+ });
+});
+
+describe('local-target findings (files, images, reference-style)', () => {
+ test('a missing ordinary-file link is a positioned finding with file evidence and no create affordance', async () => {
+ seedDoc('doc', '# Doc\n\n[report](./report.pdf)\n');
+ // report.pdf is never seeded — the file does not exist.
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ expect(result.files.map((f) => f.file)).toEqual(['doc.md']);
+ const diagnostics = result.files[0]?.diagnostics ?? [];
+ expect(diagnostics).toHaveLength(1);
+ const d = diagnostics[0];
+ expect(d?.source).toBe('links');
+ expect(d?.code).toBe('dead-link');
+ expect(d?.severity).toBe('warning');
+ expect(d?.message).toBe('Link target "report.pdf" does not resolve to an existing file.');
+ // Files never offer Create page.
+ expect(d?.linkTarget).toBeUndefined();
+ expect(d?.localTarget).toEqual({
+ href: './report.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'report.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ });
+ expect(d?.range.start).toEqual({ line: 2, character: 0 });
+ // New evidence survives the wire schema round trip untouched.
+ expect(ValidationAuditResponseSchema.parse(result)).toEqual(result);
+ });
+
+ test('a missing markdown image reports the image with a not-found message', async () => {
+ seedDoc('doc', '# Doc\n\n![logo](./logo.png)\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const d = result.files[0]?.diagnostics[0];
+ expect(d?.message).toBe('Image target "logo.png" does not resolve to an existing file.');
+ expect(d?.linkTarget).toBeUndefined();
+ expect(d?.localTarget?.role).toBe('image');
+ expect(d?.localTarget?.targetKind).toBe('file');
+ expect(d?.localTarget?.sourceForm).toBe('markdown-inline');
+ expect(d?.localTarget?.reason).toBe('no-such-file');
+ });
+
+ test('a bare HTML img with a missing source reports as an html-img image finding', async () => {
+ seedDoc('doc', '# Doc\n\n<img src="./banner.png">\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const d = result.files[0]?.diagnostics[0];
+ expect(d?.message).toBe('Image target "banner.png" does not resolve to an existing file.');
+ expect(d?.localTarget?.role).toBe('image');
+ expect(d?.localTarget?.sourceForm).toBe('html-img');
+ expect(d?.localTarget?.reason).toBe('no-such-file');
+ 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');
+
+ 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');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const diagnostics = result.files.find((file) => file.file === 'doc.md')?.diagnostics ?? [];
+ expect(diagnostics).toEqual([
+ expect.objectContaining({
+ source: 'links',
+ code: 'dead-link',
+ message: 'Link target "assets/NOTICE" does not resolve to an existing document.',
+ linkTarget: 'assets/NOTICE',
+ }),
+ ]);
+ expect(diagnostics[0]?.localTarget).toBeUndefined();
+ });
+
+ test('a missing markdown document link does not suppress a same-target wiki occurrence', async () => {
+ seedDoc('doc', '# Doc\n\n[markdown](ghost) and [[ghost]]\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const diagnostics = result.files.find((file) => file.file === 'doc.md')?.diagnostics ?? [];
+ expect(diagnostics).toHaveLength(2);
+ expect(diagnostics.filter((diagnostic) => diagnostic.linkTarget === 'ghost')).toHaveLength(2);
+ expect(diagnostics.filter((diagnostic) => diagnostic.localTarget !== undefined)).toHaveLength(
+ 1,
+ );
+ });
+
+ test('every reference-style use is positioned and points at the shared definition', async () => {
+ seedDoc('doc', '# Doc\n\n[one][r] and [two][r]\n\n[r]: ./missing.pdf\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const diagnostics = result.files[0]?.diagnostics ?? [];
+ expect(diagnostics).toHaveLength(2);
+ for (const d of diagnostics) {
+ expect(d.localTarget?.sourceForm).toBe('markdown-reference');
+ expect(d.localTarget?.targetKind).toBe('file');
+ expect(d.localTarget?.reason).toBe('no-such-file');
+ // All uses of one label share one repair location: the definition line.
+ expect(d.localTarget?.definition).toEqual({ line: 4, label: 'r' });
+ expect(d.linkTarget).toBeUndefined();
+ }
+ // The two uses are positioned independently, not collapsed to one.
+ expect(diagnostics.map((d) => d.range.start.character)).toEqual([0, 13]);
+ });
+
+ test('a reference-style link to a missing document keeps the Create-page affordance', async () => {
+ seedDoc('doc', '# Doc\n\n[it][d]\n\n[d]: ./ghost-doc\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const d = result.files[0]?.diagnostics[0];
+ // The graph does not extract reference-style links, so this is the only
+ // finding — and a missing document, unlike a file, is create-eligible.
+ expect(result.files[0]?.diagnostics).toHaveLength(1);
+ expect(d?.linkTarget).toBe('ghost-doc');
+ expect(d?.localTarget?.targetKind).toBe('document');
+ expect(d?.localTarget?.definition).toEqual({ line: 4, label: 'd' });
+ expect(d?.message).toBe('Link target "ghost-doc" does not resolve to an existing document.');
+ });
+
+ test('a tolerant document fallback stays a finding but never offers Create page', async () => {
+ seedDoc('Guide', '# Guide\n');
+ seedDoc('doc', '# Doc\n\n[it][d]\n\n[d]: guide\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const d = result.files.find((file) => file.file === 'doc.md')?.diagnostics[0];
+ expect(d?.localTarget).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'guide',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ fallbackTarget: 'Guide',
+ });
+ expect(d?.linkTarget).toBeUndefined();
+ });
+
+ test('an inline-markdown document link is reported once, by the canonical classifier', async () => {
+ seedDoc('doc', '# Doc\n\n[other](./ghost-doc)\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ // Both planes see this occurrence, and exactly one finding reaches the
+ // panel. The surviving row is the assessment plane's: it carries the same
+ // create-page `linkTarget` the graph row did, plus the canonical evidence
+ // the graph cannot produce.
+ const diagnostics = result.files[0]?.diagnostics ?? [];
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]?.linkTarget).toBe('ghost-doc');
+ expect(diagnostics[0]?.localTarget).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'ghost-doc',
+ reason: 'no-such-doc',
+ });
+ });
+
+ test('a root-escaping file target is reported as unresolvable without a resolved target', async () => {
+ seedDoc('doc', '# Doc\n\n[x](../../../secrets.pdf)\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()));
+
+ const d = result.files[0]?.diagnostics[0];
+ expect(d?.localTarget?.reason).toBe('unresolvable');
+ expect(d?.localTarget?.resolvedTarget).toBeNull();
+ expect(d?.localTarget?.resolutionMethod).toBe('none');
+ expect(d?.linkTarget).toBeUndefined();
+ expect(d?.message).toBe(
+ 'Link target "../../../secrets.pdf" could not be resolved to a project-local target.',
+ );
+ });
+
+ test('validation.links=off silences file findings; =error raises them uniformly with dead links', async () => {
+ seedDoc('doc', '# Doc\n\n[report](./report.pdf)\n');
+
+ const off = await runValidationAudit(createProjectValidators(deps({ linksValidation: 'off' })));
+ expect(off.files).toEqual([]);
+ expect(off.warnings).toEqual([]);
+
+ const asError = await runValidationAudit(
+ createProjectValidators(deps({ linksValidation: 'error' })),
+ );
+ expect(asError.files[0]?.diagnostics[0]?.severity).toBe('error');
+ expect(asError.errorCount).toBe(1);
+ });
+
+ test('a folder scope restricts file findings to sources under it', async () => {
+ seedDoc('top', '# Top\n\n[a](./top-file.pdf)\n');
+ seedDoc('sub/inner', '# Inner\n\n[b](./inner-file.pdf)\n');
+
+ const result = await runValidationAudit(createProjectValidators(deps()), { targetPath: 'sub' });
+
+ expect(result.files.map((f) => f.file)).toEqual(['sub/inner.md']);
+ expect(result.files[0]?.diagnostics[0]?.localTarget?.resolvedTarget).toBe('sub/inner-file.pdf');
+ });
+
+ test('a legacy validation payload with no localTarget field still parses', () => {
+ // A finding written before this field existed must remain valid on the wire.
+ const legacy = {
+ files: [
+ {
+ file: 'doc.md',
+ diagnostics: [
+ {
+ range: { start: { line: 2, character: 0 }, end: { line: 2, character: 0 } },
+ severity: 'warning',
+ source: 'links',
+ code: 'dead-link',
+ message: 'Link target "ghost" does not resolve to an existing document.',
+ linkTarget: 'ghost',
+ },
+ ],
+ },
+ ],
+ fileCount: 1,
+ errorCount: 0,
+ warningCount: 1,
+ warnings: [],
+ };
+ expect(ValidationAuditResponseSchema.parse(legacy)).toEqual(legacy);
+ });
});
describe('toValidationCountsPlane', () => {
diff --git a/packages/server/src/lint/validation-audit.ts b/packages/server/src/lint/validation-audit.ts
index 2e9334c6f..9e2ade664 100644
--- a/packages/server/src/lint/validation-audit.ts
+++ b/packages/server/src/lint/validation-audit.ts
@@ -18,17 +18,32 @@ import {
type ValidationDocCounts,
} from '@inkeep/open-knowledge-core';
import type { DerivedDocumentIndexApiPort } from '../derived-document-index.ts';
+import {
+ buildLocalTargetEvidence,
+ type LocalTargetAssessment,
+} from '../local-target-assessment.ts';
import { getLogger } from '../logger.ts';
import { AuditSupersededError, auditProject } from './audit.ts';
import type { AuditCache } from './audit-cache.ts';
type DeadLinksResult = Awaited<ReturnType<DerivedDocumentIndexApiPort['getDeadLinks']>>;
+type LocalTargetsResult = Awaited<
+ ReturnType<DerivedDocumentIndexApiPort['getLocalTargetAssessmentsForSources']>
+>;
interface ValidationDerivedIndexReader {
getDeadLinks(
admittedDocuments: Iterable<string>,
sourceDocumentNames?: readonly string[],
): DeadLinksResult | Promise<DeadLinksResult>;
+ /**
+ * Assessed local-target occurrences per source (all sources, or a scoped set).
+ * The links validator projects the unresolved ones — files, images, and
+ * reference-style targets — into the same plane as graph dead-links.
+ */
+ getLocalTargetAssessmentsForSources(
+ sourceDocumentNames?: readonly string[],
+ ): LocalTargetsResult | Promise<LocalTargetsResult>;
}
interface FileValidationResult {
@@ -236,19 +251,87 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator {
warnings: ['links validation unavailable: backlink index is not configured'],
};
}
+ const startGeneration = deps.auditGeneration?.();
+ const assertCurrent = (): void => {
+ if (deps.auditGeneration !== undefined && deps.auditGeneration() !== startGeneration) {
+ throw new AuditSupersededError();
+ }
+ };
const admitted = [...(await deps.admittedDocNames())];
const sourceFilter = scopedSourceDocNames(admitted, scope.targetPath);
// `getDeadLinks` reads an empty source filter as "no filter" — a scope
// matching zero docs must short-circuit here or it would silently widen
// back to the whole project.
if (sourceFilter !== undefined && sourceFilter.length === 0) {
+ assertCurrent();
return { files: [], fileCount: 0, warnings: [] };
}
const deadLinks = await deps.derivedDocumentIndex.getDeadLinks(admitted, sourceFilter);
const byFile = new Map<string, ValidationDiagnostic[]>();
+ const push = (file: string, diagnostic: ValidationDiagnostic): void => {
+ const diagnostics = byFile.get(file) ?? [];
+ diagnostics.push(diagnostic);
+ byFile.set(file, diagnostics);
+ };
+
+ // The canonical classification comes from the assessment plane, so it is
+ // computed FIRST and the graph plane fills only what it does not cover.
+ // Both planes see the same occurrence; whichever reports it must be the
+ // one every consumer reads, and the assessment row is a strict superset —
+ // same message, plus the `localTarget` evidence (definition pointer,
+ // resolution method, fallback target) and the same create-page
+ // `linkTarget`. Reconciling by source form, as this once did, is a
+ // hand-maintained rule that drifts the moment either plane learns a form.
+ const localTargetDiagnostics: Array<{ file: string; diagnostic: ValidationDiagnostic }> = [];
+ const documentTargetsFromAssessment = new Set<string>();
+ const resolvedTargetsFromAssessment = new Set<string>();
+ const warnings: string[] = [];
+ try {
+ const assessed =
+ await deps.derivedDocumentIndex.getLocalTargetAssessmentsForSources(sourceFilter);
+ for (const { source, assessments } of assessed) {
+ const file = deps.docFilePathFor(source) ?? `${source}.md`;
+ for (const assessment of assessments) {
+ const diagnostic = toLocalTargetDiagnostic(assessment, severity);
+ if (!diagnostic) continue;
+ localTargetDiagnostics.push({ file, diagnostic });
+ if (assessment.targetKind === 'document' && assessment.resolvedTarget !== null) {
+ documentTargetsFromAssessment.add(`${source}\0${assessment.resolvedTarget}`);
+ }
+ }
+ // A target the canonical classifier proved EXISTS is not a dead link,
+ // whatever the graph concluded. `assets/NOTICE` is the case: an
+ // extension-less href naming a real ordinary file, which the graph
+ // reads as a document. Suppressing here keeps Problems correct even
+ // if the graph was built before the file inventory had seeded.
+ for (const assessment of assessments) {
+ if (assessment.status === 'exact' && assessment.resolvedTarget !== null) {
+ resolvedTargetsFromAssessment.add(`${source}\0${assessment.resolvedTarget}`);
+ }
+ }
+ }
+ } catch (error) {
+ if (error instanceof AuditSupersededError) throw error;
+ getLogger('validation-audit').warn(
+ { err: error },
+ '[audit] local-target projection unavailable; preserving graph link findings',
+ );
+ const message = error instanceof Error ? error.message : String(error);
+ warnings.push(`local-target validation unavailable: ${message}`);
+ }
+
for (const { target, sources } of deadLinks) {
for (const occurrence of sources) {
+ const key = `${occurrence.source}\0${target}`;
+ // Already reported with richer evidence by the canonical classifier,
+ // or proven by it to exist and therefore not a dead link at all.
+ if (
+ occurrence.sourceForm !== 'wiki' &&
+ (documentTargetsFromAssessment.has(key) || resolvedTargetsFromAssessment.has(key))
+ ) {
+ continue;
+ }
// A source indexed from a live CRDT doc may not be on disk yet — fall
// back to the default extension so the finding still names a file.
const file = deps.docFilePathFor(occurrence.source) ?? `${occurrence.source}.md`;
@@ -256,8 +339,7 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator {
// degrade to the start of the doc rather than dropping the finding.
const line = occurrence.line ?? 0;
const character = occurrence.column ?? 0;
- const diagnostics = byFile.get(file) ?? [];
- diagnostics.push({
+ push(file, {
range: { start: { line, character }, end: { line, character } },
severity,
source: 'links',
@@ -267,18 +349,93 @@ function createLinksValidator(deps: ValidationAuditDeps): ProjectValidator {
// create-the-missing-page affordance never parses the message.
linkTarget: target,
});
- byFile.set(file, diagnostics);
}
}
+
+ for (const { file, diagnostic } of localTargetDiagnostics) push(file, diagnostic);
+
+ assertCurrent();
+
return {
files: [...byFile.entries()].map(([file, diagnostics]) => ({ file, diagnostics })),
fileCount: 0,
- warnings: [],
+ warnings,
};
},
};
}
+/** Human-readable message for a local-target finding, by reason, kind, and role. */
+function localTargetMessage(assessment: LocalTargetAssessment, shown: string): string {
+ const isImage = assessment.occurrence.role === 'image';
+ // An unresolvable target never resolved to any identity (root escape, empty,
+ // unsupported form) — distinct wording from a resolved-but-absent target. A
+ // 'unknown' kind only ever arrives with this reason.
+ if (assessment.reason === 'unresolvable') {
+ return isImage
+ ? `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.targetKind === 'file') {
+ return isImage
+ ? `Image target "${shown}" does not resolve to an existing file.`
+ : `Link target "${shown}" does not resolve to an existing file.`;
+ }
+ return `Link target "${shown}" does not resolve to an existing document.`;
+}
+
+/**
+ * Project one local-target assessment onto a validation diagnostic, or null when
+ * it is not a finding. Exact targets are dropped (not a problem), and so are
+ * forms with no local-target wire spelling — `buildLocalTargetEvidence` owns
+ * that decision.
+ *
+ * Cross-plane de-duplication is NOT decided here. The caller runs this plane
+ * first and suppresses the graph plane for any document target it already
+ * reported, so one occurrence yields one finding without either plane guessing
+ * at the other's coverage.
+ */
+function toLocalTargetDiagnostic(
+ assessment: LocalTargetAssessment,
+ severity: 'error' | 'warning',
+): ValidationDiagnostic | null {
+ // `reason` is null exactly when the target is `exact`, so this both drops
+ // resolved targets and narrows `reason` to a concrete failure below.
+ if (assessment.reason === null) return null;
+ const { occurrence, targetKind } = assessment;
+
+ // Wiki forms are classified but do not project onto the local-target wire
+ // surfaces: a wiki document link is a graph edge, and a file-shaped wiki embed
+ // resolves by vault-wide basename under its own contract.
+ // `buildLocalTargetEvidence` owns that decision, so reading its null is the
+ // single check rather than a second form predicate here that could drift.
+ const localTarget = buildLocalTargetEvidence(assessment, assessment.reason);
+ if (localTarget === null) return null;
+
+ const shown = assessment.resolvedTarget ?? occurrence.href;
+ const line = occurrence.line;
+ const character = occurrence.column;
+ const diagnostic: ValidationDiagnostic = {
+ range: { start: { line, character }, end: { line, character } },
+ severity,
+ source: 'links',
+ code: 'dead-link',
+ message: localTargetMessage(assessment, shown),
+ localTarget,
+ };
+ // Create page is document-only: only a missing document carries `linkTarget`,
+ // and a document target always has a resolved docName. Files, images, and
+ // unresolvable targets never offer it.
+ if (
+ targetKind === 'document' &&
+ assessment.status === 'missing' &&
+ assessment.resolvedTarget !== null
+ ) {
+ diagnostic.linkTarget = assessment.resolvedTarget;
+ }
+ return diagnostic;
+}
+
/**
* Translate a path scope into the dead-link source filter: a doc-file path
* narrows to that one doc, anything else is a folder prefix over the admitted
diff --git a/packages/server/src/local-target-assessment.test.ts b/packages/server/src/local-target-assessment.test.ts
new file mode 100644
index 000000000..164029f5c
--- /dev/null
+++ b/packages/server/src/local-target-assessment.test.ts
@@ -0,0 +1,420 @@
+import { describe, expect, test } from 'vitest';
+import {
+ assessLocalTargetOccurrences,
+ assessLocalTargets,
+ type LocalTargetInventory,
+ toForwardLinkLocalTargets,
+} from './local-target-assessment.ts';
+import { extractLocalTargetOccurrences } from './local-target-occurrences.ts';
+
+/**
+ * A content-scoped inventory backed by explicit membership sets — a boundary
+ * fake, not a mock: assertions check the assessment the module computes FROM the
+ * membership, so a fake that reported the wrong membership would fail the tests.
+ */
+function inventory(opts?: {
+ docs?: Iterable<string>;
+ files?: Iterable<string>;
+ tolerant?: Record<string, string>;
+}): LocalTargetInventory {
+ const docs = new Set(opts?.docs ?? []);
+ const files = new Set(opts?.files ?? []);
+ const tolerant = opts?.tolerant;
+ const base: LocalTargetInventory = {
+ hasDocument: (docName) => docs.has(docName),
+ hasFile: (filePath) => files.has(filePath),
+ };
+ if (!tolerant) return base;
+ return { ...base, resolveTolerantDocument: (docName) => tolerant[docName] ?? null };
+}
+
+const SOURCE = 'notes/index';
+
+/** Assess a single-occurrence document and return that occurrence's assessment. */
+function assessOne(markdown: string, inv: LocalTargetInventory) {
+ const [assessment, ...rest] = assessLocalTargets(markdown, SOURCE, inv);
+ expect(rest).toEqual([]);
+ return assessment;
+}
+
+describe('canonical assessment per authored form', () => {
+ test('inline markdown link to an existing document is exact', () => {
+ const a = assessOne('[see](./guide.md)', inventory({ docs: ['notes/guide'] }));
+ expect(a).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'notes/guide',
+ status: 'exact',
+ reason: null,
+ resolutionMethod: 'source-relative',
+ fallbackTarget: null,
+ });
+ expect(a?.occurrence.role).toBe('link');
+ });
+
+ test('inline markdown image resolves to a file, not a document', () => {
+ const a = assessOne('![alt](./diagram.png)', inventory({ files: ['notes/diagram.png'] }));
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'notes/diagram.png',
+ status: 'exact',
+ reason: null,
+ });
+ // The image is a role on the occurrence, distinct from the file target kind.
+ expect(a?.occurrence.role).toBe('image');
+ });
+
+ test('HTML img src resolves to a file target', () => {
+ const a = assessOne('<img src="./photo.png">', inventory({ files: ['notes/photo.png'] }));
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'notes/photo.png',
+ status: 'exact',
+ });
+ });
+
+ test('reference-style use assesses its shared definition destination', () => {
+ const a = assessOne('[a][d]\n\n[d]: ./manual.pdf', inventory({ files: ['notes/manual.pdf'] }));
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'notes/manual.pdf',
+ status: 'exact',
+ reason: null,
+ });
+ expect(a?.occurrence.sourceForm).toBe('markdown-reference');
+ });
+});
+
+describe('document vs ordinary-file membership', () => {
+ test('an extension-less link resolves to an exact ordinary file when no document exists', () => {
+ const a = assessOne('[license](../LICENSE)', inventory({ files: ['LICENSE'] }));
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'LICENSE',
+ status: 'exact',
+ reason: null,
+ });
+ });
+
+ test('an exact document wins when both extension-less target kinds exist', () => {
+ const a = assessOne(
+ '[target](./guide)',
+ inventory({ docs: ['notes/guide'], files: ['notes/guide'] }),
+ );
+ expect(a).toMatchObject({ targetKind: 'document', status: 'exact' });
+ });
+
+ test('an extension-less image is assessed as a file', () => {
+ const a = assessOne('![badge](./BADGE)', inventory({ files: ['notes/BADGE'] }));
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'notes/BADGE',
+ status: 'exact',
+ });
+ });
+
+ test('the same extension-less href is cached independently for link and image roles', () => {
+ const assessments = assessLocalTargets(
+ '[guide](./guide) ![guide](./guide)',
+ SOURCE,
+ inventory({ docs: ['notes/guide'], files: ['notes/guide'] }),
+ );
+ expect(assessments.map(({ targetKind }) => targetKind)).toEqual(['document', 'file']);
+ expect(assessments.every(({ status }) => status === 'exact')).toBe(true);
+ });
+
+ test('a document href absent from the admitted set is a missing document', () => {
+ const a = assessOne('[see](./guide.md)', inventory({ docs: [], files: ['notes/guide'] }));
+ expect(a).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'notes/guide',
+ status: 'missing',
+ reason: 'no-such-doc',
+ });
+ });
+
+ test('a file href absent from the file inventory is a missing file', () => {
+ const a = assessOne(
+ '[data](./report.csv)',
+ inventory({ docs: ['notes/report.csv'], files: [] }),
+ );
+ expect(a).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'notes/report.csv',
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ });
+
+ test('document and file oracles are consulted independently for the same document', () => {
+ // A doc target is never satisfied by a same-named entry in the file inventory.
+ const a = assessOne('[see](./guide.md)', inventory({ files: ['notes/guide'] }));
+ expect(a?.status).toBe('missing');
+ expect(a?.reason).toBe('no-such-doc');
+ });
+
+ test('root-relative resolution records its own method', () => {
+ const a = assessOne('[x](/root/file.md)', inventory({ docs: ['root/file'] }));
+ expect(a).toMatchObject({
+ resolvedTarget: 'root/file',
+ status: 'exact',
+ resolutionMethod: 'root-relative',
+ });
+ });
+});
+
+describe('exact existence is authoritative; tolerant navigation is explicit, never exact', () => {
+ test('a missing document with a tolerant match is fallback, not exact', () => {
+ const a = assessOne(
+ '[g](./guide.md)',
+ inventory({ docs: [], tolerant: { 'notes/guide': 'guides/guide' } }),
+ );
+ expect(a).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'notes/guide',
+ status: 'fallback',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ fallbackTarget: 'guides/guide',
+ });
+ });
+
+ test('an exact hit is never downgraded even when a tolerant match also exists', () => {
+ const a = assessOne(
+ '[g](./guide.md)',
+ inventory({ docs: ['notes/guide'], tolerant: { 'notes/guide': 'somewhere/else' } }),
+ );
+ expect(a?.status).toBe('exact');
+ expect(a?.fallbackTarget).toBeNull();
+ expect(a?.resolutionMethod).toBe('source-relative');
+ });
+
+ test('files have no tolerant fallback — an absent file stays missing', () => {
+ const a = assessOne(
+ '![p](./photo.png)',
+ inventory({ files: [], tolerant: { 'notes/photo.png': 'anything' } }),
+ );
+ expect(a?.status).toBe('missing');
+ expect(a?.reason).toBe('no-such-file');
+ expect(a?.fallbackTarget).toBeNull();
+ });
+});
+
+describe('ignored and escaping targets are classified without admitting them', () => {
+ test('a traversal-escaping document path is unresolvable, not missing', () => {
+ // Never probes the filesystem for an out-of-scope path: the resolver refuses it.
+ const a = assessOne('[x](../../../../etc/passwd)', inventory());
+ expect(a).toMatchObject({
+ targetKind: 'unknown',
+ resolvedTarget: null,
+ status: 'unresolvable',
+ reason: 'unresolvable',
+ resolutionMethod: 'none',
+ });
+ });
+
+ test('a traversal-escaping file path is unresolvable rather than a missing file', () => {
+ const a = assessOne('![x](../../../../etc/photo.png)', inventory());
+ expect(a).toMatchObject({ targetKind: 'file', resolvedTarget: null, status: 'unresolvable' });
+ });
+
+ test('a same-named file entry never satisfies an escaping href', () => {
+ // Guards against resolving the last segment against the inventory after an escape.
+ const a = assessOne('[x](../../secrets/passwd)', inventory({ files: ['secrets/passwd'] }));
+ expect(a?.status).toBe('unresolvable');
+ });
+});
+
+describe('repeated occurrences share existence work while each keeps its range', () => {
+ test('the inventory is consulted once per distinct href, and every occurrence is assessed', () => {
+ const md = 'One [a](./x.md) two [b](./x.md) three [c](./y.md).';
+ let docLookups = 0;
+ const inv: LocalTargetInventory = {
+ hasDocument: (docName) => {
+ docLookups += 1;
+ return docName === 'notes/x';
+ },
+ hasFile: () => false,
+ };
+ const assessments = assessLocalTargetOccurrences(
+ extractLocalTargetOccurrences(md),
+ SOURCE,
+ inv,
+ );
+ // Three occurrences, two distinct hrefs → two existence lookups.
+ expect(assessments).toHaveLength(3);
+ expect(docLookups).toBe(2);
+ // Every occurrence retains its own exact source range.
+ for (const a of assessments) {
+ expect(md.slice(a.occurrence.range.start, a.occurrence.range.end)).toContain(
+ a.occurrence.href,
+ );
+ }
+ const toX = assessments.filter((a) => a.resolvedTarget === 'notes/x');
+ expect(toX).toHaveLength(2);
+ expect(toX.every((a) => a.status === 'exact')).toBe(true);
+ expect(toX[0]?.occurrence.range).not.toEqual(toX[1]?.occurrence.range);
+ });
+});
+
+describe('scope: classification is total across every recognized form', () => {
+ test('wiki link and wiki embed occurrences are classified alongside markdown forms', () => {
+ // A form the classifier refuses to answer for is a hole some surface fills
+ // by guessing, which is how four planes came to disagree about one link.
+ // Whether a classified form reaches a given surface is decided at the
+ // projection boundary, not by declining to classify it.
+ const md = 'A [[Some Page]] and an embed ![[photo.png]] plus [real](./r.md).';
+ const assessments = assessLocalTargets(md, SOURCE, inventory({ docs: ['notes/r'] }));
+ expect(assessments.map((a) => a.occurrence.sourceForm)).toEqual([
+ 'wiki-link',
+ 'wiki-embed',
+ 'markdown-inline',
+ ]);
+ });
+
+ test('an extension-less wiki embed is document-shaped, not file-shaped', () => {
+ // `![[Note]]` transcludes a document. The image ROLE it carries is a
+ // rendering fact, not a target-kind one, so the role-based file shortcut
+ // that governs markdown and HTML images must not claim it.
+ const a = assessLocalTargets('![[targets/missing-embed]]', SOURCE, inventory())[0];
+ expect(a).toMatchObject({
+ targetKind: 'document',
+ // Vault-root-relative, not source-relative — `SOURCE` is `notes/index`,
+ // and the document graph resolves the same target the same way.
+ resolvedTarget: 'targets/missing-embed',
+ status: 'missing',
+ reason: 'no-such-doc',
+ });
+ });
+
+ test('an extension-bearing wiki embed stays file-shaped', () => {
+ const a = assessLocalTargets(
+ '![[photo.png]]',
+ SOURCE,
+ inventory({ files: ['notes/photo.png'] }),
+ )[0];
+ expect(a).toMatchObject({ targetKind: 'file', status: 'exact' });
+ });
+
+ test('a wiki target resolves entirely against the vault root, fallback included', () => {
+ // The markdown file fallback is source-relative. Running it for a wiki form
+ // would answer one occurrence with two resolution origins: the document
+ // identity from the vault root, the file probe from the source directory.
+ // An extension-less wiki target is a document by contract, so no fallback.
+ const a = assessLocalTargets(
+ '[[assets/NOTICE]]',
+ SOURCE,
+ // Source-relative would look for `notes/assets/NOTICE`; root-relative
+ // finds `assets/NOTICE`. Both are present, so a wrong origin would be
+ // invisible unless the assertion pins the KIND.
+ inventory({ files: ['assets/NOTICE', 'notes/assets/NOTICE'] }),
+ )[0];
+ expect(a).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'assets/NOTICE',
+ status: 'missing',
+ });
+ });
+
+ test('the same extension-less href resolves per form, not per href', () => {
+ // A markdown image of `assets/NOTICE` is a file; a wiki embed of it is a
+ // document. Sharing one cache entry across forms would collapse them.
+ const md = '![md image](assets/NOTICE)\n\n![[assets/NOTICE]]\n';
+ const rows = assessLocalTargets(md, SOURCE, inventory({ files: ['assets/NOTICE'] }));
+ expect(rows.map((r) => [r.occurrence.sourceForm, r.targetKind])).toEqual([
+ ['markdown-inline', 'file'],
+ ['wiki-embed', 'document'],
+ ]);
+ });
+});
+
+describe('toForwardLinkLocalTargets — Links panel Local files projection', () => {
+ test('projects file and image references but excludes document graph edges and wiki forms', () => {
+ const md = [
+ '[report](./report.pdf)',
+ '![logo](./logo.png)',
+ '<img src="./pic.png">',
+ '[other](./other.md)',
+ '[[wiki]]',
+ ].join('\n');
+ const rows = toForwardLinkLocalTargets(
+ assessLocalTargets(
+ md,
+ SOURCE,
+ inventory({ docs: ['notes/other'], files: ['notes/logo.png'] }),
+ ),
+ );
+
+ // Three local resources; the document link and the wiki link are not here.
+ expect(rows.map((r) => r.href).sort()).toEqual(['./logo.png', './pic.png', './report.pdf']);
+ expect(rows.some((r) => r.targetKind === 'document')).toBe(false);
+
+ const report = rows.find((r) => r.href === './report.pdf');
+ expect(report).toMatchObject({
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ targetKind: 'file',
+ resolvedTarget: 'notes/report.pdf',
+ status: 'missing',
+ reason: 'no-such-file',
+ definition: null,
+ });
+ // The range travels byte-exact, so the panel can navigate to the occurrence.
+ expect(report && md.slice(report.range.start, report.range.end)).toBe('[report](./report.pdf)');
+
+ expect(rows.find((r) => r.href === './logo.png')).toMatchObject({
+ role: 'image',
+ targetKind: 'file',
+ status: 'exact',
+ reason: null,
+ });
+ expect(rows.find((r) => r.href === './pic.png')).toMatchObject({
+ role: 'image',
+ sourceForm: 'html-img',
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ });
+
+ test('a reference-style file use carries its shared definition pointer', () => {
+ const md = '[grab][data]\n\n[data]: ./data.csv\n';
+ const rows = toForwardLinkLocalTargets(assessLocalTargets(md, SOURCE, inventory({})));
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ status: 'missing',
+ reason: 'no-such-file',
+ resolvedTarget: 'notes/data.csv',
+ definition: { label: 'data', line: 2 },
+ });
+ });
+
+ test('repeated references to one file yield one row each, never a deduplicated edge', () => {
+ const md = '![a](./x.png) and again ![a](./x.png)';
+ const rows = toForwardLinkLocalTargets(assessLocalTargets(md, SOURCE, inventory({})));
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.href === './x.png' && r.status === 'missing')).toBe(true);
+ // Distinct occurrences keep distinct ranges — no silent collapse.
+ expect(rows[0]?.range).not.toEqual(rows[1]?.range);
+ });
+
+ test('an image whose path escapes the content root is surfaced as unresolvable, not dropped', () => {
+ const rows = toForwardLinkLocalTargets(
+ assessLocalTargets('![up](../../secret.png)', SOURCE, inventory({})),
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ role: 'image',
+ status: 'unresolvable',
+ resolvedTarget: null,
+ });
+ });
+
+ test('a document link and an unresolvable link produce no Local files rows', () => {
+ const md = '[doc](./other.md) and [[wiki]] and [esc](../../nowhere)';
+ const rows = toForwardLinkLocalTargets(
+ assessLocalTargets(md, SOURCE, inventory({ docs: ['notes/other'] })),
+ );
+ expect(rows).toEqual([]);
+ });
+});
diff --git a/packages/server/src/local-target-assessment.ts b/packages/server/src/local-target-assessment.ts
new file mode 100644
index 000000000..9b68345a7
--- /dev/null
+++ b/packages/server/src/local-target-assessment.ts
@@ -0,0 +1,506 @@
+/**
+ * Assess extracted local-target occurrences against one content-scoped
+ * inventory: resolve each to a canonical project identity, decide whether that
+ * identity exists, and record how the answer was reached.
+ *
+ * Recognition and positioning are upstream (`local-target-occurrences.ts`); this
+ * layer owns resolution, classification, and existence. Exact project-local
+ * existence is authoritative — an occurrence is `exact` only when its authored
+ * path resolves exactly to an existing target. Tolerant navigation (slug /
+ * basename / folder-index, computed elsewhere) is offered through the optional
+ * inventory oracle and recorded as `fallback`, never blessed as `exact`, so a
+ * mistyped path that merely happens to be navigable is not silently validated.
+ *
+ * The inventory is injected because document membership and ordinary-file
+ * membership live in different places (an in-memory admitted-doc set vs the
+ * watcher's all-files inventory) and both stay behind `ContentFilter` and
+ * symlink/alias identity in the concrete implementation. This module is pure
+ * over that interface.
+ *
+ * EVERY recognized form is assessed, wiki included. Recognition is consolidated
+ * behind one grammar, so an occurrence the extractor sees is one some surface
+ * will report on, and a form this layer refuses to answer for is a hole that
+ * surface fills by guessing — which is how reporting planes come to disagree
+ * about the same authored link. Classification is therefore total.
+ *
+ * What reaches a given SURFACE is a separate, narrower question, answered at the
+ * projection boundary below (`toForwardLinkLocalTargets`,
+ * `buildLocalTargetEvidence`): wiki document links are graph edges the
+ * `forwardLinks` union already carries, and file-shaped wiki embeds resolve by
+ * vault-wide basename under their own contract, so neither projects onto the
+ * local-target wire surfaces. Classify everything; project selectively.
+ */
+
+import {
+ assertNeverLinkTarget,
+ type BrokenLinkReason,
+ classifyMarkdownHref,
+ classifyWikiLinkTarget,
+ type ForwardLinkLocalTarget,
+ type LocalTargetDiagnosticEvidence,
+ type LocalTargetSourceForm,
+ resolveAssetProjectPath,
+ toWikiLinkSlug,
+} from '@inkeep/open-knowledge-core';
+import {
+ extractLocalTargetOccurrences,
+ type LocalTargetOccurrence,
+ type OccurrenceSourceForm,
+} from './local-target-occurrences.ts';
+
+/**
+ * What a target resolves to on disk. `image` and `link` are the occurrence
+ * ROLE, not a kind — an image resolves to a `file`. `unknown` is a target with
+ * no derivable project identity (an escaping or unsupported path).
+ */
+type LocalTargetKind = 'document' | 'file' | 'unknown';
+
+/**
+ * Outcome of assessing one occurrence against the inventory.
+ * - `exact` — the authored path resolves exactly to an existing target.
+ * - `fallback` — the authored path is not an exact hit, but tolerant navigation
+ * reaches an existing target; the authored path is NOT blessed as valid.
+ * - `missing` — resolves to a canonical identity that does not exist.
+ * - `unresolvable` — cannot resolve to any project identity (root escape, empty,
+ * or unsupported relative form).
+ */
+type LocalTargetStatus = 'exact' | 'fallback' | 'missing' | 'unresolvable';
+
+/**
+ * Failure reason for an unresolved target, aligned with core's
+ * `BrokenLinkReason`. Null when the target resolves (`exact`); present for
+ * `fallback` too, because a fallback still means the authored path was broken.
+ */
+type LocalTargetReason = 'no-such-doc' | 'no-such-file' | 'unresolvable';
+
+/**
+ * How the canonical identity (or the fallback) was derived. Resolution
+ * provenance keeps a tolerant hit distinguishable from an exact one, so strict
+ * audit and tolerant navigation can never silently disagree.
+ */
+type LocalTargetResolutionMethod = 'source-relative' | 'root-relative' | 'tolerant' | 'none';
+
+/**
+ * Content-scoped existence oracle. The concrete implementation composes the
+ * admitted-document set with the watcher's all-files inventory behind
+ * `ContentFilter` and realpath/alias identity; this contract exposes only the
+ * two membership questions the assessment asks.
+ */
+export interface LocalTargetInventory {
+ /** Whether an extension-less, content-root-relative docName is an admitted live document. */
+ hasDocument(docName: string): boolean;
+ /** Whether an extension-bearing, content-root-relative file path is an admitted ordinary file. */
+ hasFile(contentRootRelativePath: string): boolean;
+ /**
+ * Optional tolerant-navigation resolver: when the exact docName is absent,
+ * return an existing docName reachable by tolerant navigation, or null. Used
+ * only to record `fallback` provenance — never to mark a wrong authored path
+ * `exact`.
+ */
+ resolveTolerantDocument?(docName: string, sourceDocName: string): string | null;
+}
+
+/** Build the deterministic tolerant document lookup shared by index and write-time assessment. */
+export function createTolerantDocumentResolver(
+ documentNames: Iterable<string>,
+): (docName: string) => string | null {
+ const documents = new Set(documentNames);
+ const bySlug = new Map<string, string>();
+ for (const docName of documents) {
+ const slug = toWikiLinkSlug(docName);
+ if (slug && !bySlug.has(slug)) bySlug.set(slug, docName);
+ }
+ const byBasename = new Map<string, string>();
+ for (const docName of [...documents].sort((a, b) => a.localeCompare(b))) {
+ const leaf = docName.slice(docName.lastIndexOf('/') + 1);
+ const slug = toWikiLinkSlug(leaf);
+ if (slug && !byBasename.has(slug)) byBasename.set(slug, docName);
+ }
+ return (docName) => {
+ 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 leaf = docName.slice(docName.lastIndexOf('/') + 1);
+ const legacyFolderNote = `${docName}/${leaf}`;
+ if (documents.has(legacyFolderNote)) return legacyFolderNote;
+ if (!docName.includes('/') && slug) return byBasename.get(slug) ?? null;
+ return null;
+ };
+}
+
+export interface LocalTargetAssessment {
+ /** The occurrence this assesses — carries role, source form, authored href, and exact range. */
+ occurrence: LocalTargetOccurrence;
+ targetKind: LocalTargetKind;
+ /**
+ * Canonical project identity the AUTHORED href resolves to (docName for a
+ * document, content-root-relative path for a file), or null when unresolvable.
+ * For `missing`/`fallback` this is the identity that does not exist; for
+ * `exact` it exists.
+ */
+ resolvedTarget: string | null;
+ status: LocalTargetStatus;
+ /** Failure reason for `missing`/`fallback`/`unresolvable`; null for `exact`. */
+ reason: LocalTargetReason | null;
+ resolutionMethod: LocalTargetResolutionMethod;
+ /**
+ * For `fallback` only: the existing target tolerant navigation reaches.
+ * Distinct from `resolvedTarget` (the authored, non-existent identity) so a
+ * wrong authored path is never presented as exact. Null otherwise.
+ */
+ fallbackTarget: string | null;
+}
+
+/** Everything in an assessment except the per-occurrence identity — shared across occurrences with the same href. */
+type SharedAssessment = Omit<LocalTargetAssessment, 'occurrence'>;
+
+/** A leading `/` is a content-root path; anything else resolves against the source doc's directory. */
+function methodForHref(href: string): 'source-relative' | 'root-relative' {
+ return href.trim().startsWith('/') ? 'root-relative' : 'source-relative';
+}
+
+const UNRESOLVABLE: SharedAssessment = {
+ targetKind: 'unknown',
+ resolvedTarget: null,
+ status: 'unresolvable',
+ reason: 'unresolvable',
+ resolutionMethod: 'none',
+ fallbackTarget: null,
+};
+
+function assessDocument(
+ docName: string,
+ href: string,
+ sourceDocName: string,
+ inventory: LocalTargetInventory,
+ exactExists?: boolean,
+): SharedAssessment {
+ if (exactExists ?? inventory.hasDocument(docName)) {
+ return {
+ targetKind: 'document',
+ resolvedTarget: docName,
+ status: 'exact',
+ reason: null,
+ resolutionMethod: methodForHref(href),
+ fallbackTarget: null,
+ };
+ }
+ const fallback = inventory.resolveTolerantDocument?.(docName, sourceDocName) ?? null;
+ if (fallback) {
+ return {
+ targetKind: 'document',
+ resolvedTarget: docName,
+ status: 'fallback',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ fallbackTarget: fallback,
+ };
+ }
+ return {
+ targetKind: 'document',
+ resolvedTarget: docName,
+ status: 'missing',
+ reason: 'no-such-doc',
+ resolutionMethod: methodForHref(href),
+ fallbackTarget: null,
+ };
+}
+
+function assessFile(
+ assetUrl: string,
+ href: string,
+ sourceDocName: string,
+ inventory: LocalTargetInventory,
+): SharedAssessment {
+ const filePath = resolveAssetProjectPath(assetUrl, sourceDocName);
+ if (filePath === null) {
+ // `../` overshoot past the content root — no project-local path.
+ return { ...UNRESOLVABLE, targetKind: 'file' };
+ }
+ if (inventory.hasFile(filePath)) {
+ return {
+ targetKind: 'file',
+ resolvedTarget: filePath,
+ status: 'exact',
+ reason: null,
+ resolutionMethod: methodForHref(href),
+ fallbackTarget: null,
+ };
+ }
+ // Ordinary files have no tolerant-navigation fallback (that affordance is
+ // document-only), so an absent file is simply missing.
+ return {
+ targetKind: 'file',
+ resolvedTarget: filePath,
+ status: 'missing',
+ reason: 'no-such-file',
+ resolutionMethod: methodForHref(href),
+ fallbackTarget: null,
+ };
+}
+
+/**
+ * Wiki forms resolve their target against the vault root, not the source doc.
+ * Exhaustive so a new `OccurrenceSourceForm` member fails to compile here too,
+ * not just in `diagnosticSourceForm` — a form routed through the wrong resolver
+ * would type-check while resolving against the wrong base.
+ */
+function isWikiForm(sourceForm: OccurrenceSourceForm): boolean {
+ switch (sourceForm) {
+ case 'wiki-link':
+ case 'wiki-embed':
+ return true;
+ case 'markdown-inline':
+ case 'markdown-reference':
+ case 'html-img':
+ return false;
+ default: {
+ const unreachable: never = sourceForm;
+ return unreachable;
+ }
+ }
+}
+
+/**
+ * Resolve + assess one authored href. Returns null when the href is not a local
+ * target at all (external / anchor) — upstream extraction already excludes those,
+ * so this is a total-function branch, not a live path.
+ */
+function assessHref(
+ href: string,
+ role: LocalTargetOccurrence['role'],
+ sourceForm: OccurrenceSourceForm,
+ sourceDocName: string,
+ inventory: LocalTargetInventory,
+): SharedAssessment | null {
+ // Wiki targets are vault-root-relative, not source-relative: `[[targets/x]]`
+ // in `notes/index` names `targets/x`, not `notes/targets/x`. The document
+ // graph has always resolved them with `classifyWikiLinkTarget`, so using the
+ // markdown resolver here would make the two planes disagree about where the
+ // same authored wiki link points — a fresh instance of the very divergence
+ // this contract exists to close, and invisible from a root-level source doc
+ // where the two resolutions coincide.
+ const classified = isWikiForm(sourceForm)
+ ? classifyWikiLinkTarget(href, null)
+ : classifyMarkdownHref(href, sourceDocName);
+ if (!classified) {
+ // A local candidate that resolves to nothing: empty, root-escaping, or an
+ // unsupported extension-less relative path.
+ return UNRESOLVABLE;
+ }
+ switch (classified.kind) {
+ case 'doc': {
+ // Extension-less hrefs are syntactically ambiguous: links usually name
+ // documents, while images always name files. Exact inventory membership
+ // resolves that ambiguity without guessing from a filename extension.
+ //
+ // A wiki EMBED carries the image role but not the image meaning: `![[Note]]`
+ // transcludes a document, and the canonical matrix expects an
+ // extension-less embed to report as a missing DOCUMENT. So the role-based
+ // shortcut is a markdown/HTML image rule, not a universal one — an
+ // extension-bearing embed still classifies as a file through the `asset`
+ // branch below, because `classifyMarkdownHref` never routes it here.
+ if (role === 'image' && !isWikiForm(sourceForm)) {
+ return assessFile(href, href, sourceDocName, inventory);
+ }
+ const documentExists = inventory.hasDocument(classified.docName);
+ // The file fallback is markdown-only, and deliberately so. It resolves
+ // SOURCE-relative, while a wiki target resolved vault-root-relative just
+ // above — running it for a wiki form would answer one occurrence with two
+ // different resolution origins. An extension-less wiki target is a
+ // document by contract anyway: `[[Note]]` names a note, and an
+ // extension-bearing one never reaches this branch.
+ if (!documentExists && !isWikiForm(sourceForm)) {
+ const file = assessFile(href, href, sourceDocName, inventory);
+ if (file.status === 'exact') return file;
+ }
+ return assessDocument(classified.docName, href, sourceDocName, inventory, documentExists);
+ }
+ case 'asset':
+ return assessFile(classified.url, href, sourceDocName, inventory);
+ case 'external':
+ case 'anchor':
+ return null;
+ default:
+ return assertNeverLinkTarget(classified);
+ }
+}
+
+/**
+ * Assess a document's occurrences, sharing existence work across repeated
+ * href/role pairs. Because the source document is fixed, a pair resolves
+ * identically every time, so its classification + inventory lookup is computed
+ * once and reused; every occurrence still yields its own assessment carrying
+ * its own range. Role is part of the key because an extension-less link may be
+ * a document while an image with the same href must be a file.
+ */
+export function assessLocalTargetOccurrences(
+ occurrences: readonly LocalTargetOccurrence[],
+ sourceDocName: string,
+ inventory: LocalTargetInventory,
+): LocalTargetAssessment[] {
+ // `undefined` = not computed yet; `null` = computed, not a local target.
+ const sharedByHrefAndRole = new Map<string, SharedAssessment | null>();
+ const assessments: LocalTargetAssessment[] = [];
+ for (const occurrence of occurrences) {
+ // Source form joins the key because an extension-less href resolves
+ // differently per form: a wiki embed of it is document-shaped while a
+ // markdown image of it is file-shaped.
+ const cacheKey = `${occurrence.role}\0${occurrence.sourceForm}\0${occurrence.href}`;
+ let shared = sharedByHrefAndRole.get(cacheKey);
+ if (shared === undefined) {
+ shared = assessHref(
+ occurrence.href,
+ occurrence.role,
+ occurrence.sourceForm,
+ sourceDocName,
+ inventory,
+ );
+ sharedByHrefAndRole.set(cacheKey, shared);
+ }
+ if (shared === null) continue;
+ assessments.push({ occurrence, ...shared });
+ }
+ return assessments;
+}
+
+/**
+ * Extract and assess a document's local targets in one pass — the per-document
+ * entry point a derived index or validator drives. Recognition never rewrites
+ * authored bytes, and assessment adds no filesystem access of its own beyond the
+ * injected inventory.
+ */
+export function assessLocalTargets(
+ markdown: string,
+ sourceDocName: string,
+ inventory: LocalTargetInventory,
+): LocalTargetAssessment[] {
+ return assessLocalTargetOccurrences(
+ extractLocalTargetOccurrences(markdown),
+ sourceDocName,
+ inventory,
+ );
+}
+
+/**
+ * Narrow an occurrence's 5-form union to the wire's 3-form subset, or null when
+ * the form has no wire spelling.
+ *
+ * Classification and projection are separate concerns. Every recognized
+ * occurrence gets a canonical classification — that is the whole point of the
+ * contract, and a form the classifier refuses to answer for is a hole some
+ * surface fills by guessing. What reaches a given SURFACE is a narrower,
+ * product-level question, and the wire's `LocalTargetSourceForm` has no wiki
+ * spelling, so wiki occurrences are classified but not projected here.
+ */
+function diagnosticSourceForm(form: OccurrenceSourceForm): LocalTargetSourceForm | null {
+ switch (form) {
+ case 'markdown-inline':
+ case 'markdown-reference':
+ case 'html-img':
+ return form;
+ case 'wiki-link':
+ case 'wiki-embed':
+ return null;
+ default: {
+ const unreachable: never = form;
+ return unreachable;
+ }
+ }
+}
+
+/**
+ * Whether an assessment carries onto the local-target wire surfaces (the Links
+ * panel's Local files rows and the `localTarget` evidence on a Problems row).
+ *
+ * Wiki forms are classified but not projected: wiki DOCUMENT links are graph
+ * edges the `forwardLinks` union already carries, and file-shaped wiki embeds
+ * (`![[assets/diagram.svg]]`) resolve by vault-wide basename under their own
+ * contract, which the canonical matrix documents as excluded from Problems and
+ * Local files. Projecting either would double-report a target the surfaces
+ * already handle correctly.
+ */
+export function isProjectableToLocalTargetSurfaces(occurrence: LocalTargetOccurrence): boolean {
+ return diagnosticSourceForm(occurrence.sourceForm) !== null;
+}
+
+/**
+ * Project one assessment onto the additive diagnostic evidence carried on both
+ * the audit plane and the write advisory, so every consumer describes a target
+ * identically (one identity, kind, role, form, reason, and — for a reference
+ * use — its shared definition pointer). The caller passes the already-narrowed
+ * non-null `reason` (an assessment's `reason` is null exactly when `exact`, and
+ * only non-exact occurrences become findings).
+ */
+export function buildLocalTargetEvidence(
+ assessment: LocalTargetAssessment,
+ reason: BrokenLinkReason,
+): LocalTargetDiagnosticEvidence | null {
+ const { occurrence } = assessment;
+ const sourceForm = diagnosticSourceForm(occurrence.sourceForm);
+ if (sourceForm === null) return null;
+ return {
+ href: occurrence.href,
+ targetKind: assessment.targetKind,
+ role: occurrence.role,
+ sourceForm,
+ resolvedTarget: assessment.resolvedTarget,
+ reason,
+ resolutionMethod: assessment.resolutionMethod,
+ ...(assessment.fallbackTarget === null ? {} : { fallbackTarget: assessment.fallbackTarget }),
+ ...(occurrence.reference
+ ? {
+ definition: {
+ line: occurrence.reference.definition.line,
+ label: occurrence.reference.definition.label,
+ },
+ }
+ : {}),
+ };
+}
+
+/**
+ * Project a source's assessments onto the Links panel's Local files rows: every
+ * local file or image reference, one row per authored occurrence. Documents are
+ * excluded because they are graph edges the `forwardLinks` union already carries;
+ * an identity-less unresolvable link (no file extension, so no derivable file
+ * identity) is excluded too. An image is inherently a file resource, so every
+ * image role is included even when its path escapes the content root. Repeated
+ * references are never deduplicated — each row keeps its own range so the panel
+ * can navigate to every occurrence rather than one collapsed edge.
+ */
+export function toForwardLinkLocalTargets(
+ assessments: readonly LocalTargetAssessment[],
+): ForwardLinkLocalTarget[] {
+ 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);
+ if (sourceForm === null) continue;
+ rows.push({
+ role: occurrence.role,
+ sourceForm,
+ targetKind: assessment.targetKind,
+ href: occurrence.href,
+ resolvedTarget: assessment.resolvedTarget,
+ status: assessment.status,
+ reason: assessment.reason,
+ resolutionMethod: assessment.resolutionMethod,
+ fallbackTarget: assessment.fallbackTarget,
+ range: { start: occurrence.range.start, end: occurrence.range.end },
+ line: occurrence.line,
+ column: occurrence.column,
+ definition: occurrence.reference
+ ? {
+ line: occurrence.reference.definition.line,
+ label: occurrence.reference.definition.label,
+ }
+ : null,
+ });
+ }
+ return rows;
+}
diff --git a/packages/server/src/local-target-index.test.ts b/packages/server/src/local-target-index.test.ts
new file mode 100644
index 000000000..0a5174032
--- /dev/null
+++ b/packages/server/src/local-target-index.test.ts
@@ -0,0 +1,482 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { createContentFilter } from './content-filter.ts';
+import { LocalTargetIndex, type LocalTargetIndexOptions } from './local-target-index.ts';
+
+const cleanups: Array<() => void> = [];
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+});
+
+/** In-memory index (no disk) — the pure incremental machinery. */
+function createIndex(): LocalTargetIndex {
+ const index = new LocalTargetIndex({ contentDir: join(tmpdir(), 'ok-lti-nonexistent') });
+ cleanups.push(() => index.close());
+ return index;
+}
+
+/** Disk-backed index over a fresh temp content dir. */
+function createDiskRig(
+ overrides: Omit<LocalTargetIndexOptions, 'contentDir' | 'contentFilter'> = {},
+): {
+ index: LocalTargetIndex;
+ contentDir: string;
+ write: (rel: string, md: string) => void;
+} {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-lti-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ const contentFilter = createContentFilter({ projectDir, contentDir });
+ const index = new LocalTargetIndex({ contentDir, contentFilter, ...overrides });
+ cleanups.push(() => {
+ index.close();
+ rmSync(projectDir, { recursive: true, force: true });
+ });
+ const write = (rel: string, md: string): void => {
+ const filePath = join(contentDir, rel);
+ mkdirSync(dirname(filePath), { recursive: true });
+ writeFileSync(filePath, md);
+ };
+ return { index, contentDir, write };
+}
+
+function statusOf(index: LocalTargetIndex, docName: string): string[] {
+ return index.getAssessments(docName).map((a) => a.status);
+}
+
+describe('LocalTargetIndex reverse-dependent freshness', () => {
+ test('creating a missing document target heals only its referencing sources', () => {
+ const index = createIndex();
+ index.setSource('src', 'See [x](target).\n');
+
+ const before = index.getAssessments('src');
+ expect(before).toHaveLength(1);
+ expect(before[0]).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'target',
+ status: 'missing',
+ reason: 'no-such-doc',
+ });
+ expect(index.getDocumentDependents('target')).toEqual(['src']);
+
+ // The target document appears; the referencing source is NOT re-authored.
+ index.setSource('target', '# Target\n');
+
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ resolvedTarget: 'target',
+ status: 'exact',
+ reason: null,
+ });
+ });
+
+ test('a source edit replaces its occurrences and removes ghost reverse dependents', () => {
+ const index = createIndex();
+ index.setSource('src', 'See [x](alpha).\n');
+ expect(index.getDocumentDependents('alpha')).toEqual(['src']);
+
+ // Re-author the source to point elsewhere.
+ index.setSource('src', 'See [x](beta).\n');
+ expect(index.getDocumentDependents('alpha')).toEqual([]);
+ expect(index.getDocumentDependents('beta')).toEqual(['src']);
+
+ // The abandoned target appearing must not touch the source anymore.
+ index.setSource('alpha', '# Alpha\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ resolvedTarget: 'beta',
+ status: 'missing',
+ });
+
+ // The current target appearing heals it.
+ index.setSource('beta', '# Beta\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ resolvedTarget: 'beta',
+ status: 'exact',
+ });
+ });
+
+ test('ordinary-file create and delete heal and break file references without re-authoring', () => {
+ const index = createIndex();
+ index.setSource('src', 'Download [pdf](assets/report.pdf).\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'file',
+ resolvedTarget: 'assets/report.pdf',
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ expect(index.getFileDependents('assets/report.pdf')).toEqual(['src']);
+
+ expect(index.setFileTarget('assets/report.pdf', true)).toBe(1);
+ expect(index.getAssessments('src')[0]).toMatchObject({ status: 'exact', reason: null });
+
+ expect(index.setFileTarget('assets/report.pdf', false)).toBe(1);
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+ });
+
+ test('an extension-less target retains both dependency candidates across precedence changes', () => {
+ const index = createIndex();
+ index.setSource('src', 'See [license](LICENSE).\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'document',
+ status: 'missing',
+ });
+ expect(index.getDocumentDependents('LICENSE')).toEqual(['src']);
+ expect(index.getFileDependents('LICENSE')).toEqual(['src']);
+
+ index.setFileTarget('LICENSE', true);
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'file',
+ status: 'exact',
+ });
+ index.setFileTarget('LICENSE', false);
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'document',
+ status: 'missing',
+ });
+ index.setFileTarget('LICENSE', true);
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'file',
+ status: 'exact',
+ });
+
+ index.setSource('LICENSE', '# License document\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'document',
+ status: 'exact',
+ });
+ index.removeSource('LICENSE');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ targetKind: 'file',
+ status: 'exact',
+ });
+ });
+
+ 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');
+ index.setFileTarget('assets/report.pdf', true);
+ const generation = index.generation;
+
+ // The watcher reports the same file again (content changed, still present).
+ expect(index.setFileTarget('assets/report.pdf', true)).toBe(0);
+ expect(index.generation).toBe(generation);
+ expect(index.getAssessments('src')[0]).toMatchObject({ status: 'exact' });
+ });
+
+ test('deleting a document target breaks its dependents', () => {
+ const index = createIndex();
+ index.setSource('target', '# Target\n');
+ index.setSource('src', 'See [x](target).\n');
+ expect(statusOf(index, 'src')).toEqual(['exact']);
+
+ index.removeSource('target');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-doc',
+ });
+ });
+
+ test('renaming a document target breaks old references and heals new ones atomically', () => {
+ const index = createIndex();
+ index.setSource('old', '# Old\n');
+ index.setSource('links-old', 'See [x](old).\n');
+ index.setSource('links-new', 'See [x](new).\n');
+ expect(statusOf(index, 'links-old')).toEqual(['exact']);
+ expect(statusOf(index, 'links-new')).toEqual(['missing']);
+
+ index.renameSource('old', 'new', '# New\n');
+
+ expect(index.getAssessments('links-old')[0]).toMatchObject({
+ resolvedTarget: 'old',
+ status: 'missing',
+ });
+ expect(index.getAssessments('links-new')[0]).toMatchObject({
+ resolvedTarget: 'new',
+ status: 'exact',
+ });
+ });
+
+ test('a target mutation reassesses exactly its reverse dependents, not the whole project', () => {
+ const index = createIndex();
+ const fanout = 40;
+ for (let i = 0; i < fanout; i++) {
+ index.setSource(`dependent-${i}`, 'Download [pdf](assets/shared.pdf).\n');
+ }
+ // Unrelated sources pointing at a different, still-missing file.
+ for (let i = 0; i < 15; i++) {
+ index.setSource(`unrelated-${i}`, 'Download [pdf](assets/other.pdf).\n');
+ }
+
+ const affected = index.setFileTarget('assets/shared.pdf', true);
+ expect(affected).toBe(fanout);
+ expect(index.getFileDependents('assets/shared.pdf')).toHaveLength(fanout);
+
+ // Every dependent healed; every unrelated source is untouched.
+ for (let i = 0; i < fanout; i++) {
+ expect(index.getAssessments(`dependent-${i}`)[0]).toMatchObject({ status: 'exact' });
+ }
+ for (let i = 0; i < 15; i++) {
+ expect(index.getAssessments(`unrelated-${i}`)[0]).toMatchObject({ status: 'missing' });
+ }
+ });
+
+ test('repeated references to one target keep every occurrence range and heal together', () => {
+ const index = createIndex();
+ index.setSource('src', 'A [one](assets/a.pdf) and again [two](assets/a.pdf).\n');
+ const before = index.getAssessments('src');
+ expect(before).toHaveLength(2);
+ expect(before.every((a) => a.status === 'missing')).toBe(true);
+ // Distinct ranges preserved per occurrence.
+ expect(before[0]?.occurrence.range).not.toEqual(before[1]?.occurrence.range);
+
+ expect(index.setFileTarget('assets/a.pdf', true)).toBe(1);
+ const after = index.getAssessments('src');
+ expect(after.every((a) => a.status === 'exact')).toBe(true);
+ expect(after[0]?.occurrence.range).toEqual(before[0]?.occurrence.range);
+ });
+
+ test('generation is monotonic across real changes and reflects healing', () => {
+ const index = createIndex();
+ const g0 = index.generation;
+ index.setSource('src', 'See [x](target).\n');
+ const g1 = index.generation;
+ expect(g1).toBeGreaterThan(g0);
+ index.setSource('target', '# Target\n');
+ expect(index.generation).toBeGreaterThan(g1);
+ });
+
+ test('an unrelated body edit with unchanged local-target evidence does not move generation', () => {
+ const index = createIndex();
+ index.setSource('src', '# Before\n\nSee [x](target).\n');
+ const generation = index.generation;
+
+ expect(index.setSource('src', '# After!\n\nSee [x](target).\n')).toBe(false);
+ expect(index.generation).toBe(generation);
+ });
+
+ test('records tolerant slug fallback provenance and follows create-delete healing', () => {
+ const index = createIndex();
+ index.setSource('src', 'See [x](guide).\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ status: 'missing',
+ resolvedTarget: 'guide',
+ fallbackTarget: null,
+ });
+
+ index.setSource('Guide', '# Guide\n');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ status: 'fallback',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ resolvedTarget: 'guide',
+ fallbackTarget: 'Guide',
+ });
+ expect(index.getDocumentDependents('Guide')).toEqual(['src']);
+
+ index.removeSource('Guide');
+ expect(index.getAssessments('src')[0]).toMatchObject({
+ status: 'missing',
+ fallbackTarget: null,
+ });
+ });
+
+ test('records canonical folder-index and bare-basename fallbacks', () => {
+ const index = createIndex();
+ index.setSource('guides/index', '# Guides\n');
+ index.setSource('nested/analysis', '# Analysis\n');
+ index.setSource('src', 'See [folder](guides) and [bare](analysis).\n');
+
+ expect(index.getAssessments('src').map((assessment) => assessment.fallbackTarget)).toEqual([
+ 'guides/index',
+ 'nested/analysis',
+ ]);
+ expect(
+ index.getAssessments('src').every((assessment) => assessment.status === 'fallback'),
+ ).toBe(true);
+ });
+
+ test('system and config source names are never indexed and create no reverse edges', () => {
+ const index = createIndex();
+ index.setSource('__system__', 'See [x](target).\n');
+ index.setSource('__config__/project', 'See [y](other).\n');
+ expect(index.getAssessments('__system__')).toEqual([]);
+ expect(index.getDocumentDependents('target')).toEqual([]);
+ expect(index.getDocumentDependents('other')).toEqual([]);
+ });
+
+ test('external, anchor, and traversal-escaping targets create no false document or file dependents', () => {
+ const index = createIndex();
+ index.setSource(
+ 'src',
+ 'Ext [a](https://example.com) anchor [b](#section) escape [c](../../secret.pdf) beyond [d](../../nope).\n',
+ );
+ // External + anchor are dropped at extraction; the two escaping forms assess
+ // as unresolvable with no resolvable identity, so nothing depends on them.
+ for (const assessment of index.getAssessments('src')) {
+ expect(assessment.status).toBe('unresolvable');
+ expect(assessment.resolvedTarget).toBeNull();
+ }
+ expect(index.getFileDependents('../../secret.pdf')).toEqual([]);
+ expect(index.getStats().documentTargets).toBe(0);
+ expect(index.getStats().fileTargets).toBe(0);
+ });
+});
+
+describe('LocalTargetIndex disk lifecycle', () => {
+ test('uses injected document identities for aliases and managed targets absent from the source walk', async () => {
+ const rig = createDiskRig();
+ rig.write('source.md', 'See [alias](aliased/guide).\n');
+
+ await rig.index.rebuildFromDisk({
+ documentTargets: ['source', 'aliased/guide'],
+ fileTargets: [],
+ });
+
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({
+ targetKind: 'document',
+ resolvedTarget: 'aliased/guide',
+ status: 'exact',
+ });
+ });
+
+ test('is not ready until rebuilt, then exposes seeded assessments', async () => {
+ const rig = createDiskRig();
+ expect(rig.index.isReady()).toBe(false);
+
+ rig.write('a.md', 'See [x](b) and [pdf](assets/f.pdf).\n');
+ rig.write('b.md', '# B\n');
+
+ await rig.index.rebuildFromDisk({
+ documentTargets: ['a', 'b'],
+ fileTargets: ['assets/f.pdf'],
+ });
+
+ expect(rig.index.isReady()).toBe(true);
+ const assessments = rig.index.getAssessments('a');
+ expect(assessments).toHaveLength(2);
+ // `b` exists as a walked document; `assets/f.pdf` exists via the seeded file inventory.
+ expect(assessments.every((assessment) => assessment.status === 'exact')).toBe(true);
+ });
+
+ test('rebuild seeds reverse dependencies so a later target create heals scoped sources', async () => {
+ const rig = createDiskRig();
+ rig.write('a.md', 'See [missing](gone).\n');
+ rig.write('c.md', 'Image ![alt](assets/pic.png).\n');
+
+ await rig.index.rebuildFromDisk({ documentTargets: ['a', 'c'], fileTargets: [] });
+ expect(rig.index.getAssessments('a')[0]).toMatchObject({ status: 'missing' });
+ expect(rig.index.getAssessments('c')[0]).toMatchObject({
+ status: 'missing',
+ targetKind: 'file',
+ });
+
+ expect(rig.index.setFileTarget('assets/pic.png', true)).toBe(1);
+ expect(rig.index.getAssessments('c')[0]).toMatchObject({ status: 'exact' });
+ // `a`'s missing doc reference is untouched by the file create.
+ expect(rig.index.getAssessments('a')[0]).toMatchObject({ status: 'missing' });
+ });
+
+ test('a dependency-only disk sweep repairs watcher events dropped in either direction', async () => {
+ const rig = createDiskRig();
+ rig.write('source.md', 'Download [pdf](assets/report.pdf).\n');
+ rig.write('assets/report.pdf', '%PDF-1.4\n');
+ await rig.index.rebuildFromDisk({
+ documentTargets: ['source'],
+ fileTargets: ['assets/report.pdf'],
+ });
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({ status: 'exact' });
+
+ unlinkSync(join(rig.contentDir, 'assets/report.pdf'));
+ expect(await rig.index.reconcileDependentFileTargetsFromDisk()).toBe(1);
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({
+ status: 'missing',
+ reason: 'no-such-file',
+ });
+
+ rig.write('assets/report.pdf', '%PDF-1.4\n');
+ expect(await rig.index.reconcileDependentFileTargetsFromDisk()).toBe(1);
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({ status: 'exact' });
+ });
+
+ test('rebuild against a missing content dir settles ready and empty', async () => {
+ const index = new LocalTargetIndex({ contentDir: join(tmpdir(), 'ok-lti-does-not-exist-xyz') });
+ cleanups.push(() => index.close());
+ const result = await index.rebuildFromDisk({ documentTargets: [], fileTargets: [] });
+ expect(result).toEqual({ sources: 0, occurrences: 0 });
+ expect(index.isReady()).toBe(true);
+ });
+
+ test('a document read failure keeps the rebuilt index not ready', async () => {
+ const rig = createDiskRig({
+ readDocument: async () => {
+ throw new Error('forced document read failure');
+ },
+ });
+ rig.write('source.md', 'See [x](target).\n');
+
+ await expect(
+ rig.index.rebuildFromDisk({ documentTargets: ['source'], fileTargets: [] }),
+ ).rejects.toThrow('forced document read failure');
+ expect(rig.index.isReady()).toBe(false);
+ expect(rig.index.getAssessments('source')).toEqual([]);
+ });
+
+ test('a directory read failure keeps the rebuilt index not ready', async () => {
+ const rig = createDiskRig({
+ readDirectory: async () => {
+ throw new Error('forced directory read failure');
+ },
+ });
+
+ await expect(
+ rig.index.rebuildFromDisk({ documentTargets: [], fileTargets: [] }),
+ ).rejects.toThrow('forced directory read failure');
+ expect(rig.index.isReady()).toBe(false);
+ });
+
+ test('a failed rebuild retains the prior complete snapshot and a later rebuild recovers', async () => {
+ let failReads = false;
+ const rig = createDiskRig({
+ readDocument: async (filePath) => {
+ if (failReads) throw new Error('transient read failure');
+ return readFileSync(filePath, 'utf-8');
+ },
+ });
+ rig.write('source.md', 'See [x](first).\n');
+ await rig.index.rebuildFromDisk({
+ documentTargets: ['source', 'first'],
+ fileTargets: [],
+ });
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({
+ resolvedTarget: 'first',
+ status: 'exact',
+ });
+
+ rig.write('source.md', 'See [x](second).\n');
+ failReads = true;
+ await expect(
+ rig.index.rebuildFromDisk({
+ documentTargets: ['source', 'second'],
+ fileTargets: [],
+ }),
+ ).rejects.toThrow('transient read failure');
+ expect(rig.index.isReady()).toBe(false);
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({ resolvedTarget: 'first' });
+
+ failReads = false;
+ await rig.index.rebuildFromDisk({
+ documentTargets: ['source', 'second'],
+ fileTargets: [],
+ });
+ expect(rig.index.isReady()).toBe(true);
+ expect(rig.index.getAssessments('source')[0]).toMatchObject({
+ resolvedTarget: 'second',
+ status: 'exact',
+ });
+ });
+});
diff --git a/packages/server/src/local-target-index.ts b/packages/server/src/local-target-index.ts
new file mode 100644
index 000000000..13c607ccc
--- /dev/null
+++ b/packages/server/src/local-target-index.ts
@@ -0,0 +1,827 @@
+/**
+ * Server-owned local-target assessment index — a sibling to `BacklinkIndex`
+ * and `TagIndex` behind `DerivedDocumentIndex`. It holds one assessment per
+ * authored local-target occurrence and the reverse dependencies that let a
+ * target mutation heal or break only the sources that reference it, never the
+ * whole project.
+ *
+ * Two maps form the narrow waist:
+ * - source → occurrence assessments (what each document authored)
+ * - target → sources (who depends on each document/ordinary-file identity)
+ *
+ * A source edit replaces only that source's occurrence memberships and drops
+ * the reverse-dependency edges it no longer authors. A target create/delete
+ * reassesses exactly the reverse dependents of that identity — the authored
+ * hrefs are unchanged, so only each occurrence's `exact`/`missing` status
+ * flips; work is O(reverse dependents), not O(project).
+ *
+ * Existence is owned here, unlike `BacklinkIndex` (which takes an admitted set
+ * per query): a document exists once it has been recorded as a source, and an
+ * ordinary file exists once the watcher's all-files inventory reports it. That
+ * keeps the inventory and the occurrences on one generation so a restart or
+ * branch switch can withhold a `ready` result rather than publish a falsely
+ * clean one against a half-seeded inventory.
+ *
+ * Recognition, resolution, and existence policy live upstream
+ * (`local-target-occurrences.ts`, `local-target-assessment.ts`); this module
+ * owns only membership, reverse dependencies, and lifecycle. Classification
+ * upstream is total, but this index stores only what the local-target surfaces
+ * project — wiki forms keep their graph-backed validation, so `BacklinkIndex`
+ * semantics are untouched and a wiki-only edit stays silent here.
+ */
+
+import { type Dirent, existsSync, realpathSync } from 'node:fs';
+import { readdir, readFile, realpath, stat } from 'node:fs/promises';
+import { isAbsolute, join, relative } from 'node:path';
+import {
+ classifyMarkdownHref,
+ resolveAssetProjectPath,
+ toWikiLinkSlug,
+} from '@inkeep/open-knowledge-core';
+import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
+import type { ContentFilter } from './content-filter.ts';
+import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
+import { instrumentIndexRebuild, instrumentIndexUpdate } from './index-telemetry.ts';
+import {
+ assessLocalTargetOccurrences,
+ createTolerantDocumentResolver,
+ isProjectableToLocalTargetSurfaces,
+ type LocalTargetAssessment,
+ type LocalTargetInventory,
+} from './local-target-assessment.ts';
+import { extractLocalTargetOccurrences } from './local-target-occurrences.ts';
+import { toPosix } from './path-utils.ts';
+
+/**
+ * Narrow a total classification to the subset this index backs.
+ *
+ * Classification is total — every recognized form gets a canonical answer, so
+ * no surface has to guess. This index, though, is the store behind the
+ * local-target SURFACES specifically, and wiki forms do not project there: a
+ * wiki document link is a graph edge `forwardLinks` already carries, and a
+ * file-shaped wiki embed resolves by vault-wide basename under its own
+ * contract. Storing what it does not serve would move this index's generation —
+ * and fire the `local-targets` signal — for edits that change nothing any
+ * consumer of it can see.
+ */
+function projectableAssessments(
+ assessments: readonly LocalTargetAssessment[],
+): LocalTargetAssessment[] {
+ return assessments.filter((assessment) =>
+ isProjectableToLocalTargetSurfaces(assessment.occurrence),
+ );
+}
+
+/** One source and its assessed occurrences — the unit of project/scope enumeration. */
+export interface LocalTargetSourceAssessments {
+ source: string;
+ assessments: readonly LocalTargetAssessment[];
+}
+
+/** Bounded-cardinality snapshot for telemetry and freshness assertions — counts only, never paths. */
+export interface LocalTargetIndexStats {
+ /** Sources carrying at least one assessed occurrence. */
+ sources: number;
+ /** Total assessed occurrences across all sources. */
+ occurrences: number;
+ /** Distinct document target identities with at least one reverse dependent. */
+ documentTargets: number;
+ /** Distinct ordinary-file target identities with at least one reverse dependent. */
+ fileTargets: number;
+}
+
+export interface LocalTargetIndexOptions {
+ contentDir: string;
+ contentFilter?: ContentFilter;
+ /** Test seam for fail-closed rebuild coverage. Production uses `readFile(path, 'utf-8')`. */
+ readDocument?: (filePath: string) => Promise<string>;
+ /** Test seam for fail-closed directory-walk coverage. */
+ readDirectory?: (dir: string) => Promise<Dirent[]>;
+}
+
+/** Outcome of a rebuild — bounded counts for telemetry (`instrumentIndexRebuild`). */
+export interface LocalTargetRebuildResult {
+ sources: number;
+ occurrences: number;
+}
+
+/** Authoritative existence identities supplied by the watcher/coordinator. */
+export interface LocalTargetRebuildInventory {
+ documentTargets: Iterable<string>;
+ fileTargets: Iterable<string>;
+}
+
+/**
+ * Every target identity an occurrence's assessment depends on for its verdict.
+ * The authored (possibly missing) identity is what flips `exact`/`missing`; a
+ * tolerant fallback identity (document-only) is
+ * included so that if it later disappears the dependent reassesses.
+ */
+function assessmentTargetDeps(
+ assessment: LocalTargetAssessment,
+ sourceDocName: string,
+): {
+ docs: string[];
+ files: string[];
+} {
+ const docs: string[] = [];
+ const files: string[] = [];
+ if (assessment.resolvedTarget !== null) {
+ if (assessment.targetKind === 'document') docs.push(assessment.resolvedTarget);
+ else if (assessment.targetKind === 'file') files.push(assessment.resolvedTarget);
+ }
+ // Extension-less links are inventory-disambiguated. Retain both candidate
+ // edges even while one wins so a file delete/recreate or document
+ // create/delete can move the verdict back in either direction.
+ if (assessment.occurrence.role === 'link') {
+ const classified = classifyMarkdownHref(assessment.occurrence.href, sourceDocName);
+ if (classified?.kind === 'doc') {
+ docs.push(classified.docName);
+ const filePath = resolveAssetProjectPath(assessment.occurrence.href, sourceDocName);
+ if (filePath === classified.docName) files.push(filePath);
+ }
+ }
+ // A fallback is always a document identity (ordinary files have no tolerant
+ // navigation affordance), so its deletion is a document-target change.
+ if (assessment.fallbackTarget !== null) docs.push(assessment.fallbackTarget);
+ return { docs, files };
+}
+
+function addReverseEdge(reverse: Map<string, Set<string>>, target: string, source: string): void {
+ let sources = reverse.get(target);
+ if (!sources) {
+ sources = new Set();
+ reverse.set(target, sources);
+ }
+ sources.add(source);
+}
+
+function removeReverseEdge(
+ reverse: Map<string, Set<string>>,
+ target: string,
+ source: string,
+): void {
+ const sources = reverse.get(target);
+ if (!sources) return;
+ sources.delete(source);
+ if (sources.size === 0) reverse.delete(target);
+}
+
+function tolerantDependencyKeys(docName: string): string[] {
+ const keys: string[] = [];
+ const slug = toWikiLinkSlug(docName);
+ if (slug) keys.push(`slug:${slug}`);
+ if (!docName.includes('/') && slug) keys.push(`basename:${slug}`);
+ keys.push(`folder:${docName}`);
+ return keys;
+}
+
+function documentMutationKeys(docName: string): string[] {
+ const keys: string[] = [];
+ const slug = toWikiLinkSlug(docName);
+ if (slug) keys.push(`slug:${slug}`);
+ const leaf = docName.slice(docName.lastIndexOf('/') + 1);
+ const leafSlug = toWikiLinkSlug(leaf);
+ if (leafSlug) keys.push(`basename:${leafSlug}`);
+ const slash = docName.lastIndexOf('/');
+ if (slash > 0) {
+ const parent = docName.slice(0, slash);
+ const parentLeaf = parent.slice(parent.lastIndexOf('/') + 1);
+ if (leaf === 'index' || leaf === parentLeaf) keys.push(`folder:${parent}`);
+ }
+ return keys;
+}
+
+function assessmentsEqual(
+ left: readonly LocalTargetAssessment[],
+ right: readonly LocalTargetAssessment[],
+): boolean {
+ if (left.length !== right.length) return false;
+ return left.every((a, index) => {
+ const b = right[index];
+ if (!b) return false;
+ const ar = a.occurrence.reference;
+ const br = b.occurrence.reference;
+ return (
+ a.targetKind === b.targetKind &&
+ a.resolvedTarget === b.resolvedTarget &&
+ a.status === b.status &&
+ a.reason === b.reason &&
+ a.resolutionMethod === b.resolutionMethod &&
+ a.fallbackTarget === b.fallbackTarget &&
+ a.occurrence.role === b.occurrence.role &&
+ a.occurrence.sourceForm === b.occurrence.sourceForm &&
+ a.occurrence.href === b.occurrence.href &&
+ a.occurrence.range.start === b.occurrence.range.start &&
+ a.occurrence.range.end === b.occurrence.range.end &&
+ a.occurrence.line === b.occurrence.line &&
+ a.occurrence.column === b.occurrence.column &&
+ ar?.label === br?.label &&
+ ar?.kind === br?.kind &&
+ ar?.definition.href === br?.definition.href &&
+ ar?.definition.repairRange.start === br?.definition.repairRange.start &&
+ ar?.definition.repairRange.end === br?.definition.repairRange.end
+ );
+ });
+}
+
+export class LocalTargetIndex {
+ private readonly contentDir: string;
+ private readonly canonicalContentDir: string;
+ private readonly contentFilter?: ContentFilter;
+ private readonly readDocument: (filePath: string) => Promise<string>;
+ private readonly readDirectory: (dir: string) => Promise<Dirent[]>;
+
+ /** docName → its assessed occurrences (only sources with ≥1 occurrence are kept). */
+ private sourceAssessments = new Map<string, LocalTargetAssessment[]>();
+ /** docName → document identities it currently depends on (for O(deps) ghost removal). */
+ private sourceDocDeps = new Map<string, Set<string>>();
+ /** docName → ordinary-file identities it currently depends on. */
+ private sourceFileDeps = new Map<string, Set<string>>();
+ /** document identity → sources whose assessment depends on it. */
+ private reverseByDoc = new Map<string, Set<string>>();
+ /** ordinary-file identity → sources whose assessment depends on it. */
+ private reverseByFile = new Map<string, Set<string>>();
+ /** Tolerant-resolution key → sources that could gain/lose that fallback. */
+ private reverseByTolerant = new Map<string, Set<string>>();
+ /** docName → tolerant-resolution keys currently authored by that source. */
+ private sourceTolerantDeps = new Map<string, Set<string>>();
+
+ /** Admitted live documents — the `hasDocument` oracle. A source's own identity is added when it is recorded. */
+ private documents = new Set<string>();
+ private tolerantDocumentResolver: (docName: string) => string | null = () => null;
+ /** Admitted ordinary files (watcher all-files inventory) — the `hasFile` oracle. */
+ private files = new Set<string>();
+
+ private generationValue = 0;
+ private freshnessEpoch = 0;
+ private readyValue = false;
+ private closed = false;
+
+ /** Existence oracle backed by this index's own inventory sets. */
+ private readonly inventory: LocalTargetInventory = {
+ hasDocument: (docName) => this.documents.has(docName),
+ hasFile: (relativePath) => this.files.has(relativePath),
+ resolveTolerantDocument: (docName) => this.tolerantDocumentResolver(docName),
+ };
+
+ constructor(options: LocalTargetIndexOptions) {
+ this.contentDir = options.contentDir;
+ try {
+ this.canonicalContentDir = realpathSync(options.contentDir);
+ } catch {
+ this.canonicalContentDir = options.contentDir;
+ }
+ this.contentFilter = options.contentFilter;
+ this.readDocument = options.readDocument ?? ((filePath) => readFile(filePath, 'utf-8'));
+ this.readDirectory = options.readDirectory ?? ((dir) => readdir(dir, { withFileTypes: true }));
+ }
+
+ /** Monotonic generation; consumers diff it to detect staleness without a full refetch. */
+ get generation(): number {
+ return this.generationValue;
+ }
+
+ /**
+ * Whether the index has settled against a seeded inventory. Queries served
+ * before this is true would be against a half-seeded inventory — the
+ * coordinator withholds them rather than publish a falsely clean result.
+ */
+ isReady(): boolean {
+ return this.readyValue;
+ }
+
+ /** Preserve the last complete snapshot but prevent it from being published. */
+ markUnavailable(): void {
+ if (this.readyValue) this.freshnessEpoch++;
+ this.readyValue = false;
+ }
+
+ /** Equality token for work that must be abandoned across lifecycle changes. */
+ get freshnessToken(): string {
+ return `${this.generationValue}:${this.freshnessEpoch}`;
+ }
+
+ /** Assessments for one source, or an empty array. The occurrence range travels on each assessment. */
+ getAssessments(docName: string): readonly LocalTargetAssessment[] {
+ return this.sourceAssessments.get(docName) ?? [];
+ }
+
+ /**
+ * Assessments for every source, optionally narrowed to a source set — the
+ * project/folder-scope enumeration a validator drives. Only sources carrying
+ * ≥1 occurrence are held, so iteration is O(sources with occurrences); each
+ * occurrence's range travels on its assessment for positioned diagnostics.
+ */
+ 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) {
+ if (filter && !filter.has(source)) continue;
+ out.push({ source, assessments });
+ }
+ return out;
+ }
+
+ /** Sources whose assessment depends on this document identity's existence (sorted). */
+ getDocumentDependents(docName: string): string[] {
+ const sources = new Set(this.reverseByDoc.get(docName) ?? []);
+ for (const key of documentMutationKeys(docName)) {
+ for (const source of this.reverseByTolerant.get(key) ?? []) sources.add(source);
+ }
+ return [...sources].sort((a, b) => a.localeCompare(b));
+ }
+
+ /** Sources whose assessment depends on this ordinary-file identity's existence (sorted). */
+ getFileDependents(relativePath: string): string[] {
+ return [...(this.reverseByFile.get(relativePath) ?? [])].sort((a, b) => a.localeCompare(b));
+ }
+
+ getStats(): LocalTargetIndexStats {
+ let occurrences = 0;
+ for (const assessments of this.sourceAssessments.values()) occurrences += assessments.length;
+ return {
+ sources: this.sourceAssessments.size,
+ occurrences,
+ documentTargets: this.reverseByDoc.size,
+ fileTargets: this.reverseByFile.size,
+ };
+ }
+
+ close(): void {
+ this.closed = true;
+ }
+
+ /**
+ * Record a source's markdown: extract its occurrences, assess them against
+ * the current inventory, and replace this source's memberships. The source's
+ * own identity becomes an existing document; when that flips a previously
+ * absent identity to present, the documents referencing it are healed.
+ *
+ * Returns whether a local-target-relevant change occurred, so the coordinator
+ * pushes the `local-targets` signal only when an assessment moved — a
+ * wiki-only or occurrence-free edit is silent.
+ */
+ setSource(docName: string, markdown: string): boolean {
+ if (isLinkIndexExcludedDoc(docName)) return false;
+ const update = instrumentIndexUpdate(
+ 'local-target',
+ 'source',
+ () => {
+ const previous = this.sourceAssessments.get(docName) ?? [];
+ const becameDocument = !this.documents.has(docName);
+ this.documents.add(docName);
+ if (becameDocument) this.refreshTolerantDocumentIndexes();
+
+ const occurrences = extractLocalTargetOccurrences(markdown);
+ const assessments = projectableAssessments(
+ assessLocalTargetOccurrences(occurrences, docName, this.inventory),
+ );
+ const sourceChanged = !assessmentsEqual(previous, assessments);
+ if (sourceChanged) this.applySourceAssessments(docName, assessments);
+
+ const healed = becameDocument ? this.reassessDocumentDependents(docName) : 0;
+ const changed = sourceChanged || healed > 0;
+ if (changed) this.generationValue++;
+ return {
+ changed,
+ occurrences: assessments.length,
+ affectedSources: healed + (sourceChanged ? 1 : 0),
+ };
+ },
+ (result) => ({
+ 'index.occurrences': result.occurrences,
+ 'index.affected_sources': result.affectedSources,
+ }),
+ );
+ return update.changed;
+ }
+
+ /**
+ * Forget a source and its identity as a document. Reference-holders that
+ * pointed at this now-absent identity are broken. Idempotent. Returns whether
+ * an assessment moved.
+ */
+ removeSource(docName: string): boolean {
+ if (isLinkIndexExcludedDoc(docName)) return false;
+ const update = instrumentIndexUpdate(
+ 'local-target',
+ 'document-target',
+ () => {
+ const occurrences = this.sourceAssessments.get(docName)?.length ?? 0;
+ const hadOccurrences = occurrences > 0;
+ const wasDocument = this.documents.delete(docName);
+ if (wasDocument) this.refreshTolerantDocumentIndexes();
+ this.applySourceAssessments(docName, []);
+ const broke = wasDocument ? this.reassessDocumentDependents(docName) : 0;
+ const changed = hadOccurrences || broke > 0;
+ if (changed) this.generationValue++;
+ return {
+ changed,
+ occurrences,
+ affectedSources: broke + (hadOccurrences ? 1 : 0),
+ };
+ },
+ (result) => ({
+ 'index.occurrences': result.occurrences,
+ 'index.affected_sources': result.affectedSources,
+ }),
+ );
+ return update.changed;
+ }
+
+ /**
+ * Rename a source atomically: the old identity's occurrences and existence
+ * drop, the new identity's are recorded from the post-rename content. Both
+ * identities' reverse dependents are reassessed, so links to the old name
+ * break and links to the new name heal in one settled step.
+ */
+ renameSource(oldDocName: string, newDocName: string, markdown: string): boolean {
+ const removed = this.removeSource(oldDocName);
+ const set = this.setSource(newDocName, markdown);
+ return removed || set;
+ }
+
+ /**
+ * Reflect an ordinary-file target's existence and reassess only its reverse
+ * dependents. A no-op when existence did not flip (a content-only file-update
+ * event), so churn stays proportional to real create/delete transitions.
+ * Returns the number of sources reassessed (bounded telemetry).
+ */
+ setFileTarget(relativePath: string, exists: boolean): number {
+ const update = instrumentIndexUpdate(
+ 'local-target',
+ 'file-target',
+ () => {
+ const present = this.files.has(relativePath);
+ if (exists === present) return { affected: 0, occurrences: 0 };
+ if (exists) this.files.add(relativePath);
+ else this.files.delete(relativePath);
+ const occurrences = this.countFileOccurrences(relativePath);
+ const affected = this.reassessFileDependents(relativePath);
+ // Existence moved, but only a reassessed dependent is consumer-visible; an
+ // unreferenced file create/delete changes no assessment, so hold generation.
+ if (affected > 0) this.generationValue++;
+ return { affected, occurrences };
+ },
+ (result) => ({
+ 'index.occurrences': result.occurrences,
+ 'index.affected_sources': result.affected,
+ }),
+ );
+ return update.affected;
+ }
+
+ /** Replace document existence from an authoritative alias-complete snapshot. */
+ reconcileDocumentTargets(documentTargets: Iterable<string>): number {
+ const next = new Set(documentTargets);
+ const changedIdentities = new Set<string>();
+ for (const docName of this.documents) {
+ if (!next.has(docName)) changedIdentities.add(docName);
+ }
+ for (const docName of next) {
+ if (!this.documents.has(docName)) changedIdentities.add(docName);
+ }
+ if (changedIdentities.size === 0) return 0;
+
+ const affected = new Set<string>();
+ for (const docName of changedIdentities) {
+ for (const source of this.reverseByDoc.get(docName) ?? []) affected.add(source);
+ for (const key of documentMutationKeys(docName)) {
+ for (const source of this.reverseByTolerant.get(key) ?? []) affected.add(source);
+ }
+ }
+ this.documents = next;
+ this.refreshTolerantDocumentIndexes();
+ let reassessed = 0;
+ for (const source of affected) {
+ if (this.reassessSource(source)) reassessed++;
+ }
+ if (reassessed > 0) this.generationValue++;
+ return reassessed;
+ }
+
+ /** Replace ordinary-file existence from an authoritative alias-complete snapshot. */
+ reconcileFileTargets(fileTargets: Iterable<string>): number {
+ return instrumentIndexUpdate(
+ 'local-target',
+ 'file-target',
+ () => {
+ const next = new Set(fileTargets);
+ const changedIdentities = new Set<string>();
+ for (const relativePath of this.files) {
+ if (!next.has(relativePath)) changedIdentities.add(relativePath);
+ }
+ for (const relativePath of next) {
+ if (!this.files.has(relativePath)) changedIdentities.add(relativePath);
+ }
+ const affected = new Set<string>();
+ let occurrences = 0;
+ for (const relativePath of changedIdentities) {
+ occurrences += this.countFileOccurrences(relativePath);
+ for (const source of this.reverseByFile.get(relativePath) ?? []) affected.add(source);
+ }
+ this.files = next;
+ let reassessed = 0;
+ for (const source of affected) {
+ if (this.reassessSource(source)) reassessed++;
+ }
+ if (reassessed > 0) this.generationValue++;
+ return { affected: reassessed, occurrences };
+ },
+ (result) => ({
+ 'index.occurrences': result.occurrences,
+ 'index.affected_sources': result.affected,
+ }),
+ ).affected;
+ }
+
+ /**
+ * Repair watcher events that the host filesystem backend dropped. The sweep
+ * is bounded to identities with reverse dependents, so an unreferenced
+ * workspace file never adds polling work. Admission and realpath containment
+ * mirror the watcher boundary before disk existence can affect an assessment.
+ */
+ async reconcileDependentFileTargetsFromDisk(
+ onChange?: (relativePath: string, exists: boolean) => void,
+ ): Promise<number> {
+ const targets = [...this.reverseByFile.keys()];
+ const existence = await Promise.all(
+ targets.map((relativePath) => this.isAdmittedFileOnDisk(relativePath)),
+ );
+ let affected = 0;
+ for (const [index, relativePath] of targets.entries()) {
+ const exists = existence[index] ?? false;
+ const targetAffected = this.setFileTarget(relativePath, exists);
+ if (targetAffected > 0) onChange?.(relativePath, exists);
+ affected += targetAffected;
+ }
+ return affected;
+ }
+
+ private async isAdmittedFileOnDisk(relativePath: string): Promise<boolean> {
+ if (this.contentFilter?.isPathIgnored(relativePath)) return false;
+ try {
+ const canonicalPath = await realpath(join(this.contentDir, relativePath));
+ const canonicalRelative = relative(this.canonicalContentDir, canonicalPath);
+ if (
+ canonicalRelative === '' ||
+ canonicalRelative === '..' ||
+ canonicalRelative.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) ||
+ isAbsolute(canonicalRelative)
+ ) {
+ return false;
+ }
+ return (await stat(canonicalPath)).isFile();
+ } catch {
+ return false;
+ }
+ }
+
+ private countFileOccurrences(relativePath: string): number {
+ 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++;
+ }
+ }
+ }
+ return occurrences;
+ }
+
+ /**
+ * Rebuild from disk: seed the document inventory from the content-dir walk,
+ * the file inventory from the watcher's authoritative all-files snapshot,
+ * then assess every source against the complete inventory. Replaces all
+ * state and marks the index ready. This is the startup / branch-switch /
+ * content-scope reconciliation.
+ */
+ rebuildFromDisk(inventory: LocalTargetRebuildInventory): Promise<LocalTargetRebuildResult> {
+ return instrumentIndexRebuild(
+ 'local-target',
+ 'full',
+ () => this.rebuildOnce(inventory),
+ (result) => ({
+ 'index.sources': result.sources,
+ 'index.occurrences': result.occurrences,
+ 'index.affected_sources': result.sources,
+ }),
+ );
+ }
+
+ private async rebuildOnce(
+ inventory: LocalTargetRebuildInventory,
+ ): Promise<LocalTargetRebuildResult> {
+ const hadContent = this.sourceAssessments.size > 0;
+ this.freshnessEpoch++;
+ this.readyValue = false;
+ const staged = new LocalTargetIndex({
+ contentDir: this.contentDir,
+ contentFilter: this.contentFilter,
+ readDocument: this.readDocument,
+ readDirectory: this.readDirectory,
+ });
+ const result = await staged.populateFromDisk(inventory);
+
+ this.sourceAssessments = staged.sourceAssessments;
+ this.sourceDocDeps = staged.sourceDocDeps;
+ this.sourceFileDeps = staged.sourceFileDeps;
+ this.reverseByDoc = staged.reverseByDoc;
+ this.reverseByFile = staged.reverseByFile;
+ this.reverseByTolerant = staged.reverseByTolerant;
+ this.sourceTolerantDeps = staged.sourceTolerantDeps;
+ this.documents = staged.documents;
+ this.tolerantDocumentResolver = staged.tolerantDocumentResolver;
+ this.files = staged.files;
+ this.readyValue = true;
+ if (hadContent || this.sourceAssessments.size > 0) this.generationValue++;
+ return result;
+ }
+
+ 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);
+ this.refreshTolerantDocumentIndexes();
+
+ if (!existsSync(this.contentDir)) {
+ this.readyValue = true;
+ return { sources: 0, occurrences: 0 };
+ }
+
+ const docs = await this.listDocsWithPaths();
+ // Source bodies are still discovered locally, but target existence comes
+ // from the injected canonical inventory. Unioning walked sources keeps a
+ // just-authored document self-consistent before its watcher event settles.
+ for (const { docName } of docs) this.documents.add(docName);
+ this.refreshTolerantDocumentIndexes();
+
+ let occurrenceCount = 0;
+ const BATCH_SIZE = 50;
+ for (let i = 0; i < docs.length && !this.closed; i += BATCH_SIZE) {
+ const batch = docs.slice(i, i + BATCH_SIZE);
+ const results = await Promise.all(
+ batch.map(async ({ docName, filePath }) => ({
+ docName,
+ markdown: await this.readDocument(filePath),
+ })),
+ );
+ for (const result of results) {
+ if (isLinkIndexExcludedDoc(result.docName)) continue;
+ const occurrences = extractLocalTargetOccurrences(result.markdown);
+ const assessments = projectableAssessments(
+ assessLocalTargetOccurrences(occurrences, result.docName, this.inventory),
+ );
+ this.applySourceAssessments(result.docName, assessments);
+ occurrenceCount += assessments.length;
+ }
+ }
+
+ this.readyValue = true;
+ return { sources: this.sourceAssessments.size, occurrences: occurrenceCount };
+ }
+
+ /**
+ * Install a source's assessments and reconcile its reverse-dependency edges:
+ * edges it no longer authors are removed (ghost removal), new ones added.
+ * The occurrences are unchanged for a pure reassessment and replaced for a
+ * source edit — either way the dependency set is recomputed from the result.
+ */
+ private applySourceAssessments(docName: string, assessments: LocalTargetAssessment[]): void {
+ const nextDocDeps = new Set<string>();
+ const nextFileDeps = new Set<string>();
+ 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);
+ if (
+ assessment.targetKind === 'document' &&
+ assessment.status !== 'exact' &&
+ assessment.resolvedTarget !== null
+ ) {
+ for (const key of tolerantDependencyKeys(assessment.resolvedTarget)) {
+ 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);
+ }
+
+ if (assessments.length === 0) {
+ this.sourceAssessments.delete(docName);
+ this.sourceDocDeps.delete(docName);
+ this.sourceFileDeps.delete(docName);
+ this.sourceTolerantDeps.delete(docName);
+ return;
+ }
+ this.sourceAssessments.set(docName, assessments);
+ this.sourceDocDeps.set(docName, nextDocDeps);
+ this.sourceFileDeps.set(docName, nextFileDeps);
+ this.sourceTolerantDeps.set(docName, nextTolerantDeps);
+ }
+
+ /** Reassess one source against the current inventory without re-extracting its occurrences. */
+ private reassessSource(docName: string): boolean {
+ const assessments = this.sourceAssessments.get(docName);
+ if (!assessments) return false;
+ const occurrences = assessments.map((assessment) => assessment.occurrence);
+ const next = assessLocalTargetOccurrences(occurrences, docName, this.inventory);
+ if (assessmentsEqual(assessments, next)) return false;
+ this.applySourceAssessments(docName, next);
+ return true;
+ }
+
+ private reassessDocumentDependents(docName: string): number {
+ // Snapshot the union before reassessment mutates the reverse sets.
+ const affected = new Set(this.reverseByDoc.get(docName) ?? []);
+ for (const key of documentMutationKeys(docName)) {
+ for (const source of this.reverseByTolerant.get(key) ?? []) affected.add(source);
+ }
+ let changed = 0;
+ for (const source of affected) {
+ if (this.reassessSource(source)) changed += 1;
+ }
+ return changed;
+ }
+
+ private reassessFileDependents(relativePath: string): number {
+ const affected = [...(this.reverseByFile.get(relativePath) ?? [])];
+ let changed = 0;
+ for (const source of affected) {
+ if (this.reassessSource(source)) changed += 1;
+ }
+ return changed;
+ }
+
+ private refreshTolerantDocumentIndexes(): void {
+ this.tolerantDocumentResolver = createTolerantDocumentResolver(this.documents);
+ }
+
+ private async listDocsWithPaths(): Promise<Array<{ docName: string; filePath: string }>> {
+ const out: Array<{ docName: string; filePath: string }> = [];
+ await this.walkContentDir(this.contentDir, out);
+ // Same-stem `.md`/`.mdx` dedupe with `.mdx` precedence, mirroring TagIndex.
+ out.sort((a, b) =>
+ a.docName === b.docName
+ ? b.filePath.localeCompare(a.filePath)
+ : a.docName.localeCompare(b.docName),
+ );
+ const seen = new Set<string>();
+ return out.filter(({ docName }) => {
+ if (seen.has(docName)) return false;
+ seen.add(docName);
+ return true;
+ });
+ }
+
+ private async walkContentDir(
+ dir: string,
+ out: Array<{ docName: string; filePath: string }>,
+ ): Promise<void> {
+ const entries = await this.readDirectory(dir);
+ for (const entry of entries) {
+ const fullPath = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ const relDir = toPosix(relative(this.contentDir, fullPath));
+ if (this.contentFilter && relDir && this.contentFilter.isDirExcluded(relDir)) continue;
+ await this.walkContentDir(fullPath, out);
+ continue;
+ }
+ if (!entry.isFile() || !isSupportedDocFile(entry.name)) continue;
+ const relPath = toPosix(relative(this.contentDir, fullPath));
+ if (this.contentFilter?.isExcluded(relPath)) continue;
+ out.push({ docName: stripDocExtension(relPath), filePath: fullPath });
+ }
+ }
+}
diff --git a/packages/server/src/local-target-inventory.test.ts b/packages/server/src/local-target-inventory.test.ts
new file mode 100644
index 000000000..b74061014
--- /dev/null
+++ b/packages/server/src/local-target-inventory.test.ts
@@ -0,0 +1,79 @@
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import type { FileIndexEntry } from './file-watcher.ts';
+import {
+ localTargetInventoryFromIndexes,
+ localTargetInventoryFromWatcher,
+} from './local-target-inventory.ts';
+
+function entry(
+ kind: FileIndexEntry['kind'],
+ canonicalPath: string,
+ aliases: string[] = [],
+): FileIndexEntry {
+ return {
+ kind,
+ canonicalPath,
+ aliases,
+ inode: 1,
+ modified: '2026-01-01T00:00:00.000Z',
+ size: 1,
+ };
+}
+
+describe('localTargetInventoryFromIndexes', () => {
+ test('includes indexed, canonical, direct-alias, and folder-alias identities by kind', () => {
+ const contentDir = '/project/content';
+ const allFiles = new Map<string, FileIndexEntry>([
+ [
+ 'canonical/guide',
+ entry('markdown', join(contentDir, 'canonical/guide.md'), ['direct-guide']),
+ ],
+ [
+ 'direct-report.csv',
+ entry('file', join(contentDir, 'canonical/report.csv'), ['other-report.csv']),
+ ],
+ ]);
+
+ const inventory = localTargetInventoryFromIndexes(
+ allFiles,
+ new Map([['folder-alias', 'canonical']]),
+ contentDir,
+ );
+
+ expect(inventory.documentTargets).toEqual(
+ expect.arrayContaining(['canonical/guide', 'direct-guide', 'folder-alias/guide']),
+ );
+ expect(inventory.fileTargets).toEqual(
+ expect.arrayContaining([
+ 'direct-report.csv',
+ 'other-report.csv',
+ 'canonical/report.csv',
+ 'folder-alias/report.csv',
+ ]),
+ );
+ });
+
+ test('distinguishes an unavailable watcher from an empty authoritative inventory', () => {
+ expect(localTargetInventoryFromWatcher(null, '/project/content')).toBeNull();
+ });
+
+ test('memoizes the projected inventory until the watcher generation changes', () => {
+ const contentDir = '/project/content';
+ const allFiles = new Map<string, FileIndexEntry>([
+ ['asset.png', entry('file', join(contentDir, 'asset.png'))],
+ ]);
+ let generation = 1;
+ const watcher = {
+ getAllFilesIndex: () => allFiles,
+ getFileIndexGeneration: () => generation,
+ getFolderAliasIndex: () => new Map<string, string>(),
+ };
+
+ const first = localTargetInventoryFromWatcher(watcher, contentDir);
+ expect(localTargetInventoryFromWatcher(watcher, contentDir)).toBe(first);
+
+ generation++;
+ expect(localTargetInventoryFromWatcher(watcher, contentDir)).not.toBe(first);
+ });
+});
diff --git a/packages/server/src/local-target-inventory.ts b/packages/server/src/local-target-inventory.ts
new file mode 100644
index 000000000..584ad0d7c
--- /dev/null
+++ b/packages/server/src/local-target-inventory.ts
@@ -0,0 +1,107 @@
+import { isAbsolute, relative } from 'node:path';
+import { stripDocExtension } from './doc-extensions.ts';
+import type { FileIndexEntry, WatcherHandle } from './file-watcher.ts';
+import { toPosix } from './path-utils.ts';
+
+export interface WatcherLocalTargetInventory {
+ documentTargets: readonly string[];
+ fileTargets: readonly string[];
+}
+
+type LocalTargetWatcher = Pick<
+ WatcherHandle,
+ 'getAllFilesIndex' | 'getFileIndexGeneration' | 'getFolderAliasIndex'
+>;
+
+interface CachedWatcherInventory {
+ contentDir: string;
+ generation: number;
+ inventory: WatcherLocalTargetInventory;
+}
+
+const watcherInventoryCache = new WeakMap<LocalTargetWatcher, CachedWatcherInventory>();
+
+function canonicalRelativePath(contentDir: string, canonicalPath: string): string | null {
+ const candidate = toPosix(relative(contentDir, canonicalPath));
+ if (
+ candidate.length === 0 ||
+ candidate === '..' ||
+ candidate.startsWith('../') ||
+ isAbsolute(candidate)
+ ) {
+ return null;
+ }
+ return candidate;
+}
+
+function projectFolderAliases(
+ identities: Set<string>,
+ folderAliases: ReadonlyMap<string, string>,
+): void {
+ const canonicalIdentities = [...identities];
+ for (const [aliasFolder, canonicalFolder] of folderAliases) {
+ for (const identity of canonicalIdentities) {
+ if (identity === canonicalFolder) {
+ identities.add(aliasFolder);
+ } else if (identity.startsWith(`${canonicalFolder}/`)) {
+ identities.add(`${aliasFolder}${identity.slice(canonicalFolder.length)}`);
+ }
+ }
+ }
+}
+
+/**
+ * Build the canonical local-target existence snapshot from the seeded watcher.
+ * Every admitted entry is represented by its indexed key, direct aliases,
+ * canonical realpath identity, and directory-symlink projections. A missing
+ * watcher is distinct from an authoritative empty inventory so callers can
+ * fail closed during startup degradation.
+ */
+export function localTargetInventoryFromWatcher(
+ watcher: LocalTargetWatcher | null | undefined,
+ contentDir: string,
+): WatcherLocalTargetInventory | null {
+ if (!watcher) return null;
+
+ const generation = watcher.getFileIndexGeneration();
+ const cached = watcherInventoryCache.get(watcher);
+ if (cached?.contentDir === contentDir && cached.generation === generation) {
+ return cached.inventory;
+ }
+
+ const inventory = localTargetInventoryFromIndexes(
+ watcher.getAllFilesIndex(),
+ watcher.getFolderAliasIndex(),
+ contentDir,
+ );
+ watcherInventoryCache.set(watcher, { contentDir, generation, inventory });
+ return inventory;
+}
+
+/** Pure index-boundary variant shared by startup and write-time assessment. */
+export function localTargetInventoryFromIndexes(
+ allFiles: ReadonlyMap<string, FileIndexEntry>,
+ folderAliases: ReadonlyMap<string, string>,
+ contentDir: string,
+): WatcherLocalTargetInventory {
+ const documentTargets = new Set<string>();
+ const fileTargets = new Set<string>();
+ for (const [indexedIdentity, entry] of allFiles) {
+ const targets = entry.kind === 'markdown' ? documentTargets : fileTargets;
+ targets.add(indexedIdentity);
+ for (const alias of entry.aliases) targets.add(alias);
+
+ const canonicalPath = canonicalRelativePath(contentDir, entry.canonicalPath);
+ if (canonicalPath) {
+ targets.add(entry.kind === 'markdown' ? stripDocExtension(canonicalPath) : canonicalPath);
+ }
+ }
+
+ projectFolderAliases(documentTargets, folderAliases);
+ projectFolderAliases(fileTargets, folderAliases);
+
+ return {
+ documentTargets: [...documentTargets],
+ fileTargets: [...fileTargets],
+ };
+}
diff --git a/packages/server/src/local-target-occurrences.test.ts b/packages/server/src/local-target-occurrences.test.ts
new file mode 100644
index 000000000..dc284b54a
--- /dev/null
+++ b/packages/server/src/local-target-occurrences.test.ts
@@ -0,0 +1,353 @@
+import { describe, expect, test } from 'vitest';
+import {
+ extractLocalTargetOccurrences,
+ type LocalTargetOccurrence,
+} from './local-target-occurrences.ts';
+
+/**
+ * Assert every occurrence's range reproduces authored bytes verbatim: the slice
+ * opens with the form's own delimiter and contains its authored href (reference
+ * uses take the href from the definition, so their bytes are exempt).
+ */
+function assertByteExact(source: string, occurrences: LocalTargetOccurrence[]): void {
+ for (const occ of occurrences) {
+ const slice = source.slice(occ.range.start, occ.range.end);
+ expect(slice.length).toBeGreaterThan(0);
+ if (occ.sourceForm !== 'markdown-reference') {
+ expect(slice).toContain(occ.href);
+ }
+ switch (occ.sourceForm) {
+ case 'markdown-inline':
+ case 'markdown-reference':
+ expect(slice.startsWith('[') || slice.startsWith('![')).toBe(true);
+ break;
+ case 'html-img':
+ expect(slice.startsWith('<img')).toBe(true);
+ break;
+ case 'wiki-link':
+ expect(slice.startsWith('[[')).toBe(true);
+ break;
+ case 'wiki-embed':
+ expect(slice.startsWith('![[')).toBe(true);
+ break;
+ }
+ }
+}
+
+describe('admitted inline forms', () => {
+ test('inline markdown link', () => {
+ const md = 'See [the doc](./guide.md) now.';
+ const [occ, ...rest] = extractLocalTargetOccurrences(md);
+ expect(rest).toEqual([]);
+ expect(occ).toMatchObject({ role: 'link', sourceForm: 'markdown-inline', href: './guide.md' });
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('[the doc](./guide.md)');
+ expect(occ?.line).toBe(0);
+ expect(occ?.column).toBe(4);
+ });
+
+ test('inline markdown image', () => {
+ const md = '![alt text](./diagram.png)';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ).toMatchObject({
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ href: './diagram.png',
+ });
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('![alt text](./diagram.png)');
+ expect(occ?.column).toBe(0);
+ });
+
+ test('angle-wrapped destination is unwrapped in href but the range covers the angles', () => {
+ const md = '[doc](<./my file.md>)';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ?.href).toBe('./my file.md');
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('[doc](<./my file.md>)');
+ });
+
+ test('root-relative and parent-relative paths are admitted', () => {
+ const md = '[a](/root/file.md) and [b](../sibling/file.md)';
+ const occ = extractLocalTargetOccurrences(md);
+ expect(occ.map((o) => o.href)).toEqual(['/root/file.md', '../sibling/file.md']);
+ });
+
+ test('a badge link emits both the outer link and nested image with exact ranges', () => {
+ const md = '[![badge](./badge.png)](./target.md)';
+ const occurrences = extractLocalTargetOccurrences(md);
+
+ expect(occurrences.map(({ role, href }) => [role, href])).toEqual([
+ ['link', './target.md'],
+ ['image', './badge.png'],
+ ]);
+ expect(md.slice(occurrences[0]?.range.start, occurrences[0]?.range.end)).toBe(md);
+ expect(md.slice(occurrences[1]?.range.start, occurrences[1]?.range.end)).toBe(
+ '![badge](./badge.png)',
+ );
+ });
+});
+
+describe('admitted HTML img forms', () => {
+ test('bare void HTML img', () => {
+ const md = 'Before <img src="./photo.png"> after';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ).toMatchObject({ role: 'image', sourceForm: 'html-img', href: './photo.png' });
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('<img src="./photo.png">');
+ });
+
+ test('self-closing HTML img', () => {
+ const md = '<img src="./photo.png" alt="p" />';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ).toMatchObject({ role: 'image', sourceForm: 'html-img', href: './photo.png' });
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('<img src="./photo.png" alt="p" />');
+ });
+});
+
+describe('admitted wiki forms', () => {
+ test('wiki link and wiki embed', () => {
+ const md = 'A [[Some Page]] and an embed ![[photo.png]] here';
+ const occ = extractLocalTargetOccurrences(md);
+ expect(occ.map((o) => [o.role, o.sourceForm, o.href])).toEqual([
+ ['link', 'wiki-link', 'Some Page'],
+ ['image', 'wiki-embed', 'photo.png'],
+ ]);
+ expect(md.slice(occ[0]?.range.start, occ[0]?.range.end)).toBe('[[Some Page]]');
+ expect(md.slice(occ[1]?.range.start, occ[1]?.range.end)).toBe('![[photo.png]]');
+ });
+});
+
+describe('reference-style forms map every use to one definition', () => {
+ test('full, collapsed, and shortcut uses resolve to the shared definition', () => {
+ const md = [
+ 'Full [see one][doc].',
+ 'Collapsed [doc][].',
+ 'Shortcut [doc].',
+ '',
+ '[doc]: ./manual.pdf',
+ ].join('\n');
+ const occ = extractLocalTargetOccurrences(md);
+ expect(occ.map((o) => o.reference?.kind)).toEqual(['full', 'collapsed', 'shortcut']);
+ // Every use carries the same resolved href and the SAME definition object.
+ expect(occ.every((o) => o.href === './manual.pdf')).toBe(true);
+ const defs = new Set(occ.map((o) => o.reference?.definition));
+ expect(defs.size).toBe(1);
+ });
+
+ test('the shared definition repair range bounds the destination token', () => {
+ const md = '[a][doc]\n\n[doc]: ./manual.pdf';
+ const [occ] = extractLocalTargetOccurrences(md);
+ const repair = occ?.reference?.definition.repairRange;
+ expect(md.slice(repair?.start, repair?.end)).toBe('./manual.pdf');
+ });
+
+ test('every authored use keeps its own occurrence range', () => {
+ const md = '[first][doc] then [second][doc]\n\n[doc]: ./x.pdf';
+ const occ = extractLocalTargetOccurrences(md);
+ expect(md.slice(occ[0]?.range.start, occ[0]?.range.end)).toBe('[first][doc]');
+ expect(md.slice(occ[1]?.range.start, occ[1]?.range.end)).toBe('[second][doc]');
+ expect(occ[0]?.reference?.definition).toBe(occ[1]?.reference?.definition);
+ });
+
+ test('reference resolution is case-insensitive and whitespace-collapsed', () => {
+ const md = '[link][My Ref]\n\n[my ref]: ./target.md';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ?.href).toBe('./target.md');
+ expect(occ?.reference?.label).toBe('my ref');
+ });
+
+ test('reference resolution applies CommonMark Unicode case folding', () => {
+ const [occ] = extractLocalTargetOccurrences('[link][ẞ]\n\n[SS]: ./target.md');
+ expect(occ?.href).toBe('./target.md');
+ });
+
+ test('reference-style image', () => {
+ const md = '![alt][img]\n\n[img]: ./picture.png';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ).toMatchObject({
+ role: 'image',
+ sourceForm: 'markdown-reference',
+ href: './picture.png',
+ });
+ });
+
+ test('a reference use with no matching definition is not a link and is not emitted', () => {
+ expect(extractLocalTargetOccurrences('[text][missing] and [alsoMissing].')).toEqual([]);
+ });
+
+ test('the definition line itself yields no occurrence', () => {
+ // `[doc]` on the definition line must not be read as a shortcut use of itself.
+ expect(extractLocalTargetOccurrences('[doc]: ./only-a-definition.pdf')).toEqual([]);
+ });
+
+ test('an external definition destination is not emitted as a local target', () => {
+ expect(extractLocalTargetOccurrences('[x][ext]\n\n[ext]: https://example.com')).toEqual([]);
+ });
+
+ test('a destination continued onto the next line is recognized with an exact repair range', () => {
+ const md = '[manual][ref]\n\n[ref]:\n <./manual file.pdf>\n';
+ const [occurrence] = extractLocalTargetOccurrences(md);
+
+ expect(occurrence?.href).toBe('./manual file.pdf');
+ expect(occurrence?.reference?.definition.line).toBe(2);
+ const repairRange = occurrence?.reference?.definition.repairRange;
+ expect(md.slice(repairRange?.start, repairRange?.end)).toBe('<./manual file.pdf>');
+ });
+
+ test('a title continued onto the next line remains part of one definition block', () => {
+ const md = '[manual][ref]\n\n[ref]: ./manual.pdf\n "Manual"\n';
+ const occurrences = extractLocalTargetOccurrences(md);
+
+ expect(occurrences).toHaveLength(1);
+ expect(occurrences[0]?.href).toBe('./manual.pdf');
+ });
+});
+
+describe('context exclusions produce no false local targets', () => {
+ test('frontmatter is excluded', () => {
+ const md = ['---', 'cover: [x](./in-frontmatter.md)', '---', '[real](./body.md)'].join('\n');
+ const occ = extractLocalTargetOccurrences(md);
+ expect(occ.map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('fenced code blocks are excluded (backtick and tilde)', () => {
+ const md = [
+ '```',
+ '[x](./in-backtick-fence.md)',
+ '```',
+ '~~~',
+ '[y](./in-tilde-fence.md)',
+ '~~~',
+ '[real](./body.md)',
+ ].join('\n');
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('inline code is excluded', () => {
+ const md = 'Type `[x](./in-code.md)` but link [real](./body.md).';
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('a backslash-escaped opener is excluded', () => {
+ const md = '\\[not a link](./escaped.md) but [real](./body.md)';
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('indented code is excluded', () => {
+ const md = ' ![not rendered](./indented.png)\n\t[x](./tabbed.pdf)\n[real](./body.md)';
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('HTML comments are excluded across and within lines', () => {
+ const md = [
+ '<!-- ![inline](./inline.png) --> [real](./body.md)',
+ '<!--',
+ '[ref]: ./comment.pdf',
+ '![block](./block.png)',
+ '-->',
+ '[ref]',
+ ].join('\n');
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+
+ test('an HTML opener inside inline code does not mask a trailing real link', () => {
+ const md = '`<!--` [real](./body.md) and `<pre>` [also](./other.md)';
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual([
+ './body.md',
+ './other.md',
+ ]);
+ });
+
+ test('raw pre and code regions are excluded, including inline regions', () => {
+ const md = [
+ '<pre>![pre](./pre.png)</pre> [real](./body.md)',
+ '<code>',
+ '[code](./code.pdf)',
+ '</code>',
+ ].join('\n');
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./body.md']);
+ });
+});
+
+describe('href classification excludes non-local targets', () => {
+ test('external URLs (any scheme, protocol-relative) are excluded', () => {
+ const md = [
+ '[a](https://example.com)',
+ '[b](http://example.com/x)',
+ '[c](mailto:[email protected])',
+ '[d](//cdn.example.com/x.png)',
+ '<img src="https://example.com/x.png">',
+ '[[https://example.com]]',
+ '[keep](./local.md)',
+ ].join('\n');
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./local.md']);
+ });
+
+ test('bare anchors are excluded', () => {
+ const md = '[section](#heading) but [doc](./page.md#heading) is local';
+ expect(extractLocalTargetOccurrences(md).map((o) => o.href)).toEqual(['./page.md#heading']);
+ });
+
+ test('a traversal-escaping path is still captured for downstream assessment, not silently dropped', () => {
+ // Recognition makes no existence claim; it captures the authored path with an
+ // exact range so the assessment layer can report it, rather than treating it
+ // as a valid local file.
+ const md = '[x](../../../../etc/passwd)';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ?.href).toBe('../../../../etc/passwd');
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('[x](../../../../etc/passwd)');
+ });
+});
+
+describe('positions fold in frontmatter and CRLF exactly', () => {
+ test('line numbers count frontmatter lines and ranges stay byte-exact', () => {
+ const md = ['---', 'title: x', '---', '', 'Body [doc](./guide.md).'].join('\n');
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ?.line).toBe(4);
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('[doc](./guide.md)');
+ });
+
+ test('CRLF documents keep exact byte ranges', () => {
+ const md = 'Line one\r\n![p](./photo.png)\r\nLine three';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(occ?.line).toBe(1);
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('![p](./photo.png)');
+ });
+
+ test('a CRLF frontmatter block offsets the body range correctly', () => {
+ const md = '---\r\ntitle: x\r\n---\r\n[doc](./guide.md)';
+ const [occ] = extractLocalTargetOccurrences(md);
+ expect(md.slice(occ?.range.start, occ?.range.end)).toBe('[doc](./guide.md)');
+ });
+});
+
+describe('mixed corpus byte-preservation invariant', () => {
+ test('every emitted occurrence and repair range reproduces its authored bytes', () => {
+ const md = [
+ '---',
+ 'title: Mixed',
+ '---',
+ '# Heading',
+ '',
+ 'An inline [link](./a.md) and image ![alt](./b.png).',
+ 'HTML <img src="./c.png"> and self-closing <img src="./d.png"/>.',
+ 'Wiki [[Some Doc]] and embed ![[e.png]].',
+ 'Reference [use][ref] and [ref][] and [ref] shortcut.',
+ '',
+ '[ref]: ./f.pdf "a title"',
+ '',
+ '```',
+ '[ignored](./g.md)',
+ '```',
+ ].join('\n');
+ const occurrences = extractLocalTargetOccurrences(md);
+ // a.md, b.png, c.png, d.png, Some Doc, e.png, ref x3
+ expect(occurrences).toHaveLength(9);
+ assertByteExact(md, occurrences);
+ for (const occ of occurrences) {
+ if (occ.reference) {
+ const { start, end } = occ.reference.definition.repairRange;
+ expect(md.slice(start, end)).toBe('./f.pdf');
+ }
+ }
+ // Fenced content never leaks in.
+ expect(occurrences.some((o) => o.href.includes('g.md'))).toBe(false);
+ });
+});
diff --git a/packages/server/src/local-target-occurrences.ts b/packages/server/src/local-target-occurrences.ts
new file mode 100644
index 000000000..f1d257c1c
--- /dev/null
+++ b/packages/server/src/local-target-occurrences.ts
@@ -0,0 +1,520 @@
+/**
+ * Lossless extraction of local-target link/image occurrences from a document's
+ * markdown source. One positioned record per authored occurrence — every
+ * supported syntax reduced to a common shape so downstream assessment
+ * (existence, reason, projection) works from the same authored intent.
+ *
+ * This is recognition + positioning only. It does NOT resolve a target to a
+ * project identity or check existence (a later assessment layer owns that): the
+ * record carries the authored href and an exact source range, and reference-style
+ * uses carry a pointer to their shared definition. Authored bytes are never
+ * rewritten; `source.slice(range.start, range.end)` reproduces an occurrence
+ * verbatim.
+ *
+ * Recognition reuses the shared grammar in `link-syntax.ts`. Only targets that
+ * could be project-local enter the result — external URLs and bare anchors are
+ * dropped here so no consumer mistakes them for a local file.
+ */
+
+import {
+ isExternalHref,
+ maskNonRenderingContextLines,
+ normalizeReferenceLabel,
+ skipInlineCode,
+ stripFrontmatter,
+} from '@inkeep/open-knowledge-core';
+import {
+ type HtmlImgMatch,
+ type MarkdownReferenceMatch,
+ type ReferenceDefinitionMatch,
+ readHtmlImgAt,
+ readMarkdownLinkAt,
+ readMarkdownReferenceAt,
+ readReferenceDefinition,
+ readWikiLinkAt,
+ type WikiLinkMatch,
+} from './link-syntax.ts';
+
+/** Whether the occurrence renders as a link (navigable) or an image (embedded). */
+type OccurrenceRole = 'link' | 'image';
+
+/** The authored syntax family an occurrence came from. */
+export type OccurrenceSourceForm =
+ | 'markdown-inline'
+ | 'markdown-reference'
+ | 'html-img'
+ | 'wiki-link'
+ | 'wiki-embed';
+
+interface SourceRange {
+ /** Inclusive start char offset into the full raw document source. */
+ start: number;
+ /** Exclusive end char offset. `source.slice(start, end)` reproduces the authored occurrence. */
+ end: number;
+}
+
+interface ReferenceDefinition {
+ /** Normalized (case-folded, whitespace-collapsed) label. */
+ label: string;
+ /** Destination as authored, angle-unwrapped. */
+ href: string;
+ /** Destination exactly as authored, including any `<…>` wrapper. */
+ hrefRaw: string;
+ /** Source range of the destination token — where a rewriter repairs the link. */
+ repairRange: SourceRange;
+ /** 0-based full-document line of the definition. */
+ line: number;
+}
+
+interface ReferenceUseDetail {
+ /** Normalized label this use resolved against. */
+ label: string;
+ /** Authored reference shape. */
+ kind: 'full' | 'collapsed' | 'shortcut';
+ /**
+ * The definition this use points at. Uses of the same label share one object
+ * identity, so a repair to the definition heals every use. Present on every
+ * emitted reference occurrence — a use with no matching definition is not a
+ * link and is not emitted.
+ */
+ definition: ReferenceDefinition;
+}
+
+export interface LocalTargetOccurrence {
+ role: OccurrenceRole;
+ sourceForm: OccurrenceSourceForm;
+ /**
+ * Authored destination href. For a reference use this is the shared
+ * definition's destination; for a wiki form it is the target token.
+ */
+ href: string;
+ /** Exact source range of the whole authored occurrence. */
+ range: SourceRange;
+ /** 0-based full-document line of the occurrence. */
+ line: number;
+ /** 0-based column (char offset from the line start) of the occurrence. */
+ column: number;
+ /** Present for reference-style uses only. */
+ reference?: ReferenceUseDetail;
+}
+
+interface BodyLine {
+ text: string;
+ /** Offset of the line's first char within the frontmatter-stripped body. */
+ start: number;
+}
+
+interface ReferenceDefinitionBlock {
+ match: ReferenceDefinitionMatch;
+ /** Line holding `[label]:`; a continued destination may live on the next line. */
+ definitionLine: number;
+ /** Body-relative offset of the destination token. */
+ destinationOffset: number;
+ /** Every source line consumed by the definition, including a continued title. */
+ consumedLines: number[];
+}
+
+interface DefinitionCollection {
+ definitions: Map<string, ReferenceDefinition>;
+ definitionLines: Set<number>;
+}
+
+/**
+ * CommonMark label matching folds case and collapses internal whitespace, so
+ * `[Foo Bar]` and `[foo bar]` resolve to one definition. Trimming handles the
+ * leading/trailing whitespace a collapsed/shortcut label may carry. The
+ * collapse set is micromark's markdown whitespace, `[\t\n\r ]` — `\s` would
+ * also collapse non-markdown whitespace (NBSP), unifying labels CommonMark
+ * keeps distinct. The shared core helper matches micromark's Unicode-aware
+ * CommonMark identifier keys.
+ */
+/**
+ * True when an authored href could name a project-local target. Excludes
+ * external URLs (any scheme, protocol-relative) and bare anchors, which are
+ * never local files, and empty destinations. A relative or root-relative path —
+ * including one that walks past the root — passes; deciding whether it resolves
+ * is the assessment layer's job, not recognition's.
+ */
+function isLocalTargetCandidateHref(rawHref: string): boolean {
+ const trimmed = rawHref.trim();
+ if (!trimmed) return false;
+ if (trimmed.startsWith('#')) return false;
+ return !isExternalHref(trimmed);
+}
+
+/**
+ * Split a body into lines with their byte offsets, preserving `\r\n` / `\r` / `\n`
+ * exactly (no normalization) so ranges map onto the raw source. Each line's
+ * `text` excludes its terminator; `start` is the offset of its first char.
+ */
+function splitLinesWithOffsets(body: string): BodyLine[] {
+ const lines: BodyLine[] = [];
+ let start = 0;
+ for (let i = 0; i < body.length; i++) {
+ const ch = body[i];
+ if (ch === '\n') {
+ lines.push({ text: body.slice(start, i), start });
+ start = i + 1;
+ } else if (ch === '\r') {
+ lines.push({ text: body.slice(start, i), start });
+ if (body[i + 1] === '\n') i += 1;
+ start = i + 1;
+ }
+ }
+ lines.push({ text: body.slice(start), start });
+ return lines;
+}
+
+/** Count line terminators (`\n`, `\r`, `\r\n`) — the body's first line index. */
+function countLineTerminators(text: string): number {
+ let count = 0;
+ for (let i = 0; i < text.length; i++) {
+ if (text[i] === '\n') {
+ count += 1;
+ } else if (text[i] === '\r') {
+ count += 1;
+ if (text[i + 1] === '\n') i += 1;
+ }
+ }
+ return count;
+}
+
+interface ScanContext {
+ /** Full-document offset of the line's first char. */
+ lineOffset: number;
+ /** 0-based full-document line number. */
+ lineNumber: number;
+ definitions: Map<string, ReferenceDefinition>;
+ out: LocalTargetOccurrence[];
+}
+
+function pushOccurrence(
+ ctx: ScanContext,
+ fields: Omit<LocalTargetOccurrence, 'range' | 'line' | 'column'> & {
+ startCol: number;
+ endCol: number;
+ },
+): void {
+ const { startCol, endCol, ...rest } = fields;
+ ctx.out.push({
+ ...rest,
+ range: { start: ctx.lineOffset + startCol, end: ctx.lineOffset + endCol },
+ line: ctx.lineNumber,
+ column: startCol,
+ });
+}
+
+function emitWiki(ctx: ScanContext, match: WikiLinkMatch, startCol: number): void {
+ if (!isLocalTargetCandidateHref(match.target)) return;
+ pushOccurrence(ctx, {
+ role: match.embed ? 'image' : 'link',
+ sourceForm: match.embed ? 'wiki-embed' : 'wiki-link',
+ href: match.target,
+ startCol,
+ endCol: match.end,
+ });
+}
+
+function emitHtmlImg(ctx: ScanContext, match: HtmlImgMatch, startCol: number): void {
+ if (!isLocalTargetCandidateHref(match.src)) return;
+ pushOccurrence(ctx, {
+ role: 'image',
+ sourceForm: 'html-img',
+ href: match.src,
+ startCol,
+ endCol: match.end,
+ });
+}
+
+/**
+ * Resolve a reference use against the definition table and emit it when it
+ * resolves to a local-target candidate. Returns the index to resume scanning
+ * from: the whole form is consumed whether or not it emits, matching CommonMark's
+ * treatment of an unresolved reference as literal text.
+ */
+function handleReference(ctx: ScanContext, ref: MarkdownReferenceMatch): number {
+ const key =
+ ref.form === 'full'
+ ? normalizeReferenceLabel(ref.referenceLabelRaw)
+ : normalizeReferenceLabel(ref.label);
+ const definition = ctx.definitions.get(key);
+ if (definition && isLocalTargetCandidateHref(definition.href)) {
+ pushOccurrence(ctx, {
+ role: ref.image ? 'image' : 'link',
+ sourceForm: 'markdown-reference',
+ href: definition.href,
+ startCol: ref.start,
+ endCol: ref.end,
+ reference: { label: definition.label, kind: ref.form, definition },
+ });
+ }
+ return ref.end;
+}
+
+/**
+ * Scan one body line for occurrences. Escapes, inline code, and both bracket
+ * families are honored so a link inside code, or one whose `[` is backslash-
+ * escaped, never produces a false occurrence. Dispatch order mirrors the
+ * backlink indexer: wiki forms before markdown so `[[…]]` is not re-read as a
+ * markdown link.
+ */
+function scanLine(ctx: ScanContext, line: string): void {
+ let idx = 0;
+ while (idx < line.length) {
+ const ch = line[idx];
+
+ if (ch === '\\') {
+ idx += 2;
+ continue;
+ }
+
+ if (ch === '`') {
+ const next = skipInlineCode(line, idx);
+ if (next !== null) {
+ idx = next;
+ continue;
+ }
+ }
+
+ if (ch === '<') {
+ const img = readHtmlImgAt(line, idx);
+ if (img) {
+ emitHtmlImg(ctx, img, idx);
+ idx = img.end;
+ continue;
+ }
+ }
+
+ if (ch === '!' && line[idx + 1] === '[' && line[idx + 2] === '[') {
+ const wiki = readWikiLinkAt(line, idx);
+ if (wiki) {
+ emitWiki(ctx, wiki, idx);
+ idx = wiki.end;
+ } else {
+ idx += 1;
+ }
+ continue;
+ }
+
+ if (ch === '[' && line[idx + 1] === '[') {
+ const wiki = readWikiLinkAt(line, idx);
+ if (wiki) {
+ emitWiki(ctx, wiki, idx);
+ idx = wiki.end;
+ } else {
+ idx += 1;
+ }
+ continue;
+ }
+
+ if (ch === '!' && line[idx + 1] === '[') {
+ const inline = readMarkdownLinkAt(line, idx);
+ if (inline?.image) {
+ if (isLocalTargetCandidateHref(inline.href)) {
+ pushOccurrence(ctx, {
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ href: inline.href,
+ startCol: idx,
+ endCol: inline.end,
+ });
+ }
+ idx = inline.end;
+ continue;
+ }
+ const ref = readMarkdownReferenceAt(line, idx);
+ if (ref?.image) {
+ idx = handleReference(ctx, ref);
+ continue;
+ }
+ }
+
+ if (ch === '[') {
+ // Badge form: the outer link and inner image are two independently
+ // repairable destinations. The strict matcher intentionally reads the
+ // inner destination at the outer opener, so recognize this composition
+ // before the generic branch and emit both exact ranges.
+ const innerImage = readMarkdownLinkAt(line, idx + 1);
+ const outerLink = readMarkdownLinkAt(line, idx, { nestedBracketLabels: true });
+ if (
+ innerImage?.image === true &&
+ outerLink?.image === false &&
+ outerLink.end > innerImage.end &&
+ line[innerImage.end] === ']'
+ ) {
+ if (isLocalTargetCandidateHref(outerLink.href)) {
+ pushOccurrence(ctx, {
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ href: outerLink.href,
+ startCol: idx,
+ endCol: outerLink.end,
+ });
+ }
+ if (isLocalTargetCandidateHref(innerImage.href)) {
+ pushOccurrence(ctx, {
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ href: innerImage.href,
+ startCol: idx + 1,
+ endCol: innerImage.end,
+ });
+ }
+ idx = outerLink.end;
+ continue;
+ }
+
+ const inline = readMarkdownLinkAt(line, idx);
+ if (inline && !inline.image) {
+ if (isLocalTargetCandidateHref(inline.href)) {
+ pushOccurrence(ctx, {
+ role: 'link',
+ sourceForm: 'markdown-inline',
+ href: inline.href,
+ startCol: idx,
+ endCol: inline.end,
+ });
+ }
+ idx = inline.end;
+ continue;
+ }
+ const ref = readMarkdownReferenceAt(line, idx);
+ if (ref && !ref.image) {
+ idx = handleReference(ctx, ref);
+ continue;
+ }
+ }
+
+ idx += 1;
+ }
+}
+
+const REFERENCE_HEADER_ONLY_RE = /^( {0,3}\[([^\]\n]+)\]:)[ \t]*$/;
+const REFERENCE_DESTINATION_CONTINUATION_RE =
+ /^([ \t]*)(<[^>\n]*>|[^\s\n]+)((?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)[ \t]*$/;
+const REFERENCE_TITLE_ONLY_RE = /^[ \t]*(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\))[ \t]*$/;
+
+function continuedTitleLine(lines: BodyLine[], index: number): number | null {
+ const next = lines[index + 1]?.text;
+ return next !== undefined && REFERENCE_TITLE_ONLY_RE.test(next) ? index + 1 : null;
+}
+
+/** Parse the one-, two-, or three-line CommonMark definition beginning at `index`. */
+function readReferenceDefinitionBlock(
+ lines: BodyLine[],
+ index: number,
+): ReferenceDefinitionBlock | null {
+ const line = lines[index];
+ if (!line) return null;
+ const direct = readReferenceDefinition(line.text);
+ if (direct) {
+ const titleLine = direct.titleSuffix ? null : continuedTitleLine(lines, index);
+ return {
+ match: direct,
+ definitionLine: index,
+ destinationOffset: line.start + direct.destinationStart,
+ consumedLines: titleLine === null ? [index] : [index, titleLine],
+ };
+ }
+
+ const header = REFERENCE_HEADER_ONLY_RE.exec(line.text);
+ const destinationLine = lines[index + 1];
+ if (!header || !destinationLine) return null;
+ const continuation = REFERENCE_DESTINATION_CONTINUATION_RE.exec(destinationLine.text);
+ if (!continuation) return null;
+ const destinationRaw = continuation[2] ?? '';
+ const destinationIndent = continuation[1]?.length ?? 0;
+ const titleSuffix = continuation[3] ?? '';
+ const titleLine = titleSuffix ? null : continuedTitleLine(lines, index + 1);
+ return {
+ match: {
+ label: header[2] ?? '',
+ destinationRaw,
+ destination:
+ destinationRaw.startsWith('<') && destinationRaw.endsWith('>')
+ ? destinationRaw.slice(1, -1)
+ : destinationRaw,
+ destinationStart: destinationIndent,
+ destinationEnd: destinationIndent + destinationRaw.length,
+ titleSuffix,
+ },
+ definitionLine: index,
+ destinationOffset: destinationLine.start + destinationIndent,
+ consumedLines: titleLine === null ? [index, index + 1] : [index, index + 1, titleLine],
+ };
+}
+
+/**
+ * First pass: collect every link reference definition, keyed by normalized
+ * label. The first definition of a label wins (CommonMark). Input lines already
+ * have fenced code and non-rendering HTML regions positionally masked; indented
+ * definitions are rejected by the definition grammar.
+ */
+function collectDefinitions(
+ lines: BodyLine[],
+ bodyOffset: number,
+ lineNumberOffset: number,
+): DefinitionCollection {
+ const definitions = new Map<string, ReferenceDefinition>();
+ const definitionLines = new Set<number>();
+ for (let i = 0; i < lines.length; i++) {
+ const block = readReferenceDefinitionBlock(lines, i);
+ if (!block) continue;
+ for (const line of block.consumedLines) definitionLines.add(line);
+ const { match } = block;
+ const key = normalizeReferenceLabel(match.label);
+ if (definitions.has(key)) {
+ i = block.consumedLines.at(-1) ?? i;
+ continue;
+ }
+ definitions.set(key, {
+ // Keep the longstanding lowercase evidence shown to users while the map
+ // key follows CommonMark's full Unicode folding.
+ label: key.toLowerCase(),
+ href: match.destination,
+ hrefRaw: match.destinationRaw,
+ repairRange: {
+ start: bodyOffset + block.destinationOffset,
+ end: bodyOffset + block.destinationOffset + match.destinationRaw.length,
+ },
+ line: lineNumberOffset + block.definitionLine,
+ });
+ i = block.consumedLines.at(-1) ?? i;
+ }
+ return { definitions, definitionLines };
+}
+
+/**
+ * Extract every project-local-target link/image occurrence from a document's
+ * markdown source. Frontmatter and fenced code are excluded; reference uses are
+ * resolved against the document's own definitions.
+ */
+export function extractLocalTargetOccurrences(markdown: string): LocalTargetOccurrence[] {
+ const { frontmatter, body } = stripFrontmatter(markdown);
+ const bodyOffset = frontmatter.length;
+ const lineNumberOffset = countLineTerminators(frontmatter);
+ const sourceLines = splitLinesWithOffsets(body);
+ const lines = maskNonRenderingContextLines(sourceLines);
+
+ const { definitions, definitionLines } = collectDefinitions(lines, bodyOffset, lineNumberOffset);
+
+ const out: LocalTargetOccurrence[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const { text, start } = lines[i] as BodyLine;
+ // Definition blocks render no content, so none of their consumed lines hold
+ // uses. Skipping all of them also prevents a continued title from being
+ // interpreted as ordinary body text.
+ if (definitionLines.has(i)) continue;
+ if (/^(?: {4}|\t)/.test(sourceLines[i]?.text ?? '')) continue;
+ scanLine(
+ {
+ lineOffset: bodyOffset + start,
+ lineNumber: lineNumberOffset + i,
+ definitions,
+ out,
+ },
+ text,
+ );
+ }
+ return out;
+}
diff --git a/packages/server/src/local-target-watcher-integration.test.ts b/packages/server/src/local-target-watcher-integration.test.ts
new file mode 100644
index 000000000..696dd486c
--- /dev/null
+++ b/packages/server/src/local-target-watcher-integration.test.ts
@@ -0,0 +1,60 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { createContentFilter } from './content-filter.ts';
+import { DerivedDocumentIndex } from './derived-document-index.ts';
+import { startWatcher } from './file-watcher.ts';
+import { localTargetInventoryFromWatcher } from './local-target-inventory.ts';
+
+const cleanups: Array<() => Promise<void> | void> = [];
+
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0)) await cleanup();
+});
+
+describe('local-target watcher integration', () => {
+ test('startup seeds ordinary-file existence from the real watcher inventory', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-lti-watch-'));
+ const contentDir = join(projectDir, 'content');
+ mkdirSync(join(contentDir, 'assets'), { recursive: true });
+ writeFileSync(
+ join(contentDir, 'src.md'),
+ 'Report [here](assets/report.pdf), image ![p](assets/logo.png), gone [x](assets/missing.pdf).\n',
+ );
+ writeFileSync(join(contentDir, 'assets', 'report.pdf'), '%PDF-1.4 test\n');
+ writeFileSync(join(contentDir, 'assets', 'logo.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ const contentFilter = createContentFilter({ projectDir, contentDir });
+
+ // Real watcher: its seed walk indexes report.pdf and logo.png as kind:'file'
+ // under their content-root-relative paths.
+ const watcher = await startWatcher(contentDir, async () => {}, contentFilter);
+ const index = new DerivedDocumentIndex({
+ projectDir,
+ contentDir,
+ contentFilter,
+ getGlobalSkillRoots: () => [],
+ signalChannel: () => {},
+ getLocalTargetInventory: () => localTargetInventoryFromWatcher(watcher, contentDir),
+ });
+ cleanups.push(async () => {
+ await index.close();
+ await watcher.unsubscribe();
+ rmSync(projectDir, { recursive: true, force: true });
+ });
+
+ const startup = index.beginStartup('main');
+ await startup.backlinksReady;
+ await index.settleStartupAfterWatcherSeed();
+
+ const status = Object.fromEntries(
+ (await index.getLocalTargetAssessments('src')).map((a) => [a.resolvedTarget, a.status]),
+ );
+ // The real watcher's file-index key equals the assessment's resolved
+ // content-root-relative identity, so present files are exact and the absent
+ // one is missing — the cross-boundary key alignment that lets findings heal.
+ expect(status['assets/report.pdf']).toBe('exact');
+ expect(status['assets/logo.png']).toBe('exact');
+ expect(status['assets/missing.pdf']).toBe('missing');
+ });
+});
diff --git a/packages/server/src/mcp/tools/advisory-warnings.test.ts b/packages/server/src/mcp/tools/advisory-warnings.test.ts
index a6017935e..8a62094ca 100644
--- a/packages/server/src/mcp/tools/advisory-warnings.test.ts
+++ b/packages/server/src/mcp/tools/advisory-warnings.test.ts
@@ -152,6 +152,37 @@ const noSuchFile: BrokenLink = {
reason: 'no-such-file',
};
+const brokenImage: BrokenLink = {
+ href: './logo.png',
+ resolvedTo: 'assets/logo.png',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'assets/logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+};
+
+const brokenReference: BrokenLink = {
+ href: './spec.pdf',
+ resolvedTo: 'spec.pdf',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './spec.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'spec.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ definition: { line: 11, label: 'spec' },
+ },
+};
+
describe('parseBrokenLinks', () => {
test('parses a well-formed array (all three reasons)', () => {
expect(parseBrokenLinks([noSuchDoc, noSuchFile, unresolvable])).toEqual([
@@ -181,6 +212,13 @@ describe('parseBrokenLinks', () => {
test('returns [] for an empty array (the all-resolve confirmation)', () => {
expect(parseBrokenLinks([])).toEqual([]);
});
+
+ test('preserves additive local-target evidence through the parse (image + reference)', () => {
+ expect(parseBrokenLinks([brokenImage, brokenReference])).toEqual([
+ brokenImage,
+ brokenReference,
+ ]);
+ });
});
describe('formatBrokenLinkLines', () => {
@@ -211,6 +249,18 @@ describe('formatBrokenLinkLines', () => {
expect(lines[0]).toContain('2 broken outbound links —');
expect(lines).toHaveLength(3);
});
+
+ test('an image finding renders its role so the break is not read as a doc link', () => {
+ const lines = formatBrokenLinkLines([brokenImage]);
+ expect(lines[1]).toBe(' • image ./logo.png → assets/logo.png (no-such-file)');
+ });
+
+ test('a reference-style finding points at its shared definition (1-based line)', () => {
+ const lines = formatBrokenLinkLines([brokenReference]);
+ expect(lines[1]).toBe(
+ ' • ./spec.pdf → spec.pdf (no-such-file) — fix the [spec] definition (line 12)',
+ );
+ });
});
describe('formatBrokenLinkBrief', () => {
diff --git a/packages/server/src/mcp/tools/advisory-warnings.ts b/packages/server/src/mcp/tools/advisory-warnings.ts
index 9e5dc300c..7c93a9611 100644
--- a/packages/server/src/mcp/tools/advisory-warnings.ts
+++ b/packages/server/src/mcp/tools/advisory-warnings.ts
@@ -73,9 +73,16 @@ export function formatBrokenLinkBrief(links: BrokenLink[]): string | null {
}
function formatBrokenLink(link: BrokenLink): string {
- return link.resolvedTo
- ? `${link.href} → ${link.resolvedTo} (${link.reason})`
- : `${link.href} (${link.reason})`;
+ // An image reads as a different kind of break than a link; the plain triple
+ // can't say which, so surface the role when the evidence carries it.
+ const rolePrefix = link.localTarget?.role === 'image' ? 'image ' : '';
+ const base = link.resolvedTo
+ ? `${rolePrefix}${link.href} → ${link.resolvedTo} (${link.reason})`
+ : `${rolePrefix}${link.href} (${link.reason})`;
+ // A reference-style target is repaired at its shared definition, not at the
+ // use — point the agent there (definition line is 0-based; show it 1-based).
+ const def = link.localTarget?.definition;
+ return def ? `${base} — fix the [${def.label}] definition (line ${def.line + 1})` : base;
}
function integrityEntries(warnings: AdvisoryWarning[]): WriteWarning[] {
diff --git a/packages/server/src/mcp/tools/audit.test.ts b/packages/server/src/mcp/tools/audit.test.ts
index 146df731b..908a92e19 100644
--- a/packages/server/src/mcp/tools/audit.test.ts
+++ b/packages/server/src/mcp/tools/audit.test.ts
@@ -102,6 +102,27 @@ function deadLinkError(line: number, target: string) {
};
}
+// A local-target (image) finding as the links validator emits it: the graph
+// triple plus additive `localTarget` evidence and an image-specific message.
+function deadImageWarning(line: number, href: string, resolved: string) {
+ return {
+ range: { start: { line, character: 0 }, end: { line, character: 0 } },
+ severity: 'warning',
+ source: 'links',
+ code: 'dead-link',
+ message: `Image target "${href}" does not resolve to an existing file.`,
+ localTarget: {
+ href,
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: resolved,
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ };
+}
+
function auditPayloadOf(fileCount: number, diagnosticsPerFile: number) {
const files = Array.from({ length: fileCount }, (_, i) => ({
file: `doc-${String(i).padStart(2, '0')}.md`,
@@ -155,6 +176,21 @@ beforeAll(async () => {
warnings: ['links validation unavailable: backlink index is not configured'],
});
}
+ if (path === 'local-targets') {
+ return Response.json({
+ ok: true,
+ files: [
+ {
+ file: 'notes/pics.md',
+ diagnostics: [deadImageWarning(3, './logo.png', 'assets/logo.png')],
+ },
+ ],
+ fileCount: 1,
+ errorCount: 0,
+ warningCount: 1,
+ warnings: [],
+ });
+ }
if (path === 'problems-and-warnings') {
return Response.json({
ok: true,
@@ -272,6 +308,30 @@ describe('audit — unified project audit', () => {
expect(text).toContain('"ghost"');
});
+ test('preserves local-target evidence in structured output; text message stays intelligible', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const result = await getTool().handler({ path: 'local-targets' });
+ const s = result.structuredContent as {
+ files: Array<{ diagnostics: Array<{ localTarget?: Record<string, unknown> }> }>;
+ };
+ // The additive evidence survives the MCP structured channel verbatim.
+ expect(s.files[0]?.diagnostics[0]?.localTarget).toEqual({
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'assets/logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ });
+ // The human-facing text distinguishes an image-file break from a doc link
+ // without relying on the structured evidence.
+ const text = result.content[0]?.text ?? '';
+ expect(text).toContain('Image target "./logo.png" does not resolve to an existing file');
+ expect(text).toContain('links/dead-link');
+ });
+
test('passes a sub-path scope through to the audit endpoint', async () => {
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
diff --git a/packages/server/src/recovered-file-target.test.ts b/packages/server/src/recovered-file-target.test.ts
new file mode 100644
index 000000000..464bac686
--- /dev/null
+++ b/packages/server/src/recovered-file-target.test.ts
@@ -0,0 +1,95 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
+import type { DiskEvent, WatcherHandle } from './file-watcher.ts';
+import { getLogger } from './logger.ts';
+import { reconcileRecoveredFileTarget } from './recovered-file-target.ts';
+
+describe('reconcileRecoveredFileTarget', () => {
+ test('evicts the file index and referenced-asset cache after a recovered delete', () => {
+ const mutations: DiskEvent[] = [];
+ const invalidateReferencedAssetsCache = vi.fn();
+ const contentDir = '/project';
+
+ reconcileRecoveredFileTarget({
+ watcher: {
+ mutateFileIndex: (event) => mutations.push(event),
+ } satisfies Pick<WatcherHandle, 'mutateFileIndex'>,
+ contentDir,
+ relativePath: 'assets/report.pdf',
+ exists: false,
+ invalidateReferencedAssetsCache,
+ });
+
+ expect(mutations).toEqual([
+ {
+ kind: 'file-delete',
+ path: join(contentDir, 'assets/report.pdf'),
+ relativePath: 'assets/report.pdf',
+ },
+ ]);
+ expect(invalidateReferencedAssetsCache).toHaveBeenCalledOnce();
+ });
+
+ test('warns when recovered file metadata fails for a reason other than disappearance', () => {
+ const warnSpy = vi.spyOn(getLogger('recovered-file-target'), 'warn');
+ const mutations: DiskEvent[] = [];
+ const relativePath = 'a'.repeat(5_000);
+
+ reconcileRecoveredFileTarget({
+ watcher: {
+ mutateFileIndex: (event) => mutations.push(event),
+ } satisfies Pick<WatcherHandle, 'mutateFileIndex'>,
+ contentDir: '/',
+ relativePath,
+ exists: true,
+ invalidateReferencedAssetsCache: null,
+ });
+
+ expect(mutations).toHaveLength(1);
+ expect(mutations[0]).toMatchObject({ kind: 'file-delete', relativePath });
+ expect(warnSpy).toHaveBeenCalledWith(
+ { code: 'ENAMETOOLONG' },
+ 'recovered file metadata unavailable; treating local target as deleted',
+ );
+ });
+
+ test('restores a recovered file with its canonical metadata', () => {
+ const contentDir = mkdtempSync(join(tmpdir(), 'ok-recovered-file-target-'));
+ try {
+ const relativePath = 'assets/report.pdf';
+ mkdirSync(join(contentDir, 'assets'));
+ const targetPath = join(contentDir, relativePath);
+ writeFileSync(targetPath, 'report');
+ const canonicalPath = realpathSync(targetPath);
+ const stats = statSync(canonicalPath);
+ const mutations: DiskEvent[] = [];
+ const invalidateReferencedAssetsCache = vi.fn();
+
+ reconcileRecoveredFileTarget({
+ watcher: {
+ mutateFileIndex: (event) => mutations.push(event),
+ } satisfies Pick<WatcherHandle, 'mutateFileIndex'>,
+ contentDir,
+ relativePath,
+ exists: true,
+ invalidateReferencedAssetsCache,
+ });
+
+ expect(mutations).toEqual([
+ {
+ kind: 'file-create',
+ path: canonicalPath,
+ relativePath,
+ size: stats.size,
+ modifiedTs: stats.mtimeMs,
+ inode: stats.ino,
+ },
+ ]);
+ expect(invalidateReferencedAssetsCache).toHaveBeenCalledOnce();
+ } finally {
+ rmSync(contentDir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/recovered-file-target.ts b/packages/server/src/recovered-file-target.ts
new file mode 100644
index 000000000..82963c949
--- /dev/null
+++ b/packages/server/src/recovered-file-target.ts
@@ -0,0 +1,57 @@
+import { realpathSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import type { WatcherHandle } from './file-watcher.ts';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('recovered-file-target');
+
+interface ReconcileRecoveredFileTargetOptions {
+ watcher: Pick<WatcherHandle, 'mutateFileIndex'>;
+ contentDir: string;
+ relativePath: string;
+ exists: boolean;
+ invalidateReferencedAssetsCache: (() => void) | null;
+}
+
+/**
+ * Repair every inventory layer after the local-target sweep detects a file event
+ * the platform watcher missed. The file index and referenced-asset cache must
+ * advance together or link diagnostics can disagree until another disk event.
+ */
+export function reconcileRecoveredFileTarget({
+ watcher,
+ contentDir,
+ relativePath,
+ exists,
+ invalidateReferencedAssetsCache,
+}: ReconcileRecoveredFileTargetOptions): void {
+ const absolutePath = join(contentDir, relativePath);
+ if (!exists) {
+ watcher.mutateFileIndex({ kind: 'file-delete', path: absolutePath, relativePath });
+ invalidateReferencedAssetsCache?.();
+ return;
+ }
+
+ try {
+ const canonicalPath = realpathSync(absolutePath);
+ const stats = statSync(canonicalPath);
+ watcher.mutateFileIndex({
+ kind: 'file-create',
+ path: canonicalPath,
+ relativePath,
+ size: stats.size,
+ modifiedTs: stats.mtimeMs,
+ inode: stats.ino,
+ });
+ } catch (error) {
+ const code =
+ error instanceof Error && 'code' in error && typeof error.code === 'string'
+ ? error.code
+ : 'UNKNOWN';
+ if (code !== 'ENOENT') {
+ log.warn({ code }, 'recovered file metadata unavailable; treating local target as deleted');
+ }
+ watcher.mutateFileIndex({ kind: 'file-delete', path: absolutePath, relativePath });
+ }
+ invalidateReferencedAssetsCache?.();
+}
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 8cab15ab4..44ab94294 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -145,6 +145,7 @@ import {
isPeerAdmitted,
} from './ingress-policy.ts';
import { createLiveDerivedIndexExtension } from './live-derived-index.ts';
+import { localTargetInventoryFromWatcher } from './local-target-inventory.ts';
import { getLogger } from './logger.ts';
import { LossCaptureRing } from './loss-capture.ts';
import {
@@ -182,6 +183,7 @@ import {
import { loadPrincipal } from './principal.ts';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
import { reconcile } from './reconciliation.ts';
+import { reconcileRecoveredFileTarget } from './recovered-file-target.ts';
import { runRemovalRedirectGuard } from './removal-redirect-guard.ts';
import { loadRemovedDocsJournal, saveRemovedDocsJournal } from './removed-docs-journal.ts';
import {
@@ -1215,7 +1217,14 @@ export function createServer(options: ServerOptions): ServerInstance {
}
function signalChannel(
- channel: 'files' | 'backlinks' | 'graph' | 'tags' | 'comments' | 'lint-config',
+ channel:
+ | 'files'
+ | 'backlinks'
+ | 'graph'
+ | 'tags'
+ | 'comments'
+ | 'lint-config'
+ | 'local-targets',
): void {
cc1Broadcaster?.signal(channel);
}
@@ -1396,6 +1405,20 @@ export function createServer(options: ServerOptions): ServerInstance {
contentFilter,
getGlobalSkillRoots: () => managedArtifactSkillsRoots(persistence.managedArtifactCtx),
signalChannel,
+ // Late-bound so startup reads the seeded watcher. The snapshot includes
+ // canonical keys plus file/folder aliases; null means the watcher is
+ // unavailable and must not be mistaken for an authoritative empty tree.
+ getLocalTargetInventory: () => localTargetInventoryFromWatcher(watcher, contentDir),
+ onRecoveredFileTarget: (relativePath, exists) => {
+ if (!watcher) return;
+ reconcileRecoveredFileTarget({
+ watcher,
+ contentDir,
+ relativePath,
+ exists,
+ invalidateReferencedAssetsCache,
+ });
+ },
});
shadowRef = { current: shadowRepo };
@@ -2699,13 +2722,22 @@ export function createServer(options: ServerOptions): ServerInstance {
}
// file-* events maintain the in-memory fileIndex as `kind:'file'`. Like
// asset events they signal `files` (cache-invalidate /api/documents and
- // the workspace search corpus) but do NOT touch relationship views
+ // the workspace search corpus) and do NOT touch relationship views
// (those surfaces stay markdown-scoped). updateFileIndex
// in handleRawEvents already mutated the index by the time we arrive
- // here.
+ // here. They DO feed the local-target index so a `[x](y.pdf)` finding
+ // heals/breaks when its ordinary-file target appears/disappears; an
+ // ordinary-file rename arrives here as delete + create.
case 'file-create':
- case 'file-update':
+ case 'file-update': {
+ await derivedDocumentIndex.recordFileTargetUpsert(event.relativePath);
+ invalidateReferencedAssetsCache?.();
+ signalChannel('files');
+ break;
+ }
case 'file-delete': {
+ await derivedDocumentIndex.recordFileTargetDelete(event.relativePath);
+ invalidateReferencedAssetsCache?.();
signalChannel('files');
break;
}
diff --git a/packages/server/src/write-advisory-links.test.ts b/packages/server/src/write-advisory-links.test.ts
new file mode 100644
index 000000000..0a0086d81
--- /dev/null
+++ b/packages/server/src/write-advisory-links.test.ts
@@ -0,0 +1,245 @@
+import { describe, expect, test } from 'vitest';
+import { computeWriteAdvisoryLinks, type WriteAdvisoryLink } from './write-advisory-links.ts';
+
+/** Existence oracle from a fixed set of content-root-relative file paths. */
+function fileOracle(...paths: string[]): (rel: string) => boolean {
+ const set = new Set(paths);
+ return (rel) => set.has(rel);
+}
+
+describe('computeWriteAdvisoryLinks', () => {
+ 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());
+ // Document (inline + wiki) and ordinary-file LINKS are the graph scan's
+ // pre-existing contract — a plain triple with no local-target evidence.
+ expect(links).toEqual([
+ { href: './guide', resolvedTo: 'guide', reason: 'no-such-doc' },
+ { href: './data.csv', resolvedTo: 'data.csv', reason: 'no-such-file' },
+ { href: '[[Ghost]]', resolvedTo: 'Ghost', reason: 'no-such-doc' },
+ ]);
+ for (const link of links) expect(link.localTarget).toBeUndefined();
+ });
+
+ test('adds a missing Markdown image as a file finding with local-target evidence', () => {
+ const links = computeWriteAdvisoryLinks(
+ '![logo](./logo.png)\n',
+ 'notes',
+ new Set<string>(),
+ fileOracle(),
+ );
+ expect(links).toEqual([
+ {
+ href: './logo.png',
+ resolvedTo: 'logo.png',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './logo.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: 'logo.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ },
+ },
+ ] satisfies WriteAdvisoryLink[]);
+ });
+
+ test('adds a missing HTML img source as an html-img image finding', () => {
+ const links = computeWriteAdvisoryLinks(
+ '<img src="./banner.png" alt="banner">\n',
+ 'notes',
+ new Set<string>(),
+ fileOracle(),
+ );
+ expect(links).toHaveLength(1);
+ expect(links[0]?.localTarget).toEqual({
+ href: './banner.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'html-img',
+ resolvedTarget: 'banner.png',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ });
+ });
+
+ 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());
+ // Two uses of one reference resolve to one href — deduped to a single write
+ // advisory entry that carries the definition repair pointer.
+ expect(links).toEqual([
+ {
+ href: './spec.pdf',
+ resolvedTo: 'spec.pdf',
+ reason: 'no-such-file',
+ localTarget: {
+ href: './spec.pdf',
+ targetKind: 'file',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'spec.pdf',
+ reason: 'no-such-file',
+ resolutionMethod: 'source-relative',
+ definition: { line: 2, label: 'spec' },
+ },
+ },
+ ] satisfies WriteAdvisoryLink[]);
+ });
+
+ 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());
+
+ expect(links).toEqual([
+ {
+ href: 'guide',
+ resolvedTo: 'guide',
+ reason: 'no-such-doc',
+ localTarget: {
+ href: 'guide',
+ targetKind: 'document',
+ role: 'link',
+ sourceForm: 'markdown-reference',
+ resolvedTarget: 'guide',
+ reason: 'no-such-doc',
+ resolutionMethod: 'tolerant',
+ fallbackTarget: 'Guide',
+ definition: { line: 2, label: 'guide' },
+ },
+ },
+ ] satisfies WriteAdvisoryLink[]);
+ });
+
+ test('does not report an image whose target exists', () => {
+ const links = computeWriteAdvisoryLinks(
+ '![ok](./ok.png)\n',
+ 'notes',
+ new Set<string>(),
+ fileOracle('ok.png'),
+ );
+ expect(links).toEqual([]);
+ });
+
+ test('reports a root-escaping image as unresolvable (path arithmetic, oracle-independent)', () => {
+ const links = computeWriteAdvisoryLinks(
+ '![out](../../../out.png)\n',
+ 'notes',
+ new Set<string>(),
+ fileOracle('anything'),
+ );
+ expect(links).toEqual([
+ {
+ href: '../../../out.png',
+ resolvedTo: null,
+ reason: 'unresolvable',
+ localTarget: {
+ href: '../../../out.png',
+ targetKind: 'file',
+ role: 'image',
+ sourceForm: 'markdown-inline',
+ resolvedTarget: null,
+ reason: 'unresolvable',
+ resolutionMethod: 'none',
+ },
+ },
+ ] satisfies WriteAdvisoryLink[]);
+ });
+
+ test('preserves distinct link and image repair sites sharing one href', () => {
+ const links = computeWriteAdvisoryLinks(
+ '[x](./both.png) and ![y](./both.png)\n',
+ 'notes',
+ new Set<string>(),
+ fileOracle(),
+ );
+ expect(links).toHaveLength(2);
+ expect(links[0]).toEqual({
+ href: './both.png',
+ resolvedTo: 'both.png',
+ reason: 'no-such-file',
+ });
+ expect(links[1]?.localTarget).toMatchObject({ role: 'image', href: './both.png' });
+ });
+
+ test('a badge link reports the outer link and nested image without a synthetic duplicate', () => {
+ const links = computeWriteAdvisoryLinks(
+ '[![badge](./badge.png)](./target.md)',
+ 'notes',
+ new Set<string>(),
+ fileOracle(),
+ );
+
+ expect(links).toHaveLength(2);
+ expect(links.map((link) => [link.localTarget?.role, link.href])).toEqual([
+ ['link', './target.md'],
+ ['image', './badge.png'],
+ ]);
+ });
+
+ test('does not report markdown-looking links from non-rendering contexts', () => {
+ const markdown = [
+ '<!-- [comment](./comment.pdf) -->',
+ ' [indented](./indented.pdf)',
+ '<pre>[raw](./raw.pdf)</pre>',
+ ].join('\n');
+
+ expect(computeWriteAdvisoryLinks(markdown, 'notes', new Set<string>(), 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());
+
+ expect(links).toHaveLength(2);
+ expect(links.map((link) => link.localTarget?.definition)).toEqual([
+ { line: 2, label: 'one' },
+ { line: 3, label: 'two' },
+ ]);
+ });
+
+ 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());
+
+ 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(),
+ );
+ expect(links).toEqual([{ href: './guide', resolvedTo: 'guide', reason: 'no-such-doc' }]);
+ });
+
+ test('without a filesystem oracle, skips file/image findings but keeps document findings', () => {
+ const links = computeWriteAdvisoryLinks(
+ '[g](./g) and ![i](./i.png)\n',
+ 'notes',
+ new Set<string>(),
+ );
+ expect(links).toEqual([{ href: './g', resolvedTo: 'g', reason: 'no-such-doc' }]);
+ });
+
+ test('does not report a resolved link/image mix (all targets exist)', () => {
+ const links = computeWriteAdvisoryLinks(
+ '[home](./home.md) and ![pic](./pic.png)\n',
+ 'notes',
+ new Set(['home']),
+ fileOracle('pic.png'),
+ );
+ expect(links).toEqual([]);
+ });
+});
diff --git a/packages/server/src/write-advisory-links.ts b/packages/server/src/write-advisory-links.ts
new file mode 100644
index 000000000..0da73cc42
--- /dev/null
+++ b/packages/server/src/write-advisory-links.ts
@@ -0,0 +1,117 @@
+/**
+ * Write-time local-target advisory: the `brokenLinks` a write/edit response
+ * carries. Composes the graph-shaped byte scan (`computeBrokenOutboundLinks` —
+ * document links inline + wiki, ordinary-file links) with the shared local-target
+ * assessment (`assessLocalTargets`, the same predicate scoped audit runs) to add
+ * the forms the graph scan cannot describe: Markdown images, HTML `img` sources,
+ * and reference-style link/image targets — each carrying additive evidence
+ * identical to the audit plane, so write-time and audit-time agree on one target.
+ *
+ * Pure over its inputs, like `computeBrokenOutboundLinks`: it validates from the
+ * just-written bytes the write handler already holds, never the debounced index,
+ * so a write's advisory is fresh in the same response. Report-only — a broken
+ * local target never blocks the write.
+ */
+
+import type { LocalTargetDiagnosticEvidence } from '@inkeep/open-knowledge-core';
+import { type BrokenOutboundLink, computeBrokenOutboundLinks } from './backlink-index.ts';
+import {
+ assessLocalTargets,
+ buildLocalTargetEvidence,
+ createTolerantDocumentResolver,
+ type LocalTargetInventory,
+} from './local-target-assessment.ts';
+
+/**
+ * A broken outbound link plus optional local-target evidence. The base triple
+ * `{href, resolvedTo, reason}` is exactly the wire `BrokenLink`; `localTarget`
+ * is present for the assessed forms (images, reference-style) the graph scan
+ * omits, absent on the plain document/wiki links the triple already describes.
+ */
+export interface WriteAdvisoryLink extends BrokenOutboundLink {
+ localTarget?: LocalTargetDiagnosticEvidence;
+}
+
+/**
+ * The `brokenLinks` for a just-written document: graph-shaped links plus assessed
+ * image / reference-style targets. Inline graph links retain their historical
+ * per-href projection; assessed forms dedupe by repair site, so repeated uses of
+ * one reference definition collapse while distinct definitions/occurrences do not.
+ *
+ * @param markdown the full just-written source (frontmatter is stripped downstream)
+ * @param sourceDocName the doc being written (relative hrefs resolve against its dir)
+ * @param admittedDocs every docName that currently exists (the doc-existence oracle)
+ * @param fileExists oracle for a content-root-relative file path's on-disk existence;
+ * omit to skip file/image-existence checks (callers without a filesystem)
+ */
+export function computeWriteAdvisoryLinks(
+ markdown: string,
+ sourceDocName: string,
+ admittedDocs: Iterable<string>,
+ fileExists?: (contentRootRelativePath: string) => boolean,
+): WriteAdvisoryLink[] {
+ const admitted = admittedDocs instanceof Set ? admittedDocs : new Set(admittedDocs);
+
+ const inventory: LocalTargetInventory = {
+ hasDocument: (docName) => admitted.has(docName),
+ hasFile: (relPath) => (fileExists ? fileExists(relPath) : false),
+ resolveTolerantDocument: createTolerantDocumentResolver(admitted),
+ };
+ const assessments = assessLocalTargets(markdown, sourceDocName, inventory);
+ const inlineLinkHrefs = new Set(
+ assessments
+ .filter(
+ ({ occurrence }) =>
+ occurrence.sourceForm === 'markdown-inline' && occurrence.role === 'link',
+ )
+ .map(({ occurrence }) => occurrence.href),
+ );
+ // Graph-shaped scan: documents (inline + wiki) + ordinary-file links, deduped
+ // by href, in document order. Its strict label grammar reads a badge's inner
+ // image destination as a link and does not model every non-rendering block;
+ // retain markdown entries only when the lossless extractor observed a real
+ // inline link. Wiki entries keep their graph-owned `[[...]]` representation.
+ const links: WriteAdvisoryLink[] = computeBrokenOutboundLinks(
+ markdown,
+ sourceDocName,
+ admitted,
+ fileExists,
+ ).filter((link) => link.href.startsWith('[[') || inlineLinkHrefs.has(link.href));
+ const graphHrefs = new Set(links.map((link) => link.href));
+ const seenRepairSites = new Set<string>();
+
+ // The assessment shares classifiers with the scan, so a form both reach (an
+ // inline-markdown doc/file link) resolves to the same identity. The graph-href
+ // guard keeps the scan's entry and drops that duplicate rather than
+ // double-reporting, leaving the assessment to contribute only what the scan
+ // cannot: images and reference-style targets.
+ for (const assessment of assessments) {
+ // `reason` is null exactly for an exact (resolved) target — not a finding.
+ if (assessment.reason === null) continue;
+ // Without a filesystem oracle, ordinary-file existence is unknowable — mirror
+ // the graph scan, which skips file links rather than guess. Document and
+ // path-unresolvable (root-escape) findings need no oracle and still report.
+ if (!fileExists && assessment.targetKind === 'file') continue;
+ const { href, role, sourceForm, range, reference } = assessment.occurrence;
+ // Plain inline links already have the graph-shaped entry. Images sharing
+ // that href are distinct rendered occurrences and must still be retained.
+ if (role === 'link' && sourceForm === 'markdown-inline' && graphHrefs.has(href)) continue;
+ // Wiki forms are classified but do not project onto the local-target wire
+ // surfaces — `buildLocalTargetEvidence` owns that decision and signals it
+ // with null, so reading it is the single check rather than a second form
+ // predicate here that could drift from it.
+ const localTarget = buildLocalTargetEvidence(assessment, assessment.reason);
+ if (localTarget === null) continue;
+ const repairRange = reference?.definition.repairRange ?? range;
+ const repairSite = `${repairRange.start}:${repairRange.end}`;
+ if (seenRepairSites.has(repairSite)) continue;
+ seenRepairSites.add(repairSite);
+ links.push({
+ href,
+ resolvedTo: assessment.resolvedTarget,
+ reason: assessment.reason,
+ localTarget,
+ });
+ }
+ return links;
+}