@pennixrv/trellis 0.7.2-beta.29 → 0.7.2-beta.30

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,446 @@
1
+ """Approved delegation packages, exact checkout ownership and Git acceptance."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import subprocess
10
+ from typing import NoReturn
11
+
12
+ from .io import read_json_checked, write_json
13
+ from .paths import get_repo_root
14
+
15
+ MAX_BYTES = 256 * 1024
16
+ SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
17
+
18
+
19
+ def fail(message: str) -> NoReturn:
20
+ from .task_workflow import TaskWorkflowError
21
+ raise TaskWorkflowError("TASK_DELEGATE_WITHHELD", message)
22
+
23
+
24
+ def digest(value) -> str:
25
+ data = value if isinstance(value, bytes) else json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
26
+ return hashlib.sha256(data).hexdigest()
27
+
28
+
29
+ def read(path: Path) -> dict:
30
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_BYTES:
31
+ fail(f"invalid bounded regular JSON file: {path}")
32
+ value, reason = read_json_checked(path)
33
+ if value is None:
34
+ fail(f"cannot read {path}: {reason}")
35
+ return value
36
+
37
+
38
+ def save(path: Path, value: dict):
39
+ rendered = json.dumps(value, indent=2, ensure_ascii=False)
40
+ size = len(rendered.encode("utf8")) + (rendered.count("\n") if os.name == "nt" else 0)
41
+ if size > MAX_BYTES:
42
+ fail(f"bounded JSON output would exceed its readable limit: {path}; previous state preserved")
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ if path.is_symlink() or not write_json(path, value):
45
+ fail(f"could not atomically save {path}; preserve current state")
46
+
47
+
48
+ def runtime_path(root: Path, task_id: str) -> Path:
49
+ if not SAFE_ID.fullmatch(task_id):
50
+ fail("unsafe task identity")
51
+ path = root / ".trellis/.runtime/delegation" / task_id / "record.json"
52
+ if path.resolve() != path.absolute():
53
+ fail("redirected delegation runtime")
54
+ return path
55
+
56
+
57
+ def resolve_record(root: Path, task_dir: Path, data: dict):
58
+ """One resolver for current runtime and historical task-meta consumers."""
59
+ path = runtime_path(root, task_dir.name)
60
+ return read(path) if path.exists() else data.get("meta", {}).get("delegated_worktree_execution_record")
61
+
62
+
63
+ def git(root: Path, *args: str, raw: bool = False) -> str:
64
+ result = subprocess.run(["git", *args], cwd=root, capture_output=True, text=True, encoding="utf8", timeout=30)
65
+ if result.returncode:
66
+ fail(f"Git identity/check failed: {args[0]}")
67
+ return result.stdout if raw else result.stdout.strip()
68
+
69
+
70
+ def git_paths(root: Path, command: str, *args: str) -> list[str]:
71
+ return [name for name in git(root, command, "-z", *args, raw=True).split("\0") if name]
72
+
73
+
74
+ def identity(root: Path) -> dict:
75
+ root = root.resolve(strict=True)
76
+ if Path(git(root, "rev-parse", "--show-toplevel")).resolve() != root:
77
+ fail("target must be the exact checkout root")
78
+ return {"checkout": str(root), "common_dir": str(Path(git(root, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve())}
79
+
80
+
81
+ def task_inputs(child_dir: Path, *, require_authorization: bool = True):
82
+ from .task_workflow import _load, _task_dir, _state, implementation_start_ready, TaskWorkflowError
83
+ from .task_continuity import assert_task_mutation_allowed, assert_task_safety_allowed
84
+ child, _ = _load(child_dir)
85
+ if not child.get("parent"):
86
+ fail("child must be linked to an authorized controller task")
87
+ parent_dir = _task_dir(child["parent"])
88
+ parent, meta = _load(parent_dir)
89
+ if require_authorization and child.get("status") not in {"planning", "in_progress"}:
90
+ raise TaskWorkflowError("TASK_DELEGATE_CHILD_TERMINAL", "child task is terminal")
91
+ if child_dir.name not in parent.get("children", []):
92
+ fail("child links or lifecycle are invalid")
93
+ guard = assert_task_mutation_allowed if require_authorization else assert_task_safety_allowed
94
+ guard(get_repo_root(), parent_dir, parent)
95
+ guard(get_repo_root(), child_dir, child)
96
+ if require_authorization and (parent.get("status") != "in_progress" or not implementation_start_ready(parent, parent_dir)):
97
+ raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "current parent implementation authorization required")
98
+ return child, parent, _state(meta), parent_dir
99
+
100
+
101
+ def file_ref(task_dir: Path, ref: str | None) -> Path:
102
+ if not isinstance(ref, str) or not ref or Path(ref).is_absolute():
103
+ fail("metadata reference must be a nonempty relative path")
104
+ path = task_dir / ref
105
+ try:
106
+ path.resolve(strict=True).relative_to(task_dir.resolve())
107
+ except (ValueError, OSError):
108
+ fail("metadata reference must stay in the child task")
109
+ if path.resolve() != path.absolute() or not path.is_file() or path.stat().st_size > MAX_BYTES:
110
+ fail("metadata reference must be a bounded regular file")
111
+ return path
112
+
113
+
114
+ def freeze(root: Path, child_dir: Path, target: Path, branch: str | None, integration: str, settings_ref: str, requirements_ref: str, base_commit: str | None = None, *, target_mode: str | None = None) -> dict:
115
+ child, parent, state, _ = task_inputs(child_dir)
116
+ target_identity = identity(target)
117
+ settings_path, requirements_path = file_ref(child_dir, settings_ref), file_ref(child_dir, requirements_ref)
118
+ settings, requirements = read(settings_path), read(requirements_path)
119
+ if settings.get("version") != 1 or settings.get("provider") != "codex" or settings.get("mode") != "full-access" or not settings.get("model") or not settings.get("effort"):
120
+ fail("settings v1 require explicit codex/model/effort/full-access; resolve defaults through capability first")
121
+ if set(settings) - {"version", "provider", "model", "effort", "mode", "daemon_home", "sandbox", "approval", "reviewer", "context"}:
122
+ fail("unknown settings field")
123
+ if any(settings.get(k, "native_default") != "native_default" for k in ["sandbox", "approval", "reviewer", "context"]):
124
+ fail("bottom-level permissions and context must retain native defaults")
125
+ fields = {"version", "required_rules", "required_skills", "required_tools", "checks", "resources", "allowed_paths", "forbidden_paths", "setup_ref", "teamwork_permission"}
126
+ if requirements.get("version") != 1 or set(requirements) - fields or not isinstance(requirements.get("allowed_paths"), list) or not requirements["allowed_paths"]:
127
+ fail("requirements v1 and nonempty allowed_paths required")
128
+ for key in fields - {"version", "setup_ref", "teamwork_permission"}:
129
+ if key in requirements and (not isinstance(requirements[key], list) or any(not isinstance(item, str) or not item or "\0" in item for item in requirements[key])):
130
+ fail(f"requirements {key} must contain nonempty strings")
131
+ if requirements.get("teamwork_permission", "none") not in {"none", "read_only"}:
132
+ fail("Teamwork may only be absent or read_only")
133
+ if "setup_ref" in requirements:
134
+ file_ref(child_dir, requirements["setup_ref"])
135
+ if not isinstance(branch, str) or not branch:
136
+ fail("child execution branch must be set through the native task interface")
137
+ for ref in [settings_ref, requirements_ref, "prd.md"]:
138
+ file_ref(child_dir, ref)
139
+ git(target, "check-ref-format", "--branch", branch)
140
+ git(target, "check-ref-format", "--branch", integration)
141
+ if target_mode not in {None, "worktree", "directory"}:
142
+ fail("target mode must be worktree or directory")
143
+ if branch == integration and target_mode != "directory":
144
+ fail("execution branch must differ from integration branch")
145
+ integration_ref = integration if integration.startswith("refs/heads/") else f"refs/heads/{integration}"
146
+ execution_ref = branch if branch.startswith("refs/heads/") else f"refs/heads/{branch}"
147
+ base = base_commit or git(target, "rev-parse", "--verify", "--end-of-options",
148
+ "HEAD^{commit}" if target_mode == "directory" else f"{integration_ref}^{{commit}}")
149
+ git(target, "rev-parse", "--verify", "--end-of-options", f"{integration_ref}^{{commit}}")
150
+ if target_mode == "directory":
151
+ if git(target, "symbolic-ref", "HEAD") != execution_ref:
152
+ fail("directory target must already be on the approved execution branch; never switch it")
153
+ else:
154
+ git(target, "merge-base", "--is-ancestor", base, integration_ref)
155
+ role = file_ref(root, ".trellis/agents/delegated-worktree-primary-agent.md")
156
+ node_method = file_ref(root, ".trellis/agents/worktree-delegation-node.md")
157
+ authorization = state["implementation_authorization"]
158
+ binding = {"format_version": 2, "parent_task_id": parent["id"], "child_task_id": child["id"], "parent_route_revision": state["task_route_revision"], "parent_contract_revision": authorization["contract_revision"], "approval_ref": authorization["approval_ref"], "target_locator": str(target), "integration_branch": integration, "execution_branch": branch, "base_commit": base, "contract_sha256": digest(file_ref(child_dir, "prd.md").read_bytes()), "role_sha256": digest(role.read_bytes()), "node_method_sha256": digest(node_method.read_bytes()), "setup_sha256": digest(file_ref(child_dir, requirements["setup_ref"]).read_bytes()) if requirements.get("setup_ref") else None, "settings_sha256": digest(settings_path.read_bytes()), "requirements_sha256": digest(requirements_path.read_bytes()), "settings_ref": settings_ref, "requirements_ref": requirements_ref}
159
+ if target_mode:
160
+ binding.update({"format_version": 3, "target_mode": target_mode,
161
+ "execution_ref": execution_ref, "integration_ref": integration_ref})
162
+ target_identity["git_dir"] = git(target, "rev-parse", "--absolute-git-dir")
163
+ binding["binding_revision"] = digest(binding)
164
+ return {"binding": binding, "target_identity": target_identity, "settings": settings, "requirements": requirements}
165
+
166
+
167
+ def attach_package(child_dir: Path, frozen: dict, package_ref: str, package_id: str | None = None) -> dict:
168
+ """The package file is part of the parent's accepted artifact, not new authority."""
169
+ _, _, state, parent_dir = task_inputs(child_dir)
170
+ accepted = state["phases"].get("solution_design_and_convergence", {})
171
+ refs = accepted.get("artifact_refs", [])
172
+ # An omitted design can bind its package attachment in the accepted requirements.
173
+ if not refs:
174
+ requirements_phase = state["phases"].get("goal_exploration_and_requirements", {})
175
+ refs = requirements_phase.get("artifact_refs", []) if requirements_phase.get("status") == "accepted" else []
176
+ if package_ref not in refs:
177
+ fail("package attachment must be included in the accepted parent contract artifact")
178
+ attachment = file_ref(parent_dir, package_ref)
179
+ manifest = read(attachment)
180
+ if (manifest.get("version") != 1 or set(manifest) - {"version", "packages", "max_active"}
181
+ or not isinstance(manifest.get("packages"), list) or not manifest["packages"]):
182
+ fail("approved package attachment v1 requires a nonempty packages list")
183
+ maximum = manifest.get("max_active")
184
+ if maximum is not None and (type(maximum) is not int or maximum < 1):
185
+ fail("max_active must be a positive integer")
186
+ packages = {}
187
+ required = {"id", "child_task_id", "target_mode", "target_repo", "execution_branch",
188
+ "integration_branch", "contract_sha256", "requirements_sha256", "dependencies"}
189
+ for item in manifest["packages"]:
190
+ if (not isinstance(item, dict) or not required.issubset(item)
191
+ or set(item) - required - {"exclusive_resources"}
192
+ or not isinstance(item["id"], str) or not SAFE_ID.fullmatch(item["id"])
193
+ or item["id"] in packages):
194
+ fail("package identity or fields are invalid/duplicated")
195
+ for key in required - {"dependencies"}:
196
+ if not isinstance(item[key], str) or not item[key]:
197
+ fail("package fields must be nonempty strings")
198
+ for key in ("dependencies", "exclusive_resources"):
199
+ values = item.get(key, [])
200
+ if (not isinstance(values, list) or any(not isinstance(value, str) or not value for value in values)
201
+ or len(values) != len(set(values))):
202
+ fail(f"package {key} must contain unique nonempty strings")
203
+ if item["target_mode"] not in {"worktree", "directory"} or not Path(item["target_repo"]).is_absolute():
204
+ fail("package target mode/path is invalid")
205
+ if any(not re.fullmatch(r"[0-9a-f]{64}", item[key]) for key in ("contract_sha256", "requirements_sha256")):
206
+ fail("package revisions must identify exact approved bytes")
207
+ packages[item["id"]] = item
208
+ visited, visiting = set(), set()
209
+
210
+ def visit(key):
211
+ if key not in packages or key in visiting:
212
+ fail("package dependencies contain an unknown identity or cycle")
213
+ if key in visited:
214
+ return
215
+ visiting.add(key)
216
+ for dependency in packages[key]["dependencies"]:
217
+ visit(dependency)
218
+ visiting.remove(key)
219
+ visited.add(key)
220
+
221
+ for key in packages:
222
+ visit(key)
223
+ binding = frozen["binding"]
224
+ matches = [item for item in packages.values()
225
+ if item["child_task_id"] == binding["child_task_id"]
226
+ and (package_id is None or item["id"] == package_id)]
227
+ if len(matches) != 1:
228
+ fail("approved child package must match exactly; select --package-id if ambiguous")
229
+ item = matches[0]
230
+ expected = {"target_repo": binding["target_locator"], **{key: binding[key] for key in (
231
+ "target_mode", "execution_branch", "integration_branch", "contract_sha256", "requirements_sha256")}}
232
+ if any(item[key] != value for key, value in expected.items()):
233
+ fail("approved package target, branch or child revisions do not match")
234
+ binding.update({"package_ref": package_ref, "package_id": item["id"],
235
+ "package_sha256": digest(attachment.read_bytes())})
236
+ binding["binding_revision"] = digest({key: value for key, value in binding.items() if key != "binding_revision"})
237
+ frozen["package"] = item
238
+ frozen["package_manifest"] = manifest
239
+ return frozen
240
+
241
+
242
+ def package_admission(root: Path, child_dir: Path, record: dict, path: Path, *, allocate=False):
243
+ _, _, state, _ = task_inputs(child_dir)
244
+ admission = state.get("route_dependency_admission") or {}
245
+ if (admission.get("admission_state") != "ready"
246
+ or admission.get("task_route_revision") != state["task_route_revision"]
247
+ or not admission.get("evidence_refs")
248
+ or not {"pennix-lifecycle", "paseo", "git"}.issubset(admission.get("dependencies", []))):
249
+ fail("current evidenced Lifecycle/Paseo/Git admission is required")
250
+ if record["binding"].get("format_version") != 3:
251
+ return
252
+ siblings = [read(other) for other in path.parent.parent.glob("*/record.json") if other != path]
253
+ dependencies = []
254
+ for package_id in record["package"]["dependencies"]:
255
+ matches = [item for item in siblings if item.get("binding", {}).get("parent_contract_revision")
256
+ == record["binding"]["parent_contract_revision"]
257
+ and item.get("binding", {}).get("parent_task_id") == record["binding"]["parent_task_id"]
258
+ and item.get("binding", {}).get("package_id") == package_id
259
+ and item.get("status") == "retired"
260
+ and item.get("closure_evidence", {}).get("disposition") == "integrated"
261
+ and item.get("owner_acceptance")]
262
+ if len(matches) != 1:
263
+ fail("business dependency has no exact owner-accepted delivery")
264
+ if matches[0].get("target_identity", {}).get("common_dir") == record["target_identity"]["common_dir"]:
265
+ dependencies.append(matches[0]["owner_acceptance"])
266
+ record["dependency_heads"] = [item["head_commit"] for item in dependencies]
267
+ record["dependency_commits"] = sorted({commit for item in dependencies for commit in item["source_commits"]})
268
+ if allocate:
269
+ active = [item for item in siblings if item.get("status") not in {"bound", "retired"}]
270
+ maximum = record["package_manifest"].get("max_active")
271
+ if maximum and sum(item.get("binding", {}).get("parent_task_id") == record["binding"]["parent_task_id"]
272
+ for item in active) >= maximum:
273
+ fail("approved package capacity is occupied")
274
+ exclusive = set(record["package"].get("exclusive_resources", []))
275
+ if any(exclusive.intersection(item.get("package", {}).get("exclusive_resources", [])) for item in active):
276
+ fail("an explicitly exclusive resource is occupied")
277
+
278
+
279
+ def checkout_claim(record: dict, path: Path, *, release=False):
280
+ """The actual git-dir provides exclusion even between different controller roots."""
281
+ tree = Path(record.get("worktree_path") or record["binding"]["target_locator"])
282
+ directory = (Path(record["checkout_git_dir"]) if record.get("checkout_git_dir")
283
+ else Path(git(tree, "rev-parse", "--absolute-git-dir")))
284
+ if directory.resolve() != directory:
285
+ fail("checkout git-dir ownership path was redirected")
286
+ if release and not directory.exists() and record.get("native_closure"):
287
+ record["claim_missing_after_native_closure"] = True
288
+ return
289
+ if not release and not directory.is_dir():
290
+ fail("recorded checkout git-dir is unavailable; do not recreate it for a claim")
291
+ if not release:
292
+ record["checkout_git_dir"] = str(directory)
293
+ claim = directory / "trellis-delegation-owner.json"
294
+ from .task_continuity import _record_lock
295
+ owner = {key: record[key] for key in ("control_project_id", "attempt_id")}
296
+ owner.update({"record_ref": str(path), "binding_revision": record["binding"]["binding_revision"]})
297
+ with _record_lock(claim):
298
+ if claim.exists():
299
+ if read(claim) != owner:
300
+ fail("another controller owns this checkout; death/idle does not release ownership")
301
+ if release:
302
+ claim.unlink()
303
+ elif release:
304
+ fail("checkout ownership claim is missing; preserve resources")
305
+ else:
306
+ save(claim, owner)
307
+
308
+
309
+ def reuse_source(root: Path, task_ref: str, record: dict) -> tuple[dict, Path]:
310
+ from .task_workflow import _task_dir, _assert_delegated_record_closed
311
+ previous_dir = _task_dir(task_ref)
312
+ previous, previous_path = current(root, previous_dir, require_authorization=False)
313
+ _assert_delegated_record_closed(previous_dir.name, previous)
314
+ binding = previous["binding"]
315
+ if (binding.get("format_version") != 3 or previous.get("quarantined") or previous.get("reused_by")
316
+ or not previous.get("owner_acceptance")
317
+ or any(item.get("delivery") != "consumed" for item in previous.get("inputs", []))
318
+ or previous.get("settings") != record["settings"]
319
+ or binding.get("role_sha256") != record["binding"]["role_sha256"]
320
+ or binding.get("node_method_sha256") != record["binding"]["node_method_sha256"]
321
+ or previous.get("worktree_path") != record["binding"]["target_locator"]
322
+ or binding.get("execution_branch") != record["binding"]["execution_branch"]):
323
+ fail("reuse requires a normally accepted, closed, same-checkout agent with identical runtime/role configuration")
324
+ locator = root / ".trellis/.runtime/delegation-agents" / previous["agent_id"] / "context.json"
325
+ expected = {"version": 1, "kind": "delegation_agent_locator", "agent_id": previous["agent_id"],
326
+ "context_ref": str(previous_path.with_name("context.json"))}
327
+ if read(locator) != expected:
328
+ fail("prior agent has no exact stable context locator; do not change its launch environment")
329
+ return previous, previous_path
330
+
331
+
332
+ def current(root: Path, child_dir: Path, *, require_authorization: bool = True) -> tuple[dict, Path]:
333
+ path = runtime_path(root, child_dir.name)
334
+ record = read(path)
335
+ b = record["binding"]
336
+ if not require_authorization:
337
+ child, parent, _, _ = task_inputs(child_dir, require_authorization=False)
338
+ if record.get("control_project_id") != digest(str(root).encode()) or b.get("parent_task_id") != parent["id"] or b.get("child_task_id") != child["id"] or b.get("binding_revision") != digest({k: v for k, v in b.items() if k != "binding_revision"}):
339
+ fail("existing controller/target binding identity does not match; preserve resources")
340
+ return record, path
341
+ if b.get("format_version") not in {2, 3}:
342
+ fail("incomplete legacy binding; inspect/interrupt and retain the old attempt before rebinding")
343
+ frozen = freeze(root, child_dir, Path(b["target_locator"]), b["execution_branch"], b["integration_branch"], b["settings_ref"], b["requirements_ref"], b["base_commit"], target_mode=b.get("target_mode"))
344
+ if b.get("package_ref"):
345
+ attach_package(child_dir, frozen, b["package_ref"], b["package_id"])
346
+ if frozen != {k: record[k] for k in frozen}:
347
+ fail("frozen input or target identity changed; preserve current attempt and rebind only after closure")
348
+ return record, path
349
+
350
+
351
+ def assert_worktree(record: dict):
352
+ tree = Path(record["worktree_path"])
353
+ actual = identity(tree)
354
+ binding = record["binding"]
355
+ if actual["common_dir"] != record["target_identity"]["common_dir"] or git(tree, "symbolic-ref", "HEAD") != binding.get("execution_ref", f"refs/heads/{binding['execution_branch']}"):
356
+ fail("native worktree identity does not match current binding")
357
+ if binding.get("target_mode") == "directory" and str(tree.resolve()) != binding["target_locator"]:
358
+ fail("directory workspace must reuse the exact bound checkout")
359
+ if binding.get("target_mode") == "directory" and git(tree, "rev-parse", "--absolute-git-dir") != record["target_identity"]["git_dir"]:
360
+ fail("directory git-dir identity changed")
361
+ git(tree, "merge-base", "--is-ancestor", record["binding"]["base_commit"], "HEAD")
362
+ return tree
363
+
364
+
365
+ def source_clean(record: dict, path: Path | None = None):
366
+ tree = Path(record.get("worktree_path") or record["binding"]["target_locator"])
367
+ if git_paths(tree, "diff", "--name-only") or git_paths(tree, "diff", "--name-only", "--cached"):
368
+ fail("source worktree has unpreserved changes")
369
+ known = [record]
370
+ if path:
371
+ for other in path.parent.parent.glob("*/*.json"):
372
+ if other == path:
373
+ continue
374
+ historical = read(other)
375
+ if (historical.get("status") == "retired"
376
+ and historical.get("worktree_path") == str(tree)
377
+ and historical.get("closure_evidence")):
378
+ known.append(historical)
379
+ reports = {}
380
+ for owner in known:
381
+ attempt = owner.get("attempt_id")
382
+ if not attempt:
383
+ continue
384
+ inputs = owner.get("inputs", []) if owner["binding"].get("format_version") == 3 else [None]
385
+ for item in inputs:
386
+ directory = Path(".trellis-delegation") / attempt
387
+ if item:
388
+ directory /= item["id"]
389
+ for kind in ("ready", "result", "blocked"):
390
+ reports[(directory / f"{kind}.json").as_posix()] = (owner, item, kind)
391
+ for name in git_paths(tree, "ls-files", "--others", "--exclude-standard"):
392
+ if name not in reports:
393
+ fail("source worktree has unpreserved untracked files")
394
+ owner, item, kind = reports[name]
395
+ report_path = tree / name
396
+ if report_path.resolve() != report_path.absolute():
397
+ fail("redirected candidate report")
398
+ value = read(report_path)
399
+ if (value.get("attempt_id") != owner["attempt_id"] or value.get("kind") != kind
400
+ or value.get("binding_revision") != owner["binding"]["binding_revision"]
401
+ or value.get("agent_id") != owner.get("agent_id")
402
+ or value.get("workspace_id") != owner.get("workspace_id")
403
+ or value.get("version") != (2 if item else 1)
404
+ or (item and (not isinstance(value.get("input_ids"), list) or item["id"] not in value["input_ids"]))):
405
+ fail("untracked report does not match an exactly mapped candidate")
406
+
407
+
408
+ def clean_result(record: dict, result: dict, path: Path | None = None):
409
+ tree = assert_worktree(record)
410
+ base, head = record["binding"]["base_commit"], result["head_commit"]
411
+ changed = git_paths(tree, "diff", "--name-only", base, head)
412
+ commits = git(tree, "rev-list", f"{base}..{head}").splitlines()
413
+ if set(changed) != set(result.get("changed_paths", [])) or set(commits) != set(result.get("source_commits", [])):
414
+ fail("result commits/paths do not match native Git")
415
+ import fnmatch
416
+ req = record["requirements"]
417
+ def allowed_path(name):
418
+ return (not name.startswith((".trellis-delegation/", ".trellis/tasks/", ".trellis/.runtime/"))
419
+ and any(fnmatch.fnmatchcase(name, pattern) for pattern in req["allowed_paths"])
420
+ and not any(fnmatch.fnmatchcase(name, pattern) for pattern in req.get("forbidden_paths", [])))
421
+
422
+ def inherited_path(name):
423
+ current = git(tree, "--literal-pathspecs", "ls-tree", "-z", head, "--", name, raw=True)
424
+ return any(current == git(tree, "--literal-pathspecs", "ls-tree", "-z", dependency, "--", name, raw=True)
425
+ for dependency in record.get("dependency_heads", []))
426
+
427
+ if any(not allowed_path(name) and not inherited_path(name) for name in changed):
428
+ fail("source changes exceed the authorized paths")
429
+ dependencies = set(record.get("dependency_commits", []))
430
+ for commit in commits:
431
+ if commit in dependencies:
432
+ continue
433
+ parents = git(tree, "rev-list", "--parents", "-n", "1", commit).split()[1:]
434
+ if len(parents) > 1:
435
+ # Approved parent history is checked separately; combined diffs retain merge resolutions.
436
+ paths = git_paths(tree, "diff-tree", "--cc", "--no-commit-id", "--name-only", "-r", commit)
437
+ else:
438
+ paths = git_paths(tree, "diff-tree", "--root", "--no-commit-id", "--name-only", "-r", commit)
439
+ if any(p.startswith((".trellis-delegation/", ".trellis/tasks/", ".trellis/.runtime/")) for p in paths):
440
+ fail("source history modifies protected controller/runtime facts")
441
+ if any(not allowed_path(name) for name in paths):
442
+ fail("source commit history exceeds the authorized paths")
443
+ source_clean(record, path)
444
+ if not isinstance(result.get("checks"), list) or not isinstance(result.get("remaining"), list):
445
+ fail("result checks/remaining required")
446
+ return changed