ueagentdevkit 0.2.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.
Tools/Hygiene/audit.py ADDED
@@ -0,0 +1,235 @@
1
+ """Read-only inventory. Never follow directory junctions or materialize Git LFS content."""
2
+
3
+ import hashlib
4
+ import os
5
+ import stat
6
+ import subprocess
7
+ from collections import Counter, defaultdict
8
+ from pathlib import Path
9
+
10
+ CACHE = {"intermediate", "deriveddatacache", "cooked", "zen", "stagedbuilds"}
11
+
12
+
13
+ def files(root, errors, excluded=()):
14
+ stack = [root]
15
+ while stack:
16
+ folder = stack.pop()
17
+ try:
18
+ with os.scandir(folder) as entries:
19
+ for entry in entries:
20
+ try:
21
+ info = entry.stat(follow_symlinks=False)
22
+ if (
23
+ stat.S_ISLNK(info.st_mode)
24
+ or getattr(info, "st_file_attributes", 0) & 1024
25
+ ):
26
+ continue
27
+ path = Path(entry.path)
28
+ if stat.S_ISDIR(info.st_mode):
29
+ if entry.name.casefold() not in excluded:
30
+ stack.append(path)
31
+ elif stat.S_ISREG(info.st_mode):
32
+ yield path, info.st_size
33
+ except OSError as exc:
34
+ errors.append(str(exc))
35
+ except OSError as exc:
36
+ errors.append(str(exc))
37
+
38
+
39
+ def digest(path):
40
+ with path.open("rb") as stream:
41
+ return hashlib.file_digest(stream, "sha256").hexdigest()
42
+
43
+
44
+ def git(root, *args, data=None):
45
+ proc = subprocess.run(
46
+ [
47
+ "git",
48
+ "--no-optional-locks",
49
+ "-c",
50
+ "core.fsmonitor=false",
51
+ "-c",
52
+ "filter.lfs.process=",
53
+ "-c",
54
+ "filter.lfs.clean=",
55
+ "-c",
56
+ "filter.lfs.required=false",
57
+ "-C",
58
+ str(root),
59
+ *args,
60
+ ],
61
+ input=data,
62
+ capture_output=True,
63
+ env=dict(os.environ, GIT_NO_LAZY_FETCH="1", GIT_TERMINAL_PROMPT="0"),
64
+ )
65
+ if proc.returncode:
66
+ raise ValueError(proc.stderr.decode("utf8", "replace").strip() or str(args))
67
+ return proc.stdout
68
+
69
+
70
+ def git_report(root, verify_content=False):
71
+ try:
72
+ common = Path(
73
+ os.fsdecode(
74
+ git(
75
+ root, "rev-parse", "--path-format=absolute", "--git-common-dir"
76
+ ).strip()
77
+ )
78
+ )
79
+ except ValueError as exc:
80
+ return {"error": str(exc)}
81
+
82
+ def lines(*args):
83
+ return git(root, *args).decode("utf8", "replace").splitlines()
84
+
85
+ history = git(root, "rev-list", "--objects", "--all").splitlines()
86
+ names = dict((line.partition(b" ")[0], line.partition(b" ")[2]) for line in history)
87
+ objects = git(
88
+ root,
89
+ "cat-file",
90
+ "--batch-check=%(objectname) %(objecttype) %(objectsize)",
91
+ data=b"".join(k + b"\n" for k in names),
92
+ ).splitlines()
93
+ sizes = [
94
+ (int(n), oid)
95
+ for row in objects
96
+ if len(v := row.split()) == 3
97
+ for oid, kind, n in [v]
98
+ if kind == b"blob"
99
+ ]
100
+ head_tree = {
101
+ row.partition(b"\t")[2]: row.partition(b"\t")[0].split()[2]
102
+ for row in git(root, "ls-tree", "-r", "-z", "HEAD").split(b"\0")
103
+ if row
104
+ }
105
+ current = set(head_tree.values())
106
+ unpublished = {
107
+ row.split()[0]
108
+ for row in git(
109
+ root, "rev-list", "--objects", "HEAD", "--not", "--remotes"
110
+ ).splitlines()
111
+ }
112
+ small = [oid for size, oid in sizes if 100 <= size <= 1024]
113
+ pointers = git(
114
+ root, "cat-file", "--batch", data=b"".join(oid + b"\n" for oid in small)
115
+ )
116
+ import io
117
+ import re
118
+
119
+ stream = io.BytesIO(pointers)
120
+ media = {}
121
+ pointer_blobs = set()
122
+ for oid in small:
123
+ length = int(stream.readline().split()[-1])
124
+ body = stream.read(length)
125
+ stream.read(1)
126
+ match = re.fullmatch(
127
+ rb"version https://git-lfs.github.com/spec/v1\r?\n(?:ext-[^\n]+\n)*oid sha256:([a-f0-9]{64})\r?\nsize (\d+)\r?\n?",
128
+ body,
129
+ )
130
+ if match:
131
+ pointer_blobs.add(oid)
132
+ key = match[1].decode()
133
+ flags = media.setdefault(key, [int(match[2]), False, False])
134
+ flags[1] |= oid in current
135
+ flags[2] |= oid in unpublished
136
+ config = (
137
+ lines("config", "--get-regexp", "^lfs[.]storage$")
138
+ if "lfs.storage" in lines("config", "--name-only", "--list")
139
+ else []
140
+ )
141
+ storage = Path(config[-1].split(" ", 1)[1]) if config else Path("lfs")
142
+ base = (common / storage / "objects").resolve()
143
+ missing = []
144
+ corrupt = []
145
+ for key, (size, head, _) in media.items():
146
+ obj = base / key[:2] / key[2:4] / key
147
+ if head and (not obj.is_file() or obj.stat().st_size != size):
148
+ missing.append(key)
149
+ elif head and verify_content and digest(obj) != key:
150
+ corrupt.append(key)
151
+ status = lines("status", "--porcelain", "--untracked-files=normal")
152
+ paths = [
153
+ p
154
+ for p, v in head_tree.items()
155
+ if v in pointer_blobs or p.lower().endswith((b".umap", b".uasset"))
156
+ ]
157
+ attrs = git(
158
+ root,
159
+ "check-attr",
160
+ "--cached",
161
+ "-z",
162
+ "--stdin",
163
+ "filter",
164
+ data=b"".join(p + b"\0" for p in paths),
165
+ ).split(b"\0")
166
+ rules = [
167
+ os.fsdecode(p)
168
+ for p, attr, value in zip(attrs[::3], attrs[1::3], attrs[2::3])
169
+ if value != b"lfs" or head_tree[p] not in pointer_blobs
170
+ ]
171
+ return dict(
172
+ common_dir=str(common),
173
+ head=lines("rev-parse", "HEAD")[0],
174
+ dirty_entries=len(status),
175
+ worktrees=lines("worktree", "list", "--porcelain"),
176
+ branches=lines("branch", "-vv"),
177
+ git_objects=lines("count-objects", "-v"),
178
+ historical_largest=[
179
+ dict(bytes=n, path=os.fsdecode(names[o]))
180
+ for n, o in sorted(sizes, reverse=True)[:12]
181
+ ],
182
+ lfs=dict(
183
+ storage=str(base),
184
+ history_oids=len(media),
185
+ head_oids=sum(v[1] for v in media.values()),
186
+ history_unique_bytes=sum(v[0] for v in media.values()),
187
+ head_unique_bytes=sum(v[0] for v in media.values() if v[1]),
188
+ corrupt_head_oids=corrupt if verify_content else None,
189
+ missing_or_wrong_size_at_head=missing,
190
+ local_only_ref_candidates=[k for k, v in media.items() if v[2]],
191
+ remote_object_presence="unknown; local remote-tracking refs only",
192
+ asset_or_pointer_rule_warnings=rules,
193
+ tracked_rules=lines("ls-files", "*gitattributes"),
194
+ ),
195
+ )
196
+
197
+
198
+ def audit(root, duplicates=False):
199
+ errors, projects, sizes, buckets = [], [], defaultdict(list), Counter()
200
+ for path, n in files(root, errors):
201
+ parts = tuple(x.lower() for x in path.relative_to(root).parts)
202
+ if path.suffix.lower() == ".uproject":
203
+ projects.append(str(path))
204
+ group = next(
205
+ (s for s in parts[:-1] if s in CACHE),
206
+ parts[0] if len(parts) > 1 else "(root)",
207
+ )
208
+ buckets[group] += n
209
+ if duplicates and n and ".git" not in parts:
210
+ sizes[n].append(path)
211
+ groups = []
212
+ for size, paths in sizes.items():
213
+ if len(paths) < 2:
214
+ continue
215
+ hashes = defaultdict(list)
216
+ for path in paths:
217
+ try:
218
+ hashes[digest(path)].append(str(path))
219
+ except OSError as exc:
220
+ errors.append(str(exc))
221
+ groups.extend(
222
+ dict(bytes_each=size, sha256=h, paths=ps)
223
+ for h, ps in hashes.items()
224
+ if len(ps) > 1
225
+ )
226
+ return dict(
227
+ root=str(root),
228
+ projects=sorted(projects),
229
+ logical_bytes=sum(buckets.values()),
230
+ categories=dict(buckets),
231
+ scan_errors=errors,
232
+ git=git_report(root),
233
+ duplicates=groups,
234
+ reclaimable_bytes_verified=0,
235
+ )
Tools/Hygiene/cli.py ADDED
@@ -0,0 +1,291 @@
1
+ """UEAgentDevKit project hygiene CLI and interactive menu."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import uuid
11
+ import zipfile
12
+
13
+ from Tools.Hygiene.audit import audit, digest, files, git_report
14
+ from Tools.Hygiene.lifecycle import cache_review, save, space_budget
15
+ from Tools.Hygiene.recovery import ART, guarded, operate, plan
16
+
17
+ REPORTS = ART / "HygieneReports"
18
+
19
+
20
+ def directory(path):
21
+ p = Path(path).expanduser().resolve(strict=True)
22
+ if p.is_file() and p.suffix.lower() == ".uproject":
23
+ return p.parent
24
+ if not p.is_dir():
25
+ raise ValueError("Supply a directory or .uproject")
26
+ return p
27
+
28
+
29
+ def volumes(targets):
30
+ """Group source, archive and restore paths by their actual file system."""
31
+ grouped = {}
32
+ for target in targets:
33
+ path = Path(target).expanduser().resolve(strict=True)
34
+ device = path.stat().st_dev
35
+ if device not in grouped:
36
+ usage = shutil.disk_usage(path)
37
+ grouped[device] = dict(paths=[], total_bytes=usage.total, free_bytes=usage.free)
38
+ grouped[device]["paths"].append(str(path))
39
+ return list(grouped.values())
40
+
41
+
42
+ def discover(root):
43
+ errors = []
44
+ projects = [
45
+ str(p)
46
+ for p, _ in files(
47
+ root,
48
+ errors,
49
+ {
50
+ ".git",
51
+ "saved",
52
+ "intermediate",
53
+ "deriveddatacache",
54
+ "content",
55
+ "node_modules",
56
+ },
57
+ )
58
+ if p.suffix.lower() == ".uproject"
59
+ ]
60
+ return dict(root=str(root), projects=sorted(projects), scan_errors=errors)
61
+
62
+
63
+ def tree(root):
64
+ result = {}
65
+ for folder, dirs, names in os.walk(
66
+ root, onerror=lambda exc: (_ for _ in ()).throw(exc)
67
+ ):
68
+ for name in dirs + names:
69
+ p = Path(folder) / name
70
+ if p.is_symlink() or getattr(p.lstat(), "st_file_attributes", 0) & 1024:
71
+ raise ValueError("Migration requires separate link handling: " + str(p))
72
+ result[str(p.relative_to(root))] = None if name in dirs else digest(p)
73
+ return result
74
+
75
+
76
+ def compare(source, restored):
77
+ if source.is_relative_to(restored) or restored.is_relative_to(source):
78
+ raise ValueError("Choose independent non-nested trees")
79
+ a, b = tree(source), tree(restored)
80
+ diff = [
81
+ k
82
+ for k in sorted(a.keys() | b.keys())
83
+ if k not in a or k not in b or a[k] != b[k]
84
+ ]
85
+ return dict(
86
+ status="FAIL" if diff else "PASS",
87
+ source=str(source),
88
+ restored=str(restored),
89
+ entries=len(a),
90
+ differences=diff,
91
+ scope="directory names, file names and SHA-256; engine startup and remote LFS need separate verification",
92
+ )
93
+
94
+
95
+ def report(action, data):
96
+ REPORTS.mkdir(parents=True, exist_ok=True)
97
+ path = REPORTS / (action + "-" + uuid.uuid4().hex + ".json")
98
+ save(path, data)
99
+ print(str(path))
100
+ if action == "plan":
101
+ print("Plan SHA-256:", digest(path))
102
+ if "status" in data:
103
+ print(data["status"])
104
+ return int(data.get("status") == "FAIL" or bool(data.get("scan_errors")))
105
+
106
+
107
+ def menu(target):
108
+ print("UEAgentDevKit 工程治理 | " + str(target))
109
+ options = {
110
+ "1": "discover",
111
+ "2": "lfs-audit",
112
+ "3": "plan",
113
+ "4": "dedup",
114
+ "5": "runs",
115
+ "6": "assets",
116
+ "7": "archive",
117
+ "8": "migration",
118
+ "9": "audit",
119
+ }
120
+ while True:
121
+ print(
122
+ "1 工程发现 2 Git/LFS 3 缓存计划 4 重复扫描 5 实验清单\n6 UE 资产引用 7 验证并归档计划 8 迁移校验 9 存储报告 0 退出"
123
+ )
124
+ try:
125
+ pick = input("> ").strip().lstrip("\ufeff")
126
+ except EOFError:
127
+ return 0
128
+ if pick == "0":
129
+ return 0
130
+ if pick not in options:
131
+ continue
132
+ op = options[pick]
133
+ argv = [op]
134
+ if op in ("archive", "plan", "assets"):
135
+ argv.append(
136
+ input(
137
+ {
138
+ "archive": "计划 JSON",
139
+ "plan": "启用兼容适配器的已完成录制 Run 目录",
140
+ "assets": "实验副本 .uproject",
141
+ }[op]
142
+ + ": "
143
+ ).strip('" ')
144
+ )
145
+ elif op != "runs":
146
+ argv.append(str(target))
147
+ if op == "migration":
148
+ argv.append(input("已恢复的独立目录: ").strip('" '))
149
+ main(argv)
150
+
151
+
152
+ def main(argv=None):
153
+ parser = argparse.ArgumentParser(description=__doc__)
154
+ sub = parser.add_subparsers(dest="action", required=True)
155
+ preflight = sub.add_parser("preflight", help="Check peak incremental space before a manual build or capture")
156
+ preflight.add_argument("path", type=directory)
157
+ preflight.add_argument("--peak-gib", type=int, required=True)
158
+ sub.add_parser("volumes", help="Snapshot free space on source, archive and restore volumes").add_argument("paths", nargs="+", type=Path)
159
+ for op in (
160
+ "menu",
161
+ "discover",
162
+ "audit",
163
+ "lfs-audit",
164
+ "dedup",
165
+ "plan",
166
+ "archive",
167
+ "verify",
168
+ "restore",
169
+ "release",
170
+ "migration",
171
+ "cache-review",
172
+ "runs",
173
+ "assets",
174
+ ):
175
+ p = sub.add_parser(op)
176
+ if op != "runs":
177
+ p.add_argument(
178
+ "target",
179
+ type=Path,
180
+ **(
181
+ {"nargs": "?", "default": Path.cwd()}
182
+ if op in ("menu", "discover", "audit", "dedup", "lfs-audit")
183
+ else {}
184
+ ),
185
+ )
186
+ if op == "migration":
187
+ p.add_argument("restored", type=Path)
188
+ if op == "release":
189
+ p.add_argument("--approve", required=True)
190
+ if op == "lfs-audit":
191
+ p.add_argument("--verify-content", action="store_true")
192
+ args = parser.parse_args(argv)
193
+ op = args.action
194
+ try:
195
+ if op == "preflight":
196
+ result = space_budget(args.path, args.peak_gib * 1024**3)
197
+ print(json.dumps(result, indent=2))
198
+ return int(not result["allowed"])
199
+ if op == "volumes":
200
+ print(json.dumps(volumes(args.paths), ensure_ascii=False, indent=2))
201
+ return 0
202
+ if op == "menu":
203
+ return menu(args.target)
204
+ if op in ("archive", "verify", "restore", "release"):
205
+ return report(op, operate(op, args.target, getattr(args, "approve", None)))
206
+ if op == "runs":
207
+ data = {"runs": []}
208
+ for parent in ("Runs", "Labs"):
209
+ for path in sorted((ART / parent).glob("*")):
210
+ if path.is_dir():
211
+ manifest = path / "lifecycle.json"
212
+ row = (
213
+ json.loads(manifest.read_bytes())
214
+ if manifest.is_file()
215
+ else dict(state="legacy-unclassified")
216
+ )
217
+ errors = []
218
+ used = sum(n for _, n in files(path, errors))
219
+ data["runs"].append(
220
+ dict(
221
+ path=str(path),
222
+ manifest=row,
223
+ logical_bytes=used,
224
+ scan_errors=errors,
225
+ )
226
+ )
227
+ return report(op, data)
228
+ root = directory(args.target)
229
+ if op == "cache-review":
230
+ return report(op, cache_review(root))
231
+ if op == "assets":
232
+ project = guarded(args.target.resolve(strict=True))
233
+ if project.suffix.lower() != ".uproject" or not any(
234
+ project.is_relative_to(ART / n) for n in ("Labs", "Runs")
235
+ ):
236
+ raise ValueError(
237
+ "Asset Registry inspection runs in an isolated lab/copy"
238
+ )
239
+ from Tools.environment import find_engine
240
+ from Tools.environment import editors
241
+
242
+ if any(Path(e["project"]).resolve() == project for e in editors()):
243
+ raise ValueError("Close the lab editor before Asset Registry scan")
244
+ engine = find_engine(
245
+ json.loads(project.read_text(encoding="utf-8-sig"))[
246
+ "EngineAssociation"
247
+ ],
248
+ None,
249
+ )
250
+ REPORTS.mkdir(parents=True, exist_ok=True)
251
+ output = REPORTS / ("assets-" + uuid.uuid4().hex + ".json")
252
+ script = Path(__file__).with_name("registry_scan.py")
253
+ subprocess.run(
254
+ [
255
+ str(engine / "Engine/Binaries/Win64/UnrealEditor-Cmd.exe"),
256
+ str(project),
257
+ "-run=pythonscript",
258
+ f"-script={script}",
259
+ "-unattended",
260
+ "-nullrhi",
261
+ "-nosound",
262
+ ],
263
+ env=dict(os.environ, DEVKIT_ASSET_REPORT=str(output)),
264
+ check=True,
265
+ timeout=900,
266
+ )
267
+ if not output.is_file():
268
+ raise ValueError("Asset Registry returned no report")
269
+ print(output)
270
+ return 0
271
+ if op == "discover":
272
+ data = discover(root)
273
+ elif op == "lfs-audit":
274
+ data = git_report(root, args.verify_content)
275
+ elif op == "plan":
276
+ data = plan(root)
277
+ elif op == "migration":
278
+ data = compare(root, directory(args.restored))
279
+ else:
280
+ data = audit(root, op == "dedup")
281
+ return report(op, data)
282
+ except (
283
+ ValueError,
284
+ KeyError,
285
+ OSError,
286
+ RuntimeError,
287
+ subprocess.SubprocessError,
288
+ zipfile.BadZipFile,
289
+ ) as exc:
290
+ print(str(exc), file=sys.stderr)
291
+ return 1
@@ -0,0 +1,148 @@
1
+ """Lifecycle records for DevKit-owned runs. Interrupted producers remain active."""
2
+
3
+ import json
4
+ import os
5
+ import shutil
6
+ import uuid
7
+ from pathlib import Path
8
+ from datetime import datetime, timezone
9
+
10
+ from Tools.Hygiene.audit import git, files, digest
11
+
12
+
13
+ def space_budget(run, estimate, reserve_gib=2):
14
+ free = shutil.disk_usage(run).free
15
+ reserve = int(os.environ.get("UEAGENT_RESERVE_GIB", reserve_gib)) * (1024**3)
16
+ target = int(os.environ.get("UEAGENT_TARGET_GIB", reserve // (1024**3))) * (1024**3)
17
+ if reserve < 0 or target < 0 or estimate < 0:
18
+ raise ValueError("Expected a non-negative disk budget")
19
+ projected = free - estimate
20
+ return dict(free=free, estimated_bytes=estimate, reserve_bytes=reserve,
21
+ below_target=projected < max(target, reserve),
22
+ allowed=projected >= reserve)
23
+
24
+
25
+ def budget(run, estimate, reserve_gib=2):
26
+ result = space_budget(run, estimate, reserve_gib)
27
+ save(run / "disk-budget.json", result)
28
+ if not result["allowed"]:
29
+ raise ValueError("Insufficient free space for this run; see disk-budget.json")
30
+
31
+
32
+ def estimate_copy(source):
33
+ errors = []
34
+ total = sum(
35
+ n
36
+ for name in ("Source", "Build", "Content", "Plugins", "Config", "Binaries")
37
+ if (source / name).is_dir()
38
+ for p, n in files(
39
+ source / name, errors, {"intermediate", "saved", "deriveddatacache", ".git"}
40
+ )
41
+ )
42
+ if errors:
43
+ raise ValueError("Cannot estimate source copy: " + errors[0])
44
+ return total
45
+
46
+
47
+ def save(path, value):
48
+ tmp = path.with_name("." + uuid.uuid4().hex)
49
+ tmp.write_text(json.dumps(value, ensure_ascii=True, indent=2), encoding="utf8")
50
+ os.replace(tmp, path)
51
+
52
+
53
+ def begin(run, source, kind, options):
54
+ try:
55
+ head = git(source.parent, "rev-parse", "HEAD").decode().strip()
56
+ dirty = bool(git(source.parent, "status", "--porcelain"))
57
+ except (ValueError, OSError):
58
+ head, dirty = None, None
59
+ inputs = {}
60
+ if source.is_file():
61
+ inputs["descriptor_sha256"] = digest(source)
62
+ if source.suffix.lower() == ".uproject":
63
+ from Tools.environment import find_engine, read_json
64
+
65
+ try:
66
+ descriptor = read_json(source)
67
+ engine = (
68
+ find_engine(descriptor["EngineAssociation"], options.get("engine"))
69
+ / "Engine"
70
+ )
71
+ inputs.update(
72
+ engine=read_json(engine / "Build/Build.version"),
73
+ build_id=read_json(engine / "Binaries/Win64/UnrealEditor.modules")[
74
+ "BuildId"
75
+ ],
76
+ declared_plugins=descriptor.get("Plugins", []),
77
+ )
78
+ except (ValueError, KeyError, OSError) as exc:
79
+ inputs["discovery_error"] = str(exc)
80
+ save(
81
+ run / "lifecycle.json",
82
+ dict(
83
+ id=run.name,
84
+ kind=kind,
85
+ state="running",
86
+ pid=os.getpid(),
87
+ started=datetime.now(timezone.utc).isoformat(),
88
+ source=str(source),
89
+ head=head,
90
+ dirty=dirty,
91
+ options=options,
92
+ inputs=inputs,
93
+ free_at_start=shutil.disk_usage(run).free,
94
+ ),
95
+ )
96
+
97
+
98
+ def cache_review(host):
99
+ """List compiler outputs for review after a successful isolated build."""
100
+ errors = []
101
+ entries = []
102
+ for path, size in files(host, errors, {".git", ".svn", "content", "saved", "sourceart"}):
103
+ parts = [part.casefold() for part in path.relative_to(host).parts]
104
+ if path.suffix.lower() in {".pch", ".obj"} and ("intermediate", "build") in zip(parts, parts[1:]):
105
+ entries.append({"path": str(path), "bytes": size})
106
+ return dict(host=str(host), entries=entries, logical_bytes=sum(x["bytes"] for x in entries),
107
+ status="incomplete" if errors else "pending review", scan_errors=errors)
108
+
109
+
110
+ def finish(run, state, **details):
111
+ path = run / "lifecycle.json"
112
+ record = json.loads(path.read_text(encoding="utf8"))
113
+ if state == "PASS":
114
+ host = run / "copy"
115
+ if details.get("host"):
116
+ host = Path(details["host"])
117
+ managed_lab = run.parent.parent / "Labs"
118
+ if host.is_dir() and host.resolve() == host and (host == run / "copy" or host.parent == managed_lab):
119
+ save(run / "build-cache-review.json", cache_review(host))
120
+ record["cache_review"] = "build-cache-review.json"
121
+ outputs = sorted(p.name for p in run.iterdir() if p.name != "lifecycle.json")
122
+ classifications = {}
123
+ for name in outputs:
124
+ if state not in ("PASS", "READY"):
125
+ role = "incident evidence"
126
+ elif name == "copy":
127
+ role = "isolated playable input; preserve pending review"
128
+ elif name in ("uap.tar", "plugin.tar"):
129
+ role = "recoverable pinned dependency"
130
+ elif name in ("ready.txt", "start.txt"):
131
+ role = "coordination marker"
132
+ else:
133
+ role = "retained output or input evidence"
134
+ classifications[name] = role
135
+ record.update(
136
+ state=state,
137
+ finished=datetime.now(timezone.utc).isoformat(),
138
+ details=details,
139
+ free_at_finish=shutil.disk_usage(run).free,
140
+ outputs=outputs,
141
+ classifications=classifications,
142
+ retention="permanent evidence; reviewed scratch eligible"
143
+ if state == "PASS"
144
+ else ("reusable lab" if state == "READY" else "preserve incident"),
145
+ archive="see HygieneReports plans and HygieneVault",
146
+ restore="hygiene restore PLAN",
147
+ )
148
+ save(path, record)