@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.
- package/README.md +28 -10
- package/README.zh-CN.md +24 -10
- package/adapters/INTEGRATION.md +6 -0
- package/adapters/mcp/__init__.py +1 -0
- package/adapters/mcp/operations.py +174 -0
- package/adapters/mcp/requirements.txt +3 -0
- package/adapters/mcp/server.py +126 -0
- package/core/admission.py +388 -0
- package/core/audit.py +1 -1
- package/core/classifier.py +2 -1
- package/core/cleanup.py +297 -0
- package/core/delete_config.py +153 -0
- package/core/policy.py +35 -7
- package/core/recovery.py +10 -0
- package/docs/README.md +14 -9
- package/docs/design/architecture.md +12 -5
- package/docs/design/compatibility.md +181 -7
- package/docs/design/threat-model.md +53 -1
- package/docs/guides/cleanup-plan.md +227 -0
- package/docs/guides/deletion-limits.md +150 -0
- package/docs/guides/getting-started.md +25 -12
- package/docs/guides/harness-capabilities.md +19 -4
- package/docs/guides/mcp.md +293 -0
- package/docs/history/friction.md +99 -1
- package/docs/releases/release-notes-0.2.7.md +217 -0
- package/docs/releases/unreleased.md +139 -5
- package/docs/reports/test-report-dsh-paired-lab.md +1 -1
- package/docs/reports/test-report-kimi-code-block.md +1 -1
- package/package.json +3 -1
- package/skills/delete-guard/SKILL.md +69 -1
- package/skills/delete-guard/references/policy.md +66 -3
- package/skills/delete-guard/scripts/check.py +39 -9
- package/skills/delete-guard/scripts/cleanup.py +164 -0
- package/skills/delete-guard/scripts/safe_delete.py +22 -4
- package/skills/delete-guard/scripts/status.py +77 -1
|
@@ -6,8 +6,11 @@ native Windows harness execution remains unverified. POSIX hook bridges have
|
|
|
6
6
|
their own platform requirements. See the
|
|
7
7
|
[compatibility contract](../../../docs/design/compatibility.md).
|
|
8
8
|
|
|
9
|
-
This reference covers 0.2.
|
|
10
|
-
maintenance and shared audit metadata projection.
|
|
9
|
+
This reference covers **0.2.7**, retaining the
|
|
10
|
+
0.2.6/0.2.5 and RC1–RC3 maintenance and shared audit metadata projection.
|
|
11
|
+
The admission additions are absent from 0.2.6; see the
|
|
12
|
+
[0.2.7 notes](../../../docs/releases/release-notes-0.2.7.md) for scope and
|
|
13
|
+
exact-version availability checks. The original published
|
|
11
14
|
0.2.4 baseline lacks the RC's control-path, GC and audit-writer maintenance;
|
|
12
15
|
the opt-in 0.2.4-hotfix.1 backports only control-path protection.
|
|
13
16
|
|
|
@@ -108,6 +111,8 @@ the published 0.2.4 artifact retains its original housekeeping order.
|
|
|
108
111
|
| 2b | SHAPE F2: file-creation op (`touch/mkdir/cp/mv/install/ln/tee`, `>`/`>>`) precedes a target-dependent destructive op in the same line | `ASK` (`COMPOUND_CREATE_DELETE`) | single-execution authorization; force-push is refused separately. Hard reset in a compound line is effect-uncertain and BLOCKED before shape rules |
|
|
109
112
|
| 2c | target *is* a filesystem root (`/`, `/home`, `/usr`, `/etc`, `/var`, `/tmp`, `/opt`, `/boot`, `$HOME`, ...) | `BLOCK_PROTECTED_ANCESTOR` | refuse. Matched exactly, so paths *under* these roots keep the ordinary codes; enforced by identity rather than workspace geometry, so it holds even when the workspace is `/` |
|
|
110
113
|
| 5 | workspace root, `.git` metadata, quarantine root/control paths, or an in-workspace parent containing configured storage | `BLOCK_PROTECTED_PATH` | refuse before the housekeeping exemption; root manifest/audit/state, state temp and sessions are control paths |
|
|
114
|
+
| 5a | Since 0.2.7: deletion configuration malformed/unreadable | `BLOCK_DELETE_CONFIG_INVALID` | refuse new deletion before artifact/housekeeping exemptions |
|
|
115
|
+
| 5b | Since 0.2.7: `.agent-guard` or configured protection, including ancestor coverage | `BLOCK_DELETE_PROTECTED` | refuse; lexical and physical locations are protected |
|
|
111
116
|
| 3 | explicit ordinary unprotected payload inside quarantine (`.agent-trash/`) | `ALLOW_TRASH_GC` | opaque globs BLOCK_WILDCARD; safe_delete may enumerate first, and an audited transaction purge uses gc.py --execute |
|
|
112
117
|
| 4 | target outside workspace | `BLOCK_OUT_OF_WORKSPACE` | refuse |
|
|
113
118
|
| 6 | any glob target | `BLOCK_WILDCARD` | refuse; use safe_delete which enumerates |
|
|
@@ -128,6 +133,56 @@ the published 0.2.4 artifact retains its original housekeeping order.
|
|
|
128
133
|
Precedence inside rule groups: `outside-workspace` > `workspace-root` >
|
|
129
134
|
`git-metadata`. RESTRICTED narrows before NORMAL relaxes.
|
|
130
135
|
|
|
136
|
+
<a id="unreleased-execution-admission"></a>
|
|
137
|
+
<a id="027-candidate-execution-admission"></a>
|
|
138
|
+
|
|
139
|
+
### 0.2.7 execution admission
|
|
140
|
+
|
|
141
|
+
The static rule table is followed by shared execution admission on covered
|
|
142
|
+
deletion paths. Missing `.agent-guard/delete-policy.json` uses defaults;
|
|
143
|
+
configuration is not automatically written. Session identity is advisory;
|
|
144
|
+
unnamed subprocesses share one stable bucket. `admission.json`, its temporary
|
|
145
|
+
file and `admission.lock` are protected quarantine controls.
|
|
146
|
+
|
|
147
|
+
| Code | Meaning and operator action |
|
|
148
|
+
|---|---|
|
|
149
|
+
| `BLOCK_DELETE_LIMIT` | Quarantine projection, cumulative session bytes/entries or bounded state inventory is full; inspect status and recovery copies. No automatic purge or permanent-delete fallback |
|
|
150
|
+
| `BLOCK_DELETE_RATE` | Rolling-window operation limit reached; wait for the window after inspecting the caller |
|
|
151
|
+
| `BLOCK_DELETE_REPEAT` | Same normalized target set repeatedly admitted within the window; investigate a delete/recreate loop |
|
|
152
|
+
| `BLOCK_DELETE_BATCH_CONFIRM` | Batch exceeds the threshold or its approval is stale/consumed; review and confirm Cleanup instead of host ASK |
|
|
153
|
+
| `BLOCK_DELETE_STATE_INVALID` | State, cross-process lock, inventory or persistence cannot be used safely; stop and diagnose |
|
|
154
|
+
|
|
155
|
+
Admission charges before mutation under a shared process lock. Failures and
|
|
156
|
+
restores do not refund session bytes/entries; short-window events expire.
|
|
157
|
+
Force-restore occupant preservation requires admission; normal restore and
|
|
158
|
+
explicit transaction GC remain available without a fresh deletion debit.
|
|
159
|
+
Existing unprotected quarantine payload housekeeping also bypasses session,
|
|
160
|
+
rate and batch debits; configuration/control-path protection still applies.
|
|
161
|
+
Compound ASK returns before automated admission; Git SNAPSHOT uses separate
|
|
162
|
+
Git storage. Neither path is newly budgeted by this addition.
|
|
163
|
+
Hook admission cannot prove the later host-side deletion succeeded.
|
|
164
|
+
|
|
165
|
+
The defaults are 5 GiB/100000 quarantine entries, 1 GiB/10000 admitted session
|
|
166
|
+
entries, 60 operations per 60 seconds, 5 repetitions of a target set, and
|
|
167
|
+
batch review above 256 MiB or 1000 entries. Byte accounting includes directory
|
|
168
|
+
metadata and conservatively counts hardlinks per entry, not physical blocks.
|
|
169
|
+
Cleanup confirmation grants ten-minute, session/config/path/metadata-bound
|
|
170
|
+
approval consumed once per path; all other limits still apply. Interactive
|
|
171
|
+
`status.py --reset-delete-budget` plus `RESET` resets only the current bucket
|
|
172
|
+
and its approvals, not capacity. See the complete
|
|
173
|
+
[configuration and accounting guide](../../../docs/guides/deletion-limits.md).
|
|
174
|
+
These additions are absent from published 0.2.6. The guide records three
|
|
175
|
+
1090-case Python/two-Node-group passes, the offline package and real Kimi
|
|
176
|
+
scenarios, with their local platform and host/tool limits. Those measurements
|
|
177
|
+
predate the versioned 0.2.7 preparation checkpoint. Subsequent local validation passed
|
|
178
|
+
1129 Python cases, both Node groups and a 155-file offline package with
|
|
179
|
+
actual installed MCP checks; no new real-model trial was run. See the
|
|
180
|
+
[versioned validation record](../../../docs/releases/release-notes-0.2.7.md#validation-status).
|
|
181
|
+
That 2026-10-29 local checkpoint did not include remote CI or publication.
|
|
182
|
+
The maintainer's bounded 0.2.7 versioning decision and changed existing shapes
|
|
183
|
+
are recorded in the [compatibility contract](../../../docs/design/compatibility.md#027-candidate-bounded-maintainer-selected-exception)
|
|
184
|
+
and [F32–F34](../../../docs/history/friction.md#f32-deletion-admission).
|
|
185
|
+
|
|
131
186
|
## Verdict actions
|
|
132
187
|
|
|
133
188
|
- `ALLOW` - run unchanged.
|
|
@@ -162,13 +217,21 @@ Default artifact patterns: `node_modules dist build out target __pycache__
|
|
|
162
217
|
.cache coverage .next .nuxt .venv venv .pytest_cache .mypy_cache .tox
|
|
163
218
|
.turbo .parcel-cache *.pyc *.pyo *.egg-info`
|
|
164
219
|
|
|
220
|
+
The deletion configuration introduced in 0.2.7 is the separate optional
|
|
221
|
+
`.agent-guard/delete-policy.json`; see [deletion limits](../../../docs/guides/deletion-limits.md).
|
|
222
|
+
`AGENT_GUARD_SESSION` also selects its persistent admission budget. Internal
|
|
223
|
+
Cleanup approval handoff is operation-bound, not a general configuration or
|
|
224
|
+
authority bypass.
|
|
225
|
+
|
|
165
226
|
## Files
|
|
166
227
|
|
|
167
228
|
```
|
|
168
229
|
.agent-trash/
|
|
169
230
|
├── state.json # authorization mode (portable fallback)
|
|
170
231
|
├── manifest.jsonl # tx-start / relocate-intent / relocate / snapshot / restore
|
|
171
|
-
|
|
232
|
+
├── audit.jsonl # decisions, compensation intents, and outcomes
|
|
233
|
+
├── admission.json # since 0.2.7: session admission counters and approvals
|
|
234
|
+
└── admission.lock # since 0.2.7: cross-process admission lock
|
|
172
235
|
```
|
|
173
236
|
|
|
174
237
|
The guard accepts an existing `.gitignore` rule or writes a workspace-local
|
|
@@ -30,7 +30,7 @@ import time
|
|
|
30
30
|
import _bootstrap # noqa: F401
|
|
31
31
|
|
|
32
32
|
from core import AUDIT_NAME, TRASH_DIRNAME
|
|
33
|
-
from core import audit, classifier, dialects, policy, recovery
|
|
33
|
+
from core import admission, audit, classifier, dialects, policy, recovery
|
|
34
34
|
from core.messages import QUARANTINE_NOTICE, gc_guidance, print_gc_guidance
|
|
35
35
|
|
|
36
36
|
|
|
@@ -267,8 +267,32 @@ def main() -> int:
|
|
|
267
267
|
record({"event": "enforce-intent", "code": top.code,
|
|
268
268
|
"command": _REDACTED_COMMAND,
|
|
269
269
|
"guard_latency_ms": latency_ms}, required=True)
|
|
270
|
-
|
|
271
|
-
|
|
270
|
+
enumerated_clean = {}
|
|
271
|
+
batch_paths = []
|
|
272
|
+
for index, (spec, verdict) in enumerate(zip(specs, verdicts)):
|
|
273
|
+
if verdict.code == policy.CODE_RELOCATE_VIA_CLEAN_ENUMERATE:
|
|
274
|
+
paths, err = engine.enumerate_git_clean(
|
|
275
|
+
base, getattr(spec, "extra_flags", []), getattr(spec, "targets", []))
|
|
276
|
+
if err:
|
|
277
|
+
raise EnumerationUnavailable("git clean enumeration failed")
|
|
278
|
+
enumerated_clean[index] = paths
|
|
279
|
+
batch_paths.extend(target.resolved for target in classifier.classify_paths(
|
|
280
|
+
paths, base, workspace, trash_root) if target.resolved)
|
|
281
|
+
elif verdict.code in (policy.CODE_ALLOW_REGENERABLE, policy.CODE_RELOCATE_PATHS,
|
|
282
|
+
policy.CODE_RELOCATE_TREE, policy.CODE_RELOCATE_NARROW):
|
|
283
|
+
batch_paths.extend(target.resolved for target in classifier.classify_paths(
|
|
284
|
+
spec.targets, base, workspace, trash_root) if target.resolved)
|
|
285
|
+
if batch_paths:
|
|
286
|
+
admission.check_batch(workspace, batch_paths)
|
|
287
|
+
for index, (spec, verdict) in enumerate(zip(specs, verdicts)):
|
|
288
|
+
if verdict.code == policy.CODE_ALLOW_REGENERABLE:
|
|
289
|
+
targets = classifier.classify_paths(spec.targets, base, workspace, trash_root)
|
|
290
|
+
# The host performs the physical deletion later. Charge the
|
|
291
|
+
# authorization here; no success or atomic execution claim.
|
|
292
|
+
with admission.admit(workspace, trash_root,
|
|
293
|
+
[target.resolved for target in targets], quarantine=False):
|
|
294
|
+
pass
|
|
295
|
+
elif spec.kind == classifier.KIND_FS_DELETE and \
|
|
272
296
|
verdict.decision == policy.DECISION_RELOCATE:
|
|
273
297
|
target_specs = classifier.classify_paths(
|
|
274
298
|
spec.targets, base, workspace, trash_root)
|
|
@@ -294,12 +318,7 @@ def main() -> int:
|
|
|
294
318
|
raise RuntimeError(
|
|
295
319
|
"relocation did not cover every requested target")
|
|
296
320
|
elif verdict.code == policy.CODE_RELOCATE_VIA_CLEAN_ENUMERATE:
|
|
297
|
-
|
|
298
|
-
paths, err = engine.enumerate_git_clean(
|
|
299
|
-
base, flags, getattr(spec, "targets", []))
|
|
300
|
-
if err:
|
|
301
|
-
raise EnumerationUnavailable(
|
|
302
|
-
f"git clean enumeration failed: {err}")
|
|
321
|
+
paths = enumerated_clean[index]
|
|
303
322
|
target_specs = classifier.classify_paths(
|
|
304
323
|
paths, base, workspace, trash_root)
|
|
305
324
|
txid = audit.new_txid()
|
|
@@ -339,6 +358,17 @@ def main() -> int:
|
|
|
339
358
|
(snap.get("error") or "unknown snapshot failure"))
|
|
340
359
|
compensation.update({"status": "complete",
|
|
341
360
|
"sha": snap["sha"]})
|
|
361
|
+
except admission.AdmissionDenied as exc:
|
|
362
|
+
out["decision"], out["code"] = "BLOCK", exc.code
|
|
363
|
+
out["explanation"], out["reasons"] = policy.EXPLANATIONS[exc.code], [exc.reason]
|
|
364
|
+
# Refusal happened before the rejected transaction's first move.
|
|
365
|
+
# Earlier completed compensations, if any, remain recoverable.
|
|
366
|
+
completed = [item for item in compensations if item.get("status") != "started"]
|
|
367
|
+
if completed:
|
|
368
|
+
out["compensations"] = completed
|
|
369
|
+
record({"event": "enforce-block", "code": exc.code,
|
|
370
|
+
"command": _REDACTED_COMMAND})
|
|
371
|
+
return finish(2)
|
|
342
372
|
except DurableAuditUnavailable:
|
|
343
373
|
return block_for_audit("durable execution audit intent unavailable",
|
|
344
374
|
compensations)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Cleanup Copilot: propose cleanup; explicitly confirm before safe_delete.
|
|
3
|
+
|
|
4
|
+
Default planning performs no workspace writes. Execution requires a reviewed
|
|
5
|
+
plan ID, named selections and interactive terminal acknowledgement. This is
|
|
6
|
+
a local workflow, not a security boundary against a same-UID process.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
# Set before importing project modules: planning must not create bytecode.
|
|
13
|
+
sys.dont_write_bytecode = True
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
import subprocess
|
|
20
|
+
|
|
21
|
+
import _bootstrap # noqa: F401
|
|
22
|
+
|
|
23
|
+
from core import classifier, recovery
|
|
24
|
+
from core.cleanup import DEFAULT_MAX_DEPTH, DEFAULT_MAX_ENTRIES, plan_cleanup, select_entries
|
|
25
|
+
from core.messages import print_gc_guidance
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
LABELS = {"regenerable": "可再生 / regenerable", "discarded": "明确废弃 / discarded",
|
|
29
|
+
"uncertain": "不确定 / uncertain", "protected": "受保护 / protected"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def print_plan(plan, *, stream=None, selected=None):
|
|
33
|
+
stream = stream or sys.stdout
|
|
34
|
+
print("Plan: " + plan["plan_id"], file=stream)
|
|
35
|
+
print("Workspace: " + json.dumps(plan["workspace"], ensure_ascii=True), file=stream)
|
|
36
|
+
print("Complete: " + str(plan["complete"]), file=stream)
|
|
37
|
+
print(plan["size_notice"], file=stream)
|
|
38
|
+
rows = plan["entries"] if selected is None else selected
|
|
39
|
+
for category, label in LABELS.items():
|
|
40
|
+
print("\n" + label + ":", file=stream)
|
|
41
|
+
for row in rows:
|
|
42
|
+
if row["category"] != category:
|
|
43
|
+
continue
|
|
44
|
+
size = "unknown" if row["size_bytes"] is None else str(row["size_bytes"]) + " B"
|
|
45
|
+
print(" " + json.dumps(row["path"], ensure_ascii=True)
|
|
46
|
+
+ " | " + size + " | " + row["effect"] + " | " + row["reason"], file=stream)
|
|
47
|
+
for error in plan["errors"]:
|
|
48
|
+
print("Scan error: " + json.dumps(error), file=stream)
|
|
49
|
+
for warning in plan["warnings"]:
|
|
50
|
+
print("Warning: " + warning, file=stream)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def confirm(plan, selected):
|
|
54
|
+
if not sys.stdin.isatty() or not sys.stderr.isatty():
|
|
55
|
+
raise ValueError("execution requires an interactive terminal; no --yes bypass is provided")
|
|
56
|
+
print_plan(plan, stream=sys.stderr, selected=selected)
|
|
57
|
+
token = "EXECUTE"
|
|
58
|
+
print("\nDelete means permanent removal; quarantine retains recovery copies and disk usage.", file=sys.stderr)
|
|
59
|
+
print("Type " + token + " to execute this selection: ", end="", file=sys.stderr, flush=True)
|
|
60
|
+
return sys.stdin.readline().rstrip("\r\n") == token
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def execute_selection(plan, selected, *, runner=None):
|
|
64
|
+
"""Only called after confirmation and revalidation; stop on first failure."""
|
|
65
|
+
runner = runner or subprocess.run
|
|
66
|
+
reports = []
|
|
67
|
+
env = dict(os.environ, AGENT_GUARD_WORKSPACE=plan["workspace"],
|
|
68
|
+
AGENT_GUARD_TRASH=plan["trash_root"], PYTHONDONTWRITEBYTECODE="1")
|
|
69
|
+
from core.admission import approve_cleanup
|
|
70
|
+
recovery.RecoveryEngine(plan["workspace"], plan["trash_root"]).ensure_layout()
|
|
71
|
+
env["AGENT_GUARD_CLEANUP_APPROVAL"] = approve_cleanup(
|
|
72
|
+
plan["workspace"], plan["trash_root"],
|
|
73
|
+
[os.path.join(plan["workspace"], entry["path"]) for entry in selected], plan["plan_id"])
|
|
74
|
+
script = str(Path(__file__).resolve().with_name("safe_delete.py"))
|
|
75
|
+
for entry in selected:
|
|
76
|
+
# One explicit target per invocation preserves the per-row policy
|
|
77
|
+
# projection instead of mixing regenerable and valuable targets.
|
|
78
|
+
try:
|
|
79
|
+
proc = runner([sys.executable, "-B", script, "--json", "--", "./" + entry["path"]],
|
|
80
|
+
cwd=plan["workspace"], env=env, capture_output=True, text=True)
|
|
81
|
+
except OSError as exc:
|
|
82
|
+
reports.append({"path": entry["path"], "exit": 1,
|
|
83
|
+
"error": "safe_delete could not start: " + str(exc)})
|
|
84
|
+
break
|
|
85
|
+
try:
|
|
86
|
+
report = json.loads(proc.stdout)
|
|
87
|
+
if not isinstance(report, dict):
|
|
88
|
+
raise ValueError("expected a JSON object")
|
|
89
|
+
except ValueError:
|
|
90
|
+
reports.append({"path": entry["path"], "exit": proc.returncode or 1,
|
|
91
|
+
"error": "safe_delete returned no valid JSON object; inspect recovery state before retrying"})
|
|
92
|
+
break
|
|
93
|
+
reports.append({"path": entry["path"], "exit": proc.returncode, "report": report})
|
|
94
|
+
if proc.returncode:
|
|
95
|
+
break
|
|
96
|
+
failed = any(report["exit"] for report in reports)
|
|
97
|
+
return {"tool": "cleanup", "plan_id": plan["plan_id"],
|
|
98
|
+
"outcome": "stopped_after_failure" if failed else "executed",
|
|
99
|
+
"reports": reports, "exit": 2 if failed else 0}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def main(argv=None):
|
|
103
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
104
|
+
parser.add_argument("--root", help="workspace root; defaults to the discovered workspace")
|
|
105
|
+
parser.add_argument("--discard", action="append", default=[], metavar="PATH",
|
|
106
|
+
help="explicitly declare a path/subtree discarded; repeatable")
|
|
107
|
+
parser.add_argument("--protect", action="append", default=[], metavar="PATH",
|
|
108
|
+
help="protect an additional path/subtree; repeatable")
|
|
109
|
+
parser.add_argument("--max-entries", type=int, default=DEFAULT_MAX_ENTRIES)
|
|
110
|
+
parser.add_argument("--max-depth", type=int, default=DEFAULT_MAX_DEPTH)
|
|
111
|
+
parser.add_argument("--json", action="store_true")
|
|
112
|
+
parser.add_argument("--execute", action="store_true")
|
|
113
|
+
parser.add_argument("--plan-id", help="exact ID from the plan being reviewed")
|
|
114
|
+
parser.add_argument("--select", action="append", default=[], metavar="PATH",
|
|
115
|
+
help="select an exact selectable plan entry; repeatable")
|
|
116
|
+
args = parser.parse_args(argv)
|
|
117
|
+
try:
|
|
118
|
+
if not args.execute and (args.select or args.plan_id):
|
|
119
|
+
raise ValueError("--select and --plan-id require --execute")
|
|
120
|
+
if args.execute and not args.plan_id:
|
|
121
|
+
raise ValueError("--execute requires the reviewed --plan-id")
|
|
122
|
+
root = args.root or classifier.discover_workspace(os.getcwd())
|
|
123
|
+
options = dict(discard=args.discard, protect=args.protect,
|
|
124
|
+
max_entries=args.max_entries, max_depth=args.max_depth)
|
|
125
|
+
plan = plan_cleanup(root, **options)
|
|
126
|
+
if not args.execute:
|
|
127
|
+
if args.json:
|
|
128
|
+
print(json.dumps(plan, ensure_ascii=True, indent=2))
|
|
129
|
+
else:
|
|
130
|
+
print_plan(plan)
|
|
131
|
+
print("\nPlanning only. Review selectable entries, then use --execute --plan-id ID --select PATH.")
|
|
132
|
+
return 0 if plan["complete"] else 1
|
|
133
|
+
selected = select_entries(plan, args.select, args.plan_id)
|
|
134
|
+
if not confirm(plan, selected):
|
|
135
|
+
result = {"tool": "cleanup", "plan_id": plan["plan_id"], "outcome": "cancelled", "exit": 0}
|
|
136
|
+
else:
|
|
137
|
+
# Prompting may take time. Recheck membership, metadata, policy,
|
|
138
|
+
# configuration and the workspace before the first mutation.
|
|
139
|
+
fresh = plan_cleanup(root, **options)
|
|
140
|
+
selected = select_entries(fresh, args.select, plan["plan_id"])
|
|
141
|
+
result = execute_selection(fresh, selected)
|
|
142
|
+
if args.json:
|
|
143
|
+
print(json.dumps(result, ensure_ascii=True, indent=2))
|
|
144
|
+
else:
|
|
145
|
+
print(result["outcome"])
|
|
146
|
+
for item in result.get("reports", []):
|
|
147
|
+
report = item.get("report", {})
|
|
148
|
+
print(json.dumps(item["path"]) + ": " + report.get("outcome", item.get("error", "")))
|
|
149
|
+
if report.get("txid"):
|
|
150
|
+
print(" txid=" + report["txid"])
|
|
151
|
+
if report.get("storage_notice"):
|
|
152
|
+
print(report["storage_notice"])
|
|
153
|
+
print_gc_guidance(report["gc"])
|
|
154
|
+
return result["exit"]
|
|
155
|
+
except (ValueError, OSError) as exc:
|
|
156
|
+
if args.json:
|
|
157
|
+
print(json.dumps({"tool": "cleanup", "outcome": "refused", "error": str(exc), "exit": 2}))
|
|
158
|
+
else:
|
|
159
|
+
print("Cleanup refused: " + str(exc), file=sys.stderr)
|
|
160
|
+
return 2
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
sys.exit(main())
|
|
@@ -24,7 +24,7 @@ import sys
|
|
|
24
24
|
import _bootstrap # noqa: F401
|
|
25
25
|
|
|
26
26
|
from core import AUDIT_NAME, TRASH_DIRNAME, audit
|
|
27
|
-
from core import classifier, policy, recovery
|
|
27
|
+
from core import admission, classifier, policy, recovery
|
|
28
28
|
from core.messages import QUARANTINE_NOTICE, gc_guidance, print_gc_guidance
|
|
29
29
|
|
|
30
30
|
|
|
@@ -91,6 +91,16 @@ def print_result(result, as_json):
|
|
|
91
91
|
print_gc_guidance(result["gc"])
|
|
92
92
|
|
|
93
93
|
|
|
94
|
+
def admission_refused(exc, result, record, specs, as_json):
|
|
95
|
+
result["verdict"] = {"decision": "BLOCK", "code": exc.code,
|
|
96
|
+
"explanation": policy.EXPLANATIONS[exc.code],
|
|
97
|
+
"reasons": [exc.reason]}
|
|
98
|
+
result["outcome"], result["exit"] = "BLOCKED: " + exc.reason, 2
|
|
99
|
+
record(safe_delete_audit_event("decision", "BLOCK", exc.code, len(specs)))
|
|
100
|
+
print_result(result, as_json)
|
|
101
|
+
return 2
|
|
102
|
+
|
|
103
|
+
|
|
94
104
|
def main() -> int:
|
|
95
105
|
ap = argparse.ArgumentParser(description=__doc__)
|
|
96
106
|
ap.add_argument("paths", nargs="+", help="paths or globs to delete")
|
|
@@ -216,7 +226,12 @@ def main() -> int:
|
|
|
216
226
|
elif args.dry_run:
|
|
217
227
|
result["outcome"] = f"would {verdict.decision.lower()} ({verdict.code})"
|
|
218
228
|
elif verdict.code == policy.CODE_ALLOW_REGENERABLE:
|
|
219
|
-
|
|
229
|
+
try:
|
|
230
|
+
with admission.admit(workspace, trash_root, [s.resolved for s in specs],
|
|
231
|
+
quarantine=False):
|
|
232
|
+
deleted = [delete_directly(s) for s in specs]
|
|
233
|
+
except admission.AdmissionDenied as exc:
|
|
234
|
+
return admission_refused(exc, result, record, specs, args.as_json)
|
|
220
235
|
result["outcome"] = "deleted directly (provably regenerable)"
|
|
221
236
|
result["deleted"] = deleted
|
|
222
237
|
elif verdict.code == policy.CODE_ALLOW_TRASH_GC:
|
|
@@ -224,8 +239,11 @@ def main() -> int:
|
|
|
224
239
|
result["outcome"] = "deleted directly (quarantine housekeeping)"
|
|
225
240
|
result["deleted"] = deleted
|
|
226
241
|
else: # RELOCATE_*
|
|
227
|
-
|
|
228
|
-
|
|
242
|
+
try:
|
|
243
|
+
report = engine.relocate(specs, meta={
|
|
244
|
+
"tool": "safe_delete", "code": verdict.code})
|
|
245
|
+
except admission.AdmissionDenied as exc:
|
|
246
|
+
return admission_refused(exc, result, record, specs, args.as_json)
|
|
229
247
|
relocation_report = report
|
|
230
248
|
result["txid"] = report["txid"]
|
|
231
249
|
result["moved"] = report["moved"]
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
status.py [--json] [--tail N]
|
|
5
5
|
status.py --trash-index [--root PATH ...] [--trash PATH ...] [--json]
|
|
6
|
+
status.py --reset-delete-budget [--json]
|
|
6
7
|
"""
|
|
7
8
|
from __future__ import annotations
|
|
8
9
|
|
|
@@ -15,7 +16,7 @@ import sys
|
|
|
15
16
|
import _bootstrap # noqa: F401
|
|
16
17
|
|
|
17
18
|
from core import AUDIT_NAME, TRASH_DIRNAME
|
|
18
|
-
from core import audit, classifier, policy, recovery
|
|
19
|
+
from core import admission, audit, classifier, policy, recovery
|
|
19
20
|
from core.messages import (
|
|
20
21
|
HOST_STATUS_NOTICE, QUARANTINE_NOTICE, gc_guidance, print_gc_guidance)
|
|
21
22
|
|
|
@@ -24,6 +25,8 @@ def main() -> int:
|
|
|
24
25
|
ap = argparse.ArgumentParser(description=__doc__)
|
|
25
26
|
ap.add_argument("--json", action="store_true", dest="as_json")
|
|
26
27
|
ap.add_argument("--tail", type=int, default=10)
|
|
28
|
+
ap.add_argument("--reset-delete-budget", action="store_true",
|
|
29
|
+
help="interactively reset this session's deletion budget; preserves recovery copies")
|
|
27
30
|
ap.add_argument("--trash-index", action="store_true",
|
|
28
31
|
help="read-only quarantine locations for agents and future UI")
|
|
29
32
|
ap.add_argument("--root", action="append", default=[],
|
|
@@ -36,6 +39,13 @@ def main() -> int:
|
|
|
36
39
|
help="index directory-entry budget (default 10000)")
|
|
37
40
|
args = ap.parse_args()
|
|
38
41
|
|
|
42
|
+
if args.reset_delete_budget and args.trash_index:
|
|
43
|
+
ap.error("--reset-delete-budget cannot be combined with --trash-index")
|
|
44
|
+
if args.reset_delete_budget and not (sys.stdin.isatty() and sys.stderr.isatty()):
|
|
45
|
+
print("Deletion-budget reset requires interactive stdin and stderr; no state changed.",
|
|
46
|
+
file=sys.stderr)
|
|
47
|
+
return 2
|
|
48
|
+
|
|
39
49
|
base = os.getcwd()
|
|
40
50
|
if args.trash_index:
|
|
41
51
|
from core.trash_index import (
|
|
@@ -82,6 +92,8 @@ def main() -> int:
|
|
|
82
92
|
trash_root = os.environ.get(
|
|
83
93
|
"AGENT_GUARD_TRASH", os.path.join(workspace, TRASH_DIRNAME))
|
|
84
94
|
engine = recovery.RecoveryEngine(workspace, trash_root)
|
|
95
|
+
if args.reset_delete_budget and not reset_delete_budget(workspace, trash_root, engine):
|
|
96
|
+
return 2
|
|
85
97
|
state = policy.load_mode(trash_root)
|
|
86
98
|
# Project display-only identity/time metadata, never authorization state.
|
|
87
99
|
mode_metadata = audit.project({"ts": state["since"], "session": state["set_by"]})
|
|
@@ -104,6 +116,7 @@ def main() -> int:
|
|
|
104
116
|
"mode_set_by": mode_metadata.get("session"),
|
|
105
117
|
"trash_root": trash_root,
|
|
106
118
|
"usage": usage,
|
|
119
|
+
"delete_admission": deletion_admission(workspace, trash_root),
|
|
107
120
|
"retention": {
|
|
108
121
|
"soft_days": plan["retention_days"],
|
|
109
122
|
"soft_limit_bytes": plan["size_limit_bytes"],
|
|
@@ -133,6 +146,19 @@ def main() -> int:
|
|
|
133
146
|
f"{usage['transactions']} transactions "
|
|
134
147
|
f"({usage['restorable_transactions']} restorable)")
|
|
135
148
|
print(f"snapshots : {stash_count} agent-guard stashes")
|
|
149
|
+
deletion = info["delete_admission"]
|
|
150
|
+
if deletion.get("status") == "BLOCKED":
|
|
151
|
+
print(f"deletion : BLOCKED [{deletion['code']}] {deletion['reason']}")
|
|
152
|
+
else:
|
|
153
|
+
limits = deletion["limits"]
|
|
154
|
+
print(f"deletion : admitted {deletion['used_bytes']}/{limits['session_max_bytes']} bytes, "
|
|
155
|
+
f"{deletion['used_entries']}/{limits['session_max_entries']} entries")
|
|
156
|
+
print(f"window : {deletion['window_operations']}/{limits['rate_max_operations']} operations "
|
|
157
|
+
f"in {limits['rate_window_seconds']}s; "
|
|
158
|
+
f"same-target limit {limits['repeat_max_operations']}")
|
|
159
|
+
print(f"capacity : admission limits {limits['quarantine_max_bytes']} bytes / "
|
|
160
|
+
f"{limits['quarantine_max_entries']} entries")
|
|
161
|
+
print(deletion["accounting"])
|
|
136
162
|
ret = info["retention"]
|
|
137
163
|
print(f"retention : soft {ret['soft_days']}d / "
|
|
138
164
|
f"{ret['soft_limit_bytes'] // (1024**3)}GiB; "
|
|
@@ -151,6 +177,56 @@ def main() -> int:
|
|
|
151
177
|
return 0
|
|
152
178
|
|
|
153
179
|
|
|
180
|
+
def deletion_admission(workspace, trash_root):
|
|
181
|
+
"""Expose unusable admission state without hiding recovery/GC guidance."""
|
|
182
|
+
try:
|
|
183
|
+
return admission.describe(workspace, trash_root)
|
|
184
|
+
except admission.AdmissionDenied as exc:
|
|
185
|
+
return {"status": "BLOCKED", "code": exc.code, "reason": exc.reason}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def reset_delete_budget(workspace, trash_root, engine):
|
|
189
|
+
"""Explicit operator reset; durable intent precedes the state mutation."""
|
|
190
|
+
if not (sys.stdin.isatty() and sys.stderr.isatty()):
|
|
191
|
+
print("Deletion-budget reset requires interactive stdin and stderr; no state changed.",
|
|
192
|
+
file=sys.stderr)
|
|
193
|
+
return False
|
|
194
|
+
current = deletion_admission(workspace, trash_root)
|
|
195
|
+
if current.get("status") == "BLOCKED":
|
|
196
|
+
print(f"[{current['code']}] {current['reason']}; no budget reset.", file=sys.stderr)
|
|
197
|
+
return False
|
|
198
|
+
print("Reset this session's admitted deletion bytes, entries and rate window.\n"
|
|
199
|
+
"Quarantine capacity, recovery files and recovery records are retained.\n"
|
|
200
|
+
f"Current admitted work: {current['used_bytes']} bytes / {current['used_entries']} entries.\n"
|
|
201
|
+
"Type RESET to continue: ", end="", file=sys.stderr, flush=True)
|
|
202
|
+
if sys.stdin.readline().rstrip("\r\n") != "RESET":
|
|
203
|
+
print("Cancelled; no state changed.", file=sys.stderr)
|
|
204
|
+
return False
|
|
205
|
+
audit_path = os.path.join(trash_root, AUDIT_NAME)
|
|
206
|
+
check_id = audit.new_txid()
|
|
207
|
+
try:
|
|
208
|
+
engine.ensure_layout()
|
|
209
|
+
audit.append({"event": "delete-budget-reset", "phase": "intent", "check_id": check_id},
|
|
210
|
+
audit_path)
|
|
211
|
+
except OSError:
|
|
212
|
+
print("Budget reset blocked: its audit intent could not be persisted.", file=sys.stderr)
|
|
213
|
+
return False
|
|
214
|
+
try:
|
|
215
|
+
admission.reset_session(workspace, trash_root)
|
|
216
|
+
except admission.AdmissionDenied as exc:
|
|
217
|
+
print(f"[{exc.code}] {exc.reason}; budget reset did not complete.", file=sys.stderr)
|
|
218
|
+
return False
|
|
219
|
+
try:
|
|
220
|
+
audit.append({"event": "delete-budget-reset", "phase": "complete", "check_id": check_id},
|
|
221
|
+
audit_path)
|
|
222
|
+
except OSError:
|
|
223
|
+
print("Session budget was reset, but its completion audit could not be persisted; inspect the intent.",
|
|
224
|
+
file=sys.stderr)
|
|
225
|
+
return False
|
|
226
|
+
print("Session deletion budget reset; recovery data retained.", file=sys.stderr)
|
|
227
|
+
return True
|
|
228
|
+
|
|
229
|
+
|
|
154
230
|
def audit_tail(trash_root, n):
|
|
155
231
|
# core.audit projects both historical field names and values. Status
|
|
156
232
|
# exposes a smaller summary, with no session or compensation details.
|