"""``list_mdm_cleanup_queue`` must tell a refuted claim from an untouched one. The sync CLEARS ``cleanup_confirmed_via`` when the vendor's roster refutes a human's "I removed it" — that is what makes the fact outrank the claim. The consequence for every read surface is that ``confirmed_by_admin`` alone collapses two different situations into one: nobody has actioned this, and somebody believes they did and was wrong. The second is the one worth reading. Two surfaces already learned this the hard way (the ledger table and the detail drawer, review rounds 5 and 6). This one is the third, and it is the surface an AI client answers 「谁还没处理」 from. """ from __future__ import annotations import uuid from datetime import UTC, datetime, timedelta import pytest from sqlalchemy.ext.asyncio import AsyncSession from app.domains.asset.models import ( MDM_MATCH_MATCHED, MDM_STATE_PENDING_CLEANUP, MdmManagedDevice, ) from app.integrations.models import Integration from app.mcp import context as _mcp_ctx from app.mcp import tools as _tools pytestmark = pytest.mark.asyncio @pytest.fixture() def _patch_factory(db_engine, monkeypatch): from sqlalchemy.ext.asyncio import AsyncSession as _AS from sqlalchemy.ext.asyncio import async_sessionmaker from app.core import database as _db monkeypatch.setattr( _db, "async_session_factory", async_sessionmaker(db_engine, class_=_AS, expire_on_commit=False), ) async def _device( db: AsyncSession, *, serial: str, confirmed_at: datetime | None, confirmed_via: str | None, contradicted_at: datetime | None, ) -> MdmManagedDevice: integ = Integration( id=uuid.uuid4(), kind="mdm", provider="jamf", name=f"jamf-{serial}", slug=f"jamf-{uuid.uuid4().hex[:6]}", enabled=True, is_primary=False, capabilities=["devices"], ) db.add(integ) await db.flush() now = datetime.now(UTC) dev = MdmManagedDevice( id=uuid.uuid4(), integration_id=str(integ.id), provider="jamf", device_type="computer", external_id=f"ext-{serial}", serial_number=serial, serial_key=serial.lower(), device_name=f"MBP {serial}", match_category=MDM_MATCH_MATCHED, enrollment_state=MDM_STATE_PENDING_CLEANUP, cleanup_reason="sold", cleanup_requested_at=now - timedelta(days=30), cleanup_confirmed_at=confirmed_at, cleanup_confirmed_via=confirmed_via, cleanup_contradicted_at=contradicted_at, first_seen_at=now, last_seen_at=now, managed=True, ) db.add(dev) await db.commit() return dev async def test_refuted_claim_is_distinguishable_from_never_actioned( admin_user, db_session, _patch_factory, ): admin, _ = admin_user now = datetime.now(UTC) await _device( db_session, serial="NEVER1", confirmed_at=None, confirmed_via=None, contradicted_at=None, ) await _device( db_session, serial="REFUTED1", confirmed_at=None, confirmed_via=None, contradicted_at=now - timedelta(days=2), ) await _device( db_session, serial="CLAIMED1", confirmed_at=now - timedelta(hours=1), confirmed_via="admin", contradicted_at=None, ) token = _mcp_ctx.mcp_user_id.set(admin.id) try: res = await _tools.list_mdm_cleanup_queue() finally: _mcp_ctx.mcp_user_id.reset(token) by_serial = {r["serial_number"]: r for r in res["items"]} never, refuted, claimed = ( by_serial["NEVER1"], by_serial["REFUTED1"], by_serial["CLAIMED1"], ) # The claim half. assert claimed["confirmed_by_admin"] is True assert never["confirmed_by_admin"] is False assert refuted["confirmed_by_admin"] is False # …which is exactly why the second half has to be there: without it # these two rows are byte-identical, and the client answering # 「谁还没处理」 reports a wrong belief as an absent one. assert never["contradicted_at"] is None assert refuted["contradicted_at"] is not None assert never != refuted async def test_a_fresh_claim_after_a_refutation_reads_as_claimed( admin_user, db_session, _patch_factory, ): """The second attempt is not a permanent black mark. ``cleanup_contradicted_at`` is history and stays until the cleanup closes; a NEW confirmation on the replacement todo is present tense. The two desktop surfaces order it that way, and a client reading this tool has to be able to reach the same conclusion — otherwise the admin who ticked the replacement card is told, by the assistant, that their removal did not take. """ admin, _ = admin_user now = datetime.now(UTC) await _device( db_session, serial="RETRY1", confirmed_at=now - timedelta(minutes=5), confirmed_via="admin", contradicted_at=now - timedelta(days=9), ) token = _mcp_ctx.mcp_user_id.set(admin.id) try: res = await _tools.list_mdm_cleanup_queue() finally: _mcp_ctx.mcp_user_id.reset(token) row = next(r for r in res["items"] if r["serial_number"] == "RETRY1") assert row["confirmed_by_admin"] is True assert row["confirmed_at"] > row["contradicted_at"]