Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions .github/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
## Key Files
| File | Description |
|------|-------------|
| None | GitHub metadata is organized in subdirectories. |
| `pull_request_template.md` | Default PR body, including exact snapshot provenance labels parsed by the guard. |
| `scripts/check_snapshot_provenance.py` | Base/head blob comparison plus PR decision validation. |

## Subdirectories
| Directory | Purpose |
|-----------|---------|
| `ISSUE_TEMPLATE/` | Structured issue form YAML files (see `ISSUE_TEMPLATE/AGENTS.md`). |
| `PULL_REQUEST_TEMPLATE/` | Pull request description template (see `PULL_REQUEST_TEMPLATE/AGENTS.md`). |
| `ISSUE_TEMPLATE/` | Numbered `.yml` issue forms and chooser config (see `ISSUE_TEMPLATE/AGENTS.md`). |
| `scripts/` | Repository governance scripts, including snapshot provenance validation. |
| `workflows/` | GitHub Actions workflow definitions (see `workflows/AGENTS.md`). |

Expand All @@ -28,11 +28,11 @@
### Testing Requirements
- Validate YAML syntax for workflow or issue template edits.
- For workflow changes, mirror commands locally where practical before relying on CI.
- Run `pytest tests/test_governance.py` when provenance scripts, workflow wiring, or PR declarations change.
- Run `pytest tests/test_governance.py tests/test_release_workflow.py` when provenance scripts, workflow wiring, or PR declarations change.

### Common Patterns
- CI installs the package with development dependencies and runs lint/type/test checks.
- Snapshot runtime changes require one validated provenance decision from the PR body.
- `test.yml` is both normal CI and the local reusable workflow called by a tag release.
- Snapshot runtime PRs require one validated provenance decision; non-PR runs still enforce append-only provenance content.

## Dependencies

Expand Down
15 changes: 8 additions & 7 deletions .github/ISSUE_TEMPLATE/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!-- Parent: ../AGENTS.md -->
<!-- Generated: 2026-05-26 | Updated: 2026-05-26 -->
<!-- Generated: 2026-05-26 | Updated: 2026-08-09 -->

# ISSUE_TEMPLATE

Expand All @@ -9,11 +9,11 @@
## Key Files
| File | Description |
|------|-------------|
| `bug_report.yaml` | Form for reproducible defects and environment details. |
| `config.yaml` | GitHub issue template chooser configuration. |
| `documentation.yaml` | Form for documentation improvements or corrections. |
| `feature_request.yaml` | Form for proposed enhancements. |
| `question.yaml` | Form for usage questions. |
| `01-bug-report.yml` | Form for reproducible defects and environment details. |
| `02-feature-request.yml` | Form for proposed enhancements. |
| `03-documentation.yml` | Form for documentation improvements or corrections. |
| `04-question.yml` | Form for usage questions. |
| `config.yml` | GitHub issue chooser configuration and valid contact links. |

## Subdirectories
| Directory | Purpose |
Expand All @@ -25,9 +25,10 @@
### Working In This Directory
- Keep issue forms scoped to this Python CLI/MCP project.
- Preserve valid GitHub issue form YAML structure.
- Ordering is controlled by numbered filenames; `config.yml` has no `issue_templates` key.

### Testing Requirements
- Validate YAML syntax after edits.
- Validate YAML syntax and run `pytest tests/test_governance.py` after path/schema edits.

### Common Patterns
- Forms collect structured fields rather than relying on free-form Markdown only.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,21 @@ contact_links:
- name: 📖 项目文档
url: https://github.com/codeasier/pt-snap-cli/tree/main/docs
about: 查看项目文档和使用指南
- name: 💬 讨论区
url: https://github.com/codeasier/pt-snap-cli/discussions
about: 在讨论区提问或分享想法
- name: 📧 联系我们
url: mailto:825770651@qq.com
about: 通过邮件联系我们

# 模板排序(按此顺序显示在 Issue 选择页面)
issue_templates:
- bug_report.yaml
- feature_request.yaml
- documentation.yaml
- question.yaml

# ============================================================
# 标签与模板映射
# ============================================================
# 每个模板文件的 `labels` 字段定义了创建 Issue 时自动分配的标签
#
# | 模板文件 | 自动标签 | 说明 |
# |--------------------|-------------------|----------------|
# | bug_report.yaml | bug | 错误报告 |
# | feature_request.yaml | enhancement | 功能请求 |
# | documentation.yaml | documentation | 文档问题 |
# | question.yaml | question | 问题咨询 |
# | 01-bug-report.yml | bug | 错误报告 |
# | 02-feature-request.yml | enhancement | 功能请求 |
# | 03-documentation.yml | documentation | 文档问题 |
# | 04-question.yml | question | 问题咨询 |
#
# 如需添加更多标签,编辑对应模板文件的 `labels:` 字段
# 示例:labels: ["bug", "critical", "help-wanted"]
Expand Down
42 changes: 0 additions & 42 deletions .github/PULL_REQUEST_TEMPLATE/AGENTS.md

This file was deleted.

68 changes: 63 additions & 5 deletions .github/scripts/check_snapshot_provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import subprocess
import sys
from collections.abc import Sequence
from pathlib import Path

SNAPSHOT_PREFIX = "src/pt_snap_cli/snapshot/"
PROVENANCE_PATH = f"{SNAPSHOT_PREFIX}PROVENANCE.md"
Expand Down Expand Up @@ -44,6 +43,38 @@ def changed_paths(base: str, head: str) -> list[str]:
return [os.fsdecode(path) for path in result.stdout.split(b"\0") if path]


def git_blob(ref: str, path: str) -> bytes | None:
result = subprocess.run(
["git", "show", f"{ref}:{path}"],
check=False,
capture_output=True,
)
return result.stdout if result.returncode == 0 else None


def validate_append_only(base: bytes | None, head: bytes | None) -> list[bytes]:
"""Return inserted lines while rejecting changes to existing provenance lines."""
if head is None:
raise GuardError(f"Append-only provenance file was deleted: {PROVENANCE_PATH}.")

base_lines = [] if base is None else base.splitlines(keepends=True)
head_lines = head.splitlines(keepends=True)
base_index = 0
inserted: list[bytes] = []
for line in head_lines:
if base_index < len(base_lines) and line == base_lines[base_index]:
base_index += 1
else:
inserted.append(line)

if base_index != len(base_lines):
raise GuardError(
f"{PROVENANCE_PATH} is append-only; existing lines may not be deleted, "
"rewritten, truncated, or reordered."
)
return inserted


def _declarations(body: str) -> dict[str, list[str]]:
declarations = {DECISION_LABEL.lower(): [], REASON_LABEL.lower(): []}
for match in _DECLARATION.finditer(body):
Expand All @@ -53,7 +84,11 @@ def _declarations(body: str) -> dict[str, list[str]]:
return declarations


def validate_provenance(changes: Sequence[str], body: str) -> str:
def validate_provenance(
changes: Sequence[str],
body: str,
inserted_lines: Sequence[bytes] = (),
) -> str:
snapshot_changes = [path for path in changes if path.startswith(SNAPSHOT_PREFIX)]
if not snapshot_changes:
return "No snapshot runtime changes detected."
Expand All @@ -75,10 +110,12 @@ def validate_provenance(changes: Sequence[str], body: str) -> str:
if decision == "updated":
if PROVENANCE_PATH not in changes:
raise GuardError(f"The 'updated' decision requires a change to {PROVENANCE_PATH}.")
if not Path(PROVENANCE_PATH).is_file():
raise GuardError(f"The updated provenance declaration is missing: {PROVENANCE_PATH}.")
if not any(line.strip() for line in inserted_lines):
raise GuardError(f"The 'updated' decision requires new content in {PROVENANCE_PATH}.")
return f"Snapshot provenance updated in {PROVENANCE_PATH}."

if PROVENANCE_PATH in changes:
raise GuardError(f"The 'no-update' decision cannot include a change to {PROVENANCE_PATH}.")
if len(reasons) != 1:
raise GuardError(f"The 'no-update' decision requires one '{REASON_LABEL}:' declaration.")
reason = reasons[0]
Expand All @@ -96,10 +133,31 @@ def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--base", required=True, help="Base commit SHA")
parser.add_argument("--head", required=True, help="Head commit SHA")
parser.add_argument(
"--require-decision",
action="store_true",
help="Require the PR provenance declaration in PR_BODY",
)
args = parser.parse_args()

try:
message = validate_provenance(changed_paths(args.base, args.head), os.getenv("PR_BODY", ""))
changes = changed_paths(args.base, args.head)
inserted_lines: Sequence[bytes] = ()
if PROVENANCE_PATH in changes:
inserted_lines = validate_append_only(
git_blob(args.base, PROVENANCE_PATH),
git_blob(args.head, PROVENANCE_PATH),
)
if args.require_decision:
message = validate_provenance(
changes,
os.getenv("PR_BODY", ""),
inserted_lines,
)
elif PROVENANCE_PATH in changes:
message = f"Append-only snapshot provenance validated in {PROVENANCE_PATH}."
else:
message = "No snapshot provenance content changes detected."
except (GuardError, subprocess.CalledProcessError) as exc:
print(f"Snapshot provenance guard failed: {exc}", file=sys.stderr)
return 1
Expand Down
6 changes: 4 additions & 2 deletions .github/workflows/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
## Key Files
| File | Description |
|------|-------------|
| `test.yml` | PR provenance gate plus lint, type, test-matrix, coverage, build, and wheel smoke checks. |
| `release.yml` | Release workflow for building and publishing package artifacts. |
| `test.yml` | Reusable provenance, lint, type, test-matrix, coverage, build, and wheel smoke checks. |
| `release.yml` | Tag workflow that gates build and publication on the tagged commit's reusable quality workflow. |

## Subdirectories
| Directory | Purpose |
Expand All @@ -24,6 +24,7 @@
- Treat release workflow edits as high-impact and verify syntax carefully.
- Do not bypass tests, lint, type checks, or publishing safeguards without explicit instruction.
- Keep snapshot provenance inputs and declaration parsing aligned with `.github/scripts/check_snapshot_provenance.py` and the PR template.
- Keep release validation before PyPI publication; release notes and package version must be validated in `build`.

### Testing Requirements
- Validate YAML syntax.
Expand All @@ -33,6 +34,7 @@
### Common Patterns
- Workflows install the package with development extras before verification.
- The test workflow defines independent provenance, lint, and Python-version test jobs that may run concurrently.
- Release ordering is `quality` -> `build` -> `publish` -> `github-release`; the local reusable workflow is resolved from the tag commit.

## Dependencies

Expand Down
54 changes: 35 additions & 19 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ permissions:
contents: read

jobs:
quality:
name: Verify tagged commit
uses: ./.github/workflows/test.yml

build:
name: Build distribution
needs: quality
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -39,13 +44,39 @@ jobs:
- name: Verify package runs
run: pt-snap --version

- name: Extract release notes from changelog
run: |
python - <<'PY'
import os
import re
from pathlib import Path

tag = os.environ["GITHUB_REF"].removeprefix("refs/tags/v")
text = Path("CHANGELOG.md").read_text()
pattern = rf"^## \[{re.escape(tag)}\].*?$(.*?)(?=^## \[|\Z)"
match = re.search(pattern, text, re.MULTILINE | re.DOTALL)
if not match:
raise SystemExit(f"CHANGELOG.md does not contain release notes for ## [{tag}]")
notes = match.group(1).strip()
if not notes:
raise SystemExit(f"CHANGELOG.md release notes for ## [{tag}] are empty")
Path("release-notes.md").write_text(notes + "\n")
PY

- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
retention-days: 90

- name: Upload release notes
uses: actions/upload-artifact@v4
with:
name: release-notes
path: release-notes.md
retention-days: 90

publish:
name: Publish to PyPI
needs: build
Expand Down Expand Up @@ -88,25 +119,10 @@ jobs:
name: dist
path: dist/

- name: Extract release notes from changelog
run: |
TAG=${GITHUB_REF#refs/tags/v}
python - <<'PY'
import os
import re
from pathlib import Path

tag = os.environ["GITHUB_REF"].removeprefix("refs/tags/v")
text = Path("CHANGELOG.md").read_text()
pattern = rf"^## \[{re.escape(tag)}\].*?$(.*?)(?=^## \[|\Z)"
match = re.search(pattern, text, re.MULTILINE | re.DOTALL)
if not match:
raise SystemExit(f"CHANGELOG.md does not contain release notes for ## [{tag}]")
notes = match.group(1).strip()
if not notes:
raise SystemExit(f"CHANGELOG.md release notes for ## [{tag}] are empty")
Path("release-notes.md").write_text(notes + "\n")
PY
- name: Download release notes
uses: actions/download-artifact@v4
with:
name: release-notes

- name: Create GitHub Release
run: |
Expand Down
Loading
Loading