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,553 @@
1
+ """Machine-readable `--summary` serialization and child-safe execution lock."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ import dataclasses
8
+ import fcntl
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import stat
13
+ import time
14
+ from typing import Any
15
+
16
+ from git_finalizer import __version__
17
+ from git_finalizer.errors import ErrorCode, FinalizerError
18
+ from git_finalizer.json_io import sha256_file
19
+
20
+ SUMMARY_SCHEMA_VERSION = 1
21
+ EXECUTION_LOCK_NAME = ".git-finalizer-execution.lock"
22
+
23
+ FIXED_SUMMARY_KEYS = (
24
+ "summary_schema_version",
25
+ "finalizer_version",
26
+ "mode",
27
+ "status",
28
+ "final_phase",
29
+ "exit_code",
30
+ "repository",
31
+ "repository_id",
32
+ "allocation_id",
33
+ "task_key",
34
+ "authority_key",
35
+ "worktree_path",
36
+ "role",
37
+ "branch",
38
+ "upstream",
39
+ "requested_path_count",
40
+ "dry_run",
41
+ "commit",
42
+ "push",
43
+ "warnings",
44
+ "warnings_omitted",
45
+ "warning_characters_omitted",
46
+ "reason",
47
+ "reason_omitted_characters",
48
+ "next_action",
49
+ "next_action_omitted_characters",
50
+ "mode_result",
51
+ )
52
+
53
+ CONDITIONAL_SUMMARY_KEYS = (
54
+ "error_code",
55
+ "resume",
56
+ "fixture_exceptions",
57
+ "reviewed_sensitive_sources",
58
+ "diagnostics",
59
+ )
60
+
61
+ ALLOWED_STATUSES = frozenset({"success", "blocked", "failed"})
62
+
63
+ ALLOWED_NEXT_ACTIONS = frozenset(
64
+ {
65
+ "none",
66
+ "resolve_blocker_and_retry",
67
+ "inspect_failure",
68
+ "inspect_failure_with_local_commit_retained",
69
+ "inspect_local_root_commit",
70
+ "inspect_existing_branch_publish_failure",
71
+ "inspect_initial_branch_publish_failure",
72
+ "resume_initial_publish",
73
+ "resume_existing_history_publish",
74
+ "retry_same_resume",
75
+ "inspect_remote_state_then_rerun_same_retirement",
76
+ "rerun_without_summary_for_diagnostics",
77
+ "run_without_dry_run_after_review",
78
+ "publish_install_verify_then_run_without_dry_run",
79
+ }
80
+ )
81
+
82
+
83
+ def _limit_text(value: str | None, maximum: int) -> tuple[str | None, int]:
84
+ if value is None or value == "":
85
+ return None, 0
86
+ normalized = " ".join(value.replace("\r", "\n").splitlines()).strip()
87
+ if not normalized:
88
+ return None, 0
89
+ if len(normalized) <= maximum:
90
+ return normalized, 0
91
+ if maximum <= 3:
92
+ return normalized[:maximum], len(normalized) - maximum
93
+ return normalized[: maximum - 3] + "...", len(normalized) - (maximum - 3)
94
+
95
+
96
+ def _parse_warnings(values: list[str]) -> tuple[list[str], int, int]:
97
+ bounded: list[str] = []
98
+ omitted_chars = 0
99
+ for item in values[:5]:
100
+ text, clipped = _limit_text(item, 240)
101
+ if text is not None:
102
+ bounded.append(text)
103
+ omitted_chars += clipped
104
+ return bounded, max(0, len(values) - 5), omitted_chars
105
+
106
+
107
+ def runtime_identity(entrypoint: Path | None = None) -> dict[str, dict[str, str]]:
108
+ """Return byte identity of the active CLI entry and pure-Python content scanner."""
109
+ from git_finalizer.delivery import content_scan
110
+
111
+ resolved_entry = (entrypoint or Path(__file__)).resolve()
112
+ scanner_path = Path(content_scan.__file__).resolve()
113
+ result: dict[str, dict[str, str]] = {}
114
+ if resolved_entry.is_file():
115
+ result["entrypoint"] = {
116
+ "path": str(resolved_entry),
117
+ "sha256": sha256_file(resolved_entry),
118
+ }
119
+ if scanner_path.is_file():
120
+ result["content_scanner"] = {
121
+ "path": str(scanner_path),
122
+ "sha256": sha256_file(scanner_path),
123
+ }
124
+ return result
125
+
126
+
127
+ @dataclasses.dataclass
128
+ class SummaryState:
129
+ """Explicit named state backing the `--summary` machine contract."""
130
+
131
+ mode: str = "normal"
132
+ status: str = "failed"
133
+ final_phase: str = "preflight"
134
+ exit_code: int = 1
135
+ repository: str = ""
136
+ repository_id: str | None = None
137
+ allocation_id: str | None = None
138
+ task_key: str | None = None
139
+ authority_key: str | None = None
140
+ worktree_path: str | None = None
141
+ role: str | None = None
142
+ branch: str | None = None
143
+ upstream: str | None = None
144
+ requested_path_count: int = 0
145
+ dry_run: bool = False
146
+ commit_created: bool = False
147
+ commit_sha: str | None = None
148
+ commit_result: str = "not_run"
149
+ push_executed: bool = False
150
+ push_result: str = "not_run"
151
+ push_branch_refspec_only: bool | None = None
152
+ push_follow_tags_requested: bool | None = None
153
+ warnings: list[str] = dataclasses.field(default_factory=list)
154
+ warnings_omitted_extra: int = 0
155
+ reason: str | None = None
156
+ next_action: str = "inspect_failure"
157
+ error_code: str | None = None
158
+ mode_state: str = "not_started"
159
+ remote_conclusion: str = "not_run"
160
+ post_verify: str = "not_run"
161
+ worktree_state: str | None = None
162
+ worktree_before_state: str | None = None
163
+ worktree_unchanged: bool | None = None
164
+ head_before: str | None = None
165
+ head_after: str | None = None
166
+ head_unchanged: bool | None = None
167
+ index_unchanged: bool | None = None
168
+ snapshot_verification: str = "not_requested"
169
+ commit_reused: bool | None = None
170
+ completed_through: str | None = None
171
+ resume_publish_kind: str | None = None
172
+ recovery_start: str | None = None
173
+ resume_required: bool = False
174
+ resume_oid: str | None = None
175
+ resume_remote: str | None = None
176
+ publish_ahead: int | None = None
177
+ publish_behind: int | None = None
178
+ publish_commit_count: int | None = None
179
+ publish_range: str | None = None
180
+ push_target: str | None = None
181
+ final_head: str | None = None
182
+ final_remote_oid: str | None = None
183
+ sync_source_remote: str | None = None
184
+ sync_expected_target_oid: str | None = None
185
+ retirement_operation: str | None = None
186
+ retirement_remote: str | None = None
187
+ retirement_branch: str | None = None
188
+ retirement_ref: str | None = None
189
+ retirement_expected_oid: str | None = None
190
+ retirement_plan_id: str | None = None
191
+ retirement_integrated_ref: str | None = None
192
+ retirement_integrated_oid: str | None = None
193
+ retirement_ancestry_verified: bool | None = None
194
+ retirement_ci_required: bool = False
195
+ retirement_ci_status: str | None = None
196
+ retirement_ci_commit_oid: str | None = None
197
+ retirement_ci_source: str = "not_required"
198
+ retirement_ci_verified_at: str | None = None
199
+ retirement_lease_bound: bool | None = None
200
+ retirement_remote_absent_after: bool | None = None
201
+ retirement_local_absent_after: bool | None = None
202
+ retirement_remote_tracking_absent: bool | None = None
203
+ retirement_tags_unchanged: bool | None = None
204
+ retirement_result: str | None = None
205
+ retirement_receipt_id: str | None = None
206
+ fixture_exceptions: list[dict[str, Any]] = dataclasses.field(default_factory=list)
207
+ reviewed_sensitive_sources: list[dict[str, Any]] = dataclasses.field(default_factory=list)
208
+ diagnostics_requested: bool = False
209
+ entrypoint: Path | None = None
210
+ scan_diagnostic: dict[str, Any] | None = None
211
+ trailers_applied: list[str] = dataclasses.field(default_factory=list)
212
+ agent_trace_note: dict[str, Any] | None = None
213
+ external_scanners: list[dict[str, Any]] = dataclasses.field(default_factory=list)
214
+ policy_verdict: dict[str, Any] | None = None
215
+
216
+ def to_dict(self) -> dict[str, Any]:
217
+ """Serialize the canonical `--summary` JSON envelope preserving exact fixed keys & ordering."""
218
+ status = self.status if self.status in ALLOWED_STATUSES else "failed"
219
+ next_action = (
220
+ self.next_action if self.next_action in ALLOWED_NEXT_ACTIONS else "inspect_failure"
221
+ )
222
+ warnings, dropped_warnings, warning_clipped = _parse_warnings(self.warnings)
223
+ warnings_omitted = dropped_warnings + max(0, self.warnings_omitted_extra)
224
+ reason_text, reason_clipped = _limit_text(self.reason, 400)
225
+ next_action_text, next_action_clipped = _limit_text(next_action, 120)
226
+ if next_action_text is None:
227
+ next_action_text = "inspect_failure"
228
+
229
+ commit_obj: dict[str, Any] = {
230
+ "created": bool(self.commit_created),
231
+ "sha": self.commit_sha or None,
232
+ }
233
+ push_obj: dict[str, Any] = {
234
+ "executed": bool(self.push_executed),
235
+ "result": self.push_result or "not_run",
236
+ "branch_refspec_only": self.push_branch_refspec_only,
237
+ "follow_tags_requested": self.push_follow_tags_requested,
238
+ }
239
+ mode_result = _build_mode_result(self)
240
+
241
+ payload: dict[str, Any] = {
242
+ "summary_schema_version": SUMMARY_SCHEMA_VERSION,
243
+ "finalizer_version": __version__,
244
+ "mode": self.mode or "normal",
245
+ "status": status,
246
+ "final_phase": self.final_phase or "preflight",
247
+ "exit_code": int(self.exit_code),
248
+ "repository": self.repository or None,
249
+ "repository_id": self.repository_id or None,
250
+ "allocation_id": self.allocation_id or None,
251
+ "task_key": self.task_key or None,
252
+ "authority_key": self.authority_key or None,
253
+ "worktree_path": self.worktree_path or None,
254
+ "role": self.role or None,
255
+ "branch": self.branch or None,
256
+ "upstream": self.upstream or None,
257
+ "requested_path_count": int(self.requested_path_count),
258
+ "dry_run": bool(self.dry_run),
259
+ "commit": commit_obj,
260
+ "push": push_obj,
261
+ "warnings": warnings,
262
+ "warnings_omitted": warnings_omitted,
263
+ "warning_characters_omitted": warning_clipped,
264
+ "reason": reason_text,
265
+ "reason_omitted_characters": reason_clipped,
266
+ "next_action": next_action_text,
267
+ "next_action_omitted_characters": next_action_clipped,
268
+ "mode_result": mode_result,
269
+ }
270
+ if status != "success":
271
+ payload["error_code"] = self.error_code or (
272
+ ErrorCode.INTERNAL_ERROR if status == "failed" else ErrorCode.CLI_INVALID_ARGS
273
+ )
274
+ if self.resume_required:
275
+ payload["resume"] = {
276
+ "head_oid": self.resume_oid,
277
+ "remote": self.resume_remote,
278
+ }
279
+ if self.fixture_exceptions:
280
+ payload["fixture_exceptions"] = list(self.fixture_exceptions)
281
+ if self.reviewed_sensitive_sources:
282
+ reviews = [dict(item) for item in self.reviewed_sensitive_sources]
283
+ if status == "success" and not self.dry_run:
284
+ for rev in reviews:
285
+ rev["content_scan"] = "passed"
286
+ payload["reviewed_sensitive_sources"] = reviews
287
+ if self.diagnostics_requested or self.scan_diagnostic is not None:
288
+ rt = runtime_identity(self.entrypoint)
289
+ if self.scan_diagnostic and self.scan_diagnostic.get("scanner_sha256") and "content_scanner" in rt:
290
+ rt["content_scanner"]["sha256"] = str(self.scan_diagnostic["scanner_sha256"])
291
+ content_scan_out = None
292
+ if self.scan_diagnostic is not None:
293
+ content_scan_out = {
294
+ k: self.scan_diagnostic.get(k)
295
+ for k in ("path", "stage", "verdict", "detector", "byte_length", "binary", "sha256", "blob_oid")
296
+ }
297
+ diag_obj: dict[str, Any] = {
298
+ "schema_version": 1,
299
+ "runtime": rt,
300
+ "content_scan": content_scan_out,
301
+ }
302
+ if self.scan_diagnostic and "external_scanners" in self.scan_diagnostic:
303
+ diag_obj["external_scanners"] = self.scan_diagnostic["external_scanners"]
304
+ payload["diagnostics"] = diag_obj
305
+ return payload
306
+
307
+
308
+ def _build_mode_result(state: SummaryState) -> dict[str, Any]:
309
+ mode = state.mode or "normal"
310
+ if mode == "initial":
311
+ mr: dict[str, Any] = {
312
+ "initial_publish": state.mode_state,
313
+ "snapshot_verification": state.snapshot_verification,
314
+ "remote_conclusion": state.remote_conclusion,
315
+ "post_verify": state.post_verify,
316
+ }
317
+ elif mode == "initial_branch":
318
+ mr = {
319
+ "initial_branch_publish": state.mode_state,
320
+ "remote_conclusion": state.remote_conclusion,
321
+ "post_verify": state.post_verify,
322
+ }
323
+ elif mode in {"publish_existing_branch", "publish_existing_history"}:
324
+ interface = (
325
+ "publish-existing-history"
326
+ if mode == "publish_existing_history"
327
+ else "publish-existing-branch"
328
+ )
329
+ mr = {
330
+ "interface": interface,
331
+ "commit_reused": state.commit_reused,
332
+ "remote_conclusion": state.remote_conclusion,
333
+ "pre_publish": {
334
+ "commit_count": state.publish_commit_count,
335
+ "commit_range": state.publish_range or None,
336
+ },
337
+ "push_target": state.push_target or None,
338
+ "post_verify": state.post_verify,
339
+ "head": {
340
+ "before": state.head_before or None,
341
+ "after": state.head_after or None,
342
+ "unchanged": state.head_unchanged,
343
+ },
344
+ "index_unchanged": state.index_unchanged,
345
+ "worktree": {
346
+ "before": state.worktree_before_state or None,
347
+ "after": state.worktree_state or None,
348
+ "unchanged": state.worktree_unchanged,
349
+ },
350
+ "final": {
351
+ "head": state.final_head or None,
352
+ "remote_ref_oid": state.final_remote_oid or None,
353
+ },
354
+ }
355
+ if mode == "publish_existing_history":
356
+ mr["bootstrap_prerequisite"] = "repo-plan/repo-ensure"
357
+ elif mode == "sync_published_branch":
358
+ mr = {
359
+ "interface": "sync-published-branch",
360
+ "source_remote": state.sync_source_remote or None,
361
+ "published_oid": state.commit_sha or None,
362
+ "expected_target_oid": state.sync_expected_target_oid or None,
363
+ "push_target": state.push_target or None,
364
+ "commit_count": state.publish_commit_count,
365
+ "post_verify": state.post_verify,
366
+ "remote_conclusion": state.remote_conclusion,
367
+ "final_remote_oid": state.final_remote_oid or None,
368
+ "local_head_unchanged": state.head_unchanged,
369
+ "local_upstream_unchanged": bool(
370
+ state.head_unchanged and state.index_unchanged and state.worktree_unchanged
371
+ ),
372
+ }
373
+ elif mode == "resume":
374
+ resume_interface = {
375
+ "initial_root": "resume-initial-publish",
376
+ "existing_commits": "resume-publish",
377
+ "existing_history_first": "resume-existing-history-publish",
378
+ }.get(state.resume_publish_kind or "")
379
+ mr = {
380
+ "interface": resume_interface,
381
+ "publish_kind": state.resume_publish_kind or None,
382
+ "recovery_start": state.recovery_start or None,
383
+ "commit_reused": state.commit_reused,
384
+ "completed_through": state.completed_through,
385
+ "resume_required": state.resume_required,
386
+ "pre_publish": {
387
+ "ahead": state.publish_ahead,
388
+ "behind": state.publish_behind,
389
+ "commit_count": state.publish_commit_count,
390
+ "commit_range": state.publish_range or None,
391
+ },
392
+ "push_target": state.push_target or None,
393
+ "post_verify": state.post_verify,
394
+ "final": {
395
+ "head": state.final_head or None,
396
+ "remote_ref_oid": state.final_remote_oid or None,
397
+ "worktree": state.worktree_state or None,
398
+ },
399
+ }
400
+ elif mode == "initial-commit-only":
401
+ mr = {
402
+ "initial_root_commit": state.mode_state,
403
+ "remote_verification": state.remote_conclusion,
404
+ "post_verify": state.post_verify,
405
+ "worktree": state.worktree_state or None,
406
+ }
407
+ elif mode == "commit-only":
408
+ mr = {
409
+ "remote_verification": state.remote_conclusion,
410
+ "post_verify": state.post_verify,
411
+ "worktree": state.worktree_state or None,
412
+ }
413
+ elif mode == "verify-only":
414
+ mr = {
415
+ "local_validation": state.mode_state,
416
+ "commit": state.commit_result,
417
+ "remote_verification": state.remote_conclusion,
418
+ "post_verify": state.post_verify,
419
+ "head": {
420
+ "before": state.head_before or None,
421
+ "after": state.head_after or None,
422
+ "unchanged": state.head_unchanged,
423
+ },
424
+ "index_unchanged": state.index_unchanged,
425
+ "worktree": {
426
+ "before": state.worktree_before_state or None,
427
+ "after": state.worktree_state or None,
428
+ "unchanged": state.worktree_unchanged,
429
+ },
430
+ }
431
+ elif mode in {"retire_local_branch", "retire_remote_branch"}:
432
+ operation_name = "local" if mode == "retire_local_branch" else "remote"
433
+ mr = {
434
+ "interface": f"retire-{operation_name}-branch",
435
+ "operation": state.retirement_operation or None,
436
+ "remote": state.retirement_remote or None,
437
+ "branch": state.retirement_branch or None,
438
+ f"{operation_name}_ref": state.retirement_ref or None,
439
+ f"expected_{operation_name}_oid": state.retirement_expected_oid or None,
440
+ "expected_oid": state.retirement_expected_oid or None,
441
+ "retirement_plan_id": state.retirement_plan_id or None,
442
+ "integrated_into_ref": state.retirement_integrated_ref or None,
443
+ "integrated_into_oid": state.retirement_integrated_oid or None,
444
+ "ancestry_verified": state.retirement_ancestry_verified,
445
+ "ci_required": state.retirement_ci_required,
446
+ "ci_status": state.retirement_ci_status,
447
+ "ci_commit_oid": state.retirement_ci_commit_oid or None,
448
+ "ci_verification_source": state.retirement_ci_source,
449
+ "ci_verified_at": state.retirement_ci_verified_at or None,
450
+ "expected_oid_lease_bound": state.retirement_lease_bound,
451
+ "remote_absent_after": state.retirement_remote_absent_after,
452
+ "local_absent_after": state.retirement_local_absent_after,
453
+ "remote_tracking_ref_absent": state.retirement_remote_tracking_absent,
454
+ "head": {
455
+ "before": state.head_before or None,
456
+ "after": state.head_after or None,
457
+ "unchanged": state.head_unchanged,
458
+ },
459
+ "index_unchanged": state.index_unchanged,
460
+ "worktree": {
461
+ "clean_before": state.worktree_before_state == "clean",
462
+ "clean_after": state.worktree_state == "clean",
463
+ "unchanged": state.worktree_unchanged,
464
+ },
465
+ "tags_unchanged": state.retirement_tags_unchanged,
466
+ "result": state.retirement_result,
467
+ }
468
+ if state.retirement_receipt_id:
469
+ mr["retirement_receipt_id"] = state.retirement_receipt_id
470
+ else:
471
+ mr = {"post_verify": state.post_verify}
472
+
473
+ if state.trailers_applied:
474
+ mr["trailers_applied"] = list(state.trailers_applied)
475
+ if state.agent_trace_note is not None:
476
+ mr["agent_trace"] = dict(state.agent_trace_note)
477
+ if state.external_scanners:
478
+ mr["external_scanners"] = list(state.external_scanners)
479
+ if state.policy_verdict is not None:
480
+ mr["policy"] = dict(state.policy_verdict)
481
+ return mr
482
+
483
+
484
+ def render_fallback_error_summary(reason: str, error_code: str = ErrorCode.SUMMARY_SERIALIZATION_ERROR) -> str:
485
+ return json.dumps(
486
+ {
487
+ "summary_schema_version": SUMMARY_SCHEMA_VERSION,
488
+ "summary_status": "serialization_failed",
489
+ "operation_status": "failed",
490
+ "operation_exit_code": 1,
491
+ "error_code": error_code,
492
+ "reason": reason,
493
+ },
494
+ ensure_ascii=False,
495
+ separators=(",", ":"),
496
+ )
497
+
498
+
499
+ @contextmanager
500
+ def execution_lock(entrypoint: Path) -> Iterator[None]:
501
+ """Hold LOCK_SH with O_CLOEXEC when an execution lockfile exists alongside the entrypoint.
502
+
503
+ Child processes (git, ssh, hooks, companion tools) never inherit the lock FD.
504
+ """
505
+ resolved = entrypoint.resolve()
506
+ lock_path = entrypoint.with_name(EXECUTION_LOCK_NAME)
507
+ if not lock_path.exists() and not lock_path.is_symlink():
508
+ alt = resolved.with_name(EXECUTION_LOCK_NAME)
509
+ if alt.exists() or alt.is_symlink():
510
+ lock_path = alt
511
+ else:
512
+ yield
513
+ return
514
+ if lock_path.is_symlink():
515
+ raise FinalizerError(
516
+ ErrorCode.EXECUTION_LOCK_UNAVAILABLE,
517
+ "拒绝符号链接形式的 Finalizer 执行锁",
518
+ final_phase="cli",
519
+ )
520
+ flags = os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0)
521
+ try:
522
+ descriptor = os.open(lock_path, flags)
523
+ except OSError as exc:
524
+ raise FinalizerError(
525
+ ErrorCode.EXECUTION_LOCK_UNAVAILABLE,
526
+ f"无法打开 Finalizer 执行锁: {exc}",
527
+ final_phase="cli",
528
+ ) from exc
529
+ try:
530
+ info = os.fstat(descriptor)
531
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or (info.st_mode & 0o077):
532
+ raise FinalizerError(
533
+ ErrorCode.EXECUTION_LOCK_UNAVAILABLE,
534
+ "Finalizer 执行锁权限或所有权不安全",
535
+ final_phase="cli",
536
+ )
537
+ deadline = time.monotonic() + 30.0
538
+ while True:
539
+ try:
540
+ fcntl.flock(descriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
541
+ break
542
+ except BlockingIOError as exc:
543
+ if time.monotonic() >= deadline:
544
+ raise FinalizerError(
545
+ ErrorCode.EXECUTION_LOCK_TIMEOUT,
546
+ "等待 Finalizer 执行锁超时",
547
+ status="failed",
548
+ final_phase="cli",
549
+ ) from exc
550
+ time.sleep(0.05)
551
+ yield
552
+ finally:
553
+ os.close(descriptor)