diff --git a/sisi/cli.py b/sisi/cli.py index 903f584..79bd35c 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -55,7 +55,8 @@ Hooks (the agent tool calls these): sisi tick | prompt | watch | gate Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository; a project's rules live in its .sisi/rules.md. Settings: "core" in its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after, -research_days, shell_workers, enforce, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts).""" +research_days, shell_workers, enforce, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts, +auto_update, update_hours, update_url).""" def main(argv): @@ -86,7 +87,7 @@ def main(argv): if cmd in ("install", "uninstall", "release", "update", "rollback", "doctor"): from . import install cmd == "release" and models.sync_shared() - return getattr(install, cmd)() + return install.update(auto="--auto" in args) if cmd == "update" else getattr(install, cmd)() if cmd in ("rulebook", "version"): print(rules.build_rulebook() if cmd == "rulebook" else store.read(os.path.join(store.ROOT, "VERSION")).strip()) return 0 diff --git a/sisi/hooks.py b/sisi/hooks.py index 3d10eb1..d3d21fe 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -112,6 +112,7 @@ def _faults(cwd, gate=False, free=None, sid=""): def tick(p): """Session start: remember where the work began; print this project's learned rules and what is due.""" sid, cwd, worker, free = p["session_id"], p["cwd"] or os.getcwd(), p["subagent"], None + __import__("sisi.install", fromlist=["maybe_auto_update"]).maybe_auto_update() # lazy: keeps importing this module free of install's heavier imports if sid: with store.session(sid) as s: _begin(s, cwd) diff --git a/sisi/install.py b/sisi/install.py index bed2bd1..1943a26 100644 --- a/sisi/install.py +++ b/sisi/install.py @@ -214,6 +214,59 @@ def _source(): return "" +SHA = r"[0-9a-f]{40}" + + +def _head(root): + """The commit a release of this checkout is of: HEAD, with "-dirty" when the tree differs from it (a developer's + unpushed release is never auto-replaced), "" outside git.""" + rc, sha = store.git(["rev-parse", "HEAD"], root) + return sha.strip() + ("-dirty" if store.git(["status", "--porcelain", "--", ":(top)", ":(top,exclude).sisi"], root)[1].strip() else "") if not rc and re.fullmatch(SHA, sha.strip()) else "" + + +def _current_commit(): + """The commit the release in use records (SOURCE line three), "" when it records none (an old release).""" + return (store.read(os.path.join(_current(), "SOURCE")).split("\n") + ["", "", ""])[2].strip() + + +def _auto_log(result, old="", new=""): + try: + store.append(os.path.join(store.STATE, "auto-update.log"), "%s %s %s->%s" % (time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()), result, (old or "?")[:7], (new or "?")[:7])) + except OSError: + pass + return 0 + + +def _float(text, default): + try: + return float(text) + except (TypeError, ValueError): + return default + + +def maybe_auto_update(): + """Session start: print a pending updated-itself notice once, and when a check is due start `sisi update --auto` + fully detached. No network or git here, silent on any failure, and the new timestamp is written before starting.""" + try: + path = os.path.join(store.STATE, "auto-update-notice") + try: + os.replace(path, taken := "%s.taken-%d" % (path, os.getpid())) # claim it first: only one session start wins + new, _, old = store.read(taken).strip().partition(" ") + os.remove(taken) + new and print("sisi: updated itself to %s (was %s); `sisi rollback` goes back." % (new[:7], old[:7] if old else "unknown")) + except OSError: + pass + cfg, exe = store.config(), os.path.join(_current(), "bin", "sisi") + stamp = os.path.join(store.STATE, "auto-update-check") + if not cfg.get("auto_update") or not os.path.isfile(exe) or time.time() - _float(store.read(stamp).strip() or 0, 0) < _float(cfg.get("update_hours"), 24) * 3600: + return # off, nothing installed to update yet, or not due (no stamp is spent before an install exists) + store.write(stamp, str(time.time())) + with open(os.path.join(store.STATE, "auto-update.log"), "ab") as log: + subprocess.Popen([sys.executable, "-B", exe, "update", "--auto"], stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True) + except Exception: + pass + + def _switch(dest): tmp = _current() + ".new" if os.path.lexists(tmp): @@ -232,13 +285,14 @@ def release(): return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode print("sisi release: run it from the source checkout.") return 1 + head = _head(store.ROOT) # before the test run: it leaves __pycache__ behind, which is not a change to the product if subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"], cwd=store.ROOT).returncode: print("sisi release: the tests fail. Nothing was released.") return 1 name = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + "%03dZ" % (time.time() % 1 * 1000) # two in one second differ dest = os.path.join(folder, name) shutil.copytree(store.ROOT, dest, ignore=shutil.ignore_patterns(".git", ".agent-work", ".sisi", "__pycache__")) - store.write(os.path.join(dest, "SOURCE"), "%s\n%s\n" % (_source(), os.path.abspath(store.ROOT))) + store.write(os.path.join(dest, "SOURCE"), "%s\n%s\n%s\n" % (_source(), os.path.abspath(store.ROOT), head)) _switch(dest) subprocess.run([os.path.join(dest, "bin", "sisi"), "rulebook"]) for old in [o for o in sorted(os.listdir(folder)) if o != name][:-3]: # never the one just put in use, even when the clock is behind @@ -263,8 +317,12 @@ def rollback(): return 0 -def update(): - """Fetch the newest sisi from where the release in use came from, and release it. No checkout needed.""" +def update(auto=False): + """Fetch the newest sisi from where the release in use came from, and release it. No checkout needed. + With auto=True (the detached background job): silent, locked, and it skips anything but a straight + move forward along the remote's main branch.""" + if auto: + return _auto_update() url = store.read(os.path.join(_current(), "SOURCE")).split("\n")[0].strip() if not url: print("sisi update: the release in use does not record where it came from. Run `sisi release` from a checkout that has a remote.") @@ -277,6 +335,42 @@ def update(): return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode +def _auto_update(): + """One background check: ls-remote, and only a known ancestor (or an unknown commit) moves forward through the + usual tested release. One log line per run, nothing to any terminal; always exits 0.""" + with store.lock("auto-update", wait=False) as held: + if not held: + return 0 + old, new = _current_commit(), "" + try: + url = str(store.config().get("update_url") or "").strip() + rc, out = store.git(["ls-remote", url, "refs/heads/main"], store.ROOT, timeout=60) if url else (1, "") + new = out.split()[0] if rc == 0 and out.split() else "" + if not re.fullmatch(SHA, new): + return _auto_log("failed ls-remote" if url else "skipped no update_url", old, new) + if old == new: + return _auto_log("current", old, new) + if old and not re.fullmatch(SHA, old): # e.g. a "-dirty" developer release + return _auto_log("skipped local commit is not an ancestor (unrecorded changes)", old, new) + with tempfile.TemporaryDirectory(prefix="sisi-update-") as tmp: + src = os.path.join(tmp, "sisi") + if subprocess.run(["git", "clone", "-q", url, src], stdin=subprocess.DEVNULL, capture_output=True).returncode: + return _auto_log("failed fetch", old, new) + head = store.git(["rev-parse", "HEAD"], src)[1].strip() + new = head if re.fullmatch(SHA, head) else new + if old and store.git(["merge-base", "--is-ancestor", old, new], src)[0] != 0: + return _auto_log("skipped local commit is not an ancestor of remote main", old, new) + if subprocess.run([sys.executable, "-B", os.path.join(src, "bin", "sisi"), "release"], stdin=subprocess.DEVNULL, capture_output=True).returncode: + return _auto_log("failed tests, nothing switched", old, new) + landed = _current_commit() + if landed and landed != old: + store.write(os.path.join(store.STATE, "auto-update-notice"), "%s %s\n" % (landed, old)) + return _auto_log("updated", old, landed) + return _auto_log("failed release, nothing switched", old, new) + except Exception as e: # a background job never breaks or talks to a session + return _auto_log("failed %r" % (e,), old, new) + + def _wired(h, d): """Does the tool's hooks file hold every current sisi entry?""" hooks = _load(os.path.join(d, h["hooks"]["file"]))[2] diff --git a/sisi/store.py b/sisi/store.py index 5bcaab9..d240fdb 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -25,7 +25,8 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 3, "shell_workers": False, "enforce": True, - "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8} + "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8, + "auto_update": True, "update_hours": 24, "update_url": "https://github.com/swaits/sisi"} def config(): cfg = dict(DEFAULTS) diff --git a/tests/test_auto_update.py b/tests/test_auto_update.py new file mode 100644 index 0000000..3323a16 --- /dev/null +++ b/tests/test_auto_update.py @@ -0,0 +1,277 @@ +"""Auto-update: a detached background check at session start, the release it makes, and its one-line notice. + +Everything runs against a local bare git repository as the remote, in a temporary home with temporary +SISI_DATA/SISI_STATE/SISI_LIB, so the person's own files are never touched (guarded below).""" +import glob, hashlib, json, os, shutil, subprocess, sys, tempfile, time, unittest +from unittest import mock + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REAL_HOME = os.path.expanduser("~") + + +def tree(): + """A fingerprint of the product tree, so a test that writes into it is caught (as in test_core).""" + out = hashlib.sha1() + for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))): + if os.path.isfile(p): + with open(p, "rb") as f: + out.update(p.encode() + f.read()) + return out.hexdigest() + + +class AutoUpdate(unittest.TestCase): + def setUp(self): + before = tree() + self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, + "a test wrote the person's own rules file")) + self.tmp = tempfile.mkdtemp(prefix="sisi-test-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.data = os.path.join(self.tmp, "data") + self.state = os.path.join(self.tmp, "state") + self.lib = os.path.join(self.tmp, "lib") + self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=self.state, + SISI_LIB=self.lib, CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) + for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"): + self.env.pop(name, None) + self.proj = self.project("alpha") + + # helpers copied in shape from tests/test_core.py + def read(self, *parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + + def write(self, path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + def project(self, name): + path = os.path.join(self.tmp, name) + os.makedirs(path) + for args in (["init", "-q", "-b", "main"], ["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"], + ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]): + subprocess.run(["git"] + args, cwd=path, check=True, capture_output=True) + return path + + def git(self, cwd, *args): + r = subprocess.run(["git"] + list(args), cwd=cwd, check=True, capture_output=True, text=True) + return r.stdout.strip() + + def run_exe(self, exe, *args, stdin=""): + return subprocess.run([sys.executable, exe] + list(args), cwd=self.proj, env=self.env, + input=stdin, capture_output=True, text=True) + + def in_process(self, fn, *args): + """Run fn in this process against the temp store and temp home (test_core's helper, plus the + SISI_* variables so a child process fn starts lands in the same temp places); (result, output).""" + import contextlib, io + from sisi import store + out, here = io.StringIO(), os.getcwd() + os.chdir(self.tmp) + try: + with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", self.state), \ + mock.patch.object(store, "LIB", self.lib), mock.patch.object(store, "HOME", self.tmp), \ + mock.patch.dict(os.environ, {k: self.env[k] for k in + ("HOME", "CLAUDE_CONFIG_DIR", "SISI_DATA", "SISI_STATE", "SISI_LIB")}), \ + contextlib.redirect_stdout(out): + return fn(*args), out.getvalue() + finally: + os.chdir(here) + + def config(self, **kw): + core = {"update_url": "file://" + self.bare} + core.update(kw) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": core})) + + def source(self, version="1.0.0", fail=False): + """A git repository (branch main) holding the product and one small test, plus its bare remote.""" + src = os.path.join(self.tmp, "source") + if not os.path.isdir(src): + for name in ("sisi", "bin", "canon"): + shutil.copytree(os.path.join(REPO, name), os.path.join(src, name), + ignore=shutil.ignore_patterns("__pycache__")) + os.makedirs(os.path.join(src, "tests")) + subprocess.run(["git", "init", "-q", "-b", "main"], cwd=src, check=True) + for args in (["config", "gc.auto", "0"], ["config", "maintenance.auto", "false"]): + subprocess.run(["git"] + args, cwd=src, check=True) + self.write(os.path.join(src, "tests", "test_ok.py"), + "import unittest\nclass T(unittest.TestCase):\n def test(self): %s\n" % ("self.fail('bad')" if fail else "pass")) + self.write(os.path.join(src, "VERSION"), version + "\n") + self.git(src, "add", "-A") + self.git(src, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", version) + self.bare = os.path.join(self.tmp, "remote.git") + if not os.path.isdir(self.bare): + subprocess.run(["git", "clone", "-q", "--bare", src, self.bare], check=True, capture_output=True) + self.git(src, "remote", "add", "origin", self.bare) + self.git(src, "push", "-q", "origin", "main") + return src + + def remote_sha(self): + return self.git(self.bare, "rev-parse", "refs/heads/main") + + def install_release(self): + """Release the version now on the remote, as the person's first install would.""" + mine = os.path.join(self.tmp, "mine") + subprocess.run(["git", "clone", "-q", self.bare, mine], check=True, capture_output=True) + r = self.run_exe(os.path.join(mine, "bin", "sisi"), "release") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + return os.path.join(self.lib, "current", "bin", "sisi") + + def releases(self): + folder = os.path.join(self.lib, "releases") + return sorted(os.listdir(folder)) if os.path.isdir(folder) else [] + + def current(self, *parts): + return self.read(self.lib, "current", *parts) + + def current_commit(self): + lines = (self.current("SOURCE").split("\n") + ["", "", ""]) + return lines[2].strip() + + def log(self): + path = os.path.join(self.state, "auto-update.log") + return self.read(path) if os.path.exists(path) else "" + + def auto(self, exe): + return self.run_exe(exe, "update", "--auto") + + def set_up_released(self): + self.source("1.0.0") + exe = self.install_release() + self.config() + return exe + + # the tests + def test_tick_starts_the_detached_job_only_when_due_and_only_when_on(self): + from sisi import hooks, install + self.bare = os.path.join(self.tmp, "remote.git") # config() names it; Popen is mocked, nothing fetches + self.config() + with mock.patch("sisi.install.subprocess.Popen") as popen: # no release in use yet: nothing is started + self.in_process(install.maybe_auto_update) + popen.assert_not_called() + self.write(os.path.join(self.lib, "current", "bin", "sisi"), "# placeholder for the installed command\n") + stamp = os.path.join(self.state, "auto-update-check") + with mock.patch("sisi.install.subprocess.Popen") as popen: + self.in_process(install.maybe_auto_update) + self.assertEqual(popen.call_count, 1) + args, kw = popen.call_args + self.assertIn("-B", args[0]) + self.assertTrue(args[0][2].endswith(os.path.join("bin", "sisi")), args[0]) + self.assertEqual(args[0][3:], ["update", "--auto"]) + self.assertTrue(kw["start_new_session"]) + self.assertEqual(kw["stdin"], subprocess.DEVNULL) + popen.return_value.wait.assert_not_called() # detached: never waited on + stamp1 = float(self.read(stamp)) + self.in_process(install.maybe_auto_update) # not due yet + self.assertEqual(popen.call_count, 1) + self.write(stamp, str(time.time() - 25 * 3600)) # due again (default 24h) + self.in_process(install.maybe_auto_update) + self.assertEqual(popen.call_count, 2) + self.assertGreater(float(self.read(stamp)), stamp1) + self.write(stamp, str(time.time() - 25 * 3600)) + popen.side_effect = OSError("cannot start") # the stamp is written first: no retry storm + self.in_process(install.maybe_auto_update) + self.assertGreater(float(self.read(stamp)), time.time() - 60) + popen.side_effect = None + self.config(auto_update=False) # off: never started, however old the stamp + self.write(stamp, str(time.time() - 99 * 3600)) + self.in_process(install.maybe_auto_update) + self.assertEqual(popen.call_count, 3) + with mock.patch.object(install, "maybe_auto_update") as called: # session start makes the call + p = hooks.normalize({"session_id": "s1", "cwd": self.proj, "agent_id": "w"}) + self.in_process(hooks.tick, p) + called.assert_called_once_with() + + def test_release_records_its_commit_and_same_commit_releases_nothing(self): + exe = self.set_up_released() + self.assertEqual(self.current_commit(), self.remote_sha()) + before = self.releases() + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr) + self.assertEqual(self.releases(), before) + self.assertIn(self.remote_sha()[:7], self.log()) + self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice"))) + + def test_remote_ahead_is_released(self): + exe = self.set_up_released() + old = self.remote_sha() + self.source("2.0.0") + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr) + self.assertEqual(self.current("VERSION").strip(), "2.0.0") + self.assertEqual(self.current_commit(), self.remote_sha()) + self.assertIn("%s->%s" % (old[:7], self.remote_sha()[:7]), self.log()) + self.assertTrue(os.path.exists(os.path.join(self.state, "auto-update-notice"))) + + def test_unknown_commit_is_treated_as_update(self): + exe = self.set_up_released() + lines = self.current("SOURCE").split("\n") + self.write(os.path.join(os.path.realpath(os.path.join(self.lib, "current")), "SOURCE"), + "\n".join(lines[:2]) + "\n") # an old release: no commit recorded + self.source("2.0.0") + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout), (0, ""), r.stdout + r.stderr) + self.assertEqual(self.current("VERSION").strip(), "2.0.0") + self.assertEqual(self.current_commit(), self.remote_sha()) + + def test_local_commit_not_an_ancestor_is_skipped_and_logged(self): + exe = self.set_up_released() + other = self.git(self.proj, "rev-parse", "HEAD") # a commit the remote has never seen + lines = self.current("SOURCE").split("\n") + ["", "", ""] + lines[2] = other + self.write(os.path.join(os.path.realpath(os.path.join(self.lib, "current")), "SOURCE"), + "\n".join(lines[:3]) + "\n") + self.source("2.0.0") + before = self.releases() + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr) + self.assertEqual(self.current("VERSION").strip(), "1.0.0") + self.assertEqual(self.releases(), before) + self.assertIn("not an ancestor", self.log()) + self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice"))) + + def test_failing_tests_in_the_new_version_switch_nothing(self): + exe = self.set_up_released() + self.source("2.0.0", fail=True) + before = self.releases() + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr) + self.assertEqual(self.current("VERSION").strip(), "1.0.0") + self.assertEqual(self.releases(), before) + self.assertIn("fail", self.log()) + self.assertFalse(os.path.exists(os.path.join(self.state, "auto-update-notice"))) + + def test_lock_held_exits_quietly(self): + from sisi import store + exe = self.set_up_released() + self.source("2.0.0") + with mock.patch.object(store, "DATA", self.data): + with store.lock("auto-update") as held: + self.assertTrue(held) + r = self.auto(exe) + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", ""), r.stdout + r.stderr) + self.assertEqual(self.current("VERSION").strip(), "1.0.0") + + def test_the_notice_shows_once_at_the_next_session_start(self): + exe = self.set_up_released() + old = self.remote_sha() + self.source("2.0.0") + self.assertEqual(self.auto(exe).returncode, 0) + new = self.remote_sha() + exe = os.path.join(self.lib, "current", "bin", "sisi") + self.write(os.path.join(self.state, "auto-update-check"), str(time.time())) # not due: no detached job + want = "sisi: updated itself to %s (was %s); `sisi rollback` goes back." % (new[:7], old[:7]) + payload = json.dumps({"session_id": "s9", "cwd": self.proj}) + first = self.run_exe(exe, "tick", stdin=payload) + self.assertEqual(first.returncode, 0, first.stdout + first.stderr) + self.assertEqual(first.stdout.splitlines().count(want), 1, first.stdout) + second = self.run_exe(exe, "tick", stdin=payload) + self.assertNotIn(want, second.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_core.py b/tests/test_core.py index 06b9e31..983960d 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -4642,7 +4642,7 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 2530, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2627, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") self.assertLess(len(rulebook.splitlines()), 139) self.assertLessEqual(len(rulebook), 10711)