"""Tests for the Traffic Pattern Learner. Tests pattern extraction from proxy traffic without requiring a real memory backend. """ from __future__ import annotations import asyncio import threading from datetime import datetime, timedelta, timezone import pytest from headroom.memory.traffic_learner import ( ExtractedPattern, PatternCategory, TrafficLearner, _bash_binaries_match, _bash_first_binary, _commands_related_as_retry, _drop_contradictions, _levenshtein, _load_persisted_patterns_from_sqlite, _normalize_bash_for_hash, _parse_iso_timestamp, _paths_related_as_typo, _patterns_to_recommendations, _project_for_pattern, _refine_error_recovery, ) UTC = timezone.utc # ============================================================================= # Error Classification Tests # ============================================================================= class TestErrorClassification: """The learner classifies tool output with the shared learn classifier.""" @pytest.fixture def learner(self): return TrafficLearner(backend=None, user_id="test-user", min_evidence=1) @staticmethod def _openai_result(learner: TrafficLearner, output: str) -> dict: messages = [ { "role": "assistant", "tool_calls": [ {"id": "c1", "function": {"name": "shell", "arguments": '{"command": "ls"}'}} ], }, {"role": "tool", "tool_call_id": "c1", "content": output}, ] return learner.extract_tool_results_from_openai_messages(messages)[0] @pytest.mark.parametrize( ("output", "is_error"), [ # Successful shell commands from Codex/Grok/opencode end in "exit code 0". ("Process exited with exit code 0\nall tests passed", False), ("README.md\nsrc\nexit code 0", False), # Nonzero exit codes and other exit-failure wording. ("Exit code: 1\nWall time: 0.2s\nOutput:\nfail", True), ("exit code 2", True), ("Command failed with non-zero status 1", True), ("process exited with status 1", True), ("x" * 1500 + "\nexit code 3", True), ("command terminated\nexit code -9", True), ("Process exited with exit code -1", True), # A zero wrapper status must not hide a separate failure. ("worker exited with signal 9\nexit code 0", True), ("child exit code 2\nwrapper exit code 0", True), ("python train.py\nKilled\n", True), # A successful command may print the word; exit code 0 then wins. ("grep result:\nKilled\nexit code 0", False), ("task killed by signal SIGKILL\nexit code 0", True), # A bare Killed is an error even below the short-content cut-off, # but a reported zero status wins over a printed "Killed". ("Killed", True), ("Killed\nexit code 0", False), # The wrapper's zero status belongs to its own line. ("worker exited with an error\nwrapper exit code 0", True), # One status phrase wrapped across lines is still one zero status. ("Process exited with\nexit code 0", False), ("Killed: 9", True), # Case-insensitive signals the shared is_error_content would miss. ("zsh: no such file or directory: ./run.sh", True), ("fatal: path 'x' does not exist in 'HEAD'", True), ("open /etc/shadow: permission denied", True), ("EACCES: permission denied, open '/x'", True), ("Operation not permitted (EPERM) on /x", True), ("File content exceeds maximum allowed tokens limit (25000)", True), ("file is too large to read", True), ("Exception: something broke badly", True), ("context deadline exceeded while dialing", True), ("x" * 1500 + "\nTraceback (most recent call last):\nValueError: late", True), # Signals the old detector already caught. ("No such file or directory: foo.py", True), ("ModuleNotFoundError: No module named 'foo'", True), ("zsh: command not found: ruff", True), ("Tool call auto-denied by policy", True), ("IndentationError: unexpected indent here", True), ("TimeoutError: deadline exceeded after 30s", True), ("Command timed out after 120s", True), ("BUILD FAILED in 3s", True), # Not errors. ("All tests passed, everything is fine", False), ("2 failed, 10 passed in 1.2s", False), ("Checked 4 files, no errors found in output", False), ("short", False), ("", False), ], ) def test_error_detection(self, learner: TrafficLearner, output: str, is_error: bool): assert self._openai_result(learner, output)["is_error"] is is_error @pytest.mark.asyncio @pytest.mark.parametrize( ("output", "category"), [ ("No such file or directory: foo.py", "file_not_found"), ("zsh: command not found: ruff", "command_not_found"), ("ModuleNotFoundError: No module named 'foo'", "module_not_found"), ("Permission denied: /etc/shadow", "permission_denied"), ("TimeoutError: deadline exceeded after 30s", "timeout"), ("ConnectionError: [Errno 111] Connection refused", "connection_error"), ("task killed by signal SIGKILL", "exit_code"), ("python train.py\nKilled", "exit_code"), ("Killed: 9", "exit_code"), ], ) async def test_error_category_recorded( self, learner: TrafficLearner, output: str, category: str ): await learner.on_tool_result( tool_name="Bash", tool_input={"command": "x"}, tool_output=output, is_error=True ) assert learner._tool_history[-1]["error_category"] == category @pytest.mark.asyncio @pytest.mark.parametrize( ("output", "is_error", "category"), [ ("Killed", True, "exit_code"), ("worker exited with an error\nwrapper exit code 0", True, "exit_code"), ("Killed\nexit code 0", False, None), ("README.md\nsrc\nexit code 0", False, None), ("worker killed by signal SIGKILL\nwrapper exit code 0", True, "exit_code"), ("command terminated\nexit code -9", True, "exit_code"), ], ) async def test_openai_result_recorded_through_on_tool_result( self, learner: TrafficLearner, output: str, is_error: bool, category: str | None ): """End to end: the OpenAI extractor's verdict is what on_tool_result records.""" result = self._openai_result(learner, output) await learner.on_tool_result( tool_name=result["tool_name"], tool_input=result["input"], tool_output=result["output"], is_error=result["is_error"], ) recorded = learner._tool_history[-1] assert recorded["is_error"] is is_error assert recorded["error_category"] == category @pytest.mark.asyncio async def test_success_has_no_error_category(self, learner: TrafficLearner): await learner.on_tool_result( tool_name="Bash", tool_input={"command": "x"}, tool_output="Everything is fine, tests passed!", is_error=False, ) assert learner._tool_history[-1]["error_category"] is None # ============================================================================= # Recovery-pair relatedness heuristics # ============================================================================= class TestPathsRelatedAsTypo: def test_identical_basename_different_dir_is_typo(self): # Same file in two locations — common path-typo case. assert _paths_related_as_typo("/a/state.rs", "/b/state.rs") def test_close_basename_is_typo(self): assert _paths_related_as_typo("/a/staet.rs", "/a/state.rs") assert _paths_related_as_typo("/a/App.tsx", "/a/app.tsx") def test_unrelated_files_in_same_dir_rejected(self): # The motivating bug: state.rs and lib.rs are unrelated files, # not typos, and should never be paired into a recovery rule. assert not _paths_related_as_typo("/src-tauri/src/state.rs", "/src-tauri/src/lib.rs") assert not _paths_related_as_typo("/x/models.py", "/x/views.py") def test_empty_or_equal_paths_rejected(self): assert not _paths_related_as_typo("", "/a/x") assert not _paths_related_as_typo("/a/x", "") assert not _paths_related_as_typo("/a/x", "/a/x") class TestCommandsRelatedAsRetry: def test_python_to_python3_is_retry(self): assert _commands_related_as_retry("python test.py", "python3 test.py") def test_path_prefixed_binary_is_retry(self): assert _commands_related_as_retry("ruff check .", ".venv/bin/ruff check .") def test_extra_flag_is_retry(self): assert _commands_related_as_retry("cargo build", "cargo build --release") def test_different_binaries_rejected(self): assert not _commands_related_as_retry("grep -n foo bar.rs", "find . -name foo") def test_same_binary_unrelated_args_rejected(self): # The motivating bug: two grep calls sharing nothing but the # binary should not pair up. Different needles, different files. failed = ( 'grep -nE "smoke|HEADROOM_SMOKE_TEST_TIMEOUT|smoke_test" ' "/Users/x/src-tauri/src/tool_manager.rs 2>&1 | head -20" ) success = ( 'grep -nE "fn hf_hub_cache_dir|HF_HOME|HUGGINGFACE_HUB_CACHE" ' "/Users/x/src-tauri/src/state.rs 2>&1 | head -10" ) assert not _commands_related_as_retry(failed, success) def test_shared_cd_prefix_alone_is_not_retry(self): # Agents prefix most commands with the same `cd &&`; that shared # prefix used to satisfy both the binary and the token-overlap checks. cd = 'cd "C:\\Users\\dev\\my-project" && ' assert not _commands_related_as_retry( cd + "npx vitest run src/form.test.tsx", cd + "git add -A && git commit -F -" ) assert not _commands_related_as_retry( "cd /home/dev/my-project && sed -n '90,130p' app/actions.ts", "cd /home/dev/my-project && cat components/icons.ts", ) def test_cd_prefixed_retry_still_matches(self): assert _commands_related_as_retry( "cd /home/dev/proj && cargo build", "cd /home/dev/proj && cargo build --release" ) def test_empty_or_equal_commands_rejected(self): assert not _commands_related_as_retry("", "ls") assert not _commands_related_as_retry("ls", "") assert not _commands_related_as_retry("ls", "ls") class TestDropContradictions: def _read_recovery(self, failed: str, success: str) -> ExtractedPattern: return ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content=f"File `{failed}` does not exist. The correct path is `{success}`.", importance=0.7, entity_refs=[success], metadata={"error_category": "file_not_found", "failed_path": failed}, evidence_count=5, ) def test_drops_inverse_pairs(self): a_to_b = self._read_recovery("/x/a.rs", "/x/b.rs") b_to_a = self._read_recovery("/x/b.rs", "/x/a.rs") keep = self._read_recovery("/x/c.rs", "/x/d.rs") cleaned = _drop_contradictions([a_to_b, b_to_a, keep]) assert keep in cleaned assert a_to_b not in cleaned assert b_to_a not in cleaned def test_passthrough_when_no_inverse(self): a_to_b = self._read_recovery("/x/a.rs", "/x/b.rs") cleaned = _drop_contradictions([a_to_b]) assert cleaned == [a_to_b] def test_only_filters_error_recovery_category(self): env_pattern = ExtractedPattern( category=PatternCategory.ENVIRONMENT, content="File `x` does not exist. The correct path is `y`.", # text alone importance=0.5, evidence_count=5, ) cleaned = _drop_contradictions([env_pattern]) assert cleaned == [env_pattern] def test_skips_error_recovery_with_non_canonical_content(self): """Bash recoveries don't match the Read regex; skip without crashing.""" bash_pattern = ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content="Command `foo` fails (exit_code). Use `bar` instead.", importance=0.7, evidence_count=5, ) cleaned = _drop_contradictions([bash_pattern]) assert cleaned == [bash_pattern] # ============================================================================= # Helper edge cases (branch coverage) # ============================================================================= class TestLevenshtein: def test_equal_returns_zero(self): assert _levenshtein("abc", "abc") == 0 def test_empty_a_returns_len_b(self): assert _levenshtein("", "abc") == 3 def test_empty_b_returns_len_a(self): assert _levenshtein("abc", "") == 3 def test_swap_when_a_longer(self): # Triggers the `len(a) > len(b)` swap branch. assert _levenshtein("abcdef", "abc") == 3 def test_simple_substitution(self): assert _levenshtein("kitten", "sitting") == 3 class TestBashFirstBinary: def test_empty_returns_none(self): assert _bash_first_binary("") is None assert _bash_first_binary(" ") is None def test_strips_source_venv_prefix(self): assert _bash_first_binary("source .venv/bin/activate && pytest -x") == "pytest" def test_skips_env_var_assignments(self): assert _bash_first_binary("FOO=bar BAZ=qux python script.py") == "python" def test_returns_first_token_otherwise(self): assert _bash_first_binary("cargo test --release") == "cargo" class TestBashBinariesMatch: def test_equal_strings_match(self): # Direct equality short-circuit; not exercised by the typical retry flow. assert _bash_binaries_match("cargo", "cargo") def test_basename_match_across_paths(self): assert _bash_binaries_match("ruff", ".venv/bin/ruff") assert _bash_binaries_match("/usr/bin/python3", "python3") def test_prefix_version_match(self): assert _bash_binaries_match("python", "python3") def test_unrelated_binaries_do_not_match(self): assert not _bash_binaries_match("grep", "find") class TestPathsRelatedAsTypoEdgeCases: def test_root_paths_rejected(self): # After basename strip both sides become empty. assert not _paths_related_as_typo("/", "/") class TestCommandsRelatedAsRetrySubstantiveToken: def test_substantive_token_beats_distance(self): # Edit distance is too high to pass the 40% gate, but both commands # share the substantive token "headroom-config", so the token-overlap # path accepts the pair. failed = "python -m foo --headroom-config=/etc/h.toml" success = "python -m bar --headroom-config=/etc/h.toml --extra" assert _commands_related_as_retry(failed, success) # ============================================================================= # Traffic Learner Core Tests # ============================================================================= class TestTrafficLearner: @pytest.fixture def learner(self): """Create a learner with low evidence threshold for testing.""" return TrafficLearner( backend=None, user_id="test-user", min_evidence=1, # Save on first sighting for tests ) @pytest.mark.asyncio async def test_error_recovery_bash(self, learner: TrafficLearner): """Test error→recovery pattern extraction for Bash commands.""" # First: a failed command await learner.on_tool_result( tool_name="Bash", tool_input={"command": "ruff check ."}, tool_output="zsh: command not found: ruff", is_error=True, ) # Then: the recovery await learner.on_tool_result( tool_name="Bash", tool_input={"command": "source .venv/bin/activate && ruff check ."}, tool_output="All checks passed!", is_error=False, ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 1 assert stats["requests_processed"] == 2 @pytest.mark.asyncio async def test_error_recovery_read(self, learner: TrafficLearner): """Test error→recovery for Read tool (wrong path → correct path).""" await learner.on_tool_result( tool_name="Read", tool_input={"file_path": "/src/old_module.py"}, tool_output="No such file or directory: /src/old_module.py", is_error=True, ) await learner.on_tool_result( tool_name="Read", tool_input={"file_path": "/src/new_module.py"}, tool_output="# Module content here\nclass Foo: pass", is_error=False, ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 1 @pytest.mark.asyncio async def test_environment_venv_detection(self, learner: TrafficLearner): """Test detection of virtual environment activation patterns.""" await learner.on_tool_result( tool_name="Bash", tool_input={"command": "source /project/.venv/bin/activate && pytest"}, tool_output="5 passed in 2.1s", is_error=False, ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 1 @pytest.mark.asyncio async def test_preference_extraction(self, learner: TrafficLearner): """Test extraction of user preference signals.""" await learner.on_messages( [ {"role": "user", "content": "don't use git push, I'll push manually"}, ] ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 1 @pytest.mark.asyncio async def test_preference_from_content_blocks(self, learner: TrafficLearner): """Test preference extraction from Anthropic content block format.""" await learner.on_messages( [ { "role": "user", "content": [ {"type": "text", "text": "stop running the full test suite without asking"}, ], }, ] ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 1 @pytest.mark.asyncio async def test_evidence_accumulation(self): """Test that patterns need min_evidence before saving.""" learner = TrafficLearner(backend=None, min_evidence=3) # Same error→recovery pattern 3 times for _ in range(3): await learner.on_tool_result( tool_name="Bash", tool_input={"command": "python test.py"}, tool_output="command not found: python", is_error=True, ) await learner.on_tool_result( tool_name="Bash", tool_input={"command": "python3 test.py"}, tool_output="OK", is_error=False, ) stats = learner.get_stats() assert stats["patterns_extracted"] >= 3 def test_pending_accumulator_is_bounded(self): """One-off patterns that never reach ``min_evidence`` must not grow the pending ``_pattern_counts`` accumulator without bound — the sibling ``_saved_hashes`` is already trimmed to ``dedup_window`` and this one was missed, so a long-lived proxy leaked memory across varied traffic. It is now LRU-capped at ``max_pending_patterns``. Sync test (drives the async accumulate via ``asyncio.run``) so it runs without the pytest-asyncio plugin. """ import asyncio learner = TrafficLearner(backend=None, min_evidence=5, max_pending_patterns=8) async def feed_one_offs() -> None: for i in range(500): await learner._accumulate( ExtractedPattern( category=PatternCategory.PREFERENCE, content=f"one-off pattern number {i}", importance=0.5, ) ) asyncio.run(feed_one_offs()) assert len(learner._pattern_counts) <= 8 # capped, not 500 @pytest.mark.asyncio async def test_extract_tool_results_from_messages(self, learner: TrafficLearner): """Test extraction of tool results from Anthropic message format.""" messages = [ { "role": "assistant", "content": [ { "type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls"}, } ], }, { "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "tu_1", "content": [{"type": "text", "text": "file1.py\nfile2.py"}], } ], }, ] results = learner.extract_tool_results_from_messages(messages) assert len(results) == 1 assert results[0]["tool_name"] == "Bash" assert "file1.py" in results[0]["output"] assert not results[0]["is_error"] def test_extract_tool_results_from_openai_messages(self, learner: TrafficLearner): """OpenAI chat/completions tool results: assistant tool_calls + role:tool. Regression for the chat-path portion of #2060 — the extractor must resolve the tool name from the assistant ``tool_calls`` id map, parse the ``arguments`` JSON string into a dict (so downstream ``input.get(...)`` works), join list content, and sniff errors from the output. """ messages = [ {"role": "user", "content": "run the tests"}, { "role": "assistant", "content": None, "tool_calls": [ { "id": "call_1", "type": "function", "function": {"name": "bash", "arguments": '{"command": "pytest -q"}'}, }, { "id": "call_2", "type": "function", "function": {"name": "read_file", "arguments": '{"file_path": "/a/b.py"}'}, }, ], }, { "role": "tool", "tool_call_id": "call_1", "content": "Traceback (most recent call last):\nModuleNotFoundError: No module named x", }, { "role": "tool", "tool_call_id": "call_2", "content": [{"type": "text", "text": "file body"}], }, ] results = learner.extract_tool_results_from_openai_messages(messages) assert len(results) == 2 by_name = {r["tool_name"]: r for r in results} assert by_name["bash"]["input"] == {"command": "pytest -q"} # parsed to dict assert by_name["bash"]["input"].get("command") == "pytest -q" # downstream .get works assert by_name["bash"]["is_error"] is True assert by_name["read_file"]["input"] == {"file_path": "/a/b.py"} assert by_name["read_file"]["output"] == "file body" # list content joined assert by_name["read_file"]["is_error"] is False def test_extract_openai_tool_results_handles_malformed_and_orphans( self, learner: TrafficLearner ): """Malformed arguments become an empty dict; an unmatched tool_call_id yields ``unknown`` — neither raises, so on_tool_result stays safe.""" messages = [ { "role": "assistant", "tool_calls": [{"id": "c1", "function": {"name": "grep", "arguments": "not json"}}], }, {"role": "tool", "tool_call_id": "c1", "content": "ok"}, {"role": "tool", "tool_call_id": "missing", "content": "orphan"}, ] results = learner.extract_tool_results_from_openai_messages(messages) assert results[0]["tool_name"] == "grep" assert results[0]["input"] == {} assert results[1]["tool_name"] == "unknown" assert results[1]["input"] == {} def test_extract_openai_tool_results_empty_without_tool_messages(self, learner: TrafficLearner): assert ( learner.extract_tool_results_from_openai_messages([{"role": "user", "content": "hi"}]) == [] ) @pytest.mark.asyncio async def test_tool_history_bounded(self, learner: TrafficLearner): """Test that tool history stays within max_history.""" for i in range(30): await learner.on_tool_result( tool_name="Read", tool_input={"file_path": f"/file{i}.py"}, tool_output=f"content {i}", is_error=False, ) assert len(learner._tool_history) <= learner._max_history @pytest.mark.asyncio async def test_no_pattern_from_success_only(self, learner: TrafficLearner): """Test that success without prior error doesn't generate error_recovery pattern.""" await learner.on_tool_result( tool_name="Bash", tool_input={"command": "echo hello"}, tool_output="hello", is_error=False, ) stats = learner.get_stats() # Only environment patterns possible, no error_recovery assert stats["requests_processed"] == 1 # ============================================================================= # Pattern Model Tests # ============================================================================= class TestExtractedPattern: def test_content_hash_deterministic(self): p1 = ExtractedPattern( category=PatternCategory.ENVIRONMENT, content="Use venv", importance=0.5, ) p2 = ExtractedPattern( category=PatternCategory.ENVIRONMENT, content="Use venv", importance=0.8, # Different importance, same hash ) assert p1.content_hash == p2.content_hash def test_different_content_different_hash(self): p1 = ExtractedPattern( category=PatternCategory.ENVIRONMENT, content="Use venv", importance=0.5, ) p2 = ExtractedPattern( category=PatternCategory.ENVIRONMENT, content="Use conda", importance=0.5, ) assert p1.content_hash != p2.content_hash # ============================================================================= # Project Routing # ============================================================================= class TestProjectForPattern: def _project(self, path: str): from pathlib import Path as _P from headroom.learn.models import ProjectInfo p = _P(path) return ProjectInfo(name=p.name, project_path=p, data_path=p) def test_matches_longest_root(self): proj_a = self._project("/x/a") proj_b = self._project("/x/a/b") pattern = ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content="File `/x/a/b/foo.py` does not exist.", importance=0.5, ) result = _project_for_pattern(pattern, [proj_a, proj_b]) assert result is proj_b def test_returns_none_for_unanchored(self): proj_a = self._project("/x/a") pattern = ExtractedPattern( category=PatternCategory.PREFERENCE, content="User preference: use terse responses", importance=0.7, ) assert _project_for_pattern(pattern, [proj_a]) is None def test_matches_via_entity_refs(self): proj = self._project("/x/a") pattern = ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content="Command failed.", importance=0.5, entity_refs=["/x/a/tool.py"], ) assert _project_for_pattern(pattern, [proj]) is proj def test_windows_root_with_trailing_backslash_matches_child_path(self): proj = self._project(r"C:\Users\john.doe\repo\\") pattern = ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content=r"File `C:\Users\john.doe\repo\src\main.py` does not exist.", importance=0.5, ) assert _project_for_pattern(pattern, [proj]) is proj def test_no_false_match_on_prefix_boundary(self): # /x/ab should not match a project rooted at /x/a proj_a = self._project("/x/a") pattern = ExtractedPattern( category=PatternCategory.ERROR_RECOVERY, content="File `/x/ab/foo.py` does not exist.", importance=0.5, ) assert _project_for_pattern(pattern, [proj_a]) is None # ============================================================================= # Persisted-pattern loading from memory.db # ============================================================================= class TestLoadPersistedPatterns: def _make_db(self, tmp_path, rows: list[dict]): import json as _json import sqlite3 as _sql db = tmp_path / "memory.db" conn = _sql.connect(db) conn.execute( "CREATE TABLE memories (" "id TEXT PRIMARY KEY, content TEXT NOT NULL, " "user_id TEXT NOT NULL DEFAULT 'default', " "metadata TEXT NOT NULL DEFAULT '{}', " "entity_refs TEXT NOT NULL DEFAULT '[]', " "importance REAL NOT NULL DEFAULT 0.5, " "created_at TEXT)" ) for i, r in enumerate(rows): conn.execute( "INSERT INTO memories " "(id, content, metadata, entity_refs, importance, created_at) " "VALUES (?,?,?,?,?,?)", ( str(i), r["content"], _json.dumps(r.get("metadata", {})), _json.dumps(r.get("entity_refs", [])), r.get("importance", 0.5), r.get("created_at"), ), ) conn.commit() conn.close() return db def test_dedupes_by_content_and_sums_evidence(self, tmp_path): db = self._make_db( tmp_path, [ { "content": "Command `foo` fails.", "metadata": { "source": "traffic_learner", "category": "error_recovery", "evidence_count": 2, }, }, { "content": "Command `foo` fails.", "metadata": { "source": "traffic_learner", "category": "error_recovery", "evidence_count": 3, }, }, ], ) patterns = _load_persisted_patterns_from_sqlite(db, "default") assert len(patterns) == 1 assert patterns[0].evidence_count == 5 assert patterns[0].category == PatternCategory.ERROR_RECOVERY def test_skips_non_traffic_rows(self, tmp_path): db = self._make_db( tmp_path, [ { "content": "Something else", "metadata": {"source": "other"}, }, { "content": "From traffic", "metadata": { "source": "traffic_learner", "category": "environment", }, }, ], ) patterns = _load_persisted_patterns_from_sqlite(db, "default") assert len(patterns) == 1 assert patterns[0].content == "From traffic" def test_reads_importance_column(self, tmp_path): db = self._make_db( tmp_path, [ { "content": "High-importance pattern", "metadata": { "source": "traffic_learner", "category": "environment", }, "importance": 0.85, }, ], ) patterns = _load_persisted_patterns_from_sqlite(db, "default") assert len(patterns) == 1 assert patterns[0].importance == 0.85 def test_skips_unknown_category(self, tmp_path): db = self._make_db( tmp_path, [ { "content": "X", "metadata": {"source": "traffic_learner", "category": "bogus"}, }, ], ) assert _load_persisted_patterns_from_sqlite(db, "default") == [] # ============================================================================= # Category → recommendation routing # ============================================================================= class TestPatternsToRecommendations: def test_routes_preference_to_memory_file(self): from headroom.learn.models import RecommendationTarget patterns = [ ExtractedPattern( category=PatternCategory.PREFERENCE, content="User prefers terse output", importance=0.8, evidence_count=3, ), ] recs = _patterns_to_recommendations(patterns) assert len(recs) == 1 assert recs[0].target == RecommendationTarget.MEMORY_FILE assert "User prefers terse output" in recs[0].content assert "