@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.
- package/README.md +45 -20
- package/README.zh-CN.md +39 -19
- package/adapters/INTEGRATION.md +6 -0
- package/adapters/mcp/__init__.py +1 -0
- package/adapters/mcp/doctor.py +325 -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 +35 -14
- package/docs/design/architecture.md +42 -16
- package/docs/design/compatibility.md +246 -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 +26 -12
- package/docs/guides/harness-capabilities.md +29 -4
- package/docs/guides/mcp.md +420 -0
- package/docs/history/friction.md +99 -1
- package/docs/releases/release-notes-0.2.7.md +217 -0
- package/docs/releases/release-notes-0.2.8.md +172 -0
- package/docs/releases/unreleased.md +182 -5
- package/docs/reports/test-report-dsh-paired-lab.md +1 -1
- package/docs/reports/test-report-kimi-code-block.md +1 -1
- package/doctor.py +25 -1
- package/live_sentinel.py +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
package/doctor.py
CHANGED
|
@@ -17,6 +17,8 @@ import sys
|
|
|
17
17
|
import tempfile
|
|
18
18
|
from typing import Any, Optional
|
|
19
19
|
|
|
20
|
+
sys.dont_write_bytecode = True
|
|
21
|
+
|
|
20
22
|
from core.dialects import resolve_dialect
|
|
21
23
|
|
|
22
24
|
|
|
@@ -747,7 +749,7 @@ def check_claude(config_path: Path, run_probe: bool = False) -> list[str]:
|
|
|
747
749
|
return _diagnose("claude", config_path, run_probe).problems
|
|
748
750
|
|
|
749
751
|
|
|
750
|
-
def main(argv: Optional[list[str]] = None) -> int:
|
|
752
|
+
def main(argv: Optional[list[str]] = None, *, _include_mcp=True) -> int:
|
|
751
753
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
752
754
|
subcommands = parser.add_subparsers(dest="harness", required=True)
|
|
753
755
|
kimi = subcommands.add_parser("kimi", help="check the local Kimi hook")
|
|
@@ -756,6 +758,15 @@ def main(argv: Optional[list[str]] = None) -> int:
|
|
|
756
758
|
claude = subcommands.add_parser("claude", help="check a selected Claude settings file")
|
|
757
759
|
claude.add_argument(
|
|
758
760
|
"--config", help="Claude settings.json (defaults to .claude/settings.json in cwd)")
|
|
761
|
+
if _include_mcp:
|
|
762
|
+
mcp = subcommands.add_parser("mcp", help="diagnose an explicit local MCP server (no model call)")
|
|
763
|
+
mcp.add_argument("--python", default=sys.executable,
|
|
764
|
+
help="Python in the optional MCP SDK environment (default: current interpreter)")
|
|
765
|
+
mcp.add_argument("--workspace", required=True, help="existing workspace bound to the server")
|
|
766
|
+
mcp.add_argument("--server", help="trusted server.py path (default: this package's MCP server)")
|
|
767
|
+
mcp.add_argument("--timeout", type=int, default=30, metavar="SECONDS",
|
|
768
|
+
help="total diagnosis deadline, 5..120 seconds (default: 30)")
|
|
769
|
+
mcp.add_argument("--json", action="store_true", help="print the independent MCP diagnosis report")
|
|
759
770
|
for command in (kimi, claude):
|
|
760
771
|
command.add_argument(
|
|
761
772
|
"--probe", action="store_true",
|
|
@@ -791,6 +802,19 @@ def main(argv: Optional[list[str]] = None) -> int:
|
|
|
791
802
|
help="live sentinel timeout, 15..600 seconds (default: 180)",
|
|
792
803
|
)
|
|
793
804
|
args = parser.parse_args(argv)
|
|
805
|
+
if args.harness == "mcp":
|
|
806
|
+
if not args.python or "\0" in args.python:
|
|
807
|
+
parser.error("--python must name a nonempty interpreter")
|
|
808
|
+
if not 5 <= args.timeout <= 120:
|
|
809
|
+
parser.error("--timeout must be from 5 to 120 seconds")
|
|
810
|
+
from adapters.mcp.doctor import diagnose, render
|
|
811
|
+
|
|
812
|
+
report = diagnose(args.python, args.workspace, server=args.server, timeout=args.timeout)
|
|
813
|
+
if args.json:
|
|
814
|
+
print(json.dumps(report, ensure_ascii=False))
|
|
815
|
+
else:
|
|
816
|
+
print(render(report), end="")
|
|
817
|
+
return 0 if report["status"] == "PASS" else 1
|
|
794
818
|
if args.write_baseline is not None and not args.probe:
|
|
795
819
|
parser.error("--write-baseline requires --probe")
|
|
796
820
|
if args.live_sentinel and args.write_baseline is not None:
|
package/live_sentinel.py
CHANGED
|
@@ -332,7 +332,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
|
332
332
|
arguments = list(sys.argv[1:] if argv is None else argv)
|
|
333
333
|
if "--live-sentinel" not in arguments:
|
|
334
334
|
arguments.append("--live-sentinel")
|
|
335
|
-
return doctor_main(arguments)
|
|
335
|
+
return doctor_main(arguments, _include_mcp=False)
|
|
336
336
|
|
|
337
337
|
|
|
338
338
|
if __name__ == "__main__":
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mokuyoaxis/agent-guard",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"description": "Harness-neutral reliability infrastructure for AI coding agents: recoverable destructive actions, disclosure checks, controlled synthetic behaviour experiments, and a shared Core with optional native adapters.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -25,6 +25,8 @@
|
|
|
25
25
|
"agent-guard-lab": "./guard_lab.py",
|
|
26
26
|
"agent-guard-check": "./skills/delete-guard/scripts/check.py",
|
|
27
27
|
"agent-guard-safe-delete": "./skills/delete-guard/scripts/safe_delete.py",
|
|
28
|
+
"agent-guard-cleanup": "./skills/delete-guard/scripts/cleanup.py",
|
|
29
|
+
"agent-guard-mcp": "./adapters/mcp/server.py",
|
|
28
30
|
"agent-guard-restore": "./skills/delete-guard/scripts/restore.py",
|
|
29
31
|
"agent-guard-status": "./skills/delete-guard/scripts/status.py",
|
|
30
32
|
"agent-guard-exfil-check": "./skills/exfil-guard/scripts/check_span.py",
|
|
@@ -10,6 +10,10 @@ description: >-
|
|
|
10
10
|
|
|
11
11
|
# delete-guard
|
|
12
12
|
|
|
13
|
+
Version **0.2.7** adds the Cleanup proposals and deletion admission described
|
|
14
|
+
below; 0.2.6 lacks these additions. See the
|
|
15
|
+
[0.2.7 scope, upgrade impact and exact-version availability checks](../../docs/releases/release-notes-0.2.7.md).
|
|
16
|
+
|
|
13
17
|
You operate inside a workspace where irreversible destruction is not a
|
|
14
18
|
default capability. This skill defines the deletion discipline the guard
|
|
15
19
|
enforces and how to work with it productively. The four pillars:
|
|
@@ -47,6 +51,66 @@ Globs passed to `safe_delete` are expanded explicitly before anything moves.
|
|
|
47
51
|
That is why `safe_delete '*.log'` works while `rm *.log` is blocked: the
|
|
48
52
|
guard refuses opaque target sets, not cleanup work.
|
|
49
53
|
|
|
54
|
+
<a id="cleanup-proposals-027-candidate"></a>
|
|
55
|
+
|
|
56
|
+
## Cleanup proposals (0.2.7)
|
|
57
|
+
|
|
58
|
+
When asked to investigate workspace cleanup, start with a read-only plan:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
python3 /absolute/path/to/agent-guard/skills/delete-guard/scripts/cleanup.py --json
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The planner separates regenerable, explicitly discarded, uncertain and
|
|
65
|
+
protected entries, with sizes, reasons and projected effects. Declare known
|
|
66
|
+
discarded paths with `--discard PATH` and evidence/backup roots with
|
|
67
|
+
`--protect PATH`. Age, ignore status and untracked status alone do not prove
|
|
68
|
+
discardability. `.internal`, Git metadata and recovery boundaries are pruned.
|
|
69
|
+
|
|
70
|
+
Only propose the plan by default. Execution requires `--execute`, the
|
|
71
|
+
reviewed `--plan-id`, exact `--select PATH` entries and a human's terminal
|
|
72
|
+
acknowledgement. Do not answer that prompt on the user's behalf. The tool
|
|
73
|
+
rechecks the plan after confirmation and delegates to existing safe_delete;
|
|
74
|
+
ordinary files retain recovery copies and disk usage. This CLI adds no
|
|
75
|
+
native host tool or human-identity guarantee. See the
|
|
76
|
+
[workflow, effects and limits](../../docs/guides/cleanup-plan.md).
|
|
77
|
+
|
|
78
|
+
<a id="deletion-admission-027-candidate"></a>
|
|
79
|
+
|
|
80
|
+
## Deletion admission (0.2.7)
|
|
81
|
+
|
|
82
|
+
Covered deletion paths now share persistent session byte/entry budgets,
|
|
83
|
+
short-window rate/repeated-target-set limits and quarantine capacity admission.
|
|
84
|
+
The optional workspace `.agent-guard/delete-policy.json` configures limits
|
|
85
|
+
and protected paths; its directory and admission control files are protected.
|
|
86
|
+
Protection wins over artifact and housekeeping exemptions. Missing configuration
|
|
87
|
+
uses defaults; malformed configuration or state blocks new admission.
|
|
88
|
+
|
|
89
|
+
Defaults are 5 GiB/100000 entries for quarantine admission, 1 GiB/10000
|
|
90
|
+
entries per persistent session, 60 operations per 60 seconds, five repeated
|
|
91
|
+
admissions of one target set per window, and batch review above 256 MiB or
|
|
92
|
+
1000 entries. Counts include filesystem entries and logical metadata; these
|
|
93
|
+
limits are not an OS storage quota. Updating the package does not silently
|
|
94
|
+
reset existing counters or replace a drifted doctor baseline.
|
|
95
|
+
|
|
96
|
+
Unnamed CLI processes share a stable budget. Failed admitted operations and
|
|
97
|
+
restores do not refund it. A limit refusal is not permission to change session
|
|
98
|
+
identity, remove state, disguise the delete or purge recovery copies. Inspect
|
|
99
|
+
status and explain the reason. Large batches require the reviewed Cleanup
|
|
100
|
+
workflow; covered automated checks BLOCK rather than creating a new host ASK flow.
|
|
101
|
+
Cleanup's ten-minute, one-use-per-path approval still obeys budgets, capacity
|
|
102
|
+
and protection. No limit automatically triggers permanent deletion or GC.
|
|
103
|
+
Existing compound ASK and Git snapshot paths are outside this new budget;
|
|
104
|
+
normal restore, explicit GC and unprotected quarantine housekeeping retain
|
|
105
|
+
their exemptions. Configuration/control-path protection still applies.
|
|
106
|
+
|
|
107
|
+
After investigation, an operator can explicitly reset the current bucket with
|
|
108
|
+
`status.py --reset-delete-budget`, an interactive terminal and `RESET`.
|
|
109
|
+
Do not supply this acknowledgement on the user's behalf. Reset does not free
|
|
110
|
+
storage or change limits; normal restore and explicit GC remain separate.
|
|
111
|
+
Portable state and TTY remain advisory against same-UID processes. See
|
|
112
|
+
[defaults, accounting and limits](../../docs/guides/deletion-limits.md).
|
|
113
|
+
|
|
50
114
|
## If you run `rm` / destructive git anyway
|
|
51
115
|
|
|
52
116
|
A harness adapter may intercept the command before execution. Verdicts you
|
|
@@ -62,6 +126,10 @@ can receive:
|
|
|
62
126
|
| `BLOCK_OUT_OF_WORKSPACE` / `BLOCK_PROTECTED_PATH` / `BLOCK_PROTECTED_ANCESTOR` | outside boundary, workspace root, `.git`, or a filesystem root (`/`, `/home`, `/usr`, `$HOME`) | do not retry; this is a hard boundary. Ask the human if it is truly needed |
|
|
63
127
|
| `BLOCK_RESTRICTED_MODE` | session is downgraded | only explicit single-file deletes are permitted; ask the human for anything more |
|
|
64
128
|
| `BLOCK_FORCE_PUSH` | remote history destruction | do not retry; escalate to the human |
|
|
129
|
+
| `BLOCK_DELETE_CONFIG_INVALID` / `BLOCK_DELETE_STATE_INVALID` | invalid configuration, state or admission machinery | stop and report; do not remove state to bypass the refusal |
|
|
130
|
+
| `BLOCK_DELETE_PROTECTED` | configured protection or deletion configuration overlap | preserve the target and its protected descendants |
|
|
131
|
+
| `BLOCK_DELETE_LIMIT` / `BLOCK_DELETE_RATE` / `BLOCK_DELETE_REPEAT` | capacity, cumulative budget or short-window limit | inspect status/loop; wait only when the reported window can expire |
|
|
132
|
+
| `BLOCK_DELETE_BATCH_CONFIRM` | large operation or stale/consumed Cleanup approval | propose and review a fresh Cleanup plan |
|
|
65
133
|
|
|
66
134
|
Shape rules on compound commands: a single line that `cd`s anywhere before a
|
|
67
135
|
destructive op (F1), or that creates files (`touch/mkdir/cp/mv/tee`,
|
|
@@ -195,7 +263,7 @@ space and remain subject to its existing explicit GC policy.
|
|
|
195
263
|
See `references/policy.md` for the complete rule table, verdict codes, and
|
|
196
264
|
manifest format.
|
|
197
265
|
|
|
198
|
-
|
|
266
|
+
Restore audit records counts and transaction associations rather
|
|
199
267
|
than duplicate paths/error text. CLI results and recovery manifests still
|
|
200
268
|
contain the exact data needed to inspect and restore; a failed CLI result
|
|
201
269
|
must still be checked against the filesystem and preservation attempts.
|
|
@@ -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"]
|