sessionyard 0.7.0__py3-none-any.whl

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 (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,487 @@
1
+ """One-shot, origin-bound viewer inspection. No credential discovery or profile reuse.
2
+
3
+ Binding v1 (provisioning-owned, not created here):
4
+ {"version": 1, "origin": "https://chat.example", "room_ids": ["<uuid>"],
5
+ "viewer_token": "<64 lowercase hex>",
6
+ "artifact_policy": {"root": "<absolute private provisioned root>", "retention_seconds": 86400}}
7
+
8
+ artifact_policy is optional. It is a provisioning-owned expiry contract, not proof
9
+ that expiry has run. No CLI option can supply or override that policy.
10
+ The Python-only test trust injection is not a command-line or environment option.
11
+ The managed environment must already contain this package and matching Chromium.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import ctypes
17
+ import json
18
+ import os
19
+ import re
20
+ import signal
21
+ import stat
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import time
26
+ from dataclasses import dataclass, field
27
+ from datetime import datetime, timezone
28
+ from pathlib import Path
29
+ from typing import Any, NoReturn
30
+ from urllib.parse import urlsplit
31
+ from uuid import UUID
32
+
33
+ VIEWPORTS = ((1280, 720), (390, 844))
34
+ RUN_SECONDS = 120
35
+ CLEANUP_SECONDS = 10
36
+ MAX_REQUESTS = 200
37
+ MAX_PAGES = 5
38
+
39
+
40
+ class Stop(Exception):
41
+ def __init__(self, code: str, result: str = "FAIL", http_status: int | None = None) -> None:
42
+ self.code, self.result, self.http_status = code, result, http_status
43
+ super().__init__(code)
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class ArtifactPolicy:
48
+ root: Path
49
+ retention_seconds: int
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Binding:
54
+ origin: str
55
+ room_ids: tuple[str, ...]
56
+ viewer_token: str = field(repr=False)
57
+ artifact_policy: ArtifactPolicy | None = None
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Request:
62
+ binding: Path
63
+ scenario: str
64
+ room: str
65
+ session: str | None
66
+ message: str | None
67
+ receipt_session: str | None
68
+ expected_title: str | None = field(repr=False)
69
+ min_participants: int | None = None
70
+ receipt_states: tuple[str, ...] = ()
71
+ screenshot: bool = False
72
+ expected_title_file: Path | None = None
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class FixtureTrust:
77
+ """Disposable HTTPS fixture's certificate and exact public-key pin; never CLI inputs."""
78
+
79
+ origin: str
80
+ certificate: Path
81
+ spki: str
82
+
83
+
84
+ class Parser(argparse.ArgumentParser):
85
+ def error(self, message: str) -> NoReturn:
86
+ # argparse's default diagnostics echo untrusted argv, including mistaken secrets.
87
+ raise Stop("INVALID_INPUT")
88
+
89
+
90
+ def uuid_text(value: str) -> str:
91
+ if not isinstance(value, str) or str(UUID(value)) != value:
92
+ raise ValueError("noncanonical UUID")
93
+ return value
94
+
95
+
96
+ def parse(argv: list[str] | None) -> Request:
97
+ parser = Parser(add_help=False, allow_abbrev=False)
98
+ parser.add_argument("--binding", type=Path, required=True)
99
+ parser.add_argument("--scenario", required=True,
100
+ choices=("snapshot", "session-title", "layout", "history-receipt"))
101
+ parser.add_argument("--room", type=uuid_text, required=True)
102
+ parser.add_argument("--session", type=uuid_text)
103
+ parser.add_argument("--message", type=uuid_text)
104
+ parser.add_argument("--receipt-session", type=uuid_text)
105
+ parser.add_argument("--expected-title-file", type=Path)
106
+ parser.add_argument("--min-participants", type=int)
107
+ parser.add_argument("--receipt-state", action="append", default=[],
108
+ choices=("stored", "handed", "acknowledged", "replied", "uncertain"))
109
+ parser.add_argument("--screenshot", action="store_true")
110
+ args = parser.parse_args(argv)
111
+ title_case = args.scenario in ("session-title", "layout")
112
+ receipt_case = args.scenario == "history-receipt"
113
+ if (
114
+ title_case != (args.session is not None)
115
+ or (args.expected_title_file is not None and not title_case)
116
+ or receipt_case != (args.message is not None)
117
+ or receipt_case != (args.receipt_session is not None)
118
+ or receipt_case != bool(args.receipt_state)
119
+ or len(set(args.receipt_state)) != len(args.receipt_state)
120
+ or (args.scenario == "layout") != (args.min_participants is not None)
121
+ or (args.min_participants is not None and not 1 <= args.min_participants <= 250)
122
+ ):
123
+ raise Stop("INVALID_INPUT")
124
+ if args.scenario == "snapshot" and args.screenshot:
125
+ # `#read-only-indicator` is a childless element: an allow-list entry
126
+ # leaves nothing to mask and PREPARE refuses, while the deny-by-default
127
+ # fallback masks that very element and retains a black rectangle.
128
+ raise Stop("SCREENSHOT_SCENARIO_UNAVAILABLE", "UNAVAILABLE")
129
+ expected = None
130
+ if args.expected_title_file is not None:
131
+ try:
132
+ expected = read_private(args.expected_title_file, 512, "EXPECTED_TITLE", allow_empty=True).decode("utf-8")
133
+ except UnicodeError:
134
+ raise Stop("EXPECTED_TITLE_INVALID") from None
135
+ return Request(args.binding, args.scenario, args.room, args.session, args.message,
136
+ args.receipt_session, expected, args.min_participants,
137
+ tuple(args.receipt_state), args.screenshot, args.expected_title_file)
138
+
139
+
140
+ def private_directory(path: Path, unsafe_code: str) -> int:
141
+ # Descriptor walking closes the resolve()+open() symlink race. Only root or
142
+ # this identity may own ancestors; the final directory must be private.
143
+ if not path.is_absolute() or ".." in path.parts or len(path.parts) < 2:
144
+ raise Stop(unsafe_code)
145
+ directory = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
146
+ try:
147
+ for index, part in enumerate(path.parts[1:], 1):
148
+ next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
149
+ os.close(directory)
150
+ directory = next_fd
151
+ info = os.fstat(directory)
152
+ mode = stat.S_IMODE(info.st_mode)
153
+ if info.st_uid not in (0, os.geteuid()) or (mode & 0o022 and not info.st_mode & stat.S_ISVTX):
154
+ raise Stop(unsafe_code)
155
+ if index == len(path.parts) - 1 and (info.st_uid != os.geteuid() or mode != 0o700):
156
+ raise Stop(unsafe_code)
157
+ return directory
158
+ except (OSError, Stop):
159
+ os.close(directory)
160
+ raise
161
+
162
+
163
+ def read_private(path: Path, maximum: int, code: str, *, allow_empty: bool = False) -> bytes:
164
+ if not path.is_absolute() or ".." in path.parts or len(path.parts) < 3:
165
+ raise Stop(code + "_UNSAFE")
166
+ try:
167
+ directory = private_directory(path.parent, code + "_UNSAFE")
168
+ except OSError:
169
+ raise Stop(code + "_UNAVAILABLE", "UNAVAILABLE") from None
170
+ try:
171
+ fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
172
+ with os.fdopen(fd, "rb") as stream:
173
+ info = os.fstat(stream.fileno())
174
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid()
175
+ or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1
176
+ or not (0 if allow_empty else 1) <= info.st_size <= maximum):
177
+ raise Stop(code + "_UNSAFE")
178
+ content = stream.read(maximum + 1)
179
+ if len(content) > maximum:
180
+ raise Stop(code + "_UNSAFE")
181
+ return content
182
+ except OSError:
183
+ raise Stop(code + "_UNAVAILABLE", "UNAVAILABLE") from None
184
+ finally:
185
+ os.close(directory)
186
+
187
+
188
+ def read_binding(path: Path) -> Binding:
189
+ content = read_private(path, 8192, "BINDING")
190
+ try:
191
+ data = json.loads(content, object_pairs_hook=_unique_keys)
192
+ required = {"version", "origin", "room_ids", "viewer_token"}
193
+ if (len(content) > 8192 or not required <= set(data) or set(data) - required - {"artifact_policy"}
194
+ or type(data["version"]) is not int or data["version"] != 1):
195
+ raise ValueError("schema")
196
+ origin = data["origin"]
197
+ parts = urlsplit(origin)
198
+ if (not isinstance(origin, str) or len(origin) > 256 or not origin.isascii()
199
+ or re.fullmatch(r"https://[a-z0-9.\[\]:-]+", origin) is None
200
+ or not parts.hostname or parts.username is not None or parts.password is not None
201
+ or parts.path or parts.query or parts.fragment or parts.port in (0, 443)):
202
+ raise ValueError("origin")
203
+ rooms = data["room_ids"]
204
+ if not isinstance(rooms, list) or not 1 <= len(rooms) <= 32:
205
+ raise ValueError("scope")
206
+ rooms = tuple(uuid_text(room) for room in rooms)
207
+ if (len(set(rooms)) != len(rooms) or re.fullmatch(r"[0-9a-f]{64}", data["viewer_token"]) is None
208
+ or data["viewer_token"] in origin):
209
+ raise ValueError("credential")
210
+ policy = None
211
+ if "artifact_policy" in data:
212
+ artifact = data["artifact_policy"]
213
+ if (not isinstance(artifact, dict) or set(artifact) != {"root", "retention_seconds"}
214
+ or not isinstance(artifact["root"], str) or not 1 <= len(artifact["root"]) <= 512
215
+ or type(artifact["retention_seconds"]) is not int
216
+ or not 1 <= artifact["retention_seconds"] <= 86400):
217
+ raise ValueError("artifact policy")
218
+ root = Path(artifact["root"])
219
+ if (not root.is_absolute() or ".." in root.parts or str(root) != artifact["root"]
220
+ or any(ord(char) < 32 or ord(char) == 127 for char in str(root))
221
+ or data["viewer_token"] in str(root) or root in path.parents):
222
+ raise ValueError("artifact root")
223
+ policy = ArtifactPolicy(root, artifact["retention_seconds"])
224
+ return Binding(origin, rooms, data["viewer_token"], policy)
225
+ except (ValueError, TypeError, KeyError, AttributeError, UnicodeError):
226
+ raise Stop("BINDING_INVALID") from None
227
+
228
+
229
+ def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
230
+ result: dict[str, Any] = {}
231
+ for key, value in pairs:
232
+ if key in result:
233
+ raise ValueError("duplicate key")
234
+ result[key] = value
235
+ return result
236
+
237
+
238
+ def evidence(request: Request | None = None, binding: Binding | None = None) -> dict[str, Any]:
239
+ return {
240
+ "version": 1, "scenario": request.scenario if request else "unknown", "mode": "inspection",
241
+ "timestamp": datetime.now(timezone.utc).isoformat(), "origin": binding.origin if binding else "unknown",
242
+ "room": request.room if request else None, "session": request.session if request else None,
243
+ "message": request.message if request else None,
244
+ "receipt_session": request.receipt_session if request else None,
245
+ "viewports": [{"width": width, "height": height} for width, height in VIEWPORTS],
246
+ "source_ref": "unknown",
247
+ "served_hashes": {
248
+ name: "unknown"
249
+ for name in ("index.html", "chat.js", "i18n.js", "chat.css", "Manrope-Variable.ttf")
250
+ },
251
+ "assertions": [], "artifacts": [], "retention": "NOT_RUN", "retention_seconds": None, "expiry": "NOT_RUN",
252
+ "cleanup": {key: "NOT_RUN" for key in ("logout", "context", "browser", "children", "temporary")}
253
+ | ({"artifacts": "NOT_RUN"} if request is not None and request.screenshot else {}),
254
+ "cleanup_steps": [], "close_steps": [], "cookie_max_lifetime_seconds": "unknown", "requests": 0,
255
+ "result": "NOT_RUN",
256
+ }
257
+
258
+
259
+ def record(result: dict[str, Any], code: str, status: str = "PASS", viewport: int | None = None) -> None:
260
+ entry = {"code": code, "result": status}
261
+ if viewport is not None:
262
+ entry["viewport"] = viewport
263
+ if entry not in result["assertions"] and len(result["assertions"]) < 96:
264
+ result["assertions"].append(entry)
265
+
266
+
267
+ def verdict(result: dict[str, Any]) -> None:
268
+ statuses = [entry["result"] for entry in result["assertions"]]
269
+ statuses += list(result["cleanup"].values())
270
+ result["result"] = ("FAIL" if "FAIL" in statuses else "PASS"
271
+ if statuses and result["assertions"] and all(s == "PASS" for s in statuses)
272
+ else "UNAVAILABLE")
273
+
274
+
275
+ def _children(pid: int) -> dict[int, str]:
276
+ found: dict[int, str] = {}
277
+ pending = [pid]
278
+ while pending:
279
+ parent = pending.pop()
280
+ try:
281
+ children = Path(f"/proc/{parent}/task/{parent}/children").read_text().split()
282
+ except FileNotFoundError:
283
+ continue
284
+ for value in children:
285
+ child = int(value)
286
+ try:
287
+ start = Path(f"/proc/{child}/stat").read_text().rsplit(")", 1)[1].split()[19]
288
+ except FileNotFoundError:
289
+ continue
290
+ if child not in found:
291
+ found[child] = start
292
+ pending.append(child)
293
+ return found
294
+
295
+
296
+ def _reap_owned(baseline: dict[int, str], deadline: float) -> bool:
297
+ # Linux subreaper adoption retains ownership even if a Chromium process starts
298
+ # its own session, or the Playwright driver dies before closing its browser.
299
+ while time.monotonic() < deadline:
300
+ owned = {pid: start for pid, start in _children(os.getpid()).items() if pid not in baseline}
301
+ if not owned:
302
+ return True
303
+ for pid, start in owned.items():
304
+ try:
305
+ current = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[19]
306
+ if current == start:
307
+ os.kill(pid, signal.SIGKILL)
308
+ os.waitpid(pid, os.WNOHANG)
309
+ except (FileNotFoundError, ProcessLookupError, ChildProcessError):
310
+ pass
311
+ time.sleep(0.01)
312
+ return not {pid for pid in _children(os.getpid()) if pid not in baseline}
313
+
314
+
315
+ def supervise(request: Request, binding: Binding, *, test_trust: FixtureTrust | None = None) -> dict[str, Any]:
316
+ result = evidence(request, binding)
317
+ if request.screenshot and binding.artifact_policy is None:
318
+ raise Stop("ARTIFACT_POLICY_UNAVAILABLE", "UNAVAILABLE")
319
+ if sys.platform != "linux":
320
+ raise Stop("PROCESS_CONTROL_UNAVAILABLE", "UNAVAILABLE")
321
+ # This is a one-shot process, not an embeddable browser service. Refuse an
322
+ # existing process tree rather than risk claiming somebody else's orphan.
323
+ baseline = _children(os.getpid())
324
+ if baseline:
325
+ raise Stop("PROCESS_OWNERSHIP_UNAVAILABLE", "UNAVAILABLE")
326
+ libc = ctypes.CDLL(None, use_errno=True)
327
+ previous = ctypes.c_int()
328
+ if libc.prctl(37, ctypes.byref(previous), 0, 0, 0) != 0 or libc.prctl(36, 1, 0, 0, 0) != 0:
329
+ raise Stop("PROCESS_CONTROL_UNAVAILABLE", "UNAVAILABLE")
330
+ from .browser_verify_artifacts import Artifacts
331
+
332
+ artifacts = None
333
+ try:
334
+ if request.screenshot and binding.artifact_policy is not None:
335
+ artifacts = Artifacts.create(binding.artifact_policy)
336
+ with tempfile.TemporaryDirectory(prefix="agent-chat-verify-") as directory:
337
+ root = Path(directory)
338
+ os.chmod(root, 0o700)
339
+ env = {"PATH": os.defpath, "LANG": "C.UTF-8", "HOME": directory, "TMPDIR": directory}
340
+ # This is an installation path, not a browser profile or browser endpoint.
341
+ if os.environ.get("PLAYWRIGHT_BROWSERS_PATH"):
342
+ env["PLAYWRIGHT_BROWSERS_PATH"] = os.environ["PLAYWRIGHT_BROWSERS_PATH"]
343
+ else:
344
+ env["PLAYWRIGHT_BROWSERS_PATH"] = str(Path.home() / ".cache/ms-playwright")
345
+ trust = None
346
+ if test_trust is not None:
347
+ if (test_trust.origin != binding.origin or urlsplit(binding.origin).hostname != "127.0.0.1"
348
+ or re.fullmatch(r"[A-Za-z0-9+/]{43}=", test_trust.spki) is None):
349
+ raise Stop("TEST_TRUST_INVALID")
350
+ certificate = root / "fixture-ca.pem"
351
+ certificate.write_bytes(test_trust.certificate.read_bytes())
352
+ certificate.chmod(0o600)
353
+ env["NODE_EXTRA_CA_CERTS"] = str(certificate)
354
+ trust = test_trust.spki
355
+ arguments = ["--binding", str(request.binding), "--scenario", request.scenario, "--room", request.room]
356
+ for flag, value in (("--session", request.session), ("--message", request.message),
357
+ ("--receipt-session", request.receipt_session),
358
+ ("--expected-title-file", request.expected_title_file),
359
+ ("--min-participants", request.min_participants)):
360
+ if value is not None:
361
+ arguments.append(flag + "=" + str(value))
362
+ for state in request.receipt_states:
363
+ arguments += ["--receipt-state", state]
364
+ if request.screenshot:
365
+ arguments.append("--screenshot")
366
+ # The worker revalidates the managed file; no alternate stdin token or
367
+ # URL route exists even at this private process boundary.
368
+ policy = binding.artifact_policy
369
+ payload = {"argv": arguments, "origin": binding.origin, "room_ids": binding.room_ids, "test_spki": trust,
370
+ "artifact_policy": [str(policy.root), policy.retention_seconds] if policy else None,
371
+ "artifact_target": {"fd": artifacts.directory_fd, "name": artifacts.name}
372
+ if artifacts else None}
373
+ child = subprocess.Popen(
374
+ [sys.executable, "-I", "-m", "agent_chat.browser_verify_run"],
375
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
376
+ env=env, start_new_session=True,
377
+ pass_fds=(artifacts.directory_fd,) if artifacts else (),
378
+ )
379
+ try:
380
+ timed_out = False
381
+ try:
382
+ output, _ = child.communicate(json.dumps(payload).encode(), timeout=RUN_SECONDS)
383
+ except subprocess.TimeoutExpired:
384
+ timed_out = True
385
+ child.send_signal(signal.SIGTERM)
386
+ try:
387
+ output, _ = child.communicate(timeout=CLEANUP_SECONDS - 2)
388
+ except subprocess.TimeoutExpired:
389
+ child.kill()
390
+ output, _ = child.communicate(timeout=1)
391
+ record(result, "RUN_LIMIT", "UNAVAILABLE")
392
+ if child.returncode == 0 and len(output) <= 32768:
393
+ worker = json.loads(output)
394
+ worker["assertions"] += result["assertions"]
395
+ result = worker
396
+ else:
397
+ record(result, "WORKER_INCOMPLETE" if timed_out else "WORKER_FAILED",
398
+ "UNAVAILABLE" if timed_out else "FAIL")
399
+ finally:
400
+ waited = True
401
+ try:
402
+ if child.poll() is None:
403
+ child.kill()
404
+ child.wait(timeout=0.25)
405
+ except (OSError, subprocess.TimeoutExpired):
406
+ waited = False
407
+ try:
408
+ cleaned = _reap_owned(baseline, time.monotonic() + 0.75)
409
+ except OSError:
410
+ cleaned = False
411
+ result["cleanup"]["children"] = "PASS" if cleaned and waited else "UNAVAILABLE"
412
+ result["cleanup"]["temporary"] = "PASS"
413
+ except Stop as error:
414
+ record(result, error.code, error.result)
415
+ except OSError:
416
+ result["cleanup"]["temporary"] = "UNAVAILABLE"
417
+ record(result, "SUPERVISION_UNAVAILABLE", "UNAVAILABLE")
418
+ except Exception:
419
+ # Preserve worker assertions if the private protocol or parent cleanup
420
+ # fails. Letting this escape would replace the original failure in main.
421
+ result["cleanup"]["temporary"] = "UNAVAILABLE"
422
+ record(result, "SUPERVISION_ERROR", "FAIL")
423
+ finally:
424
+ if libc.prctl(36, previous.value, 0, 0, 0) != 0:
425
+ result["cleanup"]["children"] = "UNAVAILABLE"
426
+ if artifacts is not None:
427
+ try:
428
+ result["cleanup"]["artifacts"] = "PASS"
429
+ verdict(result)
430
+ if result["result"] == "PASS":
431
+ result["artifacts"] = artifacts.paths(expected=len(VIEWPORTS))
432
+ result["retention"] = "PASS"
433
+ result["retention_seconds"] = artifacts.policy.retention_seconds
434
+ else:
435
+ artifacts.discard()
436
+ except (OSError, Stop) as error:
437
+ result["cleanup"]["artifacts"] = "UNAVAILABLE"
438
+ record(result, error.code if isinstance(error, Stop) else "ARTIFACT_CLEANUP_UNAVAILABLE",
439
+ error.result if isinstance(error, Stop) else "UNAVAILABLE")
440
+ result["artifacts"] = []
441
+ try:
442
+ artifacts.discard()
443
+ except (OSError, Stop):
444
+ pass
445
+ finally:
446
+ try:
447
+ artifacts.close()
448
+ except OSError:
449
+ result["artifacts"] = []
450
+ result["retention"] = "UNAVAILABLE"
451
+ result["cleanup"]["artifacts"] = "UNAVAILABLE"
452
+ record(result, "ARTIFACT_CLEANUP_UNAVAILABLE", "UNAVAILABLE")
453
+ try:
454
+ artifacts.discard()
455
+ except (OSError, Stop):
456
+ pass
457
+ verdict(result)
458
+ return result
459
+
460
+
461
+ def main(argv: list[str] | None = None, *, _test_trust: FixtureTrust | None = None) -> int:
462
+ request = binding = None
463
+ result = evidence()
464
+ try:
465
+ request = parse(argv)
466
+ result = evidence(request)
467
+ binding = read_binding(request.binding)
468
+ result = evidence(request, binding)
469
+ if request.room not in binding.room_ids:
470
+ raise Stop("ROOM_OUTSIDE_BINDING")
471
+ result = supervise(request, binding, test_trust=_test_trust)
472
+ except Stop as error:
473
+ record(result, error.code, error.result)
474
+ except (OSError, ImportError):
475
+ record(result, "PREREQUISITE_UNAVAILABLE", "UNAVAILABLE")
476
+ except KeyboardInterrupt:
477
+ record(result, "INTERRUPTED", "UNAVAILABLE")
478
+ except Exception:
479
+ # Final protocol boundary: private exception messages must never reach stderr.
480
+ record(result, "UNEXPECTED_ERROR", "FAIL")
481
+ verdict(result)
482
+ print(json.dumps(result, ensure_ascii=True, separators=(",", ":")))
483
+ return 0 if result["result"] == "PASS" else 1
484
+
485
+
486
+ if __name__ == "__main__":
487
+ raise SystemExit(main())