@mokuyoaxis/agent-guard 0.2.3-rc2 → 0.2.3

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 (37) hide show
  1. package/README.md +88 -47
  2. package/README.zh-CN.md +71 -39
  3. package/adapters/dsh/README.md +15 -10
  4. package/adapters/dsh/harness/README.md +68 -12
  5. package/adapters/dsh/harness/bootstrap.patch.yml +5 -0
  6. package/adapters/dsh/harness/bootstrap_init.mjs +48 -0
  7. package/adapters/dsh/harness/guard_lab.py +191 -29
  8. package/adapters/dsh/harness/native_session.py +41 -20
  9. package/adapters/dsh/harness/profiles.py +74 -22
  10. package/adapters/kimi-code/README.md +8 -7
  11. package/core/lab.py +24 -1
  12. package/core/redaction.py +157 -55
  13. package/docs/development-note-unguarded-deletion.md +6 -7
  14. package/docs/friction.md +68 -4
  15. package/docs/guard-lab-read-trial-task.md +7 -0
  16. package/docs/guard-lab.md +7 -0
  17. package/docs/harness-capabilities.md +1 -1
  18. package/docs/release-notes-0.2.0-rc1.md +2 -2
  19. package/docs/release-notes-0.2.0.md +2 -2
  20. package/docs/release-notes-0.2.2.md +7 -8
  21. package/docs/release-notes-0.2.3-rc1.md +4 -2
  22. package/docs/release-notes-0.2.3.md +51 -12
  23. package/docs/secret-guard-analysis.md +13 -12
  24. package/docs/secret-guard-architecture.md +5 -3
  25. package/docs/secret-guard-design.md +7 -3
  26. package/docs/test-report-codex-gpt-5.6-sol.md +10 -11
  27. package/docs/test-report-kimi-code-block.md +19 -20
  28. package/docs/test-report-release-readiness-0.2.3.md +78 -0
  29. package/docs/test-report-workbuddy-windows-core.md +53 -0
  30. package/docs/test-report-zcode-glm-flash.md +9 -9
  31. package/package.json +1 -1
  32. package/skills/delete-guard/SKILL.md +2 -3
  33. package/skills/exfil-guard/SKILL.md +37 -7
  34. package/skills/exfil-guard/references/rules.md +84 -16
  35. package/skills/exfil-guard/scripts/_payload.py +99 -0
  36. package/skills/exfil-guard/scripts/check_span.py +14 -81
  37. package/skills/exfil-guard/scripts/sanitize.py +113 -34
@@ -159,3 +159,81 @@ the approved `0.2.3` manifest/tests/README versions and validate its final
159
159
  artifact before authorizing the stable tag workflow. A
160
160
  [stable release-note draft](release-notes-0.2.3.md) is ready for that step.
161
161
  Remote publication is not authorized by this review.
162
+
163
+ ## Stable preparation — 2026-10-03
164
+
165
+ The maintainer authorized README polishing and preparation for stable 0.2.3
166
+ and a dsh-market listing. The local manifest is now `0.2.3`; committing,
167
+ pushing, tagging, npm/GitHub publication and the catalog PR are subsequent
168
+ steps. At this preparation checkpoint, registry checks showed
169
+ `latest=0.2.2`, `rc=0.2.3-rc2`, with no
170
+ published 0.2.3 package. Earlier sections retain their checkpoint dates.
171
+
172
+ The current source adds validated sanitizer execution and external plans,
173
+ bounded UTF-8 input, URI password detection, newer GitHub and PyPI token
174
+ coverage, complete-name/placeholder boundaries and targeted AWS/JWT noise
175
+ corrections. No production dependency or shared channel policy was added.
176
+ The native capture helpers now use receipt v6 / parser v3, with source-call
177
+ correlation and initialized isolated-profile fingerprints; old evidence keeps
178
+ its original interpretation. Pending Lab trials are not recorded as complete,
179
+ and no new injection L2 claim follows from this preparation.
180
+
181
+ Earlier checks on 2026-10-03 exercised installed DSH 0.2.0-rc.2 local/sandbox
182
+ read probes with the Core rules preserved in this candidate: protected
183
+ synthetic values were absent from guarded
184
+ value/content/meta, the next deterministic request and full JSONL, while
185
+ normal configuration, resource IDs and Unicode stayed readable. Those probes
186
+ made zero external model, network or shell calls. They validate reviewed
187
+ native providers, not universal output interception or shell sandboxing.
188
+
189
+ Two earlier 676-case full local runs each had a different startup/subprocess
190
+ timeout; both isolated cases subsequently passed. Those failed runs remain
191
+ failed. This preparation's 14-case preflight passed in 18.645 seconds,
192
+ including package/release checks and both previously timed-out cases.
193
+ The complete local candidate gate then passed all 676 Python tests in
194
+ 729.911 seconds, followed by both Node adapter/read-worker smoke suites.
195
+ The environment was Python 3.13.5 / Node 22.23.2 on ARM64/PRoot. The full pass
196
+ does not identify the cause of the earlier transient timeouts; no safety or
197
+ timing threshold was relaxed.
198
+
199
+ The candidate tarball contains 112 files, including the new WorkBuddy summary
200
+ and all public CLI/adapter assets. It excludes internal evidence, tests and
201
+ caches. Offline isolated installation with scripts disabled passed all ten
202
+ CLI help checks and adapter import without an installed DSH dependency.
203
+ Packaged files matched the worktree byte-for-byte. Final documentation is
204
+ repacked after recording these results; its runnable assets must match that
205
+ validated tarball. All 58 public Markdown files, 266 local links, 64 Python
206
+ syntax trees and the LF/diff checks passed; supported secret-pattern scanning
207
+ found no hits in those Markdown files.
208
+
209
+ Native Windows/macOS cannot be revalidated on this local host. The eventual
210
+ exact-source hosted CI and npm credential preflight remain required before
211
+ tagging. This preparation launched no new real-host/model trial and made no
212
+ remote repository, registry or catalog change.
213
+
214
+ The [WorkBuddy summary](test-report-workbuddy-windows-core.md) records
215
+ community Core/CLI feedback without claiming a native hook. Both READMEs
216
+ preserve their section order, add scoped evidence badges and distinguish the
217
+ prepared source from published artifacts.
218
+
219
+ dsh-market reads the community
220
+ [awesome-dsh-plugin catalog](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin/blob/main/contributing.md).
221
+ The checked catalog does not yet contain this project. A one-file bilingual
222
+ `security` entry and PR copy are prepared locally. Package-to-repository
223
+ mapping and the existing DSH bundle are already present; listing and
224
+ publication remain separate actions.
225
+
226
+ ## Publication authorization — 2026-10-03
227
+
228
+ The maintainer subsequently authorized the complete three-part publication:
229
+ GitHub Release, npm and the dsh-market catalog submission. The README and
230
+ stable notes now use release wording, while registry availability is shown by
231
+ the npm badge and Releases. This documentation pass changes no runnable asset
232
+ from the locally validated candidate.
233
+
234
+ The release sequence requires the exact pushed source to pass the 13-job CI
235
+ and npm credential preflight before the `0.2.3` tag starts publication.
236
+ The existing tag workflow creates a stable GitHub Release and publishes its
237
+ same checksummed tarball to npm `latest` with provenance. The catalog PR uses
238
+ the verified package and changes one entry; submission is distinct from
239
+ upstream acceptance and appearance in dsh-market.
@@ -0,0 +1,53 @@
1
+ # WorkBuddy on Windows: community Core/CLI feedback
2
+
3
+ Report date: 2026-09-27. Summary reviewed: 2026-10-03.
4
+
5
+ [Issue #7](https://github.com/mokuyoaxis/agent-guard/issues/7) records a community
6
+ run against Agent Guard `0.2.2`, commit `274127e`, on Windows 11 with Git Bash,
7
+ Python 3.13.15 and Git 2.55.0.windows.3. The reporter
8
+ [identified the executor as WorkBuddy](https://github.com/mokuyoaxis/agent-guard/issues/7#issuecomment-5857388494):
9
+ an AI coding agent invoked the repository's Python CLI directly.
10
+
11
+ No adapter, harness wrapper or `PreToolUse` hook was involved. This is evidence
12
+ about Core behavior in a real Windows environment, not WorkBuddy native-hook
13
+ support. The WorkBuddy version and model were not recorded. This summary does
14
+ not represent a new maintainer-run WorkBuddy trial.
15
+
16
+ ## Confirmed findings and regressions
17
+
18
+ | Finding | Resulting behavior | Regression |
19
+ |---|---|---|
20
+ | Known destructive vocabulary disappeared under a mismatched dialect; `rm -rf .` became `ALLOW_NOOP` under `cmd` | The unparsed destructive segment becomes non-compensable `UNKNOWN`, producing `BLOCK_UNDETERMINABLE_EFFECT` | [Core CLI tests](https://github.com/mokuyoaxis/agent-guard/blob/main/tests/test_delete.py), `CheckCLI.test_cmd_dialect_cannot_turn_rm_root_delete_into_noop` |
21
+ | Windows target separators could be consumed or handled differently depending on the classifier host OS | Supported Windows-native targets normalize consistently; actual target fixtures relocate instead of falling through as a no-op | [Dialect tests](https://github.com/mokuyoaxis/agent-guard/blob/main/tests/test_dialects.py), `DefaultPathUnchanged`; [CLI tests](https://github.com/mokuyoaxis/agent-guard/blob/main/tests/test_delete.py), `WindowsVerbNoDialect` |
22
+
23
+ The reporter's [final correction](https://github.com/mokuyoaxis/agent-guard/issues/7#issuecomment-5857694703)
24
+ narrows the second finding: matching `del` with cmd or `Remove-Item` with
25
+ PowerShell already worked. A missing target correctly produces a no-op, so
26
+ regressions must create the target and preserve the exact command bytes.
27
+
28
+ The same report observed working quarantine relocation, manifest and audit
29
+ records, and restoration with content intact. The resulting
30
+ [Windows Core CI job](https://github.com/mokuyoaxis/agent-guard/blob/main/.github/workflows/ci.yml) covers selected dialect,
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.
33
+
34
+ ## Withdrawn redaction finding
35
+
36
+ The original third finding was
37
+ [withdrawn](https://github.com/mokuyoaxis/agent-guard/issues/7#issuecomment-5857658162).
38
+ Git Bash input construction had altered backslashes and a newline before the
39
+ payload reached the scanner. Direct Python subprocess input confirmed the
40
+ existing Windows path detection and redaction.
41
+
42
+ The candidate added an exact-byte synthetic-path regression in
43
+ [test_exfil_sanitize.py](https://github.com/mokuyoaxis/agent-guard/blob/main/tests/test_exfil_sanitize.py),
44
+ `FormatPreservation.test_native_windows_user_path_uses_exact_bytes_and_sanitizes`.
45
+ This is an input-contract regression, not a third confirmed exfil fix.
46
+
47
+ ## Evidence boundary
48
+
49
+ This feedback supports Windows Core/CLI evaluation and the two resulting
50
+ fixes. It does not establish a WorkBuddy adapter, mandatory interception of
51
+ WorkBuddy tools, all Windows command execution, or protection against an
52
+ agent with equal OS privileges. Personal host paths and unrelated local
53
+ configuration are omitted from this summary.
@@ -12,11 +12,11 @@ acted as the forward-test agent inside its own session
12
12
  **Platform:** Windows 10.0.26200 (win32), Python 3.13.15, git 2.55.0.windows.4, Bash via
13
13
  Git Bash (POSIX shell)
14
14
 
15
- ## Executive summary
15
+ ## Assessment
16
16
 
17
17
  agent-guard `v0.1.1` did **not** work on Windows out of the box: the Python core
18
- uses `os.uname()`, which does not exist on win32, and because the audit log is
19
- the durability pillar, every mutation failed closed — `safe_delete.py` blocked
18
+ uses `os.uname()`, which does not exist on win32. The required audit write
19
+ therefore failed, and every mutation failed closed — `safe_delete.py` blocked
20
20
  **all** deletions and `restore.py` raised `module 'os' has no attribute
21
21
  'uname'`. The test suite scored 79/84.
22
22
 
@@ -30,12 +30,12 @@ ZCode's `process`-type hook semantics.
30
30
 
31
31
  One ZCode integration property could not be exercised in the original run
32
32
  session (project-scope hooks load at session start), so the workspace trust was
33
- granted and a **trusted live fire was completed in a follow-up session**: the
33
+ granted and a **hook test ran in a separate trusted session**: the
34
34
  hook intercepted a real destructive command, surfaced its ASK decision as a
35
35
  ZCode permission prompt, audited the verdict, and executed only after human
36
36
  approval — confirming that ZCode accepts the adapter's
37
37
  `hookSpecificOutput` JSON schema. One significant ZCode-side caveat was found
38
- in the same live pass: clicking **"Always allow" (Approved for this project)**
38
+ in the same test: clicking **"Always allow" (Approved for this project)**
39
39
  on that prompt saves a project permission rule that makes ZCode skip the
40
40
  PreToolUse hook entirely for subsequent Bash commands — including commands the
41
41
  guard would hard-BLOCK. agent-guard itself behaved correctly at every point;
@@ -65,7 +65,7 @@ hostile-agent security boundary.
65
65
  with stderr fed back to the model). The model decided the cleanup
66
66
  strategy and responded to guard feedback without prior knowledge of
67
67
  expected verdicts.
68
- 6. A live-fire attempt of the real hook inside the running session, with ZCode
68
+ 6. A real-hook test inside the running session, with ZCode
69
69
  log analysis to explain the outcome.
70
70
 
71
71
  No source files were modified during behavioral testing. All destructive
@@ -132,10 +132,10 @@ machine running Core and pins them in a focused Windows CI job.
132
132
  trusted — installation must precede the session, and trust must be granted
133
133
  once. Any ZCode setup guide for agent-guard must state both.
134
134
 
135
- ### Trusted live fire (follow-up session, post-trust)
135
+ ### Hook test after workspace trust (follow-up session)
136
136
 
137
137
  With trust granted, the same session that could not fire the hook earlier was
138
- followed by a live pass. The model submitted a real destructive compound
138
+ followed by a hook test. The model submitted a real destructive compound
139
139
  command (`mkdir -p <fixture>/build && echo payload > ... && rm -rf <fixture>`)
140
140
  through its own Bash tool:
141
141
 
@@ -230,7 +230,7 @@ predict — the audit trail (`compensations: []`) made the outcome verifiable.
230
230
  ## Remaining matrix expansion
231
231
 
232
232
  - Behavior of the hook under permission modes where no project allow rule
233
- exists (this report's live pass ran under a saved "Approved for this
233
+ exists (this report's hook test ran under a saved "Approved for this
234
234
  project" rule; hook firing for every Bash call in rule-free sessions is
235
235
  inferred from the trust-gate session, not yet exhaustively measured).
236
236
  - Additional model families per harness; non-minimal compositions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mokuyoaxis/agent-guard",
3
- "version": "0.2.3-rc2",
3
+ "version": "0.2.3",
4
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.",
5
5
  "type": "module",
6
6
  "main": "./adapters/dsh/lib/index.js",
@@ -25,8 +25,7 @@ enforces and how to work with it productively. The four pillars:
25
25
 
26
26
  ## The one rule
27
27
 
28
- **Prefer `safe_delete` over `rm`. It is not slower for you - it is the
29
- supported path.**
28
+ **Prefer `safe_delete` over `rm`.** It applies the guard's recovery policy.
30
29
 
31
30
  ```bash
32
31
  # delete files/dirs/globs - they are quarantined, not destroyed:
@@ -87,7 +86,7 @@ that an error means no filesystem change occurred. A durable
87
86
  After a human veto, the session runs with narrowed powers: explicit
88
87
  single-file deletes inside the workspace still work (quarantined as usual);
89
88
  recursive deletes, globs, and destructive git operations are refused. Only a
90
- human can restore NORMAL. If a task genuinely requires more, say so plainly
89
+ human can restore NORMAL. If a task requires more, say so plainly
91
90
  and ask.
92
91
 
93
92
  ## Regenerable artifacts
@@ -44,6 +44,11 @@ python3 <repo>/skills/exfil-guard/scripts/sanitize.py --channel file-write < dra
44
44
  never writes, never rewrites, and never prints the match. Exit codes are the
45
45
  contract: `0` allow/sanitize, `2` block, `3` ask, `1` error.
46
46
 
47
+ `sanitize.py` uses the same exit codes and emits no payload on ASK/BLOCK or
48
+ error. Both CLIs bound stdin while reading (4 MiB by default), support UTF-8,
49
+ and resolve the same default workspace/host-side mode. The first-byte wait is
50
+ bounded; it is not a deadline for a producer that has already started writing.
51
+
47
52
  ## Safe config view
48
53
 
49
54
  When you need to learn a JSON or dotenv config's shape, use the explicit
@@ -74,7 +79,7 @@ intercept a harness's ordinary file-read tool.
74
79
  | `ASK` (`ASK_SECRET_EMISSION` / `ASK_PATH_EMISSION`) | the channel cannot be rewritten and cannot be taken back (a terminal transcript cannot be un-printed) | stop and ask a human; do not silently proceed |
75
80
  | `BLOCK` (`BLOCK_SECRET_EMISSION` / `BLOCK_PATH_EMISSION`) | the channel is immutable or remote history (commit message, push payload) | **do not retry.** Remove the value and redo the message/commit |
76
81
  | `BLOCK_SECRET_SOURCE_DUMP` | the payload reads a whole secret store (`cat .env`, `printenv`) whose content the guard never saw | stop; emit an explicit, reviewed value instead |
77
- | `BLOCK_OUTPUT_UNSCANNABLE` | the payload was never scanned (too large, non-ASCII, unknown channel, scanner error) | an unscanned egress is not a clean egress. Do not route around it |
82
+ | `BLOCK_OUTPUT_UNSCANNABLE` | the payload was never scanned (too large, unknown channel, scanner error) | an unscanned egress is not a clean egress. Do not route around it |
78
83
 
79
84
  A `BLOCK` is not an obstacle to work around. Re-encoding a payload, splitting
80
85
  a secret across lines, or piping through a tool the guard does not scan is a
@@ -84,10 +89,17 @@ violation of the authorization pillar and is recorded in the audit log.
84
89
 
85
90
  The guard deliberately does not rewrite your payload - you hold it. Apply
86
91
  the plan back to front so offsets stay valid, or let `sanitize.py` do it.
87
- Redaction **preserves format**: `sk-proj-Ab…` becomes `sk-proj-<REDACTED>`
92
+ Redaction **preserves format**: `sk-proj-Ab…` becomes `sk-<REDACTED>`
88
93
  (so a reviewer can still see *which kind* of credential leaked), and a host
89
94
  path becomes `<PATH>`.
90
95
 
96
+ An external `--plan` is checked against a fresh scan, including offsets,
97
+ placeholders and any supplied rule metadata. A partial, stale or arbitrary plan
98
+ is refused; the rewritten payload must pass another scan. A plan made with
99
+ checker-specific mode/path overrides still has to satisfy current sanitizer
100
+ policy. URI passwords use `<REDACTED>` while retaining scheme/account/host;
101
+ this is credential redaction, not network-topology hiding or an editable URI.
102
+
91
103
  If you decline to apply a plan on a rewritable channel, the API contract is
92
104
  "you were told": the audit records `sanitize-declined`. That is a choice
93
105
  with a record, not a default.
@@ -95,16 +107,34 @@ with a record, not a default.
95
107
  ## Value-free detection (why `echo "$TOKEN"` is caught)
96
108
 
97
109
  The guard detects a secret *reference* without ever reading the secret. It
98
- classifies a variable's **name** (`*KEY*`, `*TOKEN*`, `*SECRET*`,
99
- `*PASSWORD*`, `*CRED*`, `*AUTH*`) and a secret-store **file name**
110
+ classifies a variable's **name** by complete credential components (`KEY`,
111
+ `TOKEN`, `SECRET`, `PASSWORD`, `CRED`, `AUTH`, including underscores and
112
+ camelCase), and a secret-store **file name**
100
113
  (`.env`, `*.pem`, `id_rsa*`, `.netrc`, `kubeconfig`, …), never a value.
101
114
  This keeps this scanner from creating a second value copy; it does not
102
115
  certify unrelated CLI output or existing audit records as secret-free.
103
116
 
104
117
  Consequence you will notice: if `$OPENAI_API_KEY` actually holds `"test"`,
105
- the guard still ASKs. That is intentional. The cost of a false ASK is one
106
- keystroke; the cost of a false ALLOW is permanent. Do not attempt to
107
- "resolve" the variable to reduce prompts.
118
+ the guard still BLOCKs its uninspectable source reference. Do not attempt to
119
+ resolve the variable to soften that decision. `MONKEY`/`API_KEYBOARD` are
120
+ ordinary names, and terminal `COUNT`/`LENGTH`/`ENABLED` denotes metadata.
121
+ Public-key names retain conservative handling pending separate review.
122
+ Bare lower/title-case `key` is too ambiguous to classify without an explicit
123
+ environment reference; uppercase `KEY` and qualified `apiKey` remain protected.
124
+
125
+ Placeholder exemptions require a whole documented shape or an exact static
126
+ example; incidental words inside random credentials do not exempt them.
127
+ Vendor credentials adjacent to CJK prose are scanned with original offsets.
128
+ GitHub installation credentials support both classic and `ghs_APPID_JWT`
129
+ shapes, with complete redaction of long tokens. These are shape facts, not
130
+ authentication or token-validity checks. See [rules.md](references/rules.md).
131
+
132
+ PyPI token bodies follow the documented `pypi-` scanner shape and are redacted
133
+ in full, including long bodies. AWS access-key IDs use AKIA/ASIA; IAM resource
134
+ IDs have separate types and do not match that credential rule. Generic JWT
135
+ headers require a nonempty ASCII string `alg`. Public-key variable names and
136
+ the broad legacy `sk-` shape retain conservative handling where their purpose
137
+ or complete format has not been established.
108
138
 
109
139
  ## Path rules
110
140
 
@@ -21,9 +21,19 @@ forfeits automation. A payload carrying both a sanitizable secret and an
21
21
  un-rewritable shape must ASK - you cannot silently proceed when part of the
22
22
  emission is uninspectable.
23
23
 
24
- Exit codes (`check_span.py`): `0` allow/sanitize · `2` block · `3` ask ·
24
+ Exit codes (`check_span.py` and `sanitize.py`): `0` allow/sanitize · `2` block · `3` ask ·
25
25
  `1` error.
26
26
 
27
+ The checker returns a proposal. The sanitizer outputs a payload only after
28
+ ALLOW or a verified SANITIZE; ASK/BLOCK/errors produce no payload on stdout.
29
+ External plans must match the freshly derived offsets and placeholders, with
30
+ any supplied metadata agreeing too. Missing, extra, overlapping or stale ranges
31
+ and arbitrary replacements are refused. Revalidation binds the plan to current
32
+ scan facts, not to a byte-identical input fingerprint. The library returns empty
33
+ `text` for ASK/BLOCK. Both CLIs share default workspace/mode resolution; the
34
+ checker retains its explicit mode/path overrides, which are not authorization
35
+ for the sanitizer. Input and plan files are bounded UTF-8 text.
36
+
27
37
  ## Reason codes
28
38
 
29
39
  | Code | Decision | Meaning |
@@ -37,7 +47,7 @@ Exit codes (`check_span.py`): `0` allow/sanitize · `2` block · `3` ask ·
37
47
  | `BLOCK_SECRET_EMISSION` | BLOCK | credential about to enter immutable/remote history |
38
48
  | `BLOCK_PATH_EMISSION` | BLOCK | host path about to enter immutable/remote history |
39
49
  | `BLOCK_SECRET_SOURCE_DUMP` | BLOCK | the payload reads a secret store the guard cannot see into |
40
- | `BLOCK_OUTPUT_UNSCANNABLE` | BLOCK | never scanned: unknown channel, over cap, non-ASCII, scanner error |
50
+ | `BLOCK_OUTPUT_UNSCANNABLE` | BLOCK | never scanned: unknown channel, over cap, scanner error |
41
51
 
42
52
  ## Rule table (first match wins)
43
53
 
@@ -46,7 +56,7 @@ Exit codes (`check_span.py`): `0` allow/sanitize · `2` block · `3` ask ·
46
56
  | 1 | payload reads a secret store (`.env`, `*.pem`, `id_rsa*`, `kubeconfig`, `printenv`, `env \| …`) | BLOCK | `BLOCK_SECRET_SOURCE_DUMP` |
47
57
  | 2 | match is a placeholder / already-redacted marker | ALLOW | `ALLOW_SECRET_PLACEHOLDER` |
48
58
  | 3 | path is workspace-relative (and not the root itself) | ALLOW | `ALLOW_PATH_IN_WORKSPACE` |
49
- | 4 | channel unknown or payload over the scan cap / non-ASCII / scanner error | BLOCK | `BLOCK_OUTPUT_UNSCANNABLE` |
59
+ | 4 | channel unknown or payload over the scan cap / scanner error | BLOCK | `BLOCK_OUTPUT_UNSCANNABLE` |
50
60
  | 5 | channel is immutable history (`git-commit-message`, `git-push-payload`) | BLOCK | `BLOCK_*_EMISSION` |
51
61
  | 6 | channel is neither rewritable nor persistent (`shell-stdout`) | ASK | `ASK_*_EMISSION` |
52
62
  | 7 | secret, `deterministic` (T1) or context gate fired | SANITIZE | `SANITIZE_SECRET_REDACT` |
@@ -63,19 +73,72 @@ loosens a BLOCK.
63
73
  | Rule id | Shape | Anchor |
64
74
  |---|---|---|
65
75
  | `secret/openai-key` | `sk-` + 20+ url-safe chars, incl. `sk-proj-`/`sk-ant-`/`sk-live-` | prefix + length + charset |
66
- | `secret/github-token` | `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_` + 36; `github_pat_` + 22+ | fixed-format prefix |
67
- | `secret/aws-access-key-id` | `AKIA`/`ASIA`/`AGPA`/`AIDA`/`AROA`/`ANPA` + 16 upper-alnum | globally reserved prefix |
76
+ | `secret/github-token` | classic `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_` + 36; `github_pat_` + 22–255; `ghs_APPID_JWT` installation wrapper | vendor prefix; new wrapper has a structural JWT header |
77
+ | `secret/aws-access-key-id` | `AKIA`/`ASIA` + 16 upper-alnum | access-key identifier prefixes |
68
78
  | `secret/gitlab-token` | `glpat-` + 20+ | prefix |
69
79
  | `secret/slack-token` | `xox[baprs]-` | prefix |
70
80
  | `secret/stripe-key` | `sk_live_`/`rk_live_` (never `sk_test_`) | prefix + live mode |
71
- | `secret/jwt` | three base64url segments; header decodes to JSON containing `alg` | **structural**, not just `a.b.c` |
81
+ | `secret/pypi-token` | `pypi-` + 85+ base64url body characters, without a fixed maximum | documented vendor scanner shape |
82
+ | `secret/jwt` | three base64url segments; header decodes to JSON with a nonempty ASCII string `alg` | **structural**, not just `a.b.c` |
72
83
  | `secret/private-key-block` | `-----BEGIN [X ]*PRIVATE KEY-----` … `-----END …` | delimiters; whole block withheld |
73
- | `secret/source-reference` | an env-var *name* (`*KEY*`, `*TOKEN*`, …), a secret-store file name, or a whole-environment expansion | value-free (T2) |
84
+ | `secret/connection-password` | nonempty password between the first userinfo colon and final `@` in a `scheme://` authority | URI credential context; only password withheld |
85
+ | `secret/source-reference` | an env-var *name* with a complete credential component, a secret-store file name, or a whole-environment expansion | value-free (T2) |
86
+
87
+ Vendor/JWT boundaries use ASCII identifier characters so credentials adjacent
88
+ to CJK prose are detected while English identifier substrings stay quiet.
89
+ The new GitHub installation rule retains the complete `ghs_APPID_JWT` wrapper,
90
+ including long signatures, under the normal payload cap. App ID is opaque;
91
+ the JWT header must decode to JSON with a nonempty ASCII string `alg`. Generic
92
+ JWT detection requires that same declared header type. No business claims,
93
+ issuer, expiry or signature are authenticated, and algorithms are not limited
94
+ to a hardcoded enum. Format references: [GitHub's format notice](https://github.blog/changelog/2026-04-24-notice-about-upcoming-new-format-for-github-app-installation-tokens/)
95
+ and [updated format guidance](https://github.blog/changelog/2026-05-15-github-app-installation-tokens-per-request-override-header/).
96
+
97
+ AWS group/user/role/policy IDs (`AGPA`/`AIDA`/`AROA`/`ANPA`) are resource
98
+ identifiers and are excluded from the access-key rule, following the
99
+ [AWS prefix table](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids).
100
+ Their appearance inside a URI password or another credential context does not
101
+ exempt that enclosing credential. The JWT header type follows
102
+ [RFC 7515 §4.1.1](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1).
103
+
104
+ PyPI detection follows its [official scanner format](https://docs.pypi.org/api/secrets/#detecting-the-pypi-secret-format).
105
+ The entire body is captured under the normal payload cap, including longer
106
+ Macaroon caveats. `pypi-client-library`, short examples and whole placeholders
107
+ remain quiet. This is shape detection, without deserializing the Macaroon,
108
+ verifying authorization or reporting/revoking tokens through PyPI's API.
109
+ The legacy broad `sk-` shape remains protected pending a complete format
110
+ review; ordinary long component names with that shape can still match.
111
+
112
+ Variable references support `$NAME`, `${NAME}`, `$env:NAME` and `%NAME%`.
113
+ Underscores and camelCase/acronym boundaries separate complete components:
114
+ `TOKEN`, `PASSWORD`, `API_KEY` and `accessToken` are credential names;
115
+ `MONKEY` and `API_KEYBOARD` are not. A terminal `COUNT`, `LENGTH` or `ENABLED`
116
+ component denotes metadata (`TOKEN_COUNT`, `KEY_ENABLED`). Arbitrarily glued
117
+ lowercase/all-capital names are not split by substring guessing. Public-key
118
+ names retain the existing conservative behavior; there is no `PUBLIC*`
119
+ exemption. A benign first reference cannot hide a later credential reference.
120
+ Names are classified without resolving or reading their values.
121
+ Bare lower/title-case `key` (`$key`, `${key}`) is ambiguous with an ordinary
122
+ dictionary/schema key and is not classified by name alone. Uppercase `KEY`,
123
+ qualified names such as `apiKey`, and explicit `$env:key`/`%key%` references
124
+ remain protected. This narrow name boundary does not exempt source files or
125
+ template expressions as a whole; stronger names still cause refusal.
126
+
127
+ The URI rule uses original text coordinates. It supports percent encoding,
128
+ JSON-escaped scheme slashes, empty usernames (e.g. Redis), and literal `@`
129
+ inside a password by selecting the final authority separator. Complete
130
+ template expressions (`<PASSWORD>`, `${VAR}`, `%VAR%`) and redaction markers are
131
+ exempt; plain short/weak passwords are not. Variable-reference facts still
132
+ apply independently and cannot be swallowed by an overlapping URI span.
133
+ Raw `/`, `?`, `#`, whitespace and quote delimiters end the authority: encode
134
+ them inside a password. This rule does not cover non-URI DSNs, fully encoded
135
+ URLs or arbitrary nested serialization. Accounts and hosts remain visible.
136
+ Syntax reference: [RFC 3986 §3.2.1](https://www.rfc-editor.org/rfc/rfc3986.html#section-3.2.1).
74
137
 
75
138
  Two design rules that keep T1 deterministic:
76
139
 
77
140
  1. **Structural validation** where the format allows it. A JWT is only a JWT
78
- if segment 1 base64-decodes to JSON with `alg`; otherwise it is a version
141
+ if segment 1 base64-decodes to JSON with the declared ASCII string `alg`; otherwise it is a version
79
142
  string (`1.2.3`) or a hostname (`api.example.com`), both of which occur
80
143
  constantly in this repository's own text.
81
144
  2. **No generic keyword patterns.** `password=` / `secret=` are *context*
@@ -109,19 +172,24 @@ repository's own prose quiet.
109
172
 
110
173
  ## Placeholder allowlist (design 5.1)
111
174
 
112
- Deterministic, in-repo, no config: `YOUR_API_KEY_HERE`, `EXAMPLE_SECRET`,
113
- `changeme`, `dummy`, `example`, `test`, `fake`, `placeholder`, `TODO`,
114
- `<REDACTED>`, `[REDACTED]`, `<...>` markers, `${...}` interpolations,
115
- all-same-char runs (`xxxx`, `****`), sequential runs, and vendor-prefixed
116
- words (`sk-test`). A token whose **alphabet** is trivial is a placeholder; a
117
- real credential can never live in that regime.
175
+ Deterministic, in-repo, no config: exact static words such as
176
+ `YOUR_API_KEY_HERE`, `EXAMPLE_SECRET`, `dummy-value`, `changeme`, `test`,
177
+ `fake`, `placeholder` and `TODO`; whole `<REDACTED>`/`[REDACTED]` markers,
178
+ identifier templates (`<TOKEN>`, `${NAME}`), and whole trivial-alphabet bodies.
179
+ Known public vendor prefixes can be removed before checking the entire body,
180
+ so explicit vendor examples (`sk-test`, a vendor prefix followed only by `x`)
181
+ remain quiet. The two fixed AWS documentation example IDs are exact entries.
182
+ An arbitrary random credential containing `xxx`, `dummy` or `redact`, or
183
+ ending in `none`/`example`, is not a placeholder. A marker word inside a
184
+ private-key block cannot exempt the entire block. Independent secret-source
185
+ facts still apply to variable templates.
118
186
 
119
187
  ## Configuration (environment)
120
188
 
121
189
  | Variable | Meaning |
122
190
  |---|---|
123
- | `AGENT_GUARD_EXFIL_CHANNEL` | default egress channel for `check_span.py` |
124
- | `AGENT_GUARD_EXFIL_MAX_BYTES` | payload size cap (default 4 MiB); over-cap is `BLOCK_OUTPUT_UNSCANNABLE` |
191
+ | `AGENT_GUARD_EXFIL_CHANNEL` | default egress channel for both text CLIs |
192
+ | `AGENT_GUARD_EXFIL_MAX_BYTES` | input/scan cap (default 4 MiB); over-cap input is `BLOCK_OUTPUT_UNSCANNABLE`; sanitizer plan files use the same bound |
125
193
  | `AGENT_GUARD_HOSTNAMES` / `AGENT_GUARD_HOME_MARKERS` | extra literal host names / home markers |
126
194
  | `AGENT_GUARD_HOME_PREFIXES` | extra literal prefixes to treat as host-identifying |
127
195
  | `AGENT_GUARD_SYSTEM_PREFIXES` | override the system-prefix allow set |
@@ -0,0 +1,99 @@
1
+ """Shared, bounded CLI input and host-side context resolution."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import sys
6
+ import time
7
+
8
+ from core import policy, redaction
9
+ from core.classifier import discover_workspace
10
+
11
+
12
+ DEFAULT_STDIN_TIMEOUT_SEC = 10.0
13
+
14
+
15
+ class StdinIdle(Exception):
16
+ """No first byte arrived within the configured wait."""
17
+
18
+
19
+ class PayloadTooLarge(Exception):
20
+ """Fixed, value-free diagnostic for an input budget refusal."""
21
+
22
+
23
+ def _stdin_timeout():
24
+ try:
25
+ value = float(os.environ.get("AGENT_GUARD_STDIN_TIMEOUT", ""))
26
+ except (TypeError, ValueError):
27
+ return DEFAULT_STDIN_TIMEOUT_SEC
28
+ return value if 0 < value < float("inf") else DEFAULT_STDIN_TIMEOUT_SEC
29
+
30
+
31
+ def read_bounded_text(stream, max_bytes):
32
+ """Read at most the cap plus one byte, then strictly decode UTF-8.
33
+
34
+ Text-only streams (e.g. StringIO) are bounded in characters first and
35
+ checked in bytes next. They retain at most four times the byte cap.
36
+ No partial input is ever returned as a successful payload.
37
+ """
38
+ if type(max_bytes) is not int or max_bytes < 0:
39
+ raise ValueError("invalid payload size limit")
40
+ source = getattr(stream, "buffer", stream)
41
+ chunks = []
42
+ total = 0
43
+ kind = None
44
+ while True:
45
+ data = source.read(min(65536, max_bytes + 1 - total))
46
+ if not isinstance(data, (str, bytes)) or (kind is not None and type(data) is not kind):
47
+ raise ValueError("invalid input stream")
48
+ kind = type(data)
49
+ if not data:
50
+ break
51
+ total += len(data.encode("utf-8", errors="strict")) if isinstance(data, str) else len(data)
52
+ if total > max_bytes:
53
+ raise PayloadTooLarge("payload exceeds scan cap")
54
+ chunks.append(data)
55
+ if kind is str:
56
+ return "".join(chunks)
57
+ return b"".join(chunks).decode("utf-8", errors="strict")
58
+
59
+
60
+ def read_payload(stream=None, timeout=None, max_bytes=None):
61
+ """Bound payload memory; retain the existing first-byte timeout.
62
+
63
+ This is not an end-to-end transport deadline: once a producer has
64
+ spoken, reading still waits for EOF or the size refusal boundary.
65
+ """
66
+ stdin = stream if stream is not None else sys.stdin
67
+ limit = redaction.max_scan_bytes() if max_bytes is None else max_bytes
68
+ if stdin.isatty():
69
+ sys.stderr.write("exfil-guard: reading payload from stdin "
70
+ "(Ctrl-D to finish)\n")
71
+ return read_bounded_text(stdin, limit)
72
+ try:
73
+ import select
74
+ except ImportError: # pragma: no cover - non-POSIX
75
+ return read_bounded_text(stdin, limit)
76
+ budget = _stdin_timeout() if timeout is None else timeout
77
+ deadline = time.monotonic() + budget
78
+ while True:
79
+ remaining = deadline - time.monotonic()
80
+ if remaining <= 0:
81
+ raise StdinIdle("no payload arrived on stdin within the wait; "
82
+ "pipe the text in or use a terminal")
83
+ try:
84
+ ready, _, _ = select.select([stdin], [], [], min(remaining, 0.5))
85
+ except (OSError, ValueError):
86
+ return read_bounded_text(stdin, limit)
87
+ if ready:
88
+ return read_bounded_text(stdin, limit)
89
+
90
+
91
+ def resolve_context(workspace=None, mode=None):
92
+ """Read the same workspace and host-side mode for both text CLIs."""
93
+ if workspace is None:
94
+ workspace = discover_workspace(os.getcwd())
95
+ if mode is None:
96
+ trash_root = os.environ.get(
97
+ "AGENT_GUARD_TRASH", os.path.join(workspace, ".agent-trash"))
98
+ mode = policy.load_mode(trash_root)["mode"]
99
+ return workspace, mode