@mokuyoaxis/agent-guard 0.2.6 → 0.2.7

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,297 @@
1
+ """Metadata-only cleanup proposals; deletion remains owned by safe_delete.
2
+
3
+ The plan is a local review aid, not permission to bypass policy. It does not
4
+ read candidate contents, follow directory links, or create guard metadata.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import stat
12
+ import subprocess
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
15
+
16
+ from . import TRASH_DIRNAME, classifier, policy
17
+ from .delete_config import CONFIG_DIRECTORY, fingerprint, load_config
18
+
19
+
20
+ CATEGORIES = ("regenerable", "discarded", "uncertain", "protected")
21
+ PROTECTED_NAMES = frozenset({".git", ".internal", TRASH_DIRNAME, CONFIG_DIRECTORY})
22
+ DEFAULT_MAX_ENTRIES = 10_000
23
+ DEFAULT_MAX_DEPTH = 32
24
+
25
+
26
+ def _digest(value: Any) -> str:
27
+ encoded = json.dumps(value, sort_keys=True, ensure_ascii=True,
28
+ separators=(",", ":")).encode("ascii")
29
+ return hashlib.sha256(encoded).hexdigest()
30
+
31
+
32
+ def _under(path: str, parent: str) -> bool:
33
+ return parent == "." or path == parent or path.startswith(parent + "/")
34
+
35
+
36
+ def _declared_paths(values: Iterable[str], root: str, *, must_exist: bool) -> List[str]:
37
+ result = set()
38
+ for value in values:
39
+ absolute = os.path.normpath(os.path.join(root, os.fspath(value)))
40
+ if not classifier.inside_path(absolute, root):
41
+ raise ValueError("declared cleanup paths must be inside the workspace")
42
+ if must_exist and absolute == root:
43
+ raise ValueError("the workspace root cannot be declared discarded")
44
+ if must_exist and not os.path.lexists(absolute):
45
+ raise ValueError("discard target does not exist: " + os.fspath(value))
46
+ result.add(os.path.relpath(absolute, root).replace(os.sep, "/"))
47
+ return sorted(result)
48
+
49
+
50
+ @dataclass
51
+ class _Node:
52
+ path: str
53
+ kind: str = "unknown"
54
+ signature: Optional[List[int]] = None
55
+ protected: Optional[str] = None
56
+ complete: bool = True
57
+ children: List["_Node"] = field(default_factory=list)
58
+ files: Dict[Tuple[int, int], int] = field(default_factory=dict)
59
+ fingerprint: str = ""
60
+ has_protected: bool = False
61
+
62
+
63
+ def _git_facts(root: str, paths: List[str]):
64
+ """Batch queries; an unavailable Git supplies no regenerability proof."""
65
+ env = dict(os.environ, GIT_OPTIONAL_LOCKS="0")
66
+ try:
67
+ tracked = subprocess.run(
68
+ ["git", "-C", root, "ls-files", "--cached", "-z"],
69
+ capture_output=True, timeout=10, env=env)
70
+ if tracked.returncode:
71
+ return set(), set(), "GIT_UNAVAILABLE"
72
+ ignored = subprocess.run(
73
+ ["git", "-C", root, "check-ignore", "--stdin", "-z"],
74
+ input=b"".join(os.fsencode(p) + b"\0" for p in paths),
75
+ capture_output=True, timeout=10, env=env)
76
+ if ignored.returncode not in (0, 1):
77
+ return set(), set(), "GIT_IGNORE_UNAVAILABLE"
78
+ except (OSError, subprocess.TimeoutExpired):
79
+ return set(), set(), "GIT_UNAVAILABLE"
80
+ return ({os.fsdecode(p).replace(os.sep, "/") for p in tracked.stdout.split(b"\0") if p},
81
+ {os.fsdecode(p).replace(os.sep, "/") for p in ignored.stdout.split(b"\0") if p},
82
+ None)
83
+
84
+
85
+ def plan_cleanup(
86
+ workspace: str, *, discard: Iterable[str] = (), protect: Iterable[str] = (),
87
+ max_entries: int = DEFAULT_MAX_ENTRIES, max_depth: int = DEFAULT_MAX_DEPTH,
88
+ ) -> Dict[str, Any]:
89
+ """Propose disjoint targets under a bounded workspace scan.
90
+
91
+ Protected subtrees are represented without traversal or size estimates.
92
+ Ordinary unknown subtrees collapse to one review row; generated or
93
+ explicitly discarded children remain visible. Sizes deduplicate hardlinks
94
+ and exclude directory metadata; they do not predict released disk blocks.
95
+ """
96
+ if type(max_entries) is not int or max_entries < 1:
97
+ raise ValueError("max_entries must be a positive integer")
98
+ if type(max_depth) is not int or not 1 <= max_depth <= 128:
99
+ raise ValueError("max_depth must be between 1 and 128")
100
+ root = os.path.realpath(os.path.abspath(os.fspath(workspace)))
101
+ if not os.path.isdir(root) or classifier.protected_ancestor_root(root):
102
+ raise ValueError("provide an existing workspace below a filesystem root")
103
+ delete_config = load_config(root)
104
+ discard = _declared_paths(discard, root, must_exist=True)
105
+ protect = list(protect) + delete_config.protected_paths
106
+ protect = sorted(set(_declared_paths(protect, root, must_exist=False)) | PROTECTED_NAMES)
107
+ # A declared path may cross a directory alias. Protect both spellings:
108
+ # deleting a physical ancestor must not cover the declared evidence.
109
+ physical_protection = []
110
+ for path in protect:
111
+ physical = os.path.realpath(os.path.join(root, path))
112
+ if classifier.inside_path(physical, root):
113
+ physical_protection.append(os.path.relpath(physical, root).replace(os.sep, "/"))
114
+ protect = sorted(set(protect + physical_protection))
115
+ trash = os.path.abspath(os.environ.get("AGENT_GUARD_TRASH", os.path.join(root, TRASH_DIRNAME)))
116
+ if classifier.inside_path(trash, root):
117
+ protect = sorted(set(protect + [os.path.relpath(trash, root).replace(os.sep, "/")]))
118
+ ctx = policy.PolicyContext(workspace=root, trash_root=trash, base_dir=root,
119
+ mode=policy.load_mode(trash)["mode"])
120
+ errors = []
121
+ nodes: List[_Node] = []
122
+ examined = 0
123
+
124
+ def problem(node: _Node, code: str) -> None:
125
+ node.complete = False
126
+ record = {"path": node.path, "code": code}
127
+ if record not in errors:
128
+ errors.append(record)
129
+
130
+ def visit(relative: str, depth: int) -> _Node:
131
+ nonlocal examined
132
+ node = _Node(relative)
133
+ nodes.append(node)
134
+ absolute = os.path.join(root, relative)
135
+ if (set(relative.split("/")) & PROTECTED_NAMES
136
+ or any(_under(relative, p) for p in protect)):
137
+ node.protected = "protected project or recovery subtree; not traversed"
138
+ physical = os.path.realpath(absolute)
139
+ if physical != absolute and classifier.inside_path(physical, root):
140
+ physical_relative = os.path.relpath(physical, root).replace(os.sep, "/")
141
+ if not any(_under(physical_relative, p) for p in protect):
142
+ # A nested protected alias was not known before traversal.
143
+ # Require an upfront declaration before selecting ancestors.
144
+ problem(node, "PROTECTED_ALIAS_REQUIRES_EXPLICIT_PROTECT")
145
+ else:
146
+ try:
147
+ info = os.lstat(absolute)
148
+ node.signature = [info.st_dev, info.st_ino, info.st_mode,
149
+ info.st_size, info.st_mtime_ns, info.st_ctime_ns]
150
+ spec = (classifier.classify_paths(["./" + relative], root, root, trash)[0]
151
+ if relative != "." else None)
152
+ physical = os.path.relpath(os.path.realpath(absolute), root).replace(os.sep, "/")
153
+ if ((spec and spec.protected) or set(physical.split("/")) & PROTECTED_NAMES
154
+ or any(_under(physical, p) for p in protect)
155
+ or (stat.S_ISLNK(info.st_mode)
156
+ and any(_under(p, relative) for p in protect))):
157
+ node.protected = "protected boundary or link destination; not traversed"
158
+ elif stat.S_ISDIR(info.st_mode):
159
+ node.kind = "directory"
160
+ if depth >= max_depth:
161
+ problem(node, "DEPTH_LIMIT_REACHED")
162
+ else:
163
+ names = []
164
+ with os.scandir(absolute) as entries:
165
+ for entry in entries:
166
+ if examined + len(names) >= max_entries:
167
+ problem(node, "ENTRY_LIMIT_REACHED")
168
+ break
169
+ names.append(entry.name)
170
+ for name in sorted(names):
171
+ if examined >= max_entries:
172
+ problem(node, "ENTRY_LIMIT_REACHED")
173
+ break
174
+ examined += 1
175
+ child = visit(name if relative == "." else relative + "/" + name,
176
+ depth + 1)
177
+ node.children.append(child)
178
+ node.files.update(child.files)
179
+ node.complete &= child.complete
180
+ after = os.lstat(absolute)
181
+ if [after.st_dev, after.st_ino, after.st_mode, after.st_size,
182
+ after.st_mtime_ns, after.st_ctime_ns] != node.signature:
183
+ problem(node, "SOURCE_CHANGED_DURING_SCAN")
184
+ elif stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode):
185
+ node.kind = "symlink" if stat.S_ISLNK(info.st_mode) else "file"
186
+ node.files[(info.st_dev, info.st_ino)] = info.st_size
187
+ else:
188
+ node.protected = "special filesystem entry; manual review required"
189
+ except OSError as exc:
190
+ problem(node, "OS_ERROR_" + str(exc.errno))
191
+ node.has_protected = (bool(node.protected)
192
+ or any(c.has_protected for c in node.children)
193
+ or (node.kind == "directory"
194
+ and any(_under(p, node.path) for p in protect)))
195
+ node.fingerprint = _digest([node.path, node.signature if not node.protected else None,
196
+ node.protected, node.complete,
197
+ [c.fingerprint for c in node.children]])
198
+ return node
199
+
200
+ # The workspace root is a boundary, but its children are scanned.
201
+ tree = visit(".", 0)
202
+ tracked, ignored, git_warning = _git_facts(
203
+ root, [n.path for n in nodes if n.path != "." and not n.protected])
204
+ tracked_ancestors = set(tracked)
205
+ for path in tracked:
206
+ parts = path.split("/")
207
+ tracked_ancestors.update("/".join(parts[:i]) for i in range(1, len(parts)))
208
+
209
+ def row(node: _Node, category: str, reason: str) -> Dict[str, Any]:
210
+ result = {
211
+ "path": node.path, "kind": node.kind, "category": category,
212
+ "size_bytes": None if node.protected else sum(node.files.values()),
213
+ "size_complete": node.complete and not node.has_protected,
214
+ "reason": reason, "selectable": False, "effect": "review",
215
+ "policy_code": None, "fingerprint": node.fingerprint,
216
+ }
217
+ if category == "protected":
218
+ result["effect"] = "keep"
219
+ elif category in ("regenerable", "discarded"):
220
+ # Concrete, relative spelling also used by the execution CLI.
221
+ spelling = "./" + node.path
222
+ specs = classifier.classify_paths([spelling], root, root, trash)
223
+ verdict = policy.decide_path_batch(specs, ctx, recursive=True)
224
+ result["policy_code"] = verdict.code
225
+ literal = (not specs[0].wildcard and not specs[0].indeterminable
226
+ and specs[0].resolved == os.path.join(root, node.path))
227
+ if literal and not verdict.blocked:
228
+ result["selectable"] = True
229
+ result["effect"] = ("delete" if verdict.code == policy.CODE_ALLOW_REGENERABLE
230
+ else "quarantine")
231
+ else:
232
+ result["effect"] = "blocked"
233
+ result["reason"] += "; existing path API or policy refuses execution"
234
+ return result
235
+
236
+ def flatten(node: _Node) -> List[Dict[str, Any]]:
237
+ if node.protected:
238
+ return [row(node, "protected", node.protected)]
239
+ if not node.complete and node.path != ".":
240
+ return [row(node, "uncertain", "incomplete scan; not executable")]
241
+ if node.path != "." and node.complete and not node.has_protected:
242
+ if any(_under(node.path, p) for p in discard):
243
+ return [row(node, "discarded", "explicitly declared discarded by caller")]
244
+ if (node.path in ignored and node.path not in tracked_ancestors
245
+ and policy._matches_artifact(node.path.replace("/", os.sep),
246
+ ctx.config.artifact_patterns)):
247
+ return [row(node, "regenerable", "Git-ignored and matches an artifact pattern")]
248
+ children = [entry for child in node.children for entry in flatten(child)]
249
+ if (node.path == "."
250
+ or any(entry["category"] != "uncertain" for entry in children)):
251
+ return children
252
+ return [row(node, "uncertain", "tracked content or no explicit discard/regeneration evidence")]
253
+
254
+ entries = sorted(flatten(tree), key=lambda entry: entry["path"])
255
+ summary = {}
256
+ by_path = {n.path: n for n in nodes}
257
+ for category in CATEGORIES:
258
+ subset = [e for e in entries if e["category"] == category]
259
+ unique_files = {}
260
+ for entry in subset:
261
+ unique_files.update(by_path[entry["path"]].files)
262
+ summary[category] = {"count": len(subset), "size_bytes": sum(unique_files.values())}
263
+ result = {
264
+ "schema_version": 1, "tool": "cleanup", "workspace": root,
265
+ "trash_root": trash, "mode": ctx.mode, "complete": not errors,
266
+ "examined": examined, "options": {"discard": discard, "protect": protect,
267
+ "max_entries": max_entries, "max_depth": max_depth},
268
+ "summary": summary, "entries": entries, "errors": errors,
269
+ "protected_names": sorted(PROTECTED_NAMES),
270
+ "warnings": [git_warning] if git_warning else [],
271
+ "size_notice": "Logical bytes, hardlinks counted once per category; protected subtrees omitted. Quarantine retains storage; bytes are not a freed-space estimate.",
272
+ }
273
+ result["plan_id"] = _digest({"plan": result, "tree": tree.fingerprint,
274
+ "config": vars(ctx.config),
275
+ "deletion_config": fingerprint(delete_config)})
276
+ return result
277
+
278
+
279
+ def select_entries(plan: Dict[str, Any], paths: Iterable[str], plan_id: str) -> List[Dict[str, Any]]:
280
+ """Validate the exact reviewed selection before requesting confirmation."""
281
+ if plan_id != plan["plan_id"]:
282
+ raise ValueError("plan changed; review a fresh plan before executing")
283
+ if not plan["complete"]:
284
+ raise ValueError("incomplete scan; resolve scan limits/errors before executing")
285
+ selected = _declared_paths(paths, plan["workspace"], must_exist=True)
286
+ if not selected:
287
+ raise ValueError("--execute requires at least one explicit --select path")
288
+ rows = {entry["path"]: entry for entry in plan["entries"]}
289
+ result = []
290
+ for path in selected:
291
+ entry = rows.get(path)
292
+ if entry is None or not entry["selectable"]:
293
+ raise ValueError("target is not a selectable plan entry: " + path)
294
+ if any(_under(path, other["path"]) for other in result):
295
+ raise ValueError("overlapping selections are not allowed")
296
+ result.append(entry)
297
+ return result
@@ -0,0 +1,153 @@
1
+ """Local deletion limits and protected paths; advisory against same-UID edits.
2
+
3
+ The optional JSON file is read only. Missing configuration uses documented
4
+ defaults; malformed configuration never silently disables protection.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import asdict, dataclass, field
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import stat
13
+ from typing import List, Optional
14
+
15
+
16
+ CONFIG_DIRECTORY = ".agent-guard"
17
+ CONFIG_NAME = "delete-policy.json"
18
+ MAX_CONFIG_BYTES = 1024 * 1024
19
+ MAX_INTEGER = (1 << 63) - 1
20
+
21
+
22
+ class DeleteConfigError(ValueError):
23
+ """The local deletion configuration cannot be used safely."""
24
+
25
+
26
+ @dataclass
27
+ class DeleteConfig:
28
+ quarantine_max_bytes: int = 5 * 1024 ** 3
29
+ quarantine_max_entries: int = 100_000
30
+ session_max_bytes: int = 1024 ** 3
31
+ session_max_entries: int = 10_000
32
+ rate_window_seconds: int = 60
33
+ rate_max_operations: int = 60
34
+ repeat_max_operations: int = 5
35
+ batch_max_bytes: int = 256 * 1024 ** 2
36
+ batch_max_entries: int = 1_000
37
+ protected_paths: List[str] = field(default_factory=list)
38
+
39
+ def fingerprint(self) -> str:
40
+ return fingerprint(self)
41
+
42
+
43
+ def _inside(path: str, root: str) -> bool:
44
+ try:
45
+ path, root = os.path.normcase(path), os.path.normcase(root)
46
+ return os.path.commonpath([path, root]) == root
47
+ except ValueError:
48
+ return False
49
+
50
+
51
+ def _declaration(value: str, workspace: str) -> str:
52
+ if not isinstance(value, str) or not value or "\0" in value:
53
+ raise DeleteConfigError("protected_paths must contain nonempty literal paths")
54
+ root = os.path.abspath(workspace)
55
+ path = os.path.normpath(os.path.join(root, value))
56
+ if not _inside(path, root):
57
+ raise DeleteConfigError("protected_paths must stay inside the workspace")
58
+ # Resolve directory aliases, retaining a final link's own location: a
59
+ # declaration can protect an outward-pointing link without authorizing
60
+ # configuration of an arbitrary external directory.
61
+ parent, leaf = os.path.split(path)
62
+ location = os.path.join(os.path.realpath(parent), leaf)
63
+ if path != root and not _inside(location, os.path.realpath(root)):
64
+ raise DeleteConfigError("protected_paths cannot cross an external directory link")
65
+ return os.path.relpath(path, root)
66
+
67
+
68
+ def _unique_object(pairs):
69
+ result = {}
70
+ for name, value in pairs:
71
+ if name in result:
72
+ raise DeleteConfigError("duplicate deletion configuration field")
73
+ result[name] = value
74
+ return result
75
+
76
+
77
+ def load_config(workspace: str) -> DeleteConfig:
78
+ """Read the optional workspace policy, rejecting malformed known fields."""
79
+ path = os.path.join(os.path.abspath(workspace), CONFIG_DIRECTORY, CONFIG_NAME)
80
+ try:
81
+ # A FIFO must not block even briefly before we can classify it. Check
82
+ # the opened descriptor, rather than stat-then-open with a race.
83
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
84
+ try:
85
+ if not stat.S_ISREG(os.fstat(descriptor).st_mode):
86
+ raise DeleteConfigError("deletion configuration must be a regular file")
87
+ with os.fdopen(descriptor, "rb", closefd=False) as handle:
88
+ raw = handle.read(MAX_CONFIG_BYTES + 1)
89
+ finally:
90
+ os.close(descriptor)
91
+ except FileNotFoundError as exc:
92
+ if os.path.lexists(path):
93
+ raise DeleteConfigError("deletion configuration is an unreadable link") from exc
94
+ return DeleteConfig()
95
+ except OSError as exc:
96
+ raise DeleteConfigError("cannot read deletion configuration") from exc
97
+ if len(raw) > MAX_CONFIG_BYTES:
98
+ raise DeleteConfigError("deletion configuration exceeds the size limit")
99
+ try:
100
+ data = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
101
+ except (UnicodeError, json.JSONDecodeError, RecursionError) as exc:
102
+ raise DeleteConfigError("deletion configuration must be a valid UTF-8 JSON object") from exc
103
+ if not isinstance(data, dict):
104
+ raise DeleteConfigError("deletion configuration must be an object")
105
+ known = DeleteConfig.__dataclass_fields__
106
+ if set(data) - set(known):
107
+ raise DeleteConfigError("unknown deletion configuration field")
108
+ values = dict(data)
109
+ for name, value in values.items():
110
+ if name == "protected_paths":
111
+ if not isinstance(value, list):
112
+ raise DeleteConfigError("protected_paths must be a list of literal paths")
113
+ values[name] = sorted(set(_declaration(item, workspace) for item in value))
114
+ else:
115
+ minimum = 0 if name.endswith("_bytes") else 1
116
+ if type(value) is not int or not minimum <= value <= MAX_INTEGER:
117
+ raise DeleteConfigError("deletion limits require bounded integers; only byte limits may be zero")
118
+ return DeleteConfig(**values)
119
+
120
+
121
+ def fingerprint(config: DeleteConfig) -> str:
122
+ """Digest effective limits and paths without exposing their contents."""
123
+ raw = json.dumps(asdict(config), ensure_ascii=True, sort_keys=True,
124
+ separators=(",", ":")).encode("ascii")
125
+ return hashlib.sha256(raw).hexdigest()
126
+
127
+
128
+ def protected_reason(paths: List[str], workspace: str,
129
+ config: Optional[DeleteConfig] = None) -> Optional[str]:
130
+ """Return a static reason when deleting any target overlaps protection.
131
+
132
+ Both the named location and physical destination are protected, including
133
+ deletion of an ancestor that would remove a protected descendant.
134
+ """
135
+ config = config if config is not None else load_config(workspace)
136
+ root = os.path.abspath(workspace)
137
+ protected = [os.path.join(root, CONFIG_DIRECTORY)]
138
+ protected.extend(os.path.join(root, value) for value in config.protected_paths)
139
+ boundaries = set()
140
+ for path in protected:
141
+ absolute = os.path.normpath(path)
142
+ parent, leaf = os.path.split(absolute)
143
+ boundaries.update((absolute, os.path.realpath(absolute),
144
+ os.path.join(os.path.realpath(parent), leaf)))
145
+ for value in paths:
146
+ absolute = os.path.normpath(os.path.join(root, value))
147
+ parent, leaf = os.path.split(absolute)
148
+ variants = (absolute, os.path.realpath(absolute),
149
+ os.path.join(os.path.realpath(parent), leaf))
150
+ if any(_inside(target, boundary) or _inside(boundary, target)
151
+ for target in variants for boundary in boundaries):
152
+ return "target overlaps deletion configuration or a configured protected path"
153
+ return None
package/core/policy.py CHANGED
@@ -59,6 +59,7 @@ from typing import Any, Dict, List, Optional
59
59
 
60
60
  from . import STATE_NAME, TRASH_DIRNAME
61
61
  from . import redaction
62
+ from . import delete_config
62
63
  from .redaction import get_channel
63
64
  from .classifier import (
64
65
  KIND_FS_DELETE,
@@ -105,6 +106,13 @@ CODE_BLOCK_FORCE_PUSH = "BLOCK_FORCE_PUSH"
105
106
  CODE_BLOCK_DIALECT_UNKNOWN = "BLOCK_DIALECT_UNKNOWN" # config
106
107
  CODE_BLOCK_DIALECT_INVALID = "BLOCK_DIALECT_INVALID" # config
107
108
  CODE_BLOCK_RELOCATE_FAILED_STORAGE = "RELOCATE_FAILED_STORAGE"
109
+ CODE_BLOCK_DELETE_CONFIG_INVALID = "BLOCK_DELETE_CONFIG_INVALID"
110
+ CODE_BLOCK_DELETE_PROTECTED = "BLOCK_DELETE_PROTECTED"
111
+ CODE_BLOCK_DELETE_LIMIT = "BLOCK_DELETE_LIMIT"
112
+ CODE_BLOCK_DELETE_RATE = "BLOCK_DELETE_RATE"
113
+ CODE_BLOCK_DELETE_REPEAT = "BLOCK_DELETE_REPEAT"
114
+ CODE_BLOCK_DELETE_BATCH_CONFIRM = "BLOCK_DELETE_BATCH_CONFIRM"
115
+ CODE_BLOCK_DELETE_STATE_INVALID = "BLOCK_DELETE_STATE_INVALID"
108
116
  # exfil-guard (span decisions). Rule ids (`secret/*`, `path/*`) are payload,
109
117
  # never verdict codes; these codes name the *disposition*, not the pattern.
110
118
  CODE_SANITIZE_SECRET_REDACT = "SANITIZE_SECRET_REDACT"
@@ -122,6 +130,13 @@ CODE_BLOCK_GIT_RESET_COLLISION = "BLOCK_GIT_RESET_COLLISION"
122
130
 
123
131
  # Human-facing one-liners: why the guard cannot just do it (or did do it).
124
132
  EXPLANATIONS: Dict[str, str] = {
133
+ CODE_BLOCK_DELETE_CONFIG_INVALID: "Deletion configuration is invalid or unreadable; repair it before deleting.",
134
+ CODE_BLOCK_DELETE_PROTECTED: "Target overlaps deletion configuration or a configured protected path; deletion is refused.",
135
+ CODE_BLOCK_DELETE_LIMIT: "Deletion would exceed the quarantine capacity or session budget; targets were not admitted.",
136
+ CODE_BLOCK_DELETE_RATE: "This session reached its deletion rate limit; wait for the configured window before retrying.",
137
+ CODE_BLOCK_DELETE_REPEAT: "Repeated deletion of the same target reached the configured limit; inspect the loop before retrying.",
138
+ CODE_BLOCK_DELETE_BATCH_CONFIRM: "This batch requires a reviewed Cleanup Copilot plan and explicit confirmation.",
139
+ CODE_BLOCK_DELETE_STATE_INVALID: "Deletion budget state is invalid or unavailable; no new deletion was admitted.",
125
140
  CODE_ALLOW_NOOP: "No recovery action is needed for the recognized operations. "
126
141
  "Unrecognized command effects have not been checked.",
127
142
  CODE_ALLOW_REGENERABLE: "All targets are git-ignored and match known "
@@ -509,6 +524,26 @@ def decide_path_batch(specs: List[PathSpec], ctx: PolicyContext,
509
524
  [f"protected: {s.protected} ({s.raw})"
510
525
  for s in protected_other[:5]])
511
526
 
527
+ # Preserve the existing outer-boundary reason, including parents of the
528
+ # workspace. Explicit external quarantine housekeeping remains allowed.
529
+ protected_outside = [s for s in specs if s.protected == "outside-workspace"]
530
+ if protected_outside and not all(s.inside_trash for s in specs):
531
+ return Verdict(DECISION_BLOCK, CODE_BLOCK_OUT_OF_WORKSPACE,
532
+ [f"outside workspace boundary: {s.raw}"
533
+ for s in protected_outside[:5]])
534
+
535
+ try:
536
+ deletion_config = delete_config.load_config(ctx.workspace)
537
+ protection = delete_config.protected_reason(
538
+ [s.resolved for s in specs if s.resolved], ctx.workspace,
539
+ deletion_config)
540
+ except delete_config.DeleteConfigError as exc:
541
+ return Verdict(DECISION_BLOCK, CODE_BLOCK_DELETE_CONFIG_INVALID,
542
+ [str(exc)])
543
+ if protection:
544
+ return Verdict(DECISION_BLOCK, CODE_BLOCK_DELETE_PROTECTED,
545
+ [protection])
546
+
512
547
  if specs and all(s.inside_trash for s in specs):
513
548
  if any(s.wildcard for s in specs):
514
549
  return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
@@ -516,13 +551,6 @@ def decide_path_batch(specs: List[PathSpec], ctx: PolicyContext,
516
551
  "enumerate explicitly with safe_delete"])
517
552
  return Verdict(DECISION_ALLOW, CODE_ALLOW_TRASH_GC)
518
553
 
519
- protected_outside = [s for s in specs
520
- if s.protected == "outside-workspace"]
521
- if protected_outside:
522
- return Verdict(DECISION_BLOCK, CODE_BLOCK_OUT_OF_WORKSPACE,
523
- [f"outside workspace boundary: {s.raw}"
524
- for s in protected_outside[:5]])
525
-
526
554
  wild = [s for s in specs if s.wildcard]
527
555
  if wild:
528
556
  return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
package/core/recovery.py CHANGED
@@ -31,6 +31,7 @@ from typing import Any, Dict, List, Optional, Tuple
31
31
  from . import MANIFEST_NAME, TRASH_DIRNAME
32
32
  from .audit import new_txid, utc_now_iso
33
33
  from .classifier import PathSpec, _physical, _physical_keep_final, inside_path
34
+ from . import admission
34
35
 
35
36
  # Soft retention policy (docs/references: GC). Thresholds only MARK entries
36
37
  # GC_ELIGIBLE; actual purging is an explicit maintenance action - a system
@@ -220,6 +221,15 @@ class RecoveryEngine:
220
221
 
221
222
  def relocate(self, specs: List[PathSpec], txid: Optional[str] = None,
222
223
  meta: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
224
+ """Admit one relocation batch before starting its recovery journal."""
225
+ self.ensure_layout()
226
+ paths = [spec.resolved for spec in specs
227
+ if spec.resolved and not spec.wildcard and not spec.indeterminable]
228
+ with admission.admit(self.workspace, self.trash_root, paths):
229
+ return self._relocate_admitted(specs, txid=txid, meta=meta)
230
+
231
+ def _relocate_admitted(self, specs: List[PathSpec], txid: Optional[str] = None,
232
+ meta: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
223
233
  """Move every concrete target into trash/<txid>/<workspace-relative>.
224
234
 
225
235
  Layout arithmetic uses PHYSICAL spellings on BOTH sides: the
package/docs/README.md CHANGED
@@ -7,20 +7,21 @@ setup. The three main paths are [recovery protection](../skills/delete-guard/SKI
7
7
  [harness capability matrix](guides/harness-capabilities.md) for observed coverage
8
8
  and the [architecture](design/architecture.md) for the shared Core.
9
9
 
10
- Stable release line: [0.2.6](releases/release-notes-0.2.6.md), building on
11
- 0.2.5 with Kimi feedback, diagnostics and reviewed host compatibility. The exact
12
- [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.6)
13
- and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.6)
14
- establish publication and npm `latest` availability; 0.2.5 is the previous stable.
10
+ This documentation covers [0.2.7](releases/release-notes-0.2.7.md): Cleanup
11
+ plans, deletion admission and optional local MCP tools. Before installing,
12
+ check the exact [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.7)
13
+ and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.7)
14
+ for availability. A checkout or manifest does not establish publication or
15
+ the current npm `latest` channel.
15
16
  The opt-in `rc` line remains [0.2.5-rc3](releases/release-notes-0.2.5-rc3.md), and `hotfix` is the
16
17
  opt-in [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1)
17
18
  quarantine protection backport. The [getting-started guide](guides/getting-started.md)
18
19
  explains exact-version and local-package installation.
19
20
 
20
- [0.2.6](releases/release-notes-0.2.6.md) covers Kimi Stop feedback,
21
+ The earlier published [0.2.6](releases/release-notes-0.2.6.md) covers Kimi Stop feedback,
21
22
  its doctor checks, Kimi 2.3.0 root-Bash compatibility, DSH Lab preflight
22
23
  diagnostics and alpha.4 default deletion compatibility. Existing 0.2.5 installations
23
- need an upgrade to acquire these additions; see [maintenance details](releases/unreleased.md).
24
+ need an upgrade to acquire those additions; see its [version notes](releases/release-notes-0.2.6.md).
24
25
 
25
26
  先看入门指南,再按恢复保护、外发检测、Lab 验测选择入口。测试报告按所测版本与配置保留;发布记录、
26
27
  历史设计和外部案例各自归档,不能据此扩展当前产品的承诺。
@@ -44,6 +45,9 @@ ALLOW_NOOP 覆盖边界及准确 GC 用法;纳入 0.2.5。
44
45
  |---|---|
45
46
  | [Getting started](guides/getting-started.md) | 安装路径、Agent 接入提示词与最短验证流程 |
46
47
  | [Status and cleanup feedback](guides/recovery-feedback.md) | Python/插件状态、ALLOW_NOOP、保留空间与手动 GC |
48
+ | [Cleanup Copilot](guides/cleanup-plan.md) | 0.2.7:零写入计划、四类候选、大小与显式确认执行 |
49
+ | [Deletion limits](guides/deletion-limits.md) | 0.2.7:隔离容量、会话预算、频率、保护路径与批量确认 |
50
+ | [Local MCP tools](guides/mcp.md) | 0.2.7本地stdio:安全删除、普通恢复、事务/状态和GC预览;不替代hook |
47
51
  | [Harness capabilities](guides/harness-capabilities.md) | 当前接入范围、证据等级与未验证路径 |
48
52
  | [Host drift](guides/host-drift.md) | 宿主版本、配置与本地基线检查 |
49
53
  | [Trash locations](guides/trash-index.md) | 0.2.4 的只读位置查询、Agent/前端共享 JSON 契约 |
@@ -121,8 +125,9 @@ coverage rather than treating every historical result as current acceptance.
121
125
 
122
126
  | Document / 文档 | Scope / 范围 |
123
127
  |---|---|
128
+ | [0.2.7](releases/release-notes-0.2.7.md) | Cleanup、删除准入与MCP的版本范围、升级影响和准备阶段验证 |
124
129
  | [0.2.6](releases/release-notes-0.2.6.md) | 正式版范围、升级影响与验收;Kimi 反馈/doctor、DSH 预检与版本扩展 |
125
- | [0.2.6 maintenance details](releases/unreleased.md) | 原未发布维护页,保留 0.2.6 功能说明与历史验收边界 |
130
+ | [Changes and maintenance details](releases/unreleased.md) | 0.2.7增量及0.2.6维护历史,保留原验收边界 |
126
131
  | [0.2.5](releases/release-notes-0.2.5.md) | 正式版范围;累计 RC 维护、明确反馈与升级影响 |
127
132
  | [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1) | 已发布的稳定线回收站保护回补;不含完整 RC 累计内容 |
128
133
  | [0.2.5-rc3](releases/release-notes-0.2.5-rc3.md) | 已发布的研究/文档预发布版与零模型示例 |
@@ -144,7 +149,7 @@ Current behavior is defined by the Core, Skills and current guides.
144
149
 
145
150
  | Document / 文档 | Scope / 范围 |
146
151
  |---|---|
147
- | [Friction log](history/friction.md) | F1–F20 实现发现与修复经验 |
152
+ | [Friction log](history/friction.md) | F1–F34 实现发现与修复经验 |
148
153
  | [Unguarded deletion note](history/development-note-unguarded-deletion.md) | 去标识化事故探索与恢复方向 |
149
154
  | [Secret Guard analysis](history/secret-guard-analysis.md) | 实现前的需求分析 |
150
155
  | [Secret Guard design](history/secret-guard-design.md) | 早期设计候选与原范围 |
@@ -305,19 +305,26 @@ order of value:
305
305
 
306
306
  ## Delivery status and design directions
307
307
 
308
- The stable release line is 0.2.6. Previous stable 0.2.5, opt-in
309
- 0.2.4-hotfix.1 and prerelease 0.2.5-rc3 retain their separate artifacts.
308
+ This document covers version [0.2.7](../releases/release-notes-0.2.7.md), which
309
+ adds reviewed Cleanup plans, shared deletion admission and optional local
310
+ MCP tools. Confirm availability through the exact GitHub release and npm
311
+ version links in those notes; a source version does not establish publication.
312
+ Earlier stable 0.2.6/0.2.5, opt-in 0.2.4-hotfix.1 and prerelease 0.2.5-rc3
313
+ retain their separate artifacts and evidence.
310
314
  Version 0.2.5 retains RC recovery, shared audit,
311
315
  observer maintenance and [defensive research](../research/README.md), plus
312
316
  clearer local startup/status and retained-storage feedback. Private research
313
317
  methods do not add a general authorization service or production enforcement
314
- point. Deletion rules and execution routes retain their RC behavior.
315
- See [release notes](../releases/release-notes-0.2.6.md) and
318
+ point. Those historical versions retain their RC deletion rules and execution routes.
319
+ See [release notes](../releases/release-notes-0.2.7.md) and
316
320
  [compatibility](compatibility.md) for behaviour and validation boundaries.
317
321
  Release [0.2.6](../releases/release-notes-0.2.6.md) adds
318
322
  optional Kimi Stop feedback, its doctor checks and Lab preflight diagnostics.
319
323
  It also adds reviewed DSH alpha.4 default deletion and Kimi 2.3.0 Bash compatibility.
320
- Core policy is unchanged; scope and delivery limits are tracked in the
324
+ That 0.2.6 maintenance did not change Core policy. Version 0.2.7 adds the
325
+ bounded deletion-admission rules and upgrade-visible refusals recorded in
326
+ the [compatibility contract](compatibility.md#027-bounded-maintainer-selected-exception).
327
+ Historical scope and delivery limits remain in the
321
328
  [maintenance details](../releases/unreleased.md).
322
329
 
323
330
  The milestones below describe historical delivery and future design scope,