git-finalizer 2.0.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.
@@ -0,0 +1,740 @@
1
+ # GF-INTEGRATION-ADAPTER: worktree-controller-retirement (single site: Controller retirement verify/authorize/complete client)
2
+ """Verify, authorize, CAS-delete, and complete/record branch retirements via Worktree Controller."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from datetime import UTC, datetime
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ from typing import Any
17
+ import uuid
18
+
19
+ from git_finalizer import __version__
20
+ from git_finalizer.errors import ErrorCode
21
+ from git_finalizer.git_io import FULL_OID_RE, clean_git_env, validate_remote_name
22
+ from git_finalizer.json_io import loads_unique
23
+
24
+ VERSION = __version__
25
+ COMMAND_TIMEOUT = 60.0
26
+ GIT_REMOTE_TIMEOUT = 120.0
27
+ PLAN_ID_RE = re.compile(r"^[0-9a-f]{64}$")
28
+ EXECUTOR_KINDS = ("local", "remote")
29
+ RETIREMENT_CONTRACT = "branch-retirement-execution/v1"
30
+ RETIREMENT_RESULT_CONTRACT = "retirement-execution-result/v1"
31
+
32
+
33
+ class RetirementBlocked(RuntimeError):
34
+ """Fail-closed blocker emitted before or around CAS retirement execution."""
35
+
36
+ def __init__(
37
+ self,
38
+ message: str,
39
+ *,
40
+ error_code: str = ErrorCode.RETIREMENT_BLOCKED,
41
+ next_action: str = "resolve_blocker_and_retry",
42
+ mutation_attempted: bool = False,
43
+ expected_oid_lease_bound: bool = False,
44
+ controller_complete: bool = False,
45
+ result_code: str | None = None,
46
+ receipt_id: str | None = None,
47
+ ) -> None:
48
+ self.error_code = error_code
49
+ self.next_action = next_action
50
+ self.mutation_attempted = mutation_attempted
51
+ self.expected_oid_lease_bound = expected_oid_lease_bound
52
+ self.controller_complete = controller_complete
53
+ self.result_code = result_code
54
+ self.receipt_id = receipt_id
55
+ super().__init__(message)
56
+
57
+
58
+ def git_run(
59
+ repo: Path,
60
+ *arguments: str,
61
+ mutation: bool = False,
62
+ timeout: float | None = None,
63
+ ) -> subprocess.CompletedProcess[str]:
64
+ eff_timeout = timeout or (GIT_REMOTE_TIMEOUT if mutation or "ls-remote" in arguments or "fetch" in arguments else COMMAND_TIMEOUT)
65
+ try:
66
+ return subprocess.run(
67
+ ["git", "-C", str(repo), *arguments],
68
+ capture_output=True,
69
+ text=True,
70
+ timeout=eff_timeout,
71
+ env=clean_git_env(),
72
+ close_fds=True,
73
+ check=False,
74
+ )
75
+ except (OSError, subprocess.SubprocessError) as exc:
76
+ raise RetirementBlocked(f"Git inspection failed: {exc}") from exc
77
+
78
+
79
+ def controller_program() -> str:
80
+ found = shutil.which("worktree-controller")
81
+ if not found:
82
+ raise RetirementBlocked(
83
+ "Worktree Controller is required for branch retirement",
84
+ error_code=ErrorCode.CONTROLLER_UNAVAILABLE,
85
+ )
86
+ return found
87
+
88
+
89
+ def controller_call(repo: Path, command: str, *arguments: str) -> dict[str, Any]:
90
+ program = controller_program()
91
+ try:
92
+ completed = subprocess.run(
93
+ [program, command, "--repo", str(repo), *arguments, "--json"],
94
+ capture_output=True,
95
+ text=True,
96
+ timeout=COMMAND_TIMEOUT,
97
+ close_fds=True,
98
+ check=False,
99
+ )
100
+ except (OSError, subprocess.SubprocessError) as exc:
101
+ raise RetirementBlocked(
102
+ f"Controller {command} refused or failed: {exc}",
103
+ error_code=ErrorCode.CONTROLLER_UNAVAILABLE,
104
+ ) from exc
105
+ if completed.returncode != 0 or not completed.stdout.strip():
106
+ raise RetirementBlocked(
107
+ f"Controller {command} refused or failed",
108
+ error_code=ErrorCode.CONTROLLER_UNAVAILABLE,
109
+ )
110
+ try:
111
+ payload = loads_unique(completed.stdout)
112
+ except (ValueError, UnicodeDecodeError) as exc:
113
+ raise RetirementBlocked("Controller returned invalid JSON") from exc
114
+ if not isinstance(payload, dict) or payload.get("errors"):
115
+ raise RetirementBlocked("Controller returned invalid or error payload")
116
+ decision = payload.get("decision")
117
+ if not isinstance(decision, dict):
118
+ raise RetirementBlocked("Controller decision missing")
119
+ return decision
120
+
121
+
122
+ def check_controller_namespace(repo: Path) -> None:
123
+ """Block branch retirement if repository retains legacy `codex-worktree` metadata without `worktree-controller/v1`."""
124
+ res = git_run(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")
125
+ if res.returncode != 0:
126
+ return
127
+ common_dir = Path(res.stdout.strip())
128
+ if (common_dir / "codex-worktree" / "v1").is_dir() and not (common_dir / "worktree-controller" / "v1").is_dir():
129
+ raise RetirementBlocked(
130
+ "检测到 legacy codex-worktree namespace;retirement 需先经 WC 治理激活 worktree-controller/v1"
131
+ )
132
+
133
+
134
+ def verify_capabilities(repo: Path) -> None:
135
+ check_controller_namespace(repo)
136
+ decision = controller_call(repo, "capabilities")
137
+ for key in (
138
+ "branch_retirement_version",
139
+ "branch_retirement_verify_version",
140
+ "branch_retirement_execution_version",
141
+ ):
142
+ value = decision.get(key)
143
+ if type(value) is not int or value < 1:
144
+ raise RetirementBlocked(
145
+ f"Controller lacks required public retirement protocols ({key})"
146
+ )
147
+
148
+
149
+ def normalize_integrated_ref(integrated_into: str, remote: str) -> str:
150
+ if integrated_into.startswith(("refs/heads/", "refs/remotes/")):
151
+ return integrated_into
152
+ if integrated_into.startswith(f"{remote}/"):
153
+ return f"refs/remotes/{integrated_into}"
154
+ return f"refs/remotes/{remote}/{integrated_into}"
155
+
156
+
157
+ def request_id(arguments: argparse.Namespace) -> str:
158
+ return str(
159
+ uuid.uuid5(
160
+ uuid.NAMESPACE_URL,
161
+ f"git-finalizer-retirement/{arguments.plan_id}/{arguments.operation}",
162
+ )
163
+ )
164
+
165
+
166
+ def current_holder() -> dict[str, Any]:
167
+ pid = os.getpid()
168
+ stat_path = Path(f"/proc/{pid}/stat")
169
+ boot_path = Path("/proc/sys/kernel/random/boot_id")
170
+ if stat_path.is_file() and boot_path.is_file():
171
+ raw = stat_path.read_text(encoding="ascii")
172
+ start_ticks = int(raw[raw.rfind(")") + 2 :].split()[19])
173
+ boot_id = boot_path.read_text(encoding="ascii").strip()
174
+ return {"pid": pid, "start_ticks": start_ticks, "boot_id": boot_id}
175
+ return {"pid": pid}
176
+
177
+
178
+ def holder_alive(holder: Any) -> bool:
179
+ if not isinstance(holder, dict):
180
+ return False
181
+ pid = holder.get("pid")
182
+ if type(pid) is not int or pid <= 0:
183
+ return False
184
+ stat_path = Path(f"/proc/{pid}/stat")
185
+ boot_path = Path("/proc/sys/kernel/random/boot_id")
186
+ if stat_path.is_file() and boot_path.is_file():
187
+ boot_id_expected = holder.get("boot_id")
188
+ start_ticks_expected = holder.get("start_ticks")
189
+ if type(start_ticks_expected) is not int or start_ticks_expected <= 0:
190
+ return False
191
+ try:
192
+ boot_id = boot_path.read_text(encoding="ascii").strip()
193
+ if boot_id_expected != boot_id:
194
+ return False
195
+ raw = stat_path.read_text(encoding="ascii")
196
+ ticks = int(raw[raw.rfind(")") + 2 :].split()[19])
197
+ return ticks == start_ticks_expected
198
+ except (OSError, ValueError, IndexError):
199
+ return False
200
+ try:
201
+ os.kill(pid, 0)
202
+ return True
203
+ except ProcessLookupError:
204
+ return False
205
+ except PermissionError:
206
+ return True
207
+
208
+
209
+ def _validate_holder_shape(holder: Any) -> None:
210
+ if not isinstance(holder, dict) or type(holder.get("pid")) is not int or holder["pid"] <= 0:
211
+ raise RetirementBlocked("invalid execution holder identity")
212
+ if (
213
+ Path(f"/proc/{holder['pid']}").parent.exists()
214
+ and "start_ticks" in holder
215
+ and (
216
+ type(holder.get("start_ticks")) is not int
217
+ or holder["start_ticks"] <= 0
218
+ or not isinstance(holder.get("boot_id"), str)
219
+ )
220
+ ):
221
+ raise RetirementBlocked("invalid Linux execution holder metadata")
222
+
223
+
224
+ def identity_matches(
225
+ arguments: argparse.Namespace,
226
+ doc: dict[str, Any],
227
+ *,
228
+ grant: bool = False,
229
+ status_only: bool = False,
230
+ check_expiry: bool = True,
231
+ ) -> None:
232
+ if status_only:
233
+ if type(doc.get("schema_version")) is not int or doc["schema_version"] != 1:
234
+ raise RetirementBlocked("Controller plan status schema_version mismatch")
235
+ if (
236
+ doc.get("plan_id") != arguments.plan_id
237
+ or doc.get("branch") != arguments.branch
238
+ or doc.get("remote") != arguments.remote
239
+ or doc.get("expected_oid") != arguments.expected_oid
240
+ ):
241
+ raise RetirementBlocked("Controller retirement identity differs")
242
+ expected_int = normalize_integrated_ref(arguments.integrated_into, arguments.remote)
243
+ if doc.get("integrated_ref") != expected_int:
244
+ raise RetirementBlocked(
245
+ f"Controller plan integration ref differs: {doc.get('integrated_ref')} != {expected_int}"
246
+ )
247
+ exp_int_oid = doc.get("expected_integrated_oid")
248
+ if not isinstance(exp_int_oid, str) or FULL_OID_RE.fullmatch(exp_int_oid) is None:
249
+ raise RetirementBlocked("Controller retirement identity differs (expected_integrated_oid invalid)")
250
+ if arguments.expected_integrated_oid and exp_int_oid != arguments.expected_integrated_oid:
251
+ raise RetirementBlocked("Controller retirement identity differs (expected_integrated_oid)")
252
+ return
253
+ if grant:
254
+ if type(doc.get("schema_version")) is not int or doc["schema_version"] != 1:
255
+ raise RetirementBlocked("authorization schema_version mismatch")
256
+ if doc.get("contract") != RETIREMENT_CONTRACT:
257
+ raise RetirementBlocked("authorization contract mismatch")
258
+ if doc.get("plan_id") != arguments.plan_id or doc.get("operation") != arguments.operation:
259
+ raise RetirementBlocked("authorization plan/operation mismatch")
260
+ if doc.get("branch") != arguments.branch:
261
+ raise RetirementBlocked("authorization branch mismatch")
262
+ if doc.get("expected_oid") != arguments.expected_oid or doc.get("expected_integrated_oid") != arguments.expected_integrated_oid:
263
+ raise RetirementBlocked("authorization OID mismatch")
264
+ expected_ref = (
265
+ f"refs/heads/{arguments.branch}"
266
+ if arguments.operation == "local"
267
+ else f"refs/remotes/{arguments.remote}/{arguments.branch}"
268
+ )
269
+ if doc.get("ref") != expected_ref:
270
+ raise RetirementBlocked("authorization ref mismatch")
271
+ expected_int = normalize_integrated_ref(arguments.integrated_into, arguments.remote)
272
+ if doc.get("integrated_ref") != expected_int:
273
+ raise RetirementBlocked(f"authorization integrated_ref mismatch: {doc.get('integrated_ref')}")
274
+ exp_raw = doc.get("expires_at")
275
+ if not isinstance(exp_raw, str):
276
+ raise RetirementBlocked("authorization expires_at missing")
277
+ try:
278
+ expired = datetime.fromisoformat(exp_raw).astimezone(UTC) <= datetime.now(UTC)
279
+ if check_expiry and expired:
280
+ raise RetirementBlocked("authorization grant has expired")
281
+ except ValueError as exc:
282
+ raise RetirementBlocked("authorization expires_at malformed") from exc
283
+ _validate_holder_shape(doc.get("holder"))
284
+ else:
285
+ rid = doc.get("receipt_id")
286
+ if not isinstance(rid, str) or PLAN_ID_RE.fullmatch(rid) is None:
287
+ raise RetirementBlocked("Controller receipt_id is invalid")
288
+ if (
289
+ doc.get("plan_id") != arguments.plan_id
290
+ or doc.get("operation") != arguments.operation
291
+ or doc.get("branch") != arguments.branch
292
+ or doc.get("expected_oid") != arguments.expected_oid
293
+ or doc.get("expected_integrated_oid") != arguments.expected_integrated_oid
294
+ ):
295
+ raise RetirementBlocked("Controller receipt identity mismatch")
296
+
297
+
298
+ def _ref_present(repo: Path, arguments: argparse.Namespace) -> bool:
299
+ if arguments.operation == "local":
300
+ completed = git_run(repo, "show-ref", "--verify", "--quiet", "--", f"refs/heads/{arguments.branch}")
301
+ if completed.returncode == 1:
302
+ return False
303
+ if completed.returncode != 0:
304
+ raise RetirementBlocked("unable to verify local branch ref cleanly")
305
+ return True
306
+ ref = f"refs/heads/{arguments.branch}"
307
+ completed = git_run(repo, "ls-remote", "--heads", "--", arguments.remote, ref)
308
+ if completed.returncode != 0:
309
+ raise RetirementBlocked(
310
+ "unable to query remote branch ref cleanly",
311
+ next_action="inspect_remote_state_then_rerun_same_retirement",
312
+ )
313
+ return bool(completed.stdout.strip())
314
+
315
+
316
+ def preflight(arguments: argparse.Namespace) -> dict[str, Any]:
317
+ repo = Path(arguments.repo).resolve()
318
+ status = controller_call(
319
+ repo,
320
+ "branch-retirement-status",
321
+ "--plan-id",
322
+ arguments.plan_id,
323
+ )
324
+ if str(status.get("code") or "") == "BRANCH_RETIREMENT_DRIFTED":
325
+ raise RetirementBlocked("Controller retirement verdict blocks: plan is stale; create a fresh plan")
326
+ current = status.get("current")
327
+ if not isinstance(current, dict):
328
+ raise RetirementBlocked("Controller branch-retirement-status returned invalid current payload")
329
+ identity_matches(arguments, current, status_only=True)
330
+
331
+ decision = controller_call(
332
+ repo,
333
+ "branch-retirement-verify",
334
+ "--plan-id",
335
+ arguments.plan_id,
336
+ "--operation",
337
+ arguments.operation,
338
+ )
339
+ code = str(decision.get("code") or "")
340
+ blockers = decision.get("blockers") or []
341
+ if code == "BRANCH_RETIREMENT_DRIFTED":
342
+ raise RetirementBlocked("Controller retirement verdict blocks: plan is stale; create a fresh plan")
343
+ reval = decision.get("minimum_revalidation")
344
+ if isinstance(reval, dict):
345
+ expected_int = normalize_integrated_ref(arguments.integrated_into, arguments.remote)
346
+ if (
347
+ reval.get("plan_id") != arguments.plan_id
348
+ or reval.get("operation") != arguments.operation
349
+ or reval.get("branch") != arguments.branch
350
+ or reval.get("expected_oid") != arguments.expected_oid
351
+ or reval.get("integrated_ref") != expected_int
352
+ or (
353
+ arguments.expected_integrated_oid
354
+ and reval.get("expected_integrated_oid") != arguments.expected_integrated_oid
355
+ )
356
+ ):
357
+ raise RetirementBlocked("Controller retirement identity differs (minimum_revalidation)")
358
+ elif code == "RETIREMENT_EXECUTABLE":
359
+ raise RetirementBlocked("Controller branch-retirement-verify missing minimum_revalidation")
360
+ if code == "RETIREMENT_OPERATION_COMPLETE" and (
361
+ not isinstance(reval, dict) or reval.get("ref_state") != "ABSENT"
362
+ ):
363
+ raise RetirementBlocked("Controller already records a consumed receipt while its ref remains")
364
+ if code in {"RETIREMENT_EXECUTABLE", "RETIREMENT_OPERATION_COMPLETE"} and not blockers:
365
+ return decision
366
+ if code == "RETIREMENT_BLOCKED" and blockers == ["ABSENT_UNATTESTED"]:
367
+ return decision
368
+ if (
369
+ getattr(arguments, "recover", False)
370
+ and "RETIREMENT_AUTHORIZATION_ACTIVE" in blockers
371
+ and set(blockers) <= {"RETIREMENT_AUTHORIZATION_ACTIVE", "ABSENT_UNATTESTED"}
372
+ ):
373
+ return decision
374
+ raise RetirementBlocked(f"Controller retirement verdict blocks ({code}; blockers={blockers})")
375
+
376
+
377
+ def _write_result_file(directory: Path, payload: dict[str, Any]) -> Path:
378
+ path = directory / "result.json"
379
+ path.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")
380
+ return path
381
+
382
+
383
+ def _complete_authorization(
384
+ repo: Path,
385
+ arguments: argparse.Namespace,
386
+ grant: dict[str, Any],
387
+ *,
388
+ outcome: str,
389
+ progress: dict[str, Any],
390
+ ) -> dict[str, Any]:
391
+ result_doc = {
392
+ "schema_version": 1,
393
+ "contract": RETIREMENT_RESULT_CONTRACT,
394
+ "plan_id": arguments.plan_id,
395
+ "operation": arguments.operation,
396
+ "kind": "CAS_DELETE",
397
+ "outcome": outcome,
398
+ "ref": grant["ref"],
399
+ "expected_oid": arguments.expected_oid,
400
+ "integrated_ref": grant["integrated_ref"],
401
+ "expected_integrated_oid": arguments.expected_integrated_oid,
402
+ "executor": {"name": "git-finalizer", "version": VERSION},
403
+ }
404
+ with tempfile.TemporaryDirectory(prefix="gf-retire-res-") as temporary:
405
+ result_file = _write_result_file(Path(temporary), result_doc)
406
+ resp = controller_call(
407
+ repo,
408
+ "branch-retirement-complete",
409
+ "--authorization-id",
410
+ str(grant["authorization_id"]),
411
+ "--token",
412
+ str(grant.get("token", "")),
413
+ "--result-file",
414
+ str(result_file),
415
+ )
416
+ code = resp.get("code")
417
+ if code == "RETIREMENT_EXECUTION_ABORTED":
418
+ raise RetirementBlocked(
419
+ "Controller aborted retirement execution because ref remained present",
420
+ mutation_attempted=bool(progress.get("mutation_attempted")),
421
+ expected_oid_lease_bound=bool(progress.get("expected_oid_lease_bound")),
422
+ )
423
+ if code != "RETIREMENT_EXECUTION_COMPLETE":
424
+ raise RetirementBlocked(
425
+ f"Controller refused completion (authorization {grant['authorization_id']}, {code})",
426
+ mutation_attempted=bool(progress.get("mutation_attempted")),
427
+ expected_oid_lease_bound=bool(progress.get("expected_oid_lease_bound")),
428
+ result_code="LOCAL_DELETE_UNVERIFIED" if arguments.operation == "local" else "REMOTE_DELETE_UNVERIFIED",
429
+ )
430
+ receipt = resp.get("receipt")
431
+ if not isinstance(receipt, dict):
432
+ raise RetirementBlocked(
433
+ "Controller completion missing receipt",
434
+ mutation_attempted=bool(progress.get("mutation_attempted")),
435
+ expected_oid_lease_bound=bool(progress.get("expected_oid_lease_bound")),
436
+ )
437
+ identity_matches(arguments, receipt, grant=False)
438
+ return receipt
439
+
440
+
441
+ def execute(
442
+ arguments: argparse.Namespace,
443
+ *,
444
+ progress: dict[str, Any] | None = None,
445
+ ) -> dict[str, Any]:
446
+ repo = Path(arguments.repo).resolve()
447
+ validate_remote_name(arguments.remote)
448
+ if PLAN_ID_RE.fullmatch(arguments.plan_id) is None:
449
+ raise RetirementBlocked("plan-id 必须是 64 位小写十六进制", error_code=ErrorCode.CLI_INVALID_ARGS)
450
+ for val, label in (
451
+ (arguments.expected_oid, "expected-oid"),
452
+ (arguments.expected_integrated_oid, "expected-integrated-oid"),
453
+ ):
454
+ if FULL_OID_RE.fullmatch(val) is None:
455
+ raise RetirementBlocked(f"{label} 必须是完整 OID", error_code=ErrorCode.CLI_INVALID_ARGS)
456
+
457
+ prog = progress if progress is not None else {
458
+ "mutation_attempted": False,
459
+ "controller_complete": False,
460
+ "authorization_id": None,
461
+ "expected_oid_lease_bound": False,
462
+ }
463
+ req_id = request_id(arguments)
464
+
465
+ holder_arg = f"ancestor:{Path(sys.executable).resolve(strict=True).name}"
466
+ auth = controller_call(
467
+ repo,
468
+ "branch-retirement-authorize",
469
+ "--plan-id",
470
+ arguments.plan_id,
471
+ "--operation",
472
+ arguments.operation,
473
+ "--request-id",
474
+ req_id,
475
+ "--holder",
476
+ holder_arg,
477
+ "--client-id",
478
+ "git-finalizer",
479
+ "--run-id",
480
+ req_id,
481
+ )
482
+ auth_code = str(auth.get("code") or "")
483
+ grant = auth.get("authorization")
484
+
485
+ if auth_code == "RETIREMENT_AUTHORIZED" and isinstance(grant, dict):
486
+ # Validate holder shape before deciding foreign/dead abandonment.
487
+ _validate_holder_shape(grant.get("holder"))
488
+ # Detect replay/previous unfinished execution with another holder!
489
+ if grant.get("holder") != current_holder() and _holder_is_foreign(grant.get("holder")):
490
+ if holder_alive(grant.get("holder")):
491
+ raise RetirementBlocked("Controller retirement verdict blocks: another retirement executor is active")
492
+ if _ref_present(repo, arguments):
493
+ controller_call(
494
+ repo,
495
+ "branch-retirement-executions",
496
+ "--action",
497
+ "abandon",
498
+ "--authorization-id",
499
+ str(grant["authorization_id"]),
500
+ "--token",
501
+ str(grant.get("token", "")),
502
+ "--reason",
503
+ "stale dead executor",
504
+ )
505
+ auth = controller_call(
506
+ repo,
507
+ "branch-retirement-authorize",
508
+ "--plan-id",
509
+ arguments.plan_id,
510
+ "--operation",
511
+ arguments.operation,
512
+ "--request-id",
513
+ req_id,
514
+ "--holder",
515
+ holder_arg,
516
+ "--client-id",
517
+ "git-finalizer",
518
+ "--run-id",
519
+ req_id,
520
+ )
521
+ if auth.get("code") != "RETIREMENT_AUTHORIZED" or not isinstance(auth.get("authorization"), dict):
522
+ raise RetirementBlocked("Controller retirement verdict blocks after abandoning stale execution")
523
+ grant = auth["authorization"]
524
+ else:
525
+ identity_matches(arguments, grant, grant=True, check_expiry=False)
526
+ receipt = _complete_authorization(
527
+ repo, arguments, grant, outcome="REF_ALREADY_ABSENT", progress=prog
528
+ )
529
+ prog["controller_complete"] = True
530
+ prog["receipt_id"] = receipt["receipt_id"]
531
+ return {
532
+ "result": "ALREADY_ABSENT_VERIFIED",
533
+ "receipt_id": str(receipt["receipt_id"]),
534
+ "mutation_attempted": False,
535
+ "controller_complete": True,
536
+ "expected_oid_lease_bound": False,
537
+ }
538
+
539
+ present = _ref_present(repo, arguments)
540
+ identity_matches(arguments, grant, grant=True, check_expiry=present)
541
+ if not present:
542
+ receipt = _complete_authorization(
543
+ repo, arguments, grant, outcome="REF_ALREADY_ABSENT", progress=prog
544
+ )
545
+ prog["controller_complete"] = True
546
+ prog["receipt_id"] = receipt["receipt_id"]
547
+ return {
548
+ "result": "ALREADY_ABSENT_VERIFIED",
549
+ "receipt_id": str(receipt["receipt_id"]),
550
+ "mutation_attempted": False,
551
+ "controller_complete": True,
552
+ "expected_oid_lease_bound": False,
553
+ }
554
+
555
+ prog["mutation_attempted"] = True
556
+ prog["expected_oid_lease_bound"] = True
557
+ prog["authorization_id"] = grant["authorization_id"]
558
+ if arguments.operation == "local":
559
+ del_res = git_run(repo, "update-ref", "-d", str(grant["ref"]), str(grant["expected_oid"]), mutation=True)
560
+ if del_res.returncode != 0:
561
+ _complete_authorization(repo, arguments, grant, outcome="REF_STILL_PRESENT", progress=prog)
562
+ raise RetirementBlocked(
563
+ "local CAS delete failed",
564
+ mutation_attempted=True,
565
+ expected_oid_lease_bound=True,
566
+ )
567
+ else:
568
+ del_res = git_run(
569
+ repo,
570
+ "push",
571
+ "--no-follow-tags",
572
+ "--no-verify",
573
+ f"--force-with-lease=refs/heads/{arguments.branch}:{grant['expected_oid']}",
574
+ "--",
575
+ arguments.remote,
576
+ f":refs/heads/{arguments.branch}",
577
+ mutation=True,
578
+ )
579
+ if del_res.returncode != 0:
580
+ raise RetirementBlocked(
581
+ "remote CAS delete failed or uncertain",
582
+ next_action="inspect_remote_state_then_rerun_same_retirement",
583
+ mutation_attempted=True,
584
+ expected_oid_lease_bound=True,
585
+ )
586
+ fetch_res = git_run(
587
+ repo,
588
+ "fetch",
589
+ "--prune",
590
+ "--",
591
+ arguments.remote,
592
+ f"+refs/heads/*:refs/remotes/{arguments.remote}/*",
593
+ )
594
+ if fetch_res.returncode != 0:
595
+ raise RetirementBlocked(
596
+ "remote fetch/prune failed after retirement",
597
+ next_action="inspect_remote_state_then_rerun_same_retirement",
598
+ mutation_attempted=True,
599
+ expected_oid_lease_bound=True,
600
+ )
601
+
602
+ if _ref_present(repo, arguments):
603
+ fail_code = "LOCAL_DELETE_UNVERIFIED" if arguments.operation == "local" else "REMOTE_DELETE_UNVERIFIED"
604
+ raise RetirementBlocked(
605
+ "branch ref still exists after CAS delete",
606
+ result_code=fail_code,
607
+ mutation_attempted=True,
608
+ expected_oid_lease_bound=True,
609
+ )
610
+ receipt = _complete_authorization(
611
+ repo, arguments, grant, outcome="REF_REMOVED_AT_EXPECTED_OID", progress=prog
612
+ )
613
+ prog["controller_complete"] = True
614
+ prog["receipt_id"] = receipt["receipt_id"]
615
+ return {
616
+ "result": "LOCAL_BRANCH_RETIRED_VERIFIED" if arguments.operation == "local" else "REMOTE_BRANCH_RETIRED_VERIFIED",
617
+ "receipt_id": str(receipt["receipt_id"]),
618
+ "mutation_attempted": True,
619
+ "controller_complete": True,
620
+ "expected_oid_lease_bound": True,
621
+ }
622
+
623
+ # Not authorized directly: check verify / already completed / unattested absence.
624
+ verify_dec = controller_call(
625
+ repo,
626
+ "branch-retirement-verify",
627
+ "--plan-id",
628
+ arguments.plan_id,
629
+ "--operation",
630
+ arguments.operation,
631
+ )
632
+ receipt = verify_dec.get("receipt")
633
+ ref_exists = _ref_present(repo, arguments)
634
+ if isinstance(receipt, dict) and receipt:
635
+ identity_matches(arguments, receipt, grant=False)
636
+ if ref_exists:
637
+ raise RetirementBlocked(
638
+ "Controller already records a consumed receipt while the Git ref is still present"
639
+ )
640
+ prog["controller_complete"] = True
641
+ prog["receipt_id"] = receipt["receipt_id"]
642
+ return {
643
+ "result": "ALREADY_ABSENT_VERIFIED",
644
+ "receipt_id": str(receipt["receipt_id"]),
645
+ "mutation_attempted": False,
646
+ "controller_complete": True,
647
+ "expected_oid_lease_bound": False,
648
+ }
649
+
650
+ blockers = auth.get("blockers") or verify_dec.get("blockers") or []
651
+ if not ref_exists and "ABSENT_UNATTESTED" in blockers:
652
+ record_doc = {
653
+ "schema_version": 1,
654
+ "contract": RETIREMENT_RESULT_CONTRACT,
655
+ "plan_id": arguments.plan_id,
656
+ "operation": arguments.operation,
657
+ "kind": "ATTEST_ABSENT",
658
+ "outcome": "REF_ALREADY_ABSENT",
659
+ "ref": (
660
+ f"refs/heads/{arguments.branch}"
661
+ if arguments.operation == "local"
662
+ else f"refs/remotes/{arguments.remote}/{arguments.branch}"
663
+ ),
664
+ "expected_oid": arguments.expected_oid,
665
+ "integrated_ref": normalize_integrated_ref(arguments.integrated_into, arguments.remote),
666
+ "expected_integrated_oid": arguments.expected_integrated_oid,
667
+ "executor": {"name": "git-finalizer", "version": VERSION},
668
+ }
669
+ with tempfile.TemporaryDirectory(prefix="gf-retire-rec-") as temporary:
670
+ rfile = _write_result_file(Path(temporary), record_doc)
671
+ rec = controller_call(
672
+ repo,
673
+ "branch-retirement-record",
674
+ "--plan-id",
675
+ arguments.plan_id,
676
+ "--operation",
677
+ arguments.operation,
678
+ "--result-file",
679
+ str(rfile),
680
+ )
681
+ rec_receipt = rec.get("receipt")
682
+ if rec.get("code") != "BRANCH_RETIREMENT_RESULT_RECORDED" or not isinstance(rec_receipt, dict):
683
+ raise RetirementBlocked("Controller refused recording absent branch")
684
+ identity_matches(arguments, rec_receipt, grant=False)
685
+ prog["controller_complete"] = True
686
+ prog["receipt_id"] = rec_receipt["receipt_id"]
687
+ return {
688
+ "result": "ALREADY_ABSENT_VERIFIED",
689
+ "receipt_id": str(rec_receipt["receipt_id"]),
690
+ "mutation_attempted": False,
691
+ "controller_complete": True,
692
+ "expected_oid_lease_bound": False,
693
+ }
694
+
695
+ raise RetirementBlocked(f"Controller retirement verdict blocks ({auth_code}; blockers={blockers})")
696
+
697
+
698
+ def _holder_is_foreign(holder: Any) -> bool:
699
+ if not isinstance(holder, dict):
700
+ return True
701
+ cur = current_holder()
702
+ return holder.get("pid") != cur.get("pid") or (
703
+ "start_ticks" in cur and holder.get("start_ticks") != cur.get("start_ticks")
704
+ )
705
+
706
+
707
+ def run_cli(arguments: argparse.Namespace) -> dict[str, Any]:
708
+ verify_capabilities(Path(arguments.repo).resolve())
709
+ preflight(arguments)
710
+ return execute(arguments)
711
+
712
+
713
+ def build_parser() -> argparse.ArgumentParser:
714
+ parser = argparse.ArgumentParser(prog="git-finalize-retirement")
715
+ parser.add_argument("--repo", required=True)
716
+ parser.add_argument("--plan-id", required=True)
717
+ parser.add_argument("--operation", choices=EXECUTOR_KINDS, required=True)
718
+ parser.add_argument("--branch", required=True)
719
+ parser.add_argument("--remote", default="origin")
720
+ parser.add_argument("--integrated-into", default="main")
721
+ parser.add_argument("--expected-oid", required=True)
722
+ parser.add_argument("--expected-integrated-oid", required=True)
723
+ parser.add_argument("--recover", action="store_true", default=True)
724
+ return parser
725
+
726
+
727
+ def main(argv: list[str] | None = None) -> int:
728
+ parser = build_parser()
729
+ arguments = parser.parse_args(argv)
730
+ try:
731
+ outcome = run_cli(arguments)
732
+ print(json.dumps(outcome, ensure_ascii=False, sort_keys=True))
733
+ return 0
734
+ except RetirementBlocked as exc:
735
+ print(f"retirement plan validation blocked: {exc}", file=sys.stderr)
736
+ raise SystemExit(1) from None
737
+
738
+
739
+ if __name__ == "__main__":
740
+ raise SystemExit(main())