@mokuyoaxis/agent-guard 0.2.2
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/CONTRIBUTING.md +101 -0
- package/LICENSE +21 -0
- package/README.md +558 -0
- package/README.zh-CN.md +488 -0
- package/adapters/INTEGRATION.md +94 -0
- package/adapters/claude/README.md +141 -0
- package/adapters/claude/compatibility.json +17 -0
- package/adapters/claude/harness/README.md +59 -0
- package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
- package/adapters/claude/harness/run_scenario.sh +79 -0
- package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
- package/adapters/claude/hook_bridge.sh +33 -0
- package/adapters/claude/pre_tool_use.py +264 -0
- package/adapters/claude/settings.example.json +16 -0
- package/adapters/codex/harness/README.md +53 -0
- package/adapters/codex/harness/acceptance.py +226 -0
- package/adapters/dsh/README.md +62 -0
- package/adapters/dsh/cordis.patch.yml +30 -0
- package/adapters/dsh/lib/index.js +500 -0
- package/adapters/kimi-code/README.md +169 -0
- package/adapters/kimi-code/compatibility.json +17 -0
- package/adapters/kimi-code/config.example.toml +26 -0
- package/adapters/kimi-code/hook_bridge.sh +32 -0
- package/adapters/kimi-code/pre_tool_use.py +72 -0
- package/core/__init__.py +47 -0
- package/core/audit.py +86 -0
- package/core/classifier.py +1175 -0
- package/core/dialects.py +898 -0
- package/core/policy.py +817 -0
- package/core/recovery.py +700 -0
- package/core/redaction.py +1096 -0
- package/core/safe_view.py +212 -0
- package/docs/architecture.md +223 -0
- package/docs/compatibility.md +142 -0
- package/docs/development-note-unguarded-deletion.md +187 -0
- package/docs/friction.md +266 -0
- package/docs/harness-capabilities.md +72 -0
- package/docs/host-drift.md +142 -0
- package/docs/publishing-from-ephemeral-environments.md +104 -0
- package/docs/release-notes-0.2.0-rc1.md +46 -0
- package/docs/release-notes-0.2.0.md +72 -0
- package/docs/release-notes-0.2.1.md +78 -0
- package/docs/release-notes-0.2.2.md +120 -0
- package/docs/secret-guard-analysis.md +416 -0
- package/docs/secret-guard-architecture.md +93 -0
- package/docs/secret-guard-design.md +649 -0
- package/docs/test-report-claude-code-harness.md +462 -0
- package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
- package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
- package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
- package/docs/test-report-dsh-v0.1.1.md +126 -0
- package/docs/test-report-kimi-code-block.md +198 -0
- package/docs/test-report-zcode-glm-flash.md +241 -0
- package/docs/threat-model.md +44 -0
- package/doctor.py +756 -0
- package/live_sentinel.py +339 -0
- package/package.json +69 -0
- package/skills/delete-guard/SKILL.md +109 -0
- package/skills/delete-guard/agents/openai.yaml +4 -0
- package/skills/delete-guard/references/policy.md +161 -0
- package/skills/delete-guard/scripts/_bootstrap.py +8 -0
- package/skills/delete-guard/scripts/check.py +370 -0
- package/skills/delete-guard/scripts/gc.py +103 -0
- package/skills/delete-guard/scripts/restore.py +98 -0
- package/skills/delete-guard/scripts/safe_delete.py +256 -0
- package/skills/delete-guard/scripts/status.py +130 -0
- package/skills/exfil-guard/SKILL.md +143 -0
- package/skills/exfil-guard/agents/openai.yaml +4 -0
- package/skills/exfil-guard/references/channels.md +58 -0
- package/skills/exfil-guard/references/rules.md +194 -0
- package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
- package/skills/exfil-guard/scripts/check_span.py +250 -0
- package/skills/exfil-guard/scripts/sanitize.py +155 -0
- package/skills/exfil-guard/scripts/view.py +44 -0
- package/skills/recovery-audit/SKILL.md +283 -0
- package/skills/recovery-audit/agents/openai.yaml +4 -0
- package/skills/recovery-audit/references/evidence-records.md +85 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Read-only, value-free views of explicitly selected config files.
|
|
2
|
+
|
|
3
|
+
This is a cooperative interface, not a filesystem access-control boundary.
|
|
4
|
+
It never follows a target path symlink and never returns scalar values.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import stat
|
|
12
|
+
from contextlib import ExitStack
|
|
13
|
+
from typing import Any, Dict, List
|
|
14
|
+
|
|
15
|
+
from core import redaction
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
MAX_VIEW_BYTES = 256 * 1024
|
|
19
|
+
MAX_VIEW_DEPTH = 16
|
|
20
|
+
MAX_VIEW_NODES = 2048
|
|
21
|
+
_DOTENV_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
|
22
|
+
_DISPLAY_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_.-]{0,63}\Z")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SafeViewError(Exception):
|
|
26
|
+
"""A fixed, input-free diagnostic safe to show to an agent."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, code: str, message: str):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.code = code
|
|
31
|
+
self.message = message
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _components(relative_path: str) -> List[str]:
|
|
35
|
+
if (not relative_path or relative_path.startswith("/") or
|
|
36
|
+
"\\" in relative_path or ":" in relative_path or
|
|
37
|
+
"\x00" in relative_path):
|
|
38
|
+
raise SafeViewError("INVALID_PATH", "use a workspace-relative path")
|
|
39
|
+
parts = relative_path.split("/")
|
|
40
|
+
if any(part in ("", ".", "..") for part in parts):
|
|
41
|
+
raise SafeViewError("INVALID_PATH", "use a workspace-relative path")
|
|
42
|
+
return parts
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _read_regular_file(workspace: str, parts: List[str], max_bytes: int) -> str:
|
|
46
|
+
if (not hasattr(os, "O_NOFOLLOW") or
|
|
47
|
+
not hasattr(os, "O_DIRECTORY") or
|
|
48
|
+
os.open not in os.supports_dir_fd):
|
|
49
|
+
raise SafeViewError("UNSUPPORTED_PLATFORM",
|
|
50
|
+
"safe descriptor-relative reads are unavailable")
|
|
51
|
+
|
|
52
|
+
directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
53
|
+
file_flags = os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0)
|
|
54
|
+
root = os.path.realpath(os.path.abspath(workspace))
|
|
55
|
+
with ExitStack() as stack:
|
|
56
|
+
try:
|
|
57
|
+
parent = os.open(root, directory_flags)
|
|
58
|
+
stack.callback(os.close, parent)
|
|
59
|
+
for part in parts[:-1]:
|
|
60
|
+
parent = os.open(part, directory_flags, dir_fd=parent)
|
|
61
|
+
stack.callback(os.close, parent)
|
|
62
|
+
fd = os.open(parts[-1], file_flags, dir_fd=parent)
|
|
63
|
+
stack.callback(os.close, fd)
|
|
64
|
+
before = os.fstat(fd)
|
|
65
|
+
if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1:
|
|
66
|
+
raise SafeViewError("UNSAFE_FILE",
|
|
67
|
+
"only regular, single-link files are supported")
|
|
68
|
+
if before.st_size > max_bytes:
|
|
69
|
+
raise SafeViewError("FILE_TOO_LARGE", "config file exceeds size limit")
|
|
70
|
+
chunks = []
|
|
71
|
+
total = 0
|
|
72
|
+
while True:
|
|
73
|
+
chunk = os.read(fd, min(65536, max_bytes + 1 - total))
|
|
74
|
+
if not chunk:
|
|
75
|
+
break
|
|
76
|
+
total += len(chunk)
|
|
77
|
+
if total > max_bytes:
|
|
78
|
+
raise SafeViewError("FILE_TOO_LARGE",
|
|
79
|
+
"config file exceeds size limit")
|
|
80
|
+
chunks.append(chunk)
|
|
81
|
+
after = os.fstat(fd)
|
|
82
|
+
if ((before.st_dev, before.st_ino, before.st_size,
|
|
83
|
+
before.st_mtime_ns, before.st_ctime_ns) !=
|
|
84
|
+
(after.st_dev, after.st_ino, after.st_size,
|
|
85
|
+
after.st_mtime_ns, after.st_ctime_ns)):
|
|
86
|
+
raise SafeViewError("FILE_CHANGED", "config changed during read")
|
|
87
|
+
except OSError:
|
|
88
|
+
raise SafeViewError("UNSAFE_FILE",
|
|
89
|
+
"config cannot be opened safely") from None
|
|
90
|
+
try:
|
|
91
|
+
return b"".join(chunks).decode("utf-8")
|
|
92
|
+
except UnicodeDecodeError:
|
|
93
|
+
raise SafeViewError("INVALID_ENCODING", "config is not UTF-8") from None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _safe_key(key: str, workspace: str, index: int) -> str:
|
|
97
|
+
if not _DISPLAY_KEY.fullmatch(key):
|
|
98
|
+
return f"<hidden-key-{index}>"
|
|
99
|
+
scan = redaction.scan_text(key, channel="file-write", workspace=workspace,
|
|
100
|
+
max_bytes=256)
|
|
101
|
+
if not scan.scanned or scan.spans:
|
|
102
|
+
return f"<hidden-key-{index}>"
|
|
103
|
+
return key
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _object_pairs(pairs: List[Any]) -> Dict[str, Any]:
|
|
107
|
+
result = {}
|
|
108
|
+
for key, value in pairs:
|
|
109
|
+
if key in result:
|
|
110
|
+
raise SafeViewError("INVALID_FORMAT", "duplicate JSON key")
|
|
111
|
+
result[key] = value
|
|
112
|
+
return result
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _invalid_constant(_value: str) -> None:
|
|
116
|
+
raise SafeViewError("INVALID_FORMAT", "non-standard JSON number")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _scalar_view(value: Any) -> Dict[str, str]:
|
|
120
|
+
if value is None:
|
|
121
|
+
return {"type": "null", "state": "empty"}
|
|
122
|
+
if isinstance(value, bool):
|
|
123
|
+
kind = "boolean"
|
|
124
|
+
elif isinstance(value, (int, float)):
|
|
125
|
+
kind = "number"
|
|
126
|
+
else:
|
|
127
|
+
kind = "string"
|
|
128
|
+
return {"type": kind,
|
|
129
|
+
"state": "empty" if value == "" else "set"}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _structure(value: Any, workspace: str, depth: int,
|
|
133
|
+
remaining: List[int]) -> Dict[str, Any]:
|
|
134
|
+
remaining[0] -= 1
|
|
135
|
+
if remaining[0] < 0:
|
|
136
|
+
raise SafeViewError("STRUCTURE_TOO_LARGE", "config has too many nodes")
|
|
137
|
+
if depth > MAX_VIEW_DEPTH:
|
|
138
|
+
raise SafeViewError("STRUCTURE_TOO_DEEP", "config is too deeply nested")
|
|
139
|
+
if isinstance(value, dict):
|
|
140
|
+
fields = {}
|
|
141
|
+
for index, (key, item) in enumerate(value.items(), 1):
|
|
142
|
+
name = _safe_key(key, workspace, index)
|
|
143
|
+
fields[name] = _structure(item, workspace, depth + 1, remaining)
|
|
144
|
+
return {"type": "object", "fields": fields}
|
|
145
|
+
if isinstance(value, list):
|
|
146
|
+
return {"type": "array", "items": [
|
|
147
|
+
_structure(item, workspace, depth + 1, remaining)
|
|
148
|
+
for item in value]}
|
|
149
|
+
return _scalar_view(value)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _dotenv_view(text: str, workspace: str) -> Dict[str, Any]:
|
|
153
|
+
fields = {}
|
|
154
|
+
seen = set()
|
|
155
|
+
for line in text.splitlines():
|
|
156
|
+
stripped = line.strip()
|
|
157
|
+
if not stripped or stripped.startswith("#"):
|
|
158
|
+
continue
|
|
159
|
+
if stripped.startswith("export "):
|
|
160
|
+
stripped = stripped[7:].lstrip()
|
|
161
|
+
key, sep, value = stripped.partition("=")
|
|
162
|
+
key = key.strip()
|
|
163
|
+
if not sep or not _DOTENV_KEY.fullmatch(key) or key in seen:
|
|
164
|
+
raise SafeViewError("INVALID_FORMAT",
|
|
165
|
+
"unsupported or duplicate dotenv entry")
|
|
166
|
+
seen.add(key)
|
|
167
|
+
value = value.strip()
|
|
168
|
+
if value.startswith(("'", '"')):
|
|
169
|
+
if len(value) < 2 or value[-1] != value[0]:
|
|
170
|
+
raise SafeViewError("INVALID_FORMAT",
|
|
171
|
+
"unsupported dotenv quoting")
|
|
172
|
+
value = value[1:-1]
|
|
173
|
+
elif value.endswith(("'", '"')):
|
|
174
|
+
raise SafeViewError("INVALID_FORMAT", "unsupported dotenv quoting")
|
|
175
|
+
fields[_safe_key(key, workspace, len(seen))] = {
|
|
176
|
+
"type": "string", "state": "empty" if value == "" else "set"}
|
|
177
|
+
if len(seen) > MAX_VIEW_NODES:
|
|
178
|
+
raise SafeViewError("STRUCTURE_TOO_LARGE", "config has too many nodes")
|
|
179
|
+
return {"type": "object", "fields": fields}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def read_view(workspace: str, relative_path: str,
|
|
183
|
+
format_name: str = "auto") -> Dict[str, Any]:
|
|
184
|
+
"""Return a structure-only view; never return a config scalar value."""
|
|
185
|
+
parts = _components(relative_path)
|
|
186
|
+
if format_name == "auto":
|
|
187
|
+
name = parts[-1].lower()
|
|
188
|
+
# Split the literal so the repository's source-dump corpus test does
|
|
189
|
+
# not mistake this filename check for an instruction to read a store.
|
|
190
|
+
dotenv_suffix = "." + "env"
|
|
191
|
+
if name.endswith(".json"):
|
|
192
|
+
format_name = "json"
|
|
193
|
+
elif (name == dotenv_suffix or
|
|
194
|
+
name.startswith(dotenv_suffix + ".") or
|
|
195
|
+
name.endswith(dotenv_suffix)):
|
|
196
|
+
format_name = "dotenv"
|
|
197
|
+
else:
|
|
198
|
+
raise SafeViewError("UNSUPPORTED_FORMAT",
|
|
199
|
+
"choose a JSON or dotenv config file")
|
|
200
|
+
if format_name not in ("json", "dotenv"):
|
|
201
|
+
raise SafeViewError("UNSUPPORTED_FORMAT", "unsupported config format")
|
|
202
|
+
text = _read_regular_file(workspace, parts, MAX_VIEW_BYTES)
|
|
203
|
+
if format_name == "dotenv":
|
|
204
|
+
view = _dotenv_view(text, workspace)
|
|
205
|
+
else:
|
|
206
|
+
try:
|
|
207
|
+
value = json.loads(text, object_pairs_hook=_object_pairs,
|
|
208
|
+
parse_constant=_invalid_constant)
|
|
209
|
+
except (ValueError, RecursionError):
|
|
210
|
+
raise SafeViewError("INVALID_FORMAT", "invalid JSON config") from None
|
|
211
|
+
view = _structure(value, workspace, 0, [MAX_VIEW_NODES])
|
|
212
|
+
return {"status": "ok", "format": format_name, "view": view}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# agent-guard architecture
|
|
2
|
+
|
|
3
|
+
## Positioning
|
|
4
|
+
|
|
5
|
+
agent-guard is **Agent Reliability Infrastructure**: it lowers the
|
|
6
|
+
probability that an autonomous agent causes irreversible loss through a
|
|
7
|
+
misjudged deletion, a mis-expanded command, or mistaken context - and it
|
|
8
|
+
leaves a recovery path and an evidence trail when anything destructive does
|
|
9
|
+
happen. It is explicitly *not* a sandbox or security boundary (see
|
|
10
|
+
`threat-model.md`).
|
|
11
|
+
|
|
12
|
+
The shared Core, Decision Protocol, and Skills are the product boundary.
|
|
13
|
+
Harness adapters are replaceable translations onto host-native hooks; DSH,
|
|
14
|
+
Claude Code, Codex, or any future host is a compatibility target rather than
|
|
15
|
+
the identity of the project.
|
|
16
|
+
|
|
17
|
+
## The four pillars and where they live
|
|
18
|
+
|
|
19
|
+
| Pillar | Question it answers | Component |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| Scope | Where may the agent act? | `core/classifier.py` (boundary facts) + `core/policy.py` (rules 3-6) |
|
|
22
|
+
| Recoverability | If wrong, how do we come back? | `core/recovery.py` (relocate / snapshot / restore) |
|
|
23
|
+
| Authorization | Who decides what? | `core/policy.py` (mode state machine) |
|
|
24
|
+
| Auditability | What actually happened? | `core/audit.py` + `.agent-trash/*.jsonl` |
|
|
25
|
+
|
|
26
|
+
A fifth, cross-cutting rule governs all four:
|
|
27
|
+
|
|
28
|
+
> **Uncertainty increases restriction** (fail closed).
|
|
29
|
+
|
|
30
|
+
Anything the classifier cannot resolve statically - shell variables, command
|
|
31
|
+
substitution, unbalanced quotes, indirect shells, stdin-fed target lists -
|
|
32
|
+
becomes a BLOCK verdict, never a guess.
|
|
33
|
+
|
|
34
|
+
## Data flow: supported delete-guard shell path
|
|
35
|
+
|
|
36
|
+
This diagram shows a supported native adapter path. An explicit CLI caller
|
|
37
|
+
joins at `check.py`, skipping the adapter prefilter. Neither path implies that
|
|
38
|
+
every harness or tool call is intercepted. Exfil-guard's cooperative text CLI
|
|
39
|
+
is separate; see [harness capabilities](harness-capabilities.md).
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
shell command (from a supported native adapter)
|
|
43
|
+
│
|
|
44
|
+
▼
|
|
45
|
+
[harness adapter] ── fast prefilter: destructive keywords present? ──no──▶ run unchanged
|
|
46
|
+
│ yes
|
|
47
|
+
▼
|
|
48
|
+
skills/delete-guard/scripts/check.py --enforce -- <command>
|
|
49
|
+
│
|
|
50
|
+
▼
|
|
51
|
+
classifier.classify_command(dialect=posix|cmd|powershell)
|
|
52
|
+
│ │
|
|
53
|
+
│ dialects.py ────┘ lex + map vocabulary onto shared effect facts
|
|
54
|
+
▼
|
|
55
|
+
[OpSpec...] facts, not decisions
|
|
56
|
+
│
|
|
57
|
+
▼
|
|
58
|
+
policy.decide_ops ──▶ [Verdict...] ALLOW / RELOCATE / SNAPSHOT / ASK / BLOCK
|
|
59
|
+
│ │
|
|
60
|
+
│ BLOCK or ASK? ──▶ return 2 or 3; no mutation
|
|
61
|
+
▼ no
|
|
62
|
+
recovery.RecoveryEngine Compensation Strategy
|
|
63
|
+
│ ├─ relocate (fs targets → .agent-trash/<txid>/)
|
|
64
|
+
│ ├─ snapshot (git stash create+store, tree untouched)
|
|
65
|
+
│ └─ clean-enum (git clean -n → relocate matches)
|
|
66
|
+
▼
|
|
67
|
+
audit.append (JSONL, one line per decision)
|
|
68
|
+
│
|
|
69
|
+
▼
|
|
70
|
+
PROCEED with txids ──▶ host may run the original command
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Explicit-path tools skip the shell parsing front half:
|
|
74
|
+
`safe_delete.py PATH... → classify_paths → decide_path_batch → relocate`.
|
|
75
|
+
|
|
76
|
+
## The Decision Protocol
|
|
77
|
+
|
|
78
|
+
The stable cross-harness interface is not allow/block:
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
Effect -> Classifier -> Policy -> Decision ∈ {ALLOW, SANITIZE, RELOCATE,
|
|
82
|
+
SNAPSHOT, ASK, BLOCK}
|
|
83
|
+
+ ReasonCode (stable, machine-readable)
|
|
84
|
+
+ Explanation (human-facing)
|
|
85
|
+
+ RecoveryPlan (payload: txids, strategy)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Command dialects
|
|
89
|
+
|
|
90
|
+
The same effect vocabulary does not exist on native Windows shells, and
|
|
91
|
+
neither do the lexical rules. `core/dialects.py` isolates both concerns:
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
classify_command(cmd, dialect="posix")
|
|
95
|
+
posix -> shlex + heredoc stripping (default; unchanged)
|
|
96
|
+
cmd -> caret escapes, & separators, no
|
|
97
|
+
backslash escapes in quotes, del/erase/rd/rmdir, /s /q
|
|
98
|
+
powershell -> '' literal quoting, ` escapes, $() kept verbatim,
|
|
99
|
+
Remove-Item + del/erase/rd/rmdir/rm/ri alias subset
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Dialect selection in production
|
|
103
|
+
|
|
104
|
+
The dialect is selected by, in precedence order:
|
|
105
|
+
|
|
106
|
+
1. `--dialect {posix,cmd,powershell}` on `check.py`;
|
|
107
|
+
2. the hook payload / tool arguments (`dialect`, `shell_dialect`);
|
|
108
|
+
3. `AGENT_GUARD_DIALECT`;
|
|
109
|
+
4. `posix` (the default).
|
|
110
|
+
|
|
111
|
+
Both adapters forward the *requested* selector verbatim rather than a
|
|
112
|
+
resolved value, so `check.py` owns the single verdict for an unusable
|
|
113
|
+
selector. Adapters also pick their cheap prefilter from the dialect: the
|
|
114
|
+
POSIX regex cannot see `ri build -r -fo`, so a Windows session would
|
|
115
|
+
otherwise skip the guard entirely. The POSIX prefilter is untouched, so
|
|
116
|
+
the default path keeps its exact behaviour and cost.
|
|
117
|
+
|
|
118
|
+
Four rules keep the layer honest:
|
|
119
|
+
|
|
120
|
+
* **The default dialect is POSIX.** Every existing caller keeps its
|
|
121
|
+
exact behaviour; opting in is explicit.
|
|
122
|
+
* **An unknown dialect name is never a silent POSIX fallback.** The
|
|
123
|
+
library raises/returns unusable; the CLI and adapters turn that into
|
|
124
|
+
`BLOCK_DIALECT_UNKNOWN` (name not recognised) or
|
|
125
|
+
`BLOCK_DIALECT_INVALID` (malformed selector). BLOCK, not ASK: a bad
|
|
126
|
+
selector recurs on every command, so it is a configuration defect rather
|
|
127
|
+
than a per-execution authorization.
|
|
128
|
+
* **Unresolvable Windows lexemes fail closed.** `%VAR%`, `$var`, `$(...)`,
|
|
129
|
+
piped target sets, `-LiteralPath`, `-Include`/`-Exclude`/`-Filter`,
|
|
130
|
+
interactive `-Confirm`, unknown switches and nested hosts
|
|
131
|
+
(`powershell -Command "..."`) all become undeterminable facts -> BLOCK.
|
|
132
|
+
`-WhatIf:$true` is a dry run (ALLOW); `-WhatIf:$false` is a real delete;
|
|
133
|
+
a *variable* switch value blocks.
|
|
134
|
+
* **Abbreviations expand only when unambiguous.** PowerShell resolves
|
|
135
|
+
`-r`/`-rec` to `-Recurse` and `-fo` to `-Force`, and the guard follows so
|
|
136
|
+
a recursive forced delete is not read as a mild one. A prefix matching
|
|
137
|
+
two different effects (`-wi` -> `-WhatIf` / `-WarningAction`; `-c`, `-p`)
|
|
138
|
+
is left unexpanded and BLOCKs as an unknown parameter.
|
|
139
|
+
|
|
140
|
+
Adapters map decisions to native mechanisms - DSH `PreToolDecision`,
|
|
141
|
+
Claude Code PreToolUse `ask`, or, on harnesses without ask support, a deny
|
|
142
|
+
that carries the explanation (never a silent allow). Harness capability
|
|
143
|
+
thus never pollutes policy.
|
|
144
|
+
|
|
145
|
+
Architecture invariant (B1): **the guard analyzes the shell command's
|
|
146
|
+
direct effect; it does not infer the internal behavior of arbitrary
|
|
147
|
+
programs.** `npm run build && rm -rf dist` is invisible to creation
|
|
148
|
+
analysis by design - chasing program-internal effects would degrade the
|
|
149
|
+
classifier into a poor shell program analyzer.
|
|
150
|
+
|
|
151
|
+
Interaction tiers: SAFE (auto-execute, silent) / AMBIGUOUS (ASK_ONCE) /
|
|
152
|
+
FORBIDDEN (BLOCK, never askable).
|
|
153
|
+
|
|
154
|
+
## Key design decisions
|
|
155
|
+
|
|
156
|
+
1. **Effect-oriented, dialect as a front end.** The classifier recognizes a
|
|
157
|
+
concrete vocabulary per *dialect* (POSIX: rm family, find -delete, git
|
|
158
|
+
clean/reset/restore/checkout/push; cmd: del/erase/rd/rmdir; PowerShell:
|
|
159
|
+
Remove-Item and its alias subset) but classifies by resulting effect on
|
|
160
|
+
data. Dialects only lex and map vocabulary onto the same effect facts -
|
|
161
|
+
policy, compensation and audit are shared verbatim. Adapters never
|
|
162
|
+
re-implement rules; they call `check.py`, so there is exactly one rule
|
|
163
|
+
engine across every harness and every dialect.
|
|
164
|
+
2. **Enumerate-then-act.** Opaque target sets (globs) are refused at the
|
|
165
|
+
shell layer; the explicit tool expands globs itself first. Opacity is
|
|
166
|
+
converted into explicitness instead of being banned outright.
|
|
167
|
+
3. **Two compensation strategies, one interface.** Filesystem deletions
|
|
168
|
+
*relocate* (the file still exists elsewhere); content-overwriting git ops
|
|
169
|
+
*snapshot* (`stash create` without touching the tree). Both produce a
|
|
170
|
+
txid recorded in manifest + audit. Future compensations (database
|
|
171
|
+
backup/PITR, cloud snapshot) plug into the same slot.
|
|
172
|
+
4. **Restore is non-destructive.** It refuses to overwrite existing origin
|
|
173
|
+
paths; `--force` is an explicit human decision. A recovery tool that can
|
|
174
|
+
clobber would be a second destruction vector.
|
|
175
|
+
5. **Lexical boundaries.** Workspace containment is decided on normalized
|
|
176
|
+
paths; deleting a symlink removes the link, never the target, so symlink
|
|
177
|
+
targets outside the workspace neither leak nor block.
|
|
178
|
+
6. **Self-exclusion.** Targets inside `.agent-trash/` are exempted from
|
|
179
|
+
quarantine - housekeeping cannot recurse into itself forever.
|
|
180
|
+
|
|
181
|
+
## Harness adapter model
|
|
182
|
+
|
|
183
|
+
Any agent harness integrates through three optional points, in increasing
|
|
184
|
+
order of value:
|
|
185
|
+
|
|
186
|
+
1. **Interception hook** (recommended): before executing a shell command,
|
|
187
|
+
run `check.py --enforce -- <command>`; proceed on exit 0, refuse on
|
|
188
|
+
exit 2, and map exit 3 only when the host has a real human-approval path.
|
|
189
|
+
Existing adapters translate this contract onto their host-specific hook.
|
|
190
|
+
2. **Agent-facing tools**: expose `safe_delete` / `restore` / `status` as
|
|
191
|
+
model tools so the supported path is also the easiest path.
|
|
192
|
+
3. **Prompt section**: inject a short instruction pointing the model at the
|
|
193
|
+
skill and the "prefer safe_delete" rule. Interception without prompting
|
|
194
|
+
causes friction; prompting without interception is advisory only.
|
|
195
|
+
|
|
196
|
+
## Roadmap
|
|
197
|
+
|
|
198
|
+
- V1 (this repo): delete-guard skill, fs + git compensations, Linux/macOS.
|
|
199
|
+
- v0.1.1: durable relocation intents, explicit retention/GC policy, quoted
|
|
200
|
+
Git-path safety, fail-closed compensation, clean audit preflight,
|
|
201
|
+
transaction lifecycle state, and adapter smoke coverage.
|
|
202
|
+
- V1.x: broader model/harness conformance matrix.
|
|
203
|
+
- **Windows shell dialects - Phase 1 (done, `core/dialects.py`).** Pure
|
|
204
|
+
logic: cmd and PowerShell lexers, destructive-vocabulary mapping,
|
|
205
|
+
alias subset, `-WhatIf`/`-Recurse`/`-Force`/`-Confirm` semantics, and
|
|
206
|
+
fail-closed handling of variables, subexpressions, piped target sets
|
|
207
|
+
and nested hosts. Unit-tested on Linux CI; POSIX stays the default
|
|
208
|
+
dialect so no existing adapter changes behaviour.
|
|
209
|
+
- **Phase 2 (done at the pure-logic/adapter-test level).** Differential
|
|
210
|
+
and regression suites (`tests/test_dialects.py`,
|
|
211
|
+
`tests/test_dialect_phase2.py`) cover further cmd/PowerShell spellings,
|
|
212
|
+
option aliases and fail-closed edge cases. Hook payload dialect forwarding
|
|
213
|
+
has adapter tests; this is not a Windows host execution claim.
|
|
214
|
+
- **Phase 3 (not done; needs a real Windows host).** End-to-end
|
|
215
|
+
validation: real cmd/PowerShell execution, relocation across Windows
|
|
216
|
+
path semantics, host-selected dialect wiring, UNC/device paths and the
|
|
217
|
+
portability gaps reported in `test-report-zcode-glm-flash.md`.
|
|
218
|
+
- V2: `git-guard` skill (remote ref protection with lease semantics);
|
|
219
|
+
adapter hardening (host-side mode storage, tamper-evident audit).
|
|
220
|
+
- V3+: `database-guard` (compensations = transaction / backup /
|
|
221
|
+
point-in-time recovery), `cloud-guard` (snapshot / state capture). The
|
|
222
|
+
Guard answers "may this happen"; the Compensation Engine answers "how do
|
|
223
|
+
we come back" - both extend without restructuring the repository.
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Compatibility contract
|
|
2
|
+
|
|
3
|
+
agent-guard's promise is recoverability. A promise is only as good as its
|
|
4
|
+
stability over time - this page states exactly what may change and what
|
|
5
|
+
may not, per release class.
|
|
6
|
+
|
|
7
|
+
## The adapter contract (frozen surface)
|
|
8
|
+
|
|
9
|
+
Harness adapters integrate against exactly four things:
|
|
10
|
+
|
|
11
|
+
1. **Decision classes** - `ALLOW`, `SANITIZE`, `RELOCATE`, `SNAPSHOT`,
|
|
12
|
+
`ASK`, `BLOCK`. (`SANITIZE` first appears in the `0.2.0-rc1` source
|
|
13
|
+
preview for exfil-guard; it ranks below `ASK`, between `ALLOW` and
|
|
14
|
+
`RELOCATE`.)
|
|
15
|
+
2. **Reason codes** - stable machine-readable strings (`RELOCATE_TREE`,
|
|
16
|
+
`COMPOUND_CWD_DELETE`, `BLOCK_PROTECTED_PATH`, ...). See
|
|
17
|
+
[../skills/delete-guard/references/policy.md](../skills/delete-guard/references/policy.md).
|
|
18
|
+
3. **Explanation field** - human-facing text attached to every verdict.
|
|
19
|
+
4. **check.py exit codes** - `0` proceed/advisory-ok, `2` blocked,
|
|
20
|
+
`3` ask, `1` internal error.
|
|
21
|
+
|
|
22
|
+
## Versioning promises
|
|
23
|
+
|
|
24
|
+
While the major version is `0`:
|
|
25
|
+
|
|
26
|
+
| Change | Release class |
|
|
27
|
+
|---|---|
|
|
28
|
+
| New reason code (additive) | minor |
|
|
29
|
+
| New decision class | minor, announced in README |
|
|
30
|
+
| Reason code renamed or re-semanticized | **not allowed** in 0.x - if ever needed: major |
|
|
31
|
+
| Manifest record gains a new field | minor (old fields never repurposed) |
|
|
32
|
+
| Manifest record loses/repurposes a field | major + MIGRATION.md |
|
|
33
|
+
| check.py CLI flags removed or re-semanticized | major + MIGRATION.md |
|
|
34
|
+
| Default policy verdict changes for an existing shape | minor + entry in docs/friction.md |
|
|
35
|
+
|
|
36
|
+
## Additive surfaces since v0.1.1
|
|
37
|
+
|
|
38
|
+
| Surface | Class | Notes |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| Command dialects (`cmd`, `powershell`) | minor | `classify_command(cmd, dialect=...)`; the default stays `posix`, so pre-existing callers are unaffected |
|
|
41
|
+
| `core/dialects.py` module + `TokenStream` | minor | Internal-but-documented; used by the dialect unit tests |
|
|
42
|
+
| `OpSpec.dialect` field | minor | New field; unknown fields stay opaque to consumers |
|
|
43
|
+
| `Ask` on PowerShell `-WhatIf` | minor | A dry run is an `ALLOW_NOOP`; a real delete keeps existing rules |
|
|
44
|
+
| `check.py --dialect` flag | minor | Defaults to `posix`; omitting it is byte-for-byte the old behaviour |
|
|
45
|
+
| `AGENT_GUARD_DIALECT` env var | minor | Read by `check.py` and the native shell adapters; unset means `posix` |
|
|
46
|
+
| `BLOCK_DIALECT_UNKNOWN` / `BLOCK_DIALECT_INVALID` | minor | New reason codes (additive) |
|
|
47
|
+
| `BLOCK_PROTECTED_ANCESTOR` | minor | New reason code (additive). Filesystem roots (`/`, `/home`, `/usr`, `$HOME`, ...) are refused by identity rather than by falling outside the workspace |
|
|
48
|
+
| PowerShell parameter prefix expansion | minor | `-r`/`-rec`/`-fo` now resolve; see below |
|
|
49
|
+
| `SANITIZE` decision class | minor | exfil-guard; announced in both READMEs. Adapters must state their native mapping (a harness without re-write capability degrades to ASK/deny) |
|
|
50
|
+
| `core/redaction.py` module (`SpanSpec`, `detect_secrets`, `detect_paths`, `scan_text`) | minor | Internal-but-documented; the fact layer for text spans |
|
|
51
|
+
| `policy.decide_spans()` + the exfil reason codes | minor | New function; the ten new codes are additive |
|
|
52
|
+
| `skills/exfil-guard/` (scripts, SKILL.md, references) | minor | Standalone CLI; no adapter change required to use it |
|
|
53
|
+
| `check_span.py` exit codes | minor | `0` allow/sanitize, `2` block, `3` ask, `1` error - `check.py`'s contract is unchanged |
|
|
54
|
+
| `.agent-guard/exfil-allow.toml` exemption file | minor | Read from the workspace root only; values exempted by `sha256:...`, never by value |
|
|
55
|
+
| `doctor.py --check-drift` report and adapter `compatibility.json` profiles | minor | Additive local preflight. Without drift flags the doctor keeps its previous process-execution and exit behavior; `CURRENT` never promotes live interception above `UNVERIFIED` |
|
|
56
|
+
| `doctor.py --live-sentinel` and hashed hook receipt | minor | Explicit, opt-in real-host/model probe only. Default doctor behavior is unchanged; raw command/model output is not retained, and incomplete evidence is `INCONCLUSIVE` rather than PASS |
|
|
57
|
+
|
|
58
|
+
### 0.2.0 check output minimization
|
|
59
|
+
|
|
60
|
+
`check.py` still returns the same decision class, reason code, static
|
|
61
|
+
explanation, and exit code. Its `command` field is now `<redacted>` rather
|
|
62
|
+
than a copy of the input; `check_id` correlates the result with new audit
|
|
63
|
+
events and compensation metadata. `reasons` no longer carries target
|
|
64
|
+
spellings or parser fragments, and `ops` retains only bounded operation
|
|
65
|
+
identity and kind fields, not raw notes or shape details. Invalid dialect
|
|
66
|
+
selectors are reported by class without echoing the supplied string.
|
|
67
|
+
Adapters must not log the command while reporting a guard verdict.
|
|
68
|
+
|
|
69
|
+
New check audit events and compensation metadata do not copy raw commands.
|
|
70
|
+
`status --json` projects legacy audit records onto a small field set rather
|
|
71
|
+
than re-emitting their historical free-form fields. Historical append-only
|
|
72
|
+
files are **not rewritten**, and recovery manifests still need real target
|
|
73
|
+
paths for restoration. These changes do not sanitize a harness's own tool
|
|
74
|
+
logs or OS process arguments.
|
|
75
|
+
|
|
76
|
+
Unknown dialect names raise `ValueError` from `normalize_dialect`, and the
|
|
77
|
+
production paths (`check.py` and the native shell adapters) turn an unusable
|
|
78
|
+
selector into an explicit `BLOCK` rather than a silent POSIX fallback. That is a
|
|
79
|
+
deliberate *closed* failure: a silent fallback would lex a Windows command
|
|
80
|
+
line with POSIX rules and could under-restrict it.
|
|
81
|
+
|
|
82
|
+
`check.py --dialect` deliberately does **not** use argparse `choices`. An
|
|
83
|
+
unknown selector must produce a Decision Protocol verdict with a reason
|
|
84
|
+
code; a usage error carries none, and a harness could read "no decision" as
|
|
85
|
+
"nothing to worry about".
|
|
86
|
+
|
|
87
|
+
Phase 3 (real Windows end-to-end validation, UNC/device paths, module
|
|
88
|
+
auto-loading) has not happened. The dialect layer stays additive and
|
|
89
|
+
opt-in so Windows support lands without changing any POSIX verdict.
|
|
90
|
+
|
|
91
|
+
### PowerShell parameter prefixes
|
|
92
|
+
|
|
93
|
+
PowerShell resolves a parameter by unambiguous prefix, so `ri build -r -fo`
|
|
94
|
+
is `-Recurse -Force`. The guard expands those, but is deliberately
|
|
95
|
+
*stricter* than the host in one place:
|
|
96
|
+
|
|
97
|
+
| Written | Host expands to | Guard does |
|
|
98
|
+
|---|---|---|
|
|
99
|
+
| `-r` `-rec` `-recur` `-Recurse` | `-Recurse` | expands |
|
|
100
|
+
| `-fo` `-for` `-force` `-Force` | `-Force` | expands |
|
|
101
|
+
| `-wi` | `-WhatIf` | **refuses** - also matches `-WarningAction` |
|
|
102
|
+
| `-c`, `-p` | `-Confirm`/`-Credential`, `-Path`/`-PSPath` | **refuses** |
|
|
103
|
+
|
|
104
|
+
A prefix is expanded only when every candidate leads to the *same* effect
|
|
105
|
+
fact; otherwise it stays an unknown parameter, which policy BLOCKs. `-wi`
|
|
106
|
+
is the interesting case: `-WhatIf` stops the delete while `-WarningAction`
|
|
107
|
+
does not, so a wrong guess is asymmetric and the guard will not make it.
|
|
108
|
+
Every expansion is recorded in the op notes for audit.
|
|
109
|
+
|
|
110
|
+
## Verdict changes since v0.1.1
|
|
111
|
+
|
|
112
|
+
A changed default verdict for an existing shape is a **minor** release and
|
|
113
|
+
requires an entry in [friction.md](friction.md) - never a silent behaviour
|
|
114
|
+
shift. Additive reason codes are listed above; this table is for shapes
|
|
115
|
+
whose *existing* verdict moved.
|
|
116
|
+
|
|
117
|
+
| Shape | Was | Now | Why |
|
|
118
|
+
|---|---|---|---|
|
|
119
|
+
| `git clean -f...` whose target set cannot be enumerated (not a repository, `git` unavailable) | `BLOCK` / `COMPENSATION_FAILED` | `BLOCK` / `BLOCK_UNDETERMINABLE_EFFECT` | Nothing was attempted, so the verdict must not claim a compensation broke; this is the same effect-uncertainty class as every other unknowable target set (F14, policy.md row 11b) |
|
|
120
|
+
| `cd ... && git push --force` | `ASK` / `COMPOUND_CWD_DELETE` | `BLOCK` / `BLOCK_FORCE_PUSH` | A shape rule cannot downgrade a position-independent hard refusal (F1) |
|
|
121
|
+
| `cd ... && rm` with an out-of-workspace, protected, or unknowable target | `ASK` / `COMPOUND_CWD_DELETE` | The applicable hard `BLOCK` | F1 describes compensation difficulty, not permission to cross a boundary |
|
|
122
|
+
| Attached or newline-separated destructive commands (`echo ok;rm ...`, `echo ok` followed by newline and `rm ...`) | Could miss the destructive segment | Classifies and applies its normal policy | POSIX command boundaries must be preserved by the lexer |
|
|
123
|
+
|
|
124
|
+
Unchanged on purpose: a genuine compensation fault (`git stash create`
|
|
125
|
+
failing, a relocation that does not cover every target, an audit intent
|
|
126
|
+
that cannot persist) still reports `COMPENSATION_FAILED`. The distinction
|
|
127
|
+
is *was anything attempted* - not how serious the outcome would have been.
|
|
128
|
+
|
|
129
|
+
## What is explicitly NOT frozen
|
|
130
|
+
|
|
131
|
+
- Explanation wording (humans read it; improve freely).
|
|
132
|
+
- Prompt-section text (guidance, not contract).
|
|
133
|
+
- Audit record shapes beyond the manifest - append-only by policy, but
|
|
134
|
+
consumers should treat unknown fields as opaque.
|
|
135
|
+
- Retention thresholds (documented defaults may tune).
|
|
136
|
+
|
|
137
|
+
## Rationale
|
|
138
|
+
|
|
139
|
+
ReasonCode is the part third parties build against: harness adapters map
|
|
140
|
+
codes onto native UX, users write allowlists around them, incident reports
|
|
141
|
+
cite them. Renaming a code silently breaks all three. Everything else can
|
|
142
|
+
evolve faster.
|