Items 1 and 2: a cycle file's command runs only in apply, in an exported copy with no history and a reduced environment; replay commits come from the learning's own record; vacuous commands refused. done / next: item 3 (approval cannot be self-granted)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2ecbfea7e9
commit
4418136d01
6 files changed
+377
-47
No files matched your search
+30
-20
@@ -238,23 +238,34 @@ def brief_text():
|
|||||||
|
|
||||||
# ---- replay validation (one implementation: evaluate.validate_command) -----------------
|
# ---- replay validation (one implementation: evaluate.validate_command) -----------------
|
||||||
|
|
||||||
def replay_validate(rec, action):
|
def replay_validate(rec, action, run=True):
|
||||||
"""(result, detail): `validated` only when the command ran and failed before the fix and ran
|
"""(result, detail): `validated` only when the command ran and failed before the fix and ran
|
||||||
and passed after it, in the learning's own, trusted project; `unvalidated` (with the reason)
|
and passed after it, in the learning's own, trusted project, between the two commits the
|
||||||
when it could not be shown; `failed` when it ran and did not behave so."""
|
learning's OWN record holds (its unit's start and closing commits, or the ones stored with the
|
||||||
|
finding). Commits, repository and project named in the cycle file are ignored. `unvalidated`
|
||||||
|
(with the reason) when it could not be shown; `failed` when it ran and did not behave so;
|
||||||
|
`vacuous` when the command names no path that differs between the two trees. With run=False
|
||||||
|
nothing is executed (the preflight only): the result is `unvalidated` unless it is refused."""
|
||||||
cmd = action.get("cmd") or ""
|
cmd = action.get("cmd") or ""
|
||||||
exp = (action.get("expect") or {}).get("exit", 0)
|
exp = (action.get("expect") or {}).get("exit", 0)
|
||||||
replay = rec.get("replay") or {}
|
commits = L.replay_commits(rec)
|
||||||
repo = L.normalize_project(action.get("repo") or replay.get("repo") or rec.get("origin_project"))
|
repo = rec.get("origin_project")
|
||||||
before = action.get("before") or replay.get("before")
|
if not (repo and commits and cmd):
|
||||||
after = action.get("after") or replay.get("after")
|
return "unvalidated", ("no commits are recorded for this learning (its unit %s has no start and closing "
|
||||||
if not (repo and before and after and cmd):
|
"commit, and the finding stored none), so the command was never replayed"
|
||||||
return "unvalidated", "no before/after commits are known, so the command was never replayed"
|
% rec.get("source_unit"))
|
||||||
if repo != rec.get("origin_project"):
|
before, after, where = commits
|
||||||
return "unvalidated", "the repository is not this learning's origin project; no replay was run"
|
if not run:
|
||||||
|
stop = evaluate.replay_preflight(repo, before, after, cmd)
|
||||||
|
if stop and stop["outcome"] == "vacuous":
|
||||||
|
return "vacuous", stop["reason"]
|
||||||
|
return "unvalidated", ("`check` runs nothing; `apply` replays it between the commits in %s"
|
||||||
|
% where if not stop else "not replayable: %s" % stop.get("reason"))
|
||||||
out = evaluate.validate_command(repo, before, after, cmd, exp)
|
out = evaluate.validate_command(repo, before, after, cmd, exp)
|
||||||
if out["outcome"] == "validated":
|
if out["outcome"] == "validated":
|
||||||
return "validated", "replay: failed at %s, passed at %s" % (str(before)[:12], str(after)[:12])
|
return "validated", "replay: failed at %s, passed at %s (commits from %s)" % (before[:12], after[:12], where)
|
||||||
|
if out["outcome"] == "vacuous":
|
||||||
|
return "vacuous", out.get("reason")
|
||||||
if out["outcome"] == "not-run":
|
if out["outcome"] == "not-run":
|
||||||
return "unvalidated", "replay did not establish it: %s" % out.get("reason")
|
return "unvalidated", "replay did not establish it: %s" % out.get("reason")
|
||||||
return "failed", "replay: %s" % (out.get("reason") or out["outcome"])
|
return "failed", "replay: %s" % (out.get("reason") or out["outcome"])
|
||||||
@@ -282,7 +293,7 @@ def _risk_lowers(pattern, profile):
|
|||||||
return risk._ORDER[profile] < risk._ORDER[cur]
|
return risk._ORDER[profile] < risk._ORDER[cur]
|
||||||
|
|
||||||
|
|
||||||
def _plan_promote(a, rec, virtual_rules):
|
def _plan_promote(a, rec, virtual_rules, run=True):
|
||||||
"""(normalized action, reasons that make it consequential, granted scope, replay)."""
|
"""(normalized action, reasons that make it consequential, granted scope, replay)."""
|
||||||
kind = a.get("mechanism_kind")
|
kind = a.get("mechanism_kind")
|
||||||
lid = rec["id"]
|
lid = rec["id"]
|
||||||
@@ -312,14 +323,13 @@ def _plan_promote(a, rec, virtual_rules):
|
|||||||
n["cmd"] = _text(a, "cmd", lid).strip()
|
n["cmd"] = _text(a, "cmd", lid).strip()
|
||||||
exp = a.get("expect") if isinstance(a.get("expect"), dict) else {}
|
exp = a.get("expect") if isinstance(a.get("expect"), dict) else {}
|
||||||
n["expect"] = {"exit": exp.get("exit", 0)}
|
n["expect"] = {"exit": exp.get("exit", 0)}
|
||||||
for k in ("before", "after", "repo"):
|
|
||||||
if isinstance(a.get(k), str):
|
|
||||||
n[k] = a[k]
|
|
||||||
if a.get("timeout_s") is not None:
|
if a.get("timeout_s") is not None:
|
||||||
_need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600,
|
_need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600,
|
||||||
"timeout_s for %s must be between 0 and 600" % lid)
|
"timeout_s for %s must be between 0 and 600" % lid)
|
||||||
n["timeout_s"] = a["timeout_s"]
|
n["timeout_s"] = a["timeout_s"]
|
||||||
replay = replay_validate(rec, n)
|
replay = replay_validate(rec, n, run)
|
||||||
|
_need(replay[0] != "vacuous", "command check for %s is vacuous: %s. Write a command that reads a path "
|
||||||
|
"the fix changed" % (lid, replay[1]))
|
||||||
_need(replay[0] != "failed", "replay validation failed for %s: %s; nothing is applied" % (lid, replay[1]))
|
_need(replay[0] != "failed", "replay validation failed for %s: %s; nothing is applied" % (lid, replay[1]))
|
||||||
if replay[0] != "validated":
|
if replay[0] != "validated":
|
||||||
reasons.append("an enforced command nobody has seen fail and then pass in its own project (%s)" % replay[1])
|
reasons.append("an enforced command nobody has seen fail and then pass in its own project (%s)" % replay[1])
|
||||||
@@ -374,7 +384,7 @@ def _plan_promote(a, rec, virtual_rules):
|
|||||||
return n, reasons, granted, replay
|
return n, reasons, granted, replay
|
||||||
|
|
||||||
|
|
||||||
def validate_doc(doc, rows):
|
def validate_doc(doc, rows, run=True):
|
||||||
"""Every refusal is raised before anything is applied. Returns the plan: a list of
|
"""Every refusal is raised before anything is applied. Returns the plan: a list of
|
||||||
{"kind": status|promote|disable-rule, "action", "rec", "pending", "reasons", "scope", "replay"}."""
|
{"kind": status|promote|disable-rule, "action", "rec", "pending", "reasons", "scope", "replay"}."""
|
||||||
if not isinstance(doc, dict) or not isinstance(doc.get("actions"), list) or not doc["actions"]:
|
if not isinstance(doc, dict) or not isinstance(doc.get("actions"), list) or not doc["actions"]:
|
||||||
@@ -409,7 +419,7 @@ def validate_doc(doc, rows):
|
|||||||
"rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []})
|
"rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []})
|
||||||
continue
|
continue
|
||||||
_need(act == "promote", "unknown action %r" % act)
|
_need(act == "promote", "unknown action %r" % act)
|
||||||
n, reasons, granted, replay = _plan_promote(a, rec, virtual)
|
n, reasons, granted, replay = _plan_promote(a, rec, virtual, run)
|
||||||
plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons),
|
plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons),
|
||||||
"scope": granted, "replay": replay, "reasons": reasons})
|
"scope": granted, "replay": replay, "reasons": reasons})
|
||||||
ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted]
|
ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted]
|
||||||
@@ -912,7 +922,7 @@ def cmd_cycle(args):
|
|||||||
try:
|
try:
|
||||||
with open(args[1], encoding="utf-8") as f:
|
with open(args[1], encoding="utf-8") as f:
|
||||||
doc = json.load(f)
|
doc = json.load(f)
|
||||||
plan = validate_doc(doc, L.load_learnings())
|
plan = validate_doc(doc, L.load_learnings(), run=False)
|
||||||
except (CycleError, OSError, ValueError, documents.DocumentError, overlay.OverlayError) as e:
|
except (CycleError, OSError, ValueError, documents.DocumentError, overlay.OverlayError) as e:
|
||||||
print("sisi cycle: %s" % e, file=sys.stderr)
|
print("sisi cycle: %s" % e, file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
|
|||||||
+151
-18
@@ -14,7 +14,7 @@ Standard library only. Replay of ``task`` cases goes through the existing delega
|
|||||||
(``sisi.workers.run_delegation``) unless a caller injects ``worker_runner`` or names a
|
(``sisi.workers.run_delegation``) unless a caller injects ``worker_runner`` or names a
|
||||||
``--worker-cmd``; tests always inject a fake, so no test calls a real AI tool.
|
``--worker-cmd``; tests always inject a fake, so no test calls a real AI tool.
|
||||||
"""
|
"""
|
||||||
import hashlib, json, math, os, re, shlex, shutil, statistics, subprocess, sys, tempfile, time, uuid
|
import hashlib, json, math, os, re, shlex, shutil, signal, statistics, subprocess, sys, tarfile, tempfile, time, uuid
|
||||||
|
|
||||||
from . import paths, store
|
from . import paths, store
|
||||||
|
|
||||||
@@ -396,6 +396,87 @@ class _Worktree:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _rmtree(path):
|
||||||
|
"""Delete a tree even when a command made parts of it read-only."""
|
||||||
|
def fix(func, p, _exc):
|
||||||
|
try:
|
||||||
|
os.chmod(os.path.dirname(p), 0o700)
|
||||||
|
os.chmod(p, 0o700)
|
||||||
|
func(p)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
shutil.rmtree(path, onerror=fix)
|
||||||
|
|
||||||
|
|
||||||
|
class _Export:
|
||||||
|
"""The tree of one commit, exported into a temp dir with no `.git` directory (so a command
|
||||||
|
cannot read history), plus an empty directory to serve as HOME. Both are deleted on exit,
|
||||||
|
even on error. ``env()`` is all a replayed command is given: PATH, HOME (the empty
|
||||||
|
directory) and LANG, nothing from the caller's environment."""
|
||||||
|
|
||||||
|
def __init__(self, repo, commit):
|
||||||
|
self.repo, self.commit = repo, str(commit)
|
||||||
|
self.tmp = tempfile.mkdtemp(prefix="sisi-replay-")
|
||||||
|
self.path = os.path.join(self.tmp, "tree")
|
||||||
|
self.home = os.path.join(self.tmp, "home")
|
||||||
|
|
||||||
|
def env(self):
|
||||||
|
return {"PATH": os.environ.get("PATH") or "/usr/local/bin:/usr/bin:/bin", "HOME": self.home,
|
||||||
|
"LANG": os.environ.get("LANG") or "C.UTF-8"}
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
try:
|
||||||
|
os.makedirs(self.path)
|
||||||
|
os.makedirs(self.home)
|
||||||
|
proc = subprocess.Popen(["git", "-C", self.repo, "archive", "--format=tar", self.commit],
|
||||||
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||||
|
with tarfile.open(fileobj=proc.stdout, mode="r|") as tar:
|
||||||
|
for m in tar:
|
||||||
|
name = os.path.normpath(m.name)
|
||||||
|
if name.startswith(("/", "..")) or m.name.startswith("/"):
|
||||||
|
continue
|
||||||
|
if m.name == ".git" or m.name.startswith(".git/") or name == ".git":
|
||||||
|
continue # a tracked file called .git must not give the command a history
|
||||||
|
if m.issym() or m.islnk():
|
||||||
|
target = os.path.normpath(os.path.join(os.path.dirname(name), m.linkname))
|
||||||
|
if os.path.isabs(m.linkname) or target.startswith(".."):
|
||||||
|
continue # a link out of the copy is not exported
|
||||||
|
elif not (m.isfile() or m.isdir()):
|
||||||
|
continue
|
||||||
|
tar.extract(m, self.path)
|
||||||
|
err = proc.stderr.read().decode("utf-8", "replace")
|
||||||
|
proc.stdout.close()
|
||||||
|
proc.stderr.close()
|
||||||
|
if proc.wait() != 0:
|
||||||
|
raise RuntimeError(err.strip()[-300:] or "git archive failed")
|
||||||
|
return self
|
||||||
|
except BaseException as e:
|
||||||
|
_rmtree(self.tmp)
|
||||||
|
if isinstance(e, (OSError, tarfile.TarError)):
|
||||||
|
raise RuntimeError("cannot export %s into a temporary copy: %s" % (self.commit, e))
|
||||||
|
raise
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
_rmtree(self.tmp)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _run_shell(cmd, cwd, timeout_s, env=None):
|
||||||
|
"""Run a shell command in its own process group; on timeout the whole group is killed.
|
||||||
|
Returns the exit status; raises subprocess.TimeoutExpired."""
|
||||||
|
p = subprocess.Popen(str(cmd), shell=True, cwd=cwd, env=env, stdin=subprocess.DEVNULL,
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
||||||
|
try:
|
||||||
|
return p.wait(timeout=timeout_s)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
try:
|
||||||
|
os.killpg(p.pid, signal.SIGKILL)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
p.wait()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
SHELL_BUILTINS = frozenset((":", "true", "false", "test", "[", "[[", "echo", "printf", "exit", "cd", "set",
|
SHELL_BUILTINS = frozenset((":", "true", "false", "test", "[", "[[", "echo", "printf", "exit", "cd", "set",
|
||||||
"export", "unset", "read", "type", "command", "eval", "exec", "return", "source", ".",
|
"export", "unset", "read", "type", "command", "eval", "exec", "return", "source", ".",
|
||||||
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case",
|
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case",
|
||||||
@@ -468,9 +549,10 @@ def unresolved_program(cmd, cwd):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _run_checks(case, cwd, timeout_s):
|
def _run_checks(case, cwd, timeout_s, env=None):
|
||||||
"""Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed and
|
"""Run the case's checks in ``cwd`` (with ``env`` as the whole environment when given).
|
||||||
``ran``: False when the command never really ran (program missing, exit 126/127, killed)."""
|
Returns (rows, timed_out); rows carry exit/passed and ``ran``: False when the command never
|
||||||
|
really ran (program missing, exit 126/127, killed)."""
|
||||||
rows, timed_out = [], False
|
rows, timed_out = [], False
|
||||||
for c in case.get("checks") or []:
|
for c in case.get("checks") or []:
|
||||||
expect = (c.get("expect") or {})
|
expect = (c.get("expect") or {})
|
||||||
@@ -485,11 +567,14 @@ def _run_checks(case, cwd, timeout_s):
|
|||||||
"expected_exit": want, "passed": False, "error": why})
|
"expected_exit": want, "passed": False, "error": why})
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
r = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True,
|
if env is None:
|
||||||
text=True, timeout=timeout_s)
|
code = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True,
|
||||||
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": r.returncode,
|
text=True, timeout=timeout_s).returncode
|
||||||
"ran": not exit_not_ran(r.returncode),
|
else:
|
||||||
"expected_exit": want, "passed": r.returncode == want})
|
code = _run_shell(c.get("cmd"), cwd, timeout_s, env)
|
||||||
|
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": code,
|
||||||
|
"ran": not exit_not_ran(code),
|
||||||
|
"expected_exit": want, "passed": code == want})
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
timed_out = True
|
timed_out = True
|
||||||
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False,
|
rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": None, "ran": False,
|
||||||
@@ -501,7 +586,13 @@ def _run_checks(case, cwd, timeout_s):
|
|||||||
|
|
||||||
|
|
||||||
def _checks_at(case, repo, commit, timeout_s):
|
def _checks_at(case, repo, commit, timeout_s):
|
||||||
"""(all_passed, rows, timed_out) for the case's checks at one commit, in a temp worktree."""
|
"""(all_passed, rows, timed_out) for the case's checks at one commit: in a temp worktree, or,
|
||||||
|
for a case marked ``isolated`` (a command an agent wrote), in an exported copy of the tree
|
||||||
|
with no history and a reduced environment."""
|
||||||
|
if case.get("isolated"):
|
||||||
|
with _Export(repo, commit) as ex:
|
||||||
|
rows, timed_out = _run_checks(case, ex.path, timeout_s, env=ex.env())
|
||||||
|
return (bool(rows) and all(r["passed"] for r in rows)), rows, timed_out
|
||||||
with _Worktree(repo, commit) as wt:
|
with _Worktree(repo, commit) as wt:
|
||||||
rows, timed_out = _run_checks(case, wt, timeout_s)
|
rows, timed_out = _run_checks(case, wt, timeout_s)
|
||||||
return (bool(rows) and all(r["passed"] for r in rows)), rows, timed_out
|
return (bool(rows) and all(r["passed"] for r in rows)), rows, timed_out
|
||||||
@@ -578,13 +669,29 @@ def validate_check(case, store_dir=None, timeout_s=None, record=False):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def validate_command(repo, before, after, cmd, expect_exit=0, timeout_s=None, store_dir=None):
|
def _changed_paths(repo, before, after):
|
||||||
"""Replay one command at two commits of a local, trusted repository: ``validated`` only when
|
rc, out, _e = _git(repo, "diff", "--name-only", "-z", str(before), str(after))
|
||||||
it ran and failed at ``before`` and ran and passed at ``after``. Anything that stops the
|
return [x for x in out.split("\0") if x] if rc == 0 else []
|
||||||
command from really running (program missing at either commit, exit 126/127, a timeout, a
|
|
||||||
signal) is ``not-run`` with the reason, never a failure. ``before`` must be an ancestor of
|
|
||||||
``after``; the repository must be a project on the trust list. Returns the replay outcome
|
def mentions_changed_path(cmd, changed):
|
||||||
dict (``outcome``, ``reason``, ``check_results``); nothing is recorded."""
|
"""Does the command's text name a path that differs between the two trees (the path, its file
|
||||||
|
name, or the module spelling of it)? A command that names none of them cannot tell the two
|
||||||
|
trees apart by looking at what changed."""
|
||||||
|
text = str(cmd or "")
|
||||||
|
for p in changed:
|
||||||
|
base = os.path.basename(p)
|
||||||
|
mod = re.sub(r"\.py$", "", p).replace("/", ".")
|
||||||
|
if p in text or (len(base) >= 2 and base in text) or (len(mod) >= 3 and mod in text):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def replay_preflight(repo, before, after, cmd):
|
||||||
|
"""None when a replay may go ahead, else the outcome dict that says why not. Only git is run
|
||||||
|
here, never the command: the repository must be a local, trusted directory, both commits must
|
||||||
|
exist with ``before`` an ancestor of ``after``, and the command must name a path that differs
|
||||||
|
between the two trees (``vacuous`` otherwise: it cannot show a difference the change made)."""
|
||||||
from . import trust
|
from . import trust
|
||||||
repo = os.path.realpath(str(repo or ""))
|
repo = os.path.realpath(str(repo or ""))
|
||||||
if not os.path.isdir(repo) or _is_remote(repo):
|
if not os.path.isdir(repo) or _is_remote(repo):
|
||||||
@@ -599,7 +706,33 @@ def validate_command(repo, before, after, cmd, expect_exit=0, timeout_s=None, st
|
|||||||
if rc != 0:
|
if rc != 0:
|
||||||
return {"outcome": "not-run", "check_results": [],
|
return {"outcome": "not-run", "check_results": [],
|
||||||
"reason": "the before commit is not an ancestor of the after commit"}
|
"reason": "the before commit is not an ancestor of the after commit"}
|
||||||
case = {"id": "replay", "kind": "check", "split": "dev",
|
changed = _changed_paths(repo, before, after)
|
||||||
|
if not changed:
|
||||||
|
return {"outcome": "vacuous", "check_results": [],
|
||||||
|
"reason": "the two commits have identical trees; a command cannot tell them apart"}
|
||||||
|
if not mentions_changed_path(cmd, changed):
|
||||||
|
return {"outcome": "vacuous", "check_results": [],
|
||||||
|
"reason": "the command names none of the paths that differ between the two trees (%s%s), so "
|
||||||
|
"it is vacuous: it cannot show what the change made different"
|
||||||
|
% (", ".join(changed[:4]), ", ..." if len(changed) > 4 else "")}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_command(repo, before, after, cmd, expect_exit=0, timeout_s=None, store_dir=None):
|
||||||
|
"""Replay one command at two commits of a local, trusted repository: ``validated`` only when
|
||||||
|
it ran and failed at ``before`` and ran and passed at ``after``. Each run is in an exported
|
||||||
|
copy of that commit's tree (no ``.git``), with an environment of PATH, HOME (an empty
|
||||||
|
directory) and LANG only, under a time limit; the copy is deleted afterwards. Anything that
|
||||||
|
stops the command from really running (program missing at either commit, exit 126/127, a
|
||||||
|
timeout, a signal) is ``not-run`` with the reason, never a failure. ``before`` must be an
|
||||||
|
ancestor of ``after``; the repository must be a project on the trust list; the command must
|
||||||
|
name a path that differs between the trees (``vacuous`` otherwise). Returns the replay
|
||||||
|
outcome dict (``outcome``, ``reason``, ``check_results``); nothing is recorded."""
|
||||||
|
stop = replay_preflight(repo, before, after, cmd)
|
||||||
|
if stop:
|
||||||
|
return stop
|
||||||
|
repo = os.path.realpath(str(repo))
|
||||||
|
case = {"id": "replay", "kind": "check", "split": "dev", "isolated": True,
|
||||||
"project": {"repo": repo, "start_commit": str(before), "fix_commit": str(after)},
|
"project": {"repo": repo, "start_commit": str(before), "fix_commit": str(after)},
|
||||||
"checks": [{"id": "c", "cmd": str(cmd), "expect": {"exit": expect_exit}}]}
|
"checks": [{"id": "c", "cmd": str(cmd), "expect": {"exit": expect_exit}}]}
|
||||||
timeout_s = float(timeout_s or _eval_config(store_dir)["timeout_s"])
|
timeout_s = float(timeout_s or _eval_config(store_dir)["timeout_s"])
|
||||||
|
|||||||
@@ -539,6 +539,29 @@ def withdraw(lid, why):
|
|||||||
return rec
|
return rec
|
||||||
|
|
||||||
|
|
||||||
|
def replay_commits(rec):
|
||||||
|
"""(before, after, where) for replaying a command against this learning, or None. Only the
|
||||||
|
learning's own record counts, never anything a cycle file says: the start and closing commits
|
||||||
|
of the unit it was found in (the unit record in its origin project), else the two commits
|
||||||
|
stored with the finding. A learning without both cannot be validated."""
|
||||||
|
proj, uid = rec.get("origin_project"), rec.get("source_unit")
|
||||||
|
if proj and uid and os.path.isdir(proj):
|
||||||
|
from . import store
|
||||||
|
try:
|
||||||
|
with open(os.path.join(proj, ".sisi", "units", store.safe_id(uid) + ".json"), encoding="utf-8") as f:
|
||||||
|
u = json.load(f)
|
||||||
|
a, b = u.get("start_commit"), u.get("closing_commit")
|
||||||
|
if isinstance(a, str) and isinstance(b, str) and a and b and a != b:
|
||||||
|
return a, b, "the unit record of %s" % uid
|
||||||
|
except (OSError, ValueError, AttributeError):
|
||||||
|
pass
|
||||||
|
rp = rec.get("replay") or {}
|
||||||
|
a, b = rp.get("before"), rp.get("after")
|
||||||
|
if isinstance(a, str) and isinstance(b, str) and a and b and a != b:
|
||||||
|
return a, b, "the commits stored with the finding"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def findings_for_unit(project, uid):
|
def findings_for_unit(project, uid):
|
||||||
"""Seam for the unit record: the findings recorded for one unit in one project."""
|
"""Seam for the unit record: the findings recorded for one unit in one project."""
|
||||||
pk = project_key(project)
|
pk = project_key(project)
|
||||||
|
|||||||
+11
-1
@@ -23,6 +23,16 @@ def _git_head(cwd):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _unit_start(project):
|
||||||
|
"""The commit the open unit started at (base_head in its contract), if known."""
|
||||||
|
try:
|
||||||
|
with open(os.path.join(project, ".sisi", "contract.json"), encoding="utf-8") as f:
|
||||||
|
b = json.load(f).get("base_head")
|
||||||
|
return b if isinstance(b, str) and b else None
|
||||||
|
except (OSError, ValueError, AttributeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def unit_summary(project):
|
def unit_summary(project):
|
||||||
"""What `sisi retro` with no arguments prints: the unit's record and what stands out."""
|
"""What `sisi retro` with no arguments prints: the unit's record and what stands out."""
|
||||||
from . import unit as _unit
|
from . import unit as _unit
|
||||||
@@ -161,7 +171,7 @@ def cmd_retro(argv, stdin=None):
|
|||||||
replay = None
|
replay = None
|
||||||
head = _git_head(project)
|
head = _git_head(project)
|
||||||
if head:
|
if head:
|
||||||
replay = {"repo": pk, "after": head, "before": None}
|
replay = {"repo": pk, "after": head, "before": _unit_start(project)}
|
||||||
ts = L.now()
|
ts = L.now()
|
||||||
fid = "F-" + hashlib.sha1(("%s|%s|%s|%s" % (uid, pk, ts, finding)).encode()).hexdigest()[:8]
|
fid = "F-" + hashlib.sha1(("%s|%s|%s|%s" % (uid, pk, ts, finding)).encode()).hexdigest()[:8]
|
||||||
f = {"id": fid, "unit": uid, "project": pk, "ts": ts, "finding": L.scrub_secrets(finding),
|
f = {"id": fid, "unit": uid, "project": pk, "ts": ts, "finding": L.scrub_secrets(finding),
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Hardening of the learning cycle after a real rehearsal. Docstrings cite docs/spec/requirements.json ids.
|
||||||
|
|
||||||
|
Each test is an abuse case: the cycle file's author (an agent, untrusted) tries to get something
|
||||||
|
to run, validate or take effect that nobody approved.
|
||||||
|
"""
|
||||||
|
import json, os, subprocess, sys
|
||||||
|
|
||||||
|
from support import SisiCase
|
||||||
|
from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract
|
||||||
|
from sisi import learning as L
|
||||||
|
|
||||||
|
|
||||||
|
class Replay(Base):
|
||||||
|
"""R-11.5-6, R-11.6-3, R-16-6, R-16-7, R-16-4 (items 1 and 2)."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.marker = os.path.join(self.tmp, "marker")
|
||||||
|
self.secret_name = "SISI_TEST_SECRET_TOKEN"
|
||||||
|
|
||||||
|
def recorded(self, before, after):
|
||||||
|
self.retro(*PROMOTE[1:])
|
||||||
|
self.archive_unit(before, after)
|
||||||
|
|
||||||
|
def cmd_action(self, cmd, **kw):
|
||||||
|
a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": cmd}
|
||||||
|
a.update(kw)
|
||||||
|
return a
|
||||||
|
|
||||||
|
def test_check_never_executes_anything_from_the_file(self):
|
||||||
|
"""R-16-6 (item 1): `sisi cycle check` runs nothing the file contains; `apply` does, in a copy."""
|
||||||
|
before, after = self.fixed_repo()
|
||||||
|
self.recorded(before, after)
|
||||||
|
cmd = "sh -c 'echo ran > %s; grep -q fixed f.txt'" % self.marker
|
||||||
|
p = self.cycle_file([self.cmd_action(cmd)])
|
||||||
|
r = self.sisi("cycle", "check", p)
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
self.assertFalse(os.path.exists(self.marker), "check executed a command from the file")
|
||||||
|
r = self.sisi("cycle", "apply", p)
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
self.assertTrue(os.path.exists(self.marker), "apply replays the command (in an exported copy)")
|
||||||
|
|
||||||
|
def test_replay_runs_in_an_exported_copy_without_history_or_the_callers_secrets(self):
|
||||||
|
"""R-16-4, R-16-6 (items 1, 2): no .git, HOME empty and not the caller's, the secret in the
|
||||||
|
caller's environment is not visible, the working directory is not the project, and the copy
|
||||||
|
is deleted afterwards."""
|
||||||
|
before, after = self.fixed_repo()
|
||||||
|
self.recorded(before, after)
|
||||||
|
rec = os.path.join(self.tmp, "rec.txt")
|
||||||
|
script = ("{ pwd; test -e .git && echo GIT || echo NOGIT; echo \"HOME=$HOME\"; "
|
||||||
|
"echo \"SECRET=${%s:-unset}\"; env | cut -d= -f1 | sort | paste -sd, -; "
|
||||||
|
"ls -A \"$HOME\" | wc -l; } > %s; grep -q fixed f.txt" % (self.secret_name, rec))
|
||||||
|
cmd = "sh -c '%s'" % script
|
||||||
|
import unittest.mock
|
||||||
|
with unittest.mock.patch.dict(os.environ, {self.secret_name: "hunter2-very-secret"}):
|
||||||
|
r = self.apply([self.cmd_action(cmd)])
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
self.assertEqual(self.rows()[0]["validation"]["result"], "validated", r.stdout + r.stderr)
|
||||||
|
with open(rec) as f:
|
||||||
|
out = f.read().splitlines()
|
||||||
|
self.assertNotEqual(out[0], self.proj)
|
||||||
|
self.assertFalse(os.path.exists(out[0]), "the exported copy was not deleted")
|
||||||
|
self.assertEqual(out[1], "NOGIT")
|
||||||
|
self.assertNotEqual(out[2], "HOME=" + os.environ.get("HOME", ""))
|
||||||
|
self.assertEqual(out[3], "SECRET=unset")
|
||||||
|
names = set(out[4].split(",")) - {"PWD", "SHLVL", "_", "OLDPWD"}
|
||||||
|
self.assertEqual(names, {"PATH", "HOME", "LANG"}, out[4])
|
||||||
|
self.assertEqual(out[5].strip(), "0")
|
||||||
|
self.assertNotIn("hunter2", r.stdout + r.stderr + json.dumps(self.rows()))
|
||||||
|
|
||||||
|
def test_a_command_reading_git_history_finds_none(self):
|
||||||
|
"""R-11.6-3, R-16-7 (item 2): the history trick no longer works. The command names a changed
|
||||||
|
path and reads `git log`; with no .git in the copy it cannot pass at the fix, so it is refused."""
|
||||||
|
before, after = self.fixed_repo()
|
||||||
|
self.recorded(before, after)
|
||||||
|
r = self.apply([self.cmd_action("git log -p -- f.txt | grep -q fixed")])
|
||||||
|
self.assertNotEqual(r.returncode, 0)
|
||||||
|
self.assertIn("replay validation failed", r.stderr)
|
||||||
|
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||||
|
self.assertEqual(self.rows()[0]["status"], "proposed")
|
||||||
|
|
||||||
|
def test_the_fix_commit_subject_trick_is_vacuous_and_refused(self):
|
||||||
|
"""R-11.6-3 (item 2): `git show HEAD --stat | grep -q <subject>` names no path that differs
|
||||||
|
between the two trees: refused as vacuous, with a message that says so."""
|
||||||
|
before, after = self.fixed_repo()
|
||||||
|
self.recorded(before, after)
|
||||||
|
r = self.apply([self.cmd_action('git show HEAD --stat | grep -q "fix"')])
|
||||||
|
self.assertNotEqual(r.returncode, 0)
|
||||||
|
self.assertIn("vacuous", r.stderr)
|
||||||
|
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||||
|
r = self.sisi("cycle", "check", self.cycle_file([self.cmd_action("echo ok")]))
|
||||||
|
self.assertNotEqual(r.returncode, 0)
|
||||||
|
self.assertIn("vacuous", r.stderr)
|
||||||
|
|
||||||
|
def test_a_learning_without_recorded_commits_cannot_be_validated(self):
|
||||||
|
"""R-11.6-3 (item 2): no unit record and no commits stored with the finding: the command check
|
||||||
|
waits for the owner as unvalidated, whatever commits the file names."""
|
||||||
|
before, after = self.fixed_repo()
|
||||||
|
self.retro(*PROMOTE[1:])
|
||||||
|
self.assertIsNone(L.replay_commits(self.rows()[0]) if not self.rows()[0].get("replay", {}).get("before") else None)
|
||||||
|
r = self.apply([self.cmd_action("grep -q fixed f.txt", before=before, after=after)])
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
pend = self.pending()
|
||||||
|
self.assertEqual(len(pend), 1)
|
||||||
|
self.assertEqual(pend[0]["replay"][0], "unvalidated")
|
||||||
|
self.assertIn("no commits are recorded", pend[0]["replay"][1])
|
||||||
|
self.assertNotEqual(self.rows()[0]["validation"]["result"], "validated")
|
||||||
|
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||||
|
|
||||||
|
def test_the_finding_records_the_unit_start_so_a_retro_can_be_replayed(self):
|
||||||
|
"""R-11.6-3 (item 2): the commits stored with the finding are the unit's base_head and HEAD."""
|
||||||
|
from sisi import trust
|
||||||
|
_contract(self)
|
||||||
|
self.git_init()
|
||||||
|
trust.add(self.proj)
|
||||||
|
self.write("f.txt", "bug\n")
|
||||||
|
self._commit("before")
|
||||||
|
base = self._head()
|
||||||
|
cp = os.path.join(self.proj, ".sisi", "contract.json")
|
||||||
|
with open(cp) as f:
|
||||||
|
c = json.load(f)
|
||||||
|
c["base_head"] = base
|
||||||
|
with open(cp, "w") as f:
|
||||||
|
json.dump(c, f)
|
||||||
|
self.write("f.txt", "fixed\n")
|
||||||
|
self._commit("fix")
|
||||||
|
self.retro(*PROMOTE[1:])
|
||||||
|
got = L.replay_commits(self.rows()[0])
|
||||||
|
self.assertEqual(got[:2], (base, self._head()))
|
||||||
|
r = self.apply([self.cmd_action("grep -q fixed f.txt")])
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
|
||||||
@@ -64,6 +64,15 @@ class Base(SisiCase):
|
|||||||
self._commit("fix")
|
self._commit("fix")
|
||||||
return before, self._head()
|
return before, self._head()
|
||||||
|
|
||||||
|
def archive_unit(self, before, after, uid=None, d=None):
|
||||||
|
"""The unit record, as `sisi unit close` writes it: the unit's start and closing commits."""
|
||||||
|
uid = uid or self.rows()[0]["source_unit"]
|
||||||
|
d = os.path.join(d or self.proj, ".sisi", "units")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
from sisi import store
|
||||||
|
with open(os.path.join(d, store.safe_id(uid) + ".json"), "w") as f:
|
||||||
|
json.dump({"id": uid, "start_commit": before, "closing_commit": after}, f)
|
||||||
|
|
||||||
def cycle_file(self, actions, name="c.json", base=None):
|
def cycle_file(self, actions, name="c.json", base=None):
|
||||||
p = os.path.join(self.tmp, name)
|
p = os.path.join(self.tmp, name)
|
||||||
with open(p, "w") as f:
|
with open(p, "w") as f:
|
||||||
@@ -185,9 +194,10 @@ class Retro(Base):
|
|||||||
"""R-11.5-6, R-11.5-8 (item 13): the status field itself says validated / monitored."""
|
"""R-11.5-6, R-11.5-8 (item 13): the status field itself says validated / monitored."""
|
||||||
before, after = self.fixed_repo()
|
before, after = self.fixed_repo()
|
||||||
self.retro(*PROMOTE[1:])
|
self.retro(*PROMOTE[1:])
|
||||||
|
self.archive_unit(before, after)
|
||||||
# a validated command that waits for the owner is `validated`, not `promoted`
|
# a validated command that waits for the owner is `validated`, not `promoted`
|
||||||
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
||||||
"cmd": "grep -q fixed f.txt", "before": before, "after": after, "scope": "user"}])
|
"cmd": "grep -q fixed f.txt", "scope": "user"}])
|
||||||
self.assertEqual(self.rows()[0]["status"], "validated")
|
self.assertEqual(self.rows()[0]["status"], "validated")
|
||||||
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
|
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
|
||||||
# a promoted learning becomes `monitored` once a unit in its scope has closed since
|
# a promoted learning becomes `monitored` once a unit in its scope has closed since
|
||||||
@@ -316,9 +326,12 @@ class Replay(Base):
|
|||||||
fix and ran and passed after it, in the learning's own trusted repository."""
|
fix and ran and passed after it, in the learning's own trusted repository."""
|
||||||
|
|
||||||
def promote_cmd(self, cmd, before, after, **kw):
|
def promote_cmd(self, cmd, before, after, **kw):
|
||||||
|
"""Record the learning, give its unit record the two commits, then apply a command check.
|
||||||
|
The commits come from the record; anything the cycle file says about them is ignored."""
|
||||||
self.retro(*PROMOTE[1:])
|
self.retro(*PROMOTE[1:])
|
||||||
a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
if before and after:
|
||||||
"cmd": cmd, "before": before, "after": after}
|
self.archive_unit(before, after, uid=self.rows()[0]["source_unit"])
|
||||||
|
a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": cmd}
|
||||||
a.update(kw)
|
a.update(kw)
|
||||||
return self.apply([a])
|
return self.apply([a])
|
||||||
|
|
||||||
@@ -422,8 +435,10 @@ class Replay(Base):
|
|||||||
r = self.promote_cmd("grep -q fixed f.txt", before, after)
|
r = self.promote_cmd("grep -q fixed f.txt", before, after)
|
||||||
self.assert_unvalidated(r, "trust")
|
self.assert_unvalidated(r, "trust")
|
||||||
|
|
||||||
def test_repo_chosen_by_the_author_must_be_the_learnings_project(self):
|
def test_repo_and_commits_named_by_the_author_are_ignored(self):
|
||||||
"""The cycle file names a different (trusted) repository: it is not the learning's origin."""
|
"""R-11.6-3, R-16-7: the cycle file names another (trusted) repository and its own two
|
||||||
|
commits; the replay uses the learning's own record, so a command that only passes there
|
||||||
|
is not validated here."""
|
||||||
from sisi import trust
|
from sisi import trust
|
||||||
before, after = self.fixed_repo()
|
before, after = self.fixed_repo()
|
||||||
other = self.other_project()
|
other = self.other_project()
|
||||||
@@ -433,8 +448,14 @@ class Replay(Base):
|
|||||||
ob = self._head(other)
|
ob = self._head(other)
|
||||||
self.write("f.txt", "fixed\n", other)
|
self.write("f.txt", "fixed\n", other)
|
||||||
self._commit("a", other)
|
self._commit("a", other)
|
||||||
r = self.promote_cmd("grep -q fixed f.txt", ob, self._head(other), repo=other)
|
self.retro(*PROMOTE[1:])
|
||||||
self.assert_unvalidated(r, "origin project")
|
self.archive_unit(before, after, uid=self.rows()[0]["source_unit"])
|
||||||
|
r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
||||||
|
"cmd": "grep -q fixed f.txt", "repo": other, "before": ob, "after": self._head(other)}])
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
|
||||||
|
self.assertIn(before[:12], self.rows()[0]["validation"]["detail"])
|
||||||
|
self.assertNotIn(ob[:12], self.rows()[0]["validation"]["detail"])
|
||||||
|
|
||||||
def test_nothing_validated_without_a_passing_run(self):
|
def test_nothing_validated_without_a_passing_run(self):
|
||||||
"""R-11.5-6, R-11.1-8: 'validated' requires a validation run that passed."""
|
"""R-11.5-6, R-11.1-8: 'validated' requires a validation run that passed."""
|
||||||
@@ -489,8 +510,9 @@ class Mechanisms(Base):
|
|||||||
from sisi import cycle, trust
|
from sisi import cycle, trust
|
||||||
before, after = self.fixed_repo()
|
before, after = self.fixed_repo()
|
||||||
self.retro(*PROMOTE[1:])
|
self.retro(*PROMOTE[1:])
|
||||||
|
self.archive_unit(before, after)
|
||||||
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
||||||
"cmd": "grep -q fixed f.txt", "before": before, "after": after}]).returncode, 0)
|
"cmd": "grep -q fixed f.txt"}]).returncode, 0)
|
||||||
other = self.other_project()
|
other = self.other_project()
|
||||||
trust.add(other)
|
trust.add(other)
|
||||||
self.write("f.txt", "bug\n", other)
|
self.write("f.txt", "bug\n", other)
|
||||||
|
|||||||
Reference in new issue
Block a user