@mokuyoaxis/agent-guard 0.2.3 → 0.2.5-rc1

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 (80) hide show
  1. package/README.md +158 -571
  2. package/README.zh-CN.md +133 -490
  3. package/SECURITY.md +53 -0
  4. package/adapters/INTEGRATION.md +8 -6
  5. package/adapters/claude/README.md +3 -3
  6. package/adapters/claude/harness/README.md +1 -1
  7. package/adapters/codex/harness/README.md +2 -2
  8. package/adapters/dsh/README.md +17 -6
  9. package/adapters/dsh/harness/README.md +8 -8
  10. package/adapters/dsh/harness/guard_lab.py +3 -3
  11. package/adapters/dsh/lib/index.js +1 -1
  12. package/adapters/kimi-code/README.md +7 -7
  13. package/adapters/kimi-code/harness/README.md +3 -3
  14. package/adapters/kimi-code/harness/guard_lab.py +1 -1
  15. package/assets/linux-do-community.svg +19 -0
  16. package/core/__init__.py +1 -1
  17. package/core/classifier.py +66 -17
  18. package/core/policy.py +28 -13
  19. package/core/recovery.py +261 -24
  20. package/core/redaction.py +122 -21
  21. package/core/trash_index.py +193 -0
  22. package/docs/README.md +113 -0
  23. package/docs/{architecture.md → design/architecture.md} +51 -12
  24. package/docs/{compatibility.md → design/compatibility.md} +124 -4
  25. package/docs/{threat-model.md → design/threat-model.md} +10 -8
  26. package/docs/guides/getting-started.md +104 -0
  27. package/docs/{harness-capabilities.md → guides/harness-capabilities.md} +14 -9
  28. package/docs/guides/trash-index.md +106 -0
  29. package/docs/{development-note-unguarded-deletion.md → history/development-note-unguarded-deletion.md} +2 -2
  30. package/docs/{friction.md → history/friction.md} +123 -0
  31. package/docs/{secret-guard-analysis.md → history/secret-guard-analysis.md} +12 -12
  32. package/docs/{secret-guard-architecture.md → history/secret-guard-architecture.md} +2 -2
  33. package/docs/{secret-guard-design.md → history/secret-guard-design.md} +14 -14
  34. package/docs/lab/cases/injection-case-fake-ai-api.md +346 -0
  35. package/docs/{guard-lab.md → lab/guard-lab.md} +15 -13
  36. package/docs/{release-notes-0.2.0-rc1.md → releases/release-notes-0.2.0-rc1.md} +3 -3
  37. package/docs/{release-notes-0.2.0.md → releases/release-notes-0.2.0.md} +5 -5
  38. package/docs/{release-notes-0.2.1.md → releases/release-notes-0.2.1.md} +6 -6
  39. package/docs/{release-notes-0.2.2.md → releases/release-notes-0.2.2.md} +2 -2
  40. package/docs/{release-notes-0.2.3-rc1.md → releases/release-notes-0.2.3-rc1.md} +1 -1
  41. package/docs/{release-notes-0.2.3-rc2.md → releases/release-notes-0.2.3-rc2.md} +9 -9
  42. package/docs/{release-notes-0.2.3.md → releases/release-notes-0.2.3.md} +3 -3
  43. package/docs/releases/release-notes-0.2.4.md +89 -0
  44. package/docs/releases/release-notes-0.2.5-rc1.md +91 -0
  45. package/docs/{test-report-claude-code-harness.md → reports/test-report-claude-code-harness.md} +5 -5
  46. package/docs/reports/test-report-dsh-0.2.4-ptc.md +79 -0
  47. package/docs/{test-report-dsh-guard-lab.md → reports/test-report-dsh-guard-lab.md} +1 -1
  48. package/docs/{test-report-dsh-native-session.md → reports/test-report-dsh-native-session.md} +1 -1
  49. package/docs/{test-report-dsh-paired-lab.md → reports/test-report-dsh-paired-lab.md} +1 -1
  50. package/docs/{test-report-dsh-real-followup.md → reports/test-report-dsh-real-followup.md} +1 -1
  51. package/docs/{test-report-dsh-retry-evidence.md → reports/test-report-dsh-retry-evidence.md} +1 -1
  52. package/docs/{test-report-dsh-v0.1.1.md → reports/test-report-dsh-v0.1.1.md} +4 -4
  53. package/docs/{test-report-kimi-code-block.md → reports/test-report-kimi-code-block.md} +3 -3
  54. package/docs/{test-report-kimi-guard-lab.md → reports/test-report-kimi-guard-lab.md} +3 -3
  55. package/docs/{test-report-release-readiness-0.2.3.md → reports/test-report-release-readiness-0.2.3.md} +1 -1
  56. package/docs/{test-report-workbuddy-windows-core.md → reports/test-report-workbuddy-windows-core.md} +1 -1
  57. package/docs/{test-report-zcode-glm-flash.md → reports/test-report-zcode-glm-flash.md} +2 -2
  58. package/package.json +4 -2
  59. package/skills/delete-guard/SKILL.md +80 -7
  60. package/skills/delete-guard/references/policy.md +104 -8
  61. package/skills/delete-guard/scripts/check.py +22 -0
  62. package/skills/delete-guard/scripts/restore.py +34 -7
  63. package/skills/delete-guard/scripts/safe_delete.py +52 -29
  64. package/skills/delete-guard/scripts/status.py +52 -0
  65. package/skills/exfil-guard/SKILL.md +23 -11
  66. package/skills/exfil-guard/references/channels.md +9 -2
  67. package/skills/exfil-guard/references/rules.md +83 -6
  68. package/skills/exfil-guard/scripts/_payload.py +20 -0
  69. package/skills/exfil-guard/scripts/check_span.py +5 -1
  70. package/skills/exfil-guard/scripts/sanitize.py +6 -3
  71. /package/docs/{host-drift.md → guides/host-drift.md} +0 -0
  72. /package/docs/{publishing-from-ephemeral-environments.md → guides/publishing-from-ephemeral-environments.md} +0 -0
  73. /package/docs/{guard-lab-clean-task.md → lab/tasks/guard-lab-clean-task.md} +0 -0
  74. /package/docs/{guard-lab-read-trial-task.md → lab/tasks/guard-lab-read-trial-task.md} +0 -0
  75. /package/docs/{guard-lab-trial-task.md → lab/tasks/guard-lab-trial-task.md} +0 -0
  76. /package/docs/{test-report-codex-gpt-5.6-sol.md → reports/test-report-codex-gpt-5.6-sol.md} +0 -0
  77. /package/docs/{test-report-codex-gpt-6-astra-high.md → reports/test-report-codex-gpt-6-astra-high.md} +0 -0
  78. /package/docs/{test-report-dsh-0.1.5-rc.1.md → reports/test-report-dsh-0.1.5-rc.1.md} +0 -0
  79. /package/docs/{test-report-dsh-0.2-upgrade.md → reports/test-report-dsh-0.2-upgrade.md} +0 -0
  80. /package/docs/{test-report-dsh-read-redaction.md → reports/test-report-dsh-read-redaction.md} +0 -0
package/core/policy.py CHANGED
@@ -7,7 +7,7 @@ The stable cross-harness interface is NOT allow/block. It is:
7
7
  + Explanation
8
8
  + RecoveryPlan (payload)
9
9
 
10
- Decision classes (docs/architecture.md):
10
+ Decision classes (docs/design/architecture.md):
11
11
 
12
12
  ALLOW safe to run as-is (noop / provably regenerable / trash GC)
13
13
  RELOCATE compensate by quarantine, then run
@@ -118,6 +118,7 @@ CODE_ASK_PATH_EMISSION = "ASK_PATH_EMISSION"
118
118
  CODE_ALLOW_SECRET_PLACEHOLDER = "ALLOW_SECRET_PLACEHOLDER"
119
119
  CODE_ALLOW_PATH_IN_WORKSPACE = "ALLOW_PATH_IN_WORKSPACE"
120
120
  CODE_BLOCK_COMPENSATION_FAILED = "COMPENSATION_FAILED"
121
+ CODE_BLOCK_GIT_RESET_COLLISION = "BLOCK_GIT_RESET_COLLISION"
121
122
 
122
123
  # Human-facing one-liners: why the guard cannot just do it (or did do it).
123
124
  EXPLANATIONS: Dict[str, str] = {
@@ -137,6 +138,11 @@ EXPLANATIONS: Dict[str, str] = {
137
138
  "real command ran.",
138
139
  CODE_SNAPSHOT_GIT_STASH: "Tracked modifications snapshotted as a stash "
139
140
  "before the command; apply it to recover.",
141
+ CODE_BLOCK_GIT_RESET_COLLISION: "git reset --hard would overwrite "
142
+ "untracked or ignored content, or "
143
+ "quarantine storage, that a tracked-only "
144
+ "stash cannot protect. Preserve the "
145
+ "conflicting paths separately first.",
140
146
  CODE_ASK_COMPOUND_CWD_DELETE: "This line combines a working-directory "
141
147
  "change with deletion, so the guard "
142
148
  "cannot safely relocate the target before "
@@ -160,8 +166,10 @@ EXPLANATIONS: Dict[str, str] = {
160
166
  "/usr, /etc, ...), regardless of the "
161
167
  "workspace setting. Hard boundary - not "
162
168
  "askable.",
163
- CODE_BLOCK_PROTECTED_PATH: "Target is the workspace root or git "
164
- "metadata. Hard boundary - not askable.",
169
+ CODE_BLOCK_PROTECTED_PATH: "Target is a protected workspace, Git or "
170
+ "quarantine control path. Hard boundary - "
171
+ "not askable; quarantine transaction cleanup "
172
+ "uses the explicit GC entry point.",
165
173
  CODE_BLOCK_WILDCARD: "Glob target sets are opaque; use safe_delete, "
166
174
  "which expands globs explicitly.",
167
175
  CODE_BLOCK_RESTRICTED_MODE: "This session is in RESTRICTED mode; the "
@@ -491,7 +499,20 @@ def decide_path_batch(specs: List[PathSpec], ctx: PolicyContext,
491
499
  [f"protected filesystem root: {s.raw}"
492
500
  for s in protected_ancestor[:5]])
493
501
 
502
+ # Housekeeping never overrides root, control-file or Git protection.
503
+ protected_other = [s for s in specs
504
+ if s.protected in ("workspace-root", "git-metadata",
505
+ "quarantine-control")]
506
+ if protected_other:
507
+ return Verdict(DECISION_BLOCK, CODE_BLOCK_PROTECTED_PATH,
508
+ [f"protected: {s.protected} ({s.raw})"
509
+ for s in protected_other[:5]])
510
+
494
511
  if specs and all(s.inside_trash for s in specs):
512
+ if any(s.wildcard for s in specs):
513
+ return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
514
+ ["quarantine globs may include protected evidence; "
515
+ "enumerate explicitly with safe_delete"])
495
516
  return Verdict(DECISION_ALLOW, CODE_ALLOW_TRASH_GC)
496
517
 
497
518
  protected_outside = [s for s in specs
@@ -501,13 +522,6 @@ def decide_path_batch(specs: List[PathSpec], ctx: PolicyContext,
501
522
  [f"outside workspace boundary: {s.raw}"
502
523
  for s in protected_outside[:5]])
503
524
 
504
- protected_other = [s for s in specs
505
- if s.protected in ("workspace-root", "git-metadata")]
506
- if protected_other:
507
- return Verdict(DECISION_BLOCK, CODE_BLOCK_PROTECTED_PATH,
508
- [f"protected: {s.protected} ({s.raw})"
509
- for s in protected_other[:5]])
510
-
511
525
  wild = [s for s in specs if s.wildcard]
512
526
  if wild:
513
527
  return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
@@ -607,7 +621,7 @@ def decide_op(spec: OpSpec, ctx: PolicyContext) -> Optional[Verdict]:
607
621
  # when the target set also trips a hard boundary, that boundary wins.
608
622
  # Without this, `cd /tmp && rm -rf /home` degrades a hard refusal into
609
623
  # an ASK - and any auto-approving host grants an ASK silently, which is
610
- # the incident finding described in docs/development-note-unguarded-deletion.md.
624
+ # the incident finding described in docs/history/development-note-unguarded-deletion.md.
611
625
  if spec.shape in ("F1", "F2"):
612
626
  ask_code = (CODE_ASK_COMPOUND_CWD_DELETE if spec.shape == "F1"
613
627
  else CODE_ASK_COMPOUND_CREATE_DELETE)
@@ -648,8 +662,9 @@ def decide_op(spec: OpSpec, ctx: PolicyContext) -> Optional[Verdict]:
648
662
  if spec.kind == KIND_GIT_RESET_HARD:
649
663
  return Verdict(
650
664
  DECISION_SNAPSHOT, CODE_SNAPSHOT_GIT_STASH,
651
- ["snapshot tracked modifications via git stash create/store "
652
- "before reset --hard"],
665
+ ["preflight untracked/ignored collisions with the target tree, "
666
+ "then snapshot tracked modifications via git stash "
667
+ "create/store before reset --hard"],
653
668
  )
654
669
 
655
670
  if spec.kind == KIND_GIT_DISCARD:
package/core/recovery.py CHANGED
@@ -6,7 +6,8 @@ Two compensation strategies, chosen by the caller (policy decides which):
6
6
  workspace-relative structure under one transaction id
7
7
  snapshot_git - capture tracked modifications as a stash commit WITHOUT
8
8
  changing the working tree (git stash create + store), so a
9
- subsequent reset --hard / restore stays reversible
9
+ subsequent tracked-file changes stay reversible; hard
10
+ reset also requires the untracked-collision preflight
10
11
 
11
12
  Everything lands in an append-only manifest (JSONL). Restore is itself
12
13
  non-destructive: it refuses to overwrite anything that now exists at the
@@ -29,7 +30,7 @@ from typing import Any, Dict, List, Optional, Tuple
29
30
 
30
31
  from . import MANIFEST_NAME, TRASH_DIRNAME
31
32
  from .audit import new_txid, utc_now_iso
32
- from .classifier import PathSpec, _physical, _physical_keep_final
33
+ from .classifier import PathSpec, _physical, _physical_keep_final, inside_path
33
34
 
34
35
  # Soft retention policy (docs/references: GC). Thresholds only MARK entries
35
36
  # GC_ELIGIBLE; actual purging is an explicit maintenance action - a system
@@ -44,7 +45,8 @@ _STORAGE_ERRNOS = {
44
45
 
45
46
  # A transaction directory is one direct child of the quarantine, never a
46
47
  # caller-supplied path. Accept simple historical identifiers too, but no
47
- # separators or dots that could turn an ID into a path traversal.
48
+ # separators or dots that could turn an ID into a path traversal. Restore
49
+ # uses the same identifier constraint as GC.
48
50
  _GC_TXID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*\Z")
49
51
 
50
52
 
@@ -302,6 +304,91 @@ class RecoveryEngine:
302
304
 
303
305
  # ------------------------------------------------------ git snapshot
304
306
 
307
+ def preflight_git_reset_hard(
308
+ self, cwd: Optional[str] = None, target: str = "HEAD",
309
+ ) -> Tuple[List[str], str]:
310
+ """Read-only check for content a tracked-only stash cannot protect.
311
+
312
+ Compare the target tree with Git's untracked paths (including ignored
313
+ paths and nested repositories). A collision includes either side
314
+ being an ancestor of the other: Git can replace a directory with a
315
+ file, or remove a file/symlink to create a directory. Refuse such a
316
+ reset; do not move originals or claim their bytes are in the stash.
317
+ Errors are static so callers can report them without leaking paths.
318
+ """
319
+ cwd = cwd or self.workspace
320
+ git_cwd = cwd
321
+ if re.match(r"(?:refs/)?stash(?:$|[~^@])", target):
322
+ return [], "Stash-relative targets change when a snapshot is stored"
323
+
324
+ def git(*args: str, optional: bool = False) -> bytes:
325
+ proc = subprocess.run(["git", "-C", git_cwd, *args],
326
+ capture_output=True, timeout=30)
327
+ if proc.stderr or (proc.returncode != 0 and not
328
+ (optional and proc.returncode == 1)):
329
+ raise ValueError("Git preflight command failed")
330
+ return proc.stdout
331
+
332
+ def paths(data: bytes) -> List[str]:
333
+ if data and not data.endswith(b"\0"):
334
+ raise ValueError("incomplete Git path enumeration")
335
+ return [os.fsdecode(p) for p in data.split(b"\0") if p]
336
+
337
+ def parents(path: str) -> List[str]:
338
+ parts = path.split("/")
339
+ return ["/".join(parts[:i]) for i in range(1, len(parts))]
340
+
341
+ try:
342
+ # Whole-tree reset cannot be confined to a narrower workspace.
343
+ root = os.fsdecode(git("rev-parse", "--show-toplevel")).rstrip("\n")
344
+ if _physical(root) != _physical(self.workspace):
345
+ return [], "Git repository does not match the workspace"
346
+ # ls-files is scoped by its working directory. Reset is always
347
+ # whole-tree, even when invoked from a repository subdirectory.
348
+ git_cwd = root
349
+ sha = git("rev-parse", "--verify", "--end-of-options",
350
+ target + "^{commit}").strip().decode("ascii")
351
+ tree = paths(git("ls-tree", "-r", "-z", "--full-tree", sha))
352
+ index = paths(git("ls-files", "--stage", "-z"))
353
+ # Submodule working trees are not captured by stash create.
354
+ if any(row.startswith("160000 ") for row in tree + index):
355
+ return [], "Submodule reset effects cannot be protected"
356
+ ignorecase = git("config", "--type=bool", "--get", "core.ignorecase",
357
+ optional=True).strip() == b"true"
358
+
359
+ def key(path: str) -> str:
360
+ return path.casefold() if ignorecase else path
361
+
362
+ leaves = {key(row.split("\t", 1)[1]) for row in tree}
363
+ directories = {p for leaf in leaves for p in parents(leaf)}
364
+ # Intentionally omit --exclude-standard: ignored data is at risk
365
+ # too. -z preserves newlines, quoting, and non-ASCII path bytes.
366
+ others = paths(git("ls-files", "--others", "-z"))
367
+
368
+ def collides(path: str) -> bool:
369
+ path = key(path.rstrip("/"))
370
+ return (path in leaves or path in directories or
371
+ any(p in leaves for p in parents(path)))
372
+
373
+ collisions = [p for p in others if collides(p)]
374
+ # Include future audit/snapshot files even before layout exists.
375
+ # Preserve both storage and its configured spelling: replacing
376
+ # a tracked symlink to external trash would sever recovery access.
377
+ for trash_path in {self.trash_root, _physical(self.trash_root)}:
378
+ for workspace_path in {self.workspace, _physical(self.workspace)}:
379
+ trash = os.path.relpath(trash_path, workspace_path)
380
+ if trash == ".":
381
+ return [], "Quarantine overlaps the workspace root"
382
+ if trash == os.pardir or trash.startswith(os.pardir + os.sep):
383
+ continue
384
+ trash = trash.replace(os.sep, "/")
385
+ if collides(trash) or any(p.startswith(key(trash) + "/")
386
+ for p in leaves):
387
+ collisions.append(trash)
388
+ return sorted(set(collisions)), ""
389
+ except (OSError, subprocess.TimeoutExpired, ValueError, IndexError):
390
+ return [], "Git hard reset preflight could not determine effects"
391
+
305
392
  def snapshot_git(self, cwd: Optional[str] = None,
306
393
  txid: Optional[str] = None,
307
394
  meta: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
@@ -491,24 +578,129 @@ class RecoveryEngine:
491
578
  slot["state"] = "EMPTY"
492
579
  return out
493
580
 
581
+ def _validate_restore_target(self, origin: str) -> None:
582
+ """Check the parent chain, retaining the final symlink's location.
583
+
584
+ Recorded paths are absolute and normalized. Resolve both sides for
585
+ comparison so workspace aliases remain valid, but refuse a parent
586
+ that now points outside. This preflight is not an atomic filesystem
587
+ boundary against concurrent changes.
588
+ """
589
+ if (not isinstance(origin, str) or not origin or "\0" in origin or
590
+ not os.path.isabs(origin) or os.path.normpath(origin) != origin):
591
+ raise ValueError("invalid restore target path")
592
+ root = os.path.normcase(_physical(self.workspace))
593
+ target = os.path.normcase(_physical_keep_final(origin))
594
+ if target == root or not inside_path(target, root):
595
+ raise ValueError("restore target is outside workspace")
596
+
597
+ def _restore_transaction_dir(self, txid: str) -> str:
598
+ """Bind an ID to its own direct child of the selected quarantine."""
599
+ if not isinstance(txid, str) or not _GC_TXID_RE.fullmatch(txid):
600
+ raise ValueError("invalid quarantine transaction id")
601
+ tx_dir = os.path.join(self.trash_root, txid)
602
+ expected = os.path.join(_physical(self.trash_root), txid)
603
+ if (os.path.islink(tx_dir) or
604
+ os.path.normcase(_physical(tx_dir)) != os.path.normcase(expected)):
605
+ raise ValueError("uncontained quarantine transaction directory")
606
+ return tx_dir
607
+
608
+ def _validate_restore_source(self, trash: str, txid: str) -> None:
609
+ """Check the source parent chain without following a leaf link."""
610
+ tx_dir = self._restore_transaction_dir(txid)
611
+ if (not isinstance(trash, str) or not trash or "\0" in trash or
612
+ not os.path.isabs(trash) or os.path.normpath(trash) != trash):
613
+ raise ValueError("invalid restore source path")
614
+ root = os.path.normcase(_physical(tx_dir))
615
+ source = os.path.normcase(_physical_keep_final(trash))
616
+ if source == root or not inside_path(source, root):
617
+ raise ValueError("restore source is outside its transaction")
618
+
619
+ def _validate_restore_preservation(self, origin: str) -> None:
620
+ """Never relocate the quarantine or an alias used to reach it."""
621
+ current = _physical_keep_final(origin)
622
+ pairs = ((origin, self.trash_root),
623
+ (current, _physical_keep_final(self.trash_root)),
624
+ (current, _physical(self.trash_root)))
625
+ for target, storage in pairs:
626
+ target, storage = os.path.normcase(target), os.path.normcase(storage)
627
+ if inside_path(target, storage) or inside_path(storage, target):
628
+ raise ValueError("force restore target overlaps quarantine storage")
629
+
494
630
  def restore(self, txid: str, force: bool = False,
495
631
  cwd: Optional[str] = None) -> Dict[str, Any]:
496
632
  """Undo one transaction. Refuses to overwrite unless force is set.
497
633
 
498
634
  Relocate items move back to their origin paths; snapshot items apply
499
635
  the stored stash (apply, never drop - the evidence stays until a
500
- human prunes it).
636
+ human prunes it). Relocation targets must remain inside this
637
+ workspace and sources inside their own quarantine transaction;
638
+ force does not override either check. A forced overwrite first
639
+ preserves the current occupant in a separate relocation transaction.
640
+ backup_txids identifies preservation attempts, including failed ones.
501
641
  """
502
- tx = self.transactions().get(txid)
642
+ if not isinstance(txid, str) or not _GC_TXID_RE.fullmatch(txid):
643
+ return {"ok": False, "error": "invalid quarantine transaction id"}
644
+ transactions = self.transactions()
645
+ tx = transactions.get(txid)
503
646
  if not tx:
504
647
  return {"ok": False, "error": f"unknown transaction: {txid}"}
505
648
  restored: List[str] = []
506
649
  conflicts: List[str] = []
507
650
  errors: List[str] = []
508
- for item in tx["items"]:
651
+ backup_txids: List[str] = []
652
+ known_txids = set(transactions)
653
+ items = tx["items"]
654
+ try:
655
+ self._restore_transaction_dir(txid)
656
+ except (OSError, ValueError):
657
+ errors.append(
658
+ "restore source is outside its transaction or cannot be resolved")
659
+ items = []
660
+ try:
661
+ # Check every destination before restoring an earlier valid item
662
+ # or removing an existing occupant under force.
663
+ for item in items:
664
+ if item.get("type") == "relocate":
665
+ self._validate_restore_target(item.get("origin_path"))
666
+ except (OSError, ValueError):
667
+ errors.append(
668
+ "restore target is outside workspace or cannot be resolved")
669
+ items = []
670
+ try:
671
+ for item in items:
672
+ if item.get("type") == "relocate":
673
+ self._validate_restore_source(item.get("trash_path"), txid)
674
+ except (OSError, ValueError):
675
+ errors.append(
676
+ "restore source is outside its transaction or cannot be resolved")
677
+ items = []
678
+ try:
679
+ for item in items:
680
+ if (force and item.get("type") == "relocate" and
681
+ os.path.lexists(item["origin_path"])):
682
+ self._validate_restore_preservation(item["origin_path"])
683
+ except (OSError, ValueError):
684
+ errors.append(
685
+ "force restore target overlaps quarantine storage or cannot be resolved")
686
+ items = []
687
+ for item in items:
509
688
  if item.get("type") == "relocate":
510
689
  origin = item["origin_path"]
511
690
  trash = item["trash_path"]
691
+ try:
692
+ # An earlier restore can itself recreate a parent link.
693
+ self._validate_restore_target(origin)
694
+ except (OSError, ValueError):
695
+ errors.append(
696
+ "restore target is outside workspace or cannot be resolved")
697
+ continue
698
+ try:
699
+ self._validate_restore_source(trash, txid)
700
+ except (OSError, ValueError):
701
+ errors.append(
702
+ "restore source is outside its transaction or cannot be resolved")
703
+ continue
512
704
  if not os.path.lexists(trash):
513
705
  errors.append(f"quarantine copy vanished: {trash}")
514
706
  continue
@@ -516,14 +708,48 @@ class RecoveryEngine:
516
708
  if not force:
517
709
  conflicts.append(origin)
518
710
  continue
519
- if os.path.isdir(origin) and not os.path.islink(origin):
520
- shutil.rmtree(origin)
521
- else:
522
- os.unlink(origin)
523
- parent = os.path.dirname(origin)
524
- if parent:
525
- os.makedirs(parent, exist_ok=True)
711
+ try:
712
+ self._validate_restore_preservation(origin)
713
+ backup_txid = new_txid()
714
+ backup_dir = self._restore_transaction_dir(backup_txid)
715
+ if (backup_txid in known_txids or
716
+ os.path.lexists(backup_dir)):
717
+ raise ValueError("backup transaction already exists")
718
+ except (OSError, ValueError) as exc:
719
+ errors.append(f"cannot establish current-version backup: {exc}")
720
+ continue
721
+ known_txids.add(backup_txid)
722
+ backup_txids.append(backup_txid)
723
+ try:
724
+ saved = self.relocate(
725
+ [PathSpec(raw=origin, resolved=origin)],
726
+ txid=backup_txid,
727
+ meta={"tool": "restore", "restoring_txid": txid})
728
+ if saved.get("storage_failure") or len(saved["moved"]) != 1:
729
+ errors.append(
730
+ f"current-version preservation failed; "
731
+ f"inspect backup transaction {backup_txid}")
732
+ continue
733
+ except OSError as exc:
734
+ errors.append(
735
+ f"current-version preservation failed "
736
+ f"(backup transaction {backup_txid}): {exc}")
737
+ continue
738
+ try:
739
+ self._validate_restore_target(origin)
740
+ self._validate_restore_source(trash, txid)
741
+ except (OSError, ValueError):
742
+ errors.append("restore paths changed after preservation")
743
+ continue
744
+ # Do not silently overwrite a version created while the
745
+ # occupant was being preserved, even with force set.
746
+ if os.path.lexists(origin):
747
+ conflicts.append(origin)
748
+ continue
526
749
  try:
750
+ parent = os.path.dirname(origin)
751
+ if parent:
752
+ os.makedirs(parent, exist_ok=True)
527
753
  self._move(trash, origin)
528
754
  restored.append(origin)
529
755
  except OSError as exc:
@@ -541,19 +767,26 @@ class RecoveryEngine:
541
767
  errors.append(
542
768
  f"stash apply {sha}: {(apply.stderr or '').strip()}")
543
769
 
544
- self._manifest_append([{
545
- "type": "restore", "txid": txid, "force": force,
546
- "restored": restored, "conflicts": conflicts, "errors": errors,
547
- }])
548
- # drop empty quarantine directories for tidy listings
549
- txdir = os.path.join(self.trash_root, txid)
550
770
  try:
551
- if os.path.isdir(txdir) and not os.listdir(txdir):
552
- os.rmdir(txdir)
771
+ self._manifest_append([{
772
+ "type": "restore", "txid": txid, "force": force,
773
+ "restored": restored, "conflicts": conflicts, "errors": errors,
774
+ }])
553
775
  except OSError:
776
+ errors.append("restore journal could not be stored; inspect filesystem state")
777
+ # drop empty quarantine directories for tidy listings
778
+ try:
779
+ if not errors:
780
+ txdir = self._restore_transaction_dir(txid)
781
+ if os.path.isdir(txdir) and not os.listdir(txdir):
782
+ os.rmdir(txdir)
783
+ except (OSError, ValueError):
554
784
  pass
555
- return {"ok": not errors and not conflicts,
556
- "restored": restored, "conflicts": conflicts, "errors": errors}
785
+ report = {"ok": not errors and not conflicts,
786
+ "restored": restored, "conflicts": conflicts, "errors": errors}
787
+ if backup_txids:
788
+ report["backup_txids"] = backup_txids
789
+ return report
557
790
 
558
791
  # ------------------------------------------------------------- status
559
792
 
@@ -598,9 +831,13 @@ class RecoveryEngine:
598
831
  return None
599
832
 
600
833
  def tx_inventory(self) -> List[Dict[str, Any]]:
601
- """Per-transaction age/size facts for retention decisions."""
834
+ """Active transaction age/size facts; purged history stays in the manifest."""
602
835
  inventory: List[Dict[str, Any]] = []
603
836
  for txid, tx in self.transactions().items():
837
+ # A tombstone ends our ownership for planning. A directory later
838
+ # recreated under this ID is unmanaged, not another purge target.
839
+ if tx.get("purged"):
840
+ continue
604
841
  tx_dir = os.path.join(self.trash_root, txid)
605
842
  total = 0
606
843
  for root, _dirs, names in os.walk(tx_dir):