@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.
Files changed (77) hide show
  1. package/CONTRIBUTING.md +101 -0
  2. package/LICENSE +21 -0
  3. package/README.md +558 -0
  4. package/README.zh-CN.md +488 -0
  5. package/adapters/INTEGRATION.md +94 -0
  6. package/adapters/claude/README.md +141 -0
  7. package/adapters/claude/compatibility.json +17 -0
  8. package/adapters/claude/harness/README.md +59 -0
  9. package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
  10. package/adapters/claude/harness/run_scenario.sh +79 -0
  11. package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
  12. package/adapters/claude/hook_bridge.sh +33 -0
  13. package/adapters/claude/pre_tool_use.py +264 -0
  14. package/adapters/claude/settings.example.json +16 -0
  15. package/adapters/codex/harness/README.md +53 -0
  16. package/adapters/codex/harness/acceptance.py +226 -0
  17. package/adapters/dsh/README.md +62 -0
  18. package/adapters/dsh/cordis.patch.yml +30 -0
  19. package/adapters/dsh/lib/index.js +500 -0
  20. package/adapters/kimi-code/README.md +169 -0
  21. package/adapters/kimi-code/compatibility.json +17 -0
  22. package/adapters/kimi-code/config.example.toml +26 -0
  23. package/adapters/kimi-code/hook_bridge.sh +32 -0
  24. package/adapters/kimi-code/pre_tool_use.py +72 -0
  25. package/core/__init__.py +47 -0
  26. package/core/audit.py +86 -0
  27. package/core/classifier.py +1175 -0
  28. package/core/dialects.py +898 -0
  29. package/core/policy.py +817 -0
  30. package/core/recovery.py +700 -0
  31. package/core/redaction.py +1096 -0
  32. package/core/safe_view.py +212 -0
  33. package/docs/architecture.md +223 -0
  34. package/docs/compatibility.md +142 -0
  35. package/docs/development-note-unguarded-deletion.md +187 -0
  36. package/docs/friction.md +266 -0
  37. package/docs/harness-capabilities.md +72 -0
  38. package/docs/host-drift.md +142 -0
  39. package/docs/publishing-from-ephemeral-environments.md +104 -0
  40. package/docs/release-notes-0.2.0-rc1.md +46 -0
  41. package/docs/release-notes-0.2.0.md +72 -0
  42. package/docs/release-notes-0.2.1.md +78 -0
  43. package/docs/release-notes-0.2.2.md +120 -0
  44. package/docs/secret-guard-analysis.md +416 -0
  45. package/docs/secret-guard-architecture.md +93 -0
  46. package/docs/secret-guard-design.md +649 -0
  47. package/docs/test-report-claude-code-harness.md +462 -0
  48. package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
  49. package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
  50. package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
  51. package/docs/test-report-dsh-v0.1.1.md +126 -0
  52. package/docs/test-report-kimi-code-block.md +198 -0
  53. package/docs/test-report-zcode-glm-flash.md +241 -0
  54. package/docs/threat-model.md +44 -0
  55. package/doctor.py +756 -0
  56. package/live_sentinel.py +339 -0
  57. package/package.json +69 -0
  58. package/skills/delete-guard/SKILL.md +109 -0
  59. package/skills/delete-guard/agents/openai.yaml +4 -0
  60. package/skills/delete-guard/references/policy.md +161 -0
  61. package/skills/delete-guard/scripts/_bootstrap.py +8 -0
  62. package/skills/delete-guard/scripts/check.py +370 -0
  63. package/skills/delete-guard/scripts/gc.py +103 -0
  64. package/skills/delete-guard/scripts/restore.py +98 -0
  65. package/skills/delete-guard/scripts/safe_delete.py +256 -0
  66. package/skills/delete-guard/scripts/status.py +130 -0
  67. package/skills/exfil-guard/SKILL.md +143 -0
  68. package/skills/exfil-guard/agents/openai.yaml +4 -0
  69. package/skills/exfil-guard/references/channels.md +58 -0
  70. package/skills/exfil-guard/references/rules.md +194 -0
  71. package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
  72. package/skills/exfil-guard/scripts/check_span.py +250 -0
  73. package/skills/exfil-guard/scripts/sanitize.py +155 -0
  74. package/skills/exfil-guard/scripts/view.py +44 -0
  75. package/skills/recovery-audit/SKILL.md +283 -0
  76. package/skills/recovery-audit/agents/openai.yaml +4 -0
  77. package/skills/recovery-audit/references/evidence-records.md +85 -0
@@ -0,0 +1,649 @@
1
+ # exfil-guard — design
2
+
3
+ Status: **design, pre-implementation.** Extends the Decision Protocol with
4
+ one new decision class (`SANITIZE`) and one new classifier input type
5
+ (text spans). Read `secret-guard-analysis.md` first — §2.5 there
6
+ (reachability) and §0.1 (irrevocability) are the two facts this design is
7
+ built around.
8
+
9
+ Naming: the skill is `exfil-guard`; the rule families are `secret/*` and
10
+ `path/*`. `docs/secret-guard-architecture.md` states where it sits.
11
+
12
+ ---
13
+
14
+ ## 1. Core component design
15
+
16
+ ### 1.1 Module layout (mirroring the existing tree)
17
+
18
+ ```
19
+ core/
20
+ classifier.py UNCHANGED (command/path facts) [reuse]
21
+ dialects.py UNCHANGED [reuse]
22
+ policy.py + decide_spans(), SANITIZE, new codes [extend]
23
+ audit.py UNCHANGED API (new event kinds only) [reuse]
24
+ recovery.py UNCHANGED (no compensation here) [reuse]
25
+ redaction.py NEW - the Compensation-Strategy slot:
26
+ detect(spans) -> Allowed | Sanitized | Withheld
27
+ + RedactionRecord (never the bytes)
28
+
29
+ skills/
30
+ exfil-guard/
31
+ SKILL.md model-facing discipline
32
+ agents/openai.yaml parity with delete-guard
33
+ references/
34
+ rules.md rule table = the policy doc
35
+ secret-patterns.md T1/T3 pattern catalogue (with provenance)
36
+ channels.md egress-channel taxonomy (§4.1)
37
+ scripts/
38
+ _bootstrap.py copy of the delete-guard shim (3 lines)
39
+ check_span.py NEW entry: scan text from stdin, NOT a
40
+ command line — Decision Protocol out
41
+ sanitize.py NEW: apply a redaction plan to text
42
+ scan_path.py NEW: scan a file/dir/diff (reuse of the
43
+ same span engine, different source)
44
+ status.py reuse pattern from delete-guard
45
+ ```
46
+
47
+ Two structural choices worth defending:
48
+
49
+ **(a) `redaction.py` is a new *strategy* on the existing Compensation slot,
50
+ not a new engine.** `docs/architecture.md` #3 already frames compensation
51
+ as pluggable ("Future compensations … plug into the same slot"). Redaction
52
+ is the *degraded* member of that family — it does not restore recoverable
53
+ loss, it only records what was removed. Naming it inside `recovery.py`'s
54
+ family keeps the mental model intact; giving it its own module keeps the
55
+ irreversibility explicit.
56
+
57
+ **(b) `check_span.py` is a *separate entry point*, not a flag on
58
+ `check.py`.** `check.py`'s contract is "classify a shell command line"
59
+ (its docstring, the `--` REMAINDER convention, the dialect resolution, the
60
+ compensation execution). Loading it with "or maybe a blob of text" would
61
+ break the single-responsibility that makes `tests/test_conformance.py` a
62
+ meaningful test. Span mode has a different input, a different (smaller)
63
+ decision set, and no compensation phase:
64
+
65
+ ```
66
+ check.py --enforce -- <command> → ALLOW|RELOCATE|SNAPSHOT|ASK|BLOCK exit 0|2|3
67
+ check_span.py --channel <name> < text → ALLOW|SANITIZE|ASK|BLOCK exit 0|2|3|4
68
+ ```
69
+
70
+ Both construct the *same* `Verdict` objects and both go through
71
+ `policy.worst()`, so the aggregation and adapter mapping stay shared.
72
+
73
+ ### 1.2 The classifier contract (facts, not decisions)
74
+
75
+ Following `classifier.py`'s rule ("it deliberately does NOT decide"):
76
+
77
+ ```python
78
+ @dataclass
79
+ class SpanSpec:
80
+ raw: str # the matched substring, HELD IN MEMORY ONLY
81
+ start: int # byte offset into the scanned text
82
+ end: int
83
+ rule_id: str # e.g. "secret/openai-key"
84
+ family: str # "secret" | "path"
85
+ confidence: str # "deterministic" | "contextual" | "entropy"
86
+ context: str # "key=…" | "prose" | "diff-added-line" | "env-var"
87
+ channel: str # egress channel that will carry it (§4.1)
88
+ notes: List[str] = field(default_factory=list)
89
+ ```
90
+
91
+ `raw` is the analogue of `PathSpec.raw` — the fact layer keeps the caller's
92
+ spelling, and only `audit`/`redaction` decide what may be *persisted*
93
+ (nothing). `context` and `channel` exist because §4.4 shows the right
94
+ decision is a function of both, not of the pattern alone.
95
+
96
+ ### 1.3 Fact → decision table (the shape of `decide_spans`)
97
+
98
+ ```
99
+ span.family, span.confidence, channel.rewritable, channel.persistence
100
+ │
101
+ ├─ rewritable? ──no──▶ ASK (print-like channels) | BLOCK (immutable channel)
102
+ └─ yes
103
+ ├─ deterministic secret → SANITIZE
104
+ ├─ contextual/entropy secret → SANITIZE (if rule enabled) | ASK
105
+ ├─ path inside workspace → ALLOW (not a host identifier)
106
+ ├─ path outside workspace → SANITIZE (path/* rules) | ASK
107
+ └─ anything ambiguous → ASK
108
+ ```
109
+
110
+ First-match-wins, like the delete-guard rule table. `worst()` aggregates
111
+ across spans with the existing rank, extended by one:
112
+
113
+ ```
114
+ ALLOW(0) < SANITIZE(1) < ASK(2) < BLOCK(3)
115
+ ```
116
+
117
+ `SANITIZE` ranks below `ASK` deliberately: it is *automatic* (SAFE tier,
118
+ like RELOCATE/SNAPSHOT), while ASK forfeits automation. A line containing
119
+ both a sanitizable secret and an un-rewritable askable shape must ASK —
120
+ you cannot silently proceed when part of the emission is uninspectable.
121
+
122
+ ---
123
+
124
+ ## 2. Secret detection strategy
125
+
126
+ ### 2.1 Three detectors, one pipeline
127
+
128
+ | Tier | Name | Character | Decision default |
129
+ |---|---|---|---|
130
+ | T1 | Known vendor patterns | deterministic, near-zero FP | SANITIZE |
131
+ | T2 | Environment-variable / file-content references | structural (value-free) | ASK |
132
+ | T3 | Generic high-entropy with secret-ish context | probabilistic | SANITIZE behind a threshold + context gate |
133
+
134
+ The tiers are **not** alternatives to be chosen between — the reviewer of
135
+ the seed idea asked "regex vs entropy vs known-pattern library", and the
136
+ correct answer for this repository is all three, layered, because they have
137
+ disjoint failure modes:
138
+
139
+ - T1 alone: misses self-hosted tokens, custom `X-Api-Key` values, rotated
140
+ formats. Zero FP, poor recall.
141
+ - T3 alone: flags lockfile hashes, test fixtures, base64 blobs, UUIDs, and
142
+ every `git rev-parse HEAD`. Unusable by default.
143
+ - T1+T3 without T2: cannot answer "will this command print my key?" — the
144
+ single highest-signal scenario in Class A (S3), and the only one where a
145
+ value-free answer is possible.
146
+
147
+ ### 2.2 T1 — known patterns
148
+
149
+ Catalogue lives in `references/secret-patterns.md`, each entry with the
150
+ vendor, the format documented, and a "why this is deterministic" note.
151
+ Seed list (prefix-anchored to keep FP ≈ 0):
152
+
153
+ | Rule id | Shape | Anchor |
154
+ |---|---|---|
155
+ | `secret/openai-key` | `sk-` + 20+ url-safe chars, incl. `sk-proj-`/`sk-ant-` | prefix + length + charset |
156
+ | `secret/github-token` | `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_` + 36, `github_pat_` + 82 | fixed-format prefix |
157
+ | `secret/aws-access-key-id` | `AKIA`/`ASIA`/`AGPA`/`AIDA` + 16 upper-alnum | `AKIA…` is globally reserved |
158
+ | `secret/gitlab-token` | `glpat-` + 20 | prefix |
159
+ | `secret/slack-token` | `xox[baprs]-` | prefix |
160
+ | `secret/stripe-key` | `sk_live_`/`rk_live_` (NOT `sk_test_` — see §5) | prefix + mode |
161
+ | `secret/jwt` | three base64url segments, header decodes to JSON with `alg` | **structural**, not just `a.b.c` |
162
+ | `secret/private-key-block` | `-----BEGIN (RSA |EC|OPENSSH|DSA|PGP)? ?PRIVATE KEY-----` … `-----END` | delimiters; redact the whole block |
163
+ | `secret/ssh-private-key-file` | the above, but detected as a *file* by name + first line | file source |
164
+
165
+ Design rules for T1:
166
+
167
+ 1. **Structural validation when the format allows it.** A JWT is only a JWT
168
+ if segment 1 base64-decodes to JSON containing `alg` — otherwise it is a
169
+ version string (`1.2.3`) or a hostname (`api.example.com`), both of
170
+ which occur constantly in this repo's own text.
171
+ 2. **No "generic keyword" patterns in T1.** `password=` / `secret=` are
172
+ *context*, which is T3's job. Putting them in T1 makes the whole tier
173
+ noisy and destroys the "deterministic ⇒ auto-sanitize" property that
174
+ the design depends on.
175
+ 3. **Patterns are additive and versioned** in `secret-patterns.md`; adding
176
+ one is a minor release (new reason code not required — rule ids are
177
+ payload, not verdict codes).
178
+
179
+ ### 2.3 T3 — entropy with a context gate
180
+
181
+ Entropy alone is a losing detector. The gate is the design:
182
+
183
+ ```
184
+ candidate = token matching [A-Za-z0-9+/_\-=]{20,}
185
+ entropy = Shannon bits/char over the token
186
+ signal = (entropy >= H_high) # e.g. 4.0
187
+ OR (entropy >= H_mid AND key-context) # e.g. 3.0 + context
188
+ where key-context = one of, within the same line/statement:
189
+ key|token|secret|passwd|password|pwd|auth|apikey|api_key|credential
190
+ (case-insensitive), separated by one of = : " ' , FOLLOWED BY nothing
191
+ that looks like a placeholder (§5)
192
+ ```
193
+
194
+ Why the context gate carries the weight: the two populations overlap in
195
+ entropy. A lockfile integrity hash (`sha512-…`) and a random 32-byte token
196
+ are statistically identical. What separates them is *how they are
197
+ introduced* — and the introduction is exactly what the key-context regex
198
+ sees. This mirrors the dialect layer's rule ("abbreviations expand only
199
+ when unambiguous"): expand the heuristic only inside a context that makes
200
+ the interpretation unambiguous.
201
+
202
+ Tuning levers, all explicit and all in config (§5):
203
+
204
+ - `H_high`, `H_mid`, minimum length, and the key-context word list;
205
+ - per-rule `enabled` flags so `path/*` or `secret/entropy` can be switched
206
+ off without touching the others.
207
+
208
+ ### 2.4 T2 — value-free environment/file references (Q3 answered)
209
+
210
+ The problem: detect `echo "$OPENAI_API_KEY"` without the guard ever
211
+ learning the key.
212
+
213
+ **Answer: never read the value. Score the *reference*.**
214
+
215
+ Detector inputs, all available to a pre-command hook:
216
+
217
+ 1. **The name.** A variable whose *name* matches the secret-name lexicon
218
+ (`*KEY*`, `*TOKEN*`, `*SECRET*`, `*PASSWORD*`, `*PASSWD*`, `*CRED*`,
219
+ `*AUTH*`, `*APIKEY*`) is treated as secret-bearing **by name
220
+ classification only**. The guard does not `getenv` it. This is the
221
+ property that makes the whole detector safe: the guard's output, logs,
222
+ audit, and error messages are all value-free by construction.
223
+ 2. **A reference, not a value.** `echo "$OPENAI_API_KEY"`, `printenv
224
+ GITHUB_TOKEN`, `env | grep TOKEN`, `${AWS_SECRET_ACCESS_KEY}` inside a
225
+ heredoc-bound string.
226
+ 3. **A file read whose path is a known secret store** — `.env`, `.env.*`,
227
+ `*.pem`, `id_rsa*`, `*.p12`, `.npmrc`, `.netrc`, `credentials`,
228
+ `*.tfvars`, `kubeconfig`. Path *names* are not secret; this is a path
229
+ fact the existing classifier vocabulary can already express.
230
+ 4. **An expansion form, not a name** — `env`, `printenv` with no argument,
231
+ `set`, `export -p`, `cat /proc/self/environ`. Undeterminable content
232
+ (B1 applies: we cannot know what the environment holds). Fail-closed
233
+ option: ASK, not BLOCK (see Q2 resolution, §4.4).
234
+
235
+ Detector output is *only* `(rule_id, span of the reference expression)` —
236
+ **never** a value. The audit record stores the variable **name**, not its
237
+ content. That single constraint keeps exfil-guard from becoming its own
238
+ leak vector (analysis threat #7).
239
+
240
+ **Anti-loop rule:** detection must never require reading the thing it
241
+ protects. State it as a hard invariant, in the same register as "restore
242
+ is non-destructive": *the guard reads names and shapes, never secret
243
+ values.*
244
+
245
+ **Undefined/non-secret variables (the honest corner):** if
246
+ `$OPENAI_API_KEY` happens to hold `"test"`, the guard still ASKs. This is
247
+ acceptable because the cost of a false ASK is one keystroke and the cost of
248
+ a false ALLOW is irreversible (§0.1) — the asymmetry decision, applied
249
+ consistently. It is *not* acceptable to resolve the variable to reduce
250
+ false ASKs, because that would violate the invariant above.
251
+
252
+ ### 2.5 Detector outputs are spans, not booleans
253
+
254
+ Every detector returns offsets. Reasons:
255
+
256
+ - **Redaction needs positions** (`sanitize.py`).
257
+ - **`--json` output must not contain the match**, only its span and rule —
258
+ otherwise the guard leaks into CI logs. Conformance tests can then assert
259
+ the *absence* of the value in all guard output, which is a testable
260
+ security property (see design §6 test plan).
261
+ - **Idempotence is checkable:** scanning `<REDACTED>` text must yield zero
262
+ spans.
263
+
264
+ ---
265
+
266
+ ## 3. Path detection strategy
267
+
268
+ ### 3.1 The workspace-relative exemption is the core rule
269
+
270
+ Direct reuse of the delete-guard insight (`docs/architecture.md` #5,
271
+ "Lexical boundaries"): *a path is only a host identifier if it is outside
272
+ the workspace.* `./src/main.py` says nothing about the machine;
273
+ `/home/alice/work/agent-guard/src/main.py` does.
274
+
275
+ ```
276
+ path span
277
+ │
278
+ ├─ inside workspace (lexical compare, existing _physical/inside_path)?
279
+ │ → ALLOW (rewrite to workspace-relative only if the channel
280
+ │ wants it — never as a security action)
281
+ ├─ workspace root path itself → SANITIZE (the root is the host id)
282
+ ├─ outside workspace → SANITIZE (path/host-absolute)
283
+ ├─ under the home directory → SANITIZE (path/home-absolute)
284
+ ├─ system prefix (/usr,/etc,/opt, → ALLOW by default (not host-
285
+ │ C:\Windows, /Library, …) identifying), configurable
286
+ └─ unreachable/exotic (UNC, device) → SANITIZE (conservative)
287
+ ```
288
+
289
+ This inverts the naive approach: instead of enumerating every
290
+ host-identifying prefix (unbounded, unmaintainable), the guard uses the one
291
+ boundary it already computes confidently — the workspace — and treats
292
+ everything else as suspect **unless** it is a well-known system prefix.
293
+
294
+ ### 3.2 Absolute-path regexes
295
+
296
+ | OS | Shape | Notes |
297
+ |---|---|---|
298
+ | POSIX | `/(?:[A-Za-z0-9._@+-]+/)*[A-Za-z0-9._@+-]*` | Require ≥2 components OR a known-root tie-in, else `/tmp` matches |
299
+ | macOS home | `/Users/<name>/…`, `/Volumes/<name>/…` | Distinctive, high-signal; `/Users/Shared` exempt |
300
+ | Linux home | `/home/<name>/…`, `/root/…` | `/root` is the container default — often *not* identifying; configurable |
301
+ | CI runners | `/runner/_work/…`, `/builds/…`, `/github/workspace/…`, `/var/lib/jenkins/…` | **This repo's own CI leaks these** — see §3.4 |
302
+ | Sandboxes | `/tmp/<random>`, `/var/folders/xx/…` (macOS `mkdtemp`), `C:\Users\<u>\AppData\Local\Temp\…` | Random segments are ephemeral, low value; the base is the signal |
303
+ | Windows | `[A-Za-z]:\\…`, UNC `\\\\host\\share\\…`, device `\\\\?\\…`, `\\.\pipe\…` | Windows home = `C:\Users\<u>\…`; UNC hostnames are identifiers |
304
+ | Windows env | `%USERPROFILE%`, `%LOCALAPPDATA%` | Interpolation → existing `has_interpolation` fact → undeterminable |
305
+
306
+ Reuse `classifier._is_windows_absolute()` and the `%VAR%`/`$env:` handling
307
+ from `dialects.py` verbatim: the Windows absolute-path semantics this
308
+ feature needs are already implemented and tested, dialect-independently
309
+ (the module comment says it explicitly — a Linux CI must still reason about
310
+ `C:/Windows`).
311
+
312
+ ### 3.3 Host identity: whose name is "the host's"?
313
+
314
+ The guard must not hard-code `/home/<user>`; it must derive the set of
315
+ identifying names **at runtime**:
316
+
317
+ | Source | Portability | Trust |
318
+ |---|---|---|
319
+ | `getpass.getuser()` | already used by `audit.session_id()` | high, but empty under some container/CI setups |
320
+ | `os.environ["USER"]` / `USERNAME` / `LOGNAME` | universal, spoofable | medium |
321
+ | `expanduser("~")` basename | good on macOS/Linux | medium |
322
+ | `platform.node()`, `socket.gethostname()` | hostname identifiers (in prompts, tracebacks, UNC) | medium |
323
+ | `os.environ["HOME"]`, `USERPROFILE`, `LOCALAPPDATA`, `TEMP` | the *actual* prefixes to redact, better than any username guess | high |
324
+ | The workspace path itself | **best** — its ancestors are by definition not to be echoed raw | high |
325
+ | Harness-provided overrides | `AGENT_GUARD_HOSTNAMES`, `AGENT_GUARD_HOME_MARKERS` | explicit config |
326
+
327
+ Design rule: **derive a deny-set, not a pattern** — a set of literal
328
+ prefixes built from HOME/USERPROFILE/TEMP/workspace-ancestors plus
329
+ `getpass.getuser()`. A prefix-set match is deterministic (high confidence,
330
+ auto-SANITIZE); a *generic* absolute path with no prefix correlation is
331
+ contextual (ASK). This gives the two-tier structure §1.3 needs, and it
332
+ portably degrades: on a host where `getpass` fails, the guard still has
333
+ HOME/USERPROFILE to build a smaller but still-useful deny-set, and the
334
+ `generic-absolute-path` rule remains as a low-confidence backstop.
335
+
336
+ ### 3.4 Host identity ≠ machine identity, and CI is the counter-example
337
+
338
+ This repository's own artifacts make the case: `docs/test-report-*.md` and
339
+ CI logs routinely contain
340
+ `/home/runner/work/agent-guard/agent-guard`, `/workspace`, `/tmp/agent-guard-test-*`.
341
+ Those leak the *runner image's* layout, not a person. Consequences the
342
+ design must honour:
343
+
344
+ - **Default severity for path rules is low**, and the default decision for
345
+ a bare host path in a *non-persistent* channel is ALLOW-with-note or ASK,
346
+ never BLOCK.
347
+ - **The workspace itself is the exemption**, and in CI the workspace *is*
348
+ `/home/runner/work/…` — so the guard's own primary rule already covers
349
+ the most common CI leak without a runner-specific list.
350
+ - **`.agent-trash/`** must be scanned as suspicious content (it holds
351
+ quarantined `.env` copies — analysis S8) but its *paths* are workspace
352
+ paths and exempt.
353
+
354
+ ---
355
+
356
+ ## 4. Interception points and dispositions
357
+
358
+ ### 4.1 Channel taxonomy (Q1 answered)
359
+
360
+ A channel is defined by two facts, and the decision table keys off both:
361
+
362
+ | Channel | `rewritable` | `persistence` | Reached via | Candidate default |
363
+ |---|---|---|---|---|
364
+ | `llm-request` | yes (proxy/hook) | none (but third party) | pre-request hook | SANITIZE |
365
+ | `file-write` | yes | workspace | pre-write hook / tool arg | SANITIZE |
366
+ | `git-commit-message` | yes (rewrite argv) | git history | pre-command hook | BLOCK |
367
+ | `git-push-payload` | no (would need history rewrite) | **remote** | pre-command hook | BLOCK |
368
+ | `forge-comment` / `issue-body` / `pr-description` | yes (before send) | public | pre-request hook | SANITIZE |
369
+ | `shell-stdout` | **no** | transcript/log | pre-command hook | ASK |
370
+ | `shell-file-redirect` (`> out.log`) | yes (file not yet written) | local | pre-command hook | ASK (or SANITIZE on the write) |
371
+ | `archive-upload` (`tar`, `git bundle`, `gh release upload`) | yes | remote | pre-command hook | ASK |
372
+ | `process-argv` (`foo --token=…`) | yes | ps/logs | pre-command hook | ASK |
373
+
374
+ The `rewritable` column is what makes `SANITIZE` meaningful; the
375
+ `persistence` column is what justifies BLOCK. A channel that is neither
376
+ rewritable nor persistent (stdout to a local terminal) can only ASK.
377
+
378
+ ### 4.2 Interception-point inventory
379
+
380
+ | # | Point | Scenarios | Mechanism | Status |
381
+ |---|---|---|---|---|
382
+ | 1 | **pre-command** (existing) | S3, S7, P4, S2-partial, S8 | new shapes in `classifier.py` + span scan of command literals | reuse + extend |
383
+ | 2 | **pre-write** (new) | S6, P3 | adapter hook on Write/Edit tool args; `check_span.py --channel file-write` | new adapter point |
384
+ | 3 | **pre-request** (new) | S1, P1, S5 | adapter hook or local proxy (precedent: `adapters/claude/harness/mock_anthropic_api.mjs`) | new adapter point |
385
+ | 4 | **pre-push / pre-commit** (new, subtle) | S2, S7 | `git diff --cached` / `git log @{u}..HEAD --name-only` scan, then `check_span.py --channel git-push-payload` | new, high value |
386
+ | 5 | **artifact/packaging** (deferred) | S8 | enumerate then scan, same shape as `RELOCATE_VIA_CLEAN_ENUMERATE` | MVP-excluded (§6) |
387
+
388
+ Point 4 deserves emphasis: it is the only place where the guard can see a
389
+ *whole outgoing payload* rather than one literal, and it is a natural
390
+ extension of the existing `git push` classification (which today only
391
+ checks for `--force`/ref deletion). "Scan what this push actually sends"
392
+ reuses `recovery.RecoveryEngine.enumerate_git_clean()`'s precedent of
393
+ dry-run enumeration before action.
394
+
395
+ ### 4.3 Dispositions
396
+
397
+ | Decision | Meaning | Semantics |
398
+ |---|---|---|
399
+ | `ALLOW` | nothing matched, or matches are provably benign (workspace-relative path, placeholder) | run unchanged |
400
+ | `SANITIZE` | the guard rewrites the *payload*, not the command | **new**, SAFE tier |
401
+ | `ASK` | single-execution authorization (unchanged semantics from delete-guard) | the human decides; never a rule exemption |
402
+ | `BLOCK` | refuse | reserved for: immutable-history channels with a deterministic secret, scanner failure, invalid config |
403
+
404
+ `SANITIZE` is deliberately **not** an adapter-mapped decision in the same
405
+ way as RELOCATE/SNAPSHOT, because it does not apply to a *command*: it
406
+ applies to a *payload*, and the caller of `check_span.py` is the one holding
407
+ the payload. The contract is:
408
+
409
+ ```
410
+ check_span.py --channel file-write --json < text
411
+ → {"decision":"SANITIZE", "code":"SANITIZE_KNOWN_SECRET_PATTERN",
412
+ "spans":[{"start":104,"end":151,"rule_id":"secret/openai-key",
413
+ "confidence":"deterministic"}],
414
+ "redaction_plan":[...]} # offsets + placeholder, NO bytes
415
+ ```
416
+
417
+ The payload owner then calls `sanitize.py` (or applies the plan inline) and
418
+ writes the **sanitized** text. This keeps the guard out of the payload
419
+ path, keeps check_span a pure function (testable, no I/O), and makes the
420
+ "never persist matched bytes" invariant structurally enforceable: the JSON
421
+ schema simply has no field for matched content.
422
+
423
+ ### 4.4 Q2, answered: SANITIZE on a non-rewritable channel
424
+
425
+ The fail-closed instinct says BLOCK. This design says:
426
+
427
+ - **immutable/persistent channel** (`git-commit-message`, `git-push-payload`)
428
+ → **BLOCK**. Rationale: the emission cannot be taken back, and unlike a
429
+ delete it is not compensable, so "refuse and explain" is proportionate.
430
+ The explanation names the remediation (amend/rewrite before push).
431
+ - **rewritable channel** → `SANITIZE`, and if the caller declines to apply
432
+ the plan, the API contract is "you were told"; the audit records
433
+ `sanitize-declined`.
434
+ - **non-rewritable, non-persistent channel** (stdout) → **ASK**, because
435
+ BLOCK here would block `echo` on a variable the human has every right to
436
+ print, and delete-guard's ASK tier is exactly "well-understood operation
437
+ whose safe *automation* is unavailable" — a perfect description of
438
+ "cannot un-print".
439
+ - **unreachable channel** → no verdict at all; documented (§2.4 of the
440
+ analysis), never implied to be covered.
441
+
442
+ This resolves the tension in analysis §4.4 in the direction of the repo's
443
+ existing principle: *uncertainty increases restriction, but the guard never
444
+ pretends to control what it does not*.
445
+
446
+ ### 4.5 Adapter mapping
447
+
448
+ | Core decision | Claude Code (`PreToolUse`) | DSH (`PreToolDecision`) | No-hook harness |
449
+ |---|---|---|---|
450
+ | ALLOW | exit 0 | run | run |
451
+ | SANITIZE | rewrite the tool arg, `permissionDecision: allow` + reason naming the rule (never the value) | rewrite the arg | **degrade to ASK/deny**, never silently proceed |
452
+ | ASK | `permissionDecision: ask` | native ask → deny | deny + explanation |
453
+ | BLOCK | exit 2, stderr to the model | deny + explanation | deny + explanation |
454
+
455
+ The "no re-write capability" row is the degradation rule that keeps the
456
+ feature honest: a harness that cannot rewrite must not be told it can.
457
+
458
+ ---
459
+
460
+ ## 5. False-positive handling
461
+
462
+ Five instruments, in the order they should be tried:
463
+
464
+ **5.1 Static placeholder allowlist (deterministic, no config).**
465
+ `YOUR_API_KEY_HERE`, `xxxxxxxx`, `<REDACTED>`, `sk-xxxx…`, `changeme`,
466
+ `dummy`, `example`, `test`, `fake`, `placeholder`, `TODO`, `*`-runs,
467
+ sequential runs, all-same-char runs, and *the literal variable name*
468
+ (`$OPENAI_API_KEY` inside docs about how to set it). Existing repo
469
+ precedent: `SECURITY.md`'s "Expected scanner hits". The allowlist is
470
+ **in-repo and versioned**, so a deployment scans this repository without
471
+ failing on its own test fixtures.
472
+
473
+ **5.2 Repo-local exemption file.** `.agent-guard/exfil-allow.toml` (or
474
+ `.agent-guardignore`, mirroring `.gitignore` semantics that this codebase
475
+ already reasons about) with:
476
+
477
+ - `rule_id` globs to disable,
478
+ - path globs exempted from scanning (e.g. `tests/fixtures/secrets/*`),
479
+ - literal-value exemptions **by hash** — never by value. A human who needs
480
+ a specific value exempted provides `sha256:…`, and the guard compares
481
+ hashes. This is the only way to write an exemption without writing the
482
+ secret into a tracked file, which is itself the bug the feature exists to
483
+ prevent.
484
+
485
+ **5.3 Confidence gating** (the primary lever). Auto-`SANITIZE` only on
486
+ `deterministic` confidence; `contextual`/`entropy` matches default to
487
+ `SANITIZE` **only** when the context gate fired, else `ASK`. Configurable
488
+ per rule.
489
+
490
+ **5.4 Entropy threshold + length floor.** Raise `H_high`/`H_mid` and the
491
+ minimum token length to trade recall for quiet. Ship the defaults that
492
+ keep this repository's own corpus clean (the acceptance corpus in §6.4 is
493
+ the tuning instrument, not vibes).
494
+
495
+ **5.5 Audit records every sanitize/block with enough to debug, and no
496
+ secret.** Record shape:
497
+
498
+ ```json
499
+ {"event":"exfil-sanitize","rule_id":"secret/openai-key",
500
+ "confidence":"deterministic","channel":"file-write",
501
+ "family":"secret","span":[104,151],"length":47,
502
+ "exempted":false,"plan_id":"…","ts":"…","session":"…"}
503
+ ```
504
+
505
+ No `raw`, no prefix, no suffix, no hash of the secret (a hash of a
506
+ low-entropy secret is offline-crackable — do not store it). Rule id +
507
+ offsets + length is enough to reproduce a false positive from the original
508
+ payload and is worthless to an attacker.
509
+
510
+ **5.6 Noise budget as a design constraint.** State an explicit target, so
511
+ "it's too noisy" becomes measurable: on this repository's own text corpus
512
+ (README, docs/, tests/, skills/), the default rule set must produce **zero
513
+ BLOCK and a bounded number of ASK/SANITIZE**; anything above the bound is a
514
+ bug in the rule, not a tuning problem. `docs/compatibility.md`'s promise
515
+ that "default policy verdict changes for an existing shape → minor +
516
+ friction entry" applies: rule changes that alter verdicts get a
517
+ `docs/friction.md` entry.
518
+
519
+ ---
520
+
521
+ ## 6. MVP scope
522
+
523
+ ### 6.1 In scope (ordered by yield, not by ease)
524
+
525
+ **MVP-1 — `SANITIZE` on file-write and pre-request channels with T1
526
+ patterns.** Covers S6, P3, S1/P1 on harnesses with a hook. Highest coverage
527
+ gain (0% → real), lowest FP risk (deterministic patterns only), and it
528
+ establishes the new decision class plus the span/redaction plumbing.
529
+
530
+ **MVP-2 — `check_span.py` as a standalone CLI + `sanitize.py`.** Makes the
531
+ feature usable *today* by any harness or script without adapter changes
532
+ (pipe a diff, a prompt, or a file through it). Small, self-contained,
533
+ immediately testable, and it de-risks the adapter work that follows.
534
+
535
+ **MVP-3 — commit-message and push-payload scan (Class A, point 4).**
536
+ Covers S7, P4, S2. Pure extension of existing pre-command interception; the
537
+ push scan reuses the dry-run-enumeration precedent.
538
+
539
+ **MVP-4 — T2 (value-free env reference) on the pre-command hook.** Covers
540
+ S3's highest-signal form. Small rule, no value access, ASK-only.
541
+
542
+ **MVP-5 — path rules (`path/*`) with workspace exemption, ALLOW/ASK/SANITIZE
543
+ (defaults biased to quiet).** Lowest severity, cheapest to get wrong;
544
+ ships last, and only after the noise budget (§5.6) is measured on real
545
+ corpora.
546
+
547
+ ### 6.2 Explicitly NOT in MVP (scope boundary)
548
+
549
+ 1. **No LLM-request interception for harnesses that lack a hook or proxy.**
550
+ Documented as a coverage gap, with the "you may not claim" sentence from
551
+ `threat-model.md` reused verbatim.
552
+ 2. **No git-history rewriting / no `filter-repo` integration.** Detecting a
553
+ secret already in history is a *report* at most; rewriting is a human
554
+ action with its own destructive risk (`docs/architecture.md` #4 logic).
555
+ 3. **No T3 entropy detector in the first release** unless the acceptance
556
+ corpus (§6.4) shows it clears the noise budget. It is the single largest
557
+ FP source and the least necessary for the named seeds.
558
+ 4. **No archive/packaging enumeration** (`tar`, `git bundle`, `gh release
559
+ upload`) — MVP-excluded; it is the natural MVP-6.
560
+ 5. **No database/cloud egress point.** Those belong to V3+ skills; the
561
+ RedactionRecord is the shared interface, not the rules.
562
+ 6. **No new mode/state machine.** NORMAL/RESTRICTED is reused; the only new
563
+ authorization surface is "rule config is host-side" (agent cannot
564
+ disable a rule).
565
+ 7. **No encrypted/entropy-proof detection, no obfuscation resistance.** §0
566
+ positioning.
567
+ 8. **No second skill.** One skill, two families (analysis §3.1).
568
+
569
+ ### 6.3 Delivery constraint (inherited, non-negotiable)
570
+
571
+ - Zero third-party dependencies (repo-wide invariant; a hashing/exemption
572
+ scheme must use `hashlib`).
573
+ - Python 3.9+ compatible (no `match`, no `X | Y` annotations at runtime
574
+ unless `from __future__ import annotations` — already the house style).
575
+ - Latency: the prefilter must keep non-matching text at regex cost
576
+ (friction F4's ~0.3 s/command budget applies to the new prefilter too,
577
+ and span scanning of large payloads needs an explicit size cap +
578
+ streaming/chunking rule).
579
+ - Every failure mode fails **closed for BLOCK-class channels** and is
580
+ reported, never silent (`BLOCK_EXFIL_SCANNER_UNAVAILABLE`).
581
+
582
+ ### 6.4 Acceptance corpus (the thing that makes "MVP done" checkable)
583
+
584
+ 1. **Positive corpus:** this repository's documented examples, plus
585
+ synthesised patterns per T1 rule, plus the S1–S8/P1–P5 scenario list
586
+ turned into literal payloads.
587
+ 2. **Negative corpus:** README, `docs/*.md`, `tests/**`, `skills/**`,
588
+ `package.json` lockfile-shaped text, `git log` output, base64 blobs
589
+ (images), `sha512-…` integrity strings, IPv4/IPv6, semver triplets,
590
+ long prose. **Zero BLOCK, bounded ASK/SANITIZE** (§5.6).
591
+ 3. **Leak-freedom corpus:** assert that no guard output (stdout, `--json`,
592
+ audit line, error message, explanation, traceback) contains any matched
593
+ substring. This is the test that keeps the guard from becoming the leak.
594
+
595
+ ---
596
+
597
+ ## 7. Position in the roadmap
598
+
599
+ Current roadmap (`docs/architecture.md`): V1 delete-guard → V1.x dialects →
600
+ V2 `git-guard` → V3+ `database-guard`/`cloud-guard`.
601
+
602
+ exfil-guard is a **new X-guard branch**, not a slot inside the existing
603
+ sequence, for one reason: it extends the core with a *new input type*
604
+ (text spans) and a *new decision class*, while `git-guard` is explicitly
605
+ "remote ref protection with lease semantics" — a different axis that reuses
606
+ the existing deletion machinery. Sequencing:
607
+
608
+ ```
609
+ V1 delete-guard ✅ shipped
610
+ V1.x dialects ✅ phase 1 shipped
611
+ V1.y exfil-guard ◀── this feature (Y = 2)
612
+ MVP-1/2 new decision class SANITIZE + span classifier
613
+ MVP-3/4 pre-command extensions (commit msg, push payload, env refs)
614
+ MVP-5 path rules
615
+ V2 git-guard (independent; can proceed in parallel)
616
+ V3+ database-guard / cloud-guard
617
+ ```
618
+
619
+ Justification for placing it **before** `git-guard`, despite `git-guard`
620
+ being further along the stated roadmap:
621
+
622
+ 1. **It is upstream of git-guard's own failure modes.** A `git-guard` that
623
+ protects remote refs is still useless if the pushed content is a
624
+ credential or a host path. Push-payload scanning is the missing half of
625
+ the same "protect what leaves" story.
626
+ 2. **It shares the `git push` interception point** already present in
627
+ `classifier._parse_git()` — one hook, two concerns; building
628
+ `git-guard` first means rebuilding the point twice.
629
+ 3. **The new decision class is a core-surface change.** `docs/compatibility.md`
630
+ says a new decision class is a minor release "announced in README";
631
+ landing it before V2 means `git-guard` is authored against the *final*
632
+ decision vocabulary rather than a partially frozen one. Doing it after
633
+ V2 risks a second, concurrent protocol change.
634
+ 4. **It is the feature the user actually asked for now**, and its MVP-2
635
+ (standalone `check_span.py`) delivers value with zero adapter changes —
636
+ the lowest-risk way to extend the core.
637
+
638
+ **Versioning/positioning obligations** (from `docs/compatibility.md`):
639
+
640
+ - New decision class → **minor**, README announcement, adapter mapping
641
+ table updated.
642
+ - New reason codes → **minor**, documented in
643
+ `skills/exfil-guard/references/rules.md` and the compatibility page's
644
+ "Additive surfaces" table.
645
+ - Any default-verdict change for an existing shape → minor + a
646
+ `docs/friction.md` entry.
647
+ - `README.md` / `README.zh-CN.md` must gain the honest limitation section
648
+ (§2.4 of the analysis) — a feature that arrives without its documented
649
+ blind spots would violate the repo's own threat-model discipline.