okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-029-urgent (bc694233b)99866a47a

main
32.3 KiB731 linesraw
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
6    queued -> checkpointing -> generating -> checking -> decision -> completed
7    with repeated generating/checking for bounded attempts, and the alternate terminal states
8    cancelled, 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
13  evidence is insufficient ends ``needs_user_review``; it never invents an objective score. There is
14  no 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
16  before 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
18  workspace until an explicit ``apply``, which refuses if the destination changed since it was
19  captured. 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
21  correctness, 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,
23  and 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,
72    which is how a model critique is kept from asserting objective correctness.
73    """
74
75    id: str
76    command: str | None = None
77    #: A path whose existence and digest is the check (used when no command is declared).
78    file: str | None = None
79    #: Expected content digest of `file`, if the check is a content assertion.
80    sha256: str | None = None
81    kind: str = "deterministic"
82    description: str = ""
83    timeout_s: float = 300.0
84
85    @staticmethod
86    def from_dict(raw: dict[str, Any]) -> "CheckSpec":
87        if not isinstance(raw, dict) or not raw.get("id"):
88            raise TimeSkipError("each check needs an id")
89        kind = raw.get("kind", "deterministic")
90        if kind not in ("deterministic", "advice"):
91            raise TimeSkipError(f"check {raw['id']}: kind must be 'deterministic' or 'advice'")
92        if not raw.get("command") and not raw.get("file"):
93            raise TimeSkipError(f"check {raw['id']}: needs a command or a file")
94        return CheckSpec(
95            id=str(raw["id"]),
96            command=raw.get("command"),
97            file=raw.get("file"),
98            sha256=raw.get("sha256"),
99            kind=kind,
100            description=str(raw.get("description") or ""),
101            timeout_s=float(raw.get("timeout_s") or 300.0),
102        )
103
104
105@dataclass
106class CheckResult:
107    id: str
108    kind: str
109    outcome: str
110    detail: str = ""
111    exit_code: int | None = None
112    stdout_tail: str = ""
113    stderr_tail: str = ""
114    sha256: str | None = None
115    duration_ms: int | None = None
116
117    def to_dict(self) -> dict[str, Any]:
118        return {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
134    POSIX ``sh`` says so with 126/127. ``cmd.exe`` says 9009 from a batch context but often a plain 1
135    from ``cmd /c`` (and the message is localised), so for exit 1 the first word is looked up on PATH
136    instead of trusting the code. A real failure of an existing program stays ``failed``.
137    """
138    if os.name != "nt":
139        return returncode in (126, 127)
140    if returncode == CMD_NOT_FOUND:
141        return True
142    if returncode != 1:
143        return False
144    text = command.strip()
145    if not text or _CMD_OPERATORS & set(text):
146        return False  # a pipeline or redirect: the failing part is unknowable from here
147    if text.startswith('"'):
148        program = text[1:].split('"', 1)[0]
149    else:
150        program = text.split(None, 1)[0]
151    if program.lower() in _CMD_BUILTINS:
152        return False
153    return 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,
160    so a hung check would block here until it ended on its own. On Windows the whole tree is killed.
161    """
162    if os.name != "nt":
163        return subprocess.run(command, shell=True, cwd=cwd, capture_output=True, text=True, errors="replace",
164                              timeout=timeout, env=env)
165    with subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
166                          text=True, errors="replace", env=env) as process:
167        try:
168            out, err = process.communicate(timeout=timeout)
169        except subprocess.TimeoutExpired:
170            subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True)
171            process.communicate()
172            raise
173        return 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
179    A check that could not be run is ``unknown``; a check that ran and crashed is ``error``. Neither
180    is ever reported as ``passed``.
181    """
182    started = time.time()
183    if spec.command:
184        try:
185            proc = _run_shell(spec.command, str(workdir), spec.timeout_s, {**os.environ, **(env or {})})
186        except subprocess.TimeoutExpired:
187            return CheckResult(spec.id, spec.kind, "unknown",
188                               detail=f"timed out after {spec.timeout_s:.0f}s",
189                               duration_ms=int((time.time() - started) * 1000))
190        except OSError as e:
191            return CheckResult(spec.id, spec.kind, "unknown", detail=f"could not run: {e}")
192        tail = lambda s: (s or "")[-2000:]  # noqa: E731 - a local shorthand
193        if _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.
197            return CheckResult(spec.id, spec.kind, "unknown",
198                               detail=f"the check's command could not be run (shell exit "
199                                      f"{proc.returncode}): {spec.command}",
200                               exit_code=proc.returncode, stderr_tail=tail(proc.stderr),
201                               duration_ms=int((time.time() - started) * 1000))
202        outcome = "passed" if proc.returncode == 0 else "failed"
203        return CheckResult(spec.id, spec.kind, outcome, exit_code=proc.returncode,
204                           stdout_tail=tail(proc.stdout), stderr_tail=tail(proc.stderr),
205                           duration_ms=int((time.time() - started) * 1000))
206
207    # file assertion
208    target = workdir / spec.file  # type: ignore[operator]
209    if not target.exists():
210        return CheckResult(spec.id, spec.kind, "failed", detail=f"{spec.file} is missing")
211    digest = sha256_file(target)
212    if spec.sha256 and digest != spec.sha256:
213        return CheckResult(spec.id, spec.kind, "failed",
214                           detail=f"{spec.file} digest {digest[:12]} does not match the expected "
215                                  f"{spec.sha256[:12]}", sha256=digest)
216    return CheckResult(spec.id, spec.kind, "passed", sha256=digest,
217                       duration_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."""
222    counts = {k: 0 for k in CHECK_OUTCOMES}
223    for r in results:
224        counts[r.outcome] = counts.get(r.outcome, 0) + 1
225    return {"total": len(results), **counts}
226
227
228# --------------------------------------------------------------------------- digests and snapshots
229
230def sha256_file(path: Path, chunk: int = 1 << 20) -> str:
231    h = hashlib.sha256()
232    with path.open("rb") as fh:
233        while True:
234            block = fh.read(chunk)
235            if not block:
236                break
237            h.update(block)
238    return 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
244    Digests are what make a checkpoint an identity rather than a label. Directories that belong to
245    tooling rather than to the user's work are skipped.
246    """
247    skip = set(ignore)
248    out: list[dict[str, Any]] = []
249    for dirpath, dirnames, filenames in os.walk(root):
250        dirnames[:] = sorted(d for d in dirnames if d not in skip)
251        for name in sorted(filenames):
252            p = Path(dirpath) / name
253            if p.is_symlink():
254                continue
255            try:
256                st = p.stat()
257            except OSError:
258                continue
259            rel = p.relative_to(root).as_posix()
260            out.append({"path": rel, "bytes": st.st_size, "sha256": sha256_file(p)})
261    return out
262
263
264def inventory_digest(items: Sequence[dict[str, Any]]) -> str:
265    h = hashlib.sha256()
266    for it in items:
267        h.update(f"{it['path']}\0{it['bytes']}\0{it['sha256']}\n".encode())
268    return h.hexdigest()
269
270
271def copy_tree(src: Path, dst: Path, ignore: Iterable[str] = (".git", "__pycache__", ".strata")) -> None:
272    skip = set(ignore)
273    if dst.exists():
274        shutil.rmtree(dst)
275    dst.mkdir(parents=True, exist_ok=True)
276    for dirpath, dirnames, filenames in os.walk(src):
277        dirnames[:] = [d for d in dirnames if d not in skip]
278        rel = Path(dirpath).relative_to(src)
279        (dst / rel).mkdir(parents=True, exist_ok=True)
280        for name in filenames:
281            s = Path(dirpath) / name
282            if s.is_symlink():
283                continue
284            shutil.copy2(s, dst / rel / name, follow_symlinks=False)
285
286
287# --------------------------------------------------------------------------- the run
288
289@dataclass
290class Checkpoint:
291    id: str
292    label: str
293    path: str
294    digest: str
295    inventory: list[dict[str, Any]] = field(default_factory=list)
296    checks: list[dict[str, Any]] = field(default_factory=list)
297    parent: str | None = None
298    created_at: float = field(default_factory=time.time)
299
300
301@dataclass
302class Attempt:
303    index: int
304    prompt: str
305    path: str
306    checkpoint: str | None = None
307    checks: list[dict[str, Any]] = field(default_factory=list)
308    decision: str | None = None          # keep | reject | inconclusive
309    reason: str = ""
310    created_at: float = field(default_factory=time.time)
311
312
313class TimeSkipRun:
314    """One Time-skip run, durable on disk after every transition.
315
316    The runner is injected so this module never has to know how an agent is driven: the App Host
317    passes 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
321    def __init__(self, root: Path, workspace: Path, prompt: str,
322                 checks: Sequence[CheckSpec], max_attempts: int = DEFAULT_MAX_ATTEMPTS,
323                 run_id: str | None = None, clock: Callable[[], float] = time.time) -> None:
324        self.id = run_id or uuid.uuid4().hex
325        self.root = root / self.id
326        self.workspace = Path(workspace)
327        self.prompt = prompt
328        self.checks = list(checks)
329        self.max_attempts = max(0, int(max_attempts))
330        self.clock = clock
331        self.state = "queued"
332        self.started_at = self.clock()
333        self.finished_at: float | None = None
334        self.checkpoints: list[Checkpoint] = []
335        self.attempts: list[Attempt] = []
336        self.selected_checkpoint: str | None = None
337        self.events: list[dict[str, Any]] = []
338        self.error: str | None = None
339        self.decision: dict[str, Any] | None = None
340        self._cancel_requested = False
341        self.root.mkdir(parents=True, exist_ok=True)
342
343    # ---- persistence -----------------------------------------------------
344
345    @property
346    def state_file(self) -> Path:
347        return self.root / "run.json"
348
349    def to_dict(self) -> dict[str, Any]:
350        return {
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
369    def save(self) -> None:
370        tmp = self.state_file.with_suffix(".tmp")
371        tmp.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
372        atomic.replace(tmp, self.state_file)
373
374    @staticmethod
375    def load(root: Path, run_id: str) -> dict[str, Any]:
376        p = Path(root) / run_id / "run.json"
377        if not p.exists():
378            raise TimeSkipError(f"no Time-skip run {run_id}")
379        return json.loads(p.read_text(encoding="utf-8"))
380
381    # ---- cancellation ----------------------------------------------------
382
383    def request_cancel(self) -> None:
384        """Ask the run to stop at the next phase boundary.
385
386        Cancellation 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
388        selected throughout.
389        """
390        self._cancel_requested = True
391        self.save()
392
393    def _check_cancel(self) -> None:
394        if self._cancel_requested:
395            raise _Cancelled()
396
397    # ---- events ----------------------------------------------------------
398
399    def _enter(self, state: str, **extra: Any) -> None:
400        if state not in STATES:
401            raise TimeSkipError(f"unknown state {state!r}")
402        self.state = state
403        self.events.append({"seq": len(self.events), "at": self.clock(), "state": state, **extra})
404        self.save()
405
406    # ---- phases ----------------------------------------------------------
407
408    def checkpoint(self, label: str, source: Path | None = None, parent: str | None = None) -> Checkpoint:
409        """Snapshot a directory and record what it contained."""
410        src = Path(source or (self.workspace if label == "baseline" else self.workspace))
411        # `pending` holds speculative work; the workspace itself is only read here.
412        cp_id = f"cp{len(self.checkpoints) + 1}-{label}"
413        dest = self.root / "checkpoints" / cp_id
414        copy_tree(src, dest)
415        items = inventory(dest)
416        cp = Checkpoint(id=cp_id, label=label, path=str(dest), digest=inventory_digest(items),
417                        inventory=items, parent=parent)
418        self.checkpoints.append(cp)
419        self.save()
420        return cp
421
422    def 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
426        isolated directory and returns an optional note. It must not touch the workspace.
427        """
428        try:
429            self._enter("checkpointing")
430            # 1. Retain the current good version before any speculative work.
431            baseline_dir = self.root / "baseline"
432            copy_tree(self.workspace, baseline_dir)
433            baseline = self.checkpoint("baseline", source=baseline_dir)
434            self.selected_checkpoint = baseline.id
435            self._check_cancel()
436
437            # 2. Check the baseline, so a candidate has something real to be compared against.
438            baseline.checks = [r.to_dict() for r in self._run_checks(baseline_dir)]
439            self.save()
440            self._check_cancel()
441
442            # 3. Bounded attempts, each from the *selected* checkpoint, never from a rejected one.
443            for index in range(1, self.max_attempts + 1):
444                self._check_cancel()
445                self._enter("generating", attempt=index)
446                attempt_dir = self.root / "candidates" / f"attempt{index}"
447                copy_tree(self._source_of(self.selected_checkpoint), attempt_dir)
448                note = revise(attempt_dir, self.prompt, index)
449                attempt = Attempt(index=index, prompt=self.prompt, path=str(attempt_dir),
450                                  checkpoint=self.selected_checkpoint,
451                                  checks=[])
452                if note:
453                    attempt.reason = note
454                self.attempts.append(attempt)
455                self.save()
456                self._check_cancel()
457
458                self._enter("checking", attempt=index)
459                attempt.checks = [r.to_dict() for r in self._run_checks(attempt_dir)]
460                self.save()
461                self._check_cancel()
462
463                self._enter("decision", attempt=index)
464                verdict, reason = self._decide(self._checks_of(self.selected_checkpoint), attempt.checks)
465                attempt.decision = verdict
466                attempt.reason = reason
467                if verdict == "keep":
468                    kept = self.checkpoint(f"attempt{index}", source=attempt_dir,
469                                           parent=self.selected_checkpoint)
470                    kept.checks = attempt.checks
471                    self.selected_checkpoint = kept.id
472                self.save()
473
474            self.decision = self._final_decision()
475            self._enter("completed")
476            self.finished_at = self.clock()
477            self.save()
478            return self.to_dict()
479
480        except _Cancelled:
481            self.finished_at = self.clock()
482            self.state = "cancelled"
483            self.events.append({"seq": len(self.events), "at": self.clock(), "state": "cancelled"})
484            self.save()
485            return self.to_dict()
486        except Exception as e:  # noqa: BLE001 - a failed run is a recorded outcome, not a crash
487            self.error = f"{type(e).__name__}: {e}"
488            self.finished_at = self.clock()
489            self.state = "failed"
490            self.events.append({"seq": len(self.events), "at": self.clock(), "state": "failed",
491                                "error": self.error})
492            self.save()
493            return self.to_dict()
494
495    # ---- helpers ---------------------------------------------------------
496
497    def _source_of(self, checkpoint_id: str | None) -> Path:
498        if checkpoint_id is None:
499            raise TimeSkipError("no checkpoint is selected")
500        for cp in self.checkpoints:
501            if cp.id == checkpoint_id:
502                return Path(cp.path)
503        raise TimeSkipError(f"checkpoint {checkpoint_id} is not in this run")
504
505    def _checks_of(self, checkpoint_id: str | None) -> dict[str, dict[str, Any]]:
506        """The checks recorded on a checkpoint, keyed by id.
507
508        The gate compares a candidate against the version it was derived from, so a regression is
509        measured against the retained evidence rather than against an ideal.
510        """
511        for cp in self.checkpoints:
512            if cp.id == checkpoint_id:
513                return {c["id"]: c for c in cp.checks}
514        return {}
515
516    def _run_checks(self, workdir: Path) -> list[CheckResult]:
517        return [run_check(spec, workdir) for spec in self.checks]
518
519    def _decide(self, previous: dict[str, dict[str, Any]],
520                candidate: Sequence[dict[str, Any]]) -> tuple[str, str]:
521        """Non-regression gate over deterministic checks only.
522
523        The rule is the integration specification's: **every previously passing check must still
524        pass**, there must be no hard errors, and there must be evidence of an intended improvement.
525        Advice checks are recorded but never gate, because a model's opinion cannot assert objective
526        correctness.
527
528        Outcomes:
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        """
534        det = [c for c in candidate if c.get("kind") == "deterministic"]
535        if not det:
536            return "inconclusive", "no deterministic checks were declared, so nothing can justify a change"
537
538        regressed = [c["id"] for c in det
539                     if c["outcome"] == "failed" and previous.get(c["id"], {}).get("outcome") == "passed"]
540        if regressed:
541            return "reject", f"previously passing check(s) now fail: {', '.join(regressed)}"
542
543        hard_failed = [c["id"] for c in det if c["outcome"] == "failed"]
544        if hard_failed:
545            return "reject", f"deterministic check(s) failed: {', '.join(hard_failed)}"
546
547        unevaluated = [c["id"] for c in det if c["outcome"] in ("unknown", "error")]
548        if unevaluated:
549            return "inconclusive", f"check(s) could not be evaluated: {', '.join(unevaluated)}"
550
551        improved = [c["id"] for c in det
552                    if c["outcome"] == "passed" and previous.get(c["id"], {}).get("outcome") != "passed"]
553        if not improved:
554            return "inconclusive", ("every deterministic check already passed and none changed, so "
555                                    "the evidence does not show an intended improvement")
556        return "keep", f"every deterministic check passed; newly passing: {', '.join(improved)}"
557
558    def _final_decision(self) -> dict[str, Any]:
559        """Compare the selected checkpoint with the baseline and say what is actually known."""
560        baseline = next((c for c in self.checkpoints if c.label == "baseline"), None)
561        kept = next((c for c in self.checkpoints if c.id == self.selected_checkpoint), None)
562        base_checks = {c["id"]: c["outcome"] for c in (baseline.checks if baseline else [])}
563        kept_checks = {c["id"]: c["outcome"] for c in (kept.checks if kept else [])}
564        regressions = sorted(k for k, v in base_checks.items()
565                             if v == "passed" and kept_checks.get(k) == "failed")
566        improvements = sorted(k for k, v in kept_checks.items()
567                              if v == "passed" and base_checks.get(k) != "passed")
568        if not self.attempts:
569            outcome = "inconclusive"
570            why = "no revision was attempted"
571        elif any(a.decision == "reject" for a in self.attempts) and not improvements:
572            outcome = "inconclusive"
573            why = "every candidate was rejected; the retained version is the baseline"
574        elif improvements and not regressions:
575            outcome = "accepted"
576            why = f"improved: {', '.join(improvements)}"
577        elif improvements and regressions:
578            outcome = "conflict"
579            why = f"improved {', '.join(improvements)} but regressed {', '.join(regressions)}"
580        else:
581            outcome = "inconclusive"
582            why = "no check changed outcome; the evidence does not justify a change"
583        return {
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
597    def apply(self, destination: Path | None = None, dry_run: bool = False,
598              attempt: 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
602        could not decide leaves the baseline retained, and the person is asked). The same safety
603        applies: a changed destination is a conflict, and a failure rolls back.
604
605        Refuses when the destination no longer matches what was captured, which is how a concurrent
606        user edit becomes a conflict instead of being overwritten. On any failure the previous
607        content is restored from the rollback copy.
608        """
609        dest = Path(destination or self.workspace)
610        if attempt is None:
611            kept = self._source_of(self.selected_checkpoint)
612        else:
613            chosen = next((a for a in self.attempts if a.index == attempt), None)
614            if chosen is None or not Path(chosen.path).is_dir():
615                raise TimeSkipError(f"this run has no revision attempt {attempt} to apply")
616            kept = Path(chosen.path)
617        baseline = next((c for c in self.checkpoints if c.label == "baseline"), None)
618        if baseline is None:
619            raise TimeSkipError("this run has no baseline to compare the destination against")
620
621        # The destination must still be what the baseline captured.
622        current = inventory(dest)
623        if inventory_digest(current) != baseline.digest:
624            changed = _first_difference(baseline.inventory, current)
625            return {"applied": False, "conflict": True,
626                    "reason": "the destination changed since the run started; refusing to overwrite it",
627                    "changed_path": changed}
628
629        applied = [it["path"] for it in inventory(kept) if not _same_in(baseline.inventory, it)]
630        removed = [it["path"] for it in baseline.inventory if not _exists_in(inventory(kept), it["path"])]
631        if dry_run:
632            return {"applied": False, "dry_run": True, "would_write": applied, "would_remove": removed}
633
634        rollback = self.root / "rollback"
635        copy_tree(dest, rollback)
636        try:
637            for rel in removed:
638                target = dest / rel
639                if target.exists():
640                    target.unlink()
641            for dirpath, _dirnames, filenames in os.walk(kept):
642                rel = Path(dirpath).relative_to(kept)
643                (dest / rel).mkdir(parents=True, exist_ok=True)
644                for name in filenames:
645                    shutil.copy2(Path(dirpath) / name, dest / rel / name, follow_symlinks=False)
646        except Exception as e:  # noqa: BLE001 - restore and report, never leave a half-applied tree
647            copy_tree(rollback, dest)
648            return {"applied": False, "rolled_back": True,
649                    "reason": f"apply failed and was rolled back: {type(e).__name__}: {e}"}
650        return {"applied": True, "wrote": applied, "removed": removed,
651                "rollback": str(rollback),
652                "checkpoint": self.selected_checkpoint if attempt is None else f"attempt{attempt}"}
653
654    def restore_original(self, destination: Path | None = None) -> dict[str, Any]:
655        """Put the baseline back, whatever else has happened."""
656        dest = Path(destination or self.workspace)
657        baseline = next((c for c in self.checkpoints if c.label == "baseline"), None)
658        if baseline is None:
659            raise TimeSkipError("this run has no baseline to restore")
660        copy_tree(Path(baseline.path), dest)
661        self.selected_checkpoint = baseline.id
662        self.decision = self._final_decision() if self.decision else None
663        self.save()
664        return {"restored": True, "checkpoint": baseline.id}
665
666
667class _Cancelled(Exception):
668    pass
669
670
671# --------------------------------------------------------------------------- helpers
672
673def _exists_in(items: Sequence[dict[str, Any]], path: str) -> bool:
674    return any(i["path"] == path for i in items)
675
676
677def _same_in(items: Sequence[dict[str, Any]], other: dict[str, Any]) -> bool:
678    for i in items:
679        if i["path"] == other["path"]:
680            return i["sha256"] == other["sha256"] and i["bytes"] == other["bytes"]
681    return False
682
683
684def _first_difference(before: Sequence[dict[str, Any]], after: Sequence[dict[str, Any]]) -> str | None:
685    b = {i["path"]: i["sha256"] for i in before}
686    a = {i["path"]: i["sha256"] for i in after}
687    for path in sorted(set(b) | set(a)):
688        if b.get(path) != a.get(path):
689            return path
690    return 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
698    def __init__(self, root: Path) -> None:
699        self.root = Path(root)
700        self.root.mkdir(parents=True, exist_ok=True)
701
702    def list(self) -> list[dict[str, Any]]:
703        out = []
704        for d in sorted(self.root.iterdir()):
705            f = d / "run.json"
706            if f.is_file():
707                try:
708                    data = json.loads(f.read_text(encoding="utf-8"))
709                except (OSError, json.JSONDecodeError):
710                    continue
711                out.append({k: data.get(k) for k in
712                            ("id", "state", "workspace", "prompt", "started_at", "finished_at", "decision")})
713        return out
714
715    def get(self, run_id: str) -> dict[str, Any]:
716        return TimeSkipRun.load(self.root, run_id)
717
718    def 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
722        every run inconclusive by construction rather than accidentally successful.
723        """
724        path = Path(workspace) / ".strata" / "checks.json"
725        if not path.exists():
726            return []
727        raw = json.loads(path.read_text(encoding="utf-8"))
728        items = raw.get("checks") if isinstance(raw, dict) else raw
729        if not isinstance(items, list):
730            raise TimeSkipError(f"{path}: expected a list of checks")
731        return [CheckSpec.from_dict(i) for i in items]