Repository navigation
Expand file tree
/
Copy pathcheck_charon_drift.py
More file actions
176 lines (144 loc) · 5.86 KB
/
Copy pathcheck_charon_drift.py
File metadata and controls
176 lines (144 loc) · 5.86 KB
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
"""Report Charon commits that touch spec surface since the pinned anchor.
This is the staleness alarm. The spec tracks Charon `main`, so it goes stale
silently: between 2026-07-14 and 2026-07-29 Charon moved eight commits past the
anchor, three of them wire-visible, and nothing noticed. Run this on a schedule
and the drift is a failing job instead of a discovery.
The anchor and the watched paths live in `charon_anchor.json`. Paths are watched
broadly and only the components the spec explicitly declines to cover are
ignored, so a Charon subsystem nobody has thought about yet is reported rather
than missed.
Usage:
uv run python scripts/check_charon_drift.py
uv run python scripts/check_charon_drift.py --repo-path ~/charon
Exits 0 when no watched path moved, 1 when something did (the alarm), and 2 when
the check itself could not run.
"""
from __future__ import annotations
import argparse
import os
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Sequence
from charon_repo import (
EXIT_ERROR,
EXIT_FOUND,
EXIT_OK,
Anchor,
CharonRepoError,
fetch_branch_head,
resolve_repo,
run_git,
)
@dataclass(frozen=True)
class Commit:
"""A Charon commit that touched at least one watched path."""
sha: str
subject: str
watched_paths: tuple[str, ...]
@property
def is_test_only(self) -> bool:
"""Whether every watched path is a Go test file.
Reported but deprioritised: a test-only change rarely moves the wire, and
flagging it as loudly as a protocol change trains the reader to ignore
the alarm. It is not filtered out, because Charon's tests are where the
accept/reject tables this spec mirrors actually live.
"""
return all(path.endswith("_test.go") for path in self.watched_paths)
def find_drift(anchor: Anchor, repo: Path, head: str) -> List[Commit]:
"""List commits between the anchor and `head` touching spec surface."""
if run_git(["cat-file", "-t", anchor.commit], cwd=repo).strip() != "commit":
raise CharonRepoError(f"anchor {anchor.commit} is not a commit in {anchor.repo}")
# \x1e (record separator) cannot appear in a subject line, unlike newlines,
# which --name-only already uses to separate paths. --no-renames matters:
# with rename detection, a commit moving a watched file lists only the
# destination path, so a restructure out of the watched surface would
# report as "no drift" — the exact silence this script exists to prevent.
log = run_git(
[
"log",
"--name-only",
"--no-renames",
"--no-merges",
"--format=\x1e%H%x1f%s",
f"{anchor.commit}..{head}",
],
cwd=repo,
)
commits: List[Commit] = []
for record in log.split("\x1e"):
if not record.strip():
continue
header, _, body = record.partition("\n")
sha, _, subject = header.partition("\x1f")
watched = tuple(
line
for line in (entry.strip() for entry in body.splitlines())
if line and anchor.is_watched(line)
)
if watched:
commits.append(Commit(sha=sha, subject=subject, watched_paths=watched))
# Protocol changes first; test-only noise last.
return sorted(commits, key=lambda commit: commit.is_test_only)
def format_report(anchor: Anchor, commits: Sequence[Commit], head: str) -> str:
"""Render the drift report as Markdown, for a terminal or a job summary."""
lines = [
"# Charon staleness check",
"",
f"- Anchor: `{anchor.commit[:8]}` ({anchor.date})",
f"- Charon `{anchor.branch}`: `{head[:8]}`",
"",
]
if not commits:
lines.append("No commits touching spec surface. The anchor is current.")
return "\n".join(lines)
substantive = [commit for commit in commits if not commit.is_test_only]
lines.append(
f"**{len(commits)} commit(s) touch spec surface"
f"{f', {len(substantive)} outside tests' if substantive else ', all test-only'}.**"
)
lines.append("")
for commit in commits:
marker = " _(tests only)_" if commit.is_test_only else ""
lines.append(f"- `{commit.sha[:8]}` {commit.subject}{marker}")
for path in commit.watched_paths:
lines.append(f" - `{path}`")
lines += [
"",
"Re-validate the affected specs against Charon, then advance `commit` in",
"`charon_anchor.json` and the version anchor in `README.md`. Record what",
"moved, and what was assessed and ruled out of scope, in",
"`plans/spec-completion.md`.",
]
return "\n".join(lines)
def main(argv: Sequence[str] | None = None) -> int:
"""Run the check and return the process exit code."""
parser = argparse.ArgumentParser(description=__doc__.split("\n", maxsplit=1)[0])
parser.add_argument(
"--repo-path",
default=os.environ.get("CHARON_REPO_PATH"),
help="Existing Charon checkout to use instead of cloning (env: CHARON_REPO_PATH)",
)
args = parser.parse_args(argv)
stack: List[Path] = []
try:
anchor = Anchor.load()
repo = resolve_repo(anchor, args.repo_path, stack)
head = fetch_branch_head(anchor, repo)
commits = find_drift(anchor, repo, head)
except CharonRepoError as error:
print(f"charon drift check could not run: {error}", file=sys.stderr)
return EXIT_ERROR
finally:
for path in stack:
shutil.rmtree(path, ignore_errors=True)
report = format_report(anchor, commits, head)
print(report)
summary = os.environ.get("GITHUB_STEP_SUMMARY")
if summary:
with open(summary, "a", encoding="utf-8") as handle:
handle.write(report + "\n")
return EXIT_FOUND if commits else EXIT_OK
if __name__ == "__main__":
sys.exit(main())