Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Restore docs code-block hierarchy (#3938)
Maximilian Roos750972d2c5b0
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex 783035e87..e41088780 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -52,7 +52,8 @@ View changes: http://127.0.0.1:<port>| `src/pages/index.astro` | Homepage route; renders the canonical `worktrunk.md` body || `src/styles/custom.css` | Worktrunk's visual system and narrow Starlight adjustments || `src/plugins/stable-heading-ids.mjs` | Stable public anchor IDs for Markdown headings |-| `src/plugins/worktrunk-terminal.mjs` | Prompts, copy behavior, and ANSI-derived styling for `console` fences |+| `src/plugins/worktrunk-terminal.mjs` | Shell syntax, prompts, copy behavior, Clap help roles, and ANSI-derived output styling |+| `src/themes/worktrunk-code.mjs` | Light and dark syntax themes for source and command blocks || `src/generated/terminal-styles.json` | Generated site-only span styles from ANSI command snapshots || `src/components/Head.astro` | Social metadata, structured data, and analytics || `tests/` | Renderer unit tests plus built-site and WebKit mobile checks |@@ -218,13 +219,15 @@ $ wt switch --create feature-auth```````-Starlight and Expressive Code create the terminal frame and copy button. The-small Worktrunk plugin removes `$ ` from presentation data, renders it as a-prompt, and makes mixed blocks copy only their commands. Comment lines and-blank recipe separators remain copyable; captured output does not. The plugin-restores exact ANSI roles from the generated style manifest for snapshot-backed-examples; hand-written output uses a conservative marker fallback. Committed-Markdown must remain useful without the plugin.+Starlight and Expressive Code create the frame and copy button. The Worktrunk+plugin highlights `console` commands as Bash, renders `$ ` as a prompt, and+makes mixed blocks copy only their commands. Comment lines and blank recipe+separators remain copyable; captured output does not. Snapshot-backed output+gets its exact ANSI roles from the generated style manifest, while hand-written+output uses a conservative marker fallback. Generated Clap help fences carry+the `wt-command-reference` marker, which the plugin expands into semantic+command, option, value, and metadata roles. Committed Markdown must remain+useful without the plugin.### Web-only post-processingdiff --git a/docs/astro.config.mjs b/docs/astro.config.mjsindex 4c88ac234..a0c3e99d7 100644--- a/docs/astro.config.mjs+++ b/docs/astro.config.mjs@@ -9,6 +9,10 @@ import { rehypeStableHeadingIds } from './src/plugins/stable-heading-ids.mjs';import { sidebar } from './src/site-navigation.mjs';import { sitemapCompatibility } from './src/plugins/sitemap-compatibility.mjs';import { pluginWorktrunkTerminal } from './src/plugins/worktrunk-terminal.mjs';+import {+ worktrunkDarkCodeTheme,+ worktrunkLightCodeTheme,+} from './src/themes/worktrunk-code.mjs';const repository = 'https://github.com/max-sixty/worktrunk';const site = 'https://worktrunk.dev';@@ -57,6 +61,8 @@ export default defineConfig({},expressiveCode: {plugins: [pluginWorktrunkTerminal()],+ themes: [worktrunkDarkCodeTheme, worktrunkLightCodeTheme],+ useStarlightUiThemeColors: true,styleOverrides: {borderRadius: '0',codeFontFamily: 'var(--sl-font-mono)',diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.mdindex 4fa635d39..d5caa9859 100644--- a/docs/src/content/docs/config.md+++ b/docs/src/content/docs/config.md@@ -711,7 +711,7 @@ Hooks, aliases and `step.copy-ignored.exclude` accumulate rather than replace, s## Command reference-```+```text wt-command-referencewt config - Manage user & project configsIncludes shell integration, hooks, and saved state.@@ -777,7 +777,7 @@ This tests:### Command reference-```+```text wt-command-referencewt config show - Show configuration files & locationsUsage: wt config show [OPTIONS]@@ -885,7 +885,7 @@ Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval### Command reference-```+```text wt-command-referencewt config approvals - Manage command approvalsUsage: wt config approvals [OPTIONS] <COMMAND>@@ -944,7 +944,7 @@ $ wt config alias dry-run deploy -- --env=staging### Command reference-```+```text wt-command-referencewt config alias - Inspect and preview aliasesUsage: wt config alias [OPTIONS] <COMMAND>@@ -1029,7 +1029,7 @@ $ wt config state clear### Command reference-```+```text wt-command-referencewt config state - Manage internal data and cacheUsage: wt config state [OPTIONS] <COMMAND>@@ -1098,7 +1098,7 @@ $ wt config state cache clear### Command reference-```+```text wt-command-referencewt config state cache - Regenerable cachesUsage: wt config state cache [OPTIONS] [COMMAND]@@ -1173,7 +1173,7 @@ If none of these match, detection fails; set it explicitly with `wt config state### Command reference-```+```text wt-command-referencewt config state default-branch - Default branch detection and overrideUsage: wt config state default-branch [OPTIONS] [COMMAND]@@ -1290,7 +1290,7 @@ $ wt config state logs clear### Command reference-```+```text wt-command-referencewt config state logs - Operation and debug logsUsage: wt config state logs [OPTIONS] [COMMAND]@@ -1339,7 +1339,7 @@ Without a subcommand, runs `get` for the current branch. Use `clear` to reset ca### Command reference-```+```text wt-command-referencewt config state ci-status - CI status cacheUsage: wt config state ci-status [OPTIONS] [COMMAND]@@ -1414,7 +1414,7 @@ Without a subcommand, runs `get` for the current branch. For `--branch`, use `ge### Command reference-```+```text wt-command-referencewt config state marker - Branch markersUsage: wt config state marker [OPTIONS] [COMMAND]@@ -1507,7 +1507,7 @@ Stored in git config as `worktrunk.state.<branch>.vars.<key>`. Keys must contain### Command reference-```+```text wt-command-referencewt config state vars - [experimental] Custom variables per branchUsage: wt config state vars [OPTIONS] <COMMAND>diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.mdindex 36dbd3285..2ea0aad91 100644--- a/docs/src/content/docs/hook.md+++ b/docs/src/content/docs/hook.md@@ -349,7 +349,7 @@ The long form `--var KEY=VALUE` is deprecated but still supported. It force-bind## Command reference-```+```text wt-command-referencewt hook - Run configured hooksUsage: wt hook [OPTIONS] <COMMAND>diff --git a/docs/src/content/docs/list.md b/docs/src/content/docs/list.mdindex b9dc9e815..298e520db 100644--- a/docs/src/content/docs/list.md+++ b/docs/src/content/docs/list.md@@ -478,7 +478,7 @@ Missing a field that would be generally useful? [Open an issue](https://github.c## Command reference-```+```text wt-command-referencewt list - List worktrees and their statusUsage: wt list [OPTIONS]@@ -566,7 +566,7 @@ The pace segment appears only when usage is likely to hit a rate limit before it### Command reference-```+```text wt-command-referencewt list statusline - Single-line status for the current worktreeUsage: wt list statusline [OPTIONS]diff --git a/docs/src/content/docs/merge.md b/docs/src/content/docs/merge.mdindex 1d13329cd..870989c32 100644--- a/docs/src/content/docs/merge.md+++ b/docs/src/content/docs/merge.md@@ -111,7 +111,7 @@ lint = "cargo clippy"## Command reference-```+```text wt-command-referencewt merge - Merge current branch into the target branchSquash & rebase, fast-forward the target branch, remove the worktree.diff --git a/docs/src/content/docs/remove.md b/docs/src/content/docs/remove.mdindex d33275cbf..653d0d577 100644--- a/docs/src/content/docs/remove.md+++ b/docs/src/content/docs/remove.md@@ -137,7 +137,7 @@ Detached worktrees have no branch name. Pass the worktree path instead: `wt remo## Command reference-```+```text wt-command-referencewt remove - Remove worktree; delete branch if mergedDefaults to the current worktree.diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.mdindex f9e1361b8..08b90dd72 100644--- a/docs/src/content/docs/step.md+++ b/docs/src/content/docs/step.md@@ -52,7 +52,7 @@ $ wt step push## Command reference-```+```text wt-command-referencewt step - Run individual operationsThe building blocks of wt merge — commit, squash, rebase, push — plus standalone utilities.@@ -140,7 +140,7 @@ Three sections are printed: the rendered prompt, the shell command that would in### Command reference-```+```text wt-command-referencewt step commit - Stage and commit with LLM-generated messageUsage: wt step commit [OPTIONS]@@ -235,7 +235,7 @@ Three sections are printed: the rendered prompt, the shell command that would in### Command reference-```+```text wt-command-referencewt step squash - Squash commits since branchingStages changes and generates message with LLM.@@ -330,7 +330,7 @@ A conflicting commit leaves the rebase open rather than undoing it. The worktree### Command reference-```+```text wt-command-referencewt step rebase - Rebase onto targetUsage: wt step rebase [OPTIONS] [TARGET]@@ -397,7 +397,7 @@ A worktree that is still registered but whose directory is gone is refused as we### Command reference-```+```text wt-command-referencewt step push - Fast-forward target to current branchUsage: wt step push [OPTIONS] [TARGET]@@ -489,7 +489,7 @@ $ GIT_INDEX_FILE=/tmp/idx git diff $(git merge-base HEAD $(wt config state defau### Command reference-```+```text wt-command-referencewt step diff - Show all changes since branchingIncludes committed, staged, unstaged, and untracked files.@@ -630,7 +630,7 @@ The `.worktreeinclude` pattern is shared with [Claude Code on desktop](https://c### Command reference-```+```text wt-command-referencewt step copy-ignored - Copy gitignored files to another worktreeEliminates cold starts by copying build caches and dependencies.@@ -742,7 +742,7 @@ feature/auth-oauth2### Command reference-```+```text wt-command-referencewt step eval - [experimental] Evaluate a template expressionPrints the result to stdout for use in scripts and shell substitutions.@@ -829,7 +829,7 @@ $ git fetch --prune && wt step for-each -- sh -c '[ "$(git rev-parse @{u} 2>/dev### Command reference-```+```text wt-command-referencewt step for-each - [experimental] Run command in each worktreeExecutes sequentially with real-time output; continues past command failures.@@ -917,7 +917,7 @@ The swap uses `rename()` for each entry — fast regardless of entry size, since### Command reference-```+```text wt-command-referencewt step promote - [experimental] Swap a branch into the main worktreeExchanges branches and gitignored files between two worktrees.@@ -1004,7 +1004,7 @@ $ wt step prune### Command reference-```+```text wt-command-referencewt step prune - [experimental] Remove worktrees merged into the default branchUsage: wt step prune [OPTIONS]@@ -1115,7 +1115,7 @@ refuses), unless `--commit` is passed.### Command reference-```+```text wt-command-referencewt step relocate - [experimental] Move worktrees to expected pathsRelocates worktrees whose path doesn't match the worktree-path template.@@ -1221,7 +1221,7 @@ server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"### Command reference-```+```text wt-command-referencewt step tether - [experimental] Run a command; kill its whole process tree when its worktree is removedTeardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.mdindex 3736f2b87..78e751503 100644--- a/docs/src/content/docs/switch.md+++ b/docs/src/content/docs/switch.md@@ -171,7 +171,7 @@ To change which branch a worktree is on, use `git switch` inside that worktree.## Command reference-```+```text wt-command-referencewt switch - Switch to a worktree; create if neededUsage: wt switch [OPTIONS] [BRANCH] [-- <EXECUTE_ARGS>...]diff --git a/docs/src/plugins/worktrunk-terminal.mjs b/docs/src/plugins/worktrunk-terminal.mjsindex c8d8f4d4f..aa15de7bf 100644--- a/docs/src/plugins/worktrunk-terminal.mjs+++ b/docs/src/plugins/worktrunk-terminal.mjs@@ -1,6 +1,9 @@import terminalStyles from '../generated/terminal-styles.json' with { type: 'json' };const terminalBlocks = new WeakMap();+const consoleBlocks = new WeakSet();+const commandReferenceBlocks = new WeakSet();+const commandReferenceMeta = 'wt-command-reference';const recordedTerminalBlocks = new Map(terminalStyles.map(({ plain, lines }) => [plain, lines]),);@@ -85,7 +88,6 @@ export function semanticOutputSegments(text) {function renderSemanticOutput(lineAst, text) {const segments = semanticOutputSegments(text);- if (!segments.some(({ tone }) => tone)) return;const code = findCodeElement(lineAst);if (!code) return;code.children = segments.map(({ text: value, tone }) => tone@@ -112,56 +114,120 @@ function renderRecordedOutput(lineAst, segments) {return true;}-function shellCommentIndex(text) {- let quote;- let escaped = false;- for (let index = 0; index < text.length; index += 1) {- const character = text[index];- if (escaped) {- escaped = false;- continue;- }- if (character === '\\' && quote !== "'") {- escaped = true;- continue;- }- if (character === quote) {- quote = undefined;- continue;- }- if (!quote && (character === "'" || character === '"')) {- quote = character;- continue;- }- if (!quote && character === '#' && (index === 0 || /\s/u.test(text[index - 1]))) {- return index;- }+function appendSegment(segments, text, tone) {+ if (!text) return;+ const previous = segments.at(-1);+ if (previous && previous.tone === tone) {+ previous.text += text;+ } else {+ segments.push(tone ? { text, tone } : { text });}- return -1;}-function renderCommand(lineAst, text) {+function helpInlineSegments(text) {+ const segments = [];+ const tokenPattern = /\[[^\]\n]+:\s*[^\]\n]+\]|\[experimental\]|--[a-z0-9][a-z0-9-]*(?:\.\.\.)?|(?<![\w-])-[A-Za-z](?=[,\s]|$)|<[^>\n]+>(?:\.\.\.)?|\[[A-Z][A-Z0-9_-]*\](?:\.\.\.)?/gu;+ let cursor = 0;+ for (const match of text.matchAll(tokenPattern)) {+ appendSegment(segments, text.slice(cursor, match.index));+ const token = match[0];+ const tone = token.startsWith('-')+ ? 'option'+ : token === '[experimental]' || (token.startsWith('[') && token.includes(':'))+ ? 'meta'+ : 'value';+ appendSegment(segments, token, tone);+ cursor = match.index + token.length;+ }+ appendSegment(segments, text.slice(cursor));+ return segments;+}++/** Parse the stable clap help grammar into semantic syntax roles. */+export function commandReferenceSegments(text) {+ const commandHeader = text.match(/^(wt(?: [a-z][\w-]*)*) - (.+)$/u);+ if (commandHeader) {+ return [+ { text: commandHeader[1], tone: 'command' },+ { text: ' - ' },+ ...helpInlineSegments(commandHeader[2]),+ ];+ }++ const sectionHeading = text.match(/^([A-Z][A-Za-z ]+):$/u);+ if (sectionHeading) return [{ text, tone: 'heading' }];++ const nestedHeading = text.match(/^(\s+)([A-Z][A-Za-z ]+:)$/u);+ if (nestedHeading) {+ return [+ { text: nestedHeading[1] },+ { text: nestedHeading[2], tone: 'meta' },+ ];+ }++ const possibleValue = text.match(/^(\s+- )([^:\s]+)(?::(.*))?$/u);+ if (possibleValue) {+ return [+ { text: possibleValue[1] },+ { text: possibleValue[2], tone: 'value' },+ ...(possibleValue[3] === undefined+ ? []+ : [{ text: ':' }, ...helpInlineSegments(possibleValue[3])]),+ ];+ }++ const usage = text.match(/^(Usage:)(\s+)(wt(?: [a-z][\w-]*)*)(.*)$/u);+ if (usage) {+ return [+ { text: usage[1], tone: 'heading' },+ { text: usage[2] },+ { text: usage[3], tone: 'command' },+ ...helpInlineSegments(usage[4]),+ ];+ }++ const usageContinuation = text.match(/^(\s+)(wt(?: [a-z][\w-]*)*)(\s+(?:\[|<).*)$/u);+ if (usageContinuation) {+ return [+ { text: usageContinuation[1] },+ { text: usageContinuation[2], tone: 'command' },+ ...helpInlineSegments(usageContinuation[3]),+ ];+ }++ const subcommand = text.match(/^(\s+)([a-z][\w-]*)(\s{2,})(.+)$/u);+ if (subcommand) {+ return [+ { text: subcommand[1] },+ { text: subcommand[2], tone: 'command' },+ { text: subcommand[3] },+ ...helpInlineSegments(subcommand[4]),+ ];+ }++ return helpInlineSegments(text);+}++function renderCommandReference(lineAst, text) {const code = findCodeElement(lineAst);if (!code) return;- const commentIndex = shellCommentIndex(text);- const command = commentIndex === -1 ? text : text.slice(0, commentIndex);- const comment = commentIndex === -1 ? '' : text.slice(commentIndex);- code.children = [- {- type: 'element',- tagName: 'span',- properties: { className: ['wt-command-text'] },- children: [{ type: 'text', value: command }],- },- ];- if (comment) {- code.children.push({- type: 'element',- tagName: 'span',- properties: { className: ['wt-terminal-dim'] },- children: [{ type: 'text', value: comment }],- });+ const leadingSpaces = text.match(/^ */u)?.[0].length ?? 0;+ if (leadingSpaces > 0) {+ const indentLevel = leadingSpaces <= 2 ? 1 : leadingSpaces <= 7 ? 2 : 3;+ addClass(lineAst, `wt-help-indent-${indentLevel}`);}+ const segments = commandReferenceSegments(text);+ if (leadingSpaces > 0 && segments[0]) {+ segments[0].text = segments[0].text.slice(leadingSpaces);+ }+ code.children = segments.map(({ text: value, tone }) => tone+ ? {+ type: 'element',+ tagName: 'span',+ properties: { className: [`wt-help-${tone}`] },+ children: [{ type: 'text', value }],+ }+ : { type: 'text', value });}/**@@ -177,15 +243,11 @@ export function pluginWorktrunkTerminal() {color: var(--wt-ink-muted);user-select: none;}- .expressive-code .frame.is-terminal .wt-command-text {- color: var(--wt-copper);- font-weight: 550;- }.expressive-code .frame.is-terminal .ec-line.wt-output .code {- color: var(--sl-color-gray-2);+ color: var(--wt-terminal-ink);}.expressive-code .frame.is-terminal .ec-line.wt-copyable .code {- color: var(--sl-color-gray-3);+ color: var(--wt-terminal-dim);}.expressive-code .frame.is-terminal .wt-positive {color: var(--sl-color-green-high);@@ -227,7 +289,26 @@ export function pluginWorktrunkTerminal() {font-weight: 600;}.expressive-code .frame.is-terminal .wt-terminal-dim {- opacity: 0.9;+ color: var(--wt-terminal-dim);+ opacity: 1;+ }+ .expressive-code .frame.is-terminal .wt-terminal-red.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-red) 62%, var(--wt-terminal-dim));+ }+ .expressive-code .frame.is-terminal .wt-terminal-green.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-green) 62%, var(--wt-terminal-dim));+ }+ .expressive-code .frame.is-terminal .wt-terminal-yellow.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-yellow) 62%, var(--wt-terminal-dim));+ }+ .expressive-code .frame.is-terminal .wt-terminal-blue.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-blue) 62%, var(--wt-terminal-dim));+ }+ .expressive-code .frame.is-terminal .wt-terminal-magenta.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-magenta) 62%, var(--wt-terminal-dim));+ }+ .expressive-code .frame.is-terminal .wt-terminal-cyan.wt-terminal-dim {+ color: color-mix(in srgb, var(--wt-terminal-cyan) 62%, var(--wt-terminal-dim));}.expressive-code .frame.is-terminal .wt-terminal-italic {font-style: italic;@@ -236,10 +317,59 @@ export function pluginWorktrunkTerminal() {text-decoration: underline;text-underline-offset: 0.14em;}+ .expressive-code .frame.wt-command-reference .wt-help-heading {+ color: var(--wt-copper);+ font-weight: 650;+ }+ .expressive-code .frame.wt-command-reference .wt-help-command {+ color: var(--wt-code-command);+ font-weight: 600;+ }+ .expressive-code .frame.wt-command-reference .wt-help-option {+ color: var(--wt-code-option);+ }+ .expressive-code .frame.wt-command-reference .wt-help-value {+ color: var(--wt-code-string);+ }+ .expressive-code .frame.wt-command-reference .wt-help-meta {+ color: var(--wt-terminal-dim);+ font-style: italic;+ }+ .expressive-code .frame.wt-command-reference .wt-help-indent-1 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 2ch);+ }+ .expressive-code .frame.wt-command-reference .wt-help-indent-2 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 6ch);+ }+ .expressive-code .frame.wt-command-reference .wt-help-indent-3 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 9ch);+ }+ @media (max-width: 42rem) {+ .expressive-code .frame.wt-command-reference .wt-help-indent-1 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 1ch);+ }+ .expressive-code .frame.wt-command-reference .wt-help-indent-2 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 2ch);+ }+ .expressive-code .frame.wt-command-reference .wt-help-indent-3 .code {+ padding-inline-start: calc(var(--ec-codePadInl) + 3ch);+ }+ }`,hooks: {+ preprocessLanguage({ codeBlock }) {+ if (codeBlock.language === 'console') {+ consoleBlocks.add(codeBlock);+ codeBlock.language = 'bash';+ codeBlock.props.frame = 'terminal';+ return;+ }+ if (codeBlock.metaOptions.value(commandReferenceMeta) === true) {+ commandReferenceBlocks.add(codeBlock);+ }+ },preprocessCode({ codeBlock }) {- if (codeBlock.language !== 'console') return;+ if (!consoleBlocks.has(codeBlock)) return;const lines = [...codeBlock.getLines()];const commandLines = new Set();@@ -273,6 +403,11 @@ export function pluginWorktrunkTerminal() {});},postprocessRenderedLine({ codeBlock, line, lineIndex, renderData }) {+ if (commandReferenceBlocks.has(codeBlock)) {+ addClass(renderData.lineAst, 'wt-help-line');+ renderCommandReference(renderData.lineAst, line?.text ?? '');+ return;+ }const terminal = terminalBlocks.get(codeBlock);if (!terminal) return;const className = terminal.commandLines.has(lineIndex)@@ -282,9 +417,7 @@ export function pluginWorktrunkTerminal() {: 'wt-output';addClass(renderData.lineAst, className);const text = line?.text ?? codeBlock.getLines()[lineIndex].text;- if (className === 'wt-command') {- renderCommand(renderData.lineAst, text);- } else if (className === 'wt-output') {+ if (className === 'wt-output') {const rendered = terminal.recordedByLine.has(lineIndex)&& renderRecordedOutput(renderData.lineAst, terminal.recordedByLine.get(lineIndex));if (!rendered) renderSemanticOutput(renderData.lineAst, text);@@ -292,6 +425,9 @@ export function pluginWorktrunkTerminal() {},postprocessRenderedBlock({ codeBlock, renderData }) {removeTitlelessHeader(renderData.blockAst);+ if (commandReferenceBlocks.has(codeBlock)) {+ addClass(renderData.blockAst, 'wt-command-reference');+ }const terminal = terminalBlocks.get(codeBlock);if (!terminal) {if (renderData.blockAst.properties?.className?.includes('is-terminal')) {diff --git a/docs/src/styles/custom.css b/docs/src/styles/custom.cssindex e613d559e..2d99353f2 100644--- a/docs/src/styles/custom.css+++ b/docs/src/styles/custom.css@@ -19,6 +19,11 @@--wt-terminal-magenta: #7e22ce;--wt-terminal-cyan: #0f6f73;--wt-terminal-gutter: #a8a29e;+ --wt-terminal-ink: #403a35;+ --wt-terminal-dim: #756b62;+ --wt-code-command: #9b6500;+ --wt-code-string: #527a16;+ --wt-code-option: #1d4ed8;--wt-focus: var(--wt-copper);--wt-font-display: 'Newsreader', ui-serif, 'Iowan Old Style', 'Palatino Linotype', Palatino,Georgia, serif;@@ -66,6 +71,11 @@--wt-terminal-magenta: #d8b4fe;--wt-terminal-cyan: #67d4d4;--wt-terminal-gutter: #6b7280;+ --wt-terminal-ink: #dedbd7;+ --wt-terminal-dim: #9f9488;+ --wt-code-command: #e5b567;+ --wt-code-string: #a3be8c;+ --wt-code-option: #93c5fd;--sl-color-accent-low: var(--wt-gold-wash);--sl-color-accent: var(--wt-copper);--sl-color-accent-high: #fcd34d;@@ -475,7 +485,7 @@ header.header {}}-/* Code is content, not a simulated application window. */+/* Code is content, while file excerpts keep the label of the artifact shown. */.expressive-code .frame {max-width: 100%;min-width: 0;@@ -493,6 +503,45 @@ header.header {-webkit-overflow-scrolling: touch;}+.expressive-code .frame.has-title .header {+ align-items: end;+ border: 0;+ border-radius: 0;+ padding: 0;+ background: transparent;+}++.expressive-code .frame.has-title .title {+ width: auto;+ max-width: calc(100% - 1.2rem);+ margin-inline-start: 0.6rem;+ overflow: hidden;+ border: 1px solid var(--wt-line);+ border-block-end: 0;+ border-radius: 0.28rem 0.28rem 0 0;+ padding: 0.32rem 0.68rem 0.38rem;+ background: var(--wt-paper-soft);+ color: var(--wt-craft);+ font-family: var(--sl-font-mono);+ font-size: 0.72rem;+ font-weight: 500;+ letter-spacing: 0.01em;+ line-height: 1.35;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.expressive-code .frame.has-title pre {+ border: 1px solid var(--wt-line);+ border-inline-start: 3px solid var(--wt-copper);+ box-shadow: 0 0.2rem 0.75rem color-mix(in srgb, var(--wt-ink) 7%, transparent);+}++.expressive-code .frame.wt-command-reference pre {+ border-inline-start-width: 3px;+ border-inline-start-color: var(--wt-craft);+}+.sl-markdown-content table:not(.cmd-compare):not(:where(.not-content *)) {overscroll-behavior-inline: contain;-webkit-overflow-scrolling: touch;diff --git a/docs/src/themes/worktrunk-code.mjs b/docs/src/themes/worktrunk-code.mjsnew file mode 100644index 000000000..dec3daa8d--- /dev/null+++ b/docs/src/themes/worktrunk-code.mjs@@ -0,0 +1,109 @@+const baseTokenColors = (palette) => [+ {+ settings: {+ background: palette.background,+ foreground: palette.foreground,+ },+ },+ {+ name: 'Comments',+ scope: ['comment', 'punctuation.definition.comment'],+ settings: {+ foreground: palette.comment,+ fontStyle: 'italic',+ },+ },+ {+ name: 'Keywords',+ scope: ['keyword', 'storage'],+ settings: {+ foreground: palette.keyword,+ fontStyle: 'bold',+ },+ },+ {+ name: 'Functions',+ scope: ['entity.name.function', 'meta.function-call', 'support.function.any-method'],+ settings: {+ foreground: palette.function,+ fontStyle: 'bold',+ },+ },+ {+ name: 'Strings',+ scope: ['string', 'constant.other.symbol', 'entity.other.inherited-class'],+ settings: { foreground: palette.string },+ },+ {+ name: 'Variables',+ scope: ['variable', 'support.class', 'entity.name.class', 'entity.name.type.class'],+ settings: { foreground: palette.variable },+ },+ {+ name: 'Constants',+ scope: ['constant', 'constant.numeric'],+ settings: { foreground: palette.constant },+ },+ {+ name: 'Support',+ scope: ['support.function', 'entity.name.tag', 'entity.other.attribute-name'],+ settings: { foreground: palette.support },+ },+ {+ name: 'Operators',+ scope: ['keyword.operator', 'punctuation.definition.variable', 'punctuation.definition.parameters'],+ settings: { foreground: palette.operator },+ },+ {+ name: 'Markup',+ scope: ['markup.heading', 'markup.raw.inline', 'markup.inserted'],+ settings: { foreground: palette.function },+ },+ {+ name: 'Invalid and deleted',+ scope: ['invalid', 'markup.deleted'],+ settings: { foreground: palette.invalid },+ },+];++function theme(name, type, palette) {+ return {+ name,+ type,+ colors: {+ 'editor.background': palette.background,+ 'editor.foreground': palette.foreground,+ },+ tokenColors: baseTokenColors(palette),+ };+}++// These are the syntax roles from the pre-Astro Worktrunk themes, adjusted only+// where the old foregrounds did not meet contrast on the current code surface.+export const worktrunkLightCodeTheme = theme('worktrunk-light', 'light', {+ background: '#f8f7f6',+ foreground: '#3d3632',+ comment: '#6d6258',+ keyword: '#9f4f2a',+ function: '#9b6500',+ string: '#527a16',+ variable: '#7e6247',+ constant: '#a03c15',+ support: '#9f4f2a',+ operator: '#3d3632',+ invalid: '#a03c15',+});++export const worktrunkDarkCodeTheme = theme('worktrunk-dark', 'dark', {+ background: '#252321',+ foreground: '#d8d4cf',+ comment: '#a8a29e',+ keyword: '#d8b4fe',+ function: '#e5b567',+ string: '#a3be8c',+ variable: '#d9a0a5',+ constant: '#e09a82',+ support: '#67d4d4',+ operator: '#d8d4cf',+ invalid: '#f87171',+});diff --git a/docs/tests/browser-site.test.mjs b/docs/tests/browser-site.test.mjsindex 2ae3ae00e..9c10c2b1c 100644--- a/docs/tests/browser-site.test.mjs+++ b/docs/tests/browser-site.test.mjs@@ -51,6 +51,30 @@ async function sitemapRoutes() {.map((match) => new URL(match[1]).pathname);}+function rgbChannels(value) {+ const channels = value.match(/[\d.]+/gu).slice(0, 3).map(Number);+ return value.startsWith('color(srgb')+ ? channels.map((channel) => channel * 255)+ : channels;+}++function relativeLuminance(value) {+ const linear = rgbChannels(value).map((channel) => {+ const normalized = channel / 255;+ return normalized <= 0.04045+ ? normalized / 12.92+ : ((normalized + 0.055) / 1.055) ** 2.4;+ });+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];+}++function contrastRatio(foreground, background) {+ const foregroundLuminance = relativeLuminance(foreground);+ const backgroundLuminance = relativeLuminance(background);+ return (Math.max(foregroundLuminance, backgroundLuminance) + 0.05)+ / (Math.min(foregroundLuminance, backgroundLuminance) + 0.05);+}+test('mobile pages stay viewport-bound while code remains readable', { timeout: 120_000 }, async () => {const browser = await webkit.launch();const publicRoutes = await sitemapRoutes();@@ -171,3 +195,125 @@ test('mobile pages stay viewport-bound while code remains readable', { timeout:await browser.close();}});++test('code artifacts keep their visual hierarchy in both themes', async () => {+ const browser = await webkit.launch();+ try {+ for (const theme of ['light', 'dark']) {+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, colorScheme: theme });++ await page.goto(`${baseUrl}/claude-code/`, { waitUntil: 'domcontentloaded' });+ await page.evaluate((selectedTheme) => {+ document.documentElement.dataset.theme = selectedTheme;+ }, theme);+ const commandStyles = await page.evaluate(() => {+ const frame = [...document.querySelectorAll('.expressive-code .frame')]+ .find((candidate) => candidate.textContent.includes(+ 'codex plugin marketplace add max-sixty/worktrunk',+ ));+ return {+ background: getComputedStyle(frame.querySelector('pre')).backgroundColor,+ tokens: [...frame.querySelectorAll('.code span')]+ .filter((span) => span.textContent.trim())+ .map((span) => ({+ text: span.textContent,+ color: getComputedStyle(span).color,+ })),+ };+ });+ assert.notEqual(+ commandStyles.tokens.find(({ text }) => text === 'codex').color,+ commandStyles.tokens.find(({ text }) => text === 'plugin').color,+ `${theme} shell command flattens the executable and arguments to one color`,+ );+ for (const { text, color } of commandStyles.tokens) {+ const ratio = contrastRatio(color, commandStyles.background);+ assert.ok(ratio >= 4.5, `${theme} shell token ${text} contrast is ${ratio.toFixed(2)}:1`);+ }++ await page.goto(`${baseUrl}/list/`, { waitUntil: 'domcontentloaded' });+ await page.evaluate((selectedTheme) => {+ document.documentElement.dataset.theme = selectedTheme;+ }, theme);+ const listStyles = await page.evaluate(() => {+ const frame = [...document.querySelectorAll('.frame.is-terminal')]+ .find((candidate) => candidate.textContent.includes('feature-api'));+ const normal = frame.querySelector('.wt-output .code');+ const dim = frame.querySelector('.wt-terminal-dim:not(.wt-terminal-red)');+ return {+ normal: getComputedStyle(normal).color,+ dim: getComputedStyle(dim).color,+ dimOpacity: getComputedStyle(dim).opacity,+ commandColors: new Set(+ [...frame.querySelectorAll('.wt-command .code span')]+ .filter((span) => span.textContent.trim())+ .map((span) => getComputedStyle(span).color),+ ).size,+ };+ });+ assert.notEqual(listStyles.normal, listStyles.dim, `${theme} wt list dim text is not distinct`);+ assert.equal(listStyles.dimOpacity, '1', `${theme} wt list dim text relies on opacity`);+ assert.ok(listStyles.commandColors >= 2, `${theme} console command loses Bash syntax colors`);++ const referenceStyles = await page.evaluate(() => {+ const frame = document.querySelector('.frame.wt-command-reference');+ const roles = ['heading', 'command', 'option', 'value', 'meta'];+ return {+ present: Boolean(frame),+ background: getComputedStyle(frame.querySelector('pre')).backgroundColor,+ colors: roles.map((role) => getComputedStyle(+ frame.querySelector(`.wt-help-${role}`),+ ).color),+ };+ });+ assert.equal(referenceStyles.present, true, `${theme} command reference is not classified`);+ assert.equal(+ new Set(referenceStyles.colors).size,+ referenceStyles.colors.length,+ `${theme} command reference syntax roles collapse to the same color`,+ );+ for (const color of referenceStyles.colors) {+ const ratio = contrastRatio(color, referenceStyles.background);+ assert.ok(ratio >= 4.5, `${theme} help-role contrast is ${ratio.toFixed(2)}:1`);+ }++ await page.goto(`${baseUrl}/config/`, { waitUntil: 'domcontentloaded' });+ await page.evaluate((selectedTheme) => {+ document.documentElement.dataset.theme = selectedTheme;+ }, theme);+ const fileFrame = await page.evaluate(() => {+ const frame = [...document.querySelectorAll('.frame.has-title')]+ .find((candidate) => candidate.textContent.includes('~/.config/worktrunk/config.toml'));+ const title = frame.querySelector('.title');+ const pre = frame.querySelector('pre');+ return {+ title: title.textContent,+ titleBottom: title.getBoundingClientRect().bottom,+ codeTop: pre.getBoundingClientRect().top,+ titleFont: getComputedStyle(title).fontFamily,+ titleColor: getComputedStyle(title).color,+ titleBackground: getComputedStyle(title).backgroundColor,+ codeBackground: getComputedStyle(pre).backgroundColor,+ accentWidth: getComputedStyle(pre).borderInlineStartWidth,+ };+ });+ assert.equal(fileFrame.title, '~/.config/worktrunk/config.toml');+ assert.ok(fileFrame.titleFont.includes('JetBrains Mono'), `${theme} file label is not monospaced`);+ assert.ok(+ Math.abs(fileFrame.titleBottom - fileFrame.codeTop) < 1,+ `${theme} file label is detached from its code`,+ );+ assert.notEqual(+ fileFrame.titleBackground,+ fileFrame.codeBackground,+ `${theme} file label does not read separately from its code`,+ );+ const titleContrast = contrastRatio(fileFrame.titleColor, fileFrame.titleBackground);+ assert.ok(titleContrast >= 4.5, `${theme} file-label contrast is ${titleContrast.toFixed(2)}:1`);+ assert.equal(fileFrame.accentWidth, '3px');+ await page.close();+ }+ } finally {+ await browser.close();+ }+});diff --git a/docs/tests/built-site.test.mjs b/docs/tests/built-site.test.mjsindex 9eb22b7d8..e5d10d5c8 100644--- a/docs/tests/built-site.test.mjs+++ b/docs/tests/built-site.test.mjs@@ -186,7 +186,18 @@ test('build preserves the public route contract', async () => {assert.match(listPage, /<span class="wt-terminal-green">\+54<\/span>/);assert.match(listPage, /<span class="wt-terminal-red">-5<\/span>/);assert.match(listPage, /<span class="wt-terminal-blue wt-terminal-dim">#412<\/span>/);- assert.match(listPage, /<span class="wt-command-text">wt list<\/span>/);+ assert.match(+ listPage,+ /<div class="ec-line wt-command"><div class="code"><span[^>]*>wt<\/span><span[^>]*> <\/span><span[^>]*>list<\/span>/,+ );+ assert.match(listPage, /<figure class="frame wt-command-reference not-content">/);+ assert.match(listPage, /<span class="wt-help-heading">Usage:<\/span>/);+ assert.match(listPage, /<span class="wt-help-option">--format<\/span>/);+ assert.match(listPage, /<span class="wt-help-value">\[OPTIONS\]<\/span>/);+ assert.match(+ listPage,+ /<span class="wt-help-command">wt list<\/span> <span class="wt-help-value"><COMMAND><\/span>/,+ );const llmCommitsPage = await readFile(routeFile('/llm-commits/'), 'utf8');assert.match(llmCommitsPage, /<span class="wt-terminal-cyan">◎<\/span>/);@@ -196,6 +207,10 @@ test('build preserves the public route contract', async () => {);const configPage = await readFile(routeFile('/config/'), 'utf8');+ assert.match(+ configPage,+ /<figure class="frame has-title not-content"><figcaption class="header"><span class="title">~\/.config\/worktrunk\/config\.toml<\/span><\/figcaption>/,+ );const configToc = configPage.match(/<nav aria-labelledby="starlight__on-this-page">([\s\S]*?)<\/nav>/,)?.[1];@@ -251,6 +266,7 @@ test('built pages omit low-value footer navigation', async () => {test('nested command references expose unique search-only fragment titles', async () => {const stepPage = await readFile(routeFile('/step/'), 'utf8');+ assert.match(stepPage, /<span class="wt-help-value"><COMMAND>\.\.\.<\/span>/);assert.match(stepPage, /<h2 id="command-reference">Command reference<\/h2>/);const references = [...stepPage.matchAll(@@ -278,6 +294,41 @@ test('nested command references expose unique search-only fragment titles', asyn);});+test('every command reference receives semantic syntax roles', async () => {+ let headingCount = 0;+ let frameCount = 0;+ for (const page of renderedPages) {+ const html = await readFile(page, 'utf8');+ headingCount += [...html.matchAll(/>Command reference<\/h[23]>/g)].length;+ const frames = [...html.matchAll(+ /<figure class="frame wt-command-reference not-content">([\s\S]*?)<\/figure>/g,+ )];+ frameCount += frames.length;+ for (const [, frame] of frames) {+ const renderedCode = frame.match(/<code>([\s\S]*?)<\/code>/)?.[1] ?? '';+ assert.match(frame, /class="wt-help-command"/, `${page} leaves the command unstyled`);+ assert.match(frame, /class="wt-help-heading"/, `${page} leaves help headings unstyled`);+ assert.match(frame, /class="wt-help-(?:option|value)"/, `${page} leaves help syntax unstyled`);+ assert.doesNotMatch(+ frame,+ /<div class="code">- [^<]/,+ `${page} leaves a possible-value row unstyled`,+ );+ const experimentalCount = [...renderedCode.matchAll(/\[experimental\]/g)].length;+ const styledExperimentalCount = [+ ...renderedCode.matchAll(/class="wt-help-meta">\[experimental\]<\/span>/g),+ ].length;+ assert.equal(+ styledExperimentalCount,+ experimentalCount,+ `${page} leaves an experimental annotation unstyled`,+ );+ }+ }+ assert.ok(headingCount > 0, 'expected rendered command references');+ assert.equal(frameCount, headingCount, 'some command references remain plain code blocks');+});+test('built pages only reference emitted local assets', async () => {const files = new Set(await allFiles());diff --git a/docs/tests/plugins.test.mjs b/docs/tests/plugins.test.mjsindex aac46b21f..e32328730 100644--- a/docs/tests/plugins.test.mjs+++ b/docs/tests/plugins.test.mjs@@ -8,10 +8,17 @@ import {import { rehypePagefindCommandReferences } from '../src/plugins/pagefind-command-references.mjs';import { rehypeResponsiveTables } from '../src/plugins/responsive-tables.mjs';import {+ commandReferenceSegments,pluginWorktrunkTerminal,semanticOutputSegments,} from '../src/plugins/worktrunk-terminal.mjs';+function prepareCodeBlock(plugin, codeBlock) {+ codeBlock.props ??= {};+ plugin.hooks.preprocessLanguage({ codeBlock });+ plugin.hooks.preprocessCode({ codeBlock });+}+function markdownTable(headers, rows, { className, headerProperties } = {}) {const row = (tagName, values, properties = []) => ({type: 'element',@@ -225,7 +232,10 @@ test('console blocks separate copyable recipes from output', () => {}));const codeBlock = { language: 'console', getLines: () => lines };const plugin = pluginWorktrunkTerminal();- plugin.hooks.preprocessCode({ codeBlock });+ prepareCodeBlock(plugin, codeBlock);++ assert.equal(codeBlock.language, 'bash');+ assert.equal(codeBlock.props.frame, 'terminal');const classes = lines.map((_, lineIndex) => {const renderData = { lineAst: { properties: {} } };@@ -271,7 +281,7 @@ test('console output and its blank lines stay out of copied commands', () => {}));const codeBlock = { language: 'console', getLines: () => lines };const plugin = pluginWorktrunkTerminal();- plugin.hooks.preprocessCode({ codeBlock });+ prepareCodeBlock(plugin, codeBlock);const classes = lines.map((_, lineIndex) => {const renderData = { lineAst: { properties: {} } };@@ -355,11 +365,8 @@ test('console output retains state-color semantics without ANSI in Markdown', ());});-test('console commands distinguish commands from trailing shell comments', () => {- const lines = [- '$ wt switch "#412" # inspect the PR',- "$ printf '%s' '# literal'",- ].map((text) => ({+test('console commands retain syntax highlighter token spans', () => {+ const lines = ['$ wt switch "#412" # inspect the PR'].map((text) => ({text,editText(start, end, replacement) {this.text = this.text.slice(0, start) + replacement + this.text.slice(end);@@ -367,14 +374,28 @@ test('console commands distinguish commands from trailing shell comments', () =>}));const codeBlock = { language: 'console', getLines: () => lines };const plugin = pluginWorktrunkTerminal();- plugin.hooks.preprocessCode({ codeBlock });+ prepareCodeBlock(plugin, codeBlock);const rendered = lines.map((line, lineIndex) => {const code = {type: 'element',tagName: 'div',properties: { className: ['code'] },- children: [{ type: 'text', value: line.text }],+ children: [+ {+ type: 'element',+ tagName: 'span',+ properties: { style: '--0:#aaa;--1:#111' },+ children: [{ type: 'text', value: 'wt' }],+ },+ { type: 'text', value: ' switch "#412" ' },+ {+ type: 'element',+ tagName: 'span',+ properties: { style: '--0:#bbb;--1:#222' },+ children: [{ type: 'text', value: '# inspect the PR' }],+ },+ ],};const renderData = {lineAst: { type: 'element', tagName: 'div', properties: {}, children: [code] },@@ -388,23 +409,96 @@ test('console commands distinguish commands from trailing shell comments', () =>{type: 'element',tagName: 'span',- properties: { className: ['wt-command-text'] },- children: [{ type: 'text', value: 'wt switch "#412" ' }],+ properties: { style: '--0:#aaa;--1:#111' },+ children: [{ type: 'text', value: 'wt' }],},+ { type: 'text', value: ' switch "#412" ' },{type: 'element',tagName: 'span',- properties: { className: ['wt-terminal-dim'] },+ properties: { style: '--0:#bbb;--1:#222' },children: [{ type: 'text', value: '# inspect the PR' }],},],- [- {- type: 'element',- tagName: 'span',- properties: { className: ['wt-command-text'] },- children: [{ type: 'text', value: "printf '%s' '# literal'" }],- },- ],+ ]);+});++test('command references expose clap syntax roles', () => {+ const plugin = pluginWorktrunkTerminal();+ const markedBlock = {+ language: 'text',+ metaOptions: { value: (key) => (key === 'wt-command-reference' ? true : undefined) },+ };+ const plainBlock = {+ language: 'text',+ metaOptions: { value: () => undefined },+ };+ plugin.hooks.preprocessLanguage({ codeBlock: markedBlock });+ plugin.hooks.preprocessLanguage({ codeBlock: plainBlock });+ for (const [codeBlock, expected] of [[markedBlock, true], [plainBlock, false]]) {+ const blockAst = { properties: { className: ['frame'] }, children: [] };+ plugin.hooks.postprocessRenderedBlock({ codeBlock, renderData: { blockAst } });+ assert.equal(blockAst.properties.className.includes('wt-command-reference'), expected);+ }++ assert.deepEqual(commandReferenceSegments('Usage: wt list [OPTIONS] <COMMAND>'), [+ { text: 'Usage:', tone: 'heading' },+ { text: ' ' },+ { text: 'wt list', tone: 'command' },+ { text: ' ' },+ { text: '[OPTIONS]', tone: 'value' },+ { text: ' ' },+ { text: '<COMMAND>', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments(' wt list <COMMAND>'), [+ { text: ' ' },+ { text: 'wt list', tone: 'command' },+ { text: ' ' },+ { text: '<COMMAND>', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments(' --format <FORMAT>'), [+ { text: ' ' },+ { text: '--format', tone: 'option' },+ { text: ' ' },+ { text: '<FORMAT>', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments(' [default: table]'), [+ { text: ' ' },+ { text: '[default: table]', tone: 'meta' },+ ]);+ assert.deepEqual(commandReferenceSegments(' [EXTRA_ARGS]...'), [+ { text: ' ' },+ { text: '[EXTRA_ARGS]...', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments(' <COMMAND>...'), [+ { text: ' ' },+ { text: '<COMMAND>...', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments(' Possible values:'), [+ { text: ' ' },+ { text: 'Possible values:', tone: 'meta' },+ ]);+ assert.deepEqual(commandReferenceSegments(' - all: Stage everything'), [+ { text: ' - ' },+ { text: 'all', tone: 'value' },+ { text: ':' },+ { text: ' Stage everything' },+ ]);+ assert.deepEqual(commandReferenceSegments(' - json'), [+ { text: ' - ' },+ { text: 'json', tone: 'value' },+ ]);+ assert.deepEqual(commandReferenceSegments('wt step eval - [experimental] Evaluate a template'), [+ { text: 'wt step eval', tone: 'command' },+ { text: ' - ' },+ { text: '[experimental]', tone: 'meta' },+ { text: ' Evaluate a template' },+ ]);+ assert.deepEqual(commandReferenceSegments(' eval [experimental] Evaluate a template'), [+ { text: ' ' },+ { text: 'eval', tone: 'command' },+ { text: ' ' },+ { text: '[experimental]', tone: 'meta' },+ { text: ' Evaluate a template' },]);});diff --git a/src/help.rs b/src/help.rsindex c7d09b487..799f8dce9 100644--- a/src/help.rs+++ b/src/help.rs@@ -92,6 +92,15 @@ impl PageMode {}}+ /// Opening fence for generated command references. The web marker gives+ /// the renderer explicit ownership; plain skill pages stay portable.+ fn command_reference_fence(self) -> &'static str {+ match self {+ Self::Web => "```text wt-command-reference",+ Self::Plain => "```",+ }+ }+/// Emit the page header — an auto-generated comment for web (sync test/// uses it as a region marker), or an H1 title for plain skill pages.fn emit_header(self, subcommand: &str) {@@ -435,7 +444,7 @@ Commands with schemas: list"////// ## Command reference///-/// ```bash+/// ```text wt-command-reference/// wt merge — .../// Usage: .../// ```@@ -485,7 +494,7 @@ Commands with pages: merge, switch, remove, list"// Main command reference immediately after its contentprintln!("## Command reference");println!();- println!("```");+ println!("{}", mode.command_reference_fence());println!("{}", reference_block.trim());println!("```");@@ -748,7 +757,9 @@ fn format_subcommand_section(}// Command reference comes after main content but before nested subdocs- section.push_str("### Command reference\n\n```\n");+ section.push_str("### Command reference\n\n");+ section.push_str(mode.command_reference_fence());+ section.push('\n');section.push_str(reference_block.trim());section.push_str("\n```\n");diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsindex 033ad32c9..82b0a9296 100644--- a/tests/integration_tests/readme_sync.rs+++ b/tests/integration_tests/readme_sync.rs@@ -1730,6 +1730,27 @@ const COMMAND_PAGES: &[&str] = &["switch", "list", "merge", "remove", "config", "step", "hook",];+#[test]+fn test_command_references_use_explicit_fences() {+ let project_root = Path::new(env!("CARGO_MANIFEST_DIR"));+ for command in COMMAND_PAGES {+ let path = project_root.join(format!("docs/src/content/docs/{command}.md"));+ let content = fs::read_to_string(&path)+ .unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));+ let headings = content.matches("Command reference\n\n").count();+ let marked_fences = content+ .matches("Command reference\n\n```text wt-command-reference\n")+ .count();+ assert!(headings > 0, "{} has no command references", path.display());+ assert_eq!(+ marked_fences,+ headings,+ "{} has an unmarked command-reference fence",+ path.display(),+ );+ }+}+/// Hand-edited site pages whose snapshot markers are refreshed by this test.const STANDALONE_DOC_FILES: &[&str] = &["docs/src/content/docs/worktrunk.md",