diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 7c545d4..f3b05fa 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -337,7 +337,8 @@ 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"}] - status = {"applied": "implemented", "retired": "reverted"}.get(old.get("status"), "observed") + # an old open lesson waits for a cycle, as before: it stays counted by `sisi cycle due` + status = {"applied": "implemented", "retired": "reverted", "open": "proposed"}.get(old.get("status"), "observed") kind = old.get("change_kind") target = str(old.get("target") or "") rec = { @@ -483,11 +484,44 @@ def cmd_update(args): return p.returncode +UPDATE_MARK = ".made-by-sisi-update" +DEFAULT_KEEP_UPDATE_BACKUPS = 5 + + +def backups_to_keep(): + """How many of the update step's own snapshots to keep (config backups.keep_update; at least 1).""" + try: + n = int((store.config().get("backups") or {}).get("keep_update", DEFAULT_KEEP_UPDATE_BACKUPS)) + except (TypeError, ValueError): + n = DEFAULT_KEEP_UPDATE_BACKUPS + return max(n, 1) + + +def prune_update_backups(current): + """Mark the snapshot just taken as made by the update step, then delete the oldest snapshots + carrying that mark beyond the configured number. A folder without the mark is never touched, + and the newest one is never deleted. Returns how many were deleted.""" + base = paths.data_file("backups") + try: + open(os.path.join(current, UPDATE_MARK), "w").close() + mine = sorted(n for n in os.listdir(base) if os.path.isfile(os.path.join(base, n, UPDATE_MARK))) + except OSError: + return 0 + doomed = mine[:-backups_to_keep()] + for n in doomed: + shutil.rmtree(os.path.join(base, n), ignore_errors=True) + return len(doomed) + + def post_update(): """After the product changed: back up personal data, migrate its format, keep replacements, rebuild, check.""" try: pdata.ensure() - print("backup: %s" % snapshot("update")) + bdir = snapshot("update") + print("backup: %s" % bdir) + pruned = prune_update_backups(bdir) + if pruned: + print("removed %d older update backup(s) (keeping %d)" % (pruned, backups_to_keep())) for n in run(): print(n) for r in overlay.scan_retests(): diff --git a/sisi/workers.py b/sisi/workers.py index 410778d..0d097d2 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -1789,6 +1789,9 @@ def _cmd_import(args): if not os.path.isfile(args[0]): print("sisi: no such ledger file: %s" % args[0], file=sys.stderr) return 1 + if not any(r.get("kind") in ("attempt", "run", "amend", "down", "up") for r in read_records(args[0])): + print("sisi: warning: %s contains no ledger rows (no line with a kind of attempt, run, amend, " + "down or up); is it the right file?" % args[0], file=sys.stderr) before, after, added = import_ledger(args[0]) print("imported %d rows from %s (before: %d, after: %d); the original file is unchanged" % (added, args[0], before, after)) diff --git a/tests/test_personal.py b/tests/test_personal.py index d570aba..ec9350a 100644 --- a/tests/test_personal.py +++ b/tests/test_personal.py @@ -386,6 +386,24 @@ class UpdateTests(PersonalCase): self.assertIn("backup:", r.stdout) self.assertIn("rulebook rebuilt", r.stdout) + def test_update_keeps_a_bounded_number_of_its_own_backups(self): + """R-3.2-4: the update step keeps at most N of its own snapshots, never one it did not + make, and never the newest.""" + pdata.ensure() + json.dump({"backups": {"keep_update": 2}}, open(os.path.join(self.data, "config.json"), "w")) + foreign = os.path.join(self.data, "backups", "20200101T000000-update") # someone else's, same look + os.makedirs(foreign) + for _ in range(4): + self.ok("update") + bk = os.path.join(self.data, "backups") + mine = sorted(d for d in os.listdir(bk) if os.path.exists(os.path.join(bk, d, ".made-by-sisi-update"))) + self.assertEqual(len(mine), 2, os.listdir(bk)) + self.assertTrue(os.path.isdir(foreign)) + json.dump({"backups": {"keep_update": 0}}, open(os.path.join(self.data, "config.json"), "w")) + self.ok("update") + mine = [d for d in os.listdir(bk) if os.path.exists(os.path.join(bk, d, ".made-by-sisi-update"))] + self.assertEqual(len(mine), 1) # never fewer than the newest one + def _seed_legacy_db(path, lessons, proj): """A pre-rebuild retro.db: the sqlite lesson store the migration reads.""" @@ -477,6 +495,18 @@ class MigrationTests(PersonalCase): self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before) self.assertEqual(self.ok("lessons", "--json").stdout.count('"id": "L-'), 2) + def test_a_due_cycle_stays_due_after_migration(self): + """R-3.1-2: five open lessons made a cycle due in the old store; migrated, they still do.""" + os.makedirs(os.path.join(self.state, "backups")) + _seed_legacy_db(os.path.join(self.state, "retro.db"), + [dict(aim="speed", moment="moment %d" % i, cause="cause %d" % i, change_kind="rule", + change="Change number %d to the way of working" % i, target=None) for i in range(5)], + self.proj) + self.ok("update", "--post") + out = self.ok("cycle", "due").stdout + self.assertIn("a learning cycle is due", out) + self.assertIn("5 proposed", out) + def test_old_layout_keeps_working_before_migration(self): self.legacy_state() self.ok("update", "--post") # lessons now live in learnings.jsonl; migration is the one path in diff --git a/tests/test_worker_routes.py b/tests/test_worker_routes.py index 6aee0a0..a9bb704 100644 --- a/tests/test_worker_routes.py +++ b/tests/test_worker_routes.py @@ -177,6 +177,20 @@ class StoreHistoryTests(RouteCase): self.assertNotIn("oracle.md", shown) +class ImportWarningTests(RouteCase): + def test_import_of_a_file_without_ledger_rows_warns(self): + """R-7.2-3: importing the wrong file is said out loud, not reported as a quiet success.""" + src = os.path.join(self.tmp, "not-a-ledger.jsonl") + open(src, "w").write('{"hello": "world"}\nnot json\n') + r = self.sisi("workers", "import", src, env=self.env()) + self.assertIn("contains no ledger rows", r.stderr) + good = os.path.join(self.tmp, "ledger.jsonl") + open(good, "w").write(json.dumps({"kind": "attempt", "id": "a1", "ts": 1760000000, "worker": "wk-x", + "type": "read", "difficulty": 1, "outcome": "accepted"}) + "\n") + ok = self.sisi("workers", "import", good, env=self.env()) + self.assertNotIn("no ledger rows", ok.stderr) + + class SessionStartTests(RouteCase): def tick(self, sid, model="mystery-9", source="startup"): return self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, "source": source,