@ikon85/agent-workflow-kit 0.37.0 → 0.39.0

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.
Files changed (44) hide show
  1. package/.agents/skills/kit-update/SKILL.md +33 -1
  2. package/.agents/skills/orchestrate-wave/SKILL.md +5 -5
  3. package/.agents/skills/setup-workflow/SKILL.md +42 -4
  4. package/.agents/skills/setup-workflow/board-sync.md +6 -2
  5. package/.agents/skills/setup-workflow/workflow-advisories.md +34 -0
  6. package/.agents/skills/setup-workflow/worktree-lifecycle.md +47 -1
  7. package/.agents/skills/wrapup/SKILL.md +46 -0
  8. package/.claude/hooks/drift-guard.py +212 -21
  9. package/.claude/skills/kit-update/SKILL.md +33 -1
  10. package/.claude/skills/orchestrate-wave/SKILL.md +5 -5
  11. package/.claude/skills/setup-workflow/SKILL.md +42 -4
  12. package/.claude/skills/setup-workflow/board-sync.md +6 -2
  13. package/.claude/skills/setup-workflow/workflow-advisories.md +34 -0
  14. package/.claude/skills/setup-workflow/worktree-lifecycle.md +47 -1
  15. package/.claude/skills/wrapup/SKILL.md +46 -0
  16. package/README.md +73 -0
  17. package/agent-workflow-kit.package.json +49 -25
  18. package/docs/adr/0007-session-teardown-requires-provenance-bound-ownership.md +88 -0
  19. package/docs/agents/workflow-capabilities.json +11 -1
  20. package/package.json +1 -1
  21. package/scripts/board_bootstrap.py +367 -0
  22. package/scripts/kit-update-pr.mjs +20 -7
  23. package/scripts/kit-update-pr.test.mjs +29 -0
  24. package/scripts/profile_globs.py +347 -0
  25. package/scripts/test_board_bootstrap.py +348 -0
  26. package/scripts/test_drift_guard_diagnostics.py +295 -0
  27. package/scripts/test_orchestrate_wave_contract.py +9 -0
  28. package/scripts/test_profile_globs.py +280 -0
  29. package/scripts/test_skill_setup_workflow_seeds.py +87 -0
  30. package/scripts/test_worktree_wrapup_contract.py +1592 -3
  31. package/scripts/workflow-advisories/core.py +29 -4
  32. package/scripts/worktree-lifecycle/README.md +139 -0
  33. package/scripts/worktree-lifecycle/capabilities.json +9 -1
  34. package/scripts/worktree-lifecycle/cleanup.py +22 -51
  35. package/scripts/worktree-lifecycle/core.py +1206 -5
  36. package/scripts/worktree-lifecycle/profile.py +38 -3
  37. package/scripts/worktree-lifecycle/session.py +1857 -0
  38. package/scripts/worktree-lifecycle/setup.py +15 -0
  39. package/scripts/wrapup-land.py +461 -14
  40. package/src/cli.mjs +32 -1
  41. package/src/commands/update.mjs +30 -21
  42. package/src/consumer-migrations.json +19 -0
  43. package/src/lib/bundle.mjs +11 -0
  44. package/src/lib/consumerMigrations.mjs +161 -0
@@ -2,10 +2,16 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import importlib.util
6
+ import json
7
+ import os
5
8
  import re
6
- from fnmatch import fnmatchcase
7
- from dataclasses import dataclass
8
- from pathlib import Path
9
+ import stat
10
+ import sys
11
+ from contextlib import contextmanager
12
+ from dataclasses import dataclass, replace
13
+ from hashlib import sha256
14
+ from pathlib import Path, PurePosixPath
9
15
  from time import time
10
16
  from typing import Any, Callable
11
17
 
@@ -13,6 +19,7 @@ from profile import (
13
19
  LifecycleError,
14
20
  WorktreeProfile,
15
21
  load_profile,
22
+ load_profile_text,
16
23
  local_branch_exists,
17
24
  main_worktree,
18
25
  registered_worktrees,
@@ -21,6 +28,104 @@ from profile import (
21
28
 
22
29
  _BRANCH_CHANGE_RE = re.compile(r"\b(?:git\s+(?:checkout|switch)|gh\s+pr\s+(?:merge|checkout))\b")
23
30
  _BRANCH_CREATE_RE = re.compile(r"\bgit\s+(?:checkout|switch)\s+-[bc]\s+(\S+)")
31
+ ARTIFACT_BASELINE_FILE = "awkit-artifact-baseline-v1.json"
32
+ LANDING_ATTEMPT_FILE = "awkit-landing-attempt-v1.json"
33
+ PROFILE_GLOBS_MODULE = "_agent_workflow_kit_profile_globs"
34
+
35
+
36
+ def load_profile_globs():
37
+ """Load the one shared repository-relative glob dialect exactly once."""
38
+ module = sys.modules.get(PROFILE_GLOBS_MODULE)
39
+ if module is not None:
40
+ return module
41
+ path = Path(__file__).resolve().parents[1] / "profile_globs.py"
42
+ spec = importlib.util.spec_from_file_location(PROFILE_GLOBS_MODULE, path)
43
+ if spec is None or spec.loader is None:
44
+ raise ImportError(f"cannot load the shared profile glob dialect from {path}")
45
+ module = importlib.util.module_from_spec(spec)
46
+ sys.modules[PROFILE_GLOBS_MODULE] = module
47
+ spec.loader.exec_module(module)
48
+ return module
49
+
50
+
51
+ # Consumer profile globs are matched here exactly as Workflow Advisories
52
+ # matches its own: one dialect, so an advisory and a deletion decision can
53
+ # never disagree about which repository-relative paths a pattern selects.
54
+ path_glob_matches = load_profile_globs().path_glob_matches
55
+
56
+ # Archived receipts are named from a contract-version-neutral stem plus the
57
+ # archived receipt's own contractVersion, so a v2 receipt is never filed as v1.
58
+ LANDING_ATTEMPT_ARCHIVE_STEM = "awkit-landing-attempt"
59
+ LANDING_ATTEMPT_CONTRACT_VERSION = 2
60
+ LANDING_ATTEMPT_KEYS = (
61
+ "contractVersion", "worktree", "branch", "rootDevice",
62
+ "rootInode", "baselineDigest", "generatedFiles",
63
+ "generatedEvidence", "state", "authorizedEvidence",
64
+ "pushSucceeded",
65
+ )
66
+ ABANDON_ATTEMPT_FLAG = "--abandon-unfinished-attempt"
67
+
68
+
69
+ class BaselineBackfillDeferred(LifecycleError):
70
+ """A safe legacy baseline cannot be captured until consumer state changes."""
71
+
72
+
73
+ class LegacyLandingAttempt(LifecycleError):
74
+ """A coherent attempt journal predates the active contract and is not adoptable."""
75
+
76
+
77
+ def durable_atomic_json(
78
+ path: Path,
79
+ document: dict[str, Any],
80
+ *,
81
+ label: str,
82
+ mode: int = 0o666,
83
+ sort_keys: bool = False,
84
+ ) -> None:
85
+ """Atomically replace one JSON journal and durably publish its directory entry."""
86
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
87
+ try:
88
+ descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, mode)
89
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
90
+ json.dump(
91
+ document,
92
+ handle,
93
+ ensure_ascii=False,
94
+ indent=2,
95
+ sort_keys=sort_keys,
96
+ )
97
+ handle.write("\n")
98
+ handle.flush()
99
+ os.fsync(handle.fileno())
100
+ os.replace(temporary, path)
101
+ directory_descriptor = os.open(
102
+ path.parent,
103
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0),
104
+ )
105
+ try:
106
+ os.fsync(directory_descriptor)
107
+ finally:
108
+ os.close(directory_descriptor)
109
+ except OSError as error:
110
+ temporary.unlink(missing_ok=True)
111
+ raise LifecycleError(f"cannot {label}: {error}") from error
112
+
113
+
114
+ def durable_replace(source: Path, destination: Path, *, label: str) -> None:
115
+ """Rename one journal durably without inspecting or claiming its payload files."""
116
+ try:
117
+ os.replace(source, destination)
118
+ directory_descriptor = os.open(
119
+ destination.parent,
120
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0),
121
+ )
122
+ try:
123
+ os.fsync(directory_descriptor)
124
+ finally:
125
+ os.close(directory_descriptor)
126
+ except OSError as error:
127
+ raise LifecycleError(f"cannot {label}: {error}") from error
128
+
24
129
 
25
130
  @dataclass(frozen=True)
26
131
  class RepoFacts:
@@ -49,6 +154,7 @@ class CleanupAssessment:
49
154
  root_device: int
50
155
  root_inode: int
51
156
  scratch_files: tuple[str, ...] = ()
157
+ scratch_evidence: tuple[dict[str, Any], ...] = ()
52
158
 
53
159
  @property
54
160
  def removable(self) -> bool:
@@ -70,6 +176,706 @@ class CleanupFacts:
70
176
  root_inode: int
71
177
 
72
178
 
179
+ @dataclass(frozen=True)
180
+ class ArtifactBaseline:
181
+ worktree: Path
182
+ branch: str
183
+ root_device: int
184
+ root_inode: int
185
+ setup_head: str
186
+ initial_ignored_files: tuple[str, ...]
187
+ initial_untracked_files: tuple[str, ...]
188
+ digest: str
189
+
190
+
191
+ def ignored_file_inventory(worktree: Path) -> tuple[str, ...]:
192
+ result = run(
193
+ [
194
+ "git", "ls-files", "--others", "--ignored",
195
+ "--exclude-standard", "-z",
196
+ ],
197
+ cwd=worktree,
198
+ )
199
+ return tuple(sorted(path for path in result.stdout.split("\0") if path))
200
+
201
+
202
+ def untracked_file_inventory(worktree: Path) -> tuple[str, ...]:
203
+ ordinary = run(
204
+ ["git", "ls-files", "--others", "--exclude-standard", "-z"],
205
+ cwd=worktree,
206
+ ).stdout.split("\0")
207
+ return tuple(sorted(
208
+ set(path for path in ordinary if path).union(ignored_file_inventory(worktree))
209
+ ))
210
+
211
+
212
+ def artifact_baseline_path(worktree: Path) -> Path:
213
+ result = run(
214
+ ["git", "rev-parse", "--absolute-git-dir"],
215
+ cwd=worktree,
216
+ )
217
+ git_dir = Path(result.stdout.strip())
218
+ if not git_dir.is_absolute():
219
+ raise LifecycleError("artifact provenance baseline git dir is not absolute")
220
+ return git_dir / ARTIFACT_BASELINE_FILE
221
+
222
+
223
+ def landing_attempt_path(worktree: Path) -> Path:
224
+ """Return the one landing-attempt journal path beside the artifact baseline."""
225
+ return artifact_baseline_path(worktree).with_name(LANDING_ATTEMPT_FILE)
226
+
227
+
228
+ def landing_attempt_exists(path: Path) -> bool:
229
+ """Classify journal presence without following a symlink at that name."""
230
+ return os.path.lexists(path)
231
+
232
+
233
+ def require_regular_landing_attempt(path: Path) -> None:
234
+ """Refuse a journal name occupied by a symlink or any non-regular entry."""
235
+ if path.is_symlink() or not path.is_file():
236
+ raise LifecycleError("landing-attempt provenance is not a regular file")
237
+
238
+
239
+ def landing_attempt_keys(contract_version: Any) -> list[str]:
240
+ """Return the exact journal key set recorded by one contract version."""
241
+ keys = list(LANDING_ATTEMPT_KEYS)
242
+ if contract_version == LANDING_ATTEMPT_CONTRACT_VERSION:
243
+ keys.append("policyDigest")
244
+ return keys
245
+
246
+
247
+ def _baseline_payload(
248
+ *,
249
+ worktree: Path,
250
+ branch: str,
251
+ root_device: int,
252
+ root_inode: int,
253
+ setup_head: str,
254
+ initial_ignored_files: tuple[str, ...],
255
+ initial_untracked_files: tuple[str, ...],
256
+ ) -> dict[str, Any]:
257
+ return {
258
+ "contractVersion": 2,
259
+ "worktree": str(worktree),
260
+ "branch": branch,
261
+ "rootDevice": root_device,
262
+ "rootInode": root_inode,
263
+ "setupHead": setup_head,
264
+ "initialIgnoredFiles": list(initial_ignored_files),
265
+ "initialUntrackedFiles": list(initial_untracked_files),
266
+ }
267
+
268
+
269
+ def _baseline_digest(payload: dict[str, Any]) -> str:
270
+ encoded = json.dumps(
271
+ payload,
272
+ ensure_ascii=False,
273
+ separators=(",", ":"),
274
+ sort_keys=True,
275
+ ).encode("utf-8")
276
+ return sha256(encoded).hexdigest()
277
+
278
+
279
+ def landing_cleanup_policy_digest(profile: WorktreeProfile) -> str:
280
+ """Bind one attempt to the exact ordered policy that nominated its files."""
281
+ return _baseline_digest({
282
+ "scratchPatterns": list(profile.scratch_patterns),
283
+ "landingGeneratedArtifactPatterns": list(
284
+ profile.landing_generated_artifact_patterns
285
+ ),
286
+ })
287
+
288
+
289
+ def capture_artifact_baseline(
290
+ worktree: Path,
291
+ *,
292
+ reject_ignored_patterns: tuple[str, ...] = (),
293
+ ) -> ArtifactBaseline:
294
+ worktree = worktree.resolve()
295
+ metadata = worktree.stat()
296
+ branch = run(["git", "branch", "--show-current"], cwd=worktree).stdout.strip()
297
+ setup_head = run(["git", "rev-parse", "HEAD"], cwd=worktree).stdout.strip()
298
+ ignored = ignored_file_inventory(worktree)
299
+ untracked = untracked_file_inventory(worktree)
300
+ blocked = tuple(sorted(
301
+ path
302
+ for path in ignored
303
+ if any(path_glob_matches(path, pattern) for pattern in reject_ignored_patterns)
304
+ ))
305
+ if blocked:
306
+ raise BaselineBackfillDeferred(
307
+ "landing-start generated paths are consumer-owned and protected: "
308
+ + ", ".join(blocked)
309
+ )
310
+ payload = _baseline_payload(
311
+ worktree=worktree,
312
+ branch=branch,
313
+ root_device=metadata.st_dev,
314
+ root_inode=metadata.st_ino,
315
+ setup_head=setup_head,
316
+ initial_ignored_files=ignored,
317
+ initial_untracked_files=untracked,
318
+ )
319
+ digest = _baseline_digest(payload)
320
+ path = artifact_baseline_path(worktree)
321
+ durable_atomic_json(
322
+ path,
323
+ {**payload, "sha256": digest},
324
+ label="write artifact provenance baseline",
325
+ )
326
+ return ArtifactBaseline(
327
+ worktree,
328
+ branch,
329
+ metadata.st_dev,
330
+ metadata.st_ino,
331
+ setup_head,
332
+ ignored,
333
+ untracked,
334
+ digest,
335
+ )
336
+
337
+
338
+ def load_artifact_baseline(worktree: Path) -> ArtifactBaseline:
339
+ worktree = worktree.resolve()
340
+ path = artifact_baseline_path(worktree)
341
+ try:
342
+ if path.is_symlink() or not path.is_file():
343
+ raise LifecycleError("artifact provenance baseline is missing or not a regular file")
344
+ document = json.loads(path.read_text(encoding="utf-8"))
345
+ payload = {
346
+ key: document[key]
347
+ for key in (
348
+ "contractVersion",
349
+ "worktree",
350
+ "branch",
351
+ "rootDevice",
352
+ "rootInode",
353
+ "setupHead",
354
+ "initialIgnoredFiles",
355
+ "initialUntrackedFiles",
356
+ )
357
+ }
358
+ digest = document["sha256"]
359
+ except LifecycleError:
360
+ raise
361
+ except (OSError, json.JSONDecodeError, KeyError, TypeError) as error:
362
+ raise LifecycleError(f"artifact provenance baseline is incoherent: {error}") from error
363
+ ignored = payload["initialIgnoredFiles"]
364
+ untracked = payload["initialUntrackedFiles"]
365
+ if (
366
+ payload["contractVersion"] != 2
367
+ or not isinstance(payload["worktree"], str)
368
+ or not isinstance(payload["branch"], str)
369
+ or not payload["branch"]
370
+ or type(payload["rootDevice"]) is not int
371
+ or type(payload["rootInode"]) is not int
372
+ or not isinstance(payload["setupHead"], str)
373
+ or re.fullmatch(r"[0-9a-f]{40,64}", payload["setupHead"]) is None
374
+ or not isinstance(ignored, list)
375
+ or not all(
376
+ isinstance(path_value, str)
377
+ and path_value
378
+ and not PurePosixPath(path_value).is_absolute()
379
+ and ".." not in PurePosixPath(path_value).parts
380
+ for path_value in ignored
381
+ )
382
+ or ignored != sorted(set(ignored))
383
+ or not isinstance(untracked, list)
384
+ or not all(
385
+ isinstance(path_value, str)
386
+ and path_value
387
+ and not PurePosixPath(path_value).is_absolute()
388
+ and ".." not in PurePosixPath(path_value).parts
389
+ for path_value in untracked
390
+ )
391
+ or untracked != sorted(set(untracked))
392
+ or not set(ignored).issubset(untracked)
393
+ or not isinstance(digest, str)
394
+ or re.fullmatch(r"[0-9a-f]{64}", digest) is None
395
+ or digest != _baseline_digest(payload)
396
+ ):
397
+ raise LifecycleError("artifact provenance baseline is incoherent")
398
+ try:
399
+ metadata = worktree.stat()
400
+ branch = run(["git", "branch", "--show-current"], cwd=worktree).stdout.strip()
401
+ except (OSError, LifecycleError) as error:
402
+ raise LifecycleError(
403
+ f"artifact provenance baseline binding cannot be verified: {error}"
404
+ ) from error
405
+ if (
406
+ payload["worktree"] != str(worktree)
407
+ or payload["branch"] != branch
408
+ or (payload["rootDevice"], payload["rootInode"])
409
+ != (metadata.st_dev, metadata.st_ino)
410
+ ):
411
+ raise LifecycleError("artifact provenance baseline binding does not match worktree")
412
+ return ArtifactBaseline(
413
+ worktree,
414
+ branch,
415
+ metadata.st_dev,
416
+ metadata.st_ino,
417
+ payload["setupHead"],
418
+ tuple(ignored),
419
+ tuple(untracked),
420
+ digest,
421
+ )
422
+
423
+
424
+ def ensure_artifact_baseline(
425
+ worktree: Path,
426
+ *,
427
+ reject_ignored_patterns: tuple[str, ...] = (),
428
+ ) -> ArtifactBaseline:
429
+ """Load provenance or conservatively backfill one exact clean legacy worktree."""
430
+ path = artifact_baseline_path(worktree)
431
+ if os.path.lexists(path):
432
+ return load_artifact_baseline(worktree)
433
+ if landing_attempt_exists(landing_attempt_path(worktree)):
434
+ raise LifecycleError(
435
+ "artifact provenance baseline is missing while a landing attempt exists"
436
+ )
437
+ absolute = worktree.absolute()
438
+ try:
439
+ metadata = os.lstat(absolute)
440
+ except OSError as error:
441
+ raise LifecycleError(
442
+ f"legacy artifact baseline root cannot be inspected: {error}"
443
+ ) from error
444
+ if not stat.S_ISDIR(metadata.st_mode) or absolute != worktree.resolve():
445
+ raise LifecycleError("legacy artifact baseline root is not an exact nofollow directory")
446
+ main = main_worktree(worktree)
447
+ if worktree.resolve() not in registered_worktrees(main):
448
+ raise LifecycleError("legacy artifact baseline requires an exact registered worktree")
449
+ branch = run(["git", "branch", "--show-current"], cwd=worktree).stdout.strip()
450
+ if not branch:
451
+ raise LifecycleError("legacy artifact baseline requires an attached branch")
452
+ for command in (
453
+ ["git", "diff", "--quiet"],
454
+ ["git", "diff", "--cached", "--quiet"],
455
+ ):
456
+ if run(command, cwd=worktree, check=False).returncode != 0:
457
+ raise BaselineBackfillDeferred(
458
+ "legacy artifact baseline requires a clean tracked worktree and index"
459
+ )
460
+ return capture_artifact_baseline(
461
+ worktree,
462
+ reject_ignored_patterns=reject_ignored_patterns,
463
+ )
464
+
465
+
466
+ def verified_landing_scratch_files(
467
+ profile: WorktreeProfile,
468
+ worktree: Path,
469
+ *,
470
+ expected_baseline_digest: str | None = None,
471
+ landing_start_files: tuple[str, ...] = (),
472
+ ) -> tuple[str, ...]:
473
+ return tuple(
474
+ item["path"]
475
+ for item in verified_landing_scratch_evidence(
476
+ profile,
477
+ worktree,
478
+ expected_baseline_digest=expected_baseline_digest,
479
+ landing_start_files=landing_start_files,
480
+ )
481
+ )
482
+
483
+
484
+ def _classify_superseded_landing_attempt(
485
+ payload: dict[str, Any],
486
+ digest: Any,
487
+ baseline: ArtifactBaseline,
488
+ worktree: Path,
489
+ ) -> None:
490
+ """Separate a coherent pre-upgrade journal from genuinely corrupt evidence.
491
+
492
+ A journal written before the active contract can never be adopted, but it is
493
+ not damage: it has an exact, non-deleting route out. Only evidence that also
494
+ fails its own recorded contract is reported as corruption.
495
+ """
496
+ if (
497
+ payload["contractVersion"] != 1
498
+ or payload["worktree"] != str(worktree.resolve())
499
+ or payload["branch"] != baseline.branch
500
+ or (payload["rootDevice"], payload["rootInode"])
501
+ != (baseline.root_device, baseline.root_inode)
502
+ or payload["state"] not in {"started", "frozen"}
503
+ or digest != _baseline_digest(payload)
504
+ ):
505
+ raise LifecycleError("landing-attempt provenance is incoherent")
506
+ raise LegacyLandingAttempt(
507
+ "landing attempt was started under the superseded v1 journal contract "
508
+ "and cannot be adopted; archive it with "
509
+ f"`land {ABANDON_ATTEMPT_FLAG}` — that deletes and claims no file — "
510
+ "then rerun land"
511
+ )
512
+
513
+
514
+ def landing_start_artifact_inventory(
515
+ profile: WorktreeProfile,
516
+ worktree: Path,
517
+ ) -> dict[str, Any]:
518
+ """Persist/reuse the generated-path inventory preceding the landing build."""
519
+ baseline = ensure_artifact_baseline(
520
+ worktree,
521
+ reject_ignored_patterns=profile.landing_generated_artifact_patterns,
522
+ )
523
+ attempt_path = landing_attempt_path(worktree)
524
+ if landing_attempt_exists(attempt_path):
525
+ require_regular_landing_attempt(attempt_path)
526
+ try:
527
+ document = json.loads(attempt_path.read_text(encoding="utf-8"))
528
+ contract_version = document["contractVersion"]
529
+ payload = {
530
+ key: document[key]
531
+ for key in landing_attempt_keys(contract_version)
532
+ }
533
+ digest = document["sha256"]
534
+ except (OSError, json.JSONDecodeError, KeyError, TypeError) as error:
535
+ raise LifecycleError(
536
+ f"landing-attempt provenance is incoherent: {error}"
537
+ ) from error
538
+ if contract_version != LANDING_ATTEMPT_CONTRACT_VERSION:
539
+ _classify_superseded_landing_attempt(
540
+ payload, digest, baseline, worktree
541
+ )
542
+ if payload["policyDigest"] != landing_cleanup_policy_digest(profile):
543
+ raise LifecycleError(
544
+ "landing cleanup policy changed after attempt start; "
545
+ "abandon the unfinished attempt before retrying"
546
+ )
547
+ if (
548
+ payload["contractVersion"] != LANDING_ATTEMPT_CONTRACT_VERSION
549
+ or payload["worktree"] != str(worktree.resolve())
550
+ or payload["branch"] != baseline.branch
551
+ or (payload["rootDevice"], payload["rootInode"])
552
+ != (baseline.root_device, baseline.root_inode)
553
+ or payload["baselineDigest"] != baseline.digest
554
+ or not isinstance(payload["generatedFiles"], list)
555
+ or payload["generatedFiles"] != sorted(set(payload["generatedFiles"]))
556
+ or not isinstance(payload["generatedEvidence"], list)
557
+ or payload["state"] not in {"started", "frozen"}
558
+ or not isinstance(payload["authorizedEvidence"], list)
559
+ or type(payload["pushSucceeded"]) is not bool
560
+ or digest != _baseline_digest(payload)
561
+ ):
562
+ raise LifecycleError("landing-attempt provenance is incoherent")
563
+ return {
564
+ "baselineDigest": payload["baselineDigest"],
565
+ "generatedFiles": payload["generatedFiles"],
566
+ "generatedEvidence": payload["generatedEvidence"],
567
+ "state": payload["state"],
568
+ "authorizedEvidence": payload["authorizedEvidence"],
569
+ "pushSucceeded": payload["pushSucceeded"],
570
+ "policyDigest": payload["policyDigest"],
571
+ "newAttempt": False,
572
+ }
573
+ current = set(ignored_file_inventory(worktree))
574
+ generated = tuple(sorted(
575
+ path for path in current
576
+ if any(
577
+ path_glob_matches(path, pattern)
578
+ for pattern in profile.landing_generated_artifact_patterns
579
+ )
580
+ ))
581
+ if generated:
582
+ raise LifecycleError(
583
+ "landing-start generated paths are consumer-owned and protected: "
584
+ + ", ".join(generated)
585
+ )
586
+ result = {
587
+ "baselineDigest": baseline.digest,
588
+ "generatedFiles": list(generated),
589
+ "generatedEvidence": [],
590
+ "state": "started",
591
+ "authorizedEvidence": [],
592
+ "pushSucceeded": False,
593
+ "policyDigest": landing_cleanup_policy_digest(profile),
594
+ }
595
+ payload = {
596
+ "contractVersion": LANDING_ATTEMPT_CONTRACT_VERSION,
597
+ "worktree": str(worktree.resolve()),
598
+ "branch": baseline.branch,
599
+ "rootDevice": baseline.root_device,
600
+ "rootInode": baseline.root_inode,
601
+ **result,
602
+ }
603
+ digest = _baseline_digest(payload)
604
+ durable_atomic_json(
605
+ attempt_path,
606
+ {**payload, "sha256": digest},
607
+ label="persist landing-attempt provenance",
608
+ )
609
+ return {**result, "newAttempt": True}
610
+
611
+
612
+ def verified_landing_scratch_evidence(
613
+ profile: WorktreeProfile,
614
+ worktree: Path,
615
+ *,
616
+ expected_baseline_digest: str | None = None,
617
+ landing_start_files: tuple[str, ...] = (),
618
+ ) -> tuple[dict[str, Any], ...]:
619
+ """Return frozen regular-file identities for the authorized generator delta."""
620
+ baseline = load_artifact_baseline(worktree)
621
+ if (
622
+ expected_baseline_digest is not None
623
+ and baseline.digest != expected_baseline_digest
624
+ ):
625
+ raise LifecycleError("artifact provenance baseline changed during landing")
626
+ current = set(ignored_file_inventory(worktree))
627
+ initial = current.intersection(baseline.initial_ignored_files)
628
+ initial_generated = sorted(
629
+ path for path in initial
630
+ if any(
631
+ path_glob_matches(path, pattern)
632
+ for pattern in profile.landing_generated_artifact_patterns
633
+ )
634
+ )
635
+ if initial_generated:
636
+ raise LifecycleError(
637
+ "artifact provenance baseline protects initial generated paths: "
638
+ + ", ".join(initial_generated)
639
+ )
640
+ if landing_start_files:
641
+ raise LifecycleError(
642
+ "landing-start generated paths are consumer-owned and protected: "
643
+ + ", ".join(sorted(landing_start_files))
644
+ )
645
+ candidates = tuple(sorted(
646
+ path
647
+ for path in current.difference(baseline.initial_ignored_files)
648
+ if path not in landing_start_files
649
+ if any(
650
+ path_glob_matches(path, pattern)
651
+ for pattern in profile.landing_generated_artifact_patterns
652
+ )
653
+ ))
654
+ if not candidates:
655
+ return ()
656
+ with verified_worktree_root(
657
+ worktree,
658
+ baseline.root_device,
659
+ baseline.root_inode,
660
+ ) as descriptor:
661
+ return tuple(
662
+ contained_regular_identity(descriptor, relative)
663
+ for relative in candidates
664
+ )
665
+
666
+
667
+ def freeze_landing_artifact_evidence(
668
+ profile: WorktreeProfile,
669
+ worktree: Path,
670
+ *,
671
+ push_succeeded: bool,
672
+ ) -> tuple[dict[str, Any], ...]:
673
+ """Freeze or revalidate the exact output of one generator-capable push."""
674
+ attempt = landing_start_artifact_inventory(profile, worktree)
675
+ current = verified_landing_scratch_evidence(
676
+ profile,
677
+ worktree,
678
+ expected_baseline_digest=attempt["baselineDigest"],
679
+ landing_start_files=tuple(attempt["generatedFiles"]),
680
+ )
681
+ frozen = tuple(attempt["authorizedEvidence"])
682
+ if attempt["state"] == "frozen" and frozen != current:
683
+ raise LifecycleError(
684
+ "landing-generated evidence changed after it was frozen"
685
+ )
686
+ if attempt["state"] == "frozen":
687
+ return frozen
688
+ path = landing_attempt_path(worktree)
689
+ document = json.loads(path.read_text(encoding="utf-8"))
690
+ payload = {
691
+ key: document[key]
692
+ for key in (
693
+ "contractVersion", "worktree", "branch", "rootDevice",
694
+ "rootInode", "baselineDigest", "generatedFiles",
695
+ "generatedEvidence", "policyDigest",
696
+ )
697
+ }
698
+ payload.update({
699
+ "state": "frozen",
700
+ "authorizedEvidence": list(current),
701
+ "pushSucceeded": push_succeeded,
702
+ })
703
+ digest = _baseline_digest(payload)
704
+ durable_atomic_json(
705
+ path,
706
+ {**payload, "sha256": digest},
707
+ label="freeze landing-generated evidence",
708
+ )
709
+ return current
710
+
711
+
712
+ def reopen_frozen_landing_attempt(
713
+ profile: WorktreeProfile,
714
+ worktree: Path,
715
+ ) -> tuple[dict[str, Any], ...]:
716
+ """Validate a failed push boundary before permitting its generator to retry."""
717
+ frozen = freeze_landing_artifact_evidence(
718
+ profile, worktree, push_succeeded=False
719
+ )
720
+ path = landing_attempt_path(worktree)
721
+ document = json.loads(path.read_text(encoding="utf-8"))
722
+ payload = {
723
+ key: document[key]
724
+ for key in (
725
+ "contractVersion", "worktree", "branch", "rootDevice",
726
+ "rootInode", "baselineDigest", "generatedFiles",
727
+ "generatedEvidence", "policyDigest",
728
+ )
729
+ }
730
+ payload.update({
731
+ "state": "started",
732
+ "authorizedEvidence": [],
733
+ "pushSucceeded": False,
734
+ })
735
+ digest = _baseline_digest(payload)
736
+ durable_atomic_json(
737
+ path,
738
+ {**payload, "sha256": digest},
739
+ label="reopen validated landing attempt",
740
+ )
741
+ return frozen
742
+
743
+
744
+ def abandon_unfinished_landing_attempt(
745
+ worktree: Path,
746
+ ) -> Path:
747
+ """Archive an ambiguous started attempt without claiming or deleting files."""
748
+ path = landing_attempt_path(worktree)
749
+ if not landing_attempt_exists(path):
750
+ raise LifecycleError("no pre-existing unfinished landing attempt to abandon")
751
+ try:
752
+ require_regular_landing_attempt(path)
753
+ document = json.loads(path.read_text(encoding="utf-8"))
754
+ payload = {
755
+ key: document[key]
756
+ for key in landing_attempt_keys(document["contractVersion"])
757
+ }
758
+ digest = document["sha256"]
759
+ metadata = os.lstat(worktree)
760
+ branch = run(["git", "branch", "--show-current"], cwd=worktree).stdout.strip()
761
+ except LifecycleError:
762
+ raise
763
+ except (OSError, json.JSONDecodeError, KeyError, TypeError) as error:
764
+ raise LifecycleError(f"landing-attempt provenance is incoherent: {error}") from error
765
+ if (
766
+ payload["contractVersion"] not in {1, 2}
767
+ or payload["worktree"] != str(worktree.resolve())
768
+ or payload["branch"] != branch
769
+ or not stat.S_ISDIR(metadata.st_mode)
770
+ or (payload["rootDevice"], payload["rootInode"])
771
+ != (metadata.st_dev, metadata.st_ino)
772
+ or payload["state"] not in {"started", "frozen"}
773
+ or digest != _baseline_digest(payload)
774
+ ):
775
+ raise LifecycleError("landing-attempt provenance is incoherent")
776
+ archive = path.with_name(
777
+ f"{LANDING_ATTEMPT_ARCHIVE_STEM}.v{payload['contractVersion']}"
778
+ f".abandoned-{int(time() * 1_000_000)}.json"
779
+ )
780
+ durable_replace(path, archive, label="archive landing attempt")
781
+ return archive
782
+
783
+
784
+ def canonical_recovery_evidence(
785
+ canonical: WorktreeProfile,
786
+ worktree: Path,
787
+ ) -> tuple[dict[str, Any], ...]:
788
+ """Revalidate one frozen landing attempt against canonical policy alone.
789
+
790
+ Canonical cleanup-policy drift between attempt start and post-merge cleanup
791
+ strands an already-merged worktree, because the attempt is bound to the
792
+ policy that nominated it. This route re-derives deletion authority from the
793
+ merged canonical policy only. It never re-scans the worktree for new
794
+ candidates, so broader stale candidate evidence cannot enter; every frozen
795
+ identity must additionally still be named by canonical policy and still
796
+ match byte-for-byte on disk, so a narrowed canonical policy, a changed file,
797
+ and any pre-existing state stop the recovery instead of being deleted.
798
+ """
799
+ path = landing_attempt_path(worktree)
800
+ if not landing_attempt_exists(path):
801
+ raise LifecycleError(
802
+ "canonical cleanup recovery requires the landing attempt that froze "
803
+ "this teardown's evidence"
804
+ )
805
+ try:
806
+ require_regular_landing_attempt(path)
807
+ document = json.loads(path.read_text(encoding="utf-8"))
808
+ contract_version = document["contractVersion"]
809
+ payload = {
810
+ key: document[key]
811
+ for key in landing_attempt_keys(contract_version)
812
+ }
813
+ digest = document["sha256"]
814
+ metadata = os.lstat(worktree)
815
+ branch = run(["git", "branch", "--show-current"], cwd=worktree).stdout.strip()
816
+ except LifecycleError:
817
+ raise
818
+ except (OSError, json.JSONDecodeError, KeyError, TypeError) as error:
819
+ raise LifecycleError(f"landing-attempt provenance is incoherent: {error}") from error
820
+ if (
821
+ contract_version != LANDING_ATTEMPT_CONTRACT_VERSION
822
+ or payload["worktree"] != str(worktree.resolve())
823
+ or payload["branch"] != branch
824
+ or not stat.S_ISDIR(metadata.st_mode)
825
+ or (payload["rootDevice"], payload["rootInode"])
826
+ != (metadata.st_dev, metadata.st_ino)
827
+ or not isinstance(payload["generatedFiles"], list)
828
+ or not isinstance(payload["authorizedEvidence"], list)
829
+ or type(payload["pushSucceeded"]) is not bool
830
+ or digest != _baseline_digest(payload)
831
+ ):
832
+ raise LifecycleError("landing-attempt provenance is incoherent")
833
+ if payload["state"] != "frozen" or not payload["pushSucceeded"]:
834
+ raise LifecycleError(
835
+ "canonical cleanup recovery requires a frozen landing attempt from a "
836
+ f"completed push; archive an unfinished attempt with `{ABANDON_ATTEMPT_FLAG}`"
837
+ )
838
+ if payload["generatedFiles"]:
839
+ raise LifecycleError(
840
+ "landing-start generated paths are consumer-owned and protected: "
841
+ + ", ".join(payload["generatedFiles"])
842
+ )
843
+ baseline = load_artifact_baseline(worktree)
844
+ if payload["baselineDigest"] != baseline.digest:
845
+ raise LifecycleError("artifact provenance baseline changed during landing")
846
+ frozen = tuple(payload["authorizedEvidence"])
847
+ relatives: list[str] = []
848
+ for item in frozen:
849
+ relative = item.get("path") if isinstance(item, dict) else None
850
+ if not isinstance(relative, str) or relative in relatives:
851
+ raise LifecycleError("scratch evidence is incoherent")
852
+ relatives.append(relative)
853
+ outside = sorted(
854
+ relative for relative in relatives
855
+ if not any(
856
+ path_glob_matches(relative, pattern)
857
+ for pattern in canonical.landing_generated_artifact_patterns
858
+ )
859
+ )
860
+ if outside:
861
+ raise LifecycleError(
862
+ "landing-attempt evidence is outside canonical cleanup policy: "
863
+ + ", ".join(outside)
864
+ )
865
+ with verified_worktree_root(
866
+ worktree,
867
+ baseline.root_device,
868
+ baseline.root_inode,
869
+ ) as descriptor:
870
+ current = tuple(
871
+ contained_regular_identity(descriptor, relative)
872
+ for relative in relatives
873
+ )
874
+ if current != frozen:
875
+ raise LifecycleError("landing-generated evidence changed after it was frozen")
876
+ return current
877
+
878
+
73
879
  def collect_facts(cwd: Path) -> RepoFacts:
74
880
  root = Path(run(["git", "rev-parse", "--show-toplevel"], cwd=cwd).stdout.strip()).resolve()
75
881
  main = main_worktree(root)
@@ -142,8 +948,10 @@ def cleanup_assessment(
142
948
  target: Path,
143
949
  merge_target: str | None = None,
144
950
  pr_state: str = "none",
951
+ verified_scratch_files: tuple[str, ...] = (),
952
+ verified_scratch_evidence: tuple[dict[str, Any], ...] = (),
145
953
  ) -> CleanupAssessment:
146
- return classify_cleanup(
954
+ assessment = classify_cleanup(
147
955
  profile,
148
956
  collect_cleanup_facts(
149
957
  main,
@@ -151,7 +959,20 @@ def cleanup_assessment(
151
959
  merge_target=merge_target,
152
960
  pr_state=pr_state,
153
961
  ),
962
+ verified_scratch_files=verified_scratch_files,
154
963
  )
964
+ try:
965
+ return bind_cleanup_scratch_evidence(
966
+ profile,
967
+ assessment,
968
+ verified_scratch_evidence,
969
+ require_generator_evidence=True,
970
+ )
971
+ except LifecycleError as error:
972
+ return replace(
973
+ assessment,
974
+ reasons=assessment.reasons + (f"scratch evidence stop: {error}",),
975
+ )
155
976
 
156
977
 
157
978
  def collect_cleanup_facts(
@@ -225,6 +1046,8 @@ def collect_cleanup_facts(
225
1046
  def classify_cleanup(
226
1047
  profile: WorktreeProfile,
227
1048
  facts: CleanupFacts,
1049
+ *,
1050
+ verified_scratch_files: tuple[str, ...] = (),
228
1051
  ) -> CleanupAssessment:
229
1052
  reasons = []
230
1053
  if not facts.registered:
@@ -233,9 +1056,19 @@ def classify_cleanup(
233
1056
  reasons.append("detached or unreadable branch")
234
1057
  if facts.branch in profile.protected_branches or facts.is_main:
235
1058
  reasons.append(f"protected worktree branch: {facts.branch or '<unknown>'}")
1059
+ verified = set(verified_scratch_files)
1060
+ missing_verified = sorted(verified.difference(facts.untracked_files))
1061
+ if missing_verified:
1062
+ reasons.append(
1063
+ "verified scratch evidence no longer matches inventory: "
1064
+ + ", ".join(missing_verified)
1065
+ )
236
1066
  scratch = sorted(
237
1067
  path for path in facts.untracked_files
238
- if any(fnmatchcase(path, pattern) for pattern in profile.scratch_patterns)
1068
+ if (
1069
+ path in verified
1070
+ or any(path_glob_matches(path, pattern) for pattern in profile.scratch_patterns)
1071
+ )
239
1072
  )
240
1073
  non_scratch = sorted(set(facts.untracked_files).difference(scratch))
241
1074
  if facts.tracked_files:
@@ -263,6 +1096,374 @@ def classify_cleanup(
263
1096
  )
264
1097
 
265
1098
 
1099
+ @contextmanager
1100
+ def verified_worktree_root(root: Path, expected_device: int, expected_inode: int):
1101
+ """Open the assessed worktree root without following a replacement symlink."""
1102
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
1103
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1104
+ descriptor = None
1105
+ try:
1106
+ descriptor = os.open(root, directory_flags | no_follow)
1107
+ metadata = os.fstat(descriptor)
1108
+ if (metadata.st_dev, metadata.st_ino) != (expected_device, expected_inode):
1109
+ raise LifecycleError("worktree root changed before removal")
1110
+ yield descriptor
1111
+ except OSError as error:
1112
+ raise LifecycleError("worktree root changed before removal") from error
1113
+ finally:
1114
+ if descriptor is not None:
1115
+ os.close(descriptor)
1116
+
1117
+
1118
+ def remove_contained_regular(
1119
+ root_descriptor: int,
1120
+ relative: str,
1121
+ expected_identity: dict[str, Any] | None = None,
1122
+ ) -> None:
1123
+ """Delete one exact assessed regular file without following path symlinks."""
1124
+ path = PurePosixPath(relative)
1125
+ if path.is_absolute() or not path.parts or any(
1126
+ part in {"", ".", ".."} for part in path.parts
1127
+ ):
1128
+ raise LifecycleError(f"unsafe scratch path: {relative}")
1129
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
1130
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1131
+ descriptors = []
1132
+ try:
1133
+ current = root_descriptor
1134
+ for component in path.parts[:-1]:
1135
+ current = os.open(
1136
+ component,
1137
+ directory_flags | no_follow,
1138
+ dir_fd=current,
1139
+ )
1140
+ descriptors.append(current)
1141
+ initial_metadata = os.stat(
1142
+ path.name,
1143
+ dir_fd=current,
1144
+ follow_symlinks=False,
1145
+ )
1146
+ if not stat.S_ISREG(initial_metadata.st_mode):
1147
+ raise LifecycleError(f"scratch path is not a regular file: {relative}")
1148
+ file_descriptor = os.open(
1149
+ path.name,
1150
+ os.O_RDONLY | no_follow,
1151
+ dir_fd=current,
1152
+ )
1153
+ try:
1154
+ metadata = os.fstat(file_descriptor)
1155
+ digest = sha256()
1156
+ while chunk := os.read(file_descriptor, 128 * 1024):
1157
+ digest.update(chunk)
1158
+ finally:
1159
+ os.close(file_descriptor)
1160
+ if (
1161
+ not stat.S_ISREG(metadata.st_mode)
1162
+ or (metadata.st_dev, metadata.st_ino)
1163
+ != (initial_metadata.st_dev, initial_metadata.st_ino)
1164
+ ):
1165
+ raise LifecycleError(f"scratch path changed before removal: {relative}")
1166
+ identity = {
1167
+ "path": relative,
1168
+ "device": metadata.st_dev,
1169
+ "inode": metadata.st_ino,
1170
+ "size": metadata.st_size,
1171
+ "sha256": digest.hexdigest(),
1172
+ }
1173
+ if expected_identity is not None and identity != expected_identity:
1174
+ raise LifecycleError(f"scratch path identity changed: {relative}")
1175
+ latest = os.stat(path.name, dir_fd=current, follow_symlinks=False)
1176
+ if (latest.st_dev, latest.st_ino) != (metadata.st_dev, metadata.st_ino):
1177
+ raise LifecycleError(f"scratch path changed before removal: {relative}")
1178
+ os.unlink(path.name, dir_fd=current)
1179
+ except OSError as error:
1180
+ raise LifecycleError(f"scratch path changed before removal: {relative}") from error
1181
+ finally:
1182
+ for descriptor in reversed(descriptors):
1183
+ os.close(descriptor)
1184
+
1185
+
1186
+ def remove_authorized_scratch(
1187
+ profile: WorktreeProfile,
1188
+ root_descriptor: int,
1189
+ scratch_files: tuple[str, ...] | list[str],
1190
+ verified_evidence: tuple[dict[str, Any], ...] | list[dict[str, Any]] = (),
1191
+ ) -> None:
1192
+ """Remove profile scratch or exact generator evidence without weakening overlaps."""
1193
+ evidence_by_path: dict[str, dict[str, Any]] = {}
1194
+ for item in verified_evidence:
1195
+ relative = item.get("path")
1196
+ if not isinstance(relative, str) or relative in evidence_by_path:
1197
+ raise LifecycleError("scratch evidence is incoherent")
1198
+ evidence_by_path[relative] = item
1199
+ unexpected = sorted(set(evidence_by_path).difference(scratch_files))
1200
+ if unexpected:
1201
+ raise LifecycleError(
1202
+ "scratch evidence is outside the assessed inventory: "
1203
+ + ", ".join(unexpected)
1204
+ )
1205
+ for relative in scratch_files:
1206
+ generated = any(
1207
+ path_glob_matches(relative, pattern)
1208
+ for pattern in profile.landing_generated_artifact_patterns
1209
+ )
1210
+ profile_authorized = any(
1211
+ path_glob_matches(relative, pattern)
1212
+ for pattern in profile.scratch_patterns
1213
+ )
1214
+ expected = evidence_by_path.get(relative)
1215
+ if not generated and not profile_authorized:
1216
+ raise LifecycleError(
1217
+ f"canonical cleanup policy does not authorize scratch: {relative}"
1218
+ )
1219
+ if generated and expected is None:
1220
+ raise LifecycleError(
1221
+ f"landing-generated scratch evidence is missing: {relative}"
1222
+ )
1223
+ if profile_authorized and expected is None:
1224
+ raise LifecycleError(f"profile scratch evidence is missing: {relative}")
1225
+ if not profile_authorized and expected is None:
1226
+ raise LifecycleError(f"verified scratch evidence is missing: {relative}")
1227
+ for relative in scratch_files:
1228
+ expected = evidence_by_path[relative]
1229
+ remove_contained_regular(
1230
+ root_descriptor,
1231
+ relative,
1232
+ expected_identity=expected,
1233
+ )
1234
+
1235
+
1236
+ def bind_cleanup_scratch_evidence(
1237
+ profile: WorktreeProfile,
1238
+ assessment: CleanupAssessment,
1239
+ verified_generator_evidence: tuple[dict[str, Any], ...] | list[dict[str, Any]] = (),
1240
+ *,
1241
+ require_generator_evidence: bool = False,
1242
+ ) -> CleanupAssessment:
1243
+ """Freeze identity for every assessed scratch path at its authority boundary."""
1244
+ evidence_by_path = {
1245
+ item.get("path"): item
1246
+ for item in verified_generator_evidence
1247
+ if isinstance(item, dict) and isinstance(item.get("path"), str)
1248
+ }
1249
+ if len(evidence_by_path) != len(verified_generator_evidence):
1250
+ raise LifecycleError("scratch evidence is incoherent")
1251
+ unauthorized_evidence = sorted(
1252
+ relative
1253
+ for relative in evidence_by_path
1254
+ if not any(
1255
+ path_glob_matches(relative, pattern)
1256
+ for pattern in profile.landing_generated_artifact_patterns
1257
+ )
1258
+ )
1259
+ if unauthorized_evidence:
1260
+ raise LifecycleError(
1261
+ "generator evidence is outside canonical landing policy: "
1262
+ + ", ".join(unauthorized_evidence)
1263
+ )
1264
+ scratch = set(assessment.scratch_files)
1265
+ if not set(evidence_by_path).issubset(scratch):
1266
+ raise LifecycleError("scratch evidence is outside the assessed inventory")
1267
+ profile_only = [
1268
+ relative
1269
+ for relative in assessment.scratch_files
1270
+ if not any(
1271
+ path_glob_matches(relative, pattern)
1272
+ for pattern in profile.landing_generated_artifact_patterns
1273
+ )
1274
+ ]
1275
+ missing_generator = [
1276
+ relative
1277
+ for relative in assessment.scratch_files
1278
+ if any(
1279
+ path_glob_matches(relative, pattern)
1280
+ for pattern in profile.landing_generated_artifact_patterns
1281
+ )
1282
+ and relative not in evidence_by_path
1283
+ ]
1284
+ if missing_generator and require_generator_evidence:
1285
+ raise LifecycleError(
1286
+ "landing-generated scratch evidence is missing: "
1287
+ + ", ".join(missing_generator)
1288
+ )
1289
+ with verified_worktree_root(
1290
+ assessment.worktree,
1291
+ assessment.root_device,
1292
+ assessment.root_inode,
1293
+ ) as descriptor:
1294
+ for relative in profile_only:
1295
+ evidence_by_path[relative] = contained_regular_identity(
1296
+ descriptor, relative
1297
+ )
1298
+ return replace(
1299
+ assessment,
1300
+ scratch_evidence=tuple(
1301
+ evidence_by_path[relative]
1302
+ for relative in assessment.scratch_files
1303
+ if relative in evidence_by_path
1304
+ ),
1305
+ )
1306
+
1307
+
1308
+ def contained_regular_identity(root_descriptor: int, relative: str) -> dict[str, Any]:
1309
+ """Read one exact regular file identity without following path symlinks."""
1310
+ path = PurePosixPath(relative)
1311
+ if path.is_absolute() or not path.parts or any(
1312
+ part in {"", ".", ".."} for part in path.parts
1313
+ ):
1314
+ raise LifecycleError(f"unsafe scratch path: {relative}")
1315
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
1316
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1317
+ descriptors = []
1318
+ try:
1319
+ current = root_descriptor
1320
+ for component in path.parts[:-1]:
1321
+ current = os.open(
1322
+ component,
1323
+ directory_flags | no_follow,
1324
+ dir_fd=current,
1325
+ )
1326
+ descriptors.append(current)
1327
+ initial = os.stat(path.name, dir_fd=current, follow_symlinks=False)
1328
+ if not stat.S_ISREG(initial.st_mode):
1329
+ raise LifecycleError(
1330
+ f"scratch path is not a regular file: {relative}"
1331
+ )
1332
+ file_descriptor = os.open(
1333
+ path.name,
1334
+ os.O_RDONLY | no_follow,
1335
+ dir_fd=current,
1336
+ )
1337
+ try:
1338
+ metadata = os.fstat(file_descriptor)
1339
+ if (
1340
+ not stat.S_ISREG(metadata.st_mode)
1341
+ or (metadata.st_dev, metadata.st_ino)
1342
+ != (initial.st_dev, initial.st_ino)
1343
+ ):
1344
+ raise LifecycleError(
1345
+ f"scratch path changed before inspection: {relative}"
1346
+ )
1347
+ digest = sha256()
1348
+ while chunk := os.read(file_descriptor, 128 * 1024):
1349
+ digest.update(chunk)
1350
+ finally:
1351
+ os.close(file_descriptor)
1352
+ return {
1353
+ "path": relative,
1354
+ "device": metadata.st_dev,
1355
+ "inode": metadata.st_ino,
1356
+ "size": metadata.st_size,
1357
+ "sha256": digest.hexdigest(),
1358
+ }
1359
+ except OSError as error:
1360
+ raise LifecycleError(f"scratch path changed before inspection: {relative}") from error
1361
+ finally:
1362
+ for descriptor in reversed(descriptors):
1363
+ os.close(descriptor)
1364
+
1365
+
1366
+ def contained_untracked_identity(
1367
+ root_descriptor: int,
1368
+ relative: str,
1369
+ ) -> dict[str, Any]:
1370
+ """Read exact regular/symlink identity without following any symlink."""
1371
+ path = PurePosixPath(relative)
1372
+ if path.is_absolute() or not path.parts or any(
1373
+ part in {"", ".", ".."} for part in path.parts
1374
+ ):
1375
+ raise LifecycleError(f"unsafe recovery path: {relative}")
1376
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
1377
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1378
+ descriptors = []
1379
+ try:
1380
+ current = root_descriptor
1381
+ for component in path.parts[:-1]:
1382
+ current = os.open(
1383
+ component,
1384
+ directory_flags | no_follow,
1385
+ dir_fd=current,
1386
+ )
1387
+ descriptors.append(current)
1388
+ metadata = os.stat(path.name, dir_fd=current, follow_symlinks=False)
1389
+ common = {
1390
+ "path": relative,
1391
+ "device": metadata.st_dev,
1392
+ "inode": metadata.st_ino,
1393
+ "size": metadata.st_size,
1394
+ }
1395
+ if stat.S_ISLNK(metadata.st_mode):
1396
+ target = os.readlink(path.name, dir_fd=current).encode(
1397
+ "utf-8", errors="surrogateescape"
1398
+ )
1399
+ return {**common, "kind": "symlink", "sha256": sha256(target).hexdigest()}
1400
+ if not stat.S_ISREG(metadata.st_mode):
1401
+ raise LifecycleError(f"unsupported recovery path type: {relative}")
1402
+ file_descriptor = os.open(
1403
+ path.name,
1404
+ os.O_RDONLY | no_follow,
1405
+ dir_fd=current,
1406
+ )
1407
+ try:
1408
+ opened = os.fstat(file_descriptor)
1409
+ if (opened.st_dev, opened.st_ino) != (
1410
+ metadata.st_dev, metadata.st_ino
1411
+ ):
1412
+ raise LifecycleError(
1413
+ f"recovery path changed before inspection: {relative}"
1414
+ )
1415
+ digest = sha256()
1416
+ while chunk := os.read(file_descriptor, 128 * 1024):
1417
+ digest.update(chunk)
1418
+ finally:
1419
+ os.close(file_descriptor)
1420
+ return {**common, "kind": "regular", "sha256": digest.hexdigest()}
1421
+ except OSError as error:
1422
+ raise LifecycleError(
1423
+ f"recovery path changed before inspection: {relative}"
1424
+ ) from error
1425
+ finally:
1426
+ for descriptor in reversed(descriptors):
1427
+ os.close(descriptor)
1428
+
1429
+
1430
+ def remove_contained_untracked(
1431
+ root_descriptor: int,
1432
+ expected_identity: dict[str, Any],
1433
+ ) -> None:
1434
+ """Unlink one frozen regular file or symlink if its identity still matches."""
1435
+ relative = expected_identity.get("path")
1436
+ if not isinstance(relative, str):
1437
+ raise LifecycleError("recovery path evidence is incoherent")
1438
+ current = contained_untracked_identity(root_descriptor, relative)
1439
+ if current != expected_identity:
1440
+ raise LifecycleError(f"recovery path identity changed: {relative}")
1441
+ path = PurePosixPath(relative)
1442
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
1443
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1444
+ descriptors = []
1445
+ try:
1446
+ parent = root_descriptor
1447
+ for component in path.parts[:-1]:
1448
+ parent = os.open(
1449
+ component,
1450
+ directory_flags | no_follow,
1451
+ dir_fd=parent,
1452
+ )
1453
+ descriptors.append(parent)
1454
+ latest = os.stat(path.name, dir_fd=parent, follow_symlinks=False)
1455
+ if (latest.st_dev, latest.st_ino) != (
1456
+ expected_identity["device"], expected_identity["inode"]
1457
+ ):
1458
+ raise LifecycleError(f"recovery path changed before removal: {relative}")
1459
+ os.unlink(path.name, dir_fd=parent)
1460
+ except OSError as error:
1461
+ raise LifecycleError(f"recovery path changed before removal: {relative}") from error
1462
+ finally:
1463
+ for descriptor in reversed(descriptors):
1464
+ os.close(descriptor)
1465
+
1466
+
266
1467
  @dataclass(frozen=True)
267
1468
  class SweepRow:
268
1469
  kind: str