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,1095 @@
1
+ """Local candidate and unpublished commit-range validation helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import json
7
+ from pathlib import Path, PurePosixPath
8
+ import re
9
+ from typing import Any
10
+
11
+ from git_finalizer.delivery import (
12
+ content_scan,
13
+ patch_check,
14
+ repo_state,
15
+ scanners,
16
+ source_review,
17
+ )
18
+ from git_finalizer.delivery import (
19
+ policy as policy_mod,
20
+ )
21
+ from git_finalizer.delivery.parser import ParsedCLI
22
+ from git_finalizer.errors import ErrorCode, FinalizerError
23
+ from git_finalizer.git_io import (
24
+ FULL_OID_RE,
25
+ is_binary_bytes,
26
+ parse_nul_records,
27
+ read_baseline_blob,
28
+ read_blob_bytes,
29
+ read_blob_size,
30
+ run_git,
31
+ )
32
+ from git_finalizer.json_io import loads_unique, sha256_bytes
33
+
34
+ MAX_FIXTURE_EXCEPTIONS = 16
35
+ BACKEND_TEST_PATH_RE = re.compile(r"^backend/tests/test_[A-Za-z0-9_]+\.py$")
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class ExceptionSpec:
40
+ path: str
41
+ blob_oid: str
42
+ sha256: str
43
+ detector: str
44
+ reason: str
45
+ repo_meta: dict[str, Any] = dataclasses.field(default_factory=dict)
46
+ raw_item: dict[str, Any] = dataclasses.field(default_factory=dict)
47
+ consumed: bool = False
48
+
49
+ def to_receipt(self) -> dict[str, Any]:
50
+ approved = {"schema_version": 1, "repository": self.repo_meta, "exception": self.raw_item}
51
+ encoded = json.dumps(approved, sort_keys=True, separators=(",", ":")).encode("utf-8")
52
+ digest = sha256_bytes(encoded)
53
+ return {
54
+ "exception_id": f"sha256:{digest}",
55
+ "repository": self.repo_meta,
56
+ **self.raw_item,
57
+ "applied": True,
58
+ }
59
+
60
+
61
+ @dataclasses.dataclass
62
+ class ValidationOutcome:
63
+ tree_oid: str | None = None
64
+ warnings: list[str] = dataclasses.field(default_factory=list)
65
+ fixture_exceptions: list[dict[str, Any]] = dataclasses.field(default_factory=list)
66
+ reviewed_sensitive_sources: list[dict[str, Any]] = dataclasses.field(default_factory=list)
67
+ external_scanners: list[dict[str, Any]] = dataclasses.field(default_factory=list)
68
+ policy_verdict: dict[str, Any] | None = None
69
+
70
+
71
+ def _read_root_commit(repo: Path, ref_or_oid: str = "HEAD") -> str:
72
+ res = run_git(repo, "rev-list", "--max-parents=0", ref_or_oid)
73
+ if res.returncode != 0:
74
+ raise FinalizerError(ErrorCode.REPO_INVALID, "无法确定仓库 root commit", final_phase="local_validation")
75
+ roots = [line.strip() for line in res.stdout.decode("ascii").splitlines() if line.strip()]
76
+ if len(roots) != 1 or FULL_OID_RE.fullmatch(roots[0]) is None:
77
+ raise FinalizerError(ErrorCode.REPO_INVALID, "仓库存在多个或无效的 root commit", final_phase="local_validation")
78
+ return roots[0]
79
+
80
+
81
+ def _detector_to_verdict(detector: str) -> str:
82
+ for verdict, det in content_scan.VERDICT_DETECTOR.items():
83
+ if det == detector:
84
+ return verdict
85
+ raise ValueError(f"unknown detector: {detector}")
86
+
87
+
88
+ def load_fixture_exceptions(
89
+ path_str: str,
90
+ *,
91
+ repo: Path,
92
+ remote_url: str,
93
+ local_only: bool = False,
94
+ phase: str = "history",
95
+ head_ref: str = "HEAD",
96
+ baseline_ref: str | None = None,
97
+ final_phase: str = "preflight",
98
+ ) -> list[ExceptionSpec]:
99
+ def _reject(msg: str) -> FinalizerError:
100
+ return FinalizerError(
101
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
102
+ "fixture exception 文件无效;未执行 push",
103
+ final_phase=final_phase,
104
+ )
105
+
106
+ try:
107
+ p = Path(path_str)
108
+ if not p.is_absolute() or str(p.resolve(strict=True)) != path_str or p.is_symlink() or not p.is_file():
109
+ raise ValueError("expected canonical regular file")
110
+ if p.stat().st_size > 65536:
111
+ raise ValueError("exception file exceeds 64 KiB")
112
+ raw = p.read_bytes()
113
+ doc = loads_unique(raw)
114
+ if not isinstance(doc, dict) or set(doc) != {"schema_version", "repository", "exceptions"}:
115
+ raise ValueError("unknown or missing document fields")
116
+ if type(doc["schema_version"]) is not int or doc["schema_version"] != 1:
117
+ raise ValueError("unknown exception schema")
118
+
119
+ repo_meta = doc["repository"]
120
+ if not isinstance(repo_meta, dict) or set(repo_meta) != {"root_commit", "remote_url_sha256"}:
121
+ raise ValueError("invalid repository identity")
122
+ root_commit = _read_root_commit(repo, head_ref)
123
+ if repo_meta["root_commit"] != root_commit or repo_meta["remote_url_sha256"] != sha256_bytes(remote_url.encode("utf-8")):
124
+ raise ValueError("repository identity mismatch")
125
+
126
+ raw_items = doc["exceptions"]
127
+ if not isinstance(raw_items, list) or not (1 <= len(raw_items) <= MAX_FIXTURE_EXCEPTIONS):
128
+ raise ValueError("expected 1..16 exceptions")
129
+
130
+ seen_keys: set[tuple[str, str, str]] = set()
131
+ specs: list[ExceptionSpec] = []
132
+ for item in raw_items:
133
+ if not isinstance(item, dict) or set(item) != {"path", "blob_oid", "sha256", "detector", "reason"}:
134
+ raise ValueError("unknown or missing exception fields")
135
+ if not all(type(v) is str for v in item.values()):
136
+ raise ValueError("exception fields must be strings")
137
+ rel = item["path"]
138
+ oid = item["blob_oid"]
139
+ sha = item["sha256"]
140
+ detector = item["detector"]
141
+ reason = item["reason"]
142
+ posix = PurePosixPath(rel)
143
+ backend_fixture = BACKEND_TEST_PATH_RE.fullmatch(rel) is not None
144
+ if (
145
+ not (backend_fixture or rel.startswith("tests/") or rel == "CHANGELOG.md" or rel.endswith(".py"))
146
+ or len(rel) > 1024
147
+ or posix.is_absolute()
148
+ or str(posix) != rel
149
+ or ".." in posix.parts
150
+ or any(c in rel for c in "\x00\n\r\t*?[]\\")
151
+ ):
152
+ raise ValueError("invalid exception path")
153
+ if local_only and not backend_fixture:
154
+ raise ValueError("local mode only allows backend/tests/test_*.py")
155
+ if backend_fixture and detector != "credential-assignment-v1":
156
+ raise ValueError("backend test requires credential-assignment-v1")
157
+ if (
158
+ len(oid) != len(root_commit)
159
+ or FULL_OID_RE.fullmatch(oid) is None
160
+ or re.fullmatch(r"[0-9a-f]{64}", sha) is None
161
+ ):
162
+ raise ValueError("invalid content identity")
163
+ if detector not in {"private-key-header-v1", "known-token-v1", "credential-assignment-v1"}:
164
+ raise ValueError("unknown fixture detector")
165
+ if not (0 < len(reason.strip()) <= 256) or any(c in reason for c in "\x00\n\r\t"):
166
+ raise ValueError("invalid exception reason")
167
+ key = (rel, oid, detector)
168
+ if key in seen_keys:
169
+ raise ValueError("duplicate exception")
170
+ seen_keys.add(key)
171
+
172
+ if phase == "worktree":
173
+ candidate = repo / rel
174
+ if (
175
+ candidate.is_symlink()
176
+ or not candidate.is_file()
177
+ or str(candidate.resolve(strict=True)) != str(candidate.resolve())
178
+ or candidate.stat().st_size > 16 * 1024 * 1024
179
+ ):
180
+ raise ValueError("invalid canonical worktree file")
181
+ ho = run_git(repo, "hash-object", "--no-filters", "--", rel)
182
+ if ho.returncode != 0 or ho.stdout.decode("ascii").strip() != oid:
183
+ raise ValueError("working blob oid mismatch")
184
+ content = candidate.read_bytes()
185
+ else:
186
+ content = read_blob_bytes(repo, oid, max_bytes=16 * 1024 * 1024)
187
+
188
+ if sha256_bytes(content) != sha:
189
+ raise ValueError("content sha256 mismatch")
190
+
191
+ verdict_needed = _detector_to_verdict(detector)
192
+ raw_findings = content_scan.findings(content)
193
+ if raw_findings.get(verdict_needed, 0) <= 0:
194
+ raise ValueError("approved detector did not match blob")
195
+
196
+ if rel == "CHANGELOG.md":
197
+ if detector != "private-key-header-v1" or not baseline_ref:
198
+ raise ValueError("changelog review requires baseline and private-key-header-v1")
199
+ _, base_bytes = _baseline_blob(repo, baseline_ref, "CHANGELOG.md")
200
+ if base_bytes is None or not content_scan.scan_changelog_header_preservation(content, base_bytes):
201
+ raise ValueError("changelog header validation failed")
202
+ elif not backend_fixture and not rel.startswith("tests/"):
203
+ if not rel.endswith(".py") or detector != "credential-assignment-v1" or not baseline_ref:
204
+ raise ValueError("prose review requires Python file, baseline, and credential-assignment-v1")
205
+ _, base_bytes = _baseline_blob(repo, baseline_ref, rel)
206
+ if base_bytes is None or not content_scan.scan_published_prose_reasons(content, base_bytes):
207
+ raise ValueError("published prose validation failed")
208
+
209
+ specs.append(
210
+ ExceptionSpec(
211
+ path=rel,
212
+ blob_oid=oid,
213
+ sha256=sha,
214
+ detector=detector,
215
+ reason=reason,
216
+ repo_meta=dict(repo_meta),
217
+ raw_item=dict(item),
218
+ )
219
+ )
220
+ except (OSError, UnicodeDecodeError, ValueError, TypeError, FinalizerError) as exc:
221
+ raise _reject(str(exc)) from exc
222
+ return specs
223
+
224
+
225
+ def _baseline_blob(repo: Path, ref_expr: str, path: str, env: dict[str, str] | None = None) -> tuple[str | None, bytes | None]:
226
+ return read_baseline_blob(repo, ref_expr, path, max_bytes=content_scan.MAX_SCAN_BYTES, env=env)
227
+
228
+
229
+ def _is_retained_staged_deletion(
230
+ repo: Path,
231
+ rel: str,
232
+ *,
233
+ is_unborn: bool,
234
+ env: dict[str, str] | None = None,
235
+ ) -> bool:
236
+ """Return True when `rel` is a staged deletion whose local copy is absent or gitignored."""
237
+ if is_unborn:
238
+ return False
239
+ is_del = (
240
+ run_git(
241
+ repo,
242
+ "--literal-pathspecs",
243
+ "diff",
244
+ "--cached",
245
+ "--no-renames",
246
+ "--no-ext-diff",
247
+ "--no-textconv",
248
+ "--quiet",
249
+ "--diff-filter=D",
250
+ "HEAD",
251
+ "--",
252
+ rel,
253
+ env=env,
254
+ ).returncode
255
+ == 1
256
+ )
257
+ if not is_del:
258
+ return False
259
+ target = repo / rel
260
+ return (not target.exists() and not target.is_symlink()) or (
261
+ run_git(repo, "check-ignore", "--quiet", "--no-index", "--", rel, env=env).returncode == 0
262
+ )
263
+
264
+
265
+ def _check_large_binary_policy(
266
+ path: str,
267
+ size: int,
268
+ raw: bytes,
269
+ *,
270
+ allow_large_binary_path: str | None,
271
+ policy: policy_mod.DeliveryPolicy,
272
+ ) -> tuple[bool, str | None]:
273
+ binary = is_binary_bytes(raw)
274
+ if binary and size > policy.max_file_bytes:
275
+ if size > policy.max_large_binary_bytes:
276
+ raise FinalizerError(
277
+ ErrorCode.BINARY_SIZE_EXCEEDED,
278
+ f"大二进制例外目标超过 25 MiB 硬上限: {path}",
279
+ final_phase="local_validation",
280
+ )
281
+ if allow_large_binary_path == path:
282
+ return True, f"allow-large-binary override accepted ({path}, {size} bytes)"
283
+ raise FinalizerError(
284
+ ErrorCode.BINARY_SIZE_EXCEEDED,
285
+ f"拒绝候选的大于 {policy.max_file_bytes // (1024 * 1024)} MiB 明显二进制文件: {path}",
286
+ final_phase="local_validation",
287
+ )
288
+ if not binary and size > content_scan.MAX_SCAN_BYTES:
289
+ raise FinalizerError(
290
+ ErrorCode.BINARY_SIZE_EXCEEDED,
291
+ f"文本文件超过扫描上限: {path}",
292
+ final_phase="local_validation",
293
+ )
294
+ return False, None
295
+
296
+
297
+ def _apply_content_gate(
298
+ *,
299
+ repo: Path,
300
+ path: str,
301
+ raw: bytes,
302
+ blob_oid: str | None,
303
+ stage: str,
304
+ baseline_ref: str | None,
305
+ cli: ParsedCLI,
306
+ specs: list[ExceptionSpec],
307
+ local_only: bool,
308
+ env: dict[str, str] | None = None,
309
+ ) -> tuple[list[dict[str, Any]], str | None]:
310
+ _, baseline_bytes = (
311
+ _baseline_blob(repo, baseline_ref, path, env=env)
312
+ if baseline_ref is not None
313
+ else (None, None)
314
+ )
315
+ diag = content_scan.scan_diagnostic(raw, path=path, stage=stage, blob_oid=blob_oid, baseline=baseline_bytes)
316
+ sha = sha256_bytes(raw)
317
+ if diag is None:
318
+ # Published files (e.g. prose *_REASONS unchanged from baseline) can match specs even when baseline subtraction yields CLEAR.
319
+ matched_clear = [
320
+ sp
321
+ for sp in specs
322
+ if sp.path == path and sp.sha256 == sha and (blob_oid is None or sp.blob_oid == blob_oid)
323
+ ]
324
+ if matched_clear:
325
+ for sp in matched_clear:
326
+ sp.consumed = True
327
+ order = ("private-key-header-v1", "known-token-v1", "credential-assignment-v1")
328
+ return [sp.to_receipt() for sp in sorted(matched_clear, key=lambda s: order.index(s.detector))], None
329
+ return [], None
330
+
331
+ if diag["verdict"] == "ERROR":
332
+ raise FinalizerError(
333
+ ErrorCode.CONTENT_SCAN_BLOCKED,
334
+ f"{'staged ' if stage == 'index' else ''}内容分类失败: {path}",
335
+ status="blocked" if stage != "index" else "failed",
336
+ final_phase="local_validation" if stage != "index" else "staging",
337
+ next_action="resolve_blocker_and_retry" if stage != "index" else "inspect_failure",
338
+ scan_diagnostic=diag,
339
+ )
340
+
341
+ # Check --allow-test-fixture for tests/ paths (legacy blanket override in allowlisted modes)
342
+ if (
343
+ cli.allow_test_fixtures
344
+ and path in cli.allow_test_fixtures
345
+ and path.startswith("tests/")
346
+ and cli.action in {"normal", "commit-only", "verify-only", "initial-publish", "resume-initial-publish", "initial-commit-only"}
347
+ ):
348
+ return [], f"root test fixture content override: {path}" if cli.action == "resume-initial-publish" else f"test fixture override: {path}"
349
+
350
+ detector = diag["detector"]
351
+ sha = diag["sha256"]
352
+ matching = [
353
+ sp
354
+ for sp in specs
355
+ if sp.path == path
356
+ and sp.detector == detector
357
+ and sp.sha256 == sha
358
+ and (blob_oid is None or sp.blob_oid == blob_oid)
359
+ ]
360
+ if matching:
361
+ # Enforce special rules for CHANGELOG.md & *_REASONS & local-only backend/tests!
362
+ if path == "CHANGELOG.md":
363
+ if detector != "private-key-header-v1" or baseline_bytes is None or not content_scan.scan_changelog_header_preservation(raw, baseline_bytes):
364
+ raise FinalizerError(
365
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
366
+ f"CHANGELOG.md 例外仅允许保留已有 inline-backtick header 且其余文本不变: {path}",
367
+ final_phase="local_validation",
368
+ scan_diagnostic=diag,
369
+ )
370
+ elif local_only and not BACKEND_TEST_PATH_RE.fullmatch(path):
371
+ if cli.action in {"verify-only", "commit-only"}:
372
+ raise FinalizerError(
373
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
374
+ f"本地 verify-only/commit-only 不支持该路径的 fixture exception: {path}",
375
+ final_phase="local_validation",
376
+ scan_diagnostic=diag,
377
+ )
378
+ elif (
379
+ path.endswith(".py")
380
+ and not path.startswith(("tests/", "backend/tests/"))
381
+ and (
382
+ baseline_bytes is None
383
+ or not content_scan.scan_published_prose_reasons(raw, baseline_bytes)
384
+ )
385
+ ):
386
+ raise FinalizerError(
387
+ ErrorCode.CONTENT_SCAN_BLOCKED,
388
+ f"候选敏感文件内容命中规则 ({detector}): {path}",
389
+ final_phase="local_validation",
390
+ scan_diagnostic=diag,
391
+ )
392
+
393
+ # Verify all findings on this blob have matching approvals (`other_findings <= approved_verdicts`).
394
+ all_specs_for_blob = [
395
+ sp
396
+ for sp in specs
397
+ if sp.path == path and sp.sha256 == sha and (blob_oid is None or sp.blob_oid == blob_oid)
398
+ ]
399
+ other_findings = content_scan.findings(raw)
400
+ if (
401
+ baseline_bytes is not None
402
+ and not BACKEND_TEST_PATH_RE.fullmatch(path)
403
+ and not path.startswith("tests/")
404
+ and path != "CHANGELOG.md"
405
+ ):
406
+ # Only published Python *_REASONS prose checks mask unchanged published prose separately via scan_published_prose_reasons.
407
+ other_findings = {}
408
+ approved_verdicts = {_detector_to_verdict(sp.detector) for sp in all_specs_for_blob}
409
+ unapproved = set(other_findings) - approved_verdicts
410
+ if not unapproved:
411
+ for sp in all_specs_for_blob:
412
+ sp.consumed = True
413
+ return [sp.to_receipt() for sp in sorted(all_specs_for_blob, key=lambda s: ("private-key-header-v1", "known-token-v1", "credential-assignment-v1").index(s.detector))], None
414
+
415
+ if detector == "known-token-v1":
416
+ det_label = "高置信度 token/credential 内容签名"
417
+ elif detector == "private-key-header-v1":
418
+ det_label = "private key header (private-key-header-v1)"
419
+ else:
420
+ det_label = detector
421
+ raise FinalizerError(
422
+ ErrorCode.CONTENT_SCAN_BLOCKED,
423
+ f"{'staged' if stage == 'index' else '候选'}敏感文件内容命中规则 ({det_label}): {path}(禁止硬编码敏感信息)",
424
+ status="blocked" if stage != "index" else "failed",
425
+ final_phase="local_validation" if stage != "index" else "staging",
426
+ next_action="resolve_blocker_and_retry" if stage != "index" else "inspect_failure",
427
+ scan_diagnostic=diag,
428
+ )
429
+
430
+
431
+ def validate_staged_candidate(
432
+ repo: Path,
433
+ info: repo_state.RepoInfo,
434
+ iso_env: dict[str, str],
435
+ paths: list[str],
436
+ cli: ParsedCLI,
437
+ policy: policy_mod.DeliveryPolicy,
438
+ *,
439
+ specs: list[ExceptionSpec],
440
+ local_only: bool,
441
+ ) -> ValidationOutcome:
442
+ """Run full pre-commit validation inside isolated temp GIT_INDEX_FILE & object dir."""
443
+ outcome = ValidationOutcome()
444
+
445
+ # Check source-review upfront at worktree stage if requested or sensitive path present
446
+ sensitive_paths = [p for p in paths if source_review.is_sensitive_path(p)]
447
+ if sensitive_paths and not cli.reviewed_sensitive_source:
448
+ raise FinalizerError(
449
+ ErrorCode.SOURCE_REVIEW_BLOCKED,
450
+ f"敏感命名源码文件需要 --reviewed-sensitive-source: {sensitive_paths[0]}",
451
+ final_phase="local_validation",
452
+ )
453
+ if cli.reviewed_sensitive_source and cli.allow_test_fixtures:
454
+ raise FinalizerError(
455
+ ErrorCode.CLI_INVALID_ARGS,
456
+ "--reviewed-sensitive-source 不能与 --allow-test-fixture 混用",
457
+ final_phase="cli",
458
+ )
459
+ if cli.reviewed_sensitive_source and cli.fixture_exceptions:
460
+ raise FinalizerError(
461
+ ErrorCode.CLI_INVALID_ARGS,
462
+ "--reviewed-sensitive-source 不能与 --fixture-exceptions 混用",
463
+ final_phase="cli",
464
+ )
465
+ if cli.allow_test_fixtures and cli.fixture_exceptions:
466
+ raise FinalizerError(
467
+ ErrorCode.CLI_INVALID_ARGS,
468
+ "--allow-test-fixture 不能与 --fixture-exceptions 混用",
469
+ final_phase="cli",
470
+ )
471
+ for f_path in cli.allow_test_fixtures:
472
+ if f_path not in paths:
473
+ raise FinalizerError(
474
+ ErrorCode.SCOPE_INVALID,
475
+ f"test fixture 不在本次显式文件范围内: {f_path}",
476
+ final_phase="local_validation",
477
+ )
478
+ if cli.allow_large_binary and cli.allow_large_binary not in paths:
479
+ raise FinalizerError(
480
+ ErrorCode.SCOPE_INVALID,
481
+ f"大二进制例外路径不在本次显式文件范围内: {cli.allow_large_binary}",
482
+ final_phase="local_validation",
483
+ )
484
+
485
+ retained_deletions = {
486
+ rel for rel in paths if _is_retained_staged_deletion(repo, rel, is_unborn=info.is_unborn, env=iso_env)
487
+ }
488
+
489
+ # Run worktree review path/digest checks upfront so summary carries `reviewed_sensitive_sources` even if secret scan blocks.
490
+ worktree_review_receipts: list[dict[str, Any]] = []
491
+ if cli.reviewed_sensitive_source:
492
+ worktree_review_receipts = source_review.validate_review_document(
493
+ review_file=cli.reviewed_sensitive_source,
494
+ repo=repo,
495
+ common_dir=info.common_dir,
496
+ repository_id=cli.repository_id,
497
+ allocation_id=cli.allocation_id,
498
+ task_key=cli.task_key,
499
+ authority_key=cli.authority_key,
500
+ worktree_path=cli.worktree_path,
501
+ requested_paths=paths,
502
+ stage="worktree",
503
+ stage_env=iso_env,
504
+ allowed_extensions=policy.allow_reviewed_extensions,
505
+ candidate_blobs=None,
506
+ baseline_ref=None if info.is_unborn else "HEAD",
507
+ )
508
+ outcome.reviewed_sensitive_sources = worktree_review_receipts
509
+
510
+ # 1. Worktree + Clean-filter candidate scan FIRST (before even running git add on isolated index)
511
+ candidate_blobs: dict[str, bytes] = {}
512
+ try:
513
+ for rel in paths:
514
+ if rel in retained_deletions:
515
+ continue
516
+ target = repo / rel
517
+ if target.is_symlink() or not target.exists():
518
+ continue
519
+ raw_wt = target.read_bytes()
520
+ _, w_msg = _check_large_binary_policy(
521
+ rel, len(raw_wt), raw_wt, allow_large_binary_path=cli.allow_large_binary, policy=policy
522
+ )
523
+ if w_msg:
524
+ outcome.warnings.append(w_msg)
525
+ baseline_ref = None if info.is_unborn else "HEAD"
526
+ wt_receipts, wt_warn = _apply_content_gate(
527
+ repo=repo,
528
+ path=rel,
529
+ raw=raw_wt,
530
+ blob_oid=None,
531
+ stage="worktree",
532
+ baseline_ref=baseline_ref,
533
+ cli=cli,
534
+ specs=specs,
535
+ local_only=local_only,
536
+ env=iso_env,
537
+ )
538
+ for rec in wt_receipts:
539
+ if rec not in outcome.fixture_exceptions:
540
+ outcome.fixture_exceptions.append(rec)
541
+ if wt_warn:
542
+ outcome.warnings.append(wt_warn)
543
+
544
+ cand_oid, cand_bytes = content_scan.hash_candidate_clean(repo, rel, target, env=iso_env)
545
+ candidate_blobs[rel] = cand_bytes
546
+ matching_specs = [s for s in specs if s.path == rel]
547
+ if matching_specs:
548
+ raw_hash_res = run_git(repo, "--literal-pathspecs", "hash-object", "--no-filters", "--", rel, env=iso_env)
549
+ if raw_hash_res.returncode != 0:
550
+ raise FinalizerError(
551
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
552
+ f"无法只读复核 local fixture raw blob: {rel}",
553
+ final_phase="local_validation",
554
+ )
555
+ raw_oid = raw_hash_res.stdout.decode("ascii", errors="strict").strip()
556
+ if all(s.blob_oid != raw_oid for s in matching_specs):
557
+ raise FinalizerError(
558
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
559
+ f"reviewed fixture raw blob 已漂移: {rel}",
560
+ final_phase="local_validation",
561
+ )
562
+ if cand_oid != raw_oid:
563
+ raise FinalizerError(
564
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
565
+ f"clean filter 改变了已审查的 fixture 文件: {rel}",
566
+ final_phase="local_validation",
567
+ )
568
+ # Also ensure any pre-existing staged change in real `.git/index` matches raw_oid cleanly.
569
+ real_idx_diff = run_git(repo, "--literal-pathspecs", "diff", "--cached", "--name-only", "--no-renames", "-z", "--", rel)
570
+ if real_idx_diff.returncode == 0 and real_idx_diff.stdout.strip(b"\x00"):
571
+ real_ls = run_git(repo, "--literal-pathspecs", "ls-files", "--stage", "-z", "--", rel)
572
+ real_entries = parse_nul_records(real_ls.stdout) if real_ls.returncode == 0 and real_ls.stdout.endswith(b"\x00") else []
573
+ if len(real_entries) != 1:
574
+ raise FinalizerError(
575
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
576
+ f"local fixture review staged entry 无效: {rel}",
577
+ final_phase="local_validation",
578
+ )
579
+ idx_header = real_entries[0].partition("\t")[0].split()
580
+ if len(idx_header) < 2 or idx_header[0] not in {"100644", "100755"} or idx_header[1] != raw_oid:
581
+ raise FinalizerError(
582
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
583
+ f"local fixture review staged blob 已漂移: {rel}",
584
+ final_phase="local_validation",
585
+ )
586
+ _check_large_binary_policy(
587
+ rel, len(cand_bytes), cand_bytes, allow_large_binary_path=cli.allow_large_binary, policy=policy
588
+ )
589
+ if cli.action == "verify-only":
590
+ c_receipts, _ = _apply_content_gate(
591
+ repo=repo,
592
+ path=rel,
593
+ raw=cand_bytes,
594
+ blob_oid=cand_oid,
595
+ stage="candidate",
596
+ baseline_ref=baseline_ref,
597
+ cli=cli,
598
+ specs=specs,
599
+ local_only=local_only,
600
+ env=iso_env,
601
+ )
602
+ for rec in c_receipts:
603
+ if rec not in outcome.fixture_exceptions:
604
+ outcome.fixture_exceptions.append(rec)
605
+ except FinalizerError as exc:
606
+ if worktree_review_receipts and not exc.reviewed_sensitive_sources:
607
+ exc.reviewed_sensitive_sources = [dict(r) for r in worktree_review_receipts]
608
+ raise
609
+
610
+ if cli.reviewed_sensitive_source:
611
+ outcome.reviewed_sensitive_sources = source_review.validate_review_document(
612
+ review_file=cli.reviewed_sensitive_source,
613
+ repo=repo,
614
+ common_dir=info.common_dir,
615
+ repository_id=cli.repository_id,
616
+ allocation_id=cli.allocation_id,
617
+ task_key=cli.task_key,
618
+ authority_key=cli.authority_key,
619
+ worktree_path=cli.worktree_path,
620
+ requested_paths=paths,
621
+ stage="worktree",
622
+ stage_env=iso_env,
623
+ allowed_extensions=policy.allow_reviewed_extensions,
624
+ candidate_blobs=candidate_blobs,
625
+ baseline_ref=None if info.is_unborn else "HEAD",
626
+ )
627
+
628
+ # 2. Stage requested paths exclusively in isolated temporary GIT_INDEX_FILE + GIT_OBJECT_DIRECTORY
629
+ # Keep existing staged deletions untouched if an ignored copy exists locally.
630
+ paths_to_stage = [rel for rel in paths if rel not in retained_deletions]
631
+
632
+ # 2. Gather candidate diff without `git add` in verify-only; stage in isolated temp index otherwise.
633
+ paths_to_stage = [rel for rel in paths if rel not in retained_deletions]
634
+ staged_names: list[str] = []
635
+ if cli.action == "verify-only":
636
+ if retained_deletions:
637
+ if info.is_unborn:
638
+ raise FinalizerError(
639
+ ErrorCode.SCOPE_INVALID,
640
+ "unborn HEAD 不支持 staged deletion",
641
+ final_phase="local_validation",
642
+ )
643
+ diff_del = run_git(
644
+ repo,
645
+ "--literal-pathspecs",
646
+ "diff",
647
+ "--cached",
648
+ "--name-only",
649
+ "--no-renames",
650
+ "-z",
651
+ "--",
652
+ *sorted(retained_deletions),
653
+ )
654
+ if diff_del.returncode != 0 or (diff_del.stdout and not diff_del.stdout.endswith(b"\x00")):
655
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法读取 staged deletion 范围", final_phase="local_validation")
656
+ staged_names.extend(parse_nul_records(diff_del.stdout))
657
+ for rel in paths_to_stage:
658
+ tracked = run_git(repo, "--literal-pathspecs", "ls-files", "--error-unmatch", "--", rel).returncode == 0
659
+ if not tracked:
660
+ ig = run_git(repo, "check-ignore", "--quiet", "--no-index", "--", rel)
661
+ if ig.returncode == 0:
662
+ raise FinalizerError(
663
+ ErrorCode.SCOPE_INVALID,
664
+ f"ignored 文件无法进入提交范围: {rel}",
665
+ final_phase="local_validation",
666
+ )
667
+ if ig.returncode != 1:
668
+ raise FinalizerError(
669
+ ErrorCode.INDEX_UNCLEAN,
670
+ f"无法验证 ignore 状态: {rel}",
671
+ final_phase="local_validation",
672
+ )
673
+ if paths_to_stage:
674
+ st = run_git(
675
+ repo,
676
+ "--literal-pathspecs",
677
+ "status",
678
+ "--porcelain=v1",
679
+ "-z",
680
+ "--untracked-files=all",
681
+ "--",
682
+ *paths_to_stage,
683
+ )
684
+ if st.returncode != 0 or (st.stdout and not st.stdout.endswith(b"\x00")):
685
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法读取候选变更范围", final_phase="local_validation")
686
+ recs = parse_nul_records(st.stdout)
687
+ r_idx = 0
688
+ while r_idx < len(recs):
689
+ rec = recs[r_idx]
690
+ r_idx += 1
691
+ if len(rec) >= 4:
692
+ staged_names.append(rec[3:])
693
+ if rec[0] in {"R", "C"} or rec[1] in {"R", "C"}:
694
+ r_idx += 1
695
+ changed = bool(staged_names)
696
+ else:
697
+ if paths_to_stage:
698
+ stage_res = run_git(repo, "--literal-pathspecs", "add", "-A", "--", *paths_to_stage, env=iso_env)
699
+ if stage_res.returncode != 0:
700
+ raise FinalizerError(
701
+ ErrorCode.INDEX_UNCLEAN,
702
+ f"在隔离暂存区暂存文件失败: {stage_res.stderr.decode('utf-8', errors='replace').strip()}",
703
+ final_phase="local_validation",
704
+ )
705
+
706
+ # 3. Verify non-empty staged change (unless dry-run explicitly warns on unchanged paths)
707
+ if info.is_unborn:
708
+ ls = run_git(repo, "--literal-pathspecs", "ls-files", "--cached", "-z", env=iso_env)
709
+ if ls.returncode != 0 or (ls.stdout and not ls.stdout.endswith(b"\x00")):
710
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法读取 staged 文件范围", final_phase="local_validation")
711
+ staged_names = parse_nul_records(ls.stdout)
712
+ changed = bool(staged_names)
713
+ else:
714
+ diff_names = run_git(repo, "--literal-pathspecs", "diff", "--cached", "--name-only", "--no-renames", "-z", env=iso_env)
715
+ if diff_names.returncode != 0 or (diff_names.stdout and not diff_names.stdout.endswith(b"\x00")):
716
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法读取 staged 文件范围", final_phase="local_validation")
717
+ staged_names = parse_nul_records(diff_names.stdout)
718
+ changed = bool(staged_names)
719
+
720
+ staged_set = set(staged_names)
721
+ if specs:
722
+ invalid_specs = [
723
+ s.path
724
+ for s in specs
725
+ if not s.consumed
726
+ or s.path not in staged_set
727
+ or (repo / s.path).is_symlink()
728
+ or not (repo / s.path).is_file()
729
+ ]
730
+ if invalid_specs:
731
+ raise FinalizerError(
732
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
733
+ f"未生效或不在变更候选范围内的 --fixture-exceptions 项: {', '.join(invalid_specs)}",
734
+ final_phase="local_validation",
735
+ )
736
+
737
+ if not changed:
738
+ if cli.dry_run:
739
+ outcome.warnings.extend([f"unchanged path: {p}" for p in paths])
740
+ tree_res = run_git(repo, "write-tree", env=iso_env)
741
+ outcome.tree_oid = tree_res.stdout.decode("ascii").strip() if tree_res.returncode == 0 else None
742
+ return outcome
743
+ raise FinalizerError(
744
+ ErrorCode.SCOPE_INVALID,
745
+ "显式路径范围内没有待提交的改动(diff 为空)",
746
+ status="blocked" if cli.action == "verify-only" else "failed",
747
+ final_phase="local_validation" if cli.action == "verify-only" else "staging",
748
+ next_action="resolve_blocker_and_retry" if cli.action == "verify-only" else "inspect_failure",
749
+ )
750
+
751
+ # 4. Whitespace check (+ counted unified-diff .patch context exemption)
752
+ diag_chunks: list[str] = []
753
+ ws_failed = False
754
+ if cli.action == "verify-only":
755
+ tracked_verify: list[str] = []
756
+ untracked_verify: list[str] = []
757
+ for rel in paths_to_stage:
758
+ if not info.is_unborn and run_git(repo, "--literal-pathspecs", "ls-files", "--error-unmatch", "--", rel).returncode == 0:
759
+ tracked_verify.append(rel)
760
+ else:
761
+ untracked_verify.append(rel)
762
+ if tracked_verify:
763
+ ws_t = run_git(repo, "--literal-pathspecs", "diff", "--no-ext-diff", "--no-textconv", "--check", "HEAD", "--", *tracked_verify)
764
+ if ws_t.returncode != 0:
765
+ ws_failed = True
766
+ diag_chunks.append(ws_t.stdout.decode("utf-8", errors="replace") + ws_t.stderr.decode("utf-8", errors="replace"))
767
+ for rel in untracked_verify:
768
+ target = repo / rel
769
+ if target.is_symlink() or not target.is_file():
770
+ continue
771
+ ws_u = run_git(repo, "diff", "--no-index", "--no-ext-diff", "--no-textconv", "--check", "--", "/dev/null", str(target))
772
+ raw_diag = ws_u.stdout.decode("utf-8", errors="replace") + ws_u.stderr.decode("utf-8", errors="replace")
773
+ if ws_u.returncode not in (0, 1) or raw_diag.strip():
774
+ ws_failed = True
775
+ diag_chunks.append(raw_diag.replace(str(target), rel))
776
+ else:
777
+ ws = run_git(repo, "diff", "--cached", "--check", env=iso_env)
778
+ if ws.returncode != 0:
779
+ ws_failed = True
780
+ diag_chunks.append(ws.stdout.decode("utf-8", errors="replace") + ws.stderr.decode("utf-8", errors="replace"))
781
+
782
+ if ws_failed:
783
+ diag_text = "\n".join(chunk for chunk in diag_chunks if chunk)
784
+ # Check if every reported file is `.patch` and passes exact counted empty-context validation
785
+ violating_files: set[str] = set()
786
+ for line in diag_text.splitlines():
787
+ if ":" in line:
788
+ violating_files.add(line.split(":", 1)[0])
789
+ if not violating_files:
790
+ raise FinalizerError(
791
+ ErrorCode.WHITESPACE_VIOLATION,
792
+ "git diff --check 失败;staged diff 存在 whitespace 错误",
793
+ final_phase="local_validation",
794
+ )
795
+ for vfile in violating_files:
796
+ if not vfile.endswith(".patch"):
797
+ raise FinalizerError(
798
+ ErrorCode.WHITESPACE_VIOLATION,
799
+ f"git diff --check 失败;存在 whitespace 错误: {vfile}",
800
+ final_phase="local_validation",
801
+ )
802
+ if cli.action == "verify-only":
803
+ blob_raw = candidate_blobs.get(vfile)
804
+ if blob_raw is None:
805
+ raise FinalizerError(ErrorCode.WHITESPACE_VIOLATION, f"git diff --check 失败;patch 候选不可读: {vfile}", final_phase="local_validation")
806
+ else:
807
+ ls = run_git(repo, "--literal-pathspecs", "ls-files", "--stage", "-z", "--", vfile, env=iso_env)
808
+ entries = parse_nul_records(ls.stdout)
809
+ if len(entries) != 1:
810
+ raise FinalizerError(ErrorCode.WHITESPACE_VIOLATION, f"git diff --check 失败;patch 文件暂存项异常: {vfile}", final_phase="local_validation")
811
+ blob_oid = entries[0].partition("\t")[0].split()[1]
812
+ blob_raw = read_blob_bytes(repo, blob_oid, max_bytes=patch_check.MAX_PATCH_BYTES + 1, env=iso_env)
813
+ file_diags = "\n".join(ln for ln in diag_text.splitlines() if ln.startswith(f"{vfile}:"))
814
+ if not patch_check.allow_patch_context_whitespace_only(repo, vfile, blob_raw, file_diags, env=iso_env):
815
+ raise FinalizerError(
816
+ ErrorCode.WHITESPACE_VIOLATION,
817
+ f"git diff --check 失败;patch 文件包含无效或超限的 whitespace 错误: {vfile}",
818
+ final_phase="local_validation",
819
+ )
820
+
821
+ # 5. Staged blob size, unified NUL binary check, content scan & reviewed source check (skipped re-staging in verify-only)
822
+ staged_blobs: dict[str, bytes] = dict(candidate_blobs) if cli.action == "verify-only" else {}
823
+ if cli.action != "verify-only":
824
+ ls_stage = run_git(repo, "--literal-pathspecs", "ls-files", "--stage", "-z", "--", *paths, env=iso_env)
825
+ if ls_stage.returncode != 0 or (ls_stage.stdout and not ls_stage.stdout.endswith(b"\x00")):
826
+ raise FinalizerError(ErrorCode.INDEX_UNCLEAN, "无法读取 staged 文件范围", final_phase="local_validation")
827
+ for rec in parse_nul_records(ls_stage.stdout):
828
+ meta, _, path = rec.partition("\t")
829
+ mode, oid, stage_num = meta.split()
830
+ if stage_num != "0" or mode not in {"100644", "100755", "120000"}:
831
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"拒绝非普通文件或冲突项: {path}", final_phase="local_validation")
832
+ if mode == "120000":
833
+ continue
834
+ size = read_blob_size(repo, oid, env=iso_env)
835
+ raw_blob = read_blob_bytes(repo, oid, max_bytes=max(content_scan.MAX_SCAN_BYTES, policy.max_large_binary_bytes), env=iso_env)
836
+ staged_blobs[path] = raw_blob
837
+ _check_large_binary_policy(
838
+ path, size, raw_blob, allow_large_binary_path=cli.allow_large_binary, policy=policy
839
+ )
840
+ baseline_ref = None if info.is_unborn else "HEAD"
841
+ try:
842
+ idx_receipts, _ = _apply_content_gate(
843
+ repo=repo,
844
+ path=path,
845
+ raw=raw_blob,
846
+ blob_oid=oid,
847
+ stage="index",
848
+ baseline_ref=baseline_ref,
849
+ cli=cli,
850
+ specs=specs,
851
+ local_only=local_only,
852
+ env=iso_env,
853
+ )
854
+ except FinalizerError as exc:
855
+ if worktree_review_receipts and not exc.reviewed_sensitive_sources:
856
+ exc.reviewed_sensitive_sources = [dict(r) for r in worktree_review_receipts]
857
+ raise
858
+ for r in idx_receipts:
859
+ if r not in outcome.fixture_exceptions:
860
+ outcome.fixture_exceptions.append(r)
861
+
862
+ if cli.reviewed_sensitive_source:
863
+ outcome.reviewed_sensitive_sources = source_review.validate_review_document(
864
+ review_file=cli.reviewed_sensitive_source,
865
+ repo=repo,
866
+ common_dir=info.common_dir,
867
+ repository_id=cli.repository_id,
868
+ allocation_id=cli.allocation_id,
869
+ task_key=cli.task_key,
870
+ authority_key=cli.authority_key,
871
+ worktree_path=cli.worktree_path,
872
+ requested_paths=paths,
873
+ stage="index",
874
+ stage_env=iso_env,
875
+ allowed_extensions=policy.allow_reviewed_extensions,
876
+ candidate_blobs=staged_blobs,
877
+ baseline_ref=None if info.is_unborn else "HEAD",
878
+ )
879
+ for rec in outcome.reviewed_sensitive_sources:
880
+ rec["content_scan"] = "passed"
881
+ else:
882
+ for rec in outcome.reviewed_sensitive_sources:
883
+ rec["content_scan"] = "passed"
884
+
885
+ # 6. External SARIF 2.1.0 scanners & OPA policy hook
886
+ if cli.scanners:
887
+ outcome.external_scanners = scanners.run_external_scanners(
888
+ staged_blobs, cli.scanners, policy, sarif_cmd=cli.sarif_cmd
889
+ )
890
+ if cli.opa_policy:
891
+ outcome.policy_verdict = policy_mod.evaluate_opa_policy(
892
+ Path(cli.opa_policy),
893
+ query=cli.opa_query,
894
+ input_document={
895
+ "mode": cli.mode,
896
+ "action": cli.action,
897
+ "branch": info.branch,
898
+ "requested_paths": paths,
899
+ "dry_run": cli.dry_run,
900
+ "trailer_agent": cli.trailer_agent,
901
+ "trace_ref": cli.trace_ref,
902
+ "snapshot_id": cli.snapshot,
903
+ "scanners": cli.scanners,
904
+ },
905
+ )
906
+
907
+ tree_out = run_git(repo, "write-tree", env=iso_env)
908
+ if tree_out.returncode == 0:
909
+ outcome.tree_oid = tree_out.stdout.decode("ascii").strip()
910
+ return outcome
911
+
912
+
913
+ def validate_commit_range(
914
+ repo: Path,
915
+ info: repo_state.RepoInfo,
916
+ commits: list[str],
917
+ cli: ParsedCLI,
918
+ policy: policy_mod.DeliveryPolicy,
919
+ *,
920
+ specs: list[ExceptionSpec],
921
+ local_only: bool = False,
922
+ reviewed_blobs: dict[str, str] | None = None,
923
+ ) -> ValidationOutcome:
924
+ """Validate an unpublished commit range commit-by-commit with exact parent baseline diff scanning."""
925
+ outcome = ValidationOutcome()
926
+ reviewed_fixture_paths_seen: set[str] = set()
927
+ head_large_binary_applied = False
928
+ for commit_oid in commits:
929
+ parents_res = run_git(repo, "rev-list", "--parents", "-n", "1", commit_oid)
930
+ if parents_res.returncode != 0:
931
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法读取提交父节点: {commit_oid}", final_phase="local_validation")
932
+ tokens = parents_res.stdout.decode("ascii").strip().split()
933
+ first_parent = tokens[1] if len(tokens) >= 2 else None
934
+ base_tree = first_parent if first_parent else "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
935
+
936
+ diff_tree = run_git(repo, "diff-tree", "--no-commit-id", "-r", "--name-status", "-z", base_tree, commit_oid)
937
+ if diff_tree.returncode != 0 or (diff_tree.stdout and not diff_tree.stdout.endswith(b"\x00")):
938
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法读取待发布 commit 文件范围: {commit_oid}", final_phase="local_validation")
939
+ records = parse_nul_records(diff_tree.stdout)
940
+ idx = 0
941
+ changed_paths: list[str] = []
942
+ while idx < len(records):
943
+ status_code = records[idx]
944
+ idx += 1
945
+ if status_code.startswith(("R", "C")):
946
+ if idx + 1 >= len(records):
947
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法读取待发布 commit 文件范围: {commit_oid}", final_phase="local_validation")
948
+ _old = records[idx]
949
+ new_p = records[idx + 1]
950
+ idx += 2
951
+ if not status_code.startswith("D"):
952
+ changed_paths.append(new_p)
953
+ else:
954
+ if idx >= len(records):
955
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法读取待发布 commit 文件范围: {commit_oid}", final_phase="local_validation")
956
+ p = records[idx]
957
+ idx += 1
958
+ if status_code != "D":
959
+ changed_paths.append(p)
960
+
961
+ # Check whitespace on commit diff (allowing verified .patch files)
962
+ chk = run_git(repo, "diff", "--check", base_tree, commit_oid)
963
+ if chk.returncode != 0:
964
+ diag_text = chk.stdout.decode("utf-8", errors="replace")
965
+ violating_files: set[str] = set()
966
+ for line in diag_text.splitlines():
967
+ if ":" in line:
968
+ violating_files.add(line.split(":", 1)[0])
969
+ if not violating_files:
970
+ raise FinalizerError(
971
+ ErrorCode.WHITESPACE_VIOLATION,
972
+ f"历史提交存在 whitespace 错误 ({commit_oid[:12]}): diff",
973
+ final_phase="local_validation",
974
+ )
975
+ for vfile in violating_files:
976
+ if not vfile.endswith(".patch"):
977
+ raise FinalizerError(
978
+ ErrorCode.WHITESPACE_VIOLATION,
979
+ f"历史提交存在 whitespace 错误 ({commit_oid[:12]}): {vfile}",
980
+ final_phase="local_validation",
981
+ )
982
+ _, patch_blob = _baseline_blob(repo, commit_oid, vfile)
983
+ file_diags = "\n".join(ln for ln in diag_text.splitlines() if ln.startswith(f"{vfile}:"))
984
+ if patch_blob is None or not patch_check.allow_patch_context_whitespace_only(repo, vfile, patch_blob, file_diags):
985
+ raise FinalizerError(
986
+ ErrorCode.WHITESPACE_VIOLATION,
987
+ f"历史提交 patch whitespace 错误: {vfile}",
988
+ final_phase="local_validation",
989
+ )
990
+
991
+ for rel in changed_paths:
992
+ if not rel or rel.startswith("/") or ".." in PurePosixPath(rel).parts or rel == ".git" or rel.startswith(".git/"):
993
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"待发布 commit 包含异常文件路径: {rel}", final_phase="local_validation")
994
+ ig = run_git(repo, "check-ignore", "--quiet", "--no-index", "--", rel)
995
+ if ig.returncode == 0 and cli.action in {"resume-publish"}:
996
+ raise FinalizerError(
997
+ ErrorCode.SCOPE_INVALID,
998
+ f"历史提交包含被 .gitignore 忽略的 ignored 文件: {rel}",
999
+ final_phase="local_validation",
1000
+ )
1001
+ ls = run_git(repo, "--literal-pathspecs", "ls-tree", "-z", commit_oid, "--", rel)
1002
+ if ls.returncode != 0 or (ls.stdout and not ls.stdout.endswith(b"\x00")):
1003
+ raise FinalizerError(ErrorCode.REPO_INVALID, f"无法读取待发布 commit 文件对象: {rel}", final_phase="local_validation")
1004
+ entries = parse_nul_records(ls.stdout)
1005
+ if len(entries) != 1:
1006
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"提交条目非普通文件或异常对象: {rel}", final_phase="local_validation")
1007
+ meta, _, entry_path = entries[0].partition("\t")
1008
+ parts = meta.split()
1009
+ if entry_path != rel or len(parts) != 3:
1010
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"提交条目非普通文件或异常对象: {rel}", final_phase="local_validation")
1011
+ mode, kind, blob_oid = parts
1012
+ if kind != "blob" or mode not in {"100644", "100755"} or FULL_OID_RE.fullmatch(blob_oid) is None:
1013
+ raise FinalizerError(ErrorCode.SCOPE_INVALID, f"历史提交包含非普通文件或异常对象: {rel} ({mode})", final_phase="local_validation")
1014
+
1015
+ sensitive_reason = source_review.sensitive_path_reason(rel)
1016
+ if sensitive_reason:
1017
+ if not reviewed_blobs or rel not in reviewed_blobs:
1018
+ raise FinalizerError(
1019
+ ErrorCode.SOURCE_REVIEW_BLOCKED,
1020
+ f"拒绝待发布敏感文件 {rel}: {sensitive_reason}",
1021
+ final_phase="local_validation",
1022
+ )
1023
+ if blob_oid != reviewed_blobs[rel]:
1024
+ raise FinalizerError(
1025
+ ErrorCode.SOURCE_REVIEW_BLOCKED,
1026
+ f"reviewed source history blob mismatch: {rel}",
1027
+ final_phase="local_validation",
1028
+ )
1029
+ elif reviewed_blobs and rel in reviewed_blobs and blob_oid != reviewed_blobs[rel]:
1030
+ raise FinalizerError(
1031
+ ErrorCode.SOURCE_REVIEW_BLOCKED,
1032
+ f"reviewed source history blob mismatch: {rel}",
1033
+ final_phase="local_validation",
1034
+ )
1035
+
1036
+ size = read_blob_size(repo, blob_oid)
1037
+ raw = read_blob_bytes(repo, blob_oid, max_bytes=max(content_scan.MAX_SCAN_BYTES, policy.max_large_binary_bytes))
1038
+ is_head_commit = (commit_oid == info.head_oid)
1039
+ _, warn_msg = _check_large_binary_policy(
1040
+ rel,
1041
+ size,
1042
+ raw,
1043
+ allow_large_binary_path=(cli.allow_large_binary if is_head_commit else None),
1044
+ policy=policy,
1045
+ )
1046
+ if warn_msg:
1047
+ head_large_binary_applied = True
1048
+ if warn_msg not in outcome.warnings:
1049
+ outcome.warnings.append(warn_msg)
1050
+
1051
+ has_exact_spec = any(sp.path == rel and sp.blob_oid == blob_oid for sp in specs)
1052
+ if rel in reviewed_fixture_paths_seen and not has_exact_spec:
1053
+ raise FinalizerError(
1054
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
1055
+ f"fixture exception path/blob identity mismatch: {rel}",
1056
+ final_phase="local_validation",
1057
+ )
1058
+
1059
+ rec_list, warn = _apply_content_gate(
1060
+ repo=repo,
1061
+ path=rel,
1062
+ raw=raw,
1063
+ blob_oid=blob_oid,
1064
+ stage="history",
1065
+ baseline_ref=first_parent,
1066
+ cli=cli,
1067
+ specs=specs,
1068
+ local_only=local_only,
1069
+ )
1070
+ if rec_list:
1071
+ reviewed_fixture_paths_seen.add(rel)
1072
+ for r in rec_list:
1073
+ if r not in outcome.fixture_exceptions:
1074
+ outcome.fixture_exceptions.append(r)
1075
+ if warn and warn not in outcome.warnings:
1076
+ outcome.warnings.append(warn)
1077
+
1078
+ # Reject unused --allow-large-binary
1079
+ if cli.allow_large_binary and not head_large_binary_applied:
1080
+ raise FinalizerError(
1081
+ ErrorCode.BINARY_SIZE_EXCEEDED,
1082
+ f"无效或未命中的 large binary history exception: {cli.allow_large_binary}",
1083
+ final_phase="local_validation",
1084
+ )
1085
+
1086
+ # Reject unused fixture exceptions
1087
+ unused = [sp.path for sp in specs if not sp.consumed]
1088
+ if unused:
1089
+ raise FinalizerError(
1090
+ ErrorCode.FIXTURE_EXCEPTION_BLOCKED,
1091
+ f"未使用的 --fixture-exceptions 项(或历史已发布): {', '.join(unused)}",
1092
+ final_phase="local_validation",
1093
+ )
1094
+
1095
+ return outcome