@mokuyoaxis/agent-guard 0.2.4 → 0.2.5-rc2

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 (38) hide show
  1. package/README.md +166 -573
  2. package/README.zh-CN.md +138 -489
  3. package/SECURITY.md +53 -0
  4. package/adapters/INTEGRATION.md +4 -2
  5. package/adapters/dsh/README.md +7 -0
  6. package/assets/linux-do-community.svg +19 -0
  7. package/core/audit.py +170 -25
  8. package/core/classifier.py +25 -1
  9. package/core/lab.py +77 -7
  10. package/core/policy.py +17 -9
  11. package/core/recovery.py +5 -1
  12. package/core/redaction.py +122 -21
  13. package/docs/README.md +18 -5
  14. package/docs/design/architecture.md +25 -6
  15. package/docs/design/compatibility.md +106 -1
  16. package/docs/design/threat-model.md +6 -4
  17. package/docs/guides/audit-metadata.md +77 -0
  18. package/docs/guides/getting-started.md +106 -0
  19. package/docs/guides/harness-capabilities.md +5 -0
  20. package/docs/history/friction.md +85 -0
  21. package/docs/lab/guard-lab.md +15 -1
  22. package/docs/releases/release-notes-0.2.5-rc1.md +91 -0
  23. package/docs/releases/release-notes-0.2.5-rc2.md +101 -0
  24. package/guard_lab.py +11 -0
  25. package/package.json +4 -2
  26. package/skills/delete-guard/SKILL.md +45 -7
  27. package/skills/delete-guard/references/policy.md +90 -4
  28. package/skills/delete-guard/scripts/check.py +3 -0
  29. package/skills/delete-guard/scripts/gc.py +18 -3
  30. package/skills/delete-guard/scripts/restore.py +22 -7
  31. package/skills/delete-guard/scripts/safe_delete.py +52 -29
  32. package/skills/delete-guard/scripts/status.py +9 -7
  33. package/skills/exfil-guard/SKILL.md +23 -11
  34. package/skills/exfil-guard/references/channels.md +8 -1
  35. package/skills/exfil-guard/references/rules.md +86 -6
  36. package/skills/exfil-guard/scripts/_payload.py +20 -0
  37. package/skills/exfil-guard/scripts/check_span.py +5 -1
  38. package/skills/exfil-guard/scripts/sanitize.py +6 -3
package/core/recovery.py CHANGED
@@ -831,9 +831,13 @@ class RecoveryEngine:
831
831
  return None
832
832
 
833
833
  def tx_inventory(self) -> List[Dict[str, Any]]:
834
- """Per-transaction age/size facts for retention decisions."""
834
+ """Active transaction age/size facts; purged history stays in the manifest."""
835
835
  inventory: List[Dict[str, Any]] = []
836
836
  for txid, tx in self.transactions().items():
837
+ # A tombstone ends our ownership for planning. A directory later
838
+ # recreated under this ID is unmanaged, not another purge target.
839
+ if tx.get("purged"):
840
+ continue
837
841
  tx_dir = os.path.join(self.trash_root, txid)
838
842
  total = 0
839
843
  for root, _dirs, names in os.walk(tx_dir):
package/core/redaction.py CHANGED
@@ -896,6 +896,7 @@ class ScanResult:
896
896
  truncated: bool = False
897
897
  size_bytes: int = 0
898
898
  exempted: int = 0
899
+ exemption_info: Dict[str, Any] = field(default_factory=dict)
899
900
 
900
901
  @property
901
902
  def found(self) -> bool:
@@ -1006,6 +1007,29 @@ def _secret_source_reference(text: str) -> Optional[Tuple[str, int, int, str]]:
1006
1007
 
1007
1008
  DEFAULT_ALLOWFILE = ".agent-guard/exfil-allow.toml"
1008
1009
  DEFAULT_IGNOREFILE = ".agent-guardignore"
1010
+ EXEMPTION_DIAGNOSTIC_LIMIT = 32
1011
+ EXEMPTION_DIAGNOSTICS = {
1012
+ "EXEMPTION_IGNORED_LINE": "Line has no assignment or preceding value key; gitignore syntax is unsupported.",
1013
+ "EXEMPTION_UNKNOWN_KEY": "Unknown top-level key; its values are ignored.",
1014
+ "EXEMPTION_UNKNOWN_SECTION": "Unknown section; recognized legacy keys may still apply.",
1015
+ "EXEMPTION_LEGACY_SECTION_KEY": "Nonstandard key uses the legacy section fallback; its values still apply.",
1016
+ "EXEMPTION_MALFORMED_SECTION": "Malformed section header uses legacy parsing; inspect the configuration.",
1017
+ "EXEMPTION_INVALID_HASH": "Value is not a lowercase sha256 digest of 64 hexadecimal characters; it cannot match.",
1018
+ "EXEMPTION_UNSUPPORTED_NEGATION": "Leading ! is a literal pattern character, not gitignore negation.",
1019
+ "EXEMPTION_READ_FAILED": "Configuration could not be read; the next candidate is tried.",
1020
+ "EXEMPTION_ENCODING_INVALID": "Configuration is not UTF-8; the next candidate is tried.",
1021
+ "EXEMPTION_SHADOWED": "This file is not loaded because the preferred file was readable, even if empty or malformed.",
1022
+ }
1023
+ _EXEMPTION_RULE_KEYS = frozenset({"rule", "rules", "disable"})
1024
+ _EXEMPTION_PATH_KEYS = frozenset({"path", "paths", "ignore"})
1025
+ _EXEMPTION_HASH_KEYS = frozenset({"sha256", "hash", "hashes"})
1026
+
1027
+
1028
+ def _safe_exemption_source(source: str) -> Optional[str]:
1029
+ """Only fixed workspace-relative filenames may leave the process."""
1030
+ if source in (DEFAULT_ALLOWFILE, DEFAULT_IGNOREFILE):
1031
+ return source
1032
+ return "<provided>" if source else None
1009
1033
 
1010
1034
 
1011
1035
  @dataclass
@@ -1016,6 +1040,41 @@ class Exemption:
1016
1040
  paths: List[str] = field(default_factory=list)
1017
1041
  hashes: List[str] = field(default_factory=list)
1018
1042
  source: str = ""
1043
+ diagnostics: List[Dict[str, Any]] = field(default_factory=list)
1044
+ diagnostics_omitted: int = 0
1045
+
1046
+ def diagnose(self, code: str, source: str, line: int = 0) -> None:
1047
+ """Bounded, static diagnostics; never copy keys, values or exceptions."""
1048
+ if code not in EXEMPTION_DIAGNOSTICS:
1049
+ return
1050
+ if len(self.diagnostics) >= EXEMPTION_DIAGNOSTIC_LIMIT:
1051
+ self.diagnostics_omitted += 1
1052
+ return
1053
+ row = {"code": code, "source": _safe_exemption_source(source)}
1054
+ if type(line) is int and line > 0:
1055
+ row["line"] = line
1056
+ self.diagnostics.append(row)
1057
+
1058
+ def safe(self) -> Dict[str, Any]:
1059
+ """Provenance and counts, never the exemption patterns or hashes."""
1060
+ rows = []
1061
+ for row in self.diagnostics[:EXEMPTION_DIAGNOSTIC_LIMIT]:
1062
+ code = row.get("code")
1063
+ if code not in EXEMPTION_DIAGNOSTICS:
1064
+ continue
1065
+ safe = {"code": code,
1066
+ "source": _safe_exemption_source(row.get("source", ""))}
1067
+ if type(row.get("line")) is int and row["line"] > 0:
1068
+ safe["line"] = row["line"]
1069
+ rows.append(safe)
1070
+ return {
1071
+ "source": _safe_exemption_source(self.source),
1072
+ "active": self.active,
1073
+ "counts": {"rules": len(self.rules), "paths": len(self.paths),
1074
+ "hashes": len(self.hashes)},
1075
+ "diagnostics": rows,
1076
+ "diagnostics_omitted": self.diagnostics_omitted,
1077
+ }
1019
1078
 
1020
1079
  @property
1021
1080
  def active(self) -> bool:
@@ -1059,35 +1118,51 @@ def _parse_allowfile(text: str, source: str) -> Exemption:
1059
1118
 
1060
1119
  Continuation lines are supported: a key whose value starts on its own
1061
1120
  line keeps consuming the indented lines that follow, which is how the
1062
- lists in `.agent-guard/exfil-allow.toml` stay readable. Malformed input
1063
- is ignored rather than fatal - a broken allowfile must never quietly
1064
- turn the guard off.
1121
+ lists in `.agent-guard/exfil-allow.toml` stay readable. Preserve legacy
1122
+ matching while diagnosing ignored or nonstandard constructs. Warnings
1123
+ are not whole-file rejection; recognized entries can still apply.
1065
1124
  """
1066
1125
  exemption = Exemption(source=source)
1067
1126
  section = ""
1068
1127
  key = ""
1069
- values: List[str] = []
1128
+ values: List[Tuple[str, int]] = []
1129
+ key_line = 0
1070
1130
 
1071
1131
  def flush():
1072
1132
  if not key:
1073
1133
  return
1074
- items = [v.strip().strip("'\"") for v in values if v.strip("'\"")]
1075
- if key in ("rule", "rules", "disable") or section == "rules":
1076
- exemption.rules.extend(items)
1077
- elif key in ("path", "paths", "ignore") or section == "paths":
1078
- exemption.paths.extend(items)
1079
- elif key in ("sha256", "hash", "hashes") or section == "values":
1080
- exemption.hashes.extend(items)
1081
-
1082
- def push(raw: str):
1134
+ if key in _EXEMPTION_RULE_KEYS or section == "rules":
1135
+ target = exemption.rules
1136
+ elif key in _EXEMPTION_PATH_KEYS or section == "paths":
1137
+ target = exemption.paths
1138
+ elif key in _EXEMPTION_HASH_KEYS or section == "values":
1139
+ target = exemption.hashes
1140
+ else:
1141
+ exemption.diagnose("EXEMPTION_UNKNOWN_KEY", source, key_line)
1142
+ return
1143
+ if key not in (_EXEMPTION_RULE_KEYS | _EXEMPTION_PATH_KEYS |
1144
+ _EXEMPTION_HASH_KEYS):
1145
+ exemption.diagnose("EXEMPTION_LEGACY_SECTION_KEY", source, key_line)
1146
+ for value, line in values:
1147
+ if not value.strip("'\""):
1148
+ continue
1149
+ item = value.strip().strip("'\"")
1150
+ target.append(item)
1151
+ if target is exemption.hashes:
1152
+ if not re.fullmatch(r"sha256:[0-9a-f]{64}", item):
1153
+ exemption.diagnose("EXEMPTION_INVALID_HASH", source, line)
1154
+ elif item.startswith("!"):
1155
+ exemption.diagnose("EXEMPTION_UNSUPPORTED_NEGATION", source, line)
1156
+
1157
+ def push(raw: str, line: int):
1083
1158
  """Split one value chunk on commas/whitespace, ignoring [] and ''."""
1084
1159
  chunk = raw.strip().strip("[]")
1085
1160
  for item in re.split(r"[,\s]+", chunk):
1086
1161
  item = item.strip().strip("'\"")
1087
1162
  if item:
1088
- values.append(item)
1163
+ values.append((item, line))
1089
1164
 
1090
- for raw_line in text.splitlines():
1165
+ for line_number, raw_line in enumerate(text.splitlines(), 1):
1091
1166
  line = raw_line.split("#", 1)[0].rstrip()
1092
1167
  if not line.strip():
1093
1168
  continue
@@ -1095,32 +1170,57 @@ def _parse_allowfile(text: str, source: str) -> Exemption:
1095
1170
  flush()
1096
1171
  key, values = "", []
1097
1172
  section = line.strip().strip("[]").strip().lower()
1173
+ if not re.fullmatch(r"\[[^\[\]]+\]", line.strip()):
1174
+ exemption.diagnose("EXEMPTION_MALFORMED_SECTION", source, line_number)
1175
+ if section not in ("rules", "paths", "values"):
1176
+ exemption.diagnose("EXEMPTION_UNKNOWN_SECTION", source, line_number)
1098
1177
  continue
1099
1178
  if "=" in line:
1100
1179
  flush()
1101
1180
  values = []
1102
1181
  key, _, value = line.partition("=")
1103
1182
  key = key.strip().lower()
1104
- push(value)
1183
+ key_line = line_number
1184
+ if not key:
1185
+ exemption.diagnose("EXEMPTION_UNKNOWN_KEY", source, line_number)
1186
+ push(value, line_number)
1105
1187
  continue
1106
1188
  if key:
1107
- push(line)
1189
+ push(line, line_number)
1190
+ else:
1191
+ exemption.diagnose("EXEMPTION_IGNORED_LINE", source, line_number)
1108
1192
  flush()
1109
1193
  return exemption
1110
1194
 
1111
1195
 
1112
1196
  def load_exemption(workspace: Optional[str]) -> Exemption:
1113
1197
  """Read the repo-local exemption file; absent means "no exemptions"."""
1198
+ result = Exemption()
1114
1199
  if not workspace:
1115
- return Exemption()
1200
+ return result
1116
1201
  for relative in (DEFAULT_ALLOWFILE, DEFAULT_IGNOREFILE):
1117
1202
  path = os.path.join(workspace, relative)
1118
1203
  try:
1119
1204
  with open(path, "r", encoding="utf-8") as fh:
1120
- return _parse_allowfile(fh.read(), relative)
1121
- except (OSError, UnicodeDecodeError):
1205
+ parsed = _parse_allowfile(fh.read(), relative)
1206
+ except FileNotFoundError:
1122
1207
  continue
1123
- return Exemption()
1208
+ except UnicodeDecodeError:
1209
+ result.diagnose("EXEMPTION_ENCODING_INVALID", relative)
1210
+ continue
1211
+ except OSError:
1212
+ result.diagnose("EXEMPTION_READ_FAILED", relative)
1213
+ continue
1214
+ result.rules, result.paths, result.hashes = parsed.rules, parsed.paths, parsed.hashes
1215
+ result.source = parsed.source
1216
+ for row in parsed.diagnostics:
1217
+ result.diagnose(row["code"], relative, row.get("line", 0))
1218
+ result.diagnostics_omitted += parsed.diagnostics_omitted
1219
+ if relative == DEFAULT_ALLOWFILE and os.path.lexists(
1220
+ os.path.join(workspace, DEFAULT_IGNOREFILE)):
1221
+ result.diagnose("EXEMPTION_SHADOWED", DEFAULT_IGNOREFILE)
1222
+ return result
1223
+ return result
1124
1224
 
1125
1225
 
1126
1226
  def apply_exemption(spans: List[SpanSpec], exemption: Exemption,
@@ -1189,6 +1289,7 @@ def scan_text(text: str, channel: str = "",
1189
1289
  notes=["value-free reference detection", reason]))
1190
1290
  if exemption is None:
1191
1291
  exemption = load_exemption(workspace)
1292
+ result.exemption_info = exemption.safe()
1192
1293
  # A source-reference fact must survive even inside a redaction span:
1193
1294
  # masking a literal URI password is not permission to resolve an env
1194
1295
  # secret embedded there. The aggregate BLOCK prevents plan application.
package/docs/README.md CHANGED
@@ -1,10 +1,19 @@
1
1
  # Documentation / 文档导航
2
2
 
3
- Start with the [harness capability matrix](guides/harness-capabilities.md) for
4
- current coverage, the [architecture](design/architecture.md) for the shared
5
- Core, and the [Lab guide](lab/guard-lab.md) for experiment semantics.
6
-
7
- 先看当前能力矩阵、架构和 Lab 指南。测试报告按所测版本与配置保留;发布记录、
3
+ Start with [getting started](guides/getting-started.md) for installation and
4
+ setup. The three main paths are [recovery protection](../skills/delete-guard/SKILL.md),
5
+ [disclosure checks](../skills/exfil-guard/SKILL.md), and
6
+ [behaviour experiments](lab/guard-lab.md). Use the
7
+ [harness capability matrix](guides/harness-capabilities.md) for observed coverage
8
+ and the [architecture](design/architecture.md) for the shared Core.
9
+
10
+ Previous published RC baseline: [0.2.5-rc1](releases/release-notes-0.2.5-rc1.md).
11
+ Published stable baseline: [0.2.4](releases/release-notes-0.2.4.md).
12
+ Current RC: [0.2.5-rc2](releases/release-notes-0.2.5-rc2.md),
13
+ including [shared audit metadata](guides/audit-metadata.md) and observer startup maintenance;
14
+ publication is established by its GitHub/npm receipts.
15
+
16
+ 先看入门指南,再按恢复保护、外发检测、Lab 验测选择入口。测试报告按所测版本与配置保留;发布记录、
8
17
  历史设计和外部案例各自归档,不能据此扩展当前产品的承诺。
9
18
 
10
19
  | Category / 分类 | Contents / 内容 |
@@ -20,9 +29,11 @@ Core, and the [Lab guide](lab/guard-lab.md) for experiment semantics.
20
29
 
21
30
  | Document / 文档 | Scope / 范围 |
22
31
  |---|---|
32
+ | [Getting started](guides/getting-started.md) | 安装路径、Agent 接入提示词与最短验证流程 |
23
33
  | [Harness capabilities](guides/harness-capabilities.md) | 当前接入范围、证据等级与未验证路径 |
24
34
  | [Host drift](guides/host-drift.md) | 宿主版本、配置与本地基线检查 |
25
35
  | [Trash locations](guides/trash-index.md) | 0.2.4 的只读位置查询、Agent/前端共享 JSON 契约 |
36
+ | [Audit metadata](guides/audit-metadata.md) | RC2 候选的字段投影、会话关联、GC/status 契约与保留边界 |
26
37
  | [Publishing from ephemeral environments](guides/publishing-from-ephemeral-environments.md) | 临时环境中的 GitHub 发布操作参考 |
27
38
 
28
39
  Adapter setup remains in [adapters/](../adapters/INTEGRATION.md). Skill contracts
@@ -81,6 +92,8 @@ coverage rather than treating every historical result as current acceptance.
81
92
 
82
93
  | Document / 文档 | Scope / 范围 |
83
94
  |---|---|
95
+ | [0.2.5-rc2](releases/release-notes-0.2.5-rc2.md) | 当前维护 RC;共享审计、observer 维护与兼容边界 |
96
+ | [0.2.5-rc1](releases/release-notes-0.2.5-rc1.md) | 已发布的维护预发布基线、文档整理与版本例外 |
84
97
  | [0.2.4](releases/release-notes-0.2.4.md) | 恢复维护、trash 查询及兼容性例外 |
85
98
  | [0.2.3](releases/release-notes-0.2.3.md) | 正式版范围与证据边界 |
86
99
  | [0.2.3-rc2](releases/release-notes-0.2.3-rc2.md) | 离线 Lab 与已复核 DSH 契约 |
@@ -23,6 +23,11 @@ the identity of the project.
23
23
  | Authorization | Who decides what? | `core/policy.py` (mode state machine) |
24
24
  | Auditability | What actually happened? | `core/audit.py` + `.agent-trash/*.jsonl` |
25
25
 
26
+ The 0.2.5-rc2 source candidate adds a shared
27
+ [audit metadata projection](../guides/audit-metadata.md) on append and legacy
28
+ read, with opaque session correlation. Recovery manifests retain exact paths;
29
+ authorization state and required audit durability remain separate contracts.
30
+
26
31
  A fifth, cross-cutting rule governs all four:
27
32
 
28
33
  > **Uncertainty increases restriction** (fail closed).
@@ -263,8 +268,11 @@ FORBIDDEN (BLOCK, never askable).
263
268
  5. **Lexical boundaries.** Workspace containment is decided on normalized
264
269
  paths; deleting a symlink removes the link, never the target, so symlink
265
270
  targets outside the workspace neither leak nor block.
266
- 6. **Self-exclusion.** Targets inside `.agent-trash/` are exempted from
267
- quarantine - housekeeping cannot recurse into itself forever.
271
+ 6. **Self-exclusion with protected controls.** Ordinary unprotected payloads
272
+ inside the selected quarantine use housekeeping rather than relocation.
273
+ Protection introduced in 0.2.5-rc1 checks root/control paths and storage parents first;
274
+ housekeeping cannot override protection. Opaque globs must be enumerated
275
+ explicitly, and validated transaction purge uses the GC CLI.
268
276
  7. **Diagnostics do not silently become enforcement.** `guard-lab` records
269
277
  declared synthetic channels and evaluates one case criterion. It does not
270
278
  feed a Lab observation into Core policy or claim to ban model calls. A real
@@ -295,7 +303,17 @@ order of value:
295
303
  skill and the "prefer safe_delete" rule. Interception without prompting
296
304
  causes friction; prompting without interception is advisory only.
297
305
 
298
- ## Roadmap
306
+ ## Delivery status and design directions
307
+
308
+ The current RC source is 0.2.5-rc2, with publication checked by its receipts;
309
+ stable 0.2.4 and the previous prerelease 0.2.5-rc1 remain baselines. It retains RC1 maintenance and adds
310
+ shared audit metadata projection plus observer startup diagnosis/cancellation.
311
+ See [candidate notes](../releases/release-notes-0.2.5-rc2.md) and
312
+ [compatibility](compatibility.md) for behaviour and validation boundaries.
313
+
314
+ The milestones below describe historical delivery and future design scope,
315
+ not a committed schedule or a guarantee that new compensation types need no
316
+ architecture changes.
299
317
 
300
318
  - V1 (this repo): delete-guard skill, fs + git compensations, Linux/macOS.
301
319
  - v0.1.1: durable relocation intents, explicit retention/GC policy, quoted
@@ -315,7 +333,7 @@ order of value:
315
333
  `tests/test_dialect_phase2.py`) cover further cmd/PowerShell spellings,
316
334
  option aliases and fail-closed edge cases. Hook payload dialect forwarding
317
335
  has adapter tests; this is not a Windows host execution claim.
318
- - **Phase 3a (`0.2.3-rc1` candidate).** A blocking `windows-latest` Core
336
+ - **Phase 3a (shipped since `0.2.3-rc1`).** A blocking `windows-latest` Core
319
337
  job covers the Issue #7 dialect-mismatch and separator regressions,
320
338
  deterministic cmd/PowerShell facts, and recovery inside disposable
321
339
  fixtures. The job uses Python argv/bytes so a surrounding shell cannot
@@ -325,7 +343,7 @@ order of value:
325
343
  broader UNC/device paths and full-suite portability still require
326
344
  separate evidence. A focused Core runner is not a universal Windows E2E
327
345
  claim.
328
- - `0.2.3-rc2` source candidate: offline `guard-lab` MVP with disposable
346
+ - Offline `guard-lab` MVP, introduced in `0.2.3-rc2` and shipped in `0.2.3`: disposable
329
347
  synthetic fixtures, zero-token controls, a bounded loopback observer,
330
348
  explicit-output marker scanning, chained evidence, and fail-inconclusive
331
349
  reports. General file-read visibility, remote callbacks, real-model rating,
@@ -335,4 +353,5 @@ order of value:
335
353
  - V3+: `database-guard` (compensations = transaction / backup /
336
354
  point-in-time recovery), `cloud-guard` (snapshot / state capture). The
337
355
  Guard answers "may this happen"; the Compensation Engine answers "how do
338
- we come back" - both extend without restructuring the repository.
356
+ we come back". These remain design directions requiring separate scope and
357
+ implementation decisions.
@@ -4,6 +4,9 @@ agent-guard's promise is recoverability. A promise is only as good as its
4
4
  stability over time - this page states exactly what may change and what
5
5
  may not, per release class.
6
6
 
7
+ Current RC source is [0.2.5-rc2](../releases/release-notes-0.2.5-rc2.md); publication is checked by its receipts.
8
+ Versioned sections retain the origin of changes introduced by earlier releases.
9
+
7
10
  ## The adapter contract (frozen surface)
8
11
 
9
12
  Harness adapters integrate against exactly four things:
@@ -74,6 +77,75 @@ must accept the additional refusal reason and ignore unknown optional fields.
74
77
  | `doctor.py --live-sentinel` and hashed hook receipt | minor | Explicit, opt-in real-host/model probe only. Default doctor behavior is unchanged; raw command/model output is not retained, and incomplete evidence is `INCONCLUSIVE` rather than PASS |
75
78
  | Cross-vocabulary mismatch floor (`0.2.3-rc1`) | minor safety fix | At a selected-dialect command boundary, a supported destructive shape that produced no operation becomes target-free `UNKNOWN` → `BLOCK_UNDETERMINABLE_EFFECT`; it never borrows a compensation plan from another grammar |
76
79
 
80
+ ### 0.2.5-rc1 assessment contract clarification (source candidate)
81
+
82
+ Advisory and dry-run retain their existing best-effort audit behavior and
83
+ metadata side effects. Tests and documentation distinguish unchanged command
84
+ targets from zero filesystem writes, and advisory exit 0 from execution
85
+ authorization. No flag, result field, policy decision, audit storage location
86
+ or exit code changes. See the [assessment contract](../../skills/delete-guard/references/policy.md#assessment-and-dry-run-side-effects).
87
+
88
+ ### 0.2.5-rc1 safe_delete audit minimization (source candidate)
89
+
90
+ New safe_delete audit events replace raw target/reason payloads with
91
+ `target_count`; established relocation reports retain `txid` and add
92
+ `moved_count`/`skipped_count`, including storage-failure decisions. Decision
93
+ codes, phases and static outcome labels remain available. Free-form
94
+ `--reason` stays accepted but is omitted from new audit events and
95
+ `tx-start.meta`. Essential recovery paths/intents, CLI result fields,
96
+ verdicts, exit codes and durability gates retain their behavior.
97
+ Audit event shapes are not frozen. At the released RC1 baseline, generic
98
+ audit/session handling is unchanged; the RC2 projection below
99
+ extends it. See the [writer contract](../../skills/delete-guard/references/policy.md#safe_delete-audit-metadata).
100
+
101
+ ### 0.2.5-rc2 shared audit metadata maintenance (source candidate)
102
+
103
+ `append` stores a closed metadata projection and returns the stored record;
104
+ `tail` projects legacy records without rewriting them, skips non-object JSON,
105
+ and returns no records for non-positive limits. Unknown/custom fields and
106
+ free text under allowed names are omitted. Audit shapes are not frozen, but
107
+ callers relying on arbitrary payload storage must adapt explicitly.
108
+
109
+ Session/display identities become deterministic opaque correlation. Generated
110
+ transaction/check IDs remain exact; noncanonical audit IDs become correlation
111
+ tags, and `find_by_txid` accepts the original spelling. Unknown GC selections
112
+ use digest metadata; CLI results and recovery journal IDs/paths remain exact.
113
+ Ordinary status actor display is projected without changing authorization
114
+ state or session selection. No decision/exit/flag semantics, manifest schema,
115
+ audit locations or durability gates change. This work is not included in the
116
+ published RC1; see the [full audit contract](../guides/audit-metadata.md).
117
+
118
+ ### 0.2.5-rc2 observer startup maintenance (source candidate)
119
+
120
+ The readiness window stays five seconds after spawn. Startup logs add static
121
+ phases and monotonic timestamps without tokens, paths or exception text.
122
+ They remain diagnostic and do not establish evidence health. Startup timeout
123
+ requests cooperative cancellation, then permits up to two seconds of local
124
+ child reaping; a live child remains registered without a forced signal.
125
+ Reap timeouts preserve the original LabError. Cancelled startup is
126
+ `FAILED` / `OBSERVER_STARTUP_CANCELLED` and `INCONCLUSIVE`, including late READY
127
+ publication; ordinary stops after accepted readiness retain their meaning.
128
+ Public CLI arguments, exit codes, evidence levels and loopback scope stay
129
+ unchanged. The first intermittent timeout's root cause is still unknown.
130
+ See the [Lab contract](../lab/guard-lab.md) and [RC2 notes](../releases/release-notes-0.2.5-rc2.md).
131
+
132
+ ### 0.2.5-rc1 exemption configuration diagnostics (source candidate)
133
+
134
+ The existing limited parser, first-readable-file precedence and exemption
135
+ matching are retained. No full TOML/gitignore parser, configuration migration,
136
+ production dependency or new policy reason is added. Unknown top-level keys
137
+ and bare lines remain ineffective; recognized legacy entries may still apply
138
+ alongside warnings. Diagnostics do not change verdicts or exit codes.
139
+
140
+ Successful text scans may add `exemption` provenance/count/diagnostic metadata
141
+ to checker JSON and the sanitizer library result. Human checker and sanitizer
142
+ CLI warnings use stderr; JSON checker stdout and sanitizer payload/plan stdout
143
+ keep their respective formats. Normal missing/valid configurations remain
144
+ quiet. Diagnostic codes are configuration metadata, not Decision Protocol
145
+ reason codes. Consumers should tolerate the additive fields and warnings;
146
+ these diagnostics originated in RC1 and remain in the RC2 source candidate. The diagnostic
147
+ grammar and privacy contract are in [rules.md](../../skills/exfil-guard/references/rules.md#configuration-diagnostics).
148
+
77
149
  ### 0.2.0 check output minimization
78
150
 
79
151
  `check.py` still returns the same decision class, reason code, static
@@ -161,9 +233,41 @@ Every expansion is recorded in the op notes for audit.
161
233
 
162
234
  ## Verdict changes since v0.1.1
163
235
 
236
+ ### 0.2.5-rc1 lifecycle and restore-audit maintenance (source candidate)
237
+
238
+ Existing `BLOCK_PROTECTED_PATH` now wins before `ALLOW_TRASH_GC` for
239
+ workspace/Git and quarantine control paths. Quarantine root metadata,
240
+ session state and in-workspace storage parents are protected. Ordinary
241
+ unprotected explicit payload housekeeping and the explicit GC CLI remain
242
+ available. Opaque quarantine globs now return `BLOCK_WILDCARD`; safe_delete
243
+ can enumerate a concrete batch before policy checks.
244
+ See [F26](../history/friction.md#f26--housekeeping-overrode-quarantine-control-protection).
245
+ This changes default verdicts and would ordinarily follow the minor-release
246
+ contract. The maintainer explicitly selected 0.2.5-rc1 for this maintenance
247
+ candidate instead of 0.3.0. This is a new, bounded exception for the existing
248
+ control-path/glob, PURGED inventory, audit-writer and exemption-diagnostic
249
+ maintenance, not an extension of the prior 0.2.4 exception to arbitrary changes.
250
+ Existing decision/reason strings, CLI arguments and exit codes retain their
251
+ roles. There is no manifest migration or production dependency. Publication,
252
+ and any later stable 0.2.5 decision, remain separate from candidate preparation.
253
+ The exact -rcN tag maps to GitHub prerelease and npm rc, preserving stable latest.
254
+ See the [candidate notes](../releases/release-notes-0.2.5-rc1.md).
255
+
256
+ Active `tx_inventory` and GC plans now omit `PURGED` history, while
257
+ `transactions` and manifests retain it. Failed/unpurged transactions retain
258
+ their prior eligibility rules; no stash deletion or storage migration is added.
259
+
260
+ Restore audit records replace `restored`/`conflicts`/`errors` payload copies
261
+ with `restored_count`/`conflict_count`/`error_count`. Established IDs and backup
262
+ attempt IDs stay correlated; invalid/unknown caller IDs use `txid_sha256`.
263
+ Audit shapes beyond manifests are not frozen. CLI parameters, exit codes,
264
+ recovery manifests and returned recovery paths/errors retain their roles.
265
+ That released change is one writer's minimization. The RC2 shared
266
+ projection is described above; it does not rewrite manifests or old log bytes.
267
+
164
268
  A changed default verdict for an existing shape is a **minor** release and
165
269
  requires an entry in [friction.md](../history/friction.md) - never a silent behaviour
166
- shift. The explicit 0.2.4 exception is recorded above. Additive reason codes
270
+ shift. The bounded 0.2.4 and 0.2.5-rc1 exceptions are recorded above. Additive reason codes
167
271
  are listed above; this table is for shapes
168
272
  whose *existing* verdict moved.
169
273
 
@@ -175,6 +279,7 @@ whose *existing* verdict moved.
175
279
  | Attached or newline-separated destructive commands (`echo ok;rm ...`, `echo ok` followed by newline and `rm ...`) | Could miss the destructive segment | Classifies and applies its normal policy | POSIX command boundaries must be preserved by the lexer |
176
280
  | `git reset --hard [ref]` with untracked/ignored or quarantine collisions | Tracked-only `SNAPSHOT` could proceed | `BLOCK` / `BLOCK_GIT_RESET_COLLISION` | Stash does not preserve the colliding content (0.2.4 maintenance exception, F24) |
177
281
  | Hard reset with uncertain preflight or unsupported compound/wrapper context | Could proceed or ask despite incomplete coverage | `BLOCK_UNDETERMINABLE_EFFECT` before compensation | Snapshot and preflight must describe the actual Git context (F24) |
282
+ | Quarantine root/control paths, protected metadata inside trash, or an in-workspace storage parent | Could be allowed as housekeeping or regenerable content | `BLOCK_PROTECTED_PATH` | Recovery/state evidence protection precedes housekeeping (introduced in 0.2.5-rc1, F26) |
178
283
 
179
284
  Unchanged on purpose: a genuine compensation fault (`git stash create`
180
285
  failing, a relocation that does not cover every target, an audit intent
@@ -10,8 +10,10 @@ bypass. Therefore:
10
10
  It defends against *mistakes*: misjudged context, mis-expanded commands,
11
11
  wrong working directory, hallucinated paths - which is what essentially
12
12
  all real-world "agent deleted my data" incidents are.
13
- - You may claim: default-recoverable deletions, full decision audit, graded
14
- authorization, reduced blast radius of common accidents.
13
+ - You may claim: recovery for supported valuable deletions, explicit audit
14
+ contracts for observed calls, graded authorization discipline, and reduced
15
+ blast radius of common accidents. Regenerable artifacts may be deleted
16
+ directly; best-effort audit and bypassed calls are not complete visibility.
15
17
  - You must NOT claim: sandboxing, containment of malicious agents,
16
18
  prevention of determined bypass.
17
19
 
@@ -27,10 +29,10 @@ bypass. Therefore:
27
29
  |---|---|---|---|
28
30
  | 1 | Agent deletes via unrecognized channel: its own script calling `unlink()`, `python -c`, `node -e` | Out of scope for command classification; prompt layer forbids circumvention; audit records what was seen | Real. Upgrade path: kernel-side enforcement (fanotify/eBPF/sandbox) or intercepting the FS service rather than the shell |
29
31
  | 2 | Agent tampers with `.agent-trash/state.json` to self-promote mode | Portable file is advisory by design; harness adapters SHOULD hold the authoritative mode in host memory the agent's shell cannot reach | Accepted for pure-CLI usage; documented |
30
- | 3 | Agent allocates a PTY to pass the `isatty()` human check | Documented heuristic; adapters enforce promotion out-of-band (human-only UI/command) | Heuristic, not cryptographic |
32
+ | 3 | Agent allocates a PTY to pass the `isatty()` human check | The CLI check is a heuristic. An integration requiring human-only promotion must provide independent host authority; the shipped adapters do not supply isolated mode storage | Same-UID configuration/state remain writable; no authenticated human identity guarantee |
31
33
  | 4 | Agent edits/removes `manifest.jsonl` to hide provenance | Append-only by convention; audit log is separate; adapters may ship both off-box | Tamper-evident only if exported |
32
34
  | 5 | Symlink confusion (delete link vs target, trailing slash dereference) | Lexical boundary analysis; link relocation preserves the link; realpath recorded | Low |
33
- | 6 | TOCTOU between classification and execution | Window is milliseconds inside one process; adapters that need more should classify-and-execute atomically | Small, acknowledged |
35
+ | 6 | TOCTOU between classification and execution | Checks and moves are not atomic. Native hooks run Core before handing control back to host execution; there is no promised maximum gap | Concurrent changes can invalidate facts or affect later execution. Atomic isolation remains unimplemented |
34
36
  | 7 | Destructive restore | Relocation destinations and sources are checked against the workspace and their quarantine transaction. IDs and directory locations are validated; leaf symlinks retain their semantics. Human `--force` preserves an occupant through a separate relocation transaction before replacement; failed preservation stops that item | Checks and moves are not atomic against concurrent changes. Cross-filesystem failures may leave a partial destination or backup; inspect the filesystem and reported transaction IDs. Preserved versions add storage use and follow existing explicit GC |
35
37
  | 8 | Quarantine bloat turns `.agent-trash` into a liability (exfil via packaging, disk exhaustion) | Existing `.gitignore` or `.git/info/exclude`; `status.py` exposes size; 30-day/5-GiB soft eligibility with explicit audited purge | A human or scheduler must execute purge; audit is retained |
36
38
 
@@ -0,0 +1,77 @@
1
+ # Audit metadata / 审计元信息
2
+
3
+ **Status: included in 0.2.5-rc2.** The published RC1
4
+ does not include this shared projection. Its restore/safe_delete writer
5
+ minimization remains documented in the [RC notes](../releases/release-notes-0.2.5-rc1.md).
6
+ See the [RC2 scope and evidence](../releases/release-notes-0.2.5-rc2.md).
7
+
8
+ `core.audit.append()` now persists supported metadata only and returns the
9
+ exact stored object. `tail()` applies the same projection to legacy objects
10
+ in memory. Neither function rewrites earlier log bytes or recovery manifests.
11
+ Callers must not use this log as storage for arbitrary payloads or custom
12
+ fields: unsupported names, free text and malformed values are omitted.
13
+
14
+ ## Supported evidence
15
+
16
+ | Metadata | Stored/read representation |
17
+ |---|---|
18
+ | Events, tools, decisions, reason codes, phases, outcomes | Reviewed labels from the current implementation; arbitrary strings and nested values are omitted |
19
+ | Timestamp | UTC `YYYY-MM-DDTHH:MM:SSZ` shape; a missing/invalid append timestamp gets the current time |
20
+ | Counts and flags | Nonnegative integers and actual booleans; latency also permits finite nonnegative floats |
21
+ | `txid`, `check_id`, `plan_id`, ID lists | Generated `YYYYMMDD-HHMMSS-xxxxxxxx` IDs remain exact; other nonempty spellings use `sha256:<digest>` correlation |
22
+ | `session` | Deterministic `sha256:<digest>` of a supplied identity; no raw username/hostname fallback |
23
+ | `compensations` | Strategy/status labels, transaction correlation, counts and a validated Git SHA (or `null`); nested payloads are omitted |
24
+ | `plan_reasons` | Transaction correlation mapped to `age`/`capacity` |
25
+ | Optional exfil records | Built-in rule/channel/family/confidence labels, numeric offsets/length, `span` and `exempted`; `key=<source name>` context becomes `key` |
26
+ | Command/error/reasons | Only the existing `<redacted>` command marker, static `compensation failed` diagnostic and empty reasons list can remain |
27
+
28
+ The full field/label set is in [core/audit.py](../../core/audit.py). Supporting
29
+ a new writer requires an explicit schema review; its fields are not retained
30
+ merely because they look safe. The projection does not scan or hash arbitrary
31
+ payload bodies. It is not a general recursive text sanitizer.
32
+
33
+ `tail(path, n)` skips corrupt/torn JSON and non-object JSON lines and keeps
34
+ the last `n` object records in bounded memory. Non-positive `n` returns an
35
+ empty list without reading the file. It still scans the file for positive
36
+ limits; unreadable files and invalid UTF-8 are not silently certified clean.
37
+
38
+ ## Correlation and visible status
39
+
40
+ A raw `AGENT_GUARD_SESSION` still selects the existing authorization state.
41
+ Only audit/display metadata changes. The same supplied session correlates
42
+ across CLI processes; without one, correlation is stable within a process
43
+ and differs between processes. Explicit record sessions take precedence.
44
+ Already-projected tags remain stable when read or re-appended.
45
+
46
+ `find_by_txid(path, original_id)` projects the lookup ID too, so legacy
47
+ noncanonical IDs remain findable in old and new records. A `sha256:` tag is
48
+ not a restore argument: obtain the original ID from the recovery manifest
49
+ or exact CLI result. Generated transaction IDs remain directly usable.
50
+
51
+ Normal `status` still provides a small recent-event summary. Its decision
52
+ statistics use projected reason codes; legacy free text under an allowed
53
+ field name is no longer copied into counts or text output. `mode_set_by`
54
+ uses opaque correlation and invalid display timestamps become `null`.
55
+ The state file, mode decisions and session selection are unchanged.
56
+
57
+ GC intent records keep known transaction correlation and `target_count`.
58
+ Unknown selected IDs are recorded in `missing_txid_sha256`; receipts add
59
+ `missing_count`, keep known missing IDs in `missing`, and retain `purged`.
60
+ GC reason maps cover selected transactions only. CLI missing-ID diagnostics
61
+ and results remain exact. Preflight and durable intent still precede purge.
62
+
63
+ ## Limits / 边界
64
+
65
+ 这批维护只收口共享审计存取、GC writer 和普通 status 的非恢复元信息。
66
+ 旧日志文件中的原始内容仍在;直接打开或转发文件不会经过投影。
67
+ manifest、准确恢复路径、CLI 目标/错误、隔离区位置查询和授权状态不是
68
+ 本投影的脱敏对象,仍可能含敏感文字。普通工具输出/流没有因此获得统一保护。
69
+
70
+ 摘要用于关联,不是加密、鉴权或秘密存储:低熵标识可被猜测,也可能跨记录关联。
71
+ 可信调用方仍须保证 ID、计数等事实正确;字段白名单不抵抗篡改或刻意编码。
72
+ 本次没有控制面签名、配置迁移、新依赖或新的拒绝策略。
73
+
74
+ Audit locking, flush/fsync and existing required-versus-best-effort writer
75
+ boundaries remain in place. An I/O failure can leave a partial or complete
76
+ line even when append raises; it never authorizes a required operation by
77
+ itself. Supported recovery is verified separately from audit projection.