polyctl 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- polyctl/__init__.py +7 -0
- polyctl/__main__.py +5 -0
- polyctl/a2a.py +226 -0
- polyctl/a2a_mcp.py +546 -0
- polyctl/acp.py +417 -0
- polyctl/adapters/README.md +101 -0
- polyctl/adapters/aider.json +32 -0
- polyctl/adapters/amazon-q.json +15 -0
- polyctl/adapters/amp.json +16 -0
- polyctl/adapters/antigravity.json +120 -0
- polyctl/adapters/claude-code.json +229 -0
- polyctl/adapters/cloud-generic.json +57 -0
- polyctl/adapters/codex.json +47 -0
- polyctl/adapters/command-code.json +45 -0
- polyctl/adapters/copilot.json +17 -0
- polyctl/adapters/cursor-agent.json +29 -0
- polyctl/adapters/deepseek.json +13 -0
- polyctl/adapters/droid.json +34 -0
- polyctl/adapters/gemini.json +30 -0
- polyctl/adapters/grok.json +22 -0
- polyctl/adapters/hermes.json +34 -0
- polyctl/adapters/kilocode.json +30 -0
- polyctl/adapters/kimi.json +23 -0
- polyctl/adapters/kiro.json +332 -0
- polyctl/adapters/ollama.json +29 -0
- polyctl/adapters/omp.json +34 -0
- polyctl/adapters/openai-api.json +68 -0
- polyctl/adapters/opencode.json +162 -0
- polyctl/adapters/pi.json +24 -0
- polyctl/adapters/pr-agent.json +54 -0
- polyctl/adapters/profiles.json +9 -0
- polyctl/adapters/qoder.json +163 -0
- polyctl/adapters/qwen.json +27 -0
- polyctl/adapters/reasonix.json +25 -0
- polyctl/adapters/rewriters/rtk.json +24 -0
- polyctl/adapters/trae.json +31 -0
- polyctl/adapters/vendors.json +42 -0
- polyctl/adapters/warp.json +88 -0
- polyctl/allowlist.py +1756 -0
- polyctl/api_review.py +920 -0
- polyctl/cli.py +835 -0
- polyctl/conformance_harness.py +9 -0
- polyctl/demo.py +503 -0
- polyctl/drivers.py +146 -0
- polyctl/email.py +160 -0
- polyctl/features.py +98 -0
- polyctl/journal.py +144 -0
- polyctl/language.py +945 -0
- polyctl/lib.py +1296 -0
- polyctl/matrix.py +660 -0
- polyctl/mcp.py +1362 -0
- polyctl/ntfy.py +169 -0
- polyctl/outbound.py +39 -0
- polyctl/parts/__init__.py +5 -0
- polyctl/parts/cli_authority.py +2615 -0
- polyctl/parts/cli_channels.py +1325 -0
- polyctl/parts/cli_checks.py +2293 -0
- polyctl/parts/cli_completion.py +686 -0
- polyctl/parts/cli_evidence.py +141 -0
- polyctl/parts/cli_gain.py +375 -0
- polyctl/parts/cli_harness.py +392 -0
- polyctl/parts/cli_hooks.py +1816 -0
- polyctl/parts/cli_install.py +638 -0
- polyctl/parts/cli_lanes.py +106 -0
- polyctl/parts/cli_maintenance.py +2536 -0
- polyctl/parts/cli_next.py +248 -0
- polyctl/parts/cli_pr.py +53 -0
- polyctl/parts/cli_project.py +2857 -0
- polyctl/parts/cli_review.py +5158 -0
- polyctl/parts/cli_status.py +898 -0
- polyctl/parts/lib_adapters.py +2933 -0
- polyctl/parts/lib_alarms.py +2106 -0
- polyctl/parts/lib_events.py +224 -0
- polyctl/parts/lib_evidence.py +412 -0
- polyctl/parts/lib_gates.py +2099 -0
- polyctl/parts/lib_lanes.py +829 -0
- polyctl/parts/lib_mail.py +1541 -0
- polyctl/parts/lib_next.py +652 -0
- polyctl/parts/lib_pr.py +331 -0
- polyctl/parts/lib_slices.py +3337 -0
- polyctl/parts/lib_state.py +2415 -0
- polyctl/parts/lib_transcript.py +4118 -0
- polyctl/pressure.py +325 -0
- polyctl/prices.json +47 -0
- polyctl/procs.py +1194 -0
- polyctl/settings.py +505 -0
- polyctl/skill/SKILL.md +365 -0
- polyctl/skillkit.py +503 -0
- polyctl/storage.py +2055 -0
- polyctl/telegram.py +327 -0
- polyctl/tiers.py +123 -0
- polyctl/verdicts.py +41 -0
- polyctl/watchdog.py +3887 -0
- polyctl/web.py +337 -0
- polyctl-0.7.0.dist-info/METADATA +235 -0
- polyctl-0.7.0.dist-info/RECORD +99 -0
- polyctl-0.7.0.dist-info/WHEEL +4 -0
- polyctl-0.7.0.dist-info/entry_points.txt +5 -0
- polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,2615 @@
|
|
|
1
|
+
"""Authority: verify, merge checks, commit-ok, the project marker, commit and commit-check.
|
|
2
|
+
|
|
3
|
+
A part of src/polyctl/cli.py (#44): moved out byte for byte and run in its namespace by `_part`,
|
|
4
|
+
where it stood; it is not importable on its own.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _scheduled_path():
|
|
9
|
+
"""The PATH a scheduled job runs with, fixed when the job is installed.
|
|
10
|
+
|
|
11
|
+
launchd starts jobs with /usr/bin:/bin:/usr/sbin:/sbin, which does not reach
|
|
12
|
+
~/.local/bin, where kiro-cli, polyctl and the watchdog live; the credit sampler ran
|
|
13
|
+
blind for its whole life because of it. A user systemd's own PATH does not reach
|
|
14
|
+
it either. Take the watchdog's child PATH, keep directories that exist, and drop
|
|
15
|
+
per-shell version-manager directories that disappear when the shell that created
|
|
16
|
+
them exits.
|
|
17
|
+
"""
|
|
18
|
+
from .watchdog import child_path
|
|
19
|
+
seen, keep = set(), []
|
|
20
|
+
for d in child_path().split(os.pathsep):
|
|
21
|
+
if not d or d in seen or "fnm_multishells" in d or not os.path.isdir(d):
|
|
22
|
+
continue
|
|
23
|
+
seen.add(d)
|
|
24
|
+
keep.append(d)
|
|
25
|
+
return os.pathsep.join(keep)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _launchd_path():
|
|
29
|
+
"""The PATH a launchd job runs with, escaped as the text of a plist's <string>."""
|
|
30
|
+
from xml.sax.saxutils import escape
|
|
31
|
+
return escape(_scheduled_path())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _launchctl(*args, merge=False):
|
|
35
|
+
"""(what `launchctl <args>` printed, its exit status), asked without a shell.
|
|
36
|
+
|
|
37
|
+
Through a shell the user's id came from `$(id -u)`, and the label and the plist path
|
|
38
|
+
were shell text: a project directory named with a space, a `*` or a `;` reached
|
|
39
|
+
launchctl as other words, or ran as a command. Its standard error is discarded, as the
|
|
40
|
+
shell discarded it, unless `merge` keeps it in the answer as `2>&1` did.
|
|
41
|
+
"""
|
|
42
|
+
return A._run_program(["launchctl", *args], stderr=subprocess.STDOUT if merge else subprocess.DEVNULL)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _launchd_domain(label=None):
|
|
46
|
+
"""The user's launchd domain, `gui/<uid>`, or one job's target in it."""
|
|
47
|
+
return f"gui/{os.getuid()}" + (f"/{label}" if label else "")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _launchd_listed(label):
|
|
51
|
+
"""The lines of `launchctl list` that name `label`, as `launchctl list | grep <label>` printed them.
|
|
52
|
+
|
|
53
|
+
Matched as text rather than as grep's pattern, which a `.` in every label already
|
|
54
|
+
widened and a `*` or `[` in a project's name turned into one that matched nothing.
|
|
55
|
+
"""
|
|
56
|
+
return "\n".join(line for line in _launchctl("list")[0].split("\n") if label in line).strip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# Every launchd label polyctl gives a job starts with this; `polyctl uninstall` takes the namespace whole.
|
|
60
|
+
LAUNCHD_NAMESPACE = "com.polyctl."
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _launchd_label(job, key):
|
|
64
|
+
"""The launchd label of one job polyctl schedules for a project: `watchdog`, `doctor` or `telegram`."""
|
|
65
|
+
return f"{LAUNCHD_NAMESPACE}{job}.{key.lower()}"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _launchd_plist(label):
|
|
69
|
+
return os.path.join(A.HOME, "Library", "LaunchAgents", label + ".plist")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _launchd_loaded(label):
|
|
73
|
+
"""Whether `launchctl list` names exactly this label: True or False, else why launchd cannot be asked.
|
|
74
|
+
|
|
75
|
+
`_launchd_listed` reads the listing as grep did, and the watchdog label of a project
|
|
76
|
+
called `proj` is inside the one of `proj-api`: a removal checks the label itself. A
|
|
77
|
+
listing launchctl did not give - it could not be run, or it failed - named no label, and
|
|
78
|
+
`polyctl remove` read that as the job gone and took the state of a project it ran on against
|
|
79
|
+
(LEADS-INSTALL).
|
|
80
|
+
"""
|
|
81
|
+
said, status = _launchctl("list")
|
|
82
|
+
if status != 0:
|
|
83
|
+
return "launchctl could not be run" if status is None else f"launchctl list exited {status}"
|
|
84
|
+
return any(line.rsplit("\t", 1)[-1].strip() == label for line in said.split("\n"))
|
|
85
|
+
|
|
86
|
+
PLIST_CMD = """<?xml version="1.0" encoding="UTF-8"?>
|
|
87
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
88
|
+
<plist version="1.0"><dict>
|
|
89
|
+
<key>Label</key><string>{label}</string>
|
|
90
|
+
<key>ProgramArguments</key><array>{args}</array>
|
|
91
|
+
<key>StartInterval</key><integer>{interval}</integer>
|
|
92
|
+
<key>EnvironmentVariables</key><dict><key>PATH</key><string>{path}</string></dict>
|
|
93
|
+
<key>RunAtLoad</key><true/>
|
|
94
|
+
<key>StandardOutPath</key><string>{log}</string>
|
|
95
|
+
<key>StandardErrorPath</key><string>{log}</string>
|
|
96
|
+
</dict></plist>
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
PLIST = """<?xml version="1.0" encoding="UTF-8"?>
|
|
100
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
101
|
+
<plist version="1.0"><dict>
|
|
102
|
+
<key>Label</key><string>{label}</string>
|
|
103
|
+
<key>ProgramArguments</key>
|
|
104
|
+
<array>{python_arg}<string>{script}</string>
|
|
105
|
+
<string>--root</string><string>{root}</string>
|
|
106
|
+
<string>--idle-minutes</string><string>{idle}</string></array>
|
|
107
|
+
<key>StartInterval</key><integer>{interval}</integer>
|
|
108
|
+
<key>EnvironmentVariables</key><dict><key>PATH</key><string>{path}</string></dict>
|
|
109
|
+
<key>RunAtLoad</key><true/>
|
|
110
|
+
<key>StandardOutPath</key><string>{log}</string>
|
|
111
|
+
<key>StandardErrorPath</key><string>{log}</string>
|
|
112
|
+
</dict></plist>
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _judge_gate(g, out, code):
|
|
117
|
+
"""(passed, detail, counts) for one gate's output and exit code, as `polyctl verify` judges it."""
|
|
118
|
+
counts = None
|
|
119
|
+
|
|
120
|
+
if g.get("expect") == "empty":
|
|
121
|
+
# What it prints decides, and it counts only where the command exited 0, or with a code the gate declares
|
|
122
|
+
# in `ok_exit` - grep and git grep exit 1 for finding nothing, so a sweep with them declares [0, 1]. No code
|
|
123
|
+
# is taken for an answer unsaid: grep exits 2 for an error, and `grep -R '[' src 2>/dev/null` printed
|
|
124
|
+
# nothing, measured nothing and passed, as did a program whose silent 1 is its failure (LEADS-GATE).
|
|
125
|
+
answered = _gate_ok_exits(g)
|
|
126
|
+
ran = isinstance(code, int) and not isinstance(code, bool) and code in answered
|
|
127
|
+
passed = ran and not out.strip()
|
|
128
|
+
detail = ("clean" if passed else " ".join(out.split())[:120] if out.strip()
|
|
129
|
+
else f"exit {code} and nothing printed: the command failed rather than found nothing (a sweep "
|
|
130
|
+
f"counts on {', '.join(map(str, sorted(answered)))}; a program that answers otherwise is "
|
|
131
|
+
"declared with ok_exit)")
|
|
132
|
+
else:
|
|
133
|
+
# The exit code decides; counts come only from the runner's closing
|
|
134
|
+
# summary, never from the first match in output the implementer controls (#70).
|
|
135
|
+
passed = code == 0
|
|
136
|
+
counts = A.gate_counts(out, g.get("summary"))
|
|
137
|
+
if counts:
|
|
138
|
+
p_, f_ = counts
|
|
139
|
+
detail = f"{p_}/{p_ + f_}"
|
|
140
|
+
passed = passed and f_ == 0
|
|
141
|
+
# Exit zero is not proof that anything ran. A test runner whose
|
|
142
|
+
# worker pool fails can collect zero tests and exit 0, and the
|
|
143
|
+
# gate stays green having measured nothing — the second pilot's
|
|
144
|
+
# agent found vitest doing exactly that. A gate that declares
|
|
145
|
+
# `min_tests` must see at least that many actually execute.
|
|
146
|
+
need = int(g.get("min_tests", 0) or 0)
|
|
147
|
+
if need and (p_ + f_) < need:
|
|
148
|
+
passed = False
|
|
149
|
+
detail += f" — only {p_ + f_} ran, {need} required"
|
|
150
|
+
elif g.get("min_tests"):
|
|
151
|
+
passed = False
|
|
152
|
+
detail = (f"exit {code}, but the runner's closing summary was not found "
|
|
153
|
+
f"and min_tests={g['min_tests']}")
|
|
154
|
+
else:
|
|
155
|
+
detail = f"exit {code}"
|
|
156
|
+
return passed, detail, counts
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _gate_ok_exits(g):
|
|
160
|
+
"""The exit codes an `expect: empty` gate's command answers with when it found nothing: 0, and the ones the gate
|
|
161
|
+
declares in `ok_exit` (LEADS-GATE)."""
|
|
162
|
+
declared = g.get("ok_exit")
|
|
163
|
+
return {0} | (set(declared) if isinstance(declared, list) else set())
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _run_gate(cfg, g, cwd):
|
|
167
|
+
"""(what one gate printed, its exit code): its command line run in `cwd`, as `polyctl verify` and `polyctl merge-check` run it.
|
|
168
|
+
|
|
169
|
+
In Windows' own cmd.exe, never one found in the current directory (WINDOWS-NO-CWD-EXEC); what that
|
|
170
|
+
shell runs is the project's, as on POSIX. It leads a process group of its own, so a timeout stops
|
|
171
|
+
it with whatever it started (A.run_as_group): a gate's shell was killed alone and its test workers
|
|
172
|
+
ran on, loading the machine after the run had let go of the lock they ran under (LEADS-GATE). A
|
|
173
|
+
SIGTERM or SIGHUP sent to polyctl stops the gate as Ctrl-C does, since its group hears neither.
|
|
174
|
+
"""
|
|
175
|
+
timeout = g.get("timeout") or S.get(cfg, "gates.default_timeout")
|
|
176
|
+
saved = A._hear_stop_signals()
|
|
177
|
+
try:
|
|
178
|
+
# One pipe keeps a stderr summary before the stdout summary written after it (TRIAGE-2-LOW).
|
|
179
|
+
ran = A.run_as_group(g["run"], timeout, shell=True, cwd=cwd, stdout=subprocess.PIPE,
|
|
180
|
+
stderr=subprocess.STDOUT, text=True,
|
|
181
|
+
encoding=UTF8, errors="replace", executable=A.shell_program())
|
|
182
|
+
except subprocess.TimeoutExpired as expired:
|
|
183
|
+
left, unasked = getattr(expired, "left", None), getattr(expired, "unasked", None)
|
|
184
|
+
return ("timed out" + (f"; {len(left)} process(es) it started still run after it was stopped: {left} - "
|
|
185
|
+
"stop them by hand" if left else "")
|
|
186
|
+
+ (f"; {unasked} - look for them and stop them by hand" if unasked else ""), 124)
|
|
187
|
+
except OSError as exc:
|
|
188
|
+
# A command line the system cannot start - one past ARG_MAX, a shell that is gone - is the gate's failure,
|
|
189
|
+
# recorded as its answer, where it raised once the machine lock was held (LEADS-GATE-RUNS).
|
|
190
|
+
return f"could not start: {' '.join(str(exc).split())[:200]}", 127
|
|
191
|
+
finally:
|
|
192
|
+
A._restore_signals(saved)
|
|
193
|
+
return ran.stdout or "", ran.returncode
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _profile_gates(spec, profile, cfg=None):
|
|
197
|
+
"""(the names of the gates `profile` runs, why .polyctl/gates.json cannot run them); ([], None) for a profile it does not
|
|
198
|
+
declare (LEADS-GATE).
|
|
199
|
+
|
|
200
|
+
The file is the implementer's to write, and every shape a run reads is checked before the machine
|
|
201
|
+
lock is taken: a file that was not an object, a profile that was not a list of names, a gate it
|
|
202
|
+
named that was not there or had no command, a timeout that was not a number - each raised in the
|
|
203
|
+
middle of `polyctl verify`, once the lock was held, where it is now one line and exit 2.
|
|
204
|
+
"""
|
|
205
|
+
if not isinstance(spec, dict):
|
|
206
|
+
return [], "it is not a JSON object"
|
|
207
|
+
profiles, gates = spec.get("profiles", {}), spec.get("gates", {})
|
|
208
|
+
if not isinstance(profiles, dict) or not isinstance(gates, dict):
|
|
209
|
+
return [], "its profiles and gates are not both JSON objects"
|
|
210
|
+
if not isinstance(profile, str):
|
|
211
|
+
return [], f"its default_profile {profile!r} is not a name"
|
|
212
|
+
if profile not in profiles:
|
|
213
|
+
return [], None
|
|
214
|
+
names = profiles[profile]
|
|
215
|
+
# A profile that is there is a list of names, an empty one too: `""` read as no profile at all (LEADS-GATE).
|
|
216
|
+
if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
|
|
217
|
+
return [], f"profile {profile} is not a list of gate names"
|
|
218
|
+
for name in names:
|
|
219
|
+
why = _gate_shape_problem(gates.get(name))
|
|
220
|
+
if why:
|
|
221
|
+
return [], f"profile {profile} runs gate {name}, and {why}"
|
|
222
|
+
untimed = next((name for name in names if gates[name].get("timeout") is None), None)
|
|
223
|
+
if untimed is not None and cfg is not None:
|
|
224
|
+
# The default a gate with no timeout runs under is held to what a gate's own is held to: one past a week was
|
|
225
|
+
# passed over for 600 seconds, where the gates file is refused (LEADS-GATE).
|
|
226
|
+
unusable = S.resolve(cfg, "gates.default_timeout")[2]
|
|
227
|
+
if unusable:
|
|
228
|
+
return [], f"profile {profile} runs gate {untimed} with no timeout of its own, and {unusable}"
|
|
229
|
+
return names, None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _gate_shape_problem(g):
|
|
233
|
+
"""Why one gate's definition is not one a run reads, or None (LEADS-GATE)."""
|
|
234
|
+
if g is None:
|
|
235
|
+
return "no gate defines it"
|
|
236
|
+
if not isinstance(g, dict):
|
|
237
|
+
return "it is not a JSON object"
|
|
238
|
+
if not isinstance(g.get("run"), str) or not g["run"].strip():
|
|
239
|
+
return "it has no command in run"
|
|
240
|
+
if "\x00" in g["run"]:
|
|
241
|
+
return "its command holds a NUL character, which no command line can carry"
|
|
242
|
+
timeout = g.get("timeout")
|
|
243
|
+
if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
|
244
|
+
or not 0 < timeout <= S.GATE_TIMEOUT_MAX):
|
|
245
|
+
# Zero was taken, then read as no timeout at all and replaced by the default; 1e308 was taken, then
|
|
246
|
+
# overflowed the wait once the machine lock was held (LEADS-GATE).
|
|
247
|
+
return "its timeout is not a number of seconds above zero and at most a week"
|
|
248
|
+
ok_exit = g.get("ok_exit")
|
|
249
|
+
if ok_exit is not None and not (isinstance(ok_exit, list) and ok_exit and all(
|
|
250
|
+
isinstance(code, int) and not isinstance(code, bool) and 0 <= code <= 125 for code in ok_exit)):
|
|
251
|
+
return "its ok_exit is not a list of the exit codes 0 to 125 its command answers with"
|
|
252
|
+
for key in ("expect", "summary"):
|
|
253
|
+
if g.get(key) is not None and not isinstance(g[key], str):
|
|
254
|
+
return f"its {key} is not text"
|
|
255
|
+
if g.get("summary") is not None:
|
|
256
|
+
# A missing group used to invent a zero count; refuse it before running (TRIAGE-2-LOW).
|
|
257
|
+
import re
|
|
258
|
+
try:
|
|
259
|
+
groups = re.compile(g["summary"]).groupindex
|
|
260
|
+
except re.error:
|
|
261
|
+
return "its summary is not a valid regex; use named pass and fail groups"
|
|
262
|
+
if not {"pass", "fail"} <= set(groups):
|
|
263
|
+
return "its summary must have both named pass and fail groups"
|
|
264
|
+
min_tests = g.get("min_tests")
|
|
265
|
+
# A whole number of tests or nothing: `[]` and `""` read as zero and the gate passed without its floor, and
|
|
266
|
+
# 1e309 read as infinity, which no int holds (LEADS-GATE).
|
|
267
|
+
if min_tests is not None and (isinstance(min_tests, bool) or not isinstance(min_tests, int) or min_tests < 0):
|
|
268
|
+
return "its min_tests is not a whole number of tests"
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _take_gate_lock(cfg, wait):
|
|
273
|
+
"""Take the machine gate lock for one run of the gates: the call that lets it go, or None if it stayed busy.
|
|
274
|
+
|
|
275
|
+
The lock is taken first and looked at only when the take fails. A look and then a take were
|
|
276
|
+
two steps, and two runs that looked at the same moment both found it free; the one whose take
|
|
277
|
+
failed ran its suite beside the other's all the same. A holder is waited for whatever project
|
|
278
|
+
it runs for: a `polyctl lock -- <suite>` in this checkout is as much a second suite as another
|
|
279
|
+
project's gates, and only another project's used to be waited for (GATE-LOCK-SAME-ROOT).
|
|
280
|
+
|
|
281
|
+
The one holder not waited for is the run's own: this process, or a process that started it,
|
|
282
|
+
as `polyctl lock -- polyctl verify` starts its verify. That holder is waiting for this run to finish, so
|
|
283
|
+
waiting for it could end only in a refusal; the run goes ahead inside its lock and leaves the
|
|
284
|
+
letting go to it. Nothing in polyctl holds the lock while it starts a verify - the review runner and
|
|
285
|
+
the MCP server take none, and `polyctl commit-ok --verify` and `polyctl prove` hold none when they call
|
|
286
|
+
one - so each of those runs takes the lock like any other.
|
|
287
|
+
|
|
288
|
+
Once it holds the lock, the run reads the machine and waits up to `wait` seconds more while its
|
|
289
|
+
memory, paging or disk is past its limit, keeping the lock - a run waiting for it would find the
|
|
290
|
+
same machine; a machine still short then has the lock let go, and no suite starts (MACHINE-PRESSURE).
|
|
291
|
+
Under its own holder's lock it reads nothing: the holder read the machine when it took the lock,
|
|
292
|
+
and what loads the machine now is the holder's own work.
|
|
293
|
+
"""
|
|
294
|
+
root = cfg["root"]
|
|
295
|
+
if A.acquire_gate_lock(root, 0):
|
|
296
|
+
return _room_under_the_lock(cfg, wait)
|
|
297
|
+
holder = A.gate_lock_holder()
|
|
298
|
+
ours, unread = A.ancestry(holder.get("pid")) if holder else (False, None)
|
|
299
|
+
if ours:
|
|
300
|
+
return lambda: None # its holder lets it go, after this run has finished
|
|
301
|
+
if ours is None:
|
|
302
|
+
# A walk that could not read a parent cannot tell its own holder from another run's; it says so
|
|
303
|
+
# before it waits, as for any holder, where it used to wait without a word (ANCESTOR-WINDOWS).
|
|
304
|
+
print(f"{C['yellow']}cannot tell whether pid {holder.get('pid')} started this run{C['reset']}: "
|
|
305
|
+
f"this platform did not say which process started pid {unread}", flush=True)
|
|
306
|
+
if not holder: # a lock polyctl cannot read, or one let go since the take
|
|
307
|
+
who, detail = "the machine lock is taken", A.GATE_LOCK
|
|
308
|
+
elif holder.get("root") == root:
|
|
309
|
+
who, detail = "another run in this project holds the machine lock", \
|
|
310
|
+
f"pid {holder.get('pid')}, {holder['minutes']}m"
|
|
311
|
+
else:
|
|
312
|
+
who, detail = f"{os.path.basename(holder.get('root') or 'another project')} is running its gates", \
|
|
313
|
+
f"{holder['minutes']}m"
|
|
314
|
+
print(f"{C['yellow']}{who}{C['reset']} {C['dim']}({detail}){C['reset']} — waiting up to {wait}s so two "
|
|
315
|
+
f"suites do not fight for one machine", flush=True)
|
|
316
|
+
if A.acquire_gate_lock(root, wait):
|
|
317
|
+
return _room_under_the_lock(cfg, wait)
|
|
318
|
+
print(f"{C['red']}still busy; not starting a second suite{C['reset']}")
|
|
319
|
+
return None
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _room_under_the_lock(cfg, wait):
|
|
323
|
+
"""The call that lets the gate lock go once the machine has room for the gates it is held for, or None, the lock
|
|
324
|
+
let go, when the machine stays short (MACHINE-PRESSURE)."""
|
|
325
|
+
room = False
|
|
326
|
+
try:
|
|
327
|
+
room = _machine_has_room(cfg, wait, "the gates")
|
|
328
|
+
finally:
|
|
329
|
+
if not room: # short, or stopped while it waited
|
|
330
|
+
A.release_gate_lock()
|
|
331
|
+
return A.release_gate_lock if room else None
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _machine_has_room(cfg, wait, what):
|
|
335
|
+
"""Whether the machine has room for `what`, after waiting up to `wait` seconds while it is short; a refusal is
|
|
336
|
+
printed, and the caller exits 2 on it as on a lock that stayed busy (MACHINE-PRESSURE)."""
|
|
337
|
+
from . import pressure
|
|
338
|
+
refused = pressure.wait_for_room(cfg, wait, what)
|
|
339
|
+
if refused:
|
|
340
|
+
print(f"{C['red']}{refused}{C['reset']}", flush=True)
|
|
341
|
+
return refused is None
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def cmd_merge_check(cfg, args):
|
|
345
|
+
"""Run a profile's gates on the result of a merge before it is made, and record the run (#39).
|
|
346
|
+
|
|
347
|
+
2026-09-07: four branches, each green on its own, were merged and main went
|
|
348
|
+
red - one changed a signature another still called. Hosted CI runs only when
|
|
349
|
+
dispatched by hand, so nothing caught it but a suite run afterwards. The merge
|
|
350
|
+
result is computed by git, checked out into a temporary worktree and gated
|
|
351
|
+
there; the record names both parents and the merged tree, so it vouches for
|
|
352
|
+
exactly that merge and no later one.
|
|
353
|
+
"""
|
|
354
|
+
import shutil
|
|
355
|
+
import tempfile
|
|
356
|
+
root = cfg["root"]
|
|
357
|
+
into = A.git_text(root, "rev-parse", "--verify", "--quiet", f"{args.into}^{{commit}}")
|
|
358
|
+
branch = A.git_text(root, "rev-parse", "--verify", "--quiet", f"{args.branch}^{{commit}}")
|
|
359
|
+
if not into or not branch:
|
|
360
|
+
print(f"{C['red']}cannot resolve {args.branch if into else args.into} to a commit{C['reset']}")
|
|
361
|
+
return 2
|
|
362
|
+
try:
|
|
363
|
+
tree, conflict = A.merge_result_tree(root, into, branch)
|
|
364
|
+
except RuntimeError as exc:
|
|
365
|
+
print(f"{C['red']}{exc}{C['reset']}")
|
|
366
|
+
return 2
|
|
367
|
+
row = {"id": f"MC-{A.unique_ms()}", "at": int(time.time()), "into": into, "branch": branch,
|
|
368
|
+
"tree": tree, "profile": args.profile, "gates_digest": None, "measured_by": A.measured_by()}
|
|
369
|
+
if conflict:
|
|
370
|
+
row.update(passed=False, gates=[], conflict=conflict)
|
|
371
|
+
A.record_merge_check(root, row)
|
|
372
|
+
print(f"{C['red']}{C['b']}CONFLICT{C['reset']} {conflict} {C['dim']}recorded as {row['id']}{C['reset']}")
|
|
373
|
+
return 1
|
|
374
|
+
try:
|
|
375
|
+
spec = json.loads(A._git_output(root, "show", f"{tree}:.polyctl/gates.json"))
|
|
376
|
+
except (OSError, ValueError, RuntimeError) as exc:
|
|
377
|
+
print(f"{C['red']}no usable .polyctl/gates.json{C['reset']}: {exc}")
|
|
378
|
+
return 2
|
|
379
|
+
declared = spec if isinstance(spec, dict) else {}
|
|
380
|
+
profiles = declared.get("profiles") if isinstance(declared.get("profiles"), dict) else {}
|
|
381
|
+
profile = args.profile or ("full" if "full" in profiles else declared.get("default_profile", "quick"))
|
|
382
|
+
names, problem = _profile_gates(spec, profile, cfg)
|
|
383
|
+
if problem:
|
|
384
|
+
print(f"{C['red']}no usable .polyctl/gates.json{C['reset']}: {problem}")
|
|
385
|
+
return 2
|
|
386
|
+
if not names:
|
|
387
|
+
print(f"unknown profile {profile}; have: {', '.join(profiles)}")
|
|
388
|
+
return 2
|
|
389
|
+
row.update(profile=profile, gates_digest=A.gate_definitions_digest_of(spec, profile))
|
|
390
|
+
release = _take_gate_lock(cfg, args.wait)
|
|
391
|
+
if release is None:
|
|
392
|
+
return 2
|
|
393
|
+
scratch = tempfile.mkdtemp(prefix="polyctl-merge-check-")
|
|
394
|
+
result_dir = os.path.join(scratch, "result")
|
|
395
|
+
links, results, ok = [], [], True
|
|
396
|
+
made = False
|
|
397
|
+
try:
|
|
398
|
+
added = subprocess.run([A.git_binary(), "worktree", "add", "--detach", "--quiet", result_dir, into],
|
|
399
|
+
cwd=root, capture_output=True)
|
|
400
|
+
made = added.returncode == 0 or os.path.lexists(os.path.join(result_dir, ".git"))
|
|
401
|
+
checked_out = added.returncode == 0 and subprocess.run(
|
|
402
|
+
[A.git_binary(), "read-tree", "-u", "--reset", tree], cwd=result_dir, capture_output=True).returncode == 0
|
|
403
|
+
if not checked_out:
|
|
404
|
+
print(f"{C['red']}could not check out the merge result{C['reset']}: "
|
|
405
|
+
f"{added.stderr.decode(UTF8, 'replace').strip()}")
|
|
406
|
+
return 2
|
|
407
|
+
# Dependencies are installed per checkout, not tracked; the result borrows the project's.
|
|
408
|
+
for name in S.get(cfg, "merge.link_paths"):
|
|
409
|
+
source, target = os.path.join(root, name), os.path.join(result_dir, name)
|
|
410
|
+
if os.path.exists(source) and not os.path.lexists(target):
|
|
411
|
+
try:
|
|
412
|
+
os.symlink(source, target)
|
|
413
|
+
links.append(target)
|
|
414
|
+
except OSError:
|
|
415
|
+
pass
|
|
416
|
+
print(f"{C['b']}merge {args.branch} ({branch[:12]}) into {args.into} ({into[:12]}){C['reset']} "
|
|
417
|
+
f"{C['dim']}result tree {tree[:12]}, profile {profile}{C['reset']}")
|
|
418
|
+
for name in names:
|
|
419
|
+
g = spec["gates"][name]
|
|
420
|
+
print(f"{C['dim']}▶ {name}{C['reset']} {g['run']}")
|
|
421
|
+
started = time.time()
|
|
422
|
+
out, code = _run_gate(cfg, g, result_dir)
|
|
423
|
+
passed, detail, counts = _judge_gate(g, out, code)
|
|
424
|
+
ok = ok and passed
|
|
425
|
+
print(f" {C['green'] + 'pass' if passed else C['red'] + 'FAIL'}{C['reset']} {detail}")
|
|
426
|
+
results.append({"name": name, "passed": passed, "detail": detail, "exit": code,
|
|
427
|
+
"seconds": int(time.time() - started), "run": g["run"],
|
|
428
|
+
"summary": None if g.get("expect") == "empty"
|
|
429
|
+
else A.gate_summary_line(out, g.get("summary")),
|
|
430
|
+
"counts": {"pass": counts[0], "fail": counts[1]} if counts else None})
|
|
431
|
+
finally:
|
|
432
|
+
for link in links:
|
|
433
|
+
try:
|
|
434
|
+
os.unlink(link)
|
|
435
|
+
except OSError:
|
|
436
|
+
pass
|
|
437
|
+
try:
|
|
438
|
+
cleanup_steps = (("remove", "--force", result_dir), ("prune",)) if made else ()
|
|
439
|
+
if not made:
|
|
440
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
441
|
+
for cleanup_args in cleanup_steps:
|
|
442
|
+
try:
|
|
443
|
+
A._git_worktree_cleanup(root, *cleanup_args)
|
|
444
|
+
except A.WorktreeCleanupRefused:
|
|
445
|
+
raise
|
|
446
|
+
except RuntimeError as exc:
|
|
447
|
+
print(f"{C['yellow']}worktree cleanup incomplete{C['reset']}: "
|
|
448
|
+
f"{' '.join(str(exc).split())}; inspect the worktree administration and retry cleanup")
|
|
449
|
+
if cleanup_args[0] == "remove":
|
|
450
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
451
|
+
except A.WorktreeCleanupRefused as exc:
|
|
452
|
+
ok = False
|
|
453
|
+
print(f"{C['red']}worktree cleanup failed{C['reset']}: {exc}")
|
|
454
|
+
finally:
|
|
455
|
+
release()
|
|
456
|
+
row.update(passed=ok, gates=results, conflict=None)
|
|
457
|
+
A.record_merge_check(root, row)
|
|
458
|
+
print(f"\n{C['b']}{'PASS' if ok else 'FAIL'}{C['reset']} recorded as {row['id']}; it vouches for a merge of "
|
|
459
|
+
f"these two parents whose tree is {tree[:12]}")
|
|
460
|
+
return 0 if ok else 1
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _rerun_waived_gates(cfg, root, item, wait=None):
|
|
464
|
+
"""(passed, ran_names, detail) from re-running a gates waiver's waived gates on its landed commit (WAIVE-GATES)."""
|
|
465
|
+
import shutil
|
|
466
|
+
import tempfile
|
|
467
|
+
end = item["end"]
|
|
468
|
+
profile = item.get("profile")
|
|
469
|
+
expected_digest = item.get("gates_digest")
|
|
470
|
+
ver_id = item.get("verification") or "the grant's verification"
|
|
471
|
+
if not isinstance(profile, str) or not profile or not isinstance(expected_digest, str) or not expected_digest:
|
|
472
|
+
return False, [], f"{ver_id} has no recorded gate definitions digest"
|
|
473
|
+
candidates, read_error = [], None
|
|
474
|
+
try:
|
|
475
|
+
candidates.append(json.loads(A._git_output(root, "show", f"{end}:.polyctl/gates.json")))
|
|
476
|
+
except (OSError, ValueError, RuntimeError):
|
|
477
|
+
pass
|
|
478
|
+
try:
|
|
479
|
+
with open(os.path.join(root, ".polyctl", "gates.json"), encoding=UTF8) as fh:
|
|
480
|
+
candidates.append(json.load(fh))
|
|
481
|
+
except (OSError, ValueError) as exc:
|
|
482
|
+
read_error = exc
|
|
483
|
+
dicts = [c for c in candidates if isinstance(c, dict)]
|
|
484
|
+
if not dicts:
|
|
485
|
+
return False, [], f"no usable .polyctl/gates.json: {read_error or 'not a JSON object'}"
|
|
486
|
+
# The definitions catch-up runs must match the verification the grant stood on, so rewriting an
|
|
487
|
+
# untracked .polyctl/gates.json after landing cannot close a gates waiver on weaker gates (WAIVE-GATES).
|
|
488
|
+
spec = next((c for c in dicts if A.gate_definitions_digest_of(c, profile) == expected_digest), None)
|
|
489
|
+
if spec is None:
|
|
490
|
+
return False, [], (f"gate definitions for profile {profile} changed since {ver_id} — "
|
|
491
|
+
f"restore .polyctl/gates.json to match {ver_id}")
|
|
492
|
+
profile_gates, problem = _profile_gates(spec, profile, cfg)
|
|
493
|
+
if problem or not profile_gates:
|
|
494
|
+
return False, [], problem or f"unknown profile {profile}"
|
|
495
|
+
gates = spec["gates"]
|
|
496
|
+
names = list(item.get("waived_gates") or item["waiver"].get("gates") or [])
|
|
497
|
+
if not names:
|
|
498
|
+
names = list(profile_gates)
|
|
499
|
+
else:
|
|
500
|
+
outside = [name for name in names if name not in profile_gates]
|
|
501
|
+
if outside:
|
|
502
|
+
return False, [], f"gate {', '.join(outside)} is not in profile {profile}"
|
|
503
|
+
lock_wait = S.get(cfg, "gates.default_timeout") if wait is None else wait
|
|
504
|
+
release = _take_gate_lock(cfg, lock_wait)
|
|
505
|
+
if release is None:
|
|
506
|
+
return False, names, "machine gate lock stayed busy"
|
|
507
|
+
scratch = tempfile.mkdtemp(prefix="polyctl-catchup-gates-")
|
|
508
|
+
result_dir = os.path.join(scratch, "result")
|
|
509
|
+
links, failed_names = [], []
|
|
510
|
+
made = False
|
|
511
|
+
try:
|
|
512
|
+
added = subprocess.run([A.git_binary(), "worktree", "add", "--detach", "--quiet", result_dir, end],
|
|
513
|
+
cwd=root, capture_output=True)
|
|
514
|
+
made = added.returncode == 0 or os.path.lexists(os.path.join(result_dir, ".git"))
|
|
515
|
+
if added.returncode != 0:
|
|
516
|
+
return False, names, (f"could not check out {end[:12]}: "
|
|
517
|
+
f"{added.stderr.decode(UTF8, 'replace').strip()}")
|
|
518
|
+
for name in S.get(cfg, "merge.link_paths"):
|
|
519
|
+
source, target = os.path.join(root, name), os.path.join(result_dir, name)
|
|
520
|
+
if os.path.exists(source) and not os.path.lexists(target):
|
|
521
|
+
try:
|
|
522
|
+
os.symlink(source, target)
|
|
523
|
+
links.append(target)
|
|
524
|
+
except OSError:
|
|
525
|
+
pass
|
|
526
|
+
for name in names:
|
|
527
|
+
g = gates[name]
|
|
528
|
+
print(f" {C['dim']}▶ {name}{C['reset']} {g['run']}")
|
|
529
|
+
out, code = _run_gate(cfg, g, result_dir)
|
|
530
|
+
passed, detail, _ = _judge_gate(g, out, code)
|
|
531
|
+
print(f" {C['green'] + 'pass' if passed else C['red'] + 'FAIL'}{C['reset']} {detail}")
|
|
532
|
+
if not passed:
|
|
533
|
+
failed_names.append(f"{name} ({detail})")
|
|
534
|
+
finally:
|
|
535
|
+
for link in links:
|
|
536
|
+
try:
|
|
537
|
+
os.unlink(link)
|
|
538
|
+
except OSError:
|
|
539
|
+
pass
|
|
540
|
+
try:
|
|
541
|
+
cleanup_steps = (("remove", "--force", result_dir), ("prune",)) if made else ()
|
|
542
|
+
if not made:
|
|
543
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
544
|
+
for cleanup_args in cleanup_steps:
|
|
545
|
+
try:
|
|
546
|
+
A._git_worktree_cleanup(root, *cleanup_args)
|
|
547
|
+
except A.WorktreeCleanupRefused as exc:
|
|
548
|
+
failed_names.append(f"worktree cleanup failed: {exc}")
|
|
549
|
+
except RuntimeError:
|
|
550
|
+
pass
|
|
551
|
+
if cleanup_args[0] == "remove":
|
|
552
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
553
|
+
finally:
|
|
554
|
+
release()
|
|
555
|
+
if failed_names:
|
|
556
|
+
return False, names, ", ".join(failed_names)
|
|
557
|
+
return True, names, None
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def cmd_verify(cfg, args):
|
|
561
|
+
"""Run the project's declared gates ourselves and record what we measured.
|
|
562
|
+
|
|
563
|
+
The whole point of a second agent is not needing to trust the first one's
|
|
564
|
+
report, so this executes the commands and writes the numbers to the ledger.
|
|
565
|
+
Commit authority is later granted against this record, not against a claim.
|
|
566
|
+
|
|
567
|
+
The machine lock is taken once the gates to run are known (VERIFY-LOCK-LATE): a project that
|
|
568
|
+
declares none, or a profile it does not have, is told so at once instead of after a wait for
|
|
569
|
+
another project's suite, as `polyctl merge-check` already did. The candidate is read inside the lock,
|
|
570
|
+
so a change to the index during the wait is not read as one made while the gates ran.
|
|
571
|
+
"""
|
|
572
|
+
import json as _json
|
|
573
|
+
root = cfg["root"]
|
|
574
|
+
_urgent_banner(cfg)
|
|
575
|
+
gates_file = os.path.join(root, ".polyctl", "gates.json")
|
|
576
|
+
if not os.path.exists(gates_file):
|
|
577
|
+
print(f"{C['yellow']}No .polyctl/gates.json — nothing declared to verify.{C['reset']}")
|
|
578
|
+
print(f"{C['dim']}See docs/gates.md for the shape.{C['reset']}")
|
|
579
|
+
return 1
|
|
580
|
+
try:
|
|
581
|
+
with open(gates_file, encoding=UTF8) as fh:
|
|
582
|
+
spec = _json.load(fh)
|
|
583
|
+
except (OSError, ValueError) as exc:
|
|
584
|
+
# Said in one line before the lock is taken, as `polyctl merge-check` says it, where it raised (LEADS-GATE).
|
|
585
|
+
print(f"{C['red']}no usable .polyctl/gates.json{C['reset']}: {exc}")
|
|
586
|
+
return 2
|
|
587
|
+
declared = spec if isinstance(spec, dict) else {}
|
|
588
|
+
profile = args.profile or declared.get("default_profile", "quick")
|
|
589
|
+
names, problem = _profile_gates(spec, profile, cfg)
|
|
590
|
+
if problem:
|
|
591
|
+
print(f"{C['red']}no usable .polyctl/gates.json{C['reset']}: {problem}")
|
|
592
|
+
return 2
|
|
593
|
+
if not names:
|
|
594
|
+
profiles = declared.get("profiles")
|
|
595
|
+
print(f"unknown profile {profile}; have: {', '.join(profiles if isinstance(profiles, dict) else [])}")
|
|
596
|
+
return 1
|
|
597
|
+
# The record names what ran, so a later edit to gates.json cannot inherit
|
|
598
|
+
# this result (#61).
|
|
599
|
+
gates_digest = A.gate_definitions_digest_of(spec, profile)
|
|
600
|
+
# Isolation is judged by the paths these gates read, from this reading of the file: read again after the
|
|
601
|
+
# wait for the lock, inputs narrowed meanwhile and put back after the run hid a file a gate read (TRIAGE-HIGHS).
|
|
602
|
+
inputs = A.gate_inputs_of(spec)
|
|
603
|
+
release = _take_gate_lock(cfg, args.wait)
|
|
604
|
+
if release is None:
|
|
605
|
+
return 2
|
|
606
|
+
|
|
607
|
+
try:
|
|
608
|
+
candidate_before = A.index_candidate(root)
|
|
609
|
+
candidate_issues_before = A.candidate_worktree_issues(root, cfg, candidate_before, inputs=inputs)
|
|
610
|
+
except RuntimeError as exc:
|
|
611
|
+
release()
|
|
612
|
+
print(f"{C['red']}{exc}{C['reset']}")
|
|
613
|
+
return 2
|
|
614
|
+
candidate_messages = A.candidate_issue_messages(candidate_issues_before)
|
|
615
|
+
results, ok = [], not candidate_messages
|
|
616
|
+
if candidate_messages:
|
|
617
|
+
detail = "; ".join(candidate_messages)
|
|
618
|
+
print(f"{C['red']}FAIL{C['reset']} staged candidate is not isolated: {detail}")
|
|
619
|
+
results.append({"name": "candidate-isolation", "passed": False,
|
|
620
|
+
"detail": detail, "exit": 1, "seconds": 0})
|
|
621
|
+
|
|
622
|
+
for name in names:
|
|
623
|
+
g = spec["gates"][name]
|
|
624
|
+
print(f"{C['dim']}▶ {name}{C['reset']} {g['run']}")
|
|
625
|
+
started = time.time()
|
|
626
|
+
out, code = _run_gate(cfg, g, root)
|
|
627
|
+
took = int(time.time() - started)
|
|
628
|
+
passed, detail, counts = _judge_gate(g, out, code)
|
|
629
|
+
ok = ok and passed
|
|
630
|
+
mark = f"{C['green']}pass{C['reset']}" if passed else f"{C['red']}FAIL{C['reset']}"
|
|
631
|
+
print(f" {mark} {detail} {C['dim']}{took}s{C['reset']}")
|
|
632
|
+
if not passed:
|
|
633
|
+
tail = " ".join(out.strip().split("\n")[-4:])[:400]
|
|
634
|
+
print(f" {C['dim']}{tail}{C['reset']}")
|
|
635
|
+
results.append({"name": name, "passed": passed, "detail": detail,
|
|
636
|
+
"exit": code, "seconds": took, "run": g["run"],
|
|
637
|
+
# The runner's own closing line, for reports to quote (#6).
|
|
638
|
+
"summary": None if g.get("expect") == "empty"
|
|
639
|
+
else A.gate_summary_line(out, g.get("summary")),
|
|
640
|
+
"counts": None if g.get("expect") == "empty" or not counts
|
|
641
|
+
else {"pass": counts[0], "fail": counts[1]}})
|
|
642
|
+
|
|
643
|
+
try:
|
|
644
|
+
candidate_after = A.index_candidate(root)
|
|
645
|
+
candidate_issues_after = A.candidate_worktree_issues(root, cfg, candidate_after, inputs=inputs)
|
|
646
|
+
after_messages = A.candidate_issue_messages(candidate_issues_after)
|
|
647
|
+
except RuntimeError as exc:
|
|
648
|
+
candidate_after = None
|
|
649
|
+
after_messages = [str(exc)]
|
|
650
|
+
candidate_changed = not candidate_after or \
|
|
651
|
+
candidate_after["digest"] != candidate_before["digest"]
|
|
652
|
+
integrity = []
|
|
653
|
+
if candidate_changed:
|
|
654
|
+
integrity.append("index changed while gates were running")
|
|
655
|
+
for message in after_messages:
|
|
656
|
+
if message not in candidate_messages:
|
|
657
|
+
integrity.append(message)
|
|
658
|
+
if integrity:
|
|
659
|
+
ok = False
|
|
660
|
+
detail = "; ".join(integrity)
|
|
661
|
+
print(f"\n {C['red']}FAIL{C['reset']} candidate integrity: {detail}")
|
|
662
|
+
results.append({"name": "candidate-integrity", "passed": False,
|
|
663
|
+
"detail": detail, "exit": 1, "seconds": 0})
|
|
664
|
+
candidate_ready = bool(candidate_before["changed_paths"]) and \
|
|
665
|
+
not candidate_messages and not after_messages and not candidate_changed
|
|
666
|
+
|
|
667
|
+
# A plan the implementer edited is a plan that no longer measures anything:
|
|
668
|
+
# the work and the standard it is judged by came from the same hand. Treat it
|
|
669
|
+
# as a failed gate, because that is what it is.
|
|
670
|
+
try:
|
|
671
|
+
drift = A.plan_drift(root)
|
|
672
|
+
except Exception as exc:
|
|
673
|
+
ok = False
|
|
674
|
+
drift = []
|
|
675
|
+
print(f"\n {C['red']}FAIL{C['reset']} plan baselines cannot be read: {exc}")
|
|
676
|
+
results.append({"name": "plan-integrity", "passed": False,
|
|
677
|
+
"detail": f"unreadable: {exc}"[:200], "exit": 1, "seconds": 0})
|
|
678
|
+
if drift:
|
|
679
|
+
ok = False
|
|
680
|
+
print(f"\n {C['red']}FAIL{C['reset']} plan changed after admission: "
|
|
681
|
+
f"{', '.join(drift)}")
|
|
682
|
+
print(f" {C['dim']}the implementer reads its plan; it does not write to it{C['reset']}")
|
|
683
|
+
results.append({"name": "plan-integrity", "passed": False,
|
|
684
|
+
"detail": f"drifted: {','.join(drift)}", "exit": 1, "seconds": 0})
|
|
685
|
+
|
|
686
|
+
harness = _verify_harness_config(root)
|
|
687
|
+
|
|
688
|
+
revs = A.reviews(root, cfg["reviews"], limit=1)
|
|
689
|
+
rec = {"id": _verification_id(root), "at": datetime.now().isoformat(timespec="seconds"),
|
|
690
|
+
"schema": 2, "profile": profile, "gates_digest": gates_digest,
|
|
691
|
+
"by": "polyctl verify", "passed": ok,
|
|
692
|
+
"gates": results, "plan_drift": drift,
|
|
693
|
+
"candidate": candidate_before,
|
|
694
|
+
"candidate_after": candidate_after,
|
|
695
|
+
"candidate_ready": candidate_ready,
|
|
696
|
+
"candidate_issues": candidate_messages + [
|
|
697
|
+
message for message in after_messages if message not in candidate_messages
|
|
698
|
+
],
|
|
699
|
+
# The paths isolation was judged by, from the definitions that ran; null is the whole tree (TRIAGE-HIGHS).
|
|
700
|
+
"isolation_inputs": inputs,
|
|
701
|
+
# Keep the worktree digest for telemetry and legacy readers. Commit
|
|
702
|
+
# authority is bound to the immutable index candidate above.
|
|
703
|
+
"tree": A.tree_digest(root, cfg),
|
|
704
|
+
"review": revs[0][0] if revs else None,
|
|
705
|
+
"review_verdict": revs[0][1] if revs else None,
|
|
706
|
+
"head": A._git_text(root, "rev-parse", "--short", "HEAD"),
|
|
707
|
+
# Size by kind, never one number (#34).
|
|
708
|
+
"candidate_size": _candidate_size_or_none(root, candidate_before),
|
|
709
|
+
# Which git measured the candidate, and that no shell or agent stood between (#51).
|
|
710
|
+
"measured_by": A.measured_by(),
|
|
711
|
+
# What a harness reads from the tree that changed and no person has seen (HARNESS-CONFIG).
|
|
712
|
+
"harness_config": harness,
|
|
713
|
+
"dirty": len([l for l in A._git_text(root, "status", "--short").split("\n") if l.strip()])}
|
|
714
|
+
try:
|
|
715
|
+
A.record_verification(root, rec)
|
|
716
|
+
except Exception as exc:
|
|
717
|
+
print(f"{C['red']}{C['b']}NOT RECORDED{C['reset']} verification ledger: {exc}")
|
|
718
|
+
return 2
|
|
719
|
+
finally:
|
|
720
|
+
release()
|
|
721
|
+
|
|
722
|
+
print(f"\n{C['b']}{'PASS' if ok else 'FAIL'}{C['reset']} recorded as {rec['id']}")
|
|
723
|
+
if revs:
|
|
724
|
+
col = C["green"] if "APPROVED" in (revs[0][1] or "").upper() else C["yellow"]
|
|
725
|
+
print(f"{C['dim']}newest review:{C['reset']} {col}{revs[0][1]}{C['reset']} ({revs[0][0]})")
|
|
726
|
+
return 0 if ok else 1
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _verification_id(root):
|
|
730
|
+
"""A verification's id: V- and the millisecond it is minted in, above the newest one recorded (LEADS-GATE).
|
|
731
|
+
|
|
732
|
+
It was the second, and two runs in one second - two quick runs under one `polyctl lock`, on a machine
|
|
733
|
+
whose pressure is not read - or a run after the clock stepped back recorded two verifications
|
|
734
|
+
under one id, which a grant, a commit's Polyctl-Verification trailer and a report each name.
|
|
735
|
+
A.unique_ms keeps one process's ids apart, and the newest id in the ledger keeps every run above
|
|
736
|
+
the runs before it.
|
|
737
|
+
"""
|
|
738
|
+
# Three digits of the process's id after the millisecond: two verifications under one held lock read the same
|
|
739
|
+
# newest id in the same millisecond and recorded two runs under one id; each now goes above it by its own.
|
|
740
|
+
salt = os.getpid() % 1000
|
|
741
|
+
value = A.unique_ms() * 1000 + salt
|
|
742
|
+
try:
|
|
743
|
+
newest = str((A.latest_verification(root) or {}).get("id") or "")
|
|
744
|
+
except Exception:
|
|
745
|
+
newest = "" # an unreadable ledger refuses the record itself
|
|
746
|
+
found = A.re.fullmatch(r"V-([0-9]+)", newest)
|
|
747
|
+
above = (int(found.group(1)) // 1000 + 1) * 1000 + salt if found else value
|
|
748
|
+
return f"V-{max(value, above)}"
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def _verify_harness_config(root):
|
|
752
|
+
"""Name each change to what a harness reads from the tree that no person has seen, and what records it as seen;
|
|
753
|
+
the verification's record of them (HARNESS-CONFIG).
|
|
754
|
+
|
|
755
|
+
Not a failed gate: verification measures the candidate, and a change an implementer makes to its own instructions
|
|
756
|
+
can be the slice. What holds is elsewhere - no wake, refill, nudge, hunt or lane starts in the tree until a person
|
|
757
|
+
has seen it - and the record keeps what stood unseen when the gates ran.
|
|
758
|
+
"""
|
|
759
|
+
try:
|
|
760
|
+
unseen = A.unseen_harness_config(root)
|
|
761
|
+
except Exception as exc:
|
|
762
|
+
why = " ".join(str(exc).split())[:240]
|
|
763
|
+
print(f"\n {C['yellow']}harness configuration{C['reset']} cannot be read ({why}); nothing polyctl starts in this "
|
|
764
|
+
"tree runs until it can")
|
|
765
|
+
return {"unreadable": why}
|
|
766
|
+
if not unseen:
|
|
767
|
+
return {"unseen": []}
|
|
768
|
+
print(f"\n {C['yellow']}harness configuration nobody has seen{C['reset']} {len(unseen)} change(s) to what a "
|
|
769
|
+
"harness reads from this tree:")
|
|
770
|
+
for path, state, _ in unseen:
|
|
771
|
+
print(f" {A.shown_text(path)} ({A.HARNESS_CONFIG_STATES.get(state, state)})")
|
|
772
|
+
print(f" {C['dim']}not a failed gate; no wake, refill, nudge, hunt or lane starts here until a person reads them: "
|
|
773
|
+
f"polyctl harness seen --by <name>{C['reset']}")
|
|
774
|
+
return {"unseen": [{"path": path, "state": state, "sha256": sha} for path, state, sha in unseen],
|
|
775
|
+
"digest": A.harness_config_digest(unseen)}
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def _candidate_size_or_none(root, candidate):
|
|
779
|
+
try:
|
|
780
|
+
return A.candidate_size(root, candidate)
|
|
781
|
+
except (RuntimeError, KeyError, TypeError):
|
|
782
|
+
return None
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def _latest_verification_or_problem(root):
|
|
786
|
+
"""The newest verification, or why the chained ledger cannot be read (#61)."""
|
|
787
|
+
try:
|
|
788
|
+
return A.latest_verification(root), None
|
|
789
|
+
except Exception as exc:
|
|
790
|
+
return None, str(exc)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def _boundary_review_refusals(root, evidence):
|
|
794
|
+
"""Hold an approval to the running slice's pinned boundary both when granting and when committing.
|
|
795
|
+
|
|
796
|
+
The implementer can restore a board pointer after obtaining a grant without it. Matching names alone
|
|
797
|
+
also prove nothing when the review could not read the file or compare it with its pinned commit.
|
|
798
|
+
"""
|
|
799
|
+
pointer = A.boundary_pointer(A.running_slice(root))
|
|
800
|
+
if not pointer:
|
|
801
|
+
return []
|
|
802
|
+
if not pointer[1]:
|
|
803
|
+
return ["the running slice's boundary file names no commit; pin it with boundary: path@commit "
|
|
804
|
+
"and run `polyctl review` again"]
|
|
805
|
+
reviewed = evidence.get("boundary_file") if isinstance(evidence, dict) else None
|
|
806
|
+
if not isinstance(reviewed, dict) or (reviewed.get("file"), reviewed.get("commit")) != pointer:
|
|
807
|
+
return ["the review does not name the running slice's boundary file and commit; run `polyctl review` again"]
|
|
808
|
+
digest = reviewed.get("sha256")
|
|
809
|
+
if not (isinstance(digest, str) and A.re.fullmatch(r"sha256:[0-9a-f]{64}", digest)) \
|
|
810
|
+
or not isinstance(reviewed.get("changed"), bool):
|
|
811
|
+
return ["the review did not read the boundary file and compare it with its commit; run `polyctl review` again"]
|
|
812
|
+
return []
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _verification_isolation_problem(root, record):
|
|
816
|
+
"""Bind the all-gate isolation scope without changing the existing profile digest's meaning.
|
|
817
|
+
|
|
818
|
+
Another profile can narrow isolation without changing that digest. Older records with no scope remain
|
|
819
|
+
readable history, but cannot establish which inputs isolated their candidate: they need a fresh verify.
|
|
820
|
+
"""
|
|
821
|
+
if "isolation_inputs" not in record:
|
|
822
|
+
return "verification does not record isolation inputs — re-run `polyctl verify`"
|
|
823
|
+
if record["isolation_inputs"] != A.gate_inputs(root):
|
|
824
|
+
return "verification isolation inputs changed — re-run `polyctl verify`"
|
|
825
|
+
return None
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _unstaged_coordination_paths(root, candidate):
|
|
829
|
+
"""Staged coordination paths whose working-tree bytes differ from the index."""
|
|
830
|
+
if not candidate or not candidate.get("changed_paths"):
|
|
831
|
+
return []
|
|
832
|
+
raw = A._git_output(root, "diff", "--name-only", "-z", "--no-renames", "--", *candidate["changed_paths"])
|
|
833
|
+
return sorted({os.fsdecode(item) for item in raw.split(b"\0") if item}, key=os.fsencode)
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _commit_ok_coordination(cfg, args, candidate):
|
|
837
|
+
"""Grant or refuse a coordination-only commit: a person's act with `--by`, without product gates (COORDINATION-COMMIT)."""
|
|
838
|
+
root = cfg["root"]
|
|
839
|
+
now = A.tree_digest(root, cfg)
|
|
840
|
+
scope = A.candidate_scope(candidate)
|
|
841
|
+
by = (getattr(args, "by", None) or "").strip()
|
|
842
|
+
ask = bool(getattr(args, "ask", False))
|
|
843
|
+
wanted_digest = (getattr(args, "digest", None) or "").strip()
|
|
844
|
+
digest = candidate["digest"]
|
|
845
|
+
reasons = []
|
|
846
|
+
role = A.invoking_role()
|
|
847
|
+
if role:
|
|
848
|
+
reasons.append(f"a coordination commit is a person's act, not the {role}'s")
|
|
849
|
+
if not by or not by.isprintable() or len(by) > 80:
|
|
850
|
+
reasons.append(
|
|
851
|
+
"--by is required: staged candidate holds only coordination paths, "
|
|
852
|
+
"and a coordination commit is a person's act (polyctl commit-ok --by <name> --ask)"
|
|
853
|
+
)
|
|
854
|
+
elif by.lower() in _agent_names(cfg):
|
|
855
|
+
reasons.append(f"--by names an agent or a role ({by}); a coordination commit is a person's act")
|
|
856
|
+
if ask and wanted_digest:
|
|
857
|
+
reasons.append("pass either --ask or --digest, not both")
|
|
858
|
+
product_flags = [
|
|
859
|
+
flag
|
|
860
|
+
for flag, given in (
|
|
861
|
+
("--review", getattr(args, "review", None) is not None),
|
|
862
|
+
("--verify", bool(getattr(args, "verify", False))),
|
|
863
|
+
("-p/--profile", getattr(args, "profile", None) is not None),
|
|
864
|
+
)
|
|
865
|
+
if given
|
|
866
|
+
]
|
|
867
|
+
if product_flags:
|
|
868
|
+
reasons.append(
|
|
869
|
+
f"{', '.join(product_flags)} cannot be used on a coordination commit: "
|
|
870
|
+
"a coordination commit is granted on a person's act alone, with no review or verification to bind"
|
|
871
|
+
)
|
|
872
|
+
try:
|
|
873
|
+
unstaged = _unstaged_coordination_paths(root, candidate)
|
|
874
|
+
except Exception as exc:
|
|
875
|
+
reasons.append(f"cannot measure unstaged coordination paths: {exc}")
|
|
876
|
+
else:
|
|
877
|
+
if unstaged:
|
|
878
|
+
reasons.append(
|
|
879
|
+
f"unstaged changes on staged coordination path(s) ({', '.join(unstaged)}) — "
|
|
880
|
+
"stage or revert them so what is checked is what lands"
|
|
881
|
+
)
|
|
882
|
+
try:
|
|
883
|
+
unseen = A.unseen_harness_config(root)
|
|
884
|
+
except Exception as exc:
|
|
885
|
+
reasons.append(f"cannot measure harness configuration changes: {exc}")
|
|
886
|
+
else:
|
|
887
|
+
if unseen:
|
|
888
|
+
reasons.append(
|
|
889
|
+
f"unseen harness configuration ({A.harness_config_line(unseen)}) cannot ride a coordination grant — "
|
|
890
|
+
"run `polyctl harness seen --ask` first"
|
|
891
|
+
)
|
|
892
|
+
held = A.hold_state(root)
|
|
893
|
+
if held:
|
|
894
|
+
reasons.append(f"project is held by {held.get('by')}: {held.get('reason', '')}")
|
|
895
|
+
for message in A.urgent_messages(root, cfg):
|
|
896
|
+
reasons.append(f"urgent message unacknowledged: {message['id']} — {message['title']}")
|
|
897
|
+
|
|
898
|
+
def _refuse(extra=()):
|
|
899
|
+
all_reasons = list(reasons) + list(extra)
|
|
900
|
+
try:
|
|
901
|
+
A.record_authority(root, False, all_reasons, now, None, candidate=candidate, scope=scope)
|
|
902
|
+
except Exception as exc:
|
|
903
|
+
all_reasons.append(f"authority ledger cannot record refusal: {exc}")
|
|
904
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}")
|
|
905
|
+
for reason in all_reasons:
|
|
906
|
+
print(f" {C['red']}·{C['reset']} {A.shown_text(reason)}")
|
|
907
|
+
return 1
|
|
908
|
+
|
|
909
|
+
if reasons:
|
|
910
|
+
return _refuse()
|
|
911
|
+
|
|
912
|
+
digest_cmd = f" polyctl commit-ok --by {A.copyable_word(by)} --digest {digest}"
|
|
913
|
+
if wanted_digest:
|
|
914
|
+
if wanted_digest != digest:
|
|
915
|
+
return _refuse([
|
|
916
|
+
f"--digest {wanted_digest} does not match the staged candidate ({digest}); "
|
|
917
|
+
f"read the staged paths again:\n{digest_cmd}"
|
|
918
|
+
])
|
|
919
|
+
confirmed_via = "digest"
|
|
920
|
+
elif ask:
|
|
921
|
+
print(f"{C['b']}Coordination candidate{C['reset']} ({candidate['changed_count']} path(s), "
|
|
922
|
+
f"index tree {candidate['index_tree']}):")
|
|
923
|
+
for path in candidate["changed_paths"]:
|
|
924
|
+
print(f" · {A.shown_text(path)}")
|
|
925
|
+
print(f" {C['dim']}digest {digest}{C['reset']}")
|
|
926
|
+
answer = _confirm(
|
|
927
|
+
f"Grant this coordination commit as {A.shown_text(by)} ({digest[:12]})? [y/N]: "
|
|
928
|
+
)
|
|
929
|
+
if answer is None:
|
|
930
|
+
return _refuse([
|
|
931
|
+
f"--ask needs an interactive terminal; run this in one, or pass the digest:\n{digest_cmd}"
|
|
932
|
+
])
|
|
933
|
+
if not answer:
|
|
934
|
+
return _refuse(["not confirmed at the terminal"])
|
|
935
|
+
after_reasons = []
|
|
936
|
+
try:
|
|
937
|
+
current = A.index_candidate(root)
|
|
938
|
+
unstaged_after = _unstaged_coordination_paths(root, current)
|
|
939
|
+
except Exception as exc:
|
|
940
|
+
after_reasons.append(f"cannot measure unstaged coordination paths: {exc}")
|
|
941
|
+
else:
|
|
942
|
+
if current["digest"] != digest or unstaged_after:
|
|
943
|
+
after_reasons.append(
|
|
944
|
+
"staged coordination candidate changed while waiting for confirmation; read it again"
|
|
945
|
+
)
|
|
946
|
+
try:
|
|
947
|
+
unseen_after = A.unseen_harness_config(root)
|
|
948
|
+
except Exception as exc:
|
|
949
|
+
after_reasons.append(f"cannot measure harness configuration changes: {exc}")
|
|
950
|
+
else:
|
|
951
|
+
if unseen_after:
|
|
952
|
+
after_reasons.append(
|
|
953
|
+
"harness configuration changed while waiting for confirmation — "
|
|
954
|
+
"run `polyctl harness seen --ask` first"
|
|
955
|
+
)
|
|
956
|
+
held = A.hold_state(root)
|
|
957
|
+
if held:
|
|
958
|
+
after_reasons.append(f"project is held by {held.get('by')}: {held.get('reason', '')}")
|
|
959
|
+
for message in A.urgent_messages(root, cfg):
|
|
960
|
+
after_reasons.append(f"urgent message unacknowledged: {message['id']} — {message['title']}")
|
|
961
|
+
if after_reasons:
|
|
962
|
+
return _refuse(after_reasons)
|
|
963
|
+
confirmed_via = "ask"
|
|
964
|
+
else:
|
|
965
|
+
print(f"{C['b']}Coordination candidate{C['reset']} ({candidate['changed_count']} path(s), "
|
|
966
|
+
f"index tree {candidate['index_tree']}):")
|
|
967
|
+
for path in candidate["changed_paths"]:
|
|
968
|
+
print(f" · {A.shown_text(path)}")
|
|
969
|
+
print(f" {C['dim']}digest {digest}{C['reset']}")
|
|
970
|
+
return _refuse([
|
|
971
|
+
f"confirm on an interactive terminal with --ask, or pass the digest of this exact candidate:\n{digest_cmd}"
|
|
972
|
+
])
|
|
973
|
+
|
|
974
|
+
user, interactive = A._login_and_terminal()
|
|
975
|
+
coordination = {
|
|
976
|
+
"by": by,
|
|
977
|
+
"user": user,
|
|
978
|
+
"interactive": interactive or confirmed_via == "ask",
|
|
979
|
+
"confirmed": confirmed_via,
|
|
980
|
+
"digest": digest,
|
|
981
|
+
"paths": list(candidate["changed_paths"]),
|
|
982
|
+
}
|
|
983
|
+
token = f"C-{A.unique_ns()}"
|
|
984
|
+
try:
|
|
985
|
+
A.record_authority(
|
|
986
|
+
root, True, [], now, None, token,
|
|
987
|
+
candidate=candidate, scope=scope, coordination=coordination,
|
|
988
|
+
)
|
|
989
|
+
except Exception as exc:
|
|
990
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}\n {C['red']}·{C['reset']} "
|
|
991
|
+
f"authority ledger cannot record grant: {exc}")
|
|
992
|
+
return 1
|
|
993
|
+
print(f"{C['green']}{C['b']}GRANTED{C['reset']} {token}")
|
|
994
|
+
print(f" {C['dim']}coordination by {_person_line(coordination)} · "
|
|
995
|
+
f"{candidate['changed_count']} path(s){C['reset']}")
|
|
996
|
+
print(f" {C['dim']}index tree {candidate['index_tree']}{C['reset']}")
|
|
997
|
+
return 0
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def cmd_commit_ok(cfg, args):
|
|
1001
|
+
"""Grant authority only for the exact, isolated tree in Git's index."""
|
|
1002
|
+
root = cfg["root"]
|
|
1003
|
+
try:
|
|
1004
|
+
candidate = A.index_candidate(root)
|
|
1005
|
+
issues = A.candidate_worktree_issues(root, cfg, candidate)
|
|
1006
|
+
except RuntimeError as exc:
|
|
1007
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}\n {C['red']}·{C['reset']} {exc}")
|
|
1008
|
+
return 1
|
|
1009
|
+
if A.coordination_candidate(candidate, cfg):
|
|
1010
|
+
return _commit_ok_coordination(cfg, args, candidate)
|
|
1011
|
+
if (getattr(args, "by", None) is not None
|
|
1012
|
+
or getattr(args, "ask", False)
|
|
1013
|
+
or getattr(args, "digest", None) is not None):
|
|
1014
|
+
reasons = A.candidate_issue_messages(issues)
|
|
1015
|
+
if not candidate["changed_paths"]:
|
|
1016
|
+
reasons.insert(0, "no staged candidate — stage exactly what you intend to commit")
|
|
1017
|
+
elif not issues.get("staged_coordination"):
|
|
1018
|
+
reasons.append("--by is only for a coordination commit: staged candidate holds product paths")
|
|
1019
|
+
try:
|
|
1020
|
+
A.record_authority(
|
|
1021
|
+
root, False, reasons, A.tree_digest(root, cfg), None,
|
|
1022
|
+
candidate=candidate, scope=A.candidate_scope(candidate),
|
|
1023
|
+
)
|
|
1024
|
+
except Exception as exc:
|
|
1025
|
+
reasons.append(f"authority ledger cannot record refusal: {exc}")
|
|
1026
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}")
|
|
1027
|
+
for reason in reasons:
|
|
1028
|
+
print(f" {C['red']}·{C['reset']} {A.shown_text(reason)}")
|
|
1029
|
+
return 1
|
|
1030
|
+
strict = M.is_strict(cfg)
|
|
1031
|
+
matrix_resolution = None
|
|
1032
|
+
if strict:
|
|
1033
|
+
try:
|
|
1034
|
+
# A waiver may bypass a review, but never malformed declarations or
|
|
1035
|
+
# a runtime implementer that disagrees with its bound identity.
|
|
1036
|
+
matrix_resolution = _resolve_matrix(cfg, require_independent=False)
|
|
1037
|
+
except M.MatrixError as exc:
|
|
1038
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}")
|
|
1039
|
+
for problem in exc.problems:
|
|
1040
|
+
print(f" {C['red']}·{C['reset']} capability matrix: {problem}")
|
|
1041
|
+
return 1
|
|
1042
|
+
wanted = getattr(args, "review", None)
|
|
1043
|
+
if wanted:
|
|
1044
|
+
# A submitted review grants only the tree it pinned (S1).
|
|
1045
|
+
state = _review_state(root, wanted)
|
|
1046
|
+
refusal = (f"no submitted review {wanted}" if not state
|
|
1047
|
+
else f"{wanted} is {state.get('state')}, not finished" if state.get("state") != "finished"
|
|
1048
|
+
else f"the staged tree is not the tree {wanted} reviewed: staged {candidate['index_tree']}, "
|
|
1049
|
+
f"reviewed {state.get('tree')}" if state.get("tree") != candidate["index_tree"]
|
|
1050
|
+
else None)
|
|
1051
|
+
if refusal:
|
|
1052
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}\n {C['red']}·{C['reset']} {refusal}")
|
|
1053
|
+
return 1
|
|
1054
|
+
now = A.tree_digest(root, cfg) # legacy/audit surface, not commit identity
|
|
1055
|
+
ver, ver_problem = _latest_verification_or_problem(root)
|
|
1056
|
+
running = [it["id"] for it in A.board(root)["running"]]
|
|
1057
|
+
|
|
1058
|
+
def verification_matches(record):
|
|
1059
|
+
measured = (record or {}).get("candidate") or {}
|
|
1060
|
+
if not (record and record.get("candidate_ready")
|
|
1061
|
+
and measured.get("digest") == candidate["digest"]
|
|
1062
|
+
and A.gate_definitions_digest(root, record.get("profile")) == record.get("gates_digest")
|
|
1063
|
+
and not _verification_isolation_problem(root, record)):
|
|
1064
|
+
return False
|
|
1065
|
+
if record.get("passed"):
|
|
1066
|
+
return True
|
|
1067
|
+
waivable, _ = A.verification_waivable_gates(root, record)
|
|
1068
|
+
if not waivable:
|
|
1069
|
+
return False
|
|
1070
|
+
try:
|
|
1071
|
+
gwaiver, _ = A.gates_waiver_for(root, running, candidate["digest"], failed_gates=waivable)
|
|
1072
|
+
except Exception:
|
|
1073
|
+
return False
|
|
1074
|
+
return gwaiver is not None
|
|
1075
|
+
|
|
1076
|
+
if getattr(args, "verify", False) and not verification_matches(ver):
|
|
1077
|
+
from types import SimpleNamespace
|
|
1078
|
+
print(f"{C['dim']}verification stale or missing — running quick gates first{C['reset']}")
|
|
1079
|
+
cmd_verify(cfg, SimpleNamespace(
|
|
1080
|
+
profile=getattr(args, "profile", None) or "quick", wait=900
|
|
1081
|
+
))
|
|
1082
|
+
candidate = A.index_candidate(root)
|
|
1083
|
+
issues = A.candidate_worktree_issues(root, cfg, candidate)
|
|
1084
|
+
now = A.tree_digest(root, cfg)
|
|
1085
|
+
ver, ver_problem = _latest_verification_or_problem(root)
|
|
1086
|
+
|
|
1087
|
+
reasons = []
|
|
1088
|
+
gates_waiver = None
|
|
1089
|
+
waivable_failed = None
|
|
1090
|
+
if not candidate["changed_paths"]:
|
|
1091
|
+
reasons.append("no staged candidate — stage exactly what you intend to commit")
|
|
1092
|
+
reasons.extend(A.candidate_issue_messages(issues))
|
|
1093
|
+
if issues.get("worktree_noise"):
|
|
1094
|
+
# Listed, never fatal: no declared gate reads these paths (#16).
|
|
1095
|
+
print(f"{C['dim']}worktree noise, outside the candidate and every gate's inputs: "
|
|
1096
|
+
f"{', '.join(issues['worktree_noise'])}{C['reset']}")
|
|
1097
|
+
if ver_problem:
|
|
1098
|
+
reasons.append(f"verification ledger is unreadable: {ver_problem}")
|
|
1099
|
+
elif not ver:
|
|
1100
|
+
reasons.append("no verification record — run `polyctl verify`")
|
|
1101
|
+
else:
|
|
1102
|
+
ver_reasons = []
|
|
1103
|
+
measured = ver.get("candidate")
|
|
1104
|
+
if not measured:
|
|
1105
|
+
ver_reasons.append(f"{ver['id']} predates index-candidate binding — re-run `polyctl verify`")
|
|
1106
|
+
elif measured.get("digest") != candidate["digest"]:
|
|
1107
|
+
ver_reasons.append(
|
|
1108
|
+
f"index changed since {ver['id']} — expected {measured.get('index_tree')}, "
|
|
1109
|
+
f"got {candidate['index_tree']}"
|
|
1110
|
+
)
|
|
1111
|
+
elif not ver.get("candidate_ready"):
|
|
1112
|
+
detail = "; ".join(ver.get("candidate_issues") or [])
|
|
1113
|
+
ver_reasons.append(f"{ver['id']} did not verify an isolated staged candidate"
|
|
1114
|
+
+ (f": {detail}" if detail else ""))
|
|
1115
|
+
if A.gate_definitions_digest(root, ver.get("profile")) != ver.get("gates_digest"):
|
|
1116
|
+
ver_reasons.append(f"gate definitions changed since {ver['id']} — re-run `polyctl verify`")
|
|
1117
|
+
isolation_problem = _verification_isolation_problem(root, ver)
|
|
1118
|
+
if isolation_problem:
|
|
1119
|
+
ver_reasons.append(isolation_problem)
|
|
1120
|
+
if not ver.get("passed"):
|
|
1121
|
+
failed = [g["name"] for g in ver.get("gates", []) if not g.get("passed")]
|
|
1122
|
+
waivable_failed, unwaivable_why = A.verification_waivable_gates(root, ver)
|
|
1123
|
+
gates_waiver_notes = []
|
|
1124
|
+
if waivable_failed and not ver_reasons:
|
|
1125
|
+
try:
|
|
1126
|
+
gates_waiver, gates_waiver_notes = A.gates_waiver_for(
|
|
1127
|
+
root, running, candidate["digest"], failed_gates=waivable_failed
|
|
1128
|
+
)
|
|
1129
|
+
except Exception as exc:
|
|
1130
|
+
gates_waiver, gates_waiver_notes = None, [f"waiver ledger is unreadable: {exc}"]
|
|
1131
|
+
elif not ver_reasons:
|
|
1132
|
+
try:
|
|
1133
|
+
_, gates_waiver_notes = A.gates_waiver_for(root, running, candidate["digest"])
|
|
1134
|
+
except Exception as exc:
|
|
1135
|
+
gates_waiver_notes = [f"waiver ledger is unreadable: {exc}"]
|
|
1136
|
+
if gates_waiver:
|
|
1137
|
+
print(f"{C['yellow']}gates waived{C['reset']} ({', '.join(waivable_failed)}) by "
|
|
1138
|
+
f"{gates_waiver['by']} ({gates_waiver['id']}): "
|
|
1139
|
+
f"{gates_waiver['why'][:80]} — reconcile with `polyctl catchup`")
|
|
1140
|
+
else:
|
|
1141
|
+
reasons.append(f"last verification failed: {', '.join(failed) or ver['id']}")
|
|
1142
|
+
if unwaivable_why:
|
|
1143
|
+
try:
|
|
1144
|
+
has_open_gates_waiver = bool(A.open_waivers(root, gate="gates"))
|
|
1145
|
+
except Exception:
|
|
1146
|
+
has_open_gates_waiver = False
|
|
1147
|
+
if has_open_gates_waiver:
|
|
1148
|
+
reasons.append(unwaivable_why)
|
|
1149
|
+
reasons.extend(gates_waiver_notes)
|
|
1150
|
+
reasons.extend(ver_reasons)
|
|
1151
|
+
|
|
1152
|
+
try:
|
|
1153
|
+
drift = A.plan_drift(root)
|
|
1154
|
+
except Exception as exc:
|
|
1155
|
+
drift = []
|
|
1156
|
+
reasons.append(f"plan baselines cannot be read: {exc}")
|
|
1157
|
+
# A slice the board declares move-only moves text and changes nothing (#44).
|
|
1158
|
+
move_only = [it["id"] for it in A.board(root)["running"] if "move-only" in (it.get("notes") or {})]
|
|
1159
|
+
move_proof, unproven = None, []
|
|
1160
|
+
if move_only:
|
|
1161
|
+
try:
|
|
1162
|
+
split = A.split_moves(root)
|
|
1163
|
+
except RuntimeError as exc:
|
|
1164
|
+
split = {"moved": [], "problems": [f"the candidate cannot be read: {exc}"]}
|
|
1165
|
+
reasons.extend(f"{move_only[0]} is move-only: {problem}" for problem in split["problems"])
|
|
1166
|
+
# The proof reads Python definitions. A grant keeps it only when it covers every staged
|
|
1167
|
+
# path, and a waived review of what lands then closes on it, run again (#44).
|
|
1168
|
+
unproven = [path for path in candidate["changed_paths"] if not path.endswith(".py")]
|
|
1169
|
+
if not split["problems"] and not unproven:
|
|
1170
|
+
move_proof = {"slice": move_only[0], "moved": len(split["moved"])}
|
|
1171
|
+
if drift:
|
|
1172
|
+
reasons.append(f"plan edited after admission: {', '.join(drift)}")
|
|
1173
|
+
|
|
1174
|
+
from . import features as F
|
|
1175
|
+
try:
|
|
1176
|
+
waiver, waiver_notes = A.review_waiver_for(root, running, candidate["digest"])
|
|
1177
|
+
except Exception as exc:
|
|
1178
|
+
waiver, waiver_notes = None, [f"waiver ledger is unreadable: {exc}"]
|
|
1179
|
+
review_required = F.enabled(cfg, "review")
|
|
1180
|
+
if "review" in F.unrecorded(cfg):
|
|
1181
|
+
# A config the implementer can write turned review off; it is off only on a person's record (FEATURE-RECORDED).
|
|
1182
|
+
reasons_note = ("review is off in .polyctl/config.json with no person's record, so it stays required: "
|
|
1183
|
+
"polyctl features off review --by <name>")
|
|
1184
|
+
print(f"{C['yellow']}{reasons_note}{C['reset']}")
|
|
1185
|
+
try:
|
|
1186
|
+
decision = A.candidate_review_decision(root, cfg["reviews"], candidate["digest"])
|
|
1187
|
+
except Exception as exc:
|
|
1188
|
+
decision = {"match": None, "problem": f"review ledger is unreadable: {exc}"}
|
|
1189
|
+
match = decision["match"]
|
|
1190
|
+
review_name, rbody, evidence, rwho = None, "", None, None
|
|
1191
|
+
strict_reviewer_identity = None
|
|
1192
|
+
review_tier = None
|
|
1193
|
+
scope = A.candidate_scope(candidate)
|
|
1194
|
+
|
|
1195
|
+
def bound_review():
|
|
1196
|
+
"""What the review bound to this candidate grants: (its fields, why it does not hold)."""
|
|
1197
|
+
name, _, body, ev = match
|
|
1198
|
+
fields = {"review_name": name, "rbody": body, "evidence": ev, "scope": None, "rwho": None,
|
|
1199
|
+
"strict_reviewer_identity": None, "review_tier": None}
|
|
1200
|
+
why = []
|
|
1201
|
+
reviewed_scope, integrity_reasons = A.candidate_review_integrity(root, candidate, ev)
|
|
1202
|
+
why.extend(f"{name}: {reason}" for reason in integrity_reasons)
|
|
1203
|
+
why.extend(f"{name}: {reason}" for reason in _boundary_review_refusals(root, ev))
|
|
1204
|
+
# A boundary that lists criteria lands only when the review found every one met (CRITERIA-VERDICTS).
|
|
1205
|
+
why.extend(f"{name}: {reason}" for reason in A.criteria_refusals(ev))
|
|
1206
|
+
fields["scope"] = reviewed_scope
|
|
1207
|
+
if strict:
|
|
1208
|
+
why.extend(f"{name}: {reason}" for reason in M.review_evidence_problems(matrix_resolution, ev))
|
|
1209
|
+
identity = ev.get("reviewer_identity") if isinstance(ev, dict) else None
|
|
1210
|
+
fields["strict_reviewer_identity"] = identity
|
|
1211
|
+
fields["rwho"] = (identity or {}).get("binding") if isinstance(identity, dict) else None
|
|
1212
|
+
fields["review_tier"] = next((route.get("tier") for route in matrix_resolution["reviewers"]
|
|
1213
|
+
if route["eligible"] and route["identity"] == identity), None)
|
|
1214
|
+
else:
|
|
1215
|
+
# Who reviewed is read from the evidence polyctl wrote, never from the
|
|
1216
|
+
# artefact's text, where the implementer's boundary appears too (#60).
|
|
1217
|
+
recorded = ev.get("reviewer") if isinstance(ev, dict) else None
|
|
1218
|
+
who = recorded.get("id") if isinstance(recorded, dict) else None
|
|
1219
|
+
if not isinstance(who, str) or not who:
|
|
1220
|
+
who = None
|
|
1221
|
+
why.append(f"{name} records no reviewer in its evidence — run `polyctl review` again")
|
|
1222
|
+
else:
|
|
1223
|
+
# The tier it was recorded in must still hold: a withdrawn opt-in grants nothing (REVIEW-TIERS).
|
|
1224
|
+
fields["review_tier"], refused = _recorded_review_tier(cfg, ev, who)
|
|
1225
|
+
if refused == "it runs as the implementer":
|
|
1226
|
+
why.append(f"the review was written by the implementer ({who})")
|
|
1227
|
+
elif refused:
|
|
1228
|
+
why.append(f"the review's reviewer {who} may not review this implementer: {refused}")
|
|
1229
|
+
fields["rwho"] = who
|
|
1230
|
+
return fields, why
|
|
1231
|
+
|
|
1232
|
+
no_eligible = strict and not any(route["eligible"] for route in matrix_resolution["reviewers"])
|
|
1233
|
+
bound, bound_why = bound_review() if review_required and match and not no_eligible else (None, [])
|
|
1234
|
+
if not review_required:
|
|
1235
|
+
pass
|
|
1236
|
+
elif bound is not None and (not bound_why or not waiver):
|
|
1237
|
+
# A candidate a review is bound to stands on that review, and an open waiver is left for what needs
|
|
1238
|
+
# one: the waiver was asked first, and a reviewed candidate was granted as waived, the review
|
|
1239
|
+
# unrecorded and the waiver spent on it (WAIVER-BOUND-2).
|
|
1240
|
+
reasons.extend(bound_why)
|
|
1241
|
+
review_name, rbody, evidence = bound["review_name"], bound["rbody"], bound["evidence"]
|
|
1242
|
+
rwho, review_tier = bound["rwho"], bound["review_tier"]
|
|
1243
|
+
strict_reviewer_identity = bound["strict_reviewer_identity"]
|
|
1244
|
+
if bound["scope"] is not None:
|
|
1245
|
+
scope = bound["scope"]
|
|
1246
|
+
waiver = None
|
|
1247
|
+
elif waiver:
|
|
1248
|
+
if bound_why:
|
|
1249
|
+
print(f"{C['dim']}the review bound to this candidate does not hold ({bound_why[0]}); "
|
|
1250
|
+
f"the waiver stands in{C['reset']}")
|
|
1251
|
+
print(f"{C['yellow']}review waived{C['reset']} by {waiver['by']} ({waiver['id']}): "
|
|
1252
|
+
f"{waiver['why'][:80]} — reconcile with `polyctl catchup`")
|
|
1253
|
+
elif no_eligible:
|
|
1254
|
+
reasons.append("capability matrix has no independently eligible reviewer")
|
|
1255
|
+
else:
|
|
1256
|
+
reasons.append(decision["problem"]
|
|
1257
|
+
or "no APPROVED prospective review is bound to this staged candidate")
|
|
1258
|
+
reasons.extend(waiver_notes)
|
|
1259
|
+
|
|
1260
|
+
# A proof from another running slice cannot retire this slice's waiver (TRIAGE-4-REST).
|
|
1261
|
+
proof_note = None
|
|
1262
|
+
if move_proof:
|
|
1263
|
+
authorising_slice = (waiver.get("slice") if review_required and waiver
|
|
1264
|
+
else evidence.get("slice") if evidence else None)
|
|
1265
|
+
if len(move_only) != 1:
|
|
1266
|
+
proof_note = "more than one move-only slice is running; review the range or name it with --move-only --by"
|
|
1267
|
+
elif authorising_slice != move_proof["slice"]:
|
|
1268
|
+
proof_note = ("the authorising waiver or review does not name the running move-only slice; "
|
|
1269
|
+
"review the range or name it with --move-only --by")
|
|
1270
|
+
if proof_note:
|
|
1271
|
+
move_proof = None
|
|
1272
|
+
|
|
1273
|
+
held = A.hold_state(root)
|
|
1274
|
+
if held:
|
|
1275
|
+
reasons.append(f"project is held by {held.get('by')}: {held.get('reason','')}")
|
|
1276
|
+
for message in A.urgent_messages(root, cfg):
|
|
1277
|
+
reasons.append(
|
|
1278
|
+
f"urgent message unacknowledged: {message['id']} — {message['title']}"
|
|
1279
|
+
)
|
|
1280
|
+
|
|
1281
|
+
strict_authority = M.authority_fields(
|
|
1282
|
+
matrix_resolution, strict_reviewer_identity
|
|
1283
|
+
) if strict else {}
|
|
1284
|
+
if reasons:
|
|
1285
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}")
|
|
1286
|
+
for reason in reasons:
|
|
1287
|
+
print(f" {C['red']}·{C['reset']} {A.shown_text(reason)}")
|
|
1288
|
+
try:
|
|
1289
|
+
A.record_authority(
|
|
1290
|
+
root, False, reasons, now, (ver or {}).get("id"),
|
|
1291
|
+
candidate=candidate, scope=scope, **strict_authority,
|
|
1292
|
+
)
|
|
1293
|
+
except Exception as exc:
|
|
1294
|
+
# A broken predecessor chain is itself a refusal condition. Never
|
|
1295
|
+
# traceback into ambiguity or imply that the refusal was recorded.
|
|
1296
|
+
print(f" {C['dim']}authority refusal could not be recorded: {exc}{C['reset']}")
|
|
1297
|
+
return 1
|
|
1298
|
+
|
|
1299
|
+
token = f"C-{A.unique_ns()}"
|
|
1300
|
+
waived = review_required and waiver
|
|
1301
|
+
primary_waiver = waiver["id"] if waived else (gates_waiver["id"] if gates_waiver else None)
|
|
1302
|
+
extra_gates_waiver = gates_waiver["id"] if (waived and gates_waiver) else None
|
|
1303
|
+
try:
|
|
1304
|
+
# A waived candidate is reviewed after it lands, held to the family that wrote it (#65).
|
|
1305
|
+
author = A.grant_author(cfg, matrix_resolution["implementer_identity"] if strict else None) \
|
|
1306
|
+
if waived else None
|
|
1307
|
+
A.record_authority(
|
|
1308
|
+
root, True, [], now, ver["id"], token,
|
|
1309
|
+
review=review_name, reviewer=rwho, candidate=candidate, scope=scope,
|
|
1310
|
+
waiver=primary_waiver, gates_waiver=extra_gates_waiver,
|
|
1311
|
+
waived_gates=waivable_failed if gates_waiver else None,
|
|
1312
|
+
author=author, move_only=move_proof,
|
|
1313
|
+
**strict_authority,
|
|
1314
|
+
)
|
|
1315
|
+
except Exception as exc:
|
|
1316
|
+
# Corruption and lock failures are as decisive as an I/O failure: no
|
|
1317
|
+
# durable chained row means no authority exists.
|
|
1318
|
+
print(f"{C['red']}{C['b']}REFUSED{C['reset']}")
|
|
1319
|
+
print(f" {C['red']}·{C['reset']} could not persist authority grant: {exc}")
|
|
1320
|
+
if "has no 'previous' field" in str(exc):
|
|
1321
|
+
print(" legacy ledger — archive .polyctl/ledger/authority.jsonl and re-run polyctl commit-ok (docs/ledger.md)")
|
|
1322
|
+
return 1
|
|
1323
|
+
|
|
1324
|
+
ver_summary = (f"{ver['id']} (waived {', '.join(waivable_failed)}: {gates_waiver['id']})"
|
|
1325
|
+
if gates_waiver else ver["id"])
|
|
1326
|
+
rev_summary = review_name or (f"waived ({waiver['id']})" if waived else "waived/off")
|
|
1327
|
+
print(f"{C['green']}{C['b']}GRANTED{C['reset']} {token}")
|
|
1328
|
+
print(f" {C['dim']}verified{C['reset']} {ver_summary} · "
|
|
1329
|
+
f"{C['dim']}review{C['reset']} {rev_summary}")
|
|
1330
|
+
from . import tiers as T
|
|
1331
|
+
if review_name and T.weaker(review_tier):
|
|
1332
|
+
person = f" ({_person_line(evidence.get('person'))})" if review_tier == T.PERSON else ""
|
|
1333
|
+
print(f" {C['yellow']}tier{C['reset']} {T.label(review_tier)}{person}")
|
|
1334
|
+
elif review_name and review_tier is None and not strict:
|
|
1335
|
+
print(f" {C['yellow']}tier{C['reset']} not established: no implementer is configured to compare the "
|
|
1336
|
+
"reviewer with — polyctl doctor")
|
|
1337
|
+
print(f" {C['dim']}index tree{C['reset']} {candidate['index_tree']}")
|
|
1338
|
+
if move_proof:
|
|
1339
|
+
print(f" {C['dim']}move proof{C['reset']} {move_proof['moved']} definition(s) moved byte for byte, "
|
|
1340
|
+
"recorded with the grant")
|
|
1341
|
+
elif proof_note:
|
|
1342
|
+
print(f" {C['dim']}no move proof recorded: {proof_note}{C['reset']}")
|
|
1343
|
+
elif unproven:
|
|
1344
|
+
print(f" {C['dim']}no move proof recorded: it reads Python definitions, and the candidate also "
|
|
1345
|
+
f"changes {', '.join(unproven)}{C['reset']}")
|
|
1346
|
+
print(f"\n {C['dim']}This grant names only the staged index above; push is never covered.{C['reset']}")
|
|
1347
|
+
return 0
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
PROJECT_MARKER = ".polyctl-project"
|
|
1351
|
+
PROJECT_MARKER_BYTES = b"polyctl-project-v1\n"
|
|
1352
|
+
# One command adopts polyctl state no tracked marker covers (INIT-ADOPTION). Every message about such a
|
|
1353
|
+
# project spelled out a recipe instead - write the marker, stage it, land it - with `polyctl hooks install`
|
|
1354
|
+
# still to follow, and that command refused the project until the marker was staged.
|
|
1355
|
+
PROJECT_ADOPT_COMMAND = "polyctl init --adopt"
|
|
1356
|
+
PROJECT_ADOPT_HINT = (
|
|
1357
|
+
f"{PROJECT_ADOPT_COMMAND} stages {PROJECT_MARKER} and installs the current hooks; "
|
|
1358
|
+
"then land it through polyctl commit-ok"
|
|
1359
|
+
)
|
|
1360
|
+
PROJECT_INIT_COMMAND = f"polyctl init --profile {A.default_profile()}"
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _project_refusal(problem):
|
|
1364
|
+
return (
|
|
1365
|
+
f"{PROJECT_MARKER} marks polyctl enrollment, but polyctl project state is "
|
|
1366
|
+
f"missing/unreadable: {problem}; run: {PROJECT_INIT_COMMAND}"
|
|
1367
|
+
)
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
# The pre-commit hook names the top of the working tree Git ran it in, so polyctl can hold its authority to that one
|
|
1371
|
+
# repository and refuse a planted `.git` that would move it elsewhere (NESTED-GIT).
|
|
1372
|
+
COMMIT_TOP_ENV = "POLYCTL_COMMIT_TOP"
|
|
1373
|
+
|
|
1374
|
+
|
|
1375
|
+
def _repository_identity(where):
|
|
1376
|
+
"""(the working-tree top, the shared git directory) the repository `git -C <where>` resolves to, each a real path.
|
|
1377
|
+
|
|
1378
|
+
Both come from Git run through `_hook_git`, which drops an inherited GIT_DIR and the rest of the repository
|
|
1379
|
+
environment, so what an agent exported cannot move them; only a `.git` in the tree can, which is what the caller
|
|
1380
|
+
tests for (NESTED-GIT).
|
|
1381
|
+
"""
|
|
1382
|
+
top = _hook_real(where, _hook_output_path(
|
|
1383
|
+
_hook_git(where, "rev-parse", "--show-toplevel", bound=False), "--show-toplevel"))
|
|
1384
|
+
git_dir = _hook_real(where, _hook_output_path(
|
|
1385
|
+
_hook_git(where, "rev-parse", "--git-common-dir", bound=False), "--git-common-dir"))
|
|
1386
|
+
return top, git_dir
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def _project_repository_top(root):
|
|
1390
|
+
"""Use the hook's top; otherwise find enrollment above the original project path (NESTED-GIT).
|
|
1391
|
+
|
|
1392
|
+
The hook overwrites POLYCTL_COMMIT_TOP with Git's physical cwd. No repository discovered through the
|
|
1393
|
+
project, before or after resolving symlinks, may override that authority. Outside a hook, keep
|
|
1394
|
+
the lexical path first: resolving it before searching loses an enrolled ancestor when a project
|
|
1395
|
+
directory is replaced by a symlink. Only without that evidence try the resolved path.
|
|
1396
|
+
"""
|
|
1397
|
+
hint = os.environ.get(COMMIT_TOP_ENV)
|
|
1398
|
+
if hint is not None:
|
|
1399
|
+
if not hint:
|
|
1400
|
+
raise _HookResolutionError("POLYCTL_COMMIT_TOP is empty")
|
|
1401
|
+
return os.path.realpath(os.path.abspath(os.path.expanduser(hint)))
|
|
1402
|
+
root = os.path.abspath(root)
|
|
1403
|
+
return (_project_ancestor_repository_top(root)
|
|
1404
|
+
or _project_ancestor_repository_top(os.path.realpath(root)))
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
def _project_ancestor_repository_top(root):
|
|
1408
|
+
"""Find the outermost ancestor with evidence for this path without resolving it first (NESTED-GIT).
|
|
1409
|
+
|
|
1410
|
+
A planted intermediate repository can track the marker too, so every ancestor must be searched. HEAD and
|
|
1411
|
+
index alone forget enrollment on orphan and pre-marker branches: another ref's history or the record in
|
|
1412
|
+
the common git directory still binds them. An unreadable record is evidence too, as in enrollment itself.
|
|
1413
|
+
The old record names a repository, not all its project paths; without history to distinguish them it must
|
|
1414
|
+
conservatively claim descendants.
|
|
1415
|
+
"""
|
|
1416
|
+
anchor = None
|
|
1417
|
+
parent = os.path.dirname(root)
|
|
1418
|
+
while True:
|
|
1419
|
+
if os.path.lexists(os.path.join(parent, ".git")):
|
|
1420
|
+
marker = os.path.relpath(os.path.join(root, PROJECT_MARKER), parent).replace(os.sep, "/")
|
|
1421
|
+
indexed = _hook_git(parent, "ls-files", "--stage", "-z", "--", marker, bound=False)
|
|
1422
|
+
headed = _hook_git(parent, "ls-tree", "-z", "HEAD", "--", marker, bound=False)
|
|
1423
|
+
if (indexed.returncode == 0 and indexed.stdout) or (headed.returncode == 0 and headed.stdout):
|
|
1424
|
+
anchor = parent
|
|
1425
|
+
else:
|
|
1426
|
+
history = _hook_git(parent, "log", "--all", "-1", "--format=%H", "--", marker, bound=False)
|
|
1427
|
+
common = _hook_git(parent, "rev-parse", "--git-common-dir", bound=False)
|
|
1428
|
+
recorded = common.returncode == 0 and os.path.lexists(os.path.join(
|
|
1429
|
+
_hook_real(parent, _hook_output_path(common, "--git-common-dir")), A.ENROLLMENT_RECORD))
|
|
1430
|
+
if (history.returncode == 0 and history.stdout.strip()) or recorded:
|
|
1431
|
+
anchor = parent
|
|
1432
|
+
if parent == os.path.dirname(parent):
|
|
1433
|
+
break
|
|
1434
|
+
parent = os.path.dirname(parent)
|
|
1435
|
+
return os.path.realpath(anchor) if anchor else None
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
def _commit_repository_binding(root):
|
|
1439
|
+
"""Refuse when the repository `git -C <root>` resolves to is not the one the commit is being made in; else None.
|
|
1440
|
+
|
|
1441
|
+
polyctl runs every enrollment and candidate query as `git -C <project root>`. Where the project is a subdirectory of
|
|
1442
|
+
its repository, an implementer agent - which may write any file in the working tree (docs/threat-model.md) - can
|
|
1443
|
+
plant `<project>/.git`, or a `.git` anywhere between the project and the repository's top: a directory holding a
|
|
1444
|
+
second repository whose history added and then removed the marker, a `gitdir:` file, or a symlink. Git then
|
|
1445
|
+
resolves `git -C <project>` to that other repository, `_project_enrollment` reads the project as uninitialized,
|
|
1446
|
+
and `polyctl commit-check` exits 0, so a commit of the outer repository lands unchecked (NESTED-GIT).
|
|
1447
|
+
|
|
1448
|
+
The pre-commit hook names in POLYCTL_COMMIT_TOP the top of the working tree Git set as the hook's current directory -
|
|
1449
|
+
the repository whose commit it guards - taken from `pwd -P`, never from a Git query, so a planted `.git` cannot
|
|
1450
|
+
move it. This binds polyctl's authority to that one repository: the top and shared git directory that `git -C <root>`
|
|
1451
|
+
resolves to must be its. A planted `.git` FILE, directory or symlink all fail the test, because each makes
|
|
1452
|
+
`rev-parse --show-toplevel` answer another repository's top - a `.git` at the project root answers the root
|
|
1453
|
+
itself, one between answers the directory that holds it - and the git-common-dir is checked too, so even a `.git`
|
|
1454
|
+
symlink whose worktree top coincided would part on the shared directory. Where the top cannot be resolved polyctl
|
|
1455
|
+
refuses rather than guess, and a refusal names what was found and what to do.
|
|
1456
|
+
|
|
1457
|
+
The hook's top takes precedence over all ancestor evidence, including forged history reached through a
|
|
1458
|
+
directory symlink. Without a hook, lexical ancestor evidence is checked before resolved ancestors. No
|
|
1459
|
+
environment variable is needed by hooks, prove, doctor, remove or adoption.
|
|
1460
|
+
"""
|
|
1461
|
+
anchor_raw = os.environ.get(COMMIT_TOP_ENV) or "an ancestor repository"
|
|
1462
|
+
try:
|
|
1463
|
+
anchor_raw = _project_repository_top(root)
|
|
1464
|
+
if not anchor_raw:
|
|
1465
|
+
return None
|
|
1466
|
+
resolved_top, resolved_git_dir = _repository_identity(root)
|
|
1467
|
+
anchor_top, anchor_git_dir = _repository_identity(
|
|
1468
|
+
os.path.realpath(os.path.abspath(os.path.expanduser(anchor_raw))))
|
|
1469
|
+
except _HookResolutionError as exc:
|
|
1470
|
+
return (
|
|
1471
|
+
f"polyctl cannot rule out a repository redirect: it cannot confirm that {root} is the repository being "
|
|
1472
|
+
f"committed at {anchor_raw}: {exc}. It refuses "
|
|
1473
|
+
"rather than judge a repository that may not be the one the commit lands in; look for a .git planted in "
|
|
1474
|
+
"or above the project; remove that redirect, then try again"
|
|
1475
|
+
)
|
|
1476
|
+
# A directory symlink can also substitute a different marker path inside the same repository.
|
|
1477
|
+
# Resolve the spelling above the repository top, but keep every component below it (NESTED-GIT).
|
|
1478
|
+
directory_redirect = False
|
|
1479
|
+
project_path = os.path.abspath(root)
|
|
1480
|
+
parent = project_path
|
|
1481
|
+
while True:
|
|
1482
|
+
if os.path.realpath(parent) == anchor_top and not os.path.islink(parent):
|
|
1483
|
+
expected = os.path.normpath(os.path.join(anchor_top, os.path.relpath(project_path, parent)))
|
|
1484
|
+
directory_redirect = os.path.realpath(project_path) != expected
|
|
1485
|
+
break
|
|
1486
|
+
if parent == os.path.dirname(parent):
|
|
1487
|
+
break
|
|
1488
|
+
parent = os.path.dirname(parent)
|
|
1489
|
+
if resolved_top != anchor_top or resolved_git_dir != anchor_git_dir or directory_redirect:
|
|
1490
|
+
return (
|
|
1491
|
+
f"the commit is being made in the repository at {anchor_top}, but git in {root} resolves to the "
|
|
1492
|
+
f"repository at {resolved_top}: a planted .git or project-directory symlink redirects it. polyctl "
|
|
1493
|
+
f"will not move its commit authority to another repository — remove the planted .git or directory symlink "
|
|
1494
|
+
f"in or above the project, "
|
|
1495
|
+
f"then retry from {anchor_top}"
|
|
1496
|
+
)
|
|
1497
|
+
return None
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
def _project_index_env(root, index_file=None):
|
|
1501
|
+
"""Return Git's active-index override without other inherited bindings."""
|
|
1502
|
+
if index_file is None:
|
|
1503
|
+
if "GIT_INDEX_FILE" not in os.environ:
|
|
1504
|
+
return None, None
|
|
1505
|
+
value = os.environ["GIT_INDEX_FILE"]
|
|
1506
|
+
else:
|
|
1507
|
+
value = index_file
|
|
1508
|
+
if not value:
|
|
1509
|
+
return None, "GIT_INDEX_FILE is set but empty"
|
|
1510
|
+
if not os.path.isabs(value):
|
|
1511
|
+
# The Git query below runs with ``cwd=root``. Resolve its relative index
|
|
1512
|
+
# exactly there before the sanitized environment is constructed, so a
|
|
1513
|
+
# direct ``polyctl commit-check`` and the installed hook measure the same
|
|
1514
|
+
# active candidate.
|
|
1515
|
+
value = os.path.abspath(os.path.join(root, value))
|
|
1516
|
+
return {"GIT_INDEX_FILE": value}, None
|
|
1517
|
+
|
|
1518
|
+
|
|
1519
|
+
def _marker_blob(root, oid, extra_env):
|
|
1520
|
+
result = _hook_git(root, "cat-file", "blob", oid, extra_env=extra_env)
|
|
1521
|
+
if result.returncode:
|
|
1522
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1523
|
+
return None, detail or f"git cat-file exited {result.returncode}"
|
|
1524
|
+
return result.stdout, None
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
def _index_project_marker(root, index_file=None):
|
|
1528
|
+
extra_env, problem = _project_index_env(root, index_file)
|
|
1529
|
+
if problem:
|
|
1530
|
+
return {"status": "unknown", "detail": problem}
|
|
1531
|
+
if extra_env:
|
|
1532
|
+
try:
|
|
1533
|
+
with open(extra_env["GIT_INDEX_FILE"], "rb") as fh:
|
|
1534
|
+
fh.read(1)
|
|
1535
|
+
except FileNotFoundError as exc:
|
|
1536
|
+
# Git defines a nonexistent index as empty. A dangling symlink is an
|
|
1537
|
+
# existing override we cannot read, not a new empty index.
|
|
1538
|
+
if os.path.lexists(extra_env["GIT_INDEX_FILE"]):
|
|
1539
|
+
return {"status": "unknown", "detail": f"active index cannot be read: {exc}"}
|
|
1540
|
+
except OSError as exc:
|
|
1541
|
+
return {"status": "unknown", "detail": f"active index cannot be read: {exc}"}
|
|
1542
|
+
result = _hook_git(
|
|
1543
|
+
root, "ls-files", "--stage", "-z", "--", PROJECT_MARKER,
|
|
1544
|
+
extra_env=extra_env,
|
|
1545
|
+
)
|
|
1546
|
+
if result.returncode:
|
|
1547
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1548
|
+
return {
|
|
1549
|
+
"status": "unknown",
|
|
1550
|
+
"detail": "active index marker query failed: "
|
|
1551
|
+
+ (detail or f"git exit {result.returncode}"),
|
|
1552
|
+
}
|
|
1553
|
+
rows = [row for row in result.stdout.split(b"\0") if row]
|
|
1554
|
+
if not rows:
|
|
1555
|
+
return {"status": "absent"}
|
|
1556
|
+
if len(rows) != 1 or b"\t" not in rows[0]:
|
|
1557
|
+
return {"status": "invalid", "detail": "active index marker is unmerged"}
|
|
1558
|
+
metadata, path = rows[0].split(b"\t", 1)
|
|
1559
|
+
fields = metadata.split()
|
|
1560
|
+
if len(fields) != 3 or fields[2] != b"0" or path != PROJECT_MARKER.encode("ascii"):
|
|
1561
|
+
return {"status": "invalid", "detail": "active index marker entry is malformed"}
|
|
1562
|
+
try:
|
|
1563
|
+
mode, oid = fields[0].decode("ascii"), fields[1].decode("ascii")
|
|
1564
|
+
except UnicodeError:
|
|
1565
|
+
return {"status": "invalid", "detail": "active index marker entry is not ASCII"}
|
|
1566
|
+
if mode not in ("100644", "100755"):
|
|
1567
|
+
return {"status": "invalid", "detail": f"active index marker has type/mode {mode}"}
|
|
1568
|
+
data, error = _marker_blob(root, oid, extra_env)
|
|
1569
|
+
if error:
|
|
1570
|
+
return {"status": "unknown", "detail": "active index marker blob is unreadable: " + error}
|
|
1571
|
+
if data != PROJECT_MARKER_BYTES:
|
|
1572
|
+
return {"status": "invalid", "detail": "active index marker bytes are not polyctl-project-v1"}
|
|
1573
|
+
return {"status": "canonical", "mode": mode, "oid": oid}
|
|
1574
|
+
|
|
1575
|
+
|
|
1576
|
+
def _head_project_marker(root):
|
|
1577
|
+
head = _hook_git(root, "rev-parse", "--verify", "--quiet", "HEAD")
|
|
1578
|
+
if head.returncode:
|
|
1579
|
+
if head.returncode == 1 and not head.stdout and not head.stderr:
|
|
1580
|
+
return {"status": "absent", "unborn": True}
|
|
1581
|
+
detail = head.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1582
|
+
return {
|
|
1583
|
+
"status": "unknown",
|
|
1584
|
+
"detail": "HEAD marker query failed: "
|
|
1585
|
+
+ (detail or f"git exit {head.returncode}"),
|
|
1586
|
+
}
|
|
1587
|
+
result = _hook_git(root, "ls-tree", "-z", "HEAD", "--", PROJECT_MARKER)
|
|
1588
|
+
if result.returncode:
|
|
1589
|
+
detail = result.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1590
|
+
return {
|
|
1591
|
+
"status": "unknown",
|
|
1592
|
+
"detail": "HEAD marker query failed: "
|
|
1593
|
+
+ (detail or f"git exit {result.returncode}"),
|
|
1594
|
+
}
|
|
1595
|
+
rows = [row for row in result.stdout.split(b"\0") if row]
|
|
1596
|
+
if not rows:
|
|
1597
|
+
return {"status": "absent"}
|
|
1598
|
+
if len(rows) != 1 or b"\t" not in rows[0]:
|
|
1599
|
+
return {"status": "invalid", "detail": "HEAD marker entry is malformed"}
|
|
1600
|
+
metadata, path = rows[0].split(b"\t", 1)
|
|
1601
|
+
fields = metadata.split()
|
|
1602
|
+
if len(fields) != 3 or path != PROJECT_MARKER.encode("ascii"):
|
|
1603
|
+
return {"status": "invalid", "detail": "HEAD marker entry is malformed"}
|
|
1604
|
+
try:
|
|
1605
|
+
mode = fields[0].decode("ascii")
|
|
1606
|
+
kind = fields[1].decode("ascii")
|
|
1607
|
+
oid = fields[2].decode("ascii")
|
|
1608
|
+
except UnicodeError:
|
|
1609
|
+
return {"status": "invalid", "detail": "HEAD marker entry is not ASCII"}
|
|
1610
|
+
if kind != "blob" or mode not in ("100644", "100755"):
|
|
1611
|
+
return {"status": "invalid", "detail": f"HEAD marker has type/mode {kind}/{mode}"}
|
|
1612
|
+
data, error = _marker_blob(root, oid, None)
|
|
1613
|
+
if error:
|
|
1614
|
+
return {"status": "unknown", "detail": "HEAD marker blob is unreadable: " + error}
|
|
1615
|
+
if data != PROJECT_MARKER_BYTES:
|
|
1616
|
+
return {"status": "invalid", "detail": "HEAD marker bytes are not polyctl-project-v1"}
|
|
1617
|
+
return {"status": "canonical", "mode": mode, "oid": oid}
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
def _project_config_problem(root):
|
|
1621
|
+
"""The marker is authority; validate the bounded local state it activates."""
|
|
1622
|
+
return A.project_config_document(root)["problem"]
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
def _worktree_marker_forms():
|
|
1626
|
+
"""The working-tree bytes that are the marker: exactly its bytes, and on Windows their CRLF checkout.
|
|
1627
|
+
|
|
1628
|
+
Git for Windows checks text out with CRLF (core.autocrlf=true is its default), so a
|
|
1629
|
+
Windows clone of an enrolled repository holds polyctl-project-v1 and CRLF, and `polyctl init`
|
|
1630
|
+
refused the marker Git had just checked out (#71). Enrollment is measured from the
|
|
1631
|
+
blobs in HEAD and the active index alone, which that same Git stores as the exact
|
|
1632
|
+
bytes, and stays exact; only this working-tree read accepts the one translation,
|
|
1633
|
+
of the whole marker, and only where the platform makes it.
|
|
1634
|
+
"""
|
|
1635
|
+
if os.name == "nt":
|
|
1636
|
+
return (PROJECT_MARKER_BYTES, PROJECT_MARKER_BYTES.replace(b"\n", b"\r\n"))
|
|
1637
|
+
return (PROJECT_MARKER_BYTES,)
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _worktree_project_marker_document(root):
|
|
1641
|
+
"""Read one bounded marker snapshot whose fingerprint detects replacement."""
|
|
1642
|
+
import stat
|
|
1643
|
+
|
|
1644
|
+
path = os.path.join(root, PROJECT_MARKER)
|
|
1645
|
+
try:
|
|
1646
|
+
listed = os.lstat(path)
|
|
1647
|
+
except FileNotFoundError as exc:
|
|
1648
|
+
return {
|
|
1649
|
+
"exists": False,
|
|
1650
|
+
"fingerprint": ("absent",),
|
|
1651
|
+
"problem": f"{PROJECT_MARKER} is missing or unreadable ({exc})",
|
|
1652
|
+
}
|
|
1653
|
+
except OSError as exc:
|
|
1654
|
+
return {
|
|
1655
|
+
"exists": True,
|
|
1656
|
+
"fingerprint": ("unreadable", type(exc).__name__, exc.errno),
|
|
1657
|
+
"problem": f"{PROJECT_MARKER} is missing or unreadable ({exc})",
|
|
1658
|
+
}
|
|
1659
|
+
if not stat.S_ISREG(listed.st_mode) or os.path.islink(path):
|
|
1660
|
+
return {
|
|
1661
|
+
"exists": True,
|
|
1662
|
+
"fingerprint": (
|
|
1663
|
+
"not-regular", listed.st_dev, listed.st_ino, listed.st_mode
|
|
1664
|
+
),
|
|
1665
|
+
"problem": f"{PROJECT_MARKER} is not a regular file",
|
|
1666
|
+
}
|
|
1667
|
+
forms = _worktree_marker_forms()
|
|
1668
|
+
try:
|
|
1669
|
+
with open(path, "rb") as fh:
|
|
1670
|
+
opened = os.fstat(fh.fileno())
|
|
1671
|
+
# One byte past the longest accepted form, so a longer file never reads as one.
|
|
1672
|
+
data = fh.read(max(len(form) for form in forms) + 1)
|
|
1673
|
+
finished = os.fstat(fh.fileno())
|
|
1674
|
+
except OSError as exc:
|
|
1675
|
+
return {
|
|
1676
|
+
"exists": True,
|
|
1677
|
+
"fingerprint": ("unreadable", type(exc).__name__, exc.errno),
|
|
1678
|
+
"problem": f"{PROJECT_MARKER} is unreadable ({exc})",
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
def identity(value):
|
|
1682
|
+
return (
|
|
1683
|
+
value.st_dev,
|
|
1684
|
+
value.st_ino,
|
|
1685
|
+
value.st_mode,
|
|
1686
|
+
value.st_size,
|
|
1687
|
+
getattr(value, "st_mtime_ns", int(value.st_mtime * 1_000_000_000)),
|
|
1688
|
+
# Last, so that Windows can compare a path's stat with a handle's without it (below).
|
|
1689
|
+
getattr(value, "st_ctime_ns", int(value.st_ctime * 1_000_000_000)),
|
|
1690
|
+
)
|
|
1691
|
+
|
|
1692
|
+
listed_identity = identity(listed)
|
|
1693
|
+
opened_identity = identity(opened)
|
|
1694
|
+
finished_identity = identity(finished)
|
|
1695
|
+
fingerprint = ("regular", finished_identity, data)
|
|
1696
|
+
# CPython 3.12 and later on Windows read two clocks into st_ctime: a path's stat reports when the
|
|
1697
|
+
# file was created, a handle's when its metadata last changed. They agree only while nothing
|
|
1698
|
+
# changed after creation, so init refused the marker it had just written and the one a clone
|
|
1699
|
+
# checked out (#71). There the path and the handle are one file when every other field agrees;
|
|
1700
|
+
# the handle's two readings, and so the fingerprint, still compare st_ctime.
|
|
1701
|
+
across = slice(None, -1) if os.name == "nt" else slice(None)
|
|
1702
|
+
if listed_identity[across] != opened_identity[across]:
|
|
1703
|
+
return {
|
|
1704
|
+
"exists": True,
|
|
1705
|
+
"fingerprint": fingerprint,
|
|
1706
|
+
"problem": f"{PROJECT_MARKER} changed before it could be read",
|
|
1707
|
+
}
|
|
1708
|
+
if opened_identity != finished_identity:
|
|
1709
|
+
return {
|
|
1710
|
+
"exists": True,
|
|
1711
|
+
"fingerprint": fingerprint,
|
|
1712
|
+
"problem": f"{PROJECT_MARKER} changed while it was being read",
|
|
1713
|
+
}
|
|
1714
|
+
if data not in forms:
|
|
1715
|
+
return {
|
|
1716
|
+
"exists": True,
|
|
1717
|
+
"fingerprint": fingerprint,
|
|
1718
|
+
"problem": f"{PROJECT_MARKER} bytes are not polyctl-project-v1",
|
|
1719
|
+
}
|
|
1720
|
+
return {"exists": True, "fingerprint": fingerprint, "problem": None}
|
|
1721
|
+
|
|
1722
|
+
|
|
1723
|
+
def _worktree_project_marker_problem(root):
|
|
1724
|
+
return _worktree_project_marker_document(root)["problem"]
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
def _legacy_enrollment(root):
|
|
1728
|
+
"""A project set up before .polyctl-project existed stays governed by its config.
|
|
1729
|
+
|
|
1730
|
+
The tracked marker is the right authority for a new project and for a
|
|
1731
|
+
deliberate two-phase removal, and it left one case out: a project initialised
|
|
1732
|
+
before the marker existed. That project has a real .polyctl/config.json, an
|
|
1733
|
+
enforcing commit hook, and no marker anywhere in its history. Calling it
|
|
1734
|
+
uninitialised turns its hook into a silent pass the moment the tool is
|
|
1735
|
+
upgraded, which is the fail-open the marker was introduced to close.
|
|
1736
|
+
|
|
1737
|
+
Two neighbours must stay unenforced and are told apart here: an incidental
|
|
1738
|
+
.polyctl/ directory has no config, and a completed removal has a commit in HEAD's
|
|
1739
|
+
history that touched the marker. A shallow clone that lost the removal commit
|
|
1740
|
+
reads as legacy, which errs on the enforcing side. Returns None when the
|
|
1741
|
+
project is not legacy.
|
|
1742
|
+
|
|
1743
|
+
A project whose marker `polyctl init` wrote and nobody has staged yet measures the
|
|
1744
|
+
same, so the detail states what is measured rather than how the project came
|
|
1745
|
+
to be, and names the one command that adopts either (INIT-ADOPTION).
|
|
1746
|
+
"""
|
|
1747
|
+
if not os.path.lexists(os.path.join(root, ".polyctl", "config.json")):
|
|
1748
|
+
return None
|
|
1749
|
+
head = _hook_git(root, "rev-parse", "--verify", "--quiet", "HEAD")
|
|
1750
|
+
if head.returncode == 0:
|
|
1751
|
+
touched = _hook_git(root, "rev-list", "-n", "1", "HEAD", "--", PROJECT_MARKER)
|
|
1752
|
+
if touched.returncode:
|
|
1753
|
+
detail = touched.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1754
|
+
return _unknown_project_enrollment(
|
|
1755
|
+
f"cannot read {PROJECT_MARKER} history: " + (detail or f"git exit {touched.returncode}"))
|
|
1756
|
+
if touched.stdout.strip():
|
|
1757
|
+
return None
|
|
1758
|
+
elif head.returncode != 1 or head.stdout or head.stderr:
|
|
1759
|
+
detail = head.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1760
|
+
return _unknown_project_enrollment("HEAD query failed: " + (detail or f"git exit {head.returncode}"))
|
|
1761
|
+
problem = _project_config_problem(root)
|
|
1762
|
+
if problem:
|
|
1763
|
+
return {
|
|
1764
|
+
"state": "broken",
|
|
1765
|
+
"detail": f"this project has polyctl state but it is unreadable: {problem}",
|
|
1766
|
+
}
|
|
1767
|
+
return {
|
|
1768
|
+
"state": "legacy",
|
|
1769
|
+
"detail": (
|
|
1770
|
+
f"no {PROJECT_MARKER} has ever been tracked here, so .polyctl/config.json governs "
|
|
1771
|
+
f"commits — {PROJECT_ADOPT_HINT}"
|
|
1772
|
+
),
|
|
1773
|
+
"source": None,
|
|
1774
|
+
"marker": None,
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
|
|
1778
|
+
def _unknown_project_enrollment(problem, **evidence):
|
|
1779
|
+
"""An unanswered enrollment question permits no enrollment or hook writes."""
|
|
1780
|
+
return dict(evidence, state="broken", unknown=True, recordable=False,
|
|
1781
|
+
detail=f"enrollment is unknown: {problem}")
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
def _project_enrollment(root, index_file=None):
|
|
1785
|
+
"""Measure the tracked marker in the active index and HEAD, then local state.
|
|
1786
|
+
|
|
1787
|
+
The active index wins when it has an entry, so a malformed staged replacement
|
|
1788
|
+
cannot disable a canonical HEAD marker. An absent index entry still consults
|
|
1789
|
+
HEAD, which keeps enforcement active while an authorized marker deletion is
|
|
1790
|
+
staged. A canonical staged marker permits first adoption before the first
|
|
1791
|
+
marker-bearing commit, including on an unborn branch. With neither marker,
|
|
1792
|
+
consult history across all refs and this machine's record before deciding.
|
|
1793
|
+
Failed queries are unknown and permit no writes; a missing index or unborn
|
|
1794
|
+
HEAD is known absent. Recording pre-marker state would wedge its adoption.
|
|
1795
|
+
"""
|
|
1796
|
+
root = os.path.abspath(root)
|
|
1797
|
+
redirected = _commit_repository_binding(root)
|
|
1798
|
+
if redirected is not None:
|
|
1799
|
+
# A `.git` planted in the project would move every query below to another repository, so this is
|
|
1800
|
+
# measured before the marker is read. Unlike a broken enrolled repository, a redirect supplies no
|
|
1801
|
+
# evidence of enrollment and must cause no record to be written in either repository (NESTED-GIT).
|
|
1802
|
+
return {"state": "redirected", "detail": redirected}
|
|
1803
|
+
try:
|
|
1804
|
+
indexed = _index_project_marker(root, index_file=index_file)
|
|
1805
|
+
headed = _head_project_marker(root)
|
|
1806
|
+
except _HookResolutionError as exc:
|
|
1807
|
+
return _unknown_project_enrollment(str(exc))
|
|
1808
|
+
|
|
1809
|
+
for measured in (indexed, headed):
|
|
1810
|
+
if measured["status"] == "unknown":
|
|
1811
|
+
return _unknown_project_enrollment(measured["detail"], index=indexed, head=headed)
|
|
1812
|
+
|
|
1813
|
+
# A marker that is there but not the marker still names the project, and the current hook goes on to polyctl
|
|
1814
|
+
# there, which refuses: the index and HEAD are kept so `polyctl hooks install` can tell that from a project where
|
|
1815
|
+
# no marker is tracked, which the hook stands aside in (TRIAGE-HIGHS).
|
|
1816
|
+
if indexed["status"] == "invalid":
|
|
1817
|
+
return {"state": "broken", "detail": _project_refusal(indexed["detail"]),
|
|
1818
|
+
"index": indexed, "head": headed, "recordable": True}
|
|
1819
|
+
if indexed["status"] == "canonical":
|
|
1820
|
+
source, marker = "index", indexed
|
|
1821
|
+
elif headed["status"] == "invalid":
|
|
1822
|
+
return {"state": "broken", "detail": _project_refusal(headed["detail"]),
|
|
1823
|
+
"index": indexed, "head": headed, "recordable": True}
|
|
1824
|
+
elif headed["status"] == "canonical":
|
|
1825
|
+
source, marker = "head", headed
|
|
1826
|
+
else:
|
|
1827
|
+
# Absence in this index and HEAD is not absence from the repository.
|
|
1828
|
+
# Only a completed removal in this branch's history retires enrollment;
|
|
1829
|
+
# an orphan or a branch made before enrollment must consult every ref and
|
|
1830
|
+
# then the machine record, which survives deletion of those refs.
|
|
1831
|
+
try:
|
|
1832
|
+
tracked = _hook_git(root, "log", "--all", "-1", "--format=%H", "--", PROJECT_MARKER)
|
|
1833
|
+
if tracked.returncode:
|
|
1834
|
+
detail = tracked.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1835
|
+
return _unknown_project_enrollment(
|
|
1836
|
+
f"cannot read {PROJECT_MARKER} history across all refs: "
|
|
1837
|
+
+ (detail or f"git exit {tracked.returncode}"), index=indexed, head=headed)
|
|
1838
|
+
removed = False
|
|
1839
|
+
if not headed.get("unborn"):
|
|
1840
|
+
touched = _hook_git(root, "rev-list", "-n", "1", "HEAD", "--", PROJECT_MARKER)
|
|
1841
|
+
if touched.returncode:
|
|
1842
|
+
detail = touched.stderr.decode(UTF8, "replace").strip()[:160]
|
|
1843
|
+
return _unknown_project_enrollment(
|
|
1844
|
+
f"cannot read {PROJECT_MARKER} history: " + (detail or f"git exit {touched.returncode}"),
|
|
1845
|
+
index=indexed, head=headed)
|
|
1846
|
+
removed = bool(touched.stdout.strip())
|
|
1847
|
+
except _HookResolutionError as exc:
|
|
1848
|
+
return _unknown_project_enrollment(f"cannot read {PROJECT_MARKER} history: {exc}",
|
|
1849
|
+
index=indexed, head=headed)
|
|
1850
|
+
recorded = A.enrollment_record(root)
|
|
1851
|
+
if recorded is not None and recorded.get("unreadable"):
|
|
1852
|
+
return _unknown_project_enrollment(
|
|
1853
|
+
f"machine enrollment record cannot be read: {recorded['unreadable']}", index=indexed, head=headed)
|
|
1854
|
+
if not removed and (tracked.stdout.strip() or recorded is not None):
|
|
1855
|
+
branch = ("this branch is not born yet and stages no marker" if headed.get("unborn") else
|
|
1856
|
+
f"this branch tracks no {PROJECT_MARKER} and descends from no commit that did")
|
|
1857
|
+
if tracked.stdout.strip():
|
|
1858
|
+
why = f"{branch}, but the repository's history tracks {PROJECT_MARKER} on another branch"
|
|
1859
|
+
else:
|
|
1860
|
+
why = f"{branch}, but this machine recorded the project as enrolled"
|
|
1861
|
+
why += (": commit the marker on this branch, or switch back" if headed.get("unborn") else
|
|
1862
|
+
": a branch made from before the marker's commit - commit the marker on it, or switch back")
|
|
1863
|
+
return {"state": "broken", "detail": _project_refusal(why),
|
|
1864
|
+
"index": indexed, "head": headed, "recordable": True}
|
|
1865
|
+
try:
|
|
1866
|
+
legacy = _legacy_enrollment(root)
|
|
1867
|
+
except _HookResolutionError as exc:
|
|
1868
|
+
return _unknown_project_enrollment(str(exc), index=indexed, head=headed)
|
|
1869
|
+
if legacy is not None:
|
|
1870
|
+
legacy.update({"index": indexed, "head": headed})
|
|
1871
|
+
return legacy
|
|
1872
|
+
return {
|
|
1873
|
+
"state": "uninitialized",
|
|
1874
|
+
"detail": f"no canonical {PROJECT_MARKER} exists in HEAD or the active index",
|
|
1875
|
+
"index": indexed,
|
|
1876
|
+
"head": headed,
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
problem = _project_config_problem(root)
|
|
1880
|
+
if problem:
|
|
1881
|
+
return {
|
|
1882
|
+
"state": "broken", "detail": _project_refusal(problem),
|
|
1883
|
+
"source": source, "marker": marker, "recordable": True,
|
|
1884
|
+
"index": indexed, "head": headed,
|
|
1885
|
+
}
|
|
1886
|
+
return {
|
|
1887
|
+
"state": "enrolled", "detail": f"canonical {PROJECT_MARKER} via {source}",
|
|
1888
|
+
"source": source, "marker": marker, "recordable": True,
|
|
1889
|
+
"index": indexed, "head": headed,
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
|
|
1893
|
+
def _commit_hook_probe_response(root):
|
|
1894
|
+
"""Refuse a nonce-bound synthetic index without touching the object store.
|
|
1895
|
+
|
|
1896
|
+
The execution probe reaches this branch through Git's own hook runner. It
|
|
1897
|
+
stages one gitlink in a temporary index, pointing at the existing HEAD
|
|
1898
|
+
commit, so validating the challenge needs no ``write-tree`` and leaves no
|
|
1899
|
+
loose object behind. All four namespaced challenge fields must be present
|
|
1900
|
+
before this branch activates, so a partial inherited environment cannot
|
|
1901
|
+
intercept a real commit. The namespaced index must also bind exactly to
|
|
1902
|
+
Git's active index. Once active, a missing index or malformed challenge
|
|
1903
|
+
fails closed without emitting the success marker the parent process
|
|
1904
|
+
requires.
|
|
1905
|
+
"""
|
|
1906
|
+
nonce = os.environ.get("POLYCTL_HOOK_PROBE_NONCE")
|
|
1907
|
+
path = os.environ.get("POLYCTL_HOOK_PROBE_PATH")
|
|
1908
|
+
head = os.environ.get("POLYCTL_HOOK_PROBE_HEAD")
|
|
1909
|
+
probe_index = os.environ.get("POLYCTL_HOOK_PROBE_INDEX")
|
|
1910
|
+
index = os.environ.get("GIT_INDEX_FILE")
|
|
1911
|
+
challenge = (nonce, path, head, probe_index)
|
|
1912
|
+
if any(value is None for value in challenge):
|
|
1913
|
+
return None
|
|
1914
|
+
|
|
1915
|
+
values = challenge + (index,)
|
|
1916
|
+
problem = None
|
|
1917
|
+
if not all(values):
|
|
1918
|
+
problem = "incomplete hook execution challenge"
|
|
1919
|
+
elif len(nonce) != 32 or any(ch not in "0123456789abcdef" for ch in nonce):
|
|
1920
|
+
problem = "invalid hook execution challenge nonce"
|
|
1921
|
+
elif path != ".polyctl-hook-probe-" + nonce:
|
|
1922
|
+
problem = "hook execution challenge path does not match its nonce"
|
|
1923
|
+
elif len(head) not in (40, 64) or any(ch not in "0123456789abcdef" for ch in head):
|
|
1924
|
+
problem = "invalid hook execution challenge object"
|
|
1925
|
+
elif not os.path.isabs(index):
|
|
1926
|
+
problem = "hook execution challenge index is not absolute"
|
|
1927
|
+
elif probe_index != index:
|
|
1928
|
+
problem = "hook execution challenge index does not match Git's active index"
|
|
1929
|
+
|
|
1930
|
+
if problem is None:
|
|
1931
|
+
try:
|
|
1932
|
+
measured = _hook_git(
|
|
1933
|
+
root, "ls-files", "--stage", "-z", "--", path,
|
|
1934
|
+
extra_env={"GIT_INDEX_FILE": index},
|
|
1935
|
+
)
|
|
1936
|
+
except _HookResolutionError as exc:
|
|
1937
|
+
problem = f"cannot inspect hook execution challenge: {exc}"
|
|
1938
|
+
else:
|
|
1939
|
+
expected = f"160000 {head} 0\t{path}\0".encode("ascii")
|
|
1940
|
+
if measured.returncode or measured.stdout != expected:
|
|
1941
|
+
problem = "hook execution challenge does not match the synthetic index"
|
|
1942
|
+
|
|
1943
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
1944
|
+
if problem is not None:
|
|
1945
|
+
print(f" {C['red']}·{C['reset']} {problem}")
|
|
1946
|
+
else:
|
|
1947
|
+
print(f"POLYCTL-HOOK-PROBE-REFUSED {nonce} {head} {path}")
|
|
1948
|
+
return 1
|
|
1949
|
+
|
|
1950
|
+
|
|
1951
|
+
def _message_bytes(root, message, file):
|
|
1952
|
+
"""The message polyctl commit was given, as the bytes git would have read (COMMIT-TRAILER).
|
|
1953
|
+
|
|
1954
|
+
`-m` as its argument reached git; `-F -` from standard input; any other `-F` from the file, read
|
|
1955
|
+
where git read it: from the project root, where polyctl runs git.
|
|
1956
|
+
"""
|
|
1957
|
+
if message:
|
|
1958
|
+
return os.fsencode(message)
|
|
1959
|
+
if file == "-":
|
|
1960
|
+
return sys.stdin.buffer.read()
|
|
1961
|
+
with open(os.path.join(root, file), "rb") as fh:
|
|
1962
|
+
return fh.read()
|
|
1963
|
+
|
|
1964
|
+
|
|
1965
|
+
def cmd_commit(cfg, args):
|
|
1966
|
+
"""Commit the staged candidate in the one form a tool grant can safely allow (#58).
|
|
1967
|
+
|
|
1968
|
+
A grant of `git commit:*` is a grant of `git commit --no-verify`, the flag that
|
|
1969
|
+
skips the only commit-time enforcement. This takes a message and nothing else and
|
|
1970
|
+
runs the same authority check the pre-commit hook runs, so a deleted or redirected
|
|
1971
|
+
hook does not skip it.
|
|
1972
|
+
|
|
1973
|
+
The message ends with the grant that check held the index to, as git trailers
|
|
1974
|
+
(COMMIT-TRAILER): the grant stays in this checkout's ledger while the commit
|
|
1975
|
+
leaves it, so the commit names its own authority wherever it goes, and
|
|
1976
|
+
`polyctl commit-check --range` holds it to that. A message that already ends with
|
|
1977
|
+
Polyctl- trailers is refused, not rewritten: they could only be another commit's,
|
|
1978
|
+
copied with its message, or typed by hand, and polyctl does not edit what a person
|
|
1979
|
+
wrote into a claim it did not make.
|
|
1980
|
+
|
|
1981
|
+
What lands is the tree the grant bound, on the commit it was built on, and nothing
|
|
1982
|
+
else (LEADS-GATE). `git commit` read the index again once its hooks returned, so a
|
|
1983
|
+
path staged in between - by another process, by a hook into the index Git handed
|
|
1984
|
+
it, or written into a copy of the index - landed inside the granted commit; the
|
|
1985
|
+
branch could be switched under it; and the hooks it ran were files an implementer
|
|
1986
|
+
can edit where a repository keeps them in its tree, run as the person committing.
|
|
1987
|
+
So polyctl writes the commit itself, `git commit-tree` of the granted tree on the granted
|
|
1988
|
+
commit, and moves the branch from that commit only, compared and swapped; no hook
|
|
1989
|
+
runs. A path staged after the check stays staged, uncommitted. A project polyctl does not
|
|
1990
|
+
govern passes the check with no grant, and `git commit` commits it as before.
|
|
1991
|
+
"""
|
|
1992
|
+
if project_mode(cfg) == "lite":
|
|
1993
|
+
print(
|
|
1994
|
+
f"{C['red']}commit refused{C['reset']}: there is no gate to commit through in lite mode "
|
|
1995
|
+
f"({ENFORCEMENT_OFF_LITE} — nothing is enforced; switch to full mode with `polyctl mode full`)"
|
|
1996
|
+
)
|
|
1997
|
+
return 1
|
|
1998
|
+
message, file = getattr(args, "message", None), getattr(args, "file", None)
|
|
1999
|
+
if message is not None and file is not None:
|
|
2000
|
+
print("polyctl commit takes exactly one of -m MESSAGE or -F FILE")
|
|
2001
|
+
return 2
|
|
2002
|
+
if not (file or str(message or "").strip()):
|
|
2003
|
+
# An empty message was told it had given both or neither (GRANTS-AUDIT-2).
|
|
2004
|
+
print("polyctl commit needs a message: -m MESSAGE with text in it, or -F FILE")
|
|
2005
|
+
return 2
|
|
2006
|
+
from types import SimpleNamespace
|
|
2007
|
+
check = SimpleNamespace()
|
|
2008
|
+
code = cmd_commit_check(cfg, check)
|
|
2009
|
+
if code:
|
|
2010
|
+
return code
|
|
2011
|
+
grant = getattr(check, "granted", None)
|
|
2012
|
+
if grant is None:
|
|
2013
|
+
# A project polyctl does not govern passes the check with no grant, and its commit stays git's alone.
|
|
2014
|
+
return _git_commit(cfg, message, file)
|
|
2015
|
+
return _commit_the_grant(cfg, grant, message, file)
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
def _git_commit(cfg, message, file):
|
|
2019
|
+
"""`git commit` with the message polyctl commit was given, for a project polyctl does not govern: its exit code."""
|
|
2020
|
+
import subprocess
|
|
2021
|
+
env = {name: value for name, value in os.environ.items()
|
|
2022
|
+
if not name.startswith(("GIT_CONFIG", "GIT_DIR", "GIT_WORK_TREE"))}
|
|
2023
|
+
source = ["-m", message] if message else ["-F", file]
|
|
2024
|
+
# The git polyctl measures with, never one Windows finds in the current directory first (WINDOWS-NO-CWD-EXEC).
|
|
2025
|
+
return subprocess.run([A.git_binary(), "commit", *source], cwd=cfg["root"], env=env).returncode
|
|
2026
|
+
|
|
2027
|
+
|
|
2028
|
+
def _plumbing(root, *args, data=None, timeout=60):
|
|
2029
|
+
"""One git command `polyctl commit` writes with: no hook runs - core.hooksPath names no directory, so neither the
|
|
2030
|
+
reference-transaction hook nor any other is found - and no repository binding is inherited (LEADS-GATE)."""
|
|
2031
|
+
env = _hook_git_env()
|
|
2032
|
+
try:
|
|
2033
|
+
return A.run_as_group([A.git_binary(), "-c", f"core.hooksPath={os.devnull}", "-C", str(root), *args],
|
|
2034
|
+
timeout, env=env, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
2035
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
2036
|
+
raise _HookResolutionError(f"git {args[0]} failed: {' '.join(str(exc).split())[:160]}") from exc
|
|
2037
|
+
|
|
2038
|
+
|
|
2039
|
+
def _plumbing_out(root, *args, data=None):
|
|
2040
|
+
done = _plumbing(root, *args, data=data)
|
|
2041
|
+
if done.returncode:
|
|
2042
|
+
detail = done.stderr.decode(UTF8, "replace").strip()[:200] or f"git exit {done.returncode}"
|
|
2043
|
+
raise _HookResolutionError(f"git {args[0]}: {detail}")
|
|
2044
|
+
return done.stdout
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
def _branch_before(root):
|
|
2048
|
+
"""(the ref HEAD names, or HEAD where it is detached; the commit it points at, or None on a branch not born yet):
|
|
2049
|
+
the ref `polyctl commit` moves, and the commit it moves it from (LEADS-GATE)."""
|
|
2050
|
+
named = _hook_git(root, "symbolic-ref", "-q", "HEAD")
|
|
2051
|
+
ref = named.stdout.decode(UTF8, "replace").strip() if named.returncode == 0 else "HEAD"
|
|
2052
|
+
head = _hook_git(root, "rev-parse", "--verify", "-q", "HEAD")
|
|
2053
|
+
if head.returncode and (head.stdout or head.stderr):
|
|
2054
|
+
raise _HookResolutionError(head.stderr.decode(UTF8, "replace").strip()[:160] or f"git exit {head.returncode}")
|
|
2055
|
+
return ref, (head.stdout.decode("ascii", "replace").strip() or None) if head.returncode == 0 else None
|
|
2056
|
+
|
|
2057
|
+
|
|
2058
|
+
# What `git commit` would have finished: polyctl commit finishes none of it, and sends it back to git (LEADS-GATE). A merge
|
|
2059
|
+
# is no grant's - a grant binds one parent - so a lane lands squashed, as one commit on one parent.
|
|
2060
|
+
_IN_PROGRESS = (("MERGE_HEAD", "a merge", "polyctl lands no merge: git merge --abort, then git merge --squash, which "
|
|
2061
|
+
"stages the lane as one candidate to verify, review and grant as any"),
|
|
2062
|
+
("CHERRY_PICK_HEAD", "a cherry-pick", "git cherry-pick --quit"),
|
|
2063
|
+
("REVERT_HEAD", "a revert", "git revert --quit"),
|
|
2064
|
+
("rebase-merge", "a rebase", "git rebase --abort, or finish it"),
|
|
2065
|
+
("rebase-apply", "a rebase or git am", "git rebase --abort or git am --abort, or finish it"))
|
|
2066
|
+
|
|
2067
|
+
|
|
2068
|
+
def _git_path(root, name):
|
|
2069
|
+
return os.path.join(root, os.fsdecode(_plumbing_out(root, "rev-parse", "--git-path", name).strip()))
|
|
2070
|
+
|
|
2071
|
+
|
|
2072
|
+
def _cleaned_message(root, data):
|
|
2073
|
+
"""The message as `git commit -F` would have cleaned it, by `commit.cleanup`: verbatim left as it is, strip
|
|
2074
|
+
without its comment lines, anything else without trailing space, runs of blank lines or blank ends."""
|
|
2075
|
+
done = _plumbing(root, "config", "--get", "commit.cleanup")
|
|
2076
|
+
mode = done.stdout.decode(UTF8, "replace").strip().lower() if done.returncode == 0 else ""
|
|
2077
|
+
if mode == "verbatim":
|
|
2078
|
+
return data
|
|
2079
|
+
return _plumbing_out(root, "stripspace", *(["--strip-comments"] if mode == "strip" else []), data=data)
|
|
2080
|
+
|
|
2081
|
+
|
|
2082
|
+
def _commit_the_grant(cfg, grant, message, file):
|
|
2083
|
+
"""Write the granted tree as a commit on the granted commit, and move the branch from that commit to it: the exit
|
|
2084
|
+
code (LEADS-GATE)."""
|
|
2085
|
+
root = cfg["root"]
|
|
2086
|
+
|
|
2087
|
+
def refused(why, code=1):
|
|
2088
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}\n {C['red']}·{C['reset']} {why}")
|
|
2089
|
+
return code
|
|
2090
|
+
|
|
2091
|
+
try:
|
|
2092
|
+
trailers = A.grant_trailers(grant)
|
|
2093
|
+
except ValueError as exc:
|
|
2094
|
+
return refused(exc)
|
|
2095
|
+
try:
|
|
2096
|
+
text = _message_bytes(root, message, file).decode(UTF8, "surrogateescape")
|
|
2097
|
+
data = A.with_trailers(text, trailers).encode(UTF8, "surrogateescape")
|
|
2098
|
+
except OSError as exc:
|
|
2099
|
+
print(f"polyctl commit cannot read the message file {file}: {exc}")
|
|
2100
|
+
return 2
|
|
2101
|
+
except ValueError as exc:
|
|
2102
|
+
return refused(exc, 2)
|
|
2103
|
+
candidate = grant.get("candidate") or {}
|
|
2104
|
+
tree, head = candidate.get("index_tree"), candidate.get("head")
|
|
2105
|
+
try:
|
|
2106
|
+
ref, old = _branch_before(root)
|
|
2107
|
+
shown = ref[len("refs/heads/"):] if ref.startswith("refs/heads/") else ref
|
|
2108
|
+
if not old or old != head:
|
|
2109
|
+
return refused(f"{shown} points at {(old or 'no commit')[:12]}, not at {str(head)[:12]}, the commit the "
|
|
2110
|
+
"grant was built on: nothing was committed")
|
|
2111
|
+
for name, what, how in _IN_PROGRESS:
|
|
2112
|
+
if os.path.lexists(_git_path(root, name)):
|
|
2113
|
+
return refused(f"{what} is in progress, which polyctl commit does not finish - {how}, then polyctl commit "
|
|
2114
|
+
"again")
|
|
2115
|
+
cleaned = _cleaned_message(root, data)
|
|
2116
|
+
if not cleaned.strip():
|
|
2117
|
+
return refused("the message is empty once cleaned as git commit cleans one")
|
|
2118
|
+
sign = _plumbing(root, "config", "--type=bool", "--get", "commit.gpgSign")
|
|
2119
|
+
if sign.returncode not in (0, 1):
|
|
2120
|
+
# Git refuses a commit whose commit.gpgSign it cannot read as a boolean; so does polyctl, rather than read it
|
|
2121
|
+
# as unset and write the commit unsigned (LEADS-GATE).
|
|
2122
|
+
return refused("commit.gpgSign cannot be read: "
|
|
2123
|
+
+ (sign.stderr.decode(UTF8, "replace").strip()[:160] or f"git exit {sign.returncode}"))
|
|
2124
|
+
signed = sign.returncode == 0 and sign.stdout.strip() == b"true"
|
|
2125
|
+
made = _plumbing_out(root, "commit-tree", *(["-S"] if signed else []), tree, "-p", old, data=cleaned)
|
|
2126
|
+
made = made.decode("ascii", "replace").strip()
|
|
2127
|
+
if _plumbing_out(root, "rev-parse", "--verify", f"{made}^{{tree}}").decode("ascii").strip() != tree:
|
|
2128
|
+
return refused(f"the commit written, {made[:12]}, does not hold the granted tree {tree[:12]}")
|
|
2129
|
+
subject = cleaned.decode(UTF8, "replace").split("\n", 1)[0]
|
|
2130
|
+
moved = _plumbing(root, "update-ref", "-m", f"commit: {subject}", ref, made, old)
|
|
2131
|
+
if moved.returncode:
|
|
2132
|
+
detail = moved.stderr.decode(UTF8, "replace").strip()[:200]
|
|
2133
|
+
return refused(f"{shown} moved while polyctl commit ran, so it was left where it is and nothing landed: "
|
|
2134
|
+
f"{detail}")
|
|
2135
|
+
except _HookResolutionError as exc:
|
|
2136
|
+
return refused(exc)
|
|
2137
|
+
print(f"[{shown} {made[:7]}] {subject}")
|
|
2138
|
+
try:
|
|
2139
|
+
now = _hook_git(root, "symbolic-ref", "-q", "HEAD")
|
|
2140
|
+
named = now.stdout.decode(UTF8, "replace").strip() if now.returncode == 0 else "HEAD"
|
|
2141
|
+
if named != ref:
|
|
2142
|
+
# Switched while polyctl commit ran: the commit is on the branch the grant was made on, which is not the one
|
|
2143
|
+
# checked out now (LEADS-GATE).
|
|
2144
|
+
print(f" {C['yellow']}·{C['reset']} HEAD was switched while polyctl commit ran: the commit is on {shown}, "
|
|
2145
|
+
f"and {named} is checked out now")
|
|
2146
|
+
except _HookResolutionError:
|
|
2147
|
+
pass
|
|
2148
|
+
try:
|
|
2149
|
+
stat = _plumbing(root, "diff", "--no-ext-diff", "--no-textconv", "--shortstat", old, made)
|
|
2150
|
+
if stat.returncode == 0 and stat.stdout.strip():
|
|
2151
|
+
print(stat.stdout.decode(UTF8, "replace").rstrip())
|
|
2152
|
+
except _HookResolutionError:
|
|
2153
|
+
pass
|
|
2154
|
+
return 0
|
|
2155
|
+
|
|
2156
|
+
|
|
2157
|
+
def _commit_range_check(cfg, args):
|
|
2158
|
+
"""Hold each landed commit of a revision range to the grant its Polyctl- trailers name (COMMIT-TRAILER).
|
|
2159
|
+
|
|
2160
|
+
What `polyctl commit-check --range` runs, CI among its callers: read-only, and in a clone with no .polyctl/ it
|
|
2161
|
+
judges by tree alone. Exit 0 when every commit it checked matches, 1 naming each that does not, 2
|
|
2162
|
+
when the range cannot be read. Requiring it is a person's step, a repository ruleset, never polyctl's.
|
|
2163
|
+
"""
|
|
2164
|
+
spec = args.range
|
|
2165
|
+
# A range is held to the same ancestor enrollment evidence as a staged check, even without a hook's
|
|
2166
|
+
# POLYCTL_COMMIT_TOP; a planted `.git` must not substitute the history being judged (NESTED-GIT).
|
|
2167
|
+
redirected = _commit_repository_binding(cfg["root"])
|
|
2168
|
+
if redirected is not None:
|
|
2169
|
+
print(f"{C['red']}cannot check {spec}{C['reset']}: {redirected}")
|
|
2170
|
+
return 2
|
|
2171
|
+
try:
|
|
2172
|
+
audit = A.trailer_audit(cfg["root"], spec, since_first=bool(getattr(args, "since_first_trailer", False)))
|
|
2173
|
+
except (ValueError, RuntimeError) as exc:
|
|
2174
|
+
print(f"{C['red']}cannot check {spec}{C['reset']}: {exc}")
|
|
2175
|
+
return 2
|
|
2176
|
+
if audit["unreadable"]:
|
|
2177
|
+
print(f"{C['red']}cannot check {spec}{C['reset']}: the authority ledger cannot be read: "
|
|
2178
|
+
f"{audit['unreadable']}")
|
|
2179
|
+
return 2
|
|
2180
|
+
commits = audit["commits"]
|
|
2181
|
+
if not commits:
|
|
2182
|
+
print(f"no commits in {spec}")
|
|
2183
|
+
return 0
|
|
2184
|
+
checked = [commit for commit in commits if not commit["exempt"]]
|
|
2185
|
+
failing = [commit for commit in checked if commit["problems"]]
|
|
2186
|
+
for commit in commits:
|
|
2187
|
+
sha = commit["sha"][:12]
|
|
2188
|
+
if commit["problems"]:
|
|
2189
|
+
print(f" {C['red']}NO MATCH{C['reset']} {sha} {'; '.join(commit['problems'])}")
|
|
2190
|
+
elif not commit["exempt"]:
|
|
2191
|
+
record = {None: "", True: " · on record", False: " · not in this checkout's ledger"}[commit["on_record"]]
|
|
2192
|
+
print(f" {C['green']}matches{C['reset']} {sha} {commit['grant']} · tree {commit['tree'][:12]}{record}")
|
|
2193
|
+
exempt = sum(1 for commit in commits if commit["exempt"])
|
|
2194
|
+
if exempt:
|
|
2195
|
+
why = (f"older than {audit['first'][:12]}, the first commit carrying Polyctl- trailers" if audit["first"]
|
|
2196
|
+
else f"no commit in the history of {audit['end']} carries Polyctl- trailers yet")
|
|
2197
|
+
print(f" {C['dim']}{exempt} commit(s) not checked: {why}{C['reset']}")
|
|
2198
|
+
if not audit["ledger"]:
|
|
2199
|
+
print(f" {C['dim']}checked by tree alone: this checkout keeps no authority ledger{C['reset']}")
|
|
2200
|
+
if failing:
|
|
2201
|
+
print(f"{C['red']}{C['b']}TRAILERS DO NOT MATCH{C['reset']} {len(failing)} of {len(checked)} commit(s) "
|
|
2202
|
+
f"in {spec}: " + ", ".join(commit["sha"][:12] for commit in failing))
|
|
2203
|
+
return 1
|
|
2204
|
+
print(f"{C['green']}{C['b']}TRAILERS MATCH{C['reset']} {len(checked)} commit(s) checked in {spec}")
|
|
2205
|
+
return 0
|
|
2206
|
+
|
|
2207
|
+
|
|
2208
|
+
def cmd_commit_check(cfg, args):
|
|
2209
|
+
"""Pin every Git measurement for the check before enrollment or grant validation begins (NESTED-GIT)."""
|
|
2210
|
+
spec = getattr(args, "range", None)
|
|
2211
|
+
if spec is None and getattr(args, "since_first_trailer", False):
|
|
2212
|
+
print("polyctl commit-check: --since-first-trailer goes with --range")
|
|
2213
|
+
return 2
|
|
2214
|
+
root = cfg["root"]
|
|
2215
|
+
try:
|
|
2216
|
+
top = _project_repository_top(root) or _repository_identity(root)[0]
|
|
2217
|
+
git_dir = _hook_real(top, _hook_output_path(
|
|
2218
|
+
_hook_git(top, "rev-parse", "--absolute-git-dir", bound=False), "--absolute-git-dir"))
|
|
2219
|
+
extra, problem = _project_index_env(root)
|
|
2220
|
+
if problem:
|
|
2221
|
+
raise _HookResolutionError(problem)
|
|
2222
|
+
index = (extra or {}).get("GIT_INDEX_FILE") or os.path.join(git_dir, "index")
|
|
2223
|
+
with A.bound_git_repository(top, git_dir, index):
|
|
2224
|
+
return _bound_commit_check(cfg, args)
|
|
2225
|
+
except _HookResolutionError as exc:
|
|
2226
|
+
if spec is not None:
|
|
2227
|
+
print(f"{C['red']}cannot check {spec}{C['reset']}: cannot bind the repository: {exc}; "
|
|
2228
|
+
"repair its .git and try again")
|
|
2229
|
+
return 2
|
|
2230
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}: enrollment is unknown: "
|
|
2231
|
+
f"cannot bind the repository: {exc}; repair the query failure and try again")
|
|
2232
|
+
return 1
|
|
2233
|
+
|
|
2234
|
+
|
|
2235
|
+
def _coordination_commit_check(root, cfg, args, enrollment, candidate, grant, reasons):
|
|
2236
|
+
"""Revalidate a coordination grant against the active index for `commit-check` (COORDINATION-COMMIT)."""
|
|
2237
|
+
reasons = list(reasons)
|
|
2238
|
+
if candidate is not None and candidate["changed_paths"] and not A.coordination_candidate(candidate, cfg):
|
|
2239
|
+
try:
|
|
2240
|
+
reasons.extend(A.candidate_issue_messages(
|
|
2241
|
+
A.candidate_worktree_issues(root, cfg, candidate)
|
|
2242
|
+
))
|
|
2243
|
+
except Exception as exc:
|
|
2244
|
+
reasons.append(f"cannot measure the staged candidate: {exc}")
|
|
2245
|
+
reasons.append("coordination grant covers only coordination paths")
|
|
2246
|
+
if candidate is not None:
|
|
2247
|
+
try:
|
|
2248
|
+
unstaged = _unstaged_coordination_paths(root, candidate)
|
|
2249
|
+
except Exception as exc:
|
|
2250
|
+
reasons.append(f"cannot measure unstaged coordination paths: {exc}")
|
|
2251
|
+
else:
|
|
2252
|
+
if unstaged:
|
|
2253
|
+
reasons.append(
|
|
2254
|
+
f"unstaged changes on staged coordination path(s) ({', '.join(unstaged)}) — "
|
|
2255
|
+
"stage or revert them so what is checked is what lands"
|
|
2256
|
+
)
|
|
2257
|
+
try:
|
|
2258
|
+
unseen = A.unseen_harness_config(root)
|
|
2259
|
+
except Exception as exc:
|
|
2260
|
+
reasons.append(f"cannot measure harness configuration changes: {exc}")
|
|
2261
|
+
else:
|
|
2262
|
+
if unseen:
|
|
2263
|
+
reasons.append(
|
|
2264
|
+
f"unseen harness configuration ({A.harness_config_line(unseen)}) cannot ride a coordination grant — "
|
|
2265
|
+
"run `polyctl harness seen --ask` first"
|
|
2266
|
+
)
|
|
2267
|
+
if grant.get("schema") != 2:
|
|
2268
|
+
reasons.append("latest grant predates index-candidate binding")
|
|
2269
|
+
if candidate is not None and grant.get("candidate") != candidate:
|
|
2270
|
+
reasons.append("latest grant does not match the current index candidate")
|
|
2271
|
+
stored_scope = grant.get("scope")
|
|
2272
|
+
if not isinstance(stored_scope, dict):
|
|
2273
|
+
reasons.append("latest grant has no valid candidate scope")
|
|
2274
|
+
elif candidate is not None:
|
|
2275
|
+
paths = stored_scope.get("paths")
|
|
2276
|
+
if not isinstance(paths, list):
|
|
2277
|
+
reasons.append("latest grant has no valid candidate scope paths")
|
|
2278
|
+
else:
|
|
2279
|
+
try:
|
|
2280
|
+
current_scope = A.candidate_scope(candidate, paths)
|
|
2281
|
+
except (TypeError, ValueError) as exc:
|
|
2282
|
+
reasons.append(f"latest grant has an invalid candidate scope: {exc}")
|
|
2283
|
+
else:
|
|
2284
|
+
if current_scope["outside_paths"]:
|
|
2285
|
+
reasons.append(
|
|
2286
|
+
"staged paths fall outside the granted scope: "
|
|
2287
|
+
+ ", ".join(current_scope["outside_paths"])
|
|
2288
|
+
)
|
|
2289
|
+
if stored_scope != current_scope:
|
|
2290
|
+
reasons.append("latest grant scope does not exactly match the current candidate")
|
|
2291
|
+
coord = grant.get("coordination")
|
|
2292
|
+
by = (coord.get("by") if isinstance(coord, dict) else None) or grant.get("by") or ""
|
|
2293
|
+
by = by.strip() if isinstance(by, str) else ""
|
|
2294
|
+
if not by or not by.isprintable() or len(by) > 80:
|
|
2295
|
+
reasons.append("coordination grant records no valid --by person")
|
|
2296
|
+
elif by.lower() in _agent_names(cfg):
|
|
2297
|
+
reasons.append(f"coordination grant --by names an agent or a role ({by})")
|
|
2298
|
+
try:
|
|
2299
|
+
A.grant_trailers(grant)
|
|
2300
|
+
except ValueError as exc:
|
|
2301
|
+
reasons.append(str(exc))
|
|
2302
|
+
try:
|
|
2303
|
+
held = A.hold_state(root)
|
|
2304
|
+
except Exception as exc:
|
|
2305
|
+
reasons.append(f"cannot validate project hold state: {exc}")
|
|
2306
|
+
else:
|
|
2307
|
+
if held:
|
|
2308
|
+
reasons.append(f"project is held by {held.get('by')}: {held.get('reason', '')}")
|
|
2309
|
+
try:
|
|
2310
|
+
urgent = A.urgent_messages(root, cfg)
|
|
2311
|
+
except Exception as exc:
|
|
2312
|
+
reasons.append(f"cannot validate urgent messages: {exc}")
|
|
2313
|
+
else:
|
|
2314
|
+
for message in urgent:
|
|
2315
|
+
reasons.append(
|
|
2316
|
+
f"urgent message unacknowledged: {message['id']} — {message['title']}"
|
|
2317
|
+
)
|
|
2318
|
+
redirected = _commit_repository_binding(root)
|
|
2319
|
+
if redirected:
|
|
2320
|
+
reasons.append(redirected)
|
|
2321
|
+
if reasons:
|
|
2322
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
2323
|
+
for reason in reasons:
|
|
2324
|
+
print(f" {C['red']}·{C['reset']} {A.shown_text(reason)}")
|
|
2325
|
+
if enrollment["state"] == "legacy":
|
|
2326
|
+
print(f" {C['dim']}{enrollment['detail']}{C['reset']}")
|
|
2327
|
+
return 1
|
|
2328
|
+
token = grant.get("token") or "recorded grant"
|
|
2329
|
+
print(f"{C['green']}{C['b']}AUTHORIZED{C['reset']} {candidate['index_tree']} · {token}")
|
|
2330
|
+
args.granted = grant
|
|
2331
|
+
return 0
|
|
2332
|
+
|
|
2333
|
+
|
|
2334
|
+
def _bound_commit_check(cfg, args):
|
|
2335
|
+
"""Revalidate the latest persisted grant against Git's exact active index.
|
|
2336
|
+
|
|
2337
|
+
With --range it checks landed commits instead (COMMIT-TRAILER), before anything reads the
|
|
2338
|
+
project's enrollment: a clone in CI holds the tracked marker and no .polyctl/.
|
|
2339
|
+
"""
|
|
2340
|
+
if getattr(args, "range", None) is not None:
|
|
2341
|
+
return _commit_range_check(cfg, args)
|
|
2342
|
+
root = cfg["root"]
|
|
2343
|
+
enrollment = _project_enrollment(root)
|
|
2344
|
+
if enrollment["state"] == "uninitialized":
|
|
2345
|
+
return 0
|
|
2346
|
+
if enrollment["state"] == "redirected":
|
|
2347
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
2348
|
+
print(f" {C['red']}·{C['reset']} {enrollment['detail']}")
|
|
2349
|
+
return 1
|
|
2350
|
+
if enrollment["state"] == "broken":
|
|
2351
|
+
# Malformed but positively read enrollment remains recordable. An unanswered
|
|
2352
|
+
# query supplies no such evidence and must leave the repository untouched.
|
|
2353
|
+
unkept = (A.record_enrollment(_project_repository_top(root) or root)
|
|
2354
|
+
if enrollment.get("recordable") else None)
|
|
2355
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
2356
|
+
print(f" {C['red']}·{C['reset']} {enrollment['detail']}")
|
|
2357
|
+
if unkept:
|
|
2358
|
+
print(f" {C['red']}·{C['reset']} this machine cannot record that the project is enrolled either, and a "
|
|
2359
|
+
f"branch not born yet would read as a new repository's: {unkept}")
|
|
2360
|
+
return 1
|
|
2361
|
+
probe_code = _commit_hook_probe_response(root)
|
|
2362
|
+
if probe_code is not None:
|
|
2363
|
+
return probe_code
|
|
2364
|
+
if project_mode(dict(A.load_config(root), root=root)) == "lite":
|
|
2365
|
+
return 0
|
|
2366
|
+
# On the hook path writes use its top, never the project: a .git planted after the binding check must
|
|
2367
|
+
# not redirect the enrollment record into another repository (NESTED-GIT).
|
|
2368
|
+
# Kept outside the tree, for a branch not born yet to ask where no ref tracks the marker any more; a proof that
|
|
2369
|
+
# the hook runs records nothing (LEADS-GATE).
|
|
2370
|
+
unkept = (A.record_enrollment(_project_repository_top(root) or root)
|
|
2371
|
+
if enrollment.get("recordable") else None)
|
|
2372
|
+
if unkept:
|
|
2373
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
2374
|
+
print(f" {C['red']}·{C['reset']} this machine cannot record that the project is enrolled, and a branch not "
|
|
2375
|
+
f"born yet would read as a new repository's: {unkept}")
|
|
2376
|
+
return 1
|
|
2377
|
+
reasons = []
|
|
2378
|
+
candidate = None
|
|
2379
|
+
try:
|
|
2380
|
+
candidate = A.index_candidate(root)
|
|
2381
|
+
if not candidate["changed_paths"]:
|
|
2382
|
+
reasons.append("no staged candidate")
|
|
2383
|
+
except Exception as exc:
|
|
2384
|
+
reasons.append(f"cannot measure the staged candidate: {exc}")
|
|
2385
|
+
|
|
2386
|
+
grant = None
|
|
2387
|
+
try:
|
|
2388
|
+
grant = A.latest_authority_decision(root)
|
|
2389
|
+
except Exception as exc:
|
|
2390
|
+
reasons.append(f"authority ledger is unreadable: {exc}")
|
|
2391
|
+
if grant and grant.get("granted") is True and grant.get("coordination"):
|
|
2392
|
+
return _coordination_commit_check(root, cfg, args, enrollment, candidate, grant, reasons)
|
|
2393
|
+
|
|
2394
|
+
strict = M.is_strict(cfg)
|
|
2395
|
+
matrix_resolution = None
|
|
2396
|
+
if strict:
|
|
2397
|
+
try:
|
|
2398
|
+
matrix_resolution = _resolve_matrix(cfg, require_independent=False)
|
|
2399
|
+
except M.MatrixError as exc:
|
|
2400
|
+
reasons.extend("capability matrix: " + problem for problem in exc.problems)
|
|
2401
|
+
if candidate is not None:
|
|
2402
|
+
try:
|
|
2403
|
+
reasons.extend(A.candidate_issue_messages(
|
|
2404
|
+
A.candidate_worktree_issues(root, cfg, candidate)
|
|
2405
|
+
))
|
|
2406
|
+
except Exception as exc:
|
|
2407
|
+
reasons.append(f"cannot measure the staged candidate: {exc}")
|
|
2408
|
+
if grant is None:
|
|
2409
|
+
if not any(reason.startswith("authority ledger is unreadable:") for reason in reasons):
|
|
2410
|
+
cmd_hint = ("polyctl commit-ok --by <name> --ask"
|
|
2411
|
+
if candidate is not None and A.coordination_candidate(candidate, cfg)
|
|
2412
|
+
else "polyctl commit-ok")
|
|
2413
|
+
reasons.append(f"no recorded authority decision — run `{cmd_hint}`")
|
|
2414
|
+
elif grant.get("granted") is not True:
|
|
2415
|
+
reasons.append("latest authority decision refused this commit")
|
|
2416
|
+
else:
|
|
2417
|
+
if candidate is not None and A.coordination_candidate(candidate, cfg):
|
|
2418
|
+
reasons.append(
|
|
2419
|
+
"staged candidate holds only coordination paths — "
|
|
2420
|
+
"grant with `polyctl commit-ok --by <name> --ask`"
|
|
2421
|
+
)
|
|
2422
|
+
if strict:
|
|
2423
|
+
if matrix_resolution is not None:
|
|
2424
|
+
reasons.extend(M.authority_problems(matrix_resolution, grant))
|
|
2425
|
+
elif grant.get("schema") != 3:
|
|
2426
|
+
reasons.append("strict mode requires a schema-3 capability-matrix grant")
|
|
2427
|
+
elif grant.get("schema") == 3 or grant.get("matrix") is not None:
|
|
2428
|
+
reasons.append(
|
|
2429
|
+
"capability_matrix was removed after this strict authority grant"
|
|
2430
|
+
)
|
|
2431
|
+
elif grant.get("schema") != 2:
|
|
2432
|
+
reasons.append("latest grant predates index-candidate binding")
|
|
2433
|
+
if candidate is not None and grant.get("candidate") != candidate:
|
|
2434
|
+
reasons.append("latest grant does not match the current index candidate")
|
|
2435
|
+
|
|
2436
|
+
stored_scope = grant.get("scope")
|
|
2437
|
+
if not isinstance(stored_scope, dict):
|
|
2438
|
+
reasons.append("latest grant has no valid candidate scope")
|
|
2439
|
+
elif candidate is not None:
|
|
2440
|
+
paths = stored_scope.get("paths")
|
|
2441
|
+
if not isinstance(paths, list):
|
|
2442
|
+
reasons.append("latest grant has no valid candidate scope paths")
|
|
2443
|
+
else:
|
|
2444
|
+
try:
|
|
2445
|
+
current_scope = A.candidate_scope(candidate, paths)
|
|
2446
|
+
except (TypeError, ValueError) as exc:
|
|
2447
|
+
reasons.append(f"latest grant has an invalid candidate scope: {exc}")
|
|
2448
|
+
else:
|
|
2449
|
+
if current_scope["outside_paths"]:
|
|
2450
|
+
reasons.append(
|
|
2451
|
+
"staged paths fall outside the granted scope: "
|
|
2452
|
+
+ ", ".join(current_scope["outside_paths"])
|
|
2453
|
+
)
|
|
2454
|
+
if stored_scope != current_scope:
|
|
2455
|
+
reasons.append("latest grant scope does not exactly match the current candidate")
|
|
2456
|
+
|
|
2457
|
+
verification = None
|
|
2458
|
+
try:
|
|
2459
|
+
verification = A.latest_verification(root)
|
|
2460
|
+
except Exception as exc:
|
|
2461
|
+
reasons.append(f"verification ledger is unreadable: {exc}")
|
|
2462
|
+
if verification is None:
|
|
2463
|
+
if not any(reason.startswith("verification ledger is unreadable:") for reason in reasons):
|
|
2464
|
+
reasons.append("no verification record — run `polyctl verify`")
|
|
2465
|
+
else:
|
|
2466
|
+
referenced = grant.get("verification") if grant else None
|
|
2467
|
+
if verification.get("id") != referenced:
|
|
2468
|
+
reasons.append(
|
|
2469
|
+
f"latest verification {verification.get('id') or '<unnamed>'} is not "
|
|
2470
|
+
f"the grant's referenced verification {referenced or '<missing>'}"
|
|
2471
|
+
)
|
|
2472
|
+
if verification.get("passed") is not True:
|
|
2473
|
+
waivable_failed, unwaivable_why = A.verification_waivable_gates(root, verification)
|
|
2474
|
+
wanted_gates_waiver = (grant.get("gates_waiver") or grant.get("waiver")) if grant else None
|
|
2475
|
+
if not waivable_failed or not wanted_gates_waiver:
|
|
2476
|
+
reasons.append("the grant's verification did not pass")
|
|
2477
|
+
else:
|
|
2478
|
+
try:
|
|
2479
|
+
running = [item["id"] for item in A.board(root)["running"]]
|
|
2480
|
+
gwaiver, gnotes = A.gates_waiver_for(
|
|
2481
|
+
root, running, (candidate or {}).get("digest"),
|
|
2482
|
+
failed_gates=waivable_failed, wanted=wanted_gates_waiver,
|
|
2483
|
+
)
|
|
2484
|
+
except Exception as exc:
|
|
2485
|
+
reasons.append(f"cannot validate the live gates waiver: {exc}")
|
|
2486
|
+
else:
|
|
2487
|
+
if not gwaiver:
|
|
2488
|
+
reasons.append(
|
|
2489
|
+
"the grant's verification did not pass and no matching running-slice gates waiver is open"
|
|
2490
|
+
+ f" (the grant stood on {wanted_gates_waiver})"
|
|
2491
|
+
+ (f": {'; '.join(gnotes)}" if gnotes else "")
|
|
2492
|
+
)
|
|
2493
|
+
if verification.get("candidate_ready") is not True:
|
|
2494
|
+
reasons.append("the grant's verification did not prove an isolated candidate")
|
|
2495
|
+
if candidate is not None and verification.get("candidate") != candidate:
|
|
2496
|
+
reasons.append("the grant's verification does not match the current index candidate")
|
|
2497
|
+
if A.gate_definitions_digest(root, verification.get("profile")) \
|
|
2498
|
+
!= verification.get("gates_digest"):
|
|
2499
|
+
reasons.append("gate definitions changed since the grant's verification — "
|
|
2500
|
+
"re-run `polyctl verify`")
|
|
2501
|
+
isolation_problem = _verification_isolation_problem(root, verification)
|
|
2502
|
+
if isolation_problem:
|
|
2503
|
+
reasons.append(isolation_problem)
|
|
2504
|
+
|
|
2505
|
+
if grant and grant.get("granted") is True:
|
|
2506
|
+
review_name = grant.get("review")
|
|
2507
|
+
if review_name:
|
|
2508
|
+
try:
|
|
2509
|
+
decision = A.candidate_review_decision(root, cfg["reviews"], candidate["digest"]) \
|
|
2510
|
+
if candidate is not None else {"match": None, "problem": None}
|
|
2511
|
+
except Exception as exc:
|
|
2512
|
+
decision = {"match": None, "problem": f"review ledger is unreadable: {exc}"}
|
|
2513
|
+
match = decision["match"]
|
|
2514
|
+
if not match:
|
|
2515
|
+
reasons.append(f"granted review {review_name} is no longer the current approval"
|
|
2516
|
+
+ (f": {decision['problem']}" if decision["problem"] else ""))
|
|
2517
|
+
else:
|
|
2518
|
+
if match[0] != review_name:
|
|
2519
|
+
reasons.append(
|
|
2520
|
+
f"current approval is {match[0]}, not the granted review {review_name}"
|
|
2521
|
+
)
|
|
2522
|
+
_, integrity_reasons = A.candidate_review_integrity(
|
|
2523
|
+
root, candidate, match[3]
|
|
2524
|
+
)
|
|
2525
|
+
reasons.extend(f"{match[0]}: {reason}" for reason in integrity_reasons)
|
|
2526
|
+
reasons.extend(f"{match[0]}: {reason}" for reason in _boundary_review_refusals(root, match[3]))
|
|
2527
|
+
reasons.extend(f"{match[0]}: {reason}" for reason in A.criteria_refusals(match[3]))
|
|
2528
|
+
if match[3].get("scope") != grant.get("scope"):
|
|
2529
|
+
reasons.append(
|
|
2530
|
+
"granted review scope does not exactly match the persisted authority grant"
|
|
2531
|
+
)
|
|
2532
|
+
if strict and matrix_resolution is not None:
|
|
2533
|
+
reasons.extend(
|
|
2534
|
+
f"{match[0]}: {reason}"
|
|
2535
|
+
for reason in M.review_evidence_problems(
|
|
2536
|
+
matrix_resolution, match[3]
|
|
2537
|
+
)
|
|
2538
|
+
)
|
|
2539
|
+
evidence_reviewer = match[3].get("reviewer_identity")
|
|
2540
|
+
if grant.get("reviewer_identity") != evidence_reviewer:
|
|
2541
|
+
reasons.append(
|
|
2542
|
+
"granted reviewer identity does not match the review artifact"
|
|
2543
|
+
)
|
|
2544
|
+
binding = (evidence_reviewer or {}).get("binding") \
|
|
2545
|
+
if isinstance(evidence_reviewer, dict) else None
|
|
2546
|
+
if grant.get("reviewer") != binding:
|
|
2547
|
+
reasons.append(
|
|
2548
|
+
"granted reviewer binding does not match the review artifact"
|
|
2549
|
+
)
|
|
2550
|
+
else:
|
|
2551
|
+
if strict and (
|
|
2552
|
+
grant.get("reviewer_identity") is not None
|
|
2553
|
+
or grant.get("reviewer") is not None
|
|
2554
|
+
):
|
|
2555
|
+
reasons.append("review-bypassed strict grant unexpectedly names a reviewer")
|
|
2556
|
+
from . import features as F
|
|
2557
|
+
if F.enabled(cfg, "review"):
|
|
2558
|
+
try:
|
|
2559
|
+
running = [item["id"] for item in A.board(root)["running"]]
|
|
2560
|
+
# The waiver the grant stood on is the one asked; the newest one open was, and a second
|
|
2561
|
+
# waiver opened for the slice since refused the grant the first had made (WAIVER-BOUND-2).
|
|
2562
|
+
waiver, notes = A.review_waiver_for(
|
|
2563
|
+
root, running, (candidate or {}).get("digest"), wanted=grant.get("waiver") or None
|
|
2564
|
+
)
|
|
2565
|
+
except Exception as exc:
|
|
2566
|
+
reasons.append(f"cannot validate the live review waiver: {exc}")
|
|
2567
|
+
else:
|
|
2568
|
+
if not waiver:
|
|
2569
|
+
reasons.append(
|
|
2570
|
+
"review is enabled and no matching running-slice waiver is open"
|
|
2571
|
+
+ (f" (the grant stood on {grant['waiver']})" if grant.get("waiver") else "")
|
|
2572
|
+
+ (f": {'; '.join(notes)}" if notes else "")
|
|
2573
|
+
)
|
|
2574
|
+
|
|
2575
|
+
try:
|
|
2576
|
+
drift = A.plan_drift(root)
|
|
2577
|
+
except Exception as exc:
|
|
2578
|
+
reasons.append(f"cannot validate plan integrity: {exc}")
|
|
2579
|
+
else:
|
|
2580
|
+
if drift:
|
|
2581
|
+
reasons.append(f"plan edited after admission: {', '.join(drift)}")
|
|
2582
|
+
try:
|
|
2583
|
+
held = A.hold_state(root)
|
|
2584
|
+
except Exception as exc:
|
|
2585
|
+
reasons.append(f"cannot validate project hold state: {exc}")
|
|
2586
|
+
else:
|
|
2587
|
+
if held:
|
|
2588
|
+
reasons.append(f"project is held by {held.get('by')}: {held.get('reason', '')}")
|
|
2589
|
+
try:
|
|
2590
|
+
urgent = A.urgent_messages(root, cfg)
|
|
2591
|
+
except Exception as exc:
|
|
2592
|
+
reasons.append(f"cannot validate urgent messages: {exc}")
|
|
2593
|
+
else:
|
|
2594
|
+
for message in urgent:
|
|
2595
|
+
reasons.append(
|
|
2596
|
+
f"urgent message unacknowledged: {message['id']} — {message['title']}"
|
|
2597
|
+
)
|
|
2598
|
+
|
|
2599
|
+
redirected = _commit_repository_binding(root)
|
|
2600
|
+
if redirected:
|
|
2601
|
+
reasons.append(redirected)
|
|
2602
|
+
|
|
2603
|
+
if reasons:
|
|
2604
|
+
print(f"{C['red']}{C['b']}COMMIT REFUSED{C['reset']}")
|
|
2605
|
+
for reason in reasons:
|
|
2606
|
+
print(f" {C['red']}·{C['reset']} {A.shown_text(reason)}")
|
|
2607
|
+
if enrollment["state"] == "legacy":
|
|
2608
|
+
print(f" {C['dim']}{enrollment['detail']}{C['reset']}")
|
|
2609
|
+
return 1
|
|
2610
|
+
|
|
2611
|
+
token = grant.get("token") or "recorded grant"
|
|
2612
|
+
print(f"{C['green']}{C['b']}AUTHORIZED{C['reset']} {candidate['index_tree']} · {token}")
|
|
2613
|
+
# polyctl commit names in its message the grant held to the index here, and no other (COMMIT-TRAILER).
|
|
2614
|
+
args.granted = grant
|
|
2615
|
+
return 0
|