@mokuyoaxis/agent-guard 0.2.3 → 0.2.5-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +158 -571
  2. package/README.zh-CN.md +133 -490
  3. package/SECURITY.md +53 -0
  4. package/adapters/INTEGRATION.md +8 -6
  5. package/adapters/claude/README.md +3 -3
  6. package/adapters/claude/harness/README.md +1 -1
  7. package/adapters/codex/harness/README.md +2 -2
  8. package/adapters/dsh/README.md +17 -6
  9. package/adapters/dsh/harness/README.md +8 -8
  10. package/adapters/dsh/harness/guard_lab.py +3 -3
  11. package/adapters/dsh/lib/index.js +1 -1
  12. package/adapters/kimi-code/README.md +7 -7
  13. package/adapters/kimi-code/harness/README.md +3 -3
  14. package/adapters/kimi-code/harness/guard_lab.py +1 -1
  15. package/assets/linux-do-community.svg +19 -0
  16. package/core/__init__.py +1 -1
  17. package/core/classifier.py +66 -17
  18. package/core/policy.py +28 -13
  19. package/core/recovery.py +261 -24
  20. package/core/redaction.py +122 -21
  21. package/core/trash_index.py +193 -0
  22. package/docs/README.md +113 -0
  23. package/docs/{architecture.md → design/architecture.md} +51 -12
  24. package/docs/{compatibility.md → design/compatibility.md} +124 -4
  25. package/docs/{threat-model.md → design/threat-model.md} +10 -8
  26. package/docs/guides/getting-started.md +104 -0
  27. package/docs/{harness-capabilities.md → guides/harness-capabilities.md} +14 -9
  28. package/docs/guides/trash-index.md +106 -0
  29. package/docs/{development-note-unguarded-deletion.md → history/development-note-unguarded-deletion.md} +2 -2
  30. package/docs/{friction.md → history/friction.md} +123 -0
  31. package/docs/{secret-guard-analysis.md → history/secret-guard-analysis.md} +12 -12
  32. package/docs/{secret-guard-architecture.md → history/secret-guard-architecture.md} +2 -2
  33. package/docs/{secret-guard-design.md → history/secret-guard-design.md} +14 -14
  34. package/docs/lab/cases/injection-case-fake-ai-api.md +346 -0
  35. package/docs/{guard-lab.md → lab/guard-lab.md} +15 -13
  36. package/docs/{release-notes-0.2.0-rc1.md → releases/release-notes-0.2.0-rc1.md} +3 -3
  37. package/docs/{release-notes-0.2.0.md → releases/release-notes-0.2.0.md} +5 -5
  38. package/docs/{release-notes-0.2.1.md → releases/release-notes-0.2.1.md} +6 -6
  39. package/docs/{release-notes-0.2.2.md → releases/release-notes-0.2.2.md} +2 -2
  40. package/docs/{release-notes-0.2.3-rc1.md → releases/release-notes-0.2.3-rc1.md} +1 -1
  41. package/docs/{release-notes-0.2.3-rc2.md → releases/release-notes-0.2.3-rc2.md} +9 -9
  42. package/docs/{release-notes-0.2.3.md → releases/release-notes-0.2.3.md} +3 -3
  43. package/docs/releases/release-notes-0.2.4.md +89 -0
  44. package/docs/releases/release-notes-0.2.5-rc1.md +91 -0
  45. package/docs/{test-report-claude-code-harness.md → reports/test-report-claude-code-harness.md} +5 -5
  46. package/docs/reports/test-report-dsh-0.2.4-ptc.md +79 -0
  47. package/docs/{test-report-dsh-guard-lab.md → reports/test-report-dsh-guard-lab.md} +1 -1
  48. package/docs/{test-report-dsh-native-session.md → reports/test-report-dsh-native-session.md} +1 -1
  49. package/docs/{test-report-dsh-paired-lab.md → reports/test-report-dsh-paired-lab.md} +1 -1
  50. package/docs/{test-report-dsh-real-followup.md → reports/test-report-dsh-real-followup.md} +1 -1
  51. package/docs/{test-report-dsh-retry-evidence.md → reports/test-report-dsh-retry-evidence.md} +1 -1
  52. package/docs/{test-report-dsh-v0.1.1.md → reports/test-report-dsh-v0.1.1.md} +4 -4
  53. package/docs/{test-report-kimi-code-block.md → reports/test-report-kimi-code-block.md} +3 -3
  54. package/docs/{test-report-kimi-guard-lab.md → reports/test-report-kimi-guard-lab.md} +3 -3
  55. package/docs/{test-report-release-readiness-0.2.3.md → reports/test-report-release-readiness-0.2.3.md} +1 -1
  56. package/docs/{test-report-workbuddy-windows-core.md → reports/test-report-workbuddy-windows-core.md} +1 -1
  57. package/docs/{test-report-zcode-glm-flash.md → reports/test-report-zcode-glm-flash.md} +2 -2
  58. package/package.json +4 -2
  59. package/skills/delete-guard/SKILL.md +80 -7
  60. package/skills/delete-guard/references/policy.md +104 -8
  61. package/skills/delete-guard/scripts/check.py +22 -0
  62. package/skills/delete-guard/scripts/restore.py +34 -7
  63. package/skills/delete-guard/scripts/safe_delete.py +52 -29
  64. package/skills/delete-guard/scripts/status.py +52 -0
  65. package/skills/exfil-guard/SKILL.md +23 -11
  66. package/skills/exfil-guard/references/channels.md +9 -2
  67. package/skills/exfil-guard/references/rules.md +83 -6
  68. package/skills/exfil-guard/scripts/_payload.py +20 -0
  69. package/skills/exfil-guard/scripts/check_span.py +5 -1
  70. package/skills/exfil-guard/scripts/sanitize.py +6 -3
  71. /package/docs/{host-drift.md → guides/host-drift.md} +0 -0
  72. /package/docs/{publishing-from-ephemeral-environments.md → guides/publishing-from-ephemeral-environments.md} +0 -0
  73. /package/docs/{guard-lab-clean-task.md → lab/tasks/guard-lab-clean-task.md} +0 -0
  74. /package/docs/{guard-lab-read-trial-task.md → lab/tasks/guard-lab-read-trial-task.md} +0 -0
  75. /package/docs/{guard-lab-trial-task.md → lab/tasks/guard-lab-trial-task.md} +0 -0
  76. /package/docs/{test-report-codex-gpt-5.6-sol.md → reports/test-report-codex-gpt-5.6-sol.md} +0 -0
  77. /package/docs/{test-report-codex-gpt-6-astra-high.md → reports/test-report-codex-gpt-6-astra-high.md} +0 -0
  78. /package/docs/{test-report-dsh-0.1.5-rc.1.md → reports/test-report-dsh-0.1.5-rc.1.md} +0 -0
  79. /package/docs/{test-report-dsh-0.2-upgrade.md → reports/test-report-dsh-0.2-upgrade.md} +0 -0
  80. /package/docs/{test-report-dsh-read-redaction.md → reports/test-report-dsh-read-redaction.md} +0 -0
@@ -8,7 +8,7 @@ found a quiet guard-off baseline and therefore did not run a new guarded pair.
8
8
 
9
9
  ## Recorded real-model pair
10
10
 
11
- The [Lab documentation](guard-lab.md#bounded-kimi-reference-trial) records one
11
+ The [Lab documentation](../lab/guard-lab.md#bounded-kimi-reference-trial) records one
12
12
  2026-09-28 matched pair with Kimi Code CLI 2.1.1 and the user-declared public
13
13
  label `Kimi official OAuth model`. Both runs used the same task SHA-256:
14
14
 
@@ -61,7 +61,7 @@ private endpoint details are not copied into this report.
61
61
 
62
62
  ## Repeatable capture helper and ordered repeat — 2026-09-30
63
63
 
64
- The [Kimi capture helper](../adapters/kimi-code/harness/README.md) now pins
64
+ The [Kimi capture helper](../../adapters/kimi-code/harness/README.md) now pins
65
65
  2.1.1, uses prompt mode with `stream-json`, derives matched private homes,
66
66
  checks non-Guard configuration equality, and separates assistant/tool/meta
67
67
  records before scanning. Empty/header-only, unknown, failed, timed-out,
@@ -113,5 +113,5 @@ The existing native adapter covers `Bash`, and Core `ASK` is mapped to refusal
113
113
  because the verified host contract cannot enforce it as approval. Missing,
114
114
  skipped, unspawned, or timed-out hooks, general file reads, background host
115
115
  collection, external receipt, and same-UID tampering retain the
116
- [adapter limitations](../adapters/kimi-code/README.md). Neither the historical
116
+ [adapter limitations](../../adapters/kimi-code/README.md). Neither the historical
117
117
  pair nor a current doctor pass establishes universal protection.
@@ -157,7 +157,7 @@ Follow the existing candidate sequence: review the exact diff, obtain
157
157
  authorization to commit/push rc2, run CI for that exact source, then prepare
158
158
  the approved `0.2.3` manifest/tests/README versions and validate its final
159
159
  artifact before authorizing the stable tag workflow. A
160
- [stable release-note draft](release-notes-0.2.3.md) is ready for that step.
160
+ [stable release-note draft](../releases/release-notes-0.2.3.md) is ready for that step.
161
161
  Remote publication is not authorized by this review.
162
162
 
163
163
  ## Stable preparation — 2026-10-03
@@ -29,7 +29,7 @@ The same report observed working quarantine relocation, manifest and audit
29
29
  records, and restoration with content intact. The resulting
30
30
  [Windows Core CI job](https://github.com/mokuyoaxis/agent-guard/blob/main/.github/workflows/ci.yml) covers selected dialect,
31
31
  CLI, relocation/restore and exact-byte redaction regressions on Windows.
32
- See the [rc1 notes](release-notes-0.2.3-rc1.md) for the fix scope.
32
+ See the [rc1 notes](../releases/release-notes-0.2.3-rc1.md) for the fix scope.
33
33
 
34
34
  ## Withdrawn redaction finding
35
35
 
@@ -218,11 +218,11 @@ predict — the audit trail (`compensations: []`) made the outcome verifiable.
218
218
 
219
219
  ## Relationship to prior history
220
220
 
221
- - **Codex `gpt-5.6-sol` evaluation** (`docs/test-report-codex-gpt-5.6-sol.md`):
221
+ - **Codex `gpt-5.6-sol` evaluation** (`docs/reports/test-report-codex-gpt-5.6-sol.md`):
222
222
  the fail-closed compensation contract exercised here (`COMPENSATION_FAILED`
223
223
  on empty-repo `git reset --hard`) is the P0-3 remediation that report
224
224
  pinned; it held on Windows.
225
- - **DSH v0.1.1 report** (`docs/test-report-dsh-v0.1.1.md`): same decision
225
+ - **DSH v0.1.1 report** (`docs/reports/test-report-dsh-v0.1.1.md`): same decision
226
226
  matrix methodology; its "Remaining matrix expansion" item "other harness
227
227
  live sessions" is advanced to a second harness family (ZCode) and a second
228
228
  model family (GLM Flash), on a third platform (win32/POSIX shell).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mokuyoaxis/agent-guard",
3
- "version": "0.2.3",
4
- "description": "Harness-neutral reliability infrastructure for AI coding agents: reversible destructive actions, pre-emission redaction, recovery evidence, and a shared Decision Protocol with optional native adapters.",
3
+ "version": "0.2.5-rc1",
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
  "main": "./adapters/dsh/lib/index.js",
7
7
  "exports": {
@@ -32,11 +32,13 @@
32
32
  "core",
33
33
  "skills",
34
34
  "docs",
35
+ "assets",
35
36
  "doctor.py",
36
37
  "live_sentinel.py",
37
38
  "guard_lab.py",
38
39
  "LICENSE",
39
40
  "CONTRIBUTING.md",
41
+ "SECURITY.md",
40
42
  "README.md",
41
43
  "README.zh-CN.md",
42
44
  "!**/__pycache__/**",
@@ -16,19 +16,22 @@ enforces and how to work with it productively. The four pillars:
16
16
 
17
17
  - **Scope** - you act inside the workspace; the workspace root, `.git`, and
18
18
  everything outside are never yours to delete.
19
- - **Recoverability** - deletions are compensated (relocated to `.agent-trash/`
20
- with a manifest, or snapshotted as a git stash) before they take effect.
19
+ - **Recoverability** - supported valuable deletions relocate to the selected
20
+ quarantine with a manifest; supported Git overwrites snapshot tracked state.
21
+ Provably regenerable, ignored artifacts may be deleted directly.
21
22
  - **Authorization** - a human decides permission boundaries. You can be
22
23
  *downgraded* to RESTRICTED mode; you can never promote yourself back.
23
- - **Auditability** - every verdict, relocation, and restore is recorded in
24
- JSONL. Nothing is invisible.
24
+ - **Auditability** - supported writers record decision/recovery metadata in
25
+ JSONL according to their CLI contract. Mutation intents must be durable;
26
+ assessment/blocked audit may be best effort, and early no-op paths may not
27
+ write an audit. Calls outside the covered path are not automatically visible.
25
28
 
26
29
  ## The one rule
27
30
 
28
31
  **Prefer `safe_delete` over `rm`.** It applies the guard's recovery policy.
29
32
 
30
33
  ```bash
31
- # delete files/dirs/globs - they are quarantined, not destroyed:
34
+ # delete explicit targets; valuable content is quarantined:
32
35
  python3 <repo>/skills/delete-guard/scripts/safe_delete.py src/old_module.py
33
36
  python3 <repo>/skills/delete-guard/scripts/safe_delete.py 'build/**/*.tmp' --reason "stale build output"
34
37
 
@@ -64,8 +67,17 @@ redirections) before destroying them (F2), is refused as undeterminable.
64
67
  Run deletions as standalone commands with an explicit workdir.
65
68
 
66
69
  A block is not an error to route around. Retrying the same operation in a
67
- disguised form (`/bin/rm`, `python -c`, a script) is a violation of the
68
- authorization pillar and is recorded in the audit log.
70
+ disguised form (`/bin/rm`, `python -c`, a script) violates this discipline and
71
+ can bypass both protection and audit. Do not treat a missing audit as proof
72
+ that no operation occurred.
73
+
74
+ `git reset --hard [commit]` first checks whether its target tree would
75
+ overwrite untracked or ignored content. A tracked-only stash cannot recover
76
+ those paths, so a collision returns `BLOCK_GIT_RESET_COLLISION` without
77
+ moving them or creating a snapshot. Preserve the conflicting content
78
+ separately before retrying. Use a standalone reset without shell wrappers;
79
+ compound commands, submodule effects, unknown options, and stash-relative
80
+ targets are refused as undeterminable. Unrelated untracked files are allowed.
69
81
 
70
82
  ## Compensation preflight and verification
71
83
 
@@ -81,8 +93,54 @@ stop immediately. Inspect both the origin and `.agent-trash/`; never infer
81
93
  that an error means no filesystem change occurred. A durable
82
94
  `relocate-intent` can keep an interrupted relocation discoverable.
83
95
 
96
+ ## Assessment and preflight
97
+
98
+ Advisory `check.py` and `safe_delete.py --dry-run` preserve command targets,
99
+ but may create quarantine/audit metadata and a Git local exclude rule.
100
+ They are not zero-write filesystem checks. Advisory exit 0 means the
101
+ assessment completed; inspect the decision and never execute a BLOCK/ASK
102
+ command merely because the exit was zero. Blocked safe_delete still exits 2
103
+ under dry-run. Audit warnings do not imply that all metadata writes were
104
+ undone. Use only a disposable fixture when verifying this behavior; the
105
+ [policy reference](references/policy.md#assessment-and-dry-run-side-effects)
106
+ defines the no-match, existing-ignore and external-bucket branches.
107
+
108
+ In the 0.2.5-rc1 source candidate, new `safe_delete` audit events record decisions, target counts and established
109
+ recovery IDs/counts rather than target paths or free-form reasons. `--reason`
110
+ is still accepted, but its text is not persisted in audit or transaction
111
+ metadata. Exact recovery paths remain in the CLI result and manifest.
112
+ Historical records and automatic session metadata are unchanged; see the
113
+ [policy reference](references/policy.md#safe_delete-audit-metadata).
114
+
115
+ ## Quarantine location queries
116
+
117
+ When the user asks where quarantines are or how many exist, use the shared
118
+ read-only query with a current-directory or user-selected scope:
119
+
120
+ ```bash
121
+ python3 <repo>/skills/delete-guard/scripts/status.py --trash-index --json
122
+ python3 <repo>/skills/delete-guard/scripts/status.py --trash-index --root <projects> --max-depth 3 --json
123
+ python3 <repo>/skills/delete-guard/scripts/status.py --trash-index --trash <custom-store> --json
124
+ ```
125
+
126
+ Report the scope, candidate count, metadata-identified count and read/budget
127
+ errors. Do not claim that unconfirmed/unreadable locations are absent or that
128
+ the result covers the whole host. Explain that these are bucket locations,
129
+ not file/transaction totals. If you supplement the result yourself, identify
130
+ that source separately. Existing native status tools may show the current
131
+ project only; use the CLI for this indexed query. Location metadata and cached
132
+ JSON are not authorization to purge, and recovery file contents must not be
133
+ read just to answer a location/count question.
134
+
84
135
  ## RESTRICTED mode
85
136
 
137
+ The 0.2.5-rc1 source candidate protects the quarantine root, root manifest,
138
+ audit/state files, state temp file, sessions tree and storage access parents.
139
+ Housekeeping does not override those checks. Use the existing explicit
140
+ `gc.py --execute --txid <id>` entry for a validated, audited transaction purge.
141
+ Ordinary unprotected payload housekeeping retains its existing policy.
142
+ GC plans omit `PURGED` history; they do not delete stored Git stashes.
143
+
86
144
  After a human veto, the session runs with narrowed powers: explicit
87
145
  single-file deletes inside the workspace still work (quarantined as usual);
88
146
  recursive deletes, globs, and destructive git operations are refused. Only a
@@ -104,5 +162,20 @@ overwrite anything that now exists at the origin unless a human passes
104
162
  `--force`. Git snapshots are stored as stashes named `agent-guard:<txid>`;
105
163
  restore applies them and never drops them.
106
164
 
165
+ With human `--force`, an existing occupant is first preserved by the normal
166
+ relocation journal in a separate transaction. The result's optional
167
+ `backup_txids` lists preservation attempts; an ID alone does not prove the
168
+ copy completed. Inspect those IDs with `restore.py list --json` and the
169
+ filesystem after any error. A failed old-version move must not be followed
170
+ by deleting the preserved occupant. Restoring a completed backup transaction
171
+ uses the same `restore.py <txid>` command; if the origin is occupied, the
172
+ usual conflict/force rules apply again. Preserved versions consume quarantine
173
+ space and remain subject to its existing explicit GC policy.
174
+
107
175
  See `references/policy.md` for the complete rule table, verdict codes, and
108
176
  manifest format.
177
+
178
+ The candidate's restore audit records counts and transaction associations rather
179
+ than duplicate paths/error text. CLI results and recovery manifests still
180
+ contain the exact data needed to inspect and restore; a failed CLI result
181
+ must still be checked against the filesystem and preservation attempts.
@@ -1,6 +1,13 @@
1
1
  # delete-guard policy reference (V1)
2
2
 
3
- Platforms: Linux/macOS shells + git. Windows (cmd/PowerShell) is out of V1.
3
+ The shared Core supports POSIX/cmd/PowerShell command facts. Full suites run
4
+ on Linux/macOS; focused Windows Core evidence is available, while complete
5
+ native Windows harness execution remains unverified. POSIX hook bridges have
6
+ their own platform requirements. See the
7
+ [compatibility contract](../../../docs/design/compatibility.md).
8
+
9
+ This reference describes the 0.2.5-rc1 source candidate. The published 0.2.4
10
+ baseline does not include its control-path, GC and audit-writer maintenance.
4
11
 
5
12
  ## Decision Protocol
6
13
 
@@ -25,6 +32,41 @@ RESTRICTED prohibitions) are policy violations and never askable.
25
32
 
26
33
  check.py exit codes: 0 proceed/advisory-ok · 2 blocked · 3 ask · 1 error.
27
34
 
35
+ ### Assessment and dry-run side effects
36
+
37
+ Advisory `check.py` and `safe_delete.py --dry-run` keep command targets
38
+ unchanged. They do not execute the assessed shell text, relocate targets,
39
+ create Git stashes or create recovery transactions. They may still write
40
+ metadata through their existing best-effort audit path:
41
+
42
+ | Invocation | Exit / target behavior | Possible metadata writes |
43
+ |---|---|---|
44
+ | Advisory `check.py`, including ALLOW, ASK or BLOCK | Exit 0 with the actual decision; targets unchanged | Layout initialization and an appended `check` audit |
45
+ | `safe_delete.py --dry-run` with concrete targets, including absent literals | Exit 0 unless BLOCK; targets unchanged | An advisory audit, or a blocked-decision audit |
46
+ | Policy-blocked `safe_delete.py` before compensation, including dry-run | Exit 2; targets unchanged | Best-effort blocked-decision audit |
47
+ | Unmatched-glob-only `safe_delete.py` | Exit 0 before layout/audit setup | None from that invocation |
48
+ | Non-dry-run `safe_delete.py` with an absent literal / ALLOW_NOOP | Exit 0 without mutation or layout setup | None from that invocation |
49
+
50
+ Layout initialization may create the selected quarantine directory and
51
+ `audit.jsonl`. If a quarantine inside a Git workspace is not already ignored,
52
+ it may append an ignore entry to Git's local `info/exclude`, including the
53
+ resolved exclude path of a linked worktree. It does not edit tracked
54
+ `.gitignore`. A preexisting ignore rule or an external bucket avoids that
55
+ exclude write. Repeated checks append audit lines without duplicating the
56
+ exclude rule; recovery manifests and authorization state are not created by
57
+ these assessment paths. Git status may hide metadata that was previously
58
+ untracked, so an unchanged Git status alone does not prove zero writes.
59
+
60
+ If audit/layout setup fails, assessments retain their decision and report
61
+ an audit warning; partial metadata changes may remain. `ensure_layout`
62
+ establishes the Git ignore rule before creating the bucket. Audit failure
63
+ after that step does not roll it back. This best-effort behavior is distinct
64
+ from enforced execution/ASK intents, which must be durable or execution is
65
+ refused. Advisory exit 0 must never be treated as authorization to run a
66
+ BLOCK or ASK command. Failed real compensations can leave partial target
67
+ changes and recovery IDs; this table does not promise rollback for them.
68
+ No general zero-write assessment flag is introduced.
69
+
28
70
  ### Dialects
29
71
 
30
72
  `check.py` lexes the command line for a shell dialect: `--dialect posix`
@@ -46,16 +88,19 @@ different effects (`-wi`, `-c`, `-p`) stays unknown and BLOCKs.
46
88
 
47
89
  ## Rule table (first match wins)
48
90
 
91
+ The quarantine control-path changes below belong to the 0.2.5-rc1 source candidate;
92
+ the published 0.2.4 artifact retains its original housekeeping order.
93
+
49
94
  | # | Condition | Verdict code | Effect |
50
95
  |---|---|---|---|
51
96
  | 1 | dry run / no targets | `ALLOW_NOOP` | proceed unchanged |
52
97
  | 2 | unresolvable targets: shell vars, command substitution, unbalanced quotes, `bash -c` with destructive smell, `find -delete`, `find -exec rm`, stdin-fed (`xargs`) | `BLOCK_UNDETERMINABLE_EFFECT` | refuse - allowing it would forfeit the core guarantee |
53
98
  | 2a | SHAPE F1: destructive op preceded by `cd` in the same command line, target in-workspace and resolvable | `ASK` (`COMPOUND_CWD_DELETE`) | single-execution authorization; splitting the command avoids the prompt. A shape rule describes *compensation* difficulty, never effect scope: if the target set also trips rule 2, 4, 5 or 6, that BLOCK wins (`tests/test_incident_regression.py`) |
54
- | 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; `reset --hard`/force-push exempt (position-independent) |
99
+ | 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 |
55
100
  | 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 `/` |
56
- | 3 | any target inside quarantine (`.agent-trash/`) | `ALLOW_TRASH_GC` | direct delete permitted (housekeeping) |
101
+ | 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 |
102
+ | 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 |
57
103
  | 4 | target outside workspace | `BLOCK_OUT_OF_WORKSPACE` | refuse |
58
- | 5 | target is workspace root or `.git` (any depth) | `BLOCK_PROTECTED_PATH` | refuse |
59
104
  | 6 | any glob target | `BLOCK_WILDCARD` | refuse; use safe_delete which enumerates |
60
105
  | 7 | RESTRICTED mode, git/remote destructive op | `BLOCK_RESTRICTED_MODE` | refuse |
61
106
  | 8 | RESTRICTED mode, fs delete | narrow files only -> `RELOCATE_NARROW`, else `BLOCK_RESTRICTED_MODE` | refuse or quarantine |
@@ -64,7 +109,9 @@ different effects (`-wi`, `-c`, `-p`) stays unknown and BLOCKs.
64
109
  | 11 | supported `git clean -f...` | `RELOCATE_VIA_CLEAN_ENUMERATE` | enumerate via `clean -n`, decode every Git-quoted path, relocate every match, proceed only on full coverage |
65
110
  | 11a | `git clean -ff`, interactive `-i`, or exclude `-e` | `BLOCK_UNDETERMINABLE_EFFECT` | refuse; nested-repository and interactive/exclusion semantics are not safely mirrored |
66
111
  | 11b | supported `git clean -f...` whose target set cannot be enumerated (not a repository, `git` cannot run) | `BLOCK_UNDETERMINABLE_EFFECT` | refuse; the targets exist but their set is unknowable, so nothing was attempted and nothing may be reported as a failed compensation |
67
- | 12 | `git reset --hard`, `git restore <path>`, `git checkout -- <path>` | `SNAPSHOT_GIT_STASH` | `git stash create`+`store` first; any create/store failure blocks |
112
+ | 12 | supported `git reset --hard [commit]` without untracked/ignored collisions, `git restore <path>`, `git checkout -- <path>` | `SNAPSHOT_GIT_STASH` | hard reset first checks its target tree; `git stash create`+`store` then protects tracked modifications; any create/store failure blocks |
113
+ | 12a | hard reset target overlaps untracked/ignored content or quarantine storage | `BLOCK_GIT_RESET_COLLISION` | refuse before compensation; preserve conflicting paths separately before retrying |
114
+ | 12b | hard reset target cannot be resolved/enumerated, has unsupported options or submodule effects, is stash-relative, or uses shell wrappers/compound commands | `BLOCK_UNDETERMINABLE_EFFECT` | refuse before compensation; use a standalone reset with an explicit stable commit |
68
115
  | 13 | all targets git-ignored AND match artifact patterns | `ALLOW_REGENERABLE` | direct delete |
69
116
  | 14 | rooted recursive delete | `RELOCATE_TREE` | quarantine whole tree, proceed |
70
117
  | 15 | named files/dirs | `RELOCATE_PATHS` | quarantine, proceed |
@@ -131,6 +178,44 @@ Soft policy: 30-day retention, 5 GiB cap. Thresholds only MARK transactions
131
178
  `QUARANTINED -> RESTORABLE -> GC_ELIGIBLE -> PURGED`; the audit log itself
132
179
  is never garbage-collected.
133
180
 
181
+ Local maintenance excludes `PURGED` tombstones from active GC inventory and
182
+ age/capacity plans. History remains in the manifest and transaction listing;
183
+ a directory recreated under a purged ID is unmanaged. Failed purges retain
184
+ their prior state and can still be planned. This does not add stash pruning.
185
+
186
+ Restore audit metadata now records `restored_count`, `conflict_count` and
187
+ `error_count` instead of raw path arrays/error bodies. Known `txid`, `force`,
188
+ `ok` and preservation `backup_txids` retain correlation; invalid/unknown input
189
+ IDs use `txid_sha256`. Exact restoration paths and errors remain in the
190
+ recovery journal and CLI result. Historical audit lines are not rewritten;
191
+ automatic session metadata and other generic audit writers are unchanged.
192
+
193
+ ### safe_delete audit metadata
194
+
195
+ New `safe_delete` audit events keep `event`, `tool`, `decision`, `code` and
196
+ `target_count`, plus `phase`/static `outcome` where applicable. Established
197
+ relocation reports add `txid`, `moved_count` and `skipped_count`, including
198
+ partial relocation and storage-failure decisions. `target_count` counts
199
+ classified entries after glob expansion, including absent literals and
200
+ unresolved/rejected entries in a BLOCK assessment; it is not a count of
201
+ existing or deletable files. Unmatched patterns are excluded; duplicate
202
+ input entries remain separate entries.
203
+ `skipped_count` counts the engine's skipped entries, not every target left
204
+ unmoved after a storage failure.
205
+
206
+ Target arrays, policy reason bodies, free-form `--reason` and moved/skipped
207
+ payloads are not copied into these events. `--reason` remains accepted but
208
+ its text is no longer persisted in the audit or `tx-start.meta`. Exact
209
+ origin/trash paths, write-ahead relocation records and failure diagnostics
210
+ stay in the recovery manifest; CLI target/recovery paths and errors stay
211
+ accurate. Those surfaces can still contain sensitive text.
212
+
213
+ Mutation intents remain durable before deletion; assessment and outcome
214
+ audits retain their existing best-effort behavior. Historical audit lines
215
+ and manifest metadata are not rewritten. Automatic `ts`/`session` fields
216
+ and generic `core.audit.append`/`tail` behavior are unchanged; this writer's
217
+ minimization is not a guarantee that every audit field is sanitized.
218
+
134
219
  Authority model: `gc.py --execute` is intentionally permitted
135
220
  non-interactively (scheduled maintenance is legitimate; purging
136
221
  already-quarantined evidence is lower-risk than capability escalation,
@@ -154,8 +239,19 @@ model tool.
154
239
 
155
240
  - Command-level interception covers the recognized vocabulary; arbitrary
156
241
  scripts that delete internally are invisible to `check.py` (see
157
- `docs/threat-model.md`).
158
- - `git stash create` captures tracked modifications; untracked files are not
159
- affected by `reset --hard`, so they need no snapshot.
242
+ `docs/design/threat-model.md`).
243
+ - `git stash create` captures tracked modifications only. `reset --hard`
244
+ can delete untracked and ignored content that obstructs its target tree.
245
+ `check.py` checks file/directory/ancestor collisions and refuses them;
246
+ this version does not automatically archive those paths. It also refuses
247
+ target-tree writes into quarantine. Ordinary unrelated untracked files
248
+ remain allowed. Only `--hard`, optional `-q`/`--quiet`, and at most one
249
+ commit are supported; submodules and stash-relative targets are refused.
250
+ - Hard reset must be standalone without shell wrappers: other segments can
251
+ change its revision or create a collision after preflight; wrappers can
252
+ change its Git environment. The preflight and host execution are separate;
253
+ concurrent changes are not atomically excluded.
254
+ Direct callers of `snapshot_git` receive a tracked-only snapshot and must
255
+ run the hard-reset preflight themselves before authorizing that operation.
160
256
  - Windows cmd/PowerShell, databases, cloud resources: future skills
161
257
  (`git-guard`, `database-guard`, `cloud-guard`) on the same core.
@@ -6,6 +6,9 @@
6
6
 
7
7
  Advisory mode (default): prints the verdict and does not mutate command
8
8
  targets. It records the assessment when audit storage is available.
9
+ Audit setup may create the quarantine, append audit.jsonl, and add a Git
10
+ local exclude rule. Advisory exit 0 is not execution authorization; inspect
11
+ the decision. It creates no relocation, snapshot or recovery transaction.
9
12
  --enforce: performs the compensations first (relocate targets / git snapshot
10
13
  / git-clean enumeration+relocation) and tells the caller to PROCEED, or
11
14
  refuses with BLOCKED. Any BLOCK in the line means nothing is executed.
@@ -105,6 +108,25 @@ def main() -> int:
105
108
  specs, parse_error = [], None
106
109
  verdicts = [policy.decide_dialect_failure(resolution)]
107
110
 
111
+ # Preflight every reset before ANY compensation in the line. Advisory
112
+ # and enforced checks agree, and a later unsafe reset cannot leave an
113
+ # earlier filesystem relocation half-applied. Stash create only saves
114
+ # tracked modifications, so it cannot authorize an untracked collision.
115
+ if not policy.worst(verdicts).blocked:
116
+ for index, (spec, verdict) in enumerate(zip(specs, verdicts)):
117
+ if spec.kind != classifier.KIND_GIT_RESET_HARD or \
118
+ verdict.decision != policy.DECISION_SNAPSHOT:
119
+ continue
120
+ collisions, error = engine.preflight_git_reset_hard(
121
+ cwd=base, target=spec.targets[0] if spec.targets else "HEAD")
122
+ if error or collisions:
123
+ verdicts[index] = policy.Verdict(
124
+ policy.DECISION_BLOCK,
125
+ policy.CODE_BLOCK_UNDETERMINABLE_EFFECT if error else
126
+ policy.CODE_BLOCK_GIT_RESET_COLLISION,
127
+ [error or "untracked/ignored or quarantine collision"],
128
+ )
129
+
108
130
  top = policy.worst(verdicts)
109
131
  latency_ms = round((time.monotonic() - started) * 1000, 1)
110
132
  check_id = audit.new_txid()
@@ -5,11 +5,13 @@
5
5
  restore.py TXID [--force] [--json]
6
6
 
7
7
  Restore is non-destructive by default: it refuses to overwrite anything now
8
- occupying an origin path. --force is an explicit human decision.
8
+ occupying an origin path. --force preserves that occupant in a separate
9
+ transaction before restoring. Inspect backup_txids after success or failure.
9
10
  """
10
11
  from __future__ import annotations
11
12
 
12
13
  import argparse
14
+ import hashlib
13
15
  import json
14
16
  import os
15
17
  import sys
@@ -28,6 +30,26 @@ def context():
28
30
  return recovery.RecoveryEngine(workspace, trash_root)
29
31
 
30
32
 
33
+ def restore_audit_event(txid, force, report):
34
+ """Non-recovery metadata only; exact paths/errors stay in the result/journal."""
35
+ event = {
36
+ "event": "restore", "force": force, "ok": report.get("ok"),
37
+ "restored_count": len(report.get("restored", [])),
38
+ "conflict_count": len(report.get("conflicts", [])),
39
+ "error_count": len(report.get("errors", [])) + bool(report.get("error")),
40
+ }
41
+ if report.get("error"):
42
+ # Invalid/unknown caller input is not an established transaction ID.
43
+ # Keep correlation without copying arbitrary input into the audit log.
44
+ event["txid_sha256"] = hashlib.sha256(
45
+ txid.encode("utf-8", errors="surrogatepass")).hexdigest()
46
+ else:
47
+ event["txid"] = txid
48
+ if report.get("backup_txids"):
49
+ event["backup_txids"] = report["backup_txids"]
50
+ return event
51
+
52
+
31
53
  def main() -> int:
32
54
  ap = argparse.ArgumentParser(description=__doc__)
33
55
  sub = ap.add_subparsers(dest="cmd", required=True)
@@ -68,21 +90,26 @@ def main() -> int:
68
90
  return 0
69
91
 
70
92
  report = engine.restore(args.txid, force=args.force)
71
- workspace = engine.workspace
72
- audit.append({"event": "restore", "txid": args.txid, "force": args.force,
73
- "ok": report.get("ok"), "restored": report.get("restored"),
74
- "conflicts": report.get("conflicts"),
75
- "errors": report.get("errors")},
76
- os.path.join(engine.trash_root, AUDIT_NAME))
93
+ event = restore_audit_event(args.txid, args.force, report)
94
+ try:
95
+ audit.append(event, os.path.join(engine.trash_root, AUDIT_NAME))
96
+ except OSError:
97
+ report["ok"] = False
98
+ report.setdefault("errors", []).append(
99
+ "restore audit could not be stored; inspect filesystem state")
77
100
  if args.as_json:
78
101
  print(json.dumps(report, ensure_ascii=False, indent=2))
79
102
  else:
103
+ for txid in report.get("backup_txids", []):
104
+ print(f"current-version preservation transaction: {txid} (inspect state)")
80
105
  for path in report.get("restored", []):
81
106
  print(f"restored: {path}")
82
107
  for path in report.get("conflicts", []):
83
108
  print(f"conflict (exists; use --force): {path}")
84
109
  for err in report.get("errors", []):
85
110
  print(f"error: {err}", file=sys.stderr)
111
+ if report.get("error"):
112
+ print(f"error: {report['error']}", file=sys.stderr)
86
113
  if report.get("errors"):
87
114
  return 1
88
115
  if report.get("conflicts"):
@@ -4,8 +4,13 @@
4
4
  safe_delete.py [--json] [--dry-run] [--reason TEXT] PATH...
5
5
 
6
6
  Globs are expanded here, explicitly, before classification: an opaque
7
- wildcard never reaches the filesystem unexamined. Every verdict is audited.
8
- Blocked requests exit 2 and leave the filesystem untouched.
7
+ wildcard never reaches the filesystem unexamined. Assessments are best-effort
8
+ audited; an unmatched glob returns before audit setup. --dry-run and policy
9
+ refusals before compensation leave command targets unchanged, but may create
10
+ quarantine/audit metadata and a Git local exclude rule. Policy blocks exit 2
11
+ even in dry-run. A failed real compensation can leave partial target changes.
12
+ New audit events contain decisions, counts and recovery IDs, not target paths
13
+ or free-form --reason text. Exact recovery paths stay in the manifest/result.
9
14
  """
10
15
  from __future__ import annotations
11
16
 
@@ -53,12 +58,35 @@ def delete_directly(spec):
53
58
  return "absent"
54
59
 
55
60
 
61
+ def safe_delete_audit_event(event, decision, code, target_count, *,
62
+ phase=None, report=None, outcome=None):
63
+ """Build this writer's metadata; never copy input paths/reasons/errors.
64
+
65
+ Codes and outcome labels come from this CLI. Transaction IDs come from
66
+ the recovery engine; exact moved/skipped payloads stay in its journal
67
+ and the CLI result. Automatic audit session metadata is unchanged.
68
+ """
69
+ entry = {"event": event, "tool": "safe_delete", "decision": decision,
70
+ "code": code, "target_count": target_count}
71
+ if phase is not None:
72
+ entry["phase"] = phase
73
+ if outcome is not None:
74
+ entry["outcome"] = outcome
75
+ if report is not None:
76
+ if report.get("txid"):
77
+ entry["txid"] = report["txid"]
78
+ entry["moved_count"] = len(report.get("moved", []))
79
+ entry["skipped_count"] = len(report.get("skipped", []))
80
+ return entry
81
+
82
+
56
83
  def main() -> int:
57
84
  ap = argparse.ArgumentParser(description=__doc__)
58
85
  ap.add_argument("paths", nargs="+", help="paths or globs to delete")
59
86
  ap.add_argument("--json", action="store_true", dest="as_json")
60
87
  ap.add_argument("--dry-run", action="store_true")
61
- ap.add_argument("--reason", default="", help="why this deletion is needed")
88
+ ap.add_argument("--reason", default="",
89
+ help="why this deletion is needed (text is not persisted)")
62
90
  args = ap.parse_args()
63
91
 
64
92
  base = os.getcwd()
@@ -88,6 +116,7 @@ def main() -> int:
88
116
  return 0
89
117
  verdict = policy.decide_path_batch(specs, ctx, recursive=True)
90
118
  engine = recovery.RecoveryEngine(workspace, trash_root)
119
+ relocation_report = None
91
120
 
92
121
  result = {
93
122
  "tool": "safe_delete",
@@ -119,10 +148,8 @@ def main() -> int:
119
148
  return False
120
149
 
121
150
  if verdict.blocked:
122
- record({"event": "decision", "tool": "safe_delete",
123
- "decision": "BLOCK", "code": verdict.code,
124
- "reasons": verdict.reasons, "targets": result["targets"],
125
- "reason": args.reason})
151
+ record(safe_delete_audit_event(
152
+ "decision", "BLOCK", verdict.code, len(specs)))
126
153
  result["exit"] = 2
127
154
  print(json.dumps(result, ensure_ascii=False, indent=2) if args.as_json
128
155
  else f"BLOCKED [{verdict.code}]: {verdict.reasons}")
@@ -151,16 +178,14 @@ def main() -> int:
151
178
  # Authorization/intent must be durable before direct deletion. Dry-run
152
179
  # assessments are best-effort audited but never fail for audit storage.
153
180
  if args.dry_run:
154
- record({"event": "decision", "tool": "safe_delete",
155
- "decision": verdict.decision, "code": verdict.code,
156
- "targets": result["targets"], "phase": "advisory",
157
- "reason": args.reason})
181
+ record(safe_delete_audit_event(
182
+ "decision", verdict.decision, verdict.code, len(specs),
183
+ phase="advisory"))
158
184
  elif verdict.code != policy.CODE_ALLOW_NOOP:
159
185
  try:
160
- record({"event": "decision", "tool": "safe_delete",
161
- "decision": verdict.decision, "code": verdict.code,
162
- "targets": result["targets"], "phase": "intent",
163
- "reason": args.reason}, required=True)
186
+ record(safe_delete_audit_event(
187
+ "decision", verdict.decision, verdict.code, len(specs),
188
+ phase="intent"), required=True)
164
189
  except Exception as exc:
165
190
  result["verdict"] = {
166
191
  "decision": "BLOCK",
@@ -189,7 +214,8 @@ def main() -> int:
189
214
  result["deleted"] = deleted
190
215
  else: # RELOCATE_*
191
216
  report = engine.relocate(specs, meta={
192
- "tool": "safe_delete", "code": verdict.code, "reason": args.reason})
217
+ "tool": "safe_delete", "code": verdict.code})
218
+ relocation_report = report
193
219
  if report.get("storage_failure"):
194
220
  # Hard principle: capacity limits never downgrade to deletion.
195
221
  result["verdict"] = {
@@ -200,10 +226,9 @@ def main() -> int:
200
226
  }
201
227
  result["outcome"] = "BLOCKED: quarantine cannot accept relocation"
202
228
  result["exit"] = 2
203
- record({"event": "decision", "tool": "safe_delete",
204
- "decision": "BLOCK",
205
- "code": policy.CODE_BLOCK_RELOCATE_FAILED_STORAGE,
206
- "targets": result["targets"], "reason": args.reason})
229
+ record(safe_delete_audit_event(
230
+ "decision", "BLOCK", policy.CODE_BLOCK_RELOCATE_FAILED_STORAGE,
231
+ len(specs), report=report))
207
232
  print(json.dumps(result, ensure_ascii=False, indent=2)
208
233
  if args.as_json else result["outcome"])
209
234
  return 2
@@ -222,11 +247,9 @@ def main() -> int:
222
247
  result["moved"] = report["moved"]
223
248
  result["skipped"] = report["skipped"]
224
249
  result["exit"] = 2
225
- record({"event": "decision", "tool": "safe_delete",
226
- "decision": "BLOCK",
227
- "code": policy.CODE_BLOCK_COMPENSATION_FAILED,
228
- "targets": result["targets"], "txid": report["txid"],
229
- "reason": args.reason})
250
+ record(safe_delete_audit_event(
251
+ "decision", "BLOCK", policy.CODE_BLOCK_COMPENSATION_FAILED,
252
+ len(specs), report=report))
230
253
  print(json.dumps(result, ensure_ascii=False, indent=2)
231
254
  if args.as_json else result["outcome"])
232
255
  return 2
@@ -236,10 +259,10 @@ def main() -> int:
236
259
  result["skipped"] = report["skipped"]
237
260
 
238
261
  if not args.dry_run and verdict.code != policy.CODE_ALLOW_NOOP:
239
- record({"event": "outcome", "tool": "safe_delete",
240
- "targets": result["targets"], "txid": result.get("txid"),
241
- "outcome": result.get("outcome"), "phase": "complete",
242
- "reason": args.reason})
262
+ record(safe_delete_audit_event(
263
+ "outcome", verdict.decision, verdict.code, len(specs),
264
+ phase="complete", report=relocation_report,
265
+ outcome=result.get("outcome")))
243
266
  result["exit"] = 0
244
267
  if args.as_json:
245
268
  print(json.dumps(result, ensure_ascii=False, indent=2))