Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): accept git-legal branch names in /api/history (PRD-8556) (#4333)

miles-kt-inkeep53fad1efc43b
diff --git a/.changeset/history-branch-admission.md b/.changeset/history-branch-admission.md
new file mode 100644
index 000000000..3f710713e
--- /dev/null
+++ b/.changeset/history-branch-admission.md
@@ -0,0 +1,11 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+The Timeline no longer reports "History unavailable", and a folder's timeline card no longer disappears, on branches whose names contain characters git accepts but the history endpoint used to reject.
+
+A branch named `worktree-design+atc-release-package` used to get a 400 from `/api/history`, which the document Timeline rendered as "History unavailable" and a folder's timeline card rendered as nothing at all — the card was simply absent from the folder overview, with no message. `feature-café` and fully non-Latin branch names were rejected the same way. Twenty-one printable-ASCII characters real branch names may contain — `+`, `%`, `#`, `=`, `&`, `!`, `$`, `(`, `)`, `,`, `;`, `'` and others — plus every non-ASCII character and any leading underscore are now served.
+
+Both surfaces also now log the server's problem type and title to the browser console when a history request fails, so a Timeline that will not load says why.
+
+One class is still rejected: the shared rules refuse any whitespace, including non-ASCII whitespace such as a non-breaking space, which git itself does allow. A branch named that way still gets a 400 and a dead Timeline.
diff --git a/docs/src/lib/share-splash.test.ts b/docs/src/lib/share-splash.test.ts
index 16e3fb966..37214c4b0 100644
--- a/docs/src/lib/share-splash.test.ts
+++ b/docs/src/lib/share-splash.test.ts
@@ -1,4 +1,8 @@
-import { encodeShareUrl, KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';
+import {
+ encodeShareUrl,
+ isValidBranchName,
+ KNOWN_NON_GITHUB_GIT_HOSTS,
+} from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import fixture from '../../../test-support/fixtures/share-url-v1-v2.json';
import { STABLE_DMG_URL } from './download-links.ts';
@@ -330,6 +334,26 @@ describe('buildSplashViewModel', () => {
});
});
+describe('buildSplashViewModel — branch admission agrees with the declared contract', () => {
+ test.each([
+ 'main',
+ 'release+candidate',
+ 'feat;x',
+ 'a(b)c',
+ '_leading',
+ 'x.lock',
+ '-rf',
+ 'has space',
+ 'has:colon',
+ 'a..b',
+ 'feat\u0001x',
+ 'feat/../x',
+ ])('admits %j exactly when isValidBranchName does', (branch) => {
+ const url = `https://github.com/inkeep/playbooks/blob/${encodeURIComponent(branch)}/readme.md`;
+ expect(buildSplashViewModel(encodeV1(url)).kind === 'ok').toBe(isValidBranchName(branch));
+ });
+});
+
describe('buildSplashViewModel — shell-injection guard', () => {
test('rejects a branch carrying a shell command separator', () => {
const url = 'https://github.com/inkeep/playbooks/blob/main%3Bcurl%20evil.sh%7Csh/readme.md';
diff --git a/lint-plugins/ok-rules/README.md b/lint-plugins/ok-rules/README.md
index e65832b9e..14db2df5c 100644
--- a/lint-plugins/ok-rules/README.md
+++ b/lint-plugins/ok-rules/README.md
@@ -4,7 +4,7 @@ Custom lint rules for this workspace. Each rule is a module under `rules/`, comp
Rules surface as lint errors during `pnpm run lint:oxlint` (i.e. `pnpm lint` and `pnpm check`) and as inline editor squiggles via the oxc LSP.
-One plugin holding every rule is deliberate: oxlint walks the AST once and dispatches every registered visitor, so rules amortize. Measured on this tree, 12 synthetic probe rules added 0.17s and all 23 real rules cost nothing detectable against a no-rule baseline. The GritQL plugins these replaced cost about 3.3s each because every plugin re-traversed.
+One plugin holding every rule is deliberate: oxlint walks the AST once and dispatches every registered visitor, so rules amortize. Measured on this tree, 12 synthetic probe rules added 0.17s and all 24 real rules cost nothing detectable against a no-rule baseline. The GritQL plugins these replaced cost about 3.3s each because every plugin re-traversed.
## Convention
@@ -252,6 +252,120 @@ Included: `packages/**/*.test.ts`, `packages/**/*.test.tsx`, `packages/**/*.e2e.
Rule: [`lint-plugins/ok-rules/rules/no-roundtrip-identity-oracle.mjs`](rules/no-roundtrip-identity-oracle.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-roundtrip-identity-oracle.fixture.tsx`](__fixtures__/no-roundtrip-identity-oracle.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts`](../../packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention and [PRECEDENTS.md #38](../../PRECEDENTS.md) for the Bridge-invariant contract.
+### `no-hand-rolled-branch-validation`
+
+Branch-name admissibility has one owner in `packages/server`: `isValidBranchName`
+(`packages/core/src/schemas/api/share.ts`), declared the single source of truth for the seven-rule
+contract by the commit "reject colon + `..` in branch names; unify validation across 3 surfaces".
+Testing a regex against a branch value re-implements that contract locally, where it drifts
+silently.
+
+That drift is not hypothetical. That commit migrated three surfaces and left `/api/history` on its
+own allow-list regex; the two definitions disagreed for three and a half months until the Timeline
+was reported rendering "History unavailable" for any worktree branch containing a `+`. The regex
+rejected twenty-one printable-ASCII characters real `git check-ref-format` accepts
+(``!"#$%&'()+,;<=>@]`{|}`` — the route test samples twelve of them), every non-ASCII character, and
+any leading underscore.
+
+The rule fires on a regex literal `.test(<branch>)` or `.exec(<branch>)`, or on
+`<branch>.match(<regex>)`, where `<branch>` is an identifier or member whose name reads as a branch
+(`branch`, `branchName`, `refName`, `targetBranch`, ...). It is deliberately **regex-only**: string
+methods such as
+`branch.startsWith('detached-')` select by naming convention rather than validate, and the footprint
+audit found that shape to be the only false positive under a broader predicate.
+
+**The contract is a safety allow-list, not `git check-ref-format`.** It is deliberately stricter
+where injection is the risk — a leading `-` is git-legal but rejected, and so is any of the 19
+non-ASCII codepoints JS `/\s/` treats as whitespace (`U+00A0`, `U+1680`, `U+2000`–`U+200A`,
+`U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`), every one of which
+`git check-ref-format` accepts and `git branch` will create — and deliberately looser where it is
+not: `feat/a..b`, `x.lock`, `.hidden`, `feat//x`, a trailing `/`, and the characters `~`, `^`, `?`,
+`*`, `[`, `\` and the sequence `@{` all pass the contract and fail `git check-ref-format`.
+That is safe at `/api/history`, where a branch only ever interpolates into a `for-each-ref`
+*pattern* — with one caveat, on what gets iterated rather than what matches. `for-each-ref` truncates
+a pattern at the first glob-special byte (`*`, `?`, `[`, `\`) and walks that prefix, so a branch
+*starting* with one turns `refs/checkpoints/<branch>/` into a walk of `refs/checkpoints/` before the
+filter reduces it to the empty result the match argument predicts. Measured on 30,000 loose refs
+that is 0.42s against 0.00s for a literal, and ~0.01s once `pack-refs` has run, which is the steady
+state `git gc --auto` keeps; a glob later in the segment does not widen at all. A call site that
+feeds a branch to a git *rev* needs its own additional check. Delegating to the contract does not by
+itself make a call site git-correct.
+
+**Where the contract is applied, and where it deliberately is not.** It runs on every branch value
+that arrives over the wire, in two shapes. Directly, at the two GET query parameters:
+`/api/history`'s (`http/history-routes.ts:102`) and `/api/git/branch-info`'s
+(`http/git-routes.ts:121`). Inside the request schema, at every POST body's `branch` field —
+`CheckoutRequestSchema` and `ShareTargetStatusRequestSchema` through the shared `refineBranchName`
+helper (`packages/core/src/schemas/api/share.ts:166`), and `LocalOpCloneRequestSchema` through a bare
+`.refine(isValidBranchName, ...)` (`packages/core/src/schemas/api/_envelope.ts:171`). The refinement
+on the schema, not a hand-written call in the handler, is the idiom for a new route. Outside
+`packages/server` the contract also gates `packages/core`'s share-URL serialize and decode
+(`sharing/share-url.ts:178`, `:296`) and the desktop worktree checkout
+(`packages/desktop/src/main/worktree-service.ts:139`).
+
+Being on that list is not the same as being git-correct, and `/api/git/branch-info` is the standing
+example. `computeBranchInfo` interpolates its contract-validated branch into four git *revisions* —
+`rev-parse --verify refs/heads/${targetBranch}`, `rev-parse --verify origin/${targetBranch}`,
+`cat-file -e origin/${targetBranch}:${path}` (`git-branch-info.ts:83-99`) and
+`diff --name-only HEAD..${targetRef}` (`git-dirty.ts:17`) — while the contract admits `~`, `^` and
+`@{`. By the paragraph above, that route still needs the additional check the contract does not
+supply; it has not got one yet.
+
+`/api/history` also guards the value it falls back to when no parameter is sent — the local
+checkout's `HEAD` — so a checkout named with one of the 19 whitespace codepoints listed above gets a
+400 there and a dead Timeline. That residual is known, not an oversight. `/api/history/:sha` takes no
+branch parameter, so its branch is only ever the checkout's own and it is left unguarded; the two
+handlers deliberately differ.
+
+Nowhere else is a branch value contract-checked. `HEAD` reaches the checkpoint and WIP machinery
+through `getCurrentBranch?.() ?? 'main'` across `packages/server/src` — grep that expression for the
+live set rather than trusting a census here, which nothing pins — and guarding at the origin would
+silently re-namespace a user's checkpoints under `main`.
+
+**Two different exclusions, for two different reasons.** `packages/core` is out of scope because it
+*is* the definition. `docs/src/lib/share-splash.ts` is out of scope for a weaker reason: it holds
+`isValidShareBranch`, a live re-implementation of the same seven rules, added after single ownership
+was declared. It is behaviourally faithful today, and
+[`docs/src/lib/share-splash.test.ts`](../../docs/src/lib/share-splash.test.ts) now pins that with an
+agreement test that drives a shared corpus through the public `buildSplashViewModel` seam and
+compares each verdict against `isValidBranchName`. The corpus is a sample, not a per-rule matrix: it
+pins the sampled verdicts, and an amendment outside it still needs the clone updated by hand. One
+rule is not merely unsampled but unreachable through that seam: an empty branch yields a
+four-segment path, which `parseGitHubBlobUrl` rejects on segment count (`share-splash.ts:328`)
+before it ever reaches the predicate, so the clone's own empty-string rule stays unpinned there.
+Converging it outright would pull the `@inkeep/open-knowledge-core` barrel into
+the docs client bundle — the module is reachable from `'use client'` components and core declares no
+`sideEffects` — so it would first need the predicate extracted behind a narrow subpath export, which
+this change does not do.
+
+What it does **not** catch: the regex must be a literal at the call site. A hoisted
+`const BRANCH_RE = /.../; BRANCH_RE.test(branch)`, or `new RegExp(...).test(branch)`, evades it —
+matching those needs dataflow analysis this rule does not attempt. No such shape validates a branch
+anywhere in `packages/server/src` today — every `new RegExp` site there was read during the footprint
+audit and none takes a branch value — so the rule's in-scope footprint is complete as written; the
+boundary is recorded so a future reader does not over-trust it.
+
+Nor does it catch `branch.search(<regex>)`, which answers with an index rather than a verdict and
+has no call site in `packages/server/src` today.
+
+Nor does it catch a branch value held in a differently-named local. `BRANCH_IDENTIFIER_RE` matches
+`branch` and `refName` and any `<x>Branch`, each with an optional `Name` / `Ref` suffix; it does not
+match `branchValue`, `headRef` or `branch_name`. Widening the name predicate further trades recall
+against false positives on non-admissibility regexes over branch-shaped locals.
+
+Validating something that is not a branch name, or enforcing a rule the contract deliberately omits?
+Suppress with a reason:
+
+```ts
+// oxlint-disable-next-line ok/no-hand-rolled-branch-validation -- <reason>
+```
+
+**Scoped** (see the rule's `RULE_SCOPES` entry in [`scope.mjs`](scope.mjs)) to `packages/server/src/**/*.ts`, with `!**/*.test.ts` + `!**/*.test-helper.ts` excluded.
+
+Included: `packages/server/src/**/*.ts`, `lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx`. Excluded: `**/*.test.ts`, `**/*.test-helper.ts`.
+
+Rule: [`lint-plugins/ok-rules/rules/no-hand-rolled-branch-validation.mjs`](rules/no-hand-rolled-branch-validation.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx`](__fixtures__/no-hand-rolled-branch-validation.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-hand-rolled-branch-validation.test.ts`](../../packages/app/tests/lint-plugins/no-hand-rolled-branch-validation.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.
+
### `no-hand-rolled-spinner`
Flags `animate-spin` in any `className` / `*ClassName` attribute value. Loading spinners come from the `Spinner` primitive so reduced-motion support and the accessible name are inherited rather than remembered per call site.
diff --git a/lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx b/lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx
new file mode 100644
index 000000000..73d866a47
--- /dev/null
+++ b/lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx
@@ -0,0 +1,74 @@
+// FIXTURE — drives `no-hand-rolled-branch-validation.test.ts` via shell-out to
+// `pnpm exec oxlint`. Not part of the main lint: `__fixtures__/` is in
+// `oxlint.config.ts#ignorePatterns`, and `__fixtures__/oxlint.fixtures.json`
+// re-enables the rules for the test.
+//
+// 4 positive cases (deliberate violations — rule must fire) + 4 negative cases
+// (sanctioned or unrelated shapes that must NOT fire). Exact-equality
+// (`toBe(4)`) in the test catches both false-negative regressions (drop below
+// 4) and false-positive widenings (above 4).
+//
+// Positive1 is the load-bearing one: it is the exact pre-fix source line
+// from packages/server/src/http/history-routes.ts, verbatim. If the rule
+// stops firing on it, the rule no longer covers the bug it was promoted for.
+//
+// Negative3 is the audit's only false positive under a string-method
+// predicate (a GC filter selecting by naming convention, not validating). The
+// rule is deliberately regex-only so this stays silent.
+
+declare const branch: string;
+declare const branchName: string;
+declare const ref: { branch: string };
+declare const isValidBranchName: (b: unknown) => b is string;
+declare const skillName: string;
+
+// === Positive cases — must fire ===
+
+// (1) The exact pre-fix guard, verbatim.
+export function Positive1(): boolean {
+ if (branch.includes('..') || !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(branch)) {
+ return false;
+ }
+ return true;
+}
+
+// (2) Same defect wearing a different identifier and a `.match` shape.
+export function Positive2(): boolean {
+ return branchName.match(/^[a-z0-9-]+$/) !== null;
+}
+
+// (3) Same defect reached through a member expression.
+export function Positive3(): boolean {
+ return /^[\w.-]+$/.test(ref.branch);
+}
+
+// (4) Same defect through `.exec`, which shares `.test`'s AST shape and is
+// one `typescript-eslint/prefer-regexp-exec` autofix away from Positive2.
+export function Positive4(): boolean {
+ return /^[a-z0-9-]+$/.exec(branchName) !== null;
+}
+
+// === Negative cases — must NOT fire ===
+
+// (1) The sanctioned shape: delegate to the declared contract.
+export function Negative1(): boolean {
+ return isValidBranchName(branch);
+}
+
+// (2) A regex tested against something that is not a branch value.
+export function Negative2(): boolean {
+ return /^[a-z0-9-]+$/.test(skillName);
+}
+
+// (3) A string-method filter selecting by naming convention, not validating.
+// This is shadow-branch-gc.ts:111's shape — the footprint audit's only
+// false positive under a string-method predicate.
+export function Negative3(): boolean {
+ return branch.startsWith('detached-');
+}
+
+// (4) A regex applied to a branch value for a non-admissibility purpose
+// (extraction), through a method the rule does not claim.
+export function Negative4(): string {
+ return branch.replace(/^refs\/heads\//, '');
+}
diff --git a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
index c54249fc9..9824ff812 100644
--- a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
+++ b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
@@ -6,6 +6,7 @@
"ok/microcopy-ellipsis": "error",
"ok/no-blind-agent-host-fanout": "error",
"ok/no-demoted-dialog-confirm": "error",
+ "ok/no-hand-rolled-branch-validation": "error",
"ok/no-hand-rolled-spinner": "error",
"ok/no-inline-tolerance-class": "error",
"ok/no-loosely-typed-webcontents-ipc": "error",
diff --git a/lint-plugins/ok-rules/index.mjs b/lint-plugins/ok-rules/index.mjs
index ba9eb8ebf..0b5b8dc27 100644
--- a/lint-plugins/ok-rules/index.mjs
+++ b/lint-plugins/ok-rules/index.mjs
@@ -5,6 +5,7 @@ import { cstPmHandlerTodoStub } from './rules/cst-pm-handler-todo-stub.mjs';
import { microcopyEllipsis } from './rules/microcopy-ellipsis.mjs';
import { noBlindAgentHostFanout } from './rules/no-blind-agent-host-fanout.mjs';
import { noDemotedDialogConfirm } from './rules/no-demoted-dialog-confirm.mjs';
+import { noHandRolledBranchValidation } from './rules/no-hand-rolled-branch-validation.mjs';
import { noHandRolledSpinner } from './rules/no-hand-rolled-spinner.mjs';
import { noInlineToleranceClass } from './rules/no-inline-tolerance-class.mjs';
import { noLooselyTypedWebcontentsIpc } from './rules/no-loosely-typed-webcontents-ipc.mjs';
@@ -34,6 +35,7 @@ const declared = {
'microcopy-ellipsis': microcopyEllipsis,
'no-blind-agent-host-fanout': noBlindAgentHostFanout,
'no-demoted-dialog-confirm': noDemotedDialogConfirm,
+ 'no-hand-rolled-branch-validation': noHandRolledBranchValidation,
'no-hand-rolled-spinner': noHandRolledSpinner,
'no-inline-tolerance-class': noInlineToleranceClass,
'no-loosely-typed-webcontents-ipc': noLooselyTypedWebcontentsIpc,
diff --git a/lint-plugins/ok-rules/rules/no-hand-rolled-branch-validation.mjs b/lint-plugins/ok-rules/rules/no-hand-rolled-branch-validation.mjs
new file mode 100644
index 000000000..aeb733aa0
--- /dev/null
+++ b/lint-plugins/ok-rules/rules/no-hand-rolled-branch-validation.mjs
@@ -0,0 +1,52 @@
+import { docsUrl } from '../docs.mjs';
+
+const URL = docsUrl('no-hand-rolled-branch-validation');
+
+const MESSAGE = `Hand-rolled branch-name validation — call \`isValidBranchName\` (from @inkeep/open-knowledge-core, re-exported at packages/server/src/git-branch-info.ts) instead of testing a regex against a branch value. It is the declared single source of truth for the seven-rule contract; a local regex drifts from it silently, which is how /api/history came to answer 400 on git-legal branch names containing \`+\`. Validating something other than a branch name, or enforcing a rule the contract deliberately omits? suppress with \`// oxlint-disable-next-line ok/no-hand-rolled-branch-validation -- <reason>\`. See ${URL}`;
+
+export const BRANCH_IDENTIFIER_RE =
+ /^(?:branch|refName)(?:Name|Ref)?$|^[a-z][a-zA-Z0-9]*Branch(?:Name|Ref)?$/;
+
+const REGEX_TEST_METHODS = new Set(['test', 'match', 'exec']);
+
+function isBranchIdentifier(node) {
+ if (!node) return false;
+ if (node.type === 'Identifier') return BRANCH_IDENTIFIER_RE.test(node.name);
+ if (node.type === 'MemberExpression' && node.property?.type === 'Identifier') {
+ return BRANCH_IDENTIFIER_RE.test(node.property.name);
+ }
+ return false;
+}
+
+export const noHandRolledBranchValidation = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Branch-name admissibility must come from the declared isValidBranchName contract.',
+ url: URL,
+ },
+ },
+ create(context) {
+ return {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier') return;
+ const method = callee.property.name;
+ if (!REGEX_TEST_METHODS.has(method)) return;
+
+ if (method === 'test' || method === 'exec') {
+ if (callee.object.type !== 'Literal' || !('regex' in callee.object)) return;
+ if (!isBranchIdentifier(node.arguments?.[0])) return;
+ context.report({ node, message: MESSAGE });
+ return;
+ }
+
+ if (!isBranchIdentifier(callee.object)) return;
+ const arg = node.arguments?.[0];
+ if (arg?.type !== 'Literal' || !('regex' in arg)) return;
+ context.report({ node, message: MESSAGE });
+ },
+ };
+ },
+};
diff --git a/lint-plugins/ok-rules/scope.mjs b/lint-plugins/ok-rules/scope.mjs
index 12c4e3498..81c1f8e8b 100644
--- a/lint-plugins/ok-rules/scope.mjs
+++ b/lint-plugins/ok-rules/scope.mjs
@@ -30,6 +30,12 @@ export const RULE_SCOPES = {
'!**/*.test.tsx',
'lint-plugins/ok-rules/__fixtures__/no-raw-route-hash-construction.fixture.tsx',
],
+ 'no-hand-rolled-branch-validation': [
+ 'packages/server/src/**/*.ts',
+ '!**/*.test.ts',
+ '!**/*.test-helper.ts',
+ 'lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx',
+ ],
'path-conditional-map-driven-origin': [
'packages/server/src/server-observers.ts',
'lint-plugins/ok-rules/__fixtures__/path-conditional-map-driven-origin.fixture.tsx',
diff --git a/oxlint.config.ts b/oxlint.config.ts
index 7d3f8c3e1..9ab3b57d5 100644
--- a/oxlint.config.ts
+++ b/oxlint.config.ts
@@ -54,6 +54,7 @@ export default defineConfig({
'ok/microcopy-ellipsis': 'error',
'ok/no-blind-agent-host-fanout': 'error',
'ok/no-demoted-dialog-confirm': 'error',
+ 'ok/no-hand-rolled-branch-validation': 'error',
'ok/no-hand-rolled-spinner': 'error',
'ok/no-inline-tolerance-class': 'error',
'ok/no-loosely-typed-webcontents-ipc': 'error',
diff --git a/packages/app/src/components/FolderTimelineCard.tsx b/packages/app/src/components/FolderTimelineCard.tsx
index aba090f77..9acb77b06 100644
--- a/packages/app/src/components/FolderTimelineCard.tsx
+++ b/packages/app/src/components/FolderTimelineCard.tsx
@@ -1,6 +1,6 @@
// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility
-import type { TimelineEntry } from '@inkeep/open-knowledge-core';
+import { ProblemDetailsSchema, type TimelineEntry } from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
import {
@@ -81,6 +81,21 @@ export function FolderTimelineCard({ folderPath }: { folderPath: string }) {
const res = await fetch(`/api/history?folder=${encodeURIComponent(folderPath)}&limit=50`);
if (cancelled) return;
if (!res.ok) {
+ let type = '';
+ let detail = `HTTP ${res.status}`;
+ try {
+ const problem = ProblemDetailsSchema.safeParse(await res.json());
+ if (problem.success) {
+ type = problem.data.type;
+ detail = problem.data.title;
+ }
+ } catch {}
+ console.error('[FolderTimelineCard] folder timeline request failed', {
+ folderPath,
+ status: res.status,
+ type,
+ detail,
+ });
setError(true);
setLoading(false);
return;
diff --git a/packages/app/src/components/TimelinePanel.tsx b/packages/app/src/components/TimelinePanel.tsx
index feb85f1ac..5b3f2d3a6 100644
--- a/packages/app/src/components/TimelinePanel.tsx
+++ b/packages/app/src/components/TimelinePanel.tsx
@@ -70,6 +70,21 @@ async function pollHistoryOnce(
});
if (!res.ok) {
handlers.setError(handlers.unavailableMessage);
+ let type = '';
+ let detail = `HTTP ${res.status}`;
+ try {
+ const problem = ProblemDetailsSchema.safeParse(await res.json());
+ if (problem.success) {
+ type = problem.data.type;
+ detail = problem.data.title;
+ }
+ } catch {}
+ console.error('[timeline] history request failed', {
+ docName,
+ status: res.status,
+ type,
+ detail,
+ });
return 'error';
}
const data = (await res.json()) as { entries: TimelineEntry[] };
diff --git a/packages/app/tests/integration/api-error-envelope/history.test.ts b/packages/app/tests/integration/api-error-envelope/history.test.ts
index 1f763378e..11eb97757 100644
--- a/packages/app/tests/integration/api-error-envelope/history.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/history.test.ts
@@ -96,4 +96,30 @@ describe('history envelope (RFC 9457)', () => {
expect(parsed.data.type).toBe('urn:ok:error:method-not-allowed');
}
});
+
+ test('a git-legal "+" branch is served exactly like the same branch spelled in plain ASCII', async () => {
+ const seed = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: 'branch-admission-doc',
+ markdown: '# Branch admission\n',
+ position: 'replace',
+ }),
+ });
+ expect(seed.status).toBe(200);
+
+ const request = (branch: string) =>
+ fetch(
+ `http://127.0.0.1:${server.port}/api/history?docName=branch-admission-doc&limit=10&branch=${encodeURIComponent(branch)}`,
+ );
+
+ const plus = await request('feature+plus');
+ const ascii = await request('feature-plus');
+
+ expect(plus.status).toBe(200);
+ expect(plus.status).toBe(ascii.status);
+ expect(plus.headers.get('content-type')).toBe('application/json');
+ expect(HistorySuccessSchema.safeParse(await plus.json()).success).toBe(true);
+ });
});
diff --git a/packages/app/tests/lint-plugins/no-hand-rolled-branch-validation.test.ts b/packages/app/tests/lint-plugins/no-hand-rolled-branch-validation.test.ts
new file mode 100644
index 000000000..8eb065fba
--- /dev/null
+++ b/packages/app/tests/lint-plugins/no-hand-rolled-branch-validation.test.ts
@@ -0,0 +1,73 @@
+/** The `no-hand-rolled-branch-validation` oxlint rule fixture test, per precedent #42. */
+
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { BRANCH_IDENTIFIER_RE } from '../../../../lint-plugins/ok-rules/rules/no-hand-rolled-branch-validation.mjs';
+import { isInScope } from '../../../../lint-plugins/ok-rules/scope.mjs';
+import {
+ oxlintFixtureArgs,
+ readEnabledRuleIds,
+ readRegisteredRuleNames,
+ readRuleScope,
+} from '../../../../test-support/read-ok-rules-config.test-helper';
+
+const REPO_ROOT = join(__dirname, '..', '..', '..', '..');
+const RULE = 'no-hand-rolled-branch-validation';
+const FIXTURE_REL =
+ 'lint-plugins/ok-rules/__fixtures__/no-hand-rolled-branch-validation.fixture.tsx';
+const GUARD_REL = 'packages/server/src/http/history-routes.ts';
+
+describe('no-hand-rolled-branch-validation oxlint rule', () => {
+ test('fires on exactly 4 planted positives (and on no negative case)', () => {
+ const result = spawnSync('pnpm', oxlintFixtureArgs(FIXTURE_REL), {
+ cwd: REPO_ROOT,
+ encoding: 'utf-8',
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.status).not.toBe(0);
+ const output = `${result.stdout}\n${result.stderr}`;
+ const fires = (output.match(/Hand-rolled branch-name validation/g) ?? []).length;
+ expect(fires).toBe(4);
+ expect(output).toContain('isValidBranchName');
+ expect(output).toMatch(/https?:\/\/[^\s]+/);
+ expect(output).toContain('lint-plugins/ok-rules/README.md#no-hand-rolled-branch-validation');
+ });
+
+ test('rule is registered, enabled, and scoped via its RULE_SCOPES entry', async () => {
+ expect(await readRegisteredRuleNames(REPO_ROOT)).toContain(RULE);
+ expect(await readEnabledRuleIds(REPO_ROOT)).toContain(`ok/${RULE}`);
+ expect(readRuleScope(REPO_ROOT, RULE)).not.toEqual([]);
+ });
+
+ test('its scope table still carries every include and exclude the rule depends on', () => {
+ expect(readRuleScope(REPO_ROOT, RULE).sort()).toEqual(
+ ['packages/server/src/**/*.ts', '!**/*.test.ts', '!**/*.test-helper.ts', FIXTURE_REL].sort(),
+ );
+ });
+
+ test('covers the guard it was promoted for, and neither definition site of the contract', () => {
+ expect(isInScope(RULE, GUARD_REL)).toBe(true);
+ expect(isInScope(RULE, 'packages/core/src/schemas/api/share.ts')).toBe(false);
+ expect(isInScope(RULE, 'docs/src/lib/share-splash.ts')).toBe(false);
+ expect(isInScope(RULE, 'packages/server/src/http/history-routes.test.ts')).toBe(false);
+ });
+
+ test('matches the branch-identifier shapes the fixture depends on, and no more', () => {
+ for (const name of [
+ 'branch',
+ 'branchName',
+ 'branchRef',
+ 'refName',
+ 'targetBranch',
+ 'currentBranch',
+ 'targetBranchName',
+ 'newBranchName',
+ ]) {
+ expect(BRANCH_IDENTIFIER_RE.test(name)).toBe(true);
+ }
+ for (const name of ['skillName', 'docName', 'branchless', 'rebranch', 'headRef']) {
+ expect(BRANCH_IDENTIFIER_RE.test(name)).toBe(false);
+ }
+ });
+});
diff --git a/packages/core/src/git-repository.test.ts b/packages/core/src/git-repository.test.ts
index 269543ada..65c2f7c92 100644
--- a/packages/core/src/git-repository.test.ts
+++ b/packages/core/src/git-repository.test.ts
@@ -241,6 +241,26 @@ describe('inspectGitRepository', () => {
expect(result.repository.readHead()).toEqual({ kind: 'detached', oid });
});
+ test('carries a branch name out of HEAD verbatim, including bytes only git admits', async () => {
+ const root = await makeTemporaryDirectory();
+ const gitDir = join(root, '.git');
+ mkdirSync(gitDir);
+
+ for (const branch of ['worktree-design+atc-release-package', 'feature-café']) {
+ writeFileSync(join(gitDir, 'HEAD'), `ref: refs/heads/${branch}\n`);
+
+ const result = inspectGitRepository(root);
+
+ expect(result.kind).toBe('repository');
+ if (result.kind !== 'repository') return;
+ expect(result.repository.readHead()).toEqual({
+ kind: 'branch',
+ branch,
+ ref: `refs/heads/${branch}`,
+ });
+ }
+ });
+
test('resolves packed refs from the common directory', async () => {
const root = await makeTemporaryDirectory();
diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.ts
index e059ee1e7..4b81a5566 100644
--- a/packages/core/src/schemas/api/share.test.ts
+++ b/packages/core/src/schemas/api/share.test.ts
@@ -244,6 +244,10 @@ describe('isValidBranchName', () => {
expect(isValidBranchName('feat/foo')).toBe(true));
test('accepts dots within a segment (not a `..` segment)', () =>
expect(isValidBranchName('feat..ure')).toBe(true));
+ test('accepts non-ASCII: the contract constrains bytes, not scripts', () => {
+ expect(isValidBranchName('feature-café')).toBe(true);
+ expect(isValidBranchName('функция-тест')).toBe(true);
+ });
test('rejects a non-string', () => {
expect(isValidBranchName(null)).toBe(false);
diff --git a/packages/server/src/http/history-routes.test.ts b/packages/server/src/http/history-routes.test.ts
new file mode 100644
index 000000000..30de62d22
--- /dev/null
+++ b/packages/server/src/http/history-routes.test.ts
@@ -0,0 +1,190 @@
+import { isValidBranchName } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';
+import { loggerFactory } from '../logger.ts';
+import type { ShadowHandle, ShadowRef } from '../shadow-repo.ts';
+import { createHistoryRoutes } from './history-routes.ts';
+
+type Deps = Parameters<typeof createHistoryRoutes>[0];
+
+const ADMITTED = 'branch admitted: the request reached the next validation stage';
+
+function buildGroup(overrides: Partial<Deps> = {}) {
+ const shadowRef: ShadowRef = { current: {} as ShadowHandle };
+ return createHistoryRoutes({
+ contentRoot: '/nonexistent-content',
+ log: loggerFactory.getLogger('test'),
+ shadowRef,
+ flushGitCommit: undefined,
+ commitOkArtifactWrite: () => Promise.resolve(),
+ getCurrentBranch: undefined,
+ validateFolderRel: (_raw, res) => {
+ res.writeHead(400, { 'Content-Type': 'application/problem+json' });
+ res.end(
+ JSON.stringify({ type: 'urn:ok:error:invalid-request', title: ADMITTED, status: 400 }),
+ );
+ return null;
+ },
+ safeDocPath: () => ({ error: ADMITTED }),
+ docTreePathCandidates: () => [],
+ ...overrides,
+ });
+}
+
+interface HistoryOutcome {
+ status: number;
+ type: string;
+ title: string;
+ contentType: string;
+ admitted: boolean;
+}
+
+async function dispatchHistory(path: string, overrides: Partial<Deps>): Promise<HistoryOutcome> {
+ const { table } = buildGroup(overrides);
+ const resolved = table.resolve(path.split('?')[0] ?? path);
+ if (!resolved?.dispatch) throw new Error(`${path} did not resolve to a dispatch handler`);
+ const { res, captured } = makeCaptureRes();
+ await resolved.dispatch(makeSyntheticReq({ url: path }), res);
+ const body = captured.body
+ ? (JSON.parse(captured.body) as { type?: string; title?: string })
+ : {};
+ const title = body.title ?? '';
+ return {
+ status: captured.status,
+ type: body.type ?? '',
+ title,
+ contentType: String(captured.headers['content-type'] ?? ''),
+ admitted: title === ADMITTED,
+ };
+}
+
+function getHistory(query: string, overrides: Partial<Deps> = {}): Promise<HistoryOutcome> {
+ return dispatchHistory(`/api/history?${query}`, overrides);
+}
+
+function getHistoryForBranch(
+ branch: string,
+ overrides: Partial<Deps> = {},
+): Promise<HistoryOutcome> {
+ return getHistory(`docName=alpha&branch=${encodeURIComponent(branch)}`, overrides);
+}
+
+const PLUS_BRANCH = 'worktree-design+atc-release-package';
+const NBSP_BRANCH = 'feature\u00A0nbsp';
+
+const GIT_LEGAL_BRANCH_NAMES = [
+ PLUS_BRANCH,
+ 'release(2026)#1',
+ 'feat/issue=42',
+ 'feat/a,b',
+ 'feat/100%-done',
+ 'feat/cost$estimate',
+ 'feat/this&that',
+ 'feat/ship!now',
+ 'feat/a;b',
+ "feat/miles'-branch",
+ '_leading-underscore',
+ 'feature-café',
+ 'функция-тест',
+ 'main',
+] as const;
+
+const GIT_ILLEGAL_BUT_CONTRACT_ADMITTED = [
+ 'feat/a~b',
+ 'feat/a^b',
+ 'feat/a?b',
+ 'feat/a*b',
+ 'feat/a[b',
+ 'feat/a\\b',
+ 'feat/a@{b',
+ 'x.lock',
+ '.hidden',
+ 'feat//x',
+ 'feat/',
+ 'feat/a..b',
+] as const;
+
+const CONTRACT_REJECTED_BRANCH_NAMES = [
+ '../evil',
+ NBSP_BRANCH,
+ 'a/../../heads/main',
+ '-oInject',
+ 'has space',
+ 'has:colon',
+ 'ctrl\u0001char',
+ 'nul\u0000byte',
+ '',
+] as const;
+
+describe('GET /api/history branch admission — names the shared contract accepts', () => {
+ test.each(GIT_LEGAL_BRANCH_NAMES)('admits %j from the branch query parameter', async (branch) => {
+ expect(isValidBranchName(branch)).toBe(true);
+ const outcome = await getHistoryForBranch(branch);
+ expect(outcome.title).toBe(ADMITTED);
+ });
+
+ test('admits the document Timeline shape: no branch parameter, head watcher on a "+" branch', async () => {
+ const outcome = await getHistory('docName=alpha&limit=100', {
+ getCurrentBranch: () => PLUS_BRANCH,
+ });
+ expect(outcome.title).toBe(ADMITTED);
+ });
+
+ test('admits the folder Timeline shape: no branch parameter, head watcher on a "+" branch', async () => {
+ const outcome = await getHistory('folder=notes&limit=50', {
+ getCurrentBranch: () => PLUS_BRANCH,
+ });
+ expect(outcome.title).toBe(ADMITTED);
+ });
+});
+
+describe('GET /api/history branch admission — names the shared contract rejects', () => {
+ test.each(CONTRACT_REJECTED_BRANCH_NAMES)(
+ 'rejects %j with the invalid-request envelope',
+ async (branch) => {
+ expect(isValidBranchName(branch)).toBe(false);
+ const outcome = await getHistoryForBranch(branch);
+ expect(outcome.admitted).toBe(false);
+ expect(outcome.status).toBe(400);
+ expect(outcome.type).toBe('urn:ok:error:invalid-request');
+ expect(outcome.contentType).toBe('application/problem+json');
+ },
+ );
+
+ test('rejects an argv-injecting branch arriving from the head watcher, not only from query', async () => {
+ const outcome = await getHistory('docName=alpha', { getCurrentBranch: () => '-oInject' });
+ expect(outcome.admitted).toBe(false);
+ expect(outcome.status).toBe(400);
+ expect(outcome.type).toBe('urn:ok:error:invalid-request');
+ });
+});
+
+describe('GET /api/history branch admission — agreement with the declared contract', () => {
+ test('admission decision matches isValidBranchName for every sampled name', async () => {
+ const sampled = [...GIT_LEGAL_BRANCH_NAMES, ...CONTRACT_REJECTED_BRANCH_NAMES, 'feat/a..b'];
+ const admission: Record<string, boolean> = {};
+ const contract: Record<string, boolean> = {};
+ for (const branch of sampled) {
+ admission[branch] = (await getHistoryForBranch(branch)).admitted;
+ contract[branch] = isValidBranchName(branch);
+ }
+ expect(admission).toEqual(contract);
+ });
+
+ test('admits "feat/a..b": the contract rejects ".." only as a whole path segment', async () => {
+ expect(isValidBranchName('feat/a..b')).toBe(true);
+ const outcome = await getHistoryForBranch('feat/a..b');
+ expect(outcome.title).toBe(ADMITTED);
+ });
+});
+
+describe('GET /api/history branch admission — names git rejects that the contract admits', () => {
+ test.each(GIT_ILLEGAL_BUT_CONTRACT_ADMITTED)(
+ 'admits %j, which `git check-ref-format` rejects',
+ async (branch) => {
+ expect(isValidBranchName(branch)).toBe(true);
+ const outcome = await getHistoryForBranch(branch);
+ expect(outcome.title).toBe(ADMITTED);
+ },
+ );
+});
diff --git a/packages/server/src/http/history-routes.ts b/packages/server/src/http/history-routes.ts
index d6dc79b98..1c02145b6 100644
--- a/packages/server/src/http/history-routes.ts
+++ b/packages/server/src/http/history-routes.ts
@@ -3,6 +3,7 @@ import {
EmptyRequestSchema,
HistorySuccessSchema,
HistoryVersionSuccessSchema,
+ isValidBranchName,
} from '@inkeep/open-knowledge-core';
import { getLogger, type PinoLogger } from '../logger.ts';
import {
@@ -98,7 +99,7 @@ export function createHistoryRoutes(deps: HistoryRouteDeps): HistoryRoutes {
return;
}
- if (branch.includes('..') || !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(branch)) {
+ if (!isValidBranchName(branch)) {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid branch name.', {
handler: 'history',
});
diff --git a/test-support/read-ok-rules-config.test-helper.ts b/test-support/read-ok-rules-config.test-helper.ts
index 976161368..11aeba6b0 100644
--- a/test-support/read-ok-rules-config.test-helper.ts
+++ b/test-support/read-ok-rules-config.test-helper.ts
@@ -75,5 +75,5 @@ export async function readRegisteredRuleNames(repoRoot: string): Promise<string[
}
export function readRuleScope(_repoRoot: string, ruleName: string): string[] {
- return (RULE_SCOPES as Record<string, string[]>)[ruleName] ?? [];
+ return [...((RULE_SCOPES as Record<string, string[]>)[ruleName] ?? [])];
}