okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
090e45adf
main
1#!/usr/bin/env python3 2"""One bounded Harness revision attempt, for Time-skip's `--revise-command`. 3 4Time-skip owns the job: it checkpoints, isolates a candidate directory, and decides from checks. 5This script owns only the *revision step* — it asks the pinned DeepSeek Harness for one bounded 6agent turn inside the candidate directory and returns when the turn reaches a terminal state. 7 8``` 9strata timeskip run --workspace DIR --prompt "..." \ 10--revise-command "python integrations/harness/revise_once.py" 11``` 12 13The contract Time-skip depends on: 14 15* the process runs with the **candidate directory** as its cwd, and only ever writes there; 16* the prompt arrives in `STRATA_TIMESKIP_PROMPT` and the attempt number in `STRATA_TIMESKIP_ATTEMPT`; 17* exit 0 means "an attempt was made" — *not* "the attempt succeeded". Whether it improved anything is 18decided by the checks, never by this script. A non-zero exit reports that the attempt itself could 19not be made (for example the Harness is not installed), which Time-skip records as a failed run 20rather than a rejected candidate. 21 22A bounded turn means all of: a wall-clock deadline, a per-attempt session, and a Harness that is 23stopped when the deadline passes — so a stuck agent cannot hold a Time-skip run open forever. 24""" 25 26from __future__import annotations 27 28import argparse 29import json 30import os 31import re 32import shutil 33import signal 34import subprocess 35import sys 36import tempfile 37import time 38from pathlib import Path 39 40HERE = Path (__file__ ).resolve ().parent 41sys .path .insert (0 ,str (HERE )) 42 43from _bridge import (# noqa: E402 44DEFAULT_DSH , 45PROFILE_PATCH , 46BridgeError , 47gateway_call , 48http_json , 49read_session_events , 50wait_for_agent_url , 51) 52 53#: The whole attempt's wall-clock bound. Time-skip's own phases are unbounded by design; the bound 54#: belongs to the thing that can run away, which is the agent turn. 55DEFAULT_DEADLINE_S = 240.0 56 57INSTRUCTIONS = """You are revising a copy of a user's work. Follow these rules exactly. 58 591. Work only inside the current directory. It is an isolated copy: the user's original is safe and 60you cannot see it. Never try to read or write outside this directory. 612. Make the smallest change that achieves the goal. Do not reorganise, rename or reformat anything 62that is not needed for the goal. 633. Do not add commentary files, notes, README files or explanations of what you did. Change the 64work itself. 654. If the goal cannot be achieved from what is here, change nothing and say so in one sentence. 66 67When you are finished, reply with a single short sentence describing what you changed.""" 68 69 70def main ()-> int : 71ap = argparse .ArgumentParser (description = __doc__ , 72formatter_class = argparse .RawDescriptionHelpFormatter ) 73ap .add_argument ("--dsh" ,default = os .environ .get ("DSH_CLI" ,DEFAULT_DSH )) 74ap .add_argument ("--workspace" ,default = None , 75help = "the candidate directory (default: the current directory)" ) 76ap .add_argument ("--deadline" ,type = float , 77default = float (os .environ .get ("STRATA_TIMESKIP_DEADLINE_S" ,DEFAULT_DEADLINE_S ))) 78ap .add_argument ("--keep" ,action = "store_true" , 79help = "keep the per-attempt Harness home for inspection" ) 80ap .add_argument ("--print-session" ,action = "store_true" , 81help = "print the session id and its event types, for diagnosis" ) 82args = ap .parse_args () 83 84candidate = Path (args .workspace or os .getcwd ()).resolve () 85prompt = os .environ .get ("STRATA_TIMESKIP_PROMPT" ,"" ).strip () 86attempt = os .environ .get ("STRATA_TIMESKIP_ATTEMPT" ,"1" ) 87if not prompt : 88"revise_once: STRATA_TIMESKIP_PROMPT is empty; nothing to ask for" ,file = sys .stderr ) 89return 2 90if not candidate .is_dir (): 91f"revise_once: { candidate } is not a directory" ,file = sys .stderr ) 92return 2 93 94dsh = Path (args .dsh ) 95if not dsh .exists (): 96f"revise_once: the Harness CLI is not at { dsh } ; set DSH_CLI or --dsh" ,file = sys .stderr ) 97return 3 98if not PROFILE_PATCH .exists (): 99f"revise_once: the Strata profile is not at { PROFILE_PATCH } " ,file = sys .stderr ) 100return 3 101 102# Each attempt gets its own Harness home. That keeps sessions and approvals scoped to the 103# attempt, and means a crashed attempt cannot corrupt the next one's state. 104home = Path (tempfile .mkdtemp (prefix = f"strata-revise-a { attempt } -" )) 105 (home / "sessions" ).mkdir (parents = True ,exist_ok = True ) 106agent = None 107deadline = time .time ()+ args .deadline 108try : 109env = dict (os .environ ) 110env ["DSH_HOME" ]= str (home ) 111log = (home / "dsh.log" ).open ("w" ) 112agent = subprocess .Popen ( 113 [str (dsh ),"--profile" ,"web" ,"--patch" ,str (PROFILE_PATCH ),"--port" ,"0" ,"--no-open" ], 114cwd = str (candidate ),env = env ,stdout = log ,stderr = subprocess .STDOUT ) 115text = wait_for_agent_url (home / "dsh.log" ,agent ,timeout = min (120.0 ,args .deadline )) 116m = re .search (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ,text ) 117if not m : 118raise BridgeError ("the Harness printed no usable URL" ) 119port ,token = int (m .group (1 )),m .group (2 ) 120 121# `interactions=answer` is required, or every approval request fails closed as 122# 'unavailable'. A revision attempt that needs to run a command must be able to be approved. 123_ ,_ ,set_cookie = http_json ("GET" ,"127.0.0.1" ,port , 124f"/?token= { token } &interactions=answer" ) 125cookie = set_cookie .split (";" ,1 )[0 ] 126if not cookie .startswith ("dsh-auth-" ): 127raise BridgeError ("no operator cookie was issued" ) 128 129created = gateway_call ("127.0.0.1" ,port ,cookie ,"c1" ,"session/create" , 130 {"request" : {"cwd" :str (candidate )}}) 131session_id = created ["sessionId" ] 132gateway_call ("127.0.0.1" ,port ,cookie ,"p1" ,"session/prompt" , 133 {"request" : {"requestId" :f"timeskip- { attempt } " ,"sessionId" :session_id , 134"mode" :"queue" , 135"content" : [{"type" :"text" , 136"text" :f" { INSTRUCTIONS } \n\nGoal:\n { prompt } " }]}}) 137 138# Wait for a terminal state, or the deadline, whichever comes first. 139events :list [dict ]= [] 140note = "" 141while time .time ()< deadline : 142events = read_session_events (session_id ,home = home ) 143end = next ((e for e in events if e .get ("type" )== "turn/end" ),None ) 144if end is not None : 145reason = (end .get ("data" )or {}).get ("reason" )or {} 146if reason .get ("kind" )!= "completed" : 147f"revise_once: the turn ended as { json . dumps ( reason )[: 200 ] } " ,file = sys .stderr ) 148return 1 149assistant = next ((e for e in events if e .get ("type" )== "assistant/message" ),None ) 150if assistant : 151message = (assistant .get ("data" )or {}).get ("message" )or {} 152parts = message .get ("content" )or [] 153note = " " .join (p .get ("text" ,"" )for p in parts 154if isinstance (p ,dict )and p .get ("type" )in ("text" ,"reasoning" )) 155break 156time .sleep (0.5 ) 157else : 158f"revise_once: the attempt did not finish within { args . deadline :.0f } s; " 159"stopping the Harness and reporting a made attempt" ,file = sys .stderr ) 160return 1 161 162if args .print_session : 163f"session { session_id } : { [ e . get ( 'type' ) for e in events ] } " ,file = sys .stderr ) 164# Exit 0 means an attempt was made. What it achieved is the checks' business. 165note or f"attempt { attempt } completed" ).strip ()[:500 ]) 166return 0 167 168except BridgeError as e : 169f"revise_once: { e } " ,file = sys .stderr ) 170return 1 171except Exception as e :# noqa: BLE001 - report, and let Time-skip record a failed run 172f"revise_once: { type ( e ). __name__ } : { e } " ,file = sys .stderr ) 173return 1 174finally : 175if agent is not None and agent .poll ()is None : 176try : 177agent .send_signal (signal .SIGTERM ) 178agent .wait (timeout = 8 ) 179except Exception : 180try : 181agent .kill () 182except Exception : 183pass 184if not args .keep : 185shutil .rmtree (home ,ignore_errors = True ) 186else : 187f"revise_once: kept { home } " ,file = sys .stderr ) 188 189 190if __name__ == "__main__" : 191sys .exit (main ())