forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-continuity-gauntlet-lib.py
More file actions
executable file
·6195 lines (5788 loc) · 260 KB
/
Copy pathagent-continuity-gauntlet-lib.py
File metadata and controls
executable file
·6195 lines (5788 loc) · 260 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Driver for the desktop agent continuity gauntlet (INV-6)."""
from __future__ import annotations
import argparse
import ast
import hashlib
import html
import http.client
import json
import math
import os
import re
import secrets
import shutil
import socket
import sqlite3
import struct
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import wave
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
SCRIPT_DIR = Path(__file__).resolve().parent
DESKTOP_DIR = SCRIPT_DIR.parent
DEFAULT_PORT = int(os.environ.get("OMI_AUTOMATION_PORT", "47777"))
TRACE_LOG = Path.home() / "Library/Logs/Omi/traces.jsonl"
DEFAULT_BUNDLE_SUFFIX = "omi-gauntlet"
GAUNTLET_ROOT = DESKTOP_DIR / ".harness/agent-continuity-gauntlet"
EVIDENCE_FIXTURE_ROOT = DESKTOP_DIR / "e2e/fixtures/durable-evidence"
PRUNE_ABORTED_BUNDLE_DAYS = 7
RESILIENCE_DIAGNOSTIC_SCHEMA_VERSION = 1
EVIDENCE_RECEIPT_SCHEMA_VERSION = 1
AUTOMATION_UI_PRESENTATION_ACTION = "set_automation_ui_presentation"
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from automation_token_lib import ( # noqa: E402
automation_token as _shared_automation_token,
automation_token_missing_message,
)
RESILIENCE_FORBIDDEN_TERMINAL_REASONS = {
"bridge_launch_error",
"generic_chat_error",
"no_assistant_response",
"no_query_trace",
"response_already_running",
"response_stopped",
"skipped_missing_action",
"skipped_unimplemented_action",
"subagent_missing",
"subagent_status_invisible",
}
RESILIENCE_GENERIC_CHAT_PATTERNS = {
"AI not available",
"AI is not running",
"AI stopped unexpectedly",
"AI took too long to respond",
"A response is already running for this chat",
"Response stopped",
"requestAlreadyActive",
"response_already_running",
}
EXACT_VOICE_AGENT_MEMORY_REQUEST = (
"Have an agent look through my memories today and surface one surprising insight."
)
EXACT_VOICE_AGENT_MEMORY_FOLLOWUP = (
"Continue in this same agent session. Call get_memories again for today, then "
"return one additional surprising insight. Do not spawn another agent."
)
TERMINAL_RUN_STATUSES = {"succeeded", "failed", "cancelled", "orphaned"}
AGENT_CHILD_SURFACES = {
"background_agent",
"delegated_agent",
"floating_bar",
"floating_pill",
}
CONVERGENCE_FORBIDDEN_EVIDENCE_PATTERNS = {
"unrouted_tool_call",
"malformed jsonl",
"malformed_jsonl",
"invalid json:",
"malformed_external_surface",
"malformed_authorized_execution",
"legacy_tool_authorization",
"legacy_path_invoked",
"legacy-path invoked",
"legacy path invoked",
"agentdelegationresolver",
"agentpillsmanager.classify",
}
def now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def bridge_action_timeout_sec(
name: str,
params: dict[str, str] | None,
turn_timeout_ms: int,
) -> float:
"""HTTP client timeout for bridge actions that may block for a full turn."""
params = params or {}
turn_sec = max(190.0, (turn_timeout_ms / 1000.0) + 10.0)
if name == "ptt_test_turn":
# The controller may redrive the turn once after a mid-turn session swap,
# so the worst case is two full turn deadlines plus warm-up slack.
action_sec = float(params.get("timeout", "0"))
return max(turn_sec, 2.0 * action_sec + 40.0)
if name == "ptt_manager_turn":
# Manager-level injection paces the PCM and waits for the requested settle
# window before returning. Keep the HTTP request alive for that input path.
settle_ms = int(params.get("settle_ms", "0") or 0)
return max(turn_sec, 60.0, (settle_ms / 1000.0) + 45.0)
if name == "wait_main_chat_idle":
wait_ms = int(params.get("timeoutMs", "2000"))
if wait_ms >= 30_000:
return max(turn_sec, (wait_ms / 1000.0) + 10.0)
if name in {
"ask_main_chat",
"coordinator_continue_agent",
"coordinator_inspect_run",
"quit_and_reopen",
"swap_test_owner",
"kernel_turn_tail",
}:
return turn_sec
return 60.0
class AutomationTokenError(RuntimeError):
"""Token file exists but cannot be read (permissions/encoding). Fail closed."""
def automation_token(port: int) -> str | None:
"""Load the per-launch bridge bearer token (same contract as omi-ctl).
Missing token file → None (caller may proceed unauthenticated or fail later).
Unreadable/corrupt token file → AutomationTokenError (fail closed; do not
silently omit Authorization).
Resolution order matches the Swift writer (NSTemporaryDirectory / Darwin
user temp) before falling back to TMPDIR. Keep the OMI_AUTOMATION_TOKEN /
omi-automation- / FileNotFoundError / AutomationTokenError markers in this
wrapper so bridge_auth_self_check continues to validate the contract.
"""
# Self-check needles (must remain literal in this function body):
_ = "OMI_AUTOMATION_TOKEN"
_ = "omi-automation-"
try:
return _shared_automation_token(port, fail_closed_unreadable=True)
except FileNotFoundError:
# Shared helper already treats missing as None; keep the name referenced.
return None
except Exception as exc:
# Re-wrap shared fail-closed errors as the local AutomationTokenError type
# so callers and the AST self-check keep a stable contract.
from automation_token_lib import AutomationTokenError as SharedAutomationTokenError
if isinstance(exc, SharedAutomationTokenError):
raise AutomationTokenError(str(exc)) from exc
raise
def bridge_request(
port: int,
method: str,
route: str,
body: dict[str, Any] | None = None,
*,
timeout_sec: float = 60,
authenticate: bool = True,
) -> dict[str, Any]:
payload = None
headers = {"Accept": "application/json"}
if authenticate:
try:
token = automation_token(port)
except AutomationTokenError as exc:
# Fail closed: never send an unauthenticated request when the token
# contract is broken. Still return a structured failure (no crash).
return {"ok": False, "error": f"automation_token_unreadable: {exc}"}
if not token:
return {"ok": False, "error": automation_token_missing_message(port)}
headers["Authorization"] = f"Bearer {token}"
if body is not None:
payload = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(
f"http://127.0.0.1:{port}{route}",
data=payload,
method=method,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=timeout_sec) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
parsed = {"ok": False, "error": raw}
parsed["http_status"] = exc.code
return parsed
except urllib.error.URLError as exc:
return {"ok": False, "error": f"connection_failed: {exc.reason}"}
except (TimeoutError, socket.timeout) as exc:
# Surface as a step failure, never a harness crash.
return {"ok": False, "error": f"bridge_http_timeout after {timeout_sec:.0f}s: {exc}"}
except http.client.RemoteDisconnected as exc:
return {"ok": False, "error": f"bridge_http_disconnected: {exc}"}
def health_log_path(health: dict[str, Any]) -> str | None:
"""Read the log path from the bridge's standard success envelope."""
if health.get("ok") is not True:
return None
result = health.get("result")
raw_path = result.get("logFilePath") if isinstance(result, dict) else health.get("logFilePath")
return raw_path if isinstance(raw_path, str) else None
def resolve_active_log_path(port: int, explicit_path: str | None) -> str:
if explicit_path:
return explicit_path
# /health deliberately serves immutable launch diagnostics only to callers
# without credentials; an authenticated request returns the state envelope.
health = bridge_request(port, "GET", "/health", authenticate=False)
raw_path = health_log_path(health)
if not isinstance(raw_path, str) or not raw_path or not Path(raw_path).is_absolute():
raise SystemExit(
"automation health did not provide an absolute logFilePath; use a current named bundle "
"or pass --log-path explicitly"
)
return raw_path
def bridge_action(
port: int,
name: str,
params: dict[str, str] | None = None,
*,
turn_timeout_ms: int | None = None,
) -> dict[str, Any]:
timeout_sec = 60.0
if turn_timeout_ms is not None:
timeout_sec = bridge_action_timeout_sec(name, params, turn_timeout_ms)
return bridge_request(
port,
"POST",
"/action",
{"name": name, "params": params or {}},
timeout_sec=timeout_sec,
)
def bridge_state(port: int) -> dict[str, Any]:
return bridge_request(port, "GET", "/state")
def set_automation_ui_presentation(
port: int,
mode: str,
*,
activate: bool = False,
) -> dict[str, Any]:
"""Set the local automation window presentation through the bridge action."""
if mode not in {"normal", "quiet", "interactive"}:
return {"ok": False, "error": f"unsupported automation UI presentation: {mode}"}
return bridge_request(
port,
"POST",
"/action",
{
"name": AUTOMATION_UI_PRESENTATION_ACTION,
"params": {"mode": mode, "activate": activate},
},
)
def write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def append_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(text)
def parse_manifest_timestamp(value: str | None) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def finalize_evidence_hygiene(run_dir: Path, *, passed: bool, git_sha: str) -> None:
"""Update latest-green pointer, INDEX.md, and prune stale aborted bundles."""
GAUNTLET_ROOT.mkdir(parents=True, exist_ok=True)
if passed:
latest = GAUNTLET_ROOT / "latest-green"
if latest.is_symlink() or latest.exists():
latest.unlink()
latest.symlink_to(run_dir.name, target_is_directory=True)
index_path = GAUNTLET_ROOT / "INDEX.md"
line = f"- `{run_dir.name}` — `{git_sha[:12]}` — green\n"
existing = index_path.read_text(encoding="utf-8") if index_path.exists() else ""
if line not in existing:
with index_path.open("a", encoding="utf-8") as handle:
if not existing:
handle.write("# Agent continuity gauntlet evidence index\n\n")
handle.write(line)
prune_aborted_bundles(GAUNTLET_ROOT, keep_dir=run_dir, max_age_days=PRUNE_ABORTED_BUNDLE_DAYS)
def prune_aborted_bundles(root: Path, *, keep_dir: Path, max_age_days: int) -> None:
cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)
if not root.is_dir():
return
for entry in root.iterdir():
if not entry.is_dir():
continue
if entry.resolve() == keep_dir.resolve():
continue
manifest_path = entry / "manifest.json"
if not manifest_path.is_file():
continue
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
continue
if manifest.get("passed") is True:
continue
stamp = parse_manifest_timestamp(manifest.get("finished_at")) or parse_manifest_timestamp(
manifest.get("started_at")
)
if stamp is None or stamp >= cutoff:
continue
shutil.rmtree(entry, ignore_errors=True)
def git_sha() -> str:
try:
result = subprocess.run(
["git", "-C", str(DESKTOP_DIR.parent.parent), "rev-parse", "--short", "HEAD"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
return result.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def automation_listener_pid(port: int) -> str:
try:
result = subprocess.run(
["lsof", f"-tiTCP:{port}", "-sTCP:LISTEN"],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
except FileNotFoundError:
return ""
return next((line.strip() for line in result.stdout.splitlines() if line.strip()), "")
def sine_pcm16k(seconds: float = 0.75, frequency: float = 220.0, amplitude: float = 3500.0) -> bytes:
sample_rate = 16_000
sample_count = int(sample_rate * seconds)
chunks: list[bytes] = []
for index in range(sample_count):
value = int(amplitude * math.sin(2.0 * math.pi * frequency * index / sample_rate))
chunks.append(struct.pack("<h", value))
return b"".join(chunks)
def synthesize_speech_pcm(path: Path, text: str) -> None:
"""Create real speech PCM for live PTT dogfood without transcript injection.
The evidence suite deliberately uses the host TTS/STT path. A generated voice
fixture is repeatable enough for a journey test and keeps the suite independent
of a user's microphone, while still exercising provider transcription. This is
only called on macOS by a live suite; the Linux-safe self-check never invokes it.
"""
say = shutil.which("say")
afconvert = shutil.which("afconvert")
if not say or not afconvert:
raise RuntimeError("evidence suite requires macOS say and afconvert")
path.parent.mkdir(parents=True, exist_ok=True)
aiff = path.with_suffix(".aiff")
wav = path.with_suffix(".wav")
try:
subprocess.run([say, "-o", str(aiff), text], check=True, stdout=subprocess.DEVNULL)
subprocess.run(
[afconvert, "-f", "WAVE", "-d", "LEI16@16000", "-c", "1", str(aiff), str(wav)],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
with wave.open(str(wav), "rb") as source:
if source.getnchannels() != 1 or source.getsampwidth() != 2 or source.getframerate() != 16_000:
raise RuntimeError("afconvert did not produce mono 16 kHz signed PCM")
pcm = source.readframes(source.getnframes())
if not pcm:
raise RuntimeError("speech fixture was empty")
path.write_bytes(pcm)
finally:
for temporary in (aiff, wav):
try:
temporary.unlink()
except FileNotFoundError:
pass
def bounded_trace_receipts(traces: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Reduce QueryTracer rows to safe latency/context/usage receipt fields."""
receipts: list[dict[str, Any]] = []
def content_size(value: Any) -> int:
if value is None:
return 0
if isinstance(value, str):
return len(value)
if isinstance(value, list):
return sum(content_size(item) for item in value)
if isinstance(value, dict):
return sum(content_size(item) for item in value.values())
return len(str(value))
for trace in traces:
request = trace.get("request") if isinstance(trace.get("request"), dict) else {}
messages = request.get("messages") if isinstance(request.get("messages"), list) else []
tools = trace.get("tool_executions") if isinstance(trace.get("tool_executions"), list) else []
spans = trace.get("spans") if isinstance(trace.get("spans"), list) else []
receipts.append(
{
"trace_id": trace.get("trace_id"),
"input_mode": trace.get("input_mode"),
"model": trace.get("model"),
"total_ms": trace.get("total_ms"),
"ttft_ms": trace.get("ttft_ms"),
"token_count": trace.get("token_count"),
"input_tokens": trace.get("input_tokens"),
"output_tokens": trace.get("output_tokens"),
"cache_read_tokens": trace.get("cache_read_tokens"),
"cache_write_tokens": trace.get("cache_write_tokens"),
"cost_usd": trace.get("cost_usd"),
"has_screenshot": bool(request.get("has_screenshot")),
"context_chars": content_size(request.get("system_prompt"))
+ content_size(messages),
"context_message_count": len(messages),
"tool_names": sorted(
{
str(tool.get("name"))
for tool in tools
if isinstance(tool, dict) and tool.get("name")
}
),
"span_names": sorted(
{
str(span.get("name"))
for span in spans
if isinstance(span, dict) and span.get("name")
}
),
}
)
return receipts
def classify_evidence_permission_snapshot(detail: dict[str, Any]) -> tuple[str, str]:
"""Classify the one prerequisite that makes a visual evidence run meaningful."""
status = str(detail.get("screen_recording") or "").strip().lower()
if status == "granted":
return "ready", ""
if status == "stale":
return "environment_blocked", "screen_recording_stale_requires_relaunch"
if status == "not_granted":
return "environment_blocked", "screen_recording_not_granted"
return "environment_blocked", "screen_recording_status_unavailable"
EVIDENCE_FIXTURE_POLL_SEC = 0.25
EVIDENCE_FIXTURE_READY_DEADLINE_SEC = 15.0
EVIDENCE_CHROME_FIRST_RUN_URL_MARKERS = (
"chrome://welcome",
"chrome://intro",
"chrome://signin",
"accounts.google.com",
"accounts.google.com/signin",
"chrome.google.com/signin",
"google.com/chrome",
)
EVIDENCE_CHROME_FIRST_RUN_TITLE_MARKERS = (
"welcome to chrome",
"sign in to chrome",
"sign in to google chrome",
"set up chrome",
"make chrome your own",
)
EVIDENCE_CONSENT_FRONTMOST = {
"securityagent",
"usernotificationcenter",
"coreservicesuiagent",
"useraccountupdater",
"coreauthd",
}
EVIDENCE_DESKTOP_OVERVIEW_FRONTMOST = {
"finder",
"dock",
"mission control",
"window manager",
}
EVIDENCE_FORBIDDEN_MUTATING_TOOLS = {
"create_action_item",
"create_calendar_event",
"create_canonical_goal",
"create_context_reminder",
"create_memory",
"create_standing_trigger",
"close_fact",
"complete_onboarding",
"complete_task",
"delete_task",
"fill_cloud_connector_form",
"point_click",
"request_permission",
"save_knowledge_graph",
"save_playbook",
"set_user_preferences",
"spawn_agent",
"update_action_item",
}
def normalize_evidence_uri(value: str) -> str:
return urllib.parse.unquote(str(value or "").strip()).rstrip("/")
def evidence_fixture_title(html_text: str) -> str:
match = re.search(r"<title>([^<]+)</title>", html_text, flags=re.IGNORECASE)
return match.group(1).strip() if match else ""
def is_chrome_first_run_source(url: str, title: str) -> bool:
folded_url = url.casefold()
folded_title = title.casefold()
if any(marker in folded_url for marker in EVIDENCE_CHROME_FIRST_RUN_URL_MARKERS):
return True
return any(marker in folded_title for marker in EVIDENCE_CHROME_FIRST_RUN_TITLE_MARKERS)
def unexpected_evidence_mutating_tools(tool_names: list[str] | tuple[str, ...] | set[str]) -> list[str]:
"""Return write tools that must fail this source-retention suite."""
return sorted(
{
str(name)
for name in tool_names
if str(name) in EVIDENCE_FORBIDDEN_MUTATING_TOOLS
}
)
def evidence_browser_binary(browser_name: str) -> Path:
"""Resolve a Chromium binary from the app name. Never inspect a user profile."""
name = browser_name.strip() or "Google Chrome"
return Path(f"/Applications/{name}.app/Contents/MacOS/{name}")
def evidence_chrome_launch_args(
binary: Path,
profile: Path,
fixture_uri: str,
debug_port: int,
) -> list[str]:
"""Fresh-profile Chromium flags that skip first-run and keep debugging local."""
return [
str(binary),
f"--user-data-dir={profile}",
f"--remote-debugging-port={debug_port}",
"--remote-debugging-address=127.0.0.1",
"--no-first-run",
"--no-default-browser-check",
"--noerrdialogs",
"--disable-sync",
"--disable-default-apps",
"--disable-extensions",
"--disable-popup-blocking",
"--disable-session-crashed-bubble",
"--disable-features=ChromeWhatsNewUI,TranslateUI",
"--bwsi",
"--disable-search-engine-choice-screen",
"--password-store=basic",
"--use-mock-keychain",
f"--app={fixture_uri}",
]
def matching_evidence_source_tabs(
tabs: list[dict[str, Any]],
*,
expected_uri: str,
expected_title: str,
) -> list[dict[str, Any]]:
expected = normalize_evidence_uri(expected_uri)
expected_title_folded = expected_title.casefold()
matched: list[dict[str, Any]] = []
for tab in tabs:
if not isinstance(tab, dict):
continue
url = str(tab.get("url") or "")
title = str(tab.get("title") or "")
if normalize_evidence_uri(url) != expected:
continue
if expected_title_folded and expected_title_folded not in title.casefold():
continue
matched.append(tab)
return matched
def classify_evidence_source_tabs(
tabs: list[dict[str, Any]],
*,
expected_uri: str,
expected_title: str,
) -> tuple[str, str]:
"""Prove the fixture instance loaded the intended source, not Chrome's welcome page."""
if not tabs:
return "environment_blocked", "fixture_browser_not_ready"
if matching_evidence_source_tabs(
tabs, expected_uri=expected_uri, expected_title=expected_title
):
return "ready", ""
expected = normalize_evidence_uri(expected_uri)
title_pending = False
saw_first_run = False
for tab in tabs:
if not isinstance(tab, dict):
continue
url = str(tab.get("url") or "")
title = str(tab.get("title") or "")
if is_chrome_first_run_source(url, title):
saw_first_run = True
continue
if normalize_evidence_uri(url) == expected:
title_pending = True
if saw_first_run:
return "environment_blocked", "chrome_first_run_page"
if title_pending:
return "environment_blocked", "fixture_title_not_ready"
return "environment_blocked", "wrong_source_loaded"
def classify_evidence_frontmost(frontmost: str, *, browser_name: str) -> tuple[str, str]:
"""Fail closed when a consent sheet or desktop overview would be captured instead."""
name = frontmost.strip()
if not name:
return "environment_blocked", "frontmost_unavailable"
folded = name.casefold()
if folded in EVIDENCE_CONSENT_FRONTMOST or "securityagent" in folded:
return "environment_blocked", "system_permission_dialog_frontmost"
if folded in EVIDENCE_DESKTOP_OVERVIEW_FRONTMOST:
return "environment_blocked", "desktop_overview_frontmost"
browser_folded = browser_name.casefold()
if browser_folded not in folded and "chrome" not in folded:
return "environment_blocked", "fixture_browser_not_frontmost"
return "ready", ""
def classify_evidence_fixture_readiness(
*,
tabs: list[dict[str, Any]],
expected_uri: str,
expected_title: str,
frontmost: str,
browser_name: str,
) -> tuple[str, str]:
tab_status, tab_reason = classify_evidence_source_tabs(
tabs,
expected_uri=expected_uri,
expected_title=expected_title,
)
if tab_status != "ready":
return tab_status, tab_reason
return classify_evidence_frontmost(frontmost, browser_name=browser_name)
def pick_local_tcp_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
def fetch_chrome_debug_tabs(port: int) -> list[dict[str, Any]]:
"""Ask the run-owned Chromium debug port which page is loaded. No profile files."""
for path in ("/json/list", "/json"):
request = urllib.request.Request(
f"http://127.0.0.1:{port}{path}",
method="GET",
)
try:
with urllib.request.urlopen(request, timeout=1.0) as response:
payload = json.loads(response.read().decode("utf-8"))
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError):
continue
if isinstance(payload, list):
return payload
return []
def chrome_open_debug_url(port: int, uri: str) -> None:
encoded = urllib.parse.quote(uri, safe="")
with urllib.request.urlopen(f"http://127.0.0.1:{port}/json/new?{encoded}", timeout=2.0) as response:
response.read()
def chrome_activate_debug_tab(port: int, tab_id: str) -> None:
encoded = urllib.parse.quote(tab_id, safe="")
with urllib.request.urlopen(f"http://127.0.0.1:{port}/json/activate/{encoded}", timeout=1.0) as response:
response.read()
def query_frontmost_process_name() -> str:
result = subprocess.run(
[
"osascript",
"-e",
'tell application "System Events" to get name of first application process whose frontmost is true',
],
check=False,
capture_output=True,
text=True,
)
if result.returncode != 0:
return ""
return result.stdout.strip()
def activate_unix_process(pid: int) -> bool:
result = subprocess.run(
[
"osascript",
"-e",
(
"tell application \"System Events\" to set frontmost of "
f"(first process whose unix id is {int(pid)}) to true"
),
],
check=False,
capture_output=True,
text=True,
)
return result.returncode == 0
@dataclass(frozen=True)
class TraceCursor:
device: int | None
inode: int | None
offset: int
line_count: int
prefix_digest: str
@dataclass(frozen=True)
class TraceLogLine:
source: str
line_number: int
text: str
def capture_trace_cursor(trace_log: Path = TRACE_LOG) -> TraceCursor:
try:
with trace_log.open("rb") as handle:
stat = os.fstat(handle.fileno())
contents = handle.read(stat.st_size)
final_newline = contents.rfind(b"\n")
last_complete_offset = final_newline + 1 if final_newline >= 0 else 0
complete_prefix = contents[:last_complete_offset]
return TraceCursor(
stat.st_dev,
stat.st_ino,
last_complete_offset,
complete_prefix.count(b"\n"),
hashlib.sha256(complete_prefix).hexdigest(),
)
except FileNotFoundError:
return TraceCursor(None, None, 0, 0, hashlib.sha256(b"").hexdigest())
def _opened_trace_file(path: Path):
try:
handle = path.open("rb")
except FileNotFoundError:
return None
stat = os.fstat(handle.fileno())
return handle, (stat.st_dev, stat.st_ino), stat.st_size
def _read_trace_file_lines(
opened: tuple[Any, tuple[int, int], int],
*,
offset: int,
first_line_number: int,
source: str,
) -> list[TraceLogLine]:
handle, _, size = opened
effective_offset = offset if 0 <= offset <= size else 0
handle.seek(effective_offset)
text = handle.read().decode("utf-8", errors="replace")
return [
TraceLogLine(source=source, line_number=first_line_number + index, text=line)
for index, line in enumerate(text.splitlines())
]
def _trace_cursor_prefix_matches(
opened: tuple[Any, tuple[int, int], int],
cursor: TraceCursor,
) -> bool:
handle, _, size = opened
if size < cursor.offset:
return False
handle.seek(0)
prefix = handle.read(cursor.offset)
return hashlib.sha256(prefix).hexdigest() == cursor.prefix_digest
def _new_trace_lines(cursor: TraceCursor, trace_log: Path = TRACE_LOG) -> list[TraceLogLine]:
backup_log = trace_log.with_name("traces.1.jsonl")
active = _opened_trace_file(trace_log)
backup = _opened_trace_file(backup_log)
cursor_identity = (cursor.device, cursor.inode)
try:
if active is not None and active[1] == cursor_identity:
if _trace_cursor_prefix_matches(active, cursor):
return _read_trace_file_lines(
active,
offset=cursor.offset,
first_line_number=cursor.line_count + 1,
source=trace_log.name,
)
return _read_trace_file_lines(
active,
offset=0,
first_line_number=1,
source=trace_log.name,
)
lines: list[TraceLogLine] = []
if backup is not None and backup[1] == cursor_identity:
backup_offset = cursor.offset if _trace_cursor_prefix_matches(backup, cursor) else 0
lines.extend(_read_trace_file_lines(
backup,
offset=backup_offset,
first_line_number=cursor.line_count + 1 if backup_offset else 1,
source=backup_log.name,
))
if active is not None:
lines.extend(_read_trace_file_lines(
active,
offset=0,
first_line_number=1,
source=trace_log.name,
))
return lines
finally:
if active is not None:
active[0].close()
if backup is not None:
backup[0].close()
def read_new_traces(cursor: TraceCursor, trace_log: Path = TRACE_LOG) -> list[dict[str, Any]]:
traces: list[dict[str, Any]] = []
for line in _new_trace_lines(cursor, trace_log):
raw = line.text.strip()
if not raw:
continue
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
traces.append(parsed)
return traces
def read_all_traces() -> list[dict[str, Any]]:
if not TRACE_LOG.exists():
return []
traces: list[dict[str, Any]] = []
with TRACE_LOG.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
traces.append(json.loads(line))
except json.JSONDecodeError:
continue
return traces
def read_new_trace_diagnostics(
cursor: TraceCursor,
trace_log: Path = TRACE_LOG,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Return new QueryTracer rows plus any malformed JSONL evidence.
The general-purpose trace reader intentionally tolerates a damaged historical
line. The convergence acceptance step cannot: malformed frames are one of its
explicit zero-count gates, so it records line numbers and a bounded preview.
"""
traces: list[dict[str, Any]] = []
malformed: list[dict[str, Any]] = []
for line in _new_trace_lines(cursor, trace_log):
raw = line.text.strip()
if not raw:
continue
try:
parsed = json.loads(raw)
except json.JSONDecodeError as exc:
malformed.append(
{
"source": line.source,
"line": line.line_number,
"error": exc.msg,
"preview": raw[:400],
}
)
continue
if not isinstance(parsed, dict):
malformed.append(
{
"source": line.source,
"line": line.line_number,
"error": "top-level JSONL value is not an object",
"preview": raw[:400],
}
)
continue
traces.append(parsed)
return traces, malformed
def embedded_coordinator_payload(
action_response: dict[str, Any],
detail_key: str,
) -> dict[str, Any]:
"""Decode a runtime-control JSON string returned through the Swift bridge."""
if action_response.get("ok") is False:
raise ValueError(str(action_response.get("error") or action_response))
detail = action_response.get("result", {}).get("detail", {})
if not isinstance(detail, dict):
raise ValueError("automation action detail is not an object")
raw = detail.get(detail_key)
if isinstance(raw, dict):
payload = raw
elif isinstance(raw, str) and raw.strip():
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(
f"{detail_key} contains malformed coordinator JSON: {exc.msg}"
) from exc
else:
raise ValueError(f"automation action omitted {detail_key}")
if not isinstance(payload, dict):
raise ValueError(f"{detail_key} coordinator payload is not an object")
if payload.get("ok") is False:
raise ValueError(str(payload.get("error") or payload))
return payload
def coordinator_awareness_payload(action_response: dict[str, Any]) -> dict[str, Any]:
payload = embedded_coordinator_payload(action_response, "snapshot")
snapshot = payload.get("snapshot", payload)
if not isinstance(snapshot, dict):
raise ValueError("coordinator awareness snapshot is not an object")
if not isinstance(snapshot.get("ownerId"), str) or not snapshot.get("ownerId"):