Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(storage): stop deriving media references from message history (#1583)
Call White272a3e3dbcc0
diff --git a/scripts/migration_release_guard.py b/scripts/migration_release_guard.pyindex f3f35c8f4..b5b2f87be 100644--- a/scripts/migration_release_guard.py+++ b/scripts/migration_release_guard.py@@ -7,17 +7,21 @@ never back. So editing a released revision's parentage does not change what thosdatabases have already done -- it changes what they will do next, silently, with no errorat the moment of the edit and no error at the moment of the upgrade.-Six properties, one primitive: the graph as a released tag actually shipped it, read-straight out of git. Nothing here is a hand-maintained list of known-bad cases, and-nothing needs an old Python environment -- ``env.py`` reads ``target_metadata`` only-during autogenerate, so today's runtime can drive an older ``version_locations``.+Seven properties, one primitive: the graph as a released tag actually shipped it, read+straight out of git. Nothing here is an allowlist of known-bad cases that outlives its+reason, and nothing needs an old Python environment -- ``env.py`` reads+``target_metadata`` only during autogenerate, so today's runtime can drive an older+``version_locations``.fresh_install_tables() HEAD_TABLES is what a fresh install actually has, sothe property below derives from something measurednew_slot_collisions() a change introduces no new duplicated slot numberrechained_revisions() a released revision keeps its identity and every edgeAlembic orders the graph by- edited_released_bodies() a released revision still does what the release ran+ edited_released_bodies() a released revision still does what the release ran,+ or DECLARED_BODY_EDITS pins the body replacing it+ spent_body_edit no declaration outlives the edit it was written for,+ _declarations() so that list holds only unreleased editsunrepairable_releases() a database built by a released graph, carrying rows,still comes out ready when the upgrade users runupgrades it@@ -50,6 +54,7 @@ from __future__ import annotationsimport argparseimport ast+import hashlibimport jsonimport reimport sqlite3@@ -58,6 +63,7 @@ import sysimport tempfilefrom collections import defaultdictfrom collections.abc import Iterable+from dataclasses import dataclassfrom pathlib import PathREPO_ROOT = Path(__file__).resolve().parents[1]@@ -532,6 +538,82 @@ def released_bodies(sources: dict[str, str]) -> dict[str, tuple[str, str]]:}+def body_fingerprint(source: str) -> str:+ """The sha256 a declaration pins a replacement body by."""+ return hashlib.sha256(source.encode("utf-8")).hexdigest()+++@dataclass(frozen=True)+class DeclaredBodyEdit:+ """One released revision whose body was deliberately changed, and the body it became.++ ``body`` is what makes this a declaration rather than an exemption. It authorises one+ specific replacement, so a second edit to the same revision changes the fingerprint+ and is reported like any undeclared one -- the entry cannot decay into a standing+ permission for whatever that file says next.+ """++ revision: str+ body: str+ reason: str+++DECLARED_BODY_EDITS: tuple[DeclaredBodyEdit, ...] = (+ DeclaredBodyEdit(+ revision="20260725_0037",+ body="d56e9ae949018bb1d0adc6edc1609d2f39052eb1bf70688add968c7304f4525a",+ reason=(+ "The revision backfilled media_object_references by regex-scanning every agent "+ "message for media URLs. Only that scan is gone; the DDL and the precondition "+ "20260819_0056 relies on to prove its replay repaired anything are untouched. "+ "Removed because no forward revision can express the "+ "removal: 20260819_0056 replays this body, so a later revision runs after the "+ "scan it would have to prevent, and the rows the scan writes are byte-identical "+ "to the ones media_service.register() writes when a second session reuses a "+ "token, so nothing downstream can delete one without deleting the other. What "+ "the divergence costs is bounded by the read path rather than argued: the table "+ "only ever widens access, vibe/ui_server.py falls back to the media row's own "+ "session and scope when the reference set is empty, and the owner short-circuit "+ "returns before consulting it at all -- so a row the scan would have written is "+ "at worst a 404 for a non-owner holding partial project access, never a leak. "+ "The scan is also already inert wherever it can still run: a fresh install "+ "crosses this revision with media_objects and messages empty, and a database "+ "that already crossed it is stamped and never reruns it."+ ),+ ),+)+++def _declared_body_edits() -> dict[str, DeclaredBodyEdit]:+ return {declared.revision: declared for declared in DECLARED_BODY_EDITS}+++def spent_body_edit_declarations(baseline: str | None = None) -> list[str]:+ """Declarations that no longer describe an edit, which is how the list stays short.++ A declaration is spent the moment a release ships the body it pinned: the baseline+ moves to that release, shipped and current agree, and ``edited_released_bodies`` has+ nothing left to accept. Reporting that keeps ``DECLARED_BODY_EDITS`` holding only+ edits made since the last release, so it never becomes the standing allowlist the+ rest of this module refuses to keep -- and an entry written for an edit that was+ never made, or reverted before shipping, fails here rather than sitting ready to+ excuse a future one.+ """+ baseline = baseline or latest_released_tag()+ current = released_bodies(working_tree_sources())+ shipped = released_bodies(released_sources(baseline))+ problems = []+ for revision, declared in sorted(_declared_body_edits().items()):+ if revision in shipped and revision in current and shipped[revision][1] != current[revision][1]:+ continue+ problems.append(+ f"DECLARED_BODY_EDITS names {revision}, which is not an edit against {baseline}; "+ "a declaration is spent once the release ships the body it pinned and must be "+ "removed rather than left standing"+ )+ return problems++def edited_released_bodies(baseline: str | None = None) -> list[str]:"""Released revisions whose migration no longer does what the baseline ran.@@ -554,23 +636,37 @@ def edited_released_bodies(baseline: str | None = None) -> list[str]:Restating it would describe one defect as two. The pair is what must be exhaustive,not either half, and ``collect_problems`` runs both.- No exemption for edits judged harmless. Judging them is the convention this guard- exists to replace, and no exemption is needed: restoring the shipped file and adding a- new migration carrying the change is always available, and is the only form of the- change every database can actually apply.+ An edit passes only through ``DECLARED_BODY_EDITS``, which is a declaration and not an+ exemption: it names the revision, pins the sha256 of the body replacing it, and+ records why the divergence is bounded. Pinning is what stops the entry unguarding the+ revision, and ``spent_body_edit_declarations`` is what stops the list accumulating, so+ what a declaration buys is one reviewed edit rather than a standing permission.++ This docstring used to claim no exemption was needed, because restoring the file and+ carrying the change in a new revision is always available. That is true of a change a+ later revision can apply and false of the one shape that reached here first: removing+ work an earlier revision did, on databases that have already done it. A rule whose+ stated alternative does not exist gets suspended in the moment rather than amended, so+ the narrow declared form is the safer one to hold."""baseline = baseline or latest_released_tag()+ declared = _declared_body_edits()current = released_bodies(working_tree_sources())problems = []for revision, (shipped_name, source) in sorted(released_bodies(released_sources(baseline)).items()):if revision not in current or current[revision][1] == source:continue- name = current[revision][0]+ name, body = current[revision]+ permitted = declared.get(revision)+ if permitted is not None and permitted.body == body_fingerprint(body):+ continuewhere = shipped_name if name == shipped_name else f"{shipped_name}, now {name}"- problems.append(- f"{revision} ({where}) is no longer what {baseline} shipped; a released "- "migration's body is fixed once a database has run it"+ detail = (+ f"DECLARED_BODY_EDITS pins {permitted.body} for it, not {body_fingerprint(body)}"+ if permitted is not None+ else "a released migration's body is fixed once a database has run it")+ problems.append(f"{revision} ({where}) is no longer what {baseline} shipped; {detail}")return problems@@ -1433,6 +1529,7 @@ def collect_problems(problems.extend(rechained_revisions(baseline))problems.extend(edited_released_bodies(baseline))+ problems.extend(spent_body_edit_declarations(baseline))if include_upgrade:failures, refused = unrepairable_releases()diff --git a/storage/alembic/versions/20260725_0037_media_object_references.py b/storage/alembic/versions/20260725_0037_media_object_references.pyindex b9e7d1534..095d67942 100644--- a/storage/alembic/versions/20260725_0037_media_object_references.py+++ b/storage/alembic/versions/20260725_0037_media_object_references.py@@ -1,4 +1,4 @@-"""preserve trusted media references across legacy sessions+"""record which sessions a media object is trusted byRevision ID: 20260725_0037Revises: 20260725_0036@@ -7,8 +7,6 @@ Create Date: 2026-07-25from __future__ import annotations-import re-import sqlalchemy as safrom alembic import op@@ -17,8 +15,6 @@ down_revision = "20260725_0036"branch_labels = Nonedepends_on = None-_MEDIA_TOKEN_RE = re.compile(r"/(?:api|__show)/media/([A-Za-z0-9_-]+)")-def _tables(bind) -> set[str]:return {@@ -63,55 +59,6 @@ def upgrade() -> None:if_not_exists=True,)- bind.exec_driver_sql(- """- insert or ignore into media_object_references (token, session_id, created_at)- select token, session_id, created_at- from media_objects- where session_id is not null- """- )- if "messages" not in tables:- return-- known_tokens = {- str(row[0])- for row in bind.exec_driver_sql("select token from media_objects")- }- references: dict[tuple[str, str], str] = {}- rows = bind.exec_driver_sql(- """- select session_id, content_text, content_json, created_at- from messages- where author = 'agent'- and session_id is not null- and (content_text like '%/media/%' or content_json like '%/media/%')- """- )- for session_id, content_text, content_json, created_at in rows:- haystack = f"{content_text or ''}\n{content_json or ''}"- for token in _MEDIA_TOKEN_RE.findall(haystack):- if token in known_tokens:- references[(token, str(session_id))] = str(created_at)- if references:- bind.execute(- sa.text(- """- insert or ignore into media_object_references- (token, session_id, created_at)- values (:token, :session_id, :created_at)- """- ),- [- {- "token": token,- "session_id": session_id,- "created_at": created_at,- }- for (token, session_id), created_at in references.items()- ],- )-def downgrade() -> None:bind = op.get_bind()diff --git a/tests/test_migration_release_guard.py b/tests/test_migration_release_guard.pyindex a490fb8f5..1ddd098ce 100644--- a/tests/test_migration_release_guard.py+++ b/tests/test_migration_release_guard.py@@ -425,10 +425,71 @@ def test_support_files_are_not_held_to_the_release(monkeypatch):assert guard.rechained_revisions("v0.0.0") == []+def _declare(monkeypatch, *entries: guard.DeclaredBodyEdit) -> None:+ monkeypatch.setattr(guard, "DECLARED_BODY_EDITS", entries)+++DECLARED_EDIT = SHIPPED_GRAPH["20260102_0002_linear.py"] + "\n# a declared edit\n"+++ ("pinned", "reported"),+ [+ (guard.body_fingerprint(DECLARED_EDIT), False),+ (guard.body_fingerprint(DECLARED_EDIT + "# and one more\n"), True),+ ],+ ids=["pins-the-body-present", "pins-a-different-body"],+)+def test_a_declaration_accepts_exactly_the_body_it_pins(monkeypatch, pinned, reported):+ """What separates a declaration from an exemption, stated from both sides.++ An entry naming only the revision would hand that file a standing permission: the+ edit it was written for and every later one look alike to a check that stops at the+ name. Pinning the replacement means the second edit arrives as an undeclared edit+ again, which is the whole difference between recording a decision and suspending the+ property.+ """+ current = dict(SHIPPED_GRAPH) | {"20260102_0002_linear.py": DECLARED_EDIT}+ _graphs(monkeypatch, SHIPPED_GRAPH, current)+ _declare(monkeypatch, guard.DeclaredBodyEdit(revision="20260102_0002", body=pinned, reason="recorded"))++ assert bool(guard.edited_released_bodies("v0.0.0")) is reported+++def test_a_declaration_that_describes_no_edit_is_reported_as_spent(monkeypatch):+ """The property that keeps the list from becoming the allowlist this module refuses.++ A declaration is spent the moment a release ships the body it pinned, and a spent one+ is indistinguishable from a live one by inspection. Failing on it is what bounds the+ list to edits made since the last release, and it also catches the entry written for+ an edit that was reverted before shipping -- which would otherwise sit ready to+ excuse an edit nobody reviewed.+ """+ _graphs(monkeypatch, SHIPPED_GRAPH, dict(SHIPPED_GRAPH))+ _declare(monkeypatch, guard.DeclaredBodyEdit(revision="20260102_0002", body="0" * 64, reason="recorded"))++ assert len(guard.spent_body_edit_declarations("v0.0.0")) == 1+ assert guard.edited_released_bodies("v0.0.0") == []+++def test_every_declaration_pins_a_fingerprint_and_records_a_reason():+ """A mistyped fingerprint would otherwise surface as an unexplained mismatch."""+ for declared in guard.DECLARED_BODY_EDITS:+ assert declared.revision.strip()+ assert declared.reason.strip()+ assert len(declared.body) == 64 and set(declared.body) <= set("0123456789abcdef")++@requires_release_history-def test_no_released_migration_body_has_been_edited():- """The claim measured against the graph that actually ships, not a synthetic one."""+def test_the_real_graph_has_no_undeclared_edit_and_no_spent_declaration():+ """The pair measured against the graph that actually ships, not a synthetic one.++ Both halves, because they fail in opposite directions: an undeclared edit is a+ divergence nobody wrote down, and a spent declaration is a written permission that+ outlived the edit it was written for.+ """assert guard.edited_released_bodies() == []+ assert guard.spent_body_edit_declarations() == []def test_an_unreadable_graph_has_its_head_refused_rather_than_guessed():diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex f89743648..2bd2f35db 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -6376,7 +6376,21 @@ def _write_discovered_chats(path: Path) -> None:)-def test_media_reference_migration_backfills_legacy_cross_session_tokens(tmp_path: Path) -> None:+def test_media_reference_migration_derives_no_rows_from_existing_data(tmp_path: Path) -> None:+ """The revision creates the table. Nothing in the graph reads history to fill it.++ Seeded with one row of every shape the removed backfill consumed -- a media object+ carrying its own minting session, and an agent message in a *second* session linking+ that token -- and asserting the table comes out empty, rather than asserting two+ named rows are absent. A shape the scan would have matched cannot pass by going+ unlisted.++ Nothing replaced it, because the read path already covers what it wrote:+ media_service.register() records the reference when a token is minted or reused, and+ vibe/ui_server.py falls back to the media row's own session and scope when the+ reference set is empty, so a legacy attachment stays readable by the session that+ minted it either way.+ """db_path = tmp_path / "vibe.sqlite"run_migrations(db_path, revision="20260725_0035")now = "2026-07-25T00:00:00Z"@@ -6442,10 +6456,7 @@ def test_media_reference_migration_backfills_legacy_cross_session_tokens(tmp_pat)version = conn.execute("select version_num from alembic_version").fetchone()- assert references == {- ("legacy-shared-token", "ses_media_original"),- ("legacy-shared-token", "ses_media_reuse"),- }+ assert references == set()assert version == (HEAD_REVISION,)