From f5b66be85f88ddbbff02bf45f39d729b677231ea Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 25 Oct 2026 17:49:04 +0800 Subject: [PATCH] Add AGENTS.md and SKILL.md governance check gates --- .githooks/pre-commit | 29 +++++++- .github/workflows/ci.yml | 6 ++ .zcode/config.json | 25 +++++++ AGENTS.md | 4 +- package.json | 4 +- scripts/check-agents-md.test.ts | 91 +++++++++++++++++++++++ scripts/check-agents-md.ts | 110 +++++++++++++++++++++++++++ scripts/check-skill-md.test.ts | 104 ++++++++++++++++++++++++++ scripts/check-skill-md.ts | 127 ++++++++++++++++++++++++++++++++ scripts/doc-md-common.ts | 114 ++++++++++++++++++++++++++++ 10 files changed, 609 insertions(+), 5 deletions(-) create mode 100644 scripts/check-agents-md.test.ts create mode 100644 scripts/check-agents-md.ts create mode 100644 scripts/check-skill-md.test.ts create mode 100644 scripts/check-skill-md.ts create mode 100644 scripts/doc-md-common.ts diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 457fe5c..f9ec21a 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -1,6 +1,29 @@ #!/bin/bash -# Git pre-commit hook: enforce the device branch-prefix rule -# (.agents/rules/branch-naming.md) via .githooks/branch-guard.sh +# Git pre-commit hook: +# 1. Enforce the device branch-prefix rule (.agents/rules/branch-naming.md) +# via .githooks/branch-guard.sh. +# 2. Route staged governance documents to their dedicated checkers — each +# document class has its own verifier (no all-in-one gate): +# AGENTS.md, .agents/rules/*.md -> bun run verify:agents-md +# SKILL.md, skills references -> bun run verify:skill-md +# Local gates fail open when bun is unavailable; CI re-runs both. source "$(dirname "$0")/branch-guard.sh" -guard_branch_name "$(git branch --show-current)" +guard_branch_name "$(git branch --show-current)" || exit 1 + +staged="$(git diff --cached --name-only --diff-filter=ACMR)" + +if ! command -v bun >/dev/null 2>&1; then + echo "⚠️ [pre-commit] bun 未找到,跳过治理文档校验(CI 会重新执行)。" >&2 + exit 0 +fi + +if printf '%s\n' "$staged" | grep -qx "AGENTS.md" || printf '%s\n' "$staged" | grep -q "^\.agents/rules/"; then + bun run verify:agents-md || exit 1 +fi + +if printf '%s\n' "$staged" | grep -qE "^skills/seal-use/(SKILL\.md|references/[^/]+\.md)$"; then + bun run verify:skill-md || exit 1 +fi + +exit 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 882a4a7..d80197b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,12 @@ jobs: - name: CLI Documentation Sync run: bun run verify:cli-md + - name: AGENTS.md Governance Checks + run: bun run verify:agents-md + + - name: Skill Routing Hub Checks + run: bun run verify:skill-md + - name: Embedded Skill Sync run: bun run verify:embedded-skill diff --git a/.zcode/config.json b/.zcode/config.json index c1c65d7..3274b2d 100644 --- a/.zcode/config.json +++ b/.zcode/config.json @@ -2,5 +2,30 @@ "skill": { "/Users/yingqing/.agents/skills/dws/SKILL.md": { "enable": false }, "/Users/yingqing/.agents/skills/lark-suite/SKILL.md": { "enable": false } + }, + "hooks": { + "enabled": true, + "events": { + "SessionStart": [ + { + "hooks": [ + { + "type": "process", + "command": "bun", + "args": ["${ZCODE_PROJECT_DIR}/scripts/check-agents-md.ts", "--soft"], + "timeoutMs": 15000, + "statusMessage": "校验 AGENTS.md 开发者契约" + }, + { + "type": "process", + "command": "bun", + "args": ["${ZCODE_PROJECT_DIR}/scripts/check-skill-md.ts", "--soft"], + "timeoutMs": 15000, + "statusMessage": "校验 SKILL.md 路由中枢" + } + ] + } + ] + } } } diff --git a/AGENTS.md b/AGENTS.md index 5727d68..bae73f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`. -Tests are colocated as `*.test.ts` files in `src/`. +Tests are colocated as `*.test.ts` files in `src/`. ## Build, Test, and Development Commands @@ -20,6 +20,8 @@ Tests are colocated as `*.test.ts` files in `src/`. - `bun run check`: type-check with `tsc --noEmit` (also enforces `noUnusedLocals`/`noUnusedParameters`). - `bun run lint`: lint with `oxlint src` (zero-warning gate; CI fails on warnings). - `bun test`: run all colocated Bun tests. +- `bun run verify:agents-md`: validate the root `AGENTS.md` developer contract (structure, required sections, `.agents/rules/` reference integrity); wired into pre-commit (staged docs only) and CI. +- `bun run verify:skill-md`: validate the `skills/seal-use/SKILL.md` routing hub (size budget, bidirectional `references/` routing); wired into pre-commit (staged docs only) and CI. - `bun run bump `: bump version across all manifest and skill files. - `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the existing global command found on PATH (falling back to a standalone bin directory), and sync the local Agent Skill. diff --git a/package.json b/package.json index e0f5aa6..6fe5000 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,9 @@ "generate:embedded-skill": "bun run scripts/generate-embedded-skill.mjs", "verify:embedded-skill": "bun run scripts/check-embedded-skill.mjs", "generate:cli-md": "bun run scripts/generate-cli-md.mjs", - "verify:cli-md": "bun run scripts/check-cli-md.mjs" + "verify:cli-md": "bun run scripts/check-cli-md.mjs", + "verify:agents-md": "bun run scripts/check-agents-md.ts", + "verify:skill-md": "bun run scripts/check-skill-md.ts" }, "dependencies": { "@modelcontextprotocol/server": "^2.0.0", diff --git a/scripts/check-agents-md.test.ts b/scripts/check-agents-md.test.ts new file mode 100644 index 0000000..9ddae71 --- /dev/null +++ b/scripts/check-agents-md.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, test } from "bun:test" +import { readdirSync, readFileSync } from "node:fs" +import { join } from "node:path" +import { REQUIRED_H2_SECTIONS, validateAgentsDoc } from "./check-agents-md.js" + +const RULES_FILES = new Set(["testing.md", "cli-protocol.md"]) + +function lines(...rows: string[]): string { + return rows.join("\n") +} + +function cleanDoc(): string { + const sections = REQUIRED_H2_SECTIONS.map((section) => `## ${section}`).join("\n\n") + return `${lines("# Repo Guidelines", "")}${sections}\n\nRules live in \`.agents/rules/testing.md\` and \`.agents/rules/cli-protocol.md\`.` +} + +describe("validateAgentsDoc", () => { + test("accepts a well-formed document", () => { + expect(validateAgentsDoc(cleanDoc(), RULES_FILES)).toEqual([]) + }) + + test("flags a missing required H2 section", () => { + const content = lines("# Repo Guidelines", "", "## Testing Guidelines", "Body.") + const issues = validateAgentsDoc(content, RULES_FILES) + const missing = issues.filter((issue) => issue.rule === "required-section") + expect(missing.length).toBeGreaterThan(0) + expect(missing.some((issue) => issue.message.includes("Build, Test, and Development Commands"))).toBe(true) + }) + + test("flags missing, duplicated, or non-leading H1", () => { + const noH1 = validateAgentsDoc(lines("## Only Sections", "Body."), RULES_FILES) + expect(noH1.some((issue) => issue.rule === "h1" && issue.message.includes("no H1"))).toBe(true) + + const duplicate = validateAgentsDoc(lines("# Title", "", "## A", "", "# Second Title"), RULES_FILES) + expect(duplicate.filter((issue) => issue.rule === "h1").length).toBe(1) + + const notLeading = validateAgentsDoc(lines("## A", "", "# Title"), RULES_FILES) + expect(notLeading.some((issue) => issue.rule === "h1" && issue.message.includes("first heading"))).toBe(true) + }) + + test("flags heading level jumps", () => { + const content = lines("# Title", "", "## Section", "", "#### Skipped subsection") + const issues = validateAgentsDoc(content, RULES_FILES) + expect(issues.some((issue) => issue.rule === "heading-hierarchy" && issue.line === 5)).toBe(true) + }) + + test("flags references to rules files that do not exist", () => { + const content = lines( + "# Repo Guidelines", + "", + "Rules live in `.agents/rules/missing-rule.md` and `.agents/rules/testing.md`." + ) + const issues = validateAgentsDoc(content, RULES_FILES) + const references = issues.filter((issue) => issue.rule === "rules-reference") + expect(references.length).toBe(1) + expect(references[0]!.message).toContain(".agents/rules/missing-rule.md") + }) + + test("does not false-positive on historical mentions outside the rules namespace", () => { + const content = lines( + "# Repo Guidelines", + "", + "The in-repo `.agents/skills/seal-use` symlink has been dropped; `src/cli.ts` is unaffected." + ) + expect(validateAgentsDoc(content, RULES_FILES).filter((issue) => issue.rule === "rules-reference")).toEqual([]) + }) + + test("flags hygiene violations outside code fences", () => { + const content = lines("# Title", "", "## Section", "Trailing spaces. ", "```bash", "echo ok ", "```") + const issues = validateAgentsDoc(content, RULES_FILES) + expect(issues.some((issue) => issue.rule === "trailing-whitespace" && issue.line === 4)).toBe(true) + expect(issues.some((issue) => issue.rule === "trailing-whitespace" && issue.line === 6)).toBe(false) + }) + + test("flags an unclosed code fence", () => { + const content = lines("# Title", "", "## Section", "```bash", "echo ok") + const issues = validateAgentsDoc(content, RULES_FILES) + expect(issues.some((issue) => issue.rule === "unclosed-fence" && issue.line === 4)).toBe(true) + }) + + test("the committed root AGENTS.md passes its own contract", () => { + const root = join(import.meta.dirname, "..") + const content = readFileSync(join(root, "AGENTS.md"), "utf8") + const ruleFiles = new Set( + readdirSync(join(root, ".agents", "rules"), { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) + .map((entry) => entry.name) + ) + expect(validateAgentsDoc(content, ruleFiles)).toEqual([]) + }) +}) diff --git a/scripts/check-agents-md.ts b/scripts/check-agents-md.ts new file mode 100644 index 0000000..18bf675 --- /dev/null +++ b/scripts/check-agents-md.ts @@ -0,0 +1,110 @@ +#!/usr/bin/env bun +/** + * Governance checks for the root AGENTS.md (the developer-level contract). + * + * Scope: only mechanically decidable rules — document structure, the required + * section set, and reference integrity for the .agents/rules/ registry. + * Deliberately excluded: prose style, tone, wording (subjective, noisy). + * + * Invoked as `bun run verify:agents-md` (CI + pre-commit) and with `--soft` + * from the ZCode SessionStart hook, which emits hook-safe JSON and never + * blocks the session. + */ +import { readdirSync, readFileSync } from "node:fs" +import { join } from "node:path" +import { + checkHeadingHierarchy, + checkHygiene, + checkSingleLeadingH1, + extractHeadings, + type DocIssue +} from "./doc-md-common.js" + +export const AGENTS_DOC_FILE = "AGENTS.md" + +/** + * Load-bearing H2 sections of the developer contract. Deleting one must be a + * conscious edit to this list, not an accident of a large refactor or merge. + */ +export const REQUIRED_H2_SECTIONS = [ + "Project Structure & Module Organization", + "Build, Test, and Development Commands", + "Coding Style & Naming Conventions", + "CLI & Agent Harness Protocol Guidelines", + "Testing Guidelines", + "Commit & Pull Request Guidelines", + "Release & Publishing Guidelines", + "Security & Configuration Tips", + "Agent-Specific Instructions" +] + +/** Backticked registry references only: `.agents/rules/.md`. */ +const RULES_REFERENCE = /`(\.agents\/rules\/[A-Za-z0-9._-]+\.md)`/g + +export function validateAgentsDoc(content: string, existingRuleFiles: ReadonlySet): DocIssue[] { + const file = AGENTS_DOC_FILE + const issues: DocIssue[] = [] + + const headings = extractHeadings(content) + issues.push(...checkSingleLeadingH1(headings, file)) + issues.push(...checkHeadingHierarchy(headings, file)) + + const h2Texts = new Set(headings.filter((heading) => heading.level === 2).map((heading) => heading.text)) + for (const required of REQUIRED_H2_SECTIONS) { + if (!h2Texts.has(required)) { + issues.push({ file, rule: "required-section", message: `missing required H2 section "${required}"` }) + } + } + + for (const match of content.matchAll(RULES_REFERENCE)) { + const ruleFile = match[1]!.split("/").pop()! + if (!existingRuleFiles.has(ruleFile)) { + issues.push({ + file, + rule: "rules-reference", + message: `referenced rules file ${match[1]} does not exist in .agents/rules/` + }) + } + } + + issues.push(...checkHygiene(content, file)) + return issues +} + +function main(): void { + const root = join(import.meta.dirname, "..") + const content = readFileSync(join(root, AGENTS_DOC_FILE), "utf8") + const ruleFiles = new Set( + readdirSync(join(root, ".agents", "rules"), { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) + .map((entry) => entry.name) + ) + const issues = validateAgentsDoc(content, ruleFiles) + + if (process.argv.includes("--soft")) { + // SessionStart hook mode: empty stdout passes silently; the strict hook + // schema accepts a single additionalContext key. Never block the session. + if (issues.length > 0) { + const summary = issues.map((issue) => `${issue.rule}: ${issue.message}`).join("; ") + console.log( + JSON.stringify({ + additionalContext: `AGENTS.md 治理校验未通过(${issues.length} 项):${summary}。本地运行 bun run verify:agents-md 查看详情。` + }) + ) + } + return + } + + if (issues.length > 0) { + for (const issue of issues) { + const at = issue.line === undefined ? "" : `:${issue.line}` + console.error(`${issue.file}${at} [${issue.rule}] ${issue.message}`) + } + console.error(`AGENTS.md governance checks failed (${issues.length} issue(s)).`) + process.exitCode = 1 + return + } + console.log("AGENTS.md governance checks passed.") +} + +if (import.meta.main) main() diff --git a/scripts/check-skill-md.test.ts b/scripts/check-skill-md.test.ts new file mode 100644 index 0000000..bd8c180 --- /dev/null +++ b/scripts/check-skill-md.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, test } from "bun:test" +import { readdirSync, readFileSync } from "node:fs" +import { join } from "node:path" +import { SKILL_MAX_H2_SECTIONS, SKILL_MAX_LINES, validateSkillDoc } from "./check-skill-md.js" + +const REFERENCE_FILES = ["references/alpha.md", "references/beta.md"] + +function lines(...rows: string[]): string { + return rows.join("\n") +} + +function cleanSkill(): string { + return lines( + "---", + "name: demo", + "---", + "", + "# Demo Skill", + "", + "## Routing", + "", + "| Signal | Reference |", + "| --- | --- |", + "| first case | `references/alpha.md` |", + "| second case | `references/beta.md` |" + ) +} + +describe("validateSkillDoc", () => { + test("accepts a well-formed routing hub", () => { + expect(validateSkillDoc(cleanSkill(), REFERENCE_FILES)).toEqual([]) + }) + + test("enforces the line budget as a hard error", () => { + const padded = Array.from({ length: SKILL_MAX_LINES }, () => "filler line") + const content = `${cleanSkill()}\n${padded.join("\n")}` + const issues = validateSkillDoc(content, REFERENCE_FILES) + expect(issues.some((issue) => issue.rule === "skill-budget-lines")).toBe(true) + }) + + test("enforces the H2 section budget as a hard error", () => { + const sections = Array.from( + { length: SKILL_MAX_H2_SECTIONS + 1 }, + (_, index) => `## Section ${index + 1}` + ) + const content = `${lines("# Demo Skill", "")}\n${sections.join("\n\n")}` + const issues = validateSkillDoc(content, REFERENCE_FILES) + expect(issues.some((issue) => issue.rule === "skill-budget-h2")).toBe(true) + }) + + test("flags routing that points at a missing reference file", () => { + const content = lines( + "# Demo Skill", + "", + "## Routing", + "", + "Detailed guide: `references/ghost.md`." + ) + const issues = validateSkillDoc(content, REFERENCE_FILES) + const missing = issues.filter((issue) => issue.rule === "skill-reference-exists") + expect(missing.length).toBe(1) + expect(missing[0]!.message).toContain("references/ghost.md") + }) + + test("flags reference files that exist on disk but are never routed", () => { + const content = lines( + "# Demo Skill", + "", + "## Routing", + "", + "Only this: `references/alpha.md`." + ) + const issues = validateSkillDoc(content, REFERENCE_FILES) + const unrouted = issues.filter((issue) => issue.rule === "skill-reference-routed") + expect(unrouted.length).toBe(1) + expect(unrouted[0]!.message).toContain("references/beta.md") + }) + + test("flags structure and hygiene problems", () => { + const content = lines( + "# Demo Skill", + "", + "## Section", + "", + "#### Skipped level", + "", + "Trailing spaces. " + ) + const issues = validateSkillDoc(content, REFERENCE_FILES) + expect(issues.some((issue) => issue.rule === "heading-hierarchy")).toBe(true) + expect(issues.some((issue) => issue.rule === "trailing-whitespace" && issue.line === 7)).toBe(true) + }) + + test("the committed skills/seal-use/SKILL.md passes its own charter", () => { + const root = join(import.meta.dirname, "..") + const content = readFileSync(join(root, "skills", "seal-use", "SKILL.md"), "utf8") + const referenceFiles = readdirSync(join(root, "skills", "seal-use", "references"), { + withFileTypes: true + }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) + .map((entry) => `references/${entry.name}`) + expect(validateSkillDoc(content, referenceFiles)).toEqual([]) + }) +}) diff --git a/scripts/check-skill-md.ts b/scripts/check-skill-md.ts new file mode 100644 index 0000000..8dd409e --- /dev/null +++ b/scripts/check-skill-md.ts @@ -0,0 +1,127 @@ +#!/usr/bin/env bun +/** + * Governance checks for skills/seal-use/SKILL.md (the user/agent-facing + * traffic-routing hub, per .agents/rules/skill-documentation.md). + * + * Scope: the routing-hub charter as hard numbers (size budget) and routing + * integrity (every reference file on disk is routed; every routed reference + * exists on disk). Not checked here: wording quality, table formatting. + * + * Invoked as `bun run verify:skill-md` (CI + pre-commit) and with `--soft` + * from the ZCode SessionStart hook, which emits hook-safe JSON and never + * blocks the session. + */ +import { readdirSync, readFileSync, statSync } from "node:fs" +import { join } from "node:path" +import { + checkHeadingHierarchy, + checkHygiene, + checkSingleLeadingH1, + extractHeadings, + type DocIssue +} from "./doc-md-common.js" + +export const SKILL_DOC_RELATIVE_PATH = "skills/seal-use/SKILL.md" +export const REFERENCES_DIR_RELATIVE_PATH = "skills/seal-use/references" + +/** + * The charter says SKILL.md is a lightweight routing hub, never a feature + * billboard. These budgets turn that into hard numbers; raising them must be + * a deliberate, reviewable diff, not silent growth. + */ +export const SKILL_MAX_LINES = 200 +export const SKILL_MAX_H2_SECTIONS = 12 + +/** Backticked skill-relative references only: `references/.md`. */ +const REFERENCE_MENTION = /`(references\/[A-Za-z0-9._-]+\.md)`/g + +export function validateSkillDoc(content: string, referenceFiles: readonly string[]): DocIssue[] { + const file = SKILL_DOC_RELATIVE_PATH + const issues: DocIssue[] = [] + + const headings = extractHeadings(content) + issues.push(...checkSingleLeadingH1(headings, file)) + issues.push(...checkHeadingHierarchy(headings, file)) + + const lineCount = content.split("\n").length + if (lineCount > SKILL_MAX_LINES) { + issues.push({ + file, + rule: "skill-budget-lines", + message: `SKILL.md is ${lineCount} lines (budget ${SKILL_MAX_LINES}); move detail into references/ per the routing-hub charter` + }) + } + const h2Count = headings.filter((heading) => heading.level === 2).length + if (h2Count > SKILL_MAX_H2_SECTIONS) { + issues.push({ + file, + rule: "skill-budget-h2", + message: `SKILL.md has ${h2Count} H2 sections (budget ${SKILL_MAX_H2_SECTIONS}); consolidate before adding more` + }) + } + + const diskReferences = new Set(referenceFiles) + const mentioned = new Set() + for (const match of content.matchAll(REFERENCE_MENTION)) { + mentioned.add(match[1]!) + if (!diskReferences.has(match[1]!)) { + issues.push({ + file, + rule: "skill-reference-exists", + message: `routing points to ${match[1]} which does not exist on disk` + }) + } + } + for (const reference of diskReferences) { + if (!content.includes(reference)) { + issues.push({ + file, + rule: "skill-reference-routed", + message: `${reference} exists in references/ but is never routed from SKILL.md (undiscoverable per the charter)` + }) + } + } + + issues.push(...checkHygiene(content, file)) + return issues +} + +function main(): void { + const root = join(import.meta.dirname, "..") + const content = readFileSync(join(root, SKILL_DOC_RELATIVE_PATH), "utf8") + const referencesDir = join(root, REFERENCES_DIR_RELATIVE_PATH) + const referenceFiles: string[] = [] + for (const entry of readdirSync(referencesDir, { withFileTypes: true })) { + if (entry.isFile() && entry.name.endsWith(".md") && statSync(join(referencesDir, entry.name)).isFile()) { + referenceFiles.push(`references/${entry.name}`) + } + } + const issues = validateSkillDoc(content, referenceFiles) + + if (process.argv.includes("--soft")) { + // SessionStart hook mode: empty stdout passes silently; the strict hook + // schema accepts a single additionalContext key. Never block the session. + if (issues.length > 0) { + const summary = issues.map((issue) => `${issue.rule}: ${issue.message}`).join("; ") + console.log( + JSON.stringify({ + additionalContext: `SKILL.md 路由中枢校验未通过(${issues.length} 项):${summary}。本地运行 bun run verify:skill-md 查看详情。` + }) + ) + } + return + } + + if (issues.length > 0) { + for (const issue of issues) { + const at = issue.line === undefined ? "" : `:${issue.line}` + console.error(`${issue.file}${at} [${issue.rule}] ${issue.message}`) + } + console.error(`SKILL.md routing-hub checks failed (${issues.length} issue(s)).`) + process.exitCode = 1 + return + } + console.log("SKILL.md routing-hub checks passed.") +} + +if (import.meta.main) main() diff --git a/scripts/doc-md-common.ts b/scripts/doc-md-common.ts new file mode 100644 index 0000000..59eb449 --- /dev/null +++ b/scripts/doc-md-common.ts @@ -0,0 +1,114 @@ +/** + * Shared, fence-aware Markdown scanning used by the governance doc checkers + * (check-agents-md.ts, check-skill-md.ts). Pure functions only: the CLI + * wrappers own file I/O so tests can drive fixtures without touching disk. + */ + +export interface DocIssue { + file: string + line?: number + rule: string + message: string +} + +export interface MarkdownLine { + /** 1-based line number. */ + number: number + text: string + /** True when this line sits inside an open ``` / ~~~ fence. */ + inFence: boolean +} + +const FENCE_OPEN = /^\s{0,3}(```|~~~)/ +const HEADING = /^(#{1,6})\s+(.*)$/ + +export function scanMarkdownLines(content: string): MarkdownLine[] { + let inFence = false + return content.split("\n").map((text, index) => { + const line: MarkdownLine = { number: index + 1, text, inFence } + if (FENCE_OPEN.test(text)) inFence = !inFence + return line + }) +} + +export interface Heading { + level: number + text: string + line: number +} + +export function extractHeadings(content: string): Heading[] { + const headings: Heading[] = [] + for (const line of scanMarkdownLines(content)) { + if (line.inFence) continue + const match = line.text.match(HEADING) + if (match) headings.push({ level: match[1]!.length, text: match[2]!.trim(), line: line.number }) + } + return headings +} + +/** Exactly one H1 and it must be the first heading of the document. */ +export function checkSingleLeadingH1(headings: Heading[], file: string): DocIssue[] { + const h1s = headings.filter((heading) => heading.level === 1) + if (h1s.length === 1 && h1s[0] === headings[0]) return [] + if (h1s.length === 0) { + return [{ file, rule: "h1", message: "document has no H1 heading" }] + } + if (h1s[0] !== headings[0]) { + return [{ file, line: h1s[0]!.line, rule: "h1", message: "H1 must be the first heading" }] + } + return h1s.slice(1).map((heading) => ({ + file, + line: heading.line, + rule: "h1", + message: `duplicate H1 "${heading.text}" (keep a single document title)` + })) +} + +/** Heading levels may step down freely but may never jump up by more than one. */ +export function checkHeadingHierarchy(headings: Heading[], file: string): DocIssue[] { + const issues: DocIssue[] = [] + let previous: Heading | undefined + for (const heading of headings) { + if (previous && heading.level > previous.level + 1) { + issues.push({ + file, + line: heading.line, + rule: "heading-hierarchy", + message: `heading jumps from H${previous.level} to H${heading.level} ("${heading.text}")` + }) + } + previous = heading + } + return issues +} + +/** Trailing whitespace outside code fences, and fences that never close. */ +export function checkHygiene(content: string, file: string): DocIssue[] { + const issues: DocIssue[] = [] + let lastFenceToggle: MarkdownLine | undefined + const lines = scanMarkdownLines(content) + for (const line of lines) { + if (FENCE_OPEN.test(line.text)) { + lastFenceToggle = line + continue + } + if (!line.inFence && /[ \t]+$/.test(line.text)) { + issues.push({ + file, + line: line.number, + rule: "trailing-whitespace", + message: "trailing whitespace" + }) + } + } + if (lines.length > 0 && lines[lines.length - 1]!.inFence && lastFenceToggle) { + issues.push({ + file, + line: lastFenceToggle.number, + rule: "unclosed-fence", + message: "code fence opened here is never closed" + }) + } + return issues +}