← Back to Pull requests

build(changelog): assemble release notes from per-PR changelog fragments #229

Merged
aramase merged 26 files (2181 lines) on Oct 28, 2026 03:25 UTC
View on GitHub
aramase aramase commented on Oct 27, 2026 21:20 UTC
Author

Every pull request that adds an Unreleased entry edits the same lines of CHANGELOG.md, so concurrent PRs conflict. This moves release notes into one fragment file per PR and category under changelog/unreleased/, assembled into CHANGELOG.md at release time.

  • Add hack/changelog with assemble, verify-assembled and check, and a format guide in changelog/README.md. CONTRIBUTING and the Copilot instructions point to it.

  • Move every Unreleased entry now on main into fragments, keeping each entry's wording and category (20 entries, including the ones from the Substrate kind example, tool policy hook and verified approver changes). CHANGELOG.md no longer has an Unreleased section.

  • Add a changelog workflow that fails a PR changing a public contract path without a fragment.

  • Make the release workflow refuse to publish a tag while fragments are still unassembled.
  • Tested:

  • go test -race ./hack/changelog/, go vet, gofmt, actionlint on both workflows and hack/check-doc-links.py all pass.

  • Dry run of assemble on a copy of the branch produces one release section with the same 20 entries as main's Unreleased section, leaves only .gitkeep, and passes verify-assembled.
  • Diff: 2181 lines (+2049 / -132) across 26 files Reviewer: gambtho Review duration: 365m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.77) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 2181 lines diff across 26 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.88 · 5 substantive comment(s)
    0.88
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    19 items
    Copilot Copilot commented on code on Oct 27, 2026 22:22 UTC
    Code Review
    hack/changelog/check.go:1
    @@ -0,0 +1,148 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"os/exec"
    +	"path"
    +	"slices"
    +	"strings"
    +)
    +
    +// skipLabel is the pull request label that waives the fragment requirement.
    +const skipLabel = "skip-changelog"
    +
    +// errCheckFailed is a check failure already explained on the output.
    +var errCheckFailed = errors.New("changelog check failed")
    +
    +// publicContract reports whether a changed path is part of the public contract that
    +// .github/copilot-instructions.md rule 6 asks a changelog entry for: spec.md, everything under
    +// api/ (protos, generated stubs, the Go Runtime SPI), any .proto file, and the non-test Go source
    +// of an importable package. Importable means outside internal/, testdata/ and cmd/ directories
    +// (cmd/ holds main packages) and outside hack/ and examples/. integrations/substrate is a
    +// published module, so its packages count too.
    +func publicContract(p string) bool {
    +	switch {
    +	case p == "spec.md", strings.HasPrefix(p, "api/"), strings.HasSuffix(p, ".proto"):
    +		return true
    +	case !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go"):
    +		return false
    +	}
    +	segs := strings.Split(path.Dir(p), "/")
    +	if segs[0] == "hack" || segs[0] == "examples" {
    +		return false
    +	}
    +	for _, s := range segs {
    +		if s == "internal" || s == "testdata" || s == "cmd" {
    +			return false
    +		}
    +	}
    +	return true
    +}
    +
    +// isFragment reports whether p is an entry directly under fragmentDir other than keepFile.
    +func isFragment(p string) bool {
    +	return path.Dir(p) == fragmentDir && path.Base(p) != keepFile
    +}
    +
    +func git(dir string, args ...string) ([]byte, error) {
    +	cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
    +	var stderr bytes.Buffer
    +	cmd.Stderr = &stderr
    +	out, err := cmd.Output()
    +	if err != nil {
    +		return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
    +	}
    +	return out, nil
    +}
    +
    +// fragmentsAt reads every entry under fragmentDir at the head revision of the repository in dir.
    +func fragmentsAt(dir, head string) ([]file, error) {
    +	out, err := git(dir, "ls-tree", "-z", head, fragmentDir+"/")
    +	if err != nil {
    +		return nil, err
    +	}
    +	var files []file
    +	for entry := range strings.SplitSeq(strings.TrimSuffix(string(out), "\x00"), "\x00") {
    +		if entry == "" {
    +			continue
    +		}
    +		// <mode> SP <type> SP <object> TAB <path>
    +		meta, p, ok := strings.Cut(entry, "\t")
    +		if !ok {
    +			return nil, fmt.Errorf("unexpected git ls-tree output %q", entry)
    +		}
    +		f := file{name: path.Base(p), dir: strings.Contains(meta, " tree ")}
    +		if !f.dir && f.name != keepFile {
    +			if f.data, err = git(dir, "show", head+":"+p); err != nil {
    +				return nil, err
    +			}
    +		}
    +		files = append(files, f)
    +	}
    +	return files, nil
    +}
    +
    +// check is the pull request gate. It fails when the change from base to head touches a public
    +// contract path without adding or editing a fragment, unless skip (the pull request carries
    +// skipLabel). Independently of skip, every fragment at head must be valid and CHANGELOG.md at head
    +// must not have an "## Unreleased" section. It returns its report, and errCheckFailed on a failed
    +// check or another error when git fails.
    +func check(dir, base, head string, skip bool) (string, error) {
    +	diff, err := git(dir, "diff", "--name-status", "--no-renames", "-z", base, head, "--")
    +	if err != nil {
    +		return "", err
    +	}
    +	var contract, added []string
    +	fields := strings.Split(strings.TrimSuffix(string(diff), "\x00"), "\x00")
    +	for i := 0; i+1 < len(fields); i += 2 {
    +		status, p := fields[i], fields[i+1]
    +		if publicContract(p) {
    +			contract = append(contract, p)
    +		}
    +		// A deleted fragment does not describe this change; an added or edited one does.
    +		if isFragment(p) && status != "D" {
    +			added = append(added, p)
    +		}
    +	}
    +
    +	var out strings.Builder
    +	failed := false
    +	files, err := fragmentsAt(dir, head)
    +	if err != nil {
    +		return "", err
    +	}
    +	invalid := false
    +	if _, err := parseFragments(files); err != nil {
    +		fmt.Fprintf(&out, "invalid changelog fragments (format: changelog/README.md):\n%v\n", err)
    +		invalid, failed = true, true
    +	}
    +	if changelog, err := git(dir, "show", head+":CHANGELOG.md"); err == nil && unreleasedHeading(string(changelog)) {

    Propagate the git show error instead of treating it as an absent Unreleased section. A PR that deletes or renames CHANGELOG.md currently passes this gate because the read failure is ignored and that path does not require a fragment. Both assemble and verify-assembled subsequently fail because the file is missing, blocking releases after the PR merges.

    Copilot Copilot commented on code on Oct 27, 2026 22:22 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,232 @@
    +package main
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional title.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s]+)((?:\s+"[^"]*")?\))`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. Fenced code blocks are
    +// left alone. A non-blank line in a fenced block indented less than the opening fence is refused:
    +// in a list item it ends the item, and so the block, and Markdown renders it as text (a "# " line
    +// as a heading) and the later closing fence as the start of a block that never closes.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	fenced := false
    +	fenceIndent := 0
    +	for i, line := range lines {
    +		if fenced && strings.TrimSpace(line) != "" && indentWidth(line) < fenceIndent {
    +			return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +		}
    +		if strings.HasPrefix(strings.TrimSpace(line), "```") {
    +			if !fenced {
    +				fenceIndent = indentWidth(line)
    +			}
    +			fenced = !fenced
    +			continue
    +		}

    A four-backtick opener followed by a three-backtick line is treated as a closed block, so an unterminated fragment can pass validation and make subsequent changelog sections render as code. The same toggle can reject valid longer-fenced examples or rewrite literal links inside them. Track the opening fence length and close only on a fence at least that long with no trailing content; add regression cases for both valid and unterminated longer-fenced blocks.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 27, 2026 22:22 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Incorrect handling of longer code fences can corrupt changelog rendering, while ignored git show errors allow changelog deletion or renaming to pass validation and later block releases.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Propagate git show errors for missing changelog files · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Match closing fences to the opening fence length · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Moves unreleased notes into per-PR changelog fragments to reduce merge conflicts, with tooling to assemble them into CHANGELOG.md before a release.

    Changes:

  • Adds fragment validation, release assembly, and tests.

  • Migrates the 20 existing Unreleased entries into categorized fragments.

  • Adds pull-request and release gates and updates contributor guidance.
  • | File | Description |
    | ---- | ----------- |
    | hack/​changelog/​main.go | Defines the changelog CLI commands. |
    | hack/​changelog/​fragment.go | Parses fragments, rewrites links, and renders sections. |
    | hack/​changelog/​fragment_test.go | Tests fragment validation and ordering. |
    | hack/​changelog/​check.go | Checks public-contract changes for fragments. |
    | hack/​changelog/​check_test.go | Tests the pull-request gate and CLI errors. |
    | hack/​changelog/​assemble.go | Assembles release sections and checks for pending fragments. |
    | hack/​changelog/​assemble_test.go | Tests assembly, refusals, and release verification. |
    | CONTRIBUTING.md | Documents fragment and release procedures. |
    | changelog/​unreleased/​verified-approver.md | Migrates verified-approver feature notes. |
    | changelog/​unreleased/​verified-approver-compat.md | Migrates approver compatibility notes. |
    | changelog/​unreleased/​tool-policy.md | Migrates tool-policy feature notes. |
    | changelog/​unreleased/​tool-policy-compat.md | Migrates tool-policy compatibility notes. |
    | changelog/​unreleased/​substrate-kind-example.md | Migrates example and verification feature notes. |
    | changelog/​unreleased/​substrate-kind-example-fixed.md | Migrates example, replay, and logging fixes. |
    | changelog/​unreleased/​substrate-fork-capture-refusal.md | Migrates fork-refusal compatibility notes. |
    | changelog/​unreleased/​err-missing-model.md | Migrates missing-model error notes. |
    | changelog/​unreleased/​create-harness.md | Migrates harness-creation feature notes. |
    | changelog/​unreleased/​create-harness-compat.md | Migrates harness-creation compatibility notes. |
    | changelog/​unreleased/​allocation-ownership.md | Migrates allocation-ownership feature notes. |
    | changelog/​unreleased/​allocation-ownership-compat.md | Migrates allocation migration requirements. |
    | changelog/​unreleased/​.gitkeep | Preserves the empty fragment directory after assembly. |
    | changelog/​README.md | Defines fragment format, requirements, and assembly steps. |
    | CHANGELOG.md | Replaces Unreleased entries with links to fragments. |
    | .github/​workflows/​release.yml | Blocks publishing while fragments remain unassembled. |
    | .github/​workflows/​changelog.yml | Adds the fragment gate with label-triggered reruns. |
    | .github/​copilot-instructions.md | Updates review guidance to require fragments. |
    </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Oct 27, 2026 23:08 UTC
    Code Review
    hack/changelog/check.go:1
    @@ -0,0 +1,148 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"os/exec"
    +	"path"
    +	"slices"
    +	"strings"
    +)
    +
    +// skipLabel is the pull request label that waives the fragment requirement.
    +const skipLabel = "skip-changelog"
    +
    +// errCheckFailed is a check failure already explained on the output.
    +var errCheckFailed = errors.New("changelog check failed")
    +
    +// publicContract reports whether a changed path is part of the public contract that
    +// .github/copilot-instructions.md rule 6 asks a changelog entry for: spec.md, everything under
    +// api/ (protos, generated stubs, the Go Runtime SPI), any .proto file, and the non-test Go source
    +// of an importable package. Importable means outside internal/, testdata/ and cmd/ directories
    +// (cmd/ holds main packages) and outside hack/ and examples/. integrations/substrate is a
    +// published module, so its packages count too.
    +func publicContract(p string) bool {
    +	switch {
    +	case p == "spec.md", strings.HasPrefix(p, "api/"), strings.HasSuffix(p, ".proto"):
    +		return true
    +	case !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go"):
    +		return false
    +	}
    +	segs := strings.Split(path.Dir(p), "/")
    +	if segs[0] == "hack" || segs[0] == "examples" {
    +		return false
    +	}
    +	for _, s := range segs {
    +		if s == "internal" || s == "testdata" || s == "cmd" {
    +			return false
    +		}
    +	}
    +	return true
    +}
    +
    +// isFragment reports whether p is an entry directly under fragmentDir other than keepFile.
    +func isFragment(p string) bool {
    +	return path.Dir(p) == fragmentDir && path.Base(p) != keepFile
    +}
    +
    +func git(dir string, args ...string) ([]byte, error) {
    +	cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
    +	var stderr bytes.Buffer
    +	cmd.Stderr = &stderr
    +	out, err := cmd.Output()
    +	if err != nil {
    +		return nil, fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
    +	}
    +	return out, nil
    +}
    +
    +// fragmentsAt reads every entry under fragmentDir at the head revision of the repository in dir.
    +func fragmentsAt(dir, head string) ([]file, error) {
    +	out, err := git(dir, "ls-tree", "-z", head, fragmentDir+"/")
    +	if err != nil {
    +		return nil, err
    +	}
    +	var files []file
    +	for entry := range strings.SplitSeq(strings.TrimSuffix(string(out), "\x00"), "\x00") {
    +		if entry == "" {
    +			continue
    +		}
    +		// <mode> SP <type> SP <object> TAB <path>
    +		meta, p, ok := strings.Cut(entry, "\t")
    +		if !ok {
    +			return nil, fmt.Errorf("unexpected git ls-tree output %q", entry)
    +		}
    +		f := file{name: path.Base(p), dir: strings.Contains(meta, " tree ")}
    +		if !f.dir && f.name != keepFile {
    +			if f.data, err = git(dir, "show", head+":"+p); err != nil {
    +				return nil, err
    +			}
    +		}
    +		files = append(files, f)
    +	}
    +	return files, nil
    +}
    +
    +// check is the pull request gate. It fails when the change from base to head touches a public
    +// contract path without adding or editing a fragment, unless skip (the pull request carries
    +// skipLabel). Independently of skip, every fragment at head must be valid and CHANGELOG.md at head
    +// must not have an "## Unreleased" section. It returns its report, and errCheckFailed on a failed
    +// check or another error when git fails.
    +func check(dir, base, head string, skip bool) (string, error) {
    +	diff, err := git(dir, "diff", "--name-status", "--no-renames", "-z", base, head, "--")
    +	if err != nil {
    +		return "", err
    +	}
    +	var contract, added []string
    +	fields := strings.Split(strings.TrimSuffix(string(diff), "\x00"), "\x00")
    +	for i := 0; i+1 < len(fields); i += 2 {
    +		status, p := fields[i], fields[i+1]
    +		if publicContract(p) {
    +			contract = append(contract, p)
    +		}
    +		// A deleted fragment does not describe this change; an added or edited one does.
    +		if isFragment(p) && status != "D" {
    +			added = append(added, p)
    +		}
    +	}
    +
    +	var out strings.Builder
    +	failed := false
    +	files, err := fragmentsAt(dir, head)
    +	if err != nil {
    +		return "", err
    +	}
    +	invalid := false
    +	if _, err := parseFragments(files); err != nil {
    +		fmt.Fprintf(&out, "invalid changelog fragments (format: changelog/README.md):\n%v\n", err)
    +		invalid, failed = true, true
    +	}
    +	if changelog, err := git(dir, "show", head+":CHANGELOG.md"); err == nil && unreleasedHeading(string(changelog)) {

    Fixed: the check now fails when CHANGELOG.md is missing or not a file at head, and a git failure reading it exits 2 instead of passing. The new TestCheck cases (deleting, renaming, or replacing CHANGELOG.md with a directory or symlink) and TestCheckChangelogReadError cover it.

    aramase aramase commented on code on Oct 27, 2026 23:08 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,232 @@
    +package main
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional title.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s]+)((?:\s+"[^"]*")?\))`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. Fenced code blocks are
    +// left alone. A non-blank line in a fenced block indented less than the opening fence is refused:
    +// in a list item it ends the item, and so the block, and Markdown renders it as text (a "# " line
    +// as a heading) and the later closing fence as the start of a block that never closes.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	fenced := false
    +	fenceIndent := 0
    +	for i, line := range lines {
    +		if fenced && strings.TrimSpace(line) != "" && indentWidth(line) < fenceIndent {
    +			return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +		}
    +		if strings.HasPrefix(strings.TrimSpace(line), "```") {
    +			if !fenced {
    +				fenceIndent = indentWidth(line)
    +			}
    +			fenced = !fenced
    +			continue
    +		}

    Fixed: the validator now tracks the opening fence's character and length, closes only on a fence of the same character that is at least as long with nothing after it, and handles tilde fences too. The regression cases are in TestParseFragment, starting with "shorter fence does not close a longer one" and "longer fence holds a shorter one".

    gambtho gambtho commented on code on Oct 27, 2026 23:57 UTC
    Code Review
    hack/changelog/check_test.go:1
    @@ -0,0 +1,251 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strings"
    +	"testing"
    +)
    +
    +func TestPublicContract(t *testing.T) {
    +	for p, want := range map[string]bool{
    +		"spec.md":                             true,
    +		"api/session.proto":                   true,
    +		"api/genpb/session.pb.go":             true,
    +		"api/runtime.go":                      true,
    +		"api/runtime_test.go":                 true, // everything under api/
    +		"other/x.proto":                       true,
    +		"controller/controller.go":            true,
    +		"sqlitelog/store.go":                  true,
    +		"integrations/substrate/adapter.go":   true,
    +		"controller/controller_test.go":       false,
    +		"internal/version/version.go":         false,
    +		"session/internal/x/x.go":             false,
    +		"controller/testdata/v0.1.2/main.go":  false,
    +		"cmd/agentsessionsd/main.go":          false,
    +		"integrations/substrate/cmd/x/x.go":   false,
    +		"hack/doccheck/main.go":               false,
    +		"examples/agentsuite-substrate/x.go":  false,
    +		"docs/concepts.md":                    false,
    +		"README.md":                           false,
    +		"CHANGELOG.md":                        false,
    +		"go.mod":                              false,
    +		".github/workflows/ci.yml":            false,
    +		"changelog/unreleased/create-shim.md": false,
    +	} {
    +		if got := publicContract(p); got != want {
    +			t.Errorf("publicContract(%q) = %v, want %v", p, got, want)
    +		}
    +	}
    +}
    +
    +// gitRepo is a throwaway repository whose base commit has CHANGELOG.md, a Go package, docs and the
    +// fragment directory.
    +type gitRepo struct {
    +	t   *testing.T
    +	dir string
    +}
    +
    +func newGitRepo(t *testing.T) *gitRepo {
    +	t.Helper()
    +	if _, err := exec.LookPath("git"); err != nil {
    +		t.Skip("git not found")
    +	}
    +	r := &gitRepo{t: t, dir: t.TempDir()}
    +	r.git("init", "-q")
    +	r.write("CHANGELOG.md", intro+history)
    +	r.write("controller/controller.go", "package controller\n")
    +	r.write("docs/concepts.md", "# Concepts\n")
    +	r.write(fragmentDir+"/"+keepFile, "")
    +	r.write(fragmentDir+"/old.md", frag("Added", "- Old."))
    +	r.commit("base")
    +	return r
    +}
    +
    +func (r *gitRepo) git(args ...string) {
    +	r.t.Helper()
    +	cmd := exec.Command("git", append([]string{
    +		"-C", r.dir, "-c", "user.name=test", "-c", "user.email=test@example.invalid",
    +		"-c", "commit.gpgsign=false",
    +	}, args...)...)
    +	if out, err := cmd.CombinedOutput(); err != nil {
    +		r.t.Fatalf("git %v: %v\n%s", args, err, out)
    +	}
    +}
    +
    +func (r *gitRepo) write(p, data string) {
    +	r.t.Helper()
    +	full := filepath.Join(r.dir, p)
    +	if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
    +		r.t.Fatal(err)
    +	}
    +	if err := os.WriteFile(full, []byte(data), 0o644); err != nil {
    +		r.t.Fatal(err)
    +	}
    +}
    +
    +func (r *gitRepo) remove(p string) {
    +	r.t.Helper()
    +	if err := os.Remove(filepath.Join(r.dir, p)); err != nil {
    +		r.t.Fatal(err)
    +	}
    +}
    +
    +func (r *gitRepo) commit(msg string) {
    +	r.t.Helper()
    +	r.git("add", "-A")

    Could this force-add the Finder fixture? With a global .DS_Store ignore, git add -A leaves it out and go test -race ./hack/changelog/... fails committed_Finder_metadata_fails.

    gambtho gambtho commented on code on Oct 27, 2026 23:57 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,232 @@
    +package main
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional title.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s]+)((?:\s+"[^"]*")?\))`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. Fenced code blocks are
    +// left alone. A non-blank line in a fenced block indented less than the opening fence is refused:
    +// in a list item it ends the item, and so the block, and Markdown renders it as text (a "# " line
    +// as a heading) and the later closing fence as the start of a block that never closes.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	fenced := false
    +	fenceIndent := 0
    +	for i, line := range lines {
    +		if fenced && strings.TrimSpace(line) != "" && indentWidth(line) < fenceIndent {
    +			return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +		}
    +		if strings.HasPrefix(strings.TrimSpace(line), "```") {
    +			if !fenced {
    +				fenceIndent = indentWidth(line)
    +			}
    +			fenced = !fenced
    +			continue
    +		}
    +		if fenced {
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		var b strings.Builder
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(line, -1) {

    Reference-style links pass validation but keep their fragment-relative path after assembly. [guide]: ../../docs/allocation-ownership.md then points outside the repo. Could we reject these and ask for inline links?

    gambtho gambtho approved these changes on Oct 27, 2026 23:57 UTC
    Approved Reviewer

    Approved these changes.

    aramase aramase commented on code on Oct 28, 2026 03:17 UTC
    Code Review
    hack/changelog/check_test.go:1
    @@ -0,0 +1,251 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strings"
    +	"testing"
    +)
    +
    +func TestPublicContract(t *testing.T) {
    +	for p, want := range map[string]bool{
    +		"spec.md":                             true,
    +		"api/session.proto":                   true,
    +		"api/genpb/session.pb.go":             true,
    +		"api/runtime.go":                      true,
    +		"api/runtime_test.go":                 true, // everything under api/
    +		"other/x.proto":                       true,
    +		"controller/controller.go":            true,
    +		"sqlitelog/store.go":                  true,
    +		"integrations/substrate/adapter.go":   true,
    +		"controller/controller_test.go":       false,
    +		"internal/version/version.go":         false,
    +		"session/internal/x/x.go":             false,
    +		"controller/testdata/v0.1.2/main.go":  false,
    +		"cmd/agentsessionsd/main.go":          false,
    +		"integrations/substrate/cmd/x/x.go":   false,
    +		"hack/doccheck/main.go":               false,
    +		"examples/agentsuite-substrate/x.go":  false,
    +		"docs/concepts.md":                    false,
    +		"README.md":                           false,
    +		"CHANGELOG.md":                        false,
    +		"go.mod":                              false,
    +		".github/workflows/ci.yml":            false,
    +		"changelog/unreleased/create-shim.md": false,
    +	} {
    +		if got := publicContract(p); got != want {
    +			t.Errorf("publicContract(%q) = %v, want %v", p, got, want)
    +		}
    +	}
    +}
    +
    +// gitRepo is a throwaway repository whose base commit has CHANGELOG.md, a Go package, docs and the
    +// fragment directory.
    +type gitRepo struct {
    +	t   *testing.T
    +	dir string
    +}
    +
    +func newGitRepo(t *testing.T) *gitRepo {
    +	t.Helper()
    +	if _, err := exec.LookPath("git"); err != nil {
    +		t.Skip("git not found")
    +	}
    +	r := &gitRepo{t: t, dir: t.TempDir()}
    +	r.git("init", "-q")
    +	r.write("CHANGELOG.md", intro+history)
    +	r.write("controller/controller.go", "package controller\n")
    +	r.write("docs/concepts.md", "# Concepts\n")
    +	r.write(fragmentDir+"/"+keepFile, "")
    +	r.write(fragmentDir+"/old.md", frag("Added", "- Old."))
    +	r.commit("base")
    +	return r
    +}
    +
    +func (r *gitRepo) git(args ...string) {
    +	r.t.Helper()
    +	cmd := exec.Command("git", append([]string{
    +		"-C", r.dir, "-c", "user.name=test", "-c", "user.email=test@example.invalid",
    +		"-c", "commit.gpgsign=false",
    +	}, args...)...)
    +	if out, err := cmd.CombinedOutput(); err != nil {
    +		r.t.Fatalf("git %v: %v\n%s", args, err, out)
    +	}
    +}
    +
    +func (r *gitRepo) write(p, data string) {
    +	r.t.Helper()
    +	full := filepath.Join(r.dir, p)
    +	if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
    +		r.t.Fatal(err)
    +	}
    +	if err := os.WriteFile(full, []byte(data), 0o644); err != nil {
    +		r.t.Fatal(err)
    +	}
    +}
    +
    +func (r *gitRepo) remove(p string) {
    +	r.t.Helper()
    +	if err := os.Remove(filepath.Join(r.dir, p)); err != nil {
    +		r.t.Fatal(err)
    +	}
    +}
    +
    +func (r *gitRepo) commit(msg string) {
    +	r.t.Helper()
    +	r.git("add", "-A")

    Done: the test repo commits with git add -A --force, so a global excludes file no longer drops the fixture. Passes with .DS_Store in either core.excludesFile or ~/.config/git/ignore.

    aramase aramase commented on code on Oct 28, 2026 03:17 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,232 @@
    +package main
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional title.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s]+)((?:\s+"[^"]*")?\))`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. Fenced code blocks are
    +// left alone. A non-blank line in a fenced block indented less than the opening fence is refused:
    +// in a list item it ends the item, and so the block, and Markdown renders it as text (a "# " line
    +// as a heading) and the later closing fence as the start of a block that never closes.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	fenced := false
    +	fenceIndent := 0
    +	for i, line := range lines {
    +		if fenced && strings.TrimSpace(line) != "" && indentWidth(line) < fenceIndent {
    +			return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +		}
    +		if strings.HasPrefix(strings.TrimSpace(line), "```") {
    +			if !fenced {
    +				fenceIndent = indentWidth(line)
    +			}
    +			fenced = !fenced
    +			continue
    +		}
    +		if fenced {
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		var b strings.Builder
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(line, -1) {

    Done. Fragments must use inline links now: the check refuses reference-style definitions, since a label applies to all of CHANGELOG.md and could link text in another fragment, and any other link form assembly can't rewrite (HTML href/src, angle-bracket targets, titles). changelog/README.md states the rule.

    Copilot Copilot commented on code on Oct 28, 2026 03:26 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +

    Footnote labels need the same isolation as reference-style links. Two valid fragments can each use [^1] and define [^1]: ..., which this parser explicitly permits. After assembly concatenates them into one document, both references share a label, so at least one entry displays the wrong note. Namespace footnote labels and references by fragment name, or reject footnote definitions along with reference-style link definitions.

    Copilot Copilot commented on code on Oct 28, 2026 03:26 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +
    +		`(?:$|(?:<(?:[^>\\]|\\.)*>|\S+)[ \t]*(?:$|["'(]))`)
    +	// htmlLink matches an HTML link or image target attribute, also when its tag opened on an
    +	// earlier line. An anchor without one (<a name="x"></a>), which CHANGELOG.md uses, is allowed.
    +	htmlLink = regexp.MustCompile(`(?i)\b(?:href|src|srcset)\s*=`)
    +	// htmlStart matches a line that starts with an HTML tag or comment, which can open an HTML block,
    +	// where backticks do not start code spans.
    +	htmlStart = regexp.MustCompile(containers + `<`)
    +	// parentDir matches a parent directory step (../), also with dots or slash percent-encoded or
    +	// written as HTML character references, or with a backslash, which browsers treat as a slash.
    +	parentDir = regexp.MustCompile(`(?i)(?:\.|%2e|&#0*46;?|&#x0*2e;?|&period;){2}` +
    +		`(?:/|\\|%2f|%5c|&#0*47;?|&#x0*2f;?|&sol;|&#0*92;?|&#x0*5c;?|&bsol;)`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. It refuses the link
    +// forms it cannot rewrite: an inline link in another form than linkTarget, a link reference
    +// definition (whose label would also apply to every fragment and release section) and an HTML
    +// link or image attribute. As a backstop for any other form, it refuses a parent directory step
    +// (../) left outside an inline link target and a code span: every in-repository target written
    +// relative to the fragment needs one, and a rewritten target has none. A relative target without
    +// one could only name a file in fragmentDir, which a release deletes.
    +//
    +// Fenced code blocks are left alone. A block closes as in CommonMark: on a fence of the opening
    +// fence's character, at least as long, with nothing but spaces and tabs after it. A non-blank line
    +// in a fenced block indented less than the opening fence is refused: in a list item it ends the
    +// item, and so the block, and Markdown renders it as text (a "# " line as a heading) and the later
    +// closing fence as the start of a block that never closes. A closing fence indented 1 to 3 columns
    +// past the opening fence is refused too: whether it closes the block depends on the opening fence's
    +// indentation within its list item. Indented 4 or more past it, it is code.
    +//
    +// Code spans are skipped by the link checks only where maskCodeSpans finds them for certain; see
    +// there. Where it cannot tell whether a line starts in a code span, the line is checked unmasked,
    +// and a link whose target assembly would change is refused, since it may be code that assembly
    +// must not rewrite. A link-shaped text in an HTML block, where Markdown renders no links, is
    +// rewritten like a link: that changes text only.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	var open codeFence // the opening fence of the current block; open.length == 0 outside one
    +	fenceIndent := 0
    +	// spansKnown is false from a line that may leave a code span, HTML tag or autolink open until
    +	// the paragraph ends; htmlSeen is true from a line that may open an HTML block to the end.
    +	spansKnown, htmlSeen := true, false
    +	for i, line := range lines {
    +		if open.length > 0 {
    +			indent := indentWidth(line)
    +			if strings.TrimSpace(line) != "" && indent < fenceIndent {
    +				return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +			}
    +			f, ok := parseFence(line)
    +			if !ok || f.char != open.char || f.length < open.length || strings.Trim(f.info, " \t") != "" ||
    +				indent >= fenceIndent+4 {
    +				continue
    +			}
    +			if indent > fenceIndent {
    +				return "", fmt.Errorf("line %q: closing fence indented more than its opening fence; indent it as far as the opening fence", line)
    +			}
    +			open, spansKnown = codeFence{}, true
    +			continue
    +		}
    +		if f, ok := parseFence(line); ok && (f.char != '`' || !strings.Contains(f.info, "`")) {
    +			open, fenceIndent, spansKnown = f, indentWidth(line), true
    +			continue
    +		}
    +		if strings.TrimSpace(line) == "" {
    +			spansKnown = true
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		if linkDefinition.MatchString(line) {
    +			return "", fmt.Errorf("line %q: reference-style link definitions are not allowed; write the link inline, as [text](target)", line)
    +		}
    +		if htmlStart.MatchString(line) {
    +			htmlSeen = true
    +		}
    +		// spans is line with its code span contents blanked, at the same byte offsets, when
    +		// startKnown; masked is spans unless the line may be in an HTML block, where backticks do
    +		// not start code spans, so the checks see the whole line.
    +		startKnown := spansKnown
    +		spans := line
    +		if startKnown {
    +			spans, spansKnown = maskCodeSpans(line)
    +		}
    +		masked := spans
    +		if htmlSeen {
    +			masked = line
    +		}
    +		if htmlLink.MatchString(masked) {
    +			return "", fmt.Errorf("line %q: HTML links and images are not allowed; write a Markdown link, [text](target), or image, ![alt](target)", line)
    +		}
    +		var b, rest strings.Builder // rest is masked without the inline link targets
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(masked, -1) {
    +			if strings.Contains(masked[last:loc[0]], "](") || masked[loc[2]] == '<' {
    +				return "", unparsedLink(line)
    +			}
    +			target := line[loc[2]:loc[3]]
    +			// A code span cannot start or end between the '(' and the target, which has no backtick:
    +			// the '(' is blanked in spans exactly when the target is in a code span, which is left
    +			// as written.
    +			if !startKnown || spans[loc[2]-1] == '(' {
    +				rewritten, err := rootRelative(target)
    +				if err != nil {
    +					return "", err
    +				}
    +				if !startKnown && rewritten != target {
    +					return "", fmt.Errorf("line %q: cannot tell whether the link to %q is in inline code, because an earlier line of the paragraph leaves a backtick, HTML tag or autolink open; write each piece of inline code on one line and escape a literal backtick as \\`", line, target)
    +				}
    +				target = rewritten
    +			}
    +			b.WriteString(line[last:loc[2]])
    +			b.WriteString(target)
    +			b.WriteString(line[loc[3]:loc[1]])
    +			rest.WriteString(masked[last:loc[2]])
    +			rest.WriteString(masked[loc[3]:loc[1]])
    +			last = loc[1]
    +		}
    +		if strings.Contains(masked[last:], "](") {
    +			return "", unparsedLink(line)
    +		}
    +		rest.WriteString(masked[last:])
    +		if parentDir.MatchString(rest.String()) {
    +			return "", fmt.Errorf("line %q: ../ is allowed only in an inline link target, [text](target), or in inline code; assembly rewrites only those targets, and any other relative path would resolve from CHANGELOG.md instead of the fragment", line)
    +		}
    +		b.WriteString(line[last:])
    +		lines[i] = b.String()
    +	}
    +	if open.length > 0 {
    +		return "", errors.New("unterminated code fence")
    +	}
    +	return strings.Join(lines, "\n"), nil

    A fragment containing - Entry. followed by a blank line and <!-- draft passes validation, but its unterminated HTML comment hides subsequent entries and release sections after assembly. Assembly deletes the fragment and verify-assembled succeeds despite the damaged rendering. Require HTML comments outside code to close within the fragment, or reject them, and add an assembly regression case.

    Copilot Copilot commented on code on Oct 28, 2026 03:26 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +
    +		`(?:$|(?:<(?:[^>\\]|\\.)*>|\S+)[ \t]*(?:$|["'(]))`)
    +	// htmlLink matches an HTML link or image target attribute, also when its tag opened on an
    +	// earlier line. An anchor without one (<a name="x"></a>), which CHANGELOG.md uses, is allowed.
    +	htmlLink = regexp.MustCompile(`(?i)\b(?:href|src|srcset)\s*=`)
    +	// htmlStart matches a line that starts with an HTML tag or comment, which can open an HTML block,
    +	// where backticks do not start code spans.
    +	htmlStart = regexp.MustCompile(containers + `<`)
    +	// parentDir matches a parent directory step (../), also with dots or slash percent-encoded or
    +	// written as HTML character references, or with a backslash, which browsers treat as a slash.
    +	parentDir = regexp.MustCompile(`(?i)(?:\.|%2e|&#0*46;?|&#x0*2e;?|&period;){2}` +
    +		`(?:/|\\|%2f|%5c|&#0*47;?|&#x0*2f;?|&sol;|&#0*92;?|&#x0*5c;?|&bsol;)`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. It refuses the link
    +// forms it cannot rewrite: an inline link in another form than linkTarget, a link reference
    +// definition (whose label would also apply to every fragment and release section) and an HTML
    +// link or image attribute. As a backstop for any other form, it refuses a parent directory step
    +// (../) left outside an inline link target and a code span: every in-repository target written
    +// relative to the fragment needs one, and a rewritten target has none. A relative target without
    +// one could only name a file in fragmentDir, which a release deletes.
    +//
    +// Fenced code blocks are left alone. A block closes as in CommonMark: on a fence of the opening
    +// fence's character, at least as long, with nothing but spaces and tabs after it. A non-blank line
    +// in a fenced block indented less than the opening fence is refused: in a list item it ends the
    +// item, and so the block, and Markdown renders it as text (a "# " line as a heading) and the later
    +// closing fence as the start of a block that never closes. A closing fence indented 1 to 3 columns
    +// past the opening fence is refused too: whether it closes the block depends on the opening fence's
    +// indentation within its list item. Indented 4 or more past it, it is code.
    +//
    +// Code spans are skipped by the link checks only where maskCodeSpans finds them for certain; see
    +// there. Where it cannot tell whether a line starts in a code span, the line is checked unmasked,
    +// and a link whose target assembly would change is refused, since it may be code that assembly
    +// must not rewrite. A link-shaped text in an HTML block, where Markdown renders no links, is
    +// rewritten like a link: that changes text only.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	var open codeFence // the opening fence of the current block; open.length == 0 outside one
    +	fenceIndent := 0
    +	// spansKnown is false from a line that may leave a code span, HTML tag or autolink open until
    +	// the paragraph ends; htmlSeen is true from a line that may open an HTML block to the end.
    +	spansKnown, htmlSeen := true, false
    +	for i, line := range lines {
    +		if open.length > 0 {
    +			indent := indentWidth(line)
    +			if strings.TrimSpace(line) != "" && indent < fenceIndent {
    +				return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +			}
    +			f, ok := parseFence(line)
    +			if !ok || f.char != open.char || f.length < open.length || strings.Trim(f.info, " \t") != "" ||
    +				indent >= fenceIndent+4 {
    +				continue
    +			}
    +			if indent > fenceIndent {
    +				return "", fmt.Errorf("line %q: closing fence indented more than its opening fence; indent it as far as the opening fence", line)
    +			}
    +			open, spansKnown = codeFence{}, true
    +			continue
    +		}
    +		if f, ok := parseFence(line); ok && (f.char != '`' || !strings.Contains(f.info, "`")) {
    +			open, fenceIndent, spansKnown = f, indentWidth(line), true
    +			continue
    +		}
    +		if strings.TrimSpace(line) == "" {
    +			spansKnown = true
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		if linkDefinition.MatchString(line) {
    +			return "", fmt.Errorf("line %q: reference-style link definitions are not allowed; write the link inline, as [text](target)", line)
    +		}
    +		if htmlStart.MatchString(line) {
    +			htmlSeen = true
    +		}
    +		// spans is line with its code span contents blanked, at the same byte offsets, when
    +		// startKnown; masked is spans unless the line may be in an HTML block, where backticks do
    +		// not start code spans, so the checks see the whole line.
    +		startKnown := spansKnown
    +		spans := line
    +		if startKnown {
    +			spans, spansKnown = maskCodeSpans(line)
    +		}
    +		masked := spans
    +		if htmlSeen {
    +			masked = line
    +		}
    +		if htmlLink.MatchString(masked) {
    +			return "", fmt.Errorf("line %q: HTML links and images are not allowed; write a Markdown link, [text](target), or image, ![alt](target)", line)
    +		}
    +		var b, rest strings.Builder // rest is masked without the inline link targets
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(masked, -1) {
    +			if strings.Contains(masked[last:loc[0]], "](") || masked[loc[2]] == '<' {
    +				return "", unparsedLink(line)
    +			}
    +			target := line[loc[2]:loc[3]]
    +			// A code span cannot start or end between the '(' and the target, which has no backtick:
    +			// the '(' is blanked in spans exactly when the target is in a code span, which is left
    +			// as written.
    +			if !startKnown || spans[loc[2]-1] == '(' {
    +				rewritten, err := rootRelative(target)
    +				if err != nil {
    +					return "", err
    +				}
    +				if !startKnown && rewritten != target {
    +					return "", fmt.Errorf("line %q: cannot tell whether the link to %q is in inline code, because an earlier line of the paragraph leaves a backtick, HTML tag or autolink open; write each piece of inline code on one line and escape a literal backtick as \\`", line, target)
    +				}
    +				target = rewritten
    +			}
    +			b.WriteString(line[last:loc[2]])
    +			b.WriteString(target)
    +			b.WriteString(line[loc[3]:loc[1]])
    +			rest.WriteString(masked[last:loc[2]])
    +			rest.WriteString(masked[loc[3]:loc[1]])
    +			last = loc[1]
    +		}
    +		if strings.Contains(masked[last:], "](") {
    +			return "", unparsedLink(line)
    +		}
    +		rest.WriteString(masked[last:])
    +		if parentDir.MatchString(rest.String()) {
    +			return "", fmt.Errorf("line %q: ../ is allowed only in an inline link target, [text](target), or in inline code; assembly rewrites only those targets, and any other relative path would resolve from CHANGELOG.md instead of the fragment", line)
    +		}
    +		b.WriteString(line[last:])
    +		lines[i] = b.String()
    +	}
    +	if open.length > 0 {
    +		return "", errors.New("unterminated code fence")
    +	}
    +	return strings.Join(lines, "\n"), nil
    +}
    +
    +// maskCodeSpans returns line with the contents of each code span on it replaced by '_', and
    +// whether the next line starts outside any code span, HTML tag and autolink. Pairing follows
    +// CommonMark: a run of backticks opens a span closed by the next run of the same length, an
    +// unmatched run is text, and a backslash escapes a backtick. It assumes line starts outside a code
    +// span, HTML tag and autolink; the caller does not call it after a line where that may not hold. A
    +// run of backticks inside an HTML tag or autolink that may still be open (see openTag) does not
    +// open a span: masking stops there. It returns false after an unmatched run, which a later line may
    +// close, after masking stopped, and when line ends inside a construct openTag reports open.
    +func maskCodeSpans(line string) (string, bool) {
    +	b := []byte(line)
    +	clean := true
    +	for i := 0; i < len(b); {
    +		switch {
    +		case b[i] == '\\' && i+1 < len(b) && (b[i+1] == '`' || b[i+1] == '\\'):
    +			i += 2
    +			continue
    +		case b[i] != '`':
    +			i++
    +			continue
    +		}
    +		if openTag(b[:i]) {
    +			return string(b), false
    +		}
    +		n := backtickRun(b, i)
    +		closer := -1
    +		for j := i + n; j < len(b); {
    +			if b[j] != '`' {
    +				j++
    +				continue
    +			}
    +			m := backtickRun(b, j)
    +			if m == n {
    +				closer = j
    +				break
    +			}
    +			j += m
    +		}
    +		if closer < 0 {
    +			clean = false
    +			i += n
    +			continue
    +		}
    +		for k := i + n; k < closer; k++ {
    +			b[k] = '_'
    +		}
    +		i = closer + n
    +	}
    +	return string(b), clean && !openTag(b)
    +}
    +
    +// backtickRun returns the length of the run of backticks starting at b[i].
    +func backtickRun(b []byte, i int) int {
    +	n := 0
    +	for i+n < len(b) && b[i+n] == '`' {
    +		n++
    +	}
    +	return n
    +}
    +
    +// openTag reports whether b ends inside an HTML tag, comment, processing instruction, declaration,
    +// CDATA section or autolink that starts in it. A quoted attribute value is skipped, so a '>' in one
    +// does not end its tag. It errs towards open: a '<' before a letter, '/', '!' or '?' counts as a
    +// start even if the text after it is not a valid tag, which only makes the checks stricter.
    +func openTag(b []byte) bool {
    +	for i := 0; i < len(b); i++ {
    +		if b[i] != '<' {
    +			continue
    +		}
    +		end := tagEnd(b, i)
    +		if end < 0 {
    +			return true
    +		}
    +		i = end
    +	}
    +	return false
    +}
    +
    +// tagEnd returns the index of the last byte of the construct that the '<' at b[i] may start, i if
    +// it cannot start one, or -1 if b ends inside it.
    +func tagEnd(b []byte, i int) int {
    +	s := b[i:]
    +	find := func(from int, end string) int {
    +		if from > len(s) {
    +			return -1
    +		}
    +		k := bytes.Index(s[from:], []byte(end))
    +		if k < 0 {
    +			return -1
    +		}
    +		return i + from + k + len(end) - 1
    +	}
    +	switch {
    +	case bytes.HasPrefix(s, []byte("<!--")):
    +		return find(4, "-->")
    +	case bytes.HasPrefix(s, []byte("<![CDATA[")):
    +		return find(9, "]]>")
    +	case bytes.HasPrefix(s, []byte("<?")):
    +		return find(2, "?>")
    +	case len(s) > 1 && (s[1] == '!' || s[1] == '/'):
    +		return find(2, ">")
    +	case len(s) > 1 && ('a' <= s[1]|0x20 && s[1]|0x20 <= 'z'):
    +		for j := 2; j < len(s); j++ {
    +			switch s[j] {
    +			case '"', '\'':
    +				k := bytes.IndexByte(s[j+1:], s[j])
    +				if k < 0 {
    +					return -1
    +				}
    +				j += k + 1
    +			case '>':
    +				return i + j
    +			}
    +		}
    +		return -1
    +	}
    +	return i
    +}
    +
    +// unparsedLink is the error for a "](" that does not start a linkTarget, such as a target in angle
    +// brackets, after a space, with a backtick or a 'title' or split across lines.
    +func unparsedLink(line string) error {
    +	return fmt.Errorf("line %q: write each link on one line as [text](target) or [text](target \"title\"), with no spaces, angle brackets or backticks around or in the target", line)
    +}
    +
    +// codeFence is a run of three or more backticks or tildes that opens or closes a fenced code
    +// block, and the text after it on its line.
    +type codeFence struct {
    +	char   byte
    +	length int
    +	info   string
    +}
    +
    +// parseFence parses line, after its indentation, as a code fence. A backtick fence opens a block
    +// only when its info string has no backtick; the caller checks that.
    +func parseFence(line string) (codeFence, bool) {
    +	s := strings.TrimLeft(line, " \t")
    +	if s == "" || (s[0] != '`' && s[0] != '~') {
    +		return codeFence{}, false
    +	}
    +	rest := strings.TrimLeft(s, s[:1])
    +	f := codeFence{char: s[0], length: len(s) - len(rest), info: rest}
    +	return f, f.length >= 3
    +}
    +
    +// indentWidth returns the column of line's first non-blank character, with a tab advancing to the
    +// next multiple of 4 as in CommonMark.
    +func indentWidth(line string) int {
    +	w := 0
    +	for _, r := range line {
    +		switch r {
    +		case ' ':
    +			w++
    +		case '\t':
    +			w += 4 - w%4
    +		default:
    +			return w
    +		}
    +	}
    +	return w
    +}
    +
    +// rootRelative turns a link target written relative to fragmentDir into one relative to the
    +// repository root. URLs and same-file anchors are returned unchanged.
    +func rootRelative(target string) (string, error) {
    +	if strings.HasPrefix(target, "#") || strings.Contains(target, "://") ||
    +		strings.HasPrefix(target, "mailto:") || strings.HasPrefix(target, "tel:") {
    +		return target, nil
    +	}
    +	if strings.HasPrefix(target, "/") {
    +		return "", fmt.Errorf("link %q: use a path relative to the fragment, such as ../../docs/concepts.md", target)
    +	}
    +	// path.Join resolves only a literal ../; a browser also resolves an encoded one, so a target
    +	// with one could still point outside the repository after the rewrite. The whole target is
    +	// checked: a character reference has a '#' that is not an anchor.
    +	for _, step := range parentDir.FindAllString(target, -1) {
    +		if step != "../" {
    +			return "", fmt.Errorf("link %q: write each parent directory step as ../, not %q", target, step)
    +		}
    +	}
    +	file, anchor, hasAnchor := strings.Cut(target, "#")
    +	p := path.Clean(path.Join(fragmentDir, file))
    +	if p == ".." || strings.HasPrefix(p, "../") {
    +		return "", fmt.Errorf("link %q: points outside the repository", target)
    +	}

    A link such as [related change](other.md) passes validation and resolves while the fragments exist, but this rewrites it to changelog/unreleased/other.md and assemble then deletes that target. The resulting CHANGELOG contains a broken link even though both input fragments are valid. Reject links to fragment files, or remap them to persistent locations in the assembled changelog.

    Copilot Copilot commented on code on Oct 28, 2026 03:26 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +
    +		`(?:$|(?:<(?:[^>\\]|\\.)*>|\S+)[ \t]*(?:$|["'(]))`)
    +	// htmlLink matches an HTML link or image target attribute, also when its tag opened on an
    +	// earlier line. An anchor without one (<a name="x"></a>), which CHANGELOG.md uses, is allowed.
    +	htmlLink = regexp.MustCompile(`(?i)\b(?:href|src|srcset)\s*=`)
    +	// htmlStart matches a line that starts with an HTML tag or comment, which can open an HTML block,
    +	// where backticks do not start code spans.
    +	htmlStart = regexp.MustCompile(containers + `<`)
    +	// parentDir matches a parent directory step (../), also with dots or slash percent-encoded or
    +	// written as HTML character references, or with a backslash, which browsers treat as a slash.
    +	parentDir = regexp.MustCompile(`(?i)(?:\.|%2e|&#0*46;?|&#x0*2e;?|&period;){2}` +
    +		`(?:/|\\|%2f|%5c|&#0*47;?|&#x0*2f;?|&sol;|&#0*92;?|&#x0*5c;?|&bsol;)`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. It refuses the link
    +// forms it cannot rewrite: an inline link in another form than linkTarget, a link reference
    +// definition (whose label would also apply to every fragment and release section) and an HTML
    +// link or image attribute. As a backstop for any other form, it refuses a parent directory step
    +// (../) left outside an inline link target and a code span: every in-repository target written
    +// relative to the fragment needs one, and a rewritten target has none. A relative target without
    +// one could only name a file in fragmentDir, which a release deletes.
    +//
    +// Fenced code blocks are left alone. A block closes as in CommonMark: on a fence of the opening
    +// fence's character, at least as long, with nothing but spaces and tabs after it. A non-blank line
    +// in a fenced block indented less than the opening fence is refused: in a list item it ends the
    +// item, and so the block, and Markdown renders it as text (a "# " line as a heading) and the later
    +// closing fence as the start of a block that never closes. A closing fence indented 1 to 3 columns
    +// past the opening fence is refused too: whether it closes the block depends on the opening fence's
    +// indentation within its list item. Indented 4 or more past it, it is code.
    +//
    +// Code spans are skipped by the link checks only where maskCodeSpans finds them for certain; see
    +// there. Where it cannot tell whether a line starts in a code span, the line is checked unmasked,
    +// and a link whose target assembly would change is refused, since it may be code that assembly
    +// must not rewrite. A link-shaped text in an HTML block, where Markdown renders no links, is
    +// rewritten like a link: that changes text only.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	var open codeFence // the opening fence of the current block; open.length == 0 outside one
    +	fenceIndent := 0
    +	// spansKnown is false from a line that may leave a code span, HTML tag or autolink open until
    +	// the paragraph ends; htmlSeen is true from a line that may open an HTML block to the end.
    +	spansKnown, htmlSeen := true, false
    +	for i, line := range lines {
    +		if open.length > 0 {
    +			indent := indentWidth(line)
    +			if strings.TrimSpace(line) != "" && indent < fenceIndent {
    +				return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +			}
    +			f, ok := parseFence(line)
    +			if !ok || f.char != open.char || f.length < open.length || strings.Trim(f.info, " \t") != "" ||
    +				indent >= fenceIndent+4 {
    +				continue
    +			}
    +			if indent > fenceIndent {
    +				return "", fmt.Errorf("line %q: closing fence indented more than its opening fence; indent it as far as the opening fence", line)
    +			}
    +			open, spansKnown = codeFence{}, true
    +			continue
    +		}
    +		if f, ok := parseFence(line); ok && (f.char != '`' || !strings.Contains(f.info, "`")) {
    +			open, fenceIndent, spansKnown = f, indentWidth(line), true
    +			continue
    +		}
    +		if strings.TrimSpace(line) == "" {
    +			spansKnown = true
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		if linkDefinition.MatchString(line) {
    +			return "", fmt.Errorf("line %q: reference-style link definitions are not allowed; write the link inline, as [text](target)", line)
    +		}
    +		if htmlStart.MatchString(line) {
    +			htmlSeen = true
    +		}
    +		// spans is line with its code span contents blanked, at the same byte offsets, when
    +		// startKnown; masked is spans unless the line may be in an HTML block, where backticks do
    +		// not start code spans, so the checks see the whole line.
    +		startKnown := spansKnown
    +		spans := line
    +		if startKnown {
    +			spans, spansKnown = maskCodeSpans(line)
    +		}
    +		masked := spans
    +		if htmlSeen {
    +			masked = line
    +		}
    +		if htmlLink.MatchString(masked) {
    +			return "", fmt.Errorf("line %q: HTML links and images are not allowed; write a Markdown link, [text](target), or image, ![alt](target)", line)
    +		}
    +		var b, rest strings.Builder // rest is masked without the inline link targets
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(masked, -1) {
    +			if strings.Contains(masked[last:loc[0]], "](") || masked[loc[2]] == '<' {
    +				return "", unparsedLink(line)
    +			}
    +			target := line[loc[2]:loc[3]]
    +			// A code span cannot start or end between the '(' and the target, which has no backtick:
    +			// the '(' is blanked in spans exactly when the target is in a code span, which is left
    +			// as written.
    +			if !startKnown || spans[loc[2]-1] == '(' {
    +				rewritten, err := rootRelative(target)
    +				if err != nil {
    +					return "", err
    +				}
    +				if !startKnown && rewritten != target {
    +					return "", fmt.Errorf("line %q: cannot tell whether the link to %q is in inline code, because an earlier line of the paragraph leaves a backtick, HTML tag or autolink open; write each piece of inline code on one line and escape a literal backtick as \\`", line, target)
    +				}
    +				target = rewritten
    +			}
    +			b.WriteString(line[last:loc[2]])
    +			b.WriteString(target)
    +			b.WriteString(line[loc[3]:loc[1]])
    +			rest.WriteString(masked[last:loc[2]])
    +			rest.WriteString(masked[loc[3]:loc[1]])
    +			last = loc[1]
    +		}
    +		if strings.Contains(masked[last:], "](") {
    +			return "", unparsedLink(line)
    +		}
    +		rest.WriteString(masked[last:])
    +		if parentDir.MatchString(rest.String()) {
    +			return "", fmt.Errorf("line %q: ../ is allowed only in an inline link target, [text](target), or in inline code; assembly rewrites only those targets, and any other relative path would resolve from CHANGELOG.md instead of the fragment", line)
    +		}
    +		b.WriteString(line[last:])
    +		lines[i] = b.String()
    +	}
    +	if open.length > 0 {
    +		return "", errors.New("unterminated code fence")
    +	}
    +	return strings.Join(lines, "\n"), nil
    +}
    +
    +// maskCodeSpans returns line with the contents of each code span on it replaced by '_', and
    +// whether the next line starts outside any code span, HTML tag and autolink. Pairing follows
    +// CommonMark: a run of backticks opens a span closed by the next run of the same length, an
    +// unmatched run is text, and a backslash escapes a backtick. It assumes line starts outside a code
    +// span, HTML tag and autolink; the caller does not call it after a line where that may not hold. A
    +// run of backticks inside an HTML tag or autolink that may still be open (see openTag) does not
    +// open a span: masking stops there. It returns false after an unmatched run, which a later line may
    +// close, after masking stopped, and when line ends inside a construct openTag reports open.
    +func maskCodeSpans(line string) (string, bool) {
    +	b := []byte(line)
    +	clean := true
    +	for i := 0; i < len(b); {
    +		switch {
    +		case b[i] == '\\' && i+1 < len(b) && (b[i+1] == '`' || b[i+1] == '\\'):
    +			i += 2
    +			continue
    +		case b[i] != '`':
    +			i++
    +			continue
    +		}
    +		if openTag(b[:i]) {
    +			return string(b), false
    +		}
    +		n := backtickRun(b, i)
    +		closer := -1
    +		for j := i + n; j < len(b); {
    +			if b[j] != '`' {
    +				j++
    +				continue
    +			}
    +			m := backtickRun(b, j)
    +			if m == n {
    +				closer = j
    +				break
    +			}
    +			j += m
    +		}
    +		if closer < 0 {
    +			clean = false
    +			i += n
    +			continue
    +		}
    +		for k := i + n; k < closer; k++ {
    +			b[k] = '_'
    +		}
    +		i = closer + n
    +	}
    +	return string(b), clean && !openTag(b)
    +}
    +
    +// backtickRun returns the length of the run of backticks starting at b[i].
    +func backtickRun(b []byte, i int) int {
    +	n := 0
    +	for i+n < len(b) && b[i+n] == '`' {
    +		n++
    +	}
    +	return n
    +}
    +
    +// openTag reports whether b ends inside an HTML tag, comment, processing instruction, declaration,
    +// CDATA section or autolink that starts in it. A quoted attribute value is skipped, so a '>' in one
    +// does not end its tag. It errs towards open: a '<' before a letter, '/', '!' or '?' counts as a
    +// start even if the text after it is not a valid tag, which only makes the checks stricter.
    +func openTag(b []byte) bool {
    +	for i := 0; i < len(b); i++ {
    +		if b[i] != '<' {
    +			continue
    +		}
    +		end := tagEnd(b, i)
    +		if end < 0 {
    +			return true
    +		}
    +		i = end
    +	}
    +	return false
    +}
    +
    +// tagEnd returns the index of the last byte of the construct that the '<' at b[i] may start, i if
    +// it cannot start one, or -1 if b ends inside it.
    +func tagEnd(b []byte, i int) int {
    +	s := b[i:]
    +	find := func(from int, end string) int {
    +		if from > len(s) {
    +			return -1
    +		}
    +		k := bytes.Index(s[from:], []byte(end))
    +		if k < 0 {
    +			return -1
    +		}
    +		return i + from + k + len(end) - 1
    +	}
    +	switch {
    +	case bytes.HasPrefix(s, []byte("<!--")):
    +		return find(4, "-->")
    +	case bytes.HasPrefix(s, []byte("<![CDATA[")):
    +		return find(9, "]]>")
    +	case bytes.HasPrefix(s, []byte("<?")):
    +		return find(2, "?>")
    +	case len(s) > 1 && (s[1] == '!' || s[1] == '/'):
    +		return find(2, ">")
    +	case len(s) > 1 && ('a' <= s[1]|0x20 && s[1]|0x20 <= 'z'):
    +		for j := 2; j < len(s); j++ {
    +			switch s[j] {
    +			case '"', '\'':
    +				k := bytes.IndexByte(s[j+1:], s[j])
    +				if k < 0 {
    +					return -1
    +				}
    +				j += k + 1
    +			case '>':
    +				return i + j
    +			}
    +		}
    +		return -1
    +	}
    +	return i
    +}
    +
    +// unparsedLink is the error for a "](" that does not start a linkTarget, such as a target in angle
    +// brackets, after a space, with a backtick or a 'title' or split across lines.
    +func unparsedLink(line string) error {
    +	return fmt.Errorf("line %q: write each link on one line as [text](target) or [text](target \"title\"), with no spaces, angle brackets or backticks around or in the target", line)
    +}
    +
    +// codeFence is a run of three or more backticks or tildes that opens or closes a fenced code
    +// block, and the text after it on its line.
    +type codeFence struct {
    +	char   byte
    +	length int
    +	info   string
    +}
    +
    +// parseFence parses line, after its indentation, as a code fence. A backtick fence opens a block
    +// only when its info string has no backtick; the caller checks that.
    +func parseFence(line string) (codeFence, bool) {
    +	s := strings.TrimLeft(line, " \t")
    +	if s == "" || (s[0] != '`' && s[0] != '~') {
    +		return codeFence{}, false
    +	}
    +	rest := strings.TrimLeft(s, s[:1])
    +	f := codeFence{char: s[0], length: len(s) - len(rest), info: rest}
    +	return f, f.length >= 3
    +}
    +
    +// indentWidth returns the column of line's first non-blank character, with a tab advancing to the
    +// next multiple of 4 as in CommonMark.
    +func indentWidth(line string) int {
    +	w := 0
    +	for _, r := range line {
    +		switch r {
    +		case ' ':
    +			w++
    +		case '\t':
    +			w += 4 - w%4
    +		default:
    +			return w
    +		}
    +	}
    +	return w
    +}
    +
    +// rootRelative turns a link target written relative to fragmentDir into one relative to the
    +// repository root. URLs and same-file anchors are returned unchanged.
    +func rootRelative(target string) (string, error) {
    +	if strings.HasPrefix(target, "#") || strings.Contains(target, "://") ||
    +		strings.HasPrefix(target, "mailto:") || strings.HasPrefix(target, "tel:") {
    +		return target, nil
    +	}
    +	if strings.HasPrefix(target, "/") {
    +		return "", fmt.Errorf("link %q: use a path relative to the fragment, such as ../../docs/concepts.md", target)
    +	}
    +	// path.Join resolves only a literal ../; a browser also resolves an encoded one, so a target
    +	// with one could still point outside the repository after the rewrite. The whole target is
    +	// checked: a character reference has a '#' that is not an anchor.
    +	for _, step := range parentDir.FindAllString(target, -1) {
    +		if step != "../" {
    +			return "", fmt.Errorf("link %q: write each parent directory step as ../, not %q", target, step)
    +		}
    +	}
    +	file, anchor, hasAnchor := strings.Cut(target, "#")
    +	p := path.Clean(path.Join(fragmentDir, file))
    +	if p == ".." || strings.HasPrefix(p, "../") {
    +		return "", fmt.Errorf("link %q: points outside the repository", target)
    +	}
    +	if p == "CHANGELOG.md" && hasAnchor {
    +		return "#" + anchor, nil
    +	}
    +	if hasAnchor {
    +		p += "#" + anchor
    +	}
    +	return p, nil
    +}
    +
    +// file is a directory entry under fragmentDir with its contents.
    +type file struct {
    +	name string
    +	data []byte
    +	dir  bool
    +}
    +
    +// parseFragments validates every entry of fragmentDir and returns the fragments in release order:
    +// category order, then file name. Anything other than a valid fragment or keepFile is an error, so
    +// a misnamed fragment cannot be skipped silently.
    +func parseFragments(files []file) ([]fragment, error) {
    +	var frags []fragment
    +	var errs []error
    +	for _, f := range files {
    +		switch {
    +		case f.name == keepFile:
    +		case f.dir:
    +			errs = append(errs, fmt.Errorf("%s/: directories are not allowed in %s", f.name, fragmentDir))
    +		default:
    +			frag, err := parseFragment(f.name, f.data)
    +			if err != nil {
    +				errs = append(errs, err)
    +				continue
    +			}
    +			frags = append(frags, frag)
    +		}
    +	}
    +	if err := errors.Join(errs...); err != nil {
    +		return nil, err
    +	}
    +	slices.SortFunc(frags, func(a, b fragment) int {
    +		if c := slices.Index(categories, a.category) - slices.Index(categories, b.category); c != 0 {
    +			return c
    +		}
    +		return strings.Compare(a.name, b.name)
    +	})
    +	return frags, nil
    +}
    +
    +// renderSection renders the CHANGELOG.md section for a release from fragments in release order.
    +func renderSection(version, date string, frags []fragment) string {
    +	var b strings.Builder
    +	fmt.Fprintf(&b, "## %s - %s\n", version, date)
    +	current := ""
    +	for _, f := range frags {
    +		if f.category != current {
    +			current = f.category
    +			fmt.Fprintf(&b, "\n### %s\n\n", current)
    +		}
    +		b.WriteString(f.body)
    +		b.WriteString("\n")
    +	}
    +	return b.String()
    +}
    +
    +// unreleasedHeading reports whether changelog has an "## Unreleased" section, which fragments
    +// replace.
    +func unreleasedHeading(changelog string) bool {
    +	for line := range strings.SplitSeq(changelog, "\n") {
    +		if strings.EqualFold(strings.TrimSpace(line), "## Unreleased") {
    +			return true
    +		}
    +	}
    +	return false
    +}

    Recognize Markdown's optional closing heading hashes instead of comparing the entire source line. The valid heading ## Unreleased ## returns false here, so both check and verify-assembled accept a changelog that still contains Unreleased notes, and assemble leaves that section behind. Normalize the heading syntax before comparing its title, and cover closing hashes and tab-separated headings in the tests.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 28, 2026 03:26 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Changelog validation and assembly still permit unterminated comments, colliding footnotes, links to deleted fragments, and missed Unreleased headings, allowing damaged output to pass verification.

    <details open>
    <summary><strong>4 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Duplicate footnote labels collide across assembled fragments · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Unterminated HTML comments hide assembled changelog entries · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Fragment-relative links become broken after assembly · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Closing heading hashes bypass Unreleased section detection · New

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Match closing fences to the opening fence length

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Propagate git show errors for missing changelog files

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Oct 28, 2026 05:27 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +

    Fixed in #230 by refusing footnotes in fragments rather than isolating labels: a fragment can't know which others share the assembled document.

    aramase aramase commented on code on Oct 28, 2026 05:27 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +
    +		`(?:$|(?:<(?:[^>\\]|\\.)*>|\S+)[ \t]*(?:$|["'(]))`)
    +	// htmlLink matches an HTML link or image target attribute, also when its tag opened on an
    +	// earlier line. An anchor without one (<a name="x"></a>), which CHANGELOG.md uses, is allowed.
    +	htmlLink = regexp.MustCompile(`(?i)\b(?:href|src|srcset)\s*=`)
    +	// htmlStart matches a line that starts with an HTML tag or comment, which can open an HTML block,
    +	// where backticks do not start code spans.
    +	htmlStart = regexp.MustCompile(containers + `<`)
    +	// parentDir matches a parent directory step (../), also with dots or slash percent-encoded or
    +	// written as HTML character references, or with a backslash, which browsers treat as a slash.
    +	parentDir = regexp.MustCompile(`(?i)(?:\.|%2e|&#0*46;?|&#x0*2e;?|&period;){2}` +
    +		`(?:/|\\|%2f|%5c|&#0*47;?|&#x0*2f;?|&sol;|&#0*92;?|&#x0*5c;?|&bsol;)`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. It refuses the link
    +// forms it cannot rewrite: an inline link in another form than linkTarget, a link reference
    +// definition (whose label would also apply to every fragment and release section) and an HTML
    +// link or image attribute. As a backstop for any other form, it refuses a parent directory step
    +// (../) left outside an inline link target and a code span: every in-repository target written
    +// relative to the fragment needs one, and a rewritten target has none. A relative target without
    +// one could only name a file in fragmentDir, which a release deletes.
    +//
    +// Fenced code blocks are left alone. A block closes as in CommonMark: on a fence of the opening
    +// fence's character, at least as long, with nothing but spaces and tabs after it. A non-blank line
    +// in a fenced block indented less than the opening fence is refused: in a list item it ends the
    +// item, and so the block, and Markdown renders it as text (a "# " line as a heading) and the later
    +// closing fence as the start of a block that never closes. A closing fence indented 1 to 3 columns
    +// past the opening fence is refused too: whether it closes the block depends on the opening fence's
    +// indentation within its list item. Indented 4 or more past it, it is code.
    +//
    +// Code spans are skipped by the link checks only where maskCodeSpans finds them for certain; see
    +// there. Where it cannot tell whether a line starts in a code span, the line is checked unmasked,
    +// and a link whose target assembly would change is refused, since it may be code that assembly
    +// must not rewrite. A link-shaped text in an HTML block, where Markdown renders no links, is
    +// rewritten like a link: that changes text only.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	var open codeFence // the opening fence of the current block; open.length == 0 outside one
    +	fenceIndent := 0
    +	// spansKnown is false from a line that may leave a code span, HTML tag or autolink open until
    +	// the paragraph ends; htmlSeen is true from a line that may open an HTML block to the end.
    +	spansKnown, htmlSeen := true, false
    +	for i, line := range lines {
    +		if open.length > 0 {
    +			indent := indentWidth(line)
    +			if strings.TrimSpace(line) != "" && indent < fenceIndent {
    +				return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +			}
    +			f, ok := parseFence(line)
    +			if !ok || f.char != open.char || f.length < open.length || strings.Trim(f.info, " \t") != "" ||
    +				indent >= fenceIndent+4 {
    +				continue
    +			}
    +			if indent > fenceIndent {
    +				return "", fmt.Errorf("line %q: closing fence indented more than its opening fence; indent it as far as the opening fence", line)
    +			}
    +			open, spansKnown = codeFence{}, true
    +			continue
    +		}
    +		if f, ok := parseFence(line); ok && (f.char != '`' || !strings.Contains(f.info, "`")) {
    +			open, fenceIndent, spansKnown = f, indentWidth(line), true
    +			continue
    +		}
    +		if strings.TrimSpace(line) == "" {
    +			spansKnown = true
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		if linkDefinition.MatchString(line) {
    +			return "", fmt.Errorf("line %q: reference-style link definitions are not allowed; write the link inline, as [text](target)", line)
    +		}
    +		if htmlStart.MatchString(line) {
    +			htmlSeen = true
    +		}
    +		// spans is line with its code span contents blanked, at the same byte offsets, when
    +		// startKnown; masked is spans unless the line may be in an HTML block, where backticks do
    +		// not start code spans, so the checks see the whole line.
    +		startKnown := spansKnown
    +		spans := line
    +		if startKnown {
    +			spans, spansKnown = maskCodeSpans(line)
    +		}
    +		masked := spans
    +		if htmlSeen {
    +			masked = line
    +		}
    +		if htmlLink.MatchString(masked) {
    +			return "", fmt.Errorf("line %q: HTML links and images are not allowed; write a Markdown link, [text](target), or image, ![alt](target)", line)
    +		}
    +		var b, rest strings.Builder // rest is masked without the inline link targets
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(masked, -1) {
    +			if strings.Contains(masked[last:loc[0]], "](") || masked[loc[2]] == '<' {
    +				return "", unparsedLink(line)
    +			}
    +			target := line[loc[2]:loc[3]]
    +			// A code span cannot start or end between the '(' and the target, which has no backtick:
    +			// the '(' is blanked in spans exactly when the target is in a code span, which is left
    +			// as written.
    +			if !startKnown || spans[loc[2]-1] == '(' {
    +				rewritten, err := rootRelative(target)
    +				if err != nil {
    +					return "", err
    +				}
    +				if !startKnown && rewritten != target {
    +					return "", fmt.Errorf("line %q: cannot tell whether the link to %q is in inline code, because an earlier line of the paragraph leaves a backtick, HTML tag or autolink open; write each piece of inline code on one line and escape a literal backtick as \\`", line, target)
    +				}
    +				target = rewritten
    +			}
    +			b.WriteString(line[last:loc[2]])
    +			b.WriteString(target)
    +			b.WriteString(line[loc[3]:loc[1]])
    +			rest.WriteString(masked[last:loc[2]])
    +			rest.WriteString(masked[loc[3]:loc[1]])
    +			last = loc[1]
    +		}
    +		if strings.Contains(masked[last:], "](") {
    +			return "", unparsedLink(line)
    +		}
    +		rest.WriteString(masked[last:])
    +		if parentDir.MatchString(rest.String()) {
    +			return "", fmt.Errorf("line %q: ../ is allowed only in an inline link target, [text](target), or in inline code; assembly rewrites only those targets, and any other relative path would resolve from CHANGELOG.md instead of the fragment", line)
    +		}
    +		b.WriteString(line[last:])
    +		lines[i] = b.String()
    +	}
    +	if open.length > 0 {
    +		return "", errors.New("unterminated code fence")
    +	}
    +	return strings.Join(lines, "\n"), nil

    Fixed in #230, more strictly than asked: HTML comments outside code are refused entirely, since an author can't know which entry assembly puts after theirs.

    aramase aramase commented on code on Oct 28, 2026 05:27 UTC
    Code Review
    hack/changelog/fragment.go:1
    @@ -0,0 +1,483 @@
    +package main
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"path"
    +	"regexp"
    +	"slices"
    +	"strings"
    +)
    +
    +// fragmentDir holds the fragments, relative to the repository root.
    +const fragmentDir = "changelog/unreleased"
    +
    +// keepFile keeps fragmentDir in git once a release has assembled every fragment.
    +const keepFile = ".gitkeep"
    +
    +// categories are the CHANGELOG.md section headings a fragment may name, in the order a release
    +// section lists them (the order v0.2.0 and v0.3.0 use).
    +var categories = []string{"Compatibility", "Added", "Changed", "Fixed", "Security"}
    +
    +var (
    +	fragmentName = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*\.md$`)
    +	categoryLine = regexp.MustCompile(`^category: (\S.*)$`)
    +	// atxHeading matches an ATX heading (# Title) at any indentation and inside block quotes and
    +	// list items, where Markdown still renders it as a heading. It also refuses a "# " line in an
    +	// indented code block; a fenced block holds code with such lines.
    +	atxHeading = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*#{1,6}(?:[ \t]|$)`)
    +	// setextUnderline matches a line of only = or -: a heading underline, or after a blank line a
    +	// thematic break (rule).
    +	setextUnderline = regexp.MustCompile(`^[ \t]*(?:>[ \t]*)*(?:=+|-+)[ \t]*$`)
    +	// linkTarget matches the target of an inline link or image, with an optional "title": the one
    +	// form rewriteLinks rewrites, and the one hack/check-doc-links.py checks. A target with a
    +	// backtick is not matched, so a code span cannot start inside one.
    +	linkTarget = regexp.MustCompile(`\]\(([^)\s` + "`" + `]+)((?:\s+"[^"]*")?\))`)
    +	// containers matches the block quote markers and list markers a line may start with.
    +	containers = `^[ \t]*(?:(?:>|[-*+][ \t]|[0-9]{1,9}[.)][ \t])[ \t]*)*`
    +	// linkDefinition matches the line of a link reference definition ([label]: target) with the
    +	// end of its label, at any indentation and inside block quotes and list items: a label that
    +	// starts on the line, or the last line of one that started on an earlier line (label]: or a bare
    +	// ]:), with escaped characters (\]) in it, then a target on the same line, bare or in angle
    +	// brackets, or on the next. A footnote ([^1]: text) is not one, nor is a label followed by more
    +	// than a target and a title, which Markdown renders as text.
    +	linkDefinition = regexp.MustCompile(containers +
    +		`(?:\[(?:[^\]\\^]|\\.)(?:[^\]\\]|\\.)*|(?:[^\[\]\\]|\\.)*)\]:[ \t]*` +
    +		`(?:$|(?:<(?:[^>\\]|\\.)*>|\S+)[ \t]*(?:$|["'(]))`)
    +	// htmlLink matches an HTML link or image target attribute, also when its tag opened on an
    +	// earlier line. An anchor without one (<a name="x"></a>), which CHANGELOG.md uses, is allowed.
    +	htmlLink = regexp.MustCompile(`(?i)\b(?:href|src|srcset)\s*=`)
    +	// htmlStart matches a line that starts with an HTML tag or comment, which can open an HTML block,
    +	// where backticks do not start code spans.
    +	htmlStart = regexp.MustCompile(containers + `<`)
    +	// parentDir matches a parent directory step (../), also with dots or slash percent-encoded or
    +	// written as HTML character references, or with a backslash, which browsers treat as a slash.
    +	parentDir = regexp.MustCompile(`(?i)(?:\.|%2e|&#0*46;?|&#x0*2e;?|&period;){2}` +
    +		`(?:/|\\|%2f|%5c|&#0*47;?|&#x0*2f;?|&sol;|&#0*92;?|&#x0*5c;?|&bsol;)`)
    +)
    +
    +// fragment is one parsed changelog/unreleased/<name>.md.
    +type fragment struct {
    +	name     string // file name, such as create-harness.md
    +	category string
    +	// body is the entry Markdown, trimmed, with relative links rewritten to resolve from the
    +	// repository root, where CHANGELOG.md lives.
    +	body string
    +}
    +
    +// parseFragment parses and validates one fragment. The format is documented in
    +// changelog/README.md.
    +func parseFragment(name string, data []byte) (fragment, error) {
    +	if !fragmentName.MatchString(name) {
    +		return fragment{}, fmt.Errorf("%s: name must be a lowercase slug ending in .md, such as create-harness.md", name)
    +	}
    +	text := strings.ReplaceAll(string(data), "\r\n", "\n")
    +	lines := strings.Split(text, "\n")
    +	if len(lines) < 3 || lines[0] != "---" || lines[2] != "---" {
    +		return fragment{}, fmt.Errorf("%s: must start with front matter: ---, category: <Category>, ---", name)
    +	}
    +	m := categoryLine.FindStringSubmatch(lines[1])
    +	if m == nil {
    +		return fragment{}, fmt.Errorf("%s: the only front matter line must be \"category: <Category>\", got %q", name, lines[1])
    +	}
    +	category := strings.TrimSpace(m[1])
    +	if !slices.Contains(categories, category) {
    +		return fragment{}, fmt.Errorf("%s: unknown category %q; use one of %s", name, category, strings.Join(categories, ", "))
    +	}
    +	body := strings.TrimSpace(strings.Join(lines[3:], "\n"))
    +	if body == "" {
    +		return fragment{}, fmt.Errorf("%s: no entry after the front matter", name)
    +	}
    +	if !strings.HasPrefix(body, "- ") {
    +		return fragment{}, fmt.Errorf("%s: the entry must be a Markdown list item starting with \"- \"", name)
    +	}
    +	body, err := rewriteLinks(body)
    +	if err != nil {
    +		return fragment{}, fmt.Errorf("%s: %w", name, err)
    +	}
    +	return fragment{name: name, category: category, body: body}, nil
    +}
    +
    +// rewriteLinks rewrites each relative link target in body from fragmentDir-relative to
    +// root-relative, and refuses headings, which belong to the release section. It refuses the link
    +// forms it cannot rewrite: an inline link in another form than linkTarget, a link reference
    +// definition (whose label would also apply to every fragment and release section) and an HTML
    +// link or image attribute. As a backstop for any other form, it refuses a parent directory step
    +// (../) left outside an inline link target and a code span: every in-repository target written
    +// relative to the fragment needs one, and a rewritten target has none. A relative target without
    +// one could only name a file in fragmentDir, which a release deletes.
    +//
    +// Fenced code blocks are left alone. A block closes as in CommonMark: on a fence of the opening
    +// fence's character, at least as long, with nothing but spaces and tabs after it. A non-blank line
    +// in a fenced block indented less than the opening fence is refused: in a list item it ends the
    +// item, and so the block, and Markdown renders it as text (a "# " line as a heading) and the later
    +// closing fence as the start of a block that never closes. A closing fence indented 1 to 3 columns
    +// past the opening fence is refused too: whether it closes the block depends on the opening fence's
    +// indentation within its list item. Indented 4 or more past it, it is code.
    +//
    +// Code spans are skipped by the link checks only where maskCodeSpans finds them for certain; see
    +// there. Where it cannot tell whether a line starts in a code span, the line is checked unmasked,
    +// and a link whose target assembly would change is refused, since it may be code that assembly
    +// must not rewrite. A link-shaped text in an HTML block, where Markdown renders no links, is
    +// rewritten like a link: that changes text only.
    +func rewriteLinks(body string) (string, error) {
    +	lines := strings.Split(body, "\n")
    +	var open codeFence // the opening fence of the current block; open.length == 0 outside one
    +	fenceIndent := 0
    +	// spansKnown is false from a line that may leave a code span, HTML tag or autolink open until
    +	// the paragraph ends; htmlSeen is true from a line that may open an HTML block to the end.
    +	spansKnown, htmlSeen := true, false
    +	for i, line := range lines {
    +		if open.length > 0 {
    +			indent := indentWidth(line)
    +			if strings.TrimSpace(line) != "" && indent < fenceIndent {
    +				return "", fmt.Errorf("line %q: indented less than the opening fence of its code block, which ends the block; indent every line of the block at least as far as the fence", line)
    +			}
    +			f, ok := parseFence(line)
    +			if !ok || f.char != open.char || f.length < open.length || strings.Trim(f.info, " \t") != "" ||
    +				indent >= fenceIndent+4 {
    +				continue
    +			}
    +			if indent > fenceIndent {
    +				return "", fmt.Errorf("line %q: closing fence indented more than its opening fence; indent it as far as the opening fence", line)
    +			}
    +			open, spansKnown = codeFence{}, true
    +			continue
    +		}
    +		if f, ok := parseFence(line); ok && (f.char != '`' || !strings.Contains(f.info, "`")) {
    +			open, fenceIndent, spansKnown = f, indentWidth(line), true
    +			continue
    +		}
    +		if strings.TrimSpace(line) == "" {
    +			spansKnown = true
    +			continue
    +		}
    +		if atxHeading.MatchString(line) {
    +			return "", fmt.Errorf("line %q: headings are not allowed; a release section supplies them", line)
    +		}
    +		if setextUnderline.MatchString(line) {
    +			return "", fmt.Errorf("line %q: a line of only = or - (a heading underline or a rule) is not allowed", line)
    +		}
    +		if linkDefinition.MatchString(line) {
    +			return "", fmt.Errorf("line %q: reference-style link definitions are not allowed; write the link inline, as [text](target)", line)
    +		}
    +		if htmlStart.MatchString(line) {
    +			htmlSeen = true
    +		}
    +		// spans is line with its code span contents blanked, at the same byte offsets, when
    +		// startKnown; masked is spans unless the line may be in an HTML block, where backticks do
    +		// not start code spans, so the checks see the whole line.
    +		startKnown := spansKnown
    +		spans := line
    +		if startKnown {
    +			spans, spansKnown = maskCodeSpans(line)
    +		}
    +		masked := spans
    +		if htmlSeen {
    +			masked = line
    +		}
    +		if htmlLink.MatchString(masked) {
    +			return "", fmt.Errorf("line %q: HTML links and images are not allowed; write a Markdown link, [text](target), or image, ![alt](target)", line)
    +		}
    +		var b, rest strings.Builder // rest is masked without the inline link targets
    +		last := 0
    +		for _, loc := range linkTarget.FindAllStringSubmatchIndex(masked, -1) {
    +			if strings.Contains(masked[last:loc[0]], "](") || masked[loc[2]] == '<' {
    +				return "", unparsedLink(line)
    +			}
    +			target := line[loc[2]:loc[3]]
    +			// A code span cannot start or end between the '(' and the target, which has no backtick:
    +			// the '(' is blanked in spans exactly when the target is in a code span, which is left
    +			// as written.
    +			if !startKnown || spans[loc[2]-1] == '(' {
    +				rewritten, err := rootRelative(target)
    +				if err != nil {
    +					return "", err
    +				}
    +				if !startKnown && rewritten != target {
    +					return "", fmt.Errorf("line %q: cannot tell whether the link to %q is in inline code, because an earlier line of the paragraph leaves a backtick, HTML tag or autolink open; write each piece of inline code on one line and escape a literal backtick as \\`", line, target)
    +				}
    +				target = rewritten
    +			}
    +			b.WriteString(line[last:loc[2]])
    +			b.WriteString(target)
    +			b.WriteString(line[loc[3]:loc[1]])
    +			rest.WriteString(masked[last:loc[2]])
    +			rest.WriteString(masked[loc[3]:loc[1]])
    +			last = loc[1]
    +		}
    +		if strings.Contains(masked[last:], "](") {
    +			return "", unparsedLink(line)
    +		}
    +		rest.WriteString(masked[last:])
    +		if parentDir.MatchString(rest.String()) {
    +			return "", fmt.Errorf("line %q: ../ is allowed only in an inline link target, [text](target), or in inline code; assembly rewrites only those targets, and any other relative path would resolve from CHANGELOG.md instead of the fragment", line)
    +		}
    +		b.WriteString(line[last:])
    +		lines[i] = b.String()
    +	}
    +	if open.length > 0 {
    +		return "", errors.New("unterminated code fence")
    +	}
    +	return strings.Join(lines, "\n"), nil
    +}
    +
    +// maskCodeSpans returns line with the contents of each code span on it replaced by '_', and
    +// whether the next line starts outside any code span, HTML tag and autolink. Pairing follows
    +// CommonMark: a run of backticks opens a span closed by the next run of the same length, an
    +// unmatched run is text, and a backslash escapes a backtick. It assumes line starts outside a code
    +// span, HTML tag and autolink; the caller does not call it after a line where that may not hold. A
    +// run of backticks inside an HTML tag or autolink that may still be open (see openTag) does not
    +// open a span: masking stops there. It returns false after an unmatched run, which a later line may
    +// close, after masking stopped, and when line ends inside a construct openTag reports open.
    +func maskCodeSpans(line string) (string, bool) {
    +	b := []byte(line)
    +	clean := true
    +	for i := 0; i < len(b); {
    +		switch {
    +		case b[i] == '\\' && i+1 < len(b) && (b[i+1] == '`' || b[i+1] == '\\'):
    +			i += 2
    +			continue
    +		case b[i] != '`':
    +			i++
    +			continue
    +		}
    +		if openTag(b[:i]) {
    +			return string(b), false
    +		}
    +		n := backtickRun(b, i)
    +		closer := -1
    +		for j := i + n; j < len(b); {
    +			if b[j] != '`' {
    +				j++
    +				continue
    +			}
    +			m := backtickRun(b, j)
    +			if m == n {
    +				closer = j
    +				break
    +			}
    +			j += m
    +		}
    +		if closer < 0 {
    +			clean = false
    +			i += n
    +			continue
    +		}
    +		for k := i + n; k < closer; k++ {
    +			b[k] = '_'
    +		}
    +		i = closer + n
    +	}
    +	return string(b), clean && !openTag(b)
    +}
    +
    +// backtickRun returns the length of the run of backticks starting at b[i].
    +func backtickRun(b []byte, i int) int {
    +	n := 0
    +	for i+n < len(b) && b[i+n] == '`' {
    +		n++
    +	}
    +	return n
    +}
    +
    +// openTag reports whether b ends inside an HTML tag, comment, processing instruction, declaration,
    +// CDATA section or autolink that starts in it. A quoted attribute value is skipped, so a '>' in one
    +// does not end its tag. It errs towards open: a '<' before a letter, '/', '!' or '?' counts as a
    +// start even if the text after it is not a valid tag, which only makes the checks stricter.
    +func openTag(b []byte) bool {
    +	for i := 0; i < len(b); i++ {
    +		if b[i] != '<' {
    +			continue
    +		}
    +		end := tagEnd(b, i)
    +		if end < 0 {
    +			return true
    +		}
    +		i = end
    +	}
    +	return false
    +}
    +
    +// tagEnd returns the index of the last byte of the construct that the '<' at b[i] may start, i if
    +// it cannot start one, or -1 if b ends inside it.
    +func tagEnd(b []byte, i int) int {
    +	s := b[i:]
    +	find := func(from int, end string) int {
    +		if from > len(s) {
    +			return -1
    +		}
    +		k := bytes.Index(s[from:], []byte(end))
    +		if k < 0 {
    +			return -1
    +		}
    +		return i + from + k + len(end) - 1
    +	}
    +	switch {
    +	case bytes.HasPrefix(s, []byte("<!--")):
    +		return find(4, "-->")
    +	case bytes.HasPrefix(s, []byte("<![CDATA[")):
    +		return find(9, "]]>")
    +	case bytes.HasPrefix(s, []byte("<?")):
    +		return find(2, "?>")
    +	case len(s) > 1 && (s[1] == '!' || s[1] == '/'):
    +		return find(2, ">")
    +	case len(s) > 1 && ('a' <= s[1]|0x20 && s[1]|0x20 <= 'z'):
    +		for j := 2; j < len(s); j++ {
    +			switch s[j] {
    +			case '"', '\'':
    +				k := bytes.IndexByte(s[j+1:], s[j])
    +				if k < 0 {
    +					return -1
    +				}
    +				j += k + 1
    +			case '>':
    +				return i + j
    +			}
    +		}
    +		return -1
    +	}
    +	return i
    +}
    +
    +// unparsedLink is the error for a "](" that does not start a linkTarget, such as a target in angle
    +// brackets, after a space, with a backtick or a 'title' or split across lines.
    +func unparsedLink(line string) error {
    +	return fmt.Errorf("line %q: write each link on one line as [text](target) or [text](target \"title\"), with no spaces, angle brackets or backticks around or in the target", line)
    +}
    +
    +// codeFence is a run of three or more backticks or tildes that opens or closes a fenced code
    +// block, and the text after it on its line.
    +type codeFence struct {
    +	char   byte
    +	length int
    +	info   string
    +}
    +
    +// parseFence parses line, after its indentation, as a code fence. A backtick fence opens a block
    +// only when its info string has no backtick; the caller checks that.
    +func parseFence(line string) (codeFence, bool) {
    +	s := strings.TrimLeft(line, " \t")
    +	if s == "" || (s[0] != '`' && s[0] != '~') {
    +		return codeFence{}, false
    +	}
    +	rest := strings.TrimLeft(s, s[:1])
    +	f := codeFence{char: s[0], length: len(s) - len(rest), info: rest}
    +	return f, f.length >= 3
    +}
    +
    +// indentWidth returns the column of line's first non-blank character, with a tab advancing to the
    +// next multiple of 4 as in CommonMark.
    +func indentWidth(line string) int {
    +	w := 0
    +	for _, r := range line {
    +		switch r {
    +		case ' ':
    +			w++
    +		case '\t':
    +			w += 4 - w%4
    +		default:
    +			return w
    +		}
    +	}
    +	return w
    +}
    +
    +// rootRelative turns a link target written relative to fragmentDir into one relative to the
    +// repository root. URLs and same-file anchors are returned unchanged.
    +func rootRelative(target string) (string, error) {
    +	if strings.HasPrefix(target, "#") || strings.Contains(target, "://") ||
    +		strings.HasPrefix(target, "mailto:") || strings.HasPrefix(target, "tel:") {
    +		return target, nil
    +	}
    +	if strings.HasPrefix(target, "/") {
    +		return "", fmt.Errorf("link %q: use a path relative to the fragment, such as ../../docs/concepts.md", target)
    +	}
    +	// path.Join resolves only a literal ../; a browser also resolves an encoded one, so a target
    +	// with one could still point outside the repository after the rewrite. The whole target is
    +	// checked: a character reference has a '#' that is not an anchor.
    +	for _, step := range parentDir.FindAllString(target, -1) {
    +		if step != "../" {
    +			return "", fmt.Errorf("link %q: write each parent directory step as ../, not %q", target, step)
    +		}
    +	}
    +	file, anchor, hasAnchor := strings.Cut(target, "#")
    +	p := path.Clean(path.Join(fragmentDir, file))
    +	if p == ".." || strings.HasPrefix(p, "../") {
    +		return "", fmt.Errorf("link %q: points outside the repository", target)
    +	}

    Fixed in #230 by refusing links that resolve into changelog/unreleased/ instead of rewriting them, since assembly deletes the targets.

    Reviewers
    Assignees
    aramase aramase
    Labels
    risk: low confidence: 86.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.5% (HIGH) · Higher = larger blast radius
    76.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.1% · Lower = rushed or shallow review
    86.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10.7% · Safe to merge
    10.7%