Coverage for app / services / scenarios / __main__.py: 86%
50 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Run a scenario from a shell, as the page runs it (docs/guides/scenario-runs.md).
3 python -m app.services.scenarios run samples/scenarios/builtin-knowledge.json \\
4 --email you@example.com --out /workspace/.scenario-runs
6Inside svc-core's environment (its database and svc-ai reachable, svc-ai
7able to call a model). The run is recorded like one started from the page,
8as the person named, and its export written to ``--out``. A shell is
9already an administrator's, so neither the switch nor the role is asked.
10"""
12from __future__ import annotations
14import argparse
15import json
16import sys
17from pathlib import Path
20def main(argv: list[str] | None = None) -> int:
21 parser = argparse.ArgumentParser(prog="python -m app.services.scenarios")
22 commands = parser.add_subparsers(dest="command", required=True)
23 run = commands.add_parser("run", help="run a scenario file and export it")
24 run.add_argument("file", type=Path)
25 run.add_argument("--email", required=True, help="whose run it is")
26 run.add_argument("--out", type=Path, default=Path("."))
27 args = parser.parse_args(argv)
29 from app.db.postgres.engine import SessionLocal
30 from app.db.postgres.models import ScenarioRun, User
31 from app.services.scenarios import export, runner, schema
33 try:
34 scenario, _ = schema.load(json.loads(args.file.read_text()))
35 except (OSError, ValueError) as exc:
36 print(f"Cannot run {args.file}: {exc}", file=sys.stderr)
37 return 2
39 db = SessionLocal()
40 try:
41 users = db.query(User).filter(User.email == args.email).all()
42 if len(users) != 1:
43 print(
44 f"{len(users)} users have the email {args.email}; need exactly one.",
45 file=sys.stderr,
46 )
47 return 2
48 record = runner.start(db, users[0], scenario, submit=lambda _id: None)
49 run_id = record.id
50 except runner.RunInProgress as exc:
51 print(str(exc), file=sys.stderr)
52 return 2
53 finally:
54 db.close()
56 print(f"Running {scenario.name} ({scenario.turn_count} turns) as run {run_id}…")
57 runner.execute(run_id)
59 db = SessionLocal()
60 try:
61 record = db.get(ScenarioRun, run_id)
62 args.out.mkdir(parents=True, exist_ok=True)
63 path = args.out / export.filename(record.name, record.created_at)
64 path.write_text(json.dumps(record.results, indent=2, ensure_ascii=False))
65 summary = (record.results or {}).get("summary") or {}
66 print(f"{record.status}: {path}")
67 if record.error:
68 print(f" error: {record.error}")
69 print(
70 f" {summary.get('turns', 0)} turns {summary.get('by_status', {})}; "
71 f"checks {summary.get('checks_passed', 0)}/{summary.get('checks', 0)} "
72 f"passed; cost ${summary.get('cost_usd') or 0}"
73 )
74 return 0 if record.status == runner.Status.completed else 1
75 finally:
76 db.close()
79if __name__ == "__main__":
80 sys.exit(main())