Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

7.8 KB
Raw Blame
"""Unit tests for the persona loader (`dodaios.brain.persona_loader`).

Covers:
- Extraction of the first code fence after `## System-Prompt`.
- Cache behavior (lru_cache + invalidate).
- Missing file / missing fence → empty string (no raise).
"""
from __future__ import annotations

import importlib.util
from pathlib import Path

# `dodaios.brain.__init__` pulls in the BrainManager + safety chain —
# the latter had WIP dependencies outside this scope at refactor time.
# The persona loader itself has no brain imports, so we isolate it
# with `importlib.util` from the file path.
_loader_spec = importlib.util.spec_from_file_location(
    "dodaios.brain.persona_loader",
    Path(__file__).resolve().parents[3]
    / "dodaios"
    / "brain"
    / "persona_loader.py",
)
assert _loader_spec is not None and _loader_spec.loader is not None
pl = importlib.util.module_from_spec(_loader_spec)
_loader_spec.loader.exec_module(pl)

_extract_fence_after_marker = pl._extract_fence_after_marker
invalidate_cache = pl.invalidate_cache
load_persona_prompt = pl.load_persona_prompt


def test_extract_fence_returns_code_block_body() -> None:
    md = (
        "# Title\n"
        "Some intro.\n"
        "## System-Prompt\n"
        "\n"
        "```\n"
        "You are JARVIS.\n"
        "Be concise.\n"
        "```\n"
        "\n"
        "## Sources\n"
    )
    block = _extract_fence_after_marker(md)
    assert "You are JARVIS." in block
    assert "Be concise." in block
    # The "Sources" section after it must not be included
    assert "Sources" not in block


def test_extract_fence_ignores_fences_before_marker() -> None:
    md = (
        "```\n"
        "This fence is BEFORE the marker.\n"
        "```\n"
        "## System-Prompt\n"
        "```\n"
        "Real prompt.\n"
        "```\n"
    )
    block = _extract_fence_after_marker(md)
    assert "Real prompt." in block
    assert "BEFORE the marker" not in block


def test_extract_fence_missing_marker_returns_empty() -> None:
    md = "# Title\n```\nprompt\n```\n"
    assert _extract_fence_after_marker(md) == ""


def test_extract_fence_missing_fence_returns_empty() -> None:
    md = "## System-Prompt\n\nNo fence here, just prose.\n"
    assert _extract_fence_after_marker(md) == ""


def test_load_persona_prompt_extracts_real_persona(monkeypatch) -> None:
    """Integration test against the real DODAIOS_PERSONA.md in the repo.

    Checks sections that have been live in the MD since persona mandate
    phase 2 (2026-04-25) — critical for the hangup contract and echo
    protection.
    """
    invalidate_cache()
    try:
        prompt = load_persona_prompt()
    finally:
        invalidate_cache()
    assert prompt
    # Name-neutral persona (2026-06-29): the assistant name is injected at
    # runtime from the wake word (see assistant_name.py), so the default persona
    # must NOT bake in a fixed product name like "Jarvis". This guards against a
    # regression back to a hardcoded "You are JARVIS" opener.
    assert "JARVIS" not in prompt
    assert "voice companion" in prompt
    assert "LANGUAGE POLICY" in prompt
    # The speech-transcript fact (merged from the router prompt): a sound-alike
    # name is the one under discussion.
    assert "sound-alike" in prompt
    # The host-owned two-turn confirmation must reach the brain. A farewell
    # alone must never be presented as sufficient consent to end the call.
    assert "Voice hang-up always requires confirmation" in prompt
    assert "separate explicit yes" in prompt


def test_compact_persona_is_the_full_short_block() -> None:
    """There is no separate compact persona: the full block is short enough
    for small self-hosted brains too."""
    invalidate_cache()
    try:
        full = load_persona_prompt()
        compact = pl.load_compact_persona_prompt()
    finally:
        invalidate_cache()
    assert compact == full
    assert len(full) < 1200


def test_compact_falls_back_to_full_when_section_missing(
    monkeypatch, tmp_path
) -> None:
    """A persona that silently shrank to nothing would change the voice;
    a missing compact section must serve the full block instead."""
    invalidate_cache()
    md_file = tmp_path / "DODAIOS_PERSONA.md"
    md_file.write_text(
        "## System-Prompt\n```\nFull only.\n```\n", encoding="utf-8"
    )
    monkeypatch.setattr(pl, "_persona_md_path", lambda: md_file)
    try:
        assert pl.load_compact_persona_prompt() == "Full only."
    finally:
        invalidate_cache()


def test_custom_override_wins_even_in_compact_mode(monkeypatch, tmp_path) -> None:
    """User autonomy outranks the latency optimization: their exact words
    stay, whatever profile the provider asked for."""
    invalidate_cache()
    monkeypatch.setattr(pl, "read_custom_prompt", lambda: "My own words.")
    try:
        assert pl.load_effective_persona_prompt(compact=True) == "My own words."
        assert pl.load_effective_persona_prompt(compact=False) == "My own words."
    finally:
        invalidate_cache()


def test_load_persona_prompt_missing_file_returns_empty(monkeypatch, tmp_path) -> None:
    """When the MD is missing, the loader returns an empty string — no raise."""
    invalidate_cache()
    fake_missing = tmp_path / "does_not_exist.md"
    monkeypatch.setattr(pl, "_persona_md_path", lambda: fake_missing)
    try:
        assert load_persona_prompt() == ""
    finally:
        invalidate_cache()


def test_load_persona_prompt_cache_reuses_read(monkeypatch, tmp_path) -> None:
    """`load_persona_prompt` reads the file only once per cache window."""
    invalidate_cache()
    md_file = tmp_path / "DODAIOS_PERSONA.md"
    md_file.write_text(
        "## System-Prompt\n```\nFirst version.\n```\n", encoding="utf-8"
    )
    monkeypatch.setattr(pl, "_persona_md_path", lambda: md_file)
    try:
        first = load_persona_prompt()
        assert "First version." in first
        # Change the file — without invalidate, the cached value stays.
        md_file.write_text(
            "## System-Prompt\n```\nSecond version.\n```\n", encoding="utf-8"
        )
        cached = load_persona_prompt()
        assert cached == first  # cache hit
        invalidate_cache()
        fresh = load_persona_prompt()
        assert "Second version." in fresh
    finally:
        invalidate_cache()


def test_load_persona_prompt_crlf_normalized(monkeypatch, tmp_path) -> None:
    """Windows CRLF is processed as LF."""
    invalidate_cache()
    md_file = tmp_path / "DODAIOS_PERSONA.md"
    md_file.write_bytes(
        b"## System-Prompt\r\n```\r\nCRLF content.\r\n```\r\n"
    )
    monkeypatch.setattr(pl, "_persona_md_path", lambda: md_file)
    try:
        prompt = load_persona_prompt()
        assert "CRLF content." in prompt
    finally:
        invalidate_cache()


def test_persona_loader_path_points_to_real_file() -> None:
    """Sanity: the default path points to an existing file."""
    path = pl._persona_md_path()
    assert isinstance(path, Path)
    assert path.exists(), f"expected: {path} exists"


def test_persona_ends_with_the_ending_the_call_section() -> None:
    """The realtime path cuts ``ENDING THE CALL`` to the end of the text, so the
    section must be the last one; the legacy sentinel is gone."""
    from dodaios.brain.persona_loader import invalidate_cache, load_persona_prompt
    from dodaios.realtime.session import _realtime_persona
    from dodaios.speech.hangup import END_CALL_SIGNAL

    invalidate_cache()
    try:
        prompt = load_persona_prompt()
    finally:
        invalidate_cache()
    assert prompt, "persona fence must load"
    assert END_CALL_SIGNAL not in prompt
    lines = prompt.rstrip().splitlines()
    heading = lines.index("ENDING THE CALL")
    assert all(line == line.lstrip() and not line.isupper() for line in lines[heading + 1 :])
    stripped = _realtime_persona(prompt)
    assert "ENDING THE CALL" not in stripped
    assert "REPORTING RESULTS" in stripped