FatUnc6969's picture
Publish reviewed Borderland recovery research artifact
a8aea51 verified
Raw History Blame Contribute Delete
7.99 kB
"""Explicit conversation selection; simulator state never enters this module."""
import copy
import json
from dataclasses import dataclass, field
SYSTEM = "You control one Borderland campaign. Use only public observations and legal actions. Escape is verified only by the engine. Issue exactly one tool call per decision. Use replace_notebook to preserve evidence within its displayed capacity. Blackout starts a fresh conversation with only your notebook and current public state."
def wire(value):
return value.to_dict() if hasattr(value, "to_dict") else value
def actor_view(transition):
data = wire(transition)
return {key: copy.deepcopy(data[key]) for key in
("observation", "legal_actions", "error", "reward", "terminated",
"truncated", "outcome", "context_reset") if key in data}
def actor_transition(transition):
from borderland.domain import Action, ActionError, Observation, Phase, Transition
public = actor_view(transition)
observation = public.pop("observation")
observation["phase"] = Phase(observation["phase"])
actions = tuple(Action(**action) for action in public.pop("legal_actions"))
error = public.pop("error", None)
return Transition(Observation(**observation), actions,
error=None if error is None else ActionError(**error), **public)
def notebook_budget(notebook, selected_limit=None):
field = "capacity_bytes" if "capacity_bytes" in notebook else "capacity_chars"
capacity = notebook[field]
return field, capacity if selected_limit is None else min(capacity, selected_limit)
def bounded_note(text, capacity, field):
return text.encode("utf-8")[:capacity].decode("utf-8", errors="ignore") if field == "capacity_bytes" else text[:capacity]
@dataclass
class ContextSelector:
condition: str = "full_history"
recent_messages: int = 8
notebook_chars: int = 768
messages: list = field(default_factory=list)
resets: int = 0
_phase: int | None = None
def __post_init__(self):
if self.condition not in {"full_history", "recent", "bounded_notebook"}:
raise ValueError("unknown context condition")
if self.recent_messages < 1 or self.notebook_chars < 0:
raise ValueError("invalid context bounds")
def observe(self, transition):
data = wire(transition)
observation = data["observation"]
phase = int(observation["phase"])
boundary = phase == 6 and self._phase != 6
self._phase = phase
if boundary:
self.messages.clear()
self.resets += 1
public = self._view(data)
message = {"role": "user", "content": json.dumps(public, sort_keys=True)}
if self.condition == "bounded_notebook":
self.messages = [message]
else:
self.messages.append(message)
return boundary
def _view(self, transition):
public = actor_view(transition)
notebook = public["observation"]["notebook"]
field, capacity = notebook_budget(notebook, self.notebook_chars)
notebook[field] = capacity
notebook["text"] = bounded_note(notebook["text"], capacity, field)
if "used_bytes" in notebook:
notebook["used_bytes"] = len(notebook["text"].encode("utf-8"))
return public
def assistant(self, message):
retained = {key: copy.deepcopy(message[key]) for key in
("role", "content", "reasoning_content", "tool_calls") if key in message}
retained["role"] = "assistant"
self.messages.append(retained)
def tool(self, call_id, result):
data = wire(result)
if isinstance(data, dict) and "observation" in data:
data = self._view(data)
self.messages.append({"role": "tool", "tool_call_id": call_id,
"content": json.dumps(data, sort_keys=True)})
def selected(self):
selected = self.messages
if self.condition == "recent" and len(selected) > self.recent_messages:
start = len(selected) - self.recent_messages
while start < len(selected) and selected[start]["role"] == "tool":
start += 1
selected = selected[start:]
if self.condition == "bounded_notebook":
memory = " Each decision receives only the current public state and saved notebook. Earlier observations and reasoning are unavailable. Save needed evidence before taking an action that replaces it."
elif self.condition == "recent":
memory = f" Only the most recent {self.recent_messages} conversation messages are retained before Blackout. Save evidence that may leave that window."
else:
memory = " Public conversation history is retained until the Blackout boundary."
return [{"role": "system", "content": SYSTEM + memory}] + copy.deepcopy(selected)
class CampaignContext(ContextSelector):
def __init__(self, records=()):
super().__init__("full_history", notebook_chars=768)
self.records = []
self._record_bytes = set()
for record in records:
self._expose(record)
def _expose(self, record):
encoded = json.dumps(record, sort_keys=True, separators=(",", ":"))
if encoded not in self._record_bytes:
self._record_bytes.add(encoded)
self.records.append(copy.deepcopy(record))
def observe(self, transition):
data = wire(transition)
phase = int(data["observation"]["phase"])
if phase == 6 and self._phase != 6:
self.records.clear()
self._record_bytes.clear()
if phase == 3 and not data.get("error"):
for record in data["observation"]["board"].get("records", []):
self._expose(record)
return super().observe(transition)
def current_packet(self):
current = copy.deepcopy(next(message for message in reversed(self.messages)
if message["role"] == "user"))
value = json.loads(current["content"])
value["publicArchiveIndex"] = copy.deepcopy(self.records)
current["content"] = json.dumps(value, sort_keys=True)
return current
def scripted_notebook(observation, previous="", capacity=768):
"""Scripted compression of exposed public board records, explicitly not an LLM."""
field, capacity = notebook_budget(observation["notebook"], capacity)
def fits(text):
return bounded_note(text, capacity, field) == text
board = observation.get("board", {})
try:
facts = json.loads(previous) if previous.startswith("{") else {}
if not isinstance(facts, dict):
facts = {}
except ValueError:
facts = {}
for key in ("live_sensor", "current_record", "current_claim", "record", "claim", "checks", "discovered_edges"):
if board.get(key) is not None:
facts[key] = board[key]
if board.get("live_sensor") is not None and "latch" in board:
facts["sensor_latch"] = board["latch"]
facts["experimental_bus"] = ("west", "east")[board["live_sensor"] ^ (board["latch"] & 1)]
for record in board.get("records", []):
if record.get("authenticated"):
records = facts.setdefault("authenticated_records", {})
previous_record = records.get(record.get("subject"))
if previous_record is None or record.get("issued_at", 0) > previous_record.get("issued_at", 0):
records[record["subject"]] = record
encoded = json.dumps(facts, sort_keys=True, separators=(",", ":"))
if fits(encoded):
return encoded
for key in ("discovered_edges", "checks", "current_claim", "current_record", "claim", "record"):
facts.pop(key, None)
encoded = json.dumps(facts, sort_keys=True, separators=(",", ":"))
if fits(encoded):
return encoded
return encoded if fits(encoded) else ""