Skip to content

Personal AI, On Personal Devices

Python
8.5 KB
Raw Blame
"""Tests for ``jarvis memory`` CLI commands."""

from __future__ import annotations

import importlib
from pathlib import Path

from click.testing import CliRunner

from openjarvis.cli import cli
from openjarvis.core.registry import MemoryRegistry
from openjarvis.memory.store import LocalFactStore
from openjarvis.tools.storage.sqlite import SQLiteMemory


def _register_sqlite():
    """Re-register sqlite backend (conftest clears registries)."""
    if not MemoryRegistry.contains("sqlite"):
        MemoryRegistry.register_value("sqlite", SQLiteMemory)


def test_memory_index_file(tmp_path: Path, monkeypatch):
    """Index a single text file and check success message."""
    _register_sqlite()
    db_path = str(tmp_path / "mem.db")

    # Create a text file with enough content
    doc = tmp_path / "doc.txt"
    doc.write_text(" ".join(f"word{i}" for i in range(100)))

    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    monkeypatch.setattr(
        mod,
        "_get_backend",
        lambda b=None: SQLiteMemory(db_path=db_path),
    )

    result = CliRunner().invoke(cli, ["memory", "index", str(doc)])
    assert result.exit_code == 0
    assert "Indexed" in result.output or "chunk" in result.output


def test_memory_index_replaces_existing_source(tmp_path: Path, monkeypatch):
    """Re-indexing a file replaces its previous chunks."""
    _register_sqlite()
    db_path = str(tmp_path / "mem.db")
    doc = tmp_path / "doc.txt"
    doc.write_text(" ".join(["legacy"] * 100), encoding="utf-8")

    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    monkeypatch.setattr(
        mod,
        "_get_backend",
        lambda b=None: SQLiteMemory(db_path=db_path),
    )

    first = CliRunner().invoke(cli, ["memory", "index", str(doc)])
    assert first.exit_code == 0

    doc.write_text(" ".join(["updated"] * 100), encoding="utf-8")
    second = CliRunner().invoke(cli, ["memory", "index", str(doc)])
    assert second.exit_code == 0

    backend = SQLiteMemory(db_path=db_path)
    assert backend.count() == 1
    assert backend.retrieve("legacy") == []
    updated = backend.retrieve("updated")
    assert len(updated) == 1
    assert updated[0].source == str(doc)


def test_memory_index_nonexistent(tmp_path: Path):
    """Indexing a nonexistent path should fail."""
    _register_sqlite()
    result = CliRunner().invoke(cli, ["memory", "index", str(tmp_path / "nope")])
    assert result.exit_code != 0


def test_memory_index_rejects_non_progress_chunk_values(tmp_path: Path):
    doc = tmp_path / "doc.txt"
    doc.write_text("a b", encoding="utf-8")

    zero_size = CliRunner().invoke(
        cli,
        ["memory", "index", str(doc), "--chunk-size", "0"],
    )
    negative_overlap = CliRunner().invoke(
        cli,
        ["memory", "index", str(doc), "--chunk-overlap", "-1"],
    )

    assert zero_size.exit_code != 0
    assert "0 is not in the range x>=1" in zero_size.output
    assert negative_overlap.exit_code != 0
    assert "-1 is not in the range x>=0" in negative_overlap.output


def test_memory_search_returns_results(tmp_path: Path, monkeypatch):
    """Search returns results from pre-populated backend."""
    _register_sqlite()
    db_path = str(tmp_path / "mem.db")
    backend = SQLiteMemory(db_path=db_path)
    backend.store(
        "Python programming language guide",
        source="guide.md",
    )

    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    monkeypatch.setattr(
        mod,
        "_get_backend",
        lambda b=None: SQLiteMemory(db_path=db_path),
    )

    result = CliRunner().invoke(cli, ["memory", "search", "Python"])
    assert result.exit_code == 0
    assert "Python" in result.output
    backend.close()


def test_memory_search_no_results(tmp_path: Path, monkeypatch):
    """Search with no matches shows appropriate message."""
    _register_sqlite()
    db_path = str(tmp_path / "mem.db")
    backend = SQLiteMemory(db_path=db_path)
    backend.store("some unrelated content about cats")

    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    monkeypatch.setattr(
        mod,
        "_get_backend",
        lambda b=None: SQLiteMemory(db_path=db_path),
    )

    result = CliRunner().invoke(cli, ["memory", "search", "quantum supercollider"])
    assert result.exit_code == 0
    assert "No results" in result.output
    backend.close()


def test_memory_stats_shows_count(tmp_path: Path, monkeypatch):
    """Stats command shows document count."""
    _register_sqlite()
    db_path = str(tmp_path / "mem.db")
    backend = SQLiteMemory(db_path=db_path)
    backend.store("doc one")
    backend.store("doc two")

    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    monkeypatch.setattr(
        mod,
        "_get_backend",
        lambda b=None: SQLiteMemory(db_path=db_path),
    )

    result = CliRunner().invoke(cli, ["memory", "stats"])
    assert result.exit_code == 0
    assert "2" in result.output
    backend.close()


def _patch_fact_store(monkeypatch, tmp_path: Path) -> LocalFactStore:
    """Point ``jarvis memory list/clear`` at a temp fact store."""
    mod = importlib.import_module("openjarvis.cli.memory_cmd")
    store = LocalFactStore(tmp_path / "facts.jsonl")
    monkeypatch.setattr(mod, "_get_fact_store", lambda: store)
    return store


def test_memory_list_empty(tmp_path: Path, monkeypatch):
    _patch_fact_store(monkeypatch, tmp_path)
    result = CliRunner().invoke(cli, ["memory", "list"])
    assert result.exit_code == 0
    assert "No memory facts" in result.output


def test_memory_list_shows_facts(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("User prefers dark mode")
    store.add("User lives in Berlin")

    result = CliRunner().invoke(cli, ["memory", "list"])
    assert result.exit_code == 0
    assert "dark mode" in result.output
    assert "Berlin" in result.output


def test_memory_list_marks_only_quarantined_facts(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("clean auto note", source="auto", trust="auto")
    store.add("flagged note", source="auto", trust="untrusted")

    result = CliRunner().invoke(cli, ["memory", "list"])
    assert result.exit_code == 0
    assert "quarantined" in result.output.lower()
    assert "excluded from model recall" in result.output.lower()


def test_memory_list_without_quarantine_shows_no_warning(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("clean auto note", source="auto", trust="auto")

    result = CliRunner().invoke(cli, ["memory", "list"])
    assert result.exit_code == 0
    assert "quarantined" not in result.output.lower()


def test_memory_trust_promotes_a_quarantined_fact(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("flagged note", source="auto", trust="untrusted")
    assert store.list()[0].trusted_for_recall is False

    result = CliRunner().invoke(cli, ["memory", "trust", "1"])

    assert result.exit_code == 0
    assert store.list()[0].trust == "trusted"
    assert store.list()[0].trusted_for_recall is True


def test_memory_trust_rejects_an_unknown_index(tmp_path: Path, monkeypatch):
    _patch_fact_store(monkeypatch, tmp_path).add("only note", trust="untrusted")

    result = CliRunner().invoke(cli, ["memory", "trust", "4"])

    assert result.exit_code != 0
    assert "no fact #4" in result.output.lower()


def test_memory_clear_with_confirmation(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("fact one")
    store.add("fact two")

    result = CliRunner().invoke(cli, ["memory", "clear"], input="y\n")
    assert result.exit_code == 0
    assert "Cleared 2" in result.output
    assert store.count() == 0


def test_memory_clear_aborted(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("keep me")

    result = CliRunner().invoke(cli, ["memory", "clear"], input="n\n")
    assert result.exit_code == 0
    assert "Aborted" in result.output
    assert store.count() == 1


def test_memory_clear_yes_flag(tmp_path: Path, monkeypatch):
    store = _patch_fact_store(monkeypatch, tmp_path)
    store.add("fact")

    result = CliRunner().invoke(cli, ["memory", "clear", "--yes"])
    assert result.exit_code == 0
    assert "Cleared 1" in result.output
    assert store.count() == 0


def test_memory_clear_empty(tmp_path: Path, monkeypatch):
    _patch_fact_store(monkeypatch, tmp_path)
    result = CliRunner().invoke(cli, ["memory", "clear"])
    assert result.exit_code == 0
    assert "No memory facts to clear" in result.output