@mokuyoaxis/agent-guard 0.2.3-rc1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +124 -52
  2. package/README.zh-CN.md +102 -41
  3. package/adapters/dsh/README.md +92 -10
  4. package/adapters/dsh/harness/README.md +384 -0
  5. package/adapters/dsh/harness/baseline.patch.yml +8 -0
  6. package/adapters/dsh/harness/bootstrap.patch.yml +5 -0
  7. package/adapters/dsh/harness/bootstrap_init.mjs +48 -0
  8. package/adapters/dsh/harness/guard_lab.py +771 -0
  9. package/adapters/dsh/harness/native_session.py +503 -0
  10. package/adapters/dsh/harness/profiles.py +212 -0
  11. package/adapters/dsh/harness/read_fixture.py +60 -0
  12. package/adapters/dsh/harness/retry_stream.py +171 -0
  13. package/adapters/dsh/harness/session_decode.mjs +117 -0
  14. package/adapters/dsh/lib/index.js +46 -5
  15. package/adapters/dsh/lib/read_result_guard.js +207 -0
  16. package/adapters/dsh/lib/read_result_guard.py +139 -0
  17. package/adapters/harness_support.py +109 -0
  18. package/adapters/kimi-code/README.md +15 -7
  19. package/adapters/kimi-code/harness/README.md +126 -0
  20. package/adapters/kimi-code/harness/guard_lab.py +430 -0
  21. package/core/lab.py +2396 -0
  22. package/core/redaction.py +157 -55
  23. package/docs/architecture.md +75 -0
  24. package/docs/development-note-unguarded-deletion.md +6 -7
  25. package/docs/friction.md +140 -4
  26. package/docs/guard-lab-clean-task.md +4 -0
  27. package/docs/guard-lab-read-trial-task.md +7 -0
  28. package/docs/guard-lab-trial-task.md +5 -0
  29. package/docs/guard-lab.md +398 -0
  30. package/docs/harness-capabilities.md +8 -5
  31. package/docs/release-notes-0.2.0-rc1.md +2 -2
  32. package/docs/release-notes-0.2.0.md +2 -2
  33. package/docs/release-notes-0.2.2.md +7 -8
  34. package/docs/release-notes-0.2.3-rc1.md +4 -2
  35. package/docs/release-notes-0.2.3-rc2.md +189 -0
  36. package/docs/release-notes-0.2.3.md +84 -0
  37. package/docs/secret-guard-analysis.md +13 -12
  38. package/docs/secret-guard-architecture.md +5 -3
  39. package/docs/secret-guard-design.md +7 -3
  40. package/docs/test-report-codex-gpt-5.6-sol.md +10 -11
  41. package/docs/test-report-dsh-0.2-upgrade.md +142 -0
  42. package/docs/test-report-dsh-guard-lab.md +154 -0
  43. package/docs/test-report-dsh-native-session.md +118 -0
  44. package/docs/test-report-dsh-paired-lab.md +183 -0
  45. package/docs/test-report-dsh-read-redaction.md +114 -0
  46. package/docs/test-report-dsh-real-followup.md +170 -0
  47. package/docs/test-report-dsh-retry-evidence.md +134 -0
  48. package/docs/test-report-kimi-code-block.md +19 -20
  49. package/docs/test-report-kimi-guard-lab.md +117 -0
  50. package/docs/test-report-release-readiness-0.2.3.md +239 -0
  51. package/docs/test-report-workbuddy-windows-core.md +53 -0
  52. package/docs/test-report-zcode-glm-flash.md +9 -9
  53. package/docs/threat-model.md +42 -0
  54. package/guard_lab.py +14 -0
  55. package/package.json +8 -5
  56. package/skills/delete-guard/SKILL.md +2 -3
  57. package/skills/exfil-guard/SKILL.md +37 -7
  58. package/skills/exfil-guard/references/rules.md +84 -16
  59. package/skills/exfil-guard/scripts/_payload.py +99 -0
  60. package/skills/exfil-guard/scripts/check_span.py +14 -81
  61. package/skills/exfil-guard/scripts/sanitize.py +113 -34
@@ -0,0 +1,771 @@
1
+ #!/usr/bin/env python3
2
+ """Capture, review and compare bounded DSH headless Lab trials.
3
+
4
+ This runner deliberately keeps real-host completion user-declared. A zero
5
+ exit status and a nonempty capture are prerequisites, not proof of completion.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ from typing import Optional, Sequence
18
+
19
+
20
+ ROOT = Path(__file__).resolve().parents[3]
21
+ sys.path.insert(0, str(ROOT))
22
+
23
+ from core.lab import ( # noqa: E402
24
+ INJECTION_SAMPLES, LabError, MAX_SCAN_BYTES, MAX_TASK_BYTES, TRIAL_GROUP_PATTERN,
25
+ TRIAL_LABEL_PATTERN, arm_observer, build_report, compare_runs,
26
+ prepare_run, record_host_result, request_stop, scan_bytes,
27
+ )
28
+ from adapters.harness_support import ( # noqa: E402
29
+ capture_process as _capture_process, digest as _digest,
30
+ read_regular as _read_regular, write_new as _write_new,
31
+ write_json as _write_json,
32
+ )
33
+ from adapters.dsh.harness.native_session import ( # noqa: E402
34
+ PARSER_VERSION, capture_session, check_decoder, session_inventory, split_session,
35
+ )
36
+ from adapters.dsh.harness.profiles import ( # noqa: E402
37
+ ADAPTER, MEMBERS, GUARD_PROFILES, configuration_fingerprint, guard_patch,
38
+ normalize_composition, prepare_homes,
39
+ )
40
+
41
+
42
+ TESTED_VERSION = "0.2.0-rc.2"
43
+ HOST_CONTRACTS = {"0.1.5-rc.1": (3, 4), "0.2.0-rc.2": (4, 5)}
44
+ BASELINE_PATCH = Path(__file__).with_name("baseline.patch.yml")
45
+ BOOTSTRAP_PATCH = Path(__file__).with_name("bootstrap.patch.yml")
46
+ BOOTSTRAP_INIT = Path(__file__).with_name("bootstrap_init.mjs")
47
+ RECEIPT_VERSION = 6
48
+ MAX_RECEIPT_BYTES = 64 * 1024
49
+
50
+
51
+ def _profile_options(profile, workspace, dsh_root):
52
+ return {"profile": profile, "workspace": workspace, "dsh_root": dsh_root}
53
+
54
+
55
+ def _launcher_root(executable: str, version: str) -> Path:
56
+ for parent in Path(executable).resolve().parents:
57
+ manifest = parent / "package.json"
58
+ if manifest.is_file():
59
+ value = json.loads(_read_regular(manifest, MAX_RECEIPT_BYTES))
60
+ if value.get("name") == "@deepseek-ai/dsh" and value.get("version") == version:
61
+ return parent
62
+ raise LabError("bootstrap requires the reviewed installed DSH package launcher")
63
+
64
+
65
+ def _guard_assets() -> dict:
66
+ names = ["adapters/dsh/lib/index.js", "adapters/dsh/lib/read_result_guard.js",
67
+ "adapters/dsh/lib/read_result_guard.py", "skills/exfil-guard/scripts/sanitize.py",
68
+ "skills/exfil-guard/scripts/_payload.py", "skills/exfil-guard/scripts/_bootstrap.py"]
69
+ names.extend(str(path.relative_to(ROOT)) for path in sorted((ROOT / "core").glob("*.py")))
70
+ return {name: _digest(_read_regular(ROOT / name, MAX_SCAN_BYTES)) for name in names}
71
+
72
+
73
+ def _environment(home: Path) -> dict[str, str]:
74
+ environment = dict(os.environ)
75
+ # A previous sentinel/workspace must not redirect this independent trial.
76
+ for name in tuple(environment):
77
+ if name.startswith("AGENT_GUARD_"):
78
+ environment.pop(name)
79
+ environment["DSH_HOME"] = str(home)
80
+ environment["DSH_TELEMETRY_DISABLED"] = "1"
81
+ return environment
82
+
83
+
84
+ def _host_options(
85
+ executable: str, home: Path, patches: Sequence[Path],
86
+ guard_state: str = "off", guard_patch_file: Optional[Path] = None,
87
+ *, guard_profile="deletion-v1", workspace=None, dsh_root=None,
88
+ ) -> tuple[list[str], dict[str, str]]:
89
+ if os.name != "posix":
90
+ raise LabError("this DSH runner currently supports POSIX hosts only")
91
+ resolved = shutil.which(executable)
92
+ if not resolved:
93
+ raise LabError("DSH executable was not found")
94
+ resolved = str(Path(resolved).absolute())
95
+ home = home.expanduser().resolve()
96
+ if not (home / "profiles" / "headless" / "package.json").is_file():
97
+ raise LabError("select an already initialized disposable headless DSH home")
98
+ if home == (Path.home() / ".dsh").resolve():
99
+ raise LabError("use a disposable DSH home, not the default user home")
100
+ argv = [resolved, "--profile", "headless"]
101
+ if guard_state not in {"off", "on"} or (guard_state == "on") != (guard_patch_file is not None):
102
+ raise LabError("guard-on requires the generated local guard patch; guard-off omits it")
103
+ expected_patch = guard_patch(guard_profile, workspace, dsh_root)
104
+ if guard_patch_file is not None and _read_regular(guard_patch_file, MAX_RECEIPT_BYTES) != expected_patch:
105
+ raise LabError("select the exact generated local Guard patch")
106
+ layers = (*patches, BASELINE_PATCH, *((guard_patch_file,) if guard_patch_file else ()))
107
+ for patch in layers:
108
+ selected = patch.expanduser().absolute()
109
+ _read_regular(selected, MAX_RECEIPT_BYTES)
110
+ argv.extend(["--patch", str(selected)])
111
+ return argv, _environment(home)
112
+
113
+
114
+ def _config_dump(
115
+ argv: Sequence[str], cwd: Path, environment: dict[str, str],
116
+ guard_state: str = "off",
117
+ *, guard_profile="deletion-v1", workspace=None, dsh_root=None,
118
+ ) -> bytes:
119
+ result, output = _capture_process(
120
+ [*argv, "--dump-config"], cwd, environment, 15,
121
+ )
122
+ if (
123
+ result["exit_code"] != 0 or result["timed_out"]
124
+ or result["output_limit_exceeded"] or not output["stdout"].strip()
125
+ ):
126
+ raise LabError("DSH config preflight failed; raw diagnostics are not printed")
127
+ normalize_composition(output["stdout"], guard_state,
128
+ **_profile_options(guard_profile, workspace, dsh_root))
129
+ return output["stdout"]
130
+
131
+
132
+ def check_host(
133
+ executable: str, home: Path, patches: Sequence[Path] = (),
134
+ node_executable: str = "node",
135
+ guard_state: str = "off", guard_patch_file: Optional[Path] = None,
136
+ *, guard_profile="deletion-v1", workspace=None, dsh_root=None,
137
+ ) -> tuple[dict, list[str], dict[str, str]]:
138
+ home = home.expanduser().resolve()
139
+ context = dict(guard_profile=guard_profile, workspace=workspace, dsh_root=dsh_root)
140
+ argv, environment = _host_options(executable, home, patches, guard_state, guard_patch_file, **context)
141
+ result, output = _capture_process([argv[0], "--version"], home.resolve(), environment, 10)
142
+ version = output["stdout"].strip().decode("ascii", errors="replace")
143
+ if (
144
+ result["exit_code"] != 0 or result["timed_out"]
145
+ or result["output_limit_exceeded"]
146
+ or version not in HOST_CONTRACTS
147
+ ):
148
+ raise LabError("DSH version preflight requires a reviewed exact host version")
149
+ if guard_profile == "read-redaction-v1" and _launcher_root(argv[0], version) != Path(dsh_root).resolve():
150
+ raise LabError("read profile root must match the selected DSH launcher")
151
+ configuration = _config_dump(argv, home.resolve(), environment, guard_state, **context)
152
+ decoder, _ = check_decoder(node_executable, home, environment)
153
+ return {
154
+ "harness_version": version,
155
+ "native_format_version": HOST_CONTRACTS[version][0],
156
+ "profile": "headless", "guard_state": guard_state.upper(),
157
+ "guard_state_source": "user-declared",
158
+ "guard_profile": guard_profile, "native_parser_version": PARSER_VERSION,
159
+ "composition_bytes": len(configuration),
160
+ "composition_sha256": _digest(configuration),
161
+ "telemetry_disabled": True, "configuration_retained": False,
162
+ "model_identity_source": "user-declared",
163
+ "native_decoder": decoder,
164
+ "non_guard_configuration_sha256": configuration_fingerprint(home, configuration, environment, guard_state,
165
+ **_profile_options(guard_profile, workspace, dsh_root)),
166
+ "configuration_scope": "dsh-lab-non-guard-v2",
167
+ "guard_adapter_sha256": _digest(_read_regular(ADAPTER, MAX_SCAN_BYTES)),
168
+ "guard_assets": _guard_assets(),
169
+ }, argv, environment
170
+
171
+
172
+ def _initialize_home(executable, home, patches, node_executable) -> dict:
173
+ preflight, argv, environment = check_host(executable, home, patches, node_executable)
174
+ if session_inventory(home):
175
+ raise LabError("bootstrap requires a fresh disposable home")
176
+ if preflight["harness_version"] == "0.1.5-rc.1":
177
+ return {"method": "legacy-host-no-import", "model_tasks_launched": 0}
178
+ root = _launcher_root(argv[0], preflight["harness_version"])
179
+ legacy = home / "settings.yaml"
180
+ imported = home / "settings.yaml.imported"
181
+ legacy_payload = _read_regular(legacy, MAX_SCAN_BYTES) if legacy.exists() else None
182
+ if legacy_payload is not None and imported.exists():
183
+ raise LabError("ambiguous legacy bootstrap documents")
184
+ init_argv = [node_executable, str(BOOTSTRAP_INIT), str(root),
185
+ *(str(path.expanduser().absolute()) for path in patches), str(BASELINE_PATCH), str(BOOTSTRAP_PATCH)]
186
+ capture = home / ".lab-bootstrap"
187
+ if capture.exists() or capture.is_symlink():
188
+ raise LabError("bootstrap capture already exists; use fresh copied homes")
189
+ capture.mkdir(mode=0o700)
190
+ fingerprints = []
191
+ for index in range(2):
192
+ result, streams = _capture_process(init_argv, home, environment, 60)
193
+ for name, payload in streams.items():
194
+ _write_new(capture / (str(index + 1) + "-" + name + ".bin"), payload)
195
+ _write_json(capture / (str(index + 1) + "-receipt.json"), {
196
+ "host": result, "model_tasks_launched": 0,
197
+ "streams": {name: {"bytes": len(payload), "sha256": _digest(payload)}
198
+ for name, payload in streams.items()}})
199
+ if (result["exit_code"] != 0 or any(result[key] for key in
200
+ ("timed_out", "start_failed", "output_limit_exceeded"))
201
+ or any(b"was not imported" in data for data in streams.values())
202
+ or session_inventory(home)):
203
+ raise LabError("native bootstrap failed or created a session; no model task was launched by the Lab")
204
+ if legacy.exists() or (legacy_payload is not None
205
+ and _read_regular(imported, MAX_SCAN_BYTES) != legacy_payload):
206
+ raise LabError("legacy bootstrap import did not complete")
207
+ value, _, _ = check_host(executable, home, patches, node_executable)
208
+ fingerprints.append(value["non_guard_configuration_sha256"])
209
+ if fingerprints[0] != fingerprints[1]:
210
+ raise LabError("native bootstrap settings did not stabilize")
211
+ return {"method": "native-import-with-driver-disabled-v1", "passes": 2,
212
+ "model_tasks_launched": 0, "sessions_created": 0,
213
+ "settings_stable": True, "legacy_imported": legacy_payload is not None}
214
+
215
+
216
+ def run_trial(
217
+ output_dir: Path, home: Path, executable: str, case_id: str,
218
+ task_file: Path, model_label: str, trial_group: str,
219
+ patches: Sequence[Path] = (), timeout: int = 120,
220
+ attack_sample: str = "direct-v1",
221
+ node_executable: str = "node",
222
+ guard_state: str = "off", guard_patch_file: Optional[Path] = None,
223
+ expected_configuration_sha256: Optional[str] = None,
224
+ *, guard_profile="deletion-v1", dsh_root=None,
225
+ ) -> dict:
226
+ if case_id not in {"clean", "injection-probe"}:
227
+ raise LabError("this runner supports clean and injection-probe only")
228
+ if not 1 <= timeout <= 600:
229
+ raise LabError("host timeout must be between 1 and 600 seconds")
230
+ if attack_sample not in INJECTION_SAMPLES or (case_id != "injection-probe" and attack_sample != "direct-v1"):
231
+ raise LabError("select a known attack sample for injection-probe only")
232
+ if case_id == "injection-probe" and ((attack_sample == "read-redaction-v1") != (guard_profile == "read-redaction-v1")):
233
+ raise LabError("read redaction profile and attack sample must be selected together")
234
+ if not TRIAL_LABEL_PATTERN.fullmatch(model_label):
235
+ raise LabError("model label must follow the Lab public-label format")
236
+ if not TRIAL_GROUP_PATTERN.fullmatch(trial_group):
237
+ raise LabError("trial group must follow the Lab slug format")
238
+ task = _read_regular(task_file.expanduser().absolute(), MAX_TASK_BYTES)
239
+ try:
240
+ prompt = task.decode("utf-8")
241
+ except UnicodeError as exc:
242
+ raise LabError("task must be UTF-8") from exc
243
+ if not prompt.strip() or "\x00" in prompt:
244
+ raise LabError("task must be nonempty text without NUL bytes")
245
+ output = output_dir.expanduser().absolute()
246
+ home = home.expanduser().resolve()
247
+ if output.is_symlink() or output.exists() or not output.parent.is_dir():
248
+ raise LabError("output directory must be new with an existing parent")
249
+ output = output.resolve()
250
+ if output == home or output in home.parents or home in output.parents:
251
+ raise LabError("trial output and the selected DSH home must be disjoint")
252
+ context = dict(guard_profile=guard_profile, workspace=output / "fixture", dsh_root=dsh_root)
253
+ preflight, argv, environment = check_host(executable, home, patches, node_executable, guard_state, guard_patch_file, **context)
254
+ if preflight["harness_version"] == "0.2.0-rc.2" and (home / "settings.yaml").exists():
255
+ raise LabError("initialize the copied modern DSH home before freezing a trial")
256
+ if expected_configuration_sha256 is not None and preflight["non_guard_configuration_sha256"] != expected_configuration_sha256:
257
+ raise LabError("paired non-guard settings changed; no host task was launched")
258
+ before = session_inventory(home)
259
+ selected_node = str(Path(shutil.which(node_executable)).absolute())
260
+ output.mkdir(mode=0o700)
261
+ capture = output / "capture"
262
+ capture.mkdir(mode=0o700)
263
+ metadata = {}
264
+ if case_id == "injection-probe":
265
+ metadata = {
266
+ "harness_label": "DSH", "harness_version": preflight["harness_version"],
267
+ "model_label": model_label, "guard_state": guard_state,
268
+ "trial_group": trial_group, "task_file": task_file,
269
+ "non_guard_configuration_sha256": preflight["non_guard_configuration_sha256"],
270
+ }
271
+ prepared = prepare_run(
272
+ output / "fixture", output / "evidence", case_id,
273
+ model_usage="real", attack_sample=attack_sample, **metadata,
274
+ )
275
+ if metadata and prepared["trial"]["task_sha256"] != _digest(task):
276
+ raise LabError("task changed during preparation; no host task was launched")
277
+ evidence = Path(prepared["evidence_dir"])
278
+ fixture = Path(prepared["fixture_dir"])
279
+ # Startup handles its own failure/stop request. Only a ready observer can
280
+ # be stopped here; otherwise cleanup would hide the original startup error.
281
+ arm_observer(evidence, timeout + 15)
282
+ try:
283
+ # Task bytes used for hashing are exactly the bytes passed to the host.
284
+ result, streams = _capture_process([*argv, prompt], fixture, environment, timeout)
285
+ finally:
286
+ request_stop(evidence)
287
+ composition_unchanged = False
288
+ try:
289
+ after = _config_dump(argv, home, environment, guard_state, **context)
290
+ composition_unchanged = (
291
+ _digest(after) == preflight["composition_sha256"]
292
+ and configuration_fingerprint(home, after, environment, guard_state,
293
+ **_profile_options(guard_profile, output / "fixture", dsh_root))
294
+ == preflight["non_guard_configuration_sha256"]
295
+ and _digest(_read_regular(ADAPTER, MAX_SCAN_BYTES)) == preflight["guard_adapter_sha256"]
296
+ and _guard_assets() == preflight["guard_assets"]
297
+ )
298
+ except LabError:
299
+ pass
300
+ captures = {}
301
+ for name, payload in streams.items():
302
+ _write_new(capture / (name + ".bin"), payload)
303
+ captures[name] = {"bytes": len(payload), "sha256": _digest(payload)}
304
+ native, native_captures = capture_session(
305
+ home, before, capture, fixture, _digest(task), selected_node, environment,
306
+ native_format_version=preflight["native_format_version"],
307
+ )
308
+ captures.update(native_captures)
309
+ receipt = {
310
+ "schema_version": RECEIPT_VERSION,
311
+ "run_id": prepared["run_id"], "case_id": case_id,
312
+ **({"attack_sample": prepared["attack_sample"]} if "attack_sample" in prepared else {}),
313
+ "task_sha256": _digest(task), "task_bytes": len(task),
314
+ "model_label": model_label, "trial_group": trial_group,
315
+ "task_text_retained": "session" in captures, "preflight": preflight,
316
+ "composition_unchanged": composition_unchanged,
317
+ "host": result, "captures": captures,
318
+ "native_session": native,
319
+ "completion": "USER_REVIEW_REQUIRED",
320
+ "raw_host_output_retained": True,
321
+ }
322
+ _write_json(capture / "receipt.json", receipt)
323
+ report = build_report(evidence)
324
+ return {
325
+ "output_dir": str(output), "run_id": prepared["run_id"],
326
+ "case_id": case_id, "completion": receipt["completion"],
327
+ "host": result, "composition_unchanged": composition_unchanged,
328
+ "native_session": native,
329
+ "report_result": report["result"],
330
+ "raw_host_output_retained": True,
331
+ }
332
+
333
+
334
+ def _read_capture(output_dir: Path) -> tuple[dict, dict, dict, Optional[dict], bool]:
335
+ output = output_dir.expanduser().absolute()
336
+ if (
337
+ output.is_symlink() or (output / "capture").is_symlink()
338
+ or (output / "evidence").is_symlink()
339
+ ):
340
+ raise LabError("trial directories must not be symlinks")
341
+ capture = output / "capture"
342
+ receipt = json.loads(_read_regular(capture / "receipt.json", MAX_RECEIPT_BYTES))
343
+ run = json.loads(_read_regular(output / "evidence" / "run.json", MAX_RECEIPT_BYTES))
344
+ if not isinstance(receipt, dict) or not isinstance(run, dict):
345
+ raise LabError("capture metadata must be JSON objects")
346
+ if type(receipt.get("schema_version")) is not int or receipt["schema_version"] not in {1, 2, 3, 4, 5, 6}:
347
+ raise LabError("unsupported capture receipt version")
348
+ host_version = receipt.get("preflight", {}).get("harness_version")
349
+ native_format = 4 if receipt["schema_version"] == 5 else 3
350
+ if receipt["schema_version"] == 6:
351
+ preflight = receipt.get("preflight", {})
352
+ native_format = preflight.get("native_format_version")
353
+ if (type(native_format) is not int or native_format not in {3, 4}
354
+ or type(preflight.get("native_parser_version")) is not int
355
+ or preflight["native_parser_version"] != 3
356
+ or preflight.get("configuration_scope") != "dsh-lab-non-guard-v2"
357
+ or preflight.get("guard_profile") not in GUARD_PROFILES):
358
+ raise LabError("capture parser/profile/format contract does not match")
359
+ if receipt["schema_version"] >= 3:
360
+ expected_host = "0.2.0-rc.2" if native_format == 4 else "0.1.5-rc.1"
361
+ if host_version != expected_host or (native_format == 4 and
362
+ receipt["preflight"].get("native_format_version") != 4):
363
+ raise LabError("capture host and native format contract do not match")
364
+ if receipt.get("run_id") != run.get("run_id") or receipt.get("case_id") != run.get("case_id"):
365
+ raise LabError("capture and Lab run identities do not match")
366
+ if (
367
+ Path(run["evidence_dir"]).resolve() != (output / "evidence").resolve()
368
+ or Path(run["fixture_dir"]).resolve() != (output / "fixture").resolve()
369
+ or run.get("case_id") not in {"clean", "injection-probe"}
370
+ ):
371
+ raise LabError("capture paths or case do not match this trial")
372
+ payloads = {}
373
+ names = {"stdout": "stdout.bin", "stderr": "stderr.bin"}
374
+ if receipt["schema_version"] >= 2:
375
+ for name, filename in (("session", "session.bin"), ("session_jsonl", "session.jsonl")):
376
+ if name in receipt["captures"]:
377
+ names[name] = filename
378
+ for name, filename in names.items():
379
+ payload = _read_regular(capture / filename, MAX_SCAN_BYTES)
380
+ expected = receipt["captures"][name]
381
+ if expected != {"bytes": len(payload), "sha256": _digest(payload)}:
382
+ raise LabError("host capture integrity check failed")
383
+ payloads[name] = payload
384
+ roles = None
385
+ native_ready = False
386
+ if isinstance(run.get("trial"), dict) and receipt["task_sha256"] != run["trial"]["task_sha256"]:
387
+ raise LabError("capture task fingerprint differs from the Lab trial")
388
+ if receipt["schema_version"] >= 3 and isinstance(run.get("trial"), dict):
389
+ trial = run["trial"]
390
+ if any(trial.get(key) != value for key, value in {
391
+ "harness_label": "DSH", "harness_version": host_version,
392
+ "guard_state": receipt["preflight"]["guard_state"],
393
+ "non_guard_configuration_sha256": receipt["preflight"]["non_guard_configuration_sha256"],
394
+ "model_label": receipt["model_label"], "trial_group": receipt["trial_group"],
395
+ }.items()):
396
+ raise LabError("capture configuration or identity differs from the Lab trial")
397
+ if receipt["schema_version"] >= 2:
398
+ native = receipt["native_session"]
399
+ if not isinstance(native, dict):
400
+ raise LabError("native capture metadata must be an object")
401
+ if "session_jsonl" in payloads:
402
+ if "session" not in payloads or native.get("status") != "CAPTURED" or native.get("compression") not in {"none", "zstd"}:
403
+ raise LabError("native capture is missing its original artifact or format")
404
+ summary, roles = split_session(payloads["session_jsonl"], Path(run["fixture_dir"]), receipt["task_sha256"],
405
+ parser_version=3 if receipt["schema_version"] == 6 else (2 if receipt["schema_version"] >= 4 else 1),
406
+ native_format_version=native_format)
407
+ if native.get("parser") != summary or native.get("recognized") is not summary["recognized"]:
408
+ raise LabError("native session interpretation differs from the receipt")
409
+ native_ready = native.get("status") == "CAPTURED" and summary["recognized"] and summary["completed"]
410
+ return receipt, run, payloads, roles, native_ready
411
+
412
+
413
+ def finalize_trial(output_dir: Path, status: str) -> dict:
414
+ output = output_dir.expanduser().absolute()
415
+ receipt, run, payloads, roles, native_ready = _read_capture(output)
416
+ if status == "completed" and receipt["schema_version"] >= 2 and not native_ready:
417
+ raise LabError("missing, ambiguous, unsupported or unfinished native session cannot be completed")
418
+ host = receipt["host"]
419
+ if status == "completed" and (
420
+ host["exit_code"] != 0 or host["timed_out"] or host["start_failed"]
421
+ or host["output_limit_exceeded"] or not receipt["composition_unchanged"]
422
+ or not payloads["stdout"].strip()
423
+ ):
424
+ raise LabError("failed, empty, changed or incomplete capture cannot be declared completed")
425
+ if host["timed_out"] and status != "timed-out":
426
+ raise LabError("a timed-out capture must be recorded as timed-out")
427
+ exit_code = host["exit_code"]
428
+ if not isinstance(exit_code, int) or not 0 <= exit_code <= 255:
429
+ exit_code = None
430
+ evidence = output / "evidence"
431
+ record_host_result(evidence, status, exit_code)
432
+ for name in ("stdout", "stderr"):
433
+ scan_bytes(evidence, payloads[name], "host-output", source_kind="dsh-headless-" + name)
434
+ if roles is not None and receipt["native_session"].get("recognized"):
435
+ scan_bytes(evidence, roles["tool"], "tool-output", source_kind="dsh-native-tool-result")
436
+ scan_bytes(evidence, roles["assistant"], "model-output", source_kind="dsh-native-assistant-content")
437
+ if receipt["schema_version"] >= 4:
438
+ scan_bytes(evidence, roles["attempt"], "host-output", source_kind="dsh-native-assistant-attempt-stream")
439
+ elif "session_jsonl" in payloads:
440
+ scan_bytes(evidence, payloads["session_jsonl"], "host-output", source_kind="dsh-native-unrecognized-session")
441
+ return build_report(evidence)
442
+
443
+
444
+ LEGACY_NATIVE_CHANNELS = sorted([
445
+ {"stage": "host-output", "source_kind": "dsh-headless-stdout"},
446
+ {"stage": "host-output", "source_kind": "dsh-headless-stderr"},
447
+ {"stage": "tool-output", "source_kind": "dsh-native-tool-result"},
448
+ {"stage": "model-output", "source_kind": "dsh-native-assistant-content"},
449
+ ], key=lambda item: (item["stage"], item["source_kind"]))
450
+ NATIVE_CHANNELS = sorted([
451
+ *LEGACY_NATIVE_CHANNELS,
452
+ {"stage": "host-output", "source_kind": "dsh-native-assistant-attempt-stream"},
453
+ ], key=lambda item: (item["stage"], item["source_kind"]))
454
+
455
+
456
+ def compare_trials(baseline_dir: Path, guarded_dir: Path) -> dict:
457
+ result = compare_runs(baseline_dir / "evidence", guarded_dir / "evidence")
458
+ valid = True
459
+ contracts = []
460
+ for label, directory, state in (("baseline", baseline_dir, "OFF"), ("guarded", guarded_dir, "ON")):
461
+ try:
462
+ receipt, run, _, _, ready = _read_capture(directory)
463
+ report = result[label]
464
+ if (
465
+ receipt["schema_version"] not in {3, 4, 5, 6} or not ready
466
+ or receipt["preflight"]["guard_state"] != state
467
+ or not receipt["composition_unchanged"]
468
+ or run["case_id"] != "injection-probe"
469
+ or report["scanned_channels"] != (NATIVE_CHANNELS if receipt["schema_version"] >= 4 else LEGACY_NATIVE_CHANNELS)
470
+ or receipt["host"]["exit_code"] != 0
471
+ or any(receipt["host"][key] for key in ("timed_out", "start_failed", "output_limit_exceeded"))
472
+ ):
473
+ raise LabError("trial is outside the paired native-capture scope")
474
+ contracts.append((receipt["schema_version"],
475
+ receipt["preflight"].get("guard_profile", "deletion-v1"),
476
+ receipt["preflight"].get("configuration_scope", "dsh-lab-non-guard-v1")))
477
+ except (LabError, OSError, ValueError, KeyError, TypeError):
478
+ valid = False
479
+ result["precondition_issues"].append(label.upper() + "_DSH_CAPTURE_INVALID")
480
+ result["matching_dimensions"]["dsh_native_capture_verified"] = valid
481
+ matching_contract = len(contracts) == 2 and contracts[0] == contracts[1]
482
+ result["matching_dimensions"]["dsh_capture_contract"] = matching_contract
483
+ if not matching_contract:
484
+ result["precondition_issues"].append("DSH_CAPTURE_CONTRACT_MISMATCH")
485
+ if not valid or not matching_contract:
486
+ result.update({"comparison_outcome": "INCOMPARABLE", "result": "INCONCLUSIVE",
487
+ "evidence_level": "UNESTABLISHED", "reason": "COMPARISON_PRECONDITIONS_FAILED"})
488
+ result["precondition_issues"] = sorted(set(result["precondition_issues"]))
489
+ return result
490
+
491
+
492
+ def prepare_pair(
493
+ output_dir: Path, source_home: Path, executable: str, model_label: str,
494
+ trial_group: str, task_file: Path, clean_task_file: Path,
495
+ patches: Sequence[Path] = (), timeout: int = 120,
496
+ attack_sample: str = "direct-v1", node_executable: str = "node",
497
+ *, guard_profile="deletion-v1", dsh_root=None,
498
+ ) -> dict:
499
+ if not TRIAL_LABEL_PATTERN.fullmatch(model_label) or not TRIAL_GROUP_PATTERN.fullmatch(trial_group):
500
+ raise LabError("use a public model label and trial-group slug")
501
+ if attack_sample not in INJECTION_SAMPLES or not 1 <= timeout <= 600:
502
+ raise LabError("select a known attack sample and bounded timeout")
503
+ if ((attack_sample == "read-redaction-v1") != (guard_profile == "read-redaction-v1")):
504
+ raise LabError("read redaction profile and attack sample must be selected together")
505
+ # Validate profile paths before copying any private bootstrap.
506
+ guard_patch(guard_profile, output_dir.expanduser().absolute() / "trials/guarded/fixture", dsh_root)
507
+ tasks = {}
508
+ for label, path in (("attack", task_file), ("clean", clean_task_file)):
509
+ payload = _read_regular(path.expanduser().absolute(), MAX_TASK_BYTES)
510
+ text = payload.decode("utf-8")
511
+ if not text.strip() or "\x00" in text:
512
+ raise LabError("tasks must be nonempty UTF-8 without NUL bytes")
513
+ tasks[label] = {"path": str(path.expanduser().absolute()), "sha256": _digest(payload)}
514
+ layers = [{"path": str(path.expanduser().absolute()),
515
+ "sha256": _digest(_read_regular(path.expanduser().absolute(), MAX_RECEIPT_BYTES))} for path in patches]
516
+ output = output_dir.expanduser().absolute()
517
+ if output.exists() or output.is_symlink() or not output.parent.is_dir():
518
+ raise LabError("pair directory must be new with an existing parent")
519
+ if source_home.expanduser().is_symlink():
520
+ raise LabError("source DSH home must not be a symlink")
521
+ source = source_home.expanduser().resolve()
522
+ output = output.resolve()
523
+ if output == source or output in source.parents or source in output.parents:
524
+ raise LabError("pair directory and source home must be disjoint")
525
+ # Check external inputs before creating any private profiles.
526
+ executable = shutil.which(executable)
527
+ node_executable = shutil.which(node_executable)
528
+ if not executable or not node_executable:
529
+ raise LabError("DSH and decoder executables must be available")
530
+ output.mkdir(mode=0o700)
531
+ profiles = prepare_homes(source, output / "homes")
532
+ (output / "trials").mkdir(mode=0o700)
533
+ patch = output / "guard.patch.yml"
534
+ guard_patches = {}
535
+ if guard_profile == "deletion-v1":
536
+ _write_new(patch, guard_patch())
537
+ else:
538
+ for member in ("clean-on", "guarded"):
539
+ selected = output / (member + "-guard.patch.yml")
540
+ _write_new(selected, guard_patch(guard_profile, output / "trials" / member / "fixture", dsh_root))
541
+ guard_patches[member] = {"path": str(selected), "sha256": _digest(_read_regular(selected, MAX_RECEIPT_BYTES))}
542
+ preflights = {}
543
+ initializations = {}
544
+ for member in MEMBERS:
545
+ state = "on" if member in {"clean-on", "guarded"} else "off"
546
+ initializations[member] = _initialize_home(executable, output / "homes" / member, patches, node_executable)
547
+ preflight, _, _ = check_host(executable, output / "homes" / member,
548
+ patches, node_executable, state,
549
+ Path(guard_patches[member]["path"]) if member in guard_patches else (patch if state == "on" else None),
550
+ guard_profile=guard_profile, workspace=output / "trials" / member / "fixture", dsh_root=dsh_root)
551
+ if session_inventory(output / "homes" / member):
552
+ raise LabError("paired homes must have no prior sessions")
553
+ preflights[member] = preflight
554
+ fingerprints = {value["non_guard_configuration_sha256"] for value in preflights.values()}
555
+ if len(fingerprints) != 1:
556
+ raise LabError("paired homes have different non-guard settings")
557
+ for name, expected in profiles["bootstrap_sha256"].items():
558
+ if _digest(_read_regular(source / name, MAX_SCAN_BYTES)) != expected:
559
+ raise LabError("source bootstrap changed while deriving the pair")
560
+ manifest = {
561
+ "schema_version": 2, "native_parser_version": PARSER_VERSION,
562
+ "harness_version": preflights["baseline"]["harness_version"],
563
+ "native_format_version": preflights["baseline"]["native_format_version"],
564
+ "pair_dir": str(output), "members": list(MEMBERS),
565
+ "executable": str(Path(executable).absolute()), "node_executable": str(Path(node_executable).absolute()),
566
+ "model_label": model_label, "trial_group": trial_group, "attack_sample": attack_sample,
567
+ "timeout": timeout, "tasks": tasks, "patches": layers,
568
+ "guard_profile": guard_profile, "read_guard_dsh_root": str(Path(dsh_root).resolve()) if dsh_root else None,
569
+ "configuration_scope": "dsh-lab-non-guard-v2", "initializations": initializations,
570
+ "guard_patches": guard_patches, "guard_assets": preflights["guarded"]["guard_assets"],
571
+ "non_guard_configuration_sha256": fingerprints.pop(),
572
+ "guard_patch_sha256": _digest(guard_patch()), "guard_adapter_sha256": preflights["guarded"]["guard_adapter_sha256"],
573
+ "baseline_patch_sha256": _digest(_read_regular(BASELINE_PATCH, MAX_RECEIPT_BYTES)),
574
+ "bootstrap_assets": {path.name: _digest(_read_regular(path, MAX_SCAN_BYTES))
575
+ for path in (BOOTSTRAP_INIT, BOOTSTRAP_PATCH)},
576
+ "bootstrap": profiles, "completion_source": "user-declared",
577
+ }
578
+ _write_json(output / "pair.json", manifest)
579
+ return {"pair_dir": str(output), "state": "READY", "host_tasks_launched": 0,
580
+ "non_guard_configuration_sha256": manifest["non_guard_configuration_sha256"],
581
+ "members": list(MEMBERS), "source_modified": False}
582
+
583
+
584
+ def pair_next(pair_dir: Path) -> dict:
585
+ output = pair_dir.expanduser().absolute()
586
+ if any(path.is_symlink() for path in (output, output / "homes", output / "trials")):
587
+ raise LabError("pair directories must not be symlinks")
588
+ manifest = json.loads(_read_regular(output / "pair.json", MAX_RECEIPT_BYTES))
589
+ if type(manifest.get("schema_version")) is not int or manifest["schema_version"] not in {1, 2} or manifest.get("pair_dir") != str(output.resolve()) or manifest.get("members") != list(MEMBERS):
590
+ raise LabError("unsupported pair metadata or directory identity")
591
+ parser_version = manifest.get("native_parser_version", 1)
592
+ if type(parser_version) is not int or parser_version not in {1, 2, 3}:
593
+ raise LabError("unsupported paired native parser version")
594
+ native_format = manifest.get("native_format_version", 3)
595
+ host_version = manifest.get("harness_version", "0.1.5-rc.1")
596
+ if (host_version not in HOST_CONTRACTS or type(native_format) is not int
597
+ or HOST_CONTRACTS[host_version][0] != native_format
598
+ or native_format == 4 and parser_version < 2
599
+ or (manifest["schema_version"] == 2) != (parser_version == 3)):
600
+ raise LabError("unsupported paired host/native format contract")
601
+ receipt_version = 6 if parser_version == 3 else (5 if native_format == 4 else (4 if parser_version == 2 else 3))
602
+ expected_channels = NATIVE_CHANNELS if parser_version >= 2 else LEGACY_NATIVE_CHANNELS
603
+ guard_profile = manifest.get("guard_profile", "deletion-v1")
604
+ dsh_root = manifest.get("read_guard_dsh_root")
605
+ assets = [("baseline_patch_sha256", BASELINE_PATCH), ("guard_adapter_sha256", ADAPTER)]
606
+ if guard_profile == "deletion-v1":
607
+ assets.append(("guard_patch_sha256", output / "guard.patch.yml"))
608
+ elif guard_profile == "read-redaction-v1" and manifest["schema_version"] == 2:
609
+ if set(manifest.get("guard_patches", {})) != {"clean-on", "guarded"}:
610
+ raise LabError("read pair requires both bound guard patches")
611
+ for member, item in manifest["guard_patches"].items():
612
+ expected_patch = guard_patch(guard_profile, output / "trials" / member / "fixture", dsh_root)
613
+ if (_read_regular(Path(item["path"]), MAX_RECEIPT_BYTES) != expected_patch
614
+ or _digest(expected_patch) != item["sha256"]):
615
+ raise LabError("paired read guard patch changed")
616
+ else:
617
+ raise LabError("unsupported paired guard profile")
618
+ if manifest["schema_version"] == 2 and (_guard_assets() != manifest.get("guard_assets")
619
+ or manifest.get("configuration_scope") != "dsh-lab-non-guard-v2"
620
+ or any(_digest(_read_regular(path, MAX_SCAN_BYTES)) != manifest["bootstrap_assets"].get(path.name)
621
+ for path in (BOOTSTRAP_INIT, BOOTSTRAP_PATCH))):
622
+ raise LabError("paired implementation assets changed; prepare a fresh pair")
623
+ for key, path in assets:
624
+ if _digest(_read_regular(path, MAX_SCAN_BYTES)) != manifest[key]:
625
+ raise LabError("paired launch assets changed; no host task was launched")
626
+ for item in [*manifest["tasks"].values(), *manifest["patches"]]:
627
+ if _digest(_read_regular(Path(item["path"]), MAX_TASK_BYTES)) != item["sha256"]:
628
+ raise LabError("paired tasks or overlays changed; no host task was launched")
629
+ for member in MEMBERS:
630
+ directory = output / "trials" / member
631
+ state = "on" if member in {"clean-on", "guarded"} else "off"
632
+ task = manifest["tasks"]["clean" if member.startswith("clean-") else "attack"]
633
+ if directory.exists() or directory.is_symlink():
634
+ receipt, _, _, _, ready = _read_capture(directory)
635
+ if (
636
+ receipt["schema_version"] != receipt_version or receipt["task_sha256"] != task["sha256"]
637
+ or receipt["case_id"] != ("clean" if member.startswith("clean-") else "injection-probe")
638
+ or (not member.startswith("clean-") and receipt.get("attack_sample", {}).get("id") != manifest["attack_sample"])
639
+ or receipt["model_label"] != manifest["model_label"] or receipt["trial_group"] != manifest["trial_group"]
640
+ or receipt["preflight"]["guard_state"] != state.upper()
641
+ or receipt["preflight"]["guard_adapter_sha256"] != manifest["guard_adapter_sha256"]
642
+ or receipt["preflight"]["non_guard_configuration_sha256"] != manifest["non_guard_configuration_sha256"]
643
+ or (manifest["schema_version"] == 2 and (receipt["preflight"].get("guard_profile") != guard_profile
644
+ or receipt["preflight"].get("guard_assets") != manifest["guard_assets"]))
645
+ ):
646
+ raise LabError("captured member does not belong to this pair")
647
+ report = build_report(directory / "evidence")
648
+ if report["host_execution"]["status"] == "NOT_RECORDED":
649
+ return {"pair_dir": str(output), "state": "USER_REVIEW_REQUIRED", "member": member,
650
+ "output_dir": str(directory), "host_tasks_launched": 0, "result": "INCONCLUSIVE"}
651
+ if (
652
+ not ready or report["host_execution"]["status"] != "COMPLETED"
653
+ or not receipt["composition_unchanged"] or receipt["host"]["exit_code"] != 0
654
+ or any(receipt["host"][key] for key in ("timed_out", "start_failed", "output_limit_exceeded"))
655
+ or report["observer"]["health"] != "HEALTHY"
656
+ or report["scanned_channels"] != expected_channels
657
+ or (member.startswith("clean-") and report["criterion"]["status"] != "PASS")
658
+ or report["security_outcome"] == "INCONCLUSIVE"
659
+ ):
660
+ return {"pair_dir": str(output), "state": "STOPPED", "member": member,
661
+ "reason": "CONTROL_OR_TRIAL_NOT_HEALTHY", "host_tasks_launched": 0, "result": "INCONCLUSIVE"}
662
+ if member == "baseline" and report["security_outcome"] != "EXPOSURE_OBSERVED":
663
+ return {"pair_dir": str(output), "state": "STOPPED", "member": member,
664
+ "reason": "BASELINE_ATTACK_NOT_EFFECTIVE", "host_tasks_launched": 0, "result": "INCONCLUSIVE"}
665
+ continue
666
+ if manifest["schema_version"] != 2:
667
+ raise LabError("prepare a fresh pair for retry-aware coverage; legacy plans do not launch new captures")
668
+ if session_inventory(output / "homes" / member):
669
+ raise LabError("selected paired home has prior sessions; no host task was launched")
670
+ captured = run_trial(directory, output / "homes" / member, manifest["executable"],
671
+ "clean" if member.startswith("clean-") else "injection-probe", Path(task["path"]),
672
+ manifest["model_label"], manifest["trial_group"], [Path(item["path"]) for item in manifest["patches"]],
673
+ manifest["timeout"], "direct-v1" if member.startswith("clean-") else manifest["attack_sample"],
674
+ manifest["node_executable"], state,
675
+ (Path(manifest["guard_patches"][member]["path"]) if guard_profile == "read-redaction-v1"
676
+ else output / "guard.patch.yml") if state == "on" else None,
677
+ manifest["non_guard_configuration_sha256"], guard_profile=guard_profile, dsh_root=dsh_root)
678
+ return {**captured, "pair_dir": str(output), "member": member,
679
+ "state": "USER_REVIEW_REQUIRED", "host_tasks_launched": 1}
680
+ comparison = compare_trials(output / "trials/baseline", output / "trials/guarded")
681
+ return {"pair_dir": str(output), "state": "FINISHED", "host_tasks_launched": 0, **comparison}
682
+
683
+
684
+ def main(arguments: Optional[Sequence[str]] = None) -> int:
685
+ parser = argparse.ArgumentParser(description=__doc__)
686
+ commands = parser.add_subparsers(dest="command", required=True)
687
+ check = commands.add_parser("check", help="check the selected version and composition; no model")
688
+ run = commands.add_parser("run", help="capture one real-model trial; completion remains pending")
689
+ for command in (check, run):
690
+ command.add_argument("--dsh-executable", default="dsh")
691
+ command.add_argument("--dsh-home", type=Path, required=True)
692
+ command.add_argument("--node-executable", default="node")
693
+ command.add_argument("--patch", type=Path, action="append", default=[])
694
+ command.add_argument("--guard-state", choices=("off", "on"), default="off")
695
+ command.add_argument("--guard-patch", type=Path)
696
+ command.add_argument("--guard-profile", choices=GUARD_PROFILES, default="deletion-v1")
697
+ command.add_argument("--read-guard-dsh-root", type=Path)
698
+ check.add_argument("--fixture-dir", type=Path, help="bound fixture path for the read profile")
699
+ run.add_argument("--output-dir", type=Path, required=True)
700
+ run.add_argument("--case", choices=("clean", "injection-probe"), required=True)
701
+ run.add_argument("--attack-sample", choices=sorted(INJECTION_SAMPLES), default="direct-v1")
702
+ run.add_argument("--task-file", type=Path, default=ROOT / "docs" / "guard-lab-trial-task.md")
703
+ run.add_argument("--model-label", required=True)
704
+ run.add_argument("--trial-group", required=True)
705
+ run.add_argument("--timeout", type=int, default=120)
706
+ finalize = commands.add_parser("finalize", help="record a reviewed host result and scan CLI/native output channels")
707
+ finalize.add_argument("--output-dir", type=Path, required=True)
708
+ finalize.add_argument("--status", choices=("completed", "failed", "timed-out"), required=True)
709
+ compare = commands.add_parser("compare", help="verify native captures and compare reviewed trials")
710
+ compare.add_argument("--baseline-dir", type=Path, required=True)
711
+ compare.add_argument("--guarded-dir", type=Path, required=True)
712
+ pair = commands.add_parser("prepare-pair", help="derive four fresh matched homes and a private plan; no model")
713
+ pair.add_argument("--source-home", type=Path, required=True)
714
+ pair.add_argument("--output-dir", type=Path, required=True)
715
+ pair.add_argument("--dsh-executable", default="dsh")
716
+ pair.add_argument("--node-executable", default="node")
717
+ pair.add_argument("--patch", type=Path, action="append", default=[])
718
+ pair.add_argument("--model-label", required=True)
719
+ pair.add_argument("--trial-group", required=True)
720
+ pair.add_argument("--task-file", type=Path, default=ROOT / "docs/guard-lab-trial-task.md")
721
+ pair.add_argument("--clean-task-file", type=Path, default=ROOT / "docs/guard-lab-clean-task.md")
722
+ pair.add_argument("--attack-sample", choices=sorted(INJECTION_SAMPLES), default="direct-v1")
723
+ pair.add_argument("--timeout", type=int, default=120)
724
+ pair.add_argument("--guard-profile", choices=GUARD_PROFILES, default="deletion-v1")
725
+ pair.add_argument("--read-guard-dsh-root", type=Path)
726
+ next_step = commands.add_parser("pair-next", help="capture at most one next trial after review gates")
727
+ next_step.add_argument("--pair-dir", type=Path, required=True)
728
+ options = parser.parse_args(arguments)
729
+ try:
730
+ if options.command == "check":
731
+ value, _, _ = check_host(options.dsh_executable, options.dsh_home, options.patch, options.node_executable, options.guard_state, options.guard_patch,
732
+ guard_profile=options.guard_profile, workspace=options.fixture_dir, dsh_root=options.read_guard_dsh_root)
733
+ exit_code = 0
734
+ elif options.command == "run":
735
+ value = run_trial(
736
+ options.output_dir, options.dsh_home, options.dsh_executable,
737
+ options.case, options.task_file, options.model_label,
738
+ options.trial_group, options.patch, options.timeout,
739
+ options.attack_sample,
740
+ options.node_executable,
741
+ options.guard_state, options.guard_patch,
742
+ guard_profile=options.guard_profile, dsh_root=options.read_guard_dsh_root,
743
+ )
744
+ exit_code = 0
745
+ elif options.command == "finalize":
746
+ value = finalize_trial(options.output_dir, options.status)
747
+ exit_code = {"COMPLETE": 0, "FAIL": 2}.get(value["result"], 4)
748
+ elif options.command == "prepare-pair":
749
+ value = prepare_pair(options.output_dir, options.source_home, options.dsh_executable,
750
+ options.model_label, options.trial_group, options.task_file, options.clean_task_file,
751
+ options.patch, options.timeout, options.attack_sample, options.node_executable,
752
+ guard_profile=options.guard_profile, dsh_root=options.read_guard_dsh_root)
753
+ exit_code = 0
754
+ elif options.command == "pair-next":
755
+ value = pair_next(options.pair_dir)
756
+ exit_code = {"COMPLETE": 0, "FAIL": 2, "INCONCLUSIVE": 4}.get(value.get("result"), 0)
757
+ else:
758
+ value = compare_trials(options.baseline_dir, options.guarded_dir)
759
+ exit_code = {"COMPLETE": 0, "FAIL": 2}.get(value["result"], 4)
760
+ print(json.dumps(value, sort_keys=True))
761
+ return exit_code
762
+ except LabError as exc:
763
+ print("DSH Lab: " + str(exc), file=sys.stderr)
764
+ return 1
765
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
766
+ print("DSH Lab operation refused or failed; raw host diagnostics are not printed", file=sys.stderr)
767
+ return 1
768
+
769
+
770
+ if __name__ == "__main__":
771
+ raise SystemExit(main())