Hash project content before reusing discovery evidence

This commit is contained in:
阿白叔 committed 2026-10-15 09:39:53 +08:00
1 parent 78f3b0c32a
commit 87ec3acc20
2 files changed
+59 -4

No files matched your search

@@ -1,13 +1,14 @@
"""Conservative, bounded process-local reuse of read-only CAD discovery.
Metadata fingerprints cover every project-tree file except generated logs and
explicit tool data. Links, unreadable paths and changing discovery are misses.
Content and metadata fingerprints cover every project-tree file except generated
logs and explicit tool data. Links, unreadable paths and changing discovery are misses.
This is an optimization, never a replacement for execution identity checks.
"""
from __future__ import annotations
from collections import OrderedDict
from copy import deepcopy
import hashlib
import os
from pathlib import Path
import stat
@@ -48,8 +49,23 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
info = path.lstat()
if _unsafe(info) or not stat.S_ISREG(info.st_mode):
return None
rows.append((str(path.relative_to(root)), info.st_dev, info.st_ino,
info.st_size, info.st_mtime_ns, info.st_ctime_ns))
before = _file_stamp(info)
with path.open('rb') as stream:
handle_before = _file_stamp(os.fstat(stream.fileno()))
# Windows path stat and handle stat expose different ctime
# semantics. Compare their identity/size/mtime, then compare
# each source's full stamp against itself after hashing.
if handle_before[:4] != before[:4]:
return None
digest = hashlib.file_digest(stream, 'sha256').digest()
if _file_stamp(os.fstat(stream.fileno())) != handle_before:
return None
# Check the path as well as the handle: atomic replacement can
# leave a readable handle referring to the obsolete file.
after = path.lstat()
if _unsafe(after) or _file_stamp(after) != before:
return None
rows.append((str(path.relative_to(root)), *before, digest))
if not project.is_file():
return None
return (str(project.resolve()), tuple(sorted(rows)))
@@ -57,6 +73,10 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
return None
def _file_stamp(info):
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
def _unsafe(info):
return stat.S_ISLNK(info.st_mode) or bool(
getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400))