Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): folder links navigate and stop reporting as dead (PRD-7956) (#3441)
Abrahambbb61ff6b912
diff --git a/.changeset/folder-links-resolve.md b/.changeset/folder-links-resolve.mdnew file mode 100644index 000000000..49a8d81d6--- /dev/null+++ b/.changeset/folder-links-resolve.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Folder links now work like links. Clicking a wiki link or markdown link that targets an existing folder opens the folder view (the same destination the Links panel already used) instead of doing nothing, and the Problems tab no longer reports links to existing folders as dead — the link audit's existence oracles learned folders on both of its planes, and folder existence stays fresh as documents beneath a folder come and go. Links to folders that do not exist still report as dead links.diff --git a/knip.config.ts b/knip.config.tsindex 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/src/editor/extensions/internal-link.ts b/packages/app/src/editor/extensions/internal-link.tsindex bbe6423c8..3bda5a545 100644--- a/packages/app/src/editor/extensions/internal-link.ts+++ b/packages/app/src/editor/extensions/internal-link.ts@@ -189,17 +189,16 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({// anchor / external here.switch (target.kind) {case 'doc': {- // Unresolved docs (target page missing OR a folder with no- // index) fall through so the popover surfaces "Create page" /- // "Create index" — the only useful action when there's no- // destination to navigate to.+ // Missing docs fall through so the popover surfaces "Create page" —+ // the only useful action when there's no destination to navigate+ // to. A folder target IS a destination: it opens the folder view at+ // `#/<folderPath>`, the same hash the Links panel navigates to.const cache = getPageListCache();const intent = resolveLinkTargetIntent(target.docName, {pages: cache?.pages ?? new Set<string>(),folderPaths: cache?.folderPaths ?? new Set<string>(),});if (intent.kind === 'create') return false;- if (intent.kind === 'navigate' && intent.displayState === 'folder') return false;if (newTab) {openInternalHashHrefInNewTab({ docName: target.docName, anchor: target.anchor });} else {diff --git a/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.tsindex 1f7e1c702..1c5c0b18d 100644--- a/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts+++ b/packages/app/src/editor/extensions/wiki-link.doc-activation.test.ts@@ -121,6 +121,24 @@ describe('WYSIWYG wiki-link activation', () => {expect(currentHash()).toBe('#/notes/roadmap');});+ test('a target naming an existing folder opens the folder view (PRD-7956)', () => {+ // 'notes' is in folderPaths but is NOT a page and has no index doc — the+ // pre-fix behavior dead-ended here (handlePrimary returned false and the+ // chip read as inert). The folder view at `#/notes` is the destination+ // the Links panel already navigates to; the chip must agree.+ const { activate, currentHash } = mountWikiLink('notes');++ expect(activate()).toBe(true);+ expect(currentHash()).toBe('#/notes');+ });++ test('a target naming a missing page still falls through to create (returns false)', () => {+ const { activate, currentHash } = mountWikiLink('totally/absent-page');++ expect(activate()).toBe(false);+ expect(currentHash()).toBe('');+ });+test('a target naming a real asset still opens the asset viewer', () => {const { activate, currentHash } = mountWikiLink('meeting.pdf');diff --git a/packages/app/src/editor/extensions/wiki-link.ts b/packages/app/src/editor/extensions/wiki-link.tsindex 478ae27c9..363913439 100644--- a/packages/app/src/editor/extensions/wiki-link.ts+++ b/packages/app/src/editor/extensions/wiki-link.ts@@ -321,11 +321,13 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({const layer = getInteractionLayer(editor);// Bare click navigates to the target (doc/anchor same-tab, external// always new-tab, asset same-tab). Cmd/Ctrl/middle-click forces- // new-tab. Unresolved doc targets (page missing or folder with no- // index) return false so the popover surfaces "Create page" / "Create- // index" — the only useful action when there's nothing to navigate- // to. Reads `currentNode.attrs` (reassigned by the `update` hook- // below on PropPanel edits).+ // new-tab. Missing doc targets return false so the popover surfaces+ // "Create page" — the only useful action when there's nothing to+ // navigate to. A folder target (with or without an index doc) IS a+ // destination: it opens the folder view at `#/<folderPath>`, the same+ // hash the Links panel already navigates to. Reads+ // `currentNode.attrs` (reassigned by the `update` hook below on+ // PropPanel edits).//// Single source for primary-navigation: both the InteractionLayer// (chip click / Enter) and the PropPanel's clickable destination text@@ -354,7 +356,6 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({fallbackTargets: getWikiLinkResolutionCandidates(liveTarget),});if (intent.kind === 'create') return false;- if (intent.kind === 'navigate' && intent.displayState === 'folder') return false;const targetDocName =intent.kind === 'navigate' ? intent.hashDocName : classified.docName;if (newTab) {diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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): MdastRothrow 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.tsindex 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.tsindex 779e27500..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?: StructuralFreshnessChecreturn 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) => {@@ -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/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex 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.tsindex 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.tsindex c400441b2..1e3ad29c6 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -39,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),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex 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, MarkdownlintRuleSettingMD013: 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.tsindex 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.tsindex 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.tsindex af38c2ae2..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';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 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.tsindex 01ce4a5af..3dae5c031 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;@@ -98,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.tsindex 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.tsindex 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-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 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.tsindex 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.tsindex 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.tsindex 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/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 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.tsindex 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.tsindex 0e3224206..55736041c 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 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.tsindex 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/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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.tsindex 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/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 103663fad..df944aebd 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -3613,6 +3613,19 @@ export function createApiExtension(// 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.+ // Folder-existence oracle for write-time link validation: the watcher's+ // folder index is every non-excluded directory (including empty and+ // asset-only ones) — the same inventory the client's folder navigation+ // unions in, so an existing folder target is not reported broken here+ // while the editor chip resolves it. `computeWriteAdvisoryLinks` unions+ // this with the admitted docs' ancestors, which cover CRDT-live docs the+ // watcher has not indexed yet.+ function createLinkedFolderExists(): (folderPath: string) => boolean {+ const folderIndex = getFolderIndex?.();+ if (!folderIndex) return () => false;+ return (folderPath) => folderIndex.has(folderPath);+ }+function createLinkedFileExists(allFiles = getAllFilesIndex(),): (contentRootRelativePath: string) => boolean {@@ -5633,6 +5646,7 @@ export function createApiExtension(resolvedDocName,admittedForLinks,createLinkedFileExists(),+ createLinkedFolderExists(),);const subscriberCount = getSubscriberCount(resolvedDocName);@@ -6055,6 +6069,7 @@ export function createApiExtension(if (flushErrors.get(p.docName) === undefined) admittedForLinks.add(p.docName);}const linkedFileExists = createLinkedFileExists();+ const linkedFolderExists = createLinkedFolderExists();let lastWrittenDoc: string | undefined;for (const p of pending) {@@ -6070,6 +6085,7 @@ export function createApiExtension(p.docName,admittedForLinks,linkedFileExists,+ linkedFolderExists,);results[p.index] = {status: 'written',diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 971300e0d..1218072b4 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -429,6 +429,56 @@ describe('BacklinkIndex', () => {}});+ test('getDeadLinks never reports a link to an existing folder (PRD-7956)', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-links-folder-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(join(contentDir, 'guides', 'deep'), { recursive: true });+ try {+ // 'guides' and 'guides/deep' exist purely as ancestors of docs — no+ // index doc, no page named 'guides'. Every navigating surface opens+ // them as the folder view, so the audit must not call them dead. The+ // sibling wiki AND markdown forms are both exempt; 'missing-folder'+ // names no doc and no folder and stays reported.+ writeFileSync(+ join(contentDir, 'alpha.md'),+ '# Alpha\n\nSee [[guides]] and [markdown-form](./guides/deep) plus [[missing-folder]].\n',+ 'utf-8',+ );+ writeFileSync(+ join(contentDir, 'guides', 'deep', 'guide-one.md'),+ '# Guide one\n\nBody.\n',+ 'utf-8',+ );++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ const deadLinks = index.getDeadLinks(['alpha', 'guides/deep/guide-one']);+ expect(deadLinks.map((entry) => entry.target)).toEqual(['missing-folder']);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });++ test('getDeadLinks accepts a watcher folder inventory for folders with no doc descendants', async () => {+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-links-watcher-folder-'));+ const contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ try {+ // `assets` is asset-only: no doc beneath it, so the doc-ancestor+ // derivation cannot see it — only the injected watcher inventory can.+ writeFileSync(join(contentDir, 'alpha.md'), '# Alpha\n\nSee [[assets]].\n', 'utf-8');++ const index = new BacklinkIndex({ projectDir, contentDir });+ await index.rebuildFromDisk();++ expect(index.getDeadLinks(['alpha']).map((entry) => entry.target)).toEqual(['assets']);+ expect(index.getDeadLinks(['alpha'], undefined, undefined, ['assets'])).toEqual([]);+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+test('getDeadLinks returns an empty array when every target exists', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-backlinks-dead-links-empty-'));const contentDir = join(projectDir, 'content');@@ -2066,6 +2116,18 @@ describe('computeBrokenOutboundLinks', () => {expect(computeBrokenOutboundLinks(md, 'notes/a', admitted)).toEqual([]);});+ test('a folder oracle exempts wiki and markdown links to existing folders', () => {+ // `assets` holds no docs (asset-only), so it is invisible to `admitted`;+ // only the injected watcher-backed oracle can prove it exists. Both link+ // forms navigate to the folder view, so neither is broken. A folder the+ // oracle does not know stays reported.+ const md = 'See [[assets]] and [dir](./assets) and [[missing-folder]].';+ const folderExists = (folderPath: string) => folderPath === 'assets';+ expect(computeBrokenOutboundLinks(md, 'notes', new Set(), undefined, folderExists)).toEqual<+ BrokenOutboundLink[]+ >([{ href: '[[missing-folder]]', resolvedTo: 'missing-folder', reason: 'no-such-doc' }]);+ });+test('flags the `./`-onto-content-root doubling footgun as no-such-doc (AC2.2)', () => {const md = 'See [tasks](./wiki/modules/tasks).';// Authored from inside `wiki/`, so `./wiki/...` doubles to `wiki/wiki/...`.diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex ca1762ba7..882535b19 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -1034,12 +1034,16 @@ export interface BrokenOutboundLink {* @param sourceDocName the doc being written (relative hrefs resolve against its dir)* @param admittedDocs every docName that currently exists (the same admitted set `getDeadLinks` takes)* @param fileExists oracle for a content-root-relative file path's on-disk existence; omit to skip file-link validation+ * @param folderExists oracle for a content-root-relative folder path's existence; a link+ * naming an existing folder is a navigable destination (the folder+ * view), not a broken link. Omit to treat folders as unknown.*/export function computeBrokenOutboundLinks(markdown: string,sourceDocName: string,admittedDocs: Iterable<string>,fileExists?: (contentRootRelativePath: string) => boolean,+ folderExists?: (folderPath: string) => boolean,): BrokenOutboundLink[] {const admitted = admittedDocs instanceof Set ? admittedDocs : new Set(admittedDocs);@@ -1075,7 +1079,9 @@ export function computeBrokenOutboundLinks(return;}if (classified.kind === 'doc') {- if (!admitted.has(classified.docName)) {+ // A path naming an existing folder is the folder view's destination —+ // the same exemption the dead-link audit applies.+ if (!admitted.has(classified.docName) && folderExists?.(classified.docName) !== true) {record(trimmed, classified.docName, 'no-such-doc');}return;@@ -1134,7 +1140,10 @@ export function computeBrokenOutboundLinks(// hit. `[[analysis]]` reaching `research/analysis` by basename is a working// link, and the strict check reported exactly those as broken while staying// silent about the genuinely broken ones.- if (resolveWikiLinkTargetDocName(resolved.docName, wikiLookup) === undefined) {+ if (+ resolveWikiLinkTargetDocName(resolved.docName, wikiLookup) === undefined &&+ folderExists?.(resolved.docName) !== true+ ) {record(`[[${target}${anchor ? `#${anchor}` : ''}]]`, resolved.docName, 'no-such-doc');}};@@ -1312,6 +1321,24 @@ function deserializeState(data: SerializedBranchGraphState): BranchGraphState {};}+/**+ * Every ancestor folder path of the given docNames — the server-side twin of+ * the client's `deriveKnownFolderPaths` (navigation-targets.ts). Used by+ * {@link BacklinkIndex.getDeadLinks} as the folder-existence oracle so a link+ * targeting an existing folder is never reported as a dead link.+ */+function deriveFolderPathsFromDocNames(docNames: Iterable<string>): Set<string> {+ const folderPaths = new Set<string>();+ for (const docName of docNames) {+ let slash = docName.indexOf('/');+ while (slash !== -1) {+ folderPaths.add(docName.slice(0, slash));+ slash = docName.indexOf('/', slash + 1);+ }+ }+ return folderPaths;+}+export class BacklinkIndex {private readonly projectDir: string;private readonly contentDir: string;@@ -1828,10 +1855,25 @@ export class BacklinkIndex {admittedDocs: Iterable<string>,sourceDocNames?: readonly string[],branch = this.activeBranch,+ knownFolderPaths?: Iterable<string>,): DeadLinkEntry[] {const state = this.getState(branch);const admittedDocSet = new Set(admittedDocs);const sourceDocSet = sourceDocNames?.length ? new Set(sourceDocNames) : null;+ // Folder-existence oracle: a link to an existing folder is a real+ // destination — the editor resolves it to the 'folder' display state and+ // clicking opens the folder view at `#/<folderPath>` — so reporting it+ // dead contradicts every navigating surface. Two sources, unioned to+ // match the client's own union (`deriveKnownFolderPaths(pages)` ∪ the+ // watcher folder index in PageListContext): the ancestors of every+ // existing doc (covers CRDT-live docs the watcher has not indexed yet)+ // plus the caller-provided watcher folder inventory (covers empty and+ // asset-only folders, which have no doc descendants to derive from).+ const folderPathSet = deriveFolderPathsFromDocNames([+ ...admittedDocSet,+ ...state.forward.keys(),+ ]);+ for (const folderPath of knownFolderPaths ?? []) folderPathSet.add(folderPath);return [...state.backward.entries()].filter(([target, sources]) => {@@ -1846,6 +1888,11 @@ export class BacklinkIndex {// target is never a forward node (only `state.backward` carries it), so// this never hides a real dead link.if (admittedDocSet.has(target) || state.forward.has(target)) return false;+ // A target naming an existing folder is navigable, not dead — every+ // occurrence form (wiki AND markdown path) resolves it to the folder+ // view, so the exemption is form-agnostic. Exact membership only; no+ // slug/basename fuzz, so a path naming nothing still reports dead.+ if (folderPathSet.has(target.replace(/\/+$/, ''))) return false;if (!sourceDocSet) return sources.size > 0;for (const source of sources.keys()) {if (sourceDocSet.has(source)) return true;diff --git a/packages/server/src/derived-document-index.ts b/packages/server/src/derived-document-index.tsindex fceea8685..cbd21a258 100644--- a/packages/server/src/derived-document-index.ts+++ b/packages/server/src/derived-document-index.ts@@ -240,7 +240,8 @@ export class DerivedDocumentIndexthis.contentFilter = options.contentFilter;this.getGlobalSkillRoots = options.getGlobalSkillRoots;this.getLocalTargetInventory =- options.getLocalTargetInventory ?? (() => ({ documentTargets: [], fileTargets: [] }));+ options.getLocalTargetInventory ??+ (() => ({ documentTargets: [], fileTargets: [], folderTargets: [] }));this.signalChannel = options.signalChannel;this.onRecoveredFileTarget = options.onRecoveredFileTarget;this.testOnly = {@@ -616,7 +617,16 @@ export class DerivedDocumentIndexsourceDocumentNames?: readonly string[],): Promise<DeadLinkEntry[]> {return this.runQuery(() =>- this.backlinkIndex.getDeadLinks(admittedDocuments, sourceDocumentNames),+ this.backlinkIndex.getDeadLinks(+ admittedDocuments,+ sourceDocumentNames,+ undefined,+ // The watcher folder inventory rides along so empty and asset-only+ // folders — navigable in the editor, absent from every doc-ancestor+ // derivation — are not reported dead. Null (watcher unavailable)+ // degrades to the doc-ancestor oracle inside getDeadLinks.+ this.getLocalTargetInventory()?.folderTargets,+ ),);}@@ -946,6 +956,7 @@ export class DerivedDocumentIndexnew Set([...this.backlinkIndex.getIndexedDocNames(), ...watcherInventory.documentTargets]),);this.localTargetIndex.reconcileFileTargets(watcherInventory.fileTargets);+ this.localTargetIndex.reconcileFolderTargets(watcherInventory.folderTargets);return watcherInventory;}diff --git a/packages/server/src/local-target-assessment.ts b/packages/server/src/local-target-assessment.tsindex 9b68345a7..327cb5350 100644--- a/packages/server/src/local-target-assessment.ts+++ b/packages/server/src/local-target-assessment.ts@@ -98,6 +98,16 @@ export interface LocalTargetInventory {* `exact`.*/resolveTolerantDocument?(docName: string, sourceDocName: string): string | null;+ /**+ * Optional folder-existence oracle: whether an extension-less path names an+ * existing content folder (an ancestor of at least one admitted document —+ * the same derivation every navigating surface uses). An existing folder is+ * a real destination since the folder-links fix (it opens the folder view at+ * `#/<folderPath>`), so `assessDocument` reports it `exact` instead of+ * minting a dead-link finding. Absent oracle = folders unknown, which+ * preserves the pre-folder behavior for callers that never see folders.+ */+ hasFolder?(folderPath: string): boolean;}/** Build the deterministic tolerant document lookup shared by index and write-time assessment. */@@ -187,6 +197,23 @@ function assessDocument(fallbackTarget: null,};}+ // An existing folder is an exact destination, not a missing document: every+ // navigating surface opens it as the folder view at `#/<folderPath>`.+ // Checked BEFORE tolerant fallback so a folder target keeps its+ // authored identity rather than being re-pointed at a lookalike doc; a+ // folder that also carries an index doc still navigates fine (the folder+ // view lists it). Checked AFTER the exact-document branch so a doc named+ // like a folder keeps winning.+ if (inventory.hasFolder?.(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 {diff --git a/packages/server/src/local-target-index.test.ts b/packages/server/src/local-target-index.test.tsindex 0a5174032..35974e3ac 100644--- a/packages/server/src/local-target-index.test.ts+++ b/packages/server/src/local-target-index.test.ts@@ -285,19 +285,93 @@ describe('LocalTargetIndex reverse-dependent freshness', () => {});});- test('records canonical folder-index and bare-basename fallbacks', () => {+ test('a folder target is exact; a bare basename still records its fallback', () => {+ // `guides` names an existing folder, which is a real+ // destination (the folder view) — exact under its authored identity, no+ // fallback re-pointing. The bare-basename tolerant fallback is untouched.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);+ index.getAssessments('src').map(({ status, resolvedTarget, fallbackTarget }) => ({+ status,+ resolvedTarget,+ fallbackTarget,+ })),+ ).toEqual([+ { status: 'exact', resolvedTarget: 'guides', fallbackTarget: null },+ { status: 'fallback', resolvedTarget: 'analysis', fallbackTarget: 'nested/analysis' },+ ]);+ });++ test('reconcileFolderTargets flips folder links as watcher folders come and go', () => {+ // An asset-only folder never appears among doc ancestors; only the+ // injected watcher inventory can prove it. The reconcile must reassess+ // sources holding a folder: dependency in both directions.+ const index = createIndex();+ index.setSource('src', 'See [dir](assets).\n');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: 'assets',+ });++ expect(index.reconcileFolderTargets(['assets'])).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'assets',+ });++ expect(index.reconcileFolderTargets([])).toBe(1);+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: 'assets',+ });+ });++ test('a staged rebuild carries the folder oracle into live reassessment (PRD-7956)', async () => {+ // rebuildFromDisk assesses inside a STAGED instance and swaps its fields+ // into the live one. The folder set must swap with `documents`, or the+ // first live setSource after a rebuild reassesses folder-exact targets+ // against an empty folder set and flips them to missing — clean at boot,+ // broken the moment a doc is opened.+ const index = createIndex();+ await index.rebuildFromDisk({+ documentTargets: ['guides/guide-one'],+ fileTargets: [],+ });++ index.setSource('src', 'See [folder](guides).\n');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'guides',+ });+ });++ test('folder existence tracks the docs beneath it in both directions (PRD-7956)', () => {+ const index = createIndex();+ index.setSource('src', 'See [folder](guides).\n');+ // Nothing named guides exists yet — missing.+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: 'guides',+ });++ // First doc under guides/ brings the folder into existence — heals to exact.+ index.setSource('guides/first', '# First\n');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'exact',+ resolvedTarget: 'guides',+ fallbackTarget: null,+ });++ // Deleting the folder's last doc takes the folder with it — back to missing.+ index.removeSource('guides/first');+ expect(index.getAssessments('src')[0]).toMatchObject({+ status: 'missing',+ resolvedTarget: 'guides',+ });});test('system and config source names are never indexed and create no reverse edges', () => {diff --git a/packages/server/src/local-target-index.ts b/packages/server/src/local-target-index.tsindex 13c607ccc..22e9668f8 100644--- a/packages/server/src/local-target-index.ts+++ b/packages/server/src/local-target-index.ts@@ -109,6 +109,9 @@ export interface LocalTargetRebuildResult {export interface LocalTargetRebuildInventory {documentTargets: Iterable<string>;fileTargets: Iterable<string>;+ /** Watcher folder inventory (every non-excluded directory); optional so+ * doc-only harnesses keep working — absent means "no injected folders". */+ folderTargets?: Iterable<string>;}/**@@ -183,11 +186,15 @@ function documentMutationKeys(docName: string): string[] {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}`);+ // Every ancestor folder, not just an index-like parent: adding a doc can+ // bring a folder into existence at any depth and removing one can take the+ // folder with it, and folder existence is itself an assessment input since+ // folder targets became exact destinations. Sources holding a+ // `folder:` dependency on any of these ancestors must re-run.+ let slash = docName.indexOf('/');+ while (slash !== -1) {+ keys.push(`folder:${docName.slice(0, slash)}`);+ slash = docName.indexOf('/', slash + 1);}return keys;}@@ -258,11 +265,28 @@ export class LocalTargetIndex {private readyValue = false;private closed = false;+ /**+ * Ancestor folders of every admitted document — the derived half of the+ * `hasFolder` oracle (covers CRDT-live docs the watcher has not indexed).+ * Rebuilt with the tolerant indexes (every `documents` mutation site calls+ * `refreshTolerantDocumentIndexes`), so it can never go stale independently.+ */+ private folderPaths = new Set<string>();+ /**+ * Watcher folder inventory (every non-excluded directory, including empty+ * and asset-only folders) — the injected half of the `hasFolder` oracle.+ * Seeded by `populateFromDisk`, replaced by `reconcileFolderTargets`, and+ * swapped with the other staged fields in `rebuildOnce`.+ */+ private injectedFolderPaths = new Set<string>();+/** 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),+ hasFolder: (folderPath) =>+ this.folderPaths.has(folderPath) || this.injectedFolderPaths.has(folderPath),};constructor(options: LocalTargetIndexOptions) {@@ -501,6 +525,39 @@ export class LocalTargetIndex {return reassessed;}+ /**+ * Replace the injected (watcher) folder inventory from an authoritative+ * snapshot. Sources whose assessments hold a `folder:` dependency on a+ * folder that appeared or disappeared are reassessed, so an empty or+ * asset-only folder coming or going flips its links between exact and+ * missing without waiting for a doc edit.+ */+ reconcileFolderTargets(folderTargets: Iterable<string>): number {+ const next = new Set(folderTargets);+ const changedFolders = new Set<string>();+ for (const folderPath of this.injectedFolderPaths) {+ if (!next.has(folderPath)) changedFolders.add(folderPath);+ }+ for (const folderPath of next) {+ if (!this.injectedFolderPaths.has(folderPath)) changedFolders.add(folderPath);+ }+ if (changedFolders.size === 0) return 0;++ const affected = new Set<string>();+ for (const folderPath of changedFolders) {+ for (const source of this.reverseByTolerant.get(`folder:${folderPath}`) ?? []) {+ affected.add(source);+ }+ }+ this.injectedFolderPaths = next;+ 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(@@ -633,6 +690,13 @@ export class LocalTargetIndex {this.sourceTolerantDeps = staged.sourceTolerantDeps;this.documents = staged.documents;this.tolerantDocumentResolver = staged.tolerantDocumentResolver;+ // folderPaths must swap with `documents` — it is derived from it. Missing+ // this line was a live bug: boot assessments (computed inside `staged`,+ // folder-aware) were clean, then the FIRST live reassessment on this+ // instance ran against an empty folder set and flipped folder-exact+ // targets back to missing.+ this.folderPaths = staged.folderPaths;+ this.injectedFolderPaths = staged.injectedFolderPaths;this.files = staged.files;this.readyValue = true;if (hadContent || this.sourceAssessments.size > 0) this.generationValue++;@@ -644,6 +708,9 @@ export class LocalTargetIndex {): Promise<LocalTargetRebuildResult> {for (const docName of inventory.documentTargets) this.documents.add(docName);for (const relativePath of inventory.fileTargets) this.files.add(relativePath);+ for (const folderPath of inventory.folderTargets ?? []) {+ this.injectedFolderPaths.add(folderPath);+ }this.refreshTolerantDocumentIndexes();if (!existsSync(this.contentDir)) {@@ -699,8 +766,14 @@ export class LocalTargetIndex {for (const file of files) nextFileDeps.add(file);if (assessment.targetKind === 'document' &&- assessment.status !== 'exact' &&- assessment.resolvedTarget !== null+ assessment.resolvedTarget !== null &&+ // Non-exact targets need every tolerant edge (a slug/basename/folder+ // mutation can heal them). An exact target normally needs none — its+ // reverseByDoc edge covers it — EXCEPT a folder-backed exact,+ // whose existence is a property of the folder, not of any+ // one document: it keeps its `folder:` edge so deleting the folder's+ // last doc re-runs the assessment.+ (assessment.status !== 'exact' || !this.documents.has(assessment.resolvedTarget))) {for (const key of tolerantDependencyKeys(assessment.resolvedTarget)) {nextTolerantDeps.add(key);@@ -786,6 +859,15 @@ export class LocalTargetIndex {private refreshTolerantDocumentIndexes(): void {this.tolerantDocumentResolver = createTolerantDocumentResolver(this.documents);+ const folderPaths = new Set<string>();+ for (const docName of this.documents) {+ let slash = docName.indexOf('/');+ while (slash !== -1) {+ folderPaths.add(docName.slice(0, slash));+ slash = docName.indexOf('/', slash + 1);+ }+ }+ this.folderPaths = folderPaths;}private async listDocsWithPaths(): Promise<Array<{ docName: string; filePath: string }>> {diff --git a/packages/server/src/local-target-inventory.test.ts b/packages/server/src/local-target-inventory.test.tsindex b74061014..d49ce3a3a 100644--- a/packages/server/src/local-target-inventory.test.ts+++ b/packages/server/src/local-target-inventory.test.ts@@ -54,6 +54,28 @@ describe('localTargetInventoryFromIndexes', () => {);});+ test('carries the watcher folder index as folderTargets, with folder-alias projection', () => {+ const contentDir = '/project/content';+ const inventory = localTargetInventoryFromIndexes(+ new Map(),+ new Map([['folder-alias', 'canonical']]),+ contentDir,+ new Map([+ ['canonical', { modified: '2026-01-01T00:00:00.000Z' } as never],+ ['canonical/assets-only', { modified: '2026-01-01T00:00:00.000Z' } as never],+ ]),+ );++ expect(inventory.folderTargets).toEqual(+ expect.arrayContaining([+ 'canonical',+ 'canonical/assets-only',+ 'folder-alias',+ 'folder-alias/assets-only',+ ]),+ );+ });+test('distinguishes an unavailable watcher from an empty authoritative inventory', () => {expect(localTargetInventoryFromWatcher(null, '/project/content')).toBeNull();});diff --git a/packages/server/src/local-target-inventory.ts b/packages/server/src/local-target-inventory.tsindex 584ad0d7c..f97a07be8 100644--- a/packages/server/src/local-target-inventory.ts+++ b/packages/server/src/local-target-inventory.ts@@ -1,17 +1,28 @@import { isAbsolute, relative } from 'node:path';import { stripDocExtension } from './doc-extensions.ts';-import type { FileIndexEntry, WatcherHandle } from './file-watcher.ts';+import type { FileIndexEntry, FolderIndexEntry, WatcherHandle } from './file-watcher.ts';import { toPosix } from './path-utils.ts';export interface WatcherLocalTargetInventory {documentTargets: readonly string[];fileTargets: readonly string[];+ /**+ * Every non-excluded directory the watcher indexes — including empty and+ * asset-only folders, which have no doc descendants to derive from. This is+ * the folder-existence oracle's watcher half; consumers union it with the+ * admitted docs' ancestors (covering CRDT-live docs not yet on disk), the+ * same union the client's folder navigation uses.+ */+ folderTargets: readonly string[];}type LocalTargetWatcher = Pick<WatcherHandle,'getAllFilesIndex' | 'getFileIndexGeneration' | 'getFolderAliasIndex'->;+> &+ // Optional so narrow harness stubs keep working; a missing accessor just+ // means "no injected folders" (the doc-ancestor half still applies).+ Partial<Pick<WatcherHandle, 'getFolderIndex'>>;interface CachedWatcherInventory {contentDir: string;@@ -73,6 +84,7 @@ export function localTargetInventoryFromWatcher(watcher.getAllFilesIndex(),watcher.getFolderAliasIndex(),contentDir,+ watcher.getFolderIndex?.(),);watcherInventoryCache.set(watcher, { contentDir, generation, inventory });return inventory;@@ -83,9 +95,11 @@ export function localTargetInventoryFromIndexes(allFiles: ReadonlyMap<string, FileIndexEntry>,folderAliases: ReadonlyMap<string, string>,contentDir: string,+ folderIndex?: ReadonlyMap<string, FolderIndexEntry>,): WatcherLocalTargetInventory {const documentTargets = new Set<string>();const fileTargets = new Set<string>();+ const folderTargets = new Set<string>(folderIndex?.keys() ?? []);for (const [indexedIdentity, entry] of allFiles) {const targets = entry.kind === 'markdown' ? documentTargets : fileTargets;targets.add(indexedIdentity);@@ -99,9 +113,11 @@ export function localTargetInventoryFromIndexes(projectFolderAliases(documentTargets, folderAliases);projectFolderAliases(fileTargets, folderAliases);+ projectFolderAliases(folderTargets, folderAliases);return {documentTargets: [...documentTargets],fileTargets: [...fileTargets],+ folderTargets: [...folderTargets],};}diff --git a/packages/server/src/write-advisory-links.test.ts b/packages/server/src/write-advisory-links.test.tsindex 0a0086d81..c6de56d6f 100644--- a/packages/server/src/write-advisory-links.test.ts+++ b/packages/server/src/write-advisory-links.test.ts@@ -8,6 +8,23 @@ function fileOracle(...paths: string[]): (rel: string) => boolean {}describe('computeWriteAdvisoryLinks', () => {+ test('a folder oracle exempts wiki and inline links to existing folders (both planes)', () => {+ // The graph scan owns wiki + inline entries and the assessment plane owns+ // the evidence-carrying rest; both must consult the injected folder+ // oracle, or an MCP write response reports a link broken while the+ // Problems tab and the editor resolve it. `assets` is asset-only — no doc+ // descendants — so only the injected oracle can prove it.+ const md = 'See [[assets]] and [dir](./assets) and [[missing-folder]].';+ const links = computeWriteAdvisoryLinks(+ md,+ 'notes',+ new Set<string>(),+ undefined,+ (folderPath) => folderPath === 'assets',+ );+ expect(links.map((link) => link.href)).toEqual(['[[missing-folder]]']);+ });+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',diff --git a/packages/server/src/write-advisory-links.ts b/packages/server/src/write-advisory-links.tsindex 0da73cc42..2a2ce9d52 100644--- a/packages/server/src/write-advisory-links.ts+++ b/packages/server/src/write-advisory-links.ts@@ -49,13 +49,30 @@ export function computeWriteAdvisoryLinks(sourceDocName: string,admittedDocs: Iterable<string>,fileExists?: (contentRootRelativePath: string) => boolean,+ folderExists?: (folderPath: string) => boolean,): WriteAdvisoryLink[] {const admitted = admittedDocs instanceof Set ? admittedDocs : new Set(admittedDocs);+ const folderPaths = new Set<string>();+ for (const docName of admitted) {+ let slash = docName.indexOf('/');+ while (slash !== -1) {+ folderPaths.add(docName.slice(0, slash));+ slash = docName.indexOf('/', slash + 1);+ }+ }+ // Folder targets are exact destinations (the folder view). Union the+ // admitted docs' ancestors with the caller's folder oracle (the watcher's+ // folder index, when provided) — the same union the client navigates with,+ // so an empty or asset-only folder is not reported broken here while the+ // chip resolves it.+ const hasFolder = (folderPath: string): boolean =>+ folderPaths.has(folderPath) || folderExists?.(folderPath) === true;const inventory: LocalTargetInventory = {hasDocument: (docName) => admitted.has(docName),hasFile: (relPath) => (fileExists ? fileExists(relPath) : false),resolveTolerantDocument: createTolerantDocumentResolver(admitted),+ hasFolder,};const assessments = assessLocalTargets(markdown, sourceDocName, inventory);const inlineLinkHrefs = new Set(@@ -76,6 +93,7 @@ export function computeWriteAdvisoryLinks(sourceDocName,admitted,fileExists,+ hasFolder,).filter((link) => link.href.startsWith('[[') || inlineLinkHrefs.has(link.href));const graphHrefs = new Set(links.map((link) => link.href));const seenRepairSites = new Set<string>();