chore: import upstream snapshot with attribution
Security / Dependency audit (pip-audit) (push) Has been cancelled
Security / CodeQL (javascript-typescript) (push) Has been cancelled
Security / CodeQL (python) (push) Has been cancelled
Security / Secret scan (gitleaks) (push) Has been cancelled
rust / test (ubuntu) (push) Has been cancelled
rust / simulator e2e (macos-latest) (push) Has been cancelled
rust / simulator e2e (ubuntu-latest) (push) Has been cancelled
rust / simulator e2e (windows-latest) (push) Has been cancelled
rust / wheels (aarch64-apple-darwin) (push) Has been cancelled
rust / wheels (x86_64-unknown-linux-gnu) (push) Has been cancelled
rust / wheels (x86_64-apple-darwin) (push) Has been cancelled
rust / audit (push) Has been cancelled
rust / parity (nightly, allowed to fail during Phase 0) (push) Has been cancelled
CI / commitlint (push) Has been skipped
Dev Containers / validate (.devcontainer/devcontainer.json, default) (push) Failing after 0s
Dev Containers / validate (.devcontainer/memory-stack/devcontainer.json, memory-stack) (push) Failing after 0s
Dev Containers / validate-worktree (push) Failing after 0s
CI / changes (push) Failing after 4s
Deploy Documentation / validate (push) Has been skipped
Deploy Documentation / deploy (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, claude) (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, codex) (push) Failing after 1s
Install Native E2E / install-native (ubuntu-latest) (push) Failing after 1s
OpenCode Plugin / typecheck + build + test (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, copilot) (push) Failing after 1s
Release Please / release-please (push) Failing after 1s
Wrap E2E / docker-wrap-e2e (push) Failing after 1s
Wrap Native E2E / wrap-native (ubuntu-latest) (push) Failing after 1s
Init E2E / docker-init-e2e (push) Failing after 4s
Merge Conflicts / merge-conflicts (push) Failing after 4s
CI / lint (push) Has been cancelled
CI / build-wheel (push) Has been cancelled
CI / build-wheel-windows (push) Has been cancelled
CI / prefetch-model (push) Has been cancelled
CI / test-dashboard-ui (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test-extras (push) Has been cancelled
CI / test-agno (push) Has been cancelled
CI / build (push) Has been cancelled
CI / workflow-validation (push) Has been cancelled
CI / docker-native-e2e (push) Has been cancelled
CI / windows-native-wrapper (push) Has been cancelled
CI / macos-native-wrapper (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / promote-latest (push) Has been cancelled
Init Native E2E / init-native (macos-latest, claude) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, codex) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, copilot) (push) Has been cancelled
Install Native E2E / install-native (macos-latest) (push) Has been cancelled
Wrap Native E2E / wrap-native (macos-latest) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:03:20 +08:00
commit 0ef5fcb1c5
1951 changed files with 606278 additions and 0 deletions
+302
View File
@@ -0,0 +1,302 @@
"""Tests for changelog-gen.py."""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent.parent
# Load changelog_gen module from scripts directory (filename has hyphen)
_spec = importlib.util.spec_from_file_location(
"changelog_gen", ROOT / "scripts" / "changelog-gen.py"
)
if _spec is None:
raise ImportError("Could not load changelog_gen module")
_changelog_gen = importlib.util.module_from_spec(_spec)
if _spec.loader is None:
raise ImportError("Could not load changelog_gen module")
_spec.loader.exec_module(_changelog_gen)
COMMIT_PATTERN = _changelog_gen.COMMIT_PATTERN
BREAKING_CHANGE_PATTERN = _changelog_gen.BREAKING_CHANGE_PATTERN
FIELD_SEP = _changelog_gen.FIELD_SEP
RECORD_SEP = _changelog_gen.RECORD_SEP
ParsedCommit = _changelog_gen.ParsedCommit
generate_changelog = _changelog_gen.generate_changelog
iter_commit_entries = _changelog_gen.iter_commit_entries
parse_commits = _changelog_gen.parse_commits
def make_log_entry(subject: str, commit_hash: str, body: str = "") -> str:
return f"{subject}{FIELD_SEP}{body}{FIELD_SEP}{commit_hash}{RECORD_SEP}"
class TestParseCommits:
"""Tests for parse_commits function."""
def test_parses_feat_commit(self) -> None:
log_output = make_log_entry("feat(core): add feature", "abc1234")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "feat"
assert commits[0].scope == "core"
assert commits[0].message == "add feature"
assert commits[0].hash == "abc1234"
assert commits[0].breaking is False
def test_parses_fix_commit(self) -> None:
log_output = make_log_entry("fix(ui): fix bug", "def5678")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "fix"
assert commits[0].scope == "ui"
assert commits[0].message == "fix bug"
assert commits[0].hash == "def5678"
def test_parses_ci_commit(self) -> None:
log_output = make_log_entry("ci: update github actions", "xyz789")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "ci"
assert commits[0].scope is None
assert commits[0].message == "update github actions"
assert commits[0].hash == "xyz789"
def test_parses_chore_commit(self) -> None:
log_output = make_log_entry("chore: cleanup", "xyz999")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "chore"
assert commits[0].scope is None
def test_parses_perf_commit(self) -> None:
log_output = make_log_entry("perf(dashboard): improve performance", "abc111")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "perf"
assert commits[0].scope == "dashboard"
def test_parses_refactor_commit(self) -> None:
log_output = make_log_entry("refactor(api): refactor endpoint", "abc222")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "refactor"
assert commits[0].scope == "api"
def test_parses_docs_commit(self) -> None:
log_output = make_log_entry("docs: update readme", "abc333")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "docs"
def test_parses_style_commit(self) -> None:
log_output = make_log_entry("style: format code", "abc444")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "style"
def test_parses_test_commit(self) -> None:
log_output = make_log_entry("test: add tests for feature", "abc555")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "test"
def test_detects_breaking_change_in_body(self) -> None:
log_output = make_log_entry(
"feat(core): add feature",
"abc666",
"BREAKING CHANGE: api changed",
)
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].breaking is True
def test_detects_breaking_change_exclamation(self) -> None:
log_output = make_log_entry("feat(core)!: api changed", "abc777")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].breaking is True
def test_no_scope_no_problem(self) -> None:
log_output = make_log_entry("feat: simple feature", "abc888")
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].scope is None
assert commits[0].message == "simple feature"
def test_uses_pr_title_from_merge_commit_body(self) -> None:
log_output = make_log_entry(
"Merge pull request #173 from JerrettDavis/fix/pipeline-permissions-and-docs",
"73f6673",
"fix: repair release and docs pipelines",
)
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "fix"
assert commits[0].message == "repair release and docs pipelines"
def test_falls_back_to_other_changes_for_non_conventional_merge(self) -> None:
log_output = make_log_entry(
"Merge pull request #186 from skorokithakis/patch-1",
"1e80ee3",
"Add support for custom Anthropic API URL",
)
commits = parse_commits(log_output)
assert len(commits) == 1
assert commits[0].type == "other"
assert commits[0].message == "Add support for custom Anthropic API URL"
def test_iter_commit_entries_parses_real_git_log_delimiters(self) -> None:
log_output = make_log_entry(
"fix: patch release flow", "abc1234", "BREAKING CHANGE: no"
) + make_log_entry("docs: update readme", "def5678")
assert iter_commit_entries(log_output) == [
("fix: patch release flow", "BREAKING CHANGE: no", "abc1234"),
("docs: update readme", "", "def5678"),
]
def test_iter_commit_entries_keeps_field_separator_inside_body(self) -> None:
body = f"line one{FIELD_SEP}line two"
log_output = make_log_entry("fix: patch release flow", "abc1234", body)
assert iter_commit_entries(log_output) == [
("fix: patch release flow", body, "abc1234"),
]
class TestGenerateChangelog:
"""Tests for generate_changelog function."""
def test_generates_version_header(self) -> None:
commits = [
ParsedCommit(type="feat", scope=None, breaking=False, message="test", hash="abc123")
]
result = generate_changelog("0.6.0", commits)
assert "## [0.6.0]" in result
def test_includes_date(self) -> None:
commits = []
result = generate_changelog("0.6.0", commits)
import re
date_match = re.search(r"\d{4}-\d{2}-\d{2}", result)
assert date_match is not None
def test_groups_by_type(self) -> None:
commits = [
ParsedCommit(
type="feat", scope=None, breaking=False, message="add feature", hash="abc123"
),
ParsedCommit(type="fix", scope=None, breaking=False, message="fix bug", hash="def456"),
]
result = generate_changelog("0.6.0", commits)
assert "### Features" in result
assert "### Bug Fixes" in result
assert "- add feature (abc123)" in result
assert "- fix bug (def456)" in result
def test_includes_scope_in_bullet(self) -> None:
commits = [
ParsedCommit(
type="feat", scope="core", breaking=False, message="add feature", hash="abc123"
)
]
result = generate_changelog("0.6.0", commits)
assert "- **core**: add feature (abc123)" in result
def test_breaking_change_section_when_present(self) -> None:
commits = [
ParsedCommit(
type="feat", scope="core", breaking=True, message="api changed", hash="abc123"
)
]
result = generate_changelog("0.6.0", commits)
assert "### Breaking Changes" in result
assert "**core**" in result
def test_no_breaking_change_section_when_none(self) -> None:
commits = [
ParsedCommit(
type="feat", scope=None, breaking=False, message="add feature", hash="abc123"
)
]
result = generate_changelog("0.6.0", commits)
assert "Breaking Changes" not in result
def test_includes_other_changes_section(self) -> None:
commits = [
ParsedCommit(
type="other",
scope=None,
breaking=False,
message="Add support for custom Anthropic API URL",
hash="abc123",
)
]
result = generate_changelog("0.6.0", commits)
assert "### Other Changes" in result
assert "- Add support for custom Anthropic API URL (abc123)" in result
class TestIntegrationWithMock:
"""Integration tests with mocked subprocess.run."""
def test_full_flow_with_mocked_git(self) -> None:
log_output = (
make_log_entry("feat(core): add new feature", "abc1234")
+ make_log_entry("fix(ui): fix bug", "def5678")
+ make_log_entry("ci: update github actions", "xyz789")
+ make_log_entry(
"feat(outer): breaking change", "bbb111", "BREAKING CHANGE: this is breaking"
)
+ make_log_entry("chore: cleanup", "yyy999")
)
commits = parse_commits(log_output)
assert len(commits) == 5
assert any(c.type == "feat" and c.scope == "core" for c in commits)
assert any(c.type == "fix" and c.scope == "ui" for c in commits)
assert any(c.type == "ci" for c in commits)
assert any(c.type == "feat" and c.breaking for c in commits)
assert any(c.type == "chore" for c in commits)
changelog = generate_changelog("0.7.0", commits)
assert "## [0.7.0]" in changelog
assert "### Features" in changelog
assert "### Bug Fixes" in changelog
assert "### CI/CD" in changelog
assert "### Breaking Changes" in changelog
class TestCommitPattern:
"""Tests for the commit regex pattern."""
def test_feat_with_scope(self) -> None:
match = COMMIT_PATTERN.match("feat(core): add feature")
assert match is not None
assert match.group(1) == "feat"
assert match.group(2) == "(core)"
assert match.group(4) == "add feature"
def test_fix_without_scope(self) -> None:
match = COMMIT_PATTERN.match("fix: fix bug")
assert match is not None
assert match.group(1) == "fix"
assert match.group(2) is None
assert match.group(4) == "fix bug"
def test_with_exclamation(self) -> None:
match = COMMIT_PATTERN.match("feat(core)!: api changed")
assert match is not None
assert match.group(3) == "!"
def test_without_exclamation(self) -> None:
match = COMMIT_PATTERN.match("feat(core): add feature")
assert match is not None
assert match.group(3) is None
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+16
View File
@@ -0,0 +1,16 @@
"""Tests for CI workflow hardening contracts."""
from __future__ import annotations
from pathlib import Path
def test_sharded_ci_verifies_offline_huggingface_cache_before_pytest() -> None:
workflow = Path(".github/workflows/ci.yml").read_text(encoding="utf-8")
verify_step = "Verify offline HuggingFace model cache"
pytest_step = "Run test shard ${{ matrix.shard }}/4"
assert verify_step in workflow
assert "python scripts/ci/verify_hf_model_cache.py" in workflow
assert workflow.index(verify_step) < workflow.index(pytest_step)
+214
View File
@@ -0,0 +1,214 @@
"""Tests for pr-governance.py."""
from __future__ import annotations
import importlib.util
import json
import sys
from pathlib import Path
def _load_module():
script = Path(__file__).parent.parent / "pr-governance.py"
spec = importlib.util.spec_from_file_location("pr_governance", script)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def _event(body: str, *, draft: bool = False, login: str = "octocat") -> dict[str, object]:
return {
"pull_request": {
"number": 42,
"draft": draft,
"body": body,
"user": {"login": login},
}
}
VALID_BODY = """## Description
Add a required PR-governance gate for template validation and review readiness.
Closes #123
## Type of Change
- [x] New feature (non-breaking change that adds functionality)
- [ ] Documentation update
## Changes Made
- Added a workflow-backed PR template validator.
- Added local commit message linting in the commit-msg hook.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Manual testing performed
### Test Output
```text
pytest scripts/tests/test_pr_governance.py -q
```
## Real Behavior Proof
- Environment: Ubuntu runner, Python 3.12
- Exact command / steps: Open a PR, remove the ready checkbox, re-run the workflow.
- Observed result: The governance check fails and the PR gets a needs-author-action label.
- Not tested: Automatic Copilot review rulesets in repository settings.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Additional Notes
- Maintainers can optionally enable Copilot code review from repository rulesets.
"""
def test_validate_pull_request_marks_ready_pr_valid() -> None:
module = _load_module()
report = module.validate_pull_request(_event(VALID_BODY))
assert report.valid is True
assert report.ready_for_review is True
assert report.needs_author_action is False
assert report.problems == []
assert report.labels_to_add == [module.READY_LABEL]
assert module.AUTHOR_ACTION_LABEL in report.labels_to_remove
def test_validate_pull_request_accepts_crlf_test_output_code_block() -> None:
module = _load_module()
body = VALID_BODY.replace("\n", "\r\n")
report = module.validate_pull_request(_event(body))
assert report.valid is True
assert report.problems == []
def test_validate_pull_request_body_override_uses_live_body() -> None:
module = _load_module()
stale_event_body = ""
report = module.validate_pull_request_body(_event(stale_event_body), VALID_BODY)
assert report.valid is True
assert report.ready_for_review is True
assert report.problems == []
def test_cli_body_file_override_uses_live_body(tmp_path: Path, monkeypatch) -> None:
module = _load_module()
event_path = tmp_path / "event.json"
body_path = tmp_path / "body.md"
report_path = tmp_path / "report.json"
event_path.write_text(
json.dumps(_event("")),
encoding="utf-8",
)
body_path.write_text(VALID_BODY, encoding="utf-8")
monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
exit_code = module.main(
[
"--event",
str(event_path),
"--body-file",
str(body_path),
"--report",
str(report_path),
]
)
assert exit_code == 0
report = json.loads(report_path.read_text(encoding="utf-8"))
assert report["valid"] is True
assert report["ready_for_review"] is True
def test_validate_pull_request_allows_draft_without_ready_checkboxes() -> None:
module = _load_module()
body = VALID_BODY.replace(
"- [x] I have performed a self-review", "- [ ] I have performed a self-review"
)
body = body.replace(
"- [x] This PR is ready for human review",
"- [ ] This PR is ready for human review",
)
report = module.validate_pull_request(_event(body, draft=True))
assert report.valid is True
assert report.ready_for_review is False
assert report.needs_author_action is False
assert report.labels_to_add == []
assert module.READY_LABEL in report.labels_to_remove
def test_validate_pull_request_fails_on_missing_required_content() -> None:
module = _load_module()
body = """## Description
Fixes #123
## Type of Change
- [ ] New feature (non-breaking change that adds functionality)
## Changes Made
- Change 1
## Testing
### Test Output
```text
# Paste relevant command output or artifact links here
```
## Real Behavior Proof
- Environment:
- Exact command / steps:
- Observed result:
- Not tested:
## Review Readiness
- [ ] I have performed a self-review
- [ ] This PR is ready for human review
"""
report = module.validate_pull_request(_event(body))
assert report.valid is False
assert report.needs_author_action is True
assert module.AUTHOR_ACTION_LABEL in report.labels_to_add
assert any("Description" in problem for problem in report.problems)
assert any("Type of Change" in problem for problem in report.problems)
assert any("Test Output" in problem for problem in report.problems)
assert any("Real Behavior Proof" in problem for problem in report.problems)
def test_validate_pull_request_skips_bot_authored_prs() -> None:
module = _load_module()
report = module.validate_pull_request(_event("", login="dependabot[bot]"))
assert report.valid is True
assert report.is_bot_pr is True
assert report.needs_author_action is False
assert report.labels_to_add == []
+94
View File
@@ -0,0 +1,94 @@
"""Tests for pr-health-labels.py."""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
def _load_module():
script = Path(__file__).parents[2] / ".github" / "scripts" / "pr-health-labels.py"
spec = importlib.util.spec_from_file_location("pr_health_labels", script)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def test_check_state_ignores_historical_failures_when_latest_attempt_passed() -> None:
module = _load_module()
payload = {
"statusCheckRollup": [
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "template",
"conclusion": "FAILURE",
"startedAt": "2026-06-14T13:38:35Z",
"completedAt": "2026-06-14T13:38:46Z",
},
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "template",
"conclusion": "SUCCESS",
"startedAt": "2026-06-14T13:43:26Z",
"completedAt": "2026-06-14T13:43:35Z",
},
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "label",
"conclusion": "CANCELLED",
"startedAt": "2026-06-14T13:43:18Z",
"completedAt": "2026-06-14T13:43:24Z",
},
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "label",
"conclusion": "SUCCESS",
"startedAt": "2026-06-14T13:43:26Z",
"completedAt": "2026-06-14T13:43:35Z",
},
{
"__typename": "CheckRun",
"workflowName": "",
"name": "GitGuardian Security Checks",
"conclusion": "SUCCESS",
"startedAt": "2026-06-14T13:38:32Z",
"completedAt": "2026-06-14T13:39:04Z",
},
]
}
assert module.check_state(payload) == "passing"
def test_check_state_fails_when_latest_attempt_failed() -> None:
module = _load_module()
payload = {
"statusCheckRollup": [
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "template",
"conclusion": "SUCCESS",
"startedAt": "2026-06-14T13:38:35Z",
"completedAt": "2026-06-14T13:38:46Z",
},
{
"__typename": "CheckRun",
"workflowName": "PR Governance",
"name": "template",
"conclusion": "FAILURE",
"startedAt": "2026-06-14T13:43:26Z",
"completedAt": "2026-06-14T13:43:35Z",
},
]
}
assert module.check_state(payload) == "failing"
+32
View File
@@ -0,0 +1,32 @@
"""Tests for the PR governance workflow contract."""
from __future__ import annotations
from pathlib import Path
def test_incomplete_pr_template_is_reported_without_failing_job() -> None:
workflow = Path(".github/workflows/pr-health.yml").read_text(encoding="utf-8")
assert "Fetch current PR body" in workflow
assert "--body-file .pr-body.md" in workflow
assert "Report incomplete PR body" in workflow
assert "PR template validation found missing fields" in workflow
assert "Fail when the PR body is incomplete" not in workflow
assert 'echo "PR template validation failed' not in workflow
def test_ready_for_review_label_is_removed_when_changes_are_requested() -> None:
workflow = Path(".github/workflows/pr-health.yml").read_text(encoding="utf-8")
assert "reviewDecision" in workflow
assert 'review_decision="$(jq -r \'.reviewDecision // ""\'' in workflow
assert '$review_decision" == "CHANGES_REQUESTED"' in workflow
def test_merge_state_unknown_does_not_clear_conflict_or_rebase_labels() -> None:
workflow = Path(".github/workflows/pr-health.yml").read_text(encoding="utf-8")
assert 'elif [[ "$merge_state" != "UNKNOWN" ]]; then' in workflow
assert 'gh pr edit "$pr" --repo "$REPO" --remove-label "status: needs rebase"' in workflow
assert 'gh pr edit "$pr" --repo "$REPO" --remove-label "status: has conflicts"' in workflow
+131
View File
@@ -0,0 +1,131 @@
"""Tests for sync-plugin-versions.py."""
from __future__ import annotations
import importlib.util
from pathlib import Path
def _load_module():
script = Path(__file__).parent.parent / "sync-plugin-versions.py"
spec = importlib.util.spec_from_file_location("sync_plugin_versions", script)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_compute_repo_semver_uses_release_helpers(monkeypatch) -> None:
module = _load_module()
calls: dict[str, object] = {}
monkeypatch.setattr(module, "list_release_tags", lambda root: ["v0.9.0"])
monkeypatch.setattr(module, "find_latest_release_tag", lambda tags: "v0.9.0")
monkeypatch.setattr(module, "list_release_commits", lambda root, tag: ["feat: add init"])
monkeypatch.setattr(module, "determine_bump_level", lambda commits: "minor")
monkeypatch.setattr(module, "get_canonical_version", lambda root: "0.5.25")
def fake_compute_release_version(*, canonical_version: str, level: str, tags: list[str]):
calls["canonical_version"] = canonical_version
calls["level"] = level
calls["tags"] = tags
return type("Info", (), {"npm_version": "0.10.0"})()
monkeypatch.setattr(module, "compute_release_version", fake_compute_release_version)
assert module.compute_repo_semver(Path("repo")) == "0.10.0"
assert calls == {
"canonical_version": "0.5.25",
"level": "minor",
"tags": ["v0.9.0"],
}
def test_main_runs_plugin_only_version_sync(monkeypatch) -> None:
"""Locks the sync-execution path. ``_should_sync`` is forced True so
we don't depend on the test machine's git branch context."""
module = _load_module()
commands: list[list[str]] = []
monkeypatch.setattr(module, "compute_repo_semver", lambda root: "0.10.0")
monkeypatch.setattr(module, "_should_sync", lambda root: True)
monkeypatch.setattr(
module.subprocess,
"run",
lambda command, cwd, check: commands.append(command),
)
module.main()
assert commands == [
[
module.sys.executable,
str(module.ROOT / "scripts" / "version-sync.py"),
"--root",
str(module.ROOT),
"--version",
"0.10.0",
"--plugin-manifests-only",
]
]
def test_main_is_noop_on_feature_branch(monkeypatch, capsys) -> None:
"""Locks the branch-aware contract: when ``_should_sync`` returns
False (feature branch, no HEADROOM_SYNC_VERSIONS opt-in), main()
prints a skip line and returns without invoking the version-sync
subprocess. Pre-this-fix the hook bumped manifests on every commit
regardless of branch — leaking version-bump noise into every PR."""
module = _load_module()
commands: list[list[str]] = []
monkeypatch.setattr(module, "_should_sync", lambda root: False)
monkeypatch.setattr(module, "_current_branch", lambda root: "feature/foo")
monkeypatch.setattr(
module.subprocess,
"run",
lambda *args, **kwargs: commands.append(args),
)
module.main()
assert commands == [], "Subprocess must not run when _should_sync returns False"
captured = capsys.readouterr()
assert "skipping on branch 'feature/foo'" in captured.out
def test_should_sync_honours_env_override(monkeypatch) -> None:
"""``HEADROOM_SYNC_VERSIONS=1`` forces a sync even on feature
branches — the release workflow uses this opt-in so the canonical
manifest sync still happens at publish time."""
module = _load_module()
monkeypatch.setenv("HEADROOM_SYNC_VERSIONS", "1")
# Even on a "feature" branch, env override wins.
monkeypatch.setattr(module, "_current_branch", lambda root: "feature/foo")
assert module._should_sync(Path("ignored")) is True
def test_should_sync_main_branch_runs(monkeypatch) -> None:
"""On ``main``, sync runs without needing the env var."""
module = _load_module()
monkeypatch.delenv("HEADROOM_SYNC_VERSIONS", raising=False)
monkeypatch.setattr(module, "_current_branch", lambda root: "main")
assert module._should_sync(Path("ignored")) is True
def test_should_sync_feature_branch_is_skip(monkeypatch) -> None:
"""On any non-main branch without the env var, sync is a no-op."""
module = _load_module()
monkeypatch.delenv("HEADROOM_SYNC_VERSIONS", raising=False)
monkeypatch.setattr(module, "_current_branch", lambda root: "fix/some-bug")
assert module._should_sync(Path("ignored")) is False
def test_should_sync_returns_false_when_git_unavailable(monkeypatch) -> None:
"""Defensive: if ``_current_branch`` returns None (git not on
PATH, detached HEAD, etc.) the safe default is no-op."""
module = _load_module()
monkeypatch.delenv("HEADROOM_SYNC_VERSIONS", raising=False)
monkeypatch.setattr(module, "_current_branch", lambda root: None)
assert module._should_sync(Path("ignored")) is False
+291
View File
@@ -0,0 +1,291 @@
"""Tests for version-sync.py."""
import json
import subprocess
import sys
from pathlib import Path
import pytest
@pytest.fixture
def temp_project(tmp_path: Path) -> dict[str, Path]:
"""Create a temporary project with all versioned files."""
# Create directory structure
root = tmp_path / "project"
headroom = root / "headroom"
headroom.mkdir(parents=True)
repo_claude_plugin = root / ".claude-plugin"
repo_claude_plugin.mkdir(parents=True)
repo_github_plugin = root / ".github" / "plugin"
repo_github_plugin.mkdir(parents=True)
plugins = root / "plugins"
openclaw = plugins / "openclaw"
openclaw.mkdir(parents=True)
agent_hooks_claude = plugins / "headroom-agent-hooks" / ".claude-plugin"
agent_hooks_claude.mkdir(parents=True)
agent_hooks_github = plugins / "headroom-agent-hooks" / ".github" / "plugin"
agent_hooks_github.mkdir(parents=True)
sdk = root / "sdk"
typescript = sdk / "typescript"
typescript.mkdir(parents=True)
# pyproject.toml
pyproject = root / "pyproject.toml"
pyproject.write_text('[project]\nversion = "0.5.25"\n')
# headroom/_version.py is runtime-derived and must not be rewritten by version-sync.
version_py = headroom / "_version.py"
version_py.write_text('"""Package version metadata."""\n\n__version__ = "0.5.25"\n')
# plugins/openclaw/package.json
openclaw_pkg = openclaw / "package.json"
openclaw_pkg.write_text(json.dumps({"name": "test", "version": "0.5.25"}))
repo_claude_marketplace = repo_claude_plugin / "marketplace.json"
repo_claude_marketplace.write_text(
json.dumps(
{
"metadata": {"name": "claude-marketplace", "version": "0.1.0"},
"plugins": [{"name": "headroom-agent-hooks", "version": "0.1.0"}],
}
)
)
repo_github_marketplace = repo_github_plugin / "marketplace.json"
repo_github_marketplace.write_text(
json.dumps(
{
"metadata": {"name": "copilot-marketplace", "version": "0.1.0"},
"plugins": [{"name": "headroom-agent-hooks", "version": "0.1.0"}],
}
)
)
claude_plugin = agent_hooks_claude / "plugin.json"
claude_plugin.write_text(json.dumps({"name": "headroom-agent-hooks", "version": "0.1.0"}))
github_plugin = agent_hooks_github / "plugin.json"
github_plugin.write_text(json.dumps({"name": "headroom-agent-hooks", "version": "0.1.0"}))
# sdk/typescript/package.json
typescript_pkg = typescript / "package.json"
typescript_pkg.write_text(json.dumps({"name": "test", "version": "0.5.25"}))
return {
"root": root,
"pyproject": pyproject,
"version_py": version_py,
"openclaw_pkg": openclaw_pkg,
"repo_claude_marketplace": repo_claude_marketplace,
"repo_github_marketplace": repo_github_marketplace,
"claude_plugin": claude_plugin,
"github_plugin": github_plugin,
"typescript_pkg": typescript_pkg,
}
def test_version_sync_explicit_version(temp_project: dict[str, Path]) -> None:
"""Test --version flag updates all files."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[sys.executable, str(script), "--root", str(root), "--version", "0.7.0"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
# Verify pyproject.toml
pyproject_content = temp_project["pyproject"].read_text()
assert 'version = "0.7.0"' in pyproject_content
# Verify headroom/_version.py is not a synced manifest.
version_py_content = temp_project["version_py"].read_text()
assert '__version__ = "0.5.25"' in version_py_content
# Verify plugins/openclaw/package.json
openclaw_pkg = json.loads(temp_project["openclaw_pkg"].read_text())
assert openclaw_pkg["version"] == "0.7.0"
# Verify sdk/typescript/package.json
typescript_pkg = json.loads(temp_project["typescript_pkg"].read_text())
assert typescript_pkg["version"] == "0.7.0"
repo_claude_marketplace = json.loads(temp_project["repo_claude_marketplace"].read_text())
assert repo_claude_marketplace["metadata"]["version"] == "0.7.0"
assert repo_claude_marketplace["plugins"][0]["version"] == "0.7.0"
repo_github_marketplace = json.loads(temp_project["repo_github_marketplace"].read_text())
assert repo_github_marketplace["metadata"]["version"] == "0.7.0"
assert repo_github_marketplace["plugins"][0]["version"] == "0.7.0"
claude_plugin = json.loads(temp_project["claude_plugin"].read_text())
assert claude_plugin["version"] == "0.7.0"
github_plugin = json.loads(temp_project["github_plugin"].read_text())
assert github_plugin["version"] == "0.7.0"
# Verify .releasemetadata was created
release_metadata = root / ".releasemetadata"
assert release_metadata.exists()
metadata = json.loads(release_metadata.read_text())
assert metadata["version"] == "0.7.0"
assert metadata["packages"]["pypi"] == "0.7.0"
assert metadata["packages"]["npm-sdk"] == "0.7.0"
assert metadata["packages"]["npm-openclaw"] == "0.7.0"
assert metadata["packages"]["agent-hooks-plugin"] == "0.7.0"
def test_bump_patch(temp_project: dict[str, Path]) -> None:
"""Test --bump patch bumps 0.5.25 to 0.5.26."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[sys.executable, str(script), "--root", str(root), "--bump", "patch"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
# Verify all files updated to 0.5.26
pyproject_content = temp_project["pyproject"].read_text()
assert 'version = "0.5.26"' in pyproject_content
version_py_content = temp_project["version_py"].read_text()
assert '__version__ = "0.5.25"' in version_py_content
openclaw_pkg = json.loads(temp_project["openclaw_pkg"].read_text())
assert openclaw_pkg["version"] == "0.5.26"
typescript_pkg = json.loads(temp_project["typescript_pkg"].read_text())
assert typescript_pkg["version"] == "0.5.26"
claude_plugin = json.loads(temp_project["claude_plugin"].read_text())
assert claude_plugin["version"] == "0.5.26"
def test_bump_minor(temp_project: dict[str, Path]) -> None:
"""Test --bump minor bumps 0.5.25 to 0.6.0."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[sys.executable, str(script), "--root", str(root), "--bump", "minor"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
# Verify all files updated to 0.6.0
pyproject_content = temp_project["pyproject"].read_text()
assert 'version = "0.6.0"' in pyproject_content
version_py_content = temp_project["version_py"].read_text()
assert '__version__ = "0.5.25"' in version_py_content
openclaw_pkg = json.loads(temp_project["openclaw_pkg"].read_text())
assert openclaw_pkg["version"] == "0.6.0"
typescript_pkg = json.loads(temp_project["typescript_pkg"].read_text())
assert typescript_pkg["version"] == "0.6.0"
github_plugin = json.loads(temp_project["github_plugin"].read_text())
assert github_plugin["version"] == "0.6.0"
def test_bump_major(temp_project: dict[str, Path]) -> None:
"""Test --bump major bumps 0.5.25 to 1.0.0."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[sys.executable, str(script), "--root", str(root), "--bump", "major"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
# Verify all files updated to 1.0.0
pyproject_content = temp_project["pyproject"].read_text()
assert 'version = "1.0.0"' in pyproject_content
version_py_content = temp_project["version_py"].read_text()
assert '__version__ = "0.5.25"' in version_py_content
openclaw_pkg = json.loads(temp_project["openclaw_pkg"].read_text())
assert openclaw_pkg["version"] == "1.0.0"
typescript_pkg = json.loads(temp_project["typescript_pkg"].read_text())
assert typescript_pkg["version"] == "1.0.0"
repo_claude_marketplace = json.loads(temp_project["repo_claude_marketplace"].read_text())
assert repo_claude_marketplace["metadata"]["version"] == "1.0.0"
def test_release_metadata_written(temp_project: dict[str, Path]) -> None:
"""Test .releasemetadata is written correctly."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[sys.executable, str(script), "--root", str(root), "--version", "0.6.0"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
release_metadata = root / ".releasemetadata"
assert release_metadata.exists()
metadata = json.loads(release_metadata.read_text())
assert metadata == {
"version": "0.6.0",
"packages": {
"pypi": "0.6.0",
"npm-sdk": "0.6.0",
"npm-openclaw": "0.6.0",
"agent-hooks-plugin": "0.6.0",
},
}
def test_plugin_manifests_only_leaves_package_versions_unchanged(
temp_project: dict[str, Path],
) -> None:
"""Test plugin-only sync leaves canonical package versions alone."""
root = temp_project["root"]
script = Path(__file__).parent.parent / "version-sync.py"
result = subprocess.run(
[
sys.executable,
str(script),
"--root",
str(root),
"--version",
"0.8.0",
"--plugin-manifests-only",
],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Script failed: {result.stderr}"
assert 'version = "0.5.25"' in temp_project["pyproject"].read_text()
assert '__version__ = "0.5.25"' in temp_project["version_py"].read_text()
assert json.loads(temp_project["openclaw_pkg"].read_text())["version"] == "0.5.25"
assert json.loads(temp_project["typescript_pkg"].read_text())["version"] == "0.5.25"
assert json.loads(temp_project["claude_plugin"].read_text())["version"] == "0.8.0"
assert (
json.loads(temp_project["repo_github_marketplace"].read_text())["metadata"]["version"]
== "0.8.0"
)
assert not (root / ".releasemetadata").exists()