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,547 @@
1
+ # GF-INTEGRATION-ADAPTER: worktree-controller-integration-publication (single site: Controller publication session & lease-bound push verification)
2
+ """Execute lease-bound integration candidate publication through Worktree Controller's public session protocol."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from contextlib import suppress
8
+ from datetime import UTC, datetime
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import select
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ from typing import Any
19
+
20
+ from git_finalizer import __version__
21
+ from git_finalizer.errors import ErrorCode
22
+ from git_finalizer.json_io import loads_unique
23
+
24
+ SUMMARY_SCHEMA_VERSION = 1
25
+ VERSION = __version__
26
+ MODE = "integration_candidate_publish"
27
+ CONTRACT = "integration-publication-session/v1"
28
+ FULL_OID_RE = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$")
29
+ LINE_BYTES = 16 * 1024
30
+ RESPONSE_TIMEOUT_SECONDS = 30.0
31
+ GIT_LOCAL_TIMEOUT = 30.0
32
+ GIT_REMOTE_TIMEOUT = 120.0
33
+ NEXT_ACTION = "read_remote_fact_and_reenter_controller_publish_gate"
34
+
35
+
36
+ class PublishError(RuntimeError):
37
+ """Fail-closed publication blocker preserving attempted remote state."""
38
+
39
+ def __init__(
40
+ self,
41
+ message: str,
42
+ *,
43
+ error_code: str = ErrorCode.INTEGRATION_PUBLISH_BLOCKED,
44
+ exit_code: int = 1,
45
+ next_action: str = NEXT_ACTION,
46
+ final_phase: str | None = None,
47
+ ) -> None:
48
+ self.error_code = error_code
49
+ self.exit_code = exit_code
50
+ self.next_action = next_action
51
+ self.final_phase = final_phase
52
+ super().__init__(message)
53
+
54
+
55
+ class PublicationProgress:
56
+ """Structured progress receipt distinguishing blocked vs remote-attempted state."""
57
+
58
+ def __init__(self, *, candidate_oid: str, lease_id: str, run_id: str) -> None:
59
+ self.phase = "preflight"
60
+ self.candidate_oid = candidate_oid
61
+ self.lease_id = lease_id
62
+ self.run_id = run_id
63
+ self.identity: dict[str, Any] | None = None
64
+ self.repository_id: str | None = None
65
+ self.allocation_id: str | None = None
66
+ self.target_ref: str | None = None
67
+ self.expected_main_oid: str | None = None
68
+ self.remote: str | None = None
69
+ self.mutation_attempted = False
70
+ self.push_returncode: int | None = None
71
+ self.remote_verified = False
72
+ self.remote_oid: str | None = None
73
+ self.controller_completed = False
74
+ self.record_id: str | None = None
75
+
76
+ def to_dict(self) -> dict[str, Any]:
77
+ return {
78
+ "schema_version": 1,
79
+ "phase": self.phase,
80
+ "candidate_oid": self.candidate_oid,
81
+ "lease_id": self.lease_id,
82
+ "run_id": self.run_id,
83
+ "identity": self.identity,
84
+ "repository_id": self.repository_id,
85
+ "allocation_id": self.allocation_id,
86
+ "target_ref": self.target_ref,
87
+ "expected_main_oid": self.expected_main_oid,
88
+ "remote": self.remote,
89
+ "mutation_attempted": self.mutation_attempted,
90
+ "push_returncode": self.push_returncode,
91
+ "remote_verified": self.remote_verified,
92
+ "remote_oid": self.remote_oid,
93
+ "controller_completed": self.controller_completed,
94
+ "record_id": self.record_id,
95
+ }
96
+
97
+
98
+ def run_git(repo: Path, *arguments: str, timeout: float = GIT_LOCAL_TIMEOUT) -> subprocess.CompletedProcess[str]:
99
+ env = dict(os.environ)
100
+ env["LC_ALL"] = "C"
101
+ env["GIT_TERMINAL_PROMPT"] = "0"
102
+ env["GIT_OPTIONAL_LOCKS"] = "0"
103
+ return subprocess.run(
104
+ ["git", "-C", str(repo), *arguments],
105
+ capture_output=True,
106
+ text=True,
107
+ timeout=timeout,
108
+ env=env,
109
+ close_fds=True,
110
+ check=False,
111
+ )
112
+
113
+
114
+ def controller_program() -> str:
115
+ found = shutil.which("worktree-controller")
116
+ if not found:
117
+ raise PublishError("Worktree Controller is required for integration candidate publication")
118
+ return found
119
+
120
+
121
+ def validate_oid(value: str, label: str) -> str:
122
+ if FULL_OID_RE.fullmatch(value) is None:
123
+ raise PublishError(f"invalid {label}: {value!r}")
124
+ return value
125
+
126
+
127
+ def validate_safe_remote(remote: str) -> str:
128
+ if not remote or remote.startswith("-") or any(c.isspace() for c in remote) or ".." in remote:
129
+ raise PublishError(f"Controller publication identity invalid remote name: {remote!r}")
130
+ return remote
131
+
132
+
133
+ def validate_target_ref(target_ref: str) -> str:
134
+ if not target_ref.startswith("refs/heads/") or len(target_ref) <= len("refs/heads/") or ".." in target_ref:
135
+ raise PublishError(f"unsupported target ref: {target_ref!r}")
136
+ return target_ref
137
+
138
+
139
+ def verify_controller_capabilities(controller: str, repo: Path) -> None:
140
+ try:
141
+ completed = subprocess.run(
142
+ [controller, "capabilities", "--repo", str(repo), "--json"],
143
+ capture_output=True,
144
+ text=True,
145
+ timeout=RESPONSE_TIMEOUT_SECONDS,
146
+ close_fds=True,
147
+ check=False,
148
+ )
149
+ except (OSError, subprocess.SubprocessError) as exc:
150
+ raise PublishError(f"Controller capabilities failed: {exc}") from exc
151
+ if completed.returncode != 0:
152
+ raise PublishError("Controller capabilities refused or failed")
153
+ try:
154
+ payload = loads_unique(completed.stdout)
155
+ except (ValueError, UnicodeDecodeError) as exc:
156
+ raise PublishError("Controller capabilities returned invalid JSON") from exc
157
+ decision = payload.get("decision") if isinstance(payload, dict) else None
158
+ if not isinstance(decision, dict):
159
+ raise PublishError("Controller capabilities verdict is invalid")
160
+ if payload.get("errors") not in (None, []):
161
+ raise PublishError("Controller capabilities returned errors")
162
+ cap_ver = decision.get("integration_publication_execution_version")
163
+ if type(cap_ver) is not int or cap_ver != 1:
164
+ raise PublishError("Controller lacks required public integration publication protocol")
165
+
166
+
167
+ class ControllerChannel:
168
+ """Bounded line-oriented JSON-line session speaking integration-publication-session/v1."""
169
+
170
+ def __init__(self, controller: str, repo: Path, candidate_oid: str, lease_id: str, run_id: str) -> None:
171
+ self.process = subprocess.Popen(
172
+ [
173
+ controller,
174
+ "publication-execution-session",
175
+ "--repo",
176
+ str(repo),
177
+ "--candidate-oid",
178
+ candidate_oid,
179
+ "--lease-id",
180
+ lease_id,
181
+ "--run-id",
182
+ run_id,
183
+ "--json",
184
+ ],
185
+ stdin=subprocess.PIPE,
186
+ stdout=subprocess.PIPE,
187
+ stderr=subprocess.DEVNULL,
188
+ text=False,
189
+ close_fds=True,
190
+ )
191
+
192
+ def close(self) -> None:
193
+ if self.process.stdin and not self.process.stdin.closed:
194
+ with suppress(OSError):
195
+ self.process.stdin.close()
196
+ if self.process.poll() is None:
197
+ try:
198
+ self.process.wait(timeout=5.0)
199
+ except subprocess.TimeoutExpired:
200
+ self.process.terminate()
201
+ try:
202
+ self.process.wait(timeout=2.0)
203
+ except subprocess.TimeoutExpired:
204
+ self.process.kill()
205
+ self.process.wait(timeout=2.0)
206
+ for stream in (self.process.stdout, self.process.stderr):
207
+ if stream and not stream.closed:
208
+ stream.close()
209
+
210
+ def read_message(self) -> dict[str, Any]:
211
+ assert self.process.stdout is not None
212
+ fd = self.process.stdout.fileno()
213
+ deadline = time.monotonic() + RESPONSE_TIMEOUT_SECONDS
214
+ buf = bytearray()
215
+ while True:
216
+ remaining = deadline - time.monotonic()
217
+ if remaining <= 0:
218
+ raise PublishError(
219
+ "Controller publication session timed out",
220
+ error_code=ErrorCode.INTEGRATION_PUBLISH_FAILED,
221
+ )
222
+ ready, _, _ = select.select([fd], [], [], remaining)
223
+ if not ready:
224
+ raise PublishError(
225
+ "Controller publication session timed out",
226
+ error_code=ErrorCode.INTEGRATION_PUBLISH_FAILED,
227
+ )
228
+ chunk = os.read(fd, 1)
229
+ if not chunk:
230
+ raise PublishError("Controller publication session closed unexpectedly")
231
+ if chunk == b"\n":
232
+ break
233
+ buf.extend(chunk)
234
+ if len(buf) > LINE_BYTES:
235
+ raise PublishError("Controller publication response exceeded size budget")
236
+ try:
237
+ payload = loads_unique(bytes(buf))
238
+ except (ValueError, UnicodeDecodeError) as exc:
239
+ raise PublishError(f"Controller publication returned invalid JSON ({exc})") from exc
240
+ if not isinstance(payload, dict):
241
+ raise PublishError("Controller publication response must be a JSON object")
242
+ return payload
243
+
244
+ def send_json(self, message: dict[str, Any]) -> dict[str, Any]:
245
+ assert self.process.stdin is not None
246
+ line = (json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
247
+ try:
248
+ self.process.stdin.write(line)
249
+ self.process.stdin.flush()
250
+ except OSError as exc:
251
+ raise PublishError("failed writing to Controller publication session") from exc
252
+ return self.read_message()
253
+
254
+
255
+ def remote_head_oid(repo: Path, remote: str, target_ref: str) -> str | None:
256
+ completed = run_git(repo, "ls-remote", "--exit-code", "--refs", "--", remote, target_ref, timeout=GIT_REMOTE_TIMEOUT)
257
+ if completed.returncode == 2:
258
+ return None
259
+ if completed.returncode != 0:
260
+ raise PublishError(f"failed querying remote ref {target_ref}")
261
+ lines = [line.strip() for line in completed.stdout.splitlines() if line.strip()]
262
+ if len(lines) != 1:
263
+ return None
264
+ parts = lines[0].split()
265
+ if len(parts) != 2 or parts[1] != target_ref:
266
+ raise PublishError("ambiguous ls-remote response")
267
+ return validate_oid(parts[0], "remote OID")
268
+
269
+
270
+ def _validate_phase_message(
271
+ message: dict[str, Any],
272
+ *,
273
+ expected_phase: str,
274
+ expected_lease: str,
275
+ expected_run: str,
276
+ expected_candidate: str,
277
+ ) -> dict[str, Any]:
278
+ if type(message.get("schema_version")) is not int or message["schema_version"] != 1:
279
+ raise PublishError("Controller publication schema_version mismatch")
280
+ if message.get("contract") != CONTRACT:
281
+ raise PublishError("Controller publication contract mismatch")
282
+ phase = message.get("phase")
283
+ if phase == "blocked":
284
+ code = message.get("code") or "CONTROLLER_BLOCKED"
285
+ reason = message.get("reason") or "public protocol refused execution"
286
+ raise PublishError(f"Controller publication blocked ({code}): {reason}")
287
+ if phase != expected_phase:
288
+ raise PublishError(f"Controller publication phase drift: expected {expected_phase}, got {phase}")
289
+
290
+ identity = message.get("identity")
291
+ if not isinstance(identity, dict):
292
+ raise PublishError("Controller publication message missing identity")
293
+ if (
294
+ type(identity.get("record_version")) is not int
295
+ or identity.get("lease_id") != expected_lease
296
+ or identity.get("run_id") != expected_run
297
+ or identity.get("candidate_oid") != expected_candidate
298
+ ):
299
+ raise PublishError("Controller publication identity drift detected")
300
+ validate_safe_remote(str(identity.get("remote") or ""))
301
+ validate_target_ref(str(identity.get("target_ref") or ""))
302
+ validate_oid(str(identity.get("expected_main_oid") or ""), "expected_main_oid")
303
+ expires_raw = identity.get("expires_at")
304
+ if not isinstance(expires_raw, str):
305
+ raise PublishError("Controller lease expiry is missing")
306
+ try:
307
+ expires_at = datetime.fromisoformat(expires_raw).astimezone(UTC)
308
+ except ValueError as exc:
309
+ raise PublishError("Controller lease expiry is malformed") from exc
310
+ if expected_phase in {"verified", "authorized"}:
311
+ action = message.get("action")
312
+ if not isinstance(action, str) or action not in {"PUSH_CANDIDATE", "RECOVER_ALREADY_PUBLISHED"}:
313
+ raise PublishError("Controller publication action is invalid")
314
+ expected_remote = (
315
+ identity["candidate_oid"] if action == "RECOVER_ALREADY_PUBLISHED" else identity["expected_main_oid"]
316
+ )
317
+ if message.get("remote_oid") != expected_remote:
318
+ raise PublishError("Controller publication authorization action differs")
319
+ if action == "PUSH_CANDIDATE" and expires_at <= datetime.now(UTC):
320
+ raise PublishError("Controller publication lease has expired")
321
+ return identity
322
+
323
+
324
+ def publish(arguments: argparse.Namespace, progress: PublicationProgress | None = None) -> dict[str, Any]:
325
+ repo = Path(arguments.repo).resolve()
326
+ candidate_oid = validate_oid(arguments.publish_integration_candidate, "candidate OID")
327
+ lease_id = arguments.lease_id
328
+ run_id = arguments.run_id
329
+ prog = progress or PublicationProgress(candidate_oid=candidate_oid, lease_id=lease_id, run_id=run_id)
330
+
331
+ controller = controller_program()
332
+ verify_controller_capabilities(controller, repo)
333
+
334
+ head_res = run_git(repo, "rev-parse", "--verify", "HEAD")
335
+ if head_res.returncode != 0 or head_res.stdout.strip() != candidate_oid:
336
+ raise PublishError("candidate worktree HEAD does not match requested candidate OID")
337
+
338
+ channel = ControllerChannel(controller, repo, candidate_oid, lease_id, run_id)
339
+ try:
340
+ prog.phase = "verify"
341
+ verified = channel.read_message()
342
+ identity = _validate_phase_message(
343
+ verified,
344
+ expected_phase="verified",
345
+ expected_lease=lease_id,
346
+ expected_run=run_id,
347
+ expected_candidate=candidate_oid,
348
+ )
349
+ remote = str(identity["remote"])
350
+ target_ref = str(identity["target_ref"])
351
+ expected_main_oid = str(identity["expected_main_oid"])
352
+ prog.identity = dict(identity)
353
+ prog.remote = remote
354
+ prog.target_ref = target_ref
355
+ prog.expected_main_oid = expected_main_oid
356
+ prog.repository_id = str(identity["repository_id"])
357
+ prog.allocation_id = str(identity["allocation_id"])
358
+
359
+ prog.phase = "authorize"
360
+ authorized = channel.send_json(
361
+ {
362
+ "schema_version": 1,
363
+ "contract": CONTRACT,
364
+ "action": "authorize",
365
+ "identity": identity,
366
+ }
367
+ )
368
+ auth_identity = _validate_phase_message(
369
+ authorized,
370
+ expected_phase="authorized",
371
+ expected_lease=lease_id,
372
+ expected_run=run_id,
373
+ expected_candidate=candidate_oid,
374
+ )
375
+ if auth_identity != identity:
376
+ raise PublishError("Controller authorization identity differs from verified identity")
377
+
378
+ action = str(authorized["action"])
379
+ record_id = f"git-finalizer-integration-{lease_id}-{candidate_oid}"
380
+ prog.record_id = record_id
381
+
382
+ if action == "RECOVER_ALREADY_PUBLISHED":
383
+ live_before = remote_head_oid(repo, remote, target_ref)
384
+ if live_before != candidate_oid:
385
+ raise PublishError("Controller reported RECOVER_ALREADY_PUBLISHED but remote differs")
386
+ prog.remote_oid = live_before
387
+ prog.remote_verified = True
388
+ result_push = "already_published_recovered"
389
+ else:
390
+ live_before = remote_head_oid(repo, remote, target_ref)
391
+ if live_before == candidate_oid:
392
+ prog.remote_oid = live_before
393
+ prog.remote_verified = True
394
+ result_push = "already_published_recovered"
395
+ else:
396
+ if live_before != expected_main_oid:
397
+ raise PublishError("remote main drifted from expected_main_oid before push")
398
+ prog.phase = "push"
399
+ prog.mutation_attempted = True
400
+ try:
401
+ push = run_git(
402
+ repo,
403
+ "push",
404
+ "--porcelain",
405
+ "--no-follow-tags",
406
+ "--",
407
+ remote,
408
+ f"{candidate_oid}:{target_ref}",
409
+ timeout=GIT_REMOTE_TIMEOUT,
410
+ )
411
+ except subprocess.TimeoutExpired as exc:
412
+ raise PublishError(
413
+ f"integration push timed out after {GIT_REMOTE_TIMEOUT}s; remote state uncertain",
414
+ final_phase="push",
415
+ next_action="recheck_remote_and_recover",
416
+ ) from exc
417
+ prog.push_returncode = push.returncode
418
+ if push.returncode != 0:
419
+ prog.remote_oid = remote_head_oid(repo, remote, target_ref)
420
+ raise PublishError("integration push failed")
421
+ result_push = "published"
422
+
423
+ prog.phase = "remote_verify"
424
+ live_after = remote_head_oid(repo, remote, target_ref)
425
+ if live_after != candidate_oid:
426
+ raise PublishError("remote verification failed: remote OID does not match candidate")
427
+ prog.remote_oid = live_after
428
+ prog.remote_verified = True
429
+
430
+ prog.phase = "controller_complete"
431
+ completed = channel.send_json(
432
+ {
433
+ "schema_version": 1,
434
+ "contract": CONTRACT,
435
+ "action": "complete",
436
+ "identity": identity,
437
+ "result": {
438
+ "record_id": record_id,
439
+ "executor": {"name": "git-finalizer", "version": VERSION},
440
+ "push_executed": prog.mutation_attempted,
441
+ "remote_oid": prog.remote_oid,
442
+ },
443
+ }
444
+ )
445
+ _validate_phase_message(
446
+ completed,
447
+ expected_phase="completed",
448
+ expected_lease=lease_id,
449
+ expected_run=run_id,
450
+ expected_candidate=candidate_oid,
451
+ )
452
+ if (
453
+ completed.get("record_id") != record_id
454
+ or completed.get("remote_verify") != {"status": "verified", "oid": candidate_oid}
455
+ or completed.get("lifecycle_completion_required") is not True
456
+ ):
457
+ raise PublishError("Controller completion record_id mismatch")
458
+ if channel.process.wait(timeout=3) != 0:
459
+ raise PublishError("Controller publication session failed after result verification")
460
+ prog.controller_completed = True
461
+ prog.phase = "complete"
462
+
463
+ return {
464
+ "summary_schema_version": SUMMARY_SCHEMA_VERSION,
465
+ "finalizer_version": VERSION,
466
+ "mode": MODE,
467
+ "status": "success",
468
+ "final_phase": "complete",
469
+ "reason": None,
470
+ "next_action": "none",
471
+ "repository_id": prog.repository_id,
472
+ "allocation_id": prog.allocation_id,
473
+ "lease_id": lease_id,
474
+ "run_id": run_id,
475
+ "remote": remote,
476
+ "target_ref": target_ref,
477
+ "expected_main_oid": expected_main_oid,
478
+ "candidate_oid": candidate_oid,
479
+ "record_id": record_id,
480
+ "push": {
481
+ "executed": prog.mutation_attempted,
482
+ "result": result_push,
483
+ "branch_refspec_only": True,
484
+ "follow_tags_requested": False,
485
+ },
486
+ "remote_verify": {"status": "verified", "oid": prog.remote_oid},
487
+ "controller_execution": {
488
+ "contract": CONTRACT,
489
+ "completion": "completed",
490
+ "lifecycle_completion_required": True,
491
+ },
492
+ "progress": prog.to_dict(),
493
+ }
494
+ finally:
495
+ channel.close()
496
+
497
+
498
+ def build_parser() -> argparse.ArgumentParser:
499
+ parser = argparse.ArgumentParser(prog="git-finalize")
500
+ parser.add_argument("--publish-integration-candidate", required=True)
501
+ parser.add_argument("--repo", required=True)
502
+ parser.add_argument("--lease-id", required=True)
503
+ parser.add_argument("--run-id", required=True)
504
+ parser.add_argument("--summary", action="store_true")
505
+ return parser
506
+
507
+
508
+ def main(argv: list[str] | None = None) -> int:
509
+ parser = build_parser()
510
+ try:
511
+ arguments = parser.parse_args(argv)
512
+ except SystemExit as exc:
513
+ return int(exc.code) if isinstance(exc.code, int) else 2
514
+
515
+ prog = PublicationProgress(
516
+ candidate_oid=arguments.publish_integration_candidate,
517
+ lease_id=arguments.lease_id,
518
+ run_id=arguments.run_id,
519
+ )
520
+ try:
521
+ receipt = publish(arguments, progress=prog)
522
+ if arguments.summary:
523
+ print(json.dumps(receipt, ensure_ascii=False, sort_keys=True))
524
+ else:
525
+ print(f"Git Finalizer integration publication complete: {receipt['candidate_oid']}")
526
+ return 0
527
+ except PublishError as exc:
528
+ if arguments.summary:
529
+ blocked = {
530
+ "summary_schema_version": SUMMARY_SCHEMA_VERSION,
531
+ "finalizer_version": VERSION,
532
+ "mode": MODE,
533
+ "status": "blocked",
534
+ "final_phase": exc.final_phase or prog.phase,
535
+ "error_code": exc.error_code,
536
+ "reason": str(exc),
537
+ "next_action": exc.next_action,
538
+ "progress": prog.to_dict(),
539
+ }
540
+ print(json.dumps(blocked, ensure_ascii=False, sort_keys=True))
541
+ else:
542
+ print(f"ERROR [{exc.error_code}]: {exc}", file=sys.stderr)
543
+ raise SystemExit(exc.exit_code) from None
544
+
545
+
546
+ if __name__ == "__main__":
547
+ raise SystemExit(main())