@mokuyoaxis/agent-guard 0.2.6 → 0.2.8

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 (39) hide show
  1. package/README.md +45 -20
  2. package/README.zh-CN.md +39 -19
  3. package/adapters/INTEGRATION.md +6 -0
  4. package/adapters/mcp/__init__.py +1 -0
  5. package/adapters/mcp/doctor.py +325 -0
  6. package/adapters/mcp/operations.py +174 -0
  7. package/adapters/mcp/requirements.txt +3 -0
  8. package/adapters/mcp/server.py +126 -0
  9. package/core/admission.py +388 -0
  10. package/core/audit.py +1 -1
  11. package/core/classifier.py +2 -1
  12. package/core/cleanup.py +297 -0
  13. package/core/delete_config.py +153 -0
  14. package/core/policy.py +35 -7
  15. package/core/recovery.py +10 -0
  16. package/docs/README.md +35 -14
  17. package/docs/design/architecture.md +42 -16
  18. package/docs/design/compatibility.md +246 -7
  19. package/docs/design/threat-model.md +53 -1
  20. package/docs/guides/cleanup-plan.md +227 -0
  21. package/docs/guides/deletion-limits.md +150 -0
  22. package/docs/guides/getting-started.md +26 -12
  23. package/docs/guides/harness-capabilities.md +29 -4
  24. package/docs/guides/mcp.md +420 -0
  25. package/docs/history/friction.md +99 -1
  26. package/docs/releases/release-notes-0.2.7.md +217 -0
  27. package/docs/releases/release-notes-0.2.8.md +172 -0
  28. package/docs/releases/unreleased.md +182 -5
  29. package/docs/reports/test-report-dsh-paired-lab.md +1 -1
  30. package/docs/reports/test-report-kimi-code-block.md +1 -1
  31. package/doctor.py +25 -1
  32. package/live_sentinel.py +1 -1
  33. package/package.json +3 -1
  34. package/skills/delete-guard/SKILL.md +69 -1
  35. package/skills/delete-guard/references/policy.md +66 -3
  36. package/skills/delete-guard/scripts/check.py +39 -9
  37. package/skills/delete-guard/scripts/cleanup.py +164 -0
  38. package/skills/delete-guard/scripts/safe_delete.py +22 -4
  39. package/skills/delete-guard/scripts/status.py +77 -1
@@ -0,0 +1,388 @@
1
+ """Shared, recoverable deletion admission; no automatic purging or refunds.
2
+
3
+ Limits describe admitted work, not successful deletions or physical disk
4
+ quotas. The portable files and session identity remain advisory to same-UID
5
+ processes. A lock covers measurement, durable debit and the guarded mutation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from contextlib import contextmanager
10
+ from dataclasses import asdict
11
+ import errno
12
+ import hashlib
13
+ import json
14
+ import math
15
+ import os
16
+ import secrets
17
+ import stat
18
+ import time
19
+
20
+ from . import classifier
21
+ from .delete_config import DeleteConfigError, fingerprint, load_config, protected_reason
22
+
23
+
24
+ STATE_NAME = "admission.json"
25
+ LOCK_NAME = "admission.lock"
26
+ MAX_SCAN_ENTRIES = 200_000
27
+ MAX_STATE_BYTES = 8 * 1024 * 1024
28
+ MAX_SESSIONS = 1024
29
+ APPROVAL_SECONDS = 600
30
+
31
+
32
+ class AdmissionDenied(OSError):
33
+ def __init__(self, code, reason):
34
+ super().__init__(code + ": " + reason)
35
+ self.code, self.reason = code, reason
36
+
37
+
38
+ def _digest(value):
39
+ raw = json.dumps(value, ensure_ascii=True, sort_keys=True,
40
+ separators=(",", ":")).encode("ascii")
41
+ return hashlib.sha256(raw).hexdigest()
42
+
43
+
44
+ def _session_key():
45
+ return _digest(os.environ.get("AGENT_GUARD_SESSION") or "<shared-cli-session>")
46
+
47
+
48
+ def _location(path):
49
+ absolute = os.path.normpath(os.path.abspath(path))
50
+ parent, leaf = os.path.split(absolute)
51
+ return os.path.normcase(os.path.join(os.path.realpath(parent), leaf))
52
+
53
+
54
+ def _roots(paths):
55
+ result = []
56
+ for path in sorted({_location(path) for path in paths}, key=lambda p: (len(p), p)):
57
+ if not any(classifier.inside_path(path, parent) for parent in result):
58
+ result.append(path)
59
+ return result
60
+
61
+
62
+ def _signature(info):
63
+ return [info.st_dev, info.st_ino, info.st_mode, info.st_size,
64
+ info.st_mtime_ns, info.st_ctime_ns]
65
+
66
+
67
+ def _measure(paths, *, max_entries=MAX_SCAN_ENTRIES):
68
+ """Bounded lstat inventory; links are entries, never traversal edges."""
69
+ entries, size = 0, 0
70
+ trees = {}
71
+
72
+ def visit(path, depth):
73
+ nonlocal entries, size
74
+ if entries >= max_entries or depth > 128:
75
+ raise OSError("deletion inventory exceeds its scan bound")
76
+ info = os.lstat(path)
77
+ entries += 1
78
+ # Logical lengths, including directory metadata. Hardlinks are
79
+ # deliberately counted per entry; this is a conservative admission.
80
+ size += info.st_size
81
+ children = []
82
+ if stat.S_ISDIR(info.st_mode):
83
+ with os.scandir(path) as listing:
84
+ bounded = []
85
+ for child in listing:
86
+ if len(bounded) >= max_entries - entries:
87
+ raise OSError("deletion inventory exceeds its scan bound")
88
+ bounded.append(child)
89
+ for child in sorted(bounded, key=lambda row: row.name):
90
+ children.append([child.name, visit(child.path, depth + 1)])
91
+ if _signature(os.lstat(path)) != _signature(info):
92
+ raise OSError("deletion source changed during inventory")
93
+ elif not (stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)):
94
+ raise OSError("special filesystem entries require manual review")
95
+ return _digest([_signature(info), children])
96
+
97
+ for path in _roots(paths):
98
+ if os.path.lexists(path):
99
+ trees[_digest(path)] = visit(path, 0)
100
+ return {"entries": entries, "bytes": size,
101
+ "fingerprint": _digest(trees), "trees": trees}
102
+
103
+
104
+ def _config(workspace):
105
+ try:
106
+ return load_config(workspace)
107
+ except DeleteConfigError as exc:
108
+ raise AdmissionDenied("BLOCK_DELETE_CONFIG_INVALID", str(exc)) from exc
109
+
110
+
111
+ def _check_protected(paths, workspace, config):
112
+ reason = protected_reason(paths, workspace, config)
113
+ if reason:
114
+ raise AdmissionDenied("BLOCK_DELETE_PROTECTED", reason)
115
+
116
+
117
+ @contextmanager
118
+ def _locked(trash_root):
119
+ """Portable process lock, with a bounded wait and no third-party module."""
120
+ os.makedirs(trash_root, exist_ok=True)
121
+ path = os.path.join(trash_root, LOCK_NAME)
122
+ if os.path.islink(path):
123
+ raise OSError("deletion admission lock must not be a link")
124
+ fd = os.open(path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
125
+ acquired = False
126
+ try:
127
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
128
+ raise OSError("deletion admission lock must be a regular file")
129
+ if os.name == "nt":
130
+ import msvcrt
131
+ if os.fstat(fd).st_size == 0:
132
+ os.write(fd, b"\0")
133
+
134
+ def lock():
135
+ os.lseek(fd, 0, os.SEEK_SET)
136
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
137
+
138
+ def unlock():
139
+ os.lseek(fd, 0, os.SEEK_SET)
140
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
141
+ else:
142
+ import fcntl
143
+
144
+ def lock():
145
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
146
+
147
+ def unlock():
148
+ fcntl.flock(fd, fcntl.LOCK_UN)
149
+ deadline = time.monotonic() + 10
150
+ while True:
151
+ try:
152
+ lock()
153
+ acquired = True
154
+ break
155
+ except OSError as exc:
156
+ if exc.errno not in (errno.EAGAIN, errno.EACCES, errno.EDEADLK):
157
+ raise
158
+ if time.monotonic() >= deadline:
159
+ raise OSError("deletion admission lock timed out") from exc
160
+ time.sleep(0.05)
161
+ yield
162
+ finally:
163
+ if acquired:
164
+ unlock()
165
+ os.close(fd)
166
+
167
+
168
+ def _unique_object(pairs):
169
+ result = {}
170
+ for key, value in pairs:
171
+ if key in result:
172
+ raise ValueError("duplicate admission state field")
173
+ result[key] = value
174
+ return result
175
+
176
+
177
+ def _load(trash_root):
178
+ path = os.path.join(trash_root, STATE_NAME)
179
+ if not os.path.lexists(path):
180
+ return {"version": 1, "sessions": {}, "approvals": {}}
181
+ if os.path.islink(path) or not os.path.isfile(path):
182
+ raise ValueError("admission state must be a regular file")
183
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
184
+ | getattr(os, "O_NOFOLLOW", 0))
185
+ with os.fdopen(fd, "rb") as handle:
186
+ if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
187
+ raise ValueError("admission state must be a regular file")
188
+ raw = handle.read(MAX_STATE_BYTES + 1)
189
+ if len(raw) > MAX_STATE_BYTES:
190
+ raise ValueError("admission state is too large")
191
+ data = json.loads(raw, object_pairs_hook=_unique_object)
192
+ if (not isinstance(data, dict) or data.get("version") != 1
193
+ or not isinstance(data.get("sessions"), dict)
194
+ or not isinstance(data.get("approvals"), dict)
195
+ or len(data["sessions"]) > MAX_SESSIONS or len(data["approvals"]) > 32):
196
+ raise ValueError("invalid admission state")
197
+ for key, record in data["sessions"].items():
198
+ if not isinstance(key, str) or not isinstance(record, dict):
199
+ raise ValueError("invalid session budget")
200
+ if any(type(record.get(field)) is not int or record[field] < 0
201
+ for field in ("used_bytes", "used_entries")):
202
+ raise ValueError("invalid session counters")
203
+ if not isinstance(record.get("events"), list) or len(record["events"]) > 10_000:
204
+ raise ValueError("invalid admission window")
205
+ for event in record["events"]:
206
+ if (not isinstance(event, dict) or type(event.get("at")) not in (int, float)
207
+ or not math.isfinite(event["at"]) or event["at"] < 0
208
+ or not isinstance(event.get("targets"), str)):
209
+ raise ValueError("invalid admission event")
210
+ for key, record in data["approvals"].items():
211
+ if (not isinstance(key, str) or not isinstance(record, dict)
212
+ or not isinstance(record.get("session"), str)
213
+ or not isinstance(record.get("config"), str)
214
+ or type(record.get("expires")) not in (int, float)
215
+ or not math.isfinite(record["expires"])
216
+ or not isinstance(record.get("paths"), dict)
217
+ or len(record["paths"]) > 10_000
218
+ or any(not isinstance(k, str) or not isinstance(v, str)
219
+ for k, v in record["paths"].items())):
220
+ raise ValueError("invalid cleanup approval")
221
+ return data
222
+
223
+
224
+ def _save(trash_root, state):
225
+ raw = (json.dumps(state, ensure_ascii=True, sort_keys=True) + "\n").encode("ascii")
226
+ if len(raw) > MAX_STATE_BYTES:
227
+ raise OSError("admission state exceeds its storage bound")
228
+ temporary = os.path.join(trash_root, STATE_NAME + ".tmp")
229
+ if os.path.islink(temporary):
230
+ raise OSError("admission temporary state must not be a link")
231
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC
232
+ | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0), 0o600)
233
+ with os.fdopen(fd, "wb") as handle:
234
+ if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
235
+ raise OSError("admission temporary state must be a regular file")
236
+ handle.write(raw)
237
+ handle.flush()
238
+ os.fsync(handle.fileno())
239
+ os.replace(temporary, os.path.join(trash_root, STATE_NAME))
240
+
241
+
242
+ def _empty_session():
243
+ return {"used_bytes": 0, "used_entries": 0, "events": []}
244
+
245
+
246
+ def check_batch(workspace, paths):
247
+ """Read-only combined shell-request preflight, before any compensation."""
248
+ config = _config(workspace)
249
+ paths = _roots(paths)
250
+ _check_protected(paths, workspace, config)
251
+ try:
252
+ measured = _measure(paths)
253
+ except OSError as exc:
254
+ raise AdmissionDenied("BLOCK_DELETE_STATE_INVALID", "cannot safely inventory the deletion batch") from exc
255
+ if (measured["bytes"] > config.batch_max_bytes
256
+ or measured["entries"] > config.batch_max_entries):
257
+ raise AdmissionDenied("BLOCK_DELETE_BATCH_CONFIRM", "large deletion requires a reviewed Cleanup plan and interactive execution confirmation")
258
+ return measured
259
+
260
+
261
+ @contextmanager
262
+ def admit(workspace, trash_root, paths, *, quarantine=True, approval=None):
263
+ """Debit once before yielding; a failed guarded operation is not refunded."""
264
+ config = _config(workspace)
265
+ paths = _roots(paths)
266
+ _check_protected(paths, workspace, config)
267
+ executing = False
268
+ try:
269
+ with _locked(trash_root):
270
+ state = _load(trash_root)
271
+ measured = _measure(paths)
272
+ if not measured["entries"]:
273
+ executing = True
274
+ yield measured
275
+ return
276
+ now, sid = time.time(), _session_key()
277
+ record = state["sessions"].get(sid, _empty_session())
278
+ events = [event for event in record["events"]
279
+ if event["at"] > now - config.rate_window_seconds]
280
+ targets = _digest(paths)
281
+ if len(events) >= min(config.rate_max_operations, 10_000):
282
+ raise AdmissionDenied("BLOCK_DELETE_RATE", "deletion admission rate exceeded; wait for the window to expire")
283
+ if sum(event["targets"] == targets for event in events) >= config.repeat_max_operations:
284
+ raise AdmissionDenied("BLOCK_DELETE_REPEAT", "repeated admission of the same target set; inspect the delete/recreate loop")
285
+ if (record["used_bytes"] + measured["bytes"] > config.session_max_bytes
286
+ or record["used_entries"] + measured["entries"] > config.session_max_entries):
287
+ raise AdmissionDenied("BLOCK_DELETE_LIMIT", "session deletion budget exhausted; inspect status and explicitly reset or adjust policy")
288
+ if sid not in state["sessions"] and len(state["sessions"]) >= MAX_SESSIONS:
289
+ raise AdmissionDenied("BLOCK_DELETE_LIMIT", "session budget inventory is full; operator review is required")
290
+ if quarantine:
291
+ usage = _measure([trash_root])
292
+ if (usage["bytes"] + measured["bytes"] > config.quarantine_max_bytes
293
+ or usage["entries"] + measured["entries"] > config.quarantine_max_entries):
294
+ raise AdmissionDenied("BLOCK_DELETE_LIMIT", "quarantine admission capacity exceeded; inspect existing recovery copies and the explicit GC plan")
295
+ token = approval or os.environ.get("AGENT_GUARD_CLEANUP_APPROVAL")
296
+ authorized = False
297
+ if token:
298
+ grant = state["approvals"].get(_digest(token))
299
+ authorized = bool(grant and grant["expires"] >= now
300
+ and grant["session"] == sid
301
+ and grant["config"] == fingerprint(config)
302
+ and all(grant["paths"].get(key) == value
303
+ for key, value in measured["trees"].items()))
304
+ if not authorized:
305
+ raise AdmissionDenied("BLOCK_DELETE_BATCH_CONFIRM", "cleanup approval expired, changed or already consumed; review a fresh plan")
306
+ if (measured["bytes"] > config.batch_max_bytes
307
+ or measured["entries"] > config.batch_max_entries) and not authorized:
308
+ raise AdmissionDenied("BLOCK_DELETE_BATCH_CONFIRM", "large deletion requires a reviewed Cleanup plan and interactive execution confirmation")
309
+ if authorized:
310
+ for key in measured["trees"]:
311
+ del grant["paths"][key]
312
+ record = {"used_bytes": record["used_bytes"] + measured["bytes"],
313
+ "used_entries": record["used_entries"] + measured["entries"],
314
+ "events": events + [{"at": now, "targets": targets}]}
315
+ state["sessions"][sid] = record
316
+ state["approvals"] = {key: value for key, value in state["approvals"].items()
317
+ if value["expires"] >= now and value["paths"]}
318
+ _save(trash_root, state)
319
+ # Keep the process lock while executing. It does not isolate
320
+ # unrelated filesystem writers or authenticated host approval.
321
+ executing = True
322
+ yield measured
323
+ except AdmissionDenied:
324
+ raise
325
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
326
+ if executing:
327
+ raise
328
+ raise AdmissionDenied("BLOCK_DELETE_STATE_INVALID", "cannot safely measure, lock or persist deletion admission") from exc
329
+
330
+
331
+ def approve_cleanup(workspace, trash_root, paths, plan_id):
332
+ """Called only by Cleanup after its terminal confirmation and rescan."""
333
+ config = _config(workspace)
334
+ paths = _roots(paths)
335
+ _check_protected(paths, workspace, config)
336
+ try:
337
+ with _locked(trash_root):
338
+ state = _load(trash_root)
339
+ measured = _measure(paths)
340
+ now = time.time()
341
+ state["approvals"] = {key: value for key, value in state["approvals"].items()
342
+ if value["expires"] >= now and value["paths"]}
343
+ if len(state["approvals"]) >= 32:
344
+ raise AdmissionDenied("BLOCK_DELETE_LIMIT", "too many outstanding cleanup confirmations")
345
+ token = secrets.token_hex(32)
346
+ state["approvals"][_digest(token)] = {
347
+ "session": _session_key(), "config": fingerprint(config),
348
+ "expires": now + APPROVAL_SECONDS, "paths": measured["trees"],
349
+ "plan_id": plan_id}
350
+ _save(trash_root, state)
351
+ return token
352
+ except AdmissionDenied:
353
+ raise
354
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
355
+ raise AdmissionDenied("BLOCK_DELETE_STATE_INVALID", "cannot persist cleanup confirmation") from exc
356
+
357
+
358
+ def describe(workspace, trash_root):
359
+ """Read-only current-session counters; never creates a lock or state."""
360
+ config = _config(workspace)
361
+ try:
362
+ state = _load(trash_root)
363
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
364
+ raise AdmissionDenied("BLOCK_DELETE_STATE_INVALID", "cannot read deletion admission state") from exc
365
+ record = state["sessions"].get(_session_key(), _empty_session())
366
+ limits = asdict(config)
367
+ limits.pop("protected_paths")
368
+ return {"used_bytes": record["used_bytes"], "used_entries": record["used_entries"],
369
+ "window_operations": sum(event["at"] > time.time() - config.rate_window_seconds
370
+ for event in record["events"]),
371
+ "limits": limits, "config_fingerprint": fingerprint(config),
372
+ "protected_path_count": len(config.protected_paths),
373
+ "accounting": "admitted work; failures and restores do not refund session budget"}
374
+
375
+
376
+ def reset_session(workspace, trash_root):
377
+ """Operator entry point; CLI requires explicit interactive confirmation."""
378
+ _config(workspace)
379
+ try:
380
+ with _locked(trash_root):
381
+ state = _load(trash_root)
382
+ sid = _session_key()
383
+ state["sessions"].pop(sid, None)
384
+ state["approvals"] = {key: value for key, value in state["approvals"].items()
385
+ if value["session"] != sid}
386
+ _save(trash_root, state)
387
+ except (OSError, ValueError, TypeError, RecursionError) as exc:
388
+ raise AdmissionDenied("BLOCK_DELETE_STATE_INVALID", "cannot reset deletion admission state") from exc
package/core/audit.py CHANGED
@@ -66,7 +66,7 @@ def _enums():
66
66
  "event": frozenset({
67
67
  "check", "ask", "decision", "advisory", "intent", "outcome",
68
68
  "enforce-block", "enforce-intent", "enforce-error", "enforce-proceed",
69
- "restore", "gc-intent", "gc",
69
+ "restore", "gc-intent", "gc", "delete-budget-reset",
70
70
  }) | {"exfil-" + decision.lower() for decision in decisions},
71
71
  "decision": decisions, "action": decisions | {"PURGED"},
72
72
  "code": frozenset(policy.EXPLANATIONS),
@@ -262,7 +262,8 @@ def _quarantine_control_path(absolute: str, physical: str,
262
262
  (trash_physical, _physical_keep_final(trash_root)))):
263
263
  return True
264
264
  controls = {MANIFEST_NAME, AUDIT_NAME, STATE_NAME, STATE_NAME + ".tmp",
265
- "sessions"}
265
+ "sessions", "admission.json", "admission.json.tmp",
266
+ "admission.lock"}
266
267
  for candidate in (physical, _physical_keep_final(absolute)):
267
268
  if inside_path(candidate, trash_physical):
268
269
  relative = os.path.relpath(candidate, trash_physical)