File size: 23,821 Bytes
3f4bb1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

"""Fragment.validate β€” PR-gate filename + content rules."""

from __future__ import annotations

from pathlib import Path

import cli
import pytest

FIXTURES = Path(__file__).parent


def _write(path: Path, body: str) -> Path:
    path.write_text(body, encoding="utf-8")
    return path


# ---------------------------------------------------------------------------
# Acceptance β€” well-formed fragments
# ---------------------------------------------------------------------------


def test_validate_accepts_well_formed(tmp_path):
    p = _write(tmp_path / "1234.rst", "Added\n^^^^^\n\n* Added X.\n")
    assert cli.Fragment(p).validate() is None


def test_validate_accepts_minor_suffix(tmp_path):
    p = _write(tmp_path / "1234.minor.rst", "Added\n^^^^^\n\n* Added X.\n")
    assert cli.Fragment(p).validate() is None


def test_validate_accepts_major_suffix(tmp_path):
    p = _write(tmp_path / "1234.major.rst", "Removed\n^^^^^^^\n\n* Removed X.\n")
    assert cli.Fragment(p).validate() is None


# ---------------------------------------------------------------------------
# Rejection β€” uses checked-in fixtures so the malformed inputs are reviewable
# ---------------------------------------------------------------------------


def test_validate_rejects_unknown_filename_from_fixture():
    err = cli.Fragment(FIXTURES / "invalid_filenames" / "multi.dot.slug.rst").validate()
    assert err is not None and "invalid filename" in err


def test_validate_rejects_unknown_bump_tier_from_fixture():
    err = cli.Fragment(FIXTURES / "invalid_filenames" / "1234.notabump.rst").validate()
    assert err is not None and "invalid filename" in err


def test_validate_rejects_empty_file_from_fixture():
    err = cli.Fragment(FIXTURES / "invalid_content" / "3001.rst").validate()
    assert err is not None and "empty" in err


def test_validate_rejects_missing_section_heading_from_fixture():
    err = cli.Fragment(FIXTURES / "invalid_content" / "3002.rst").validate()
    assert err is not None and "section" in err.lower()


def test_validate_rejects_section_without_bullets_from_fixture():
    err = cli.Fragment(FIXTURES / "invalid_content" / "3003.rst").validate()
    assert err is not None and "bullet" in err.lower()


def test_validate_rejects_orphan_paragraph_from_fixture():
    """A flush-left paragraph between bullets / after the last bullet must be
    rejected β€” the compile step would splice it verbatim into ``CHANGELOG.rst``
    and Sphinx then fails the doc build with ``Unexpected indentation``."""
    err = cli.Fragment(FIXTURES / "invalid_content" / "3004.rst").validate()
    assert err is not None and "orphan" in err.lower()


# ---------------------------------------------------------------------------
# check_fragments β€” gate orchestration: immutability, slug uniqueness, and
# the "PR must add at least one fragment per touched package" rule
# ---------------------------------------------------------------------------


def _pkg_under(tmp_path: Path, name: str) -> cli.Package:
    """Build a managed-looking Package rooted at ``tmp_path/source/<name>``."""
    root = tmp_path / "source" / name
    (root / "config").mkdir(parents=True)
    (root / "docs").mkdir(parents=True)
    (root / "config" / "extension.toml").write_text('version = "0.0.0"\n', encoding="utf-8")
    (root / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n\n", encoding="utf-8")
    return cli.Package(root)


def test_check_fragments_immutability_rejects_modified_fragment(tmp_path):
    """Modifying an existing fragment is forbidden β€” must add a new one instead."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-fix-bug.rst"}
    added = {"source/isaaclab/code.py"}  # fragment exists already; the PR only modified it
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    assert missing == ["isaaclab"]
    invalid_map = dict(invalid)
    assert "source/isaaclab/changelog.d/jdoe-fix-bug.rst" in invalid_map
    assert "immutable" in invalid_map["source/isaaclab/changelog.d/jdoe-fix-bug.rst"]


def test_check_fragments_chain_allows_other_pr_fragment(tmp_path):
    """A chained PR (B based on A's branch, A still open) sees A's fragment in
    its diff. That should pass β€” both fragments have distinct slugs and B
    contributes its own fragment for the touched package."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    (pkg.root / "changelog.d").mkdir()
    (pkg.root / "changelog.d" / "alice-feature-a.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8")
    (pkg.root / "changelog.d" / "bob-feature-b.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8")
    changed = {
        "source/isaaclab/code.py",
        "source/isaaclab/changelog.d/alice-feature-a.rst",  # parent PR's fragment
        "source/isaaclab/changelog.d/bob-feature-b.rst",  # this PR's own fragment
    }
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    assert missing == []
    assert invalid == []


def test_check_fragments_slug_collision_with_existing(tmp_path):
    """Adding a fragment whose slug collides with one already in changelog.d/ fails."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    (pkg.root / "changelog.d").mkdir()
    # Pre-existing fragment on develop with the same slug as the one this PR adds.
    (pkg.root / "changelog.d" / "jdoe-fix-bug.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8")
    # PR adds a fresh fragment whose slug collides β€” different tier, same slug.
    (pkg.root / "changelog.d" / "jdoe-fix-bug.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8")
    changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst"}
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    invalid_map = dict(invalid)
    assert "source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst" in invalid_map
    assert "collides" in invalid_map["source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst"]


def test_check_fragments_collision_independent_of_iterdir_order(tmp_path, monkeypatch):
    """Regression: an added file must not be allowed to *replace* a colliding
    pre-existing fragment in the existing-slug map. The CI checkout contains
    both, and depending on filesystem iteration order the added file could
    end up as the "existing" entry, hiding the collision."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    (pkg.root / "changelog.d").mkdir()
    (pkg.root / "changelog.d" / "jdoe-foo.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8")
    (pkg.root / "changelog.d" / "jdoe-foo.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8")
    changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-foo.minor.rst"}
    added = changed

    # Force iterdir() to return the added file *last* so it would overwrite
    # the pre-existing entry in a buggy implementation. Sort with the added
    # file ranked highest, so it lands at the tail regardless of natural
    # alphabetical order.
    real_iterdir = Path.iterdir
    added_name = "jdoe-foo.minor.rst"

    def ordered_iterdir(self):
        if self == pkg.root / "changelog.d":
            return iter(sorted(real_iterdir(self), key=lambda p: (p.name == added_name, p.name)))
        return real_iterdir(self)

    monkeypatch.setattr(Path, "iterdir", ordered_iterdir)

    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    invalid_map = dict(invalid)
    assert "source/isaaclab/changelog.d/jdoe-foo.minor.rst" in invalid_map
    assert "collides" in invalid_map["source/isaaclab/changelog.d/jdoe-foo.minor.rst"]


def test_check_fragments_slug_collision_within_pr(tmp_path):
    """Two added fragments in the same PR that share a slug (e.g. across tiers) fail."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    (pkg.root / "changelog.d").mkdir()
    (pkg.root / "changelog.d" / "jdoe-fix.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8")
    (pkg.root / "changelog.d" / "jdoe-fix.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8")
    changed = {
        "source/isaaclab/code.py",
        "source/isaaclab/changelog.d/jdoe-fix.rst",
        "source/isaaclab/changelog.d/jdoe-fix.minor.rst",
    }
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    # One of the two is the offender; the other is the first-seen "winner".
    invalid_paths = [p for p, _ in invalid]
    assert any("jdoe-fix" in p for p in invalid_paths)
    assert any("collides" in r for _, r in invalid)


def test_check_fragments_skip_file_satisfies_requirement(tmp_path):
    """A ``<slug>.skip`` opt-out is a valid form of "PR owns a fragment for this pkg"."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    (pkg.root / "changelog.d").mkdir()
    (pkg.root / "changelog.d" / "ci-only.skip").write_text("", encoding="utf-8")
    changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/ci-only.skip"}
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    assert missing == []
    assert invalid == []


def test_check_fragments_no_source_changes_means_no_required_fragment(tmp_path):
    """Pure docs / CI / changelog-tooling PRs don't trigger the requirement."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    changed = {"docs/something.rst"}  # not under source/isaaclab/
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    assert missing == []
    assert invalid == []


def test_check_fragments_missing_when_source_touched_without_fragment(tmp_path):
    """If the PR touches a package's source but adds no fragment, the package is missing."""
    pkg = _pkg_under(tmp_path, "isaaclab")
    changed = {"source/isaaclab/code.py"}
    added = changed
    missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg])
    assert missing == ["isaaclab"]
    assert invalid == []


# ---------------------------------------------------------------------------
# _display_path β€” handles paths inside *and* outside REPO_ROOT
# ---------------------------------------------------------------------------


def test_display_path_strips_repo_root_for_internal_paths():
    """Inside-repo paths are shown relative for terse log lines."""
    p = cli.REPO_ROOT / "tools" / "changelog" / "cli.py"
    assert cli._display_path(p) == "tools/changelog/cli.py"


def test_display_path_falls_back_to_absolute_for_external(tmp_path):
    """External paths (e.g. ``--fragments-dir /tmp/foo`` outside the repo)
    used to crash on ``relative_to(REPO_ROOT)``; the helper now returns the
    absolute path in that case."""
    external = tmp_path / "external_fragments" / "1234.rst"
    external.parent.mkdir(parents=True)
    external.write_text("", encoding="utf-8")
    assert cli._display_path(external) == str(external)


# ---------------------------------------------------------------------------
# Package.compile bails on unmanaged packages instead of silently warning
# ---------------------------------------------------------------------------


def test_compile_raises_on_package_missing_changelog(tmp_path):
    """Constructing a Package directly at an unmanaged root and calling
    ``compile()`` must raise (not silently warn-and-write a stale toml)."""
    pkg_root = tmp_path / "pkg"
    (pkg_root / "config").mkdir(parents=True)
    (pkg_root / "config" / "extension.toml").write_text('version = "1.2.3"\n', encoding="utf-8")
    # No docs/CHANGELOG.rst β€” package is not managed.
    pkg = cli.Package(pkg_root)
    assert pkg.is_managed is False

    fragments = tmp_path / "fragments"
    fragments.mkdir()
    (fragments / "1234.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8")

    with pytest.raises(ValueError, match="not managed"):
        pkg.compile(fragments_dir=fragments, dry_run=True)


# ---------------------------------------------------------------------------
# cmd_compile parser guards β€” argparse-level errors fire as SystemExit
# ---------------------------------------------------------------------------


def _parse_compile(argv: list[str]):
    """Build the parser and parse a compile invocation. Returns (parser, args)."""
    parser = cli._build_parser()
    return parser, parser.parse_args(argv)


def test_compile_guard_version_with_all_errors():
    """``--version`` with ``--all`` is meaningless β€” each package has its own version."""
    parser, args = _parse_compile(["compile", "--all", "--version", "1.2.3"])
    with pytest.raises(SystemExit):
        cli.cmd_compile(args, parser)


def test_compile_guard_fragments_dir_with_all_errors():
    """``--fragments-dir`` with ``--all`` is meaningless β€” different dirs per package."""
    parser, args = _parse_compile(["compile", "--all", "--fragments-dir", "/tmp/x"])
    with pytest.raises(SystemExit):
        cli.cmd_compile(args, parser)


def test_compile_guard_malformed_version_errors():
    """A garbage ``--version`` value fails before any file is touched."""
    parser, args = _parse_compile(["compile", "--package", "isaaclab", "--version", "not-semver"])
    with pytest.raises(SystemExit):
        cli.cmd_compile(args, parser)


def test_compile_guard_nonexistent_package_errors():
    """A ``--package`` that doesn't exist on disk fails fast."""
    parser, args = _parse_compile(["compile", "--package", "definitely_not_a_real_package_xyz"])
    with pytest.raises(SystemExit):
        cli.cmd_compile(args, parser)


def test_changelog_header_re_accepts_minimum_stub():
    """The minimum-valid stub ``Changelog\\n---------\\n\\n`` is accepted.

    This is the smallest seed a new package needs to start receiving
    bot-written entries. Anything shorter (e.g. ``Changelog\\n---------\\n``
    without a trailing blank line) leaves no anchor for the prepend and
    must be rejected.
    """
    assert cli.CHANGELOG_HEADER_RE.search("Changelog\n---------\n\n") is not None


def test_changelog_header_re_rejects_unterminated_stub():
    """A header missing the trailing blank line cannot anchor an insert.

    Regression: ``isaaclab_ppisp`` landed on develop with this exact
    20-byte shape, wedging the nightly compile job (run
    https://github.com/isaac-sim/IsaacLab/actions/runs/26494922179).
    """
    assert cli.CHANGELOG_HEADER_RE.search("Changelog\n---------\n") is None


def test_every_managed_package_has_parseable_changelog_header():
    """Lock the compile precondition: every managed package on disk must
    have a ``CHANGELOG.rst`` whose header is parseable AFTER the same
    self-healing normalization compile applies.

    Mirrors what ``cmd_check`` does on every PR: self-heal the narrow
    "missing trailing blank line" case, then require the strict regex to
    match. A file that passes self-healing but not the regex is genuinely
    malformed (no ``Changelog`` line, no underline, etc.) and would wedge
    the nightly.
    """
    import re

    self_heal = re.compile(r"^(Changelog\n-+)\n(?!\n)", re.MULTILINE)
    bad: list[tuple[str, str]] = []
    for pkg in cli.Package.discover():
        text = pkg.changelog_path.read_text(encoding="utf-8")
        text = self_heal.sub(r"\1\n\n", text, count=1)
        if cli.CHANGELOG_HEADER_RE.search(text) is None:
            bad.append((pkg.name, str(pkg.changelog_path)))
    assert not bad, (
        "Malformed CHANGELOG.rst β€” each file must contain "
        "'Changelog\\n---------\\n\\n' (header + underline + blank line) "
        "so the nightly compile has a place to prepend the next version block. "
        f"Bad files: {bad}"
    )


def test_write_changelog_entry_self_heals_missing_blank_line(tmp_path):
    """Compile against a ``Changelog\\n---------\\n`` stub auto-inserts the
    missing blank line and writes a well-formed file.

    Regression: ``isaaclab_ppisp`` shipped with this exact 20-byte shape
    (PR #5748); the nightly compile raised before this self-heal landed.
    """
    pkg_root = tmp_path / "pkg"
    (pkg_root / "config").mkdir(parents=True)
    (pkg_root / "docs").mkdir(parents=True)
    (pkg_root / "config" / "extension.toml").write_text('version = "0.1.0"\n', encoding="utf-8")
    # The exact malformed shape that wedged the nightly.
    (pkg_root / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n", encoding="utf-8")
    pkg = cli.Package(pkg_root)
    pkg.write_changelog_entry("0.2.0 (2026-05-28)\n~~~~~~~~~~~~~~~~~~\n", dry_run=False)
    out = (pkg_root / "docs" / "CHANGELOG.rst").read_text(encoding="utf-8")
    assert out.startswith("Changelog\n---------\n\n0.2.0 (2026-05-28)")


def test_write_changelog_entry_self_heal_is_noop_on_well_formed(tmp_path):
    """Self-heal must not alter files that already have the blank line.

    Idempotence is the whole point of the negative-lookahead in the
    self-heal regex; this test locks it.
    """
    pkg_root = tmp_path / "pkg"
    (pkg_root / "config").mkdir(parents=True)
    (pkg_root / "docs").mkdir(parents=True)
    (pkg_root / "config" / "extension.toml").write_text('version = "0.1.0"\n', encoding="utf-8")
    original = "Changelog\n---------\n\n0.1.0 (2026-05-20)\n~~~~~~~~~~~~~~~~~~\n\nAdded\n^^^^^\n\n* Initial.\n"
    (pkg_root / "docs" / "CHANGELOG.rst").write_text(original, encoding="utf-8")
    pkg = cli.Package(pkg_root)
    pkg.write_changelog_entry("0.2.0 (2026-05-28)\n~~~~~~~~~~~~~~~~~~\n", dry_run=False)
    out = (pkg_root / "docs" / "CHANGELOG.rst").read_text(encoding="utf-8")
    # New entry on top; the original 0.1.0 block still ends in a single ``\n``
    # before its content (no double-blank artifact from over-eager self-heal).
    assert "0.2.0 (2026-05-28)" in out
    assert "Changelog\n---------\n\n0.2.0" in out
    assert "\n\n\n0.1.0" not in out  # no extra blank line inserted


def test_compile_failure_preserves_fragments_and_version(tmp_path):
    """A package whose ``CHANGELOG.rst`` is genuinely malformed must not
    have its fragments deleted or its version bumped.

    Locks the "fail before any write" guarantee for the failure modes
    per-package isolation defends against. Fragment deletion (step 6 of
    ``Package.compile``) runs strictly after both writes succeed, so a
    header-regex raise in step 4 short-circuits before any side effect
    reaches disk. Without this guarantee, per-package isolation would
    silently lose work on the failed package each cycle.
    """
    pkg_root = tmp_path / "pkg"
    (pkg_root / "config").mkdir(parents=True)
    (pkg_root / "docs").mkdir(parents=True)
    (pkg_root / "changelog.d").mkdir()
    (pkg_root / "config" / "extension.toml").write_text('version = "0.1.0"\n', encoding="utf-8")
    # Unrecoverable shape: no ``Changelog`` header at all β€” self-heal can't
    # do anything and the strict regex raises ValueError.
    (pkg_root / "docs" / "CHANGELOG.rst").write_text("No header at all\n", encoding="utf-8")
    fragment = pkg_root / "changelog.d" / "test.rst"
    fragment.write_text("Added\n^^^^^\n\n* Did a thing.\n", encoding="utf-8")

    pkg = cli.Package(pkg_root)
    with pytest.raises(ValueError, match="Could not locate changelog header"):
        pkg.compile(dry_run=False)

    # Fragment survived the failed compile.
    assert fragment.exists(), "fragment must be preserved when compile raises"
    assert fragment.read_text(encoding="utf-8") == "Added\n^^^^^\n\n* Did a thing.\n"
    # Version unchanged.
    assert 'version = "0.1.0"' in (pkg_root / "config" / "extension.toml").read_text(encoding="utf-8")
    # CHANGELOG.rst unchanged (no entry prepended).
    assert (pkg_root / "docs" / "CHANGELOG.rst").read_text(encoding="utf-8") == "No header at all\n"


def test_cmd_compile_continues_after_per_package_failure(tmp_path, monkeypatch, capsys):
    """One package's compile failure must not abort the batch.

    Defense-in-depth for future failure modes (version mismatch between
    extension.toml and pyproject.toml, filesystem permission, direct push
    bypassing PR gate). The healthy package still ships; the broken one
    is named in the failure summary.
    """
    packages_root = tmp_path / "source"
    packages_root.mkdir()

    def _mk(name: str, changelog_text: str) -> None:
        root = packages_root / name
        (root / "config").mkdir(parents=True)
        (root / "docs").mkdir(parents=True)
        (root / "changelog.d").mkdir()
        (root / "config" / "extension.toml").write_text('version = "0.1.0"\n', encoding="utf-8")
        (root / "docs" / "CHANGELOG.rst").write_text(changelog_text, encoding="utf-8")
        (root / "changelog.d" / "test.rst").write_text("Added\n^^^^^\n\n* Did a thing.\n", encoding="utf-8")

    # ``good_pkg`` has a canonical CHANGELOG.rst and will compile fine.
    _mk("good_pkg", "Changelog\n---------\n\n")
    # ``bad_pkg`` has a genuinely unrecoverable CHANGELOG.rst (no header at
    # all) β€” self-heal doesn't apply, strict regex fails, compile raises.
    _mk("bad_pkg", "Some other content with no header\n")

    # ``Package.discover`` evaluates ``PACKAGES_ROOT`` at class-definition
    # time (default arg), so a monkeypatch of the module constant alone
    # wouldn't redirect it. Patch the classmethod to return our two packages.
    monkeypatch.setattr(
        cli.Package,
        "discover",
        classmethod(
            lambda cls: sorted([cls(packages_root / "good_pkg"), cls(packages_root / "bad_pkg")], key=lambda p: p.name)
        ),
    )
    parser, args = _parse_compile(["compile", "--all"])
    rc = cli.cmd_compile(args, parser)
    captured = capsys.readouterr()

    assert rc == 1
    # Good package compiled β€” its CHANGELOG.rst now carries the new entry
    # and its fragment was deleted.
    assert "Added" in (packages_root / "good_pkg" / "docs" / "CHANGELOG.rst").read_text()
    assert not (packages_root / "good_pkg" / "changelog.d" / "test.rst").exists()
    # Bad package's fragment is preserved β€” per-package isolation does not
    # discard work on the failed package; the next compile gets another try
    # against the same fragment after the human fixes the CHANGELOG.rst.
    assert (packages_root / "bad_pkg" / "changelog.d" / "test.rst").exists()
    # Bad package surfaces in the failure summary.
    assert "bad_pkg" in captured.err
    assert "1 package(s) failed to compile" in captured.err


def test_compile_rejects_fragments_that_check_would_reject(tmp_path):
    """``compile`` must enforce the same content rules as ``check``.

    Regression: a fragment with a section heading but no bullet body
    used to slip past compile (parsed to ``{"Added": []}``, emitted an
    empty Added section), while check correctly rejected it. The two
    paths must agree on what a valid fragment looks like.
    """
    pkg_root = tmp_path / "pkg"
    (pkg_root / "config").mkdir(parents=True)
    (pkg_root / "docs").mkdir(parents=True)
    (pkg_root / "config" / "extension.toml").write_text('version = "1.2.3"\n', encoding="utf-8")
    (pkg_root / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n\n", encoding="utf-8")
    pkg = cli.Package(pkg_root)

    fragments = tmp_path / "fragments"
    fragments.mkdir()
    # Header but no bullets β€” same shape as fixtures/invalid_content/3003.rst.
    (fragments / "1234.rst").write_text("Added\n^^^^^\n\n", encoding="utf-8")

    with pytest.raises(ValueError, match="failed content validation"):
        pkg.compile(fragments_dir=fragments, dry_run=True)