APISHIFT / server /environment.py
yaswanth169's picture
Initial APIShift env push
3040bf7 verified
Raw History Blame Contribute Delete
19.3 kB
"""APIShiftEnvironment — the OpenEnv Environment implementation.
Implements reset(), step(), state(). Routes Manager actions to the
appropriate specialist, accumulates episode state, and returns rewards.
"""
import uuid
from typing import Any, Dict, List, Optional
from models import (
APIShiftAction,
APIShiftObservation,
APIShiftState,
DetectedChange,
GeneratedPatch,
ManagerCommand,
MemoryHit,
)
from scenarios import get_scenario, list_scenarios, Scenario
from server.curriculum import CurriculumAgent, DifficultySampler
from server.episode_logger import EpisodeLogger
from server.memory import LessonRetriever, MemoryAgent
from server.program_loader import ProgramLoader
from server.reward import compute_total
from server.specialists import (
DiffSpecialist,
PatchSpecialist,
RollbackSpecialist,
TestSpecialist,
)
# ---------------------------------------------------------------------
# OpenEnv Environment base import (graceful fallback if not installed)
# ---------------------------------------------------------------------
try:
from openenv.core.env_server import Environment as _BaseEnv
except ImportError:
from abc import ABC
class _BaseEnv(ABC): # type: ignore[no-redef]
SUPPORTS_CONCURRENT_SESSIONS = True
COMMAND_LIST: List[str] = [
"inspect",
"dispatch_diff",
"classify_impact",
"dispatch_patch",
"dispatch_test",
"dispatch_rollback",
"read_memory",
"submit",
]
def optimal_steps_for(scenario: Scenario) -> int:
"""Heuristic 'minimum-needed-for-success' step count, used by the
simplicity bonus."""
n_changes = max(1, len(scenario.ground_truth_changes))
# diff (1) + classify (1) + patch * n + test (1) + rollback (1) + submit (1)
return 5 + n_changes
class APIShiftEnvironment(_BaseEnv):
SUPPORTS_CONCURRENT_SESSIONS = True
MAX_STEPS = 30
def __init__(
self,
program_path: str = "apishift_program.md",
lessons_path: str = "lessons.md",
curriculum_path: str = "curriculum.md",
results_path: str = "results.tsv",
):
# Initialize the openenv-core base (sets transform / rubric attrs).
try:
super().__init__()
except TypeError:
# Fallback Environment from the local stub takes no args
pass
self._diff = DiffSpecialist()
self._patch = PatchSpecialist()
self._test = TestSpecialist()
self._rollback = RollbackSpecialist()
self._program_loader = ProgramLoader(program_path)
self._memory_agent = MemoryAgent(lessons_path=lessons_path)
self._retriever = LessonRetriever(lessons_path=lessons_path)
self._sampler = DifficultySampler(curriculum_path=curriculum_path)
self._curriculum_agent = CurriculumAgent(
curriculum_path=curriculum_path,
results_path=results_path,
)
self._episode_logger = EpisodeLogger(results_path=results_path)
self._scenario: Optional[Scenario] = None
self._state = APIShiftState()
self._done = False
self._action_log: List[Dict] = []
self._lessons_used: List[str] = []
self._last_command: str = ""
# ----- OpenEnv interface --------------------------------------------------
def reset(
self,
seed: Optional[int] = None,
episode_id: Optional[str] = None,
**kwargs: Any,
) -> APIShiftObservation:
"""Begin a new episode. Either pass a `task_id` (named scenario)
or omit it to let the CurriculumAgent pick one."""
task_id = kwargs.get("task_id") or self._sampler.pick()
self._scenario = get_scenario(scenario_id=task_id, seed=seed or 42)
self._action_log = []
self._lessons_used = []
self._done = False
self._last_command = ""
ep_id = episode_id or f"ep_{uuid.uuid4().hex[:8]}"
self._state = APIShiftState(
episode_id=ep_id,
step_count=0,
scenario_id=self._scenario.scenario_id,
difficulty=self._scenario.difficulty,
initial_quality=0.0,
current_quality=0.0,
component_rewards={},
diff_call_count=0,
test_call_count=0,
rollback_called=False,
submitted=False,
)
memory_hits = self._retriever.retrieve(self._scenario_summary())
program_section = self._program_loader.section_for_step("", 0)
recent_summary = self._recent_summary()
return self._build_observation(
memory_hits=memory_hits,
program_section=program_section,
recent_summary=recent_summary,
message=(
f"Loaded scenario {self._scenario.scenario_id} "
f"({self._scenario.difficulty}). "
f"{len(memory_hits)} relevant lessons retrieved from memory."
),
)
def step(
self,
action: APIShiftAction,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> APIShiftObservation:
if self._done:
return self._build_observation(message="Episode already finished.")
if self._scenario is None:
return self._build_observation(
message="No active episode; call reset() first.",
error="no_active_episode",
)
self._state.step_count += 1
self._last_command = action.command
# Route command
try:
message = self._route(action)
error = None
except Exception as exc: # noqa: BLE001
message = f"Action raised: {exc}"
error = str(exc)[:200]
# Compute reward
prev_quality = self._state.current_quality
total, components = compute_total(
detected=self._detected_changes,
patches=self._generated_patches,
test_result=self._last_test_result,
rollback=self._rollback_plan,
ground_truth=self._scenario.ground_truth_changes,
language=self._scenario.language,
steps_taken=self._state.step_count,
optimal_steps=optimal_steps_for(self._scenario),
rollback_called=self._state.rollback_called,
)
self._state.current_quality = total
self._state.component_rewards = components
delta = round(total - prev_quality, 4)
# Termination conditions
if action.command == "submit":
self._state.submitted = True
self._done = True
elif self._state.step_count >= self.MAX_STEPS:
self._done = True
message = (message + " | Max steps reached, auto-submitting.").strip()
# Log action for memory mining
self._action_log.append({
"command": action.command,
"target": action.target,
"rationale": action.rationale,
})
if self._done:
self._finalize()
return self._build_observation(
reward=delta if not self._done else total,
done=self._done,
message=message,
error=error,
)
@property
def state(self) -> APIShiftState:
return self._state
# ----- internal data accessors --------------------------------------------
@property
def _detected_changes(self) -> List[DetectedChange]:
return getattr(self, "_dc_cache", [])
@_detected_changes.setter
def _detected_changes(self, v):
self._dc_cache = v
@property
def _generated_patches(self) -> List[GeneratedPatch]:
return getattr(self, "_gp_cache", [])
@_generated_patches.setter
def _generated_patches(self, v):
self._gp_cache = v
@property
def _last_test_result(self):
return getattr(self, "_ltr_cache", None)
@_last_test_result.setter
def _last_test_result(self, v):
self._ltr_cache = v
@property
def _rollback_plan(self):
return getattr(self, "_rp_cache", None)
@_rollback_plan.setter
def _rollback_plan(self, v):
self._rp_cache = v
# ----- command routing ----------------------------------------------------
def _route(self, action: APIShiftAction) -> str:
cmd = action.command
if cmd == "inspect":
return self._cmd_inspect(action)
if cmd == "dispatch_diff":
return self._cmd_diff(action)
if cmd == "classify_impact":
return self._cmd_classify(action)
if cmd == "dispatch_patch":
return self._cmd_patch(action)
if cmd == "dispatch_test":
return self._cmd_test(action)
if cmd == "dispatch_rollback":
return self._cmd_rollback(action)
if cmd == "read_memory":
return self._cmd_read_memory(action)
if cmd == "submit":
return self._cmd_submit(action)
return f"Unknown command '{cmd}'."
def _cmd_inspect(self, action: APIShiftAction) -> str:
target = action.target or ""
if target.endswith(".py") or target.endswith(".js") or target.endswith(".ts") or target.endswith(".go"):
content = self._scenario.client_files.get(target, "")
if content:
return f"Inspected file {target}: {len(content)} chars."
return f"File {target} not found in client surface."
return (
f"Scenario {self._scenario.scenario_id}: "
f"{len(self._scenario.client_files)} client files, "
f"{len(self._scenario.ground_truth_changes)} expected breaking changes "
f"(label hidden from agent)."
)
def _cmd_diff(self, action: APIShiftAction) -> str:
self._state.diff_call_count += 1
if self._state.diff_call_count > 2:
return "Diff already run twice — use read_memory or proceed to patch."
changes = self._diff.diff(self._scenario.v1_spec, self._scenario.v2_spec)
self._detected_changes = changes
return (
f"DiffSpecialist returned {len(changes)} change(s); "
f"{sum(1 for c in changes if c.severity == 'breaking')} breaking."
)
def _cmd_classify(self, action: APIShiftAction) -> str:
# Manager-supplied severity overrides for any detected change_id.
overrides = action.payload.get("classifications", {})
if not overrides:
return "No classifications provided in payload."
n = 0
for c in self._detected_changes:
if c.change_id in overrides:
ov = overrides[c.change_id]
if isinstance(ov, dict):
if "severity" in ov:
c.severity = ov["severity"]
if "blast_radius" in ov:
c.blast_radius = ov["blast_radius"]
n += 1
return f"Updated classification on {n} change(s)."
def _cmd_patch(self, action: APIShiftAction) -> str:
target_change_id = action.payload.get("change_id") or action.target
target_file = action.payload.get("file_path") or self._first_file()
if not target_change_id:
return "Missing change_id in payload."
if not target_file:
return "No client files available to patch."
change = next(
(c for c in self._detected_changes if c.change_id == target_change_id),
None,
)
if change is None:
return f"change_id {target_change_id} not in detected changes."
patch = self._patch.patch(change, target_file, self._scenario.language)
# Replace existing patch for the same change if present
existing = [p for p in self._generated_patches if p.targets_change_id != target_change_id]
existing.append(patch)
self._generated_patches = existing
return f"Patched {target_change_id} in {target_file} (confidence {patch.confidence:.2f})."
def _cmd_test(self, action: APIShiftAction) -> str:
self._state.test_call_count += 1
result = self._test.run(
self._generated_patches,
self._scenario.ground_truth_changes,
self._scenario.language,
)
# convert dict ground truth to DetectedChange-shaped objects
self._last_test_result = result
return (
f"TestSpecialist: {result.passed}/{result.total} passed "
f"({result.failed} failures)."
)
def _cmd_rollback(self, action: APIShiftAction) -> str:
plan = self._rollback.plan(self._generated_patches)
self._rollback_plan = plan
self._state.rollback_called = True
return (
f"RollbackSpecialist produced plan {plan.plan_id} "
f"(reversible={plan.is_reversible})."
)
def _cmd_read_memory(self, action: APIShiftAction) -> str:
hits = self._retriever.retrieve(self._scenario_summary())
for h in hits:
if h.lesson_id not in self._lessons_used:
self._lessons_used.append(h.lesson_id)
return f"Re-fetched memory: {len(hits)} relevant lesson(s)."
def _cmd_submit(self, action: APIShiftAction) -> str:
return "Submission accepted; finalizing scoring."
# ----- finalization -------------------------------------------------------
def _finalize(self):
# Episode log
status = "success" if self._state.current_quality >= 0.65 else (
"partial" if self._state.current_quality >= 0.40 else "failure"
)
summary = self._episode_summary_text()
self._episode_logger.append(
episode_id=self._state.episode_id or "ep_unknown",
scenario_id=self._scenario.scenario_id,
difficulty=self._scenario.difficulty,
score=self._state.current_quality,
n_steps=self._state.step_count,
lessons_used=self._lessons_used,
status=status,
summary=summary,
)
# Memory update
dominant = self._dominant_change_type()
self._memory_agent.update(
episode_id=self._state.episode_id or "ep_unknown",
score=self._state.current_quality,
n_steps=self._state.step_count,
action_log=self._action_log,
dominant_change_type=dominant,
component_rewards=self._state.component_rewards,
)
# Curriculum update (every N episodes)
ep_count = self._episode_logger.episode_count()
self._curriculum_agent.maybe_update(ep_count)
# ----- helpers ------------------------------------------------------------
def _build_observation(
self,
*,
reward: Optional[float] = None,
done: Optional[bool] = None,
message: str = "",
error: Optional[str] = None,
memory_hits: Optional[List[MemoryHit]] = None,
program_section: Optional[str] = None,
recent_summary: Optional[str] = None,
) -> APIShiftObservation:
if self._scenario is None:
return APIShiftObservation(
done=done if done is not None else self._done,
reward=reward,
message=message,
last_action_error=error,
available_commands=COMMAND_LIST,
max_steps=self.MAX_STEPS,
)
if memory_hits is None:
memory_hits = self._retriever.retrieve(self._scenario_summary())
for h in memory_hits:
if h.lesson_id not in self._lessons_used:
self._lessons_used.append(h.lesson_id)
if program_section is None:
program_section = self._program_loader.section_for_step(
self._last_command, self._state.step_count,
)
if recent_summary is None:
recent_summary = self._recent_summary()
return APIShiftObservation(
done=done if done is not None else self._done,
reward=reward,
program_section=program_section,
scenario_id=self._scenario.scenario_id,
task_description=self._scenario.description,
framework=self._scenario.framework,
language=self._scenario.language,
v1_spec_summary=self._spec_summary(self._scenario.v1_spec),
v2_spec_summary=self._spec_summary(self._scenario.v2_spec),
client_files=list(self._scenario.client_files.keys()),
inspected_file_content="",
detected_changes=self._detected_changes,
generated_patches=self._generated_patches,
last_test_result=self._last_test_result,
rollback_plan=self._rollback_plan,
memory_hits=memory_hits,
recent_episode_summary=recent_summary,
quality_score=self._state.current_quality,
steps_taken=self._state.step_count,
max_steps=self.MAX_STEPS,
available_commands=COMMAND_LIST,
message=message,
last_action_error=error,
)
def _spec_summary(self, spec: Dict[str, Any]) -> str:
info = spec.get("info", {})
title = info.get("title", "<no title>")
version = info.get("version", "<no version>")
paths = list(spec.get("paths", {}).keys())
return f"{title} v{version} — endpoints: {paths}"
def _scenario_summary(self) -> str:
if self._scenario is None:
return ""
v1 = self._scenario.v1_spec.get("info", {})
v2 = self._scenario.v2_spec.get("info", {})
return (
f"{v1.get('title', '')} {v1.get('version', '')} -> "
f"{v2.get('title', '')} {v2.get('version', '')} "
f"language={self._scenario.language} framework={self._scenario.framework}"
)
def _first_file(self) -> str:
if self._scenario and self._scenario.client_files:
return next(iter(self._scenario.client_files.keys()))
return ""
def _dominant_change_type(self) -> Optional[str]:
if not self._scenario:
return None
gt = self._scenario.ground_truth_changes
if not gt:
return None
counts: Dict[str, int] = {}
for g in gt:
counts[g["change_type"]] = counts.get(g["change_type"], 0) + 1
return max(counts, key=counts.get)
def _episode_summary_text(self) -> str:
commands = [a["command"] for a in self._action_log]
return f"actions={'+'.join(commands) if commands else '(none)'}"
def _recent_summary(self) -> str:
ep_count = self._episode_logger.episode_count()
return (
f"Total episodes logged: {ep_count}. "
f"Lessons memorized: {self._count_lessons()}."
)
def _count_lessons(self) -> int:
from server.memory.lesson_schema import parse_lessons_md
import os
path = self._memory_agent.lessons_path
if not os.path.exists(path):
return 0
with open(path, "r", encoding="utf-8") as f:
return len(parse_lessons_md(f.read()))
def list_tasks() -> List[Dict[str, Any]]:
"""Public helper for /tasks endpoint."""
return list_scenarios()