Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

174 KB
Raw Blame
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0

"""Tests for Admin API endpoints (openviking/server/routers/admin.py)."""

import asyncio
import hashlib
import json
import threading
import uuid
from copy import deepcopy
from unittest.mock import AsyncMock, Mock

import httpx
import pytest
import pytest_asyncio
import yaml
from fastapi import FastAPI
from fastapi import Request as FastAPIRequest
from fastapi.responses import JSONResponse

from openviking.config.binding import manager_over_source
from openviking.config.source import MemoryConfigSource
from openviking.pyagfs.exceptions import AGFSNotFoundError
from openviking.server.app import create_app
from openviking.server.config import ServerConfig, UserConfig
from openviking.server.dependencies import set_service
from openviking.server.identity import RequestContext, Role
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.server.store_assembly import build_api_key_manager
from openviking.server.user_config import (
    read_user_add_targets,
    read_user_config,
    user_config_backup_uri,
)
from openviking.service.core import OpenVikingService
from openviking.service.deletion import DeletionService, setup_deletion
from openviking.service.task_store import (
    SYSTEM_TASK_ACCOUNT_ID,
    SYSTEM_TASK_USER_ID,
)
from openviking.service.task_tracker import get_task_tracker
from openviking.service.task_work_index import (
    TaskWorkRejected,
    bind_task_context,
)
from openviking.session.memory.account_templates import (
    EDITABLE_MEMORY_TEMPLATE_FIELDS,
    account_memory_template_path,
    legacy_account_memory_template_path,
    resolve_account_memory_registry,
)
from openviking.session.memory.extract_loop import ExtractLoop
from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry, get_default_registry
from openviking.session.memory.patch_merge_context_provider import PatchMergeContextProvider
from openviking.session.memory.session_extract_context_provider import SessionExtractContextProvider
from openviking_cli.exceptions import OpenVikingError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.config import get_openviking_config


def _uid() -> str:
    return f"acme_{uuid.uuid4().hex[:8]}"


def _seed_secret(user_id: str, seed: str) -> str:
    return hashlib.sha256(f"{user_id}\0{seed}".encode("utf-8")).hexdigest()


ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"


class _FakeAGFS:
    def __init__(self):
        self._files = {}
        self._dirs = {"/", "/local"}

    def read(self, path, **_kwargs):
        if path not in self._files:
            raise AGFSNotFoundError(path)
        return self._files[path]

    def write(self, path, content, **_kwargs):
        self.ensure_parent_dirs(path)
        self._files[path] = content

    def mv(self, old_path, new_path, **_kwargs):
        self._files[new_path] = self._files.pop(old_path)

    def rm(self, path, **_kwargs):
        self._files.pop(path, None)

    def mkdir(self, path, **_kwargs):
        self._dirs.add(path)

    def ensure_parent_dirs(self, path, **_kwargs):
        parent = path.rsplit("/", 1)[0]
        if not parent:
            return
        current = ""
        for part in [part for part in parent.strip("/").split("/") if part]:
            current = f"{current}/{part}" if current else f"/{part}"
            self._dirs.add(current)

    def pathlock_acquire_exact(self, ctx, path, timeout_secs=0.0, owner_lease_ref=None):
        return {"lease_ref": f"test:{path}"}

    async def pathlock_acquire_batch_async(self, ctx, requests, *args):
        return self.pathlock_acquire_exact(ctx, requests[0]["path"], *args)

    def pathlock_release(self, ctx, lease):
        return None


class _FakeVikingFS:
    def __init__(self):
        self.agfs = _FakeAGFS()
        self.files = {}
        self.writes = []

    async def read_file(self, uri, **_kwargs):
        if uri not in self.files:
            raise FileNotFoundError(uri)
        return self.files[uri]

    async def _ensure_access(self, uri, ctx, *, action):
        return None

    async def write_file(self, uri, content, **_kwargs):
        self.writes.append(uri)
        self.files[uri] = content

    async def rm(self, uri, **_kwargs):
        self.files.pop(uri, None)


class _FakeService:
    def __init__(self):
        self.viking_fs = _FakeVikingFS()
        self.sessions = self
        self.runtime_config_manager = manager_over_source(MemoryConfigSource())

    async def get_agent_evolution_enabled(self, account_id):
        del account_id
        return True

    async def initialize_account_directories(self, ctx):
        return None

    async def initialize_user_directories(self, ctx):
        return None

    async def initialize_account_workspace(self, ctx):
        return None


def _build_lightweight_admin_test_app() -> FastAPI:
    from openviking.server.auth.plugins import ApiKeyAuthPlugin
    from openviking.server.auth.registry import get_registry
    from openviking.server.routers import admin as admin_router

    app = FastAPI()
    from openviking.server.restart import RestartController

    app.state.restart_controller = RestartController()
    app.state.config = ServerConfig(root_api_key=ROOT_KEY)
    fake_service = _FakeService()
    app.state.fake_service = fake_service
    set_service(fake_service)

    @app.exception_handler(OpenVikingError)
    async def openviking_error_handler(request: FastAPIRequest, exc: OpenVikingError):
        http_status = ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500)
        return JSONResponse(
            status_code=http_status,
            content=Response(
                status="error",
                error=ErrorInfo(code=exc.code, message=exc.message, details=exc.details),
            ).model_dump(),
        )

    manager = build_api_key_manager(root_key=ROOT_KEY, viking_fs=fake_service.viking_fs)
    app.state.api_key_manager = manager

    # Set auth plugin (lifespan not triggered in ASGI tests)
    registry = get_registry()
    if registry.get("api_key") is None:
        registry.register(ApiKeyAuthPlugin)
    app.state.auth_plugin = registry.get("api_key")()
    app.state.auth_plugin._api_key_manager = manager

    app.include_router(admin_router.router)
    return app


@pytest_asyncio.fixture(scope="function")
async def lightweight_admin_app(monkeypatch):
    app = _build_lightweight_admin_test_app()
    await app.state.fake_service.runtime_config_manager.initialize()
    await app.state.api_key_manager.load()
    return app


@pytest_asyncio.fixture(scope="function")
async def lightweight_admin_client(lightweight_admin_app):
    transport = httpx.ASGITransport(app=lightweight_admin_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
        yield c


@pytest_asyncio.fixture(scope="function")
async def admin_service(service):
    """Use the shared service fixture with local fake models."""
    yield service


@pytest_asyncio.fixture(scope="function")
async def admin_app(admin_service):
    from openviking.server.auth.plugins import ApiKeyAuthPlugin
    from openviking.server.auth.registry import get_registry

    config = ServerConfig(root_api_key=ROOT_KEY)
    app = create_app(config=config, service=admin_service)
    set_service(admin_service)

    manager = build_api_key_manager(root_key=ROOT_KEY, viking_fs=admin_service.viking_fs)
    await manager.load()
    app.state.api_key_manager = manager
    app.state.deletion_service = await setup_deletion(
        service=admin_service,
        manager=manager,
    )

    # Set auth plugin (lifespan not triggered in ASGI tests)
    registry = get_registry()
    if registry.get("api_key") is None:
        registry.register(ApiKeyAuthPlugin)
    app.state.auth_plugin = registry.get("api_key")()
    app.state.auth_plugin._api_key_manager = manager

    return app


@pytest_asyncio.fixture(scope="function")
async def admin_client(admin_app):
    transport = httpx.ASGITransport(app=admin_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
        yield c


def root_headers():
    return {"X-API-Key": ROOT_KEY}


def trusted_headers(
    *,
    account: str,
    user: str,
    include_api_key: bool = False,
):
    headers = {
        "X-OpenViking-Account": account,
        "X-OpenViking-User": user,
    }
    if include_api_key:
        headers["X-API-Key"] = ROOT_KEY
    return headers


async def _agfs_exists(service: OpenVikingService, path: str) -> bool:
    try:
        await service.viking_fs._async_agfs.stat(path)
    except Exception:
        return False
    return True


async def _agfs_mkdirp(service: OpenVikingService, path: str) -> None:
    parts = [part for part in path.strip("/").split("/") if part]
    current = ""
    for part in parts:
        current = f"{current}/{part}" if current else f"/{part}"
        if await _agfs_exists(service, current):
            continue
        await service.viking_fs._async_agfs.mkdir(current)


async def _agfs_write(service: OpenVikingService, path: str, content: str) -> None:
    await _agfs_mkdirp(service, path.rsplit("/", 1)[0])
    await service.viking_fs._async_agfs.write(path, content.encode("utf-8"))


async def _wait_for_task(client: httpx.AsyncClient, task_id: str) -> dict:
    # Budget ~30s: recursive AGFS cleanup can take a couple of seconds, and the
    # original 1s budget was too tight on slower backends/interpreters.
    for _ in range(600):
        resp = await client.get(f"/api/v1/tasks/{task_id}", headers=root_headers())
        assert resp.status_code == 200
        task = resp.json()["result"]
        if task["status"] in {"completed", "failed"}:
            return task
        await asyncio.sleep(0.05)
    raise AssertionError(f"Task {task_id} did not finish")


# ---- Account CRUD ----


async def test_delete_account_files_disables_automatic_pathlock(monkeypatch):
    """Account cleanup must bypass the deleted tree's automatic PathLock."""
    path = "/local/account-to-delete"
    agfs = Mock()
    agfs.rm = AsyncMock()
    agfs.stat = AsyncMock(side_effect=AGFSNotFoundError(path))
    service = Mock()
    service.viking_fs._async_agfs = agfs
    deletion = DeletionService(
        service=service,
        manager=Mock(),
        service_loop=asyncio.get_running_loop(),
    )

    await deletion._delete_account_files("account-to-delete")

    agfs.rm.assert_awaited_once_with(path, recursive=True, auto_pathlock=False)


@pytest_asyncio.fixture
async def template_account(lightweight_admin_client):
    account_id = _uid()
    response = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": account_id, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert response.status_code == 200, response.text
    return account_id, {"X-API-Key": response.json()["result"]["user_key"]}


async def test_studio_file_configuration_permissions_revision_and_overrides(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    tmp_path,
    monkeypatch,
):
    from openviking.config.scope import ConfigScope
    from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton

    account_id, admin_headers = template_account
    config_path = tmp_path / "ov.conf"
    config_path.write_text(
        json.dumps({"vlm": {"provider": "openai", "model": "gpt-4o", "api_key": "file-secret"}})
    )
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", config_path)
    manager = lightweight_admin_app.state.fake_service.runtime_config_manager
    await manager.patch_account(
        account_id,
        {
            "vlm": {
                "model": "override-model",
                "credentials": [{"provider": "openai", "api_key": "account-secret"}],
            }
        },
    )
    url = "/api/v1/admin/configuration"
    params = {"source": "file", "account_id": account_id}
    denied = await lightweight_admin_client.get(url, params=params, headers=admin_headers)
    assert denied.status_code == 403 and "file-secret" not in denied.text
    response = await lightweight_admin_client.get(url, params=params, headers=root_headers())
    assert response.status_code == 200, response.text
    assert response.headers["cache-control"] == "no-store"
    result = response.json()["result"]
    assert result["models"]["vlm"]["config"]["model"] == "gpt-4o"
    assert result["overrides"]["account"] == ["vlm"]
    # Persisted overrides still need reporting even outside the form's scope.
    await manager._source.update(
        ConfigScope.cluster(), lambda _: {"query_planner": {"model": "planner-override"}}
    )
    override_response = await lightweight_admin_client.get(
        url, params=params, headers=root_headers()
    )
    assert override_response.json()["result"]["overrides"]["cluster"] == ["query_planner"]
    content = json.loads(result["content"])
    content["rerank"] = {
        "provider": "jev",
        "api_key": "jev-secret",
        "mode": "choice",
        "threshold": 0,
    }
    body = {"revision": result["revision"], "content": json.dumps(content)}
    assert (
        await lightweight_admin_client.patch(
            url, params={"source": "file"}, headers=admin_headers, json=body
        )
    ).status_code == 403
    saved = await lightweight_admin_client.patch(
        url, params={"source": "file"}, headers=root_headers(), json=body
    )
    assert saved.status_code == 200, saved.text
    assert saved.json()["result"]["restart_required"]
    assert json.loads(config_path.read_text())["rerank"]["provider"] == "jev"
    assert (
        await lightweight_admin_client.patch(
            url, params={"source": "file"}, headers=root_headers(), json=body
        )
    ).status_code == 400
    settings = await manager.get_settings(ConfigScope.account(account_id))
    assert settings["vlm"]["model"] == "override-model"


@pytest.mark.parametrize("cli_host", [None, "127.0.0.1"])
async def test_studio_full_configuration_preview_and_save_are_root_only(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    tmp_path,
    monkeypatch,
    cli_host,
):
    from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton

    _, admin_headers = template_account
    path = tmp_path / "startup.conf"
    server = {"port": 1933}
    if cli_host:
        server.update(host="0.0.0.0", auth_mode="trusted", root_api_key=ROOT_KEY)
        lightweight_admin_app.state.server_config_overrides = {"host": cli_host}
    path.write_text(json.dumps({"server": server, "storage": {"workspace": "/tmp/old"}}))
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)
    before = path.read_bytes()
    url = "/api/v1/admin/configuration"
    loaded = await lightweight_admin_client.get(
        url, params={"source": "file"}, headers=root_headers()
    )
    result = loaded.json()["result"]
    assert result["content"] == before.decode()
    content = json.dumps({"server": {**server, "port": 1934}, "storage": {"workspace": "/tmp/new"}})
    preview_params = {"source": "file", "dry_run": True}
    denied = await lightweight_admin_client.patch(
        url, params=preview_params, headers=admin_headers, json={"content": content}
    )
    assert denied.status_code == 403
    preview = await lightweight_admin_client.patch(
        url, params=preview_params, headers=root_headers(), json={"content": content}
    )
    assert preview.status_code == 200, preview.text
    assert preview.headers["cache-control"] == "no-store"
    assert preview.json()["result"]["content"] == content
    assert path.read_bytes() == before
    assert not path.with_name(path.name + ".studio.bak").exists()
    for params in ({"dry_run": True}, preview_params):
        rejected = await lightweight_admin_client.patch(
            url, params=params, headers=root_headers(), json={"settings": {}}
        )
        assert rejected.status_code == 400
    rejected = await lightweight_admin_client.patch(
        url, params={"dry_run": True}, headers=root_headers(), json={"content": content}
    )
    assert rejected.status_code == 400
    assert path.read_bytes() == before
    body = {"content": content, "revision": result["revision"]}
    for extra_body in (
        {"settings": {"vlm": {"timeout": 1}}},
        {**body, "settings": {"vlm": {"timeout": 1}}},
    ):
        rejected = await lightweight_admin_client.patch(
            url, params={"source": "file"}, headers=root_headers(), json=extra_body
        )
        assert rejected.status_code == 400
        assert path.read_bytes() == before
    denied = await lightweight_admin_client.patch(
        url, params={"source": "file"}, headers=admin_headers, json=body
    )
    assert denied.status_code == 403
    saved = await lightweight_admin_client.patch(
        url, params={"source": "file"}, headers=root_headers(), json=body
    )
    assert saved.status_code == 200, saved.text
    assert saved.headers["cache-control"] == "no-store"
    assert path.read_text() == content
    assert path.with_name(path.name + ".studio.bak").read_bytes() == before
    stale = await lightweight_admin_client.patch(
        url, params={"source": "file"}, headers=root_headers(), json=body
    )
    assert stale.status_code == 400
    runtime = await lightweight_admin_client.patch(url, headers=root_headers(), json=body)
    assert runtime.status_code == 400
    invalid = await lightweight_admin_client.patch(
        url,
        params=preview_params,
        headers=root_headers(),
        json={"content": '{"server":{"port":"bad"}}'},
    )
    assert invalid.status_code == 400
    assert path.read_text() == content


@pytest.mark.parametrize(
    "memory_type",
    ["profile", "preferences", "entities", "events", "soul", "identity"],
)
async def test_account_memory_templates_publish_and_reset(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
):
    client = lightweight_admin_client
    account_id, headers = template_account
    root = f"/api/v1/admin/accounts/{account_id}/memory-templates"
    path = account_memory_template_path(account_id, memory_type)
    fs = lightweight_admin_app.state.fake_service.viking_fs
    settings_path = f"/local/{account_id}/_system/setting.json"
    fs.agfs._files[settings_path] = b'{"agent_evolution":{"enabled":false}}'
    registry = get_default_registry()
    original = {s.memory_type: s.model_dump() for s in registry.list_all(True)}
    initial = await client.get(root, headers=headers)
    assert initial.status_code == 200, initial.text
    assert {item["memory_type"] for item in initial.json()["result"]["templates"]} == {
        "profile",
        "events",
        "preferences",
        "entities",
        "soul",
        "identity",
    }
    assert all(item["status"] == "system_default" for item in initial.json()["result"]["templates"])
    assert path not in fs.agfs._files

    editable_fields = {
        "profile": ("content",),
        "events": ("event_name", "summary"),
        "preferences": ("topic", "content"),
        "entities": ("category", "name", "content"),
        "soul": ("core_truths", "boundaries", "vibe", "continuity"),
        "identity": ("creature", "name", "vibe", "avatar", "emoji", "introduction"),
    }[memory_type]
    body = {
        "description": "Remember business facts in {{ language.lower() }}.",
        "fields": [
            {"name": name, "description": f"Business {name}: {{{{ language }}}}"}
            for name in editable_fields
        ],
    }
    if memory_type in {"events", "soul", "identity"}:
        variable = {"events": "summary", "soul": "core_truths", "identity": "introduction"}[
            memory_type
        ]
        body["content_template"] = "# Business\n{{ " + variable + " }}"
    publish = await client.put(f"{root}/{memory_type}", json=body, headers=headers)
    assert publish.status_code == 200, publish.text
    result = publish.json()["result"]
    assert result["status"] == "custom"
    assert result["updated_at"]
    assert all(result["effective"][key] == value for key, value in body.items() if key != "fields")
    assert result["effective"]["fields"][0]["type"] == "string"
    stored = yaml.safe_load(fs.agfs._files[path])
    assert stored.pop("_updated_at") == result["updated_at"]
    assert stored == result["effective"]
    assert stored["memory_type"] == memory_type
    assert "stage" in stored and "embedding_template" in stored
    assert fs.agfs._files[settings_path] == b'{"agent_evolution":{"enabled":false}}'
    assert (await client.get(f"{root}/{memory_type}", headers=headers)).json()["result"] == result
    roundtrip = await client.put(f"{root}/{memory_type}", json=result["effective"], headers=headers)
    assert roundtrip.status_code == 200, roundtrip.text
    assert roundtrip.json()["result"] == result
    listed = (await client.get(root, headers=headers)).json()["result"]["templates"]
    assert (
        next(item for item in listed if item["memory_type"] == memory_type)["effective"] == stored
    )
    resolved = await resolve_account_memory_registry(fs, account_id, registry)
    assert resolved is not registry
    assert all(resolved.get(schema.memory_type) is not schema for schema in registry.list_all(True))
    schema = resolved.get(memory_type)
    assert schema.description == body["description"]
    expected = dict(original[memory_type])
    expected["description"] = body["description"]
    if "content_template" in body:
        expected["content_template"] = body["content_template"]
    expected["fields"] = [
        {**field, "description": f"Business {field['name']}: {{{{ language }}}}"}
        if field["name"] in editable_fields
        else field
        for field in expected["fields"]
    ]
    assert schema.model_dump() == expected
    # All fields, including Events goal/ranges, survive a partial request.
    assert [field.name for field in schema.fields] == [
        field["name"] for field in original[memory_type]["fields"]
    ]
    assert {s.memory_type: s.model_dump() for s in registry.list_all(True)} == original

    noop = await client.put(f"{root}/{memory_type}", json=body, headers=headers)
    assert noop.json()["result"]["updated_at"] == result["updated_at"]
    replacement = await client.put(
        f"{root}/{memory_type}", json={"description": "Replacement"}, headers=headers
    )
    assert replacement.status_code == 200, replacement.text
    assert replacement.json()["result"]["effective"]["fields"] == result["defaults"]["fields"]
    assert path + ".backup" not in fs.agfs._files
    # An earlier extraction retains its complete snapshot across publication.
    assert resolved.get(memory_type).description == body["description"]
    reset = await client.delete(f"{root}/{memory_type}", headers=headers)
    assert reset.status_code == 200, reset.text
    assert reset.json()["result"]["effective"] == result["defaults"]
    assert reset.json()["result"]["status"] == "system_default"
    assert path not in fs.agfs._files
    restored = await resolve_account_memory_registry(fs, account_id, registry)
    assert {s.memory_type: s.model_dump() for s in restored.list_all(True)} == original
    assert (await client.delete(f"{root}/{memory_type}", headers=headers)).status_code == 200
    default_form = await client.put(
        f"{root}/{memory_type}", json=result["defaults"], headers=headers
    )
    assert default_form.status_code == 200, default_form.text
    assert default_form.json()["result"]["effective"] == result["defaults"]
    assert default_form.json()["result"]["status"] == "system_default"
    assert default_form.json()["result"]["updated_at"] is None
    assert path not in fs.agfs._files


async def test_account_memory_template_yaml_uses_literal_multiline_strings(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    account_id, headers = template_account
    path = account_memory_template_path(account_id, "profile")
    backup_path = path + ".backup"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    fs.agfs._files[backup_path] = b"obsolete"
    description = "# Role and objective\nReadable custom instructions."

    response = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{account_id}/memory-templates/profile",
        json={"description": description},
        headers=headers,
    )

    assert response.status_code == 200, response.text
    raw = fs.agfs._files[path].decode("utf-8")
    assert "description: |" in raw
    assert yaml.safe_load(raw)["description"] == description
    assert backup_path not in fs.agfs._files


@pytest.mark.parametrize(
    "memory_type,edit",
    [
        (kind, edit)
        for kind in EDITABLE_MEMORY_TEMPLATE_FIELDS
        for edit in ("exact", "description", "field_description")
    ]
    + [
        (kind, edit)
        for kind in ("events", "soul", "identity")
        for edit in ("rstrip", "newline", "crlf", "heading")
    ],
)
async def test_account_memory_templates_default_form_roundtrip(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
    edit,
):
    from openviking.session.memory.dataclass import MemoryFile
    from openviking.session.memory.memory_updater import ExtractContext
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
    from openviking.session.memory.utils.template_utils import TemplateUtils

    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    initial = await client.get(url, headers=headers)
    assert initial.status_code == 200, initial.text
    assert initial.json()["result"]["status"] == "system_default"
    defaults = initial.json()["result"]["defaults"]
    # Match the managed form: only editable fields from the actual GET result.
    body = {
        "description": defaults["description"],
        "fields": [
            {"name": f["name"], "description": f["description"]}
            for f in defaults["fields"]
            if f["name"] in EDITABLE_MEMORY_TEMPLATE_FIELDS[memory_type]
        ],
    }
    if memory_type in ("events", "soul", "identity"):
        original = defaults["content_template"]
        body["content_template"] = {
            "rstrip": original.rstrip(),
            "newline": original + "\n",
            "crlf": original.replace("\n", "\r\n"),
            "heading": "# Account memory\n" + original,
        }.get(edit, original)
    if edit == "description":
        body["description"] += "\nAccount instructions."
    elif edit == "field_description":
        body["fields"][0]["description"] += "\nAccount field instructions."
    published = await client.put(url, json=body, headers=headers)
    assert published.status_code == 200, published.text
    result = published.json()["result"]
    assert result["defaults"] == defaults
    effective = result["effective"]
    is_default = effective == defaults
    assert result["status"] == ("system_default" if is_default else "custom")
    assert (result["updated_at"] is None) == is_default
    assert effective["description"] == body["description"]
    for field in body["fields"]:
        actual = next(f for f in effective["fields"] if f["name"] == field["name"])
        assert actual["description"] == field["description"]
    assert (await client.get(url, headers=headers)).json()["result"] == result
    roundtrip = await client.put(url, json=effective, headers=headers)
    assert roundtrip.status_code == 200, roundtrip.text
    assert roundtrip.json()["result"] == result
    fs = lightweight_admin_app.state.fake_service.viking_fs
    snapshot = await resolve_account_memory_registry(fs, account_id, get_default_registry())
    schema = snapshot.get(memory_type)
    if "content_template" in body:
        assert schema.content_template == effective["content_template"] == body["content_template"]
        assert schema._account_content_template == (body["content_template"] != original)
        values = {f.name: "Business fact" for f in schema.fields}
        values["ranges"] = ""
        context = ExtractContext([])
        rendered = MemoryFileUtils.write(
            MemoryFile(memory_type=memory_type, extra_fields=values),
            content_template=schema.content_template,
            extract_context=context,
            account_content_template_type=memory_type if schema._account_content_template else None,
        )
        assert MemoryFileUtils.read(rendered).content == TemplateUtils.render(
            body["content_template"], values, context
        )
    reset = await client.delete(url, headers=headers)
    assert reset.status_code == 200, reset.text
    assert reset.json()["result"]["effective"] == defaults
    assert reset.json()["result"]["status"] == "system_default"


def _editable_template_form(defaults, memory_type):
    body = {
        "description": defaults["description"],
        "fields": [
            {"name": field["name"], "description": field["description"]}
            for field in defaults["fields"]
            if field["name"] in EDITABLE_MEMORY_TEMPLATE_FIELDS[memory_type]
        ],
    }
    if memory_type in ("events", "soul", "identity"):
        body["content_template"] = defaults["content_template"]
    return body


@pytest.mark.parametrize(
    "memory_type,module",
    [
        (kind, module)
        for kind, fields in EDITABLE_MEMORY_TEMPLATE_FIELDS.items()
        for module in ("description", *fields)
    ]
    + [(kind, "content_template") for kind in ("events", "soul", "identity")],
)
async def test_account_memory_templates_module_reset_clears_override(
    lightweight_admin_client, lightweight_admin_app, template_account, memory_type, module
):
    account_id, headers = template_account
    client = lightweight_admin_client
    root = f"/api/v1/admin/accounts/{account_id}/memory-templates"
    url = f"{root}/{memory_type}"
    initial = (await client.get(url, headers=headers)).json()["result"]
    form = _editable_template_form(initial["defaults"], memory_type)
    body = deepcopy(form)
    if module in ("description", "content_template"):
        body[module] += "\nAccount instructions."
    else:
        field = next(field for field in body["fields"] if field["name"] == module)
        field["description"] += "\nAccount field instructions."
    publish = await client.put(url, json=body, headers=headers)
    assert publish.status_code == 200, publish.text
    result = publish.json()["result"]
    assert result["status"] == "custom"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, memory_type)
    snapshot = await resolve_account_memory_registry(fs, account_id, get_default_registry())
    previous_schema = snapshot.get(memory_type).model_dump()
    untouched = {key: value for key, value in fs.agfs._files.items() if key != path}

    # Reopen the editor, reset only the edited module, then save the whole form.
    reopened = (await client.get(url, headers=headers)).json()["result"]
    body = _editable_template_form(reopened["effective"], memory_type)
    if module in ("description", "content_template"):
        body[module] = form[module]
    else:
        field = next(field for field in body["fields"] if field["name"] == module)
        field["description"] = next(
            field["description"] for field in form["fields"] if field["name"] == module
        )
    # Field order does not change the completed configuration.
    body["fields"].reverse()
    restored = await client.put(url, json=body, headers=headers)
    assert restored.status_code == 200, restored.text
    assert restored.json()["result"] == initial
    assert path not in fs.agfs._files
    assert path + ".backup" not in fs.agfs._files
    assert all(fs.agfs._files[key] == value for key, value in untouched.items())
    assert (await client.get(url, headers=headers)).json()["result"] == initial
    listed = (await client.get(root, headers=headers)).json()["result"]["templates"]
    assert next(item for item in listed if item["memory_type"] == memory_type) == {
        key: value for key, value in initial.items() if key != "account_id"
    }
    resolved = await resolve_account_memory_registry(fs, account_id, get_default_registry())
    assert (
        resolved.get(memory_type).model_dump()
        == get_default_registry().get(memory_type).model_dump()
    )
    assert snapshot.get(memory_type).model_dump() == previous_schema
    stored = dict(fs.agfs._files)
    repeated = await client.put(url, json=body, headers=headers)
    assert repeated.status_code == 200, repeated.text
    assert repeated.json()["result"] == initial
    assert fs.agfs._files == stored


@pytest.mark.parametrize("memory_type", EDITABLE_MEMORY_TEMPLATE_FIELDS)
async def test_account_memory_templates_module_reset_keeps_other_edits(
    lightweight_admin_client, lightweight_admin_app, template_account, memory_type
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    initial = (await client.get(url, headers=headers)).json()["result"]
    body = _editable_template_form(initial["defaults"], memory_type)
    body["description"] += "\nType edit."
    body["fields"][0]["description"] += "\nField edit."
    response = await client.put(url, json=body, headers=headers)
    assert response.status_code == 200, response.text
    body["description"] = initial["defaults"]["description"]
    response = await client.put(url, json=body, headers=headers)
    assert response.status_code == 200, response.text
    result = response.json()["result"]
    assert result["status"] == "custom"
    assert result["updated_at"]
    assert result["effective"]["description"] == initial["defaults"]["description"]
    field = next(f for f in result["effective"]["fields"] if f["name"] == body["fields"][0]["name"])
    assert field["description"] == body["fields"][0]["description"]
    assert account_memory_template_path(account_id, memory_type) in (
        lightweight_admin_app.state.fake_service.viking_fs.agfs._files
    )


async def test_account_memory_templates_save_clears_legacy_default_override(
    lightweight_admin_client, lightweight_admin_app, template_account
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    initial = (await client.get(url, headers=headers)).json()["result"]
    legacy = {**initial["defaults"], "_updated_at": "2026-09-01T00:00:00+00:00"}
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    fs.agfs._files[path] = yaml.safe_dump(legacy).encode()
    before = (await client.get(url, headers=headers)).json()["result"]
    assert before["status"] == "custom"  # Reads do not migrate persisted overrides.
    response = await client.put(url, json=before["effective"], headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["result"] == initial
    assert path not in fs.agfs._files


@pytest.mark.parametrize(
    "body",
    [
        {"description": 123},
        {"description": "{{ language | length }}"},
        {"description": "{{ cycler.__init__.__globals__.__builtins__.len('harmless') }}"},
        {"description": "literal {{ unclosed"},
        {"fields": [{"name": "summary", "description": "{{ summary }}"}]},
        {"fields": [{"name": "summary", "description": "{{ language | trim('x') }}"}]},
        {"fields": [{"name": "summary", "description": "literal {{ unclosed"}]},
        {"_account_description": False},
        {"fields": [{"name": "summary", "_account_description": False}]},
        {"memory_type": "other"},
        {"fields": None},
        {"fields": [{}]},
        {"fields": [{"name": "x", "type": "not-a-type"}]},
        {"fields": [{"name": "x", "merge_op": "not-an-op"}]},
        {"fields": [{"name": "x"}, {"name": "x"}]},
        {"fields": [{"name": "x", "description": "{{"}]},
        {"content_template": "{{"},
        {"content_template": "{{ unknown_field }}"},
        {"content_template": "{{ extract_context.messages }}"},
        {"content_template": "{% include 'private.yaml' %}"},
        {"content_template": "{{ summary | attr('__class__') }}"},
        {"content_template": "{{ summary | length }}"},
        {"content_template": "{{ summary | trim('x') }}"},
        {"content_template": "{{ summary | default('pending', true) }}"},
        {"content_template": "{{ summary.strip('x') }}"},
        {"content_template": "x" * (64 * 1024 + 1)},
    ],
)
async def test_account_memory_templates_reject_invalid_configuration(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    body,
):
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    assert (
        await lightweight_admin_client.put(
            url, json={"description": "Keep current"}, headers=headers
        )
    ).status_code == 200
    fs = lightweight_admin_app.state.fake_service.viking_fs
    original = dict(fs.agfs._files)
    response = await lightweight_admin_client.put(url, json=body, headers=headers)
    assert response.status_code in {400, 422}, response.text
    assert fs.agfs._files == original


@pytest.mark.parametrize("field", ["description", "fields.content.description"])
@pytest.mark.parametrize(
    ("text", "reason"),
    [
        ("{{ language | length }}", "unsupported_filter"),
        ("{{ cycler.__init__.__globals__.__builtins__.len('harmless') }}", "unsupported_call"),
        ("{{", "invalid_jinja"),
    ],
)
async def test_account_memory_templates_description_diagnostics_and_legacy_recovery(
    lightweight_admin_client, lightweight_admin_app, template_account, field, text, reason
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    active = await client.put(url, json={"description": "Current"}, headers=headers)
    assert active.status_code == 200
    before = dict(fs.agfs._files)
    body = (
        {"description": text}
        if field == "description"
        else {"fields": [{"name": "content", "description": text}]}
    )
    response = await client.put(url, json=body, headers=headers)
    assert response.status_code == 400, response.text
    details = response.json()["error"]["details"]
    assert details["field"] == field
    assert details["reason"] == reason
    assert details["line"] == 1
    assert fs.agfs._files == before

    # An old well-formed YAML override may contain now-unsupported expressions.
    # Reading/resetting must stay possible, while extraction must reject it.
    path = account_memory_template_path(account_id, "profile")
    stored = yaml.safe_load(fs.agfs._files[path])
    target = stored if field == "description" else stored["fields"][0]
    target["description"] = text
    target["_account_description"] = False
    fs.agfs._files[path] = yaml.safe_dump(stored).encode()
    assert (await client.get(url, headers=headers)).status_code == 200
    from openviking_cli.exceptions import FailedPreconditionError

    with pytest.raises(FailedPreconditionError, match="republish or reset"):
        await resolve_account_memory_registry(fs, account_id, MemoryTypeRegistry())
    assert (await client.delete(url, headers=headers)).status_code == 200
    assert path not in fs.agfs._files


@pytest.mark.parametrize("memory_type", list(EDITABLE_MEMORY_TEMPLATE_FIELDS))
@pytest.mark.parametrize("character", ["a", "中", "😀"])
async def test_account_memory_templates_description_character_limit(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
    character,
):
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    text = character * 50_000
    fs = lightweight_admin_app.state.fake_service.viking_fs
    # Check one field at a time without exceeding the aggregate 1 MiB cap.
    for field_name in [None, *EDITABLE_MEMORY_TEMPLATE_FIELDS[memory_type]]:
        body = {"description": text}
        target = body
        if field_name is not None:
            target = {"name": field_name, "description": text}
            body["fields"] = [target]
        response = await lightweight_admin_client.put(url, json=body, headers=headers)
        assert response.status_code == 200, response.text
        effective = response.json()["result"]["effective"]
        assert effective["description"] == text
        if field_name is not None:
            field = next(field for field in effective["fields"] if field["name"] == field_name)
            assert field["description"] == text
        original = dict(fs.agfs._files)
        target["description"] = text + character
        response = await lightweight_admin_client.put(url, json=body, headers=headers)
        assert response.status_code == 400, response.text
        assert "50000 Unicode characters" in response.json()["error"]["message"]
        assert fs.agfs._files == original
    assert (await lightweight_admin_client.get(url, headers=headers)).status_code == 200
    assert (await lightweight_admin_client.delete(url, headers=headers)).status_code == 200


async def test_account_memory_templates_content_validation_error_details(
    lightweight_admin_client,
    template_account,
):
    account_id, headers = template_account
    response = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{account_id}/memory-templates/events",
        json={"content_template": "# Summary\n{{ typo }}"},
        headers=headers,
    )
    assert response.status_code == 400
    assert response.json()["error"]["details"] == {
        "field": "content_template",
        "reason": "unknown_variable",
        "line": 2,
    }


@pytest.mark.parametrize(
    "expression",
    ["selected", "ranges|default('')|trim", "ranges|default('0-999')", "ranges if summary else ''"],
)
async def test_account_memory_templates_range_expressions_reach_file_body(
    lightweight_admin_client, lightweight_admin_app, template_account, expression
):
    from openviking.message import Message, TextPart
    from openviking.session.memory.dataclass import MemoryFile
    from openviking.session.memory.memory_updater import ExtractContext
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils

    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    template = (
        "{% set selected = ranges %}{{ extract_context.get_event_content("
        + expression
        + ", summary, 0) }}"
    )
    published = await lightweight_admin_client.put(
        url, json={"content_template": template}, headers=headers
    )
    assert published.status_code == 200, published.text
    result = (await lightweight_admin_client.get(url, headers=headers)).json()["result"]
    assert result["effective"]["content_template"] == template
    roundtrip = await lightweight_admin_client.put(url, json=result["effective"], headers=headers)
    assert roundtrip.status_code == 200, roundtrip.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    snapshot = await resolve_account_memory_registry(fs, account_id, MemoryTypeRegistry())
    schema = snapshot.get("events")
    context = ExtractContext(
        [
            Message(id="m1", role="user", parts=[TextPart("Selected source message")]),
            Message(id="m2", role="user", parts=[TextPart("Unrelated source message")]),
        ]
    )
    rendered = MemoryFileUtils.write(
        MemoryFile(memory_type="events", extra_fields={"ranges": "0", "summary": "summary"}),
        content_template=schema.content_template,
        extract_context=context,
        account_content_template_type="events" if schema._account_content_template else None,
    )
    content = MemoryFileUtils.read(rendered).content
    assert "Selected source message" in content
    assert "Unrelated source message" not in content


async def test_account_memory_templates_range_values_are_checked_at_render_time(
    lightweight_admin_client, lightweight_admin_app, template_account
):
    from types import SimpleNamespace

    from openviking.session.memory.dataclass import MemoryFile
    from openviking.session.memory.utils.content_template import ContentTemplateError
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils

    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    template = "{% set selected = summary %}{{ extract_context.get_year(selected) }}"
    published = await lightweight_admin_client.put(
        url, json={"content_template": template}, headers=headers
    )
    assert published.status_code == 200, published.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    snapshot = await resolve_account_memory_registry(fs, account_id, MemoryTypeRegistry())
    schema = snapshot.get("events")
    get_year = Mock(spec=[], return_value="2026")
    with pytest.raises(ContentTemplateError, match="invalid_ranges"):
        MemoryFileUtils.write(
            MemoryFile(memory_type="events", extra_fields={"ranges": "0", "summary": "0-999"}),
            content_template=schema.content_template,
            extract_context=SimpleNamespace(get_year=get_year),
            account_content_template_type="events",
        )
    get_year.assert_not_called()


@pytest.mark.parametrize(
    "memory_type, field_name",
    [("events", "summary"), ("soul", "core_truths"), ("identity", "introduction")],
)
@pytest.mark.parametrize("formatting", [".strip().upper()", " | trim | upper"])
async def test_account_memory_templates_string_formatting_reaches_file_body(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
    field_name,
    formatting,
):
    from openviking.session.memory.dataclass import MemoryFile
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils

    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    body = {"content_template": "# {{ " + field_name + formatting + " }}"}
    response = await lightweight_admin_client.put(url, json=body, headers=headers)
    assert response.status_code == 200, response.text
    effective = (await lightweight_admin_client.get(url, headers=headers)).json()["result"][
        "effective"
    ]
    assert effective["content_template"] == body["content_template"]
    roundtrip = await lightweight_admin_client.put(url, json=effective, headers=headers)
    assert roundtrip.status_code == 200, roundtrip.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    snapshot = await resolve_account_memory_registry(fs, account_id, MemoryTypeRegistry())
    schema = snapshot.get(memory_type)
    assert schema._account_content_template is True
    rendered = MemoryFileUtils.write(
        MemoryFile(memory_type=memory_type, extra_fields={field_name: " business fact "}),
        content_template=schema.content_template,
        account_content_template_type=schema.memory_type,
    )
    assert MemoryFileUtils.read(rendered).content == "# BUSINESS FACT"


async def test_account_memory_templates_description_only_keeps_safe_deployment_methods(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, headers = template_account
    defaults = MemoryTypeRegistry()
    defaults.get("events").content_template = "# {{ summary.strip().upper() }}"
    monkeypatch.setattr("openviking.server.routers.admin.get_default_registry", lambda: defaults)
    response = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{account_id}/memory-templates/events",
        json={"description": "Capture release decisions"},
        headers=headers,
    )
    assert response.status_code == 200, response.text
    assert response.json()["result"]["effective"]["content_template"] == (
        "# {{ summary.strip().upper() }}"
    )
    snapshot = await resolve_account_memory_registry(
        lightweight_admin_app.state.fake_service.viking_fs, account_id, defaults
    )
    assert snapshot.get("events")._account_content_template is False
    assert snapshot.get("events").content_template == "# {{ summary.strip().upper() }}"


@pytest.mark.parametrize(
    "memory_type, field_name",
    [("events", "summary"), ("soul", "core_truths"), ("identity", "introduction")],
)
@pytest.mark.parametrize("request_kind", ["description_only", "empty", "roundtrip"])
async def test_account_memory_templates_inherit_exact_deployment_body(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
    memory_type,
    field_name,
    request_kind,
):
    from openviking.session.memory.dataclass import MemoryFile
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils

    account_id, headers = template_account
    defaults = MemoryTypeRegistry()
    # Deployment code may use methods/filters that custom Account bodies cannot.
    deployment_body = "# {{ " + field_name + ".replace('old', 'new') | upper }}"
    defaults.get(memory_type).content_template = deployment_body
    monkeypatch.setattr("openviking.server.routers.admin.get_default_registry", lambda: defaults)
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    body = {"description": "Account instructions"} if request_kind == "description_only" else {}
    if request_kind == "roundtrip":
        response = await lightweight_admin_client.get(url, headers=headers)
        assert response.status_code == 200, response.text
        body = response.json()["result"]["effective"]
        body["description"] = "Account instructions"
    response = await lightweight_admin_client.put(url, json=body, headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["result"]["status"] == (
        "system_default" if request_kind == "empty" else "custom"
    )
    assert response.json()["result"]["effective"]["content_template"] == deployment_body
    # Roundtrip a persisted override too, not only defaults returned before a PUT.
    response = await lightweight_admin_client.put(
        url, json=response.json()["result"]["effective"], headers=headers
    )
    assert response.status_code == 200, response.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, memory_type)
    if request_kind == "empty":
        assert path not in fs.agfs._files
        assert response.json()["result"]["updated_at"] is None
    else:
        stored = yaml.safe_load(fs.agfs._files[path])
        assert "_account_content_template" not in stored
    snapshot = await resolve_account_memory_registry(fs, account_id, defaults)
    schema = snapshot.get(memory_type)
    assert schema._account_content_template is False
    assert schema.content_template == deployment_body
    assert defaults.get(memory_type)._account_content_template is False
    rendered = MemoryFileUtils.write(
        MemoryFile(memory_type=memory_type, extra_fields={field_name: "old fact"}),
        content_template=schema.content_template,
        account_content_template_type=(
            schema.memory_type if schema._account_content_template else None
        ),
    )
    assert MemoryFileUtils.read(rendered).content == "# NEW FACT"


@pytest.mark.parametrize("alteration", ["whitespace", "different_body"])
async def test_account_memory_templates_recheck_persisted_body_without_trusting_flags(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
    alteration,
):
    from openviking_cli.exceptions import FailedPreconditionError

    account_id, headers = template_account
    defaults = MemoryTypeRegistry()
    deployment_body = "{{ summary | length }}"
    defaults.get("events").content_template = deployment_body
    monkeypatch.setattr("openviking.server.routers.admin.get_default_registry", lambda: defaults)
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    response = await lightweight_admin_client.put(
        url, json={"description": "Account instructions"}, headers=headers
    )
    assert response.status_code == 200, response.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "events")
    original = fs.agfs._files[path]
    altered_body = deployment_body + (" " if alteration == "whitespace" else "changed")
    # Even a whitespace change is custom; equality is exact, not normalized.
    response = await lightweight_admin_client.put(
        url, json={"content_template": altered_body}, headers=headers
    )
    assert response.status_code == 400, response.text
    assert fs.agfs._files[path] == original
    corrupted = yaml.safe_load(original)
    corrupted["content_template"] = altered_body
    corrupted["_account_content_template"] = False
    corrupted["deployment_content_template"] = altered_body
    fs.agfs._files[path] = yaml.safe_dump(corrupted).encode()
    with pytest.raises(FailedPreconditionError):
        await resolve_account_memory_registry(fs, account_id, defaults)
    # Management reads remain available for recovery; no unsafe body is rendered.
    assert (await lightweight_admin_client.get(url, headers=headers)).status_code == 200


@pytest.mark.parametrize("restore_defaults", [False, True])
async def test_account_memory_templates_recheck_trust_after_deployment_change(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
    restore_defaults,
):
    from openviking_cli.exceptions import FailedPreconditionError

    account_id, headers = template_account
    defaults = MemoryTypeRegistry()
    old_body = "{{ summary | length }}"
    defaults.get("events").content_template = old_body
    monkeypatch.setattr("openviking.server.routers.admin.get_default_registry", lambda: defaults)
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    response = await lightweight_admin_client.put(
        url, json={"description": "Account instructions"}, headers=headers
    )
    assert response.status_code == 200, response.text
    fs = lightweight_admin_app.state.fake_service.viking_fs
    old_snapshot = await resolve_account_memory_registry(fs, account_id, defaults)
    if restore_defaults:
        response = await lightweight_admin_client.put(url, json={}, headers=headers)
        assert response.status_code == 200, response.text
        assert response.json()["result"]["status"] == "system_default"
    defaults.get("events").content_template = "# {{ summary }}"
    if restore_defaults:
        current = await resolve_account_memory_registry(fs, account_id, defaults)
        assert current.get("events").content_template == "# {{ summary }}"
    else:
        with pytest.raises(FailedPreconditionError):
            await resolve_account_memory_registry(fs, account_id, defaults)
    # Already-started extractions keep their snapshot, not a mutable defaults view.
    assert old_snapshot.get("events").content_template == old_body
    assert old_snapshot.get("events")._account_content_template is False
    response = await lightweight_admin_client.put(
        url, json={"description": "Use current defaults"}, headers=headers
    )
    assert response.status_code == 200, response.text
    new_snapshot = await resolve_account_memory_registry(fs, account_id, defaults)
    assert new_snapshot.get("events").content_template == "# {{ summary }}"
    assert new_snapshot.get("events")._account_content_template is False


async def test_account_memory_templates_old_content_can_be_read_replaced_and_reset(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    from openviking_cli.exceptions import FailedPreconditionError

    account_id, headers = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/events"
    path = account_memory_template_path(account_id, "events")
    response = await lightweight_admin_client.put(
        url, json={"description": "Account instructions"}, headers=headers
    )
    assert response.status_code == 200, response.text
    legacy = yaml.safe_load(fs.agfs._files[path])
    legacy["content_template"] = "{{ summary | length }}"
    raw = yaml.safe_dump(legacy).encode()
    for operation in ("PUT", "DELETE"):
        fs.agfs._files[path] = raw
        response = await lightweight_admin_client.get(url, headers=headers)
        assert response.status_code == 200
        assert (
            response.json()["result"]["effective"]["content_template"] == legacy["content_template"]
        )
        with pytest.raises(FailedPreconditionError):
            await resolve_account_memory_registry(fs, account_id, MemoryTypeRegistry())
        response = await lightweight_admin_client.request(
            operation,
            url,
            headers=headers,
            **(
                {"json": {"content_template": "{{ summary.upper() }}"}}
                if operation == "PUT"
                else {}
            ),
        )
        assert response.status_code == 200, response.text
        assert path + ".backup" not in fs.agfs._files


@pytest.mark.parametrize(
    "memory_type", ["profile", "events", "preferences", "entities", "soul", "identity"]
)
async def test_account_memory_templates_locked_fields_cannot_be_modified(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
):
    client = lightweight_admin_client
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    active = await client.put(url, json={"description": "Active policy"}, headers=headers)
    assert active.status_code == 200, active.text
    defaults = active.json()["result"]["defaults"]
    fs = lightweight_admin_app.state.fake_service.viking_fs
    original = dict(fs.agfs._files)
    editable = {"description", "fields"}
    if memory_type in {"events", "soul", "identity"}:
        editable.add("content_template")
    invalid = [
        {key: None if value is not None else "changed"}
        for key, value in defaults.items()
        if key not in editable
    ]
    invalid.extend(
        [
            {"unknown": "ignored?"},
            {"Description": "wrong key"},
            {"_updated_at": "forged"},
            {"_account_content_template": False},
            {"deployment_content_template": "forged"},
            {"enabled": 1},
            {"fields": [{"name": "renamed_field", "description": "changed"}]},
            {"description": None},
            {"description": " \n"},
            {"fields": [None]},
        ]
    )
    for field in defaults["fields"]:
        invalid.extend(
            {"fields": [{"name": field["name"], key: None if value is not None else "changed"}]}
            for key, value in field.items()
            if key not in {"name", "description"}
        )
        invalid.extend(
            [
                {"fields": [{"name": field["name"], "unknown": "ignored?"}]},
                {"fields": [{"name": field["name"], "description": ""}]},
                {"fields": [{"name": field["name"]}, {"name": field["name"]}]},
            ]
        )
    if memory_type == "events":
        invalid.extend(
            {"fields": [{"name": name, "description": "changed"}]} for name in ("goal", "ranges")
        )
    if memory_type in {"events", "soul", "identity"}:
        invalid.extend([{"content_template": None}, {"content_template": " "}])
    for body in invalid:
        response = await client.put(url, json=body, headers=headers)
        assert response.status_code == 400, (memory_type, body, response.text)
        assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
        assert fs.agfs._files == original
    # Partial field lists are updates by name, never a way to remove locked fields.
    response = await client.put(url, json={"fields": []}, headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["result"]["effective"]["fields"] == defaults["fields"]
    response = await client.put(
        url, json={"fields": list(reversed(defaults["fields"]))}, headers=headers
    )
    assert response.status_code == 200, response.text
    assert response.json()["result"]["effective"]["fields"] == defaults["fields"]


@pytest.mark.parametrize("memory_type", ["experiences", "cases", "trajectories"])
async def test_account_memory_templates_unexposed_types_rejected(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    memory_type,
):
    account_id, headers = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    original = dict(fs.agfs._files)
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}"
    for method in ("GET", "PUT", "DELETE"):
        response = await lightweight_admin_client.request(
            method,
            url,
            headers=headers,
            **({"json": {"description": "New"}} if method == "PUT" else {}),
        )
        assert response.status_code == 400, response.text
        assert fs.agfs._files == original


async def test_account_memory_templates_permissions_and_isolation(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    client = lightweight_admin_client
    account_id, admin_headers = template_account
    other = _uid()
    created = await client.post(
        "/api/v1/admin/accounts",
        json={"account_id": other, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert created.status_code == 200
    user = await client.post(
        f"/api/v1/admin/accounts/{account_id}/users", json={"user_id": "bob"}, headers=admin_headers
    )
    assert user.status_code == 200
    user_headers = {"X-API-Key": user.json()["result"]["user_key"]}
    for method in ("GET", "PUT", "DELETE"):
        body = {"json": {"description": "custom"}} if method == "PUT" else {}
        url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
        assert (await client.request(method, url, headers=user_headers, **body)).status_code == 403
        other_url = f"/api/v1/admin/accounts/{other}/memory-templates/profile"
        assert (
            await client.request(method, other_url, headers=admin_headers, **body)
        ).status_code == 403
        missing_url = "/api/v1/admin/accounts/missing-account/memory-templates/profile"
        assert (
            await client.request(method, missing_url, headers=root_headers(), **body)
        ).status_code == 404
        assert (
            await client.request(
                method, url.replace("/profile", "/missing-template"), headers=admin_headers, **body
            )
        ).status_code == 404
    root = f"/api/v1/admin/accounts/{account_id}/memory-templates"
    assert (await client.get(root, headers=user_headers)).status_code == 403
    for memory_type in ("profile", "events"):
        assert (
            await client.put(
                f"{root}/{memory_type}", json={"description": memory_type}, headers=root_headers()
            )
        ).status_code == 200
    await client.delete(f"{root}/profile", headers=admin_headers)
    assert (await client.get(f"{root}/events", headers=admin_headers)).json()["result"][
        "effective"
    ]["description"] == "events"
    other_result = await client.get(
        f"/api/v1/admin/accounts/{other}/memory-templates", headers=root_headers()
    )
    assert all(
        item["status"] == "system_default" for item in other_result.json()["result"]["templates"]
    )


@pytest.mark.parametrize("merge", [False, True], ids=["extraction", "patch-merge"])
@pytest.mark.parametrize("output_format", ["python", "json"])
@pytest.mark.parametrize(
    "marker",
    [
        "{{ language.upper() }}",
        "{% if language == 'en' %}EN{% else %}OTHER{% endif %}",
        "{{ language | trim | upper }}",
    ],
    ids=["safe-method", "safe-condition", "safe-filters"],
)
async def test_account_memory_templates_reach_live_prompts(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    merge,
    output_format,
    marker,
    monkeypatch,
):
    monkeypatch.setattr(get_openviking_config().memory, "extraction_output_format", output_format)
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    registry = MemoryTypeRegistry()
    base_description = registry.get("profile").description

    async def prompt_for(account, user, peer=None):
        snapshot = await resolve_account_memory_registry(fs, account, registry)
        ctx = RequestContext(user=UserIdentifier(account, user), role=Role.USER, actor_peer_id=peer)
        if merge:
            provider = PatchMergeContextProvider(
                memory_type="profile", patches=[], memory_registry=snapshot
            )
        else:
            provider = SessionExtractContextProvider(
                messages=[], ctx=ctx, viking_fs=fs, memory_registry=snapshot
            )
        provider._output_language = "en"
        provider.prefetch = AsyncMock(return_value=[])
        vlm = Mock(
            model="test-memory-templates",
            get_completion_async=AsyncMock(
                return_value="sdk.commit()" if output_format == "python" else '{"delete_ids":[]}'
            ),
        )
        isolation = MemoryIsolationHandler(
            ctx,
            provider.get_extract_context(),
            allowed_memory_types={"profile"},
            allowed_peer_ids={peer} if peer else None,
        )
        isolation.prepare_messages()
        provider._isolation_handler = isolation
        loop = ExtractLoop(
            vlm=vlm, viking_fs=fs, ctx=ctx, context_provider=provider, isolation_handler=isolation
        )
        operations, _ = await loop.run()
        assert not operations.has_errors()
        return vlm.get_completion_async.await_args.kwargs["messages"][0]["content"]

    initial = await prompt_for(account_id, "alice")
    # Account descriptions render through the same restricted schema path.
    body = {
        "description": "CUSTOM_ACCOUNT_SCOPE " + marker,
        "fields": [
            {
                "name": "content",
                "description": "ACCOUNT_FIELD " + marker + " {{ language }}",
            }
        ],
    }
    assert (await lightweight_admin_client.put(url, json=body, headers=headers)).status_code == 200
    for user, peer in (("alice", None), ("bob", None), ("bob", "customer")):
        prompt = await prompt_for(account_id, user, peer)
        assert "CUSTOM_ACCOUNT_SCOPE EN" in prompt
        assert "ACCOUNT_FIELD EN en" in prompt
    assert "CUSTOM_ACCOUNT_SCOPE" not in await prompt_for("other-account", "alice")
    assert registry.get("profile").description == base_description
    assert (await lightweight_admin_client.delete(url, headers=headers)).status_code == 200
    assert await prompt_for(account_id, "alice") == initial


async def test_account_memory_templates_commit_keeps_snapshot_through_file_write(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    from openviking.message import Message, TextPart
    from openviking.session.compressor_v3 import SessionCompressorV3
    from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOperations
    from openviking.session.memory.streaming_memory_updater import (
        StreamingMemoryUpdater,
        StreamingMemoryUpdaterConfig,
    )
    from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils

    account_id, headers = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/soul"
    template = {
        "description": "ACCOUNT_DESCRIPTION",
        "content_template": "# OLD_TEMPLATE\n{{ core_truths }}",
        "fields": [{"name": "core_truths", "description": "Business core values"}],
    }
    assert (
        await lightweight_admin_client.put(url, json=template, headers=headers)
    ).status_code == 200
    for module in (
        "openviking.session.compressor_v3",
        "openviking.session.memory.memory_updater",
        "openviking.session.memory.streaming_memory_updater",
        "openviking.storage.viking_fs",
    ):
        monkeypatch.setattr(f"{module}.get_viking_fs", lambda: fs)
    initialized = []

    async def initialize(registry, ctx, allowed_memory_types=None):
        initialized.append(registry.get("soul").filename_template)

    monkeypatch.setattr(MemoryTypeRegistry, "initialize_memory_files", initialize)
    # Deliberately retain a cached deployment registry: request snapshots must win.
    updater = StreamingMemoryUpdater(
        registry=MemoryTypeRegistry(),
        config=StreamingMemoryUpdaterConfig(max_operations_per_update=1),
    )
    monkeypatch.setattr(
        "openviking.session.compressor_v3.get_streaming_memory_updater",
        AsyncMock(return_value=updater),
    )
    ctx = RequestContext(user=UserIdentifier(account_id, "alice"), role=Role.USER)
    uri = "viking://user/alice/memories/soul.md"

    def orchestrator(**kwargs):
        provider = kwargs["context_provider"]
        assert provider.get_memory_schemas(ctx)[0].description == "ACCOUNT_DESCRIPTION"

        async def run():
            # A publish during the LLM call must not switch the writer's template.
            changed = {**template, "content_template": "# NEW_TEMPLATE\n{{ core_truths }}"}
            assert (
                await lightweight_admin_client.put(url, json=changed, headers=headers)
            ).status_code == 200
            return ResolvedOperations(
                delete_file_contents=[],
                errors=[],
                upsert_operations=[
                    ResolvedOperation(
                        memory_type="soul",
                        uris=[uri],
                        memory_fields={"core_truths": "Business fact"},
                    )
                ],
            ), []

        return Mock(run=run)

    vlm = Mock()
    resolver = Mock(get_vlm=AsyncMock(return_value=vlm))
    compressor = SessionCompressorV3(vikingdb=None, vlm_resolver=resolver)
    monkeypatch.setattr(compressor, "_get_or_create_react", orchestrator)
    try:
        await compressor._extract_user_memories(
            messages=[Message(id="m1", role="user", parts=[TextPart("Business fact")])],
            ctx=ctx,
            allowed_memory_types={"soul"},
        )
    finally:
        await updater.close()
    resolver.get_vlm.assert_awaited_once_with(account_id)
    assert initialized == ["soul.md"]
    content = MemoryFileUtils.read(fs.files[uri], uri=uri).content
    assert "# OLD_TEMPLATE" in content and "Business fact" in content
    assert "# NEW_TEMPLATE" not in content


async def test_account_memory_templates_write_failure_preserves_active_configuration(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    client = lightweight_admin_client
    assert (
        await client.put(url, json={"description": "Active"}, headers=headers)
    ).status_code == 200
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    original = fs.agfs._files[path]
    write = fs.agfs.write
    failed = False

    def fail_once(target, content, **kwargs):
        nonlocal failed
        if target.startswith(path + ".") and target.endswith(".tmp") and not failed:
            failed = True
            fs.agfs._files[target] = b"partial"
            raise OSError("simulated write failure")
        return write(target, content, **kwargs)

    monkeypatch.setattr(fs.agfs, "write", fail_once)
    with pytest.raises(OSError, match="simulated write failure"):
        await client.put(url, json={"description": "Unpublished"}, headers=headers)
    assert fs.agfs._files[path] == original
    assert (await client.get(url, headers=headers)).json()["result"]["effective"][
        "description"
    ] == "Active"


@pytest.fixture
def template_path_lock(
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, _ = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    lock = threading.Lock()

    def acquire(ctx, target, timeout_secs=0, owner_lease_ref=None):
        from openviking.storage.errors import LockAcquisitionError

        assert target == path
        assert ctx["account_id"] == account_id
        if not lock.acquire(timeout=timeout_secs):
            raise LockAcquisitionError("publication in progress")
        return {"lease_ref": "publication-test"}

    def release(ctx, lease):
        lock.release()

    monkeypatch.setattr(fs.agfs, "pathlock_acquire_exact", acquire)
    monkeypatch.setattr(fs.agfs, "pathlock_release", release)
    return lock


async def test_account_memory_templates_concurrent_publications_keep_both_types(
    lightweight_admin_client,
    template_account,
):
    account_id, headers = template_account
    root = f"/api/v1/admin/accounts/{account_id}/memory-templates"
    responses = await asyncio.gather(
        lightweight_admin_client.put(
            f"{root}/profile", json={"description": "Profile override"}, headers=headers
        ),
        lightweight_admin_client.put(
            f"{root}/events", json={"description": "Events override"}, headers=headers
        ),
    )
    assert [response.status_code for response in responses] == [200, 200]
    result = (await lightweight_admin_client.get(root, headers=headers)).json()["result"]
    effective = {item["memory_type"]: item["effective"] for item in result["templates"]}
    assert effective["profile"]["description"] == "Profile override"
    assert effective["events"]["description"] == "Events override"


async def test_account_memory_templates_read_does_not_wait_for_publication(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    template_path_lock,
    monkeypatch,
):
    account_id, headers = template_account
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    client = lightweight_admin_client
    assert (
        await client.put(url, json={"description": "Active"}, headers=headers)
    ).status_code == 200
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    acquiring = threading.Event()
    acquire = fs.agfs.pathlock_acquire_exact

    def observe_acquire(*args, **kwargs):
        acquiring.set()
        return acquire(*args, **kwargs)

    monkeypatch.setattr(fs.agfs, "pathlock_acquire_exact", observe_acquire)
    with template_path_lock:
        # A writer may be preparing a partial staging file, but the active path
        # remains a complete version and readers never request its lock.
        fs.agfs._files[path + ".test.tmp"] = b"partial"
        response = await asyncio.wait_for(client.get(url, headers=headers), timeout=1)
        assert not acquiring.is_set()
    assert response.status_code == 200, response.text
    assert response.json()["result"]["effective"]["description"] == "Active"


async def test_account_memory_templates_reject_oversized_serialized_config(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, headers = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    original = dict(fs.agfs._files)
    monkeypatch.setattr("openviking.session.memory.account_templates._MAX_CONFIG_BYTES", 100)
    response = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{account_id}/memory-templates/profile",
        json={"description": "A valid description"},
        headers=headers,
    )
    assert response.status_code == 400, response.text
    assert fs.agfs._files == original


async def test_account_memory_templates_read_rejects_corrupt_storage_but_writes_can_recover(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    account_id, headers = template_account
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    corrupt = b'{"invalid-json"'

    fs.agfs._files[path] = corrupt
    response = await lightweight_admin_client.get(url, headers=headers)
    assert response.status_code == 412, response.text
    assert response.json()["error"]["code"] == "FAILED_PRECONDITION"
    assert fs.agfs._files[path] == corrupt

    response = await lightweight_admin_client.put(
        url, headers=headers, json={"description": "Recovered"}
    )
    assert response.status_code == 200, response.text
    assert response.json()["result"]["effective"]["description"] == "Recovered"
    assert path + ".backup" not in fs.agfs._files

    fs.agfs._files[path] = corrupt
    response = await lightweight_admin_client.delete(url, headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["result"]["status"] == "system_default"
    assert path not in fs.agfs._files
    assert path + ".backup" not in fs.agfs._files


async def test_account_memory_templates_read_legacy_without_side_effect_then_migrate_on_put(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    legacy_path = legacy_account_memory_template_path(account_id, "profile")

    published = await client.put(url, headers=headers, json={"description": "Legacy"})
    assert published.status_code == 200, published.text
    original = fs.agfs._files.pop(path)
    fs.agfs._files[legacy_path] = original

    read = await client.get(url, headers=headers)
    assert read.status_code == 200, read.text
    assert read.json()["result"]["effective"]["description"] == "Legacy"
    assert path not in fs.agfs._files
    assert fs.agfs._files[legacy_path] == original

    migrated = await client.put(url, headers=headers, json=read.json()["result"]["effective"])
    assert migrated.status_code == 200, migrated.text
    assert migrated.json()["result"]["effective"]["description"] == "Legacy"
    assert path in fs.agfs._files
    assert legacy_path not in fs.agfs._files
    assert path + ".backup" not in fs.agfs._files


async def test_account_memory_templates_invalid_new_path_does_not_fallback_to_legacy(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    legacy_path = legacy_account_memory_template_path(account_id, "profile")

    published = await client.put(url, headers=headers, json={"description": "Legacy"})
    assert published.status_code == 200, published.text
    fs.agfs._files[legacy_path] = fs.agfs._files[path]
    fs.agfs._files[path] = b"invalid: ["

    response = await client.get(url, headers=headers)
    assert response.status_code == 412, response.text
    assert response.json()["error"]["code"] == "FAILED_PRECONDITION"


async def test_account_memory_templates_retry_cleans_legacy_after_published_migration(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    legacy_path = legacy_account_memory_template_path(account_id, "profile")

    published = await client.put(url, headers=headers, json={"description": "Legacy"})
    assert published.status_code == 200, published.text
    fs.agfs._files[legacy_path] = fs.agfs._files.pop(path)
    remove = fs.agfs.rm
    failed = False

    def fail_legacy_cleanup_once(target, **kwargs):
        nonlocal failed
        if target == legacy_path and not failed:
            failed = True
            raise OSError("legacy cleanup failed")
        return remove(target, **kwargs)

    monkeypatch.setattr(fs.agfs, "rm", fail_legacy_cleanup_once)
    response = await client.put(url, headers=headers, json={"description": "Current"})
    assert response.status_code == 412, response.text
    assert response.json()["error"]["details"] == {
        "published": True,
        "legacy_cleanup_pending": True,
        "retryable": True,
    }
    assert path in fs.agfs._files
    assert legacy_path in fs.agfs._files
    current = (await client.get(url, headers=headers)).json()["result"]
    assert current["effective"]["description"] == "Current"

    retry = await client.put(url, headers=headers, json={"description": "Current"})
    assert retry.status_code == 200, retry.text
    assert retry.json()["result"]["updated_at"] == current["updated_at"]
    assert legacy_path not in fs.agfs._files


async def test_account_memory_templates_reset_removes_legacy_before_current(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    monkeypatch,
):
    account_id, headers = template_account
    client = lightweight_admin_client
    url = f"/api/v1/admin/accounts/{account_id}/memory-templates/profile"
    fs = lightweight_admin_app.state.fake_service.viking_fs
    path = account_memory_template_path(account_id, "profile")
    legacy_path = legacy_account_memory_template_path(account_id, "profile")

    published = await client.put(url, headers=headers, json={"description": "Current"})
    assert published.status_code == 200, published.text
    current = fs.agfs._files[path]
    fs.agfs._files[legacy_path] = current
    remove = fs.agfs.rm
    removed = []
    failed = False

    def fail_legacy_cleanup_once(target, **kwargs):
        nonlocal failed
        removed.append(target)
        if target == legacy_path and not failed:
            failed = True
            raise OSError("legacy cleanup failed")
        return remove(target, **kwargs)

    monkeypatch.setattr(fs.agfs, "rm", fail_legacy_cleanup_once)
    response = await client.delete(url, headers=headers)
    assert response.status_code == 412, response.text
    assert response.json()["error"]["details"] == {
        "legacy_cleanup_pending": True,
        "retryable": True,
    }
    assert removed == [legacy_path]
    assert fs.agfs._files[path] == current
    assert fs.agfs._files[legacy_path] == current

    response = await client.delete(url, headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["result"]["status"] == "system_default"
    assert removed[-3:] == [legacy_path, path, path + ".backup"]
    assert path not in fs.agfs._files
    assert legacy_path not in fs.agfs._files
    assert path + ".backup" not in fs.agfs._files


async def test_create_account(
    admin_client: httpx.AsyncClient, admin_service: OpenVikingService, monkeypatch
):
    """ROOT provisioning applies account settings before initializing storage."""
    settings = {
        "embedding": {"max_retries": 5},
        "vectordb": {
            "backend": "vikingdb",
            "name": "account_context",
            "index_name": "default",
            "dimension": 1024,
            "vikingdb": {"host": "https://account.invalid"},
        },
    }
    adapter = Mock(mode="vikingdb", USE_CONTENT_FIELD=True)
    adapter.get.return_value = []
    adapter.get_collection.return_value.get_meta_data.return_value = {
        "Fields": [
            {"FieldName": name}
            for name in (
                "id",
                "uri",
                "account_id",
                "context_type",
                "abstract",
                "level",
                "user",
                "agent",
                "vector",
                "sparse_vector",
                "created_at",
                "updated_at",
            )
        ]
    }
    adapter.upsert.side_effect = lambda rows: [row["id"] for row in rows]
    factory = Mock(return_value=adapter)
    monkeypatch.setattr(
        "openviking.storage.viking_vector_index_backend.create_collection_adapter",
        factory,
    )
    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice", "settings": settings},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["result"]["account_id"] == acct
    assert body["result"]["admin_user_id"] == "alice"
    assert "user_key" in body["result"]

    ctx = RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN)
    assert await admin_service.viking_fs.abstract("viking://resources", ctx=ctx)
    assert await admin_service.viking_fs.abstract("viking://user", ctx=ctx)
    stored = await admin_client.get(
        f"/api/v1/admin/accounts/{acct}/configuration", headers=root_headers()
    )
    assert stored.json()["result"]["settings"] == settings
    effective = await admin_service.vector_config_resolver.resolve(acct)
    assert effective.dedicated_vectordb
    assert effective.vectordb.name == "account_context"
    assert effective.embedding.max_retries == 5
    assert factory.call_args.args[0].vikingdb.host == "https://account.invalid"
    adapter.create_collection.assert_not_called()


async def test_create_account_rolls_back_when_runtime_config_write_fails(
    admin_client: httpx.AsyncClient,
    admin_service: OpenVikingService,
    admin_app: FastAPI,
    monkeypatch: pytest.MonkeyPatch,
):
    """A post-registry initialization failure must not leave a half-created account."""
    acct = _uid()

    async def fail_patch(*args, **kwargs):
        raise OSError("runtime config unavailable")

    monkeypatch.setattr(
        admin_service.runtime_config_manager,
        "patch_account",
        fail_patch,
    )

    response = await admin_client.post(
        "/api/v1/admin/accounts",
        json={
            "account_id": acct,
            "admin_user_id": "alice",
            "settings": {"github": {"token": "account-token"}},
        },
        headers=root_headers(),
    )

    assert response.status_code == 500
    assert not any(
        item["account_id"] == acct for item in await admin_app.state.api_key_manager.list_accounts()
    )
    assert not await _agfs_exists(admin_service, f"/local/{acct}")


async def test_create_user_paths_accept_initial_user_config(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app: FastAPI,
):
    acct = _uid()
    viking_fs = lightweight_admin_app.state.fake_service.viking_fs

    resp = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={
            "account_id": acct,
            "admin_user_id": "alice",
            # Legacy uid-less spelling, normalized to the viking://~ home alias.
            "user_config": {"add_targets": {"resource_uri": "viking://user/resources/admin"}},
        },
        headers=root_headers(),
    )
    assert resp.status_code == 200, resp.text

    alice_settings = await read_user_add_targets(
        viking_fs,
        RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN),
    )
    assert alice_settings.resource_uri == "viking://user/alice/resources/admin"

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={
            "user_id": "bob",
            "role": "user",
            "user_config": {"add_targets": {"resource_uri": "viking://~/resources/bob"}},
        },
        headers=root_headers(),
    )
    assert resp.status_code == 200, resp.text

    bob_settings = await read_user_add_targets(
        viking_fs,
        RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER),
    )
    assert bob_settings.resource_uri == "viking://user/bob/resources/bob"


async def test_user_settings_preserve_policy_inheritance_backup_and_sparse_updates(
    lightweight_admin_client, lightweight_admin_app, monkeypatch
):
    import fakeredis.aioredis

    from openviking.ttl import wiring
    from openviking.ttl.runtime import DirectoryTTL
    from openviking_cli.utils.config.open_viking_config import set_openviking_config

    client = lightweight_admin_client
    acct = _uid()
    created = await client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert created.status_code == 200, created.text
    created = await client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={
            "user_id": "bob",
            "role": "user",
            "user_config": {"memory_policy": {"memory_types": ["profile"]}},
        },
        headers=root_headers(),
    )
    assert created.status_code == 200, created.text
    url = f"/api/v1/admin/accounts/{acct}/users/bob/settings"
    service = lightweight_admin_app.state.fake_service
    fs = service.viking_fs
    user_ctx = RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER)
    monkeypatch.setattr(wiring, "_adapter", None)
    before = dict(fs.files)
    rejected = await client.patch(url, json={"ttl": {"sessions": 7}}, headers=root_headers())
    assert rejected.status_code == 501 and fs.files == before

    engine = DirectoryTTL(resource_id="settings-contract", timezone_name="UTC")
    engine.bind_runtime(service, lightweight_admin_app.state.api_key_manager)
    engine.redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
    monkeypatch.setattr(wiring, "_adapter", engine)
    previous_config = get_openviking_config()
    try:
        await service.runtime_config_manager.patch_cluster({"ttl": {"global": 60, "sessions": 30}})
        configured = await client.patch(
            f"/api/v1/admin/accounts/{acct}/configuration",
            json={"settings": {"ttl": {"global": 45, "peer_events": 14}}},
            headers=root_headers(),
        )
        assert configured.status_code == 200, configured.text
        patched = await client.patch(
            url,
            json={
                "memory_policy": {"memory_types": ["experiences"]},
                "ttl": {"sessions": 7, "peer_events": 3, "user_events": "disabled"},
            },
            headers=root_headers(),
        )
        assert patched.status_code == 200, patched.text
        settings = (await client.get(url, headers=root_headers())).json()["result"]
        assert settings["ttl"] == {"sessions": 7, "peer_events": 3, "user_events": "disabled"}
        assert settings["memory_policy"]["memory_types"] == ["cases", "experiences", "trajectories"]
        persisted = await read_user_config(fs, user_ctx)
        assert persisted.ttl.sessions == 7
        assert persisted.memory_policy["memory_types"] == settings["memory_policy"]["memory_types"]
        backup = json.loads(fs.files[user_config_backup_uri(user_ctx)])
        assert backup["memory_policy"]["memory_types"] == ["profile"]

        first_peer = "viking://user/bob/peers/first/memories/events/2026/01/01"
        second_peer = "viking://user/bob/peers/second/memories/events/2026/01/01"
        user_event = "viking://user/bob/memories/events/2026/01/01"
        assert await engine.resolve_expires_at([first_peer, second_peer, user_event], user_ctx) == {
            first_peer: "2026-01-04T00:00:00Z",
            second_peer: "2026-01-04T00:00:00Z",
            user_event: None,
        }
        queried = await client.get(
            f"/api/v1/admin/accounts/{acct}/configuration",
            params={"path": "viking://user/bob/peers"},
            headers=root_headers(),
        )
        assert queried.status_code == 200 and queried.json()["result"]["effective_policy"] == 3

        writes_before_noop = len(fs.writes)
        noop = await client.patch(
            url, json={"memory_policy": persisted.memory_policy}, headers=root_headers()
        )
        assert noop.status_code == 200 and len(fs.writes) == writes_before_noop
        patched = await client.patch(
            url, json={"ttl": {"sessions": None, "peer_events": "disabled"}}, headers=root_headers()
        )
        assert patched.status_code == 200, patched.text
        assert patched.json()["result"]["ttl"] == {
            "peer_events": "disabled",
            "user_events": "disabled",
        }
        assert (await engine.policy(acct, "viking://user/bob/sessions")).days == 30
        assert not (await engine.policy(acct, first_peer)).enabled
        assert patched.json()["result"]["memory_policy"] == settings["memory_policy"]
        assert json.loads(fs.files[user_config_backup_uri(user_ctx)])["ttl"]["sessions"] == 7

        # Enabling retention must persist recovery intent before changing UserConfig.
        before = dict(fs.files)
        with monkeypatch.context() as failure:
            failure.setattr(engine, "client", AsyncMock(side_effect=OSError("Redis unavailable")))
            rejected = await client.patch(
                url, json={"ttl": {"user_events": 7}}, headers=root_headers()
            )
        assert rejected.status_code == 503 and fs.files == before
        cleared = await client.patch(url, json={"ttl": None}, headers=root_headers())
        assert cleared.status_code == 200, cleared.text
        assert cleared.json()["result"]["ttl"] is None
        assert cleared.json()["result"]["memory_policy"] == settings["memory_policy"]
        assert (await engine.policy(acct, first_peer)).days == 14

        lightweight_admin_app.state.config.user_config_defaults = UserConfig(
            memory_policy={"memory_types": ["events"]}
        )
        reset = await client.patch(url, json={"memory_policy": None}, headers=root_headers())
        assert reset.status_code == 200, reset.text
        assert reset.json()["result"]["memory_policy"]["memory_types"] == ["events"]
        assert (await read_user_config(fs, user_ctx)).memory_policy is None
        assert json.loads(fs.files[user_config_backup_uri(user_ctx)])["memory_policy"][
            "memory_types"
        ] == ["cases", "experiences", "trajectories"]
    finally:
        set_openviking_config(previous_config)
        await engine.aclose()


async def test_user_memory_policy_uses_server_default_without_user_override(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app: FastAPI,
):
    acct = _uid()
    lightweight_admin_app.state.config.user_config_defaults = UserConfig(
        memory_policy={"memory_types": ["profile"]}
    )
    create_account = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert create_account.status_code == 200, create_account.text

    get_settings = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users/alice/settings",
        headers=root_headers(),
    )
    assert get_settings.status_code == 200, get_settings.text
    assert get_settings.json()["result"]["memory_policy"] == {
        "self": {"enabled": True},
        "peer": {"enabled": True},
        "working_memory": {"enabled": False},
        "memory_types": ["profile"],
    }


async def test_create_user_paths_ignore_deprecated_agent_evolution_config(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app: FastAPI,
):
    acct = _uid()
    viking_fs = lightweight_admin_app.state.fake_service.viking_fs

    resp = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={
            "account_id": acct,
            "admin_user_id": "alice",
            "user_config": {"agent_evolution": {"enabled": True}},
        },
        headers=root_headers(),
    )
    assert resp.status_code == 200, resp.text

    alice_config = await read_user_config(
        viking_fs,
        RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN),
    )
    assert alice_config.agent_evolution.enabled is None

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={
            "user_id": "bob",
            "role": "user",
            "user_config": {"agent_evolution": {"enabled": False}},
        },
        headers=root_headers(),
    )
    assert resp.status_code == 200, resp.text

    bob_config = await read_user_config(
        viking_fs,
        RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER),
    )
    assert bob_config.agent_evolution.enabled is None


async def test_list_accounts(admin_client: httpx.AsyncClient):
    """ROOT can list all accounts."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.get("/api/v1/admin/accounts", headers=root_headers())
    assert resp.status_code == 200
    accounts = resp.json()["result"]
    account_ids = {a["account_id"] for a in accounts}
    assert "default" in account_ids
    assert acct in account_ids

    # `query` is a case-insensitive substring match on the account id.
    fragment = acct[:5].upper()  # "ACME_", proving the match ignores case
    resp = await admin_client.get(
        "/api/v1/admin/accounts",
        params={"query": fragment},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    queried_ids = {a["account_id"] for a in resp.json()["result"]}
    assert acct in queried_ids
    assert "default" not in queried_ids


async def test_list_users_for_default_account_without_users_file_returns_empty_list(
    lightweight_admin_client: httpx.AsyncClient,
):
    """The initialized default account may legitimately have no users.json."""
    resp = await lightweight_admin_client.get(
        "/api/v1/admin/accounts/default/users", headers=root_headers()
    )

    assert resp.status_code == 200, resp.text
    assert resp.json()["result"] == []


async def test_list_accounts_with_watcher_uses_memory(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app: FastAPI,
    monkeypatch: pytest.MonkeyPatch,
):
    """A running watcher keeps list requests on the in-memory fast path."""
    loop = asyncio.get_running_loop()
    watch_task = loop.create_future()

    async def _unexpected_read(_path: str):
        raise AssertionError("list accounts should not read AGFS while watcher is running")

    manager = lightweight_admin_app.state.api_key_manager
    manager._store._watch_task = watch_task
    monkeypatch.setattr(manager._store, "_read_json", _unexpected_read)
    try:
        resp = await lightweight_admin_client.get("/api/v1/admin/accounts", headers=root_headers())
        users_resp = await lightweight_admin_client.get(
            "/api/v1/admin/accounts/default/users", headers=root_headers()
        )
    finally:
        watch_task.cancel()

    assert resp.status_code == 200, resp.text
    assert users_resp.status_code == 200, users_resp.text


async def test_identity_settings_refreshes_a_stale_registry_on_demand(
    admin_client: httpx.AsyncClient,
    admin_app: FastAPI,
    admin_service: OpenVikingService,
):
    """Detail settings reads must not depend on a preceding list request."""
    writer = build_api_key_manager(
        root_key=ROOT_KEY,
        viking_fs=admin_service.viking_fs,
    )
    await writer.load()
    acct = _uid()

    await writer.ensure_trusted_identities({acct: {"trusted-user"}})

    account_settings = await admin_client.get(
        f"/api/v1/admin/accounts/{acct}/settings",
        headers=root_headers(),
    )
    assert account_settings.status_code == 200, account_settings.text

    await writer.ensure_trusted_identities({acct: {"trusted-user-2"}})

    user_settings = await admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users/trusted-user-2/settings",
        headers=root_headers(),
    )
    assert user_settings.status_code == 200, user_settings.text
    await writer.close()


@pytest.mark.parametrize("index_updates_immediately", [True, False])
async def test_delete_account(
    admin_client, admin_service, admin_app, monkeypatch, index_updates_immediately
):
    """Cleanup submits all IDs without depending on immediate query consistency."""
    from itertools import islice
    from types import SimpleNamespace

    from openviking.storage.expr import Eq
    from openviking.storage.queuefs.queue_manager import QueueManager
    from openviking.storage.vectordb_adapters.local_adapter import LocalCollectionAdapter
    from openviking.storage.viking_vector_index_backend import _SingleAccountBackend

    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    key = resp.json()["result"]["user_key"]
    path = f"/local/{acct}/resources/project/nested/file.md"
    await _agfs_write(admin_service, path, "project data")
    await _agfs_write(admin_service, "/local/other/resources/keep.md", "keep")
    old_task = await get_task_tracker().create(
        "session_commit", account_id=acct, user_id="alice", resource_id="old-session"
    )
    user_cleanup = await get_task_tracker().create(
        "user_delete", account_id=acct, user_id="alice", resource_id=f"{acct}/bob"
    )

    manager = admin_app.state.api_key_manager

    # Exercise the real filter-deletion loop with bounded in-memory I/O.
    rows = {str(i): {"id": str(i), "account_id": acct} for i in range(100_001)}
    rows["keep"] = {"id": "keep", "account_id": "other"}
    indexed_rows = rows.copy()
    deleted_ids = []
    adapter = LocalCollectionAdapter("context", "", "default")

    def delete_data(ids):
        assert 0 < len(ids) <= 100
        deleted_ids.extend(ids)
        for record_id in ids:
            rows.pop(record_id, None)

    adapter._collection = SimpleNamespace(delete_data=delete_data)
    scan_rows = rows if index_updates_immediately else indexed_rows
    adapter.query = lambda *, filter, limit, offset=0, **kwargs: list(
        islice(
            (row for row in scan_rows.values() if row[filter.field] == filter.value),
            offset,
            offset + limit,
        )
    )
    # Other read APIs may still expose data after delete requests succeed.
    adapter.get = lambda ids: [
        indexed_rows[record_id] for record_id in ids if record_id in indexed_rows
    ]
    adapter.count = lambda filter: sum(
        row[filter.field] == filter.value for row in indexed_rows.values()
    )
    vectors = admin_service.viking_fs.vector_store
    vectors._resolved_backends[acct] = _SingleAccountBackend(
        vectors._config, bound_account_id=acct, shared_adapter=adapter
    )
    original_delete = vectors.delete_account_data
    started, release = asyncio.Event(), asyncio.Event()

    async def fail_vectors(account_id, *, ctx):
        started.set()
        await release.wait()
        raise RuntimeError("injected vector failure")

    monkeypatch.setattr(vectors, "delete_account_data", fail_vectors)

    resp = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
    assert resp.status_code == 202
    result = resp.json()["result"]
    assert result["status"] == "deleting"
    task_id = result["task_id"]
    await asyncio.wait_for(started.wait(), 10)
    duplicate = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
    assert duplicate.json()["result"]["task_id"] == task_id
    denied = await admin_client.get("/api/v1/fs/ls?uri=viking://", headers={"X-API-Key": key})
    assert denied.status_code == 401
    conflict = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "new"},
        headers=root_headers(),
    )
    assert conflict.status_code == 409
    release.set()
    failed = await _wait_for_task(admin_client, task_id)
    assert failed["status"] == "failed"
    assert "injected vector failure" in failed["error"]
    assert await _agfs_exists(admin_service, path)
    assert (await manager.get_deletion(acct))["task_id"] == task_id

    retried = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
    retry_task_id = retried.json()["result"]["task_id"]
    assert retry_task_id != task_id
    assert (await _wait_for_task(admin_client, retry_task_id))["status"] == "failed"

    monkeypatch.setattr(vectors, "delete_account_data", original_delete)
    # Reconcile a durable fence whose previous process stopped before enqueue.
    retry = await manager.replace_deletion_task(
        acct,
        None,
        expected_task_id=retry_task_id,
        task_id=str(uuid.uuid4()),
        owner_account_id=SYSTEM_TASK_ACCOUNT_ID,
        owner_user_id=SYSTEM_TASK_USER_ID,
    )
    await admin_app.state.deletion_service.initialize()
    completed = await _wait_for_task(admin_client, retry["task_id"])
    assert completed["status"] == "completed", completed
    assert completed["result"] == {"deleted": True}
    assert set(rows) == {"keep"}
    assert len(deleted_ids) == len(set(deleted_ids)) == 100_001
    assert adapter.count(Eq("account_id", acct)) == 100_001
    assert adapter.get(deleted_ids[:100])
    assert not await _agfs_exists(admin_service, f"/local/{acct}")
    assert await _agfs_exists(admin_service, "/local/other/resources/keep.md")
    assert await manager.get_deletion(acct) is None
    assert not await manager.has_user(acct, "alice")
    assert await get_task_tracker().get(old_task.task_id, account_id=acct, user_id="alice") is None
    assert (
        await get_task_tracker().get(user_cleanup.task_id, account_id=acct, user_id="alice") is None
    )
    assert (await _wait_for_task(admin_client, task_id))["status"] == "failed"

    # Late cleanup deliveries are harmless after deletion, including when the
    # same account/user IDs have since been recreated.
    queue = admin_service._queue_manager.get_queue(QueueManager.DATA_CLEANUP)
    for recreated in (False, True):
        if recreated:
            replacement_key = await manager.create_account(acct, "bob")
            await _agfs_write(admin_service, path, "new data")
        late_task_id = str(uuid.uuid4())
        await get_task_tracker().create(
            "user_delete",
            task_id=late_task_id,
            resource_id=f"{acct}/bob",
            account_id=SYSTEM_TASK_ACCOUNT_ID,
            user_id=SYSTEM_TASK_USER_ID,
        )
        with bind_task_context(user_cleanup.task_id, acct, "alice"):
            with pytest.raises(TaskWorkRejected, match="unavailable"):
                await queue.enqueue(
                    {
                        "task_id": user_cleanup.task_id,
                        "account_id": acct,
                        "user_id": "alice",
                        "target": {"account_id": acct, "user_id": "bob"},
                    }
                )
        with bind_task_context(
            late_task_id,
            SYSTEM_TASK_ACCOUNT_ID,
            SYSTEM_TASK_USER_ID,
        ):
            await queue.enqueue(
                {
                    "task_id": late_task_id,
                    "account_id": SYSTEM_TASK_ACCOUNT_ID,
                    "user_id": SYSTEM_TASK_USER_ID,
                    "target": {"account_id": acct, "user_id": "bob"},
                }
            )
        skipped = await _wait_for_task(admin_client, late_task_id)
        assert skipped["status"] == "completed"
        assert skipped["result"] == {"deleted": not recreated, "stale": True}
        assert (
            await get_task_tracker().get(user_cleanup.task_id, account_id=acct, user_id="alice")
            is None
        )
        assert await _agfs_exists(admin_service, path) is recreated
        if recreated:
            assert (await manager.resolve_identity(replacement_key)).user_id == "bob"


async def test_delete_account_retries_cleanup_and_retires_ttl_callbacks(
    admin_client, admin_service, admin_app, monkeypatch
):
    import fakeredis.aioredis

    from openviking.scheduling.expiry.api import CallbackRequest, ItemIdentity
    from openviking.ttl import wiring
    from openviking.ttl.runtime import DirectoryTTL

    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    user_key = resp.json()["result"]["user_key"]
    engine = DirectoryTTL(resource_id="account-cleanup")
    engine.bind_runtime(admin_service, admin_app.state.api_key_manager)
    engine.redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
    scheduler = Mock(report=AsyncMock(), unregister=AsyncMock())
    engine.install_expiry(scheduler)
    monkeypatch.setattr(wiring, "_adapter", engine)
    prefix = engine.prefix(acct)
    other = engine.prefix("other") + "sessions"
    await engine.redis.zadd(prefix + "sessions", {"viking://user/alice/sessions/s": 1})
    await engine.redis.hset(prefix + "backfill:initial", "roots", "[]")
    await engine.redis.set(prefix + "backfill:initial:done", "1")
    await engine.redis.zadd(other, {"viking://user/alice/sessions/kept": 1})
    unlink = engine.redis.unlink
    monkeypatch.setattr(engine.redis, "unlink", AsyncMock(side_effect=OSError("Redis unavailable")))
    delete_config = AsyncMock(side_effect=OSError("provider unavailable"))
    monkeypatch.setattr(admin_service.runtime_config_manager, "delete_account", delete_config)
    try:
        resp = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
        assert resp.status_code == 202
        failed = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])
        assert failed["status"] == "failed" and "Redis unavailable" in failed["error"]
        assert await engine.redis.zcard(prefix + "sessions") == 1
        denied = await admin_client.get(
            "/api/v1/fs/ls?uri=viking://", headers={"X-API-Key": user_key}
        )
        assert denied.status_code == 401
        assert await admin_app.state.api_key_manager.get_deletion(acct) is not None
        conflict = await admin_client.post(
            "/api/v1/admin/accounts",
            json={"account_id": acct, "admin_user_id": "replacement"},
            headers=root_headers(),
        )
        assert conflict.status_code == 409

        monkeypatch.setattr(engine.redis, "unlink", unlink)
        retry = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
        failed = await _wait_for_task(admin_client, retry.json()["result"]["task_id"])
        assert failed["status"] == "failed" and "provider unavailable" in failed["error"]
        assert await admin_app.state.api_key_manager.get_deletion(acct) is not None
        delete_config.side_effect = None
        retry = await admin_client.delete(f"/api/v1/admin/accounts/{acct}", headers=root_headers())
        completed = await _wait_for_task(admin_client, retry.json()["result"]["task_id"])
        assert completed["status"] == "completed"
        assert await admin_app.state.api_key_manager.get_deletion(acct) is None
        assert delete_config.await_count == 2
        assert not [key async for key in engine.redis.scan_iter(match=prefix + "*")]
        assert await engine.redis.zcard(other) == 1

        # A delivery already in flight cannot revive maintenance for the deleted account.
        callback = CallbackRequest(ItemIdentity("ttl", acct, "_system", "maintenance"))
        assert (await engine.handle(callback)).reason == "account_deleted"
        scheduler.report.assert_not_awaited()
        assert not [key async for key in engine.redis.scan_iter(match=prefix + "*")]
    finally:
        await engine.aclose()


async def test_create_duplicate_account_fails(admin_client: httpx.AsyncClient):
    """Creating duplicate account should fail."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "bob"},
        headers=root_headers(),
    )
    assert resp.status_code == 409  # ALREADY_EXISTS


# ---- User CRUD ----


async def test_register_user(admin_client: httpx.AsyncClient):
    """ROOT can register a user in an account."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["result"]["user_id"] == "bob"
    assert "user_key" in body["result"]

    # Bob's key should work
    bob_key = body["result"]["user_key"]
    resp = await admin_client.get(
        "/api/v1/fs/ls?uri=viking://",
        headers={"X-API-Key": bob_key},
    )
    assert resp.status_code == 200


async def test_root_can_register_admin_role_user(
    lightweight_admin_client: httpx.AsyncClient,
):
    """ROOT can create an ADMIN user via register_user."""
    acct = _uid()
    await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob-admin", "role": "admin"},
        headers=root_headers(),
    )
    assert resp.status_code == 200

    admin_key = resp.json()["result"]["user_key"]
    list_users = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users",
        headers={"X-API-Key": admin_key},
    )
    assert list_users.status_code == 200


async def test_root_cannot_register_root_role_user(
    lightweight_admin_client: httpx.AsyncClient,
):
    """ROOT is the configured server identity, not an account user role."""
    acct = _uid()
    await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "mallory-root", "role": "root"},
        headers=root_headers(),
    )
    assert resp.status_code == 403


async def test_admin_can_register_user_in_own_account(admin_client: httpx.AsyncClient):
    """ADMIN can register users in their own account."""
    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = resp.json()["result"]["user_key"]

    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 200


async def test_admin_can_register_admin_role_user(
    lightweight_admin_client: httpx.AsyncClient,
):
    """ADMIN can create another ADMIN in the same account via register_user."""
    acct = _uid()
    resp = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = resp.json()["result"]["user_key"]

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "mallory-admin", "role": "admin"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 200

    admin_key = resp.json()["result"]["user_key"]
    list_users = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users",
        headers={"X-API-Key": admin_key},
    )
    assert list_users.status_code == 200


async def test_admin_cannot_register_root_role_user(
    lightweight_admin_client: httpx.AsyncClient,
):
    """ADMIN should not be able to mint a ROOT key via register_user."""
    acct = _uid()
    resp = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = resp.json()["result"]["user_key"]

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "mallory-root", "role": "root"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 403


async def test_admin_cannot_mint_root_key_that_reaches_root_only_endpoint(
    lightweight_admin_client: httpx.AsyncClient,
):
    """ADMIN registration must never yield a key that works on ROOT-only endpoints."""
    acct = _uid()
    resp = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = resp.json()["result"]["user_key"]

    resp = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "mallory-root", "role": "root"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 403
    result = resp.json().get("result") or {}
    assert "user_key" not in result

    mallory_key = result.get("user_key")
    if mallory_key:
        root_only = await lightweight_admin_client.get(
            "/api/v1/admin/accounts",
            headers={"X-API-Key": mallory_key},
        )
        assert root_only.status_code == 403


async def test_admin_cannot_register_user_in_other_account(admin_client: httpx.AsyncClient):
    """ADMIN cannot register users in another account."""
    acct = _uid()
    other = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = resp.json()["result"]["user_key"]

    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": other, "admin_user_id": "eve"},
        headers=root_headers(),
    )

    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{other}/users",
        json={"user_id": "bob", "role": "user"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 403


async def test_list_users(admin_client: httpx.AsyncClient):
    """ROOT can list users in an account."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=root_headers(),
    )
    resp = await admin_client.get(f"/api/v1/admin/accounts/{acct}/users", headers=root_headers())
    assert resp.status_code == 200
    users = resp.json()["result"]
    user_ids = {u["user_id"] for u in users}
    assert user_ids == {"alice", "bob"}


@pytest.mark.parametrize("include_summary", [False, True])
@pytest.mark.parametrize("include_credentials", [None, True, False])
async def test_user_list_credentials_follow_caller_role(
    lightweight_admin_client, lightweight_admin_app, include_summary, include_credentials
):
    manager = lightweight_admin_app.state.api_key_manager
    account = _uid()
    admin_key = await manager.create_account(account, "owner")
    keys = {"owner": admin_key}
    keys["alice"] = await manager.register_user(account, "alice")
    keys["manager"] = await manager.register_user(account, "manager", Role.ADMIN)
    params = {"include_summary": include_summary, "limit": 2, "page": 1}
    if include_credentials is not None:
        params["include_credentials"] = include_credentials
    url = f"/api/v1/admin/accounts/{account}/users"

    # Each ADMIN sees its own stored key in plaintext and only masked key_prefix
    # for every other user; ROOT sees every plaintext key.
    callers = [
        (admin_key, "owner", False),
        (keys["manager"], "manager", False),
        (keys["alice"], "alice", False),
        (ROOT_KEY, None, True),
    ]
    for caller_key, caller_id, is_root in callers:
        users = []
        for page in (1, 2):
            response = await lightweight_admin_client.get(
                url, params={**params, "page": page}, headers={"X-API-Key": caller_key}
            )
            assert response.status_code == 200
            result = response.json()["result"]
            if include_summary:
                assert result["total"] == result["account_total"] == 3
                if caller_id == "alice":
                    assert "key_count" not in result
                else:
                    assert result["key_count"] == 3
                result = result["users"]
            users.extend(result)
        assert len(users) == 3
        for user in users:
            key = keys[user["user_id"]]
            if caller_id == "alice" and user["user_id"] != caller_id:
                assert set(user) == {"user_id", "role"}
            elif include_credentials is False:
                assert user["api_key_available"] is True
                assert "api_key" not in user and "key_prefix" not in user
            elif is_root or user["user_id"] == caller_id:
                assert user["api_key"] == key
                assert "key_prefix" not in user
            else:
                account_part, user_part, secret = key.split(".")
                assert user["key_prefix"] == (
                    f"{account_part}.{user_part}.{'*' * (len(secret) - 4)}{secret[-4:]}"
                )
                assert "api_key" not in user
                assert key not in json.dumps(users)
                assert secret not in json.dumps(users)
        if not is_root and include_credentials is not False:
            payload = json.dumps(users)
            assert keys[caller_id] in payload
            for other_id, other_key in keys.items():
                if other_id != caller_id:
                    assert other_key not in payload
                    assert other_key.split(".")[2] not in payload
    assert (await manager.resolve_identity(keys["alice"])).user_id == "alice"
    response = await lightweight_admin_client.get(url, headers={"X-API-Key": keys["alice"]})
    assert response.status_code == 200


@pytest.mark.parametrize("seed", [None, "new-self-service-seed"])
async def test_user_can_rotate_only_their_own_key(
    lightweight_admin_client, lightweight_admin_app, seed
):
    manager = lightweight_admin_app.state.api_key_manager
    account = _uid()
    admin_key = await manager.create_account(account, "owner")
    old_key = await manager.register_user(account, "alice")
    await manager.create_account("other", "alice")
    headers = {"X-API-Key": old_key, "X-OpenViking-User": "owner", "X-OpenViking-Account": "other"}
    for target_account, target_user in [(account, "owner"), ("other", "alice")]:
        denied = await lightweight_admin_client.post(
            f"/api/v1/admin/accounts/{target_account}/users/{target_user}/key", headers=headers
        )
        assert denied.status_code == 403
    denied = await lightweight_admin_client.get(
        "/api/v1/admin/accounts/other/users", headers=headers
    )
    assert denied.status_code == 403
    response = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{account}/users/alice/key",
        headers=headers,
        json={"seed": seed} if seed else {},
    )
    assert response.status_code == 200
    new_key = response.json()["result"]["user_key"]
    assert new_key != old_key
    url = f"/api/v1/admin/accounts/{account}/users"
    assert (
        await lightweight_admin_client.get(url, headers={"X-API-Key": old_key})
    ).status_code == 401
    current = await lightweight_admin_client.get(url, headers={"X-API-Key": new_key})
    assert current.status_code == 200
    assert current.json()["result"][1]["api_key"] == new_key
    assert (await manager.resolve_identity(admin_key)).role == Role.ADMIN


@pytest.mark.parametrize(
    "auth_mode,from_oauth",
    [("api_key", True), ("oidc", False), ("ldap", False), ("trusted", False)],
)
async def test_user_other_auth_cannot_disclose_or_rotate_personal_key(
    lightweight_admin_client, lightweight_admin_app, auth_mode, from_oauth
):
    from openviking.server.auth import get_request_context

    manager = lightweight_admin_app.state.api_key_manager
    account = _uid()
    await manager.create_account(account, "owner")
    key = await manager.register_user(account, "alice")
    lightweight_admin_app.state.config = lightweight_admin_app.state.config.model_copy(
        update={"auth_mode": auth_mode}
    )
    lightweight_admin_app.dependency_overrides[get_request_context] = lambda: RequestContext(
        UserIdentifier(account, "alice"), Role(Role.USER), from_oauth=from_oauth, api_key="identity-token"
    )
    response = await lightweight_admin_client.get(f"/api/v1/admin/accounts/{account}/users")
    assert response.status_code == 200
    assert all(set(row) == {"user_id", "role"} for row in response.json()["result"])
    response = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{account}/users/alice/key"
    )
    assert response.status_code == 403
    assert (await manager.resolve_identity(key)).user_id == "alice"


async def test_in_flight_user_rotation_cannot_overwrite_admin_reset(
    lightweight_admin_client, lightweight_admin_app, monkeypatch
):
    manager = lightweight_admin_app.state.api_key_manager
    account = _uid()
    await manager.create_account(account, "owner")
    old_key = await manager.register_user(account, "alice")
    authenticated = asyncio.Event()
    resume = asyncio.Event()
    regenerate = manager.regenerate_key

    async def pause_user_rotation(*args, **kwargs):
        if kwargs.get("expected_api_key") == old_key:
            authenticated.set()
            await resume.wait()
        return await regenerate(*args, **kwargs)

    monkeypatch.setattr(manager, "regenerate_key", pause_user_rotation)
    path = f"/api/v1/admin/accounts/{account}/users/alice/key"
    pending = asyncio.create_task(
        lightweight_admin_client.post(path, headers={"X-API-Key": old_key})
    )
    try:
        await asyncio.wait_for(authenticated.wait(), timeout=5)
        reset = await lightweight_admin_client.post(path, headers={"X-API-Key": ROOT_KEY})
        assert reset.status_code == 200
        reset_key = reset.json()["result"]["user_key"]
    finally:
        resume.set()
        response = await asyncio.wait_for(pending, timeout=5)
    assert response.status_code == 401
    url = f"/api/v1/admin/accounts/{account}/users"
    assert (await lightweight_admin_client.get(url, headers={"X-API-Key": reset_key})).status_code == 200
    assert (await lightweight_admin_client.get(url, headers={"X-API-Key": old_key})).status_code == 401


@pytest.mark.parametrize(
    "key,expected",
    [
        ("YWNtZQ.YWxpY2U.abcdefghijklmnop", "YWNtZQ.YWxpY2U.************mnop"),
        ("YWNtZQ.YWxpY2U.abcdefgh", "YWNtZQ.YWxpY2U.****efgh"),
        ("YWNtZQ.YWxpY2U.abcde", "YWNtZQ.YWxpY2U.*bcde"),
        ("YWNtZQ.YWxpY2U.abcd", "YWNtZQ.YWxpY2U.****"),
        ("YWNtZQ.YWxpY2U.a", "YWNtZQ.YWxpY2U.*"),
        ("legacy-secret", "*************"),
        ("two.parts", "*********"),
        ("abcd", "****"),
        ("a", "*"),
    ],
)
async def test_user_key_mask_handles_malformed_and_short_keys(key, expected):
    from openviking.server.api_keys import APIKeyManager

    store = Mock()
    store.list_users_page = AsyncMock(
        return_value={
            "users": [
                {"user_id": "alice", "api_key": key},
                {"user_id": "hashed", "key_prefix": "existing-prefix"},
                {"user_id": "keyless"},
            ],
            "key_count": 2,
        }
    )
    result = await APIKeyManager("root", store).list_users_page("acme", mask_keys=True)
    assert result["users"] == [
        {"user_id": "alice", "key_prefix": expected},
        {"user_id": "hashed", "key_prefix": "existing-prefix"},
        {"user_id": "keyless"},
    ]
    assert result["key_count"] == 2
    store.list_users_page.assert_awaited_once_with("acme")


async def test_user_key_mask_reveals_only_the_viewers_own_key():
    from openviking.server.api_keys import APIKeyManager
    from openviking.server.api_keys.key_mgr import generate_api_key, mask_api_key

    alice_key = generate_api_key("acme", "alice")
    bob_key = generate_api_key("acme", "bob")
    other_alice_key = generate_api_key("other", "alice")
    rows = {
        "users": [
            {"user_id": "alice", "api_key": alice_key},
            {"user_id": "bob", "api_key": bob_key},
            # Stored key that does not belong to the row's declared identity.
            {"user_id": "carol", "api_key": other_alice_key},
            {"user_id": "hashed", "key_prefix": "existing-prefix"},
        ],
        "key_count": 3,
    }

    def store_with_rows():
        store = Mock()
        store.list_users_page = AsyncMock(return_value=deepcopy(rows))
        return store

    # Matching viewer: only the viewer's own row stays plaintext.
    result = await APIKeyManager("root", store_with_rows()).list_users_page(
        "acme", mask_keys=True, viewer_account_id="acme", viewer_user_id="alice"
    )
    assert result["users"] == [
        {"user_id": "alice", "api_key": alice_key},
        {"user_id": "bob", "key_prefix": mask_api_key(bob_key)},
        {"user_id": "carol", "key_prefix": mask_api_key(other_alice_key)},
        {"user_id": "hashed", "key_prefix": "existing-prefix"},
    ]

    # Account mismatch suppresses the plaintext reveal.
    result = await APIKeyManager("root", store_with_rows()).list_users_page(
        "acme", mask_keys=True, viewer_account_id="other", viewer_user_id="alice"
    )
    assert result["users"][0] == {"user_id": "alice", "key_prefix": mask_api_key(alice_key)}

    # User-only mismatch (row belongs to another account's identity) never reveals.
    result = await APIKeyManager("root", store_with_rows()).list_users_page(
        "acme", mask_keys=True, viewer_account_id="acme", viewer_user_id="carol"
    )
    assert result["users"][2] == {
        "user_id": "carol",
        "key_prefix": mask_api_key(other_alice_key),
    }

    # Without viewer identity everything is masked, including the caller's row.
    result = await APIKeyManager("root", store_with_rows()).list_users_page("acme", mask_keys=True)
    assert result["users"][0] == {"user_id": "alice", "key_prefix": mask_api_key(alice_key)}


async def test_user_list_hides_other_prefixes_and_mismatched_keys():
    from openviking.server.api_keys import APIKeyManager, generate_api_key

    store = Mock()
    store.list_users_page = AsyncMock(
        return_value={
            "users": [
                {
                    "user_id": "alice",
                    "api_key": generate_api_key("other", "alice"),
                    "key_prefix": "other-prefix",
                },
                {"user_id": "hashed", "key_prefix": "sensitive-prefix"},
            ],
            "key_count": 2,
        }
    )
    page = await APIKeyManager("root", store).list_users_page(
        "acme", hide_other_keys=True, viewer_account_id="acme", viewer_user_id="alice"
    )
    assert page["users"] == [{"user_id": "alice"}, {"user_id": "hashed"}]


async def test_remove_user(
    admin_client: httpx.AsyncClient,
    admin_service: OpenVikingService,
    admin_app: FastAPI,
    monkeypatch,
):
    """Deletion revokes the user and removes only their private data, uploads, tasks,
    and embedded gateway state."""
    import openviking_gateway.app as gateway_module

    gateway = object()
    delete_gateway_data = AsyncMock()
    monkeypatch.setattr(gateway_module, "delete_data", delete_gateway_data)
    monkeypatch.setattr(admin_app.state.deletion_service, "_gateway_app", gateway)
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=root_headers(),
    )
    bob_key = resp.json()["result"]["user_key"]
    bob_ctx = RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER)
    private_uri = "viking://user/bob/memories/private.md"
    await admin_service.viking_fs.write_file(private_uri, "private", ctx=bob_ctx)
    alice_upload_uri = "viking://upload/1800000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    bob_upload_uri = "viking://upload/1800000000000-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
    upload_ctx = RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ROOT)
    for upload_uri, user_id in ((alice_upload_uri, "alice"), (bob_upload_uri, "bob")):
        await admin_service.viking_fs.write_file(
            f"{upload_uri}/meta",
            json.dumps({"account": acct, "user": user_id}),
            ctx=upload_ctx,
        )
    bob_task = await get_task_tracker().create(
        "session_commit",
        resource_id="bob-session",
        account_id=acct,
        user_id="bob",
    )
    resp = await admin_client.delete(
        f"/api/v1/admin/accounts/{acct}/users/bob", headers=root_headers()
    )
    assert resp.status_code == 202
    task_id = resp.json()["result"]["task_id"]

    # The fence invalidates Bob before background cleanup finishes.
    resp = await admin_client.get(
        "/api/v1/fs/ls?uri=viking://",
        headers={"X-API-Key": bob_key},
    )
    assert resp.status_code == 401

    deletion_task = await _wait_for_task(admin_client, task_id)
    assert deletion_task["status"] == "completed"
    assert not await admin_service.viking_fs.exists(private_uri, ctx=bob_ctx)
    assert not await admin_service.viking_fs.exists(bob_upload_uri, ctx=upload_ctx)
    assert await admin_service.viking_fs.exists(alice_upload_uri, ctx=upload_ctx)
    assert not await admin_app.state.api_key_manager.has_user(acct, "bob")
    delete_gateway_data.assert_awaited_once_with(gateway, acct, "bob")
    assert (
        await get_task_tracker().get(
            bob_task.task_id,
            account_id=acct,
            user_id="bob",
        )
        is None
    )

    missing = await admin_client.delete(
        f"/api/v1/admin/accounts/{acct}/users/bob",
        headers=root_headers(),
    )
    assert missing.status_code == 404


# ---- Role management ----


@pytest.mark.parametrize("actor_role", [Role.ROOT, Role.ADMIN])
@pytest.mark.parametrize(
    ("initial_role", "requested_role", "new_role"),
    [
        (Role.USER, "admin", Role.ADMIN),
        (Role.USER, "Admin", Role.ADMIN),
        (Role.USER, "ADMIN", Role.ADMIN),
        (Role.ADMIN, "user", Role.USER),
        (Role.ADMIN, "User", Role.USER),
        (Role.ADMIN, "USER", Role.USER),
    ],
)
async def test_root_or_admin_can_set_user_role(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app,
    actor_role: str,
    initial_role: str,
    requested_role: str,
    new_role: str,
):
    """ROOT and ADMIN can promote and demote account users without rotating keys."""
    acct = _uid()
    create_account = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    alice_key = create_account.json()["result"]["user_key"]
    create_user = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": initial_role},
        headers=root_headers(),
    )
    bob_key = create_user.json()["result"]["user_key"]

    resp = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{acct}/users/bob/role",
        json={"role": requested_role},
        headers=root_headers() if actor_role == Role.ROOT else {"X-API-Key": alice_key},
    )
    assert resp.status_code == 200
    assert resp.json()["result"] == {
        "account_id": acct,
        "user_id": "bob",
        "role": new_role,
    }
    manager = lightweight_admin_app.state.api_key_manager
    assert (await manager.get_user(acct, "bob"))["role"] == new_role
    assert (await manager.resolve_identity(bob_key)).role == new_role

    register_user = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "charlie", "role": "user"},
        headers={"X-API-Key": bob_key},
    )
    assert register_user.status_code == (200 if new_role == Role.ADMIN else 403)


@pytest.mark.parametrize("actor_role", [Role.ROOT, Role.ADMIN])
@pytest.mark.parametrize("new_role", [Role.ROOT, "ROOT", "global", "Global", "invalid"])
async def test_set_user_role_rejects_unsupported_roles(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app,
    actor_role: str,
    new_role: str,
):
    manager = lightweight_admin_app.state.api_key_manager
    acct = _uid()
    alice_key = await manager.create_account(acct, "alice")
    bob_key = await manager.register_user(acct, "bob", Role.ADMIN)

    resp = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{acct}/users/bob/role",
        json={"role": new_role},
        headers=root_headers() if actor_role == Role.ROOT else {"X-API-Key": alice_key},
    )
    assert resp.status_code == 400
    assert resp.json()["error"]["code"] == "INVALID_ARGUMENT"
    assert (await manager.resolve_identity(bob_key)).role == Role.ADMIN


@pytest.mark.parametrize("actor_role", [Role.USER, Role.ADMIN])
@pytest.mark.parametrize("new_role", [Role.USER, Role.ADMIN])
async def test_set_user_role_rejects_unauthorized_callers(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app,
    actor_role: str,
    new_role: str,
):
    """USER cannot change roles; ADMIN cannot change another account's roles."""
    manager = lightweight_admin_app.state.api_key_manager
    acct = _uid()
    await manager.create_account(acct, "alice")
    initial_role = Role.ADMIN if new_role == Role.USER else Role.USER
    bob_key = await manager.register_user(acct, "bob", initial_role)
    if actor_role == Role.ADMIN:
        actor_key = await manager.create_account(_uid(), "other-admin")
    else:
        actor_key = await manager.register_user(acct, "charlie", Role.USER)

    resp = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{acct}/users/bob/role",
        json={"role": new_role},
        headers={"X-API-Key": actor_key},
    )
    assert resp.status_code == 403
    assert (await manager.resolve_identity(bob_key)).role == initial_role


async def test_admin_can_demote_self_and_loses_role_management_access(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app,
):
    manager = lightweight_admin_app.state.api_key_manager
    acct = _uid()
    alice_key = await manager.create_account(acct, "alice")
    await manager.register_user(acct, "bob", Role.ADMIN)

    resp = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{acct}/users/alice/role",
        json={"role": "user"},
        headers={"X-API-Key": alice_key},
    )
    assert resp.status_code == 200
    assert (await manager.resolve_identity(alice_key)).role == Role.USER

    restore_role = await lightweight_admin_client.put(
        f"/api/v1/admin/accounts/{acct}/users/alice/role",
        json={"role": "admin"},
        headers={"X-API-Key": alice_key},
    )
    assert restore_role.status_code == 403


async def test_regenerate_key(admin_client: httpx.AsyncClient):
    """ROOT can regenerate a user's key."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=root_headers(),
    )
    old_key = resp.json()["result"]["user_key"]

    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users/bob/key",
        headers=root_headers(),
    )
    assert resp.status_code == 200
    new_key = resp.json()["result"]["user_key"]
    assert new_key != old_key

    # Old key invalid
    resp = await admin_client.get(
        "/api/v1/fs/ls?uri=viking://",
        headers={"X-API-Key": old_key},
    )
    assert resp.status_code == 401

    # New key valid
    resp = await admin_client.get(
        "/api/v1/fs/ls?uri=viking://",
        headers={"X-API-Key": new_key},
    )
    assert resp.status_code == 200


async def test_seeded_admin_key_endpoints(admin_client: httpx.AsyncClient):
    from openviking.server.api_keys import parse_api_key

    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice", "seed": "admin-seed"},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    admin_key = resp.json()["result"]["user_key"]
    account_id, user_id, secret = parse_api_key(admin_key)
    assert account_id == acct
    assert user_id == "alice"
    assert secret == _seed_secret("alice", "admin-seed")

    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user", "seed": "bob-seed"},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    old_key = resp.json()["result"]["user_key"]
    _, _, old_secret = parse_api_key(old_key)
    assert old_secret == _seed_secret("bob", "bob-seed")

    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users/bob/key",
        json={"seed": "bob-new-seed"},
        headers=root_headers(),
    )
    assert resp.status_code == 200
    new_key = resp.json()["result"]["user_key"]
    _, _, new_secret = parse_api_key(new_key)
    assert new_secret == _seed_secret("bob", "bob-new-seed")
    assert new_key != old_key

    resp = await admin_client.get(
        "/api/v1/fs/ls?uri=viking://",
        headers={"X-API-Key": old_key},
    )
    assert resp.status_code == 401


async def test_empty_seed_rejected(admin_client: httpx.AsyncClient):
    acct = _uid()
    resp = await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice", "seed": ""},
        headers=root_headers(),
    )
    assert resp.status_code == 400


# ---- Permission guard ----


async def test_user_role_cannot_register_users(admin_client: httpx.AsyncClient):
    """USER self-service does not grant user-management privileges."""
    acct = _uid()
    await admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=root_headers(),
    )
    bob_key = resp.json()["result"]["user_key"]

    # USER cannot register users
    resp = await admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "charlie", "role": "user"},
        headers={"X-API-Key": bob_key},
    )
    assert resp.status_code == 403


async def test_no_auth_admin_api_returns_401(admin_client: httpx.AsyncClient):
    """Admin API without key should return 401."""
    resp = await admin_client.get("/api/v1/admin/accounts")
    assert resp.status_code == 401


async def test_migration_endpoint_is_root_only_and_unsupported(
    lightweight_admin_app, lightweight_admin_client
):
    """The reserved endpoint rejects migration without relaxing ROOT authentication."""
    from openviking.server.auth import get_request_context

    url = "/api/v1/admin/migrate"
    response = await lightweight_admin_client.post(url)
    assert response.status_code == 401

    for payload in (None, {"action": "migrate"}, {"action": "cleanup"}):
        response = await lightweight_admin_client.post(url, headers=root_headers(), json=payload)
        assert response.status_code == 400
        body = response.json()
        assert body["status"] == "error"
        assert body["error"]["code"] == "INVALID_ARGUMENT"
        assert body["error"]["message"] == "Data migration is not currently supported."
        assert body.get("result") is None

    for role in (Role.ADMIN, Role.USER):
        lightweight_admin_app.dependency_overrides[get_request_context] = lambda role=role: (
            RequestContext(user=UserIdentifier("default", "default"), role=role)
        )
        response = await lightweight_admin_client.post(url)
        assert response.status_code == 403


async def test_session_storage_uses_canonical_uri(
    admin_service: OpenVikingService,
):
    """Canonical session URIs can read existing session storage."""
    ctx = RequestContext(user=UserIdentifier("default", "admin_user"), role=Role.USER)
    await _agfs_write(
        admin_service,
        "/local/default/session/old-session/messages.jsonl",
        '{"role":"user"}\n',
    )
    await _agfs_write(
        admin_service,
        "/local/default/session/old-session/.meta.json",
        '{"created_by_user_id":"admin_user"}',
    )

    assert (
        await admin_service.viking_fs.read_file(
            "viking://user/admin_user/sessions/old-session/messages.jsonl",
            ctx=ctx,
        )
        == '{"role":"user"}\n'
    )


@pytest_asyncio.fixture(scope="function")
async def trusted_admin_app(admin_service):
    from openviking.server.auth.plugins import TrustedAuthPlugin
    from openviking.server.auth.registry import get_registry

    config = ServerConfig(
        auth_mode="trusted",
        root_api_key=ROOT_KEY,
        trusted_identity_flush_interval_seconds=0,
    )
    app = create_app(config=config, service=admin_service)
    set_service(admin_service)

    # Initialize the plugin directly because the ASGI transport does not run lifespan.
    registry = get_registry()
    if registry.get("trusted") is None:
        registry.register(TrustedAuthPlugin)
    app.state.auth_plugin = registry.get("trusted")()
    await app.state.auth_plugin.initialize(app, admin_service, config)

    manager = app.state.api_key_manager
    if await manager.get_account("platform") is None:
        await manager.create_account("platform", "gateway-admin")

    return app


@pytest_asyncio.fixture(scope="function")
async def trusted_admin_client(trusted_admin_app):
    transport = httpx.ASGITransport(app=trusted_admin_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
        yield c


async def test_trusted_mode_root_can_create_account(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted ROOT requests should be able to create accounts."""
    acct = _uid()
    resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={
            "account_id": acct,
            "admin_user_id": "alice",
        },
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=True,
        ),
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["result"]["account_id"] == acct
    assert body["result"]["admin_user_id"] == "alice"
    assert "user_key" not in body["result"]
    listed = await trusted_admin_client.get(
        "/api/v1/admin/accounts",
        headers=trusted_headers(account="platform", user="gateway-admin", include_api_key=True),
    )
    assert listed.status_code == 200
    account = next(item for item in listed.json()["result"] if item["account_id"] == acct)
    assert set(account) == {"account_id", "created_at", "user_count", "status"}
    assert account["status"] == "active"
    assert account["user_count"] == 1


async def test_trusted_mode_admin_can_register_user_in_own_account(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted ADMIN requests should be able to manage users in their own account."""
    acct = _uid()
    create_resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=True,
        ),
    )
    assert create_resp.status_code == 200

    resp = await trusted_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=trusted_headers(
            account=acct,
            user="alice",
            include_api_key=True,
        ),
    )
    assert resp.status_code == 200
    assert resp.json()["result"]["account_id"] == acct
    assert resp.json()["result"]["user_id"] == "bob"
    assert "user_key" not in resp.json()["result"]

    users = await trusted_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users",
        params={"include_credentials": "false"},
        headers=trusted_headers(account=acct, user="alice", include_api_key=True),
    )
    assert users.status_code == 200
    assert all(user["api_key_available"] is False for user in users.json()["result"])

    rotated = await trusted_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users/bob/key",
        headers=root_headers(),
    )
    assert rotated.status_code == 412
    assert rotated.json()["error"]["code"] == "FAILED_PRECONDITION"


async def test_trusted_mode_admin_can_list_users_with_account_only_in_url(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted ADMIN requests may omit X-OpenViking-Account when the URL already provides it."""
    acct = _uid()
    create_resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=True,
        ),
    )
    assert create_resp.status_code == 200

    resp = await trusted_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users",
        headers={
            "X-API-Key": ROOT_KEY,
            "X-OpenViking-User": "alice",
            "X-OpenViking-Account": acct,
        },
    )
    assert resp.status_code == 200
    assert any(user["user_id"] == "alice" for user in resp.json()["result"])


async def test_trusted_mode_admin_can_list_users_without_account_or_user_headers(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted admin routes may omit caller account/user when the route itself identifies the target."""
    acct = _uid()
    create_resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=True,
        ),
    )
    assert create_resp.status_code == 200

    resp = await trusted_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users",
        headers={"X-API-Key": ROOT_KEY},
    )
    assert resp.status_code == 200
    assert any(user["user_id"] == "alice" for user in resp.json()["result"])


async def test_trusted_mode_admin_cannot_register_user_in_other_account(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted ADMIN requests should reject conflicting account identity."""
    acct = _uid()
    other = _uid()
    for account_id, admin_user_id in ((acct, "alice"), (other, "eve")):
        create_resp = await trusted_admin_client.post(
            "/api/v1/admin/accounts",
            json={"account_id": account_id, "admin_user_id": admin_user_id},
            headers=trusted_headers(
                account="platform",
                user="gateway-admin",
                include_api_key=True,
            ),
        )
        assert create_resp.status_code == 200

    resp = await trusted_admin_client.post(
        f"/api/v1/admin/accounts/{other}/users",
        json={"user_id": "bob", "role": "user"},
        headers=trusted_headers(
            account=acct,
            user="alice",
            include_api_key=True,
        ),
    )
    assert resp.status_code == 400
    assert resp.json()["error"]["code"] == "INVALID_ARGUMENT"


async def test_trusted_mode_admin_api_uses_trusted_gateway_identity(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted admin routes use the trusted gateway identity instead of tenant user role."""
    acct = _uid()
    manager = trusted_admin_app.state.api_key_manager
    create_resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "alice"},
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=True,
        ),
    )
    assert create_resp.status_code == 200

    # Change alice to USER role
    await manager.set_role(acct, "alice", "user")

    resp = await trusted_admin_client.post(
        f"/api/v1/admin/accounts/{acct}/users",
        json={"user_id": "bob", "role": "user"},
        headers=trusted_headers(
            account=acct,
            user="alice",
            include_api_key=True,
        ),
    )
    assert resp.status_code == 200
    assert resp.json()["result"]["account_id"] == acct
    assert resp.json()["result"]["user_id"] == "bob"
    assert "user_key" not in resp.json()["result"]


async def test_trusted_mode_requires_matching_api_key_for_admin_api(
    trusted_admin_client: httpx.AsyncClient,
    trusted_admin_app,
):
    """Trusted admin requests should require the configured server API key when present."""
    resp = await trusted_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": _uid(), "admin_user_id": "alice"},
        headers=trusted_headers(
            account="platform",
            user="gateway-admin",
            include_api_key=False,
        ),
    )
    assert resp.status_code == 401


async def test_user_page_summary_and_search_preserve_legacy_response(
    lightweight_admin_client: httpx.AsyncClient,
    lightweight_admin_app: FastAPI,
):
    acct = _uid()
    created = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "owner"},
        headers=root_headers(),
    )
    assert created.status_code == 200
    manager = lightweight_admin_app.state.api_key_manager
    for index in range(1, 113):
        last_key = await manager.register_user(
            acct, f"user-{index}", Role.ADMIN if index == 112 else Role.USER
        )
    await manager.register_user(acct, "deleting-user", Role.ADMIN)
    await manager.begin_deletion(
        acct, "deleting-user", task_id="delete", owner_account_id=acct, owner_user_id="owner"
    )
    url = f"/api/v1/admin/accounts/{acct}/users"

    response = await lightweight_admin_client.get(
        url, params={"include_summary": True, "limit": 20, "page": 6}, headers=root_headers()
    )
    assert response.status_code == 200, response.text
    result = response.json()["result"]
    assert len(result["users"]) == 13
    assert result["users"][-1]["user_id"] == "user-112"
    assert result["total"] == result["account_total"] == result["key_count"] == 113
    assert result["manager_count"] == 2

    response = await lightweight_admin_client.get(
        url,
        params={"include_summary": True, "limit": 20, "query": " UsEr-112 "},
        headers=root_headers(),
    )
    result = response.json()["result"]
    assert result["total"] == 1
    assert result["users"][0]["user_id"] == "user-112"
    assert result["account_total"] == 113
    assert result["manager_count"] == 2

    response = await lightweight_admin_client.get(
        url,
        params={"include_summary": True, "limit": 20, "query": "missing"},
        headers=root_headers(),
    )
    assert response.json()["result"]["total"] == 0
    assert response.json()["result"]["users"] == []
    assert response.json()["result"]["account_total"] == 113

    response = await lightweight_admin_client.get(url, headers=root_headers())
    assert isinstance(response.json()["result"], list)
    assert len(response.json()["result"]) == 113
    response = await lightweight_admin_client.get(
        url,
        params={"limit": 1, "page": 2, "name": "user-*", "role": "user"},
        headers=root_headers(),
    )
    assert response.json()["result"][0]["user_id"] == "user-2"

    hidden = await manager.list_users_page(acct, expose_key=False, limit=1)
    assert hidden["key_count"] == 0
    assert "api_key" not in hidden["users"][0]
    assert "key_prefix" not in hidden["users"][0]

    # MCP exposes an account directory, not the admin response or credentials.
    from types import SimpleNamespace

    import openviking.server.mcp_endpoint as mcp_endpoint
    from openviking_cli.exceptions import PermissionDeniedError

    await manager.create_group(acct, "engineering")
    await manager.add_group_member(acct, "engineering", "user-1")
    request = FastAPIRequest({"type": "http", "app": lightweight_admin_app})
    context = SimpleNamespace(request_context=SimpleNamespace(request=request))
    for role in (Role.USER, Role.ADMIN, Role.ROOT):
        identity = RequestContext(UserIdentifier(acct, "user-1"), role, api_key="personal-key")
        token = mcp_endpoint._mcp_ctx.set(identity)
        try:
            directory = await mcp_endpoint.list_users(context, query="user-112")
            assert directory == {"users": [{"user_id": "user-112"}], "total": 1}
            assert await mcp_endpoint.list_groups(context) == {
                "groups": [{"group_id": "engineering"}]
            }
            credentials = await mcp_endpoint.list_users(
                context, query="user-112", include_credentials=True
            )
            if role == Role.ROOT:
                assert credentials["users"][0]["api_key"] == last_key
            elif role == Role.ADMIN:
                account_part, user_part, secret = last_key.split(".")
                assert credentials["users"][0]["key_prefix"] == (
                    f"{account_part}.{user_part}.{'*' * (len(secret) - 4)}{secret[-4:]}"
                )
                assert "api_key" not in credentials["users"][0]
            else:
                assert credentials == {
                    "users": [{"user_id": "user-112", "role": "admin"}],
                    "total": 1,
                }
                own = await mcp_endpoint.list_users(
                    context, query="user-1", include_credentials=True
                )
                assert "api_key" in own["users"][0]
                assert all(set(row) == {"user_id", "role"} for row in own["users"][1:])
                assert await mcp_endpoint.list_users(
                    context, query="missing", include_credentials=True
                ) == {"users": [], "total": 0}
            if role != Role.ROOT:
                assert last_key not in json.dumps(credentials)
            original_config = lightweight_admin_app.state.config
            lightweight_admin_app.state.config = ServerConfig(
                auth_mode="trusted", root_api_key=ROOT_KEY
            )
            try:
                with pytest.raises(PermissionDeniedError, match="trusted"):
                    await mcp_endpoint.list_users(context, include_credentials=True)
                assert await mcp_endpoint.list_users(context, query="user-112") == directory
            finally:
                lightweight_admin_app.state.config = original_config

        finally:
            mcp_endpoint._mcp_ctx.reset(token)


async def test_user_page_summary_respects_account_access(lightweight_admin_client):
    acct = _uid()
    response = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": acct, "admin_user_id": "owner"},
        headers=root_headers(),
    )
    admin_key = response.json()["result"]["user_key"]
    own = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{acct}/users?include_summary=true&limit=20",
        headers={"X-API-Key": admin_key},
    )
    assert own.status_code == 200
    assert own.json()["result"]["account_total"] == 1
    denied = await lightweight_admin_client.get(
        "/api/v1/admin/accounts/default/users?include_summary=true&limit=20",
        headers={"X-API-Key": admin_key},
    )
    assert denied.status_code == 403


@pytest.mark.parametrize("cli_host", [None, "127.0.0.1"])
async def test_server_restart_requires_root_and_valid_revision(
    lightweight_admin_client,
    lightweight_admin_app,
    template_account,
    tmp_path,
    monkeypatch,
    cli_host,
):
    import os

    from openviking.config.config_file import read_config_file
    from openviking.server.restart import RestartController, RestartRecovery
    from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton

    account_id, admin_headers = template_account
    user = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{account_id}/users",
        headers=admin_headers,
        json={"user_id": "restart-test-user"},
    )
    assert user.status_code == 200
    user_headers = {"X-API-Key": user.json()["result"]["user_key"]}
    stopped = Mock()
    monkeypatch.delenv("OPENVIKING_RESTART_RECOVERY", raising=False)
    monkeypatch.delenv("OPENVIKING_RESTART_ROLLED_BACK", raising=False)
    controller = RestartController(stopped, RestartRecovery())
    lightweight_admin_app.state.restart_controller = controller
    path = tmp_path / "ov.conf"
    server = {}
    server_overrides = {}
    if cli_host:
        server = {"host": "0.0.0.0", "auth_mode": "trusted", "root_api_key": ROOT_KEY}
        server_overrides = {"host": cli_host}
        lightweight_admin_app.state.server_config_overrides = server_overrides
    path.write_text(
        json.dumps(
            {
                "server": server,
                "vlm": {"provider": "openai", "model": "gpt-4o", "api_key": "test-key"},
            }
        )
    )
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file_content", path.read_bytes())
    revision = read_config_file(server_overrides)["revision"]
    url = "/api/v1/admin/restart"
    for headers in [admin_headers, user_headers, {}]:
        assert (
            await lightweight_admin_client.get(
                "/api/v1/admin/configuration?source=file", headers=headers
            )
        ).status_code in (401, 403)
        assert (
            await lightweight_admin_client.post(url, headers=headers, json={"revision": revision})
        ).status_code in (401, 403)
    stopped.assert_not_called()
    assert not controller.requested
    status = await lightweight_admin_client.get(
        "/api/v1/admin/configuration?source=file", headers=root_headers()
    )
    assert status.json()["result"]["restart"]["supported"]
    assert status.headers["cache-control"] == "no-store"
    stale = await lightweight_admin_client.post(
        url, headers=root_headers(), json={"revision": "stale"}
    )
    assert stale.status_code == 400
    stopped.assert_not_called()
    original = path.read_bytes()
    accepted = await lightweight_admin_client.post(
        url, headers=root_headers(), json={"revision": revision}
    )
    assert accepted.status_code == 202
    assert accepted.json()["result"]["instance_id"] == controller.instance_id
    assert accepted.json()["result"]["restarting"]
    stopped.assert_called_once()
    recovery = json.loads(os.environ["OPENVIKING_RESTART_RECOVERY"])
    assert recovery["revision"] == revision
    with open(recovery["backup"], "rb") as backup:
        assert backup.read() == original
    assert path.read_bytes() == original
    blocked = await lightweight_admin_client.patch(
        "/api/v1/admin/configuration",
        params={"source": "file"},
        headers=root_headers(),
        json={"revision": revision, "content": original.decode()},
    )
    assert blocked.status_code == 412


@pytest.mark.parametrize(
    "invalid_server",
    [
        {"port": "invalid"},
        {"root_api_key": ""},
        {"auth_mode": "api_key"},
        {"auth_mode": "trusted", "host": "127.0.0.1"},
        {"auth_mode": "dev", "host": "0.0.0.0"},
    ],
)
async def test_server_restart_unsupported_or_invalid_file_does_not_stop(
    lightweight_admin_client,
    lightweight_admin_app,
    tmp_path,
    monkeypatch,
    invalid_server,
):
    import hashlib

    from openviking.server.restart import RestartController
    from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton

    path = tmp_path / "ov.conf"
    path.write_text("{}")
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)
    url = "/api/v1/admin/restart"
    status = await lightweight_admin_client.get(
        "/api/v1/admin/configuration?source=file", headers=root_headers()
    )
    assert not status.json()["result"]["restart"]["supported"]
    assert (
        await lightweight_admin_client.post(url, headers=root_headers(), json={"revision": "r"})
    ).status_code == 412
    stopped = Mock()
    lightweight_admin_app.state.restart_controller = RestartController(stopped)
    path.write_text(json.dumps({"server": invalid_server}))
    monkeypatch.setattr(OpenVikingConfigSingleton, "_config_file", path)
    response = await lightweight_admin_client.post(
        url,
        headers=root_headers(),
        json={"revision": hashlib.sha256(path.read_bytes()).hexdigest()},
    )
    assert response.status_code == 400
    stopped.assert_not_called()


@pytest.fixture
def private_probe_config(monkeypatch, tmp_path):
    from openviking_cli.utils.config.open_viking_config import (
        OpenVikingConfig,
        OpenVikingConfigSingleton,
    )

    config = OpenVikingConfig.from_dict(
        {
            "storage": {"workspace": str(tmp_path)},
            "vlm": {"provider": "openai", "model": "test-model", "api_key": "test-key"},
            "embedding": {
                "dense": {
                    "provider": "openai",
                    "model": "embedding",
                    "api_key": "test-key",
                    "dimension": 8,
                }
            },
        }
    )
    monkeypatch.setattr(OpenVikingConfigSingleton, "_instance", config)


async def test_private_model_probe_requires_authentication(
    private_probe_config, lightweight_admin_client, monkeypatch
):
    probe = AsyncMock(return_value={"ok": True, "ms": 1})
    monkeypatch.setattr("openviking.server.model_connection_test.probe_model", probe)
    response = await lightweight_admin_client.post(
        "/api/v1/admin/configuration/test-model",
        json={"kind": "vlm", "config": {"provider": "openai"}},
    )
    assert response.status_code == 401
    probe.assert_not_awaited()


async def test_private_model_probe_is_hidden_and_root_only(
    private_probe_config, lightweight_admin_app, lightweight_admin_client, monkeypatch
):
    from openviking.server.auth import get_request_context

    probe = AsyncMock(return_value={"ok": True, "ms": 1})
    monkeypatch.setattr("openviking.server.model_connection_test.probe_model", probe)
    schema = lightweight_admin_app.openapi()
    assert "/api/v1/admin/configuration/test-model" not in schema["paths"]
    assert "ModelConnectionTestRequest" not in schema.get("components", {}).get("schemas", {})
    for role in (Role.ADMIN, Role.USER):
        lightweight_admin_app.dependency_overrides[get_request_context] = lambda role=role: (
            RequestContext(user=UserIdentifier("default", "default"), role=role)
        )
        response = await lightweight_admin_client.post(
            "/api/v1/admin/configuration/test-model",
            json={"kind": "vlm", "config": {"provider": "openai"}},
        )
        assert response.status_code == 403
    probe.assert_not_awaited()


async def test_private_model_probe_passes_draft_without_saving(
    private_probe_config, lightweight_admin_client, monkeypatch
):
    probe = AsyncMock(return_value={"ok": True, "ms": 12})
    monkeypatch.setattr("openviking.server.model_connection_test.probe_model", probe)
    body = {
        "kind": "vlm",
        "config": {"provider": "openai", "api_key": "draft-secret"},
        "fallback": {"model": "o3"},
        "thinking": True,
    }
    response = await lightweight_admin_client.post(
        "/api/v1/admin/configuration/test-model", headers={"X-API-Key": ROOT_KEY}, json=body
    )
    assert response.status_code == 200
    assert response.headers["cache-control"] == "no-store"
    assert response.json()["result"] == {"ok": True, "ms": 12}
    assert "draft-secret" not in response.text
    probe.assert_awaited_once_with("vlm", body["config"], body["fallback"], True, "dense")


# ---- Exact account/user existence probes ----


async def test_get_account_returns_credential_free_metadata_or_404(
    lightweight_admin_client,
):
    account_id = _uid()
    missing = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{account_id}", headers=root_headers()
    )
    assert missing.status_code == 404

    created = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": account_id, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert created.status_code == 200

    response = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{account_id}", headers=root_headers()
    )
    assert response.status_code == 200, response.text
    result = response.json()["result"]
    assert result == {
        "account_id": account_id,
        "created_at": result["created_at"],
        "user_count": 1,
        "status": "active",
    }
    # Existence metadata must never carry credentials.
    body = response.text
    for secret_field in ("api_key", "user_key", "key_prefix", "seed"):
        assert secret_field not in body


async def test_get_account_is_root_only(template_account, lightweight_admin_client):
    account_id, admin_headers = template_account
    response = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{account_id}", headers=admin_headers
    )
    assert response.status_code == 403


async def test_user_point_read_returns_role_without_credentials(
    lightweight_admin_client,
):
    account_id = _uid()
    created = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": account_id, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    assert created.status_code == 200
    admin_headers = {"X-API-Key": created.json()["result"]["user_key"]}

    registered = await lightweight_admin_client.post(
        f"/api/v1/admin/accounts/{account_id}/users",
        json={"user_id": "bob"},
        headers=admin_headers,
    )
    assert registered.status_code == 200

    for user_id, role in (("alice", "admin"), ("bob", "user")):
        response = await lightweight_admin_client.get(
            f"/api/v1/admin/accounts/{account_id}/users/{user_id}",
            headers=root_headers(),
        )
        assert response.status_code == 200, response.text
        assert response.json()["result"] == {"user_id": user_id, "role": role}
        # The point read is defined as a credential-free membership probe; weld
        # that contract shut so no credential field can ever leak through it.
        for secret_field in ("api_key", "user_key", "key_prefix", "seed"):
            assert secret_field not in response.text

    unknown_user = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{account_id}/users/ghost",
        headers=root_headers(),
    )
    assert unknown_user.status_code == 404
    assert unknown_user.json()["error"]["message"] == "User not found: ghost"

    # An unknown account bubbles up the account-level 404 from the refresh,
    # matching list_users rather than masquerading as a missing user.
    unknown_account_id = _uid()
    unknown_account = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{unknown_account_id}/users/alice",
        headers=root_headers(),
    )
    assert unknown_account.status_code == 404
    assert (
        unknown_account.json()["error"]["message"]
        == f"Account not found: {unknown_account_id}"
    )


async def test_user_point_read_admin_scoped_to_own_account(lightweight_admin_client):
    account_id = _uid()
    other = _uid()
    created = await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": account_id, "admin_user_id": "alice"},
        headers=root_headers(),
    )
    admin_headers = {"X-API-Key": created.json()["result"]["user_key"]}
    await lightweight_admin_client.post(
        "/api/v1/admin/accounts",
        json={"account_id": other, "admin_user_id": "alice"},
        headers=root_headers(),
    )

    own = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{account_id}/users/alice",
        headers=admin_headers,
    )
    assert own.status_code == 200
    assert own.json()["result"] == {"user_id": "alice", "role": "admin"}

    denied = await lightweight_admin_client.get(
        f"/api/v1/admin/accounts/{other}/users/alice",
        headers=admin_headers,
    )
    assert denied.status_code == 403


async def test_user_point_read_sees_peer_process_writes_without_a_list(
    admin_client: httpx.AsyncClient,
    admin_app: FastAPI,
    admin_service: OpenVikingService,
):
    """Point read must not depend on a preceding list to refresh the registry.

    With the account-store watcher off (the default), a user created or re-roled
    by a peer process landed in the shared store but not in this instance's
    memory. The membership probe refreshes on demand, so it must not return a
    stale 404 or a stale role.
    """
    writer = build_api_key_manager(
        root_key=ROOT_KEY,
        viking_fs=admin_service.viking_fs,
    )
    await writer.load()
    try:
        acct = _uid()
        await writer.create_account(acct, "alice")
        await writer.register_user(acct, "bob", role="user")

        # The serving instance never listed this account, so bob is only in the
        # peer's store. The probe must still resolve him.
        created = await admin_client.get(
            f"/api/v1/admin/accounts/{acct}/users/bob",
            headers=root_headers(),
        )
        assert created.status_code == 200, created.text
        assert created.json()["result"] == {"user_id": "bob", "role": "user"}

        # A peer-side role change must be reflected too, not served from stale
        # memory.
        await writer.set_role(acct, "bob", "admin")
        rerole = await admin_client.get(
            f"/api/v1/admin/accounts/{acct}/users/bob",
            headers=root_headers(),
        )
        assert rerole.status_code == 200, rerole.text
        assert rerole.json()["result"] == {"user_id": "bob", "role": "admin"}
    finally:
        await writer.close()