Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

58.4 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""How recalled turns get back into a compacted request, and what must not ride along."""

import os
import sys

import pytest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from core.inference import llama_cpp  # noqa: E402
from core.inference import tools as tools_mod  # noqa: E402
from core.rag import conversation_archive  # noqa: E402

THREAD = "thread-recall"


@pytest.fixture
def archived(rag_home, rag_conn, stub_embeddings):
    turns = [
        {"role": "user", "content": "write me a limerick about pelicans"},
        {"role": "assistant", "content": "There once was a bird with a bill"},
    ]
    from storage import studio_db

    studio_db.upsert_chat_thread(
        {
            "id": THREAD,
            "title": "t",
            "modelType": "base",
            "modelId": "local-model",
            "createdAt": 1,
        }
    )
    for index, message in enumerate(turns):
        studio_db.upsert_chat_message(
            {
                "id": f"{THREAD}-{index}",
                "threadId": THREAD,
                "role": message["role"],
                "content": [{"type": "text", "text": message["content"]}],
                "createdAt": index + 2,
            }
        )
    conversation_archive.archive_turns(THREAD, turns)
    return rag_conn


def _conversation():
    return [
        {"role": "system", "content": "you are helpful"},
        {"role": "user", "content": "what was that pelicans limerick"},
    ]


def _truncated_turn(
    *,
    role = "assistant",
    content = "a",
    fits = True,
    dropped_messages = 4,
):
    """A stored turn carrying a context-truncation record, with per-test overrides."""
    return {
        "role": role,
        "content": content,
        "metadata": {
            "custom": {"contextTruncation": {"fits": fits, "dropped_messages": dropped_messages}}
        },
    }


def test_recall_runs_even_when_document_rag_is_off(archived):
    """Conversation recall runs even when document RAG is off, since it recalls the chat's own turns."""
    built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "tool")

    assert built is not None
    assert built["sources"] >= 1
    assert built["messages"][0]["tool_calls"][0]["function"]["name"] == "search_conversation"


def test_tool_style_matches_the_rag_autoinject_shape(archived):
    """The UI renders forced retrieval through the existing tool-card path."""
    built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "tool")

    assert [event["type"] for event in built["events"]] == [
        "status",
        "tool_start",
        "tool_end",
        "status",
    ]
    assert [message["role"] for message in built["messages"]] == ["assistant", "tool"]
    call_id = built["messages"][0]["tool_calls"][0]["id"]
    assert call_id.startswith("conv_recall_")
    assert built["messages"][1]["tool_call_id"] == call_id


def test_inline_style_returns_a_prefix_and_no_forged_tool_messages(archived):
    """The plain path sends no tools array; a tool role there is a template hazard."""
    built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "inline")

    assert built["messages"] == []
    assert built["events"] == []
    assert "<recalled_conversation>" in built["prefix"]


def test_recall_is_none_without_a_thread_id(archived):
    assert tools_mod.build_conversation_recall(_conversation(), None) is None


def test_recall_is_none_when_nothing_matches(archived):
    built = tools_mod.build_conversation_recall(
        [{"role": "user", "content": "zzzz unrelated quantum plumbing"}], THREAD
    )

    assert built is None or built["sources"] >= 0


def test_prefix_user_text_does_not_mutate_the_original():
    message = {"role": "user", "content": "original"}

    updated = llama_cpp._prefix_user_text(message, "PREFIX ")

    assert message["content"] == "original"
    assert updated["content"] == "PREFIX original"


def test_prefix_user_text_handles_content_parts():
    message = {
        "role": "user",
        "content": [{"type": "image_url", "image_url": {}}, {"type": "text", "text": "hello"}],
    }

    updated = llama_cpp._prefix_user_text(message, "PREFIX ")

    assert updated["content"][1]["text"] == "PREFIX hello"
    assert message["content"][1]["text"] == "hello"


def test_archive_and_recall_reports_counts_only(archived):
    """Only counts ride the context_truncated SSE event to the client; message text must not."""
    before = _conversation() + [{"role": "user", "content": "evicted turn"}]
    after = _conversation()

    result = llama_cpp._archive_and_recall(
        after, before, thread_id = THREAD, style = "tool", recall_done = False
    )

    assert set(result["counts"]) <= {"archived_messages", "recalled_chunks"}
    assert all(isinstance(value, int) for value in result["counts"].values())


def test_archive_and_recall_skips_recall_once_already_done(archived):
    before = _conversation() + [{"role": "user", "content": "evicted turn"}]
    after = _conversation()

    result = llama_cpp._archive_and_recall(
        after, before, thread_id = THREAD, style = "tool", recall_done = True
    )

    assert result["recalled"] is False
    assert result["conversation"] is after
    assert "recalled_chunks" not in result["counts"]


@pytest.mark.parametrize("stopped", [False, True])
def test_a_stopped_request_skips_the_automatic_recall(archived, monkeypatch, stopped):
    """Recall embeds the query; a Stopped request must not pay for it (#14519)."""
    recalls = []
    monkeypatch.setattr(tools_mod, "build_conversation_recall", lambda *_a, **_k: recalls.append(1))
    before = _conversation() + [{"role": "user", "content": "evicted turn"}]
    after = _conversation()

    result = llama_cpp._archive_and_recall(
        after,
        before,
        thread_id = THREAD,
        style = "tool",
        recall_done = False,
        recall_budget_tokens = 100_000,
        cancel_check = lambda: stopped,
    )

    assert recalls == ([] if stopped else [1])
    assert result["recalled"] is False


def test_a_refused_fit_still_archives_what_it_evicted(archived):
    """`recall_done` skips recall without skipping the archive write."""
    before = _conversation() + [{"role": "user", "content": "a turn only the fit saw"}]
    after = _conversation()

    result = llama_cpp._archive_and_recall(
        after, before, thread_id = THREAD, style = "tool", recall_done = True
    )

    assert result["counts"]["archived_messages"] >= 1
    assert result["recalled"] is False


def test_a_shrunken_window_hands_the_respawn_refit_a_reduced_refusal():
    """A smaller window can produce a reduced prompt with `fits` false."""
    from core.inference.context_window import fit_rolling_context

    latest = {"role": "user", "content": "latest" * 133}
    messages = [
        {"role": "user", "content": "old" * 133},
        {"role": "assistant", "content": "answer" * 66},
        latest,
    ]
    counter = lambda candidate: sum(  # noqa: E731
        len(str(message.get("content", ""))) for message in candidate
    )

    fitted, info = fit_rolling_context(
        messages,
        context_length = 1000,
        max_tokens = 250,
        count_tokens = counter,
    )

    assert counter(messages) > 1000 >= counter(fitted)
    assert info["fits"] is False
    assert info["dropped_messages"] == 2
    assert fitted == [latest]


def test_archive_and_recall_is_a_noop_without_a_thread_id(archived):
    after = _conversation()

    result = llama_cpp._archive_and_recall(
        after, after, thread_id = None, style = "tool", recall_done = False
    )

    assert result["conversation"] is after
    assert result["counts"] == {}


def test_recall_reserve_is_zero_without_a_thread():
    assert llama_cpp._conversation_recall_reserve(None) == 0


def test_recall_reserve_is_zero_when_the_archive_is_disabled(monkeypatch):
    monkeypatch.setattr(conversation_archive.config, "CONVERSATION_ARCHIVE", False)

    assert llama_cpp._conversation_recall_reserve(THREAD) == 0


def test_build_rag_autoinject_still_emits_its_original_shape(monkeypatch):
    """Guards the extraction that gave recall and document auto-inject a shared builder."""
    from core.rag import tool as rag_tool

    # Patched on core.rag.tool: build_rag_autoinject imports it lazily inside the function.
    monkeypatch.setattr(
        rag_tool,
        "search_for_autoinject",
        lambda **kwargs: ("passage text", [{"citationId": 1, "filename": "doc.txt"}]),
    )

    built = tools_mod.build_rag_autoinject(
        [{"role": "user", "content": "question"}],
        {"kb_id": "kb-1", "autoinject": True, "autoinject_min_score": 0.0},
    )

    assert built is not None
    assert [event["type"] for event in built["events"]] == [
        "status",
        "tool_start",
        "tool_end",
        "status",
    ]
    assert built["messages"][0]["tool_calls"][0]["function"]["name"] == "search_knowledge_base"
    assert built["messages"][0]["tool_calls"][0]["id"].startswith("rag_auto_")
    assert built["messages"][1]["content"] == "passage text"


def test_search_conversation_is_always_safe():
    """Read-only, so auto mode must not prompt on every call."""
    assert tools_mod.is_always_safe_tool("search_conversation") is True


def test_search_conversation_tool_is_registered():
    names = {tool["function"]["name"] for tool in tools_mod.ALL_TOOLS}

    assert "search_conversation" in names


def test_execute_tool_without_a_thread_returns_a_message_not_a_traceback():
    result = tools_mod.execute_tool(
        "search_conversation", {"query": "anything"}, thread_id = None, timeout = None
    )

    assert isinstance(result, str)
    assert "no earlier conversation" in result.lower()


def test_execute_tool_rejects_an_empty_query(archived):
    result = tools_mod.execute_tool(
        "search_conversation", {"query": "  "}, thread_id = THREAD, timeout = None
    )

    assert result == "Error: query is empty."


def test_execute_tool_finds_an_archived_turn(archived):
    result = tools_mod.execute_tool(
        "search_conversation", {"query": "pelicans"}, thread_id = THREAD, timeout = None
    )

    assert "pelicans" in result


def test_compaction_nudge_only_fires_when_the_tool_is_present():
    import routes.inference as routes_mod

    without = routes_mod._apply_compaction_nudge("base.", [])
    with_tool = routes_mod._apply_compaction_nudge(
        "base.", [{"function": {"name": "search_conversation"}}]
    )

    assert without == "base."
    assert "search_conversation" in with_tool


def _fake_studio_db(monkeypatch, messages):
    """Stand in for storage.studio_db.list_chat_messages."""
    import sys
    import types

    from core.inference import checkpoint

    module = types.SimpleNamespace(list_chat_messages = lambda thread_id: messages)
    package = types.ModuleType("storage")
    package.studio_db = module
    monkeypatch.setitem(sys.modules, "storage", package)
    monkeypatch.setitem(sys.modules, "storage.studio_db", module)
    # Rolling-shaped fixtures; the process default is checkpoint, which refuses omitted-key records.
    monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")


def test_sticky_boundary_reads_the_newest_assistant_truncation(monkeypatch):
    from core.inference import llama_cpp
    _fake_studio_db(
        monkeypatch,
        [
            {"role": "user", "content": "q"},
            _truncated_turn(dropped_messages = 12),
            {"role": "user", "content": "q2"},
            _truncated_turn(content = "a2", dropped_messages = 18),
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 18


def test_sticky_boundary_ignores_a_sibling_branchs_assistant_turn(monkeypatch):
    """Sticky boundary must come from this branch's reply, since the newest row may be a sibling."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {"role": "user", "content": "q"},
            _truncated_turn(content = "answer on the branch we are on"),
            _truncated_turn(
                content = "regenerated answer the user switched away from",
                dropped_messages = 40,
            ),
        ],
    )
    branch = [
        {"role": "user", "content": "q"},
        {"role": "assistant", "content": "answer on the branch we are on"},
        {"role": "user", "content": "next"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1") == 40
    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4


def test_sticky_boundary_takes_the_smaller_of_two_identical_replies(monkeypatch):
    """Identical replies cannot be told apart, so take the smaller boundary as the safe one."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {"role": "user", "content": "q"},
            _truncated_turn(content = "Done."),
            _truncated_turn(content = "Done.", dropped_messages = 60),
        ],
    )
    branch = [
        {"role": "user", "content": "q"},
        {"role": "assistant", "content": "Done."},
        {"role": "user", "content": "next"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4


def test_sticky_boundary_still_prefers_the_newest_distinguishable_reply(monkeypatch):
    """Only replies indistinguishable from the newest are folded in, or the boundary ratchets backwards."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            _truncated_turn(content = "an earlier, shallower answer", dropped_messages = 2),
            _truncated_turn(content = "the newest answer", dropped_messages = 30),
        ],
    )
    branch = [
        {"role": "assistant", "content": "an earlier, shallower answer"},
        {"role": "assistant", "content": "the newest answer"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 30


def test_sticky_boundary_prefers_a_reply_that_matches_the_branch_exactly(monkeypatch):
    """The branch check is a substring test, so a short reply like 'Done' matches a longer live reply."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {"role": "user", "content": "did it work"},
            _truncated_turn(content = "Not done yet, still running."),
            _truncated_turn(content = "Done", dropped_messages = 60),
        ],
    )
    branch = [
        {"role": "user", "content": "did it work"},
        {"role": "assistant", "content": "Not done yet, still running."},
        {"role": "user", "content": "keep going"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4


def test_sticky_boundary_still_reads_a_reply_no_branch_message_matches_exactly(monkeypatch):
    """Exact match may be preferred, not required; stored rows are not always byte-identical."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            _truncated_turn(content = "the answer", dropped_messages = 9),
        ],
    )
    branch = [
        {"role": "user", "content": "q"},
        {"role": "assistant", "content": "the answer, with a block the request drops"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 9


def test_sticky_boundary_prefers_the_recorded_branch_boundary(monkeypatch):
    """Summed dropped counts include tool exchanges the transcript lacks; restore the recorded boundary."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {
                "role": "assistant",
                "content": "a",
                "metadata": {
                    "custom": {
                        "contextTruncation": {
                            "fits": True,
                            "dropped_messages": 12,
                            "boundary_messages": 4,
                        }
                    }
                },
            },
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 4


def _anchored_row(
    boundary,
    anchor,
    content = "a",
):
    return {
        "role": "assistant",
        "content": content,
        "metadata": {
            "custom": {
                "contextTruncation": {
                    "fits": True,
                    "boundary_messages": boundary,
                    "boundary_anchor": anchor,
                }
            }
        },
    }


def test_sticky_boundary_rebases_after_an_evicted_turn_is_deleted(monkeypatch):
    """Recorded boundary counts are absolute, so re-derive the cut from the anchor after a delete."""
    from core.inference import llama_cpp

    _fake_studio_db(monkeypatch, [_anchored_row(4, "kept first")])
    branch = [
        {"role": "user", "content": "old prompt"},
        {"role": "assistant", "content": "old reply"},
        {"role": "user", "content": "kept first"},
        {"role": "assistant", "content": "a"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2


def test_sticky_boundary_anchor_never_deepens_the_cut(monkeypatch):
    """An anchor may make the boundary shallower but never deeper, since a repeat can match far in."""
    from core.inference import llama_cpp

    _fake_studio_db(monkeypatch, [_anchored_row(2, "kept first")])
    branch = [
        {"role": "user", "content": "one"},
        {"role": "assistant", "content": "two"},
        {"role": "user", "content": "three"},
        {"role": "assistant", "content": "four"},
        {"role": "user", "content": "kept first"},
        {"role": "assistant", "content": "a"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2


def test_sticky_boundary_ignores_an_anchor_the_branch_no_longer_has(monkeypatch):
    """The anchor's own turn can be the one deleted. Fall back to the recorded count."""
    from core.inference import llama_cpp

    _fake_studio_db(monkeypatch, [_anchored_row(2, "a text this branch does not have")])
    branch = [
        {"role": "user", "content": "one"},
        {"role": "assistant", "content": "two"},
        {"role": "user", "content": "three"},
        {"role": "assistant", "content": "a"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2


def test_sticky_boundary_anchor_skips_the_system_turn(monkeypatch):
    """Count as _branch_boundary does, skipping system and developer turns, or each anchor lands late."""
    from core.inference import llama_cpp

    _fake_studio_db(monkeypatch, [_anchored_row(4, "kept first")])
    branch = [
        {"role": "system", "content": "you are a helpful assistant"},
        {"role": "user", "content": "old prompt"},
        {"role": "assistant", "content": "old reply"},
        {"role": "user", "content": "kept first"},
        {"role": "assistant", "content": "a"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2


def test_branch_boundary_anchor_names_the_first_kept_message():
    """The anchor and the count describe the same cut, or the rebase is meaningless."""
    from core.inference import llama_cpp

    branch = [
        {"role": "system", "content": "sys"},
        {"role": "user", "content": "evicted prompt"},
        {"role": "assistant", "content": "evicted reply"},
        {"role": "user", "content": "kept prompt"},
        {"role": "assistant", "content": "kept reply"},
        {"role": "user", "content": "the turn just sent"},
    ]
    conversation = [branch[0]] + branch[3:]

    assert llama_cpp._branch_boundary(conversation, branch) == 2
    assert llama_cpp._branch_boundary_anchor(conversation, branch) == "kept prompt"


def test_sticky_boundary_falls_back_for_turns_saved_before_the_boundary_existed(monkeypatch):
    """Rows written by an earlier build carry only the dropped count."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            _truncated_turn(dropped_messages = 6),
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 6


def test_the_recall_reserve_is_dropped_once_archiving_has_failed(monkeypatch):
    """Drop the recall reserve once archiving fails: the embedder cannot start, so nothing is recalled."""
    from core.inference import llama_cpp
    from core.rag import conversation_archive as archive

    monkeypatch.setattr(archive, "can_archive", lambda _tid: True)
    monkeypatch.setattr(archive, "degraded", lambda: False)
    assert llama_cpp._conversation_recall_reserve("t1") > 0

    monkeypatch.setattr(archive, "degraded", lambda: True)
    assert llama_cpp._conversation_recall_reserve("t1") == 0


def test_sticky_boundary_only_matches_assistant_messages(monkeypatch):
    """Match only assistant messages; a user message that merely contains 'Done' must not count."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {"role": "user", "content": "did the deploy finish? not done yet I think"},
            _truncated_turn(content = "Done", dropped_messages = 60),
        ],
    )
    branch = [{"role": "user", "content": "did the deploy finish? not done yet I think"}]

    assert llama_cpp._sticky_compaction_boundary("t1", branch) == 0


def test_sticky_boundary_reads_the_flattened_metadata_shape(monkeypatch):
    """The history row flattens `custom` into `metadata`; both shapes are in the wild."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {
                "role": "assistant",
                "content": "a",
                "metadata": {"contextTruncation": {"fits": True, "dropped_messages": 7}},
            },
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 7


def test_sticky_boundary_ignores_a_provider_summary(monkeypatch):
    """A provider summary is useful only while its opaque block is replayed to that provider."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            {
                "role": "assistant",
                "content": "a",
                "metadata": {
                    "custom": {
                        "contextTruncation": {
                            "fits": True,
                            "dropped_messages": 7,
                            "boundary_messages": 7,
                            "summarized": True,
                        }
                    }
                },
            },
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 0


def test_sticky_boundary_is_zero_without_a_thread_or_history(monkeypatch):
    from core.inference import llama_cpp

    assert llama_cpp._sticky_compaction_boundary(None) == 0
    assert llama_cpp._sticky_compaction_boundary("") == 0
    _fake_studio_db(monkeypatch, [])
    assert llama_cpp._sticky_compaction_boundary("t1") == 0


def test_sticky_boundary_ignores_a_fit_that_did_not_fit(monkeypatch):
    """`fits: false` means the fit gave up, so it describes no boundary to restore."""
    from core.inference import llama_cpp

    _fake_studio_db(
        monkeypatch,
        [
            _truncated_turn(fits = False, dropped_messages = 40),
        ],
    )

    assert llama_cpp._sticky_compaction_boundary("t1") == 0


def test_sticky_boundary_never_raises_on_a_storage_failure(monkeypatch):
    """A boundary is an optimisation; losing it must never cost the user a turn."""
    import sys
    import types

    from core.inference import llama_cpp

    def explode(thread_id):
        raise RuntimeError("database is locked")

    module = types.SimpleNamespace(list_chat_messages = explode)
    package = types.ModuleType("storage")
    package.studio_db = module
    monkeypatch.setitem(sys.modules, "storage", package)
    monkeypatch.setitem(sys.modules, "storage.studio_db", module)

    assert llama_cpp._sticky_compaction_boundary("t1") == 0


def test_recall_is_sized_by_the_room_the_fit_actually_obtained():
    """Size recall to the room the fit obtained, since protected messages can leave the trim short."""
    from core.inference import llama_cpp

    assert llama_cpp._recall_top_k(0) == 0
    assert llama_cpp._recall_top_k(-500) == 0
    assert 0 < llama_cpp._recall_top_k(1024) <= 4
    assert llama_cpp._recall_top_k(1_000_000) == 4


def test_a_tool_loop_retrieval_leaves_room_for_the_turn_it_enables():
    """A tool-loop retrieval leaves room for the reply that follows it."""
    from core.inference import llama_cpp

    single_shot = llama_cpp._retrieval_budget(3000, 3000, 747)
    in_loop = llama_cpp._retrieval_budget(3000, 3000, 747, reply_returns = True)

    assert single_shot == 2250 - 747
    assert in_loop == 1125
    assert in_loop < single_shot


def test_a_retrieval_budget_is_only_capped_where_it_would_take_most_of_the_turn():
    from core.inference import llama_cpp
    assert llama_cpp._retrieval_budget(32768, 32768, 18976, reply_returns = True) == 24576 - 18976
    assert llama_cpp._retrieval_budget(3000, 3000, 9000, reply_returns = True) == 0


def test_a_recorded_boundary_is_still_not_a_replayable_one():
    """A rescue's depth is recorded for the compaction notice, but only fitted boundaries are replayed."""
    from core.inference import llama_cpp

    rescued = {"fits": False, "dropped_messages": 6, "boundary_messages": 6}
    fitted = {"fits": True, "dropped_messages": 6, "boundary_messages": 6}
    refused = {"fits": False, "dropped_messages": 0}

    assert llama_cpp._records_boundary(rescued) is True
    assert llama_cpp._records_boundary(fitted) is True
    assert llama_cpp._records_boundary(refused) is False


def test_both_local_tool_loops_size_retrieval_with_the_same_policy():
    """GGUF and safetensors loops must share one retrieval sizing policy; a private copy drifts."""
    import inspect

    from core.inference import context_window, llama_cpp, safetensors_agentic

    assert llama_cpp._retrieval_budget is context_window.retrieval_budget

    source = inspect.getsource(safetensors_agentic)
    assert "retrieval_budget(" in source
    budget_call = source[source.index('kwargs["conversation_budget_tokens"] = retrieval_budget(') :]
    assert "reply_returns = True" in budget_call[:400]


def test_the_sticky_boundary_is_applied_once_per_request():
    """Apply the sticky boundary once per request; a second fit re-applying it evicts live history."""
    from core.inference.context_window import fit_rolling_context

    def counter(messages):
        return sum(max(1, len(m["content"]) // 4) for m in messages)

    conversation = [{"role": "system", "content": "s" * 80}]
    for index in range(40):
        conversation.append({"role": "user", "content": f"q{index} " * 200})
        conversation.append({"role": "assistant", "content": f"a{index} " * 200})
    conversation.append({"role": "user", "content": "latest"})

    conversation, first = fit_rolling_context(
        conversation,
        context_length = 8000,
        max_tokens = 512,
        count_tokens = counter,
        sticky_dropped = 52,
    )
    assert first["dropped_messages"] == 52
    conversation = conversation + [
        {"role": "assistant", "content": "calling"},
        {"role": "tool", "content": "R" * (2600 * 4)},
    ]
    _, reapplied = fit_rolling_context(
        conversation,
        context_length = 8000,
        max_tokens = 512,
        count_tokens = counter,
        sticky_dropped = 52,
    )
    _, once = fit_rolling_context(
        conversation,
        context_length = 8000,
        max_tokens = 512,
        count_tokens = counter,
        sticky_dropped = 0,
    )
    assert reapplied["dropped_messages"] > once["dropped_messages"]
    from pathlib import Path

    source = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"
    text = source.read_text(encoding = "utf-8")
    assert "_sticky_boundary_applied = True" in text
    assert "(0, True) if _sticky_boundary_applied" in " ".join(text.split())


def test_conversation_search_top_k_is_clamped(archived, monkeypatch):
    """top_k is written by the model. A negative reaches a slice as out[:-1]."""
    seen = {}

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
        extra_queries = None,
        forced = False,
    ):
        seen["top_k"] = top_k
        seen["branch_messages"] = branch_messages
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    tools_mod._search_conversation({"query": "pelicans", "top_k": -1}, {"thread_id": THREAD})
    assert seen["top_k"] >= 1

    tools_mod._search_conversation({"query": "pelicans", "top_k": 10_000}, {"thread_id": THREAD})
    assert seen["top_k"] <= tools_mod._MAX_CONVERSATION_SEARCH_TOP_K


def test_conversation_search_top_k_is_clamped_by_the_live_budget(archived, monkeypatch):
    """A fixed top_k ceiling is not a budget: clamp retrieval by the live window, or the turn overflows."""
    from core.rag import config as rag_config

    seen = {}

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
        extra_queries = None,
        forced = False,
    ):
        seen["top_k"] = top_k
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    tools_mod._search_conversation(
        {"query": "pelicans", "top_k": 8},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
    )
    assert seen["top_k"] == 2

    seen.clear()
    tools_mod._search_conversation(
        {"query": "pelicans"},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS},
    )
    assert seen["top_k"] == 1

    seen.clear()
    answer = tools_mod._search_conversation(
        {"query": "pelicans", "top_k": 4},
        {"thread_id": THREAD, "budget_tokens": 10},
    )
    assert "no room" in answer.lower()
    assert not seen


def test_an_omitted_top_k_still_means_the_configured_default(archived, monkeypatch):
    """An omitted top_k means the configured default, capped by room; room is a ceiling, not a target."""
    from core.rag import config as rag_config

    asked = []

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        asked.append(top_k)
        return ("an earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    tools_mod._search_conversation(
        {"query": "pelicans"}, {"thread_id": THREAD, "budget_tokens": 100_000}
    )
    assert asked == [
        min(rag_config.CONVERSATION_ARCHIVE_TOP_K, tools_mod._MAX_CONVERSATION_SEARCH_TOP_K)
    ]

    asked.clear()
    tools_mod._search_conversation(
        {"query": "pelicans"},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
    )
    assert asked == [2]


def test_conversation_search_refuses_a_result_the_budget_cannot_hold(archived, monkeypatch):
    """CHUNK_TOKENS is a chunker target, not a chunk's real weight once overlap and markup are added."""
    from core.rag import config as rag_config

    asked = []

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        asked.append(top_k)
        return ("x" * 4 * rag_config.CHUNK_TOKENS * (top_k or 1) * 6, [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    answer = tools_mod._search_conversation(
        {"query": "pelicans", "top_k": 8},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 4},
    )

    assert asked == [4, 3, 2, 1]
    assert "no room" in answer.lower()


def test_conversation_search_returns_what_the_budget_does_hold(archived, monkeypatch):
    """The backoff must not become a refusal on a result that fits."""
    from core.rag import config as rag_config

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        return ("an earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    answer = tools_mod._search_conversation(
        {"query": "pelicans", "top_k": 4},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 4},
    )

    assert "an earlier turn" in answer


def test_conversation_search_prices_only_what_the_model_reads(archived, monkeypatch):
    from core.inference.tool_loop_controller import strip_result_for_model
    from core.rag import config as rag_config
    from core.rag import tool as rag_tool

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        sources = [
            {"filename": "conversation", "text": "y" * 4 * rag_config.CHUNK_TOKENS, "turn": n}
            for n in range(1, top_k + 1)
        ]
        return rag_tool.render_conversation_sources(sources), sources

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    def model_chunks(budget, top_k):
        answer = tools_mod._search_conversation(
            {"query": "pelicans", "top_k": top_k},
            {"thread_id": THREAD, "budget_tokens": budget, "token_counter": lambda t: len(t) // 4},
        )
        # The source card still receives the citation data the model does not read.
        assert tools_mod.RAG_SOURCES_SENTINEL in answer
        return strip_result_for_model(answer, "search_conversation").count("<chunk ")

    assert model_chunks(rag_config.CHUNK_TOKENS * 5, 4) == 4
    assert model_chunks(rag_config.CHUNK_TOKENS * 3 // 2, 1) == 1
    # Markup pushes four full chunks past four chunks of room; three still fit.
    assert model_chunks(rag_config.CHUNK_TOKENS * 4, 8) == 3


def test_the_conversation_tool_survives_studios_explicit_allowlist(monkeypatch):
    """The allowlist must keep search_conversation, since Unsloth's enabled_tools never names it."""
    import asyncio
    import types

    import routes.inference as routes_mod

    monkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: True)

    payload = types.SimpleNamespace(
        enabled_tools = ["search_knowledge_base", "web_search"],
        rag_scope = {"thread_id": THREAD},
        thread_id = THREAD,
        bypass_permissions = False,
    )
    tools = asyncio.run(routes_mod._select_request_tools(payload, tools_on = True, mcp_allowed = False))
    names = [tool["function"]["name"] for tool in tools]

    assert "search_conversation" in names
    assert names.count("search_conversation") == 1
    monkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: False)
    tools = asyncio.run(routes_mod._select_request_tools(payload, tools_on = True, mcp_allowed = False))
    assert "search_conversation" not in [t["function"]["name"] for t in tools]


def test_both_retrieval_tools_share_the_per_turn_search_cap():
    """Both retrieval tools share a per-turn cap: each search adds passages the window cannot evict."""
    from pathlib import Path

    from core.inference.tool_call_parser import RAG_SEARCH_TOOLS

    assert RAG_SEARCH_TOOLS == {"search_knowledge_base", "search_conversation"}
    backend = Path(__file__).resolve().parent.parent / "core/inference"
    for module in ("llama_cpp.py", "safetensors_agentic.py"):
        text = (backend / module).read_text(encoding = "utf-8")
        assert "decision.tool_name in RAG_SEARCH_TOOLS" in text, module
        assert 'decision.tool_name == "search_knowledge_base"' not in text, module


def test_an_omitted_top_k_falls_through_to_the_configured_default(archived, monkeypatch):
    """An omitted top_k uses the configured default, not the ceiling, since eight turns fill the window."""
    seen = {}

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
        extra_queries = None,
        forced = False,
    ):
        seen["top_k"] = top_k
        seen["branch_messages"] = branch_messages
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)
    tools_mod._search_conversation({"query": "pelicans"}, {"thread_id": THREAD})

    assert seen["top_k"] is None


def test_a_thread_that_cannot_be_archived_holds_back_no_reserve(monkeypatch):
    """A thread that cannot be archived holds no reserve, since nothing can be recalled into it."""
    from core.inference import llama_cpp
    from core.rag import conversation_archive

    monkeypatch.setattr(conversation_archive, "enabled", lambda: True)

    monkeypatch.setattr(conversation_archive, "can_archive", lambda thread_id: False)
    assert llama_cpp._conversation_recall_reserve("incognito") == 0

    monkeypatch.setattr(conversation_archive, "can_archive", lambda thread_id: True)
    assert llama_cpp._conversation_recall_reserve("saved") > 0
    assert llama_cpp._conversation_recall_reserve(None) == 0


def test_the_forced_recall_searches_for_the_USERS_question(archived, monkeypatch):
    """Forced recall must search the user's question, not an internal user-role re-prompt."""
    seen = {}

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
        extra_queries = None,
        forced = False,
    ):
        seen["query"] = query
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)
    branch = [
        {"role": "user", "content": "what was the VULPINE code from earlier"},
        {"role": "assistant", "content": "checking"},
    ]
    conversation = branch + [
        {"role": "user", "content": "You said you would use a tool. Do it now or answer."}
    ]

    tools_mod.build_conversation_recall(
        conversation, THREAD, style = "inline", branch_messages = branch
    )

    assert seen["query"] == "what was the VULPINE code from earlier"


def test_the_forced_recall_skips_notices_a_tool_loop_added_to_its_branch(archived, monkeypatch):
    """A tool loop's live branch ends on its own user-role notices; query_messages names the
    user's question so the final pass does not search for the budget nudge (#16187)."""
    seen = {}

    def fake_recall(thread_id, query, **kwargs):
        seen["query"] = query
        seen["branch_messages"] = kwargs.get("branch_messages")
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)
    request = [{"role": "user", "content": "what was the VULPINE code from earlier"}]
    live = request + [
        {"role": "assistant", "content": "", "tool_calls": [{"id": "c1"}]},
        {"role": "tool", "content": "result", "tool_call_id": "c1"},
        {"role": "user", "content": "You have used all available tool calls. Answer now."},
    ]

    tools_mod.build_conversation_recall(
        live, THREAD, style = "inline", branch_messages = live, query_messages = request
    )

    assert seen["query"] == "what was the VULPINE code from earlier"
    assert seen["branch_messages"] is live


def test_archive_and_recall_hands_query_messages_to_the_recall(archived, monkeypatch):
    seen = {}

    def build(_conversation, _thread_id, **kwargs):
        seen.update(kwargs)
        return None

    monkeypatch.setattr(tools_mod, "build_conversation_recall", build)
    request = [{"role": "user", "content": "the question"}]
    live = request + [{"role": "user", "content": "a loop notice"}]

    llama_cpp._archive_and_recall(
        live,
        live,
        thread_id = THREAD,
        style = "inline",
        recall_done = False,
        recall_budget_tokens = 100_000,
        branch_messages = live,
        query_messages = request,
    )

    assert seen["query_messages"] is request
    assert seen["branch_messages"] is live


def test_a_model_initiated_search_is_filtered_to_the_request_branch(archived, monkeypatch):
    """A model-initiated search must be branch-filtered too, or a replaced reply returns through it."""
    seen = {}

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        seen["branch_messages"] = branch_messages
        return ("earlier turn", [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)
    branch = [{"role": "user", "content": "on this branch"}]

    tools_mod.execute_tool(
        "search_conversation",
        {"query": "pelicans"},
        thread_id = THREAD,
        conversation_branch = branch,
    )

    assert seen["branch_messages"] == branch


def test_inline_recall_anchors_only_the_turn_it_rewrote(archived, monkeypatch):
    """Inline recall rewrites the latest user message in place, so anchor only that turn."""
    from core.inference import llama_cpp

    conversation = [
        {"role": "user", "content": "an earlier question"},
        {"role": "assistant", "content": "an earlier answer"},
        {"role": "user", "content": "what was that limerick"},
    ]
    monkeypatch.setattr(
        tools_mod,
        "build_conversation_recall",
        lambda *args, **kwargs: {"prefix": "RECALLED ", "messages": [], "events": [], "sources": 1},
    )

    out = llama_cpp._archive_and_recall(
        conversation,
        conversation,
        thread_id = THREAD,
        style = "inline",
        recall_done = False,
        recall_budget_tokens = 100_000,
    )

    assert out["recalled"] is True
    assert len(out["anchored"]) == 1
    assert out["anchored"][0]["content"].startswith("RECALLED ")
    assert out["anchored"][0] is out["conversation"][-1]
    assert id(conversation[1]) not in {id(message) for message in out["anchored"]}


def test_tool_recall_anchors_the_synthetic_exchange(archived, monkeypatch):
    """The tool style DOES append two messages, and those are what must survive a refit."""
    from core.inference import llama_cpp

    conversation = [{"role": "user", "content": "what was that limerick"}]
    synthetic = [
        {"role": "assistant", "content": None, "tool_calls": [{"id": "conv_recall_x"}]},
        {"role": "tool", "tool_call_id": "conv_recall_x", "content": "an earlier turn"},
    ]
    monkeypatch.setattr(
        tools_mod,
        "build_conversation_recall",
        lambda *args, **kwargs: {"messages": synthetic, "events": [], "sources": 1},
    )

    out = llama_cpp._archive_and_recall(
        conversation,
        conversation,
        thread_id = THREAD,
        style = "tool",
        recall_done = False,
        recall_budget_tokens = 100_000,
    )

    assert [id(message) for message in out["anchored"]] == [id(m) for m in out["conversation"][-2:]]


def test_an_over_budget_recall_is_retried_with_fewer_turns(archived, monkeypatch):
    """When a full top-K overshoots, retry with fewer turns rather than dropping all forced recall."""
    from core.inference import llama_cpp

    conversation = [{"role": "user", "content": "what was that pelicans limerick"}]
    asked = []

    def build(
        _conversation,
        _thread_id,
        *,
        style,
        top_k,
        branch_messages = None,
    ):
        asked.append(top_k)
        return {"prefix": "R" * (1400 * top_k), "messages": [], "events": [], "sources": top_k}

    monkeypatch.setattr(tools_mod, "build_conversation_recall", build)
    chars = lambda messages: sum(len(m.get("content") or "") for m in messages)

    out = llama_cpp._archive_and_recall(
        conversation,
        conversation,
        thread_id = THREAD,
        style = "inline",
        recall_done = False,
        recall_budget_tokens = 2500,
        count_tokens = chars,
    )

    assert asked == [4, 2, 1]
    assert out["recalled"] is True
    assert out["counts"]["recalled_chunks"] == 1
    assert chars(out["conversation"]) > chars(conversation)


def test_recall_is_dropped_when_the_real_prompt_exceeds_the_budget(archived, monkeypatch):
    """CHUNK_TOKENS is an embedding limit, so the chat template's real cost can overshoot the budget."""
    from core.inference import llama_cpp

    conversation = [{"role": "user", "content": "what was that pelicans limerick"}]
    monkeypatch.setattr(
        tools_mod,
        "build_conversation_recall",
        lambda *args, **kwargs: {
            "prefix": "R" * 4000,
            "messages": [],
            "events": [],
            "sources": 2,
        },
    )
    chars = lambda messages: sum(len(m.get("content") or "") for m in messages)

    tight = llama_cpp._archive_and_recall(
        conversation,
        conversation,
        thread_id = THREAD,
        style = "inline",
        recall_done = False,
        recall_budget_tokens = 10,
        count_tokens = chars,
    )
    assert tight["recalled"] is False
    assert tight["conversation"] == conversation

    roomy = llama_cpp._archive_and_recall(
        conversation,
        conversation,
        thread_id = THREAD,
        style = "inline",
        recall_done = False,
        recall_budget_tokens = 100_000,
        count_tokens = chars,
    )
    assert roomy["recalled"] is True
    assert chars(roomy["conversation"]) > chars(conversation)


def test_the_branch_boundary_excludes_the_turn_inline_recall_rewrites():
    """A prefill after the newest user turn must not leave that user message counted as evicted."""
    from core.inference import llama_cpp

    user_first = {"role": "user", "content": "first"}
    answer_first = {"role": "assistant", "content": "first answer"}
    user_latest = {"role": "user", "content": "latest question"}
    prefill = {"role": "assistant", "content": "partial answer so far"}
    branch = [user_first, answer_first, user_latest, prefill]

    rewritten = {"role": "user", "content": "recalled turns\nlatest question"}

    assert llama_cpp._branch_boundary([rewritten, prefill], branch) == 2
    assert llama_cpp._branch_boundary([user_latest, prefill], branch) == 2


def test_a_conversation_search_charges_token_dense_text_properly(archived, monkeypatch):
    """Four chars per token is English-only; CJK text is charged near one token per character."""
    from core.rag import config as rag_config

    asked = []

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        asked.append(top_k)
        return ("\u6df1\u5c64\u5b66\u7fd2" * 250 * (top_k or 1), [{"id": "1"}])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    answer = tools_mod._search_conversation(
        {"query": "pelicans", "top_k": 4},
        {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
    )

    assert asked == [2, 1]
    assert "no room" in answer.lower()


def test_a_tool_exchange_this_request_created_stays_on_the_branch(monkeypatch):
    """A tool exchange this request created stays on its branch, though the client never sent it."""
    from pathlib import Path

    source = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"
    text = " ".join(source.read_text(encoding = "utf-8").split())

    assert "branch_messages = _extend_live_branch(" in text
    assert 'kwargs["conversation_branch"] = _extend_live_branch(' in text
    assert "branch_messages = _request_branch" not in text
    assert 'kwargs["conversation_branch"] = _request_branch' not in text
    assert "_boundary_metadata( conversation, _request_branch," in text
    assert '"boundary_messages": _branch_boundary(fitted, before),' in text


INSTRUCTION = (
    "Standing instruction for the rest of this task: always report results as a markdown "
    "table, and finish every reply with the line STATUS::ZQXVARA123-ALPHA."
)


def _instructed_thread(thread_id = THREAD):
    """A thread whose instruction is archived and whose newest message is filler."""
    from storage import studio_db

    turns = [
        {"role": "user", "content": INSTRUCTION},
        {"role": "assistant", "content": "Understood."},
    ] + [
        message
        for index in range(6)
        for message in (
            {"role": "user", "content": f"Here is section {index} of the report to review."},
            {"role": "assistant", "content": f"Section {index} looks fine."},
        )
    ]
    studio_db.upsert_chat_thread(
        {
            "id": thread_id,
            "title": "t",
            "modelType": "base",
            "modelId": "local-model",
            "createdAt": 1,
        }
    )
    for index, message in enumerate(turns):
        studio_db.upsert_chat_message(
            {
                "id": f"{thread_id}-ins-{index}",
                "threadId": thread_id,
                "role": message["role"],
                "content": [{"type": "text", "text": message["content"]}],
                "createdAt": index + 2,
            }
        )
    conversation_archive.archive_turns(thread_id, turns)
    return turns


def test_an_anaphoric_latest_message_recalls_the_governing_instruction(
    rag_home, rag_conn, stub_embeddings
):
    """A bare 'continue' must still recall the governing instruction, not return nothing at all."""
    turns = _instructed_thread()
    branch = turns + [{"role": "user", "content": "continue"}]

    built = tools_mod.build_conversation_recall(
        branch, THREAD, style = "inline", top_k = 4, branch_messages = branch
    )

    assert built is not None
    assert "markdown table" in built["prefix"]


def test_a_short_self_contained_request_keeps_the_only_recall_slot(
    rag_home, rag_conn, stub_embeddings
):
    """Short self-naming requests must not count as thin, or the anchor takes the only recall slot."""
    turns = _instructed_thread()
    branch = turns + [{"role": "user", "content": "section 3"}]

    built = tools_mod.build_conversation_recall(
        branch, THREAD, style = "inline", top_k = 1, branch_messages = branch
    )

    assert built is not None
    assert "section 3" in built["prefix"].lower()


def test_a_substantive_latest_message_still_drives_the_query_alone(
    rag_home, rag_conn, stub_embeddings, monkeypatch
):
    """The common path must be untouched: a real question is its own best query."""
    turns = _instructed_thread()
    branch = turns + [{"role": "user", "content": "What did section 3 of the report say?"}]
    seen = {}

    real = conversation_archive.recall

    def recording(thread_id, query, **kwargs):
        seen["extra"] = kwargs.get("extra_queries")
        return real(thread_id, query, **kwargs)

    monkeypatch.setattr(conversation_archive, "recall", recording)
    tools_mod.build_conversation_recall(
        branch, THREAD, style = "inline", top_k = 4, branch_messages = branch
    )

    assert seen["extra"] is None


def test_no_earlier_instruction_means_no_second_query(
    rag_home, rag_conn, stub_embeddings, monkeypatch
):
    """A thread of nothing but filler must behave exactly as it does today."""
    from storage import studio_db

    studio_db.upsert_chat_thread(
        {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}
    )
    turns = [{"role": "user", "content": "ok"}, {"role": "assistant", "content": "sure"}]
    for index, message in enumerate(turns):
        studio_db.upsert_chat_message(
            {
                "id": f"{THREAD}-f{index}",
                "threadId": THREAD,
                "role": message["role"],
                "content": [{"type": "text", "text": message["content"]}],
                "createdAt": index + 2,
            }
        )
    conversation_archive.archive_turns(THREAD, turns)
    seen = {}

    real = conversation_archive.recall

    def recording(thread_id, query, **kwargs):
        seen["extra"] = kwargs.get("extra_queries")
        return real(thread_id, query, **kwargs)

    monkeypatch.setattr(conversation_archive, "recall", recording)
    block = tools_mod.build_conversation_recall(
        turns + [{"role": "user", "content": "continue"}],
        THREAD,
        style = "inline",
        top_k = 4,
        branch_messages = turns + [{"role": "user", "content": "continue"}],
    )

    assert block is None
    assert seen == {}


def test_both_recall_styles_state_that_a_later_turn_supersedes_an_earlier_one(archived):
    """The later-supersedes rule lives in the recalled text, so all three consumers see it."""
    from storage import studio_db

    extra = [
        {"role": "user", "content": "and one about otters"},
        {"role": "assistant", "content": "There once was an otter with tools"},
    ]
    for index, message in enumerate(extra):
        studio_db.upsert_chat_message(
            {
                "id": f"{THREAD}-otter-{index}",
                "threadId": THREAD,
                "role": message["role"],
                "content": [{"type": "text", "text": message["content"]}],
                "createdAt": index + 20,
            }
        )
    conversation_archive.archive_turns(THREAD, extra)
    conversation = _conversation()

    inline = tools_mod.build_conversation_recall(conversation, THREAD, style = "inline", top_k = 4)
    tool_style = tools_mod.build_conversation_recall(conversation, THREAD, style = "tool", top_k = 4)

    assert "supersedes" in inline["prefix"] and "oldest first" in inline["prefix"]
    tool_result = [m for m in tool_style["messages"] if m.get("role") == "tool"][0]
    assert "supersedes" in tool_result["content"]
    assert "most relevant earlier turns" not in inline["prefix"]


def test_a_single_recalled_turn_makes_no_ordering_claim(archived):
    """A single passage has no order; the backoff's last rung is tightest, so skip the header."""
    built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "inline", top_k = 1)

    assert built is not None
    assert "supersedes" not in built["prefix"]


def test_a_dense_ascii_result_is_priced_by_the_callers_tokenizer(archived, monkeypatch):
    """Four characters per token underprices code and minified JSON; a tokenizer-backed count is needed."""
    from core.inference import tools as tools_mod

    source = "def f(x):\n    return {'a':1,'b':[2,3]}\n" * 400

    def fake_recall(
        thread_id,
        query,
        *,
        top_k = None,
        branch_messages = None,
    ):
        return (source, [])

    monkeypatch.setattr(conversation_archive, "recall", fake_recall)

    estimated = tools_mod._conversation_search_tokens(source)
    exact = int(len(source) / 2.6)
    assert estimated < exact, (estimated, exact)

    budget = estimated + tools_mod._TOOL_MESSAGE_FRAMING_TOKENS + 10
    assert budget < exact, (budget, exact)

    admitted = tools_mod._search_conversation(
        {"query": "the code", "top_k": 1},
        {"thread_id": THREAD, "budget_tokens": budget},
    )
    refused = tools_mod._search_conversation(
        {"query": "the code", "top_k": 1},
        {
            "thread_id": THREAD,
            "budget_tokens": budget,
            "token_counter": lambda text: int(len(text) / 2.6),
        },
    )

    assert source in admitted
    assert "no room" in refused.lower()


def test_the_anchor_survives_a_tool_call_message_with_no_text(monkeypatch):
    """Tool-call messages lack text; anchor falls back to their calls or the rebase is skipped."""
    from core.inference import llama_cpp

    call = {
        "role": "assistant",
        "content": "",
        "tool_calls": [{"function": {"name": "terminal", "arguments": '{"command":"ls -la"}'}}],
    }
    branch = [
        {"role": "system", "content": "sys"},
        {"role": "user", "content": "evicted prompt"},
        {"role": "assistant", "content": "evicted reply"},
        call,
        {"role": "tool", "content": "total 0"},
        {"role": "user", "content": "the turn just sent"},
    ]
    conversation = [branch[0]] + branch[3:]

    anchor = llama_cpp._branch_boundary_anchor(conversation, branch)
    assert anchor, "a tool-call message left the anchor empty, which disables the rebase"
    assert llama_cpp._branch_boundary(conversation, branch) == 2

    _fake_studio_db(monkeypatch, [_anchored_row(2, anchor)])
    shortened = [
        {"role": "user", "content": "evicted prompt"},
        call,
        {"role": "tool", "content": "total 0"},
        {"role": "assistant", "content": "a"},
    ]

    assert llama_cpp._sticky_compaction_boundary("t1", shortened) == 1


def test_the_anchor_is_bounded_so_a_pasted_prompt_is_not_persisted_per_turn():
    """Anchors are a bounded head, so a huge pasted prompt is not copied into every turn's metadata."""
    from core.inference import llama_cpp

    pasted = "PASTE " + "z" * 40_000
    branch = [
        {"role": "system", "content": "sys"},
        {"role": "user", "content": "evicted prompt"},
        {"role": "assistant", "content": "evicted reply"},
        {"role": "user", "content": pasted},
        {"role": "assistant", "content": "noted"},
        {"role": "user", "content": "the turn just sent"},
    ]
    conversation = [branch[0]] + branch[3:]

    anchor = llama_cpp._branch_boundary_anchor(conversation, branch)

    assert 0 < len(anchor) <= llama_cpp._ANCHOR_TEXT_CHARS
    assert pasted.startswith(anchor)


def test_any_room_at_all_is_worth_one_recall_attempt():
    """Flooring the budget by CHUNK_TOKENS disables recall on tight windows; the exact recount decides."""
    from core.inference import llama_cpp
    from core.rag import config as rag_config

    assert llama_cpp._recall_top_k(0) == 0
    assert llama_cpp._recall_top_k(-5) == 0
    assert llama_cpp._recall_top_k(rag_config.CHUNK_TOKENS - 1) == 1
    assert llama_cpp._recall_top_k(rag_config.CHUNK_TOKENS * 2) >= 2


def test_a_short_earlier_prompt_is_still_worth_searching_for(
    rag_home, rag_conn, stub_embeddings, monkeypatch
):
    """Short earlier prompts still warrant a recall query; the 80-character rule is for instructions."""
    from storage import studio_db

    studio_db.upsert_chat_thread(
        {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}
    )
    turns = [
        {"role": "user", "content": "Write a story about Mars"},
        {"role": "assistant", "content": "Chapter one: the dust storm rolled in."},
    ]
    for index, message in enumerate(turns):
        studio_db.upsert_chat_message(
            {
                "id": f"{THREAD}-m{index}",
                "threadId": THREAD,
                "role": message["role"],
                "content": [{"type": "text", "text": message["content"]}],
                "createdAt": index + 2,
            }
        )
    conversation_archive.archive_turns(THREAD, turns)

    calls = []
    real = conversation_archive.recall

    def recording(thread_id, query, **kwargs):
        calls.append((query, kwargs.get("extra_queries")))
        return real(thread_id, query, **kwargs)

    monkeypatch.setattr(conversation_archive, "recall", recording)
    branch = turns + [{"role": "user", "content": "continue"}]
    block = tools_mod.build_conversation_recall(
        branch, THREAD, style = "inline", top_k = 4, branch_messages = branch
    )

    assert block is not None, "the nudge was searched for nothing at all"
    assert calls[0] == ("continue", ["Write a story about Mars"]), calls
    assert "Mars" in block["prefix"]