## Summary
The onboarding wizard's data-sync step started a full cold-start import
and closed; nothing on the page showed the run again, a gateway restart
lost it silently, and the web path never landed the profile mirror or
the skills the CLI does. This PR closes all of that in one piece,
backend first.
Backend (`raven.importer`, `import.*` RPC):
- The two post-import phases move out of the CLI into
`raven/importer/phases.py` and run per platform on both paths. Hermes
keeps its `USER.md` entries and skills tree; Claude Code now contributes
the memory files it marks as being about the user (`metadata.type` of
`user` or `feedback`, deduplicated on the text) and the skills under
`~/.claude/skills` through a new `ClaudeCodeSkillSource`. The installer
lands each platform under `skills/<platform>/` and reports progress per
copy.
- `import.run` records the tier and platforms it was asked for in the
state file's `meta`; `import.status` returns them together with a `phase
{kind, current, total}` object while a phase is in flight (both
nullable, additive fields on the contract). A client that finds a run
stopped short can start the same request again without having remembered
it.
- A stop is honoured between the batches of one source, not only between
sources. The interrupted source keeps no entry and is sent whole next
time.
- The CLI keeps its own bar labels and TTY-aware provider; its
skills-only path and scan preview count every platform's skills.
- The store budget fix measured on 2026-09-20 rides along, folded from a
PR first opened against main and closed in favour of this one at the
maintainer's request (everything lands on the architecture branch): an
import write is tagged `bulk` and the EverOS backend gives it the
extraction budget instead of the per-message estimate, and the import
batch drops from 100 to 50 messages. Without it every real-size source
dies on the shipped 10 s store timeout, which is exactly what the new
row would then report.
Frontend (`ui-web`):
- A new `importSync` domain draws one row in the rail's foot, above
Settings, from `import.status` alone. States: scanning, the message pass
with its settled share, the phase in flight with its own count, paused
(nothing running, counts short of the total), finished (with how many
did not make it). It polls only while a run is on, stops a run with its
close button, and asks for the recorded request again when a paused or
partly failed row is clicked. A finished row is dismissed per run and
stays dismissed across reloads.
- The wizard's sync step imports memory files only (the store used to
start a full import silently). The maintainer's call: conversations take
many hours and are not offered from the web at all; the full tier stays
a CLI option (`raven import run --tier full`). The step shows each
agent's memory-file, conversation and skill counts so the reader knows
what is there.
- Found during acceptance and fixed here: the row's first status read
sat with the seam installers, before the socket connects, and was
refused as not connected; it now runs in the boot sequence after the
connection is up and again on reconnect.
Deliberately not in this PR: a way to force the "did not make it" state
in the real host (covered by unit tests and the offline fixture), and
the CLI tier labels (`minutes` / `hours`), which measurement has since
put at tens of minutes and many hours respectively.
## Type
- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other
## Verification
Backend:
uv run pytest tests/test_rpc_schema_match.py
tests/test_rpc_import_sync.py tests/test_importer_state.py
tests/test_importer_orchestrator.py tests/test_importer_phases.py
tests/test_importer_claude_code_skills.py
tests/test_importer_hermes_skills.py
tests/test_importer_hermes_user_md.py tests/test_cli_import_commands.py
tests/test_cli_onboard_commands.py tests/integration/test_import_e2e.py
-q
908 passed
Reverse check: with `state.py`, `orchestrator.py`,
`skills/installer.py`, `import_sync.py` and `models.py` reverted and the
tests kept, 14 tests fail (the new state, orchestrator, installer,
phases and rpc cases); restored, all pass.
Frontend:
npm test --prefix ui-web 188 files, 2570 passed (gates included)
npm run gen:check --prefix ui-web generated.ts matches the contract (189
methods)
npm run type-check --prefix ui-web clean
npm run lint --prefix ui-web 0 errors (5 pre-existing warnings in
unrelated files)
npm run lint:i18n --prefix ui-tui generated catalogue is up to date
Reverse check: with the importSync store and page, the onboard store and
page and the import fixture reverted, 5 tests fail and the two
importSync test files no longer import; restored byte for byte, 48 pass.
Gates: ruff check and format on every changed Python file, commitlint
and `check_commit_messages.py` over the branch,
`check_source_language.py` over the branch, `make check-large-files` --
all pass.
Acceptance in the real host, driven with playwright-cli against `raven
web --foreground` from this checkout, an isolated `RAVEN_HOME`, an empty
EverOS root on its own port with real LLM and embedding credentials, and
a synthetic Claude Code home (global CLAUDE.md, one project memory
directory holding user, feedback and project memories, two real small
conversations, one skill):
- Wizard step 4 lists Claude Code with its counts and a switch, opencode
and codex as unsupported; the tier rows default to memory files and
their counts follow the switch. Start closes the wizard and the rail row
appears at once: "Syncing data 0%" -> 50% -> "Building your profile 1/2"
-> "Memory import finished" in 30s. On disk: two entries in
`user_memory/profile/user.md` (the project-typed memory correctly
absent), `skills/claude_code/demo-skill/`.
- Dismiss hides the row; a reload keeps it hidden.
- A full import stopped 5s in shows "Sync paused 75%" 8s later with a
clickable row; the gateway log has `import cancelled inside
.../<conversation>` and the state file has no entry for it.
- Killing the gateway, restarting it, re-authenticating and reloading
shows "Sync paused 75%" again from the state file. Clicking the row runs
"Syncing data 75%" to "Memory import finished" in 31s; the conversation
is then `submitted`.
- The CLI path over the same home (`raven import run --platform
claude_code --tier memory_files --yes`) shows the two phase bars
(`Mirroring profile [2/2]`, `Installing skills [1/1]`) and reports
`Profile: 2 entries into user.md`, `Skills: 1 installed`.
- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed (new copy
is in `i18n/messages.json`; no docs page describes the wizard yet)
After folding the store budget commits, on the branch head: `uv run
pytest` over the importer, EverOS backend, RPC and CLI import suites
plus `tests/integration/test_import_e2e.py`: 1095 passed; `ruff check`
clean; commitlint, `check_commit_messages`, `check_large_files`,
`check_source_language` and pre-commit green over the 8-commit range.
## Risk
The batch size takes part in the EverOS message id an import write
carries, so a run imported under the 100-message batch would not be
deduplicated against a re-import under 50; no import of real size had
completed under the old budget, so nothing on disk depends on the old
id.
User-visible: the rail gains a row while an import exists on disk; the
wizard's sync step imports memory files only where it used to start a
full import silently (conversations remain a CLI-only import);
`import.status` gains three optional fields. The CLI's skills-only path
now offers every platform's skills, and its scan line reads `Skills: N
importable` rather than `Hermes skills`.
The `import.status` additions are optional in the contract, so an older
client reading the new gateway is unaffected. A client that stores
nothing new: `localStorage` holds only the dismissed run's signature.
Rollback: revert the squash commit; no data migration is involved. The
state file's new `meta` keys are ignored by older code.
- [x] Security impact considered (no new inputs, credentials or
endpoints; the profile mirror reads the same files the importer already
reads)
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes
## Related Issues
N/A
---------
Co-authored-by: gloryfromca <23442919+gloryfromca@users.noreply.github.com>
Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
1034 lines
43 KiB
Python
1034 lines
43 KiB
Python
"""Tests for raven import CLI commands."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from collections.abc import Iterator
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
import typer
|
|
from typer.testing import CliRunner
|
|
|
|
from raven.cli._theme import POINTER, QMARK
|
|
from raven.cli.import_commands import (
|
|
ImportRunResult,
|
|
_build_and_run,
|
|
_format_skill_summary,
|
|
_make_profile_provider,
|
|
_pick_platform,
|
|
_platform_choice_label,
|
|
_print_summary,
|
|
import_app,
|
|
)
|
|
from raven.config.schema import Config
|
|
from raven.contracts.memory import BackendHealth, HealthCheck
|
|
from raven.importer.hermes_user_md import ImportedSections
|
|
from raven.importer.orchestrator import ImportSummary
|
|
from raven.importer.phases import PhaseOutcome
|
|
from raven.importer.skills import DiscoveredSkill, SkillOrigin
|
|
from raven.importer.skills.installer import SkillImportSummary
|
|
from raven.importer.state import ImportState
|
|
from raven.importer.types import Platform, ScanResult, SourceKind, Tier
|
|
from tests._everos_presence import everos_plugin_absent
|
|
|
|
runner = CliRunner()
|
|
|
|
|
|
def _scan_result(
|
|
key: str = "k1",
|
|
platform: Platform = Platform.CLAUDE_CODE,
|
|
kind: SourceKind = SourceKind.CONVERSATION,
|
|
size: int = 1000,
|
|
) -> ScanResult:
|
|
return ScanResult(
|
|
source_key=key,
|
|
platform=platform,
|
|
kind=kind,
|
|
file_paths=(Path("/fake"),),
|
|
estimated_size=size,
|
|
mtime=1000.0,
|
|
)
|
|
|
|
|
|
def _make_scan_results() -> list[ScanResult]:
|
|
return [
|
|
_scan_result("global-claude-md", kind=SourceKind.MEMORY_FILE, size=2048),
|
|
_scan_result("proj-memory", kind=SourceKind.MEMORY_FILE, size=48000),
|
|
_scan_result("sess-001", kind=SourceKind.CONVERSATION, size=120000),
|
|
]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# scan
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestScan:
|
|
def test_scan_shows_results(self) -> None:
|
|
with patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
):
|
|
result = runner.invoke(import_app, ["scan"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "Claude Code" in result.stdout
|
|
assert "global-claude-md" in result.stdout
|
|
|
|
def test_scan_empty(self) -> None:
|
|
# discover() has to be stubbed too, or the result depends on how many
|
|
# skills the developer's own Hermes install happens to hold.
|
|
with (
|
|
patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=[]),
|
|
),
|
|
patch(
|
|
"raven.importer.skills.hermes.HermesSkillSource.discover",
|
|
new=AsyncMock(return_value=[]),
|
|
),
|
|
):
|
|
result = runner.invoke(import_app, ["scan"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "No importable data found" in result.stdout
|
|
|
|
def test_scan_with_only_skills_does_not_say_there_is_nothing(self) -> None:
|
|
"""Skills never travel as ScanResults, so an install whose only
|
|
importable data is skills produced an empty result list and was told
|
|
there was nothing to import."""
|
|
skills = [DiscoveredSkill(name="a", path=Path("/fake/a"), origin=SkillOrigin.LOCAL_UNKNOWN, registry_name="a")]
|
|
with (
|
|
patch("raven.importer.scanners.scan_all", new=AsyncMock(return_value=[])),
|
|
patch(
|
|
"raven.importer.skills.hermes.HermesSkillSource.discover",
|
|
new=AsyncMock(return_value=skills),
|
|
),
|
|
patch("raven.importer.skills.claude_code.ClaudeCodeSkillSource.discover", new=AsyncMock(return_value=[])),
|
|
):
|
|
result = runner.invoke(import_app, ["scan"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "Skills: 1 importable" in result.stdout
|
|
assert "No importable data found" not in result.stdout
|
|
|
|
def test_scan_shows_importable_skill_count(self) -> None:
|
|
skills = [
|
|
DiscoveredSkill(name="a", path=Path("/fake/a"), origin=SkillOrigin.LOCAL_UNKNOWN, registry_name="a"),
|
|
DiscoveredSkill(name="b", path=Path("/fake/b"), origin=SkillOrigin.BUNDLED_PRISTINE, registry_name="b"),
|
|
]
|
|
with (
|
|
patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
),
|
|
patch(
|
|
"raven.importer.skills.hermes.HermesSkillSource.discover",
|
|
new=AsyncMock(return_value=skills),
|
|
),
|
|
patch("raven.importer.skills.claude_code.ClaudeCodeSkillSource.discover", new=AsyncMock(return_value=[])),
|
|
):
|
|
result = runner.invoke(import_app, ["scan"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "Skills: 1 importable" in result.stdout
|
|
|
|
def test_scan_with_a_platform_that_has_no_skills_skips_the_skill_line(self) -> None:
|
|
with (
|
|
patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
),
|
|
patch("raven.importer.skills.hermes.HermesSkillSource.discover") as hermes_discover,
|
|
patch("raven.importer.skills.claude_code.ClaudeCodeSkillSource.discover") as claude_discover,
|
|
):
|
|
result = runner.invoke(import_app, ["scan", "--platform", "codex"])
|
|
|
|
assert result.exit_code == 0
|
|
hermes_discover.assert_not_called()
|
|
claude_discover.assert_not_called()
|
|
assert "Skills:" not in result.stdout
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# status
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestStatus:
|
|
def test_status_shows_summary(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
state.set_total(10)
|
|
state.mark_submitted("claude_code", "a")
|
|
state.mark_submitted("claude_code", "b")
|
|
state.mark_failed("claude_code", "c", "err")
|
|
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["status"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "10" in result.stdout
|
|
assert "2" in result.stdout
|
|
|
|
def test_status_json(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
state.set_total(5)
|
|
state.mark_submitted("claude_code", "a")
|
|
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["status", "--json"])
|
|
|
|
data = json.loads(result.stdout)
|
|
assert data["total"] == 5
|
|
assert data["submitted"] == 1
|
|
|
|
def test_status_no_state(self) -> None:
|
|
state = ImportState(path=Path("/nonexistent/state.json"))
|
|
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["status"])
|
|
|
|
assert result.exit_code == 0
|
|
assert "No import in progress" in result.stdout
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# run
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestRun:
|
|
def test_run_non_interactive(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
summary = ImportSummary(total=2, submitted=2, skipped=0, failed=0, errors=())
|
|
|
|
with (
|
|
patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
),
|
|
patch(
|
|
"raven.cli.import_commands._build_and_run",
|
|
new=AsyncMock(return_value=ImportRunResult(summary=summary)),
|
|
),
|
|
patch("raven.cli.import_commands._default_state", return_value=state),
|
|
):
|
|
result = runner.invoke(
|
|
import_app,
|
|
["run", "--platform", "claude_code", "--tier", "full", "--yes"],
|
|
)
|
|
|
|
assert result.exit_code == 0
|
|
|
|
def test_run_no_backend(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
|
|
with (
|
|
patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
),
|
|
patch("raven.cli.import_commands._default_state", return_value=state),
|
|
patch(
|
|
"raven.cli.import_commands.maybe_build_memory_backend",
|
|
return_value=None,
|
|
),
|
|
):
|
|
result = runner.invoke(
|
|
import_app,
|
|
["run", "--platform", "claude_code", "--tier", "full", "--yes"],
|
|
)
|
|
|
|
assert result.exit_code == 1
|
|
|
|
def test_run_no_sources(self) -> None:
|
|
with patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=[]),
|
|
):
|
|
result = runner.invoke(
|
|
import_app,
|
|
["run", "--platform", "claude_code", "--tier", "full", "--yes"],
|
|
)
|
|
|
|
assert result.exit_code == 0
|
|
assert "No importable data found" in result.stdout
|
|
|
|
@staticmethod
|
|
@contextmanager
|
|
def _patched_skills_only(tmp_path: Path) -> Iterator[AsyncMock]:
|
|
"""A machine whose only importable data is 12 Hermes skills.
|
|
|
|
`_importable_skill_count` has to be stubbed too: it walks the real
|
|
`~/.hermes` skill tree, so left alone the count -- and whether this test
|
|
passes at all -- would come from whoever's machine is running it.
|
|
"""
|
|
installer = AsyncMock(return_value=SkillImportSummary(total=12, installed=12))
|
|
with (
|
|
patch("raven.importer.scanners.scan_all", new=AsyncMock(return_value=[])),
|
|
patch("raven.cli.import_commands._importable_skill_count", new=AsyncMock(return_value=12)),
|
|
patch("raven.cli.import_commands.install_skills", new=installer),
|
|
patch("raven.cli.import_commands.load_config", return_value=SimpleNamespace(workspace_path=tmp_path)),
|
|
):
|
|
yield installer
|
|
|
|
def test_run_installs_skills_when_the_scan_finds_nothing(self, tmp_path: Path) -> None:
|
|
"""Skills are directories rather than message sources, so they never
|
|
arrive as ScanResults. An install whose only importable data is skills
|
|
reaches this early return, and stopping there tells that user there is
|
|
nothing to import while a dozen skills sit on disk.
|
|
"""
|
|
with self._patched_skills_only(tmp_path):
|
|
result = runner.invoke(import_app, ["run", "--platform", "hermes", "--tier", "full", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert "12 installed" in result.stdout
|
|
assert "No importable data found" not in result.stdout
|
|
|
|
def test_run_asks_before_copying_a_skill_tree(self, tmp_path: Path) -> None:
|
|
"""This path runs before the run's own `Proceed?` gate and copies
|
|
directories nothing undoes, so declining has to stop it. Every other test
|
|
here passes `--yes`, which is what hid the missing gate.
|
|
"""
|
|
with self._patched_skills_only(tmp_path) as installer:
|
|
result = runner.invoke(
|
|
import_app,
|
|
["run", "--platform", "hermes", "--tier", "full"],
|
|
input="n\n",
|
|
)
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert "About to import 12 skills" in result.stdout
|
|
installer.assert_not_awaited()
|
|
# A decline is an answer; reporting "nothing to import" on top of it
|
|
# would contradict the count just shown.
|
|
assert "No importable data found" not in result.stdout
|
|
|
|
def test_run_copies_the_skill_tree_once_accepted(self, tmp_path: Path) -> None:
|
|
with self._patched_skills_only(tmp_path) as installer:
|
|
result = runner.invoke(
|
|
import_app,
|
|
["run", "--platform", "hermes", "--tier", "full"],
|
|
input="y\n",
|
|
)
|
|
|
|
assert result.exit_code == 0, result.output
|
|
installer.assert_awaited_once()
|
|
assert "12 installed" in result.stdout
|
|
|
|
def test_run_installs_skills_when_the_tier_keeps_nothing(self, tmp_path: Path) -> None:
|
|
"""The tier filter has nothing of the skills' to keep either, so the
|
|
memory-files tier on a Hermes install with conversations only lands on
|
|
the same dead end.
|
|
"""
|
|
results = [_scan_result("h1", platform=Platform.HERMES, kind=SourceKind.CONVERSATION)]
|
|
|
|
with (
|
|
patch("raven.importer.scanners.scan_all", new=AsyncMock(return_value=results)),
|
|
patch("raven.cli.import_commands._importable_skill_count", new=AsyncMock(return_value=12)),
|
|
patch(
|
|
"raven.cli.import_commands.install_skills",
|
|
new=AsyncMock(return_value=SkillImportSummary(total=12, installed=12)),
|
|
),
|
|
patch("raven.cli.import_commands.load_config", return_value=SimpleNamespace(workspace_path=tmp_path)),
|
|
):
|
|
result = runner.invoke(import_app, ["run", "--platform", "hermes", "--tier", "memory_files", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert "12 installed" in result.stdout
|
|
assert "No items match the selected tier" not in result.stdout
|
|
|
|
def test_run_selects_platform_and_tier_inside_the_event_loop(self, tmp_path: Path) -> None:
|
|
"""The selectors run under `asyncio.run(_run_async(...))`, so they must
|
|
reach questionary's async API: `ask()` drives prompt_toolkit through
|
|
`asyncio.run()`, which raises inside a running loop. Both selectors are
|
|
exercised here because only an unfiltered invocation reaches them.
|
|
"""
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
results = [
|
|
_scan_result("c1", platform=Platform.CLAUDE_CODE),
|
|
_scan_result("h1", platform=Platform.HERMES),
|
|
]
|
|
fake = _RecordingQuestionary(iter([Platform.HERMES, Tier.FULL]))
|
|
|
|
with self._patched_run(state, summary, results, fake):
|
|
result = runner.invoke(import_app, ["run", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert [message for message, _choices, _kwargs in fake.calls] == [
|
|
"Select platform:",
|
|
"Select import tier:",
|
|
]
|
|
|
|
def test_run_selectors_carry_the_shared_prompt_chrome(self, tmp_path: Path) -> None:
|
|
"""Both selectors must pass the shared style and glyphs; questionary's
|
|
defaults ("?" marker, ">>" pointer, no palette) read as another program.
|
|
"""
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
results = [
|
|
_scan_result("c1", platform=Platform.CLAUDE_CODE),
|
|
_scan_result("h1", platform=Platform.HERMES),
|
|
]
|
|
fake = _RecordingQuestionary(iter([Platform.HERMES, Tier.FULL]))
|
|
|
|
with self._patched_run(state, summary, results, fake):
|
|
result = runner.invoke(import_app, ["run", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
for _message, _choices, kwargs in fake.calls:
|
|
assert kwargs["qmark"] == QMARK
|
|
assert kwargs["pointer"] == POINTER
|
|
assert kwargs["style"] is not None
|
|
|
|
def test_run_menus_name_the_skills_that_would_be_installed(self, tmp_path: Path) -> None:
|
|
"""Skills never travel as ScanResults, so a menu built from them alone
|
|
offers "2 items" and then installs a dozen skills nobody was told about.
|
|
Factory-pristine skills are not installed and must not be counted.
|
|
"""
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
results = [
|
|
_scan_result("c1", platform=Platform.CLAUDE_CODE),
|
|
_scan_result("h1", platform=Platform.HERMES, kind=SourceKind.MEMORY_FILE),
|
|
_scan_result("h2", platform=Platform.HERMES),
|
|
]
|
|
skills = [
|
|
DiscoveredSkill(name="a", path=Path("/fake/a"), origin=SkillOrigin.LOCAL_UNKNOWN, registry_name="a"),
|
|
DiscoveredSkill(name="b", path=Path("/fake/b"), origin=SkillOrigin.CURATOR_MANAGED, registry_name="b"),
|
|
DiscoveredSkill(name="c", path=Path("/fake/c"), origin=SkillOrigin.BUNDLED_PRISTINE, registry_name="c"),
|
|
]
|
|
fake = _RecordingQuestionary(iter([Platform.HERMES, Tier.MEMORY_FILES]))
|
|
|
|
with (
|
|
self._patched_run(state, summary, results, fake),
|
|
patch(
|
|
"raven.importer.skills.hermes.HermesSkillSource.discover",
|
|
new=AsyncMock(return_value=skills),
|
|
),
|
|
):
|
|
result = runner.invoke(import_app, ["run", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
platform_choices, tier_choices = (choices for _m, choices, _k in fake.calls)
|
|
hermes_row = next(c["name"] for c in platform_choices if c["value"] is Platform.HERMES)
|
|
assert "2 skills" in hermes_row
|
|
claude_row = next(c["name"] for c in platform_choices if c["value"] is Platform.CLAUDE_CODE)
|
|
assert "skills" not in claude_row
|
|
assert any("2 skills" in c["name"] for c in tier_choices)
|
|
assert "2 skills" in result.output
|
|
|
|
def test_menu_rows_fit_eighty_columns(self, tmp_path: Path) -> None:
|
|
"""A row past 80 columns wraps mid-phrase, which costs far more
|
|
legibility than wide padding buys. Four-digit counts are the widest
|
|
case worth planning for, and every count of that many digits is the
|
|
same width.
|
|
"""
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
results = [
|
|
_scan_result("h-md", platform=Platform.HERMES, kind=SourceKind.MEMORY_FILE),
|
|
*[_scan_result(f"h{i}", platform=Platform.HERMES) for i in range(1000)],
|
|
_scan_result("c-md", platform=Platform.CLAUDE_CODE, kind=SourceKind.MEMORY_FILE),
|
|
*[_scan_result(f"c{i}", platform=Platform.CLAUDE_CODE) for i in range(1000)],
|
|
]
|
|
skills = [
|
|
DiscoveredSkill(
|
|
name=f"s{i}", path=Path(f"/fake/s{i}"), origin=SkillOrigin.LOCAL_UNKNOWN, registry_name=f"s{i}"
|
|
)
|
|
for i in range(1000)
|
|
]
|
|
fake = _RecordingQuestionary(iter([Platform.HERMES, Tier.MEMORY_FILES]))
|
|
|
|
with (
|
|
self._patched_run(state, summary, results, fake),
|
|
patch(
|
|
"raven.importer.skills.hermes.HermesSkillSource.discover",
|
|
new=AsyncMock(return_value=skills),
|
|
),
|
|
):
|
|
result = runner.invoke(import_app, ["run", "--yes"])
|
|
|
|
assert result.exit_code == 0, result.output
|
|
# Two columns for the pointer and the space questionary puts before it.
|
|
widest = max(len(c["name"]) + 2 for _m, choices, _k in fake.calls for c in choices)
|
|
assert widest <= 80, widest
|
|
|
|
@staticmethod
|
|
def _patched_run(
|
|
state: ImportState,
|
|
summary: ImportSummary,
|
|
results: list[ScanResult],
|
|
questionary: "_RecordingQuestionary",
|
|
) -> Any:
|
|
from contextlib import ExitStack
|
|
|
|
stack = ExitStack()
|
|
for ctx in (
|
|
patch("raven.importer.scanners.scan_all", new=AsyncMock(return_value=results)),
|
|
patch(
|
|
"raven.cli.import_commands._build_and_run", new=AsyncMock(return_value=ImportRunResult(summary=summary))
|
|
),
|
|
patch("raven.cli.import_commands._default_state", return_value=state),
|
|
patch("raven.cli.import_commands._require_questionary", return_value=questionary),
|
|
# CliRunner is never a TTY; these tests exercise the pickers, not TTY policy.
|
|
patch("raven.cli.import_commands.die_if_not_tty", new=lambda *a, **k: None),
|
|
):
|
|
stack.enter_context(ctx)
|
|
return stack
|
|
|
|
|
|
class _RecordingQuestionary:
|
|
"""questionary stand-in that records each prompt and refuses the sync `ask`.
|
|
|
|
`ask()` fails the way prompt_toolkit does inside a running loop, so a
|
|
selector that skips `ask_async` is caught rather than silently passing.
|
|
"""
|
|
|
|
def __init__(self, answers: Iterator[object]) -> None:
|
|
self._answers = answers
|
|
self.calls: list[tuple[str, list[dict[str, Any]], dict[str, Any]]] = []
|
|
|
|
def select(self, message: str, choices: list[dict[str, Any]], **kwargs: Any) -> Any:
|
|
self.calls.append((message, choices, kwargs))
|
|
answers = self._answers
|
|
|
|
class _Question:
|
|
def ask(self) -> object:
|
|
raise RuntimeError("asyncio.run() cannot be called from a running event loop")
|
|
|
|
async def ask_async(self) -> object:
|
|
return next(answers)
|
|
|
|
return _Question()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# stop
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestStop:
|
|
def test_stop_creates_cancel_file(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
state.set_total(5)
|
|
state.mark_submitted("claude_code", "item1")
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["stop"])
|
|
assert result.exit_code == 0
|
|
assert state.cancel_path.exists()
|
|
assert "cancel" in result.output.lower() or "Cancel" in result.output
|
|
|
|
def test_stop_no_import(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["stop"])
|
|
assert result.exit_code == 0
|
|
assert "No import" in result.output
|
|
|
|
def test_stop_already_cancelled(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
state.set_total(5)
|
|
state.cancel_path.touch()
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["stop"])
|
|
assert result.exit_code == 0
|
|
assert "already" in result.output.lower()
|
|
|
|
|
|
def test_build_scanners_includes_hermes() -> None:
|
|
from raven.importer.scanners import build_scanners
|
|
|
|
platforms = {s.platform for s in build_scanners()}
|
|
assert Platform.HERMES in platforms
|
|
assert Platform.CLAUDE_CODE in platforms
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Hermes user.md native landing
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestMakeProfileProvider:
|
|
def test_returns_none_without_credentials(self) -> None:
|
|
assert _make_profile_provider(Config()) is None
|
|
|
|
def test_returns_provider_with_credentials(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
from raven.providers import factory as _helpers
|
|
|
|
stub = SimpleNamespace(name="stub")
|
|
monkeypatch.setattr(_helpers, "make_provider", lambda _c: stub)
|
|
config = Config()
|
|
config.providers.anthropic.api_key = "sk-ant-test"
|
|
|
|
assert _make_profile_provider(config) is stub
|
|
|
|
def test_strips_tty_handlers_after_building(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""litellm reattaches its stderr handler when it is imported, which happens
|
|
inside make_provider -- after redirect_loguru_to_file already stripped."""
|
|
from raven.cli import _log_file
|
|
from raven.providers import factory as _helpers
|
|
|
|
calls: list[str] = []
|
|
monkeypatch.setattr(_helpers, "make_provider", lambda _c: SimpleNamespace(name="stub"))
|
|
monkeypatch.setattr(
|
|
_log_file,
|
|
"_strip_tty_stream_handlers",
|
|
lambda: calls.append("strip"),
|
|
)
|
|
config = Config()
|
|
config.providers.anthropic.api_key = "sk-ant-test"
|
|
|
|
_make_profile_provider(config)
|
|
|
|
assert calls == ["strip"]
|
|
|
|
def test_does_not_strip_when_no_provider(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
from raven.cli import _log_file
|
|
|
|
calls: list[str] = []
|
|
monkeypatch.setattr(_log_file, "_strip_tty_stream_handlers", lambda: calls.append("strip"))
|
|
|
|
assert _make_profile_provider(Config()) is None
|
|
assert calls == []
|
|
|
|
|
|
class _OrderingBackend:
|
|
def __init__(self, calls: list[str], health: BackendHealth | None = None) -> None:
|
|
self._calls = calls
|
|
self._health = health
|
|
|
|
async def start(self) -> None:
|
|
self._calls.append("start")
|
|
|
|
async def stop(self) -> None:
|
|
self._calls.append("stop")
|
|
|
|
async def health(self) -> BackendHealth | None:
|
|
return self._health
|
|
|
|
|
|
class TestBuildAndRunPhases:
|
|
"""The two post-import phases live in ``raven.importer.phases``; this layer
|
|
decides only whether they run, and carries their outcome to the summary."""
|
|
|
|
async def test_phases_run_after_the_message_pass_and_before_the_backend_stops(self, tmp_path: Path) -> None:
|
|
calls: list[str] = []
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
|
|
async def _fake_run_import(*_args: object, **_kwargs: object) -> ImportSummary:
|
|
calls.append("run_import")
|
|
return summary
|
|
|
|
async def _fake_phases(*_args: object, **_kwargs: object) -> PhaseOutcome:
|
|
calls.append("phases")
|
|
return PhaseOutcome(skills=SkillImportSummary(total=1, installed=1))
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with (
|
|
patch("raven.cli.import_commands.maybe_build_memory_backend", return_value=_OrderingBackend(calls)),
|
|
patch("raven.cli.import_commands.run_import", new=_fake_run_import),
|
|
patch("raven.cli.import_commands.run_phases", new=_fake_phases),
|
|
):
|
|
result = await _build_and_run([], state)
|
|
|
|
assert calls == ["start", "run_import", "phases", "stop"]
|
|
assert result.summary is summary
|
|
assert result.skills == SkillImportSummary(total=1, installed=1)
|
|
|
|
async def test_a_cancelled_run_skips_the_phases(self, tmp_path: Path) -> None:
|
|
"""`run_import` returns normally when it sees the cancel file, so nothing
|
|
downstream notices unless it reads `cancelled`. The phases are the run's
|
|
most expensive steps -- one LLM call per profile entry, and a copy of
|
|
every skill tree -- so `raven import stop` was starting the work it was
|
|
asked to stop.
|
|
"""
|
|
calls: list[str] = []
|
|
cancelled = ImportSummary(total=4, submitted=1, skipped=0, failed=0, errors=(), cancelled=True)
|
|
|
|
async def _fake_run_import(*_args: object, **_kwargs: object) -> ImportSummary:
|
|
calls.append("run_import")
|
|
return cancelled
|
|
|
|
async def _fake_phases(*_args: object, **_kwargs: object) -> PhaseOutcome:
|
|
calls.append("phases")
|
|
return PhaseOutcome()
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with (
|
|
patch("raven.cli.import_commands.maybe_build_memory_backend", return_value=_OrderingBackend(calls)),
|
|
patch("raven.cli.import_commands.run_import", new=_fake_run_import),
|
|
patch("raven.cli.import_commands.run_phases", new=_fake_phases),
|
|
):
|
|
result = await _build_and_run([], state)
|
|
|
|
assert calls == ["start", "run_import", "stop"], calls
|
|
assert result.summary is cancelled
|
|
assert result.profile is None
|
|
assert result.skills is None
|
|
|
|
async def test_phase_failures_travel_beside_the_import_result(self, tmp_path: Path) -> None:
|
|
"""The EverOS pass already succeeded, so its result must survive whatever
|
|
the phases report."""
|
|
calls: list[str] = []
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
|
|
async def _fake_run_import(*_args: object, **_kwargs: object) -> ImportSummary:
|
|
calls.append("run_import")
|
|
return summary
|
|
|
|
async def _fake_phases(*_args: object, **_kwargs: object) -> PhaseOutcome:
|
|
return PhaseOutcome(profile_error="bad byte", skill_error="claude_code: disk full")
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with (
|
|
patch("raven.cli.import_commands.maybe_build_memory_backend", return_value=_OrderingBackend(calls)),
|
|
patch("raven.cli.import_commands.run_import", new=_fake_run_import),
|
|
patch("raven.cli.import_commands.run_phases", new=_fake_phases),
|
|
):
|
|
result = await _build_and_run([], state)
|
|
|
|
assert result.summary is summary
|
|
assert result.profile_error == "bad byte"
|
|
assert result.skill_error == "claude_code: disk full"
|
|
|
|
async def test_phase_progress_reaches_the_bar_under_its_label(self, tmp_path: Path) -> None:
|
|
seen: list[tuple[str, int, int]] = []
|
|
summary = ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())
|
|
|
|
async def _fake_run_import(*_args: object, **_kwargs: object) -> ImportSummary:
|
|
return summary
|
|
|
|
async def _fake_phases(*_args: object, on_phase=None, **_kwargs: object) -> PhaseOutcome:
|
|
on_phase("profile", 1, 3)
|
|
on_phase("skills", 0, 2)
|
|
return PhaseOutcome()
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with (
|
|
patch("raven.cli.import_commands.maybe_build_memory_backend", return_value=_OrderingBackend([])),
|
|
patch("raven.cli.import_commands.run_import", new=_fake_run_import),
|
|
patch("raven.cli.import_commands.run_phases", new=_fake_phases),
|
|
):
|
|
await _build_and_run([], state, on_phase=lambda label, i, n: seen.append((label, i, n)))
|
|
|
|
assert seen == [("Mirroring profile", 1, 3), ("Installing skills", 0, 2)]
|
|
|
|
|
|
class TestBuildAndRunReadinessGate:
|
|
async def test_a_backend_that_is_not_ready_still_gets_stopped(self, tmp_path: Path) -> None:
|
|
"""The readiness check has to sit inside the ``try``: it exits the
|
|
command, and a backend that was started and never stopped leaves its
|
|
connections behind.
|
|
"""
|
|
calls: list[str] = []
|
|
not_ready = BackendHealth(ready=False, checks=[HealthCheck("server", "missing", "not running")])
|
|
|
|
async def _fake_run_import(*_args: object, **_kwargs: object) -> ImportSummary:
|
|
calls.append("run_import")
|
|
raise AssertionError("run_import must not be reached when the backend is not ready")
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
with (
|
|
patch(
|
|
"raven.cli.import_commands.maybe_build_memory_backend", return_value=_OrderingBackend(calls, not_ready)
|
|
),
|
|
patch("raven.cli.import_commands.run_import", new=_fake_run_import),
|
|
pytest.raises(typer.Exit),
|
|
):
|
|
await _build_and_run([], state)
|
|
|
|
assert calls == ["start", "stop"], calls
|
|
|
|
|
|
class TestFormatSkillSummary:
|
|
def test_names_the_untouched_factory_skills(self) -> None:
|
|
line = _format_skill_summary(SkillImportSummary(total=82, installed=12, pristine=70))
|
|
assert line == "12 installed, 70 kept as factory"
|
|
|
|
def test_rerun_reports_already_present_rather_than_a_bare_zero(self) -> None:
|
|
line = _format_skill_summary(SkillImportSummary(total=82, installed=0, pristine=70, skipped=12))
|
|
assert line == "0 installed, 70 kept as factory, 12 already present"
|
|
|
|
def test_failures_are_surfaced(self) -> None:
|
|
line = _format_skill_summary(SkillImportSummary(total=2, installed=1, failed=1))
|
|
assert line == "1 installed, 1 failed"
|
|
|
|
|
|
class TestPrintSummary:
|
|
"""The block `_build_and_run` no longer prints from inside the progress bar."""
|
|
|
|
@staticmethod
|
|
def _render(result: ImportRunResult, log_path: Path | None = None) -> str:
|
|
import io
|
|
|
|
from rich.console import Console
|
|
|
|
buf = io.StringIO()
|
|
with patch("raven.cli.import_commands.console", Console(file=buf, width=100)):
|
|
_print_summary(result, log_path=log_path)
|
|
return buf.getvalue()
|
|
|
|
def test_every_phase_reports_inside_the_block(self) -> None:
|
|
"""Each phase used to print its own line the moment it finished, which
|
|
put it above the progress bars -- before the numbers it qualifies."""
|
|
out = self._render(
|
|
ImportRunResult(
|
|
summary=ImportSummary(total=4, submitted=4, skipped=0, failed=0, errors=()),
|
|
profile=ImportedSections(written=("## Preferences", "## Notes"), skipped=1),
|
|
skills=SkillImportSummary(total=82, installed=12, pristine=70),
|
|
),
|
|
log_path=Path("/fake/import.log"),
|
|
)
|
|
|
|
header = out.index("Import Complete")
|
|
assert header < out.index("Submitted:") < out.index("Profile:") < out.index("Skills:") < out.index("Log:")
|
|
assert "2 entries into user.md, 1 already present" in out
|
|
assert "12 installed, 70 kept as factory" in out
|
|
|
|
def test_labels_share_one_column(self) -> None:
|
|
out = self._render(
|
|
ImportRunResult(
|
|
summary=ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=()),
|
|
profile=ImportedSections(written=("## Notes",), skipped=0),
|
|
skills=SkillImportSummary(total=1, installed=1),
|
|
),
|
|
log_path=Path("/fake/import.log"),
|
|
)
|
|
|
|
starts = {
|
|
line.index(line.split(":", 1)[1].lstrip()[:1], line.index(":"))
|
|
for line in out.splitlines()
|
|
if line.startswith(" ") and ":" in line and line.split(":", 1)[1].strip()
|
|
}
|
|
assert len(starts) == 1, out
|
|
|
|
def test_a_failed_phase_names_its_reason(self) -> None:
|
|
"""A phase that failed after a successful EverOS pass has no other way
|
|
to reach the user: loguru is file-only during `run`."""
|
|
out = self._render(
|
|
ImportRunResult(
|
|
summary=ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=()),
|
|
profile_error="disk full",
|
|
skill_error="permission denied",
|
|
)
|
|
)
|
|
|
|
assert "not mirrored: disk full" in out
|
|
assert "not installed: permission denied" in out
|
|
|
|
def test_phases_that_did_not_run_stay_out_of_the_block(self) -> None:
|
|
out = self._render(ImportRunResult(summary=ImportSummary(total=1, submitted=1, skipped=0, failed=0, errors=())))
|
|
|
|
assert "Profile:" not in out
|
|
assert "Skills:" not in out
|
|
|
|
|
|
class TestNonTTYGuard:
|
|
def test_import_run_nontty_no_traceback(self) -> None:
|
|
"""``run`` without --platform (two platforms found) in a non-TTY
|
|
terminal exits 2 with a re-run hint instead of crashing in questionary."""
|
|
results = [
|
|
_scan_result("a", platform=Platform.CLAUDE_CODE),
|
|
_scan_result("b", platform=Platform.CODEX),
|
|
]
|
|
with patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=results),
|
|
):
|
|
result = runner.invoke(import_app, ["run"])
|
|
assert result.exit_code == 2
|
|
assert "Traceback" not in result.output
|
|
assert "Re-run with:" in result.output
|
|
|
|
def test_import_run_nontty_tier_picker_guarded(self) -> None:
|
|
"""The tier picker (no --tier) is guarded the same way."""
|
|
with patch(
|
|
"raven.importer.scanners.scan_all",
|
|
new=AsyncMock(return_value=_make_scan_results()),
|
|
):
|
|
result = runner.invoke(import_app, ["run", "--platform", "claude_code"])
|
|
assert result.exit_code == 2
|
|
assert "Traceback" not in result.output
|
|
assert "Re-run with:" in result.output
|
|
|
|
|
|
class TestStatusCancelled:
|
|
def test_status_shows_cancelled(self, tmp_path: Path) -> None:
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
state.set_total(5)
|
|
state.mark_submitted("claude_code", "item1")
|
|
state.cancel_path.touch()
|
|
with patch("raven.cli.import_commands._default_state", return_value=state):
|
|
result = runner.invoke(import_app, ["status"])
|
|
assert result.exit_code == 0
|
|
assert "Cancelled" in result.output or "cancelled" in result.output
|
|
|
|
|
|
class TestImportRefusesToRunWithoutMemory:
|
|
"""An import against an unavailable memory service must not start.
|
|
|
|
The guard here caught an exception from ``backend.start()``. Once start
|
|
stopped raising -- it degrades and keeps probing, which is right for a
|
|
session -- the guard became unreachable, and an import would walk the whole
|
|
source list writing into nothing. An import is not a session: it is one
|
|
deliberate batch whose entire value is that the writes land.
|
|
"""
|
|
|
|
def test_a_backend_that_is_not_ready_stops_the_run(self) -> None:
|
|
import asyncio
|
|
|
|
import typer
|
|
|
|
from raven.cli.import_commands import _require_memory_service_ready
|
|
from raven.contracts.memory import BackendHealth, HealthCheck
|
|
|
|
class _NotReady:
|
|
async def health(self):
|
|
return BackendHealth(ready=False, checks=[HealthCheck("server", "ok", "not running")])
|
|
|
|
with pytest.raises(typer.Exit):
|
|
asyncio.run(_require_memory_service_ready(_NotReady()))
|
|
|
|
def test_a_bad_identity_does_not_send_the_user_to_the_server_log(self, capsys: pytest.CaptureFixture) -> None:
|
|
"""The service is fine; the config is not. Its log holds nothing about
|
|
this, and the backend already names the key to edit."""
|
|
import asyncio
|
|
|
|
import typer
|
|
|
|
from raven.cli.import_commands import _require_memory_service_ready
|
|
from raven.contracts.memory import BackendHealth, HealthCheck
|
|
|
|
class _BadIdentity:
|
|
async def health(self):
|
|
return BackendHealth(ready=False, checks=[HealthCheck("identity", "missing", "Fix memory.userId")])
|
|
|
|
with pytest.raises(typer.Exit):
|
|
asyncio.run(_require_memory_service_ready(_BadIdentity()))
|
|
|
|
out = " ".join(capsys.readouterr().out.split())
|
|
assert "server log" not in out
|
|
assert "memory.userId" in out
|
|
|
|
def test_a_ready_backend_passes(self) -> None:
|
|
import asyncio
|
|
|
|
from raven.cli.import_commands import _require_memory_service_ready
|
|
from raven.contracts.memory import BackendHealth
|
|
|
|
class _Ready:
|
|
async def health(self):
|
|
return BackendHealth(ready=True, checks=[])
|
|
|
|
asyncio.run(_require_memory_service_ready(_Ready()))
|
|
|
|
def test_a_backend_with_no_diagnostics_is_allowed(self) -> None:
|
|
"""``health()`` may answer ``None``. A backend that offers no
|
|
diagnostics must not be locked out of importing."""
|
|
import asyncio
|
|
|
|
from raven.cli.import_commands import _require_memory_service_ready
|
|
|
|
class _Silent:
|
|
async def health(self):
|
|
return None
|
|
|
|
asyncio.run(_require_memory_service_ready(_Silent()))
|
|
|
|
def test_a_backend_without_a_health_method_is_allowed(self) -> None:
|
|
"""``health`` arrived after the Protocol shipped. A backend built
|
|
before it has no diagnostics to offer, which is the same answer as
|
|
``None`` -- not a reason to refuse the import."""
|
|
import asyncio
|
|
|
|
from raven.cli.import_commands import _require_memory_service_ready
|
|
|
|
class _Older:
|
|
async def store(self, *_a, **_kw):
|
|
return True
|
|
|
|
asyncio.run(_require_memory_service_ready(_Older()))
|
|
|
|
async def test_a_missing_plugin_is_not_an_unconfigured_backend(
|
|
self, tmp_path: Path, capsys: pytest.CaptureFixture
|
|
) -> None:
|
|
"""Both cases arrive as ``backend is None`` and need different words.
|
|
|
|
`raven onboard` is the fix for "nobody configured one" and no fix at all
|
|
for "the configured one ships separately and is not installed here" --
|
|
sending the second case to the wizard is a loop with no exit.
|
|
"""
|
|
import typer
|
|
|
|
state = ImportState(path=tmp_path / "state.json")
|
|
|
|
with everos_plugin_absent(), pytest.raises(typer.Exit):
|
|
await _build_and_run([], state)
|
|
|
|
out = " ".join(capsys.readouterr().out.split())
|
|
assert "everos-memory" in out
|
|
assert "raven onboard" not in out
|
|
|
|
def test_the_run_path_consults_the_guard(self) -> None:
|
|
"""Pins the wiring: the guard is worthless if _build_and_run never
|
|
calls it, and that is exactly how the previous check died."""
|
|
import inspect
|
|
|
|
from raven.cli import import_commands
|
|
|
|
assert "_require_memory_service_ready" in inspect.getsource(import_commands._build_and_run)
|
|
|
|
|
|
class TestSkillCountsFollowThePlatform:
|
|
"""The count shown before consent has to be the count of the directories the
|
|
run then copies: each platform's own, not Hermes' for everyone."""
|
|
|
|
def test_a_platform_row_names_its_own_skills(self) -> None:
|
|
results = _make_scan_results()
|
|
assert "2 skills" in _platform_choice_label(Platform.CLAUDE_CODE, 11, results, 2)
|
|
assert "skills" not in _platform_choice_label(Platform.CLAUDE_CODE, 11, results, 0)
|
|
|
|
async def test_the_platform_picker_shows_each_platforms_count(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
results = _make_scan_results() + [_scan_result("h1", platform=Platform.HERMES, kind=SourceKind.MEMORY_FILE)]
|
|
offered: list[str] = []
|
|
|
|
class _Select:
|
|
def __init__(self, _q: str, *, choices: list[dict[str, Any]], **_k: Any) -> None:
|
|
offered.extend(c["name"] for c in choices)
|
|
|
|
async def ask_async(self) -> Platform:
|
|
return Platform.HERMES
|
|
|
|
monkeypatch.setattr("raven.cli.import_commands.die_if_not_tty", lambda *_a, **_k: None)
|
|
monkeypatch.setattr("raven.cli.import_commands._require_questionary", lambda: SimpleNamespace(select=_Select))
|
|
|
|
picked = await _pick_platform(results, {Platform.CLAUDE_CODE: 2, Platform.HERMES: 5})
|
|
|
|
assert picked is Platform.HERMES
|
|
claude_row = next(row for row in offered if row.startswith("Claude Code"))
|
|
hermes_row = next(row for row in offered if row.startswith("Hermes"))
|
|
assert "2 skills" in claude_row
|
|
assert "5 skills" in hermes_row
|
|
|
|
def test_the_consent_line_counts_the_selected_platforms_skills(self) -> None:
|
|
async def _count(platform: Platform | None) -> int:
|
|
return {Platform.CLAUDE_CODE: 2, Platform.HERMES: 5}.get(platform, 0) # type: ignore[arg-type]
|
|
|
|
with (
|
|
patch("raven.importer.scanners.scan_all", new=AsyncMock(return_value=_make_scan_results())),
|
|
patch("raven.cli.import_commands._importable_skill_count", new=_count),
|
|
):
|
|
result = runner.invoke(
|
|
import_app, ["run", "--platform", "claude_code", "--tier", "memory_files"], input="n\n"
|
|
)
|
|
|
|
assert result.exit_code == 0, result.output
|
|
assert "About to import 4 items (2 memory files, 2 skills, 0 conversations)" in result.stdout
|