@mokuyoaxis/agent-guard 0.2.3 → 0.2.5-rc1

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 (80) hide show
  1. package/README.md +158 -571
  2. package/README.zh-CN.md +133 -490
  3. package/SECURITY.md +53 -0
  4. package/adapters/INTEGRATION.md +8 -6
  5. package/adapters/claude/README.md +3 -3
  6. package/adapters/claude/harness/README.md +1 -1
  7. package/adapters/codex/harness/README.md +2 -2
  8. package/adapters/dsh/README.md +17 -6
  9. package/adapters/dsh/harness/README.md +8 -8
  10. package/adapters/dsh/harness/guard_lab.py +3 -3
  11. package/adapters/dsh/lib/index.js +1 -1
  12. package/adapters/kimi-code/README.md +7 -7
  13. package/adapters/kimi-code/harness/README.md +3 -3
  14. package/adapters/kimi-code/harness/guard_lab.py +1 -1
  15. package/assets/linux-do-community.svg +19 -0
  16. package/core/__init__.py +1 -1
  17. package/core/classifier.py +66 -17
  18. package/core/policy.py +28 -13
  19. package/core/recovery.py +261 -24
  20. package/core/redaction.py +122 -21
  21. package/core/trash_index.py +193 -0
  22. package/docs/README.md +113 -0
  23. package/docs/{architecture.md → design/architecture.md} +51 -12
  24. package/docs/{compatibility.md → design/compatibility.md} +124 -4
  25. package/docs/{threat-model.md → design/threat-model.md} +10 -8
  26. package/docs/guides/getting-started.md +104 -0
  27. package/docs/{harness-capabilities.md → guides/harness-capabilities.md} +14 -9
  28. package/docs/guides/trash-index.md +106 -0
  29. package/docs/{development-note-unguarded-deletion.md → history/development-note-unguarded-deletion.md} +2 -2
  30. package/docs/{friction.md → history/friction.md} +123 -0
  31. package/docs/{secret-guard-analysis.md → history/secret-guard-analysis.md} +12 -12
  32. package/docs/{secret-guard-architecture.md → history/secret-guard-architecture.md} +2 -2
  33. package/docs/{secret-guard-design.md → history/secret-guard-design.md} +14 -14
  34. package/docs/lab/cases/injection-case-fake-ai-api.md +346 -0
  35. package/docs/{guard-lab.md → lab/guard-lab.md} +15 -13
  36. package/docs/{release-notes-0.2.0-rc1.md → releases/release-notes-0.2.0-rc1.md} +3 -3
  37. package/docs/{release-notes-0.2.0.md → releases/release-notes-0.2.0.md} +5 -5
  38. package/docs/{release-notes-0.2.1.md → releases/release-notes-0.2.1.md} +6 -6
  39. package/docs/{release-notes-0.2.2.md → releases/release-notes-0.2.2.md} +2 -2
  40. package/docs/{release-notes-0.2.3-rc1.md → releases/release-notes-0.2.3-rc1.md} +1 -1
  41. package/docs/{release-notes-0.2.3-rc2.md → releases/release-notes-0.2.3-rc2.md} +9 -9
  42. package/docs/{release-notes-0.2.3.md → releases/release-notes-0.2.3.md} +3 -3
  43. package/docs/releases/release-notes-0.2.4.md +89 -0
  44. package/docs/releases/release-notes-0.2.5-rc1.md +91 -0
  45. package/docs/{test-report-claude-code-harness.md → reports/test-report-claude-code-harness.md} +5 -5
  46. package/docs/reports/test-report-dsh-0.2.4-ptc.md +79 -0
  47. package/docs/{test-report-dsh-guard-lab.md → reports/test-report-dsh-guard-lab.md} +1 -1
  48. package/docs/{test-report-dsh-native-session.md → reports/test-report-dsh-native-session.md} +1 -1
  49. package/docs/{test-report-dsh-paired-lab.md → reports/test-report-dsh-paired-lab.md} +1 -1
  50. package/docs/{test-report-dsh-real-followup.md → reports/test-report-dsh-real-followup.md} +1 -1
  51. package/docs/{test-report-dsh-retry-evidence.md → reports/test-report-dsh-retry-evidence.md} +1 -1
  52. package/docs/{test-report-dsh-v0.1.1.md → reports/test-report-dsh-v0.1.1.md} +4 -4
  53. package/docs/{test-report-kimi-code-block.md → reports/test-report-kimi-code-block.md} +3 -3
  54. package/docs/{test-report-kimi-guard-lab.md → reports/test-report-kimi-guard-lab.md} +3 -3
  55. package/docs/{test-report-release-readiness-0.2.3.md → reports/test-report-release-readiness-0.2.3.md} +1 -1
  56. package/docs/{test-report-workbuddy-windows-core.md → reports/test-report-workbuddy-windows-core.md} +1 -1
  57. package/docs/{test-report-zcode-glm-flash.md → reports/test-report-zcode-glm-flash.md} +2 -2
  58. package/package.json +4 -2
  59. package/skills/delete-guard/SKILL.md +80 -7
  60. package/skills/delete-guard/references/policy.md +104 -8
  61. package/skills/delete-guard/scripts/check.py +22 -0
  62. package/skills/delete-guard/scripts/restore.py +34 -7
  63. package/skills/delete-guard/scripts/safe_delete.py +52 -29
  64. package/skills/delete-guard/scripts/status.py +52 -0
  65. package/skills/exfil-guard/SKILL.md +23 -11
  66. package/skills/exfil-guard/references/channels.md +9 -2
  67. package/skills/exfil-guard/references/rules.md +83 -6
  68. package/skills/exfil-guard/scripts/_payload.py +20 -0
  69. package/skills/exfil-guard/scripts/check_span.py +5 -1
  70. package/skills/exfil-guard/scripts/sanitize.py +6 -3
  71. /package/docs/{host-drift.md → guides/host-drift.md} +0 -0
  72. /package/docs/{publishing-from-ephemeral-environments.md → guides/publishing-from-ephemeral-environments.md} +0 -0
  73. /package/docs/{guard-lab-clean-task.md → lab/tasks/guard-lab-clean-task.md} +0 -0
  74. /package/docs/{guard-lab-read-trial-task.md → lab/tasks/guard-lab-read-trial-task.md} +0 -0
  75. /package/docs/{guard-lab-trial-task.md → lab/tasks/guard-lab-trial-task.md} +0 -0
  76. /package/docs/{test-report-codex-gpt-5.6-sol.md → reports/test-report-codex-gpt-5.6-sol.md} +0 -0
  77. /package/docs/{test-report-codex-gpt-6-astra-high.md → reports/test-report-codex-gpt-6-astra-high.md} +0 -0
  78. /package/docs/{test-report-dsh-0.1.5-rc.1.md → reports/test-report-dsh-0.1.5-rc.1.md} +0 -0
  79. /package/docs/{test-report-dsh-0.2-upgrade.md → reports/test-report-dsh-0.2-upgrade.md} +0 -0
  80. /package/docs/{test-report-dsh-read-redaction.md → reports/test-report-dsh-read-redaction.md} +0 -0
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.
@@ -0,0 +1,193 @@
1
+ """Read-only quarantine locations for CLI, agent and future UI callers.
2
+
3
+ This queries directory layout, not recovery contents or purge authority. No
4
+ RecoveryEngine is constructed, no Git command runs, and no layout is created.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import errno
9
+ import os
10
+ import stat
11
+ from typing import Any, Dict, Iterable, List
12
+
13
+ from . import AUDIT_NAME, MANIFEST_NAME, STATE_NAME, TRASH_DIRNAME
14
+
15
+
16
+ SCHEMA_VERSION = 1
17
+ DEFAULT_MAX_DEPTH = 3
18
+ DEFAULT_MAX_ENTRIES = 10_000
19
+ EXCLUDED_DIRS = (".git", "node_modules", ".internal", "__pycache__")
20
+
21
+
22
+ def _paths(values: Iterable[str]) -> List[str]:
23
+ if isinstance(values, (str, bytes)):
24
+ raise ValueError("paths must be a sequence of text paths")
25
+ try:
26
+ values = iter(values)
27
+ except TypeError:
28
+ raise ValueError("paths must be a sequence of text paths") from None
29
+ result = []
30
+ for value in values:
31
+ try:
32
+ value = os.fspath(value)
33
+ except TypeError:
34
+ raise ValueError("paths must contain text paths") from None
35
+ if not isinstance(value, str) or not value or "\0" in value:
36
+ raise ValueError("paths must contain nonempty text paths")
37
+ normalized = os.path.normpath(os.path.abspath(os.path.expanduser(value)))
38
+ if normalized not in result:
39
+ result.append(normalized)
40
+ return result
41
+
42
+
43
+ def _error_code(exc: OSError) -> str:
44
+ if exc.errno in (errno.EACCES, errno.EPERM):
45
+ return "PERMISSION_DENIED"
46
+ if exc.errno == errno.ENOENT:
47
+ return "NOT_FOUND"
48
+ if exc.errno == errno.ENOTDIR:
49
+ return "NOT_DIRECTORY"
50
+ return "IO_ERROR"
51
+
52
+
53
+ def list_trash_locations(
54
+ roots: Iterable[str] = (), *, trash_paths: Iterable[str] = (),
55
+ max_depth: int = DEFAULT_MAX_DEPTH,
56
+ max_entries: int = DEFAULT_MAX_ENTRIES,
57
+ ) -> Dict[str, Any]:
58
+ """Return schema v1 location candidates within explicit bounded roots.
59
+
60
+ Depth counts directories below a root: depth 0 still checks that root's
61
+ .agent-trash. A recognized bucket is never traversed. Ordinary child
62
+ directory links are skipped; explicitly supplied roots/buckets may use
63
+ aliases. Expected marker names are lstat'ed, never opened.
64
+
65
+ count includes unconfirmed/unreadable candidates; identified_count only
66
+ counts existing metadata layouts. Neither identifies ownership, content
67
+ integrity or permission to restore/purge. complete covers the declared
68
+ depth/exclusions and successful reads, not the whole host or an atomic
69
+ filesystem snapshot. Errors retain partial results.
70
+ """
71
+ if type(max_depth) is not int or max_depth < 0:
72
+ raise ValueError("max_depth must be a nonnegative integer")
73
+ if type(max_entries) is not int or max_entries < 1:
74
+ raise ValueError("max_entries must be a positive integer")
75
+ roots, trash_paths = _paths(roots), _paths(trash_paths)
76
+ if not roots and not trash_paths:
77
+ raise ValueError("provide roots or trash_paths")
78
+
79
+ buckets: Dict[str, Dict[str, Any]] = {}
80
+ errors: List[Dict[str, str]] = []
81
+ visited: Dict[str, int] = {}
82
+ examined = 0
83
+ exhausted = False
84
+
85
+ def error(path: str, code: str) -> None:
86
+ record = {"path": path, "code": code}
87
+ if record not in errors:
88
+ errors.append(record)
89
+
90
+ def charge(path: str) -> bool:
91
+ nonlocal examined, exhausted
92
+ if examined >= max_entries:
93
+ if not exhausted:
94
+ error(path, "ENTRY_LIMIT_REACHED")
95
+ exhausted = True
96
+ return False
97
+ examined += 1
98
+ return True
99
+
100
+ def bucket(path: str, source: str) -> None:
101
+ try:
102
+ if not stat.S_ISDIR(os.stat(path).st_mode):
103
+ error(path, "NOT_DIRECTORY")
104
+ return
105
+ resolved = os.path.normpath(os.path.realpath(path))
106
+ except OSError as exc:
107
+ error(path, _error_code(exc))
108
+ return
109
+ key = os.path.normcase(resolved)
110
+ if key in buckets:
111
+ row = buckets[key]
112
+ if path not in row["locations"]:
113
+ row["locations"].append(path)
114
+ if source not in row["sources"]:
115
+ row["sources"].append(source)
116
+ return
117
+
118
+ present = unreadable = False
119
+ for name in (MANIFEST_NAME, AUDIT_NAME, STATE_NAME, "sessions"):
120
+ try:
121
+ mode = os.lstat(os.path.join(path, name)).st_mode
122
+ present |= (stat.S_ISDIR(mode) if name == "sessions"
123
+ else stat.S_ISREG(mode))
124
+ except FileNotFoundError:
125
+ continue
126
+ except OSError as exc:
127
+ unreadable = True
128
+ error(path, _error_code(exc))
129
+ status = ("unreadable" if unreadable else
130
+ "metadata_present" if present else "unconfirmed")
131
+ buckets[key] = {
132
+ "trash_root": path, "resolved_trash_root": resolved,
133
+ "directory": os.path.dirname(path), "locations": [path],
134
+ "sources": [source], "status": status,
135
+ }
136
+
137
+ for path in trash_paths:
138
+ if not charge(path):
139
+ break
140
+ bucket(path, "declared")
141
+
142
+ for root in roots:
143
+ if exhausted:
144
+ break
145
+ stack = [(root, 0)]
146
+ while stack and not exhausted:
147
+ directory, depth = stack.pop()
148
+ if not charge(directory):
149
+ break
150
+ if os.path.basename(directory) == TRASH_DIRNAME:
151
+ bucket(directory, "discovered")
152
+ continue
153
+ try:
154
+ physical = os.path.normcase(os.path.realpath(directory))
155
+ except OSError as exc:
156
+ error(directory, _error_code(exc))
157
+ continue
158
+ remaining = max_depth - depth
159
+ if visited.get(physical, -1) >= remaining:
160
+ continue
161
+ visited[physical] = remaining
162
+ children = []
163
+ try:
164
+ with os.scandir(directory) as entries:
165
+ for entry in entries:
166
+ if not charge(entry.path):
167
+ break
168
+ if entry.name == TRASH_DIRNAME:
169
+ bucket(entry.path, "discovered")
170
+ elif (depth < max_depth and entry.name not in EXCLUDED_DIRS
171
+ and entry.is_dir(follow_symlinks=False)):
172
+ children.append(entry.path)
173
+ except OSError as exc:
174
+ error(directory, _error_code(exc))
175
+ # Reverse push gives stable lexical order among directory children.
176
+ stack.extend((path, depth + 1) for path in sorted(children, reverse=True))
177
+
178
+ rows = sorted(buckets.values(), key=lambda row: row["resolved_trash_root"])
179
+ for row in rows:
180
+ row["locations"].sort()
181
+ row["sources"].sort()
182
+ row["trash_root"] = row["locations"][0]
183
+ row["directory"] = os.path.dirname(row["trash_root"])
184
+ return {
185
+ "schema_version": SCHEMA_VERSION,
186
+ "roots": roots, "trash_paths": trash_paths,
187
+ "max_depth": max_depth, "max_entries": max_entries,
188
+ "excluded_dirs": list(EXCLUDED_DIRS), "examined": examined,
189
+ "complete": not errors,
190
+ "count": len(rows),
191
+ "identified_count": sum(row["status"] == "metadata_present" for row in rows),
192
+ "entries": rows, "errors": errors,
193
+ }
package/docs/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # Documentation / 文档导航
2
+
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
+ Current source: [0.2.5-rc1 candidate](releases/release-notes-0.2.5-rc1.md).
11
+ Published stable baseline: [0.2.4](releases/release-notes-0.2.4.md).
12
+ Candidate preparation and package validation do not establish publication.
13
+
14
+ 先看入门指南,再按恢复保护、外发检测、Lab 验测选择入口。测试报告按所测版本与配置保留;发布记录、
15
+ 历史设计和外部案例各自归档,不能据此扩展当前产品的承诺。
16
+
17
+ | Category / 分类 | Contents / 内容 |
18
+ |---|---|
19
+ | [Guides](#guides) / 使用指南 | 宿主接入证据、漂移检查、维护者发布指南 |
20
+ | [Design](#design) / 架构与契约 | 当前架构、威胁模型与兼容契约 |
21
+ | [Lab](#lab) / 实验与候选素材 | Lab 流程、任务模板、外部攻击案例 |
22
+ | [Reports](#reports) / 测试报告 | 按宿主、版本和观察范围记录的证据 |
23
+ | [Releases](#releases) / 发布记录 | 正式版与预览版各自的范围 |
24
+ | [History](#history) / 历史设计与经验 | 早期设计、实现教训和事故探索 |
25
+
26
+ ## Guides
27
+
28
+ | Document / 文档 | Scope / 范围 |
29
+ |---|---|
30
+ | [Getting started](guides/getting-started.md) | 安装路径、Agent 接入提示词与最短验证流程 |
31
+ | [Harness capabilities](guides/harness-capabilities.md) | 当前接入范围、证据等级与未验证路径 |
32
+ | [Host drift](guides/host-drift.md) | 宿主版本、配置与本地基线检查 |
33
+ | [Trash locations](guides/trash-index.md) | 0.2.4 的只读位置查询、Agent/前端共享 JSON 契约 |
34
+ | [Publishing from ephemeral environments](guides/publishing-from-ephemeral-environments.md) | 临时环境中的 GitHub 发布操作参考 |
35
+
36
+ Adapter setup remains in [adapters/](../adapters/INTEGRATION.md). Skill contracts
37
+ remain in [skills/](../skills/delete-guard/SKILL.md).
38
+
39
+ ## Design
40
+
41
+ | Document / 文档 | Scope / 范围 |
42
+ |---|---|
43
+ | [Architecture](design/architecture.md) | Core、Decision Protocol、适配器与数据流 |
44
+ | [Threat model](design/threat-model.md) | 资产、可信假设与已知防护边界 |
45
+ | [Compatibility](design/compatibility.md) | 适配器契约、接口兼容与版本约定 |
46
+
47
+ ## Lab
48
+
49
+ | Document / 文档 | Scope / 范围 |
50
+ |---|---|
51
+ | [Guard Lab guide](lab/guard-lab.md) | 操作流程、信道、L0/L1/L2 语义与限制 |
52
+ | [Clean task](lab/tasks/guard-lab-clean-task.md) | 干净对照任务模板 |
53
+ | [Injection trial task](lab/tasks/guard-lab-trial-task.md) | 提示注入试次任务模板 |
54
+ | [Native-read trial task](lab/tasks/guard-lab-read-trial-task.md) | 原生读取脱敏任务模板 |
55
+ | [fake-ai-api reference](lab/cases/injection-case-fake-ai-api.md) | 外部攻击端候选素材;尚未作为 Lab 样本验证 |
56
+
57
+ Task templates and external case references are separate from completed test
58
+ reports. A scripted provider checks host behavior; a real-model injection
59
+ trial needs an effective unguarded baseline before a matched comparison.
60
+
61
+ ## Reports
62
+
63
+ Each report preserves its original version, configuration, result and limits.
64
+ Use the [capability matrix](guides/harness-capabilities.md) to interpret current
65
+ coverage rather than treating every historical result as current acceptance.
66
+
67
+ | Document / 文档 | Scope / 范围 |
68
+ |---|---|
69
+ | [0.2.3 contract review](reports/test-report-release-readiness-0.2.3.md) | 发布前契约复核与 DSH 原生验收 |
70
+ | [0.2.4 official Flash / PTC](reports/test-report-dsh-0.2.4-ptc.md) | 实模主/子代理碰撞拒绝;原始主 PTC 任务失败与独立收尾分别记录 |
71
+ | [Claude Code harness](reports/test-report-claude-code-harness.md) | 脚本模型驱动的真实宿主 hook 验证 |
72
+ | [Kimi Code blocking](reports/test-report-kimi-code-block.md) | 所测版本的 Bash BLOCK 与故障路径 |
73
+ | [Kimi Code Lab](reports/test-report-kimi-guard-lab.md) | 历史配对试次与后续本地复核 |
74
+ | [Codex / GPT-6 Astra](reports/test-report-codex-gpt-6-astra-high.md) | Skill/CLI 验收,不声明原生拦截 |
75
+ | [Codex / GPT-5.6 Sol](reports/test-report-codex-gpt-5.6-sol.md) | v0.1.1 历史 Skill/CLI 评估 |
76
+ | [DSH 0.1.5-rc.1](reports/test-report-dsh-0.1.5-rc.1.md) | 打包插件与执行级 Bash 验收 |
77
+ | [DSH 0.2 upgrade](reports/test-report-dsh-0.2-upgrade.md) | 升级初期兼容快照,后续状态见契约复核 |
78
+ | [DSH Lab baseline](reports/test-report-dsh-guard-lab.md) | 真实模型基线;未形成 L2 结论 |
79
+ | [DSH native sessions](reports/test-report-dsh-native-session.md) | 原生工具结果捕获与保留日志复核 |
80
+ | [DSH paired Lab](reports/test-report-dsh-paired-lab.md) | 配对工作流与结果改写契约调查 |
81
+ | [DSH retry evidence](reports/test-report-dsh-retry-evidence.md) | 失败尝试、重试会话与证据解析 |
82
+ | [DSH read redaction](reports/test-report-dsh-read-redaction.md) | 零模型原生读取、下一请求与落盘检查 |
83
+ | [DSH real follow-up](reports/test-report-dsh-real-followup.md) | 真实读取开关对照;不等于注入 L2 |
84
+ | [DSH v0.1.1](reports/test-report-dsh-v0.1.1.md) | 历史真机测试 |
85
+ | [WorkBuddy / Windows Core](reports/test-report-workbuddy-windows-core.md) | 社区 Core/CLI 反馈与修复回归 |
86
+ | [ZCode / Windows](reports/test-report-zcode-glm-flash.md) | 历史 CLI/hook 试次及许可绕过观察 |
87
+
88
+ ## Releases
89
+
90
+ | Document / 文档 | Scope / 范围 |
91
+ |---|---|
92
+ | [0.2.5-rc1](releases/release-notes-0.2.5-rc1.md) | 当前维护候选、文档整理、版本例外与验收状态 |
93
+ | [0.2.4](releases/release-notes-0.2.4.md) | 恢复维护、trash 查询及兼容性例外 |
94
+ | [0.2.3](releases/release-notes-0.2.3.md) | 正式版范围与证据边界 |
95
+ | [0.2.3-rc2](releases/release-notes-0.2.3-rc2.md) | 离线 Lab 与已复核 DSH 契约 |
96
+ | [0.2.3-rc1](releases/release-notes-0.2.3-rc1.md) | Windows Core 与预发布范围 |
97
+ | [0.2.2](releases/release-notes-0.2.2.md) | 宿主漂移、实时哨兵与 DSH 打包验收 |
98
+ | [0.2.1](releases/release-notes-0.2.1.md) | adapter/doctor 变更 |
99
+ | [0.2.0](releases/release-notes-0.2.0.md) | exfil 与配置安全视图等发布范围 |
100
+ | [0.2.0-rc1](releases/release-notes-0.2.0-rc1.md) | 早期源码预览范围 |
101
+
102
+ ## History
103
+
104
+ These documents explain earlier proposals and implementation experience.
105
+ Current behavior is defined by the Core, Skills and current guides.
106
+
107
+ | Document / 文档 | Scope / 范围 |
108
+ |---|---|
109
+ | [Friction log](history/friction.md) | F1–F20 实现发现与修复经验 |
110
+ | [Unguarded deletion note](history/development-note-unguarded-deletion.md) | 去标识化事故探索与恢复方向 |
111
+ | [Secret Guard analysis](history/secret-guard-analysis.md) | 实现前的需求分析 |
112
+ | [Secret Guard design](history/secret-guard-design.md) | 早期设计候选与原范围 |
113
+ | [Secret Guard architecture](history/secret-guard-architecture.md) | 早期架构草图;不代表拦截点已交付 |
@@ -36,7 +36,7 @@ becomes a BLOCK verdict, never a guess.
36
36
  This diagram shows a supported native adapter path. An explicit CLI caller
37
37
  joins at `check.py`, skipping the adapter prefilter. Neither path implies that
38
38
  every harness or tool call is intercepted. Exfil-guard's cooperative text CLI
39
- is separate; see [harness capabilities](harness-capabilities.md).
39
+ is separate; see [harness capabilities](../guides/harness-capabilities.md).
40
40
 
41
41
  ```
42
42
  shell command (from a supported native adapter)
@@ -119,11 +119,11 @@ a harness-owned background sidecar.
119
119
 
120
120
  This layout separates accidental access in the intended workflow, not OS
121
121
  privileges. A same-UID adversary can inspect or alter both sides. See
122
- [guard-lab](guard-lab.md) for the evidence semantics and unsupported channels.
122
+ [guard-lab](../lab/guard-lab.md) for the evidence semantics and unsupported channels.
123
123
 
124
124
  ## Opt-in DSH text-read boundary
125
125
 
126
- The [experimental read prototype](test-report-dsh-read-redaction.md) adds a
126
+ The [experimental read prototype](../reports/test-report-dsh-read-redaction.md) adds a
127
127
  separate post-execute path for reviewed, artifact-pinned native text-read
128
128
  contracts (local FS and DSH `0.2.0-rc.2` sandbox FS):
129
129
  native complete read value → bounded Python stdin worker → existing Core
@@ -134,7 +134,7 @@ reviewed deletion-only Lab profiles keep this path disabled.
134
134
 
135
135
  Native validation uses the actual read, AgentLoop and JSONL backend with a
136
136
  deterministic synthetic stream; it checks next-request content and durable
137
- metadata too; the [current review](test-report-release-readiness-0.2.3.md)
137
+ metadata too; the [current review](../reports/test-report-release-readiness-0.2.3.md)
138
138
  records both new-host providers. Pagination, custom finalizers/unreviewed providers, PTC, other tools and
139
139
  events before this hook remain outside this boundary. No real-model L2
140
140
  evidence follows from the zero-model probe.
@@ -242,19 +242,47 @@ FORBIDDEN (BLOCK, never askable).
242
242
  *snapshot* (`stash create` without touching the tree). Both produce a
243
243
  txid recorded in manifest + audit. Future compensations (database
244
244
  backup/PITR, cloud snapshot) plug into the same slot.
245
+ Hard reset first compares its target tree with untracked and ignored
246
+ paths. Collisions are blocked because the tracked-only stash cannot
247
+ protect them; no automatic untracked archive is created in this version.
245
248
  4. **Restore is non-destructive.** It refuses to overwrite existing origin
246
- paths; `--force` is an explicit human decision. A recovery tool that can
247
- clobber would be a second destruction vector.
249
+ paths; `--force` is an explicit human decision. Relocation paths are checked
250
+ as a batch before mutation and again before each item: destination parent
251
+ chains must stay inside the selected workspace, and source parent chains
252
+ inside their own quarantine transaction. IDs cannot contain path separators
253
+ or traversal; transaction directories cannot redirect to another location.
254
+ The final component is kept unresolved so restoring a symlink restores the
255
+ link. `--force` cannot bypass either boundary check. Before replacing an
256
+ occupant, it uses the existing relocation journal to preserve that version
257
+ in a separate transaction. Preservation failure stops that item; the result
258
+ lists preservation attempts in optional `backup_txids`. Quarantine roots,
259
+ aliases and ancestor paths cannot themselves be moved for preservation.
260
+ This is not an atomic restore: concurrent changes and cross-filesystem
261
+ failures may leave a partial destination, so inspect the reported paths
262
+ and transaction state before retrying.
248
263
  5. **Lexical boundaries.** Workspace containment is decided on normalized
249
264
  paths; deleting a symlink removes the link, never the target, so symlink
250
265
  targets outside the workspace neither leak nor block.
251
- 6. **Self-exclusion.** Targets inside `.agent-trash/` are exempted from
252
- quarantine - housekeeping cannot recurse into itself forever.
266
+ 6. **Self-exclusion with protected controls.** Ordinary unprotected payloads
267
+ inside the selected quarantine use housekeeping rather than relocation.
268
+ The 0.2.5-rc1 candidate checks root/control paths and storage parents first;
269
+ housekeeping cannot override protection. Opaque globs must be enumerated
270
+ explicitly, and validated transaction purge uses the GC CLI.
253
271
  7. **Diagnostics do not silently become enforcement.** `guard-lab` records
254
272
  declared synthetic channels and evaluates one case criterion. It does not
255
273
  feed a Lab observation into Core policy or claim to ban model calls. A real
256
274
  block would require a host hook or request gateway that owns the call.
257
275
 
276
+ ## Read-only quarantine queries
277
+
278
+ core/trash_index.py exposes list_trash_locations for CLI, agent and future
279
+ trusted local frontend callers. status.py --trash-index supplies explicit
280
+ roots or declared buckets and returns schema version 1. This branch executes
281
+ before ordinary status accounting: no RecoveryEngine, Git, audit writes,
282
+ payload traversal or GC planning. Discovery is bounded, prunes quarantine
283
+ subtrees and deduplicates physical addresses. Metadata presence is a layout
284
+ hint; location results are not authorization for later restore or purge.
285
+
258
286
  ## Harness adapter model
259
287
 
260
288
  Any agent harness integrates through three optional points, in increasing
@@ -270,7 +298,17 @@ order of value:
270
298
  skill and the "prefer safe_delete" rule. Interception without prompting
271
299
  causes friction; prompting without interception is advisory only.
272
300
 
273
- ## Roadmap
301
+ ## Delivery status and design directions
302
+
303
+ The current source candidate is 0.2.5-rc1; 0.2.4 remains the published stable
304
+ baseline. The candidate contains the documented lifecycle/audit maintenance
305
+ and exemption diagnostics, alongside a README/documentation reorganization.
306
+ See [candidate notes](../releases/release-notes-0.2.5-rc1.md) and
307
+ [compatibility](compatibility.md) for behaviour and validation boundaries.
308
+
309
+ The milestones below describe historical delivery and future design scope,
310
+ not a committed schedule or a guarantee that new compensation types need no
311
+ architecture changes.
274
312
 
275
313
  - V1 (this repo): delete-guard skill, fs + git compensations, Linux/macOS.
276
314
  - v0.1.1: durable relocation intents, explicit retention/GC policy, quoted
@@ -290,7 +328,7 @@ order of value:
290
328
  `tests/test_dialect_phase2.py`) cover further cmd/PowerShell spellings,
291
329
  option aliases and fail-closed edge cases. Hook payload dialect forwarding
292
330
  has adapter tests; this is not a Windows host execution claim.
293
- - **Phase 3a (`0.2.3-rc1` candidate).** A blocking `windows-latest` Core
331
+ - **Phase 3a (shipped since `0.2.3-rc1`).** A blocking `windows-latest` Core
294
332
  job covers the Issue #7 dialect-mismatch and separator regressions,
295
333
  deterministic cmd/PowerShell facts, and recovery inside disposable
296
334
  fixtures. The job uses Python argv/bytes so a surrounding shell cannot
@@ -300,7 +338,7 @@ order of value:
300
338
  broader UNC/device paths and full-suite portability still require
301
339
  separate evidence. A focused Core runner is not a universal Windows E2E
302
340
  claim.
303
- - `0.2.3-rc2` source candidate: offline `guard-lab` MVP with disposable
341
+ - Offline `guard-lab` MVP, introduced in `0.2.3-rc2` and shipped in `0.2.3`: disposable
304
342
  synthetic fixtures, zero-token controls, a bounded loopback observer,
305
343
  explicit-output marker scanning, chained evidence, and fail-inconclusive
306
344
  reports. General file-read visibility, remote callbacks, real-model rating,
@@ -310,4 +348,5 @@ order of value:
310
348
  - V3+: `database-guard` (compensations = transaction / backup /
311
349
  point-in-time recovery), `cloud-guard` (snapshot / state capture). The
312
350
  Guard answers "may this happen"; the Compensation Engine answers "how do
313
- we come back" - both extend without restructuring the repository.
351
+ we come back". These remain design directions requiring separate scope and
352
+ implementation decisions.