Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): WYSIWYG ⇄ source toggle for JSON markdownlint config files (#2723)
serafin-garcia02ca6b52d4f6
diff --git a/.changeset/lint-config-wysiwyg-toggle.md b/.changeset/lint-config-wysiwyg-toggle.mdnew file mode 100644index 000000000..78a0a3c30--- /dev/null+++ b/.changeset/lint-config-wysiwyg-toggle.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Opening a JSON markdownlint config file (`.markdownlint.json` / `.markdownlint.jsonc`) now offers a toggle between a **Source** view and a **Rules** view. Source is the raw, read-only file (comments, `extends`, and formatting intact); Rules is the same searchable rule browser as Settings — flip rules on or off and edit their options, with changes written back to the file through the format-preserving writer (comments, `extends`, and trailing commas are preserved). Rule editing targets the project's root config, so a nested or not-yet-created config opens in Source with the Rules option disabled and an explanation. Your Source/Rules choice is remembered per user, separately from the markdown editor's own mode.diff --git a/docs/content/advanced/content-rules/markdownlint.mdx b/docs/content/advanced/content-rules/markdownlint.mdxindex c703a4ec7..24a2f88c4 100644--- a/docs/content/advanced/content-rules/markdownlint.mdx+++ b/docs/content/advanced/content-rules/markdownlint.mdx@@ -29,6 +29,8 @@ The rules live in your project's own native markdownlint file — `.markdownlint**Settings ▸ Plugins ▸ markdownlint** (markdownlint appears there once the plugin is enabled) lists the full catalog — all 53 rules, generated from the installed engine's own config schema, so it always matches what actually runs. Search by id, alias, or name; browse by category (Headings, Lists, Whitespace, Code, Links & images, Style); or check **Only modified** to see just the rules your config changes. Expanding a rule reveals a link to its upstream documentation and typed editors for each of its options.+The same browser also opens **directly on the config file**. Open your project's root `.markdownlint.json` or `.markdownlint.jsonc` in the editor (reveal hidden files to find it) and use the **Source / Rules** toggle: **Source** — the default — shows the raw file read-only, and **Rules** is the same no-code browser. Because rule edits target the project's governing root config, **Rules** is enabled only for that root file; open a nested or otherwise non-governing `.markdownlint.*` and **Rules** is disabled with a tooltip while **Source** still shows the file. Your Source/Rules choice is remembered separately from the document editor's own Visual/Markdown mode.+Every edit writes back to your native `.markdownlint.*` file, preserving what you wrote: JSON and JSONC files get minimal text edits (comments and formatting survive), and a rule you configured under an alias stays under that alias. Severity strings are shown as a read-only badge. If the project has no file yet, the first change creates a `.markdownlint.json` seeded with the defaults — from then on that file is the whole story for OK and every other markdownlint tool.## Auto-fix and severitiesdiff --git a/packages/app/package.json b/packages/app/package.jsonindex 10f4855e2..3517ef553 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -26,7 +26,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.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-compact-folders.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/sidebar-search-pill.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",+ "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-compact-folders.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/sidebar-search-pill.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","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",@@ -52,7 +52,7 @@{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "3.35 MB",+ "limit": "3.36 MB","gzip": true,"running": false},diff --git a/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsxnew file mode 100644index 000000000..a6d657234--- /dev/null+++ b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx@@ -0,0 +1,172 @@+/**+ * Dispatch test for the EditorArea asset branch: a markdownlint JSON config file+ * routes to the LintConfigEditor (Source/Rules toggle), while every other asset+ * — including a non-config `.json` like package.json — keeps the read-only+ * AssetPreview. Both branch targets are stubbed to markers so this test observes+ * only WHICH branch EditorArea selects; LintConfigEditor's own toggle behavior+ * is covered by its dedicated DOM test.+ *+ * The heavy EditorArea dependency graph is mocked following the sibling+ * `EditorArea.share-receive-miss.dom.test.tsx` harness. The config predicate+ * (`isMarkdownlintJsonConfig`) runs for real — it is the seam under test.+ */++import { cleanup, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { ConfigProvider } from '@/lib/config-provider';++function assetCtx(assetPath: string) {+ return {+ activeDocName: null,+ activeProvider: {} as never,+ activeTarget: {+ kind: 'asset' as const,+ target: assetPath,+ assetPath,+ mediaKind: 'text' as string | null,+ },+ recycleDocument: () => {},+ docPanelMode: 'timeline',+ docPanelAgentId: null,+ docPanelExpandSignal: 0,+ };+}+let docCtx: ReturnType<typeof assetCtx> = assetCtx('.markdownlint.json');++vi.doMock('@/lib/perf', () => ({+ mark: () => {},+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,+}));+vi.doMock('@/components/PropertyContext', () => ({+ PropertyProvider: ({ children }: { children: ReactNode }) => children,+ useProperties: () => ({ requestAddProperty: () => {} }),+}));+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => docCtx,+ useDocumentTransition: () => ({ openDocumentTransition: null }),+}));+vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));+vi.doMock('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));+vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));+vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));+vi.doMock('@/lib/use-settings-route', () => ({+ useSettingsRoute: () => ({ open: false, close: () => {} }),+ SETTINGS_OPEN_HASH: '#settings',+ isSettingsShortcut: () => false,+}));+vi.doMock('@/components/settings/SettingsDialogShell', () => ({+ SettingsDialogShell: () => <div data-testid="settings-shell" />,+}));+vi.doMock('@/components/EditorSkeleton', () => ({+ EditorSkeleton: () => <div data-testid="editor-skeleton" />,+}));+vi.doMock('@/components/EmptyEditorState', () => ({+ EmptyEditorState: () => <div data-testid="empty-editor-state" />,+}));+vi.doMock('./TerminalDock', () => ({+ TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.doMock('react-resizable-panels', () => ({+ usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),+ useGroupRef: () => ({ current: { getLayout: () => [], setLayout: () => {} } }),+}));+vi.doMock('@/components/ui/resizable', () => ({+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ ResizableHandle: () => <div />,+}));+vi.doMock('./EditorActivityPool', () => ({+ EditorActivityPool: () => <div data-testid="editor-pool" />,+}));+vi.doMock('@/editor/find-replace/FindReplaceController', () => ({+ FindReplaceController: () => null,+}));+vi.doMock('./EditorToolbar', () => ({+ EditorToolbar: () => <div data-testid="editor-toolbar" />,+}));+vi.doMock('./EditorFooter', () => ({ EditorFooter: () => <div data-testid="editor-footer" /> }));+vi.doMock('./BottomComposer', () => ({+ BottomComposer: () => <div data-testid="bottom-composer" />,+}));+vi.doMock('./editor-area-overlay', () => ({ shouldPaintOverlay: () => false }));+vi.doMock('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="doc-panel" /> }));++// The two asset-branch targets, stubbed to markers so the test reads which+// branch EditorArea picked (not the components' own rendering).+vi.doMock('@/components/AssetPreview', () => ({+ AssetPreview: ({ assetPath }: { assetPath: string }) => (+ <div data-testid="asset-preview" data-asset-path={assetPath} />+ ),+}));+vi.doMock('@/components/LintConfigEditor', () => ({+ LintConfigEditor: ({ assetPath }: { assetPath: string }) => (+ <div data-testid="lint-config-editor" data-asset-path={assetPath} />+ ),+}));++const { EditorArea } = await import('./EditorArea');++function renderEditorArea() {+ return render(+ <ConfigProvider collabUrl={null}>+ <EditorArea+ editorMode="wysiwyg"+ onModeChange={() => {}}+ activeTab="timeline"+ onActiveTabChange={() => {}}+ />+ </ConfigProvider>,+ );+}++describe('EditorArea — markdownlint config dispatch', () => {+ beforeEach(() => cleanup());+ afterEach(() => cleanup());++ test('routes a root .markdownlint.json to the config editor, not the asset preview', () => {+ docCtx = assetCtx('.markdownlint.json');+ renderEditorArea();++ expect(screen.getByTestId('lint-config-editor').getAttribute('data-asset-path')).toBe(+ '.markdownlint.json',+ );+ expect(screen.queryByTestId('asset-preview')).toBeNull();+ });++ test('routes a .markdownlint.jsonc to the config editor', () => {+ docCtx = assetCtx('.markdownlint.jsonc');+ renderEditorArea();++ expect(screen.getByTestId('lint-config-editor')).toBeDefined();+ expect(screen.queryByTestId('asset-preview')).toBeNull();+ });++ test('routes a nested config to the config editor (dispatch is basename-driven)', () => {+ docCtx = assetCtx('docs/.markdownlint.json');+ renderEditorArea();++ expect(screen.getByTestId('lint-config-editor').getAttribute('data-asset-path')).toBe(+ 'docs/.markdownlint.json',+ );+ expect(screen.queryByTestId('asset-preview')).toBeNull();+ });++ test('leaves a non-config JSON (package.json) on the asset preview', () => {+ docCtx = assetCtx('package.json');+ renderEditorArea();++ expect(screen.getByTestId('asset-preview').getAttribute('data-asset-path')).toBe(+ 'package.json',+ );+ expect(screen.queryByTestId('lint-config-editor')).toBeNull();+ });++ test('leaves an ordinary .json data file on the asset preview', () => {+ docCtx = assetCtx('data/settings.json');+ renderEditorArea();++ expect(screen.getByTestId('asset-preview')).toBeDefined();+ expect(screen.queryByTestId('lint-config-editor')).toBeNull();+ });+});diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsxindex 6c03748b8..c1a2cdaf8 100644--- a/packages/app/src/components/EditorArea.tsx+++ b/packages/app/src/components/EditorArea.tsx@@ -1,4 +1,7 @@-import { detectEmbeddedHostFromBrowser } from '@inkeep/open-knowledge-core';+import {+ detectEmbeddedHostFromBrowser,+ isMarkdownlintJsonConfig,+} from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import { useTheme } from 'next-themes';import {@@ -23,6 +26,7 @@ import { EditorSkeleton } from '@/components/EditorSkeleton';import { EmptyEditorState } from '@/components/EmptyEditorState';import { FolderOverview } from '@/components/FolderOverview';import { LargeFileEditorState } from '@/components/LargeFileEditorState';+import { LintConfigEditor } from '@/components/LintConfigEditor';import { MountStalledAffordance } from '@/components/MountStalledAffordance';import { PropertyProvider, useProperties } from '@/components/PropertyContext';import { ShareReceiveMissPanel } from '@/components/ShareReceiveMissPanel';@@ -879,6 +883,18 @@ function EditorAreaInner({</>);}+ } else if (+ activeTarget?.kind === 'asset' &&+ isMarkdownlintJsonConfig(activeTarget.assetPath.split('/').pop() ?? activeTarget.assetPath)+ ) {+ // A markdownlint JSON config file opens in the dedicated config editor (a+ // Source/Rules toggle) instead of the read-only asset preview. Like the+ // skill-file branch below it's a plain REST-backed sibling — NOT+ // DocumentBoundary-wrapped: the config is served over HTTP, not a pooled+ // CRDT doc. Keyed by path so navigating between configs remounts + resets.+ viewContent = (+ <LintConfigEditor key={activeTarget.assetPath} assetPath={activeTarget.assetPath} />+ );} else if (activeTarget?.kind === 'asset') {// `key={assetPath}` forces a fresh `AssetPreview` instance on every asset// navigation so the in-pane `forceText` toggle (from the "View as text"diff --git a/packages/app/src/components/EditorModeToggle.tsx b/packages/app/src/components/EditorModeToggle.tsxindex b613d5e5b..5b3cd4319 100644--- a/packages/app/src/components/EditorModeToggle.tsx+++ b/packages/app/src/components/EditorModeToggle.tsx@@ -1,4 +1,5 @@import { Trans, useLingui } from '@lingui/react/macro';+import { useId } from 'react';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import type { EditorModeValue } from '@/editor/use-editor-mode';@@ -10,19 +11,49 @@ interface EditorModeToggleProps {onModeChange: (mode: EditorModeValue) => void;/** Disables the Markdown (source) option (e.g. doc editor when offline). */sourceDisabled?: boolean;+ /**+ * Disables the Visual (wysiwyg) option (e.g. the lint-config editor when the+ * opened file is not the governing root config the rule writer can target).+ */+ wysiwygDisabled?: boolean;+ /**+ * Overrides the default segment labels ("Visual" / "Markdown"), applied to+ * both the tooltip and the accessible name. The lint-config editor passes+ * "Rules" / "Source". Pass an already-translated string so message extraction+ * stays at the call site.+ */+ wysiwygLabel?: string;+ sourceLabel?: string;+ /**+ * Tooltip shown on the Visual segment while `wysiwygDisabled` — explains why+ * the option is unavailable so a pointer user learns the reason.+ */+ wysiwygDisabledReason?: string;}/*** Visual ⇄ Markdown editor-mode toggle — the segmented control shared by the- * document editor toolbar (`EditorToolbar`) and the skill editor, so both read- * identically.+ * document editor toolbar (`EditorToolbar`), the skill editor, and the+ * lint-config editor, so all three read identically. Labels default to+ * Visual/Markdown; a caller may relabel the two segments and disable the visual+ * one without affecting the others.*/export function EditorModeToggle({isSourceMode,onModeChange,sourceDisabled = false,+ wysiwygDisabled = false,+ wysiwygLabel,+ sourceLabel,+ wysiwygDisabledReason,}: EditorModeToggleProps) {const { t } = useLingui();+ const wysiwygName = wysiwygLabel ?? t`Visual editor`;+ const sourceName = sourceLabel ?? t`Markdown source`;+ // Stable id so the disabled Visual segment can point `aria-describedby` at a+ // visually-hidden element carrying its reason.+ const wysiwygReasonId = useId();+ const describeWysiwyg = wysiwygDisabled && wysiwygDisabledReason ? wysiwygDisabledReason : null;return (<ToggleGrouptype="single"@@ -37,18 +68,38 @@ export function EditorModeToggle({className="shrink-0 bg-muted p-0.5 data-[size=sm]:rounded-[10px]"><Tooltip>- <ToggleGroupItem- value="wysiwyg"- aria-label={t`Visual editor`}- className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"- asChild- >- <TooltipTrigger>- <Textbox className="size-4" />- </TooltipTrigger>- </ToggleGroupItem>+ <TooltipTrigger asChild>+ {/* Disabled <button> doesn't fire pointer events; wrap so the tooltip still triggers. */}+ <div>+ <ToggleGroupItem+ value="wysiwyg"+ aria-label={wysiwygName}+ // A disabled <button> is skipped by the toggle's roving tabindex,+ // so its tooltip (pointer-only) never reaches keyboard / screen-+ // reader users. Point `aria-describedby` at a visually-hidden+ // element carrying the reason: `aria-describedby` has broad SR+ // support where the ARIA 1.3 `aria-description` attribute does not.+ aria-describedby={describeWysiwyg ? wysiwygReasonId : undefined}+ disabled={wysiwygDisabled}+ className="size-7 px-0 dark:data-[state=on]:bg-foreground/15"+ >+ <Textbox className="size-4" />+ </ToggleGroupItem>+ {describeWysiwyg ? (+ <span id={wysiwygReasonId} className="sr-only">+ {describeWysiwyg}+ </span>+ ) : null}+ </div>+ </TooltipTrigger><TooltipContent side="bottom">- <Trans>Visual</Trans>+ {wysiwygDisabled && wysiwygDisabledReason ? (+ wysiwygDisabledReason+ ) : wysiwygLabel ? (+ wysiwygLabel+ ) : (+ <Trans>Visual</Trans>+ )}</TooltipContent></Tooltip><Tooltip>@@ -57,7 +108,7 @@ export function EditorModeToggle({<div><ToggleGroupItemvalue="source"- aria-label={t`Markdown source`}+ aria-label={sourceName}disabled={sourceDisabled}className="size-7 px-0 dark:data-[state=on]:bg-foreground/15">@@ -71,6 +122,8 @@ export function EditorModeToggle({Source mode requires a live connection — your edits are saved and will appear when youreconnect.</Trans>+ ) : sourceLabel ? (+ sourceLabel) : (<Trans>Markdown</Trans>)}diff --git a/packages/app/src/components/LintConfigEditor.dom.test.tsx b/packages/app/src/components/LintConfigEditor.dom.test.tsxnew file mode 100644index 000000000..b4bb246f9--- /dev/null+++ b/packages/app/src/components/LintConfigEditor.dom.test.tsx@@ -0,0 +1,244 @@+/**+ * DOM tests for the lint-config editor pane: the Source/Rules toggle, its+ * correct-target gating (Rules is offered only for the governing root config),+ * and the mount discipline that lets the Source view reflect a WYSIWYG edit.+ *+ * The system boundaries are mocked: the governing-config lookup+ * (`useProjectLintConfig`), the read-only source viewer (`TextViewer`, which+ * fetches `/api/asset-text`), and the rule browser (`MarkdownlintRuleBrowser`).+ * The toggle, its gating logic, the persistence hook, and the active-segment+ * mount decision are the real code under test.+ */++import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';++// Radix primitives reach for DOM globals the jsdom preload doesn't expose;+// hoist the same shims the sibling settings DOM tests use.+type WindowGlobals = { NodeFilter?: typeof NodeFilter };+type GlobalWithDomShims = typeof globalThis &+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };+const globalWithDomShims = globalThis as GlobalWithDomShims;+if (+ globalWithDomShims.NodeFilter === undefined &&+ globalWithDomShims.window?.NodeFilter !== undefined+) {+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;+}+if (globalWithDomShims.ResizeObserver === undefined) {+ class NoopResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalWithDomShims.ResizeObserver = NoopResizeObserver;+}++const VIEW_MODE_KEY = 'ok-lint-config-view-mode-v1';+const ROOT_CONFIG = '.markdownlint.json';+const NESTED_CONFIG = 'docs/.markdownlint.json';++let mockProjectLintData: { configFile: string | null } | null = null;++vi.doMock('@/editor/lint-config-client', () => ({+ useProjectLintConfig: () => ({ data: mockProjectLintData }),+}));++vi.doMock('@/components/TextViewer', () => ({+ TextViewer: (props: { src?: string; fileName: string; extension: string }) => (+ <div+ data-testid="mock-text-viewer"+ data-src={props.src}+ data-filename={props.fileName}+ data-extension={props.extension}+ />+ ),+}));++vi.doMock('@/components/settings/markdownlint-rule-browser', () => ({+ MarkdownlintRuleBrowser: () => <div data-testid="mock-rule-browser" />,+}));++// The not-in-sidebar chrome reads ConfigProvider context; mock it as a boundary+// and capture the entry it is handed (its own behavior is covered by its tests).+vi.doMock('@/components/NotInSidebarIndicator', () => ({+ NotInSidebarIndicator: (props: { entry: unknown }) => (+ <div data-testid="mock-not-in-sidebar" data-entry={JSON.stringify(props.entry)} />+ ),+}));++const { LintConfigEditor } = await import('./LintConfigEditor');++function renderEditor(assetPath: string) {+ return render(+ <TooltipProvider>+ <LintConfigEditor assetPath={assetPath} />+ </TooltipProvider>,+ );+}++// The toggle segments name themselves via aria-label ("Rules" / "Source").+function rulesSegment(): HTMLButtonElement {+ return screen.getByLabelText('Rules') as HTMLButtonElement;+}+function sourceSegment(): HTMLButtonElement {+ return screen.getByLabelText('Source') as HTMLButtonElement;+}++beforeEach(() => {+ localStorage.clear();+ mockProjectLintData = { configFile: ROOT_CONFIG };+});++afterEach(() => {+ cleanup();+});++describe('LintConfigEditor — toggle and default view', () => {+ test('renders a Source/Rules toggle and defaults to the Source view', () => {+ renderEditor(ROOT_CONFIG);++ expect(rulesSegment()).toBeDefined();+ expect(sourceSegment()).toBeDefined();++ // Default is Source: the read-only viewer mounts, the rule browser does not.+ const viewer = screen.getByTestId('mock-text-viewer');+ expect(viewer.getAttribute('data-src')).toBe(+ `/api/asset-text?path=${encodeURIComponent(ROOT_CONFIG)}`,+ );+ expect(viewer.getAttribute('data-extension')).toBe('json');+ expect(screen.queryByTestId('mock-rule-browser')).toBeNull();++ // Carries the same not-in-sidebar chrome as AssetPreview, keyed to this asset.+ expect(screen.getByTestId('mock-not-in-sidebar').getAttribute('data-entry')).toBe(+ JSON.stringify({ kind: 'asset', path: ROOT_CONFIG }),+ );+ });++ test('renders JSON-highlighted source directly for a .jsonc config', () => {+ const jsoncPath = '.markdownlint.jsonc';+ mockProjectLintData = { configFile: jsoncPath };+ renderEditor(jsoncPath);++ expect(screen.getByTestId('mock-text-viewer').getAttribute('data-extension')).toBe('jsonc');+ });+});++describe('LintConfigEditor — correct-target gating', () => {+ test('enables Rules for the governing root config', () => {+ renderEditor(ROOT_CONFIG);+ expect(rulesSegment().disabled).toBe(false);+ });++ test('disables Rules for a non-governing nested config, Source still works', () => {+ mockProjectLintData = { configFile: ROOT_CONFIG };+ renderEditor(NESTED_CONFIG);++ expect(rulesSegment().disabled).toBe(true);+ expect(screen.getByTestId('mock-text-viewer')).toBeDefined();+ });++ test('disables Rules when no native config file governs, Source still works', () => {+ mockProjectLintData = { configFile: null };+ renderEditor(ROOT_CONFIG);++ expect(rulesSegment().disabled).toBe(true);+ expect(screen.getByTestId('mock-text-viewer')).toBeDefined();+ });++ test('the disabled Rules segment explains why via a tooltip', async () => {+ const user = userEvent.setup();+ mockProjectLintData = { configFile: null };+ renderEditor(ROOT_CONFIG);++ // The disabled <button> can't fire pointer events; the wrapping trigger does.+ const trigger = rulesSegment().parentElement;+ if (trigger === null) throw new Error('expected the Rules segment to have a wrapping trigger');+ await user.hover(trigger);+ await Promise.resolve();++ expect(screen.getByRole('tooltip').textContent).toBe(+ "Rule editing is available for the project's root markdownlint config",+ );+ });++ test('the disabled Rules reason is exposed via aria-describedby (not the poorly-supported aria-description)', () => {+ mockProjectLintData = { configFile: null };+ renderEditor(ROOT_CONFIG);++ const rules = rulesSegment();+ // Announced to keyboard/SR users via a broadly-supported mechanism.+ const describedById = rules.getAttribute('aria-describedby');+ expect(describedById).not.toBeNull();+ expect(document.getElementById(describedById as string)?.textContent).toBe(+ "Rule editing is available for the project's root markdownlint config",+ );+ // The ARIA 1.3 draft attribute (uneven SR support) is not relied upon.+ expect(rules.getAttribute('aria-description')).toBeNull();+ });++ test('the enabled Rules segment names itself via its tooltip', async () => {+ const user = userEvent.setup();+ renderEditor(ROOT_CONFIG);++ const trigger = rulesSegment().parentElement;+ if (trigger === null) throw new Error('expected the Rules segment to have a wrapping trigger');+ await user.hover(trigger);+ await Promise.resolve();++ expect(screen.getByRole('tooltip').textContent).toBe('Rules');+ });++ test('the Source segment names itself via its tooltip (the sourceLabel override)', async () => {+ const user = userEvent.setup();+ renderEditor(ROOT_CONFIG);++ const trigger = sourceSegment().parentElement;+ if (trigger === null) throw new Error('expected the Source segment to have a wrapping trigger');+ await user.hover(trigger);+ await Promise.resolve();++ // The lint-config editor passes sourceLabel="Source"; without the override+ // this would read "Markdown".+ expect(screen.getByRole('tooltip').textContent).toBe('Source');+ });+});++describe('LintConfigEditor — switching and persistence', () => {+ test('switching to Rules mounts the rule browser, unmounts Source, and persists', async () => {+ const user = userEvent.setup();+ renderEditor(ROOT_CONFIG);++ await user.click(rulesSegment());+ expect(screen.getByTestId('mock-rule-browser')).toBeDefined();+ expect(screen.queryByTestId('mock-text-viewer')).toBeNull();+ expect(localStorage.getItem(VIEW_MODE_KEY)).toBe('rules');++ // Returning to Source unmounts the browser and remounts the viewer (a fresh+ // mount refetches, so a WYSIWYG edit is reflected).+ await user.click(sourceSegment());+ expect(screen.getByTestId('mock-text-viewer')).toBeDefined();+ expect(screen.queryByTestId('mock-rule-browser')).toBeNull();+ expect(localStorage.getItem(VIEW_MODE_KEY)).toBe('source');+ });++ test('a persisted Rules preference reopens in Rules on a governing config', () => {+ localStorage.setItem(VIEW_MODE_KEY, 'rules');+ renderEditor(ROOT_CONFIG);++ expect(screen.getByTestId('mock-rule-browser')).toBeDefined();+ expect(screen.queryByTestId('mock-text-viewer')).toBeNull();+ });++ test('a persisted Rules preference falls back to Source on a non-governing config', () => {+ localStorage.setItem(VIEW_MODE_KEY, 'rules');+ mockProjectLintData = { configFile: ROOT_CONFIG };+ renderEditor(NESTED_CONFIG);++ expect(rulesSegment().disabled).toBe(true);+ expect(screen.getByTestId('mock-text-viewer')).toBeDefined();+ expect(screen.queryByTestId('mock-rule-browser')).toBeNull();+ });+});diff --git a/packages/app/src/components/LintConfigEditor.tsx b/packages/app/src/components/LintConfigEditor.tsxnew file mode 100644index 000000000..b7707300e--- /dev/null+++ b/packages/app/src/components/LintConfigEditor.tsx@@ -0,0 +1,101 @@+/**+ * Editor pane for an opened markdownlint JSON config file. Offers a segmented+ * toggle between the raw read-only Source view (`TextViewer`) and the WYSIWYG+ * Rules view (`MarkdownlintRuleBrowser`, the same rule editor the Settings+ * dialog uses), so a config owner can edit rules without hand-writing JSON while+ * still inspecting the file's comments / `extends`.+ *+ * The rule browser writes only the project's ROOT config (its write endpoint+ * targets whatever file the server reports as governing), so Rules is offered+ * only when the opened file IS that governing file — otherwise a nested or+ * not-yet-created config would edit the wrong bytes. When Rules is unavailable+ * the segment is disabled with an explanation and Source stays usable.+ *+ * Only the active segment is mounted: returning to Source remounts `TextViewer`,+ * which refetches the file so a rule written through the Rules view is reflected.+ */++import { useLingui } from '@lingui/react/macro';+import { EditorModeToggle } from '@/components/EditorModeToggle';+import { NotInSidebarIndicator } from '@/components/NotInSidebarIndicator';+import { MarkdownlintRuleBrowser } from '@/components/settings/markdownlint-rule-browser';+import { TextViewer } from '@/components/TextViewer';+import { useProjectLintConfig } from '@/editor/lint-config-client';+import { useLintConfigViewMode } from '@/editor/useLintConfigViewMode';++interface LintConfigEditorProps {+ /** Root-relative path of the opened config asset (no leading slash). */+ assetPath: string;+}++// `/api/asset-text` is the ungated sibling of `/api/asset`: it serves any+// path-safe file as UTF-8 text regardless of the asset allowlist, which is how+// a hidden dotfile config renders. Path-safety is enforced server-side.+function assetTextUrl(assetPath: string): string {+ return `/api/asset-text?path=${encodeURIComponent(assetPath)}`;+}++export function LintConfigEditor({ assetPath }: LintConfigEditorProps) {+ const { t } = useLingui();+ const [viewMode, setViewMode] = useLintConfigViewMode();+ const { data } = useProjectLintConfig();++ // Server and client paths are both root-relative with no leading slash, so a+ // direct string equality identifies the governing root config. `assetPath` is+ // always a non-null string, so the equality alone already rejects a null+ // (or absent) configFile.+ const governingConfigFile = data?.configFile ?? null;+ const rulesEnabled = governingConfigFile === assetPath;++ // Rules lives in the wysiwyg slot; force Source when it's unavailable so a+ // persisted 'rules' preference on a non-governing file never renders blank.+ const isSourceMode = !rulesEnabled || viewMode === 'source';++ const fileName = assetPath.split('/').pop() ?? assetPath;+ const extension = fileName.includes('.') ? (fileName.split('.').pop() ?? '').toLowerCase() : '';++ return (+ <div className="flex h-full min-h-0 flex-col bg-background" data-lint-config-editor="">+ {/* Same not-in-sidebar chrome AssetPreview carries, so a config opened as a+ hidden dotfile advertises the same reveal affordance. Self-gates to null+ when the file is visible in the tree. */}+ <NotInSidebarIndicator+ entry={{ kind: 'asset', path: assetPath }}+ className="shrink-0 border-b bg-background px-3 py-1.5"+ />+ <div className="flex shrink-0 items-center justify-center border-b bg-background py-2">+ <EditorModeToggle+ isSourceMode={isSourceMode}+ onModeChange={(next) => setViewMode(next === 'source' ? 'source' : 'rules')}+ wysiwygDisabled={!rulesEnabled}+ wysiwygLabel={t`Rules`}+ sourceLabel={t`Source`}+ wysiwygDisabledReason={t`Rule editing is available for the project's root markdownlint config`}+ />+ </div>+ {isSourceMode ? (+ // Source is a CodeMirror viewer that owns its own scroll — full-bleed,+ // no wrapper padding (a second scroll container would double-scroll).+ <div className="min-h-0 flex-1 overflow-hidden">+ <TextViewer+ key={assetPath}+ src={assetTextUrl(assetPath)}+ fileName={fileName}+ extension={extension}+ />+ </div>+ ) : (+ // The rule browser has no scroll or padding of its own — in Settings it+ // inherits both from the dialog body. Standalone it needs its own+ // scroll container and the same content gutter as other panes.+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-6">+ <div className="mx-auto w-full max-w-3xl">+ {/* The user is looking at the config file — the "these rules come from+ <file>" note the Settings dialog shows would be redundant here. */}+ <MarkdownlintRuleBrowser hideConfigSourceNote />+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsx b/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsxindex 5cff28019..f580776d6 100644--- a/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsx+++ b/packages/app/src/components/settings/markdownlint-rule-browser.dom.test.tsx@@ -8,13 +8,13 @@* resets, and expanded-row option edits write through the lint-config client.*/-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';import {DEFAULT_MARKDOWNLINT_CONFIG,MARKDOWNLINT_RULE_CATALOG,} from '@inkeep/open-knowledge-core';import { cleanup, render, screen, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';// Radix primitives reach for DOM globals the jsdom preload doesn't expose;@@ -56,7 +56,7 @@ function lintData(rules: Record<string, unknown>, configFile?: string): unknown};}-mock.module('@/editor/lint-config-client', () => ({+vi.doMock('@/editor/lint-config-client', () => ({emitLintConfigChanged: () => {},subscribeToLintConfigChanged: () => () => {},runLintAudit: async () => null,@@ -69,7 +69,7 @@ mock.module('@/editor/lint-config-client', () => ({},}));-mock.module('sonner', () => ({+vi.doMock('sonner', () => ({toast: {error: (msg: string) => {toastErrors.push(msg);@@ -80,10 +80,10 @@ mock.module('sonner', () => ({const { MarkdownlintRuleBrowser } = await import('./markdownlint-rule-browser');-function renderBrowser() {+function renderBrowser(props?: { hideConfigSourceNote?: boolean }) {return render(<TooltipProvider>- <MarkdownlintRuleBrowser />+ <MarkdownlintRuleBrowser {...props} /></TooltipProvider>,);}@@ -116,6 +116,23 @@ describe('MarkdownlintRuleBrowser — no-file disclaimer', () => {});});+describe('MarkdownlintRuleBrowser — config source note', () => {+ test('shows the source note by default but hides it when hideConfigSourceNote is set', () => {+ mockProjectLintData = lintData({ default: true }, '.markdownlint.json');++ renderBrowser();+ expect(screen.getByTestId('markdownlint-config-source-note')).toBeDefined();+ cleanup();++ // The lint-config editor mounts with the note suppressed — the user is+ // already looking at the file, so the "these rules come from <file>" note+ // is redundant. The Modified-badge legend stays.+ renderBrowser({ hideConfigSourceNote: true });+ expect(screen.queryByTestId('markdownlint-config-source-note')).toBeNull();+ expect(screen.getByTestId('markdownlint-rule-browser-legend')).toBeDefined();+ });+});+describe('MarkdownlintRuleBrowser — full-catalog listing', () => {test('renders every generated-catalog rule grouped into category sections', () => {renderBrowser();diff --git a/packages/app/src/components/settings/markdownlint-rule-browser.tsx b/packages/app/src/components/settings/markdownlint-rule-browser.tsxindex 1d55fc844..abd7f4b28 100644--- a/packages/app/src/components/settings/markdownlint-rule-browser.tsx+++ b/packages/app/src/components/settings/markdownlint-rule-browser.tsx@@ -43,7 +43,18 @@ import { RuleOptionField, type RuleOptionValue } from './rule-option-field';type RuleValues = Record<string, MarkdownlintRuleSetting>;-export function MarkdownlintRuleBrowser() {+interface MarkdownlintRuleBrowserProps {+ /**+ * Hide the "these rules come from <file>" source note. The lint-config editor+ * sets this: the user is already looking at the file, so the note is redundant+ * there. The Settings dialog (no file context) leaves it on.+ */+ hideConfigSourceNote?: boolean;+}++export function MarkdownlintRuleBrowser({+ hideConfigSourceNote = false,+}: MarkdownlintRuleBrowserProps = {}) {const { t } = useLingui();const { data } = useProjectLintConfig();const ready = data !== null;@@ -77,57 +88,61 @@ export function MarkdownlintRuleBrowser() {return (<div className="space-y-3" data-testid="settings-linting-markdownlint-rules">- {!ready ? (- // Stable placeholder while the project config loads. Rendering either the- // has-file or no-file copy before we know which one is correct causes a- // visible reflow when the fetch resolves (the no-file state is a taller- // two-paragraph + callout block); the skeleton reserves height instead.- <div- className="space-y-2"- aria-busy="true"- data-testid="markdownlint-rule-browser-config-loading"- >- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-2/3" />- </div>- ) : configFile ? (- <p className="text-sm text-muted-foreground">- <Trans>- These rules come from your project's{' '}- <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">{configFile}</code>{' '}- file, which fully governs linting for this project. Turn rules on or off and edit their- options here; changes write back to the file.- </Trans>- </p>- ) : (- <div className="space-y-2">- <p className="text-sm text-muted-foreground">+ {!hideConfigSourceNote &&+ (!ready ? (+ // Stable placeholder while the project config loads. Rendering either the+ // has-file or no-file copy before we know which one is correct causes a+ // visible reflow when the fetch resolves (the no-file state is a taller+ // two-paragraph + callout block); the skeleton reserves height instead.+ <div+ className="space-y-2"+ aria-busy="true"+ data-testid="markdownlint-rule-browser-config-loading"+ >+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ ) : configFile ? (+ <p+ className="text-sm text-muted-foreground"+ data-testid="markdownlint-config-source-note"+ ><Trans>- No{' '}- <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">- .markdownlint.*- </code>{' '}- file yet — every rule runs on the same defaults as the VS Code markdownlint extension:- all on, except line length.+ These rules come from your project's{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">{configFile}</code>{' '}+ file, which fully governs linting for this project. Turn rules on or off and edit+ their options here; changes write back to the file.</Trans></p>- <p- className="flex items-start gap-1.5 rounded-md border border-dashed p-2.5 text-sm text-muted-foreground"- data-testid="markdownlint-no-file-disclaimer"- >- <Info aria-hidden className="mt-0.5 size-4 shrink-0" />- <span>+ ) : (+ <div className="space-y-2">+ <p className="text-sm text-muted-foreground"><Trans>- Heads up: editing any rule or option here creates a{' '}+ No{' '}<code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">- .markdownlint.json+ .markdownlint.*</code>{' '}- file in your project to save your changes.+ file yet — every rule runs on the same defaults as the VS Code markdownlint+ extension: all on, except line length.</Trans>- </span>- </p>- </div>- )}+ </p>+ <p+ className="flex items-start gap-1.5 rounded-md border border-dashed p-2.5 text-sm text-muted-foreground"+ data-testid="markdownlint-no-file-disclaimer"+ >+ <Info aria-hidden className="mt-0.5 size-4 shrink-0" />+ <span>+ <Trans>+ Heads up: editing any rule or option here creates a{' '}+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">+ .markdownlint.json+ </code>{' '}+ file in your project to save your changes.+ </Trans>+ </span>+ </p>+ </div>+ ))}<p className="text-sm text-muted-foreground" data-testid="markdownlint-rule-browser-legend"><Trans>diff --git a/packages/app/src/editor/useLintConfigViewMode.test.ts b/packages/app/src/editor/useLintConfigViewMode.test.tsnew file mode 100644index 000000000..48c0f58e7--- /dev/null+++ b/packages/app/src/editor/useLintConfigViewMode.test.ts@@ -0,0 +1,254 @@+/**+ * useLintConfigViewMode — unit tests for the pure-logic surfaces:+ * - `isLintConfigViewMode` (type guard)+ * - `readPersistedViewMode` (storage read + validation + throw swallow)+ * - `persistViewMode` (storage write + throw swallow with console.warn)+ *+ * Repo convention (see use-editor-mode.test.ts): no @testing-library/react, no+ * happy-dom. The React state-transition behavior (useState init, load-time+ * read) is exercised end-to-end when the config editor mounts; these unit+ * tests cover the entire input-validation + storage-interaction surface with a+ * fake Storage injected at the one real boundary (localStorage).+ */++import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import {+ isLintConfigViewMode,+ LINT_CONFIG_VIEW_MODES,+ type LintConfigViewMode,+ persistViewMode,+ readPersistedViewMode,+} from './useLintConfigViewMode';++// ---------------------------------------------------------------------------+// Fake storage (minimal `getItem` / `setItem` surface)+// ---------------------------------------------------------------------------++interface FakeStorage {+ getItem: ReturnType<typeof vi.fn>;+ setItem: ReturnType<typeof vi.fn>;+}++function storageWith(value: string | null): FakeStorage {+ return {+ getItem: vi.fn(() => value),+ setItem: vi.fn(() => undefined),+ };+}++function storageThatThrowsOnGet(err: Error = new Error('privacy mode')): FakeStorage {+ return {+ getItem: vi.fn(() => {+ throw err;+ }),+ setItem: vi.fn(() => undefined),+ };+}++function storageThatThrowsOnSet(err: Error = new Error('quota exceeded')): FakeStorage {+ return {+ getItem: vi.fn(() => null),+ setItem: vi.fn(() => {+ throw err;+ }),+ };+}++// ---------------------------------------------------------------------------+// isLintConfigViewMode+// ---------------------------------------------------------------------------++describe('isLintConfigViewMode — type guard', () => {+ test("accepts 'source'", () => {+ expect(isLintConfigViewMode('source')).toBe(true);+ });++ test("accepts 'rules'", () => {+ expect(isLintConfigViewMode('rules')).toBe(true);+ });++ // The doc editor persists 'wysiwyg'; this surface must never treat that as a+ // valid view mode, so a leaked/shared value can't cross between the two.+ test("rejects 'wysiwyg' (the doc editor's value, not a config view mode)", () => {+ expect(isLintConfigViewMode('wysiwyg')).toBe(false);+ });++ test('rejects other strings (garbage, case-mismatch)', () => {+ expect(isLintConfigViewMode('garbage')).toBe(false);+ expect(isLintConfigViewMode('Source')).toBe(false);+ expect(isLintConfigViewMode('RULES')).toBe(false);+ });++ test('rejects empty string', () => {+ expect(isLintConfigViewMode('')).toBe(false);+ });++ test('rejects null, undefined, numbers, objects', () => {+ expect(isLintConfigViewMode(null)).toBe(false);+ expect(isLintConfigViewMode(undefined)).toBe(false);+ expect(isLintConfigViewMode(0)).toBe(false);+ expect(isLintConfigViewMode({})).toBe(false);+ });++ // Drift-prevention: the guard and the type derive from the same+ // `LINT_CONFIG_VIEW_MODES` const array, so adding a mode updates both. This+ // fails loudly if the const and the guard ever diverge.+ test('every LINT_CONFIG_VIEW_MODES entry is accepted by the guard', () => {+ for (const value of LINT_CONFIG_VIEW_MODES) {+ expect(isLintConfigViewMode(value)).toBe(true);+ }+ });++ test('LINT_CONFIG_VIEW_MODES contains exactly the current mode set', () => {+ expect([...LINT_CONFIG_VIEW_MODES].sort()).toEqual(['rules', 'source']);+ });+});++// ---------------------------------------------------------------------------+// readPersistedViewMode — storage read + validation + throw swallow+// ---------------------------------------------------------------------------++describe('readPersistedViewMode — localStorage read with validation', () => {+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;++ beforeEach(() => {+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ });++ afterEach(() => {+ warnSpy?.mockRestore();+ warnSpy = undefined;+ });++ test("returns 'source' when storage is empty (default fallback)", () => {+ const storage = storageWith(null);+ expect(readPersistedViewMode(storage)).toBe('source');+ // First-time user; no warn — only the invalid-value branch logs.+ expect(warnSpy).not.toHaveBeenCalled();+ });++ test("returns 'rules' when storage holds 'rules' (round-trip)", () => {+ const storage = storageWith('rules');+ expect(readPersistedViewMode(storage)).toBe('rules');+ expect(warnSpy).not.toHaveBeenCalled();+ });++ test("returns 'source' when storage holds 'source'", () => {+ const storage = storageWith('source');+ expect(readPersistedViewMode(storage)).toBe('source');+ expect(warnSpy).not.toHaveBeenCalled();+ });++ test("falls back to 'source' when storage holds an invalid value", () => {+ const storage = storageWith('garbage');+ expect(readPersistedViewMode(storage)).toBe('source');+ });++ test('logs a diagnostic warn on an invalid persisted value', () => {+ const storage = storageWith('garbage-from-tampering-or-old-schema');+ expect(readPersistedViewMode(storage)).toBe('source');+ expect(warnSpy).toHaveBeenCalledTimes(1);+ const firstCall = warnSpy?.mock.calls[0];+ expect(firstCall?.[0]).toBe(+ '[lint-config-view-mode] invalid persisted value, falling back to default',+ );+ expect(firstCall?.[1]).toMatchObject({ raw: 'garbage-from-tampering-or-old-schema' });+ });++ // A value from the doc editor's storage is not a valid config view mode; it+ // is treated as any other invalid value (default + warn), never adopted.+ test("falls back to 'source' AND warns when storage holds 'wysiwyg'", () => {+ const storage = storageWith('wysiwyg');+ expect(readPersistedViewMode(storage)).toBe('source');+ expect(warnSpy).toHaveBeenCalledTimes(1);+ });++ test("returns 'source' and swallows SILENTLY when getItem throws (privacy mode)", () => {+ const storage = storageThatThrowsOnGet();+ expect(readPersistedViewMode(storage)).toBe('source');+ expect(storage.getItem).toHaveBeenCalledTimes(1);+ // Privacy-mode throws are a normal environmental condition, not a bug —+ // only the invalid-value branch warns.+ expect(warnSpy).not.toHaveBeenCalled();+ });++ test('reads exactly once per call (no redundant storage access)', () => {+ const storage = storageWith('rules');+ readPersistedViewMode(storage);+ expect(storage.getItem).toHaveBeenCalledTimes(1);+ });++ // Contract: the config view mode has its own key and MUST NOT read the doc+ // editor's 'ok-editor-mode-v1'. A key rename is a 1-way door.+ test("reads from 'ok-lint-config-view-mode-v1', never the doc editor's key", () => {+ const storage = storageWith(null);+ readPersistedViewMode(storage);+ expect(storage.getItem).toHaveBeenCalledWith('ok-lint-config-view-mode-v1');+ expect(storage.getItem).not.toHaveBeenCalledWith('ok-editor-mode-v1');+ });+});++// ---------------------------------------------------------------------------+// persistViewMode — storage write + throw swallow + warn prefix+// ---------------------------------------------------------------------------++describe('persistViewMode — localStorage write with error swallow', () => {+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;++ beforeEach(() => {+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ });++ afterEach(() => {+ warnSpy?.mockRestore();+ warnSpy = undefined;+ });++ test("writes 'rules' to storage under the correct key", () => {+ const storage = storageWith(null);+ const ok = persistViewMode('rules', storage);+ expect(ok).toBe(true);+ expect(storage.setItem).toHaveBeenCalledTimes(1);+ expect(storage.setItem).toHaveBeenCalledWith('ok-lint-config-view-mode-v1', 'rules');+ expect(warnSpy).not.toHaveBeenCalled();+ });++ // Contract: writes go to the config key, never the doc editor's key.+ test("writes 'source' under 'ok-lint-config-view-mode-v1', never the doc editor's key", () => {+ const storage = storageWith(null);+ const ok = persistViewMode('source', storage);+ expect(ok).toBe(true);+ expect(storage.setItem).toHaveBeenCalledWith('ok-lint-config-view-mode-v1', 'source');+ expect(storage.setItem).not.toHaveBeenCalledWith('ok-editor-mode-v1', 'source');+ });++ test('returns false and logs warn when setItem throws (quota / privacy mode)', () => {+ const storage = storageThatThrowsOnSet();+ const ok = persistViewMode('source', storage);+ expect(ok).toBe(false);+ expect(warnSpy).toHaveBeenCalledTimes(1);+ const firstCall = warnSpy?.mock.calls[0];+ expect(firstCall?.[0]).toBe('[lint-config-view-mode] persist failed');+ // Second arg is the error — included for observability.+ expect(firstCall?.[1]).toBeInstanceOf(Error);+ });++ test('write throw is fully swallowed — caller never sees the exception', () => {+ const storage = storageThatThrowsOnSet();+ expect(() => persistViewMode('source', storage)).not.toThrow();+ });+});++// ---------------------------------------------------------------------------+// Module shape — type-level `as const` drift guard+// ---------------------------------------------------------------------------++describe('module exports — type-level shape', () => {+ test('LINT_CONFIG_VIEW_MODES keeps its `as const` tuple shape (runtime readonly)', () => {+ // Type-only assertion: `as const` produces `readonly [...]`; this compiles+ // iff the constant keeps its tuple-literal shape (losing `as const` widens+ // it to `string[]` and fails this assignment).+ const values: readonly LintConfigViewMode[] = LINT_CONFIG_VIEW_MODES;+ expect(values).toHaveLength(2);+ });+});diff --git a/packages/app/src/editor/useLintConfigViewMode.ts b/packages/app/src/editor/useLintConfigViewMode.tsnew file mode 100644index 000000000..129798d0a--- /dev/null+++ b/packages/app/src/editor/useLintConfigViewMode.ts@@ -0,0 +1,90 @@+/**+ * useLintConfigViewMode — persists the user's chosen view for an opened+ * markdownlint config file (`source` raw text vs `rules` rule browser) to+ * localStorage as a user-global preference.+ *+ * This is deliberately its own preference, keyed separately from the markdown+ * document editor's mode (`ok-editor-mode-v1`): a person who prefers `source`+ * for their prose and `rules` for their config should not have one choice+ * silently move the other.+ *+ * Read-once: the hook reads localStorage exactly once in its `useState`+ * initializer and writes on each set, so the last toggle wins at the next+ * open. Open tabs/windows do NOT update each other live — a spontaneous view+ * flip on tab-focus would surprise the user mid-task.+ */+import { useState } from 'react';++const STORAGE_KEY = 'ok-lint-config-view-mode-v1';++// Single source for the persistable view-mode set — `LintConfigViewMode` and+// the type guard both derive from this, so adding a value updates both at once.+export const LINT_CONFIG_VIEW_MODES = ['source', 'rules'] as const;++export type LintConfigViewMode = (typeof LINT_CONFIG_VIEW_MODES)[number];++const DEFAULT_VIEW_MODE: LintConfigViewMode = 'source';++/** Type guard — exported for unit testing and for validating stored values. */+export function isLintConfigViewMode(raw: unknown): raw is LintConfigViewMode {+ return (LINT_CONFIG_VIEW_MODES as readonly unknown[]).includes(raw);+}++/**+ * Read the persisted view mode. Default on miss, invalid value, or storage+ * throw. Logs a diagnostic warn only on structurally invalid values —+ * storage-throw stays silent because privacy-mode / quota are normal+ * environmental conditions, not bugs, while a value that fails the guard means+ * manual tampering or an old schema and is worth tracing.+ */+export function readPersistedViewMode(+ storage: Pick<Storage, 'getItem'> = localStorage,+): LintConfigViewMode {+ try {+ const raw = storage.getItem(STORAGE_KEY);+ if (raw === null) return DEFAULT_VIEW_MODE;+ if (isLintConfigViewMode(raw)) return raw;+ console.warn('[lint-config-view-mode] invalid persisted value, falling back to default', {+ raw,+ });+ } catch {+ // Privacy mode / quota — stay silent; only the invalid-value branch warns.+ }+ return DEFAULT_VIEW_MODE;+}++/**+ * Persist view mode to storage. Swallows throws (privacy mode, quota) with a+ * console.warn; returns false on throw so a caller can react if it needs to.+ */+export function persistViewMode(+ next: LintConfigViewMode,+ storage: Pick<Storage, 'setItem'> = localStorage,+): boolean {+ try {+ storage.setItem(STORAGE_KEY, next);+ return true;+ } catch (err) {+ console.warn('[lint-config-view-mode] persist failed', err);+ return false;+ }+}++/**+ * Returns `[mode, setMode]`. `setMode` updates React state AND persists to+ * localStorage. Does NOT listen for cross-window changes — open tabs remain+ * independent until one reloads.+ */+export function useLintConfigViewMode(): readonly [+ LintConfigViewMode,+ (next: LintConfigViewMode) => void,+] {+ const [mode, setMode] = useState<LintConfigViewMode>(readPersistedViewMode);++ function persistAndSet(next: LintConfigViewMode) {+ setMode(next);+ persistViewMode(next);+ }++ return [mode, persistAndSet] as const;+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex de8cb9c99..70843f10f 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -225,6 +225,7 @@"4BITzH": ["Error:"],"4CfgPM": ["Project folder created, but git init failed. Try again."],"4E9jPa": ["Create your first project"],+ "4EZrJN": ["Rules"],"4Gz2wC": ["Failed to upload file"],"4KmEoC": ["Hotkeys"],"4NC2Ym": ["Move to the next or previous table cell."],@@ -695,6 +696,7 @@"EcM3k7": ["Failed to clean up pending ", ["kind"]],"EcR0fl": ["Checking for installed agents"],"EdQY6l": ["None"],+ "EeUucb": ["Rule editing is available for the project's root markdownlint config"],"Ef7StM": ["Unknown"],"EhDLBx": ["You modified <0>", ["filePath"], "</0> locally, but it was deleted upstream."],"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 3bc9e470f..719df6b9a 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -6804,6 +6804,14 @@ msgstr "Role"msgid "root"msgstr "root"+#: src/components/LintConfigEditor.tsx+msgid "Rule editing is available for the project's root markdownlint config"+msgstr "Rule editing is available for the project's root markdownlint config"++#: src/components/LintConfigEditor.tsx+msgid "Rules"+msgstr "Rules"+#: src/components/settings/LintingSection.tsxmsgid "Run a project audit from the Problems panel."msgstr "Run a project audit from the Problems panel."@@ -7479,6 +7487,7 @@ msgid "Something went wrong. Please try again."msgstr "Something went wrong. Please try again."#: src/components/AgentDiffPane.tsx+#: src/components/LintConfigEditor.tsx#: src/components/MermaidFileViewer.tsx#: src/components/TimelineDiffPane.tsxmsgid "Source"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 3ffea1a67..ca4732529 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -225,6 +225,7 @@"4BITzH": ["Ēŕŕōŕ:"],"4CfgPM": ["ƤŕōĴēćţ ƒōĺďēŕ ćŕēàţēď, ƀũţ ĝĩţ ĩńĩţ ƒàĩĺēď. Ţŕŷ àĝàĩń."],"4E9jPa": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƥŕōĴēćţ"],+ "4EZrJN": ["Ŕũĺēś"],"4Gz2wC": ["Ƒàĩĺēď ţō ũƥĺōàď ƒĩĺē"],"4KmEoC": ["Ĥōţķēŷś"],"4NC2Ym": ["Ḿōvē ţō ţĥē ńēxţ ōŕ ƥŕēvĩōũś ţàƀĺē ćēĺĺ."],@@ -695,6 +696,7 @@"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],"EcR0fl": ["Ćĥēćķĩńĝ ƒōŕ ĩńśţàĺĺēď àĝēńţś"],"EdQY6l": ["Ńōńē"],+ "EeUucb": ["Ŕũĺē ēďĩţĩńĝ ĩś àvàĩĺàƀĺē ƒōŕ ţĥē ƥŕōĴēćţ'ś ŕōōţ ḿàŕķďōŵńĺĩńţ ćōńƒĩĝ"],"Ef7StM": ["Ũńķńōŵń"],"EhDLBx": ["Ŷōũ ḿōďĩƒĩēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ďēĺēţēď ũƥśţŕēàḿ."],"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 60b0669f5..f48e9eee4 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -6800,6 +6800,14 @@ msgstr ""msgid "root"msgstr ""+#: src/components/LintConfigEditor.tsx+msgid "Rule editing is available for the project's root markdownlint config"+msgstr ""++#: src/components/LintConfigEditor.tsx+msgid "Rules"+msgstr ""+#: src/components/settings/LintingSection.tsxmsgid "Run a project audit from the Problems panel."msgstr ""@@ -7475,6 +7483,7 @@ msgid "Something went wrong. Please try again."msgstr ""#: src/components/AgentDiffPane.tsx+#: src/components/LintConfigEditor.tsx#: src/components/MermaidFileViewer.tsx#: src/components/TimelineDiffPane.tsxmsgid "Source"diff --git a/packages/app/tests/stress/lint-config-toggle.e2e.ts b/packages/app/tests/stress/lint-config-toggle.e2e.tsnew file mode 100644index 000000000..731023356--- /dev/null+++ b/packages/app/tests/stress/lint-config-toggle.e2e.ts@@ -0,0 +1,347 @@+/**+ * End-to-end coverage for the markdownlint-config Source/Rules toggle+ * (LintConfigEditor). These are the running-app fidelities the DOM tests can't+ * reach: the DOM test (`LintConfigEditor.dom.test.tsx`) mocks the three system+ * boundaries — `useProjectLintConfig` (GET /api/lint/config), `TextViewer`+ * (GET /api/asset-text), and `MarkdownlintRuleBrowser` (POST+ * /api/lint/markdownlint-config) — so the real chain+ * open -> real config discovery -> real rule write -> real disk -> Source+ * re-render is UNKNOWN until exercised against a live server. This file drives+ * the real Vite dev server + API (per-worker fixture) with real+ * `.markdownlint.json` / `.markdownlint.jsonc` files on disk.+ *+ * The config is a hidden dotfile served through the ungated `/api/asset-text`+ * route and opened by hash (`#/__asset__/<path>`), so no "Show hidden files"+ * sidebar toggle is needed to reach it here — direct hash nav mirrors selecting+ * the file once it is revealed (the FileTree dotfile-hiding path is the+ * sidebar's concern, out of scope for the editor pane under test).+ *+ * Discovery is live and filesystem-bound (`existsSync`/`readFileSync` per+ * request in `markdownlint-discovery.ts` + the GET/POST lint handlers), so a+ * config written straight into the worker's content dir is seen immediately by+ * both `/api/lint/config` and `/api/asset-text` with no watcher/index round.+ */++import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import { expect, test } from './_helpers';++/** Hash for opening a content-dir asset directly (mirrors `hashFromAssetPath`). */+function assetHash(assetPath: string): string {+ return `/#/__asset__/${assetPath.split('/').map(encodeURIComponent).join('/')}`;+}++const configEditor = (page: Page) => page.locator('[data-lint-config-editor]');+// The toggle segments name themselves via aria-label ("Rules" / "Source"),+// scoped to the config editor so the doc-editor toggle ("Visual editor" /+// "Markdown source") can never be matched by accident.+const rulesSegment = (page: Page) =>+ configEditor(page).getByRole('radio', { name: 'Rules', exact: true });+const sourceSegment = (page: Page) =>+ configEditor(page).getByRole('radio', { name: 'Source', exact: true });+// The read-only source viewer, loaded branch only (data-text-viewer is stamped+// on every fetch state; `-state="loaded"` disambiguates the mounted-with-bytes+// variant).+const loadedSource = (page: Page) =>+ configEditor(page).locator('[data-text-viewer][data-text-viewer-state="loaded"]');+const ruleBrowser = (page: Page) =>+ page.locator('[data-testid="settings-linting-markdownlint-rules"]');++// Config basenames this suite writes into the shared per-worker content dir.+// The afterEach hook clears them so a leftover governing `.markdownlint.json`+// never changes lint resolution for sibling stress files on the same worker.+const CLEANUP_PATHS = [+ '.markdownlint.json',+ '.markdownlint.jsonc',+ 'base.json',+ 'docs/.markdownlint.json',+ 'lint-cfg-package.json',+] as const;++function cleanupConfigs(contentDir: string): void {+ for (const rel of CLEANUP_PATHS) {+ rmSync(join(contentDir, rel), { force: true });+ }+}++test.describe('lint-config Source/Rules toggle — running-app E2E (PRD-7378)', () => {+ test.afterEach(({ workerServer }) => {+ cleanupConfigs(workerServer.contentDir);+ });++ // Opening the governing root config shows the toggle with Source as the+ // default view, and the Source view is byte-faithful to the on-disk file.+ test('root .markdownlint.json opens with a Source/Rules toggle, Source default, byte-faithful', async ({+ page,+ workerServer,+ }) => {+ const assetPath = '.markdownlint.json';+ // Distinctive bytes: a rule map with unusual (3-space) indentation so the+ // byte-fidelity assertion is meaningful, not a formatter no-op.+ const fileBytes = '{\n "MD013": false,\n "MD033": false\n}\n';+ writeFileSync(join(workerServer.contentDir, assetPath), fileBytes, 'utf-8');++ await page.goto(assetHash(assetPath));++ // The dedicated config editor mounts (not the plain AssetPreview).+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });++ // Both segments render; Source is the default view (the read-only viewer is+ // mounted, the rule browser is not — the behavioral signal for the active+ // segment, mirroring the DOM test's mount assertions).+ await expect(sourceSegment(page)).toBeVisible();+ await expect(rulesSegment(page)).toBeVisible();+ await expect(loadedSource(page)).toBeVisible({ timeout: 15_000 });+ await expect(ruleBrowser(page)).toHaveCount(0);++ // Byte faithfulness: the ungated /api/asset-text route serves the file+ // exactly as it is on disk — no reformat, no BOM/newline mutation. Compare+ // the served bytes to a direct disk read (the true oracle; the rendered+ // CodeMirror DOM is virtualized/normalized and not byte-exact).+ const served = await page.request.get(`/api/asset-text?path=${encodeURIComponent(assetPath)}`);+ expect(served.status()).toBe(200);+ const servedText = await served.text();+ const diskText = readFileSync(join(workerServer.contentDir, assetPath), 'utf-8');+ expect(servedText).toBe(diskText);+ expect(servedText).toBe(fileBytes);+ });++ // Toggling a rule in Rules writes to the real config on disk, the real+ // MarkdownlintRuleBrowser mounts and is interactive outside Settings, Source+ // reflects the WYSIWYG edit after switching back, and the Rules preference+ // persists across close/reopen.+ test('toggling a rule in Rules writes to disk, Source reflects it, and the preference persists', async ({+ page,+ api,+ workerServer,+ }) => {+ const assetPath = '.markdownlint.json';+ writeFileSync(join(workerServer.contentDir, assetPath), '{\n "MD013": false\n}\n', 'utf-8');++ await page.goto(assetHash(assetPath));+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });++ // Rules is enabled once the governing config resolves (GET /api/lint/config+ // reports configFile === the opened path). The segment is disabled until+ // that fetch lands, so wait for enablement rather than asserting eagerly.+ await expect(rulesSegment(page)).toBeEnabled({ timeout: 15_000 });+ await rulesSegment(page).click();++ // The REAL rule browser (the same component Settings mounts) renders+ // in the editor pane — providers satisfied, catalog interactive.+ await expect(ruleBrowser(page)).toBeVisible({ timeout: 15_000 });+ await expect(loadedSource(page)).toHaveCount(0);++ // Narrow to MD013 (search forces every section open so the row renders) and+ // flip it on. The Switch write path is real: onWrite -> writeMarkdownlintRule+ // -> POST /api/lint/markdownlint-config -> format-preserving writer -> disk.+ await page.locator('[data-testid="markdownlint-rule-search"]').fill('MD013');+ const md013Toggle = page.locator('[data-testid="markdownlint-rule-toggle-MD013"]');+ await expect(md013Toggle).toBeEnabled({ timeout: 15_000 });+ await md013Toggle.click();++ // The change is on the actual file on disk (false -> true).+ await expect+ .poll(+ () => {+ const raw = readFileSync(join(workerServer.contentDir, assetPath), 'utf-8');+ return JSON.parse(raw).MD013;+ },+ { timeout: 15_000, message: 'MD013 must be written to .markdownlint.json on disk' },+ )+ .toBe(true);++ // Switching back to Source remounts TextViewer (Rules had unmounted it),+ // which refetches /api/asset-text and shows the just-written bytes.+ await sourceSegment(page).click();+ await expect(loadedSource(page)).toBeVisible({ timeout: 15_000 });+ await expect(loadedSource(page).locator('.cm-content')).toContainText(/"MD013"\s*:\s*true/, {+ timeout: 15_000,+ });++ // The Rules preference is now persisted. Reopen the config after navigating+ // away — LintConfigEditor remounts and honors the persisted 'rules' on the+ // governing config.+ await sourceSegment(page).click(); // ensure Source is active first...+ await rulesSegment(page).click(); // ...then choose Rules so the pref is 'rules'.+ await expect(ruleBrowser(page)).toBeVisible({ timeout: 15_000 });++ await api.createPage('lint-cfg-away.md');+ await page.goto(`/#/lint-cfg-away`);+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)', { timeout: 15_000 });++ await page.goto(assetHash(assetPath));+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });+ // Reopened straight into Rules (persisted), not the default Source.+ await expect(ruleBrowser(page)).toBeVisible({ timeout: 15_000 });+ await expect(loadedSource(page)).toHaveCount(0);+ });++ // Format-preserving round-trip through the running UI, and .jsonc renders+ // with jsonc-highlighted source directly on open.+ test('editing a .jsonc rule preserves comment, extends, trailing comma, and default:false', async ({+ page,+ workerServer,+ }) => {+ const assetPath = '.markdownlint.jsonc';+ // A base the extends points at, so `extends` resolves cleanly (no problem+ // noise) while remaining a construct the writer must preserve verbatim.+ writeFileSync(join(workerServer.contentDir, 'base.json'), '{}\n', 'utf-8');+ const jsoncBytes = [+ '// project markdownlint config',+ '{',+ ' "extends": "./base.json",',+ ' "default": false,',+ ' "MD013": false,',+ ' "MD033": false,',+ '}',+ '',+ ].join('\n');+ writeFileSync(join(workerServer.contentDir, assetPath), jsoncBytes, 'utf-8');++ await page.goto(assetHash(assetPath));+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });++ // The .jsonc opens directly in a jsonc-highlighted source view — no "View+ // as text" indirection. TextViewer stamps the resolved extension.+ await expect(loadedSource(page)).toHaveAttribute('data-text-viewer-extension', 'jsonc', {+ timeout: 15_000,+ });++ // Edit one rule through the real Rules browser.+ await expect(rulesSegment(page)).toBeEnabled({ timeout: 15_000 });+ await rulesSegment(page).click();+ await expect(ruleBrowser(page)).toBeVisible({ timeout: 15_000 });+ await page.locator('[data-testid="markdownlint-rule-search"]').fill('MD009');+ const md009Toggle = page.locator('[data-testid="markdownlint-rule-toggle-MD009"]');+ await expect(md009Toggle).toBeEnabled({ timeout: 15_000 });+ await md009Toggle.click();++ // Read the file back from disk and prove every hand-authored JSONC construct+ // survived the write, alongside the applied change. Poll until the write+ // lands (POST is async after the click).+ await expect+ .poll(() => readFileSync(join(workerServer.contentDir, assetPath), 'utf-8'), {+ timeout: 15_000,+ message: 'the MD009 write must land in .markdownlint.jsonc',+ })+ .toContain('MD009');+ const roundTripped = readFileSync(join(workerServer.contentDir, assetPath), 'utf-8');+ expect(roundTripped).toContain('// project markdownlint config'); // leading comment+ expect(roundTripped).toContain('"extends": "./base.json"'); // extends reference+ expect(roundTripped).toContain('"default": false'); // default:false entry+ expect(roundTripped).toMatch(/"MD033":\s*false,/); // trailing comma preserved+ });++ // A non-governing nested config disables Rules with an explanatory tooltip+ // while Source still works; the disabled Rules segment keeps its accessible+ // name and the reason tooltip is reachable on the wrapping trigger.+ test('a nested docs/.markdownlint.json disables Rules with a tooltip while Source still works', async ({+ page,+ workerServer,+ }) => {+ // Root config governs; the nested one is NOT the governing file the writer+ // targets, so Rules must be disabled for it.+ writeFileSync(+ join(workerServer.contentDir, '.markdownlint.json'),+ '{\n "MD013": false\n}\n',+ 'utf-8',+ );+ mkdirSync(join(workerServer.contentDir, 'docs'), { recursive: true });+ const nestedPath = 'docs/.markdownlint.json';+ writeFileSync(join(workerServer.contentDir, nestedPath), '{\n "MD041": false\n}\n', 'utf-8');++ await page.goto(assetHash(nestedPath));+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });++ // Source still renders the nested file's bytes.+ await expect(loadedSource(page)).toBeVisible({ timeout: 15_000 });++ // The disabled Rules segment keeps its accessible name...+ const rules = rulesSegment(page);+ await expect(rules).toHaveCount(1);+ // ...and is disabled (correct-target gating — configFile is the root, not+ // this nested path).+ await expect(rules).toBeDisabled({ timeout: 15_000 });+ // Deterministically confirm the gating input resolved to a different file,+ // then that Rules stays disabled — a leading-slash / separator equality bug+ // would have flipped it enabled once the config landed.+ const nestedCfg = await page.request.get('/api/lint/config');+ expect(nestedCfg.status()).toBe(200);+ expect((await nestedCfg.json()).configFile).not.toBe(nestedPath);+ await expect(rules).toBeDisabled();++ // The reason tooltip is reachable. The disabled <button> can't fire pointer+ // events, so the wrapping <div> (the TooltipTrigger) is hovered.+ await rules.locator('xpath=..').hover();+ await expect(page.getByRole('tooltip')).toContainText(+ "Rule editing is available for the project's root markdownlint config",+ { timeout: 15_000 },+ );+ });++ // A normal .json file is unaffected — no toggle, the existing AssetPreview.+ test('a normal package.json opens in the plain read-only preview with no Source/Rules toggle', async ({+ page,+ workerServer,+ }) => {+ // A real package.json basename would be governing-adjacent noise for other+ // files on the shared worker; use a package.json copy under a distinct name+ // that still classifies as a plain .json asset (mediaKind 'text') and is+ // NOT a markdownlint config basename.+ const assetPath = 'lint-cfg-package.json';+ writeFileSync(+ join(workerServer.contentDir, assetPath),+ '{\n "name": "not-a-lint-config",\n "version": "1.0.0"\n}\n',+ 'utf-8',+ );++ await page.goto(assetHash(assetPath));++ // The plain AssetPreview text viewer renders the file...+ const preview = page.locator('[data-text-viewer][data-text-viewer-state="loaded"]');+ await expect(preview).toBeVisible({ timeout: 15_000 });+ await expect(preview.locator('.cm-content')).toContainText('not-a-lint-config', {+ timeout: 15_000,+ });++ // ...WITHOUT the LintConfigEditor wrapper or its Source/Rules toggle. The+ // feature is scoped strictly to markdownlint config basenames, so ordinary+ // JSON is untouched.+ await expect(configEditor(page)).toHaveCount(0);+ await expect(page.getByRole('radio', { name: 'Rules', exact: true })).toHaveCount(0);+ });+ // When no native config governs, configFile is null and Rules is disabled+ // while Source still works. Distinct cause from the nested-config case: here+ // NOTHING governs, so the server GET /api/lint/config reports configFile: null+ // (root-level discovery finds no native file), disabling Rules because no+ // governing file equals the opened path — not by a path mismatch.+ test('when no native config governs (configFile null), Rules is disabled and Source works', async ({+ page,+ workerServer,+ }) => {+ // Only a nested config exists; there is NO root `.markdownlint.*`, so+ // root-level discovery (the no-`?doc` GET the editor issues) returns null.+ mkdirSync(join(workerServer.contentDir, 'docs'), { recursive: true });+ const nestedPath = 'docs/.markdownlint.json';+ writeFileSync(join(workerServer.contentDir, nestedPath), '{\n "MD041": false\n}\n', 'utf-8');++ await page.goto(assetHash(nestedPath));+ await expect(configEditor(page)).toBeVisible({ timeout: 15_000 });++ // Source renders the file bytes...+ await expect(loadedSource(page)).toBeVisible({ timeout: 15_000 });++ // ...and Rules stays disabled (configFile null branch).+ const rules = rulesSegment(page);+ await expect(rules).toBeDisabled({ timeout: 15_000 });++ // Deterministically confirm the branch cause (server reports configFile+ // null), then that Rules stays disabled once that resolved.+ const cfg = await page.request.get('/api/lint/config');+ expect(cfg.status()).toBe(200);+ expect((await cfg.json()).configFile).toBeNull();+ await expect(rules).toBeDisabled();+ });+});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 27901cf42..596973fe2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -448,6 +448,7 @@ export {findRuleConfigEntry,fixDocument,fixMarkdownText,+ isMarkdownlintJsonConfig,LINT_PLUGINS,type LintAuditResponse,LintAuditResponseSchema,diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsnew file mode 100644index 000000000..312c9c74b--- /dev/null+++ b/packages/core/src/markdown/lint/config-files.ts@@ -0,0 +1,8 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([+ '.markdownlint.json',+ '.markdownlint.jsonc',+]);++export function isMarkdownlintJsonConfig(basename: string): boolean {+ return MARKDOWNLINT_JSON_CONFIG_FILES.has(basename);+}diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex d1a5ab4dc..8a154ce30 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -29,6 +29,7 @@ export function fixDocument(text: string, config: LinterConfig): string {return out;}+export { isMarkdownlintJsonConfig } from './config-files.ts';export {type LintAuditResponse,LintAuditResponseSchema,diff --git a/packages/server/src/lint/markdownlint-write.test.ts b/packages/server/src/lint/markdownlint-write.test.tsindex b5849decf..57bd20bbb 100644--- a/packages/server/src/lint/markdownlint-write.test.ts+++ b/packages/server/src/lint/markdownlint-write.test.ts@@ -5,7 +5,6 @@* prune-to-empty file deletion. Round-trips are asserted via the discovery read.*/-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import {chmodSync,existsSync,@@ -18,6 +17,7 @@ import {import { tmpdir } from 'node:os';import { join } from 'node:path';import { DEFAULT_MARKDOWNLINT_CONFIG } from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { parse as parseYaml } from 'yaml';import { discoverMarkdownlintConfig, readOwnNativeRules } from './markdownlint-discovery.ts';import { writeMarkdownlintRule } from './markdownlint-write.ts';@@ -122,7 +122,7 @@ describe('writeMarkdownlintRule', () => {// Root reads any file regardless of mode, so the permission probe only// proves the abort when the process isn't privileged.- test.if(process.getuid?.() !== 0)(+ test.runIf(process.getuid?.() !== 0)('a transient read failure ABORTS the write — the hand-tuned file is untouched',() => {const original = JSON.stringify({ MD013: false, MD041: { level: 2 } });@@ -246,6 +246,42 @@ describe('JSONC comment preservation', () => {});});+describe('JSONC format-preserving round-trip', () => {+ // Every construct a naive re-serialization to strict JSON would destroy, in+ // one hand-authored file: a leading comment, an `extends` reference, a+ // trailing comma on the last entry, and a rule disabled with `false`.+ const HAND_AUTHORED = [+ '// hand-tuned markdownlint rules',+ '{',+ ' "extends": "./shared.markdownlint.json",',+ ' "MD007": { "indent": 4 },',+ ' "MD013": false,',+ '}',+ '',+ ].join('\n');++ test('writing one rule keeps the comment, extends, trailing comma, and default:false intact', () => {+ writeFileSync(join(dir, '.markdownlint.jsonc'), HAND_AUTHORED, 'utf-8');++ const res = writeMarkdownlintRule(dir, 'MD007', { indent: 2 });+ expect(res).toEqual({ action: 'written', file: '.markdownlint.jsonc' });++ const raw = readFileSync(join(dir, '.markdownlint.jsonc'), 'utf-8');+ expect(raw).toContain('// hand-tuned markdownlint rules');+ expect(raw).toContain('"extends": "./shared.markdownlint.json"');+ expect(raw).toContain('"MD013": false');+ // A comma still sits before the closing brace — the trailing comma survived.+ expect(raw).toMatch(/,\s*}\s*$/);++ // The edit landed on its own keys without materializing the extends base.+ expect(readOwnNativeRules(dir)?.rules).toEqual({+ extends: './shared.markdownlint.json',+ MD007: { indent: 2 },+ MD013: false,+ });+ });+});+describe('alias-keyed configs', () => {test('setting a rule writes through the existing alias key — no dual MD### key', () => {writeFileSync(diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.tsindex 21df0b9ce..be021a6c5 100644--- a/packages/server/src/timeline-query.test.ts+++ b/packages/server/src/timeline-query.test.ts@@ -1,4 +1,3 @@-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';@@ -6,6 +5,7 @@ import { tmpdir } from 'node:os';import { resolve } from 'node:path';import { formatOkActor, type OkActorEntry } from '@inkeep/open-knowledge-core/shadow-repo-layout';import simpleGit from 'simple-git';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import {appendRenameLogEntry,createEmptyIndex,@@ -635,6 +635,44 @@ describe('getDocumentHistory — rename-history mitigation (US-004)', () => {expect(shas).toContain(bWipSha); // post-rename});+ test('byte-preserving rename a → b: the rename commit survives the no-op row filter', async () => {+ // A managed rename changes the doc's PATH, not its bytes — so the rename+ // commit's blob for `b.md` is byte-identical to the pre-rename `a.md` blob.+ // The byte-identical no-op filter must treat the rename commit as a+ // name-epoch landmark (like a checkpoint) and keep it; otherwise the+ // timeline silently loses the rename event and no longer spans the rename.+ // The sibling 'rename a → b' test above changes the bytes at rename time+ // (`# A v1` → `# B v1`), so it never exercises this byte-identical path —+ // exactly the gap that let the no-op filter regress the rename invariant.+ const { contentDir, shadow } = await setup();+ const { cw, sv } = datedCommits(shadow);++ // Cycle 1: write `a.md`, save → checkpoint (so its tree has a.md).+ writeFileSync(resolve(contentDir, 'a.md'), '# A v1\n');+ const aWipSha = await cw('WIP: a v1');+ await sv();++ // Cycle 2: byte-preserving rename a → b — SAME bytes at the new path.+ rmSync(resolve(contentDir, 'a.md'));+ writeFileSync(resolve(contentDir, 'b.md'), '# A v1\n');+ const renameSha = await cw('rename: a -> b');+ await sv();++ // Cycle 3: a real edit at b so the post-rename row differs and survives.+ writeFileSync(resolve(contentDir, 'b.md'), '# A v2\n');+ const bWipSha = await cw('WIP: b v2');++ const index = createEmptyIndex();+ appendRenameLogEntry(shadow.gitDir, entry({ from: 'a', to: 'b', commitSha: renameSha }), index);+ setRenameLogIndex(shadow.gitDir, index);++ const result = await getDocumentHistory(shadow, { docName: 'b' }, 'content/docs');+ const shas = result.entries.map((e) => e.sha);+ expect(shas).toContain(aWipSha); // pre-rename content+ expect(shas).toContain(renameSha); // rename event — byte-identical, but a landmark+ expect(shas).toContain(bWipSha); // post-rename edit+ });+test('FR2: un-renamed doc → empty rename log → identical results to pre-spec behavior', async () => {const { contentDir, shadow } = await setup();diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.tsindex 1af042530..d755cb6ae 100644--- a/packages/server/src/timeline-query.ts+++ b/packages/server/src/timeline-query.ts@@ -322,13 +322,16 @@ async function filterEntriesByChain<E extends { sha: string }>(* each entry the doc blob OID is resolved by probing every chain step whose* cycle bound the entry's SHA satisfies (reusing `predecessorAncestors`) and* taking the first that resolves — the same path-resolution shape as- * `filterEntriesByChain`. Walking oldest→newest, a non-checkpoint entry is- * dropped when its OID equals the nearest older non-checkpoint entry's OID.- * Checkpoints are landmarks: never dropped, and skipped as the byte baseline- * (mirroring the `parentSha` walk). The oldest of a run of identical versions is- * kept — it is the commit that introduced that content — and a later revert back- * to earlier content is a real change (different from its immediate predecessor)- * so it survives.+ * `filterEntriesByChain`. Walking oldest→newest, a non-landmark entry is+ * dropped when its OID equals the nearest older non-landmark entry's OID.+ * Landmarks — checkpoints AND managed-rename commits — are never dropped and+ * are skipped as the byte baseline (mirroring the `parentSha` walk). A managed+ * rename changes the doc's PATH, not its bytes, so a rename commit's blob is+ * byte-identical to the pre-rename version; it must survive as a name-epoch+ * marker so the timeline still spans the rename (the rename-history invariant).+ * The oldest of a run of identical versions is kept — it is the commit that+ * introduced that content — and a later revert back to earlier content is a+ * real change (different from its immediate predecessor) so it survives.** One exception overrides "keep the oldest": within a run of identical bytes an* authored row always beats an `upstream` import row. The import is a mechanical@@ -350,12 +353,22 @@ async function dropByteIdenticalRows(): Promise<ParsedEntry[]> {if (entries.length < 2 || chain.length === 0) return entries;+ // Landmarks are never dropped and never serve as a byte baseline: checkpoints+ // (restore-point landmarks) and managed-rename commits (name-epoch markers).+ // A rename commit's blob for the doc is byte-identical to the pre-rename+ // version — it only moved the path — so without this exemption the no-op+ // filter would drop it and the timeline would no longer span the rename.+ const renameCommitShas = new Set(+ chain.map((step) => step.renameCommit).filter((sha): sha is string => sha !== null),+ );+ const isLandmark = (entry: ParsedEntry): boolean =>+ entry.type === 'checkpoint' || renameCommitShas.has(entry.sha);+type Probe = { entryIdx: number; sha: string; path: string };const probes: Probe[] = [];for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {- // Checkpoints are never dropped and never serve as a baseline — skip them- // entirely so we don't spend probes resolving their blobs.- if (entries[entryIdx].type === 'checkpoint') continue;+ // Skip landmarks entirely so we don't spend probes resolving their blobs.+ if (isLandmark(entries[entryIdx])) continue;for (let chainIdx = 0; chainIdx < chain.length; chainIdx++) {const ancestors = predecessorAncestors[chainIdx];if (ancestors !== null && !ancestors.has(entries[entryIdx].sha)) continue;@@ -381,7 +394,7 @@ async function dropByteIdenticalRows(let baselineOid: string | null = null;let baselineIdx = -1;for (let i = entries.length - 1; i >= 0; i--) {- if (entries[i].type === 'checkpoint') continue;+ if (isLandmark(entries[i])) continue;const oid = oidByEntry[i];if (oid === null) continue; // unresolved: keep, and don't move the baselineif (baselineOid !== null && oid === baselineOid) {