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
4873 lines (4597 loc) · 235 KB
/
Copy pathstore.py
File metadata and controls
4873 lines (4597 loc) · 235 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 hashlib
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
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import requests
import yaml
from orbit import load_bundle
from .assistant_tools import normalize_settings as normalize_assistant_tools
from .models import PHASE_ALIASES, 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_pointer() -> Path:
"""Keep an operator-selected data location outside the data it points to."""
if os.name == "nt":
root = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "Orbit"
elif sys.platform == "darwin":
root = Path.home() / "Library" / "Preferences" / "Orbit"
else:
root = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "orbit"
return root / "app-data-path"
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()
pointer = _application_data_pointer()
try:
selected = pointer.read_text(encoding="utf-8").strip()
except OSError:
selected = ""
if selected:
return Path(selected).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__
__ORBIT_MANAGER_OUTPUT_LANGUAGE__
Your final response must be exactly one JSON object:
{
\"evaluation\": {\"score\":\"number from 0 to 10\",\"approval\":\"approved|rejected|pending\",\"summary\":\"string\",\"behavior_trace\": {\"purpose\":\"string\",\"rationale\":\"string\",\"observation\":\"string\",\"decision\":\"string\",\"next_action\":\"string\"}, \"behavior_summary\":\"legacy string, only when the evaluated target is an AI\"},
\"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\"}]
}
For an evaluated AI, include behavior_trace and fill every field. It is an evidence-backed activity record for a person reviewing the run: purpose explains why this check or action matters now; rationale names only the observable evidence or declared plan behind it; observation records the material change or finding in this iteration; decision records what the target AI did or deliberately did not do; next_action states the specific next check or hypothesis. Compare with the immediately previous iteration when that evidence is supplied. Do not narrate repeated mechanics (navigation, waits, screenshots, or generic control inspection). When there is no material change, say so briefly and make next_action explain how the next check will differ or escalate. Do not reveal hidden reasoning or evaluator chain-of-thought. Do not include behavior_trace for non-AI targets. behavior_summary is optional legacy compatibility only; prefer behavior_trace. Always include both array keys, using empty arrays when there are no items."""
LEGACY_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\",\"behavior_summary\":\"string, only when the evaluated target is an AI\"},
\"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\"}]
}
Include behavior_summary only when the evaluated target is an AI. It must describe the AI's observed responses, decisions, tool use, refusals, or other behavior in plain language; do not describe pass/fail outcomes, metrics, baselines, or the evaluator's actions. Omit behavior_summary for non-AI targets. Always include both array keys, using empty arrays when there are no items."""
PROPOSAL_DECISION_POLICY = """# Improvement decision policy
Decide each improvement status independently from the evaluation approval score.
Use `adopted` for a prompt-only change when it is low-risk, additive, reversible through the retained prompt version, directly supported by the observed evidence, and has measurable acceptance evidence. Prefer `adopted` for such changes; do not defer it merely to wait for another iteration or a repeated candidate fingerprint.
Use `proposed` when the change needs code, infrastructure, product, security, or human-policy approval, or when the evidence is insufficient. Use `rejected` for unsafe, duplicate, or unsupported changes."""
MANAGER_PROMPT_SLOT = "__ORBIT_MANAGER_AI_PROMPT__"
MANAGER_OUTPUT_LANGUAGE_SLOT = "__ORBIT_MANAGER_OUTPUT_LANGUAGE__"
NATIVE_IMPROVEMENT_CYCLE_TEMPLATE = r"""# Requirements
# - PROJECT_ROOT is a Git repository.
# - The build selects fixed target-AI prompts and a configured model
# profile, plus a readable managed_prompt_path 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.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.build.get("managed_prompt_path") or ctx.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")
if not proposals:
# Do not manufacture a changing candidate when the supervisor has not
# accepted a change. A stable candidate must retain the same fingerprint
# across repeated validations before it can be promoted.
return {"path": prompt_path, "changed": False, "reason": "no_accepted_proposals"}
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)
def managed_prompt_evidence(ctx):
'''Expose the current managed prompt beside the target-AI response evidence.'''
prompt_path = str(ctx.build.get("managed_prompt_path") or ctx.build.get("prompt_bundle") or "").strip()
if not prompt_path:
raise ValueError("native improvement cycle requires target_environment.managed_prompt_path")
content = ctx.project_path(prompt_path).read_text(encoding="utf-8")
return {
"path": prompt_path,
"sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),
"content": content,
}
@runner.phase("before_all")
def before_all(ctx):
# Process-level validation runs once before the iteration loop begins.
git(ctx, "rev-parse", "--show-toplevel")
if not ctx.test_cases:
raise ValueError("Select at least one fixed target-AI prompt for a native improvement cycle")
if not isinstance(ctx.resource("model_profile", {}), dict) or not ctx.resource("model_profile", {}).get("model"):
raise ValueError("Select a configured model profile for a native improvement cycle")
ctx.log("Validated an OpenOrbit-native target-AI prompt improvement cycle")
@runner.phase("before_each")
def before_each(ctx):
# Keep the target's complete pre-evaluation state outside commit history.
# The call is idempotent because before_each runs for every iteration.
ctx.save_before_each_snapshot()
# 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"}
]
requires_human_approval = bool(
ctx.build.get("require_human_approval_before_apply", False)
)
if requires_human_approval and accepted:
# A supervisor's adoption is a recommendation, not an operator
# authorization. Keep it as evidence until an operator approves it.
prompt_update = {
"changed": False,
"reason": "awaiting_human_approval",
"proposal_count": len(accepted),
}
accepted = []
else:
prompt_update = update_prompt_from_accepted_proposals(ctx, accepted)
accepted_ids = [str(value) for value in feedback.get("_orbit_proposal_ids", [])]
proposal_applications = ctx.record_proposal_application(accepted_ids, prompt_update)
fingerprint, changed = candidate(ctx)
ctx.emit_result(
{
"improvement_cycle": {
"iteration": ctx.loop_index,
"candidate_fingerprint": fingerprint,
"changed_paths": changed,
"prompt_update": prompt_update,
"requires_human_approval": requires_human_approval,
"managed_prompt": managed_prompt_evidence(ctx),
"proposal_applications": proposal_applications,
}
}
)
ctx.log("Refreshed the rollback-protected prompt from accepted supervisor feedback")
@runner.phase("execute")
def execute(ctx):
# Exercise the evaluated AI with the current managed prompt. The raw reply
# is retained as supervisor evidence instead of treating a browser page as
# proof that a prompt instruction was followed.
managed_prompt = managed_prompt_evidence(ctx)
responses = []
for case in ctx.test_cases:
request = str(case.get("prompt") or "").strip()
if not request:
raise ValueError("each target-AI test case requires a prompt")
turn = ctx.complete_model(
"# Managed agent instructions\\n"
+ managed_prompt["content"]
+ "\\n\\n# User request\\n"
+ request
+ "\\n\\nRespond as the managed agent."
)
responses.append(
{
"id": case.get("id"),
"name": case.get("name"),
"request": request,
"acceptance": str(case.get("acceptance") or ""),
"response": turn["response"],
"model": turn["model"],
}
)
artifact = ctx.save_data_file(
"target-ai-responses.json",
json.dumps(responses, ensure_ascii=False, indent=2),
label="Target AI responses",
content_type="application/json",
)
fingerprint, changed = candidate(ctx)
ctx.emit_result(
{
"improvement_cycle": {
"iteration": ctx.loop_index,
"candidate_fingerprint": fingerprint,
"changed_paths": changed,
"evidence": {"target_ai_responses": responses, "artifact": artifact},
}
}
)
@runner.phase("verify")
def verify(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("after_each")
def after_each(ctx):
# Preserve the first evaluated state as a named recovery checkpoint.
ctx.save_first_after_each_snapshot()
# Per-iteration evidence remains available for supervisor review.
ctx.log("Retained prompt versions, decisions, and validation evidence")
@runner.phase("after_all")
def after_all(ctx):
# Return the target to its exact baseline without creating a Git commit.
ctx.restore_before_each_snapshot()
ctx.log("Restored the native improvement target without committing changes")
if __name__ == "__main__":
runner.main()
"""
SITE_EXPLORATION_TEMPLATE = r"""# Requirements
# - The target application is running at the build's browser base URL.
# - Playwright Chromium and LangGraph are available.
# This runner follows only same-site links and excludes destructive-looking routes.
import json
import subprocess
from pathlib import Path
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
import orbit_sdk
from orbit_sdk import runner
class ExplorerState(TypedDict, total=False):
base_url: str
max_clicks: int
evidence: dict
opinion: str
def explore_browser(ctx, state):
module = str(Path(orbit_sdk.__file__).resolve().parents[1] / "frontend" / "node_modules" / "playwright")
artifacts = ctx.app_data / "artifacts" / ctx.environment.get("ORBIT_RUN_ID", "manual") / f"loop-{ctx.loop_index}"
artifacts.mkdir(parents=True, exist_ok=True)
payload = {"baseUrl": state["base_url"], "maxClicks": state["max_clicks"], "screenshot": str(artifacts / "site-exploration.png")}
script = r'''const { chromium } = require(process.argv[1]); const input = JSON.parse(process.argv[2]);
const blocked = /(logout|signout|delete|remove|destroy|payment|checkout|purchase|upgrade|unsubscribe)/i;
(async () => { const browser = await chromium.launch({headless:true}); const page = await browser.newPage(); const visited = []; const origin = new URL(input.baseUrl).origin;
try { await page.goto(input.baseUrl, {waitUntil:"domcontentloaded", timeout:30000});
for (let step = 0; step <= input.maxClicks; step++) { const text = (await page.locator("body").innerText().catch(() => "")).replace(/\s+/g, " ").slice(0, 1200); visited.push({url:page.url(), title:await page.title(), text});
if (step === input.maxClicks) break;
const links = await page.locator("a[href]").evaluateAll(items => items.map((item, index) => ({index, href:item.href, text:(item.textContent || "").trim()})).filter(item => item.href));
const candidates = links.filter(item => { try { const url = new URL(item.href); return url.origin === origin && !blocked.test(url.pathname + " " + item.text); } catch { return false; } });
if (!candidates.length) break; const target = candidates[step % candidates.length]; await page.locator("a[href]").nth(target.index).click({timeout:5000}); await page.waitForLoadState("domcontentloaded", {timeout:10000}).catch(() => {}); await page.waitForTimeout(300);
}
await page.screenshot({path:input.screenshot, fullPage:true}); console.log(JSON.stringify({visited, screenshot:input.screenshot}));
} finally { await browser.close(); } })().catch(error => { console.error(error); process.exit(1); });'''
result = subprocess.run(["node", "-e", script, module, json.dumps(payload)], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=120)
if result.returncode:
raise RuntimeError(result.stdout[-4000:] or "Site exploration failed")
return json.loads(result.stdout.strip().splitlines()[-1])
def form_opinion(state):
pages = state["evidence"].get("visited", [])
titles = [str(page.get("title") or page.get("url")) for page in pages]
return {"opinion": f"Explored {len(pages)} rendered page(s): " + "; ".join(titles[:3]) + ". Review the captured pages for clarity, usefulness, and friction."}
def graph(ctx):
workflow = StateGraph(ExplorerState)
workflow.add_node("explore", lambda state: {"evidence": explore_browser(ctx, state)})
workflow.add_node("form_opinion", form_opinion)
workflow.add_edge(START, "explore")
workflow.add_edge("explore", "form_opinion")
workflow.add_edge("form_opinion", END)
return workflow.compile()
@runner.phase("before_all")
def before_all(ctx):
if not ctx.build.get("browser_base_url"):
raise ValueError("Set a browser base URL before exploring a site")
@runner.phase("execute")
def execute(ctx):
result = graph(ctx).invoke({"base_url": ctx.build["browser_base_url"], "max_clicks": 3})
ctx.emit_result({"site_exploration": {"opinion": result["opinion"], "evidence": result["evidence"]}})
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,
"build": ctx.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("before_all")
def before_all(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("before_each")
def before_each(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("execute")
def execute(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("verify")
def verify(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("after_each")
def after_each(ctx):
# The external process has already returned; no daemon cleanup is required.
ctx.log("Completed one bounded external agent cycle")
@runner.phase("after_all")
def after_all(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,
"build": ctx.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("before_all")
def before_all(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("before_each")
def before_each(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("execute")
def execute(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("verify")
def verify(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("after_each")
def after_each(ctx):
ctx.log("Completed one evidence-gated probe matrix")
@runner.phase("after_all")
def after_all(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"
TEMPLATE_TRANSLATIONS = DATA / "template-translations.json"
def configure_application_data(path: str) -> Path:
"""Switch the local state root and retain it for later application starts."""
requested = Path(path.strip()).expanduser()
if not requested.is_absolute():
raise ValueError("app data location must be an absolute path")
target = requested.resolve()
target.mkdir(parents=True, exist_ok=True)
pointer = _application_data_pointer()
pointer.parent.mkdir(parents=True, exist_ok=True)
temporary = pointer.with_suffix(".tmp")
temporary.write_text(str(target), encoding="utf-8")
temporary.replace(pointer)
os.environ["ORBIT_APP_DATA"] = str(target)
global APP_DATA, CONFIG, TARGET_TEST_CASE_SETS, EXECUTION_ENVIRONMENTS, TARGET_ENVIRONMENTS
global CYCLE_INTERVENTIONS, DATA, RUNS, TELEMETRY, SETTINGS, TOOL_TIMES, RUNNERS
global RUNNER_TEMPLATES, QUICK_STARTS, QUICK_START_INSTANCES, TEMPLATE_TRANSLATIONS
APP_DATA = target
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"
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"
TEMPLATE_TRANSLATIONS = DATA / "template-translations.json"
return APP_DATA
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_build_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 {}
)
current_prompt = str(application.get("manager_prompt_template", "")).strip()
if not current_prompt or current_prompt == LEGACY_OPERATIONAL_MANAGER_PROMPT:
document["application_settings"] = {
**application,
"manager_prompt_template": DEFAULT_OPERATIONAL_MANAGER_PROMPT,
"manager_output_locale": str(application.get("manager_output_locale", "en")).strip(),
"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 and retains page evidence. Requires a running app and Playwright browser.",
"source": """# Requirements
# - The target application is running at the build's browser base URL.
# - The build selects at least one fixed test case.
# - Playwright Chromium and its operating-system libraries 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.build
if not build.get("browser_base_url"):
raise ValueError("Set a browser base URL on the 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.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("before_all")
def before_all(ctx):
# Process-level preparation: run once before OpenOrbit starts repeating.
validate(ctx)
ctx.log("Validated the bounded user-journey contract")
@runner.phase("before_each")
def before_each(ctx):
# Iteration-level preparation: persist a plan that the execute 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("execute")
def execute(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("verify")
def verify(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("after_each")
def after_each(ctx): ctx.log("Closed this bounded browser journey")
@runner.phase("after_all")
def after_all(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("before_all")\ndef before_all(ctx):\n # Process-level readiness check, performed once before the repeat loop.\n invoke(ctx, "status")\n\n@runner.phase("before_each")\ndef before_each(ctx):\n # Per-iteration preparation, such as refreshing target-side test data.\n invoke(ctx, "prepare")\n\n@runner.phase("execute")\ndef execute(ctx):\n # Exactly one unit of adapter work; OpenOrbit schedules further iterations.\n invoke(ctx, "run-once")\n\n@runner.phase("verify")\ndef verify(ctx):\n # Return machine-readable or textual evidence for the supervisor to assess.\n invoke(ctx, "collect-evidence")\n\n@runner.phase("after_each")\ndef after_each(ctx):\n # Per-iteration cleanup after evidence collection.\n ctx.log("Completed the bounded external command")\n\n@runner.phase("after_all")\ndef after_all(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 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.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("before_all")\ndef before_all(ctx):\n git(ctx, "rev-parse", "--show-toplevel")\n if not ctx.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("before_each")\ndef before_each(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("execute")\ndef execute(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("verify")\ndef verify(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("after_each")\ndef after_each(ctx): ctx.log("Retained native improvement evidence for supervision")\n@runner.phase("after_all")\ndef after_all(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": "site-exploration",
"name": "Site exploration review",
"description": "Explores safe same-site links through LangGraph and retains rendered evidence for product feedback.",
"source": SITE_EXPLORATION_TEMPLATE,
},
{
"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()]
def template_translation_input(self, kind: str, template_id: str) -> dict[str, Any]:
"""Return only display text that may safely be translated."""
if kind == "runner-template":
template = next(
(item for item in self.available_runner_templates() if item["id"] == template_id), None
)
if template is None:
raise KeyError(template_id)
return {"name": template["name"], "description": template["description"]}
if kind == "quick-start":
quick_start = next((item for item in self.quick_starts() if item["id"] == template_id), None)
if quick_start is None:
raise KeyError(template_id)
return {
"name": quick_start["name"],
"description": quick_start["description"],
"parameters": [
{
**{"label": parameter["label"]},
**({"description": parameter["description"]} if "description" in parameter else {}),
**({"placeholder": parameter["placeholder"]} if "placeholder" in parameter else {}),
**(
{
"options": [
{"label": option["label"]} for option in parameter.get("options", [])
]
}
if "options" in parameter
else {}
),
}
for parameter in quick_start["parameters"]
],
}
if kind == "supervisor-result":
run_id, separator, iteration_value = template_id.partition(":")
if not separator or not iteration_value.isdigit():
raise ValueError("supervisor result translation ID must be run_id:iteration")
record = next(
(
item
for item in self._load(run_id).supervisor_results
if isinstance(item, dict) and int(item.get("iteration", 0)) == int(iteration_value)
),
None,
)
response = record.get("response") if isinstance(record, dict) else None
if not isinstance(response, dict):
raise KeyError(template_id)
def display_fields(item: Any, fields: tuple[str, ...]) -> dict[str, str]:
return {
field: value
for field in fields
if isinstance((value := item.get(field)), str) and value.strip()
}
evaluation = response.get("evaluation")