@mokuyoaxis/agent-guard 0.2.5-rc1 → 0.2.5-rc3

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/CONTRIBUTING.md +24 -0
  2. package/README.md +43 -10
  3. package/README.zh-CN.md +35 -9
  4. package/SECURITY.md +14 -8
  5. package/adapters/dsh/harness/README.md +5 -0
  6. package/adapters/dsh/harness/guard_lab.py +3 -2
  7. package/adapters/kimi-code/harness/README.md +5 -0
  8. package/core/audit.py +170 -25
  9. package/core/lab.py +82 -9
  10. package/docs/README.md +20 -4
  11. package/docs/design/architecture.md +12 -5
  12. package/docs/design/compatibility.md +48 -6
  13. package/docs/guides/audit-metadata.md +77 -0
  14. package/docs/guides/getting-started.md +13 -6
  15. package/docs/guides/harness-capabilities.md +7 -1
  16. package/docs/history/friction.md +4 -3
  17. package/docs/lab/blue-team-calibration.md +45 -0
  18. package/docs/lab/examples/blue-team-calibration.py +53 -0
  19. package/docs/lab/guard-lab.md +20 -2
  20. package/docs/releases/release-notes-0.2.5-rc2.md +101 -0
  21. package/docs/releases/release-notes-0.2.5-rc3.md +74 -0
  22. package/docs/reports/blue-team-lab-2026-10.md +73 -0
  23. package/docs/research/README.md +41 -0
  24. package/docs/research/content-authorization.md +54 -0
  25. package/docs/research/dataflow-observability.md +48 -0
  26. package/docs/research/delegation-provenance.md +56 -0
  27. package/docs/research/evaluation-method.md +51 -0
  28. package/docs/research/lab-observations-2026-10.json +43 -0
  29. package/guard_lab.py +11 -0
  30. package/package.json +1 -1
  31. package/skills/delete-guard/SKILL.md +6 -3
  32. package/skills/delete-guard/references/policy.md +14 -10
  33. package/skills/delete-guard/scripts/gc.py +18 -3
  34. package/skills/delete-guard/scripts/safe_delete.py +1 -1
  35. package/skills/delete-guard/scripts/status.py +9 -7
  36. package/skills/exfil-guard/SKILL.md +1 -1
  37. package/skills/exfil-guard/references/rules.md +6 -3
package/CONTRIBUTING.md CHANGED
@@ -57,6 +57,20 @@ Review, merge, tagging, GitHub Release, and npm publication are separate
57
57
  maintainer decisions. Acceptance of a contribution does not promise a specific
58
58
  release date.
59
59
 
60
+ ### Defensive research and reproductions
61
+
62
+ Lab develops through small, bounded experiments. Forks, PRs, method reviews
63
+ and independent reproductions are welcome, without a promised experiment or
64
+ release cadence. Public research focuses on defensive controls, provenance,
65
+ task utility and evidence limits. Share synthetic, sanitized observations;
66
+ coordinate sensitive details privately before posting executable adversarial
67
+ payloads or raw captures.
68
+
69
+ Include the code/host versions, declared model configuration, input/task,
70
+ budget, control conditions and observed channels. Report authorization,
71
+ task completion and evidence health separately, retaining failed and
72
+ inconclusive trials. See the [research index](docs/research/README.md).
73
+
60
74
  ## 中文
61
75
 
62
76
  ### 先发 Issue
@@ -99,3 +113,13 @@ Core/CLI、模拟宿主还是真实宿主。模拟测试通过不能写成所有
99
113
 
100
114
  审阅、合并、标签、GitHub Release 与 npm 发布是维护者分别作出的决定;贡献被
101
115
  接受不代表承诺在某个版本或日期发布。
116
+
117
+ ### 防守研究与独立复现
118
+
119
+ Lab 将按小规模、明确范围逐步推进,欢迎 fork、PR、方法评审与独立复现,
120
+ 不承诺固定实验频率或发布时间。公开研究重点是防护、来源、正常任务效用和证据边界。
121
+ 分享合成、去敏后的观察;可执行诱导载荷、敏感复现细节与原始捕获先私下协调。
122
+
123
+ 注明代码/宿主版本、客户端声明的模型配置、输入/任务、预算、对照条件和观察信道。
124
+ 分别报告授权遵守、任务完成和证据健康,保留失败及未定试次。
125
+ 方法与公开示例见[研究导航](docs/research/README.md)。
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![npm stable](https://img.shields.io/npm/v/%40mokuyoaxis%2Fagent-guard.svg)](https://www.npmjs.com/package/@mokuyoaxis/agent-guard)
5
5
  [![License](https://img.shields.io/github/license/mokuyoaxis/agent-guard)](LICENSE)
6
6
  [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
7
- [![0.2.5-rc1](https://img.shields.io/badge/RC-0.2.5--rc1-5B6B7A)](docs/releases/release-notes-0.2.5-rc1.md)
7
+ [![0.2.5-rc3 candidate](https://img.shields.io/badge/RC-0.2.5--rc3-5B6B7A)](docs/releases/release-notes-0.2.5-rc3.md)
8
8
 
9
9
  **Make destructive agent actions reversible by default.** · [简体中文](README.zh-CN.md)
10
10
 
@@ -65,6 +65,23 @@ external transfer or model request. Existing
65
65
  [DSH](docs/reports/test-report-dsh-guard-lab.md) reports retain their bounded
66
66
  results, failures and review states.
67
67
 
68
+ RC3 adds [blue-team research](docs/research/README.md), a
69
+ [sanitized experiment report](docs/reports/blue-team-lab-2026-10.md) and a
70
+ [portable four-control example](docs/lab/blue-team-calibration.md).
71
+ The research covers provenance, disclosure permissions and task utility in
72
+ bounded private experiments; those methods do not extend production hook
73
+ coverage. Lab proceeds gradually. Forks, PRs and independent defensive
74
+ reproductions are welcome; preserve failed and inconclusive results.
75
+
76
+ From the RC3 checkout or review package, run all four existing controls:
77
+
78
+ ```sh
79
+ blue_run="$(mktemp -d)"
80
+ python3 docs/lab/examples/blue-team-calibration.py --output-dir "$blue_run/controls"
81
+ ```
82
+
83
+ This example calls no model; its summary describes instrument calibration.
84
+
68
85
  <a id="quick-start-with-your-coding-agent"></a>
69
86
 
70
87
  ## Install and choose a version
@@ -75,7 +92,9 @@ native bridges and optional capture helpers have their own requirements.
75
92
  | Version | Status |
76
93
  |---|---|
77
94
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | Published stable baseline |
78
- | [0.2.5-rc1](docs/releases/release-notes-0.2.5-rc1.md) | Maintenance release candidate; select the exact RC version |
95
+ | [0.2.5-rc1](docs/releases/release-notes-0.2.5-rc1.md) | Previous published prerelease baseline |
96
+ | [0.2.5-rc2](docs/releases/release-notes-0.2.5-rc2.md) | Maintenance prerelease; check the exact publication receipts |
97
+ | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | Research/documentation source preview; package publication requires separate receipts |
79
98
 
80
99
  For the published stable package, use a chosen, stable user-owned prefix:
81
100
 
@@ -92,13 +111,18 @@ git clone https://github.com/mokuyoaxis/agent-guard.git
92
111
  cd agent-guard
93
112
  ```
94
113
 
95
- For the RC, select `@mokuyoaxis/agent-guard@0.2.5-rc1` explicitly; the RC
114
+ For RC2, select `@mokuyoaxis/agent-guard@0.2.5-rc2` explicitly; the RC
96
115
  channel does not replace stable `latest`. Check the
97
- [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.5-rc1)
98
- or [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.5-rc1)
99
- for publication. A reviewed checkout or locally supplied tarball is also usable. See
116
+ [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.5-rc2)
117
+ and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.5-rc2)
118
+ for publication. A reviewed checkout or supplied tarball is also usable;
119
+ the manifest alone does not establish registry availability. See
100
120
  [setup and the agent setup prompt](docs/guides/getting-started.md).
101
121
 
122
+ Evaluate RC3 through a reviewed source checkout or supplied tarball. Its
123
+ manifest and a main-branch commit do not establish a registry release;
124
+ version tags and GitHub/npm package publication are separate steps.
125
+
102
126
  ## Recover a supported deletion
103
127
 
104
128
  From the workspace being protected, point at your package/checkout root:
@@ -122,11 +146,18 @@ may write quarantine/audit metadata and a Git local exclude entry. Advisory
122
146
  exit 0 is not permission to execute a BLOCK or ASK.
123
147
  See the [policy and assessment contract](skills/delete-guard/references/policy.md).
124
148
 
125
- The RC adds quarantine control-path protection, excludes PURGED transactions
126
- from active GC planning, and minimizes restore/safe_delete audit fields.
149
+ RC1 added quarantine control-path protection, excluded PURGED transactions
150
+ from active GC planning, and minimized restore/safe_delete audit fields.
127
151
  Exact CLI/manifest recovery paths remain available. These changes are not in
128
152
  the published 0.2.4 package; see the [RC notes](docs/releases/release-notes-0.2.5-rc1.md).
129
153
 
154
+ RC2 introduced shared audit metadata projection,
155
+ uses opaque session correlation, and limits legacy status/GC metadata.
156
+ See the [audit contract and remaining boundaries](docs/guides/audit-metadata.md).
157
+ It adds observer startup diagnostics and correct cancellation accounting;
158
+ the original intermittent timeout's cause remains unknown. See the
159
+ [RC2 scope and evidence](docs/releases/release-notes-0.2.5-rc2.md).
160
+
130
161
  ## Check text before emission
131
162
 
132
163
  The payload owner invokes the scanner and applies its decision.
@@ -202,13 +233,15 @@ reconstruction and known gaps. It cannot recreate bytes that no source kept.
202
233
  | [Architecture](docs/design/architecture.md) | Shared Core, compensation and adapter flow |
203
234
  | [Threat model](docs/design/threat-model.md) | Trust assumptions and unresolved boundaries |
204
235
  | [Compatibility](docs/design/compatibility.md) | Interface and release contracts |
205
- | [0.2.5-rc1 notes](docs/releases/release-notes-0.2.5-rc1.md) | This candidate's changes and validation status |
236
+ | [Blue-team research](docs/research/README.md) | Defensive methods, sanitized results and a zero-model starting point |
237
+ | [0.2.5-rc3 notes](docs/releases/release-notes-0.2.5-rc3.md) | Current source candidate's scope and validation status |
206
238
 
207
239
  ## Contributing
208
240
 
209
241
  Bug reports, compatibility evidence, documentation fixes and focused code
210
242
  changes are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) before sharing
211
- logs. Use [Issues](https://github.com/mokuyoaxis/agent-guard/issues) and
243
+ defensive research, independent reproductions or logs. Use
244
+ [Issues](https://github.com/mokuyoaxis/agent-guard/issues) and
212
245
  [Pull Requests](https://github.com/mokuyoaxis/agent-guard/pulls); keep credentials,
213
246
  private configuration and unredacted incident records out of public reports.
214
247
 
package/README.zh-CN.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![npm 稳定版](https://img.shields.io/npm/v/%40mokuyoaxis%2Fagent-guard.svg)](https://www.npmjs.com/package/@mokuyoaxis/agent-guard)
5
5
  [![License](https://img.shields.io/github/license/mokuyoaxis/agent-guard)](LICENSE)
6
6
  [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
7
- [![0.2.5-rc1](https://img.shields.io/badge/RC-0.2.5--rc1-5B6B7A)](docs/releases/release-notes-0.2.5-rc1.md)
7
+ [![0.2.5-rc3 候选](https://img.shields.io/badge/RC-0.2.5--rc3-5B6B7A)](docs/releases/release-notes-0.2.5-rc3.md)
8
8
 
9
9
  **让 AI Agent 的破坏性操作默认可逆。** · [English](README.md)
10
10
 
@@ -56,6 +56,21 @@ harness/版本/模型、任务、协议及非防护配置。结果只覆盖
56
56
  [DSH](docs/reports/test-report-dsh-guard-lab.md) 报告保留各自的有限结论、
57
57
  失败和待审状态。
58
58
 
59
+ RC3 新增[蓝队研究](docs/research/README.md)、
60
+ [去敏实验报告](docs/reports/blue-team-lab-2026-10.md)和
61
+ [便携四控制示例](docs/lab/blue-team-calibration.md),公开来源、发送授权和正常任务效用的
62
+ 有界研究。私有装配中的验证不扩展生产 hook 覆盖。Lab 将缓慢、小规模推进,欢迎 fork、PR
63
+ 与独立防守复现;失败和未定结果也应保留。
64
+
65
+ 在 RC3 源码或评审包根目录,可一次运行现有四种控制:
66
+
67
+ ```sh
68
+ blue_run="$(mktemp -d)"
69
+ python3 docs/lab/examples/blue-team-calibration.py --output-dir "$blue_run/controls"
70
+ ```
71
+
72
+ 示例不调用模型,摘要只用于仪器校准。
73
+
59
74
  ## 安装与版本选择
60
75
 
61
76
  Core 需要 Python 3.9+ 和 Git。示例采用 POSIX Shell;原生桥接和可选采集
@@ -64,7 +79,9 @@ Core 需要 Python 3.9+ 和 Git。示例采用 POSIX Shell;原生桥接和可
64
79
  | 版本 | 状态 |
65
80
  |---|---|
66
81
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | 已发布的稳定基线 |
67
- | [0.2.5-rc1](docs/releases/release-notes-0.2.5-rc1.md) | 维护预发布;显式选择准确 RC 版本 |
82
+ | [0.2.5-rc1](docs/releases/release-notes-0.2.5-rc1.md) | 已发布的历史预发布基线 |
83
+ | [0.2.5-rc2](docs/releases/release-notes-0.2.5-rc2.md) | 维护预发布;以准确版本的发布回执为准 |
84
+ | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | 研究/文档源码预览;包发布以独立回执为准 |
68
85
 
69
86
  稳定包可安装到用户选定的长期目录:
70
87
 
@@ -81,12 +98,15 @@ git clone https://github.com/mokuyoaxis/agent-guard.git
81
98
  cd agent-guard
82
99
  ```
83
100
 
84
- RC 显式选择 `@mokuyoaxis/agent-guard@0.2.5-rc1`;RC 通道不替换稳定版 `latest`。
85
- 发布状态以 [GitHub Release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.5-rc1)
86
- 和 [npm 版本页](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.5-rc1)为准,
87
- 也可使用已核查的 checkout 或本地提供的 tarball。
101
+ RC2 显式选择 `@mokuyoaxis/agent-guard@0.2.5-rc2`;RC 通道不替换稳定版 `latest`。
102
+ 发布状态以 [GitHub Release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.5-rc2)
103
+ 和 [npm 版本页](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.5-rc2)为准,
104
+ 也可使用已核查的 checkout 或提供的 tarball;manifest 版本不代表 registry 已可安装。
88
105
  接入步骤与 Agent 提示词见[入门指南](docs/guides/getting-started.md)。
89
106
 
107
+ 通过已核查源码 checkout 或提供的 tarball 评估 RC3;manifest 或 main 提交不代表 registry 已发布。
108
+ 版本标签与 GitHub/npm 包发布分别执行。
109
+
90
110
  ## 恢复一次受支持的删除
91
111
 
92
112
  从要保护的工作区调用你的安装包/源码路径:
@@ -108,10 +128,15 @@ advisory `check.py` 和 `safe_delete.py --dry-run` 保持命令目标不变,
108
128
  隔离区/审计元数据及 Git 本地 exclude。advisory 退出码 0 不代表 BLOCK/ASK
109
129
  操作获准执行。详见[策略与评估契约](skills/delete-guard/references/policy.md)。
110
130
 
111
- 本 RC 增加隔离区控制路径保护、从活跃 GC 计划排除 PURGED 事务,并最小化
131
+ RC1 已增加隔离区控制路径保护、从活跃 GC 计划排除 PURGED 事务,并最小化
112
132
  restore/safe_delete 审计字段;CLI/manifest 仍保留准确恢复路径。
113
133
  这些维护不属于已发布的 0.2.4 包,见 [RC 说明](docs/releases/release-notes-0.2.5-rc1.md)。
114
134
 
135
+ RC2 进一步限定通用审计字段、使用不透明 session 关联,
136
+ 并收口旧日志 status 展示与 GC 元信息,见[审计契约及保留边界](docs/guides/audit-metadata.md)。
137
+ 同时补充 observer 启动诊断与取消健康记账;最初偶发超时的具体原因仍未知,
138
+ 见 [RC2 范围与证据](docs/releases/release-notes-0.2.5-rc2.md)。
139
+
115
140
  ## 外发前检查文本
116
141
 
117
142
  持有载荷的调用方主动运行扫描器,并按判决处理文本:
@@ -178,11 +203,12 @@ Git/会话/缓存证据恢复项目,区分原文、重建与确认缺失
178
203
  | [架构](docs/design/architecture.md) | 共享 Core、补偿与适配器数据流 |
179
204
  | [威胁模型](docs/design/threat-model.md) | 信任假设与尚未解决的边界 |
180
205
  | [兼容契约](docs/design/compatibility.md) | 接口与发布约定 |
181
- | [0.2.5-rc1 说明](docs/releases/release-notes-0.2.5-rc1.md) | 本候选变更与验收状态 |
206
+ | [蓝队研究](docs/research/README.md) | 防守方法、去敏结果与零模型起点 |
207
+ | [0.2.5-rc3 说明](docs/releases/release-notes-0.2.5-rc3.md) | 当前源码候选范围与验收状态 |
182
208
 
183
209
  ## 参与贡献
184
210
 
185
- 欢迎缺陷报告、兼容性证据、文档修订和范围明确的代码改动。分享日志前阅读
211
+ 欢迎 fork、PR、独立防守复现、缺陷报告、兼容性证据和文档修订。分享研究资料或日志前阅读
186
212
  [CONTRIBUTING.md](CONTRIBUTING.md),通过
187
213
  [Issues](https://github.com/mokuyoaxis/agent-guard/issues) 和
188
214
  [Pull Requests](https://github.com/mokuyoaxis/agent-guard/pulls)参与;
package/SECURITY.md CHANGED
@@ -3,8 +3,9 @@
3
3
  ## Reporting
4
4
 
5
5
  Open a GitHub issue for non-sensitive issues, or contact the maintainer
6
- directly for anything you believe is exploitable. Please include the
7
- verdict JSON and audit lines involved.
6
+ directly for anything you believe is exploitable. Include the minimal
7
+ sanitized verdict/audit metadata needed to explain it, using synthetic data
8
+ where possible. See [CONTRIBUTING.md](CONTRIBUTING.md) before sharing captures.
8
9
 
9
10
  ## What agent-guard claims to be
10
11
 
@@ -27,10 +28,10 @@ will therefore report hits such as:
27
28
  - credential-adjacent wording in `docs/guides/publishing-from-ephemeral-environments.md`
28
29
  (a guide about *avoiding* credential leaks).
29
30
 
30
- As of v0.1.0 a full self-scan reports 61 hits (29 high / 10 medium / 22
31
- low) with **zero in runtime decision paths** - all are documentation or
32
- test fixtures. If you find a hit outside docs/tests/fixtures, please
33
- report it.
31
+ A historical v0.1.0 self-scan reported 61 hits (29 high / 10 medium / 22 low).
32
+ That count is a dated checkpoint, not a current runtime-reachability audit.
33
+ Review the concrete call and its context; report unexpected runtime behavior
34
+ with a minimal, sanitized reproduction.
34
35
 
35
36
  ## Data handling
36
37
 
@@ -47,7 +48,12 @@ the configured provider through the host and consume quota; they are separate
47
48
  from local command checks and require a selected experiment scope.
48
49
 
49
50
  Recovery manifests, CLI diagnostics and historical audit records can contain
50
- exact paths or other private text. Audit minimization in the 0.2.5-rc1 source
51
- candidate does not make every output or old record secret-free. The exfil text
51
+ exact paths or other private text. Writer minimization introduced in RC1 and
52
+ the shared projection introduced in RC2 remain in RC3; they do not make every
53
+ output or old record secret-free. The exfil text
52
54
  CLIs return decisions/plans or sanitized stdout; they do not automatically
53
55
  persist egress audit events. Review and redact evidence before sharing it.
56
+
57
+ The [public blue-team research](docs/research/README.md) shares sanitized
58
+ methods and aggregate observations. Raw sessions, private configuration and
59
+ reusable induction payloads are not part of those new public materials.
@@ -6,6 +6,11 @@ host completion explicitly user-declared. No production dependency is added.
6
6
  The default remains guard-off; the paired workflow below supplies the local
7
7
  Guard patch only to guard-on members.
8
8
 
9
+ For a zero-model starting point, use the [four-control example](../../../docs/lab/blue-team-calibration.md).
10
+ The [defensive research](../../../docs/research/README.md) describes separate
11
+ private provenance/delegation experiments; it does not expand this runner's
12
+ single-root native receipt contract.
13
+
9
14
  ## Select the runtime
10
15
 
11
16
  Use Node.js 22.23.2 or another runtime with the required native Zstandard APIs.
@@ -221,7 +221,7 @@ def run_trial(
221
221
  node_executable: str = "node",
222
222
  guard_state: str = "off", guard_patch_file: Optional[Path] = None,
223
223
  expected_configuration_sha256: Optional[str] = None,
224
- *, guard_profile="deletion-v1", dsh_root=None,
224
+ *, guard_profile="deletion-v1", dsh_root=None, _prepare_run=None,
225
225
  ) -> dict:
226
226
  if case_id not in {"clean", "injection-probe"}:
227
227
  raise LabError("this runner supports clean and injection-probe only")
@@ -268,7 +268,8 @@ def run_trial(
268
268
  "trial_group": trial_group, "task_file": task_file,
269
269
  "non_guard_configuration_sha256": preflight["non_guard_configuration_sha256"],
270
270
  }
271
- prepared = prepare_run(
271
+ # Private experiments can pass a fixture constructor without module patches.
272
+ prepared = (prepare_run if _prepare_run is None else _prepare_run)(
272
273
  output / "fixture", output / "evidence", case_id,
273
274
  model_usage="real", attack_sample=attack_sample, **metadata,
274
275
  )
@@ -5,6 +5,11 @@ This POSIX helper pins **Kimi Code 2.1.1**, captures prompt mode with
5
5
  Configuration checks and profile preparation require Python 3.11+ for `tomllib`;
6
6
  the shared Guard Core retains its Python 3.9+ floor. No dependency is installed.
7
7
 
8
+ Start with the [four-control example](../../../docs/lab/blue-team-calibration.md)
9
+ for host-independent calibration. The [defensive research](../../../docs/research/README.md)
10
+ includes separate Node Kimi 0.42.0 observations; they do not change this helper's
11
+ Kimi 2.1.1 version contract.
12
+
8
13
  ## Private matched homes
9
14
 
10
15
  Select the approved source home and the exact 2.1.1 executable. There may be a
package/core/audit.py CHANGED
@@ -1,22 +1,167 @@
1
1
  """Auditability pillar: append-only JSONL evidence log.
2
2
 
3
- Every decision the guard makes - allow, relocate, compensate, block - is
4
- appended as one JSON object per line. The log is intentionally dumb: no
5
- rotation, no aggregation, no mutation. Post-hoc verification reads it
6
- sequentially. A torn or corrupt line is skipped on read, never rewritten.
3
+ Records contain supported metadata, not arbitrary caller payloads. Reading
4
+ legacy records applies the same projection without rewriting the log.
5
+ Durability and append-only storage remain separate from recovery manifests,
6
+ which retain the exact paths required to restore data.
7
7
  """
8
8
  from __future__ import annotations
9
9
 
10
- import getpass
10
+ from collections import deque
11
+ from functools import lru_cache
12
+ import hashlib
11
13
  import json
14
+ import math
12
15
  import os
13
- import platform
16
+ import re
14
17
  import threading
15
18
  import time
16
19
  import uuid
17
- from typing import Any, Dict, List, Optional
20
+ from typing import Any, Dict, List
18
21
 
19
22
  _APPEND_LOCK = threading.Lock()
23
+ _LOCAL_SESSION = uuid.uuid4().hex
24
+ _CORRELATION_RE = re.compile(r"sha256:[0-9a-f]{64}\Z")
25
+ _TXID_RE = re.compile(r"[0-9]{8}-[0-9]{6}-[0-9a-f]{8}\Z")
26
+ _TIMESTAMP_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\Z")
27
+ _HASH_RE = re.compile(r"[0-9a-f]{64}\Z")
28
+ _GIT_SHA_RE = re.compile(r"[0-9a-f]{40}(?:[0-9a-f]{24})?\Z")
29
+ _COUNTS = frozenset({
30
+ "target_count", "moved_count", "skipped_count", "restored_count",
31
+ "conflict_count", "error_count", "missing_count", "moved", "skipped",
32
+ "enumerated", "start", "end", "length",
33
+ })
34
+ _IDENTIFIERS = frozenset({"txid", "check_id", "plan_id"})
35
+ _ID_LISTS = frozenset({"txids", "backup_txids", "purged", "missing"})
36
+ _COMPENSATION_FIELDS = frozenset({
37
+ "strategy", "txid", "status", "moved", "skipped", "enumerated", "sha",
38
+ })
39
+
40
+
41
+ def correlation_id(value: str) -> str:
42
+ """Opaque, deterministic correlation; not encryption or authentication.
43
+
44
+ Already-projected identifiers remain stable when read or re-appended.
45
+ Surrogate escapes in POSIX metadata are hashed without emitting them.
46
+ """
47
+ if _CORRELATION_RE.fullmatch(value):
48
+ return value
49
+ return "sha256:" + hashlib.sha256(
50
+ value.encode("utf-8", errors="surrogatepass")).hexdigest()
51
+
52
+
53
+ def _identifier(value: str) -> str:
54
+ # Generated recovery/check IDs stay directly usable. Other spellings
55
+ # retain correlation without becoming an arbitrary text channel.
56
+ return value if _TXID_RE.fullmatch(value) else correlation_id(value)
57
+
58
+
59
+ @lru_cache(maxsize=1)
60
+ def _enums():
61
+ # Import after module initialization: recovery imports the ID/time
62
+ # helpers above, and needs no policy or redaction decisions here.
63
+ from . import dialects, policy, redaction
64
+ decisions = frozenset({"ALLOW", "RELOCATE", "SNAPSHOT", "SANITIZE", "ASK", "BLOCK"})
65
+ return {
66
+ "event": frozenset({
67
+ "check", "ask", "decision", "advisory", "intent", "outcome",
68
+ "enforce-block", "enforce-intent", "enforce-error", "enforce-proceed",
69
+ "restore", "gc-intent", "gc",
70
+ }) | {"exfil-" + decision.lower() for decision in decisions},
71
+ "decision": decisions, "action": decisions | {"PURGED"},
72
+ "code": frozenset(policy.EXPLANATIONS),
73
+ "tool": frozenset({"safe_delete", "check", "restore", "gc"}),
74
+ "phase": frozenset({"advisory", "intent", "complete"}),
75
+ "outcome": frozenset({
76
+ "relocated to quarantine", "deleted directly (provably regenerable)",
77
+ "deleted directly (quarantine housekeeping)",
78
+ }),
79
+ "dialect": frozenset(dialects.DIALECT_ALIASES.values()),
80
+ "dialect_requested": frozenset(dialects.DIALECT_ALIASES) | {"<redacted>"},
81
+ "dialect_outcome": frozenset({"ok", "unusable"}),
82
+ "strategy": frozenset({"relocate", "clean-enumerate", "snapshot"}),
83
+ "status": frozenset({"started", "complete", "partial", "storage-failed",
84
+ "failed", "incomplete"}),
85
+ "rule_id": frozenset(value for key, value in vars(redaction).items()
86
+ if key.startswith("RULE_") and isinstance(value, str)),
87
+ "family": frozenset({"secret", "path"}),
88
+ "confidence": frozenset({"deterministic", "contextual"}),
89
+ "channel": frozenset(redaction.CHANNELS),
90
+ "context": frozenset({"prose", "key", "uri-userinfo", "env-var"}),
91
+ "command": frozenset({"<redacted>"}),
92
+ "error": frozenset({"compensation failed"}),
93
+ }
94
+
95
+
96
+ def project(record: Dict[str, Any]) -> Dict[str, Any]:
97
+ """Supported metadata only; unknown fields/types/free text are omitted.
98
+
99
+ This is a closed record projection, not a general text sanitizer. Nested
100
+ compensation records and GC reason maps have explicit shapes. Recovery
101
+ journals, authorization state, and caller objects are never modified.
102
+ """
103
+ if not isinstance(record, dict):
104
+ raise TypeError("audit record must be an object")
105
+ stored: Dict[str, Any] = {}
106
+ for key, allowed in _enums().items():
107
+ value = record.get(key)
108
+ if key == "context" and isinstance(value, str) and value.startswith("key="):
109
+ value = "key"
110
+ if isinstance(value, str) and value in allowed:
111
+ stored[key] = value
112
+ for key in _COUNTS:
113
+ value = record.get(key)
114
+ if type(value) is int and value >= 0:
115
+ stored[key] = value
116
+ for key in ("force", "ok", "exempted"):
117
+ if type(record.get(key)) is bool:
118
+ stored[key] = record[key]
119
+ latency = record.get("guard_latency_ms")
120
+ if (type(latency) is int and latency >= 0 or
121
+ type(latency) is float and math.isfinite(latency) and latency >= 0):
122
+ stored["guard_latency_ms"] = latency
123
+ ts = record.get("ts")
124
+ if isinstance(ts, str) and _TIMESTAMP_RE.fullmatch(ts):
125
+ stored["ts"] = ts
126
+ for key in _IDENTIFIERS:
127
+ value = record.get(key)
128
+ if isinstance(value, str) and value:
129
+ stored[key] = _identifier(value)
130
+ for key in _ID_LISTS:
131
+ values = record.get(key)
132
+ if isinstance(values, list):
133
+ stored[key] = [_identifier(v) for v in values if isinstance(v, str) and v]
134
+ session = record.get("session")
135
+ if isinstance(session, str) and session:
136
+ stored["session"] = correlation_id(session)
137
+ digest = record.get("txid_sha256")
138
+ if isinstance(digest, str) and _HASH_RE.fullmatch(digest):
139
+ stored["txid_sha256"] = digest
140
+ digests = record.get("missing_txid_sha256")
141
+ if isinstance(digests, list):
142
+ stored["missing_txid_sha256"] = [
143
+ v for v in digests if isinstance(v, str) and _HASH_RE.fullmatch(v)]
144
+ sha = record.get("sha")
145
+ if "sha" in record and (sha is None or isinstance(sha, str) and _GIT_SHA_RE.fullmatch(sha)):
146
+ stored["sha"] = sha
147
+ span = record.get("span")
148
+ if (isinstance(span, list) and len(span) == 2 and
149
+ all(type(v) is int and v >= 0 for v in span) and span[1] >= span[0]):
150
+ stored["span"] = list(span)
151
+ if record.get("reasons") == []:
152
+ stored["reasons"] = []
153
+ compensations = record.get("compensations")
154
+ if isinstance(compensations, list):
155
+ stored["compensations"] = [
156
+ project({k: v for k, v in item.items() if k in _COMPENSATION_FIELDS})
157
+ for item in compensations if isinstance(item, dict)]
158
+ reasons = record.get("plan_reasons")
159
+ if isinstance(reasons, dict):
160
+ stored["plan_reasons"] = {
161
+ _identifier(txid): reason for txid, reason in reasons.items()
162
+ if isinstance(txid, str) and txid and isinstance(reason, str)
163
+ and reason in {"age", "capacity"}}
164
+ return stored
20
165
 
21
166
 
22
167
  def utc_now_iso() -> str:
@@ -29,27 +174,20 @@ def new_txid() -> str:
29
174
 
30
175
 
31
176
  def session_id() -> str:
32
- """Best-effort identity of the acting session.
177
+ """Opaque correlation for the acting session.
33
178
 
34
179
  An agent harness may identify itself through AGENT_GUARD_SESSION.
35
180
  This is correlation metadata, not authentication.
36
181
  """
37
182
  env = os.environ.get("AGENT_GUARD_SESSION")
38
183
  if env:
39
- return env
40
- try:
41
- user = getpass.getuser()
42
- except Exception: # pragma: no cover - exotic passwd setups
43
- user = "unknown"
44
- # platform.node() is the cross-platform form of os.uname().nodename
45
- # (os.uname does not exist on Windows); empty on exotic setups.
46
- host = platform.node() or "localhost"
47
- return f"{user}@{host}:{os.getpid()}"
184
+ return correlation_id(env)
185
+ return correlation_id(f"{_LOCAL_SESSION}:{os.getpid()}")
48
186
 
49
187
 
50
188
  def append(record: Dict[str, Any], audit_path: str) -> Dict[str, Any]:
51
- """Append one record; returns the stored record (with defaults filled)."""
52
- stored = dict(record)
189
+ """Append projected metadata; return exactly what was stored."""
190
+ stored = project(record)
53
191
  stored.setdefault("ts", utc_now_iso())
54
192
  stored.setdefault("session", session_id())
55
193
  line = json.dumps(stored, ensure_ascii=False, sort_keys=True)
@@ -65,22 +203,29 @@ def append(record: Dict[str, Any], audit_path: str) -> Dict[str, Any]:
65
203
 
66
204
 
67
205
  def tail(audit_path: str, n: int = 20) -> List[Dict[str, Any]]:
68
- """Read the last n valid records. Corrupt/torn lines are skipped."""
69
- if not os.path.exists(audit_path):
206
+ """Last n projected objects; malformed/non-object lines are skipped.
207
+
208
+ A non-positive limit reads nothing. Old bytes are never rewritten.
209
+ """
210
+ if n <= 0 or not os.path.exists(audit_path):
70
211
  return []
71
- records: List[Dict[str, Any]] = []
212
+ records = deque(maxlen=n)
72
213
  with open(audit_path, "r", encoding="utf-8") as fh:
73
214
  for raw in fh:
74
215
  raw = raw.strip()
75
216
  if not raw:
76
217
  continue
77
218
  try:
78
- records.append(json.loads(raw))
219
+ record = json.loads(raw)
79
220
  except json.JSONDecodeError:
80
221
  continue
81
- return records[-max(n, 0):]
222
+ if isinstance(record, dict):
223
+ records.append(project(record))
224
+ return list(records)
82
225
 
83
226
 
84
227
  def find_by_txid(audit_path: str, txid: str) -> List[Dict[str, Any]]:
85
228
  """All audit records belonging to one compensation transaction."""
86
- return [r for r in tail(audit_path, n=100_000) if r.get("txid") == txid]
229
+ key = _identifier(txid)
230
+ return [r for r in tail(audit_path, n=100_000)
231
+ if r.get("txid") == key]