"""Which extensions a session runs and what that composition exposes. Guards the component refactor: the closed plugin type, the composition and selection modules and the python kernel lifecycle are all going to move, while a user's choices must keep meaning the same. Every test drives the daemon's HTTP API and the model's python namespace, so none of them names an internal module, plugin kind or python file; the refactor may change those freely and only a change of behavior can fail them. What is pinned: per-session and global selection and its persistence; requirement closure and refusals; compaction exclusivity; a busy session's refusals; desired against loaded revisions and a failed apply keeping the choice; whole-bundle activation (a bundle that cannot prepare leaves nothing behind, unrelated extensions keep working, open tolerates it, reload reports it); a collision dropping a whole bundle; commands, context blocks and hooks following selection; the capability-change notice and the pinned prompt; and quarantine listing and refusal. """ import json import re import sqlite3 import threading import unittest import urllib.error from harness import Albedo, Provider, exclusive, operation_id, python, text # An extension that cannot prepare, with nothing installed to break: the # memory snapshot of a workspace refuses a memory.md that is not UTF-8. BAD_MEMORY = b"\xff\xfe not utf-8" BOUND = """ import json def _bound(name): try: eval(name) return True except NameError: return False print(json.dumps({name: _bound(name) for name in %r})) """ def skill(name, description): return f"---\nname: {name}\ndescription: {description}\n---\nbody of {name}\n" class CompositionCase(unittest.TestCase): """One session on the shared fixture; `cell` runs python as the model.""" def setUp(self): self.code = None self.provider = Provider(self.reply) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.sid = self.app.session() def reply(self, request): items = request["input"] if self.code is not None and items[-1].get("role") == "user": code, self.code = self.code, None return python(code) return text("done") # reading and changing def get(self, path): with self.app.api(path) as response: return json.load(response) def snapshot(self, session=None): return self.get(f"/sessions/{session or self.sid}?tail=0") def effective(self, session=None): return self.snapshot(session)["selection"]["effective"]["extensions"] def overrides(self, session=None): return self.snapshot(session)["selection"]["overrides"]["extensions"] def composition(self, session=None): return self.snapshot(session)["composition"] def commands(self, session=None): catalog = self.get(f"/sessions/{session or self.sid}/catalog") return {row["slash_name"] for row in catalog["loaded"]["commands"]} def attempt(self, path, body, *, method="PATCH", headers=None): """The status and decoded body of a write, refused or not.""" try: with self.app.api(path, body, method=method, headers=headers) as response: return response.status, json.load(response) except urllib.error.HTTPError as refusal: return refusal.code, json.load(refusal) def try_select(self, extensions, session=None): route = f"/sessions/{session or self.sid}?view=configuration" with self.app.api(route) as response: json.load(response) etag = response.headers["ETag"] return self.attempt( route, {"selection": {"extensions": extensions}}, headers={"If-Match": etag}, ) def select(self, extensions, session=None): status, body = self.try_select(extensions, session) self.assertEqual(status, 200, body) def reload(self, session=None): _, body = self.attempt( f"/sessions/{session or self.sid}/reload", {"target": "session"}, method="POST", ) return body["session"] def apply(self, extensions, session=None): self.select(extensions, session) applied = self.reload(session) self.assertEqual(applied["state"], "applied", applied) def set_defaults(self, defaults): with self.app.api("/settings?group=extensions") as response: response.read() etag = response.headers["ETag"] status, body = self.attempt( "/settings?group=extensions", {"defaults": defaults}, headers={"If-Match": etag}, ) self.assertEqual(status, 200, body) # turns def turn(self, prompt="plain turn", session=None): sid = session or self.sid before = len(self.provider.requests) self.app.prompt(sid, prompt).close() self.app.idle(sid) return [entry["request"] for entry in self.provider.requests[before:]] def cell(self, code, session=None): """What `code` printed when the model ran it as a cell.""" self.code = code requests = self.turn("run a cell", session) self.assertEqual(len(requests), 2, "the cell did not run") raw = next( item["output"] for item in reversed(requests[-1]["input"]) if item.get("type") == "function_call_output" ) return raw.partition("\n")[2] def bound(self, *names, session=None): return json.loads(self.cell(BOUND % (names,), session)) def notes(self, request): return [ item["content"] for item in request["input"] if item.get("role") == "user" and str(item.get("content", "")).startswith( '' ) ] def warnings(self, session=None): page = self.app.stream_page(session or self.sid, tail=100) return [ line["text"] for line in page["snapshot"]["activity"]["lines"] if line["kind"] == "note" and line["text"].startswith("Warning:") ] # the memory fixture: the one built-in whose bundle a file can break def memory_file(self, content): slug = re.sub("[^A-Za-z0-9]", "-", str(self.app.workspace)) root = self.app.home / "memories" / slug root.mkdir(parents=True, exist_ok=True) path = root / "memory.md" path.write_bytes(content if isinstance(content, bytes) else content.encode()) return path class SelectionTests(CompositionCase): # exclusive: saves global defaults and restarts the daemon @exclusive def test_a_session_override_beats_the_global_default_and_both_survive_a_restart( self, ): self.set_defaults({"schedule": False}) follower, overridden, other = (self.app.session() for _ in range(3)) self.select({"schedule": True}, overridden) self.assertEqual( [self.effective(s)["schedule"] for s in (follower, overridden, other)], [False, True, False], ) self.assertEqual(self.overrides(overridden), {"schedule": True}) self.assertEqual(self.overrides(follower), {}) for session in (follower, overridden): self.turn(session=session) self.assertNotIn("/schedule", self.commands(follower)) self.assertIn("/schedule", self.commands(overridden)) self.app.restart() self.assertEqual( [self.effective(s)["schedule"] for s in (follower, overridden, other)], [False, True, False], ) self.assertEqual(self.overrides(overridden), {"schedule": True}) # Sessions without an override follow the default when it moves; the # override stays where it was put until it is changed. self.set_defaults({"schedule": True}) self.select({"schedule": False}, other) self.assertEqual( [self.effective(s)["schedule"] for s in (follower, overridden, other)], [True, True, False], ) def test_a_selection_change_in_one_session_leaves_the_others_alone(self): sibling = self.app.session() self.select({"schedule": False}) self.assertFalse(self.effective()["schedule"]) self.assertTrue(self.effective(sibling)["schedule"]) self.assertEqual(self.overrides(sibling), {}) def test_disabling_a_requirement_is_refused_unless_its_dependents_go_with_it(self): self.turn() for extensions in ({"run": False}, {"python": False}, {"commands": False}): status, body = self.try_select(extensions) self.assertEqual((status, body["code"]), (400, "selection_invalid")) self.assertEqual(self.overrides(), {}) # files needs run, so they leave together. self.apply({"run": False, "files": False}) self.assertEqual( self.bound("run", "files", "work"), {"run": False, "files": False, "work": True}, ) status, body = self.try_select({"files": True}) self.assertEqual((status, body["code"]), (400, "selection_invalid")) self.assertFalse(self.effective()["files"]) self.apply({"run": True, "files": True}) self.assertEqual(self.bound("run", "files"), {"run": True, "files": True}) # exclusive: saves global defaults @exclusive def test_a_global_default_cannot_disable_what_an_enabled_extension_requires(self): route = "/settings?group=extensions" with self.app.api(route) as response: before, etag = json.load(response), response.headers["ETag"] status, body = self.attempt( route, {"defaults": {"models": False}}, headers={"If-Match": etag} ) self.assertEqual((status, body["code"]), (400, "selection_invalid")) self.assertIn("requires", body["detail"]) with self.app.api(route) as response: self.assertEqual(json.load(response), before) self.assertEqual(response.headers["ETag"], etag) self.assertTrue(self.effective()["models"]) def test_naming_an_extension_that_is_not_installed_is_refused(self): status, body = self.try_select({"no-such-extension": True}) self.assertEqual((status, body["code"]), (409, "candidate_unavailable")) self.assertEqual(self.overrides(), {}) class CompactionTests(CompositionCase): def strategies(self): effective = self.effective() return { name: effective[name] for name in ("rolling", "coding-lcm", "snapcompact", "persistent-agent") } def test_enabling_a_strategy_replaces_the_active_one_in_the_same_save(self): self.assertEqual( self.strategies(), { "rolling": True, "coding-lcm": False, "snapcompact": False, "persistent-agent": False, }, ) self.select({"coding-lcm": True}) self.assertEqual( self.strategies(), { "rolling": False, "coding-lcm": True, "snapcompact": False, "persistent-agent": False, }, ) self.select({"rolling": True}) self.assertTrue(self.strategies()["rolling"]) self.assertFalse(self.strategies()["coding-lcm"]) def test_two_strategies_in_one_save_are_refused_and_change_nothing(self): status, body = self.try_select({"coding-lcm": True, "snapcompact": True}) self.assertEqual((status, body["code"]), (400, "selection_conflict")) self.assertTrue(self.strategies()["rolling"]) self.assertEqual(self.overrides(), {}) def test_disabling_the_only_strategy_cannot_be_applied_and_the_old_one_keeps_working( self, ): self.turn("first") self.turn("second") loaded = self.composition()["loaded_revision"] self.select({"rolling": False}) refused = self.reload() self.assertEqual(refused["state"], "failed", refused) self.assertIn("compaction strategy", refused["failure"]["detail"]) self.assertEqual(refused["loaded_revision"], loaded) # The choice stays saved for retry, and the session still compacts. self.assertFalse(self.effective()["rolling"]) self.assertTrue(self.composition()["needs_reload"]) status, report = self.attempt( f"/sessions/{self.sid}/compaction", {}, method="POST" ) self.assertEqual(status, 200, report) self.assertEqual( (report["effective_strategy"], report["state"]), ("rolling", "compacted") ) # Replacing it applies. self.apply({"coding-lcm": True}) self.assertFalse(self.composition()["needs_reload"]) class BusySessionTests(CompositionCase): def test_a_busy_session_refuses_reload_and_keeps_its_loaded_composition(self): self.turn() loaded = self.composition()["loaded_revision"] entered, release = threading.Event(), threading.Event() self.addCleanup(release.set) def held(_request): entered.set() release.wait(30) return text("done") self.select({"schedule": False}) self.provider.script = held self.app.prompt(self.sid, "hold this turn").close() self.assertTrue(entered.wait(10)) status, body = self.try_select({"schedule": True}) self.assertEqual((status, body["code"]), (409, "session_busy")) refused = self.reload() self.assertEqual(refused["state"], "failed", refused) self.assertIn("idle", refused["failure"]["detail"]) self.assertEqual(refused["loaded_revision"], loaded) release.set() self.app.idle(self.sid) # The saved choice waited for the session to be idle. self.assertFalse(self.effective()["schedule"]) self.assertIn("/schedule", self.commands()) self.assertEqual(self.reload()["state"], "applied") self.assertNotIn("/schedule", self.commands()) class RevisionTests(CompositionCase): def test_a_saved_choice_is_desired_until_a_reload_loads_it(self): self.turn() before = self.composition() self.assertFalse(before["needs_reload"]) self.assertEqual(before["desired_revision"], before["loaded_revision"]) self.select({"schedule": False}) saved = self.composition() self.assertTrue(saved["needs_reload"]) self.assertNotEqual(saved["desired_revision"], saved["loaded_revision"]) self.assertEqual(saved["loaded_revision"], before["loaded_revision"]) self.assertIn("/schedule", self.commands()) self.assertEqual(self.reload()["state"], "applied") loaded = self.composition() self.assertFalse(loaded["needs_reload"]) self.assertEqual(loaded["desired_revision"], loaded["loaded_revision"]) self.assertNotEqual(loaded["loaded_revision"], before["loaded_revision"]) # Selecting what was loaded before returns to the first revision. self.apply({"schedule": True}) self.assertEqual( self.composition()["loaded_revision"], before["loaded_revision"] ) def test_a_failed_apply_keeps_the_desired_choice_and_the_loaded_composition(self): self.turn() loaded = self.composition()["loaded_revision"] self.memory_file(BAD_MEMORY) self.select({"schedule": False}) failed = self.reload() self.assertEqual(failed["state"], "failed", failed) self.assertIn("memory", failed["failure"]["detail"]) self.assertEqual(failed["loaded_revision"], loaded) self.assertEqual(self.composition()["loaded_revision"], loaded) self.assertTrue(self.composition()["needs_reload"]) self.assertFalse(self.effective()["schedule"]) self.assertIn("/schedule", self.commands()) self.assertTrue(self.bound("memory")["memory"]) # Repaired, the same saved choice applies. self.memory_file("fine again") self.assertEqual(self.reload()["state"], "applied") self.assertFalse(self.composition()["needs_reload"]) self.assertNotIn("/schedule", self.commands()) class BundleTests(CompositionCase): def test_reading_the_catalog_prepares_nothing(self): self.memory_file(BAD_MEMORY) self.get(f"/sessions/{self.sid}/catalog") self.get(f"/sessions/{self.sid}/catalog?kind=commands") self.get("/server?include=extensions") before = self.snapshot() self.assertIsNone(before["composition"]["loaded_revision"]) self.assertEqual(before["kernel"]["state"], "none") # A prepared composition would have found the broken bundle by now. self.assertEqual(before["composition"]["quarantine"], []) self.assertEqual(self.provider.requests, []) self.assertEqual(self.snapshot()["kernel"]["state"], "none") def test_a_bundle_that_cannot_prepare_leaves_nothing_behind_and_others_run(self): self.memory_file(BAD_MEMORY) names = self.bound("memory", "files", "work", "run") self.assertEqual( names, {"memory": False, "files": True, "work": True, "run": True} ) (inactive,) = self.composition()["quarantine"] self.assertEqual(inactive["id"], "memory") self.assertIn("not UTF-8", inactive["reason"]["detail"]) self.assertTrue( any("extension memory is inactive" in w for w in self.warnings()), self.warnings(), ) # The other extensions did their work: a command and a file write. self.assertIn("/work", self.commands()) self.cell("files.write('made.txt', 'ok')") self.assertEqual((self.app.workspace / "made.txt").read_text(), "ok") def test_an_explicit_reload_reports_the_bundle_that_open_tolerated(self): self.memory_file(BAD_MEMORY) self.turn() failed = self.reload() self.assertEqual(failed["state"], "failed", failed) self.assertIn("memory", failed["failure"]["detail"]) self.assertIn("not UTF-8", failed["failure"]["detail"]) self.memory_file("RECOVERED_MARK") self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.composition()["quarantine"], []) self.assertTrue(self.bound("memory")["memory"]) self.assertIn("RECOVERED_MARK", self.cell("print(memory.read())")) def test_a_skill_that_collides_with_a_command_drops_the_whole_skills_bundle(self): for name in ("demo", "work"): path = self.app.workspace / ".albedo/skills" / name / "SKILL.md" path.parent.mkdir(parents=True) path.write_text(skill(name, f"the {name} skill")) self.turn() # The built-in /work keeps its name; the skills extension, which # could not take its own /work, contributes none of its commands. commands = self.commands() self.assertIn("/work", commands) self.assertNotIn("/demo", commands) (inactive,) = self.composition()["quarantine"] self.assertEqual(inactive["id"], "skills") self.assertIn("duplicates", inactive["reason"]["detail"]) self.assertTrue( any("extension skills is inactive" in w for w in self.warnings()) ) self.assertNotIn("the demo skill", json.dumps(self.provider.requests[-1])) failed = self.reload() self.assertEqual(failed["state"], "failed", failed) self.assertIn("skills", failed["failure"]["detail"]) # Without the collision the same bundle comes back whole. (self.app.workspace / ".albedo/skills/work/SKILL.md").unlink() self.assertEqual(self.reload()["state"], "applied") self.assertIn("/demo", self.commands()) self.assertEqual(self.composition()["quarantine"], []) class FollowSelectionTests(CompositionCase): def test_commands_follow_selection_in_the_catalog_and_the_kernel(self): self.turn() listed = self.cell( "print(json.dumps([c['name'] for c in await commands.catalog()]))" ) self.assertIn("/schedule", json.loads(listed)) self.assertIn("/schedule", self.commands()) self.apply({"schedule": False}) self.assertNotIn("/schedule", self.commands()) kinds = self.get(f"/sessions/{self.sid}/catalog?kind=commands") self.assertNotIn( "/schedule", {row["slash_name"] for row in kinds["loaded"]["commands"]} | {row["slash_name"] for row in kinds.get("native_commands", [])}, ) listed = self.cell( "print(json.dumps([c['name'] for c in await commands.catalog()]))" ) self.assertNotIn("/schedule", json.loads(listed)) refusal = self.cell( "try:\n await commands.invoke('/schedule', '')\n" "except LookupError as error:\n print('refused', error)" ) self.assertIn("refused unknown command '/schedule'", refusal) self.apply({"schedule": True}) self.assertIn("/schedule", self.commands()) self.assertNotIn( "refused", self.cell("await commands.invoke('/schedule', '')\nprint('ran')") ) def test_a_skill_command_and_its_activation_follow_the_skills_extension(self): path = self.app.workspace / ".albedo/skills/demo/SKILL.md" path.parent.mkdir(parents=True) path.write_text(skill("demo", "the demo skill")) self.turn() self.assertIn("/demo", self.commands()) self.assertIn("the demo skill", json.dumps(self.provider.requests[-1])) self.apply({"skills": False}) self.assertNotIn("/demo", self.commands()) status, turns = self.activation() self.assertGreaterEqual(status, 400) self.assertEqual(turns, 0, "a disabled extension's command ran") self.apply({"skills": True}) self.assertIn("/demo", self.commands()) self.assertEqual(self.activation(), (202, 1)) def activation(self): """The status of activating /demo as a user, and the turns it started.""" catalog = self.get(f"/sessions/{self.sid}/catalog?kind=skills")["discovery"] rows = [ row for row in catalog["candidates"] if row["kind"] == "skill" and row["preference_key"] == "demo" ] self.assertEqual(len(rows), 1) before = len(self.provider.requests) status, _ = self.attempt( f"/sessions/{self.sid}/inputs/{operation_id()}", { "kind": "skill", "candidate_id": rows[0]["id"], "catalog_revision": catalog["revision"], "arguments": "", }, method="PUT", ) self.app.idle(self.sid) return status, len(self.provider.requests) - before def test_context_blocks_follow_selection_and_the_prompt_stays_pinned(self): self.memory_file("ALPHA_MEMORY_MARK") # A cell first: the kernel is open, as in a working session. self.cell("print('open')") first = self.provider.requests[0]["request"] self.assertIn("ALPHA_MEMORY_MARK", json.dumps(first["input"])) self.assertEqual(self.notes(self.provider.requests[-1]["request"]), []) self.apply({"memory": False}) (second,) = self.turn("after disabling") (removed,) = self.notes(second) self.assertIn("Context removed: memory", removed) self.assertEqual(second["instructions"], first["instructions"]) self.apply({"memory": True}) (third,) = self.turn("after enabling") added = self.notes(third) self.assertEqual(len(added), 2) self.assertIn('', added[-1]) self.assertIn("ALPHA_MEMORY_MARK", added[-1]) self.assertEqual(third["instructions"], first["instructions"]) def test_a_session_opened_without_an_extension_never_sees_its_context(self): self.memory_file("ALPHA_MEMORY_MARK") self.select({"memory": False}) (request,) = self.turn() self.assertNotIn("ALPHA_MEMORY_MARK", json.dumps(request)) self.assertFalse(self.bound("memory")["memory"]) class HookSelectionTests(CompositionCase): # exclusive: saves global defaults and hooks.json @exclusive def test_a_disabled_extensions_hook_is_no_longer_asked(self): self.set_defaults({"hooks": True}) script = self.app.workspace / "gate.sh" script.write_text("grep -q forbidden && exit 2; exit 0") gate = {"type": "command", "command": f"sh {script}", "timeout": 5} (self.app.home / "hooks.json").write_text( json.dumps( {"hooks": {"PreToolUse": [{"matcher": "^python$", "hooks": [gate]}]}} ) ) session = self.app.session() def attempt(name): self.cell(f"files.write('{name}', 'forbidden')", session) return (self.app.workspace / name).exists() self.assertFalse(attempt("while-enabled")) self.apply({"hooks": False}, session) self.assertTrue(attempt("while-disabled")) self.apply({"hooks": True}, session) self.assertFalse(attempt("enabled-again")) class QuarantineTests(CompositionCase): """lcm-memory cannot install over a table of the wrong shape, which takes the extensions that require it along; nothing else is affected.""" DEPENDENTS = ("coding-lcm", "persistent-agent") def setUp(self): self.provider = Provider(self.reply) self.addCleanup(self.provider.close) self.code = None def prepare(app): app.home.mkdir(parents=True, exist_ok=True) with sqlite3.connect(app.home / "albedo.sqlite") as db: db.execute("CREATE TABLE lcm_compaction_node(id INTEGER)") self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.sid = self.app.session() def inventory(self): rows = self.get("/server?include=extensions")["extension_inventory"] return {row["id"]: row for row in rows} # exclusive: boots on a prepared database @exclusive def test_a_broken_extension_and_its_dependents_are_listed_with_the_reason(self): inventory = self.inventory() broken = inventory["lcm-memory"] self.assertTrue(broken["quarantined"]) self.assertTrue(broken["diagnostic"]) for name in self.DEPENDENTS: self.assertTrue(inventory[name]["quarantined"], name) self.assertEqual(inventory[name]["diagnostic"], broken["diagnostic"]) self.assertFalse(inventory[name]["enabled"]) self.assertFalse(inventory["rolling"]["quarantined"]) listed = {row["id"]: row for row in self.composition()["quarantine"]} self.assertEqual(set(listed), {"lcm-memory", *self.DEPENDENTS}) self.assertEqual(listed["coding-lcm"]["reason"]["detail"], broken["diagnostic"]) row = next( row for row in self.get(f"/sessions/{self.sid}/catalog")["discovery"][ "candidates" ] if row["id"] == "coding-lcm" ) self.assertTrue(row["quarantined"]) self.assertEqual(row["diagnostic"]["detail"], broken["diagnostic"]) # exclusive: boots on a prepared database @exclusive def test_enabling_a_quarantined_extension_is_refused_and_saves_nothing(self): for name in ("lcm-memory", *self.DEPENDENTS): status, body = self.try_select({name: True}) self.assertEqual((status, body["code"]), (409, "candidate_unavailable")) self.assertFalse(self.effective()[name]) self.assertEqual(self.overrides(), {}) route = "/settings?group=extensions" with self.app.api(route) as response: response.read() etag = response.headers["ETag"] status, body = self.attempt( route, {"defaults": {"coding-lcm": True}}, headers={"If-Match": etag} ) self.assertEqual((status, body["code"]), (400, "selection_invalid")) with self.app.api(route) as response: self.assertNotIn("coding-lcm", json.load(response)["defaults"]) # exclusive: boots on a prepared database @exclusive def test_unrelated_extensions_keep_working_beside_a_quarantined_one(self): self.assertEqual(self.bound("files", "work"), {"files": True, "work": True}) self.turn("second") status, report = self.attempt( f"/sessions/{self.sid}/compaction", {}, method="POST" ) self.assertEqual(status, 200, report) self.assertEqual(report["effective_strategy"], "rolling") self.assertEqual(self.reload()["state"], "applied") if __name__ == "__main__": unittest.main()