Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): encode doc and folder hashes so # names resolve (PRD-8437) (#3968)
Andrew Mikofalvy22c374c81871
diff --git a/.changeset/prd-8437-doc-hash-route-encoding.md b/.changeset/prd-8437-doc-hash-route-encoding.mdnew file mode 100644index 000000000..bef9fcf34--- /dev/null+++ b/.changeset/prd-8437-doc-hash-route-encoding.md@@ -0,0 +1,8 @@+---+'@inkeep/open-knowledge': patch+---++Documents and folders whose name contains `#`, `?` or `%` are addressable again.+Opening one used to mint a New Tab, drop the tab on restart, and leave the+sidebar without a selection, because the route hash was built with the name+unescaped and the first `#` was then read as a section anchor.diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 787dbabab..7c645346f 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -340,6 +340,20 @@ The rule does NOT catch:Plugin: [`biome-plugins/no-physical-direction-utility.grit`](no-physical-direction-utility.grit). Fixture: [`biome-plugins/__fixtures__/no-physical-direction-utility.fixture.tsx`](__fixtures__/no-physical-direction-utility.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts`](../packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+### `no-raw-route-hash-construction.grit`++Sole route-hash builder. [`packages/app/src/lib/doc-hash.ts`](../packages/app/src/lib/doc-hash.ts) owns the `#/` route prefix. Every other file in the app asks it for a hash — `hashFromDocName`, `hashFromFolderPath`, `hashFromAssetPath` or `encodeShareTargetForHash` — rather than joining a name onto the prefix itself.++**Why.** A doc or folder name reaches the router through `window.location.hash`, and the WHATWG fragment percent-encode set does not include `#`, `?` or `%`. A hash built by hand therefore hands those characters to `docNameFromHash` as routing syntax: it reads the text before the first one, so a leading `#` yields null and the app opens a New Tab instead of the document, while a `#` mid-name resolves silently to a truncation. The rule is structural rather than a set of fixes because the prefix is trivially easy to spell, so hand-built copies accumulate faster than they are found, and each one fails silently: the link is still built, it just points somewhere else.++**Scoped via `overrides[].plugins`** to `packages/app/src/**/*.{ts,tsx}`, with `!packages/app/src/lib/doc-hash.ts` (the sanctioned builder) and `!**/*.test.{ts,tsx}` (tests write expected hashes as literals) excluded. `packages/server` builds preview URLs through its own `encodeDocName` and is out of scope.++Reading a hash is untouched: `hash.startsWith('#/')`, `hash === '#/'` and the bare `'#/'` content-root sentinel are comparisons, not constructions, and the fixture pins that they stay legal.++The rule matches a node's own source text, so a comment, JSX text or a regex literal spelling the shape cannot trigger it — the fixture pins all three. The rule does NOT catch: the prefix behind a named constant (`const P = '#/'; P + name`), which needs dataflow and has no occurrence today; `name + '#/'`, the prefix on the right of a concatenation, which does not build a route hash; a helper that takes the prefix as a parameter; and the read side, where [`editor/internal-link-helpers.ts`](../packages/app/src/editor/internal-link-helpers.ts) still carries a hand-rolled parser — a different rule.++Plugin: [`biome-plugins/no-raw-route-hash-construction.grit`](no-raw-route-hash-construction.grit). Fixture: [`biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx`](__fixtures__/no-raw-route-hash-construction.fixture.tsx). Test: [`packages/app/src/lint-plugins/no-raw-route-hash-construction.test.ts`](../packages/app/src/lint-plugins/no-raw-route-hash-construction.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+### `no-demoted-dialog-confirm.grit`Dialog-footer emphasis hierarchy. A confirmation dialog's footer holds two actions, and the confirm has to outrank the dismiss. `secondary` is the one Button variant that draws no border and whose fill is imperceptible: `bg-secondary` sits within roughly 1.1:1 of the dialog surface in both light and dark, so the button reads as flat text rather than an action. Every other variant either fills with a contrasting color or draws a border, so `secondary` is the only one that can lose that contest with the `outline` Cancel standing beside it. A footer authored that way inverts the hierarchy: the escape action reads as the primary one, and the actual primary CTA reads as de-emphasized text. The rule flags a `DialogFooter` or `AlertDialogFooter` containing `variant="secondary"` and asks for `default` (or `destructive`, when the action is irreversible removal).diff --git a/biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx b/biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsxnew file mode 100644index 000000000..b2c2a6fb7--- /dev/null+++ b/biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx@@ -0,0 +1,52 @@+/**+ * Fixture for `no-raw-route-hash-construction`.+ *+ * 5 positives, then the negatives the rule must leave alone. The negatives+ * carry the weight here: the guard this replaced was a hand-rolled lexer that+ * went blind after a regex literal, so a comment and a string spelling the+ * offending shape are pinned explicitly.+ *+ * Comment spelling the shape, which must NOT fire: `#/${docName}`+ */+declare const docName: string;+declare const folderPath: string;+declare const BASE: string;+declare const hash: string;++// POSITIVE 1 — interpolation directly onto the prefix.+export const p1 = `#/${docName}`;++// POSITIVE 2 — single-quoted concatenation.+export const p2 = '#/' + docName;++// POSITIVE 3 — double-quoted concatenation.+export const p3 = "#/" + folderPath;++// POSITIVE 4 — the prefix reached later in a template.+export const p4 = `${BASE}#/${docName}`;++// POSITIVE 5 — inside a JSX attribute, after a regex literal and a JSX+// apostrophe, both of which desynchronised the lexer this replaced.+const escaped = folderPath.replace(/"/g, '"');+export function Row(): JSX.Element {+ return (+ <a href={`#/${docName}`} title={escaped}>+ Open an agent's page+ </a>+ );+}++// NEGATIVE — reading a hash is a comparison, not a construction.+export const n1 = hash.startsWith('#/');+export const n2 = hash === '#/';++// NEGATIVE — the bare prefix, the content-root sentinel every folder builder+// returns for the root.+export const n3 = '#/';+export const n4 = `#/`;++// NEGATIVE — a string that merely contains the prefix, not joined to a name.+export const n5 = 'navigate to #/ for the root';++// NEGATIVE — a different prefix that happens to end in a slash.+export const n6 = `#!/${docName}`;diff --git a/biome-plugins/no-raw-route-hash-construction.grit b/biome-plugins/no-raw-route-hash-construction.gritnew file mode 100644index 000000000..6080f74f0--- /dev/null+++ b/biome-plugins/no-raw-route-hash-construction.grit@@ -0,0 +1,55 @@+// no-raw-route-hash-construction — `lib/doc-hash.ts` is the sole route-hash builder.+//+// A doc or folder name reaches the router through `window.location.hash`, and+// the browser does not escape `#`, `?` or `%` in a fragment. A hash built by+// joining a name onto the `#/` prefix therefore hands those characters to the+// parser as routing syntax: `docNameFromHash` reads the text before the first+// one, so a leading `#` yields null and the app opens a New Tab instead of the+// document, and a `#` mid-name silently resolves to a truncation.+//+// The reason this is a rule and not a set of fixes is that the prefix is+// trivially easy to spell, so hand-built copies accumulate faster than they+// are found — and the failure is silent, because the link is still built, it+// just points somewhere else. So the rule is structural: ask `hashFromDocName`,+// `hashFromFolderPath`, `hashFromAssetPath` or `encodeShareTargetForHash` for a+// hash, and get one that is escaped.+//+// Reading a hash is untouched. `hash.startsWith('#/')`, `hash === '#/'` and the+// bare `'#/'` content-root sentinel are comparisons, not constructions, and the+// fixture pins that they stay legal.+//+// The two shapes, matched against a node's own source text so comments, JSX+// text and regex literals are excluded by construction rather than by hand:+//+// 1. A template literal containing `#/${…}` — the prefix joined to an+// interpolation, wherever in the template it appears.+// 2. A string literal `'#/'` immediately concatenated with `+`.+//+// Does NOT catch (documented honestly):+// - The prefix behind a named constant (`const P = '#/'; P + name`). That+// needs dataflow, which is outside a syntactic rule. No occurrence today.+// - `name + '#/'` — the prefix on the RIGHT of the concatenation, which does+// not produce a route hash.+// - A hash assembled by a helper that itself takes the prefix as a parameter.+// - The read side: `getCurrentDocNameFromHash` in `editor/internal-link-helpers.ts`+// is a second hand-rolled PARSER. Different rule, not this one.+//+// Scope: `packages/app/src/**` only, minus `lib/doc-hash.ts`, which is the+// sanctioned builder. `packages/server` builds preview URLs through its own+// `encodeDocName` and is out of scope.+//+// Suppress a legitimate exception with:+// // biome-ignore lint/plugin/no-raw-route-hash-construction: <reason>++language js++$e where {+ or {+ $e <: r"`[^`]*#/\$\{[^`]*`",+ $e <: r"['\"`]#/['\"`]\s*\+.*"+ },+ register_diagnostic(+ span = $e,+ message = "Raw route-hash construction: this joins a name onto the `#/` prefix by hand, so a name containing `#`, `?` or `%` reaches the router unescaped and resolves to the wrong target (or to none, which opens a New Tab). Call `hashFromDocName`, `hashFromFolderPath`, `hashFromAssetPath` or `encodeShareTargetForHash` from `@/lib/doc-hash` instead — they percent-encode per segment so `/` stays a route separator. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-route-hash-constructiongrit"+ )+}diff --git a/biome.jsonc b/biome.jsoncindex 05bf0355e..fe9197271 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -56,6 +56,25 @@}},"overrides": [+ {+ // Sole route-hash builder. `lib/doc-hash.ts` owns the `#/` prefix; every+ // other file in the app asks it for a hash. Building one by hand emits+ // the doc name unescaped, and the browser leaves `#`, `?` and `%` alone+ // in a fragment, so the parser reads them as routing syntax and the+ // navigation lands somewhere else. Excluded: `lib/doc-hash.ts` itself+ // (the sanctioned site) and tests, which build expected hashes as+ // literals. `packages/server` has its own `encodeDocName` for preview+ // URLs and is out of scope.+ "includes": [+ "packages/app/src/**/*.ts",+ "packages/app/src/**/*.tsx",+ "!packages/app/src/lib/doc-hash.ts",+ "!**/*.test.ts",+ "!**/*.test.tsx",+ "biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx"+ ],+ "plugins": ["./biome-plugins/no-raw-route-hash-construction.grit"]+ },{// Observer A origin discipline. Scoped to the one file that owns the// observer-cross-CRDT transact spine. Inside this file everydiff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsxindex 4db9419fd..d5b837dca 100644--- a/packages/app/src/App.dom.test.tsx+++ b/packages/app/src/App.dom.test.tsx@@ -1,7 +1,7 @@import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';-import { pushHashWithoutNavigation } from '@/lib/doc-hash';+import { hashFromDocName, pushHashWithoutNavigation } from '@/lib/doc-hash';import { matchesKeyboardShortcut, type ShortcutEventLike } from '@/lib/keyboard-shortcuts';import {__resetLocalMenuActionBusForTests,@@ -539,6 +539,35 @@ describe('App runtime wiring', () => {});});+ test('a document whose name contains a "#" opens instead of clearing the target', async () => {+ const target: NavigationTarget = {+ kind: 'doc',+ target: '# 2 - Tokens',+ docName: '# 2 - Tokens',+ };+ resolveNavigationTargetMock = vi.fn(() => target);+ // Built, then round-tripped through the same URL normalization the browser+ // applies on assignment. `#` is not in the fragment percent-encode set, so+ // an unescaped one survives into `location.hash` and reads as the start of+ // the anchor: the document resolves to nothing and the app clears the+ // target, which opens a New Tab over the document the user asked for.+ setHash(hashFromDocName('# 2 - Tokens'));++ renderApp();++ await waitFor(() => {+ // Assert the docName the hash PARSED to, not just that something opened:+ // the resolver mock answers unconditionally, so without this a fix that+ // resolved the user to a different document would still pass.+ expect(resolveNavigationTargetMock).toHaveBeenCalledWith('# 2 - Tokens', expect.anything());+ expect(openTargetTransitionMock).toHaveBeenCalledWith(target, {+ disposition: 'permanent',+ consumeActiveNewTab: true,+ });+ });+ expect(clearTargetMock).not.toHaveBeenCalled();+ });+test('hash navigation keeps an open extension-qualified markdown tab exact', async () => {openTabs = ['docs/guide.mdx'];resolveNavigationTargetMock = vi.fn(() => ({diff --git a/packages/app/src/comments/reveal-comment.dom.test.ts b/packages/app/src/comments/reveal-comment.dom.test.tsindex 33da7b642..3a524105b 100644--- a/packages/app/src/comments/reveal-comment.dom.test.ts+++ b/packages/app/src/comments/reveal-comment.dom.test.ts@@ -48,9 +48,9 @@ const captured = {vi.doMock('@/components/doc-panel-events', () => ({ requestDocPanelTab: () => {} }));-vi.doMock('@/lib/doc-hash', () => ({- hashFromDocName: (docName: string) => `#/${docName}`,-}));+// doc-hash is deliberately NOT stubbed: nothing here needs it isolated, only+// present. A stub would be a second copy of the route-hash contract, and this+// file asserts nothing about the hash./** False models a scroller owned by a landing that does not yield. */let scrollAllowed = true;diff --git a/packages/app/src/components/ActivityModeContent.tsx b/packages/app/src/components/ActivityModeContent.tsxindex d15924eb7..c4e4ede9f 100644--- a/packages/app/src/components/ActivityModeContent.tsx+++ b/packages/app/src/components/ActivityModeContent.tsx@@ -31,6 +31,7 @@ import { usePageList } from '@/components/PageListContext';import { Spinner } from '@/components/ui/spinner';import { useDocumentContext, useDocumentTransition } from '@/editor/DocumentContext';import { openAgentDiff, setAgentDiffMax } from '@/lib/agent-diff-store';+import { hashFromDocName } from '@/lib/doc-hash';import { closeTimelineDiff } from '@/lib/timeline-diff-store';import type { FileData } from '@/lib/use-activity-panel';import { useActivityPanel } from '@/lib/use-activity-panel';@@ -67,16 +68,9 @@ async function postAgentUndo(body: {}// ----------------------------------------------------------------// `window.location.hash` helper — mirrors PresenceBar's navigateToDoc.+// `window.location.hash` helper// ----------------------------------------------------------------function hashFromDocName(docName: string): string {- return `#/${docName- .split('/')- .map((part) => encodeURIComponent(part))- .join('/')}`;-}-function navigateToDoc(docName: string): void {if (typeof window === 'undefined') return;window.location.hash = hashFromDocName(docName);diff --git a/packages/app/src/components/PropertyInlineLinks.tsx b/packages/app/src/components/PropertyInlineLinks.tsxindex a58d55f3a..73f743bf2 100644--- a/packages/app/src/components/PropertyInlineLinks.tsx+++ b/packages/app/src/components/PropertyInlineLinks.tsx@@ -26,6 +26,7 @@import type { ReactNode } from 'react';import { UserText } from '@/components/UserText';+import { hashFromDocName } from '@/lib/doc-hash';import { dispatchExternalLinkClick } from '@/lib/external-link';import { cn } from '@/lib/utils';import {@@ -34,20 +35,6 @@ import {tokenizePropertyInlineLinks,} from './property-inline-link-tokens';-/**- * Hash route a wikilink target points to. Matches the `navigateToDoc`- * helpers in `ActivityModeContent.tsx`, `CommandPalette.tsx`, etc. —- * one source of truth would be nice.- */-function hashFromTarget(target: string, anchor: string | null): string {- const docHash = target- .split('/')- .map((part) => encodeURIComponent(part))- .join('/');- const anchorSuffix = anchor ? `#${encodeURIComponent(anchor)}` : '';- return `#/${docHash}${anchorSuffix}`;-}-interface PropertyInlineLinksProps {text: string;/** Optional className passed through to the outer element. */@@ -92,7 +79,7 @@ function renderSegment(seg: PropertyInlineSegment, index: number): ReactNode {return (<akey={key}- href={hashFromTarget(seg.target, seg.anchor)}+ href={hashFromDocName(seg.target, seg.anchor)}data-testid="property-inline-wikilink"data-target={seg.target}title={seg.target}diff --git a/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsxindex 4c210be18..13ca4aecb 100644--- a/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx+++ b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx@@ -117,7 +117,7 @@ const workspace: Workspace = {contentDir: '/Users/abraham/repo/public/open-knowledge',pathSeparator: '/',};-const pages = new Set(['reports/foo/REPORT', 'notes/haiku']);+const pages = new Set(['reports/foo/REPORT', 'notes/haiku', 'notes/@team']);function renderWithResolver(text: string) {const resolver = buildDocPathResolver({ workspace, pages });@@ -155,6 +155,37 @@ describe('AgentMarkdown doc-path links', () => {expect(link?.querySelector('code')?.textContent).toBe('notes/haiku.md');});+ test('a resolved path whose name needs escaping keeps the tooltip readable', () => {+ // `DOC_PATH_REGEX` admits `@`, and `encodeURIComponent` escapes it to+ // `%40`, so the resolver's own output is enough to reach the escaped case+ // — the one shape in this suite where the href and the name differ.+ const { container } = renderWithResolver('see `notes/@team.md` for the roster');+ const link = container.querySelector('a[data-testid="agent-thread-doc-link"]');+ expect(link).not.toBeNull();+ expect(link?.getAttribute('href')).toBe('#/notes/%40team');+ expect(link?.getAttribute('title')).toBe('Open notes/@team');+ });++ test('the tooltip decodes the escapes in a hash the agent wrote itself', () => {+ // The other way in: any `#/` link in agent markdown reaches this anchor,+ // and a space is the common case the resolver cannot produce, since+ // `DOC_PATH_REGEX` does not match one. A reader that does not decode shows+ // the user `Open My%20Notes` instead of the name they know.+ const { container } = renderWithResolver('[My Notes](#/My%20Notes)');+ const link = container.querySelector('a[data-testid="agent-thread-doc-link"]');+ expect(link).not.toBeNull();+ expect(link?.getAttribute('href')).toBe('#/My%20Notes');+ expect(link?.getAttribute('title')).toBe('Open My Notes');+ });++ test('a hash the reader cannot parse leaves the tooltip showing the raw href', () => {+ // The `?? href` fallback. `#/` alone has no doc name to decode, and the+ // tooltip has to say something.+ const { container } = renderWithResolver('[home](#/)');+ const link = container.querySelector('a[data-testid="agent-thread-doc-link"]');+ expect(link?.getAttribute('title')).toBe('Open #/');+ });+test('an unresolvable path stays plain text — no link, no create-on-open trap', () => {const { container } = renderWithResolver('wrote reports/DOES-NOT-EXIST.md just now');expect(container.querySelector('a[data-testid="agent-thread-doc-link"]')).toBeNull();diff --git a/packages/app/src/components/acp/AgentMarkdown.tsx b/packages/app/src/components/acp/AgentMarkdown.tsxindex 76e81d692..0e5791579 100644--- a/packages/app/src/components/acp/AgentMarkdown.tsx+++ b/packages/app/src/components/acp/AgentMarkdown.tsx@@ -13,6 +13,7 @@ import { ErrorBoundary } from 'react-error-boundary';import { type Components, defaultRemarkPlugins, Streamdown } from 'streamdown';import { codeHighlighter } from '@/lib/acp/code-highlighter';import { remarkHardBreaks } from '@/lib/acp/remark-hard-breaks';+import { docNameFromHash } from '@/lib/doc-hash';import { remarkDocPathLinks } from './doc-path-links';import { DocPathResolverReadyContext } from './doc-path-links-context';@@ -31,7 +32,12 @@ function AgentAnchor(props: { href?: string; children?: ReactNode }): ReactNodeconst { t } = useLingui();const { href, children } = props;if (href?.startsWith('#/')) {- const docName = decodeDocNameFromHash(href);+ // Parse with the canonical reader rather than a local slice. The href is+ // percent-encoded by the time it lands here either way: `hashFromDocName`+ // escapes what it builds, and the markdown renderer's URL sanitizer+ // escapes whatever a hand-written link left unescaped. A reader that+ // slices without decoding therefore shows the escapes to the user.+ const docName = docNameFromHash(href) ?? href;return (<ahref={href}@@ -56,15 +62,6 @@ function AgentAnchor(props: { href?: string; children?: ReactNode }): ReactNode);}-/** `#/<docName>[#anchor]` → `<docName>`. Mirrors `docNameFromHash`'s shape- * without pulling in its stricter validation — the href we're reading was- * built by `hashFromDocName` in the same render pass. */-function decodeDocNameFromHash(hash: string): string {- const withoutPrefix = hash.slice(2);- const anchorAt = withoutPrefix.indexOf('#');- return anchorAt === -1 ? withoutPrefix : withoutPrefix.slice(0, anchorAt);-}-export function AgentMarkdown({ text }: { text: string }): ReactNode {// Reads the resolver-ready flag from context so ThreadView can derive// workspace + page list ONCE above the transcript instead of per messagediff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsxindex 0cdc36b5f..aab339271 100644--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx@@ -88,6 +88,21 @@ vi.doMock('../../lib/config-provider', () => ({}),}));+// The create-missing-page boundary. The real implementation writes a file;+// the panel's contract is what it does with the name it gets back, so the mock+// hands one straight to `onCreated`.+let createdDocName = 'created/doc';+vi.doMock('../../lib/create-page', () => ({+ createPageFromSeedAndUpdate: async (+ _seed: unknown,+ options: { addPage: (d: string) => void; onCreated: (d: string) => void },+ ) => {+ options.addPage(createdDocName);+ options.onCreated(createdDocName);+ return { docName: createdDocName };+ },+}));+vi.doMock('../../components/InteractionPropPanel', () => ({InteractionPropPanel: ({ children }: { children: ReactNode }) => (<div data-testid="prop-panel">{children}</div>@@ -96,6 +111,7 @@ vi.doMock('../../components/InteractionPropPanel', () => ({const { InternalLinkPropPanel } = await import('./InternalLinkPropPanel');const { _resetPendingLinkEditForTest, setPendingLinkEdit } = await import('./link-edit-autoopen');+const { docNameFromHash } = await import('@/lib/doc-hash');function makeEditor(options: {@@ -305,7 +321,46 @@ describe('InternalLinkPropPanel', () => {expect(container.querySelector('[data-slot="internal-link-prop-panel-create"]')).toBeNull();expect(container.querySelector('[data-slot="internal-link-prop-panel-text"]')?.getAttribute('href'),- ).toBe('#/targets/Case Sensitive');+ ).toBe('#/targets/Case%20Sensitive');+ });++ test('creating a missing page navigates to the created doc, not past its `#`', () => {+ // The writer this pins is the one the source lint rule cannot see: the rule+ // catches a re-inlined `#/` prefix, not a builder called on the wrong value+ // or an assignment dropped altogether. Assert through the reader rather+ // than on the hash string, so the test states the contract the user cares+ // about — the created page is the one that opens.+ createdDocName = 'targets/# 2 - Tokens';+ currentMarkInfo = {+ id: 'm1',+ markType: 'link',+ attrs: { href: 'targets/# 2 - Tokens' },+ from: 0,+ to: 4,+ };+ pageListHarness.pages = new Set();+ pageListHarness.pagesBySlug = new Map();+ window.location.hash = '#/somewhere-else';++ const { container } = render(+ <TooltipProvider>+ <InternalLinkPropPanel+ editor={makeEditor()}+ nodeId="m1"+ sourceDocName="all-link-types"+ onClose={() => {}}+ onNavigate={() => true}+ />+ </TooltipProvider>,+ );++ const create = container.querySelector('[data-slot="internal-link-prop-panel-create"]');+ expect(create).not.toBeNull();+ fireEvent.click(create as Element);++ return waitFor(() => {+ expect(docNameFromHash(window.location.hash)).toBe('targets/# 2 - Tokens');+ });});test('reference-style links preserve navigation without offering a lossy destination edit', () => {diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsxindex 9201063ae..a15f067ce 100644--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx@@ -52,6 +52,7 @@ import { Input } from '../../components/ui/input';import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';import { useConfigContext } from '../../lib/config-provider';import { type CreatePageSeed, createPageFromSeedAndUpdate } from '../../lib/create-page';+import { hashFromDocName } from '../../lib/doc-hash';import { normalizeDocNameInput } from '../../lib/doc-paths';import { cn } from '../../lib/utils';import {@@ -647,7 +648,7 @@ export function InternalLinkPropPanel({addPage,onCreated(docName) {updateMissingLinkHref(docName);- window.location.hash = `#/${docName}`;+ window.location.hash = hashFromDocName(docName);onClose();},});diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsxindex 63c423a51..6f287cc9c 100644--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx@@ -12,7 +12,7 @@* stubbed verdict. Lingui macros resolve to the English-passthrough shim.*/-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { Editor } from '@tiptap/core';import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';@@ -47,6 +47,21 @@ vi.doMock('../../components/InteractionPropPanel', () => ({),}));+// The create-missing-page boundary. The real implementation writes a file;+// the panel's contract is what it does with the name it gets back, so the mock+// hands one straight to `onCreated`.+let createdDocName = 'created/doc';+vi.doMock('../../lib/create-page', () => ({+ createPageFromSeedAndUpdate: async (+ _seed: unknown,+ options: { addPage: (d: string) => void; onCreated: (d: string) => void },+ ) => {+ options.addPage(createdDocName);+ options.onCreated(createdDocName);+ return { docName: createdDocName };+ },+}));+vi.doMock('../../components/PageListContext', () => ({usePageList: () => ({addPage: () => {},@@ -93,6 +108,8 @@ async function renderPanel(target: string) {);}+const { docNameFromHash } = await import('@/lib/doc-hash');+function card(container: HTMLElement): HTMLElement | null {return container.querySelector('[data-slot="internal-doc-preview-card"]');}@@ -125,3 +142,23 @@ describe('WikiLinkPropPanel — unresolved target keeps create-page, no card', (expect(screen.getByText('Create page')).toBeTruthy();});});++describe('WikiLinkPropPanel — creating the missing page navigates to it', () => {+ test('a created name carrying a `#` opens that doc, not a truncation of it', async () => {+ // The writer here is the one the source lint rule cannot see: the rule+ // catches a re-inlined `#/` prefix, not a builder called on the wrong value+ // or an assignment dropped altogether. Asserted through the reader, so the+ // test states the contract the user cares about.+ createdDocName = 'ghost/# 2 - Tokens';+ window.location.hash = '#/somewhere-else';+ const { container } = await renderPanel('ghost/# 2 - Tokens');++ const create = container.querySelector('[data-slot="wiki-link-prop-panel-create"]');+ expect(create).toBeTruthy();+ fireEvent.click(create as Element);++ await waitFor(() => {+ expect(docNameFromHash(window.location.hash)).toBe('ghost/# 2 - Tokens');+ });+ });+});diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsxindex 7f5d0294f..ce5df137a 100644--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx@@ -53,7 +53,7 @@ import {import { Input } from '../../components/ui/input';import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';import { type CreatePageSeed, createPageFromSeedAndUpdate } from '../../lib/create-page';-import { hashFromAssetPath } from '../../lib/doc-hash';+import { hashFromAssetPath, hashFromDocName } from '../../lib/doc-hash';import { cn } from '../../lib/utils';import { handleChipLinkClick, toInternalHashHref } from '../internal-link-helpers';import {@@ -439,7 +439,7 @@ export function WikiLinkPropPanel({ editor, getPos, onClose, onNavigate }: WikiLaddPage,onCreated(docName) {updateMissingLinkTarget(docName);- window.location.hash = `#/${docName}`;+ window.location.hash = hashFromDocName(docName);onClose();},});diff --git a/packages/app/src/lib/create-page-request.test.ts b/packages/app/src/lib/create-page-request.test.tsindex c10180bf2..21f3eac8c 100644--- a/packages/app/src/lib/create-page-request.test.ts+++ b/packages/app/src/lib/create-page-request.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { createPageRequest, nextUntitledDocName } from './create-page-request';+import { createPageRequest, nextUntitledDocName, openCreatedPage } from './create-page-request';describe('nextUntitledDocName', () => {it('starts at bare "untitled" at the content root', () => {@@ -78,3 +78,40 @@ describe('createPageRequest', () => {expect(result).toEqual({ ok: false, error: 'Network error — please try again' });});});++describe('openCreatedPage', () => {+ const realWindow = (globalThis as { window?: unknown }).window;++ afterEach(() => {+ // This tier has no DOM. Restore rather than delete: leaving a stub behind+ // makes later files in the same worker believe they are in a browser.+ if (realWindow === undefined) delete (globalThis as { window?: unknown }).window;+ else (globalThis as { window?: unknown }).window = realWindow;+ });++ function harness(docName: string): string {+ const stub = {+ location: { hash: '' },+ dispatchEvent: () => true,+ };+ (globalThis as { window?: unknown }).window = stub;+ openCreatedPage(docName, () => {});+ return stub.location.hash;+ }++ it('percent-encodes the created doc name', () => {+ expect(harness('My Notes')).toBe('#/My%20Notes');+ });++ it('encodes a name containing a route metacharacter so the new page opens', () => {+ // Creating is the path the bug was reported through: the name is legal to+ // create, and left raw the "#" reads as the anchor delimiter, so the parser+ // resolves no document and the app opens a New Tab over the new page.+ expect(harness('# 2 - Tokens')).toBe('#/%23%202%20-%20Tokens');+ expect(harness('What now?')).toBe('#/What%20now%3F');+ });++ it('keeps the slash a route separator for a nested name', () => {+ expect(harness('My Notes/# 2 - Tokens')).toBe('#/My%20Notes/%23%202%20-%20Tokens');+ });+});diff --git a/packages/app/src/lib/create-page-request.ts b/packages/app/src/lib/create-page-request.tsindex f44670729..624f7971c 100644--- a/packages/app/src/lib/create-page-request.ts+++ b/packages/app/src/lib/create-page-request.ts@@ -5,6 +5,7 @@ import { CreatePageSuccessSchema } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { emitDocumentsChanged } from '@/lib/documents-events';import { parseServerResponse } from '@/lib/parse-server-response';+import { hashFromDocName } from './doc-hash';/*** `POST /api/create-page` with the canonical response parse.@@ -53,7 +54,7 @@ export async function createPageRequest(args: {* seed it into the page list optimistically, and fan out the change event.*/export function openCreatedPage(docName: string, addPage: (docName: string) => void) {- window.location.hash = `#/${docName}`;+ window.location.hash = hashFromDocName(docName);addPage(docName);emitDocumentsChanged(['files', 'backlinks', 'graph']);}diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.tsindex 231cc517b..5e40039dc 100644--- a/packages/app/src/lib/doc-hash.test.ts+++ b/packages/app/src/lib/doc-hash.test.ts@@ -152,17 +152,183 @@ describe('hashFromFolderPath', () => {});});+/**+ * What `window.location.hash` actually holds once the app assigns a built hash:+ * the WHATWG fragment percent-encode set, applied by a real URL parser rather+ * than by a literal written here.+ *+ * Deliberately NOT a hand-written encoded literal. A literal would bake this+ * file's own belief about which characters the browser escapes into the+ * assertion, so the test would still pass if that belief were wrong — and the+ * encode set is precisely what these round-trips turn on (a space is escaped, a+ * `#`, `?` or `%` is not, so those three reach the parser intact and are re-read+ * as routing syntax). Pushing the built hash through a real `URL` keeps the+ * encode set an input to the test rather than a constant inside it.+ */+function browserNormalizedHash(builtHash: string): string {+ const url = new URL('file:///app/index.html');+ url.hash = builtHash;+ return url.hash;+}++/**+ * The builders are one half of a round trip: the app assigns `hashFromDocName`+ * / `hashFromFolderPath` to `window.location.hash`, the browser normalizes it,+ * and `docNameFromHash` reads the name back out. A name carrying a route+ * metacharacter has to survive that trip unchanged, exactly as a name carrying+ * a space already does.+ *+ * `hashFromAssetPath` is the in-repo reference implementation of this+ * contract: it percent-encodes per segment, so `/` stays a route separator.+ * (`encodeShareTargetForHash` also encodes, but whole-path by design, so a+ * deep link's `/` becomes `%2F` — a different contract, not a model for this+ * one.) These pin the per-segment contract for the two builders every in-app+ * navigation goes through.+ */+describe('doc and folder hashes round-trip through the browser', () => {+ function roundTripDoc(docName: string): string | null {+ return docNameFromHash(browserNormalizedHash(hashFromDocName(docName)));+ }++ function roundTripFolder(folderPath: string): string | null {+ // A folder hash reads back with its trailing slash — that slash is the+ // folder signal `tabIdFromHash` strips to recover the folder path.+ return docNameFromHash(browserNormalizedHash(hashFromFolderPath(folderPath)));+ }++ test('a spaced name round-trips (control — the already-working common path)', () => {+ expect(roundTripDoc('My Notes/Ideas')).toBe('My Notes/Ideas');+ expect(roundTripFolder('My Notes')).toBe('My Notes/');+ });++ test('a doc named with a leading `# ` round-trips', () => {+ // The reported document. A markdown heading pasted in as a title is an+ // ordinary name to the user; `#` only means "anchor" to the router.+ expect(roundTripDoc('# 2 - Tokens')).toBe('# 2 - Tokens');+ });++ test('a doc named with a leading `#` and no space round-trips', () => {+ expect(roundTripDoc('#Heading')).toBe('#Heading');+ });++ test('a doc with a mid-name `#` round-trips', () => {+ expect(roundTripDoc('A # B')).toBe('A # B');+ });++ test('a `#` doc inside a folder resolves to the doc, not to its folder', () => {+ // The dangerous shape: truncating at the `#` yields a still-valid folder+ // hash, so the navigation silently succeeds at the wrong target instead of+ // failing loudly.+ expect(roundTripDoc('My Notes/# 2 - Tokens')).toBe('My Notes/# 2 - Tokens');+ });++ test('the separator survives as a separator, not as an escape', () => {+ // No round trip above can see this. `docNameFromHash` decodes per segment+ // too, so a whole-string `encodeURIComponent` in the builders round-trips+ // every name here perfectly while emitting `#/My%20Notes%2FIdeas` — a hash+ // with no route structure left in it, which the folder arm of+ // `tabIdFromHash` and every href in the app read as one flat name. The+ // built string is the only place the difference shows, so assert on it.+ expect(hashFromDocName('My Notes/Ideas')).toBe('#/My%20Notes/Ideas');+ expect(hashFromFolderPath('My Notes/Ideas')).toBe('#/My%20Notes/Ideas/');+ });++ test('a doc with a `?` round-trips', () => {+ // `?` is the other route delimiter `firstRouteDelimiterIndex` looks for,+ // and the browser leaves it unescaped in a fragment just like `#`.+ expect(roundTripDoc('What now?')).toBe('What now?');+ });++ test('a doc with a `%` round-trips', () => {+ // A raw `%` is not a percent-escape but is read as the start of one. It+ // must reach the parser already escaped (`%25`), so the decode returns the+ // literal `%` rather than throwing and falling back to the raw string.+ expect(roundTripDoc('100% done')).toBe('100% done');+ });++ test('an anchor stays separable from a `#` in the doc name', () => {+ // Both halves have to survive: the name must not swallow the anchor, and+ // the anchor delimiter must remain the FIRST unescaped `#`, which is what+ // both parsers look for. Encoding the name's own `#` is what makes the+ // first unescaped one the anchor's.+ const hash = browserNormalizedHash(hashFromDocName('# 2 - Tokens', 'intro'));+ expect(docNameFromHash(hash)).toBe('# 2 - Tokens');+ expect(anchorFromHash(hash)).toBe('intro');+ });++ test('folder paths carrying route metacharacters round-trip', () => {+ expect(roundTripFolder('# Notes')).toBe('# Notes/');+ expect(roundTripFolder('A # B')).toBe('A # B/');+ expect(roundTripFolder('What now?')).toBe('What now?/');+ expect(roundTripFolder('100% done')).toBe('100% done/');+ });++ test('a name carrying a lone surrogate does not throw', () => {+ // encodeURIComponent throws URIError on an unpaired surrogate, which a+ // docName can carry because it comes from a filename. Raw interpolation+ // never threw, and these builders run inside render paths, so a throw+ // would take out the surrounding tree instead of breaking one link.+ const lone = 'note-\ud800-x';+ expect(() => hashFromDocName(lone)).not.toThrow();+ expect(() => hashFromFolderPath(lone)).not.toThrow();+ expect(() => hashFromDocName(`folder/${lone}`)).not.toThrow();+ // The encodable siblings of an unencodable segment are still encoded.+ expect(hashFromDocName(`My Notes/${lone}`)).toContain('My%20Notes/');+ });++ test('the anchor is sanitized on the same terms as the name', () => {+ // A heading slug is derived from user text, so it reaches the encoder from+ // the same kind of source the name does. Every value this module escapes+ // goes through one helper for that reason; without it the anchor argument+ // was the one bare `encodeURIComponent` left on the headline builders.+ expect(() => hashFromDocName('doc', 'head-\ud800')).not.toThrow();+ expect(() => hashFromFolderPath('folder', 'head-\ud800')).not.toThrow();+ expect(hashFromDocName('doc', 'a b\ud800')).toBe('#/doc#a%20b%EF%BF%BD');+ });++ test('a route metacharacter beside a lone surrogate is still escaped', () => {+ // encodeURIComponent has no partial result: it throws for the whole call.+ // Catching that and passing the segment through would hand the `#` to the+ // router raw, which is the misparse this whole contract exists to stop, so+ // the unpairable code unit is substituted before encoding instead.+ const hash = browserNormalizedHash(hashFromDocName('#Heading\ud800'));+ expect(hash).not.toContain('/#');+ expect(docNameFromHash(hash)).not.toBeNull();+ // Round-trips to the sanitized name, not to the original bad code unit.+ expect(docNameFromHash(hash)).toBe('#Heading\uFFFD');+ });++ test('the same names round-trip through the share-target encoder', () => {+ // `encodeShareTargetForHash` encodes whole-path, not per segment; the names+ // here are slash-free, which is why the two agree. What it pins is that+ // escaping, not the parser, is what carries a route metacharacter across+ // the trip, so a change to the parser has to keep this passing too.+ for (const docName of ['# 2 - Tokens', '#Heading', 'A # B', 'What now?', '100% done']) {+ const hash = browserNormalizedHash(encodeShareTargetForHash('doc', docName));+ expect(docNameFromHash(hash)).toBe(docName);+ }+ });+});+describe('isSameHash', () => {- test('matches a browser-encoded hash against a builder hash for a name with a space', () => {+ // Note on this group: now that the builders percent-encode, a builder hash+ // and the browser's own form of the same target are byte-identical, so these+ // pairs settle on the `===` fast path and no longer exercise the decode. The+ // decode is covered by the legacy-raw-hash case below, which is the only+ // input shape that still needs it. These are kept as the equality cases they+ // have become: they still pin that the builder's output IS the browser form.++ test('matches the browser form of a spaced name, which the builder now emits verbatim', () => {// `window.location.hash` for a folder named `consolidated ux`, versus what- // `hashFromFolderPath` emits. A raw `===` here is what left such a folder- // permanently expanded in the sidebar: the file tree read "not the current- // page", swallowed the click, and never let the tree toggle the row.+ // `hashFromFolderPath` emits. A raw `===` between these was once false,+ // which left such a folder permanently expanded in the sidebar: the file+ // tree read "not the current page", swallowed the click, and never toggled+ // the row. It is true now because the builder encodes.expect(isSameHash('#/consolidated%20ux/', hashFromFolderPath('consolidated ux'))).toBe(true);expect(isSameHash('#/My%20Notes/Ideas', hashFromDocName('My Notes/Ideas'))).toBe(true);});- test('matches non-ASCII names the browser also percent-encodes', () => {+ test('matches non-ASCII names, which the builder encodes the same way', () => {expect(isSameHash('#/notes/caf%C3%A9', hashFromDocName('notes/café'))).toBe(true);});@@ -175,10 +341,34 @@ describe('isSameHash', () => {expect(isSameHash('#/alpha/', hashFromFolderPath('beta'))).toBe(false);});- test('commutes — either side may be the browser-encoded one', () => {+ test('commutes: either side may be the browser-encoded one', () => {expect(isSameHash(hashFromFolderPath('consolidated ux'), '#/consolidated%20ux/')).toBe(true);});+ test('matches a raw hash persisted by an older build against the encoded form', () => {+ // The builders encode now, so every other positive case here settles on the+ // `===` fast path and the decode branch would go untested. This is the case+ // that still needs it: a history entry or bookmark written when the+ // builders emitted the path raw, compared against what they emit today.+ // Without the tolerance, restoring such an entry reads as a different+ // target and re-navigates.+ expect(isSameHash('#/My Notes/Ideas', hashFromDocName('My Notes/Ideas'))).toBe(true);+ expect(isSameHash('#/consolidated ux/', hashFromFolderPath('consolidated ux'))).toBe(true);+ });++ test('still conflates a "#" in a name with the anchor delimiter (known limit)', () => {+ // Pinning a limitation, not an intent. The builders now emit these two+ // targets as DIFFERENT strings, where before they emitted the same one, so+ // this is narrower than it was. It survives because the decode is+ // whole-string: `%23` collapses back to a structural `#`. Separating them+ // means decoding path and anchor independently, which changes the guard+ // for every caller. Change this expectation only alongside that.+ const anchorOnDocA = hashFromDocName('a', 'b');+ const docNamedAHashB = hashFromDocName('a#b');+ expect(anchorOnDocA).not.toBe(docNamedAHashB);+ expect(isSameHash(anchorOnDocA, docNamedAHashB)).toBe(true);+ });+test('falls back to raw comparison on malformed escapes', () => {expect(isSameHash('#/100%zz', '#/100%zz')).toBe(true);expect(isSameHash('#/100%zz', '#/200%zz')).toBe(false);diff --git a/packages/app/src/lib/doc-hash.ts b/packages/app/src/lib/doc-hash.tsindex 2450b8ecf..535959b95 100644--- a/packages/app/src/lib/doc-hash.ts+++ b/packages/app/src/lib/doc-hash.ts@@ -57,29 +57,89 @@ export function anchorFromHash(hash: string): string | null {}}-/** Build a `#/<docName>#<anchor>` hash for the given docName. */+/**+ * A surrogate with no partner. `encodeURIComponent` throws `URIError` on one,+ * and it has no partial result, so one bad code unit would otherwise cost the+ * whole value its escaping.+ */+const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;++/**+ * Percent-encode one hash component: a path segment, an anchor, a branch name.+ *+ * Every value these builders escape ultimately comes from a filename, and a+ * filename can carry an unpaired surrogate. Substituting U+FFFD first keeps+ * the call total, so the rest of the value is still escaped and the builders+ * cannot throw — they run inside render paths, where a `URIError` takes out+ * the surrounding tree rather than breaking one link. The substitution is+ * visible in the URL as `%EF%BF%BD` rather than silently corrupting the route.+ *+ * Mirrors the sanitizer in `packages/server/src/services/search.ts`, including+ * why `String.prototype.toWellFormed` is not used: this subtree targets ES2022.+ */+function encodeSegment(value: string): string {+ return encodeURIComponent(value.replace(LONE_SURROGATE, '\uFFFD'));+}++/**+ * Percent-encode a route path one `/`-separated segment at a time, so the+ * separators survive while everything else is escaped.+ *+ * Encoding matters most for `#`: the browser does not escape it when the hash+ * is assigned, so an unescaped one in a name comes back looking like the start+ * of an anchor.+ */+function encodeRoutePath(path: string): string {+ return path.split('/').map(encodeSegment).join('/');+}++/**+ * Build a `#/<docName>#<anchor>` hash for the given docName.+ *+ * The path is encoded per segment so that `/` stays a real route separator+ * while every other character is escaped, mirroring the per-segment decode in+ * `docNameFromHash`. Encoding matters most for `#`: the browser does not+ * escape it when the hash is assigned, so an unescaped one in a docName would+ * come back looking like the start of the anchor. The parser then reads only+ * the text before it, which is the empty string for a leading `#` and a+ * truncated name for one in the middle.+ */export function hashFromDocName(docName: string, anchor?: string | null): string {- const base = `#/${docName}`;- return anchor ? `${base}#${encodeURIComponent(anchor)}` : base;+ const base = `#/${encodeRoutePath(docName)}`;+ return anchor ? `${base}#${encodeSegment(anchor)}` : base;}/*** `true` when two hashes address the same target, tolerating the* percent-encoding difference between the two ways a hash reaches us.*- * `window.location.hash` comes back percent-encoded (`#/My%20Notes/`) because- * the browser encodes spaces and non-ASCII characters in the URL, while the- * `hashFrom*` builders emit the raw path (`#/My Notes/`). A `===` between the- * two is therefore false for every name carrying a space or non-ASCII- * character, which silently inverts any "are we already here?" guard for- * exactly those documents and folders.+ * The `hashFrom*` builders encode the path, so a freshly built hash and the+ * `window.location.hash` the browser hands back are normally identical and+ * settle on the `===` fast path. The decode earns its place for hashes this+ * app did not build: entries persisted in history or a bookmark by an older+ * build, whose builders emitted the path raw (`#/My Notes/`), and hashes typed+ * or edited by hand in the address bar. Without the tolerance a `===` against+ * those is false for every name carrying a space or non-ASCII character, which+ * silently inverts any "are we already here?" guard for exactly those+ * documents and folders.** Both sides are decoded rather than just the location side, so the arguments* commute — callers pass location first or second depending on the call site.*- * Inherited limitation: because the builders emit the path raw, a name that- * itself contains a percent escape (`100%20`) already shares a hash with its- * decoded form (`100 `). That ambiguity is in the hash format, not here.+ * Two residual ambiguities survive the encoding:+ *+ * A raw name that itself contains a percent escape (`100%20`) shares a hash+ * with its decoded form (`100 `), and the two cannot be told apart after the+ * fact. A hash built here cannot collide that way, because the escape's `%` is+ * itself encoded, so the ambiguity is confined to legacy and hand-written+ * input.+ *+ * The decode is whole-string, so it also collapses an encoded `%23` back to a+ * structural `#`: a document named `a#b` and the anchor `b` on document `a`+ * compare equal, even though their built hashes are distinguishable+ * (`#/a%23b` versus `#/a#b`). Telling those apart means decoding the path and+ * anchor separately rather than the whole string, which changes this guard for+ * every caller and is deliberately not attempted here.*/export function isSameHash(a: string, b: string): boolean {return a === b || decodeHashForComparison(a) === decodeHashForComparison(b);@@ -145,11 +205,17 @@ export function filePathToDocName(filePath: string): string {return filePath;}-/** Build a `#/<folderPath>/#<anchor>` hash for a folder target. */+/**+ * Build a `#/<folderPath>/#<anchor>` hash for a folder target.+ *+ * Encoded per segment for the same reason as `hashFromDocName`. The trailing+ * slash stays outside the encoding so it remains the folder marker the parser+ * looks for, and an empty path still yields the `#/` content-root sentinel.+ */export function hashFromFolderPath(folderPath: string, anchor?: string | null): string {const normalized = folderPath.replace(/^\/+|\/+$/g, '');- const base = normalized ? `#/${normalized}/` : '#/';- return anchor ? `${base}#${encodeURIComponent(anchor)}` : base;+ const base = normalized ? `#/${encodeRoutePath(normalized)}/` : '#/';+ return anchor ? `${base}#${encodeSegment(anchor)}` : base;}/**@@ -174,9 +240,9 @@ export function encodeShareTargetForHash(branch?: string | null,): string {if (kind === 'folder') return hashFromFolderPath(path);- const base = `#/${encodeURIComponent(path)}`;+ const base = `#/${encodeSegment(path)}`;if (branch === undefined || branch === null || branch === '') return base;- return `${base}?branch=${encodeURIComponent(branch)}`;+ return `${base}?branch=${encodeSegment(branch)}`;}/**@@ -221,7 +287,7 @@ export function assetPathFromHash(hash: string): string | null {}export function hashFromAssetPath(assetPath: string): string {- return `${ASSET_HASH_PREFIX}${assetPath.split('/').map(encodeURIComponent).join('/')}`;+ return `${ASSET_HASH_PREFIX}${encodeRoutePath(assetPath)}`;}const SKILL_FILE_HASH_PREFIX = '#/__skill-file__/';@@ -296,7 +362,7 @@ export function encodeSkillPreviewSegments(target: SkillPreviewHashTarget): stritarget.subtitle,target.level ?? DEFAULT_PREVIEW_LEVEL,]- .map(encodeURIComponent)+ .map(encodeSegment).join('/');}@@ -330,7 +396,7 @@ export function hashFromSkillPreview(target: SkillPreviewHashTarget): string {let body = encodeSkillPreviewSegments(target);// The identity is always 5 segments now (level defaulted, never dropped), so// `path` is unambiguously the 6th with no padding.- if (target.path) body += `/${encodeURIComponent(target.path)}`;+ if (target.path) body += `/${encodeSegment(target.path)}`;return `${SKILL_PREVIEW_HASH_PREFIX}${body}`;}@@ -380,8 +446,8 @@ const SKILL_FILE_HOST_SEP = ':';export function hashFromSkillFile(target: SkillFileHashTarget): string {const named =target.host === undefined ? target.name : `${target.name}${SKILL_FILE_HOST_SEP}${target.host}`;- const head = [target.scope, named].map(encodeURIComponent).join('/');- const tail = target.path.split('/').map(encodeURIComponent).join('/');+ const head = [target.scope, named].map(encodeSegment).join('/');+ const tail = encodeRoutePath(target.path);return `${SKILL_FILE_HASH_PREFIX}${head}/${tail}`;}diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.tsindex 682b09ab5..5bdb0b390 100644--- a/packages/app/src/lib/managed-artifact-doc-name.ts+++ b/packages/app/src/lib/managed-artifact-doc-name.ts@@ -3,10 +3,10 @@* (`__skill__/global/<name>`); a PROJECT skill is a content doc at its real path* (`.ok/skills/<name>/SKILL`). These are real CRDT doc names opened as ordinary* editor tabs, so they follow the SAME convention as document doc names: the- * canonical key is the raw/decoded string. `hashFromDocName` builds the `#/…`- * hash without encoding (the browser encodes the URL); `docNameFromHash` decodes- * it back — so a builder that encoded here would round-trip to a different key- * than the tab/provider uses.+ * canonical key is the raw/decoded string. `hashFromDocName` percent-encodes+ * that key per segment on the way into the hash and `docNameFromHash` decodes+ * it back — so build the name here raw. Encoding it a second time here would+ * round-trip to a different key than the tab/provider uses.** Templates are content docs too — build their doc name with* `templateContentDocName` from `@inkeep/open-knowledge-core`, not here.diff --git a/packages/app/src/lib/single-file-initial-doc.test.ts b/packages/app/src/lib/single-file-initial-doc.test.tsindex dcadaba3f..bf4445012 100644--- a/packages/app/src/lib/single-file-initial-doc.test.ts+++ b/packages/app/src/lib/single-file-initial-doc.test.ts@@ -35,10 +35,19 @@ describe('seedInitialDocHash', () => {expect(harness('todo', '#/').hash).toBe('#/todo');});- test('preserves a docName with a space (browser percent-encodes on assignment)', () => {- // `hashFromDocName` writes the raw name; the browser encodes it and- // `docNameFromHash` decodes per-segment, so the round-trip holds.- expect(harness('My Notes', '').hash).toBe('#/My Notes');+ test('percent-encodes a docName with a space', () => {+ // `setHash` here just records; in production it assigns+ // `window.location.hash`. `hashFromDocName` encodes per segment and+ // `docNameFromHash` decodes per segment, so the round-trip holds.+ expect(harness('My Notes', '').hash).toBe('#/My%20Notes');+ });++ test('percent-encodes a docName containing a route metacharacter', () => {+ // An ephemeral window opened on a `#`-named file seeds through this seam.+ // Left raw, the `#` survives assignment (the browser does not escape it)+ // and the parser reads it as the anchor delimiter, so the window opens on+ // no document at all.+ expect(harness('# 2 - Tokens', '').hash).toBe('#/%23%202%20-%20Tokens');});test('no-op when initialDoc is null (every non-ephemeral window)', () => {diff --git a/packages/app/src/lint-plugins/no-raw-route-hash-construction.test.ts b/packages/app/src/lint-plugins/no-raw-route-hash-construction.test.tsnew file mode 100644index 000000000..22aaaa268--- /dev/null+++ b/packages/app/src/lint-plugins/no-raw-route-hash-construction.test.ts@@ -0,0 +1,77 @@+/**+ * Sole route-hash builder — `no-raw-route-hash-construction` GritQL plugin.+ *+ * Plugin: `biome-plugins/no-raw-route-hash-construction.grit`+ * Fixture: `biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx`+ *+ * The fixture pairs 5 positives (a template interpolation onto the prefix, the+ * single- and double-quoted concatenations, the prefix reached later in a+ * template, and one inside a JSX attribute) with negatives: the comparison+ * forms `startsWith('#/')` and `=== '#/'`, the bare content-root sentinel, a+ * string that merely mentions the prefix, and a different prefix ending in a+ * slash. Exact equality on the fire count catches drift both ways — a+ * false-negative regression (< 5) and a false-positive widening (> 5).+ *+ * Two of the negatives are the reason this is a lint plugin rather than a+ * source scan. The positive inside the JSX attribute sits after a regex+ * literal (`.replace(/"/g, …)`) and a JSX apostrophe, and a comment at the top+ * of the fixture spells the offending shape verbatim. A hand-rolled lexer has+ * to model regex literals, JSX text and comments to get those three right;+ * matching a node's own source text gets them right by construction.+ *+ * The plugin is registered via `overrides[].plugins` in `biome.jsonc`, scoped+ * to `packages/app/src/**` minus `lib/doc-hash.ts` — the sanctioned builder —+ * and minus tests, which write expected hashes as literals.+ */++import { spawnSync } from 'node:child_process';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper.ts';++const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'biome-plugins/__fixtures__/no-raw-route-hash-construction.fixture.tsx';+const PLUGIN_REL = './biome-plugins/no-raw-route-hash-construction.grit';++describe('no-raw-route-hash-construction GritQL plugin', () => {+ test('fires exactly 5 times — one per hand-built hash, none on the read forms', () => {+ const result = spawnSync('pnpm', ['exec', 'biome', 'check', FIXTURE_REL], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ windowsHide: true,+ });+ // Guard against a vacuous pass if `pnpm exec biome` itself fails to spawn+ // (missing binary / PATH) — `result.status` would be null and+ // `not.toBe(0)` would pass while asserting nothing about biome's output.+ expect(result.error).toBeUndefined();+ expect(result.status).not.toBe(0);+ const output = `${result.stdout}\n${result.stderr}`;++ const fires = (output.match(/Raw route-hash construction/g) ?? []).length;+ expect(fires).toBe(5);++ // The message names the escape route rather than only the offence.+ expect(output).toContain('hashFromDocName');+ expect(output).toContain('hashFromFolderPath');+ expect(output).toContain('biome-plugins/README.md#no-raw-route-hash-constructiongrit');+ });++ test('plugin is registered in biome.jsonc via overrides, with doc-hash.ts excluded', () => {+ const config = readBiomeConfig(REPO_ROOT);++ expect(config.plugins ?? []).not.toContain(PLUGIN_REL);++ const overrides = config.overrides ?? [];+ const matchingOverride = overrides.find((entry) => (entry.plugins ?? []).includes(PLUGIN_REL));+ expect(matchingOverride).toBeDefined();++ const includes = matchingOverride?.includes ?? [];+ expect(includes).toContain('packages/app/src/**/*.ts');+ expect(includes).toContain('packages/app/src/**/*.tsx');+ // The exclusion is the whole rule: doc-hash.ts is the one sanctioned+ // builder, so scoping that leaks it back in would make the rule unusable+ // and someone would delete it rather than the exclusion.+ expect(includes).toContain('!packages/app/src/lib/doc-hash.ts');+ expect(includes).toContain(FIXTURE_REL);+ });+});diff --git a/packages/app/tests/stress/file-tree-collapse-spaced-folder.e2e.ts b/packages/app/tests/stress/file-tree-collapse-spaced-folder.e2e.tsindex c2308187b..b055618b9 100644--- a/packages/app/tests/stress/file-tree-collapse-spaced-folder.e2e.ts+++ b/packages/app/tests/stress/file-tree-collapse-spaced-folder.e2e.ts@@ -5,9 +5,11 @@* that folder's page, and steps aside — letting @pierre/trees toggle the row —* only when the URL already points at that folder. That check compared* `window.location.hash` (which the browser percent-encodes) against- * `hashFromFolderPath` (which emits the path raw), so for a name with a space- * it was never true: every click was swallowed, and the folder could be- * expanded but never collapsed. A space-free sibling is the control.+ * `hashFromFolderPath`, which then emitted the path raw, so for a name with a+ * space it was never true: every click was swallowed, and the folder could be+ * expanded but never collapsed. The builder percent-encodes now, so the two+ * agree directly; `isSameHash` still bridges hashes persisted by older builds.+ * A space-free sibling is the control.*/import { expect, resetContentToFixtureBaseline, test } from './_helpers';