Skip to content

The agent that grows with you

fix(website): cross-page doc links resolve on GitHub as well as on the site

teknium136fb2be9267c
diff --git a/.github/workflows/docs-site-checks.yml b/.github/workflows/docs-site-checks.yml
index 1e82698218e..8a3e71ef2a5 100644
--- a/.github/workflows/docs-site-checks.yml
+++ b/.github/workflows/docs-site-checks.yml
@@ -44,6 +44,9 @@ jobs:
- name: Regenerate per-skill docs pages + catalogs
run: python3 website/scripts/generate-skill-docs.py
+ - name: Check cross-page links resolve on GitHub and on the site
+ run: python3 website/scripts/check_doc_links.py
+
- name: Lint docs diagrams
run: npm run lint:diagrams
working-directory: website
diff --git a/tests/website/test_check_doc_links.py b/tests/website/test_check_doc_links.py
new file mode 100644
index 00000000000..21face2e0da
--- /dev/null
+++ b/tests/website/test_check_doc_links.py
@@ -0,0 +1,61 @@
+"""Tests for website/scripts/check_doc_links.py.
+
+Cross-page links in hand-authored docs must be relative Markdown paths so they
+resolve on GitHub's file viewer as well as on the rendered site (#114428).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+CHECKER = REPO_ROOT / "website" / "scripts" / "check_doc_links.py"
+
+
[email protected](scope="module")
+def checker():
+ spec = importlib.util.spec_from_file_location("check_doc_links", CHECKER)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_hand_authored_docs_have_no_route_style_links(checker):
+ """The live tree stays clean: every route-style link 404s on GitHub."""
+ assert checker.main(["--en-only"]) == 0
+
+
+def test_fix_rewrites_route_to_relative_path_keeping_anchor(checker, tmp_path, monkeypatch):
+ docs = tmp_path / "docs"
+ (docs / "getting-started").mkdir(parents=True)
+ (docs / "user-guide" / "features").mkdir(parents=True)
+ (docs / "user-guide" / "features" / "skills.md").write_text("# Skills\n", encoding="utf-8")
+ (docs / "user-guide" / "features" / "index.md").write_text("# Features\n", encoding="utf-8")
+ src = docs / "getting-started" / "learning-path.md"
+ src.write_text(
+ "[Skills](/user-guide/features/skills#bundles) [Docs](/docs/user-guide/features)\n"
+ "[Site page](/skills) [Same](./quickstart.md)\n"
+ "```\n[example](/user-guide/features/skills)\n```\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(checker, "EN_DOCS", docs)
+ monkeypatch.setattr(checker, "ZH_DOCS", tmp_path / "missing")
+
+ assert checker.main([]) == 1
+ assert checker.main(["--fix"]) == 0
+ text = src.read_text(encoding="utf-8")
+ assert "[Skills](../user-guide/features/skills.md#bundles)" in text
+ assert "[Docs](../user-guide/features/index.md)" in text
+ # Non-doc routes and fenced examples are left alone.
+ assert "[Site page](/skills)" in text
+ assert "```\n[example](/user-guide/features/skills)\n```" in text
+ assert checker.main([]) == 0
+
+ # A route that maps to no file is an error, not a silent rewrite.
+ src.write_text("[Gone](/user-guide/nope)\n", encoding="utf-8")
+ assert checker.main(["--fix"]) == 1
+ assert src.read_text(encoding="utf-8") == "[Gone](/user-guide/nope)\n"
diff --git a/website/README.md b/website/README.md
index b22ff47a88f..cd074109229 100644
--- a/website/README.md
+++ b/website/README.md
@@ -3,19 +3,23 @@
This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
> **Reading the docs on GitHub?** The Markdown under `docs/` is authored for the rendered site at
-> <https://hermes-agent.nousresearch.com/docs/>. Most cross-page links are Docusaurus site routes
-> (`/getting-started/installation`), which GitHub's file viewer resolves as repository paths and 404s.
-> Every page has an **Edit this page** link on the site that opens the source file here.
+> <https://hermes-agent.nousresearch.com/docs/>. Cross-page links are relative Markdown paths, so they
+> follow through on GitHub's file viewer too. Every page on the site has an **Edit this page** link
+> that opens the source file here.
## Authoring links in `docs/`
-- Link to another page with a doc-root route (`[Profiles](/user-guide/profiles)`) or a relative
- Markdown path (`[Profiles](../user-guide/profiles.md)`). Both render on the site; only the
- relative form also resolves on GitHub.
-- Never write `/docs/...` in a link: `baseUrl` is already `/docs/`, so the zh-Hans build emits
- `/docs/zh-Hans/docs/...` 404s.
-- Cross-section links with an anchor use the route form (`/section/page#anchor`); pin `{#anchor}`
- on the target heading so the zh-Hans mirror keeps the same id.
+- Link to another page with a relative Markdown path, anchors included:
+ `[Profiles](../user-guide/profiles.md)`, `[Bundles](../user-guide/features/skills.md#skill-bundles)`.
+ Docusaurus turns the file path into the page route; GitHub follows the same path. Site routes
+ (`/user-guide/profiles`, `/docs/user-guide/profiles`) only work on the rendered site — GitHub
+ resolves them as repository paths and 404s, and the `/docs/` form also emits
+ `/docs/zh-Hans/docs/...` 404s in the zh-Hans build because `baseUrl` is already `/docs/`.
+- `python3 website/scripts/check_doc_links.py` fails on any route-style link in hand-authored pages
+ (EN and the zh-Hans mirror); `--fix` rewrites them. It runs in the `Docs Site Checks` workflow.
+ Generated pages (`user-guide/skills/{bundled,optional}`, `reference/*skills-catalog.md`) are
+ produced by `scripts/generate-skill-docs.py`, which emits the same relative form.
+- Pin `{#anchor}` on cross-linked headings so the zh-Hans mirror keeps the same id.
## Installation
diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts
index 4963c548708..cb82b8e85ec 100644
--- a/website/docusaurus.config.ts
+++ b/website/docusaurus.config.ts
@@ -1,6 +1,7 @@
import {themes as prismThemes} from 'prism-react-renderer';
import type {Config} from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
+import relativeDocLinks from './src/remark/relativeDocLinks';
const config: Config = {
title: 'Hermes Agent',
@@ -81,6 +82,9 @@ const config: Config = {
routeBasePath: '/', // Docs at the root of /docs/
sidebarPath: './sidebars.ts',
editUrl: 'https://github.com/NousResearch/hermes-agent/edit/main/website/',
+ // Relative `.md` links (readable on GitHub, #114428) must also resolve
+ // across the zh-Hans fallback boundary; see src/remark/relativeDocLinks.js.
+ beforeDefaultRemarkPlugins: [[relativeDocLinks, {siteDir: __dirname}]],
},
blog: false,
theme: {
diff --git a/website/scripts/check_doc_links.py b/website/scripts/check_doc_links.py
new file mode 100644
index 00000000000..9c5dc5df4aa
--- /dev/null
+++ b/website/scripts/check_doc_links.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+"""Keep cross-page links in website/docs resolvable on GitHub AND on the site.
+
+Docusaurus turns a relative Markdown file link (`../user-guide/profiles.md#anchor`)
+into the page route, and GitHub's file viewer follows the same path. A site
+route written as a link (`/user-guide/profiles`, `/docs/user-guide/profiles`)
+only works on the rendered site: GitHub resolves it as a repository path and
+404s (issue #114428).
+
+Check mode (default) lists every route-style link in hand-authored pages and
+exits 1 when any exist. `--fix` rewrites them in place to relative file links,
+preserving `#anchor`, and fails on a route that does not map to a doc file.
+
+Exempt, in both modes:
+- generated pages (per-skill pages and the skills catalogs produced by
+ generate-skill-docs.py; the generator itself emits relative links);
+- routes that are not docs: `/skills`, `/plugins` (React pages), `/img/...`,
+ `/llms*.txt`, `/api/...` (static assets).
+
+Usage:
+ python3 website/scripts/check_doc_links.py # lint EN + zh-Hans
+ python3 website/scripts/check_doc_links.py --fix # rewrite in place
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+from pathlib import Path
+
+WEBSITE = Path(__file__).resolve().parents[1]
+EN_DOCS = WEBSITE / "docs"
+ZH_DOCS = WEBSITE / "i18n" / "zh-Hans" / "docusaurus-plugin-content-docs" / "current"
+
+# Written by generate-skill-docs.py; edit the generator, never these outputs.
+GENERATED_PREFIXES = ("user-guide/skills/bundled/", "user-guide/skills/optional/")
+GENERATED_FILES = {"reference/skills-catalog.md", "reference/optional-skills-catalog.md"}
+
+# Site routes that are not documents: React pages and static assets.
+NON_DOC_ROUTE_PREFIXES = ("/skills", "/plugins", "/img/", "/llms", "/api/")
+
+LINK_RE = re.compile(r"\]\((/[^)\s]*)\)")
+FENCE_RE = re.compile(r"^\s*(```|~~~)")
+
+
+def is_generated(rel: str) -> bool:
+ return rel.startswith(GENERATED_PREFIXES) or rel in GENERATED_FILES
+
+
+def frontmatter_slug(text: str) -> str | None:
+ if not text.startswith("---"):
+ return None
+ end = text.find("\n---", 3)
+ if end < 0:
+ return None
+ m = re.search(r"^slug:\s*(\S+)\s*$", text[3:end], re.MULTILINE)
+ return m.group(1).strip("'\"") if m else None
+
+
+def route_for(rel: str, text: str) -> str:
+ """Docusaurus route (relative to the docs root) for a source file."""
+ slug = frontmatter_slug(text)
+ if slug and slug.startswith("/"):
+ return slug.rstrip("/") or "/"
+ stem = re.sub(r"\.mdx?$", "", rel)
+ if stem == "index":
+ return "/"
+ if stem.endswith("/index"):
+ stem = stem[: -len("/index")]
+ return "/" + stem
+
+
+def route_map(docs_root: Path) -> dict[str, Path]:
+ routes: dict[str, Path] = {}
+ for path in sorted(docs_root.rglob("*.md*")):
+ if path.suffix not in (".md", ".mdx"):
+ continue
+ rel = path.relative_to(docs_root).as_posix()
+ routes[route_for(rel, path.read_text(encoding="utf-8"))] = path
+ return routes
+
+
+def normalize_route(target: str) -> tuple[str, str]:
+ """Split a link target into (route, suffix) where suffix is `#anchor`/`?q`."""
+ suffix = ""
+ cut = min((i for i in (target.find("#"), target.find("?")) if i >= 0), default=-1)
+ if cut >= 0:
+ target, suffix = target[:cut], target[cut:]
+ if target.startswith("/docs/"):
+ target = target[len("/docs") :]
+ elif target == "/docs":
+ target = "/"
+ if len(target) > 1:
+ target = target.rstrip("/")
+ return target, suffix
+
+
+def relative_link(source: Path, source_root: Path, target: Path, target_root: Path) -> str:
+ """Path from `source` to `target`, expressed inside the source's own tree.
+
+ zh-Hans pages fall back to the EN file when no translation exists; the
+ relative path is computed as if the target sat in the same tree, which is
+ how both Docusaurus (locale content paths) and GitHub (EN files) resolve it.
+ """
+ target_rel = target.relative_to(target_root)
+ virtual_target = source_root / target_rel
+ rel = Path(os.path.relpath(virtual_target, source.parent)).as_posix()
+ return rel if rel.startswith(".") else "./" + rel
+
+
+def iter_links(text: str):
+ """Yield (line_no, match) for markdown links outside fenced code blocks."""
+ in_fence = False
+ for line_no, line in enumerate(text.splitlines(), 1):
+ if FENCE_RE.match(line):
+ in_fence = not in_fence
+ continue
+ if in_fence:
+ continue
+ for m in LINK_RE.finditer(line):
+ # Skip links quoted inside inline code (`[x](/y)` examples).
+ if line[: m.start()].count("`") % 2 == 1:
+ continue
+ yield line_no, m
+
+
+def process_tree(
+ docs_root: Path,
+ en_routes: dict[str, Path],
+ fix: bool,
+ include_generated: bool,
+) -> tuple[list[str], list[str], int]:
+ """Return (route_style_findings, unresolved_findings, files_rewritten)."""
+ local_routes = route_map(docs_root) if docs_root != EN_DOCS else en_routes
+ findings: list[str] = []
+ unresolved: list[str] = []
+ rewritten = 0
+ for path in sorted(docs_root.rglob("*.md*")):
+ if path.suffix not in (".md", ".mdx"):
+ continue
+ rel = path.relative_to(docs_root).as_posix()
+ if is_generated(rel) and not include_generated:
+ continue
+ text = path.read_text(encoding="utf-8")
+ replacements: dict[str, str] = {}
+ for line_no, m in iter_links(text):
+ target = m.group(1)
+ route, suffix = normalize_route(target)
+ if route.startswith(NON_DOC_ROUTE_PREFIXES):
+ continue
+ shown = path.relative_to(WEBSITE) if path.is_relative_to(WEBSITE) else path
+ where = f"{shown}:{line_no}: {target}"
+ hit = local_routes.get(route) or en_routes.get(route)
+ if hit is None:
+ unresolved.append(where)
+ continue
+ findings.append(where)
+ if fix:
+ root = docs_root if hit.is_relative_to(docs_root) else EN_DOCS
+ replacements[m.group(0)] = "](" + relative_link(path, docs_root, hit, root) + suffix + ")"
+ if fix and replacements and not unresolved:
+ new_text = text
+ for old, new in replacements.items():
+ new_text = new_text.replace(old, new)
+ path.write_text(new_text, encoding="utf-8")
+ rewritten += 1
+ return findings, unresolved, rewritten
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--fix", action="store_true", help="rewrite route-style links to relative file links")
+ parser.add_argument(
+ "--include-generated",
+ action="store_true",
+ help="also process generator outputs (only for a one-off migration; the generator owns them)",
+ )
+ parser.add_argument("--en-only", action="store_true", help="skip the zh-Hans mirror")
+ args = parser.parse_args(argv)
+
+ en_routes = route_map(EN_DOCS)
+ trees = [EN_DOCS] if args.en_only or not ZH_DOCS.exists() else [EN_DOCS, ZH_DOCS]
+ all_findings: list[str] = []
+ all_unresolved: list[str] = []
+ rewritten = 0
+ for tree in trees:
+ f, u, r = process_tree(tree, en_routes, args.fix, args.include_generated)
+ all_findings += f
+ all_unresolved += u
+ rewritten += r
+
+ if all_unresolved:
+ print("Route-style links that match no doc file (fix the target first):", file=sys.stderr)
+ for line in all_unresolved:
+ print(f" {line}", file=sys.stderr)
+ return 1
+ if args.fix:
+ print(f"Rewrote {len(all_findings)} route-style links in {rewritten} files.")
+ return 0
+ if all_findings:
+ print(
+ "Route-style links found in hand-authored docs. They 404 on GitHub; write a relative\n"
+ "Markdown path instead (`../user-guide/profiles.md#anchor`) or run\n"
+ "`python3 website/scripts/check_doc_links.py --fix`:",
+ file=sys.stderr,
+ )
+ for line in all_findings:
+ print(f" {line}", file=sys.stderr)
+ return 1
+ print("OK: no route-style links in hand-authored docs.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/website/scripts/generate-skill-docs.py b/website/scripts/generate-skill-docs.py
index 7e10e858b64..0cd510998f0 100755
--- a/website/scripts/generate-skill-docs.py
+++ b/website/scripts/generate-skill-docs.py
@@ -395,9 +395,10 @@ def render_skill_page(
if skill_index is not None:
target_meta = skill_index.get(r)
if target_meta is not None:
+ # Relative file link: resolves on the site and on GitHub (#114428).
href = (
- f"/docs/user-guide/skills/{target_meta['source_kind']}"
- f"/{target_meta['category']}/{page_id(target_meta)}"
+ f"../../{target_meta['source_kind']}"
+ f"/{target_meta['category']}/{page_id(target_meta)}.md"
)
link_parts.append(f"[`{r}`]({href})")
else:
@@ -495,7 +496,7 @@ def build_catalog_md_bundled(entries: list[tuple[dict[str, Any], dict[str, Any]]
desc = (fm.get("description") or "").strip()
if len(desc) > 240:
desc = desc[:237].rstrip() + "..."
- link_target = f"/docs/user-guide/skills/bundled/{meta['category']}/{page_id(meta)}"
+ link_target = f"../user-guide/skills/bundled/{meta['category']}/{page_id(meta)}.md"
path = f"`{meta['rel_path']}`"
desc_esc = mdx_escape_body(desc).replace("|", "\\|").replace("\n", " ")
lines.append(
@@ -556,7 +557,7 @@ def build_catalog_md_optional(entries: list[tuple[dict[str, Any], dict[str, Any]
desc = (fm.get("description") or "").strip()
if len(desc) > 240:
desc = desc[:237].rstrip() + "..."
- link_target = f"/docs/user-guide/skills/optional/{meta['category']}/{page_id(meta)}"
+ link_target = f"../user-guide/skills/optional/{meta['category']}/{page_id(meta)}.md"
desc_esc = mdx_escape_body(desc).replace("|", "\\|").replace("\n", " ")
lines.append(f"| [**{name}**]({link_target}) | {desc_esc} |")
lines.append("")
diff --git a/website/src/remark/relativeDocLinks.js b/website/src/remark/relativeDocLinks.js
new file mode 100644
index 00000000000..4d2c478200c
--- /dev/null
+++ b/website/src/remark/relativeDocLinks.js
@@ -0,0 +1,66 @@
+// Remark plugin: make relative Markdown file links resolve across the zh-Hans
+// fallback boundary.
+//
+// Docs are authored with relative file links (`../user-guide/profiles.md`) so
+// they also open on GitHub (#114428). Docusaurus resolves `./x.md` and
+// `../x.md` only against the *source file's own directory*. In a localized
+// build, an untranslated EN page (served as fallback) linking to a translated
+// page — or the reverse — then fails to resolve, because the target's source
+// lives in the other content root. A content-root-absolute file link
+// (`/user-guide/profiles.md`) is resolved against every content path
+// (i18n/<locale>/.../current first, then docs/), so this plugin rewrites the
+// relative form to that form before Docusaurus's own link resolution runs.
+//
+// Only links with a Markdown extension are touched; anything else (routes,
+// assets, external URLs) passes through untouched.
+
+const path = require('path');
+
+const MARKDOWN_LINK = /^(\.\.?\/[^?#]*\.mdx?)([?#].*)?$/i;
+const LOCALIZED_ROOT = /^(.*\/i18n\/[^/]+\/docusaurus-plugin-content-docs\/[^/]+)\//;
+
+function contentRoot(sourceFilePath, siteDir) {
+ const posixPath = sourceFilePath.split(path.sep).join('/');
+ const localized = LOCALIZED_ROOT.exec(posixPath);
+ if (localized) {
+ return localized[1];
+ }
+ return path.posix.join(siteDir.split(path.sep).join('/'), 'docs');
+}
+
+function walk(node, visitor) {
+ if (!node || typeof node !== 'object') {
+ return;
+ }
+ if (node.type === 'link' || node.type === 'definition') {
+ visitor(node);
+ }
+ if (Array.isArray(node.children)) {
+ node.children.forEach((child) => walk(child, visitor));
+ }
+}
+
+function plugin(options = {}) {
+ const siteDir = options.siteDir || process.cwd();
+ return (root, file) => {
+ if (!file.path) {
+ return;
+ }
+ const sourceDir = path.posix.dirname(file.path.split(path.sep).join('/'));
+ const root_ = contentRoot(file.path, siteDir);
+ walk(root, (node) => {
+ const match = MARKDOWN_LINK.exec(node.url || '');
+ if (!match) {
+ return;
+ }
+ const resolved = path.posix.normalize(path.posix.join(sourceDir, match[1]));
+ const relToRoot = path.posix.relative(root_, resolved);
+ if (relToRoot.startsWith('../')) {
+ return; // points outside the docs tree; leave it to Docusaurus
+ }
+ node.url = '/' + relToRoot + (match[2] || '');
+ });
+ };
+}
+
+module.exports = plugin;