okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
99866a47a
main
1"""Real Time-skip: retain a good result, try a bounded improvement, check it, and decide honestly. 2 3This replaces the supplied 28-second scripted flow. The contract it implements is the integration 4specification's section 5: 5 6queued -> checkpointing -> generating -> checking -> decision -> completed 7with repeated generating/checking for bounded attempts, and the alternate terminal states 8cancelled, failed, interrupted, needs_user_review. 9 10Design rules that are load-bearing, and the reason each one exists: 11 12* **Nothing is fabricated.** A check that did not run is ``unknown``, never ``passed``. A run whose 13evidence is insufficient ends ``needs_user_review``; it never invents an objective score. There is 14no timer that decides anything: phases advance because work completed, not because time passed. 15* **The last good version survives everything.** Checkpoints are content-addressed snapshots taken 16before any speculative work. Cancel, crash and failure leave the selected checkpoint intact. 17* **Candidates are isolated.** Each attempt writes into its own directory; nothing is applied to the 18workspace until an explicit ``apply``, which refuses if the destination changed since it was 19captured. A user edit becomes a conflict, never a silent overwrite. 20* **Only deterministic checks gate.** A model's opinion can advise, but it cannot assert objective 21correctness, so it is recorded as advice and never promotes a candidate on its own. 22* **Applying is a separate, verified, reversible step.** It checks digests, writes a rollback copy, 23and restores on failure. 24 25The module is deliberately stdlib-only: the terminal distribution's serving path and the App Host 26both import it, and neither may depend on the agent runtime or a web framework. 27""" 28 29from __future__import annotations 30 31import hashlib 32import json 33import os 34import shutil 35import subprocess 36import time 37import uuid 38from dataclasses import dataclass ,field 39from pathlib import Path 40from typing import Any ,Callable ,Iterable ,Sequence 41 42from strata_control import atomic 43 44SCHEMA_VERSION = 1 45 46# --------------------------------------------------------------------------- phases and states 47 48PHASES = ("queued" ,"checkpointing" ,"generating" ,"checking" ,"decision" ,"completed" ) 49TERMINAL = ("completed" ,"cancelled" ,"failed" ,"interrupted" ,"needs_user_review" ) 50 51#: Every phase that a run can be observed in, including terminal states. 52STATES = PHASES + TERMINAL 53 54#: Outcome vocabulary for one check. `unknown` is a real answer and must survive to the report. 55CHECK_OUTCOMES = ("passed" ,"failed" ,"unknown" ,"error" ) 56 57#: The most attempts after the baseline. The specification's default is at most two revisions. 58DEFAULT_MAX_ATTEMPTS = 2 59 60 61class TimeSkipError (RuntimeError ): 62"""A refusal the caller should surface verbatim.""" 63 64 65# --------------------------------------------------------------------------- checks 66 67@dataclass( frozen = True ) 68class CheckSpec : 69"""One declared check. 70 71``kind`` is ``deterministic`` or ``advice``. Only deterministic checks can gate a decision, 72which is how a model critique is kept from asserting objective correctness. 73""" 74 75id :str 76command :str | None = None 77#: A path whose existence and digest is the check (used when no command is declared). 78file :str | None = None 79#: Expected content digest of `file`, if the check is a content assertion. 80sha256 :str | None = None 81kind :str = "deterministic" 82description :str = "" 83timeout_s :float = 300.0 84 85@staticmethod 86def from_dict (raw :dict [str ,Any ])-> "CheckSpec" : 87if not isinstance (raw ,dict )or not raw .get ("id" ): 88raise TimeSkipError ("each check needs an id" ) 89kind = raw .get ("kind" ,"deterministic" ) 90if kind not in ("deterministic" ,"advice" ): 91raise TimeSkipError (f"check { raw [ 'id' ] } : kind must be 'deterministic' or 'advice'" ) 92if not raw .get ("command" )and not raw .get ("file" ): 93raise TimeSkipError (f"check { raw [ 'id' ] } : needs a command or a file" ) 94return CheckSpec ( 95id = str (raw ["id" ]), 96command = raw .get ("command" ), 97file = raw .get ("file" ), 98sha256 = raw .get ("sha256" ), 99kind = kind , 100description = str (raw .get ("description" )or "" ), 101timeout_s = float (raw .get ("timeout_s" )or 300.0 ), 102 ) 103 104 105@dataclass 106class CheckResult : 107id :str 108kind :str 109outcome :str 110detail :str = "" 111exit_code :int | None = None 112stdout_tail :str = "" 113stderr_tail :str = "" 114sha256 :str | None = None 115duration_ms :int | None = None 116 117def to_dict (self )-> dict [str ,Any ]: 118return {k :v for k ,v in self .__dict__ .items ()if v not in ("" ,None )or k in ("id" ,"kind" ,"outcome" )} 119 120 121#: cmd.exe's own "command not found" exit code. 122CMD_NOT_FOUND = 9009 123#: Things cmd.exe runs itself, so there is no program to look up. 124_CMD_BUILTINS = frozenset (( 125"assoc call cd chdir cls copy date del dir echo endlocal erase exit for ftype goto if md mkdir mklink " 126"move path pause popd prompt pushd rd rem ren rename rmdir set setlocal shift start time title type " 127"ver verify vol" ).split ()) 128_CMD_OPERATORS = set ("&|<>^%" ) 129 130 131def _shell_could_not_run (command :str ,returncode :int ,env :dict [str ,str ])-> bool : 132"""True when the shell reported that the program does not exist or cannot be executed. 133 134POSIX ``sh`` says so with 126/127. ``cmd.exe`` says 9009 from a batch context but often a plain 1 135from ``cmd /c`` (and the message is localised), so for exit 1 the first word is looked up on PATH 136instead of trusting the code. A real failure of an existing program stays ``failed``. 137""" 138if os .name != "nt" : 139return returncode in (126 ,127 ) 140if returncode == CMD_NOT_FOUND : 141return True 142if returncode != 1 : 143return False 144text = command .strip () 145if not text or _CMD_OPERATORS & set (text ): 146return False # a pipeline or redirect: the failing part is unknowable from here 147if text .startswith ('"' ): 148program = text [1 :].split ('"' ,1 )[0 ] 149else : 150program = text .split (None ,1 )[0 ] 151if program .lower ()in _CMD_BUILTINS : 152return False 153return shutil .which (program ,path = env .get ("PATH" )or env .get ("Path" ))is None 154 155 156def _run_shell (command :str ,cwd :str ,timeout :float ,env :dict [str ,str ])-> "subprocess.CompletedProcess[str]" : 157"""``subprocess.run(shell=True)`` that also stops what the shell started when the check times out. 158 159``cmd.exe /c`` is a parent process: killing it leaves the real program holding the output pipes, 160so a hung check would block here until it ended on its own. On Windows the whole tree is killed. 161""" 162if os .name != "nt" : 163return subprocess .run (command ,shell = True ,cwd = cwd ,capture_output = True ,text = True ,errors = "replace" , 164timeout = timeout ,env = env ) 165with subprocess .Popen (command ,shell = True ,cwd = cwd ,stdout = subprocess .PIPE ,stderr = subprocess .PIPE , 166text = True ,errors = "replace" ,env = env )as process : 167try : 168out ,err = process .communicate (timeout = timeout ) 169except subprocess .TimeoutExpired : 170subprocess .run (["taskkill" ,"/F" ,"/T" ,"/PID" ,str (process .pid )],capture_output = True ) 171process .communicate () 172raise 173return subprocess .CompletedProcess (command ,process .returncode ,out ,err ) 174 175 176def run_check (spec :CheckSpec ,workdir :Path ,env :dict [str ,str ]| None = None )-> CheckResult : 177"""Run one check and report what actually happened. 178 179A check that could not be run is ``unknown``; a check that ran and crashed is ``error``. Neither 180is ever reported as ``passed``. 181""" 182started = time .time () 183if spec .command : 184try : 185proc = _run_shell (spec .command ,str (workdir ),spec .timeout_s , {** os .environ ,** (env or {})}) 186except subprocess .TimeoutExpired : 187return CheckResult (spec .id ,spec .kind ,"unknown" , 188detail = f"timed out after { spec . timeout_s :.0f } s" , 189duration_ms = int ((time .time ()- started )* 1000 )) 190except OSError as e : 191return CheckResult (spec .id ,spec .kind ,"unknown" ,detail = f"could not run: { e } " ) 192tail = lambda s : (s or "" )[- 2000 :]# noqa: E731 - a local shorthand 193if _shell_could_not_run (spec .command ,proc .returncode , {** os .environ ,** (env or {})}): 194# The shell's own "not executable" / "command not found" (126/127 on sh, 9009 on cmd). 195# The check never ran, so this is `unknown`: reporting it as `failed` would blame the 196# candidate for a declaration mistake, and reporting it as `passed` would be worse. 197return CheckResult (spec .id ,spec .kind ,"unknown" , 198detail = f"the check's command could not be run (shell exit " 199f" { proc . returncode } ): { spec . command } " , 200exit_code = proc .returncode ,stderr_tail = tail (proc .stderr ), 201duration_ms = int ((time .time ()- started )* 1000 )) 202outcome = "passed" if proc .returncode == 0 else "failed" 203return CheckResult (spec .id ,spec .kind ,outcome ,exit_code = proc .returncode , 204stdout_tail = tail (proc .stdout ),stderr_tail = tail (proc .stderr ), 205duration_ms = int ((time .time ()- started )* 1000 )) 206 207# file assertion 208target = workdir / spec .file # type: ignore[operator] 209if not target .exists (): 210return CheckResult (spec .id ,spec .kind ,"failed" ,detail = f" { spec . file } is missing" ) 211digest = sha256_file (target ) 212if spec .sha256 and digest != spec .sha256 : 213return CheckResult (spec .id ,spec .kind ,"failed" , 214detail = f" { spec . file } digest { digest [: 12 ] } does not match the expected " 215f" { spec . sha256 [: 12 ] } " ,sha256 = digest ) 216return CheckResult (spec .id ,spec .kind ,"passed" ,sha256 = digest , 217duration_ms = int ((time .time ()- started )* 1000 )) 218 219 220def summarise (results :Sequence [CheckResult ])-> dict [str ,Any ]: 221"""Count outcomes without collapsing `unknown` into anything friendlier.""" 222counts = {k :0 for k in CHECK_OUTCOMES } 223for r in results : 224counts [r .outcome ]= counts .get (r .outcome ,0 )+ 1 225return {"total" :len (results ),** counts } 226 227 228# --------------------------------------------------------------------------- digests and snapshots 229 230def sha256_file (path :Path ,chunk :int = 1 << 20 )-> str : 231h = hashlib .sha256 () 232with path .open ("rb" )as fh : 233while True : 234block = fh .read (chunk ) 235if not block : 236break 237h .update (block ) 238return h .hexdigest () 239 240 241def inventory (root :Path ,ignore :Iterable [str ]= (".git" ,"__pycache__" ,".strata" ))-> list [dict [str ,Any ]]: 242"""A sorted relative-path/digest inventory of a directory tree. 243 244Digests are what make a checkpoint an identity rather than a label. Directories that belong to 245tooling rather than to the user's work are skipped. 246""" 247skip = set (ignore ) 248out :list [dict [str ,Any ]]= [] 249for dirpath ,dirnames ,filenames in os .walk (root ): 250dirnames [:]= sorted (d for d in dirnames if d not in skip ) 251for name in sorted (filenames ): 252p = Path (dirpath )/ name 253if p .is_symlink (): 254continue 255try : 256st = p .stat () 257except OSError : 258continue 259rel = p .relative_to (root ).as_posix () 260out .append ({"path" :rel ,"bytes" :st .st_size ,"sha256" :sha256_file (p )}) 261return out 262 263 264def inventory_digest (items :Sequence [dict [str ,Any ]])-> str : 265h = hashlib .sha256 () 266for it in items : 267h .update (f" { it [ 'path' ] } \0 { it [ 'bytes' ] } \0 { it [ 'sha256' ] } \n" .encode ()) 268return h .hexdigest () 269 270 271def copy_tree (src :Path ,dst :Path ,ignore :Iterable [str ]= (".git" ,"__pycache__" ,".strata" ))-> None : 272skip = set (ignore ) 273if dst .exists (): 274shutil .rmtree (dst ) 275dst .mkdir (parents = True ,exist_ok = True ) 276for dirpath ,dirnames ,filenames in os .walk (src ): 277dirnames [:]= [d for d in dirnames if d not in skip ] 278rel = Path (dirpath ).relative_to (src ) 279 (dst / rel ).mkdir (parents = True ,exist_ok = True ) 280for name in filenames : 281s = Path (dirpath )/ name 282if s .is_symlink (): 283continue 284shutil .copy2 (s ,dst / rel / name ,follow_symlinks = False ) 285 286 287# --------------------------------------------------------------------------- the run 288 289@dataclass 290class Checkpoint : 291id :str 292label :str 293path :str 294digest :str 295inventory :list [dict [str ,Any ]]= field (default_factory = list ) 296checks :list [dict [str ,Any ]]= field (default_factory = list ) 297parent :str | None = None 298created_at :float = field (default_factory = time .time ) 299 300 301@dataclass 302class Attempt : 303index :int 304prompt :str 305path :str 306checkpoint :str | None = None 307checks :list [dict [str ,Any ]]= field (default_factory = list ) 308decision :str | None = None # keep | reject | inconclusive 309reason :str = "" 310created_at :float = field (default_factory = time .time ) 311 312 313class TimeSkipRun : 314"""One Time-skip run, durable on disk after every transition. 315 316The runner is injected so this module never has to know how an agent is driven: the App Host 317passes a callable that performs one bounded revision attempt. That keeps the ownership boundary 318(Harness owns the loop) while Strata Control owns the job and its evidence. 319""" 320 321def __init__ (self ,root :Path ,workspace :Path ,prompt :str , 322checks :Sequence [CheckSpec ],max_attempts :int = DEFAULT_MAX_ATTEMPTS , 323run_id :str | None = None ,clock :Callable [[],float ]= time .time )-> None : 324self .id = run_id or uuid .uuid4 ().hex 325self .root = root / self .id 326self .workspace = Path (workspace ) 327self .prompt = prompt 328self .checks = list (checks ) 329self .max_attempts = max (0 ,int (max_attempts )) 330self .clock = clock 331self .state = "queued" 332self .started_at = self .clock () 333self .finished_at :float | None = None 334self .checkpoints :list [Checkpoint ]= [] 335self .attempts :list [Attempt ]= [] 336self .selected_checkpoint :str | None = None 337self .events :list [dict [str ,Any ]]= [] 338self .error :str | None = None 339self .decision :dict [str ,Any ]| None = None 340self ._cancel_requested = False 341self .root .mkdir (parents = True ,exist_ok = True ) 342 343# ---- persistence ----------------------------------------------------- 344 345@property 346def state_file (self )-> Path : 347return self .root / "run.json" 348 349def to_dict (self )-> dict [str ,Any ]: 350return { 351"schema_version" :SCHEMA_VERSION , 352"id" :self .id , 353"workspace" :str (self .workspace ), 354"prompt" :self .prompt , 355"state" :self .state , 356"started_at" :self .started_at , 357"finished_at" :self .finished_at , 358"max_attempts" :self .max_attempts , 359"checks" : [c .__dict__ for c in self .checks ], 360"checkpoints" : [c .__dict__ for c in self .checkpoints ], 361"attempts" : [a .__dict__ for a in self .attempts ], 362"selected_checkpoint" :self .selected_checkpoint , 363"events" :self .events , 364"error" :self .error , 365"decision" :self .decision , 366"cancel_requested" :self ._cancel_requested , 367 } 368 369def save (self )-> None : 370tmp = self .state_file .with_suffix (".tmp" ) 371tmp .write_text (json .dumps (self .to_dict (),indent = 2 ),encoding = "utf-8" ) 372atomic .replace (tmp ,self .state_file ) 373 374@staticmethod 375def load (root :Path ,run_id :str )-> dict [str ,Any ]: 376p = Path (root )/ run_id / "run.json" 377if not p .exists (): 378raise TimeSkipError (f"no Time-skip run { run_id } " ) 379return json .loads (p .read_text (encoding = "utf-8" )) 380 381# ---- cancellation ---------------------------------------------------- 382 383def request_cancel (self )-> None : 384"""Ask the run to stop at the next phase boundary. 385 386Cancellation is cooperative and never claims the work stopped before it did: the run reaches 387`cancelled` when the running phase observes the flag, and the last complete checkpoint stays 388selected throughout. 389""" 390self ._cancel_requested = True 391self .save () 392 393def _check_cancel (self )-> None : 394if self ._cancel_requested : 395raise _Cancelled () 396 397# ---- events ---------------------------------------------------------- 398 399def _enter (self ,state :str ,** extra :Any )-> None : 400if state not in STATES : 401raise TimeSkipError (f"unknown state { state !r } " ) 402self .state = state 403self .events .append ({"seq" :len (self .events ),"at" :self .clock (),"state" :state ,** extra }) 404self .save () 405 406# ---- phases ---------------------------------------------------------- 407 408def checkpoint (self ,label :str ,source :Path | None = None ,parent :str | None = None )-> Checkpoint : 409"""Snapshot a directory and record what it contained.""" 410src = Path (source or (self .workspace if label == "baseline" else self .workspace )) 411# `pending` holds speculative work; the workspace itself is only read here. 412cp_id = f"cp { len ( self . checkpoints ) + 1 } - { label } " 413dest = self .root / "checkpoints" / cp_id 414copy_tree (src ,dest ) 415items = inventory (dest ) 416cp = Checkpoint (id = cp_id ,label = label ,path = str (dest ),digest = inventory_digest (items ), 417inventory = items ,parent = parent ) 418self .checkpoints .append (cp ) 419self .save () 420return cp 421 422def run (self ,revise :Callable [[Path ,str ,int ],str | None ])-> dict [str ,Any ]: 423"""Execute the whole state machine. 424 425`revise(candidate_dir, prompt, attempt_index)` performs one bounded revision attempt in an 426isolated directory and returns an optional note. It must not touch the workspace. 427""" 428try : 429self ._enter ("checkpointing" ) 430# 1. Retain the current good version before any speculative work. 431baseline_dir = self .root / "baseline" 432copy_tree (self .workspace ,baseline_dir ) 433baseline = self .checkpoint ("baseline" ,source = baseline_dir ) 434self .selected_checkpoint = baseline .id 435self ._check_cancel () 436 437# 2. Check the baseline, so a candidate has something real to be compared against. 438baseline .checks = [r .to_dict ()for r in self ._run_checks (baseline_dir )] 439self .save () 440self ._check_cancel () 441 442# 3. Bounded attempts, each from the *selected* checkpoint, never from a rejected one. 443for index in range (1 ,self .max_attempts + 1 ): 444self ._check_cancel () 445self ._enter ("generating" ,attempt = index ) 446attempt_dir = self .root / "candidates" / f"attempt { index } " 447copy_tree (self ._source_of (self .selected_checkpoint ),attempt_dir ) 448note = revise (attempt_dir ,self .prompt ,index ) 449attempt = Attempt (index = index ,prompt = self .prompt ,path = str (attempt_dir ), 450checkpoint = self .selected_checkpoint , 451checks = []) 452if note : 453attempt .reason = note 454self .attempts .append (attempt ) 455self .save () 456self ._check_cancel () 457 458self ._enter ("checking" ,attempt = index ) 459attempt .checks = [r .to_dict ()for r in self ._run_checks (attempt_dir )] 460self .save () 461self ._check_cancel () 462 463self ._enter ("decision" ,attempt = index ) 464verdict ,reason = self ._decide (self ._checks_of (self .selected_checkpoint ),attempt .checks ) 465attempt .decision = verdict 466attempt .reason = reason 467if verdict == "keep" : 468kept = self .checkpoint (f"attempt { index } " ,source = attempt_dir , 469parent = self .selected_checkpoint ) 470kept .checks = attempt .checks 471self .selected_checkpoint = kept .id 472self .save () 473 474self .decision = self ._final_decision () 475self ._enter ("completed" ) 476self .finished_at = self .clock () 477self .save () 478return self .to_dict () 479 480except _Cancelled : 481self .finished_at = self .clock () 482self .state = "cancelled" 483self .events .append ({"seq" :len (self .events ),"at" :self .clock (),"state" :"cancelled" }) 484self .save () 485return self .to_dict () 486except Exception as e :# noqa: BLE001 - a failed run is a recorded outcome, not a crash 487self .error = f" { type ( e ). __name__ } : { e } " 488self .finished_at = self .clock () 489self .state = "failed" 490self .events .append ({"seq" :len (self .events ),"at" :self .clock (),"state" :"failed" , 491"error" :self .error }) 492self .save () 493return self .to_dict () 494 495# ---- helpers --------------------------------------------------------- 496 497def _source_of (self ,checkpoint_id :str | None )-> Path : 498if checkpoint_id is None : 499raise TimeSkipError ("no checkpoint is selected" ) 500for cp in self .checkpoints : 501if cp .id == checkpoint_id : 502return Path (cp .path ) 503raise TimeSkipError (f"checkpoint { checkpoint_id } is not in this run" ) 504 505def _checks_of (self ,checkpoint_id :str | None )-> dict [str ,dict [str ,Any ]]: 506"""The checks recorded on a checkpoint, keyed by id. 507 508The gate compares a candidate against the version it was derived from, so a regression is 509measured against the retained evidence rather than against an ideal. 510""" 511for cp in self .checkpoints : 512if cp .id == checkpoint_id : 513return {c ["id" ]:c for c in cp .checks } 514return {} 515 516def _run_checks (self ,workdir :Path )-> list [CheckResult ]: 517return [run_check (spec ,workdir )for spec in self .checks ] 518 519def _decide (self ,previous :dict [str ,dict [str ,Any ]], 520candidate :Sequence [dict [str ,Any ]])-> tuple [str ,str ]: 521"""Non-regression gate over deterministic checks only. 522 523The rule is the integration specification's: **every previously passing check must still 524pass**, there must be no hard errors, and there must be evidence of an intended improvement. 525Advice checks are recorded but never gate, because a model's opinion cannot assert objective 526correctness. 527 528Outcomes: 529* a previously passing deterministic check now fails -> ``reject`` 530* a deterministic check could not be evaluated -> ``inconclusive`` 531* deterministic checks pass but nothing improved -> ``inconclusive`` 532* deterministic checks pass and something improved -> ``keep`` 533""" 534det = [c for c in candidate if c .get ("kind" )== "deterministic" ] 535if not det : 536return "inconclusive" ,"no deterministic checks were declared, so nothing can justify a change" 537 538regressed = [c ["id" ]for c in det 539if c ["outcome" ]== "failed" and previous .get (c ["id" ], {}).get ("outcome" )== "passed" ] 540if regressed : 541return "reject" ,f"previously passing check(s) now fail: { ', ' . join ( regressed ) } " 542 543hard_failed = [c ["id" ]for c in det if c ["outcome" ]== "failed" ] 544if hard_failed : 545return "reject" ,f"deterministic check(s) failed: { ', ' . join ( hard_failed ) } " 546 547unevaluated = [c ["id" ]for c in det if c ["outcome" ]in ("unknown" ,"error" )] 548if unevaluated : 549return "inconclusive" ,f"check(s) could not be evaluated: { ', ' . join ( unevaluated ) } " 550 551improved = [c ["id" ]for c in det 552if c ["outcome" ]== "passed" and previous .get (c ["id" ], {}).get ("outcome" )!= "passed" ] 553if not improved : 554return "inconclusive" , ("every deterministic check already passed and none changed, so " 555"the evidence does not show an intended improvement" ) 556return "keep" ,f"every deterministic check passed; newly passing: { ', ' . join ( improved ) } " 557 558def _final_decision (self )-> dict [str ,Any ]: 559"""Compare the selected checkpoint with the baseline and say what is actually known.""" 560baseline = next ((c for c in self .checkpoints if c .label == "baseline" ),None ) 561kept = next ((c for c in self .checkpoints if c .id == self .selected_checkpoint ),None ) 562base_checks = {c ["id" ]:c ["outcome" ]for c in (baseline .checks if baseline else [])} 563kept_checks = {c ["id" ]:c ["outcome" ]for c in (kept .checks if kept else [])} 564regressions = sorted (k for k ,v in base_checks .items () 565if v == "passed" and kept_checks .get (k )== "failed" ) 566improvements = sorted (k for k ,v in kept_checks .items () 567if v == "passed" and base_checks .get (k )!= "passed" ) 568if not self .attempts : 569outcome = "inconclusive" 570why = "no revision was attempted" 571elif any (a .decision == "reject" for a in self .attempts )and not improvements : 572outcome = "inconclusive" 573why = "every candidate was rejected; the retained version is the baseline" 574elif improvements and not regressions : 575outcome = "accepted" 576why = f"improved: { ', ' . join ( improvements ) } " 577elif improvements and regressions : 578outcome = "conflict" 579why = f"improved { ', ' . join ( improvements ) } but regressed { ', ' . join ( regressions ) } " 580else : 581outcome = "inconclusive" 582why = "no check changed outcome; the evidence does not justify a change" 583return { 584"outcome" :outcome , 585"reason" :why , 586"retained" :self .selected_checkpoint , 587"baseline" :baseline .id if baseline else None , 588"improvements" :improvements , 589"regressions" :regressions , 590"attempts" : [{"index" :a .index ,"decision" :a .decision ,"reason" :a .reason }for a in self .attempts ], 591"checks" : {"baseline" :base_checks ,"retained" :kept_checks }, 592"needs_user_review" :outcome in ("inconclusive" ,"conflict" ), 593 } 594 595# ---- applying -------------------------------------------------------- 596 597def apply (self ,destination :Path | None = None ,dry_run :bool = False , 598attempt :int | None = None )-> dict [str ,Any ]: 599"""Apply the retained checkpoint to the workspace, transactionally. 600 601``attempt`` names a revision attempt the *person* chose after looking at it (a run whose checks 602could not decide leaves the baseline retained, and the person is asked). The same safety 603applies: a changed destination is a conflict, and a failure rolls back. 604 605Refuses when the destination no longer matches what was captured, which is how a concurrent 606user edit becomes a conflict instead of being overwritten. On any failure the previous 607content is restored from the rollback copy. 608""" 609dest = Path (destination or self .workspace ) 610if attempt is None : 611kept = self ._source_of (self .selected_checkpoint ) 612else : 613chosen = next ((a for a in self .attempts if a .index == attempt ),None ) 614if chosen is None or not Path (chosen .path ).is_dir (): 615raise TimeSkipError (f"this run has no revision attempt { attempt } to apply" ) 616kept = Path (chosen .path ) 617baseline = next ((c for c in self .checkpoints if c .label == "baseline" ),None ) 618if baseline is None : 619raise TimeSkipError ("this run has no baseline to compare the destination against" ) 620 621# The destination must still be what the baseline captured. 622current = inventory (dest ) 623if inventory_digest (current )!= baseline .digest : 624changed = _first_difference (baseline .inventory ,current ) 625return {"applied" :False ,"conflict" :True , 626"reason" :"the destination changed since the run started; refusing to overwrite it" , 627"changed_path" :changed } 628 629applied = [it ["path" ]for it in inventory (kept )if not _same_in (baseline .inventory ,it )] 630removed = [it ["path" ]for it in baseline .inventory if not _exists_in (inventory (kept ),it ["path" ])] 631if dry_run : 632return {"applied" :False ,"dry_run" :True ,"would_write" :applied ,"would_remove" :removed } 633 634rollback = self .root / "rollback" 635copy_tree (dest ,rollback ) 636try : 637for rel in removed : 638target = dest / rel 639if target .exists (): 640target .unlink () 641for dirpath ,_dirnames ,filenames in os .walk (kept ): 642rel = Path (dirpath ).relative_to (kept ) 643 (dest / rel ).mkdir (parents = True ,exist_ok = True ) 644for name in filenames : 645shutil .copy2 (Path (dirpath )/ name ,dest / rel / name ,follow_symlinks = False ) 646except Exception as e :# noqa: BLE001 - restore and report, never leave a half-applied tree 647copy_tree (rollback ,dest ) 648return {"applied" :False ,"rolled_back" :True , 649"reason" :f"apply failed and was rolled back: { type ( e ). __name__ } : { e } " } 650return {"applied" :True ,"wrote" :applied ,"removed" :removed , 651"rollback" :str (rollback ), 652"checkpoint" :self .selected_checkpoint if attempt is None else f"attempt { attempt } " } 653 654def restore_original (self ,destination :Path | None = None )-> dict [str ,Any ]: 655"""Put the baseline back, whatever else has happened.""" 656dest = Path (destination or self .workspace ) 657baseline = next ((c for c in self .checkpoints if c .label == "baseline" ),None ) 658if baseline is None : 659raise TimeSkipError ("this run has no baseline to restore" ) 660copy_tree (Path (baseline .path ),dest ) 661self .selected_checkpoint = baseline .id 662self .decision = self ._final_decision ()if self .decision else None 663self .save () 664return {"restored" :True ,"checkpoint" :baseline .id } 665 666 667class _Cancelled (Exception ): 668pass 669 670 671# --------------------------------------------------------------------------- helpers 672 673def _exists_in (items :Sequence [dict [str ,Any ]],path :str )-> bool : 674return any (i ["path" ]== path for i in items ) 675 676 677def _same_in (items :Sequence [dict [str ,Any ]],other :dict [str ,Any ])-> bool : 678for i in items : 679if i ["path" ]== other ["path" ]: 680return i ["sha256" ]== other ["sha256" ]and i ["bytes" ]== other ["bytes" ] 681return False 682 683 684def _first_difference (before :Sequence [dict [str ,Any ]],after :Sequence [dict [str ,Any ]])-> str | None : 685b = {i ["path" ]:i ["sha256" ]for i in before } 686a = {i ["path" ]:i ["sha256" ]for i in after } 687for path in sorted (set (b )| set (a )): 688if b .get (path )!= a .get (path ): 689return path 690return None 691 692 693# --------------------------------------------------------------------------- job store 694 695class TimeSkipStore : 696"""The runs on disk, so the UI and the CLI read the same durable truth.""" 697 698def __init__ (self ,root :Path )-> None : 699self .root = Path (root ) 700self .root .mkdir (parents = True ,exist_ok = True ) 701 702def list (self )-> list [dict [str ,Any ]]: 703out = [] 704for d in sorted (self .root .iterdir ()): 705f = d / "run.json" 706if f .is_file (): 707try : 708data = json .loads (f .read_text (encoding = "utf-8" )) 709except (OSError ,json .JSONDecodeError ): 710continue 711out .append ({k :data .get (k )for k in 712 ("id" ,"state" ,"workspace" ,"prompt" ,"started_at" ,"finished_at" ,"decision" )}) 713return out 714 715def get (self ,run_id :str )-> dict [str ,Any ]: 716return TimeSkipRun .load (self .root ,run_id ) 717 718def load_checks (self ,workspace :Path )-> list [CheckSpec ]: 719"""Read the declared checks for a workspace. 720 721`.strata/checks.json` holds ``{"checks": [...]}``. Absent file means no checks, which makes 722every run inconclusive by construction rather than accidentally successful. 723""" 724path = Path (workspace )/ ".strata" / "checks.json" 725if not path .exists (): 726return [] 727raw = json .loads (path .read_text (encoding = "utf-8" )) 728items = raw .get ("checks" )if isinstance (raw ,dict )else raw 729if not isinstance (items ,list ): 730raise TimeSkipError (f" { path } : expected a list of checks" ) 731return [CheckSpec .from_dict (i )for i in items ]