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,2364 @@
1
+ """Core delivery orchestration engine replacing the legacy Bash state machine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+ import subprocess
8
+ from typing import Any
9
+
10
+ from git_finalizer.delivery import (
11
+ policy as policy_mod,
12
+ )
13
+ from git_finalizer.delivery import (
14
+ repo_state,
15
+ retirement_plan,
16
+ snapshot_verify,
17
+ source_review,
18
+ validation,
19
+ )
20
+ from git_finalizer.delivery import (
21
+ trailers as trailer_mod,
22
+ )
23
+ from git_finalizer.delivery.parser import ParsedCLI
24
+ from git_finalizer.delivery.runtime import SummaryState
25
+ from git_finalizer.errors import ErrorCode, FinalizerError
26
+ from git_finalizer.git_io import (
27
+ isolated_staging_env,
28
+ parse_nul_records,
29
+ remote_git_timeout,
30
+ run_git,
31
+ validate_branch_name,
32
+ validate_oid,
33
+ validate_remote_name,
34
+ )
35
+
36
+ FULL_DEFAULT_EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
37
+
38
+
39
+ def _emit(line: str, *, quiet: bool) -> None:
40
+ if not quiet:
41
+ print(line, flush=True)
42
+
43
+
44
+ def _run_remote_push(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes]:
45
+ """Execute remote git push, surfacing timeouts as non-zero returncode so callers record uncertainty."""
46
+ try:
47
+ return run_git(repo, *args, timeout=remote_git_timeout())
48
+ except FinalizerError as exc:
49
+ if exc.code == ErrorCode.REMOTE_UNAVAILABLE:
50
+ return subprocess.CompletedProcess(["git", *args], 124, b"", exc.message.encode("utf-8"))
51
+ raise
52
+
53
+
54
+ def create_summary(cli: ParsedCLI, *, entrypoint: Path | None = None) -> SummaryState:
55
+ return SummaryState(
56
+ mode=cli.mode,
57
+ status="failed",
58
+ final_phase="preflight",
59
+ exit_code=1,
60
+ repository=str(Path(cli.repo).resolve()) if cli.repo else "",
61
+ repository_id=cli.repository_id,
62
+ allocation_id=cli.allocation_id,
63
+ task_key=cli.task_key,
64
+ authority_key=cli.authority_key,
65
+ worktree_path=cli.worktree_path,
66
+ role=cli.role,
67
+ requested_path_count=len(cli.paths),
68
+ dry_run=cli.dry_run,
69
+ diagnostics_requested=cli.diagnostics,
70
+ entrypoint=entrypoint,
71
+ )
72
+
73
+
74
+ def _normalize_heads_ref(raw: str, flag: str) -> tuple[str, str]:
75
+ value = raw.strip()
76
+ if value.startswith("refs/heads/"):
77
+ branch = value.removeprefix("refs/heads/")
78
+ ref = value
79
+ elif value.startswith("refs/"):
80
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, f"{flag} 必须是 branch 名或 refs/heads/ ref: {raw}", final_phase="cli")
81
+ else:
82
+ branch = value
83
+ ref = f"refs/heads/{branch}"
84
+ validate_branch_name(branch)
85
+ return branch, ref
86
+
87
+
88
+ def _normalize_integration_ref(raw: str, remote: str) -> tuple[str, str]:
89
+ value = raw.strip()
90
+ if value.startswith("refs/heads/"):
91
+ branch = value.removeprefix("refs/heads/")
92
+ validate_branch_name(branch)
93
+ return branch, value
94
+ if value.startswith("refs/remotes/"):
95
+ rest = value.removeprefix("refs/remotes/")
96
+ rem, sep, branch = rest.partition("/")
97
+ if not sep or rem != remote:
98
+ raise FinalizerError(
99
+ ErrorCode.CLI_INVALID_ARGS,
100
+ f"--integrated-into remote prefix 必须匹配 --remote {remote}",
101
+ final_phase="cli",
102
+ )
103
+ validate_branch_name(branch)
104
+ return branch, f"refs/heads/{branch}"
105
+ if value.startswith("refs/"):
106
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, f"--integrated-into 非法 ref: {raw}", final_phase="cli")
107
+ if value.startswith(f"{remote}/"):
108
+ branch = value.removeprefix(f"{remote}/")
109
+ validate_branch_name(branch)
110
+ return branch, f"refs/heads/{branch}"
111
+ if "/" in value:
112
+ # Either branch name with `/` (e.g. release/v1) or conflicting foreign remote prefix.
113
+ validate_branch_name(value)
114
+ return value, f"refs/heads/{value}"
115
+ validate_branch_name(value)
116
+ return value, f"refs/heads/{value}"
117
+
118
+
119
+ def _show_ref_hash(repo: Path, ref: str, *, label: str) -> str | None:
120
+ """Fail-closed wrapper around `git show-ref --verify`: `--quiet` returns 1 cleanly on missing/unborn refs."""
121
+ chk = run_git(repo, "show-ref", "--verify", "--quiet", "--", ref)
122
+ if chk.returncode == 1:
123
+ return None
124
+ if chk.returncode != 0:
125
+ raise FinalizerError(
126
+ ErrorCode.REPO_INVALID,
127
+ f"无法验证 {label} ({ref}) 引用状态 (exit {chk.returncode})",
128
+ status="failed",
129
+ )
130
+ res = run_git(repo, "show-ref", "--verify", "--hash", "--", ref)
131
+ if res.returncode == 0:
132
+ oid = res.stdout.decode("ascii", errors="strict").strip()
133
+ if not oid:
134
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"{label} 返回空 OID", status="failed")
135
+ return oid
136
+ raise FinalizerError(
137
+ ErrorCode.REPO_INVALID,
138
+ f"无法验证 {label} ({ref}) 引用状态 (exit {res.returncode})",
139
+ status="failed",
140
+ )
141
+
142
+
143
+ def _git_config_get_all(repo: Path, key: str) -> list[str]:
144
+ """Fail-closed `git config --null --get-all` wrapper (exit 1 -> empty, >=2 -> error)."""
145
+ res = run_git(repo, "config", "--null", "--get-all", key)
146
+ if res.returncode == 1:
147
+ return []
148
+ if res.returncode != 0:
149
+ raise FinalizerError(
150
+ ErrorCode.REPO_INVALID,
151
+ f"读取 Git 配置 {key} 失败 (exit {res.returncode})",
152
+ status="failed",
153
+ )
154
+ return parse_nul_records(res.stdout)
155
+
156
+
157
+ def _classify_branch_upstream(
158
+ repo: Path, branch: str, selected_remote: str, expected_merge_ref: str
159
+ ) -> tuple[str, str | None, str | None]:
160
+ """Return `(state, oid, error)` in {'none', 'exact_resolved', 'exact_unresolved', 'conflicting'}."""
161
+ remote_vals = _git_config_get_all(repo, f"branch.{branch}.remote")
162
+ merge_vals = _git_config_get_all(repo, f"branch.{branch}.merge")
163
+ if not remote_vals and not merge_vals:
164
+ return "none", None, None
165
+ if (
166
+ len(remote_vals) != 1
167
+ or len(merge_vals) != 1
168
+ or remote_vals[0] != selected_remote
169
+ or merge_vals[0] != expected_merge_ref
170
+ ):
171
+ return "conflicting", None, "upstream 配置与 selected remote/branch 冲突或含糊"
172
+ rev = run_git(repo, "rev-parse", "--verify", "@{upstream}^{commit}")
173
+ if rev.returncode == 0:
174
+ return "exact_resolved", rev.stdout.decode("ascii", errors="strict").strip(), None
175
+ return "exact_unresolved", None, None
176
+
177
+
178
+ def _ls_remote_refs(repo: Path, remote: str, *ref_patterns: str) -> tuple[dict[str, str], str | None]:
179
+ """Query live remote refs and optional `HEAD` symbolic ref cleanly."""
180
+ validate_remote_name(remote)
181
+ args = ["ls-remote", "--quiet", "--symref" if not ref_patterns else "--refs", "--", remote, *ref_patterns]
182
+ if not ref_patterns:
183
+ args = ["ls-remote", "--quiet", "--refs", "--", remote]
184
+ completed = run_git(repo, *args, timeout=remote_git_timeout())
185
+ if completed.returncode != 0:
186
+ raise FinalizerError(
187
+ ErrorCode.REMOTE_UNAVAILABLE,
188
+ f"无法查询远端 {remote} refs (exit {completed.returncode})",
189
+ final_phase="remote_preflight",
190
+ )
191
+ refs: dict[str, str] = {}
192
+ for line in completed.stdout.decode("utf-8", errors="replace").splitlines():
193
+ if not line.strip():
194
+ continue
195
+ parts = line.split("\t")
196
+ if len(parts) != 2 or not parts[0] or not parts[1]:
197
+ raise FinalizerError(
198
+ ErrorCode.REMOTE_UNAVAILABLE,
199
+ f"远端 {remote} ls-remote 输出格式异常",
200
+ final_phase="remote_preflight",
201
+ )
202
+ oid, refname = parts
203
+ if refname in refs:
204
+ raise FinalizerError(
205
+ ErrorCode.REMOTE_UNAVAILABLE,
206
+ f"远端 {remote} 返回重复 ref: {refname}",
207
+ final_phase="remote_preflight",
208
+ )
209
+ refs[refname] = oid
210
+ return refs, None
211
+
212
+
213
+ def _query_remote_default_branch(repo: Path, remote: str) -> str:
214
+ validate_remote_name(remote)
215
+ res = run_git(repo, "ls-remote", "--symref", "--quiet", "--", remote, "HEAD", timeout=remote_git_timeout())
216
+ if res.returncode != 0:
217
+ raise FinalizerError(ErrorCode.REMOTE_UNAVAILABLE, f"无法查询 remote default branch (exit {res.returncode})")
218
+ default_ref: str | None = None
219
+ for line in res.stdout.decode("utf-8", errors="replace").splitlines():
220
+ if not line.strip():
221
+ continue
222
+ parts = line.split("\t")
223
+ if len(parts) == 2 and parts[0].startswith("ref: refs/heads/") and parts[1] == "HEAD":
224
+ if default_ref is not None:
225
+ raise FinalizerError(ErrorCode.REMOTE_UNAVAILABLE, "remote default branch 返回重复 symbolic ref")
226
+ default_ref = parts[0].removeprefix("ref: ")
227
+ if not default_ref:
228
+ raise FinalizerError(ErrorCode.REMOTE_UNAVAILABLE, "无法安全确定 remote default branch;fail closed")
229
+ return default_ref
230
+
231
+
232
+ def _fetch_remote(
233
+ repo: Path,
234
+ remote: str,
235
+ *refspecs: str,
236
+ prune: bool = False,
237
+ no_write_fetch_head: bool = False,
238
+ phase: str = "remote_preflight",
239
+ phase_label: str = "",
240
+ ) -> None:
241
+ validate_remote_name(remote)
242
+ args = ["fetch", "--no-tags", "--no-recurse-submodules"]
243
+ if prune:
244
+ args.append("--prune")
245
+ if no_write_fetch_head:
246
+ args.append("--no-write-fetch-head")
247
+ args.extend(["--", remote, *refspecs])
248
+ res = run_git(repo, *args, timeout=remote_git_timeout())
249
+ if res.returncode != 0:
250
+ err_code = ErrorCode.REMOTE_UNAVAILABLE if phase == "remote_preflight" else ErrorCode.POST_VERIFY_FAILED
251
+ raise FinalizerError(
252
+ err_code,
253
+ f"{phase_label}git fetch 失败 ({remote}, exit {res.returncode})",
254
+ final_phase=phase,
255
+ status="failed" if phase in {"post_verify", "push"} else "blocked",
256
+ )
257
+
258
+
259
+ def _snapshot_tags(repo: Path) -> str:
260
+ res = run_git(repo, "for-each-ref", "--format=%(objectname)\t%(refname)", "refs/tags")
261
+ if res.returncode != 0:
262
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法记录本地 refs/tags 基线", status="failed")
263
+ return res.stdout.decode("utf-8", errors="strict")
264
+
265
+
266
+ def _snapshot_local_state(repo: Path) -> dict[str, Any]:
267
+ sym = run_git(repo, "symbolic-ref", "--quiet", "HEAD")
268
+ if sym.returncode != 0:
269
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "要求 symbolic attached HEAD branch")
270
+ head_res = run_git(repo, "rev-parse", "--verify", "HEAD^{commit}")
271
+ if head_res.returncode != 0:
272
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法解析 HEAD commit")
273
+ idx_res = run_git(repo, "ls-files", "--stage")
274
+ if idx_res.returncode != 0:
275
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法读取 index snapshot")
276
+ st_res = run_git(repo, "status", "--porcelain=v1", "--untracked-files=all")
277
+ if st_res.returncode != 0:
278
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法读取 worktree snapshot")
279
+ cnt_res = run_git(repo, "rev-list", "--count", "HEAD")
280
+ if cnt_res.returncode != 0:
281
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法统计 commit count")
282
+ return {
283
+ "symbolic_head": sym.stdout.decode("utf-8", errors="strict").strip(),
284
+ "head": head_res.stdout.decode("ascii", errors="strict").strip(),
285
+ "index": idx_res.stdout.decode("utf-8", errors="replace"),
286
+ "status": st_res.stdout.decode("utf-8", errors="replace"),
287
+ "commit_count": cnt_res.stdout.decode("ascii", errors="strict").strip(),
288
+ "tags": _snapshot_tags(repo),
289
+ "other_heads": _snapshot_other_local_heads(repo, excluded_ref=None),
290
+ }
291
+
292
+
293
+ def _snapshot_other_local_heads(repo: Path, excluded_ref: str | None) -> str:
294
+ res = run_git(repo, "for-each-ref", "--format=%(objectname)\t%(refname)", "refs/heads")
295
+ if res.returncode != 0:
296
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法枚举 refs/heads", status="failed")
297
+ lines = [
298
+ ln
299
+ for ln in res.stdout.decode("utf-8", errors="strict").splitlines()
300
+ if ln and (excluded_ref is None or ln.split("\t", 1)[1] != excluded_ref)
301
+ ]
302
+ return "\n".join(lines)
303
+
304
+
305
+ def _assert_local_state_unchanged(
306
+ repo: Path,
307
+ baseline: dict[str, Any],
308
+ *,
309
+ phase: str = "post_verify",
310
+ failure_status: str = "failed",
311
+ next_action: str = "inspect_failure",
312
+ commit_created: bool = False,
313
+ commit_sha: str | None = None,
314
+ push_executed: bool = False,
315
+ push_result: str = "not_run",
316
+ context_label: str = "验证/发布",
317
+ ) -> None:
318
+ sym = run_git(repo, "symbolic-ref", "--quiet", "HEAD")
319
+ head = run_git(repo, "rev-parse", "--verify", "HEAD^{commit}")
320
+ idx = run_git(repo, "ls-files", "--stage")
321
+ st = run_git(repo, "status", "--porcelain=v1", "--untracked-files=all")
322
+ cnt = run_git(repo, "rev-list", "--count", "HEAD")
323
+ tags = _snapshot_tags(repo)
324
+ checks = [
325
+ (sym.returncode == 0 and sym.stdout.decode("utf-8", errors="replace").strip() == baseline["symbolic_head"], "symbolic HEAD 发生变化"),
326
+ (head.returncode == 0 and head.stdout.decode("ascii", errors="replace").strip() == baseline["head"], "HEAD commit 发生变化"),
327
+ (idx.returncode == 0 and idx.stdout.decode("utf-8", errors="replace") == baseline["index"], f"index 在 {context_label} 期间发生变化"),
328
+ (st.returncode == 0 and st.stdout.decode("utf-8", errors="replace") == baseline["status"], f"worktree 在 {context_label} 期间发生变化"),
329
+ (cnt.returncode == 0 and cnt.stdout.decode("ascii", errors="replace").strip() == baseline["commit_count"], "commit history 发生变化"),
330
+ (tags == baseline["tags"], "refs/tags 在操作期间发生变化"),
331
+ ]
332
+ for ok, msg in checks:
333
+ if not ok:
334
+ raise FinalizerError(
335
+ ErrorCode.POST_VERIFY_FAILED if phase == "post_verify" else ErrorCode.REPO_INVALID,
336
+ msg,
337
+ status=failure_status,
338
+ final_phase=phase,
339
+ next_action=next_action,
340
+ commit_created=commit_created,
341
+ commit_sha=commit_sha,
342
+ push_executed=push_executed,
343
+ push_result=push_result,
344
+ )
345
+
346
+
347
+ def _require_clean_repo_state(repo: Path, info: repo_state.RepoInfo) -> None:
348
+ diff_c = run_git(repo, "diff", "--cached", "--quiet")
349
+ if diff_c.returncode != 0:
350
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "该模式要求 index/staged 状态干净", final_phase="preflight")
351
+ _, _, wt_state = repo_state.working_tree_dirty_status(repo)
352
+ if wt_state != "clean":
353
+ raise FinalizerError(ErrorCode.WORKING_TREE_DIRTY, "该模式要求 worktree 完全干净(包括 untracked 文件)", final_phase="preflight")
354
+ if not info.branch:
355
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "该模式要求 symbolic attached branch", final_phase="preflight")
356
+ if info.is_unborn or not info.head_oid:
357
+ raise FinalizerError(ErrorCode.UNBORN_REPO, "该模式要求已有可解析 HEAD commit", final_phase="preflight")
358
+
359
+
360
+ def _check_normal_remote_state(
361
+ repo: Path,
362
+ remote: str,
363
+ target_branch: str,
364
+ *,
365
+ phase_label: str,
366
+ phase_name: str = "remote_preflight",
367
+ commit_created: bool = False,
368
+ commit_sha: str | None = None,
369
+ ) -> tuple[str, str, int, int, str]:
370
+ """Fetch `remote`, query live `refs/heads/<target_branch>`, return `(local_oid, upstream_oid, ahead, behind, remote_oid)`."""
371
+ _fetch_remote(repo, remote, phase=phase_name, phase_label=phase_label)
372
+ target_ref = f"refs/heads/{target_branch}"
373
+ refs, _ = _ls_remote_refs(repo, remote, target_ref)
374
+ if target_ref not in refs:
375
+ raise FinalizerError(
376
+ ErrorCode.REMOTE_MISSING if phase_name == "remote_preflight" else ErrorCode.POST_VERIFY_FAILED,
377
+ f"{phase_label}远端 branch 不存在: {target_ref}",
378
+ status="failed" if commit_created else "blocked",
379
+ final_phase=phase_name,
380
+ next_action="inspect_failure_with_local_commit_retained" if commit_created else "resolve_blocker_and_retry",
381
+ commit_created=commit_created,
382
+ commit_sha=commit_sha,
383
+ )
384
+ remote_oid = refs[target_ref]
385
+ validate_oid(remote_oid, "remote branch OID")
386
+ up_res = run_git(repo, "rev-parse", "--verify", "@{upstream}^{commit}")
387
+ if up_res.returncode != 0:
388
+ raise FinalizerError(
389
+ ErrorCode.UPSTREAM_CONFLICT,
390
+ f"{phase_label}无法解析 @{{upstream}}",
391
+ status="failed" if commit_created else "blocked",
392
+ final_phase=phase_name,
393
+ next_action="inspect_failure_with_local_commit_retained" if commit_created else "resolve_blocker_and_retry",
394
+ commit_created=commit_created,
395
+ commit_sha=commit_sha,
396
+ )
397
+ upstream_oid = up_res.stdout.decode("ascii", errors="strict").strip()
398
+ if upstream_oid != remote_oid:
399
+ raise FinalizerError(
400
+ ErrorCode.REMOTE_DIVERGED,
401
+ f"{phase_label}fetch 后 @{{upstream}} 与远端 branch OID 不一致",
402
+ status="failed" if commit_created else "blocked",
403
+ final_phase=phase_name,
404
+ next_action="inspect_failure_with_local_commit_retained" if commit_created else "resolve_blocker_and_retry",
405
+ commit_created=commit_created,
406
+ commit_sha=commit_sha,
407
+ )
408
+ head_res = run_git(repo, "rev-parse", "--verify", "HEAD^{commit}")
409
+ if head_res.returncode != 0:
410
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"{phase_label}无法解析 HEAD commit", status="failed", final_phase=phase_name)
411
+ local_oid = head_res.stdout.decode("ascii", errors="strict").strip()
412
+ cnt_res = run_git(repo, "rev-list", "--left-right", "--count", f"{local_oid}...{upstream_oid}")
413
+ if cnt_res.returncode != 0:
414
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"{phase_label}无法计算 ahead/behind", status="failed", final_phase=phase_name)
415
+ ahead_s, behind_s = cnt_res.stdout.decode("ascii", errors="strict").strip().split()
416
+ ahead, behind = int(ahead_s), int(behind_s)
417
+ if behind > 0:
418
+ msg = (
419
+ f"{phase_label}本地已与 upstream 分叉(HEAD...upstream ahead/behind: {ahead}/{behind})"
420
+ if ahead > 0
421
+ else f"{phase_label}本地落后 upstream(HEAD...upstream ahead/behind: {ahead}/{behind})"
422
+ )
423
+ raise FinalizerError(
424
+ ErrorCode.REMOTE_DIVERGED if ahead > 0 else ErrorCode.REMOTE_BEHIND,
425
+ msg,
426
+ status="failed" if commit_created else "blocked",
427
+ final_phase=phase_name,
428
+ next_action="inspect_failure_with_local_commit_retained" if commit_created else "resolve_blocker_and_retry",
429
+ commit_created=commit_created,
430
+ commit_sha=commit_sha,
431
+ )
432
+ return local_oid, upstream_oid, ahead, behind, remote_oid
433
+
434
+
435
+ def _check_initial_target(
436
+ repo: Path, info: repo_state.RepoInfo, remote_arg: str | None, *, require_remote: bool
437
+ ) -> tuple[str, str | None]:
438
+ if not info.branch:
439
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "initial root commit 要求 symbolic attached branch")
440
+ if not info.is_unborn:
441
+ raise FinalizerError(ErrorCode.REPO_INVALID, "initial root commit 只接受尚无 commit 的 unborn 仓库")
442
+ any_commit = run_git(repo, "rev-list", "--all", "--max-count=1")
443
+ if any_commit.returncode != 0 or any_commit.stdout.strip():
444
+ raise FinalizerError(ErrorCode.REPO_INVALID, "initial root commit 不接受已有可解析 commit 的仓库")
445
+ branch_ref = f"refs/heads/{info.branch}"
446
+ if _show_ref_hash(repo, branch_ref, label="initial branch ref") is not None:
447
+ raise FinalizerError(ErrorCode.REPO_INVALID, "initial root commit 只接受 branch ref 尚不存在的 unborn 仓库")
448
+ ls = run_git(repo, "ls-files", "--stage")
449
+ if ls.returncode != 0 or ls.stdout.strip():
450
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "initial 模式不允许预先存在 index 或 staged 内容")
451
+ if not require_remote:
452
+ return branch_ref, None
453
+ remote = validate_remote_name(remote_arg or "")
454
+ repo_state.validate_remote_endpoints(repo, remote)
455
+ up_state, _, up_err = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
456
+ if up_state == "exact_resolved":
457
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, "initial-publish 不接受可解析 upstream")
458
+ if up_state == "conflicting":
459
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, up_err or "upstream 配置冲突")
460
+ return branch_ref, remote
461
+
462
+
463
+ def _check_initial_worktree_scope(repo: Path, allowed_set: set[str]) -> None:
464
+ res = run_git(repo, "--literal-pathspecs", "status", "--porcelain=v1", "-z", "--untracked-files=all")
465
+ if res.returncode != 0:
466
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法读取 initial root worktree 状态")
467
+ for entry in parse_nul_records(res.stdout):
468
+ if len(entry) < 4:
469
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法解析 initial root worktree 状态")
470
+ rel = entry[3:]
471
+ if rel not in allowed_set:
472
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"initial root 存在显式范围外改动: {rel}")
473
+
474
+
475
+ def _retained_staged_deletions(repo: Path, paths: list[str], *, is_unborn: bool) -> set[str]:
476
+ if is_unborn:
477
+ return set()
478
+ retained: set[str] = set()
479
+ for rel in paths:
480
+ d = run_git(
481
+ repo,
482
+ "--literal-pathspecs",
483
+ "diff",
484
+ "--cached",
485
+ "--no-renames",
486
+ "--no-ext-diff",
487
+ "--no-textconv",
488
+ "--quiet",
489
+ "--diff-filter=D",
490
+ "HEAD",
491
+ "--",
492
+ rel,
493
+ )
494
+ if d.returncode == 1:
495
+ target = repo / rel
496
+ if (not target.exists() and not target.is_symlink()) or (
497
+ run_git(repo, "check-ignore", "--quiet", "--no-index", "--", rel).returncode == 0
498
+ ):
499
+ retained.add(rel)
500
+ return retained
501
+
502
+
503
+ def _unpublished_commits(repo: Path, expected_oid: str, exclude_oids: list[str]) -> list[str]:
504
+ args = ["rev-list", "--reverse", "--topo-order", expected_oid]
505
+ unique_excludes = list(dict.fromkeys(oid for oid in exclude_oids if oid))
506
+ for ex in unique_excludes:
507
+ chk = run_git(repo, "cat-file", "-e", f"{ex}^{{commit}}")
508
+ if chk.returncode != 0:
509
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法解析远端基准 commit: {ex}", final_phase="remote_preflight")
510
+ if unique_excludes:
511
+ args.extend(["--not", *unique_excludes])
512
+ res = run_git(repo, *args)
513
+ if res.returncode != 0:
514
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法计算待发布 commit 集合", final_phase="remote_preflight")
515
+ return [ln.strip() for ln in res.stdout.decode("ascii", errors="strict").splitlines() if ln.strip()]
516
+
517
+
518
+ def _emit_scope_banner(cli: ParsedCLI, repo: Path, info: repo_state.RepoInfo) -> None:
519
+ if cli.summary:
520
+ return
521
+ from git_finalizer import __version__
522
+
523
+ status_res = run_git(repo, "status", "--short")
524
+ status_text = status_res.stdout.decode("utf-8", errors="replace").strip() if status_res.returncode == 0 else ""
525
+ verify_only = cli.action == "verify-only"
526
+ remotes_text = ""
527
+ if not verify_only:
528
+ rem_res = run_git(repo, "remote")
529
+ remotes_text = rem_res.stdout.decode("utf-8", errors="replace").strip() if rem_res.returncode == 0 else ""
530
+
531
+ print(f"\n== Git Finalizer v{__version__}: 提交前状态 ==", flush=True)
532
+ print("$ git branch --show-current", flush=True)
533
+ print(info.branch or "(detached)", flush=True)
534
+ print("$ git rev-parse HEAD", flush=True)
535
+ print(info.head_oid or "(unborn HEAD)", flush=True)
536
+ print("$ git status --short", flush=True)
537
+ print(status_text or "(clean)", flush=True)
538
+ print("$ git remote", flush=True)
539
+ print("(skipped by verify-only)" if verify_only else (remotes_text or "(none)"), flush=True)
540
+ print("$ git rev-parse --abbrev-ref --symbolic-full-name @{upstream}", flush=True)
541
+ print("(skipped by verify-only)" if verify_only else (info.upstream or "(none)"), flush=True)
542
+ staged_res = run_git(repo, "ls-files", "--stage")
543
+ staged_count = len(staged_res.stdout.splitlines()) if staged_res.returncode == 0 else 0
544
+ print(f"index entries: {staged_count}", flush=True)
545
+
546
+ print("\n== 显式范围 ==", flush=True)
547
+ print(f"repo: {repo}", flush=True)
548
+ if cli.action in {"verify-only", "commit-only", "initial-commit-only"}:
549
+ print(f"mode: {cli.action}", flush=True)
550
+ elif cli.action == "initial-publish":
551
+ print("mode: initial-publish", flush=True)
552
+ print(f"remote: {cli.remote}", flush=True)
553
+ if cli.snapshot:
554
+ print(f"snapshot: {cli.snapshot}", flush=True)
555
+ elif cli.action == "initial-branch-publish":
556
+ print("mode: initial-branch-publish", flush=True)
557
+ print(f"remote: {cli.remote}", flush=True)
558
+ print(f"remote branch: {cli.remote_branch}", flush=True)
559
+ else:
560
+ print(f"mode: {cli.action}", flush=True)
561
+ print(f"branch: {info.branch or '(detached)'}", flush=True)
562
+ print(f"head before: {info.head_oid or '(unborn)'}", flush=True)
563
+ print(f"requested paths ({len(cli.paths)}):", flush=True)
564
+ for rel in cli.paths:
565
+ print(f" - {rel}", flush=True)
566
+
567
+
568
+ def _run_dry_run_commit_flow(
569
+ cli: ParsedCLI, info: repo_state.RepoInfo, policy: policy_mod.DeliveryPolicy, summary: SummaryState
570
+ ) -> tuple[int, SummaryState]:
571
+ repo = info.repo
572
+ paths = repo_state.validate_explicit_paths(repo, cli.paths, is_unborn=info.is_unborn)
573
+ summary.requested_path_count = len(paths)
574
+ _, _, wt_before = repo_state.working_tree_dirty_status(repo)
575
+ summary.worktree_before_state = wt_before
576
+ summary.branch = info.branch
577
+ summary.head_before = info.head_oid
578
+ _emit_scope_banner(cli, repo, info)
579
+
580
+ # Target checks in dry-run mirror real mode rules without mutating anything.
581
+ if cli.action == "initial-commit-only":
582
+ _check_initial_target(repo, info, None, require_remote=False)
583
+ _check_initial_worktree_scope(repo, set(paths))
584
+ elif cli.action == "initial-publish":
585
+ branch_ref, remote = _check_initial_target(repo, info, cli.remote, require_remote=True)
586
+ _check_initial_worktree_scope(repo, set(paths))
587
+ summary.upstream = f"{remote}/{info.branch}"
588
+ summary.warnings.append("dry-run did not query the remote empty-state")
589
+ _emit(" - dry-run 未执行 ls-remote;未实时核验远端是否完全为空。", quiet=cli.summary)
590
+ elif cli.action == "initial-branch-publish":
591
+ if not info.branch or info.is_unborn:
592
+ raise FinalizerError(ErrorCode.REPO_INVALID, "initial-branch-publish 要求已有 attached branch commit")
593
+ if repo_state.is_protected_branch(info.branch, policy):
594
+ raise FinalizerError(ErrorCode.BRANCH_PROTECTED, f"initial-branch-publish 拒绝受保护分支: {info.branch}")
595
+ if cli.remote_branch != info.branch:
596
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "本地 branch 名必须与 --remote-branch 完全一致")
597
+ remote = validate_remote_name(cli.remote or "")
598
+ repo_state.validate_remote_endpoints(repo, remote)
599
+ summary.upstream = f"{remote}/{info.branch}"
600
+ summary.warnings.append("dry-run did not query the explicit remote branch")
601
+ _emit(" - dry-run 未执行 ls-remote;未实时核验显式远端目标 branch 是否不存在。", quiet=cli.summary)
602
+ elif cli.action == "commit-only":
603
+ if not info.branch:
604
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "detached HEAD 拒绝 commit")
605
+ else:
606
+ # normal
607
+ if info.is_unborn or not info.branch:
608
+ raise FinalizerError(
609
+ ErrorCode.UNBORN_REPO if info.is_unborn else ErrorCode.DETACHED_HEAD,
610
+ "正常模式拒绝 unborn HEAD(要求已有非空 attached branch)"
611
+ if info.is_unborn
612
+ else "正常模式要求已有非空 attached branch",
613
+ )
614
+ remote, target_branch = repo_state.resolve_configured_upstream(repo, info.branch)
615
+ summary.upstream = f"{remote}/{target_branch}"
616
+ summary.warnings.append("dry-run did not fetch or verify remote ahead/behind")
617
+ _emit(" - dry-run 未执行 fetch;未实时核验远端 branch 或 ahead/behind。", quiet=cli.summary)
618
+
619
+ trailers = trailer_mod.build_provenance_trailers(
620
+ trailer_agent=cli.trailer_agent,
621
+ trace_ref=cli.trace_ref,
622
+ snapshot_id=cli.snapshot,
623
+ )
624
+ policy_mod.enforce_declarative_policy(
625
+ policy,
626
+ branch=info.branch,
627
+ requested_paths=paths,
628
+ trailers=trailers,
629
+ active_scanners=list(cli.scanners),
630
+ mutating_commit=False,
631
+ )
632
+
633
+ with isolated_staging_env(repo, info.git_dir, info.common_dir) as (iso_env, _):
634
+ outcome = validation.validate_staged_candidate(
635
+ repo,
636
+ info,
637
+ iso_env,
638
+ paths,
639
+ cli,
640
+ policy,
641
+ specs=[],
642
+ local_only=True,
643
+ )
644
+ summary.warnings.extend(outcome.warnings)
645
+ summary.reviewed_sensitive_sources.extend(outcome.reviewed_sensitive_sources)
646
+ if (
647
+ not outcome.warnings
648
+ and "no static risk found; tests and review remain caller responsibilities" not in summary.warnings
649
+ ):
650
+ summary.warnings.append("no static risk found; tests and review remain caller responsibilities")
651
+ summary.status = "success"
652
+ summary.exit_code = 0
653
+ summary.final_phase = "preflight"
654
+ summary.mode_state = "dry_run_complete"
655
+ summary.next_action = "run_without_dry_run_after_review"
656
+ if not cli.summary:
657
+ print("\nDRY-RUN 完成:未执行 git add、git commit、git fetch 或 git push。", flush=True)
658
+ return 0, summary
659
+
660
+
661
+ def _run_commit_delivery(
662
+ cli: ParsedCLI, summary: SummaryState
663
+ ) -> tuple[int, SummaryState]:
664
+ mode_map = {
665
+ "verify-only": "verify-only",
666
+ "commit-only": "commit-only",
667
+ "initial-commit-only": "initial-commit-only",
668
+ "initial-publish": "initial",
669
+ "initial-branch-publish": "initial_branch",
670
+ "normal": "normal",
671
+ }
672
+ summary.mode = mode_map.get(cli.action, "normal")
673
+ summary.final_phase = "preflight"
674
+ require_attached = True
675
+ info = repo_state.inspect_repository(
676
+ cli.repo,
677
+ merge_parent_arg=cli.merge_parent,
678
+ mode=cli.action,
679
+ require_attached=require_attached,
680
+ )
681
+ repo = info.repo
682
+ summary.repository = str(repo)
683
+ policy = policy_mod.load_delivery_policy(repo)
684
+
685
+ if cli.dry_run:
686
+ return _run_dry_run_commit_flow(cli, info, policy, summary)
687
+
688
+ paths = repo_state.validate_explicit_paths(repo, cli.paths, is_unborn=info.is_unborn)
689
+ summary.requested_path_count = len(paths)
690
+ summary.branch = info.branch
691
+ summary.head_before = info.head_oid
692
+ _emit_scope_banner(cli, repo, info)
693
+
694
+ local_only = cli.action in {"verify-only", "commit-only", "initial-commit-only"}
695
+ remote_name: str | None = None
696
+ target_branch: str | None = None
697
+ remote_refs_before: dict[str, str] = {}
698
+ local_tags_before: str = ""
699
+ local_head_before_commit = info.head_oid
700
+
701
+ # 1. Resolve target & run read-only remote preflight BEFORE mutating anything.
702
+ if cli.action == "initial-commit-only":
703
+ branch_ref, _ = _check_initial_target(repo, info, None, require_remote=False)
704
+ _check_initial_worktree_scope(repo, set(paths))
705
+ summary.remote_conclusion = "skipped_by_initial_commit_only"
706
+ elif cli.action == "initial-publish":
707
+ branch_ref, remote_name = _check_initial_target(repo, info, cli.remote, require_remote=True)
708
+ _check_initial_worktree_scope(repo, set(paths))
709
+ summary.upstream = f"{remote_name}/{info.branch}"
710
+ if cli.snapshot:
711
+ summary.snapshot_verification = "pending"
712
+ snapshot_verify.verify_snapshot_evidence(cli.snapshot, repo, "worktree", paths)
713
+ summary.snapshot_verification = "worktree_verified"
714
+
715
+ _, _, wt_before = repo_state.working_tree_dirty_status(repo)
716
+ summary.worktree_before_state = wt_before
717
+
718
+ if cli.action in {"initial-commit-only", "initial-publish"}:
719
+ pass
720
+ elif cli.action == "initial-branch-publish":
721
+ if not info.branch or info.is_unborn or not info.head_oid:
722
+ raise FinalizerError(ErrorCode.REPO_INVALID, "initial-branch-publish 要求已有 attached branch commit")
723
+ if repo_state.is_protected_branch(info.branch, policy):
724
+ raise FinalizerError(ErrorCode.BRANCH_PROTECTED, f"initial-branch-publish 拒绝受保护分支: {info.branch}")
725
+ if cli.remote_branch != info.branch:
726
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "本地 branch 名必须与 --remote-branch 完全一致")
727
+ remote_name = validate_remote_name(cli.remote or "")
728
+ repo_state.validate_remote_endpoints(repo, remote_name)
729
+ branch_ref = f"refs/heads/{info.branch}"
730
+ summary.upstream = f"{remote_name}/{info.branch}"
731
+ elif cli.action == "commit-only":
732
+ if not info.branch:
733
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "detached HEAD 拒绝 commit")
734
+ summary.remote_conclusion = "skipped_by_commit_only"
735
+ elif cli.action == "verify-only":
736
+ if not info.branch:
737
+ raise FinalizerError(ErrorCode.DETACHED_HEAD, "detached HEAD 拒绝 verify-only")
738
+ summary.remote_conclusion = "skipped_by_verify_only"
739
+ else:
740
+ # normal
741
+ if not cli.summary:
742
+ print("\n== Commit 前 fetch 与 fast-forward 检查 ==", flush=True)
743
+ print("$ git rev-parse --abbrev-ref --symbolic-full-name @{upstream}", flush=True)
744
+ print(info.upstream or "(none)", flush=True)
745
+ if info.is_unborn or not info.head_oid or not info.branch:
746
+ raise FinalizerError(
747
+ ErrorCode.UNBORN_REPO if info.is_unborn else ErrorCode.DETACHED_HEAD,
748
+ "正常模式拒绝 unborn HEAD(要求已有非空 attached branch)"
749
+ if info.is_unborn
750
+ else "正常模式要求已有非空 attached branch",
751
+ )
752
+ remote_name, target_branch = repo_state.resolve_configured_upstream(repo, info.branch)
753
+ summary.upstream = f"{remote_name}/{target_branch}"
754
+
755
+ trailers = trailer_mod.build_provenance_trailers(
756
+ trailer_agent=cli.trailer_agent,
757
+ trace_ref=cli.trace_ref,
758
+ snapshot_id=cli.snapshot,
759
+ )
760
+ policy_mod.enforce_declarative_policy(
761
+ policy,
762
+ branch=info.branch,
763
+ requested_paths=paths,
764
+ trailers=trailers,
765
+ active_scanners=list(cli.scanners),
766
+ mutating_commit=(cli.action != "verify-only"),
767
+ )
768
+
769
+ specs: list[validation.ExceptionSpec] = []
770
+ if cli.fixture_exceptions:
771
+ if cli.action in {"verify-only", "commit-only"}:
772
+ try:
773
+ remote_url = repo_state.validate_remote_endpoints(repo, "origin")
774
+ except FinalizerError as exc:
775
+ raise FinalizerError(
776
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
777
+ "fixture exception 文件无效;未执行 push",
778
+ final_phase="preflight",
779
+ ) from exc
780
+ elif cli.action == "initial-commit-only":
781
+ raise FinalizerError(
782
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
783
+ "fixture exception 文件无效;未执行 push",
784
+ final_phase="preflight",
785
+ )
786
+ else:
787
+ remote_url = repo_state.validate_remote_endpoints(repo, remote_name or "")
788
+ specs = validation.load_fixture_exceptions(
789
+ cli.fixture_exceptions,
790
+ repo=repo,
791
+ remote_url=remote_url,
792
+ local_only=(cli.action in {"verify-only", "commit-only"}),
793
+ phase="worktree",
794
+ head_ref="HEAD",
795
+ baseline_ref=None if info.is_unborn else "HEAD",
796
+ final_phase="preflight",
797
+ )
798
+
799
+ # 2. Isolated staging & full local validation BEFORE mutating `.git/index` OR `.git/objects`.
800
+ summary.final_phase = "local_validation"
801
+ idx_before_res = run_git(repo, "ls-files", "--stage")
802
+ idx_before = idx_before_res.stdout.decode("utf-8", errors="replace") if idx_before_res.returncode == 0 else ""
803
+
804
+ with isolated_staging_env(repo, info.git_dir, info.common_dir) as (iso_env, _):
805
+ outcome = validation.validate_staged_candidate(
806
+ repo,
807
+ info,
808
+ iso_env,
809
+ paths,
810
+ cli,
811
+ policy,
812
+ specs=specs,
813
+ local_only=local_only,
814
+ )
815
+ summary.warnings.extend(outcome.warnings)
816
+ summary.fixture_exceptions.extend(outcome.fixture_exceptions)
817
+ summary.reviewed_sensitive_sources.extend(outcome.reviewed_sensitive_sources)
818
+ summary.external_scanners = list(outcome.external_scanners)
819
+ summary.policy_verdict = outcome.policy_verdict
820
+
821
+ if cli.action == "verify-only":
822
+ idx_after_res = run_git(repo, "ls-files", "--stage")
823
+ idx_after = idx_after_res.stdout.decode("utf-8", errors="replace") if idx_after_res.returncode == 0 else ""
824
+ _, _, wt_after = repo_state.working_tree_dirty_status(repo)
825
+ head_after_res = run_git(repo, "rev-parse", "--verify", "HEAD^{commit}")
826
+ head_after = head_after_res.stdout.decode("ascii", errors="strict").strip() if head_after_res.returncode == 0 else None
827
+ if head_after != info.head_oid or idx_after != idx_before or wt_after != wt_before:
828
+ raise FinalizerError(
829
+ ErrorCode.POST_VERIFY_FAILED,
830
+ "verify-only 验证期间仓库状态发生变化",
831
+ status="failed",
832
+ final_phase="local_validation",
833
+ )
834
+ summary.head_after = head_after
835
+ summary.head_unchanged = True
836
+ summary.index_unchanged = True
837
+ summary.worktree_state = wt_after
838
+ summary.worktree_unchanged = True
839
+ summary.mode_state = "passed"
840
+ summary.commit_result = "skipped_by_verify_only"
841
+ summary.push_result = "skipped_by_verify_only"
842
+ summary.post_verify = "skipped_by_verify_only"
843
+ summary.remote_conclusion = "skipped_by_verify_only"
844
+ summary.completed_through = "local_validation"
845
+ summary.status = "success"
846
+ summary.exit_code = 0
847
+ summary.next_action = "none"
848
+ if not cli.summary:
849
+ status_short = run_git(repo, "status", "--short").stdout.decode("utf-8", errors="replace").strip()
850
+ for line in (
851
+ "\n== Verify-only 结果 ==",
852
+ "mode: verify-only",
853
+ "local validation: passed",
854
+ "commit: skipped (--mode verify-only)",
855
+ "push: skipped (--mode verify-only)",
856
+ "remote verification: skipped (--mode verify-only)",
857
+ f"HEAD before: {info.head_oid}",
858
+ f"HEAD after: {head_after}",
859
+ "HEAD unchanged: yes",
860
+ "index unchanged: yes",
861
+ f"worktree before: {wt_before}",
862
+ f"worktree after: {wt_after}",
863
+ "worktree unchanged: yes",
864
+ "$ git status --short",
865
+ status_short or "(clean)",
866
+ ):
867
+ print(line, flush=True)
868
+ _emit("Git Finalizer 完成:本地验证通过;未执行 add、commit、push 或远端验证。", quiet=cli.summary)
869
+ return 0, summary
870
+
871
+ # 3. Remote preflight for remote-publishing modes BEFORE mutating real `.git/index`.
872
+ if cli.action == "initial-publish":
873
+ summary.final_phase = "remote_preflight"
874
+ assert remote_name is not None
875
+ refs, _ = _ls_remote_refs(repo, remote_name)
876
+ if refs:
877
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "远端不是完全空 remote;未执行新增 git add、commit 或 push", final_phase="remote_preflight")
878
+ summary.remote_conclusion = "empty_remote_verified"
879
+ elif cli.action == "initial-branch-publish":
880
+ summary.final_phase = "remote_preflight"
881
+ assert remote_name is not None and info.branch is not None and info.head_oid is not None
882
+ branch_ref = f"refs/heads/{info.branch}"
883
+ remote_refs_before, _ = _ls_remote_refs(repo, remote_name)
884
+ if branch_ref in remote_refs_before:
885
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, f"远端目标 branch 已存在: {branch_ref}", final_phase="remote_preflight")
886
+ local_tags_before = _snapshot_tags(repo)
887
+ _fetch_remote(repo, remote_name, phase="remote_preflight")
888
+ remote_refs_after, _ = _ls_remote_refs(repo, remote_name)
889
+ if remote_refs_after != remote_refs_before:
890
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "fetch 期间远端 refs 发生变化;未执行 commit", final_phase="remote_preflight")
891
+ head_oids = [oid for ref, oid in remote_refs_before.items() if ref.startswith("refs/heads/")]
892
+ range_commits = _unpublished_commits(repo, info.head_oid, head_oids)
893
+ if range_commits:
894
+ rng_out = validation.validate_commit_range(repo, info, range_commits, cli, policy, specs=specs, local_only=False)
895
+ summary.fixture_exceptions.extend(rng_out.fixture_exceptions)
896
+ summary.warnings.extend(rng_out.warnings)
897
+ summary.remote_conclusion = "target_absent_verified"
898
+ elif cli.action == "normal":
899
+ summary.final_phase = "remote_preflight"
900
+ assert remote_name is not None and target_branch is not None
901
+ local_oid, upstream_oid, ahead, _, _ = _check_normal_remote_state(repo, remote_name, target_branch, phase_label="commit 前 ")
902
+ if ahead > 0:
903
+ if cli.fixture_exceptions:
904
+ raise FinalizerError(
905
+ ErrorCode.CLI_INVALID_ARGS,
906
+ "normal fixture review 要求 HEAD 与 upstream 对齐;existing commits 使用 resume-publish",
907
+ final_phase="remote_preflight",
908
+ )
909
+ range_commits = _unpublished_commits(repo, local_oid, [upstream_oid])
910
+ if range_commits:
911
+ rng_out = validation.validate_commit_range(repo, info, range_commits, cli, policy, specs=specs, local_only=False)
912
+ summary.warnings.extend(rng_out.warnings)
913
+
914
+ # 4. Stage validated paths onto real `.git/index` and assert exact write-tree equality (TOCTOU guard).
915
+ summary.final_phase = "staging"
916
+ retained = _retained_staged_deletions(repo, paths, is_unborn=info.is_unborn)
917
+ for rel_del in sorted(retained):
918
+ _emit(f"保留已暂存删除及本地忽略副本: {rel_del}", quiet=cli.summary)
919
+ paths_to_add = [p for p in paths if p not in retained]
920
+ if paths_to_add:
921
+ add_res = run_git(repo, "--literal-pathspecs", "add", "-A", "--", *paths_to_add)
922
+ if add_res.returncode != 0:
923
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "git add 失败;未执行 commit 或 push", status="failed", final_phase="staging")
924
+
925
+ # Verify staged scope matches candidate validation exact tree OID.
926
+ tree_res = run_git(repo, "write-tree")
927
+ if tree_res.returncode != 0:
928
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法生成已验证 index tree", status="failed", final_phase="staging")
929
+ expected_tree_oid = tree_res.stdout.decode("ascii", errors="strict").strip()
930
+ if outcome.tree_oid and expected_tree_oid != outcome.tree_oid:
931
+ raise FinalizerError(
932
+ ErrorCode.INDEX_UNCLEAN,
933
+ "真实 staging tree 与隔离候选 tree 不一致(工作区在验证后发生修改);未执行 commit",
934
+ status="failed",
935
+ final_phase="staging",
936
+ )
937
+ if cli.action == "initial-publish" and cli.snapshot:
938
+ snapshot_verify.verify_snapshot_evidence(cli.snapshot, repo, "index", paths)
939
+ summary.snapshot_verification = "index_verified"
940
+
941
+ # 5. Commit with optional AI provenance trailers.
942
+ summary.final_phase = "commit"
943
+ assert cli.message is not None
944
+ commit_message = trailer_mod.format_commit_message_with_trailers(repo, cli.message, trailers)
945
+ if not cli.summary:
946
+ diff_ns = run_git(repo, "--literal-pathspecs", "diff", "--cached", "--name-status", "--no-renames")
947
+ print("\n== 显式暂存 ==", flush=True)
948
+ print("$ git diff --cached --name-status --no-renames", flush=True)
949
+ print(diff_ns.stdout.decode("utf-8", errors="replace").strip() or "(empty)", flush=True)
950
+ print("$ git diff --cached --check", flush=True)
951
+ print("(passed)", flush=True)
952
+ print("\n== Commit ==", flush=True)
953
+ print(f"$ git commit -m <explicit message> (branch={info.branch}, paths={len(paths)})", flush=True)
954
+ sym_before = run_git(repo, "symbolic-ref", "--quiet", "HEAD").stdout.decode("utf-8", errors="strict").strip()
955
+ commit_res = run_git(repo, "commit", "-m", commit_message)
956
+ if not cli.summary:
957
+ out_txt = commit_res.stdout.decode("utf-8", errors="replace").strip()
958
+ if out_txt:
959
+ print(out_txt, flush=True)
960
+
961
+ head_after_commit = run_git(repo, "rev-parse", "--verify", "HEAD^{commit}")
962
+ commit_hash = head_after_commit.stdout.decode("ascii", errors="strict").strip() if head_after_commit.returncode == 0 else None
963
+ if not commit_hash or commit_hash == local_head_before_commit:
964
+ raise FinalizerError(
965
+ ErrorCode.COMMIT_FAILED,
966
+ f"git commit 失败,未创建 commit: {commit_res.stderr.decode('utf-8', errors='replace').strip()}",
967
+ status="failed",
968
+ final_phase="commit",
969
+ )
970
+
971
+ summary.commit_created = True
972
+ summary.commit_sha = commit_hash
973
+ summary.completed_through = "commit"
974
+
975
+ def _fail_created_commit(code: str, msg: str, phase: str = "post_commit_verify") -> FinalizerError:
976
+ if cli.action == "initial-publish":
977
+ summary.mode_state = "commit_retained"
978
+ summary.resume_required = True
979
+ summary.resume_oid = commit_hash
980
+ summary.resume_remote = remote_name
981
+ return FinalizerError(
982
+ code,
983
+ msg,
984
+ status="failed",
985
+ final_phase=phase,
986
+ next_action="resume_initial_publish",
987
+ commit_created=True,
988
+ commit_sha=commit_hash,
989
+ resume={"head_oid": commit_hash, "remote": remote_name},
990
+ )
991
+ if cli.action == "initial-commit-only":
992
+ summary.mode_state = "commit_retained"
993
+ summary.push_result = "skipped_by_initial_commit_only"
994
+ summary.post_verify = "skipped_by_initial_commit_only"
995
+ summary.remote_conclusion = "skipped_by_initial_commit_only"
996
+ return FinalizerError(
997
+ code,
998
+ msg,
999
+ status="failed",
1000
+ final_phase=phase,
1001
+ next_action="inspect_local_root_commit",
1002
+ commit_created=True,
1003
+ commit_sha=commit_hash,
1004
+ )
1005
+ if cli.action == "initial-branch-publish":
1006
+ summary.mode_state = "commit_retained"
1007
+ return FinalizerError(
1008
+ code,
1009
+ msg,
1010
+ status="failed",
1011
+ final_phase=phase,
1012
+ next_action="inspect_initial_branch_publish_failure",
1013
+ commit_created=True,
1014
+ commit_sha=commit_hash,
1015
+ )
1016
+ return FinalizerError(
1017
+ code,
1018
+ msg,
1019
+ status="failed",
1020
+ final_phase=phase,
1021
+ next_action="inspect_failure_with_local_commit_retained",
1022
+ commit_created=True,
1023
+ commit_sha=commit_hash,
1024
+ )
1025
+
1026
+ if commit_res.returncode != 0:
1027
+ raise _fail_created_commit(
1028
+ ErrorCode.HOOK_FAILED,
1029
+ "git commit 返回失败但 HEAD 已改变;保留本地 commit,未执行 push",
1030
+ phase="commit",
1031
+ )
1032
+
1033
+ # 6. Post-commit structural, tree, parent, scope, and baseline-aware reviewed-source verification.
1034
+ summary.final_phase = "post_commit_verify"
1035
+ sym_after = run_git(repo, "symbolic-ref", "--quiet", "HEAD")
1036
+ if sym_after.returncode != 0 or sym_after.stdout.decode("utf-8", errors="strict").strip() != sym_before:
1037
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "commit 后 attached branch 发生变化或 detached")
1038
+
1039
+ expected_parents = [commit_hash]
1040
+ if local_head_before_commit:
1041
+ expected_parents.append(local_head_before_commit)
1042
+ if info.merge_parent:
1043
+ expected_parents.append(info.merge_parent)
1044
+ parents_res = run_git(repo, "rev-list", "--parents", "-n", "1", commit_hash)
1045
+ if parents_res.returncode != 0 or parents_res.stdout.decode("ascii", errors="strict").strip().split() != expected_parents:
1046
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "commit parents 与已验证 HEAD 不一致;未执行 push")
1047
+
1048
+ ct_res = run_git(repo, "rev-parse", f"{commit_hash}^{{tree}}")
1049
+ if ct_res.returncode != 0 or ct_res.stdout.decode("ascii", errors="strict").strip() != expected_tree_oid:
1050
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "commit tree 与已验证 index tree 不一致;检查 commit hooks,未执行 push")
1051
+
1052
+ diff_t = run_git(repo, "diff-tree", "--root", "--diff-merges=first-parent", "--no-commit-id", "--name-only", "-r", "--no-renames", "-z", commit_hash)
1053
+ if diff_t.returncode != 0:
1054
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "无法读取 commit 文件范围;保留本地 commit,未执行 push")
1055
+ committed_paths = parse_nul_records(diff_t.stdout)
1056
+ extra_committed = [p for p in committed_paths if p not in set(paths)]
1057
+ if extra_committed:
1058
+ raise _fail_created_commit(ErrorCode.SCOPE_INVALID, f"commit 包含超出显式范围的文件: {', '.join(extra_committed)}")
1059
+
1060
+ if cli.reviewed_sensitive_source:
1061
+ # P0 FIX (v1.9.9 regression): verify created commit blobs against first parent (or None on root commit).
1062
+ summary.reviewed_sensitive_sources = source_review.validate_review_document(
1063
+ review_file=cli.reviewed_sensitive_source,
1064
+ repo=repo,
1065
+ common_dir=info.common_dir,
1066
+ repository_id=cli.repository_id,
1067
+ allocation_id=cli.allocation_id,
1068
+ task_key=cli.task_key,
1069
+ authority_key=cli.authority_key,
1070
+ worktree_path=cli.worktree_path,
1071
+ requested_paths=paths,
1072
+ stage="head",
1073
+ allowed_extensions=policy.allow_reviewed_extensions,
1074
+ commit_ref=commit_hash,
1075
+ baseline_ref=local_head_before_commit,
1076
+ )
1077
+ for rec in summary.reviewed_sensitive_sources:
1078
+ rec["content_scan"] = "passed"
1079
+
1080
+ if cli.agent_trace:
1081
+ summary.agent_trace_note = trailer_mod.write_agent_trace_note(
1082
+ repo,
1083
+ commit_hash,
1084
+ paths,
1085
+ trailer_agent=cli.trailer_agent,
1086
+ trace_ref=cli.trace_ref,
1087
+ snapshot_id=cli.snapshot,
1088
+ task_key=cli.task_key,
1089
+ allocation_id=cli.allocation_id,
1090
+ )
1091
+
1092
+ if cli.action == "initial-publish" and cli.snapshot:
1093
+ snapshot_verify.verify_snapshot_evidence(cli.snapshot, repo, "head", paths)
1094
+ summary.snapshot_verification = "passed"
1095
+
1096
+ _emit(f"commit hash: {commit_hash}", quiet=cli.summary)
1097
+
1098
+ if cli.action in {"commit-only", "initial-commit-only"}:
1099
+ skip_tag = "initial_commit_only" if cli.action == "initial-commit-only" else "commit_only"
1100
+ _, _, wt_final = repo_state.working_tree_dirty_status(repo)
1101
+ if cli.action == "initial-commit-only":
1102
+ if wt_final != "clean" or run_git(repo, "diff", "--cached", "--quiet").returncode != 0:
1103
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "root commit 后 worktree 或 index 不干净")
1104
+ summary.mode_state = "committed"
1105
+ summary.worktree_state = wt_final
1106
+ summary.push_result = f"skipped_by_{skip_tag}"
1107
+ summary.post_verify = f"skipped_by_{skip_tag}"
1108
+ summary.remote_conclusion = f"skipped_by_{skip_tag}"
1109
+ summary.status = "success"
1110
+ summary.exit_code = 0
1111
+ summary.next_action = "none"
1112
+ if not cli.summary:
1113
+ skip_display = "--initial-commit-only" if cli.action == "initial-commit-only" else "--mode commit-only"
1114
+ result_mode = "initial-commit-only" if cli.action == "initial-commit-only" else "commit-only"
1115
+ status_short = run_git(repo, "status", "--short").stdout.decode("utf-8", errors="replace").strip()
1116
+ for line in (
1117
+ f"mode: {result_mode}",
1118
+ f"commit hash: {commit_hash}",
1119
+ f"push: skipped ({skip_display})",
1120
+ f"remote verification: skipped ({skip_display})",
1121
+ "$ git status --short",
1122
+ status_short or "(clean)",
1123
+ ):
1124
+ print(line, flush=True)
1125
+ return 0, summary
1126
+
1127
+ # 7. Push & post-push verification per publishing mode.
1128
+ if cli.action == "initial-publish":
1129
+ assert remote_name is not None and info.branch is not None
1130
+ branch_ref = f"refs/heads/{info.branch}"
1131
+ pre_push_refs, _ = _ls_remote_refs(repo, remote_name)
1132
+ if pre_push_refs:
1133
+ raise _fail_created_commit(
1134
+ ErrorCode.REMOTE_DIVERGED,
1135
+ "commit 后远端不是完全空 remote;保留本地 root commit,未执行 push",
1136
+ phase="post_commit_verify",
1137
+ )
1138
+ summary.remote_conclusion = "empty_remote_reverified"
1139
+ summary.final_phase = "push"
1140
+ summary.push_executed = True
1141
+ summary.push_branch_refspec_only = True
1142
+ summary.push_follow_tags_requested = False
1143
+ if not cli.summary:
1144
+ print("\n== Root commit 后远端空状态复查 ==", flush=True)
1145
+ print(f"$ git ls-remote -- {remote_name}", flush=True)
1146
+ print("(verified empty)", flush=True)
1147
+ print("\n== Initial push ==", flush=True)
1148
+ print(f"$ git push --no-follow-tags --set-upstream -- {remote_name} HEAD:{branch_ref}", flush=True)
1149
+ push_res = _run_remote_push(
1150
+ repo,
1151
+ "push",
1152
+ "--no-follow-tags",
1153
+ "--set-upstream",
1154
+ "--",
1155
+ remote_name,
1156
+ f"HEAD:{branch_ref}",
1157
+ )
1158
+ if not cli.summary and push_res.returncode == 0:
1159
+ for chunk in (push_res.stdout, push_res.stderr):
1160
+ txt = chunk.decode("utf-8", errors="replace").strip()
1161
+ if txt:
1162
+ print(txt, flush=True)
1163
+ if push_res.returncode != 0:
1164
+ summary.push_result = "uncertain"
1165
+ raise _fail_created_commit(ErrorCode.PUSH_FAILED, "initial push 失败或结果无法确认", phase="push")
1166
+ summary.push_result = "succeeded"
1167
+ summary.mode_state = "pushed"
1168
+ summary.final_phase = "post_verify"
1169
+ up_state, up_oid, up_err = _classify_branch_upstream(repo, info.branch, remote_name, branch_ref)
1170
+ remote_refs, _ = _ls_remote_refs(repo, remote_name)
1171
+ if len(remote_refs) != 1 or remote_refs.get(branch_ref) != commit_hash:
1172
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "push 后远端 ref 集合不是唯一目标 branch", phase="post_verify")
1173
+ if up_state != "exact_resolved" or up_oid != commit_hash:
1174
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, up_err or "initial push 后 upstream 与远端 OID 未对齐", phase="post_verify")
1175
+ _, _, wt_final = repo_state.working_tree_dirty_status(repo)
1176
+ if wt_final != "clean":
1177
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "initial push 后 worktree 不干净", phase="post_verify")
1178
+ summary.post_verify = "passed"
1179
+ summary.remote_conclusion = "published_and_upstream_aligned"
1180
+ summary.mode_state = "verified"
1181
+ if not cli.summary:
1182
+ for line in (
1183
+ "\n== Initial push 后验证 ==",
1184
+ "$ git rev-parse HEAD",
1185
+ commit_hash,
1186
+ "$ git rev-parse @{upstream}",
1187
+ up_oid,
1188
+ f"$ git ls-remote --heads -- {remote_name}",
1189
+ f"{remote_refs.get(branch_ref)}\t{branch_ref}",
1190
+ f"branch: {info.branch}",
1191
+ f"remote: {remote_name}",
1192
+ f"upstream: {summary.upstream}",
1193
+ "local branch, tags, and Git config: verified",
1194
+ "worktree state: clean",
1195
+ "post-verify: passed",
1196
+ ):
1197
+ print(line, flush=True)
1198
+ elif cli.action == "initial-branch-publish":
1199
+ assert remote_name is not None and info.branch is not None
1200
+ branch_ref = f"refs/heads/{info.branch}"
1201
+ live_refs, _ = _ls_remote_refs(repo, remote_name)
1202
+ if branch_ref in live_refs:
1203
+ raise _fail_created_commit(ErrorCode.REMOTE_DIVERGED, "远端目标 branch 已在 push 前出现")
1204
+ if live_refs != remote_refs_before:
1205
+ raise _fail_created_commit(ErrorCode.REMOTE_DIVERGED, "commit 后远端 refs 发生变化,拒绝 initial-branch push")
1206
+ summary.remote_conclusion = "target_absent_reverified"
1207
+ summary.final_phase = "push"
1208
+ summary.push_executed = True
1209
+ summary.push_branch_refspec_only = True
1210
+ summary.push_follow_tags_requested = False
1211
+ push_res = _run_remote_push(
1212
+ repo,
1213
+ "push",
1214
+ "--no-follow-tags",
1215
+ "--set-upstream",
1216
+ "--",
1217
+ remote_name,
1218
+ f"HEAD:{branch_ref}",
1219
+ )
1220
+ if push_res.returncode != 0:
1221
+ summary.push_result = "uncertain"
1222
+ raise _fail_created_commit(ErrorCode.PUSH_FAILED, "initial branch push 失败或结果无法确认", phase="push")
1223
+ summary.push_result = "succeeded"
1224
+ summary.mode_state = "pushed"
1225
+ summary.final_phase = "post_verify"
1226
+ post_refs, _ = _ls_remote_refs(repo, remote_name)
1227
+ other_post = {k: v for k, v in post_refs.items() if k != branch_ref}
1228
+ if post_refs.get(branch_ref) != commit_hash or other_post != remote_refs_before or _snapshot_tags(repo) != local_tags_before:
1229
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "push 后远端 branch 或非目标 refs/tags 校验失败", phase="post_verify")
1230
+ up_state, up_oid, up_err = _classify_branch_upstream(repo, info.branch, remote_name, branch_ref)
1231
+ if up_state != "exact_resolved" or up_oid != commit_hash:
1232
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, up_err or "push 后 upstream 未对齐", phase="post_verify")
1233
+ summary.post_verify = "passed"
1234
+ summary.remote_conclusion = "published_and_upstream_aligned"
1235
+ summary.mode_state = "verified"
1236
+ if not cli.summary:
1237
+ for line in (
1238
+ "\n== 显式暂存 ==",
1239
+ f"staged paths: {', '.join(paths)}",
1240
+ "\n== Commit ==",
1241
+ f"commit hash: {commit_hash}",
1242
+ "\n== Initial push ==",
1243
+ f"$ git push --no-follow-tags --set-upstream -- {remote_name} HEAD:{branch_ref}",
1244
+ "\n== Initial push 后验证 ==",
1245
+ f"branch: {info.branch}",
1246
+ f"remote: {remote_name}",
1247
+ f"head: {commit_hash}",
1248
+ f"remote ref ({branch_ref}): {post_refs.get(branch_ref)}",
1249
+ f"upstream: {summary.upstream}",
1250
+ "local branch, tags, and Git config: verified",
1251
+ "post-verify: passed",
1252
+ ):
1253
+ print(line, flush=True)
1254
+ else:
1255
+ # normal
1256
+ assert remote_name is not None and target_branch is not None
1257
+ if not cli.summary:
1258
+ print("\n== Commit 后 fetch 与 fast-forward 检查 ==", flush=True)
1259
+ print(f"$ git fetch --prune -- {remote_name}", flush=True)
1260
+ _check_normal_remote_state(
1261
+ repo,
1262
+ remote_name,
1263
+ target_branch,
1264
+ phase_label="commit 后 ",
1265
+ phase_name="post_commit_verify",
1266
+ commit_created=True,
1267
+ commit_sha=commit_hash,
1268
+ )
1269
+ summary.final_phase = "push"
1270
+ summary.push_executed = True
1271
+ summary.push_branch_refspec_only = True
1272
+ summary.push_follow_tags_requested = False
1273
+ if not cli.summary:
1274
+ print("\n== Push ==", flush=True)
1275
+ print(f"$ git push --no-follow-tags -- {remote_name} HEAD:refs/heads/{target_branch}", flush=True)
1276
+ push_res = _run_remote_push(
1277
+ repo,
1278
+ "push",
1279
+ "--no-follow-tags",
1280
+ "--",
1281
+ remote_name,
1282
+ f"HEAD:refs/heads/{target_branch}",
1283
+ )
1284
+ if not cli.summary and push_res.returncode == 0:
1285
+ for chunk in (push_res.stdout, push_res.stderr):
1286
+ txt = chunk.decode("utf-8", errors="replace").strip()
1287
+ if txt:
1288
+ print(txt, flush=True)
1289
+ if push_res.returncode != 0:
1290
+ summary.push_result = "uncertain"
1291
+ raise _fail_created_commit(ErrorCode.PUSH_FAILED, "git push 失败", phase="push")
1292
+ summary.push_result = "succeeded"
1293
+ summary.final_phase = "post_verify"
1294
+ local_after, upstream_after, ahead_after, behind_after, remote_after = _check_normal_remote_state(
1295
+ repo,
1296
+ remote_name,
1297
+ target_branch,
1298
+ phase_label="push 后 ",
1299
+ phase_name="post_verify",
1300
+ commit_created=True,
1301
+ commit_sha=commit_hash,
1302
+ )
1303
+ if local_after != commit_hash or upstream_after != commit_hash or remote_after != commit_hash or ahead_after != 0 or behind_after != 0:
1304
+ raise _fail_created_commit(ErrorCode.POST_VERIFY_FAILED, "push 后本地 HEAD 与远端 branch / upstream 未对齐", phase="post_verify")
1305
+ summary.post_verify = "passed"
1306
+ if not cli.summary:
1307
+ for line in (
1308
+ "\n== Push 后验证 ==",
1309
+ "$ git rev-parse HEAD",
1310
+ local_after,
1311
+ "$ git rev-parse @{upstream}",
1312
+ upstream_after,
1313
+ f"remote branch OID: {remote_after}",
1314
+ f"ahead/behind: {ahead_after}\t{behind_after}",
1315
+ "$ git status --short",
1316
+ "(clean)",
1317
+ "post-verify: passed",
1318
+ ):
1319
+ print(line, flush=True)
1320
+
1321
+ summary.completed_through = "post_verify"
1322
+ summary.status = "success"
1323
+ summary.exit_code = 0
1324
+ summary.next_action = "none"
1325
+ _emit("\nGit Finalizer 完成:commit 与 push 已验证。", quiet=cli.summary)
1326
+ return 0, summary
1327
+
1328
+
1329
+ def _run_publish_existing_branch_or_history(cli: ParsedCLI, summary: SummaryState) -> tuple[int, SummaryState]:
1330
+ is_history = cli.action in {"publish-existing-history", "resume-existing-history-publish"}
1331
+ is_resume_history = cli.action == "resume-existing-history-publish"
1332
+ summary.mode = "resume" if is_resume_history else ("publish_existing_history" if is_history else "publish_existing_branch")
1333
+ summary.commit_reused = True
1334
+ summary.commit_result = "reused"
1335
+ if is_resume_history:
1336
+ summary.resume_publish_kind = "existing_history_first"
1337
+ summary.recovery_start = "existing_history_first_publish"
1338
+
1339
+ info = repo_state.inspect_repository(cli.repo, merge_parent_arg=None, mode=cli.action, require_attached=True)
1340
+ repo = info.repo
1341
+ summary.repository = str(repo)
1342
+ _require_clean_repo_state(repo, info)
1343
+ policy = policy_mod.load_delivery_policy(repo)
1344
+ assert info.branch is not None and info.head_oid is not None
1345
+
1346
+ expected_oid = validate_oid(cli.head_oid or "", "expected HEAD")
1347
+ if expected_oid != info.head_oid:
1348
+ raise FinalizerError(ErrorCode.REPO_INVALID, "当前 HEAD 与 expected HEAD 不一致")
1349
+ if not is_history and repo_state.is_protected_branch(info.branch, policy):
1350
+ raise FinalizerError(ErrorCode.BRANCH_PROTECTED, f"publish-existing-branch 拒绝受保护分支: {info.branch}")
1351
+ if cli.remote_branch != info.branch:
1352
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "本地 branch 名必须与 --remote-branch 完全一致")
1353
+ remote = validate_remote_name(cli.remote or "")
1354
+ remote_url = repo_state.validate_remote_endpoints(repo, remote)
1355
+ branch_ref = f"refs/heads/{info.branch}"
1356
+
1357
+ up_state, up_oid, up_err = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1358
+ if not is_history and up_state != "none":
1359
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, "publish-existing-branch 只接受尚未配置 upstream 的本地 branch")
1360
+ if is_history and not is_resume_history and up_state not in {"none", "exact_unresolved"}:
1361
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, "existing-history first publication 只接受无 upstream 或精确未解析 upstream")
1362
+ if is_resume_history and (up_state == "conflicting" or (up_state == "exact_resolved" and up_oid != expected_oid)):
1363
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, up_err or "existing-history resume upstream 与 expected target 不一致")
1364
+
1365
+ summary.branch = info.branch
1366
+ summary.upstream = f"{remote}/{info.branch}"
1367
+ summary.commit_sha = expected_oid
1368
+ summary.head_before = expected_oid
1369
+ summary.worktree_before_state = "clean"
1370
+ summary.push_target = f"{remote}:{branch_ref}"
1371
+
1372
+ baseline = _snapshot_local_state(repo)
1373
+ specs = (
1374
+ validation.load_fixture_exceptions(
1375
+ cli.fixture_exceptions,
1376
+ repo=repo,
1377
+ remote_url=remote_url,
1378
+ local_only=False,
1379
+ phase="history",
1380
+ head_ref=expected_oid,
1381
+ final_phase="preflight",
1382
+ )
1383
+ if cli.fixture_exceptions
1384
+ else []
1385
+ )
1386
+ reviewed_blobs: dict[str, str] | None = None
1387
+ if cli.reviewed_sensitive_source:
1388
+ summary.reviewed_sensitive_sources = source_review.validate_review_document(
1389
+ review_file=cli.reviewed_sensitive_source,
1390
+ repo=repo,
1391
+ common_dir=info.common_dir,
1392
+ repository_id=cli.repository_id,
1393
+ allocation_id=cli.allocation_id,
1394
+ task_key=cli.task_key,
1395
+ authority_key=cli.authority_key,
1396
+ worktree_path=cli.worktree_path,
1397
+ requested_paths=cli.paths,
1398
+ stage="head",
1399
+ allowed_extensions=policy.allow_reviewed_extensions,
1400
+ commit_ref=expected_oid,
1401
+ baseline_ref=f"{expected_oid}^1" if run_git(repo, "rev-parse", "--verify", f"{expected_oid}^1").returncode == 0 else None,
1402
+ )
1403
+ for rec in summary.reviewed_sensitive_sources:
1404
+ rec["content_scan"] = "passed"
1405
+ reviewed_blobs = source_review.reviewed_blob_map(repo, summary.reviewed_sensitive_sources, commit_ref=expected_oid)
1406
+
1407
+ summary.final_phase = "remote_preflight"
1408
+ refs_before, _ = _ls_remote_refs(repo, remote)
1409
+ if is_history:
1410
+ if not is_resume_history and refs_before:
1411
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "远端不是完全空 repository(包含非目标用户 Git refs);existing-history first publication 已阻断", final_phase="remote_preflight")
1412
+ if is_resume_history and refs_before and refs_before != {branch_ref: expected_oid}:
1413
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "远端包含冲突或意外分支,拒绝 resume-existing-history-publish", final_phase="remote_preflight")
1414
+ elif branch_ref in refs_before:
1415
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, f"远端目标 branch 已存在: {branch_ref}", final_phase="remote_preflight")
1416
+
1417
+ _fetch_remote(repo, remote, phase="remote_preflight")
1418
+ refs_after_fetch, _ = _ls_remote_refs(repo, remote)
1419
+ if refs_after_fetch != refs_before:
1420
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "fetch 期间远端 refs 发生变化;未执行 push", final_phase="remote_preflight")
1421
+ _assert_local_state_unchanged(repo, baseline, phase="remote_preflight")
1422
+
1423
+ remote_heads = [oid for ref, oid in refs_before.items() if ref.startswith("refs/heads/")] if not is_history else []
1424
+ commits = _unpublished_commits(repo, expected_oid, remote_heads)
1425
+ summary.publish_commit_count = len(commits)
1426
+ summary.publish_range = (
1427
+ f"{expected_oid} --not captured:{remote}/heads" if not is_history else f"{len(commits)} commits up to {expected_oid}"
1428
+ )
1429
+ if is_history and not commits:
1430
+ raise FinalizerError(ErrorCode.REPO_INVALID, "existing-history publication 要求至少一个本地 commit", final_phase="remote_preflight")
1431
+ if commits:
1432
+ rng_out = validation.validate_commit_range(
1433
+ repo,
1434
+ info,
1435
+ commits,
1436
+ cli,
1437
+ policy,
1438
+ specs=specs,
1439
+ local_only=False,
1440
+ reviewed_blobs=reviewed_blobs,
1441
+ )
1442
+ summary.fixture_exceptions.extend(rng_out.fixture_exceptions)
1443
+ summary.warnings.extend(rng_out.warnings)
1444
+ elif specs:
1445
+ raise FinalizerError(ErrorCode.FIXTURE_EXCEPTION_BLOCKED, "fixture exception 未匹配待发布历史中的 exact path/blob/detector", final_phase="remote_preflight")
1446
+
1447
+ _assert_local_state_unchanged(repo, baseline, phase="remote_preflight")
1448
+ summary.completed_through = "preflight"
1449
+ summary.remote_conclusion = (
1450
+ "target_absent_reverified"
1451
+ if not is_history
1452
+ else ("empty_or_expected_target_reverified" if is_resume_history else "empty_repository_reverified")
1453
+ )
1454
+
1455
+ summary.final_phase = "push"
1456
+ summary.push_executed = True
1457
+ summary.push_branch_refspec_only = True
1458
+ summary.push_follow_tags_requested = False
1459
+ push_res = _run_remote_push(repo, "push", "--no-follow-tags", "--set-upstream", "--", remote, f"HEAD:{branch_ref}")
1460
+ if push_res.returncode != 0:
1461
+ summary.push_result = "uncertain"
1462
+ if is_history:
1463
+ summary.resume_required = True
1464
+ summary.resume_oid = expected_oid
1465
+ summary.resume_remote = remote
1466
+ raise FinalizerError(
1467
+ ErrorCode.PUSH_FAILED,
1468
+ "existing-history push 失败或结果无法确认",
1469
+ status="failed",
1470
+ final_phase="push",
1471
+ next_action="resume_existing_history_publish",
1472
+ push_executed=True,
1473
+ push_result="uncertain",
1474
+ resume={"head_oid": expected_oid, "remote": remote},
1475
+ )
1476
+ raise FinalizerError(
1477
+ ErrorCode.PUSH_FAILED,
1478
+ "existing branch push 失败或结果无法确认",
1479
+ status="failed",
1480
+ final_phase="push",
1481
+ next_action="inspect_existing_branch_publish_failure",
1482
+ push_executed=True,
1483
+ push_result="uncertain",
1484
+ )
1485
+ summary.push_result = "succeeded"
1486
+ summary.completed_through = "push"
1487
+ summary.mode_state = "pushed"
1488
+
1489
+ summary.final_phase = "post_verify"
1490
+ post_refs, _ = _ls_remote_refs(repo, remote)
1491
+ expected_other = {k: v for k, v in refs_before.items() if k != branch_ref}
1492
+ actual_other = {k: v for k, v in post_refs.items() if k != branch_ref}
1493
+ if post_refs.get(branch_ref) != expected_oid or actual_other != expected_other:
1494
+ msg = (
1495
+ "push 后远端目标 branch 与 HEAD 不一致"
1496
+ if post_refs.get(branch_ref) != expected_oid
1497
+ else "push 后远端 refs 校验失败"
1498
+ )
1499
+ raise FinalizerError(
1500
+ ErrorCode.POST_VERIFY_FAILED,
1501
+ msg,
1502
+ status="failed",
1503
+ final_phase="post_verify",
1504
+ next_action="resume_existing_history_publish" if is_history else "inspect_existing_branch_publish_failure",
1505
+ push_executed=True,
1506
+ push_result="succeeded",
1507
+ )
1508
+ up_state_after, up_oid_after, _ = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1509
+ if up_state_after != "exact_resolved" or up_oid_after != expected_oid:
1510
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "push 后 upstream 未对齐", status="failed", final_phase="post_verify", push_executed=True, push_result="succeeded")
1511
+ _assert_local_state_unchanged(
1512
+ repo,
1513
+ baseline,
1514
+ phase="post_verify",
1515
+ next_action="resume_existing_history_publish" if is_history else "inspect_existing_branch_publish_failure",
1516
+ push_executed=True,
1517
+ push_result="succeeded",
1518
+ context_label="existing-history publish" if is_history else "existing-branch publish",
1519
+ )
1520
+
1521
+ summary.head_after = expected_oid
1522
+ summary.head_unchanged = True
1523
+ summary.index_unchanged = True
1524
+ summary.worktree_unchanged = True
1525
+ summary.worktree_state = "clean"
1526
+ summary.final_head = expected_oid
1527
+ summary.final_remote_oid = expected_oid
1528
+ summary.post_verify = "passed"
1529
+ summary.remote_conclusion = "published_and_upstream_aligned"
1530
+ summary.completed_through = "post_verify"
1531
+ summary.mode_state = "verified"
1532
+ summary.status = "success"
1533
+ summary.exit_code = 0
1534
+ summary.next_action = "none"
1535
+ return 0, summary
1536
+
1537
+
1538
+ def _run_resume_publish_or_initial(cli: ParsedCLI, summary: SummaryState) -> tuple[int, SummaryState]:
1539
+ is_initial = cli.action == "resume-initial-publish"
1540
+ summary.mode = "resume"
1541
+ summary.mode_state = "recovering"
1542
+ summary.commit_reused = True
1543
+ summary.commit_result = "reused"
1544
+ info = repo_state.inspect_repository(cli.repo, merge_parent_arg=None, mode=cli.action, require_attached=True)
1545
+ repo = info.repo
1546
+ summary.repository = str(repo)
1547
+ if info.is_unborn or not info.head_oid:
1548
+ raise FinalizerError(ErrorCode.UNBORN_REPO, "当前 HEAD 无法解析为 commit", final_phase="preflight")
1549
+ _require_clean_repo_state(repo, info)
1550
+ policy = policy_mod.load_delivery_policy(repo)
1551
+ assert info.branch is not None and info.head_oid is not None
1552
+
1553
+ expected_oid = validate_oid(cli.head_oid or "", "expected HEAD")
1554
+ if expected_oid != info.head_oid:
1555
+ raise FinalizerError(ErrorCode.REPO_INVALID, "当前 HEAD 与 expected HEAD 不一致")
1556
+
1557
+ summary.branch = info.branch
1558
+ summary.commit_sha = expected_oid
1559
+ summary.head_before = expected_oid
1560
+ summary.worktree_before_state = "clean"
1561
+ summary.push_branch_refspec_only = True
1562
+ summary.push_follow_tags_requested = False
1563
+
1564
+ baseline = _snapshot_local_state(repo)
1565
+ branch_ref = f"refs/heads/{info.branch}"
1566
+
1567
+ if is_initial:
1568
+ remote = validate_remote_name(cli.remote or "")
1569
+ remote_url = repo_state.validate_remote_endpoints(repo, remote)
1570
+ summary.resume_publish_kind = "initial_root"
1571
+ summary.upstream = f"{remote}/{info.branch}"
1572
+ summary.push_target = f"{remote}:{branch_ref}"
1573
+ parents_res = run_git(repo, "rev-list", "--parents", "-n", "1", expected_oid)
1574
+ if parents_res.returncode != 0 or parents_res.stdout.decode("ascii").strip().split() != [expected_oid]:
1575
+ raise FinalizerError(ErrorCode.REPO_INVALID, "resume-initial-publish 要求 HEAD 为单一 root commit")
1576
+
1577
+ for fixture_rel in cli.allow_test_fixtures:
1578
+ if not fixture_rel.startswith("tests/") or ".." in Path(fixture_rel).parts:
1579
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"allow-test-fixture 只接受 tests/ 路径: {fixture_rel}")
1580
+ lt = run_git(repo, "--literal-pathspecs", "ls-tree", "-z", expected_oid, "--", fixture_rel)
1581
+ recs = parse_nul_records(lt.stdout) if lt.returncode == 0 else []
1582
+ if len(recs) != 1 or "\t" not in recs[0]:
1583
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"allow-test-fixture 必须指向一个 regular root-commit blob: {fixture_rel}")
1584
+ meta, _, found_p = recs[0].partition("\t")
1585
+ mp = meta.split()
1586
+ if found_p != fixture_rel or len(mp) != 3 or mp[1] != "blob" or mp[0] not in {"100644", "100755"}:
1587
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"allow-test-fixture 必须指向一个 regular root-commit blob: {fixture_rel}")
1588
+
1589
+ specs = (
1590
+ validation.load_fixture_exceptions(
1591
+ cli.fixture_exceptions,
1592
+ repo=repo,
1593
+ remote_url=remote_url,
1594
+ local_only=False,
1595
+ phase="history",
1596
+ head_ref=expected_oid,
1597
+ final_phase="preflight",
1598
+ )
1599
+ if cli.fixture_exceptions
1600
+ else []
1601
+ )
1602
+ reviewed_blobs_init: dict[str, str] | None = None
1603
+ if cli.reviewed_sensitive_source:
1604
+ summary.reviewed_sensitive_sources = source_review.validate_review_document(
1605
+ review_file=cli.reviewed_sensitive_source,
1606
+ repo=repo,
1607
+ common_dir=info.common_dir,
1608
+ repository_id=cli.repository_id,
1609
+ allocation_id=cli.allocation_id,
1610
+ task_key=cli.task_key,
1611
+ authority_key=cli.authority_key,
1612
+ worktree_path=cli.worktree_path,
1613
+ requested_paths=cli.paths,
1614
+ stage="head",
1615
+ allowed_extensions=policy.allow_reviewed_extensions,
1616
+ commit_ref=expected_oid,
1617
+ baseline_ref=None,
1618
+ )
1619
+ for rec in summary.reviewed_sensitive_sources:
1620
+ rec["content_scan"] = "passed"
1621
+ reviewed_blobs_init = source_review.reviewed_blob_map(repo, summary.reviewed_sensitive_sources, commit_ref=expected_oid)
1622
+ summary.publish_commit_count = 1
1623
+ summary.publish_range = expected_oid
1624
+ rng_out = validation.validate_commit_range(
1625
+ repo,
1626
+ info,
1627
+ [expected_oid],
1628
+ cli,
1629
+ policy,
1630
+ specs=specs,
1631
+ local_only=False,
1632
+ reviewed_blobs=reviewed_blobs_init,
1633
+ )
1634
+ summary.fixture_exceptions.extend(rng_out.fixture_exceptions)
1635
+ summary.warnings.extend(rng_out.warnings)
1636
+ summary.completed_through = "preflight"
1637
+
1638
+ up_state, up_oid, up_err = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1639
+ if up_state == "conflicting" or (up_state == "exact_resolved" and up_oid != expected_oid):
1640
+ raise FinalizerError(ErrorCode.UPSTREAM_CONFLICT, up_err or "upstream commit 与 expected HEAD 不一致", final_phase="remote_preflight")
1641
+
1642
+ def _classify_init_remote(refs_map: dict[str, str]) -> tuple[str, str]:
1643
+ if not refs_map:
1644
+ return "A", ""
1645
+ if refs_map == {branch_ref: expected_oid}:
1646
+ return "B", ""
1647
+ if len(refs_map) > 1:
1648
+ return "C", "远端存在额外或含糊的 refs"
1649
+ ref_k, oid_v = next(iter(refs_map.items()))
1650
+ if ref_k == branch_ref:
1651
+ return "C", f"远端目标 branch 指向其他 OID ({oid_v})"
1652
+ return "C", f"远端存在非目标 ref ({ref_k})"
1653
+
1654
+ refs, _ = _ls_remote_refs(repo, remote)
1655
+ r_state, r_err = _classify_init_remote(refs)
1656
+ need_push = False
1657
+ if r_state == "A":
1658
+ summary.recovery_start = "empty_remote"
1659
+ summary.remote_conclusion = "empty_remote"
1660
+ need_push = True
1661
+ elif r_state == "B":
1662
+ summary.remote_conclusion = "expected_branch_present"
1663
+ if up_state != "exact_resolved" or up_oid != expected_oid:
1664
+ summary.recovery_start = "published_without_upstream"
1665
+ need_push = True
1666
+ else:
1667
+ summary.recovery_start = "already_published"
1668
+ else:
1669
+ summary.recovery_start = "conflicting_remote"
1670
+ summary.remote_conclusion = "conflicting_or_ambiguous"
1671
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, f"远端处于冲突或含糊状态;拒绝恢复: {r_err}", final_phase="remote_preflight")
1672
+ summary.completed_through = "remote_classification"
1673
+
1674
+ if need_push:
1675
+ summary.final_phase = "push"
1676
+ summary.push_executed = True
1677
+ push_res = _run_remote_push(repo, "push", "--no-follow-tags", "--set-upstream", "--", remote, f"HEAD:{branch_ref}")
1678
+ if push_res.returncode != 0:
1679
+ summary.push_result = "uncertain"
1680
+ refs_chk, _ = _ls_remote_refs(repo, remote)
1681
+ c_state, c_err = _classify_init_remote(refs_chk)
1682
+ if c_state == "A":
1683
+ summary.resume_required = True
1684
+ summary.resume_oid = expected_oid
1685
+ summary.resume_remote = remote
1686
+ raise FinalizerError(
1687
+ ErrorCode.PUSH_FAILED,
1688
+ "resume push 失败且远端仍为空",
1689
+ status="failed",
1690
+ final_phase="push",
1691
+ next_action="retry_same_resume",
1692
+ push_executed=True,
1693
+ push_result="uncertain",
1694
+ resume={"head_oid": expected_oid, "remote": remote},
1695
+ )
1696
+ if c_state == "C":
1697
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, f"resume push 后远端进入冲突或含糊状态: {c_err}", status="failed", final_phase="push", push_executed=True, push_result="uncertain")
1698
+ # c_state == "B": remote has expected_oid; check upstream and run bounded up-to-date second push if missing!
1699
+ u_s, u_o, _ = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1700
+ if u_s != "exact_resolved" or u_o != expected_oid:
1701
+ _emit("\n== Resume up-to-date push ==", quiet=cli.summary)
1702
+ second_res = _run_remote_push(repo, "push", "--no-follow-tags", "--set-upstream", "--", remote, f"HEAD:{branch_ref}")
1703
+ if second_res.returncode != 0:
1704
+ refs_chk2, _ = _ls_remote_refs(repo, remote)
1705
+ c_state2, c_err2 = _classify_init_remote(refs_chk2)
1706
+ if c_state2 == "A":
1707
+ summary.resume_required = True
1708
+ summary.resume_oid = expected_oid
1709
+ summary.resume_remote = remote
1710
+ raise FinalizerError(ErrorCode.PUSH_FAILED, "up-to-date push 失败且远端仍为空", status="failed", final_phase="push", next_action="retry_same_resume", push_executed=True, push_result="uncertain", resume={"head_oid": expected_oid, "remote": remote})
1711
+ if c_state2 == "C":
1712
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, f"up-to-date push 后远端冲突或含糊: {c_err2}", status="failed", final_phase="push", push_executed=True, push_result="uncertain")
1713
+ u_s2, u_o2, _ = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1714
+ if u_s2 != "exact_resolved" or u_o2 != expected_oid:
1715
+ summary.resume_required = True
1716
+ summary.resume_oid = expected_oid
1717
+ summary.resume_remote = remote
1718
+ raise FinalizerError(ErrorCode.PUSH_FAILED, "远端已正确但本地 upstream 尚未建立", status="failed", final_phase="push", next_action="retry_same_resume", push_executed=True, push_result="uncertain", resume={"head_oid": expected_oid, "remote": remote})
1719
+ summary.push_result = "succeeded"
1720
+ else:
1721
+ summary.push_result = "succeeded"
1722
+ summary.completed_through = "push"
1723
+ summary.final_phase = "post_verify"
1724
+ refs_final, _ = _ls_remote_refs(repo, remote)
1725
+ up_after, up_oid_after, _ = _classify_branch_upstream(repo, info.branch, remote, branch_ref)
1726
+ if refs_final != {branch_ref: expected_oid} or up_after != "exact_resolved" or up_oid_after != expected_oid:
1727
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "resume-initial-publish 验证失败", status="failed", final_phase="post_verify")
1728
+ _assert_local_state_unchanged(repo, baseline, phase="post_verify", push_executed=need_push, push_result=summary.push_result)
1729
+ else:
1730
+ parents_chk = run_git(repo, "rev-list", "--parents", "-n", "1", expected_oid)
1731
+ if parents_chk.returncode != 0 or len(parents_chk.stdout.decode("ascii").strip().split()) < 2:
1732
+ raise FinalizerError(
1733
+ ErrorCode.REPO_INVALID,
1734
+ f"resume-publish 要求非 root commit(root commit 请使用 --resume-initial-publish {expected_oid})",
1735
+ final_phase="preflight",
1736
+ )
1737
+ summary.resume_publish_kind = "existing_commits"
1738
+ summary.recovery_start = "local_ahead_commits"
1739
+ remote, target_branch = repo_state.resolve_upstream_for_resume(repo, info.branch)
1740
+ remote_url = repo_state.validate_remote_endpoints(repo, remote)
1741
+ target_ref = f"refs/heads/{target_branch}"
1742
+ summary.upstream = f"{remote}/{target_branch}"
1743
+ summary.push_target = f"{remote}:{target_ref}"
1744
+
1745
+ summary.final_phase = "remote_preflight"
1746
+ local_oid, upstream_oid, ahead, behind, _ = _check_normal_remote_state(repo, remote, target_branch, phase_label="resume-publish 前 ")
1747
+ if local_oid != expected_oid:
1748
+ raise FinalizerError(ErrorCode.REPO_INVALID, "resume-publish 预检后 当前 HEAD 与 expected HEAD 不一致")
1749
+ if ahead < 1:
1750
+ raise FinalizerError(ErrorCode.REPO_INVALID, "resume-publish 要求当前分支至少 ahead configured upstream 1 个 commit")
1751
+ commits = _unpublished_commits(repo, local_oid, [upstream_oid])
1752
+ summary.publish_ahead = ahead
1753
+ summary.publish_behind = behind
1754
+ summary.publish_commit_count = len(commits)
1755
+ summary.publish_range = f"{upstream_oid}..{local_oid}"
1756
+ specs = (
1757
+ validation.load_fixture_exceptions(
1758
+ cli.fixture_exceptions,
1759
+ repo=repo,
1760
+ remote_url=remote_url,
1761
+ local_only=False,
1762
+ phase="history",
1763
+ head_ref=expected_oid,
1764
+ baseline_ref=upstream_oid,
1765
+ final_phase="preflight",
1766
+ )
1767
+ if cli.fixture_exceptions
1768
+ else []
1769
+ )
1770
+ reviewed_blobs_res: dict[str, str] | None = None
1771
+ if cli.reviewed_sensitive_source:
1772
+ summary.reviewed_sensitive_sources = source_review.validate_review_document(
1773
+ review_file=cli.reviewed_sensitive_source,
1774
+ repo=repo,
1775
+ common_dir=info.common_dir,
1776
+ repository_id=cli.repository_id,
1777
+ allocation_id=cli.allocation_id,
1778
+ task_key=cli.task_key,
1779
+ authority_key=cli.authority_key,
1780
+ worktree_path=cli.worktree_path,
1781
+ requested_paths=cli.paths,
1782
+ stage="head",
1783
+ allowed_extensions=policy.allow_reviewed_extensions,
1784
+ commit_ref=expected_oid,
1785
+ baseline_ref=f"{expected_oid}^1" if run_git(repo, "rev-parse", "--verify", f"{expected_oid}^1").returncode == 0 else None,
1786
+ )
1787
+ for rec in summary.reviewed_sensitive_sources:
1788
+ rec["content_scan"] = "passed"
1789
+ reviewed_blobs_res = source_review.reviewed_blob_map(repo, summary.reviewed_sensitive_sources, commit_ref=expected_oid)
1790
+ rng_out = validation.validate_commit_range(
1791
+ repo,
1792
+ info,
1793
+ commits,
1794
+ cli,
1795
+ policy,
1796
+ specs=specs,
1797
+ local_only=False,
1798
+ reviewed_blobs=reviewed_blobs_res,
1799
+ )
1800
+ summary.fixture_exceptions.extend(rng_out.fixture_exceptions)
1801
+ summary.warnings.extend(rng_out.warnings)
1802
+ summary.completed_through = "preflight"
1803
+ summary.remote_conclusion = "fast_forward_publish_ready"
1804
+
1805
+ summary.final_phase = "push"
1806
+ summary.push_executed = True
1807
+ summary.push_branch_refspec_only = True
1808
+ summary.push_follow_tags_requested = False
1809
+ push_res = _run_remote_push(repo, "push", "--no-follow-tags", remote, f"HEAD:{target_ref}")
1810
+ if push_res.returncode != 0:
1811
+ summary.push_result = "uncertain"
1812
+ summary.resume_required = True
1813
+ summary.resume_oid = expected_oid
1814
+ summary.resume_remote = remote
1815
+ raise FinalizerError(
1816
+ ErrorCode.PUSH_FAILED,
1817
+ "resume-publish push 失败或远端仍未包含待发布 commits",
1818
+ status="failed",
1819
+ final_phase="push",
1820
+ next_action="retry_same_resume",
1821
+ push_executed=True,
1822
+ push_result="uncertain",
1823
+ resume={"head_oid": expected_oid, "remote": remote},
1824
+ )
1825
+ summary.push_result = "succeeded"
1826
+ summary.completed_through = "push"
1827
+ summary.final_phase = "post_verify"
1828
+ l_after, u_after, ah_after, bh_after, r_after = _check_normal_remote_state(repo, remote, target_branch, phase_label="resume-publish 后 ", phase_name="post_verify")
1829
+ if l_after != expected_oid or u_after != expected_oid or r_after != expected_oid or ah_after != 0 or bh_after != 0:
1830
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "resume-publish 验证后未对齐", status="failed", final_phase="post_verify")
1831
+ _assert_local_state_unchanged(repo, baseline, phase="post_verify", push_executed=True, push_result="succeeded")
1832
+
1833
+ summary.head_after = expected_oid
1834
+ summary.head_unchanged = True
1835
+ summary.index_unchanged = True
1836
+ summary.worktree_unchanged = True
1837
+ summary.worktree_state = "clean"
1838
+ summary.final_head = expected_oid
1839
+ summary.final_remote_oid = expected_oid
1840
+ summary.post_verify = "passed"
1841
+ summary.remote_conclusion = "published_and_upstream_aligned"
1842
+ summary.completed_through = "post_verify"
1843
+ summary.mode_state = "verified"
1844
+ summary.status = "success"
1845
+ summary.exit_code = 0
1846
+ summary.next_action = "none"
1847
+ if not cli.summary and is_initial:
1848
+ for line in (
1849
+ "\n== Resume initial publish ==",
1850
+ f"repo: {repo}",
1851
+ "mode: resume-initial-publish",
1852
+ "publish kind: initial_root",
1853
+ f"branch: {info.branch}",
1854
+ f"expected HEAD: {expected_oid}",
1855
+ f"remote: {remote}",
1856
+ f"target ref: {branch_ref}",
1857
+ f"snapshot: {cli.snapshot or '(none)'}",
1858
+ f"recovery start: {summary.recovery_start or 'unknown'}",
1859
+ f"remote conclusion: {summary.remote_conclusion or 'unknown'}",
1860
+ "\n== Existing commit safety check ==",
1861
+ f"$ git rev-list --reverse {expected_oid}",
1862
+ f"root commit count: {summary.publish_commit_count}",
1863
+ f"publish range: {summary.publish_range or expected_oid}",
1864
+ "range safety checks: passed (all commits validated against clean-tree content & binary limits)",
1865
+ "snapshot verification: " + (summary.snapshot_verification or "not_requested"),
1866
+ "\n== Resume push ==",
1867
+ f"$ git push --no-follow-tags --set-upstream -- {remote} HEAD:{branch_ref}",
1868
+ f"push executed: {summary.push_executed}",
1869
+ f"push result: {summary.push_result}",
1870
+ "push branch_refspec_only: true",
1871
+ "push follow_tags_requested: false",
1872
+ "\n== Resume 最终验证 ==",
1873
+ f"$ git ls-remote --heads -- {remote}",
1874
+ f"head: {expected_oid}",
1875
+ f"remote ref ({branch_ref}): {expected_oid}",
1876
+ f"upstream: {summary.upstream or '(none)'}",
1877
+ f"$ git rev-parse --verify {branch_ref}",
1878
+ f"$ git rev-list --left-right --count HEAD...{summary.upstream or '@{upstream}'}",
1879
+ "0\t0",
1880
+ "local branch, tags, and Git config: unchanged",
1881
+ "index unchanged: true",
1882
+ "worktree state: clean",
1883
+ "post-verify: passed",
1884
+ "\nGit Finalizer 完成:initial publish 恢复已验证。",
1885
+ ):
1886
+ print(line, flush=True)
1887
+ elif not cli.summary:
1888
+ for line in (
1889
+ "\n== Resume existing commits ==",
1890
+ "mode: resume-publish",
1891
+ f"publish kind: {summary.resume_publish_kind}",
1892
+ f"pre-publish ahead/behind: {summary.publish_ahead}/{summary.publish_behind}",
1893
+ f"commit count: {summary.publish_commit_count}",
1894
+ "\n== Existing commit range 安全检查 ==",
1895
+ "range safety checks: passed",
1896
+ "\n== Resume publish 后验证 ==",
1897
+ "local branch, tags, and Git config: unchanged",
1898
+ "post-verify: passed",
1899
+ "\nGit Finalizer 完成:既有本地 commit range 已发布并完成远端验证。",
1900
+ ):
1901
+ print(line, flush=True)
1902
+ return 0, summary
1903
+
1904
+
1905
+ def _run_sync_published_branch(cli: ParsedCLI, summary: SummaryState) -> tuple[int, SummaryState]:
1906
+ summary.mode = "sync_published_branch"
1907
+ summary.commit_reused = True
1908
+ summary.commit_result = "reused"
1909
+ info = repo_state.inspect_repository(cli.repo, merge_parent_arg=None, mode=cli.action, require_attached=True)
1910
+ repo = info.repo
1911
+ summary.repository = str(repo)
1912
+ _require_clean_repo_state(repo, info)
1913
+ policy = policy_mod.load_delivery_policy(repo)
1914
+ assert info.branch is not None and info.head_oid is not None
1915
+
1916
+ published_oid = validate_oid(cli.head_oid or "", "published OID")
1917
+ expected_target_oid = validate_oid(cli.expected_target_oid or "", "expected target OID")
1918
+ _, branch_ref = _normalize_heads_ref(cli.remote_branch or "", "--remote-branch")
1919
+ source_remote = validate_remote_name(cli.source_remote or "")
1920
+ target_remote = validate_remote_name(cli.remote or "")
1921
+ if source_remote == target_remote:
1922
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "sync source and target remote must differ", final_phase="cli")
1923
+ src_url = repo_state.validate_remote_endpoints(repo, source_remote)
1924
+ tgt_url = repo_state.validate_remote_endpoints(repo, target_remote)
1925
+ if src_url == tgt_url:
1926
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "sync source and target endpoints must differ", final_phase="cli")
1927
+
1928
+ summary.branch = info.branch
1929
+ summary.upstream = info.upstream
1930
+ summary.commit_sha = published_oid
1931
+ summary.head_before = info.head_oid
1932
+ summary.worktree_before_state = "clean"
1933
+ summary.sync_source_remote = source_remote
1934
+ summary.sync_expected_target_oid = expected_target_oid
1935
+ summary.push_target = f"{target_remote}:{branch_ref}"
1936
+ summary.push_branch_refspec_only = True
1937
+ summary.push_follow_tags_requested = False
1938
+
1939
+ upstream_cfg_before = (
1940
+ tuple(_git_config_get_all(repo, f"branch.{info.branch}.remote")),
1941
+ tuple(_git_config_get_all(repo, f"branch.{info.branch}.merge")),
1942
+ )
1943
+ baseline = _snapshot_local_state(repo)
1944
+ summary.final_phase = "remote_preflight"
1945
+ src_refs, _ = _ls_remote_refs(repo, source_remote, branch_ref)
1946
+ if src_refs.get(branch_ref) != published_oid:
1947
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "sync source branch does not equal the exact published OID", final_phase="remote_preflight")
1948
+ tgt_refs, _ = _ls_remote_refs(repo, target_remote, branch_ref)
1949
+ target_before = tgt_refs.get(branch_ref)
1950
+ if target_before is None:
1951
+ raise FinalizerError(ErrorCode.REMOTE_MISSING, f"sync target branch 不存在: {branch_ref}", final_phase="remote_preflight")
1952
+
1953
+ if target_before != published_oid:
1954
+ if target_before != expected_target_oid:
1955
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "sync live target differs from expected target OID", final_phase="remote_preflight")
1956
+ _fetch_remote(repo, source_remote, branch_ref, no_write_fetch_head=True, phase="remote_preflight")
1957
+ _fetch_remote(repo, target_remote, branch_ref, no_write_fetch_head=True, phase="remote_preflight")
1958
+ # Re-verify source, target, and local upstream config didn't drift during fetch before push.
1959
+ live_src, _ = _ls_remote_refs(repo, source_remote, branch_ref)
1960
+ live_tgt, _ = _ls_remote_refs(repo, target_remote, branch_ref)
1961
+ upstream_cfg_after = (
1962
+ tuple(_git_config_get_all(repo, f"branch.{info.branch}.remote")),
1963
+ tuple(_git_config_get_all(repo, f"branch.{info.branch}.merge")),
1964
+ )
1965
+ if live_src.get(branch_ref) != published_oid or live_tgt.get(branch_ref) != target_before or upstream_cfg_after != upstream_cfg_before:
1966
+ raise FinalizerError(ErrorCode.REMOTE_DIVERGED, "fetch 期间 source/target/upstream 发生漂移;未执行 push", final_phase="remote_preflight")
1967
+ anc = run_git(repo, "merge-base", "--is-ancestor", target_before, published_oid)
1968
+ if anc.returncode != 0:
1969
+ raise FinalizerError(
1970
+ ErrorCode.REMOTE_DIVERGED,
1971
+ "sync target is not an ancestor of the published source; no force or merge is allowed",
1972
+ final_phase="remote_preflight",
1973
+ )
1974
+ commits = _unpublished_commits(repo, published_oid, [target_before])
1975
+ summary.publish_commit_count = len(commits)
1976
+ summary.publish_range = f"{target_before}..{published_oid}"
1977
+ specs = (
1978
+ validation.load_fixture_exceptions(
1979
+ cli.fixture_exceptions,
1980
+ repo=repo,
1981
+ remote_url=tgt_url,
1982
+ local_only=False,
1983
+ phase="history",
1984
+ head_ref=published_oid,
1985
+ baseline_ref=target_before,
1986
+ final_phase="preflight",
1987
+ )
1988
+ if cli.fixture_exceptions
1989
+ else []
1990
+ )
1991
+ rng_out = validation.validate_commit_range(repo, info, commits, cli, policy, specs=specs, local_only=False)
1992
+ summary.fixture_exceptions.extend(rng_out.fixture_exceptions)
1993
+ summary.warnings.extend(rng_out.warnings)
1994
+ _assert_local_state_unchanged(repo, baseline, phase="remote_preflight")
1995
+ summary.completed_through = "preflight"
1996
+ summary.remote_conclusion = "published_source_fast_forward_ready"
1997
+
1998
+ if cli.dry_run:
1999
+ summary.head_after = info.head_oid
2000
+ summary.head_unchanged = True
2001
+ summary.index_unchanged = True
2002
+ summary.worktree_unchanged = True
2003
+ summary.worktree_state = "clean"
2004
+ summary.final_head = info.head_oid
2005
+ summary.push_result = "skipped_by_dry_run"
2006
+ summary.post_verify = "skipped_by_dry_run"
2007
+ summary.status = "success"
2008
+ summary.exit_code = 0
2009
+ summary.next_action = "run_without_dry_run_after_review"
2010
+ return 0, summary
2011
+
2012
+ summary.final_phase = "push"
2013
+ summary.push_executed = True
2014
+ summary.push_branch_refspec_only = True
2015
+ summary.push_follow_tags_requested = False
2016
+ push_res = _run_remote_push(repo, "push", "--no-follow-tags", "--", target_remote, f"{published_oid}:{branch_ref}")
2017
+ if push_res.returncode != 0:
2018
+ summary.push_result = "uncertain"
2019
+ post_check, _ = _ls_remote_refs(repo, target_remote, branch_ref)
2020
+ if post_check.get(branch_ref) == published_oid:
2021
+ summary.push_result = "confirmed_after_uncertain"
2022
+ else:
2023
+ raise FinalizerError(ErrorCode.SYNC_FAILED, "sync push 失败且远端结果未对齐", status="failed", final_phase="push", push_executed=True, push_result="uncertain")
2024
+ else:
2025
+ summary.push_result = "succeeded"
2026
+ else:
2027
+ if cli.fixture_exceptions:
2028
+ raise FinalizerError(ErrorCode.FIXTURE_EXCEPTION_BLOCKED, "already-aligned sync does not consume fixture exceptions", final_phase="remote_preflight")
2029
+ summary.push_result = "not_needed_already_aligned"
2030
+
2031
+ summary.final_phase = "post_verify"
2032
+ post_src, _ = _ls_remote_refs(repo, source_remote, branch_ref)
2033
+ post_tgt, _ = _ls_remote_refs(repo, target_remote, branch_ref)
2034
+ if post_src.get(branch_ref) != published_oid or post_tgt.get(branch_ref) != published_oid:
2035
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "post-verify: source 与 target live OID 不一致", status="failed", final_phase="post_verify")
2036
+ _assert_local_state_unchanged(repo, baseline, phase="post_verify", push_executed=summary.push_executed, push_result=summary.push_result)
2037
+
2038
+ summary.head_after = info.head_oid
2039
+ summary.head_unchanged = True
2040
+ summary.index_unchanged = True
2041
+ summary.worktree_unchanged = True
2042
+ summary.worktree_state = "clean"
2043
+ summary.final_head = info.head_oid
2044
+ summary.final_remote_oid = published_oid
2045
+ summary.post_verify = "passed"
2046
+ summary.completed_through = "post_verify"
2047
+ summary.remote_conclusion = "source_and_target_exactly_aligned"
2048
+ summary.status = "success"
2049
+ summary.exit_code = 0
2050
+ summary.next_action = "none"
2051
+ return 0, summary
2052
+
2053
+
2054
+ def _run_retire_branch(cli: ParsedCLI, summary: SummaryState) -> tuple[int, SummaryState]:
2055
+ is_local = cli.action == "retire-local-branch"
2056
+ op_name = "local" if is_local else "remote"
2057
+ summary.mode = "retire_local_branch" if is_local else "retire_remote_branch"
2058
+ summary.retirement_operation = "dry_run" if cli.dry_run else "delete"
2059
+
2060
+ if is_local and not cli.retirement_plan_id:
2061
+ raise FinalizerError(
2062
+ ErrorCode.CLI_INVALID_ARGS,
2063
+ "retire-local-branch 必须提供 Controller --retirement-plan-id(通过 worktree-controller branch-retirement-plan 获取)",
2064
+ final_phase="cli",
2065
+ )
2066
+ if cli.retirement_plan_id is not None and not retirement_plan.PLAN_ID_RE.fullmatch(cli.retirement_plan_id):
2067
+ raise FinalizerError(
2068
+ ErrorCode.CLI_INVALID_ARGS,
2069
+ "--retirement-plan-id 要求 64 位小写十六进制 ID",
2070
+ final_phase="cli",
2071
+ )
2072
+
2073
+ info = repo_state.inspect_repository(cli.repo, merge_parent_arg=None, mode=cli.action, require_attached=True)
2074
+ repo = info.repo
2075
+ summary.repository = str(repo)
2076
+ policy = policy_mod.load_delivery_policy(repo)
2077
+ assert info.branch is not None and info.head_oid is not None
2078
+ summary.branch = info.branch
2079
+ summary.head_before = info.head_oid
2080
+
2081
+ raw_branch = cli.retire_branch or ""
2082
+ branch, feature_ref = _normalize_heads_ref(raw_branch, f"--retire-{op_name}-branch")
2083
+ if repo_state.is_protected_branch(branch, policy):
2084
+ raise FinalizerError(ErrorCode.BRANCH_PROTECTED, f"retire-{op_name}-branch 拒绝受保护分支: {branch}")
2085
+
2086
+ remote = validate_remote_name(cli.remote or "")
2087
+ summary.retirement_remote = remote
2088
+ summary.retirement_branch = branch
2089
+ summary.retirement_ref = feature_ref
2090
+
2091
+ raw_expected = cli.expected_local_oid if is_local else cli.expected_remote_oid
2092
+ expected_oid = validate_oid(raw_expected or "", f"expected_{op_name}_oid")
2093
+ summary.retirement_expected_oid = expected_oid
2094
+
2095
+ expected_integrated_oid = (
2096
+ validate_oid(cli.expected_integrated_oid, "expected_integrated_oid")
2097
+ if cli.expected_integrated_oid
2098
+ else None
2099
+ )
2100
+ if is_local and not expected_integrated_oid:
2101
+ raise FinalizerError(ErrorCode.CLI_INVALID_ARGS, "retire-local-branch 要求 --expected-integrated-oid", final_phase="cli")
2102
+
2103
+ int_branch, integration_ref = _normalize_integration_ref(cli.integrated_into or "main", remote)
2104
+ summary.retirement_integrated_ref = integration_ref
2105
+ if feature_ref == integration_ref:
2106
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "feature ref 与 integration target 不能相同")
2107
+
2108
+ # CI verification evidence validation
2109
+ summary.retirement_ci_required = cli.ci_required
2110
+ summary.retirement_ci_status = cli.ci_status
2111
+ summary.retirement_ci_commit_oid = cli.ci_commit_oid
2112
+ summary.retirement_ci_source = cli.ci_verification_source
2113
+ summary.retirement_ci_verified_at = cli.ci_verified_at
2114
+
2115
+ summary.retirement_plan_id = cli.retirement_plan_id
2116
+
2117
+ plan_args: argparse.Namespace | None = None
2118
+ if cli.retirement_plan_id:
2119
+ plan_args = argparse.Namespace(
2120
+ repo=str(repo),
2121
+ plan_id=cli.retirement_plan_id,
2122
+ operation=op_name,
2123
+ branch=branch,
2124
+ remote=remote,
2125
+ integrated_into=cli.integrated_into or "main",
2126
+ expected_oid=expected_oid,
2127
+ expected_integrated_oid=expected_integrated_oid or "",
2128
+ recover=not cli.dry_run,
2129
+ )
2130
+ try:
2131
+ retirement_plan.verify_capabilities(repo)
2132
+ retirement_plan.preflight(plan_args)
2133
+ except retirement_plan.RetirementBlocked as exc:
2134
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, str(exc), final_phase="preflight") from exc
2135
+
2136
+ _require_clean_repo_state(repo, info)
2137
+ summary.worktree_before_state = "clean"
2138
+ baseline = _snapshot_local_state(repo)
2139
+ other_local_before = _snapshot_other_local_heads(repo, excluded_ref=feature_ref)
2140
+
2141
+ repo_state.validate_remote_endpoints(repo, remote)
2142
+ remote_default_ref = _query_remote_default_branch(repo, remote)
2143
+ if feature_ref == remote_default_ref:
2144
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, f"retire-{op_name}-branch 拒绝 remote default branch: {branch}")
2145
+
2146
+ summary.final_phase = "remote_preflight"
2147
+ _fetch_remote(repo, remote, prune=True, phase="remote_preflight")
2148
+ live_refs, _ = _ls_remote_refs(repo, remote, feature_ref, integration_ref)
2149
+ if integration_ref not in live_refs:
2150
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "live remote integration target 不存在", final_phase="remote_preflight")
2151
+ live_int_oid = live_refs[integration_ref]
2152
+ if expected_integrated_oid and live_int_oid != expected_integrated_oid:
2153
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "live integration target OID 与 expected_integrated_oid 不一致", final_phase="remote_preflight")
2154
+ summary.retirement_integrated_oid = live_int_oid
2155
+
2156
+ if plan_args is not None and not plan_args.expected_integrated_oid:
2157
+ plan_args.expected_integrated_oid = live_int_oid
2158
+
2159
+ if cli.ci_required:
2160
+ if cli.ci_status != "SUCCESS" or cli.ci_verification_source not in {"tool_authenticated", "human_authenticated_ui"}:
2161
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "repository policy 要求 CI SUCCESS (effective evidence required)", final_phase="remote_preflight")
2162
+ ci_oid = validate_oid(cli.ci_commit_oid or "", "ci_commit_oid")
2163
+ if ci_oid != live_int_oid:
2164
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "ci_commit_oid 与 live integration target OID 不一致", final_phase="remote_preflight")
2165
+ elif cli.ci_status not in (None, "NOT_REQUIRED") or cli.ci_verification_source not in (None, "not_required") or cli.ci_commit_oid or cli.ci_verified_at:
2166
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "未启用 --ci-required 时 CI evidence 必须为 not_required", final_phase="remote_preflight")
2167
+
2168
+ # Verify ancestry against integration target & check no local worktree / local-only commits block retirement.
2169
+ live_remote_feature_oid = live_refs.get(feature_ref)
2170
+ if is_local and live_remote_feature_oid and live_remote_feature_oid != expected_oid:
2171
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "live remote feature OID 与 expected_local_oid 不一致", final_phase="remote_preflight")
2172
+ if not is_local and live_remote_feature_oid and live_remote_feature_oid != expected_oid:
2173
+ raise FinalizerError(
2174
+ ErrorCode.RETIREMENT_BLOCKED,
2175
+ f"live remote feature OID 与 expected_remote_oid 不一致(与 remote feature OID 不一致: {expected_oid})",
2176
+ final_phase="remote_preflight",
2177
+ )
2178
+
2179
+ if live_remote_feature_oid or is_local or cli.retirement_plan_id:
2180
+ anc_res = run_git(repo, "merge-base", "--is-ancestor", expected_oid, live_int_oid)
2181
+ if anc_res.returncode != 0:
2182
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "expected feature OID 不是 integration target OID 的 ancestor", final_phase="remote_preflight")
2183
+ summary.retirement_ancestry_verified = True
2184
+
2185
+ wt_list = run_git(repo, "worktree", "list", "--porcelain")
2186
+ if wt_list.returncode != 0 or f"branch {feature_ref}" in wt_list.stdout.decode("utf-8", errors="replace").splitlines():
2187
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "目标 branch 仍被一个 local worktree checkout", final_phase="remote_preflight")
2188
+
2189
+ # Verify local ref does not contain local-only commits or mismatch expected OID.
2190
+ local_oid = _show_ref_hash(repo, feature_ref, label="local feature ref")
2191
+ if local_oid is not None:
2192
+ ahead_local = int(run_git(repo, "rev-list", "--count", f"{expected_oid}..{feature_ref}").stdout.decode("ascii").strip() or "0")
2193
+ if ahead_local > 0 or local_oid != expected_oid:
2194
+ raise FinalizerError(
2195
+ ErrorCode.RETIREMENT_BLOCKED,
2196
+ "local feature branch 存在 local-only commit,或 local branch OID 与 remote feature OID 不一致",
2197
+ final_phase="remote_preflight",
2198
+ )
2199
+
2200
+ # Reject if another local branch uses `refs/remotes/<remote>/<branch>` as upstream.
2201
+ target_tracking = f"refs/remotes/{remote}/{branch}"
2202
+ up_refs_out = run_git(repo, "for-each-ref", "--format=%(refname)\t%(upstream)", "refs/heads")
2203
+ for line in up_refs_out.stdout.decode("utf-8", errors="replace").splitlines():
2204
+ b_ref, _, u_ref = line.partition("\t")
2205
+ if u_ref == target_tracking and b_ref != feature_ref:
2206
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "其他 local branch 仍把目标 remote ref 作为 upstream", final_phase="remote_preflight")
2207
+
2208
+ already_absent = (local_oid is None) if is_local else (live_remote_feature_oid is None)
2209
+ if already_absent:
2210
+ if plan_args is not None and not cli.dry_run:
2211
+ try:
2212
+ res_doc = retirement_plan.execute(plan_args)
2213
+ summary.retirement_receipt_id = res_doc.get("receipt_id")
2214
+ summary.retirement_lease_bound = bool(res_doc.get("expected_oid_lease_bound", False))
2215
+ except retirement_plan.RetirementBlocked as exc:
2216
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, str(exc), status="failed", final_phase="post_verify") from exc
2217
+ else:
2218
+ summary.retirement_lease_bound = False
2219
+ summary.retirement_result = "ALREADY_ABSENT_VERIFIED"
2220
+ summary.retirement_local_absent_after = True if is_local else summary.retirement_local_absent_after
2221
+ summary.retirement_remote_absent_after = True if not is_local else (live_remote_feature_oid is None)
2222
+ summary.remote_conclusion = "local_branch_already_absent_verified" if is_local else "already_absent_verified"
2223
+ summary.post_verify = "passed"
2224
+ summary.mode_state = "verified"
2225
+ summary.completed_through = "post_verify"
2226
+ summary.status = "success"
2227
+ summary.exit_code = 0
2228
+ summary.next_action = "none"
2229
+ return 0, summary
2230
+
2231
+ if cli.dry_run:
2232
+ _assert_local_state_unchanged(repo, baseline, phase="preflight")
2233
+ summary.retirement_local_absent_after = False if is_local else None
2234
+ summary.retirement_remote_absent_after = False if not is_local else (live_remote_feature_oid is None)
2235
+ summary.retirement_result = "RETIREMENT_PREFLIGHT_PASSED"
2236
+ summary.remote_conclusion = "retirement_preflight_passed"
2237
+ summary.post_verify = "skipped_by_dry_run"
2238
+ summary.mode_state = "dry_run_complete"
2239
+ summary.completed_through = "preflight"
2240
+ summary.status = "success"
2241
+ summary.exit_code = 0
2242
+ summary.next_action = (
2243
+ "run_without_dry_run_after_review" if is_local else "publish_install_verify_then_run_without_dry_run"
2244
+ )
2245
+ return 0, summary
2246
+
2247
+ # Execute CAS delete (Controller-authorized if --retirement-plan-id, else direct Git CAS).
2248
+ summary.final_phase = "local_mutation" if is_local else "remote_mutation"
2249
+ summary.push_branch_refspec_only = True if not is_local else None
2250
+ summary.push_follow_tags_requested = False if not is_local else None
2251
+ if plan_args is not None:
2252
+ prog: dict[str, Any] = {
2253
+ "mutation_attempted": False,
2254
+ "controller_complete": False,
2255
+ "authorization_id": None,
2256
+ "expected_oid_lease_bound": False,
2257
+ }
2258
+ try:
2259
+ exec_res = retirement_plan.execute(plan_args, progress=prog)
2260
+ except retirement_plan.RetirementBlocked as exc:
2261
+ summary.retirement_lease_bound = bool(prog.get("expected_oid_lease_bound"))
2262
+ summary.retirement_result = f"{'LOCAL' if is_local else 'REMOTE'}_DELETE_UNVERIFIED"
2263
+ raise FinalizerError(
2264
+ ErrorCode.RETIREMENT_BLOCKED,
2265
+ str(exc),
2266
+ status="failed" if prog.get("mutation_attempted") else "blocked",
2267
+ final_phase=summary.final_phase,
2268
+ next_action=exc.next_action or "inspect_remote_state_then_rerun_same_retirement",
2269
+ ) from exc
2270
+ summary.retirement_lease_bound = bool(exec_res.get("expected_oid_lease_bound", True))
2271
+ summary.retirement_receipt_id = exec_res.get("receipt_id")
2272
+ if not is_local:
2273
+ summary.push_executed = bool(exec_res.get("mutation_attempted", True))
2274
+ summary.push_result = "succeeded"
2275
+ else:
2276
+ summary.retirement_lease_bound = True
2277
+ if is_local:
2278
+ del_res = run_git(repo, "update-ref", "-d", feature_ref, expected_oid)
2279
+ if del_res.returncode != 0:
2280
+ summary.retirement_result = "LOCAL_DELETE_UNVERIFIED"
2281
+ raise FinalizerError(ErrorCode.RETIREMENT_BLOCKED, "lease-bound local update-ref 删除被拒绝", status="failed", final_phase="local_mutation")
2282
+ else:
2283
+ summary.push_executed = True
2284
+ del_res = _run_remote_push(
2285
+ repo,
2286
+ "push",
2287
+ "--no-follow-tags",
2288
+ f"--force-with-lease={feature_ref}:{expected_oid}",
2289
+ "--",
2290
+ remote,
2291
+ f":{feature_ref}",
2292
+ )
2293
+ if del_res.returncode != 0:
2294
+ summary.push_result = "uncertain"
2295
+ summary.retirement_result = "REMOTE_DELETE_UNVERIFIED"
2296
+ raise FinalizerError(
2297
+ ErrorCode.RETIREMENT_BLOCKED,
2298
+ "lease-bound remote delete 被拒绝或结果无法验证",
2299
+ status="failed",
2300
+ final_phase="remote_mutation",
2301
+ next_action="inspect_remote_state_then_rerun_same_retirement",
2302
+ push_executed=True,
2303
+ push_result="uncertain",
2304
+ )
2305
+ summary.push_result = "succeeded"
2306
+
2307
+ summary.final_phase = "post_verify"
2308
+ summary.retirement_result = "LOCAL_DELETE_UNVERIFIED" if is_local else "REMOTE_DELETE_UNVERIFIED"
2309
+ _fetch_remote(repo, remote, prune=True, phase="post_verify")
2310
+ post_live, _ = _ls_remote_refs(repo, remote, feature_ref, integration_ref)
2311
+ if post_live.get(integration_ref) != live_int_oid:
2312
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "post-delete integration target 缺失或 OID 发生变化", status="failed", final_phase="post_verify")
2313
+ if is_local:
2314
+ if _show_ref_hash(repo, feature_ref, label="post-delete local ref") is not None:
2315
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "post-delete local feature ref 仍存在", status="failed", final_phase="post_verify")
2316
+ if _snapshot_other_local_heads(repo, excluded_ref=feature_ref) != other_local_before:
2317
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "retirement 前后其他 local branch refs 发生变化", status="failed", final_phase="post_verify")
2318
+ summary.retirement_local_absent_after = True
2319
+ summary.retirement_remote_absent_after = feature_ref not in post_live
2320
+ else:
2321
+ if feature_ref in post_live or _show_ref_hash(repo, target_tracking, label="post-delete tracking ref") is not None:
2322
+ raise FinalizerError(ErrorCode.POST_VERIFY_FAILED, "post-delete remote 或 tracking feature ref 仍存在", status="failed", final_phase="post_verify")
2323
+ summary.retirement_remote_absent_after = True
2324
+ summary.retirement_remote_tracking_absent = True
2325
+ _assert_local_state_unchanged(repo, baseline, phase="post_verify")
2326
+
2327
+ summary.head_after = info.head_oid
2328
+ summary.head_unchanged = True
2329
+ summary.index_unchanged = True
2330
+ summary.worktree_unchanged = True
2331
+ summary.worktree_state = "clean"
2332
+ summary.retirement_tags_unchanged = True
2333
+ summary.post_verify = "passed"
2334
+ summary.retirement_result = "LOCAL_BRANCH_RETIRED_VERIFIED" if is_local else "REMOTE_BRANCH_RETIRED_VERIFIED"
2335
+ summary.remote_conclusion = "local_branch_retired_verified" if is_local else "remote_branch_retired_verified"
2336
+ summary.completed_through = "post_verify"
2337
+ summary.mode_state = "verified"
2338
+ summary.status = "success"
2339
+ summary.exit_code = 0
2340
+ summary.next_action = "none"
2341
+ return 0, summary
2342
+
2343
+
2344
+ def run_delivery(
2345
+ cli: ParsedCLI,
2346
+ *,
2347
+ entrypoint: Path | None = None,
2348
+ summary: SummaryState | None = None,
2349
+ ) -> tuple[int, SummaryState]:
2350
+ """Execute one parsed delivery operation through its dedicated workflow."""
2351
+ summary_state = summary if summary is not None else create_summary(cli, entrypoint=entrypoint)
2352
+ if cli.action in {"publish-existing-branch", "publish-existing-history", "resume-existing-history-publish"}:
2353
+ rc, out = _run_publish_existing_branch_or_history(cli, summary_state)
2354
+ elif cli.action in {"resume-publish", "resume-initial-publish"}:
2355
+ rc, out = _run_resume_publish_or_initial(cli, summary_state)
2356
+ elif cli.action == "sync-published-branch":
2357
+ rc, out = _run_sync_published_branch(cli, summary_state)
2358
+ elif cli.action in {"retire-local-branch", "retire-remote-branch"}:
2359
+ rc, out = _run_retire_branch(cli, summary_state)
2360
+ else:
2361
+ rc, out = _run_commit_delivery(cli, summary_state)
2362
+ if rc == 0:
2363
+ out.final_phase = "complete"
2364
+ return rc, out