EnergyVenom commited on
Commit
78f6825
·
verified ·
1 Parent(s): ec5a037

Live view on the runner, runs read their own areas, state in an OCI bucket (a196206)

Browse files
automation/remote_runner/server.py CHANGED
@@ -13,6 +13,7 @@ Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (d
13
  AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
14
  from __future__ import annotations
15
 
 
16
  import hmac
17
  import io
18
  import json
@@ -77,6 +78,18 @@ def _relativize(report: Path, run_dir: Path) -> None:
77
  report.write_text(json.dumps(data), encoding="utf-8")
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def start(body: dict) -> dict:
81
  ids = [str(i) for i in body.get("ids") or []]
82
  if not ids or not all(ID.match(i) for i in ids):
@@ -95,16 +108,27 @@ def start(body: dict) -> dict:
95
  jd = HOME / jid
96
  (jd / "drafts").mkdir(parents=True)
97
  (jd / "library").mkdir()
 
 
 
 
 
98
  for kind in ("drafts", "library"):
99
  for name, text in (body.get(kind) or {}).items():
100
  if not SPEC.match(name):
101
  raise ValueError(f"{kind}: {name!r} is not a spec file name")
102
- (jd / kind / name).write_text(str(text), encoding="utf-8")
103
  report = jd / "report.json"
104
  env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
105
  env.update(env_in)
106
  env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),
107
  "FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})
 
 
 
 
 
 
108
  for kind in ("drafts", "library"):
109
  key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"
110
  if any((jd / kind).glob("*.spec.ts")):
@@ -170,6 +194,28 @@ def start_screens(body: dict) -> dict:
170
  raise
171
 
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  def _lines(log: Path, since: int) -> tuple[list[str], int]:
174
  """The log's lines from `since` on (at most 200), and how many lines it has."""
175
  try:
@@ -266,12 +312,14 @@ class H(BaseHTTPRequestHandler):
266
  return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists()})
267
  if not self._auth():
268
  return
269
- m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle)?(?:\?since=(\d{1,7}))?", self.path)
270
  if not m:
271
  return self._send(404, {"error": "not found"})
272
  job = self._job(m.group(1))
273
  if not job:
274
  return
 
 
275
  if m.group(2):
276
  if job["state"] == "running":
277
  return self._send(409, {"error": "the attempt is still running"})
 
13
  AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
14
  from __future__ import annotations
15
 
16
+ import base64
17
  import hmac
18
  import io
19
  import json
 
78
  report.write_text(json.dumps(data), encoding="utf-8")
79
 
80
 
81
+ YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$")
82
+ _IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""")
83
+ _STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""")
84
+
85
+
86
+ def local_spec(text: str, steps_dir: Path) -> str:
87
+ """A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point to
88
+ this runner's, and a steps scenario reads its YAML from the job's steps folder."""
89
+ text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text)
90
+ return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text)
91
+
92
+
93
  def start(body: dict) -> dict:
94
  ids = [str(i) for i in body.get("ids") or []]
95
  if not ids or not all(ID.match(i) for i in ids):
 
108
  jd = HOME / jid
109
  (jd / "drafts").mkdir(parents=True)
110
  (jd / "library").mkdir()
111
+ (jd / "steps").mkdir()
112
+ for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here)
113
+ if not YAML_NAME.match(name):
114
+ raise ValueError(f"steps: {name!r} is not a scenario file name")
115
+ (jd / "steps" / name).write_text(str(text), encoding="utf-8")
116
  for kind in ("drafts", "library"):
117
  for name, text in (body.get(kind) or {}).items():
118
  if not SPEC.match(name):
119
  raise ValueError(f"{kind}: {name!r} is not a spec file name")
120
+ (jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")
121
  report = jd / "report.json"
122
  env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}
123
  env.update(env_in)
124
  env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),
125
  "FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})
126
+ live = body.get("live") or {}
127
+ for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):
128
+ env.pop(k, None)
129
+ if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here
130
+ (jd / "live").mkdir()
131
+ env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"})
132
  for kind in ("drafts", "library"):
133
  key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"
134
  if any((jd / kind).glob("*.spec.ts")):
 
194
  raise
195
 
196
 
197
+ def live_now(job: dict) -> dict:
198
+ """The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and the
199
+ hook's status. The hook never writes a sign-in screen (it masks pages with a password field)."""
200
+ d = job["dir"] / "live"
201
+ out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None}
202
+ if not d.is_dir():
203
+ return out
204
+ try:
205
+ out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8"))
206
+ except (OSError, ValueError):
207
+ pass
208
+ for key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")):
209
+ f = d / name
210
+ try:
211
+ if key == "frame":
212
+ out["frame_at"] = f.stat().st_mtime
213
+ out[key] = base64.b64encode(f.read_bytes()).decode()
214
+ except OSError:
215
+ pass
216
+ return out
217
+
218
+
219
  def _lines(log: Path, since: int) -> tuple[list[str], int]:
220
  """The log's lines from `since` on (at most 200), and how many lines it has."""
221
  try:
 
312
  return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists()})
313
  if not self._auth():
314
  return
315
+ m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path)
316
  if not m:
317
  return self._send(404, {"error": "not found"})
318
  job = self._job(m.group(1))
319
  if not job:
320
  return
321
+ if m.group(2) == "/live":
322
+ return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None})
323
  if m.group(2):
324
  if job["state"] == "running":
325
  return self._send(409, {"error": "the attempt is still running"})
coworker/__main__.py CHANGED
@@ -338,10 +338,10 @@ def cmd_state(a) -> int:
338
 
339
  from .graph.services import build_services
340
  from .platform import statesync
341
- from .platform import supabase as sb
342
  cfg = get_settings()
343
- if not (cfg.supabase_url and (os.getenv("SUPABASE_SERVICE_KEY"))) or not cfg.state_sync:
344
- print("state sync is off (SUPABASE_URL and SUPABASE_SERVICE_KEY are not both set)")
 
345
  return 0
346
  if a.action == "restore":
347
  if (cfg.home / "fpt.sqlite").exists():
@@ -351,19 +351,19 @@ def cmd_state(a) -> int:
351
  # the egress gate needs an audit log; while FPT_HOME is still empty it writes to a throwaway one
352
  with tempfile.TemporaryDirectory() as tmp:
353
  scratch = build_services(cfg.model_copy(update={"fpt_home": Path(tmp)}))
354
- client = sb.Supabase(cfg, scratch.egress, None)
355
  done, err = statesync.restore_at_boot(cfg, client)
356
  if err:
357
  print(f"state restore failed (saving to the bucket is paused until the next start): {err}")
358
  return 0 if a.soft else 1
359
- print("state restored from Supabase Storage" if done else "no saved state yet: starting empty")
360
  return 0
361
  svc = build_services(cfg)
362
  if a.action == "push":
363
  meta = statesync.push(svc, "manual")
364
  print(f"state saved: {meta['bytes']} bytes at {meta['saved_at']}")
365
  return 0
366
- raw = sb.of(svc).download(statesync.META)
367
  print(raw.decode() if raw else "no saved state yet")
368
  return 0
369
 
 
338
 
339
  from .graph.services import build_services
340
  from .platform import statesync
 
341
  cfg = get_settings()
342
+ from .platform.ocistore import par_url
343
+ if not ((cfg.supabase_url and os.getenv("SUPABASE_SERVICE_KEY")) or par_url()) or not cfg.state_sync:
344
+ print("state sync is off (set OCI_STATE_PAR_URL, or SUPABASE_URL and SUPABASE_SERVICE_KEY)")
345
  return 0
346
  if a.action == "restore":
347
  if (cfg.home / "fpt.sqlite").exists():
 
351
  # the egress gate needs an audit log; while FPT_HOME is still empty it writes to a throwaway one
352
  with tempfile.TemporaryDirectory() as tmp:
353
  scratch = build_services(cfg.model_copy(update={"fpt_home": Path(tmp)}))
354
+ client = statesync.store_for(cfg, scratch.egress, None)
355
  done, err = statesync.restore_at_boot(cfg, client)
356
  if err:
357
  print(f"state restore failed (saving to the bucket is paused until the next start): {err}")
358
  return 0 if a.soft else 1
359
+ print(f"state restored from {'the OCI bucket' if par_url() else 'Supabase Storage'}" if done else "no saved state yet: starting empty")
360
  return 0
361
  svc = build_services(cfg)
362
  if a.action == "push":
363
  meta = statesync.push(svc, "manual")
364
  print(f"state saved: {meta['bytes']} bytes at {meta['saved_at']}")
365
  return 0
366
+ raw = statesync.store_of(svc).download(statesync.META)
367
  print(raw.decode() if raw else "no saved state yet")
368
  return 0
369
 
coworker/adapters/remote_runner.py CHANGED
@@ -8,8 +8,10 @@ polled, and its bundle is unpacked where a local attempt would leave its files:
8
  ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged."""
9
  from __future__ import annotations
10
 
 
11
  import io
12
  import json
 
13
  import time
14
  import zipfile
15
  from pathlib import Path
@@ -30,6 +32,22 @@ def _specs(d: Path | None) -> dict[str, str]:
30
  return {p.name: p.read_text(encoding="utf-8") for p in Path(d).glob("*.spec.ts")}
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  def _absolutize(report: Path, run_dir: Path) -> None:
34
  data = json.loads(report.read_text(encoding="utf-8"))
35
 
@@ -138,9 +156,37 @@ def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dic
138
  return st.get("exit_code"), lines
139
 
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
142
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
143
- log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0) -> dict:
 
144
  from ..platform.cleanup import LEDGER
145
  from ..platform.failures import ExecutionError
146
  base = base_url.rstrip("/")
@@ -153,8 +199,18 @@ def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: l
153
  env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov)
154
  body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s,
155
  "drafts": _specs(drafts_dir), "library": _specs(library_dir)}
 
 
 
 
 
 
 
 
 
156
  r = egress.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body=body, headers=hdr,
157
- log_body={"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"])},
 
158
  timeout=60)
159
  if r.status_code != 202:
160
  raise RemoteRunnerError(f"the remote browser runner refused the attempt (HTTP {r.status_code}: {r.text[:200]})")
@@ -175,6 +231,8 @@ def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: l
175
  log_body=None, timeout=30).json()
176
  except Exception: # noqa: BLE001 - a dropped poll is tried again; the attempt keeps running on the runner
177
  st = {}
 
 
178
  if st.get("state") in ("done", "cancelled"):
179
  break
180
  if time.time() > deadline:
 
8
  ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged."""
9
  from __future__ import annotations
10
 
11
+ import base64
12
  import io
13
  import json
14
+ import re
15
  import time
16
  import zipfile
17
  from pathlib import Path
 
32
  return {p.name: p.read_text(encoding="utf-8") for p in Path(d).glob("*.spec.ts")}
33
 
34
 
35
+ _STEPS_ENTRY = re.compile(r"stepsTest\('([A-Za-z0-9][A-Za-z0-9._-]{0,80})',.*?dir:\s*(\"(?:[^\"\\]|\\.)*\")", re.S)
36
+
37
+
38
+ def _step_yamls(*spec_sets: dict[str, str]) -> dict[str, str]:
39
+ """The YAML of every steps scenario the specs run (stepsTest(id, tags, { dir })): the runner has no copy of this
40
+ server's staging folder or library, so the steps travel with the attempt."""
41
+ out: dict[str, str] = {}
42
+ for specs in spec_sets:
43
+ for text in specs.values():
44
+ for cid, d in _STEPS_ENTRY.findall(text):
45
+ f = Path(json.loads(d)) / f"{cid}.yaml"
46
+ if f.is_file():
47
+ out[f"{cid}.yaml"] = f.read_text(encoding="utf-8")
48
+ return out
49
+
50
+
51
  def _absolutize(report: Path, run_dir: Path) -> None:
52
  data = json.loads(report.read_text(encoding="utf-8"))
53
 
 
156
  return st.get("exit_code"), lines
157
 
158
 
159
+ def _write_atomic(d: Path, name: str, data: bytes) -> None:
160
+ tmp = d / f".{name}.remote.tmp"
161
+ try:
162
+ tmp.write_bytes(data)
163
+ tmp.replace(d / name)
164
+ except OSError: # a reader holding the file (Windows): this frame is skipped
165
+ tmp.unlink(missing_ok=True)
166
+
167
+
168
+ def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dict) -> None:
169
+ """Copy the runner's latest frame and status into this run's live folder (the Live panel reads it as for a local
170
+ attempt). Frames only: never stored with the evidence, never sent anywhere else."""
171
+ try:
172
+ v = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/live", allowed_base=base, headers=hdr,
173
+ log_body=None, timeout=20).json()
174
+ except Exception: # noqa: BLE001 - a missed frame is not an error
175
+ return
176
+ if v.get("status"):
177
+ _write_atomic(live_dir, "status.json", json.dumps(v["status"]).encode())
178
+ if v.get("frame") and v.get("frame_at") != seen.get("frame_at"):
179
+ seen["frame_at"] = v.get("frame_at")
180
+ _write_atomic(live_dir, "frame.jpg", base64.b64decode(v["frame"]))
181
+ if v.get("failed") and v["failed"] != seen.get("failed"):
182
+ seen["failed"] = v["failed"]
183
+ _write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"]))
184
+
185
+
186
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
187
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
188
+ log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0,
189
+ live_dir: Path | None = None, live_meta: dict | None = None) -> dict:
190
  from ..platform.cleanup import LEDGER
191
  from ..platform.failures import ExecutionError
192
  base = base_url.rstrip("/")
 
199
  env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov)
200
  body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s,
201
  "drafts": _specs(drafts_dir), "library": _specs(library_dir)}
202
+ body["steps"] = _step_yamls(body["drafts"], body["library"])
203
+ if live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the run
204
+ from ..platform import liveview
205
+ meta = {"attempt_key": f"{run_id}-a{attempt}", "attempt": attempt, "ids": ids, "all_ids": ids, "chunk": 0, "chunks": 1,
206
+ **(live_meta or {})}
207
+ liveview.prepare(Path(live_dir), meta)
208
+ body["live"] = {"attempt": meta["attempt_key"]}
209
+ poll_s = min(poll_s, 2.0)
210
+ seen: dict = {}
211
  r = egress.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body=body, headers=hdr,
212
+ log_body={"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"]),
213
+ "steps": len(body["steps"])},
214
  timeout=60)
215
  if r.status_code != 202:
216
  raise RemoteRunnerError(f"the remote browser runner refused the attempt (HTTP {r.status_code}: {r.text[:200]})")
 
231
  log_body=None, timeout=30).json()
232
  except Exception: # noqa: BLE001 - a dropped poll is tried again; the attempt keeps running on the runner
233
  st = {}
234
+ if live_dir and st.get("state") == "running":
235
+ _pull_live(egress, base, hdr, jid, Path(live_dir), seen)
236
  if st.get("state") in ("done", "cancelled"):
237
  break
238
  if time.time() > deadline:
coworker/graph/nodes/execute.py CHANGED
@@ -116,7 +116,8 @@ def run_planned(plan: dict, svc, **extra) -> dict:
116
  out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
117
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
118
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
119
- config=plan["config"], kill=lambda: svc.kill.check("executor.remote"))
 
120
  if plan["mode"] == "live" and not plan.get("config"):
121
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
122
  if plan.get("config"):
 
116
  out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
117
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
118
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
119
+ config=plan["config"], kill=lambda: svc.kill.check("executor.remote"),
120
+ live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None)
121
  if plan["mode"] == "live" and not plan.get("config"):
122
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
123
  if plan.get("config"):
coworker/graph/nodes/research.py CHANGED
@@ -79,7 +79,7 @@ def scout(state, config, svc) -> dict:
79
  roles: set[str] = set()
80
  found = None
81
  if getattr(pod, "kind", "") == "fusion":
82
- found = _discover(svc, run_id, pod)
83
  status = {a["code"]: a for a in found["areas"]}
84
  for m in pod.modules():
85
  if found is not None: # a Fusion pod: keep the areas discovery found on it, with their real record counts
@@ -150,9 +150,10 @@ def identifying_values(test_data: dict) -> list[str]:
150
  for v in (vals if isinstance(vals, list) else [vals]) if v and str(v).strip().lower() not in FLAG_WORDS})
151
 
152
 
153
- def _discover(svc, run_id: str, pod) -> dict:
154
  """Discovery on the run's Fusion pod (platform/discovery.py), saved on the pod so the next run and the Test
155
- environments page see the same areas and test data."""
 
156
  from ...platform import discovery, fusion_catalog
157
  from ...platform.pods import PodRegistry
158
  try:
@@ -161,7 +162,7 @@ def _discover(svc, run_id: str, pod) -> dict:
161
  raise FatalNodeError(f"{e}: check the test user on the Test environments page") from e
162
  pid = svc.fusion_pod_id(run_id)
163
  if pid is not None:
164
- PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).save_discovery(pid, found, "scout")
165
  used = discovery.in_use(found)
166
  svc.db.add_event(run_id, "scout", "message", {"message": f"Discovered on the pod: {', '.join(used) if used else 'no business area in use'}"
167
  f" ({len(found['areas'])} areas checked)."})
 
79
  roles: set[str] = set()
80
  found = None
81
  if getattr(pod, "kind", "") == "fusion":
82
+ found = _discover(svc, run_id, pod, state.get("modules"))
83
  status = {a["code"]: a for a in found["areas"]}
84
  for m in pod.modules():
85
  if found is not None: # a Fusion pod: keep the areas discovery found on it, with their real record counts
 
150
  for v in (vals if isinstance(vals, list) else [vals]) if v and str(v).strip().lower() not in FLAG_WORDS})
151
 
152
 
153
+ def _discover(svc, run_id: str, pod, areas: list[str] | None = None) -> dict:
154
  """Discovery on the run's Fusion pod (platform/discovery.py), saved on the pod so the next run and the Test
155
+ environments page see the same areas and test data. Only the run's own `areas` get their screens read
156
+ in the background."""
157
  from ...platform import discovery, fusion_catalog
158
  from ...platform.pods import PodRegistry
159
  try:
 
162
  raise FatalNodeError(f"{e}: check the test user on the Test environments page") from e
163
  pid = svc.fusion_pod_id(run_id)
164
  if pid is not None:
165
+ PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).save_discovery(pid, found, "scout", read_areas=areas or None)
166
  used = discovery.in_use(found)
167
  svc.db.add_event(run_id, "scout", "message", {"message": f"Discovered on the pod: {', '.join(used) if used else 'no business area in use'}"
168
  f" ({len(found['areas'])} areas checked)."})
coworker/platform/ocistore.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Oracle Cloud Object Storage as the place the encrypted state archive is kept (platform/statesync.py), instead of
2
+ Supabase Storage. Always Free on any OCI account (20 GB, 50,000 requests a month).
3
+
4
+ Configured by one secret, OCI_STATE_PAR_URL: a pre-authenticated request on one private bucket (access "read and write
5
+ objects", listing denied), e.g. https://objectstorage.<region>.oraclecloud.com/p/<token>/n/<namespace>/b/<bucket>/o/.
6
+ No account key leaves the operator's machine. The address itself grants access, so it is read from the environment or
7
+ the vault only, and the audit log records it with the token replaced by ***. The archive is encrypted before it leaves
8
+ (statesync: Fernet, FPT_STATE_KEY), so the bucket only ever holds ciphertext."""
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ from urllib.parse import quote, urlparse
14
+
15
+ from .supabase import SupabaseError
16
+
17
+ PAR = re.compile(r"^https://objectstorage\.[a-z0-9-]+\.oraclecloud\.com/p/[^/]+/n/[^/]+/b/[^/]+/o/?$")
18
+
19
+
20
+ def par_url(vault=None) -> str:
21
+ """The configured pre-authenticated address (with a trailing /), or ""."""
22
+ raw = (os.getenv("OCI_STATE_PAR_URL") or (vault.get("OCI_STATE_PAR_URL") if vault else None) or "").strip()
23
+ if not raw:
24
+ return ""
25
+ raw = raw if raw.endswith("/") else raw + "/"
26
+ return raw if PAR.match(raw) else ""
27
+
28
+
29
+ class OciParStore:
30
+ """The storage half of platform/supabase.Supabase (ensure_bucket, upload, download, remove), on an OCI bucket."""
31
+ kind = "oci"
32
+
33
+ def __init__(self, cfg, egress, vault):
34
+ self.cfg, self.egress, self.vault = cfg, egress, vault
35
+ self.url = par_url(vault)
36
+ u = urlparse(self.url)
37
+ self.base = f"{u.scheme}://{u.netloc}" if self.url else ""
38
+ self.shown = re.sub(r"/p/[^/]+/", "/p/***/", self.url) # what the audit log sees
39
+
40
+ @property
41
+ def storage_enabled(self) -> bool:
42
+ return bool(self.url)
43
+
44
+ def service_key(self) -> str | None: # no service key here: the archive key is FPT_STATE_KEY (statesync._fernet)
45
+ return None
46
+
47
+ def _call(self, method: str, path: str, *, content: bytes | None = None, action: str, timeout: float = 120.0):
48
+ if not self.url:
49
+ raise SupabaseError("STORAGE", "OCI_STATE_PAR_URL is not set", 500)
50
+ p = quote(path, safe="/")
51
+ return self.egress.service_request("oci_storage", method, self.url + p, allowed_base=self.base, content=content,
52
+ headers={"Content-Type": "application/octet-stream"} if content is not None else None,
53
+ log_body={"action": action, "path": path, **({"bytes": len(content)} if content is not None else {})},
54
+ log_url=self.shown + p, timeout=timeout)
55
+
56
+ def ensure_bucket(self) -> None: # the bucket exists: a pre-authenticated request is made on it
57
+ return None
58
+
59
+ def upload(self, path: str, data: bytes) -> None:
60
+ r = self._call("PUT", path, content=data, action="upload")
61
+ if r.status_code >= 400:
62
+ raise SupabaseError("STORAGE", f"upload to the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
63
+
64
+ def download(self, path: str) -> bytes | None:
65
+ r = self._call("GET", path, action="download")
66
+ if r.status_code == 404:
67
+ return None # nothing saved yet; any other error is an error, never "empty" (an empty start would overwrite the backup)
68
+ if r.status_code >= 400:
69
+ raise SupabaseError("STORAGE", f"download from the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
70
+ return r.content
71
+
72
+ def remove(self, path: str) -> None:
73
+ r = self._call("DELETE", path, action="remove")
74
+ if r.status_code >= 400 and r.status_code != 404:
75
+ raise SupabaseError("STORAGE", f"remove from the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
coworker/platform/pods.py CHANGED
@@ -388,14 +388,16 @@ class PodRegistry:
388
  raise PodError("SIGN_IN_REFUSED", f"{e}. Check the test user on this page.", 409) from e
389
  return self.save_discovery(pod_id, found, actor)
390
 
391
- def save_discovery(self, pod_id: int, found: dict, actor: str) -> dict:
 
 
392
  used = discovery.in_use(found)
393
  self.db.update("pods", "id", pod_id, discovery=json.dumps({"areas": found["areas"]}), discovered_at=found["discovered_at"],
394
  test_data=json.dumps(found.get("test_data") or {}), modules=json.dumps(used), updated_at=now_iso())
395
  self.audit.append("pod.discovered", actor=actor, summary=f"pod {pod_id}: {', '.join(used) or 'no business area in use'}",
396
  payload={"pod_id": pod_id, "areas": {a["code"]: a["status"] for a in found["areas"]},
397
  "test_data_keys": {k: sorted(v) for k, v in (found.get("test_data") or {}).items()}})
398
- self.read_in_background(pod_id, actor) # the areas just found: their screens are read before any run needs them
399
  return self.get(pod_id)
400
 
401
  def set_test_data(self, pod_id: int, overrides: dict, actor: str) -> dict:
 
388
  raise PodError("SIGN_IN_REFUSED", f"{e}. Check the test user on this page.", 409) from e
389
  return self.save_discovery(pod_id, found, actor)
390
 
391
+ def save_discovery(self, pod_id: int, found: dict, actor: str, read_areas: list[str] | None = None) -> dict:
392
+ """Save what discovery found, then read in the background the screens of `read_areas` (a run: the areas it tests,
393
+ so it does not wait for areas it never uses), or of every area in use."""
394
  used = discovery.in_use(found)
395
  self.db.update("pods", "id", pod_id, discovery=json.dumps({"areas": found["areas"]}), discovered_at=found["discovered_at"],
396
  test_data=json.dumps(found.get("test_data") or {}), modules=json.dumps(used), updated_at=now_iso())
397
  self.audit.append("pod.discovered", actor=actor, summary=f"pod {pod_id}: {', '.join(used) or 'no business area in use'}",
398
  payload={"pod_id": pod_id, "areas": {a["code"]: a["status"] for a in found["areas"]},
399
  "test_data_keys": {k: sorted(v) for k, v in (found.get("test_data") or {}).items()}})
400
+ self.read_in_background(pod_id, actor, read_areas) # their screens are read before a run needs them
401
  return self.get(pod_id)
402
 
403
  def set_test_data(self, pod_id: int, overrides: dict, actor: str) -> dict:
coworker/platform/statesync.py CHANGED
@@ -1,4 +1,5 @@
1
- """Keep the application's data in Supabase Storage so a restart does not lose it.
 
2
 
3
  The product stores its state under FPT_HOME (SQLite database, secrets vault, reports, encrypted evidence, tickets).
4
  On hosts without a persistent disk that folder is empty after every restart. This module saves an encrypted archive
@@ -48,8 +49,22 @@ def _fernet(client: sb.Supabase) -> Fernet:
48
  return Fernet(base64.urlsafe_b64encode(hashlib.sha256(secret.encode()).digest()))
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def enabled(svc) -> bool:
52
- return bool(svc.cfg.state_sync) and sb.of(svc).storage_enabled
53
 
54
 
55
  def signature(svc) -> str:
@@ -103,7 +118,7 @@ def restore_failed(home: Path | str) -> bool:
103
 
104
 
105
  def push(svc, reason: str = "changed") -> dict:
106
- client = sb.of(svc)
107
  home = svc.cfg.home
108
  if restore_failed(home):
109
  # Starting empty because the saved state could not be read must never replace that saved state with nothing.
@@ -200,7 +215,9 @@ class Syncer:
200
  """Background saver for the API process: checks for changes every few seconds and saves when there are any."""
201
 
202
  def __init__(self, svc, interval_s: int):
203
- self.svc, self.interval = svc, max(10, int(interval_s))
 
 
204
  self._stop = threading.Event()
205
  self._thread: threading.Thread | None = None
206
  self.last_error: str | None = None
 
1
+ """Keep the application's data in Supabase Storage, or an OCI Object Storage bucket (platform/ocistore.py, when
2
+ OCI_STATE_PAR_URL is set), so a restart does not lose it.
3
 
4
  The product stores its state under FPT_HOME (SQLite database, secrets vault, reports, encrypted evidence, tickets).
5
  On hosts without a persistent disk that folder is empty after every restart. This module saves an encrypted archive
 
49
  return Fernet(base64.urlsafe_b64encode(hashlib.sha256(secret.encode()).digest()))
50
 
51
 
52
+ def store_for(cfg, egress, vault):
53
+ """Where the archive is kept: the OCI bucket when OCI_STATE_PAR_URL is set, else Supabase Storage."""
54
+ from .ocistore import OciParStore, par_url
55
+ return OciParStore(cfg, egress, vault) if par_url(vault) else sb.Supabase(cfg, egress, vault)
56
+
57
+
58
+ def store_of(svc):
59
+ s = svc.extra.get("state_store")
60
+ if s is None:
61
+ from .ocistore import par_url
62
+ s = svc.extra["state_store"] = store_for(svc.cfg, svc.egress, svc.vault) if par_url(svc.vault) else sb.of(svc)
63
+ return s
64
+
65
+
66
  def enabled(svc) -> bool:
67
+ return bool(svc.cfg.state_sync) and store_of(svc).storage_enabled
68
 
69
 
70
  def signature(svc) -> str:
 
118
 
119
 
120
  def push(svc, reason: str = "changed") -> dict:
121
+ client = store_of(svc)
122
  home = svc.cfg.home
123
  if restore_failed(home):
124
  # Starting empty because the saved state could not be read must never replace that saved state with nothing.
 
215
  """Background saver for the API process: checks for changes every few seconds and saves when there are any."""
216
 
217
  def __init__(self, svc, interval_s: int):
218
+ # an OCI bucket counts requests (Always Free: 50,000 a month): at most one save every 5 minutes there
219
+ floor = 300 if getattr(store_of(svc), "kind", "") == "oci" else 10
220
+ self.svc, self.interval = svc, max(floor, int(interval_s))
221
  self._stop = threading.Event()
222
  self._thread: threading.Thread | None = None
223
  self.last_error: str | None = None
coworker/tests/test_ocistore.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The state archive kept in an OCI Object Storage bucket through a pre-authenticated request (platform/ocistore.py),
2
+ against a simulated bucket: it is encrypted, round-trips into an empty home, the address's token never reaches the audit
3
+ log, a missing object is "nothing saved yet", and the saver keeps under the Always Free request allowance."""
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import sqlite3
8
+ import tempfile
9
+ import unittest
10
+ from pathlib import Path
11
+
12
+ import httpx
13
+
14
+ from coworker.graph.services import build_services
15
+ from coworker.platform import ocistore, statesync
16
+ from coworker.tests.fakes import PASSWORD, temp_settings
17
+
18
+ HOST = "objectstorage.ap-hyderabad-1.oraclecloud.com"
19
+ TOKEN = "SecretParToken-do-not-leak"
20
+ PAR_URL = f"https://{HOST}/p/{TOKEN}/n/axns/b/patchwise-state/o/"
21
+
22
+
23
+ class FakeBucket:
24
+ def __init__(self):
25
+ self.objects, self.seen = {}, []
26
+
27
+ def handler(self, req: httpx.Request) -> httpx.Response:
28
+ self.seen.append(req)
29
+ prefix = f"/p/{TOKEN}/n/axns/b/patchwise-state/o/"
30
+ if req.url.host != HOST or not req.url.path.startswith(prefix):
31
+ return httpx.Response(404, json={"code": "NotAuthorizedOrNotFound"})
32
+ name = req.url.path[len(prefix):]
33
+ if req.method == "PUT":
34
+ self.objects[name] = req.content
35
+ return httpx.Response(200)
36
+ if req.method == "DELETE":
37
+ return httpx.Response(204 if self.objects.pop(name, None) is not None else 404)
38
+ if name in self.objects:
39
+ return httpx.Response(200, content=self.objects[name])
40
+ return httpx.Response(404, json={"code": "ObjectNotFound"})
41
+
42
+
43
+ def make(bucket: FakeBucket):
44
+ cfg = temp_settings()
45
+ svc = build_services(cfg, transport=httpx.MockTransport(bucket.handler))
46
+ svc.users.create("admin", PASSWORD, "admin", created_by="test")
47
+ return svc
48
+
49
+
50
+ class TestOciStateStore(unittest.TestCase):
51
+ def setUp(self):
52
+ self._env = {k: os.environ.get(k) for k in ("OCI_STATE_PAR_URL", "FPT_STATE_KEY", "SUPABASE_SERVICE_KEY")}
53
+ os.environ["OCI_STATE_PAR_URL"] = PAR_URL
54
+ os.environ["FPT_STATE_KEY"] = "a-state-key-for-the-test"
55
+ os.environ.pop("SUPABASE_SERVICE_KEY", None)
56
+
57
+ def tearDown(self):
58
+ for k, v in self._env.items():
59
+ os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v)
60
+
61
+ def test_the_archive_is_encrypted_in_the_bucket_and_restores_into_an_empty_home(self):
62
+ bucket = FakeBucket()
63
+ svc = make(bucket)
64
+ self.assertTrue(statesync.enabled(svc))
65
+ self.assertEqual(statesync.store_of(svc).kind, "oci")
66
+ (svc.cfg.home / "screens").mkdir(parents=True, exist_ok=True)
67
+ (svc.cfg.home / "screens" / "po-manage-orders.json").write_text('{"task": "PO > Manage Orders"}', encoding="utf-8")
68
+ meta = statesync.push(svc, "test")
69
+ blob = bucket.objects[statesync.OBJECT]
70
+ self.assertEqual(len(blob), meta["bytes"])
71
+ for plain in (b"SQLite format 3", b"PO > Manage Orders"):
72
+ self.assertNotIn(plain, blob) # only ciphertext leaves
73
+ fresh = Path(tempfile.mkdtemp(prefix="fpt-oci-restore-"))
74
+ cfg2 = svc.cfg.model_copy(update={"fpt_home": fresh})
75
+ self.assertTrue(statesync.restore(cfg2, statesync.store_for(cfg2, svc.egress, None)))
76
+ self.assertEqual((fresh / "screens" / "po-manage-orders.json").read_text(encoding="utf-8"), '{"task": "PO > Manage Orders"}')
77
+ with sqlite3.connect(str(fresh / "fpt.sqlite")) as db:
78
+ self.assertEqual(db.execute("SELECT role FROM users WHERE username='admin'").fetchone()[0], "admin")
79
+ import json
80
+ audit = json.dumps(svc.audit.query(kind="egress.oci_storage.request", limit=50), default=str)
81
+ self.assertIn("/p/***/", audit)
82
+ self.assertNotIn(TOKEN, audit) # the address's token is never logged
83
+
84
+ def test_nothing_saved_yet_is_empty_and_saves_are_spaced_for_the_free_allowance(self):
85
+ bucket = FakeBucket()
86
+ svc = make(bucket)
87
+ self.assertIsNone(statesync.store_of(svc).download(statesync.OBJECT))
88
+ self.assertEqual(statesync.Syncer(svc, 60).interval, 300)
89
+ self.assertEqual(statesync.Syncer(svc, 900).interval, 900)
90
+
91
+ def test_a_malformed_address_is_not_used(self):
92
+ os.environ["OCI_STATE_PAR_URL"] = "https://evil.example/p/x/n/y/b/z/o/"
93
+ self.assertEqual(ocistore.par_url(), "")
94
+ os.environ["OCI_STATE_PAR_URL"] = PAR_URL.rstrip("/")
95
+ self.assertEqual(ocistore.par_url(), PAR_URL)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ unittest.main()
coworker/tests/test_remote_screens.py CHANGED
@@ -97,6 +97,84 @@ class TestRemoteScreens(unittest.TestCase):
97
  self.assertIsNone(R.runner_for(svc))
98
 
99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  class TestRunnerScreenJobs(unittest.TestCase):
101
  def test_screen_jobs_are_checked(self):
102
  S = load_server()
 
97
  self.assertIsNone(R.runner_for(svc))
98
 
99
 
100
+ class TestStepsScenariosTravel(unittest.TestCase):
101
+ """AI-written scenarios are steps YAML behind a small spec that imports the server's step runner by its absolute path:
102
+ the runner gets the YAML with the attempt and runs the spec against its own automation folder."""
103
+
104
+ def test_the_yaml_travels_and_the_spec_is_made_local(self):
105
+ from coworker.platform.step_writer import staged_entry_spec
106
+ with tempfile.TemporaryDirectory() as d:
107
+ ydir = Path(d) / "staging folder"
108
+ ydir.mkdir()
109
+ (ydir / "PO-FUS-101.yaml").write_text("id: PO-FUS-101\nrunner: steps\n")
110
+ spec = staged_entry_spec("PO-FUS-101", "P1", ydir)
111
+ self.assertEqual(R._step_yamls({"PO-FUS-101.spec.ts": spec}, {}), {"PO-FUS-101.yaml": "id: PO-FUS-101\nrunner: steps\n"})
112
+ S = load_server()
113
+ local = S.local_spec(spec, Path("/home/ubuntu/runner-data/job_x/steps"))
114
+ self.assertIn(f'from "{(S.AUTOMATION / "src").as_posix()}/fusion/steps"', local)
115
+ self.assertIn('dir: "/home/ubuntu/runner-data/job_x/steps"', local)
116
+ code = "\n".join(line for line in local.splitlines() if not line.startswith("//")) # the header comment may name it
117
+ self.assertNotIn(ydir.as_posix(), code)
118
+ fixtures = 'import { test, expect } from "/app/automation/src/fixtures";\n'
119
+ self.assertIn(f'"{(S.AUTOMATION / "src").as_posix()}/fixtures"', S.local_spec(fixtures, Path("/x")))
120
+
121
+ def test_bad_scenario_file_names_are_refused(self):
122
+ S = load_server()
123
+ self.assertIsNone(S.YAML_NAME.match("../../etc/passwd.yaml"))
124
+ self.assertIsNotNone(S.YAML_NAME.match("PO-FUS-101.yaml"))
125
+
126
+
127
+ class LiveEgress:
128
+ """A runner whose attempt runs for two polls, showing a frame, then finishes with a report."""
129
+
130
+ def __init__(self):
131
+ self.calls, self.polls = [], 0
132
+
133
+ def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
134
+ import base64 as b64
135
+ self.calls.append({"method": method, "url": url, "body": json_body})
136
+ if method == "POST":
137
+ return httpx.Response(202, json={"id": "job_0123456789ab", "state": "running"})
138
+ if url.endswith("/live"):
139
+ return httpx.Response(200, json={"status": {"scenario_id": "PO-FUS-101", "status": "running", "action": "Click Search"},
140
+ "frame": b64.b64encode(b"jpeg-1").decode(), "failed": None, "frame_at": 1.0})
141
+ if url.endswith("/bundle"):
142
+ buf = io.BytesIO()
143
+ with zipfile.ZipFile(buf, "w") as z:
144
+ z.writestr("report.json", json.dumps({"suites": []}))
145
+ return httpx.Response(200, content=buf.getvalue())
146
+ self.polls += 1
147
+ return httpx.Response(200, json={"state": "done" if self.polls > 2 else "running", "exit_code": 0})
148
+
149
+
150
+ class TestRemoteLiveView(unittest.TestCase):
151
+ def test_the_runners_frames_reach_the_live_panel(self):
152
+ eg = LiveEgress()
153
+ with tempfile.TemporaryDirectory() as d:
154
+ d, live = Path(d), Path(d) / "live"
155
+ R.run_attempt_remote(eg, "https://runner.example", "tok", run_id="r9", ids=["PO-FUS-101"], attempt=0, out_file=d / "attempt-0.json",
156
+ cred_env={}, drafts_dir=None, library_dir=None, overrides_file=None, log_dir=d,
157
+ config="playwright.fusion.config.ts", poll_s=0.01, live_dir=live)
158
+ self.assertEqual(eg.calls[0]["body"]["live"], {"attempt": "r9-a0"})
159
+ self.assertEqual((live / "frame.jpg").read_bytes(), b"jpeg-1")
160
+ self.assertEqual(json.loads((live / "status.json").read_text())["action"], "Click Search")
161
+ self.assertEqual(json.loads((live / "plan.json").read_text())["attempt_key"], "r9-a0")
162
+ self.assertEqual(sum(1 for c in eg.calls if c["url"].endswith("/live")), 2) # only while it runs
163
+ import shutil
164
+ shutil.rmtree(R.AUTOMATION / "results" / "runs" / "fpt-r9-a0", ignore_errors=True)
165
+
166
+ def test_without_live_view_nothing_is_asked(self):
167
+ eg = LiveEgress()
168
+ with tempfile.TemporaryDirectory() as d:
169
+ R.run_attempt_remote(eg, "https://runner.example", "tok", run_id="r8", ids=["PO-FUS-101"], attempt=0, out_file=Path(d) / "a.json",
170
+ cred_env={}, drafts_dir=None, library_dir=None, overrides_file=None, log_dir=Path(d),
171
+ config="playwright.fusion.config.ts", poll_s=0.01)
172
+ self.assertNotIn("live", eg.calls[0]["body"])
173
+ self.assertFalse(any(c["url"].endswith("/live") for c in eg.calls))
174
+ import shutil
175
+ shutil.rmtree(R.AUTOMATION / "results" / "runs" / "fpt-r8-a0", ignore_errors=True)
176
+
177
+
178
  class TestRunnerScreenJobs(unittest.TestCase):
179
  def test_screen_jobs_are_checked(self):
180
  S = load_server()