forked from forthfate/openorbit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.py
More file actions
3312 lines (3085 loc) · 157 KB
/
Copy pathstore.py
File metadata and controls
3312 lines (3085 loc) · 157 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
from __future__ import annotations
import base64
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time
import uuid
from copy import deepcopy
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
import requests
import yaml
from orbit import load_bundle
from .models import Run, Step, Workflow
from .observability import configure_telemetry
from .providers import AzureOpenAIProvider, BedrockProvider, ModelSettings
from .remote import RemoteInvocation
ROOT = Path(__file__).resolve().parents[2]
def _application_data_dir() -> Path:
"""Return Orbit's writable per-user state directory on every platform."""
override = os.environ.get("ORBIT_APP_DATA")
if override:
return Path(override).expanduser()
if os.name == "nt":
return Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "Orbit"
if sys.platform == "darwin":
return Path.home() / "Library" / "Application Support" / "Orbit"
return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "orbit"
APP_DATA = _application_data_dir()
CONFIG = APP_DATA / "config"
TARGET_TEST_CASE_SETS = CONFIG / "target-ai-test-case-sets.yaml"
EXECUTION_ENVIRONMENTS = CONFIG / "execution-environments.yaml"
TARGET_ENVIRONMENTS = CONFIG / "target-environments.yaml"
CYCLE_INTERVENTIONS = CONFIG / "cycle-interventions.yaml"
DEFAULT_OPERATIONAL_MANAGER_PROMPT = """You are an approval-first operations manager for recurring AI evaluations.
Preserve the task safety boundary, collect observable evidence, and never
claim success without stated acceptance evidence. Escalate required approvals
and stop immediately when an emergency stop is requested.
__ORBIT_MANAGER_AI_PROMPT__
Your final response must be exactly one JSON object:
{
\"evaluation\": {\"score\":\"number from 0 to 10\",\"approval\":\"approved|rejected|pending\",\"summary\":\"string\"},
\"improvements\": [{\"title\":\"string\",\"status\":\"proposed|adopted|rejected\",\"rationale\":\"string\",\"acceptanceEvidence\":\"string\"}],
\"reported_issues\": [{\"title\":\"string\",\"severity\":\"low|medium|high|critical\",\"evidence\":\"string\",\"reproduction\":\"string\",\"status\":\"open|acknowledged|resolved\"}]
}
Always include both keys, using empty arrays when there are no items."""
MANAGER_PROMPT_SLOT = "__ORBIT_MANAGER_AI_PROMPT__"
NATIVE_IMPROVEMENT_CYCLE_TEMPLATE = r"""# Requirements
# - PROJECT_ROOT is a Git repository.
# - The evaluation build selects fixed browser test cases, a browser base URL,
# and, when this native runner is selected, a readable managed_prompt_path
# configured on its Target Environment.
# - Only supervisor feedback explicitly marked adopted is applied to the prompt.
# This runner never commits target changes; ctx.update_file keeps rollback versions.
import hashlib
import json
import re
from orbit_sdk import runner
REQUIRED_SUFFICIENT_EVALUATIONS = 3
# Marker comments make replacement idempotent and preserve the surrounding
# target prompt content that OpenOrbit does not own.
PROMPT_BLOCK_START = "<!-- OPENORBIT_ACCEPTED_PROPOSALS_START -->"
PROMPT_BLOCK_END = "<!-- OPENORBIT_ACCEPTED_PROPOSALS_END -->"
def state_path(ctx):
'''Return the per-build state file outside the target repository.'''
build_id = re.sub(r"[^a-zA-Z0-9_-]+", "-", str(ctx.evaluation_build.get("id") or "manual"))
directory = ctx.app_data / "improvement-cycles"
directory.mkdir(parents=True, exist_ok=True)
return directory / f"{build_id}.json"
def load_state(ctx):
'''Load the previous verdict state, or start a fresh candidate baseline.'''
path = state_path(ctx)
if not path.exists():
return {"candidate_fingerprint": None, "sufficient_evaluations": 0, "history": []}
return json.loads(path.read_text(encoding="utf-8"))
def save_state(ctx, state):
'''Persist only bounded history so recurring evaluations do not grow unbounded.'''
state["history"] = state.get("history", [])[-24:]
state_path(ctx).write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
def git(ctx, *args):
'''Run Git in the configured project root without invoking a shell.'''
return ctx.exec(["git", *args], cwd=ctx.project_root, timeout=300)
def candidate(ctx):
'''Fingerprint the current working-tree diff and retain its changed paths.'''
patch = git(ctx, "diff", "--binary", "--")
changed = [line for line in git(ctx, "diff", "--name-only").splitlines() if line]
return (hashlib.sha256(patch.encode("utf-8")).hexdigest() if patch else None), changed
def update_prompt_from_accepted_proposals(ctx, proposals):
'''Replace only OpenOrbit's managed prompt block and retain a rollback version.'''
prompt_path = str(ctx.evaluation_build.get("managed_prompt_path") or ctx.evaluation_build.get("prompt_bundle") or "").strip()
if not prompt_path:
raise ValueError("native improvement cycle requires target_environment.managed_prompt_path")
target = ctx.project_path(prompt_path)
current = target.read_text(encoding="utf-8")
lines = ["## Accepted improvement proposals", "", f"Iteration: {ctx.loop_index}", ""]
for proposal in proposals:
lines.extend(
(
f"### {proposal.get('title') or 'Accepted proposal'}",
str(proposal.get("rationale") or ""),
f"Acceptance evidence: {proposal.get('acceptanceEvidence') or ''}",
"",
)
)
block = "\n".join((PROMPT_BLOCK_START, "\n".join(lines).rstrip(), PROMPT_BLOCK_END))
start, end = current.find(PROMPT_BLOCK_START), current.find(PROMPT_BLOCK_END)
if start >= 0 and end > start:
updated = current[:start] + block + current[end + len(PROMPT_BLOCK_END) :]
elif start >= 0 or end >= 0:
raise ValueError("prompt has an incomplete OpenOrbit accepted-proposals block")
else:
updated = current.rstrip() + "\n\n" + block + "\n"
return ctx.update_file(prompt_path, updated)
@runner.phase("init")
def init(ctx):
# Process-level validation runs once before the iteration loop begins.
git(ctx, "rev-parse", "--show-toplevel")
if not ctx.evaluation_build.get("browser_base_url") or not ctx.test_cases:
raise ValueError("Select a browser base URL and fixed test cases for a native improvement cycle")
ctx.log("Validated an OpenOrbit-native prompt improvement cycle")
@runner.phase("setup")
def setup(ctx):
# Apply the latest accepted supervisor feedback before the next validation.
feedback = ctx.previous_supervisor_feedback
accepted = [
proposal for proposal in feedback.get("improvements", [])
if isinstance(proposal, dict) and str(proposal.get("status") or "").lower() in {"adopted", "accepted"}
]
prompt_update = update_prompt_from_accepted_proposals(ctx, accepted)
fingerprint, changed = candidate(ctx)
ctx.emit_result(
{
"improvement_cycle": {
"iteration": ctx.loop_index,
"candidate_fingerprint": fingerprint,
"changed_paths": changed,
"prompt_update": prompt_update,
}
}
)
ctx.log("Refreshed the rollback-protected prompt from accepted supervisor feedback")
@runner.phase("run")
def run(ctx):
# Browser evidence is the acceptance input; no target change is made here.
evidence = ctx.playwright_journey()
results = evidence["results"]
passed = all(item["passed"] for item in results)
fingerprint, changed = candidate(ctx)
ctx.emit_result(
{
"improvement_cycle": {
"iteration": ctx.loop_index,
"candidate_fingerprint": fingerprint,
"changed_paths": changed,
"passed": passed,
"evidence": evidence,
}
}
)
if not passed:
raise SystemExit("A fixed validation journey failed")
@runner.phase("eval")
def evaluate(ctx):
# Promote a candidate only after the required number of stable evaluations.
state = load_state(ctx)
fingerprint, changed = candidate(ctx)
if not fingerprint:
state["candidate_fingerprint"] = None
state["sufficient_evaluations"] = 0
verdict = "no_candidate"
elif state.get("candidate_fingerprint") == fingerprint:
state["sufficient_evaluations"] = int(state.get("sufficient_evaluations", 0)) + 1
verdict = "ready_for_approval" if state["sufficient_evaluations"] >= REQUIRED_SUFFICIENT_EVALUATIONS else "continue_validation"
else:
state["candidate_fingerprint"] = fingerprint
state["sufficient_evaluations"] = 1
verdict = "continue_validation"
state.setdefault("history", []).append(
{"iteration": ctx.loop_index, "fingerprint": fingerprint, "paths": changed, "verdict": verdict}
)
save_state(ctx, state)
ctx.emit_result(
{
"improvement_cycle": {
"candidate_fingerprint": fingerprint,
"changed_paths": changed,
"sufficient_evaluations": state["sufficient_evaluations"],
"required_evaluations": REQUIRED_SUFFICIENT_EVALUATIONS,
"verdict": verdict,
}
}
)
ctx.log(f"Candidate verdict: {verdict}")
@runner.phase("teardown")
def teardown(ctx):
# Per-iteration evidence remains available for supervisor review.
ctx.log("Retained prompt versions, decisions, and validation evidence")
@runner.phase("finalize")
def finalize(ctx):
# Process-level finalization intentionally leaves the target repository uncommitted.
ctx.log("Finalized the native improvement cycle without committing changes")
if __name__ == "__main__":
runner.main()
"""
JSON_AGENT_CYCLE_TEMPLATE = r'''"""Run a portable, bounded external agent cycle.
Set ORBIT_AGENT_COMMAND to a JSON argument array or a shell-like command
prefix. The external tool receives one action at a time: ``status`` or
``run-once``. It must write one JSON object to stdout and must never start a
daemon or scheduler; OpenOrbit owns repetition, timing, and supervision.
"""
import json
import os
import shlex
from orbit_sdk import runner
def agent_command():
"""Read an explicit command prefix without depending on target source files."""
configured = os.environ.get("ORBIT_AGENT_COMMAND", "").strip()
if not configured:
raise ValueError("Set ORBIT_AGENT_COMMAND to the external agent command")
if configured.startswith("["):
value = json.loads(configured)
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise ValueError("ORBIT_AGENT_COMMAND JSON must be an array of strings")
return value
return shlex.split(configured)
def cycle_input(ctx, action):
"""Expose non-secret evaluation context through one documented JSON contract."""
return json.dumps(
{
"action": action,
"iteration": ctx.loop_index,
"evaluation_build": ctx.evaluation_build,
"test_cases": ctx.test_cases,
},
ensure_ascii=False,
)
def invoke(ctx, action):
"""Run one bounded action and require structured evidence from the agent."""
output = ctx.exec(
[*agent_command(), action],
cwd=ctx.project_root,
timeout=3600,
env={"ORBIT_CYCLE_INPUT": cycle_input(ctx, action)},
)
try:
result = json.loads(output)
except json.JSONDecodeError as error:
raise RuntimeError(f"External agent action {action!r} did not return JSON") from error
if not isinstance(result, dict):
raise RuntimeError(f"External agent action {action!r} must return a JSON object")
return result
@runner.phase("init")
def init(ctx):
# Check availability once; later phases must not start an independent loop.
status = invoke(ctx, "status")
ctx.emit_result({"agent_cycle": {"status": status}})
@runner.phase("setup")
def setup(ctx):
# Record the fixed inputs so every external action is auditable.
ctx.emit_result(
{
"agent_cycle": {
"iteration": ctx.loop_index,
"test_case_ids": [str(case.get("id", "")) for case in ctx.test_cases],
}
}
)
@runner.phase("run")
def run(ctx):
# Exactly one unit of agent work; OpenOrbit schedules a future iteration.
result = invoke(ctx, "run-once")
ctx.emit_result({"agent_cycle": {"iteration": ctx.loop_index, "result": result}})
@runner.phase("eval")
def evaluate(ctx):
# Re-read status rather than assuming the prior action completed correctly.
status = invoke(ctx, "status")
ctx.emit_result({"agent_cycle": {"iteration": ctx.loop_index, "status": status}})
@runner.phase("teardown")
def teardown(ctx):
# The external process has already returned; no daemon cleanup is required.
ctx.log("Completed one bounded external agent cycle")
@runner.phase("finalize")
def finalize(ctx):
ctx.log("Finalized the external agent evaluation")
if __name__ == "__main__":
runner.main()
'''
EVIDENCE_GATED_PROBE_CYCLE_TEMPLATE = r'''"""Run a portable evidence-gated probe matrix through an external tool.
Set ORBIT_PROBE_COMMAND to a JSON argument array or a shell-like command
prefix. The tool must support ``preflight``, ``prepare``, ``run-probes``, and
``collect-evidence`` actions. Every action receives ORBIT_CYCLE_INPUT and
returns one JSON object. The tool may create disposable workspaces, but it
must not schedule itself or commit changes to the target repository.
"""
import json
import os
import shlex
from orbit_sdk import runner
def probe_command():
"""Read the explicit probe command prefix configured by the operator."""
configured = os.environ.get("ORBIT_PROBE_COMMAND", "").strip()
if not configured:
raise ValueError("Set ORBIT_PROBE_COMMAND to the evidence-gate command")
if configured.startswith("["):
value = json.loads(configured)
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise ValueError("ORBIT_PROBE_COMMAND JSON must be an array of strings")
return value
return shlex.split(configured)
def cycle_input(ctx, action):
"""Pass selected probes and non-secret evaluation context to the tool."""
return json.dumps(
{
"action": action,
"iteration": ctx.loop_index,
"evaluation_build": ctx.evaluation_build,
"probes": ctx.test_cases,
},
ensure_ascii=False,
)
def invoke(ctx, action):
"""Run one gate action and reject unstructured evidence early."""
output = ctx.exec(
[*probe_command(), action],
cwd=ctx.project_root,
timeout=3600,
env={"ORBIT_CYCLE_INPUT": cycle_input(ctx, action)},
)
try:
result = json.loads(output)
except json.JSONDecodeError as error:
raise RuntimeError(f"Probe action {action!r} did not return JSON") from error
if not isinstance(result, dict):
raise RuntimeError(f"Probe action {action!r} must return a JSON object")
return result
@runner.phase("init")
def init(ctx):
# A fixed probe set keeps the gate repeatable and its evidence comparable.
if not ctx.test_cases:
raise ValueError("Select a fixed test case set before running an evidence gate")
preflight = invoke(ctx, "preflight")
ctx.emit_result({"probe_gate": {"preflight": preflight}})
@runner.phase("setup")
def setup(ctx):
# Prepare disposable inputs without mutating the target repository.
prepared = invoke(ctx, "prepare")
ctx.emit_result({"probe_gate": {"iteration": ctx.loop_index, "prepared": prepared}})
@runner.phase("run")
def run(ctx):
# Run the complete fixed matrix once and retain the tool's structured report.
report = invoke(ctx, "run-probes")
ctx.emit_result({"probe_gate": {"iteration": ctx.loop_index, "report": report}})
@runner.phase("eval")
def evaluate(ctx):
# Collect final evidence separately so a supervisor can make an independent decision.
evidence = invoke(ctx, "collect-evidence")
ctx.emit_result({"probe_gate": {"iteration": ctx.loop_index, "evidence": evidence}})
@runner.phase("teardown")
def teardown(ctx):
ctx.log("Completed one evidence-gated probe matrix")
@runner.phase("finalize")
def finalize(ctx):
ctx.log("Finalized the evidence-gated probe evaluation")
if __name__ == "__main__":
runner.main()
'''
DATA = APP_DATA / "data"
RUNS = DATA / "runs"
TELEMETRY = DATA / "telemetry.jsonl"
SETTINGS = DATA / "settings.json"
TOOL_TIMES = DATA / "tool-times.json"
RUNNERS = APP_DATA / "runners"
RUNNER_TEMPLATES = APP_DATA / "runner-templates"
QUICK_STARTS = APP_DATA / "quick-starts"
QUICK_START_INSTANCES = CONFIG / "quick-start-instances.yaml"
def now() -> datetime:
return datetime.now(UTC)
class ConsoleStore:
"""File-backed local state. Commands are always executed without a shell."""
def __init__(self) -> None:
self._initialize_application_data()
RUNS.mkdir(parents=True, exist_ok=True)
RUNNERS.mkdir(parents=True, exist_ok=True)
RUNNER_TEMPLATES.mkdir(parents=True, exist_ok=True)
QUICK_STARTS.mkdir(parents=True, exist_ok=True)
self._migrate_evaluation_environments()
self._processes: dict[str, subprocess.Popen[str]] = {}
# Test runs are deliberately process-local: they support the build-page
# test dialog without becoming an evaluation-run record or surviving a
# server restart.
self._test_sessions: dict[str, Run] = {}
self._lock = threading.Lock()
self._recover_interrupted_runs()
self.tracer = configure_telemetry(TELEMETRY)
def _recover_interrupted_runs(self) -> None:
"""Do not present orphaned in-memory pipelines as still running.
The local scheduler is process-bound. A server restart ends all worker
threads, so unfinished records from the previous process are explicitly
marked cancelled before they can distort active-evaluation metrics.
"""
for path in RUNS.glob("*.json"):
try:
run = Run.model_validate_json(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if run.status not in {"queued", "running", "awaiting_approval"}:
continue
run.status, run.current_step, run.current_phase = "cancelled", None, None
run.updated_at, run.finished_at = now(), now()
run.step_results.append(
{
"step_id": "orbit-restart",
"error": "OpenOrbit restarted before this local pipeline completed.",
"ended_at": now(),
}
)
temporary = path.with_suffix(".tmp")
temporary.write_text(run.model_dump_json(indent=2), encoding="utf-8")
temporary.replace(path)
@staticmethod
def _initialize_application_data() -> None:
"""Create empty, environment-local state; never seed operational assets from Git."""
for destination in (CONFIG, DATA):
destination.mkdir(parents=True, exist_ok=True)
stored = json.loads(SETTINGS.read_text(encoding="utf-8")) if SETTINGS.exists() else {}
document = stored if isinstance(stored, dict) else {}
application = (
document.get("application_settings")
if isinstance(document.get("application_settings"), dict)
else {}
)
if not str(application.get("manager_prompt_template", "")).strip():
document["application_settings"] = {
**application,
"manager_prompt_template": DEFAULT_OPERATIONAL_MANAGER_PROMPT,
"chat_model_profile_name": str(application.get("chat_model_profile_name", "")).strip(),
}
SETTINGS.write_text(json.dumps(document, indent=2), encoding="utf-8")
@staticmethod
def runner_templates() -> list[dict[str, str]]:
templates = [
{
"id": "user-journey-cycle",
"name": "Browser journey validation",
"description": "Validates fixed browser journeys directly and retains page evidence and screenshots for every bounded iteration.",
"source": """# Requirements
# - The target application is running at the evaluation build's browser base URL.
# - The evaluation build selects at least one fixed test case.
# - OpenOrbit's bundled Playwright dependency and browser are available.
# No external runner script, adapter repository, or background program is required.
import json
import re
from orbit_sdk import runner
# Validate only configuration that the runner cannot safely infer. This runs
# once when an evaluation process starts, before its iteration loop.
def validate(ctx):
build = ctx.evaluation_build
if not build.get("browser_base_url"):
raise ValueError("Set a browser base URL on the evaluation build")
if not ctx.test_cases:
raise ValueError("Select a fixed test case set before running a user journey")
def state_path(ctx):
# Keep state in OpenOrbit AppData, keyed by build, so a later iteration can
# resume its focused journey without writing into the target repository.
build_id = re.sub(r"[^a-zA-Z0-9_-]+", "-", str(ctx.evaluation_build.get("id") or "manual"))
directory = ctx.app_data / "user-journey-state"
directory.mkdir(parents=True, exist_ok=True)
return directory / f"{build_id}.json"
def load_state(ctx):
# A build's first iteration begins with an empty rotation and no failures.
path = state_path(ctx)
if not path.exists():
return {"next_case_index": 0, "failed_case_ids": [], "history": []}
return json.loads(path.read_text(encoding="utf-8"))
def save_state(ctx, state):
# Retain a bounded history so a long-running evaluation does not grow
# indefinitely while still preserving useful handoffs.
state["history"] = state.get("history", [])[-24:]
state_path(ctx).write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
def plan(ctx, state):
# Supervisor feedback from the completed prior iteration is an input to
# planning, not a replacement for browser-observable evidence.
feedback = ctx.previous_supervisor_feedback
failed = set(state.get("failed_case_ids", []))
cases = ctx.test_cases
# Failed cases take precedence; otherwise rotate through fixed cases one at
# a time to keep each scheduled iteration bounded and explainable.
focused = [case for case in cases if case.get("id") in failed]
if not focused:
index = int(state.get("next_case_index", 0)) % len(cases)
focused = [cases[index]]
rules = ["Preserve observable evidence for every browser action.", "Do not infer a result that the page did not expose."]
if failed:
rules.insert(0, "Revisit previously failed journeys before exploring a new route.")
if feedback.get("reported_issues"):
rules.insert(0, "Prioritize the supervisor's previously reported issues.")
reason = "Previously failed journeys require confirmation." if failed else "Rotate one fixed journey to retain broad, bounded coverage."
return {"case_ids": [str(case.get("id")) for case in focused], "rules": rules, "reason": reason, "supervisor_feedback": feedback}
@runner.phase("init")
def init(ctx):
# Process-level preparation: run once before OpenOrbit starts repeating.
validate(ctx)
ctx.log("Validated the bounded user-journey contract")
@runner.phase("setup")
def setup(ctx):
# Iteration-level preparation: persist a plan that the run phase consumes.
state = load_state(ctx)
journey_plan = plan(ctx, state)
state["plan"] = journey_plan
save_state(ctx, state)
ctx.emit_result({"user_journey": {"iteration": ctx.loop_index, "case_count": len(ctx.test_cases), "plan": journey_plan}})
ctx.log(f"Planned {len(journey_plan['case_ids'])} focused journey case(s): {journey_plan['reason']}")
@runner.phase("run")
def run(ctx):
# Execute only the focused fixed cases; Playwright returns screenshots and
# page evidence that can be inspected by both users and the supervisor.
state = load_state(ctx)
journey_plan = state.get("plan") or plan(ctx, state)
case_ids = set(journey_plan["case_ids"])
focused_cases = [case for case in ctx.test_cases if str(case.get("id")) in case_ids]
evidence = ctx.playwright_journey(focused_cases)
results = evidence["results"]
passed = len([item for item in results if item["passed"]])
failed = [str(item.get("id")) for item in results if not item["passed"]]
state["failed_case_ids"] = failed
state["next_case_index"] = (int(state.get("next_case_index", 0)) + 1) % len(ctx.test_cases)
# This compact handoff is the explicit input to the next scheduled cycle.
state["handoff"] = {"iteration": ctx.loop_index, "reason": journey_plan["reason"], "rules": journey_plan["rules"], "passed": passed, "failed": len(results) - passed, "failed_case_ids": failed}
state.setdefault("history", []).append(state["handoff"])
save_state(ctx, state)
ctx.emit_result({"user_journey": {"iteration": ctx.loop_index, "plan": journey_plan, "passed": passed, "failed": len(results) - passed, "results": results, "evidence": evidence, "handoff": state["handoff"]}})
@runner.phase("eval")
def evaluate(ctx):
# Expose the persisted handoff as structured run output for supervision.
state = load_state(ctx)
ctx.emit_result({"user_journey": {"next_iteration": state.get("handoff", {}), "state_path": str(state_path(ctx))}})
ctx.log("Stored the journey summary, reasons, and behavior rules for the next iteration")
@runner.phase("teardown")
def teardown(ctx): ctx.log("Closed this bounded browser journey")
@runner.phase("finalize")
def finalize(ctx): ctx.log("Finalized the user-journey evaluation")
if __name__ == "__main__": runner.main()
""",
},
{
"id": "external-command-adapter",
"name": "External automation integration",
"description": "Connects an existing automation tool while OpenOrbit retains scheduling, evidence collection, and supervision.",
"source": """import json\nimport os\nimport shlex\n\nfrom orbit_sdk import ORBIT_PROJECT_PATH, runner\n\n# Set ORBIT_ADAPTER_COMMAND to the command prefix for an external tool. It may\n# be a JSON array or a shell-like string. The tool must support the bounded\n# actions appended below and must never start its own scheduler.\ndef adapter_command():\n # Parse once per invocation so the configuration remains explicit and does\n # not depend on a target repository's source files.\n configured = os.environ.get("ORBIT_ADAPTER_COMMAND", "").strip()\n if not configured:\n raise ValueError("Set ORBIT_ADAPTER_COMMAND to an external tool command")\n if configured.startswith("["):\n value = json.loads(configured)\n if not isinstance(value, list) or not all(isinstance(item, str) for item in value):\n raise ValueError("ORBIT_ADAPTER_COMMAND JSON must be an array of strings")\n return value\n return shlex.split(configured)\n\ndef invoke(ctx, action):\n # OpenOrbit owns the lifecycle: the adapter receives one bounded action and\n # must return instead of starting a daemon or an independent scheduler.\n return ctx.exec([*adapter_command(), action], cwd=ORBIT_PROJECT_PATH(), timeout=3600)\n\n@runner.phase("init")\ndef init(ctx):\n # Process-level readiness check, performed once before the repeat loop.\n invoke(ctx, "status")\n\n@runner.phase("setup")\ndef setup(ctx):\n # Per-iteration preparation, such as refreshing target-side test data.\n invoke(ctx, "prepare")\n\n@runner.phase("run")\ndef run(ctx):\n # Exactly one unit of adapter work; OpenOrbit schedules further iterations.\n invoke(ctx, "run-once")\n\n@runner.phase("eval")\ndef evaluate(ctx):\n # Return machine-readable or textual evidence for the supervisor to assess.\n invoke(ctx, "collect-evidence")\n\n@runner.phase("teardown")\ndef teardown(ctx):\n # Per-iteration cleanup after evidence collection.\n ctx.log("Completed the bounded external command")\n\n@runner.phase("finalize")\ndef finalize(ctx):\n # Process-level finalization, performed once after the loop exits.\n ctx.log("Finalized the external command evaluation")\n\nif __name__ == "__main__": runner.main()\n""",
},
{
"id": "native-improvement-cycle",
"name": "Native improvement cycle",
"description": "Tracks a Git change candidate, validates fixed browser journeys, and promotes only repeatedly sufficient evidence. OpenOrbit owns all cycle state and never runs an external improvement script.",
"source": """# Requirements\n# - PROJECT_ROOT is a Git repository.\n# - The evaluation build selects fixed browser test cases and a browser base URL.\n# - Candidate source changes are supplied through the normal reviewed change flow.\n# This runner never launches an external improvement script or commits a change.\n\nimport hashlib\nimport json\nimport re\nfrom pathlib import Path\n\nfrom orbit_sdk import runner\n\nREQUIRED_SUFFICIENT_EVALUATIONS = 3\n\ndef state_path(ctx):\n build_id = re.sub(r"[^a-zA-Z0-9_-]+", "-", str(ctx.evaluation_build.get("id") or "manual"))\n directory = ctx.app_data / "improvement-cycles"\n directory.mkdir(parents=True, exist_ok=True)\n return directory / f"{build_id}.json"\n\ndef load_state(ctx):\n path = state_path(ctx)\n if not path.exists():\n return {"candidate_fingerprint": None, "sufficient_evaluations": 0, "history": []}\n return json.loads(path.read_text(encoding="utf-8"))\n\ndef save_state(ctx, state):\n state["history"] = state.get("history", [])[-24:]\n state_path(ctx).write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")\n\ndef git(ctx, *args):\n return ctx.exec(["git", *args], cwd=ctx.project_root, timeout=300)\n\ndef candidate(ctx):\n patch = git(ctx, "diff", "--binary", "--")\n changed = [line for line in git(ctx, "diff", "--name-only").splitlines() if line]\n return (hashlib.sha256(patch.encode("utf-8")).hexdigest() if patch else None), changed\n\n@runner.phase("init")\ndef init(ctx):\n git(ctx, "rev-parse", "--show-toplevel")\n if not ctx.evaluation_build.get("browser_base_url") or not ctx.test_cases:\n raise ValueError("Select a browser base URL and fixed test cases for a native improvement cycle")\n ctx.log("Validated a Git-backed, OpenOrbit-native improvement cycle")\n\n@runner.phase("setup")\ndef setup(ctx):\n fingerprint, changed = candidate(ctx)\n ctx.emit_result({"improvement_cycle": {"iteration": ctx.loop_index, "candidate_fingerprint": fingerprint, "changed_paths": changed}})\n ctx.log("Captured the candidate baseline before validation")\n\n@runner.phase("run")\ndef run(ctx):\n evidence = ctx.playwright_journey()\n results = evidence["results"]\n passed = all(item["passed"] for item in results)\n fingerprint, changed = candidate(ctx)\n ctx.emit_result({"improvement_cycle": {"iteration": ctx.loop_index, "candidate_fingerprint": fingerprint, "changed_paths": changed, "passed": passed, "evidence": evidence}})\n if not passed:\n raise SystemExit("A fixed validation journey failed")\n\n@runner.phase("eval")\ndef evaluate(ctx):\n state = load_state(ctx)\n fingerprint, changed = candidate(ctx)\n if not fingerprint:\n state["candidate_fingerprint"] = None\n state["sufficient_evaluations"] = 0\n verdict = "no_candidate"\n elif state.get("candidate_fingerprint") == fingerprint:\n state["sufficient_evaluations"] = int(state.get("sufficient_evaluations", 0)) + 1\n verdict = "ready_for_approval" if state["sufficient_evaluations"] >= REQUIRED_SUFFICIENT_EVALUATIONS else "continue_validation"\n else:\n state["candidate_fingerprint"] = fingerprint\n state["sufficient_evaluations"] = 1\n verdict = "continue_validation"\n state.setdefault("history", []).append({"iteration": ctx.loop_index, "fingerprint": fingerprint, "paths": changed, "verdict": verdict})\n save_state(ctx, state)\n ctx.emit_result({"improvement_cycle": {"candidate_fingerprint": fingerprint, "changed_paths": changed, "sufficient_evaluations": state["sufficient_evaluations"], "required_evaluations": REQUIRED_SUFFICIENT_EVALUATIONS, "verdict": verdict}})\n ctx.log(f"Candidate verdict: {verdict}")\n\n@runner.phase("teardown")\ndef teardown(ctx): ctx.log("Retained native improvement evidence for supervision")\n@runner.phase("finalize")\ndef finalize(ctx): ctx.log("Finalized the native improvement cycle without committing changes")\n\nif __name__ == "__main__": runner.main()\n""",
},
]
templates[-1] = {
"id": "native-improvement-cycle",
"name": "Prompt improvement validation",
"description": "Applies accepted prompt improvements with rollback history, validates fixed browser journeys, and records review decisions.",
"source": NATIVE_IMPROVEMENT_CYCLE_TEMPLATE,
}
templates.extend(
(
{
"id": "json-agent-cycle",
"name": "User journey simulation",
"description": "Runs one bounded agent simulation per iteration while OpenOrbit retains fixed inputs, evidence, and supervision.",
"source": JSON_AGENT_CYCLE_TEMPLATE,
},
{
"id": "evidence-gated-probe-cycle",
"name": "Evidence-driven improvement gate",
"description": "Validates a fixed probe matrix and returns structured preflight, result, and evidence records for improvement decisions.",
"source": EVIDENCE_GATED_PROBE_CYCLE_TEMPLATE,
},
)
)
return templates
def _custom_runner_templates(self) -> list[dict[str, str]]:
templates = []
for path in sorted(RUNNER_TEMPLATES.glob("*.py")):
metadata = path.with_suffix(".json")
if metadata.exists():
values = json.loads(metadata.read_text(encoding="utf-8"))
templates.append({**values, "source": path.read_text(encoding="utf-8"), "origin": "user"})
return templates
def available_runner_templates(self) -> list[dict[str, str]]:
builtins = [{**item, "origin": "built-in"} for item in self.runner_templates()]
return [*builtins, *self._custom_runner_templates()]
@staticmethod
def _quick_start_browser_runner() -> str:
return """from orbit_sdk import runner
@runner.phase("init")
def init(ctx):
if not ctx.evaluation_build.get("browser_base_url"):
raise ValueError("Quick start browser evaluation requires a browser base URL")
@runner.phase("run")
def run(ctx):
evidence = ctx.playwright_journey()
if not all(item["passed"] for item in evidence["results"]):
raise SystemExit("A browser journey failed")
@runner.phase("eval")
def evaluate(ctx):
ctx.log("Quick start browser evaluation completed")
if __name__ == "__main__":
runner.main()
"""
def _built_in_quick_starts(self) -> list[dict[str, Any]]:
return [
{
"schema_version": 1,
"id": "openorbit.user-journey-smoke-test",
"version": "1.0.0",
"name": "User journey smoke test",
"description": "Create a browser-based smoke test for one important user journey.",
"publisher": {"name": "OpenOrbit"},
"parameters": [
{
"key": "build_name",
"label": "Evaluation name",
"type": "string",
"required": True,
"default": "Browser quality check",
},
{
"key": "repository",
"label": "Target repository",
"type": "workspace",
"required": True,
"placeholder": "/absolute/path/to/your-repository",
},
{
"key": "base_url",
"label": "Browser base URL",
"type": "url",
"required": True,
"placeholder": "http://localhost:3000",
},
{
"key": "journey_name",
"label": "User journey name",
"type": "string",
"required": True,
"default": "Home page smoke test",
"placeholder": "e.g. Sign in and view orders",
},
{
"key": "journey_path",
"label": "Journey start path",
"type": "string",
"required": True,
"default": "/",
"placeholder": "e.g. /login",
},
{
"key": "journey_prompt",
"label": "User actions",
"type": "string",
"required": True,
"placeholder": "e.g. Sign in with the test account and open order history.",
},
{
"key": "acceptance",
"label": "Success condition",
"type": "string",
"required": True,
"placeholder": "e.g. The order history page loads without an error.",
},
{
"key": "expected_text",
"label": "Expected visible text (optional)",
"type": "string",
"required": False,
"placeholder": "e.g. Recent orders",
},
{
"key": "profile_name",
"label": "AI model profile name",
"type": "string",
"required": True,
"default": "Browser quality AI",
"placeholder": "e.g. Evaluation GPT-4o",
},
{
"key": "provider",
"label": "AI provider",
"type": "select",
"required": True,
"default": "azure-openai",
"options": [
{"value": "azure-openai", "label": "Azure OpenAI"},
{"value": "aws-bedrock", "label": "AWS Bedrock"},
],
},
{
"key": "model",
"label": "Model / deployment",
"type": "string",
"required": True,
"placeholder": "e.g. gpt-4o",
},
{
"key": "endpoint",
"label": "Provider endpoint",
"type": "url",
"required": False,
"placeholder": "https://your-resource.openai.azure.com",
},
{
"key": "region",
"label": "Region",
"type": "string",
"required": True,
"default": "us-east-1",
"placeholder": "e.g. eastus",
},
{
"key": "secret_env",
"label": "API key environment variable",
"type": "string",
"required": True,
"default": "AZURE_OPENAI_API_KEY",
"placeholder": "e.g. AZURE_OPENAI_API_KEY",
},
],
"assets": {
"runner": {
"name": "${build_name} runner",
"description": "Browser journey runner created by Quick Start.",
"template_id": "quickstart-browser",
"source": self._quick_start_browser_runner(),
},
"prompt_template": {
"name": "${build_name} policy",
"version": 1,
"content": "Assess the fixed browser journey evidence and return the required evaluation JSON.",
},
"test_case_set": {
"name": "${build_name} smoke tests",
"description": "A smoke journey created by Quick Start.",
"cases": [
{
"id": "primary-journey",
"name": "${journey_name}",
"path": "${journey_path}",
"prompt": "${journey_prompt}",
"acceptance": "${acceptance}",
"expected_text": "${expected_text}",
}
],
},
"execution_environment": {"name": "${build_name} execution", "executor_type": "local"},
"target_environment": {
"name": "${build_name} target",
"repository": "${repository}",
"browser_base_url": "${base_url}",
},
"model_profile": {
"profile_name": "${profile_name}",
"provider": "${provider}",
"model": "${model}",
"endpoint": "${endpoint}",
"region": "${region}",
"secret_env": "${secret_env}",
},
},
"build": {
"name": "${build_name}",
"purpose": "Evaluate the browser journey created by Quick Start.",
"model_profile_name": "${profile_name}",
"timezone": "Asia/Tokyo",
"repeat_interval_minutes": 30,
"run_limit": 1,
"approval_score": 8,
"enabled": True,
},
},
{
"schema_version": 1,
"id": "openorbit.agent-self-improvement",
"version": "1.0.0",
"name": "Agent self-improvement",
"description": "Validate agent or prompt changes against a fixed user journey and retain rollback-ready improvement evidence.",
"publisher": {"name": "OpenOrbit"},
"parameters": [
{
"key": "build_name",
"label": "Evaluation name",
"type": "string",
"required": True,
"default": "Agent self-improvement",
},
{
"key": "repository",
"label": "Git repository",
"type": "workspace",
"required": True,
"placeholder": "/absolute/path/to/your-git-repository",
},
{
"key": "base_url",
"label": "Browser base URL",
"type": "url",
"required": True,
"placeholder": "http://localhost:3000",
},
{
"key": "managed_prompt_path",
"label": "Agent prompt file path",
"type": "string",
"required": True,
"placeholder": "e.g. prompts/system.md",
},
{
"key": "journey_name",
"label": "Validation journey name",
"type": "string",
"required": True,
"default": "Agent quality journey",
"placeholder": "e.g. Resolve a customer support request",
},
{
"key": "journey_path",
"label": "Journey start path",
"type": "string",
"required": True,
"default": "/",
"placeholder": "e.g. /chat",
},
{
"key": "journey_prompt",
"label": "User actions",
"type": "string",
"required": True,
"placeholder": "e.g. Ask the agent to find and explain a policy.",
},
{
"key": "acceptance",
"label": "Success condition",
"type": "string",
"required": True,
"placeholder": "e.g. The response is complete, grounded, and has no error.",
},
{
"key": "expected_text",
"label": "Expected visible text (optional)",
"type": "string",
"required": False,
"placeholder": "e.g. Return policy",
},
{
"key": "profile_name",
"label": "AI model profile name",
"type": "string",
"required": True,
"default": "Agent improvement AI",
"placeholder": "e.g. Agent evaluation GPT-4o",
},
{
"key": "provider",
"label": "AI provider",
"type": "select",
"required": True,
"default": "azure-openai",
"options": [
{"value": "azure-openai", "label": "Azure OpenAI"},
{"value": "aws-bedrock", "label": "AWS Bedrock"},
],
},
{
"key": "model",
"label": "Model / deployment",
"type": "string",
"required": True,
"placeholder": "e.g. gpt-4o",