From 19e2b23a878be3508e3f27f5047a2811188f260f Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 03:16:50 -0600 Subject: [PATCH 1/2] Rename sloth-memory to kvpark with explicit legacy migration --- .github/workflows/ci.yml | 3 +- CHANGELOG.md | 11 + CONTRIBUTING.md | 3 +- LICENSE | 2 +- NOTICE.md | 4 +- README.md | 85 +++---- SECURITY.md | 4 +- docs/backends.md | 51 ++-- docs/compatibility.md | 12 +- docs/hermes.md | 122 +++++----- docs/integration.md | 29 +-- docs/uninstall.md | 68 +++--- docs/updates.md | 194 +++++++++++---- docs/validation.md | 9 +- examples/chat.py | 4 +- pyproject.toml | 16 +- scripts/acceptance.py | 20 +- scripts/test_migration_release.py | 220 ++++++++++++++++++ scripts/test_update_release.py | 26 +-- src/kvpark/__init__.py | 11 + src/{sloth_memory => kvpark}/__main__.py | 0 src/{sloth_memory => kvpark}/backends.py | 0 src/{sloth_memory => kvpark}/cli.py | 42 ++-- src/{sloth_memory => kvpark}/hermes.py | 64 ++--- .../hermes_service.py | 18 +- .../hermes_uninstall.py | 24 +- src/kvpark/migration.py | 137 +++++++++++ src/{sloth_memory => kvpark}/network.py | 0 src/{sloth_memory => kvpark}/platforms.py | 0 src/{sloth_memory => kvpark}/proxy.py | 50 ++-- src/{sloth_memory => kvpark}/releases.py | 14 +- src/{sloth_memory => kvpark}/removal.py | 13 +- src/{sloth_memory => kvpark}/retention.py | 0 src/{sloth_memory => kvpark}/runtime.py | 4 +- .../update_compat.json | 0 src/{sloth_memory => kvpark}/updates.py | 28 +-- src/{sloth_memory => kvpark}/windows_job.py | 0 src/sloth_memory/__init__.py | 3 - tests/hermes/test_integration.py | 131 +++++++---- tests/test_archive.py | 6 +- tests/test_backends.py | 16 +- tests/test_cli_runtime.py | 10 +- tests/test_hermes_service.py | 26 +-- tests/test_migration.py | 77 ++++++ tests/test_platforms.py | 12 +- tests/test_removal.py | 16 +- tests/test_retention.py | 4 +- tests/test_updates.py | 14 +- 48 files changed, 1120 insertions(+), 483 deletions(-) create mode 100644 scripts/test_migration_release.py create mode 100644 src/kvpark/__init__.py rename src/{sloth_memory => kvpark}/__main__.py (100%) rename src/{sloth_memory => kvpark}/backends.py (100%) rename src/{sloth_memory => kvpark}/cli.py (76%) rename src/{sloth_memory => kvpark}/hermes.py (85%) rename src/{sloth_memory => kvpark}/hermes_service.py (94%) rename src/{sloth_memory => kvpark}/hermes_uninstall.py (89%) create mode 100644 src/kvpark/migration.py rename src/{sloth_memory => kvpark}/network.py (100%) rename src/{sloth_memory => kvpark}/platforms.py (100%) rename src/{sloth_memory => kvpark}/proxy.py (95%) rename src/{sloth_memory => kvpark}/releases.py (85%) rename src/{sloth_memory => kvpark}/removal.py (84%) rename src/{sloth_memory => kvpark}/retention.py (100%) rename src/{sloth_memory => kvpark}/runtime.py (96%) rename src/{sloth_memory => kvpark}/update_compat.json (100%) rename src/{sloth_memory => kvpark}/updates.py (92%) rename src/{sloth_memory => kvpark}/windows_job.py (100%) delete mode 100644 src/sloth_memory/__init__.py create mode 100644 tests/test_migration.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d6b4da1..4004017 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: python-version: ${{ matrix.python }} - run: python -m pip install . - run: python -m unittest discover -s tests -v - - run: sloth-memory --version + - run: kvpark --version runtime: runs-on: ${{ matrix.os }} strategy: @@ -65,6 +65,7 @@ jobs: - run: python -m pip install build psutil packaging - run: python -m build --wheel - run: python scripts/test_update_release.py dist + - run: python scripts/test_migration_release.py dist hermes: runs-on: ${{ matrix.os }} strategy: diff --git a/CHANGELOG.md b/CHANGELOG.md index 94cdf00..fb1531d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.3.0a1 — kvpark rename and migration + +- Rename the repository, Python distribution/module, CLI, and Hermes plugin to `kvpark`. +- Use `kvpark save / status / forget` and `/kvpark save / status / forget`; retain `park` as a compatibility alias and Hermes’ `delete` alias. +- Use `KVPARK_*` configuration names and `kvpark` default data directories for new installations; accept legacy `SLOTH_*` environment settings during migration. +- Add `python -m kvpark migrate --hermes` previews and `--confirm` application for existing sloth-memory profiles. +- Preserve the original archive directory, snapshot format, backend process, model configuration, and Hermes route backups; drain and stop only the verified legacy proxy. +- Disable the old plugin and enable kvpark. Migration requires stopped clients; restart Hermes afterward to launch and verify the new proxy before removing the old package. + +Releases below were published under the former **sloth-memory** name. Their command names and validation scope are historical. + ## 0.2.0a2 — uninstall and route recovery - Add `/sloth uninstall` previews and `/sloth uninstall confirm`, with terminal equivalents for Hermes and standalone services. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6481794..fa8e914 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,8 +13,7 @@ python -m pip install -e . python -m unittest discover -s tests -v ``` -Keep the Python runtime dependency-free unless a dependency solves a concrete -problem. Preserve session ownership, atomic archive publication, runtime identity +Keep runtime dependencies small; add one only when it solves a concrete problem. Preserve session ownership, atomic archive publication, runtime identity checks, and honest metrics. Add regression tests for behavior changes. Runtime changes need a fresh build and a real-model restart acceptance run. diff --git a/LICENSE b/LICENSE index 873712f..641c91b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Ulises Rayon and sloth-memory contributors +Copyright (c) 2026 Ulises Rayon and kvpark contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/NOTICE.md b/NOTICE.md index 14fb374..a88cd56 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -1,7 +1,7 @@ # Attribution -sloth-memory originated as a local Qwen conversation slot archive integrated with -Hermes. Its standalone proxy and CLI are MIT licensed. +kvpark originated as a local Qwen conversation slot archive integrated with +Hermes and was first released as sloth-memory. Its standalone proxy and CLI are MIT licensed. The included patch modifies llama.cpp, Copyright (c) 2023–2026 The ggml authors, under the MIT license. The upstream license is reproduced in diff --git a/README.md b/README.md index ac58f04..4dd76fd 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,19 @@ -# 🦥 sloth-memory +# 🅿️ kvpark -**Let your local AI nap. Resume long conversations without repeating all the work.** +**Park your model’s conversation state. Pick up where you left off.** -sloth-memory saves a local model's conversation inference state to disk and restores +kvpark saves a local model's conversation inference state to disk and restores it when you return. Built for people running open-weight models on their own hardware. MIT licensed. No cloud service or account. The portable runtime uses psutil. -**Alpha release `0.2.0a2`.** Supports Linux, macOS, and +**Alpha release `0.3.0a1`.** Supports Linux, macOS, and Windows startup, automatic free-port selection, and routing adapters for llama.cpp, Ollama, vLLM, and MLX-LM. Disk park/resume through this adapter still requires the managed patched llama.cpp runtime and one slot. See [backend capabilities](docs/backends.md). -Download the [current alpha](https://github.com/uncrayon/sloth-memory/releases/tag/v0.2.0a2). -Existing users: follow the [update guide](docs/updates.md), including the one-time -proxy replacement for installations older than this release. +Download the [current alpha](https://github.com/uncrayon/kvpark/releases/tag/v0.3.0a1). +Previously installed **sloth-memory**? Follow the +[one-time rename migration](docs/updates.md#migrate-from-sloth-memory) before enabling kvpark. +The package, CLI, Hermes command, and repository are now named `kvpark`. The service is independent of Hermes. A native Hermes adapter provides startup, slash-command onboarding, and cleanup controls. Other agents integrate through an HTTP proxy and explicit session metadata; a plain Python example is included. @@ -32,7 +33,7 @@ It does not add semantic memory, expand the context window, or reconstruct a cha from a cache file. Parking does not release the model's preallocated KV buffer. ```text -Your agent → sloth-memory (local proxy) → inference server +Your agent → kvpark (local proxy) → inference server ↕ local archive files ``` @@ -50,8 +51,8 @@ instead of creating the standalone environment below. Standalone installation on macOS/Linux: ```bash -git clone --branch v0.2.0a2 https://github.com/uncrayon/sloth-memory.git -cd sloth-memory +git clone --branch v0.3.0a1 https://github.com/uncrayon/kvpark.git +cd kvpark python3 -m venv .venv source .venv/bin/activate python -m pip install . @@ -79,7 +80,7 @@ The multiline shell examples below use macOS/Linux syntax; in PowerShell, put the command on one line and omit the continuation backslashes: ```bash -sloth-memory backend \ +kvpark backend \ --server runtime/build/bin/llama-server \ --model /absolute/path/to/your-model.gguf \ -- --ctx-size 8192 --cache-ram 0 --ctx-checkpoints 8 --checkpoint-min-step 128 --jinja @@ -88,41 +89,43 @@ sloth-memory backend \ In another terminal with the same virtual environment active: ```bash -sloth-memory serve +kvpark serve ``` -Keep both terminals running. Run `sloth-memory doctor` from a third terminal with +Keep both terminals running. Run `kvpark doctor` from a third terminal with the same environment active. Ports 8080 and 8090 are preferences; occupied ports automatically fall back to free ones. CLI controls discover the selected proxy. -Storage defaults to `~/Library/Application Support/sloth-memory` on macOS, -`~/.local/share/sloth-memory` on Linux, or `%LOCALAPPDATA%\sloth-memory` on Windows; +Storage defaults to `~/Library/Application Support/kvpark` on macOS, +`~/.local/share/kvpark` on Linux, or `%LOCALAPPDATA%\kvpark` on Windows; `XDG_DATA_HOME` overrides these. To change it, pass the **same** `--archive-dir` to the backend, proxy, and control commands. ## Updates -In Hermes, use `/sloth update check` to compare installed, loaded, and running -versions, then `/sloth update` to install a published release. The updater saves +For an installed kvpark package, use `/kvpark update check` in Hermes to compare +installed, loaded, and running versions, then `/kvpark update` to install a +published release. The former sloth-memory package needs the one-time migration first. The updater saves resident state, replaces its proxy, verifies health, and attempts rollback on failure. Hermes gateways restart through their native restart lifecycle. -For terminal use on any OS: `python -m sloth_memory update check` and -`python -m sloth_memory update`. See [updates and recovery](docs/updates.md). +For terminal use on any OS: `python -m kvpark update check` and +`python -m kvpark update`. See [updates and recovery](docs/updates.md). ## Use with Hermes Before trying the plugin, read [uninstall and return to your original backend](docs/uninstall.md). -It covers `/sloth uninstall`, package removal, and optional archive/build cleanup. +It covers `/kvpark uninstall`, package removal, and optional archive/build cleanup. -Install sloth-memory in Hermes' Python environment, enable it with -`hermes plugins enable sloth-memory`, and restart Hermes. Then run: +Install kvpark in Hermes' Python environment, enable it with +`hermes plugins enable kvpark`, and restart Hermes. Then run: ```text -/sloth-memory setup +/kvpark setup ``` The [Hermes setup guide](docs/hermes.md) covers selecting the backend and model. +Migrating from sloth-memory? Use the [rename migration](docs/updates.md#migrate-from-sloth-memory), which preserves its archive and backend. Already using a custom proxy or qwen-slot? Follow the [migration steps](docs/hermes.md#migrate-an-existing-custom-integration) to retire the old services and preserve your model settings. Complete setup starts the proxy and selects its actual URL for new Hermes sessions. @@ -131,12 +134,12 @@ under your control. Services keep running after Hermes closes for cleanup. No su is needed. Disk controls below require native snapshot mode. ```text -/sloth-memory park -/sloth-memory delete -/sloth-memory retention 7 -/sloth-memory cleanup off -/sloth-memory cleanup on -/sloth-memory base-url http://127.0.0.1:8080 +/kvpark save +/kvpark forget +/kvpark retention 7 +/kvpark cleanup off +/kvpark cleanup on +/kvpark base-url http://127.0.0.1:8080 ``` By default, cleanup runs hourly and expires snapshots **seven days after saving**. @@ -153,8 +156,8 @@ The example client defaults to port 8080. If the proxy selected another port, pa python examples/chat.py --session cli:orchid:1 --history orchid-chat.json \ 'Our project code is ORCHID-731. Help me plan a workshop.' -sloth-memory park --session cli:orchid:1 -sloth-memory status +kvpark save --session cli:orchid:1 +kvpark status ``` Stop both services with Ctrl-C, then start them again with exactly the same @@ -164,7 +167,7 @@ commands. Continue using the same transcript and session: python examples/chat.py --session cli:orchid:1 --history orchid-chat.json \ 'What was the project code?' -sloth-memory status +kvpark status ``` Short chats demonstrate the workflow but may gain little speed. Long stable @@ -195,14 +198,14 @@ streaming and authentication. The optional Hermes adapter does not patch Hermes. | Command | Purpose | | --- | --- | -| `sloth-memory backend --server … --model … -- …` | Launch the backend and record runtime identity | -| `sloth-memory serve` | Run the inference proxy | -| `sloth-memory doctor` | Check backend reachability, runtime identity, and the single-slot topology | -| `sloth-memory park --session …` | Save exactly that resident conversation | -| `sloth-memory status` | Inspect archives and actual completed-request reuse | -| `sloth-memory forget --session …` | Delete that saved archive; keep the transcript | -| `sloth-memory settings --ttl-days 7 --cleanup` | Persist cleanup preferences without a restart | -| `sloth-memory cleanup` | Run cleanup now | +| `kvpark backend --server … --model … -- …` | Launch the backend and record runtime identity | +| `kvpark serve` | Run the inference proxy | +| `kvpark doctor` | Check backend reachability, runtime identity, and the single-slot topology | +| `kvpark save --session …` | Save exactly that resident conversation | +| `kvpark status` | Inspect archives and actual completed-request reuse | +| `kvpark forget --session …` | Delete that saved archive; keep the transcript | +| `kvpark settings --ttl-days 7 --cleanup` | Persist cleanup preferences without a restart | +| `kvpark cleanup` | Run cleanup now | `doctor` does not prove checkpoint support or cache reuse. Verify the complete flow with your own model: @@ -247,4 +250,4 @@ python -m unittest discover -s tests -v Useful early contributions: reproducible model compatibility reports, agent adapters, installation feedback, and upstream checkpoint persistence work. -See [CONTRIBUTING.md](CONTRIBUTING.md). Bring a slow conversation; let the sloth help. +See [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/SECURITY.md b/SECURITY.md index d9b3b1a..b4a0fa5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,7 +1,7 @@ # Security and deployment scope -This alpha is for a trusted user on one Linux machine. It binds to localhost, -rejects browser Origin requests, and optionally requires `SLOTH_API_KEY` for all +This alpha is for a trusted user on one Linux, macOS, or Windows machine. It binds to localhost, +rejects browser Origin requests, and optionally requires `KVPARK_API_KEY` for all proxy endpoints. It is not a multi-user inference gateway. Do not expose its ports through a tunnel or public reverse proxy as a shared service. diff --git a/docs/backends.md b/docs/backends.md index c10c823..014aabd 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -1,11 +1,11 @@ # Backends and operating systems -This describes alpha `0.2.0a2`. Older alpha.2 installations retain their original -Linux-only scope until upgraded. +This describes kvpark alpha `0.3.0a1`. Existing sloth-memory users should follow +the [rename migration](updates.md#migrate-from-sloth-memory). ## Capability contract -| Backend | Chat proxy and Hermes routing | sloth-memory disk park/resume | +| Backend | Chat proxy and Hermes routing | kvpark disk park/resume | | --- | --- | --- | | Patched llama.cpp, managed locally | Yes | Yes; validate each model/build | | Stock llama.cpp, existing server | Yes, `--cache-mode routing` | Unavailable | @@ -17,7 +17,7 @@ Routing preserves the served model name, messages, tool calls, and streaming. `status` and `doctor` report `capabilities.disk_snapshots` explicitly. In routing mode, parking returns an error instead of claiming that inference state was saved. No transcript cache is substituted for a KV snapshot. Seven-day cleanup only -manages files owned by sloth-memory, never a backend's independent prefix cache. +manages files owned by kvpark, never a backend's independent prefix cache. The proxy and Python runtime target Linux, macOS, and Windows. CI runs the Python suite and builds the patched llama.cpp runtime on all three systems. The backend @@ -32,9 +32,9 @@ Then configure Hermes with the **exact model ID served by that server**. Use [the model-ID lookup below](#find-your-model-id) before replacing the placeholders: ```text -/sloth-memory setup --backend ollama --upstream-url http://127.0.0.1:11434 --model "your-model:tag" -/sloth-memory setup --backend vllm --upstream-url http://127.0.0.1:8000 --model "your-served-model" -/sloth-memory setup --backend mlx --upstream-url http://127.0.0.1:8081 --model "your-mlx-model" +/kvpark setup --backend ollama --upstream-url http://127.0.0.1:11434 --model "your-model:tag" +/kvpark setup --backend vllm --upstream-url http://127.0.0.1:8000 --model "your-served-model" +/kvpark setup --backend mlx --upstream-url http://127.0.0.1:8081 --model "your-mlx-model" ``` Choose one backend per archive directory. To run another stack, include @@ -43,13 +43,13 @@ selected URL into Hermes' model configuration. No sudo, packet interception, firewall edits, or privileged ports are required: ```text -Hermes → sloth-memory (selected localhost port) → your inference server +Hermes → kvpark (selected localhost port) → your inference server ``` An existing unpatched llama.cpp server can be attached explicitly: ```text -/sloth-memory setup --backend llama.cpp --cache-mode routing --upstream-url http://127.0.0.1:8090 --model "your-served-alias" +/kvpark setup --backend llama.cpp --cache-mode routing --upstream-url http://127.0.0.1:8090 --model "your-served-alias" ``` For native disk snapshots, build the included runtime and use the existing @@ -60,8 +60,8 @@ For native disk snapshots, build the included runtime and use the existing Standalone example, without Hermes: ```bash -sloth-memory serve --backend ollama --upstream-url http://127.0.0.1:11434 -sloth-memory doctor +kvpark serve --backend ollama --upstream-url http://127.0.0.1:11434 +kvpark doctor ``` Both commands use the same default archive directory. With a custom directory, @@ -76,10 +76,10 @@ It may be a serving alias, a repository name, a tagged name, or a full file path Copy it exactly, including capitalization, slashes, and tags; a display name such as “Gemma” is not enough unless you configured that exact alias. -Start the backend, then query its **own address**, before connecting Sloth. Run +Start the backend, then query its **own address**, before connecting kvpark. Run the appropriate command from the machine running Hermes: -| Backend | List models (example address) | Value to use for Sloth's `--model` | +| Backend | List models (example address) | Value to use for kvpark's `--model` | | --- | --- | --- | | Existing llama.cpp | `curl -fsS http://127.0.0.1:8090/v1/models` | An `id` inside `data`; usually the `--alias` value, otherwise the model file path | | Ollama | `curl -fsS http://127.0.0.1:11434/v1/models` | An `id` inside `data`, including its tag, such as `example-model:latest` | @@ -104,8 +104,8 @@ For example, if your vLLM server returns: Use the **`id` string `my-gemma`**, not the entire JSON object: ```text -/sloth setup --backend vllm --cache-mode routing --upstream-url http://127.0.0.1:8000 --model "my-gemma" -/sloth status +/kvpark setup --backend vllm --cache-mode routing --upstream-url http://127.0.0.1:8000 --model "my-gemma" +/kvpark status ``` `my-gemma` is an example alias, not a model to download. If you choose to set that @@ -121,8 +121,8 @@ the model you intend to serve; a listing alone does not prove that it can load o generate successfully. A locally served model can appear as an absolute directory path, so keep the quotes around `--model` when the path contains spaces. -For Sloth's **managed native llama.cpp setup**, `--model` instead takes your local -GGUF path, as shown in the [Hermes guide](hermes.md#guided-setup). Sloth starts that +For kvpark's **managed native llama.cpp setup**, `--model` instead takes your local +GGUF path, as shown in the [Hermes guide](hermes.md#guided-setup). kvpark starts that backend with the alias `local` and selects it for Hermes automatically. If discovery fails: @@ -132,7 +132,7 @@ If discovery fails: - **401 or 403:** use the backend's required authentication. For a Bearer-protected endpoint, supply an `Authorization: Bearer …` header; keep the credential out of chat and committed files. See [upstream credentials](#port-selection-and-routing) - when configuring Sloth to connect to that server. + when configuring kvpark to connect to that server. - **404 or HTML response:** check that this is the inference API address, not a web UI, and that `/v1` was not added twice. - **Empty `data` list:** check the backend's model configuration/downloads and @@ -163,17 +163,20 @@ non-OpenAI client implementations are untouched; restart those sessions through the configured proxy. Disabling autostart leaves already running services alive. The proxy listens only on `127.0.0.1`. Remote upstreams can use HTTPS and an -upstream credential file (`SLOTH_UPSTREAM_KEY_FILE`); the proxy's optional -`SLOTH_API_KEY` is separate. Credentials are not stored in service metadata. +upstream credential file (`KVPARK_UPSTREAM_KEY_FILE`); the proxy's optional +`KVPARK_API_KEY` is separate. Credentials are not stored in service metadata. ## Platform storage Defaults follow `XDG_DATA_HOME` when set; otherwise: -- Linux: `~/.local/share/sloth-memory` -- macOS: `~/Library/Application Support/sloth-memory` -- Windows: `%LOCALAPPDATA%\sloth-memory` +- Linux: `~/.local/share/kvpark` +- macOS: `~/Library/Application Support/kvpark` +- Windows: `%LOCALAPPDATA%\kvpark` +These defaults apply to new installations. The [sloth-memory migration](updates.md#migrate-from-sloth-memory) +keeps the existing archive directory, even when its name still contains `sloth-memory`. +Do not move it to match the new brand: its path is part of runtime compatibility. Explicit `--archive-dir` keeps an existing installation in place. Portable process identity uses psutil; Windows uses native byte-range file locks and a Job Object for managed child lifetime. Metadata files are flushed before atomic replacement. @@ -185,7 +188,7 @@ durability than the Unix directory-flush path. Full disk resume across all four engines is **not implemented**. The next backend work needs real engine-side integration and model/hardware acceptance tests: -- Ollama's documented OpenAI API provides chat routing, but not sloth-memory's +- Ollama's documented OpenAI API provides chat routing, but not kvpark's snapshot controls. `keep_alive` controls model residency, not durable snapshots. [Ollama API](https://docs.ollama.com/api/openai-compatibility), [generate parameters](https://docs.ollama.com/api/generate). diff --git a/docs/compatibility.md b/docs/compatibility.md index fd96cda..645f51c 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,7 +1,9 @@ # Runtime compatibility -This page describes alpha `0.2.0a2`. See [backends](backends.md) for routing -capabilities. Older alpha.2 installations retain their original Linux-only scope. +This page describes alpha `0.3.0a1`. See [backends](backends.md) for routing +capabilities. The rename from sloth-memory preserves snapshot format 2; the +[migration](updates.md#migrate-from-sloth-memory) keeps the archive path and runtime +unchanged so existing compatible snapshots remain usable. ## Runtime @@ -10,7 +12,7 @@ The build script pins ggml-org/llama.cpp to `patches/llama-slot-resume.patch`. This patch persists hybrid/recurrent context checkpoints as well as target, draft, and speculative state. The `.bin.resume` companion is mandatory: a stock `.bin` alone cannot be published as a usable -sloth-memory archive in the current implementation. Stock llama.cpp already has +kvpark archive in the current implementation. Stock llama.cpp already has slot save/restore APIs; the companion requirement is specific to this adapter. This persistence patch is separate from the originating project's DFlash2 position fix and is not restricted to DFlash2. @@ -67,7 +69,7 @@ python scripts/build_runtime.py --output runtime-rocm --cmake-arg=-DGGML_HIP=ON ``` These switches select upstream backends, not verified support for your GPU. -Use the resulting binary path with `sloth-memory backend` and pass any device +Use the resulting binary path with `kvpark backend` and pass any device settings after `--`. Use explicit local file paths and long-form model/draft/ projector arguments. `LLAMA_ARG_*` environment defaults are refused to keep the runtime identity reproducible. Other kernel environment settings are fingerprinted. @@ -85,7 +87,7 @@ also cleaned; arbitrary files, symlinks, and live RAM state are not swept. `settings --ttl-days 7 --max-gib 32 --cleanup` changes and persists preferences. `--no-cleanup` disables scheduled deletion and age expiry on restore; -`--ttl-days 0` disables age expiry only. `sloth-memory cleanup` runs a manual sweep. +`--ttl-days 0` disables age expiry only. `kvpark cleanup` runs a manual sweep. Explicit `serve --ttl-days … --max-gib … --[no-]cleanup` flags override saved preferences; omitted flags preserve them. diff --git a/docs/hermes.md b/docs/hermes.md index 9d4ecbf..e2dbb68 100644 --- a/docs/hermes.md +++ b/docs/hermes.md @@ -1,32 +1,34 @@ # Hermes adapter and onboarding -These instructions install alpha `0.2.0a2`, including portable startup, automatic +These instructions install alpha `0.3.0a1`, including portable startup, automatic port selection, and release updates. See [backend setup](backends.md) for capabilities. -The adapter ships inside sloth-memory as a native Hermes plugin. It uses plugin +The adapter ships inside kvpark as a native Hermes plugin. It uses plugin discovery, request middleware, commands, and profile settings. It does not patch Hermes source or replace its semantic memory provider. ## Install alongside Hermes -Install into **the same Python environment that runs Hermes**: +If you already installed sloth-memory, use the [rename migration](updates.md#migrate-from-sloth-memory) instead of enabling a second plugin. + +For a new installation, use **the same Python environment that runs Hermes**: ```bash # With your Hermes virtual environment activated: -git clone --branch v0.2.0a2 https://github.com/uncrayon/sloth-memory.git -cd sloth-memory +git clone --branch v0.3.0a1 https://github.com/uncrayon/kvpark.git +cd kvpark python -m pip install --upgrade . -hermes plugins enable sloth-memory +hermes plugins enable kvpark ``` If Hermes asks whether the plugin may replace built-in tools, answer **No**. -sloth-memory registers commands and middleware; it needs no tool overrides. +kvpark registers commands and middleware; it needs no tool overrides. Use `hermes plugins list --plain --no-bundled` to check that it is enabled. -For an existing installation, follow [updates and recovery](updates.md). Versions -older than `0.2.0a1` need a one-time package installation and proxy replacement; -subsequent releases can use `/sloth update`. Run `sloth-memory --version` in -Hermes' environment to confirm `0.2.0a2`. Restart Hermes after installation to +Existing kvpark installations can use `/kvpark update`; sloth-memory installations +need the [one-time rename migration](updates.md#migrate-from-sloth-memory), because +the old updater cannot replace a differently named package. Run `kvpark --version` in +Hermes' environment to confirm `0.3.0a1`. Restart Hermes after installation to load the entry point. The adapter is tested against Hermes 0.21.0, upstream commit `9dd6634c5635321cf38840cc30e9b51226689128`. Use Python 3.11–3.13 for Hermes; the standalone service also supports 3.10/3.14. @@ -68,13 +70,13 @@ snapshots; rebooting does not reset their age. A gateway restart reuses an existing compatible proxy so it does not interrupt shared inference. It does not automatically replace that proxy's Python code. -Use `/sloth update check` to see all three versions and `/sloth update` for the +Use `/kvpark update check` to see all three versions and `/kvpark update` for the coordinated release update. See [updates and recovery](updates.md). ## Guided setup -`/sloth` is a shortcut for `/sloth-memory` on every platform. Use `/sloth` in -Telegram, including for the setup commands below. +Use `/kvpark` in the Hermes CLI, Discord, and Telegram. It opens setup instructions +when called without arguments. Already serving a model with vLLM, Ollama, MLX-LM, or llama.cpp? First [find its exact model ID](backends.md#find-your-model-id), then follow @@ -83,15 +85,15 @@ That guide shows the lookup command for each backend and which response value to copy into `--model`; no llama.cpp build is needed for routing an existing server. ```text -/sloth-memory setup +/kvpark setup ``` This shows defaults and the next step. For managed disk snapshots, configure the included patched runtime: ```text -/sloth-memory setup --server "/absolute/path/to/llama-server" --model "/absolute/path/to/model.gguf" -/sloth-memory status +/kvpark setup --server "/absolute/path/to/llama-server" --model "/absolute/path/to/model.gguf" +/kvpark status ``` Complete setup starts services and saves the selected proxy `/v1` URL through @@ -107,18 +109,18 @@ redirected by the native OpenAI client middleware; unrelated routes are unchange Keep that server running and use its listening URL and served model ID: ```text -/sloth-memory setup --backend llama.cpp --cache-mode routing --upstream-url http://127.0.0.1:8090 --model "your-served-alias" -/sloth-memory status +/kvpark setup --backend llama.cpp --cache-mode routing --upstream-url http://127.0.0.1:8090 --model "your-served-alias" +/kvpark status ``` -This tests `Hermes → sloth-memory → your existing llama.cpp`. It does **not** +This tests `Hermes → kvpark → your existing llama.cpp`. It does **not** enable disk park/resume: stock llama.cpp has save/restore APIs, but this adapter currently requires its additional state companion for native archives. To test persistence after this routing test, explicitly clear the existing upstream and select native mode with a separate archive directory: ```text -/sloth-memory setup --backend llama.cpp --cache-mode native --upstream-url "" --no-external --archive-dir "/absolute/path/to/sloth-native" --server "/absolute/path/to/llama-server" --model "/absolute/path/to/model.gguf" +/kvpark setup --backend llama.cpp --cache-mode native --upstream-url "" --no-external --archive-dir "/absolute/path/to/kvpark-native" --server "/absolute/path/to/llama-server" --model "/absolute/path/to/model.gguf" ``` See [other backends](backends.md#connect-an-existing-server) for Ollama, vLLM, and MLX-LM. @@ -153,43 +155,42 @@ also checked before restoring a snapshot. ## Daily controls ```text -/sloth-memory park -/sloth-memory status -/sloth-memory slots -/sloth-memory delete +/kvpark save +/kvpark status +/kvpark slots +/kvpark forget ``` Disk park/resume requires native snapshot mode. Routing-only adapters report `capabilities.disk_snapshots: false` in status and reject parking. Before the first park after installation or migration, **send a normal message -in that same conversation and wait for the reply**. Then run `/sloth-memory park`. +in that same conversation and wait for the reply**. Then run `/kvpark save`. Opening a saved transcript, `/status`, and restarting the gateway do not send its history through the model, so they cannot create resident state to save. A chat from the old integration may need a fresh prefill on this first message. If the command says there is no saved or resident state, follow that sequence. -`/sloth-memory slots` lists snapshots already saved through this plugin; it cannot +`/kvpark slots` lists snapshots already saved through this plugin; it cannot recover a conversation that has never run through the new proxy. -Park and delete target the current verified conversation and make no model call. +`save` and `forget` target the current verified conversation and make no model call. To delete another saved slot, copy its full key from `slots`: ```text -/sloth-memory delete k- +/kvpark forget k- ``` Resume by sending a normal message in the same compatible session. ## Telegram command picker -Use `/sloth setup`, `/sloth status`, and `/sloth park` in Telegram. Telegram -command names cannot contain hyphens; the short alias also preserves the current -chat's identity through Hermes' command hooks. Avoid the automatically converted -`/sloth_memory` spelling on the tested Hermes version. +Use `/kvpark setup`, `/kvpark status`, and `/kvpark save` in Telegram. The command +name is valid on Telegram and preserves the current chat’s identity through +Hermes’ command hooks. Hermes limits its Telegram menu to 60 commands by default, so a working plugin -command can be omitted from the picker. To keep `/sloth` visible, add it to the +command can be omitted from the picker. To keep `/kvpark` visible, add it to the menu priority in your Hermes profile's `config.yaml`, merging with any existing platform settings and priority entries: @@ -198,19 +199,19 @@ platforms: telegram: extra: command_menu: - priority: [sloth] + priority: [kvpark] priority_mode: prepend ``` Restart the Hermes gateway after installation and configuration. It publishes the menu to Telegram for default, private-chat, and group scopes. Reopen the chat or command menu if the client still shows cached suggestions. You can also type -`/sloth status` directly while checking menu registration. +`/kvpark status` directly while checking menu registration. ## Discord command picker -The enabled plugin registers `/sloth-memory` with Hermes' native Discord command -list. In the picker, select it and enter `setup`, `status`, `park`, or another +The enabled plugin registers `/kvpark` with Hermes' native Discord command +list. In the picker, select it and enter `setup`, `status`, `save`, `forget`, or another subcommand in the optional **args** field. Typing the complete text command also works. @@ -228,13 +229,13 @@ accepted the application's command catalog. ## Preferences ```text -/sloth-memory retention 7 -/sloth-memory budget 32 -/sloth-memory cleanup off -/sloth-memory cleanup on -/sloth-memory cleanup now -/sloth-memory autostart off -/sloth-memory autostart on +/kvpark retention 7 +/kvpark budget 32 +/kvpark cleanup off +/kvpark cleanup on +/kvpark cleanup now +/kvpark autostart off +/kvpark autostart on ``` Retention and budget use days and GiB. `retention 0` disables age expiry. @@ -247,7 +248,7 @@ inference. Autostart off affects future launches; it does not stop running servi Change the base address with: ```text -/sloth-memory base-url http://127.0.0.1:18080 +/kvpark base-url http://127.0.0.1:18080 ``` Use `connect` afterward to select the new route for future sessions. A second @@ -255,36 +256,41 @@ managed stack needs a separate archive directory. Ports below are preferences; occupied ports fall back automatically: ```text -/sloth-memory setup --base-url http://127.0.0.1:18080 --upstream-port 18090 --archive-dir "/path/to/separate/archive" --server "/path/to/llama-server" --model "/path/to/model.gguf" +/kvpark setup --base-url http://127.0.0.1:18080 --upstream-port 18090 --archive-dir "/path/to/separate/archive" --server "/path/to/llama-server" --model "/path/to/model.gguf" ``` Existing services are never silently moved or killed. To attach to a separately -managed **alpha.2 or newer** sloth-memory proxy: +managed **kvpark 0.3.0a1 or newer** proxy: ```text -/sloth-memory setup --external --base-url http://127.0.0.1:18080 +/kvpark setup --external --base-url http://127.0.0.1:18080 ``` External mode never launches services. `--no-external` returns to managed startup. `--backend-args` accepts a quoted argument string; for a CPU setup, for example: ```text -/sloth-memory setup --backend-args "--device none --n-gpu-layers 0 --ctx-size 8192 --cache-ram 0 --ctx-checkpoints 8 --checkpoint-min-step 128 --jinja" +/kvpark setup --backend-args "--device none --n-gpu-layers 0 --ctx-size 8192 --cache-ram 0 --ctx-checkpoints 8 --checkpoint-min-step 128 --jinja" ``` Backend settings apply when the backend is next launched. Setup never restarts an active model. Plugin settings live under -`plugins.entries.sloth-memory.settings.service` in the active Hermes profile. -Secrets stay in `SLOTH_API_KEY` and `SLOTH_UPSTREAM_KEY_FILE`; onboarding does not -write or print them. +`plugins.entries.kvpark.settings.service` in the active Hermes profile. +Secrets stay in `KVPARK_API_KEY` and `KVPARK_UPSTREAM_KEY_FILE`; onboarding does not +write or print them. Legacy `SLOTH_*` environment settings remain supported during +migration; prefer `KVPARK_*` for new configuration. ## Migrate an existing custom integration -Install and verify `/sloth-memory setup` before changing the active model route. +These steps are for qwen-slot or another custom integration. **For sloth-memory, +use the [rename migration](updates.md#migrate-from-sloth-memory)** and keep its +archive directory and running backend unchanged. + +Install and verify `/kvpark setup` before changing the active model route. Keep a private backup of your Hermes profile's `config.yaml`, `.env`, old service configuration, and plugin links. These files can contain credentials; do not commit them. Keep existing transcripts and legacy archives in place. Use a fresh -sloth-memory archive directory: changing the runtime arguments or archive namespace +kvpark archive directory: changing the runtime arguments or archive namespace can invalidate previous snapshots, so the first request may need a fresh prefill. Before configuring managed startup: @@ -293,12 +299,12 @@ Before configuring managed startup: 2. Park the resident conversation through the old integration if it supports it. 3. Stop the old proxy and model service, and disable their automatic startup. Port fallback prevents address conflicts but does not prevent loading a second - copy of the model. System-level services may need sudo to retire; sloth-memory + copy of the model. System-level services may need sudo to retire; kvpark itself runs as your normal user. 4. Disable the old archive plugin (`hermes plugins disable qwen-slot` for the original integration). Retire any custom provider override that injected its archive metadata. Preserve unrelated providers and model settings. -5. Configure sloth-memory, start a new Hermes session, then restart the gateway +5. Configure kvpark, start a new Hermes session, then restart the gateway after the new route and disk persistence have been checked. A model-specific GPU runtime that already includes the compatible slot-resume @@ -312,7 +318,7 @@ This option **replaces** the default argument list. Include `--ctx-checkpoints 8 --checkpoint-min-step 128`; use `--cache-ram 0` for the restart test so RAM prompt caching cannot stand in for a disk restore. Do not copy `--model`, `--alias`, `--host`, `--port`, `--parallel`, -`--slot-save-path`, or UI switches from the old launcher; sloth-memory owns them. +`--slot-save-path`, or UI switches from the old launcher; kvpark owns them. The managed model is advertised as `local`. Custom GPU bundles may require environment variables such as `LD_LIBRARY_PATH`. diff --git a/docs/integration.md b/docs/integration.md index c7f572c..486825a 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -1,6 +1,6 @@ # Agent integration contract -sloth-memory owns inference state. Your agent owns the transcript and session +kvpark owns inference state. Your agent owns the transcript and session lifecycle. No Hermes imports or model-provider dependency exists in the core. ## Request identity @@ -37,20 +37,21 @@ including draining disconnected clients, before another request may claim the sl ## Controls -`GET /_sloth/status` returns resident identity, archives, global activity, and recent -events. `GET /_sloth/doctor` checks runtime identity and backend slot topology when -idle. `POST /_sloth/park` and `POST /_sloth/forget` take: +`GET /_kvpark/status` returns resident identity, archives, global activity, and recent +events. `GET /_kvpark/doctor` checks runtime identity and backend slot topology when +idle. `POST /_kvpark/save` and `POST /_kvpark/forget` take: ```json {"key": "k-"} ``` -The CLI hashes `--session` for you. Parking is a native command/action; it should +The CLI hashes `--session` for you: `kvpark save --session …` saves and +`kvpark forget --session …` removes that archive. Parking is a native command/action; it should not require an LLM turn that could displace the state you wanted to save. Resume is automatic on the next matching inference request. There is no manual restore action that reconstructs a transcript. -An internal `POST /_sloth/simulate-gap` control also saves and erases a resident +An internal `POST /_kvpark/simulate-gap` control also saves and erases a resident slot for diagnostics. It does not prove a process-restart or physical SSD test. Control failures return HTTP 409 with a reason. Archive failures during inference @@ -73,19 +74,19 @@ separate measurements. ## Authentication The alpha binds only to `127.0.0.1` and rejects browser Origin requests. For an -additional local access boundary, set `SLOTH_API_KEY` on the proxy and CLI/client; +additional local access boundary, set `KVPARK_API_KEY` on the proxy and CLI/client; all endpoints then require that bearer token. If the backend requires a key, set -`SLOTH_UPSTREAM_KEY_FILE` to a private local file in the proxy environment and pass +`KVPARK_UPSTREAM_KEY_FILE` to a private local file in the proxy environment and pass the corresponding upstream authentication option when launching the backend. Never publish keys, transcript files, or archive directories. ## Cleanup settings API -`GET /_sloth/settings` reads `ttl_days`, `max_gib`, and `cleanup_enabled`. -`POST /_sloth/settings` atomically persists any subset of those settings. -`POST /_sloth/cleanup` runs a manual sweep with the saved age/budget rules. +`GET /_kvpark/settings` reads `ttl_days`, `max_gib`, and `cleanup_enabled`. +`POST /_kvpark/settings` atomically persists any subset of those settings. +`POST /_kvpark/cleanup` runs a manual sweep with the saved age/budget rules. Unknown keys, invalid booleans, negative ages, and nonpositive budgets are refused. -Status includes the running package `version`, `maintenance`, `service: "sloth-memory"` and `control_version: 4` for adapters. +Status includes the running package `version`, `maintenance`, `service: "kvpark"` and `control_version: 4` for adapters. ## Hermes @@ -93,4 +94,6 @@ The native adapter now ships as a `hermes_agent.plugins` entry point. Follow the [Hermes guide](hermes.md) for launch-on-load, slash-command setup, parking, deletion, and persistent cleanup controls. It does not edit Hermes internals. Legacy `/qwen-slot` plugins use `/__slot_proxy/` and `SLOT_PROXY_*`; this package -uses `/_sloth/` and `SLOTH_*`. +uses `/_kvpark/` and `KVPARK_*`. The former sloth-memory package used `/_sloth/`; +its migration is documented in [updates](updates.md#migrate-from-sloth-memory). +The request identity fields and Hermes profile namespace remain unchanged by the rename. diff --git a/docs/uninstall.md b/docs/uninstall.md index c173bfc..f086e81 100644 --- a/docs/uninstall.md +++ b/docs/uninstall.md @@ -1,7 +1,9 @@ # Uninstall and return to your original backend -The automated commands below require **`0.2.0a2` or newer**. For `0.2.0a1`, -use `/sloth update` first or follow the manual procedure below. +The commands below apply to **kvpark `0.3.0a1` or newer**. Still using the former +sloth-memory package? Its `0.2.0a2` release provides `/sloth uninstall`; for +`0.2.0a1`, follow the [legacy manual procedure](#manual-procedure-for-sloth-memory-020a1) below. +The [rename migration](updates.md#migrate-from-sloth-memory) is separate from uninstall. Uninstall has two steps: disconnect the integration, then remove the package and any files you no longer want. Disconnect first so Hermes does not keep calling a @@ -11,10 +13,10 @@ proxy that has been removed. No sudo is required for the standard installation. | Component | Location / owner | Removal | | --- | --- | --- | -| Python package and Hermes entry point | The Python environment used for installation | `python -m pip uninstall sloth-memory` | +| Python package and Hermes entry point | The Python environment used for installation | `python -m pip uninstall kvpark` | | Enabled plugin and model route | Active Hermes profile's `config.yaml` | Automated disconnect restores the saved route and disables the plugin | -| Proxy and hourly cleanup loop | A Sloth Python process | Automated disconnect stops the verified archive-owned proxy | -| Managed llama.cpp backend, if selected | Process started by Sloth | Automated disconnect stops the verified archive-owned backend | +| Proxy and hourly cleanup loop | A kvpark Python process | Automated disconnect stops the verified archive-owned proxy | +| Managed llama.cpp backend, if selected | Process started by kvpark | Automated disconnect stops the verified archive-owned backend | | Existing llama.cpp, Ollama, vLLM, or MLX server | Your existing installation | Kept running | | Saved slots, logs, update backups and metadata | Configured archive directory | Kept until you explicitly remove that directory | | Optional patched llama.cpp build | `runtime/` in the source checkout, or your `--output` directory | Remove this separate build directory when no longer used | @@ -30,20 +32,20 @@ rollback procedure. ## Disconnect from Hermes Finish active turns and close other clients sharing the proxy. For a shared bot, -restrict `/sloth` and `/sloth-memory` to administrators through Hermes' command +restrict `/kvpark` to administrators through Hermes' command access controls. This operation changes the active profile's model route and stops its owned services; it is not limited to the current chat. Preview without changing anything: ```text -/sloth uninstall +/kvpark uninstall ``` Apply the preview: ```text -/sloth uninstall confirm +/kvpark uninstall confirm ``` The command drains current inference, saves verified resident state in native @@ -65,8 +67,8 @@ or automatically restart the gateway. Terminal equivalent, in the Python environment that runs Hermes: ```bash -python -m sloth_memory uninstall --hermes -python -m sloth_memory uninstall --hermes --confirm +python -m kvpark uninstall --hermes +python -m kvpark uninstall --hermes --confirm ``` These commands use the active Hermes profile (`HERMES_HOME` when set). They read @@ -85,10 +87,10 @@ After disconnecting, close all Hermes processes using the installation (for a gateway, `hermes gateway stop`). Activate that same Python environment, then run: ```bash -python -m pip uninstall sloth-memory +python -m pip uninstall kvpark ``` -This removes Sloth's installed package, command launcher, and plugin entry point. +This removes kvpark's installed package, command launcher, and plugin entry point. It keeps dependencies that Hermes or other packages may also use. Do not delete Hermes' virtual environment. Restart the gateway if you want Hermes running again. Discord and Telegram menus update when Hermes synchronizes its command catalog; @@ -98,14 +100,15 @@ For a complete disk cleanup, remove these **only after all their services have stopped**: 1. The exact archive directory printed by the preview. On a default Mac setup it - is `~/Library/Application Support/sloth-memory`; `--archive-dir`, - `SLOTH_ARCHIVE_DIR`, or `XDG_DATA_HOME` can change it. This deletes saved KV - snapshots, logs, and update rollback backups. Inspect a custom directory first; + is `~/Library/Application Support/kvpark`; `--archive-dir`, + `KVPARK_ARCHIVE_DIR`, or `XDG_DATA_HOME` can change it. This deletes saved KV + snapshots, logs, and update rollback backups. A migrated installation keeps its + original archive path, which may still be named `sloth-memory`. Inspect a custom directory first; it may contain other files you placed there. 2. The optional `runtime/` build directory, or the custom build output you chose. Removing this isolated source/build tree removes its patched runtime. Do not remove your pre-existing inference server installation. -3. The `sloth-memory` source checkout if you no longer need it. Check for your own +3. The `kvpark` source checkout if you no longer need it. Check for your own changes, downloaded weights, or other files before removing the directory. Use Finder/Trash on macOS or your OS file manager to review these removals. The @@ -114,10 +117,10 @@ Model weights and conversation transcripts are not reconstructed by reinstalling the plugin. The disabled profile entry and original route backup remain for recovery. After -the package is removed, you may delete `plugins.entries.sloth-memory` and the -`sloth-memory` item from `plugins.disabled` in the active profile's `config.yaml`. -Preserve other entries. If you manually added `sloth` to Telegram's command-menu -priority list, remove that one item too. Remove any Sloth-only environment +the package is removed, you may delete `plugins.entries.kvpark` and the +`kvpark` item from `plugins.disabled` in the active profile's `config.yaml`. +Preserve other entries. If you manually added `kvpark` to Telegram's command-menu +priority list, remove that one item too. Remove any kvpark-only environment variables you added to the profile or shell; preserve variables needed by other services. Do not restore an entire old config file over newer unrelated settings. @@ -126,43 +129,44 @@ services. Do not restore an entire old config file over newer unrelated settings Restore your agent's original backend URL and stop other clients first. Then: ```bash -python -m sloth_memory uninstall --archive-dir "/absolute/path/to/archive" -python -m sloth_memory uninstall --archive-dir "/absolute/path/to/archive" --confirm -python -m pip uninstall sloth-memory +python -m kvpark uninstall --archive-dir "/absolute/path/to/archive" +python -m kvpark uninstall --archive-dir "/absolute/path/to/archive" --confirm +python -m pip uninstall kvpark ``` Standalone uninstall has no knowledge of an agent's configuration. It previews and stops only the proxy and managed backend recorded in that archive. If a -supervisor outside Sloth starts them automatically, disable that supervisor first. +supervisor outside kvpark starts them automatically, disable that supervisor first. Services started with unrecognized launch arguments must be stopped through their original terminal or service owner. Remove optional data/builds as described above. -## Manual procedure for 0.2.0a1 +## Manual procedure for sloth-memory 0.2.0a1 1. Finish active turns. If using native snapshots, `/sloth park` can save the current conversation before shutdown. 2. Run `/sloth autostart off`, then `hermes plugins disable sloth-memory` in the terminal. Autostart off alone does not stop an existing process. 3. Use `hermes model` to select your original server URL and served model ID. - Consult your pre-install profile backup if necessary. Do not select Sloth's + Consult your pre-install profile backup if necessary. Do not select sloth-memory's proxy address. Then stop the gateway (`hermes gateway stop`) and close other interactive Hermes clients. -4. Stop the Sloth proxy using its original terminal (Ctrl-C), supervisor, or OS +4. Stop the sloth-memory proxy using its original terminal (Ctrl-C), supervisor, or OS process manager. For a detached process, `proxy.json` inside the archive records its PID. Inspect the running process's command and start time before terminating it; a stale manifest can refer to a reused PID. Its command should be `python -m sloth_memory serve` with your archive path. A managed backend is recorded in `runtime.json`; its command must match the stored `argv` including `--slot-save-path`. Stop only that managed instance. Keep any server you were - already running before installing Sloth. -5. Remove the Python package and optional files using the preceding section. + already running before installing sloth-memory. +5. Run `python -m pip uninstall sloth-memory` in Hermes’ environment. Remove + optional files only after inspecting their actual paths and stopping their services. Restart Hermes and start a new conversation to check the direct backend route. ## Reinstall after disconnecting -Install the desired Sloth version in Hermes' environment, enable it again with -`hermes plugins enable sloth-memory`, then restart Hermes. Run `/sloth setup` with +Install the desired kvpark version in Hermes' environment, enable it again with +`hermes plugins enable kvpark`, then restart Hermes. Run `/kvpark setup` with the backend arguments again (see [backend setup](backends.md)). Explicit setup clears the saved uninstall flag and re-enables automatic startup. A bare -`/sloth setup` only shows instructions. Reuse an archive only when its model and +`/kvpark setup` only shows instructions. Reuse an archive only when its model and runtime are compatible, or select a new archive for the next backend test. diff --git a/docs/updates.md b/docs/updates.md index 86d6a9c..d38a02f 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -1,10 +1,11 @@ # Updates and recovery -Use these commands after installing `0.2.0a1` or newer: +Use these commands after installing **kvpark `0.3.0a1` or newer**. If you still +have sloth-memory installed, first follow the [rename migration](#migrate-from-sloth-memory). ```text -/sloth update check -/sloth update +/kvpark update check +/kvpark update ``` `check` is read-only. It reports the installed package, the adapter loaded in this @@ -40,68 +41,164 @@ native draining restart, as `/restart` does. In an interactive Hermes CLI, or when the gateway restart hook is unavailable, the reply tells you to restart Hermes yourself. Reopen an interactive CLI after updating it. If several agents or profiles share the Python environment, restart their other adapters and -update their proxies separately. `/sloth update check` shows a pending restart +update their proxies separately. `/kvpark update check` shows a pending restart until this adapter has loaded the installed version. From a terminal, with the same environment activated: ```bash -python -m sloth_memory update check -python -m sloth_memory update +python -m kvpark update check +python -m kvpark update ``` Pass `--archive-dir /your/archive` to either command for a custom archive. The -module invocation also works on Windows, where an active `sloth-memory.exe` +module invocation also works on Windows, where an active `kvpark.exe` launcher cannot safely replace itself. Externally managed proxies must be -updated through their service owner. On shared bots, keep `/sloth` and -`/sloth-memory` restricted to administrators using Hermes' slash-command access +updated through their service owner. On shared bots, keep `/kvpark` restricted to administrators using Hermes' slash-command access settings: these commands can install code in the bot's Python environment. -## One-time upgrade from older alphas or development installs +## Migrate from sloth-memory -Old installations do not contain an updater or a proxy drain endpoint. A -package reinstall alone leaves their old proxy process running. To bootstrap: +`kvpark` is the new repository, Python package/module, CLI, and Hermes plugin +name. **The old `/sloth update` cannot cross package names.** Installing kvpark +alongside sloth-memory does not automatically stop the old proxy or transfer its +profile settings. Use this explicit migration once per Hermes profile. -1. Stop Hermes and other clients of this proxy. For a managed Hermes gateway, - run `hermes gateway stop` from a separate terminal; close interactive clients. -2. Activate the Python environment that runs Hermes and install the release: +The migration preserves the original archive directory, snapshot files and keys, +cleanup policy, model settings, and original Hermes route backup. It does not +move data, rebuild a patched runtime, or stop the model backend. Keep the archive +path and runtime build unchanged: they are part of snapshot compatibility. A +migrated directory can retain `sloth-memory` in its name. + +### Hermes migration sequence + +1. Finish active turns. Stop the Hermes gateway and close all interactive Hermes + sessions and other clients sharing the proxy. Leave the backend and old proxy + running so migration can save resident state safely: + + ```bash + hermes gateway stop + ``` + +2. Activate the **same Python environment that runs Hermes** and select the same + Hermes profile (`HERMES_HOME` when set). Install the new package alongside the + old one: ```bash - python -m pip install --upgrade https://github.com/uncrayon/sloth-memory/releases/download/v0.2.0a2/sloth_memory-0.2.0a2-py3-none-any.whl + python -m pip install https://github.com/uncrayon/kvpark/releases/download/v0.3.0a1/kvpark-0.3.0a1-py3-none-any.whl + python -m kvpark --version ``` -3. With all inference clients still stopped, save any resident state and stop - the old proxy. Set `archive` explicitly if you use a custom archive directory. - Use the proxy's `SLOTH_API_KEY` environment setting if authentication is enabled. - - ```python - from sloth_memory.cli import request - from sloth_memory.network import proxy_record - from sloth_memory.runtime import directory - from sloth_memory.updates import stop_proxy - - archive = directory() - record = proxy_record(archive) - if record: - status = request(record["base_url"], "status") - if status["activity"]["phase"] != "idle": - raise RuntimeError("Wait for inference to finish before upgrading") - if status.get("resident_key"): - request(record["base_url"], "park", {"key": status["resident_key"]}) - stop_proxy(record) + The version should be `0.3.0a1`. Keep `sloth-memory` installed until the new + integration has been checked. Do not separately enable kvpark yet. + +3. Preview the profile migration: + + ```bash + python -m kvpark migrate --hermes ``` - Run this Python snippet with the same environment's interpreter. It validates - the recorded process identity before stopping it. Do not kill arbitrary - listeners on port 8080 or stop the model backend. + Check the printed profile, archive directory, and proxy before applying it. + The command reads the archive location from the old plugin entry; no + `--archive-dir` is needed. An externally managed legacy proxy is refused; + its service owner must coordinate replacement. + +4. With clients still stopped, apply the preview: + + ```bash + python -m kvpark migrate --hermes --confirm + ``` + + Migration backs up the profile, drains inference, saves verified resident + foreground state in native mode, and stops only the verified old proxy. It + copies plugin settings and route backups to the `kvpark` entry, enables + kvpark, and disables sloth-memory. Routing mode keeps the existing backend + process and its engine-managed cache. A failure to drain or save aborts the + migration; follow any recovery details printed by the command. + + **This command does not launch or validate the new proxy, or restart Hermes.** + A successful migration means the profile is ready for the next step. + +5. Start Hermes and verify the new integration: + + ```bash + hermes gateway start + ``` + + In Hermes, run: + + ```text + /kvpark status + /kvpark update check + ``` + + Confirm that the expected backend, archive path, saved slots, and new versions + are shown. With autostart enabled, loading Hermes starts the new proxy and + reuses the managed backend. If autostart was deliberately off, it stays off; + use `/kvpark start` to start the service explicitly. In native mode, send a + normal message in the same compatible conversation and check reuse, then use + `/kvpark save`. A rename does not make incompatible snapshots restorable. + +6. Only after those checks pass, stop Hermes processes using this environment + again, remove the old package, and start Hermes: + + ```bash + hermes gateway stop + python -m pip uninstall sloth-memory + hermes gateway start + ``` + + Close interactive clients too. Other profiles sharing this Python environment + must be migrated and checked before removing the old package. Keep the profile + backup until you are satisfied with the new installation. + +New configuration uses `KVPARK_*`. Legacy `SLOTH_*` environment settings are +accepted during migration, including authentication settings; keep required +credentials available to both the migration command and Hermes startup. Prefer +new names when you next edit the profile or service environment. Never copy +credentials into command output, issues, or committed files. + +Use `/kvpark` on Discord and Telegram. Replace any manually configured old +command-menu priority or access-control entries with the new command name, +preserving administrator restrictions. Restarting the gateway republishes its +command catalog; clients may cache the old menu temporarily. + +### Earlier or custom installations + +The automated migration needs an identifiable legacy profile and a proxy with +coordinated drain support (sloth-memory `0.2.0a1` or newer). If it refuses an older +proxy, do not kill a guessed port or PID. Stop clients, save through the old +integration if supported, and stop that proxy through its original terminal or +service owner. Keep a private profile backup and follow the old release's +recovery instructions before retrying. An absent `proxy.json` does not prove +that a very old proxy is stopped. + +For qwen-slot or a custom integration, use the separate +[custom-integration guide](hermes.md#migrate-an-existing-custom-integration). +That integration has a different ownership contract from sloth-memory. + +Standalone users must coordinate their agent's configuration themselves. With +clients stopped and the new package installed, preview and drain an owned legacy +proxy using the original archive path: + +```bash +python -m kvpark migrate --archive-dir /your/existing/archive +python -m kvpark migrate --archive-dir /your/existing/archive --confirm +``` - The oldest alpha.2 proxy did not publish `proxy.json`. Stop that proxy through - the terminal or service that launched it after parking the conversation; an - absent record does not prove that an older proxy is stopped. +Start kvpark with the **same explicit `--archive-dir`**, backend, cache mode, and +upstream URL, then point the agent at the new proxy's selected address. Keep the +model backend running and verify status before removing the old package. If a +supervisor owns the old proxy, coordinate replacement through that owner so it +cannot restart the old process. Standalone migration does not edit agent routes; +`migrate --hermes` additionally migrates the active Hermes profile. -4. Start Hermes again (`hermes gateway start` for a managed gateway). The enabled - plugin starts the new proxy and discovers its selected port. Run - `/sloth update check`; installed, loaded, and proxy versions should agree. +If new startup fails after a successful migration, keep clients stopped and +inspect `hermes-proxy.log` in the unchanged archive. Retain the old package and +migration backup for recovery. Stop any new proxy through its owner before +restoring the saved profile and restarting the old integration; never run both +against the same archive. Do not overwrite newer unrelated profile changes with +an old backup. ## If an update fails @@ -123,9 +220,10 @@ rollback. From the same Python environment, reinstall the previous wheel named in the backup directory, then restart Hermes: ```bash -python -m pip install --no-index --no-deps --force-reinstall /path/to/backup/sloth_memory-PREVIOUS-py3-none-any.whl +python -m pip install --no-index --no-deps --force-reinstall /path/to/backup/kvpark-PREVIOUS-py3-none-any.whl ``` -This alpha does not apply configuration or snapshot-format migrations. A release -requiring them is refused with a pointer to its release notes rather than -silently invalidating saved state. +The release updater does not apply configuration or snapshot-format migrations. +The explicit sloth-memory rename migration above is separate and retains the +snapshot format. A release requiring an unsupported compatibility change is +refused with a pointer to its release notes. diff --git a/docs/validation.md b/docs/validation.md index b537caa..b5a2f4b 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -1,5 +1,10 @@ # Alpha validation +The observations below were recorded under the former **sloth-memory** name. +They describe their stated release and environment; they are not new real-model +acceptance results for the kvpark rename. Current test invocation examples use +the new package and environment-variable names. + ## Coordinated updates — 0.2.0a1 Local release checks on September 6, 2026: @@ -93,13 +98,13 @@ the CPU backend and proxy, native park/delete operate on a real conversation, unloading Hermes leaves cleanup services running, and reloading attaches without duplicate processes. It passed locally with Qwen3-4B and the pinned CPU runtime. -Run the integration tests in Hermes' Python environment with sloth-memory installed: +Run the integration tests in Hermes' Python environment with kvpark installed: ```bash python tests/hermes/test_integration.py -v ``` -For the optional real-model test, set `SLOTH_TEST_SERVER` and `SLOTH_TEST_MODEL` +For the optional real-model test, set `KVPARK_TEST_SERVER` and `KVPARK_TEST_MODEL` to absolute local paths. It uses temporary profiles, ports, and archive files, and terminates only the processes it launches. The Hermes CI job pins upstream `9dd6634c5635321cf38840cc30e9b51226689128` and runs without model downloads. diff --git a/examples/chat.py b/examples/chat.py index c1a45bd..fa922bb 100644 --- a/examples/chat.py +++ b/examples/chat.py @@ -21,8 +21,8 @@ def main(): payload = dict(model="local", messages=messages, max_tokens=256, slot_archive_role="foreground", slot_archive_key=args.session) headers = {"Content-Type": "application/json"} - if os.environ.get("SLOTH_API_KEY"): - headers["Authorization"] = "Bearer " + os.environ["SLOTH_API_KEY"] + if os.environ.get("KVPARK_API_KEY"): + headers["Authorization"] = "Bearer " + os.environ["KVPARK_API_KEY"] with urlopen(Request(args.url.rstrip("/") + "/v1/chat/completions", data=json.dumps(payload).encode(), headers=headers), timeout=1800) as response: message = json.load(response)["choices"][0]["message"] diff --git a/pyproject.toml b/pyproject.toml index 1277783..12008a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,9 +3,9 @@ requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] -name = "sloth-memory" -version = "0.2.0a2" -description = "Let your local AI nap. Resume long conversations from saved inference state." +name = "kvpark" +version = "0.3.0a1" +description = "Park and restore model KV caches for local AI agents." readme = "README.md" requires-python = ">=3.10" dependencies = ["psutil>=5.9", "packaging>=23"] @@ -22,17 +22,17 @@ classifiers = [ ] [project.urls] -Homepage = "https://github.com/uncrayon/sloth-memory" -Issues = "https://github.com/uncrayon/sloth-memory/issues" +Homepage = "https://github.com/uncrayon/kvpark" +Issues = "https://github.com/uncrayon/kvpark/issues" [project.scripts] -sloth-memory = "sloth_memory.cli:main" +kvpark = "kvpark.cli:main" [project.entry-points."hermes_agent.plugins"] -sloth-memory = "sloth_memory.hermes" +kvpark = "kvpark.hermes" [tool.setuptools.packages.find] where = ["src"] [tool.setuptools.package-data] -sloth_memory = ["update_compat.json"] +kvpark = ["update_compat.json"] diff --git a/scripts/acceptance.py b/scripts/acceptance.py index 2e22cad..a68ed5f 100644 --- a/scripts/acceptance.py +++ b/scripts/acceptance.py @@ -29,12 +29,12 @@ def main(): if args.output.exists(): parser.error("output exists; choose a fresh evidence filename") children, logs = [], [] - with tempfile.TemporaryDirectory(prefix="sloth-acceptance-") as tmp: + with tempfile.TemporaryDirectory(prefix="kvpark-acceptance-") as tmp: root = Path(tmp) proxy_port, backend_port = free_port(), free_port() while proxy_port == backend_port: backend_port = free_port() - env = {k: v for k, v in os.environ.items() if not k.startswith(("SLOTH_", "LLAMA_ARG_"))} + env = {k: v for k, v in os.environ.items() if not k.startswith(("KVPARK_", "LLAMA_ARG_"))} env.update(HIP_VISIBLE_DEVICES="", ROCR_VISIBLE_DEVICES="", CUDA_VISIBLE_DEVICES="") def call(port, path, body=None): @@ -46,7 +46,7 @@ def call(port, path, body=None): def spawn(argv, name): log = (root / name).open("w") logs.append(log) - process = subprocess.Popen([sys.executable, "-m", "sloth_memory", *argv], + process = subprocess.Popen([sys.executable, "-m", "kvpark", *argv], stdout=log, stderr=subprocess.STDOUT, env=env) children.append(process) return process @@ -67,7 +67,7 @@ def ready(process, port, endpoint, log): def start(): nonlocal backend_port, proxy_port - from sloth_memory.network import managed_port, proxy_record + from kvpark.network import managed_port, proxy_record backend = spawn(["backend", "--server", str(args.server), "--model", str(args.model), "--archive-dir", str(root / "archive"), "--port", str(backend_port), "--", "--device", "none", "--n-gpu-layers", "0", "--ctx-size", "4096", @@ -79,8 +79,8 @@ def start(): def bound_port(): record = proxy_record(root / "archive") return int(record["base_url"].rsplit(":", 1)[1]) if record else None - proxy_port = ready(proxy, bound_port, "/_sloth/status", "proxy.log") - if not call(proxy_port, "/_sloth/doctor")["ok"]: + proxy_port = ready(proxy, bound_port, "/_kvpark/status", "proxy.log") + if not call(proxy_port, "/_kvpark/doctor")["ok"]: raise RuntimeError("runtime diagnostics failed") def stop(): @@ -104,7 +104,7 @@ def completion(messages): temperature=0, seed=42, reasoning_effort="none")) # HTTP EOF can precede the proxy's final bookkeeping by a few ms. for _ in range(100): - status = call(proxy_port, "/_sloth/status") + status = call(proxy_port, "/_kvpark/status") if status["activity"]["phase"] == "idle": break time.sleep(.01) @@ -123,8 +123,8 @@ def completion(messages): cold = completion(messages) if cold["cached_tokens"] != 0: raise RuntimeError("cold baseline unexpectedly reused tokens") - status = call(proxy_port, "/_sloth/status") - parked = call(proxy_port, "/_sloth/park", {"key": status["resident_key"]}) + status = call(proxy_port, "/_kvpark/status") + parked = call(proxy_port, "/_kvpark/park", {"key": status["resident_key"]}) continued = messages + [cold["message"], dict(role="user", content="What is the project code? Reply with the code only.")] warm = completion(continued) print("Restarting both processes with RAM prompt cache disabled.", flush=True) @@ -132,7 +132,7 @@ def completion(messages): start() replay = completion(messages) restored = completion(continued) - status = call(proxy_port, "/_sloth/status") + status = call(proxy_port, "/_kvpark/status") checks = dict(disk_restore=any(e["action"] == "restored" for e in status["recent"]), replay_reused_majority=(replay["cached_tokens"] or 0) > (replay["processed_tokens"] or 0), continuation_reused_majority=(restored["cached_tokens"] or 0) > (restored["processed_tokens"] or 0), diff --git a/scripts/test_migration_release.py b/scripts/test_migration_release.py new file mode 100644 index 0000000..7cdeb42 --- /dev/null +++ b/scripts/test_migration_release.py @@ -0,0 +1,220 @@ +"""Migrate the actual sloth-memory 0.2.0a2 wheel in an isolated routing stack. + +Usage: python scripts/test_migration_release.py dist [--legacy-wheel PATH] +Without --legacy-wheel, download the fixed release and verify its pinned SHA-256. +The synthetic archive marker tests preservation, not native KV-cache correctness. +""" + +import argparse +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import metadata +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import time +from urllib.error import HTTPError +from urllib.request import Request, urlopen +import uuid +import venv + +import psutil + +LEGACY_NAME = "sloth_memory-0.2.0a2-py3-none-any.whl" +LEGACY_URL = "https://github.com/uncrayon/kvpark/releases/download/v0.2.0a2/" + LEGACY_NAME +LEGACY_SHA256 = "36a8aca441565383821e8b1321885fd025aa73f4c41ea5aad3902bf099fe3541" +MAX_WHEEL_BYTES = 25 * 1024**2 + + +class Backend(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + body = b'{"status":"ok","data":[]}' + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +def get(url, token=None): + headers = {"Authorization": "Bearer " + token} if token else {} + with urlopen(Request(url, headers=headers), timeout=3) as response: + return json.load(response) + + +def legacy_wheel(destination, fixture): + if fixture: + with Path(fixture).open("rb") as source: + data = source.read(MAX_WHEEL_BYTES + 1) + else: + with urlopen(Request(LEGACY_URL, headers={"User-Agent": "kvpark-migration-acceptance"}), timeout=30) as source: + data = source.read(MAX_WHEEL_BYTES + 1) + if len(data) > MAX_WHEEL_BYTES or hashlib.sha256(data).hexdigest() != LEGACY_SHA256: + raise ValueError("Legacy release wheel did not match the pinned checksum") + path = destination / LEGACY_NAME + path.write_bytes(data) + return path + + +def wait_ready(archive, launcher, service, prefix, token, log): + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + if launcher.poll() is not None: + raise RuntimeError(f"{service} exited: {log.read_text(errors='replace')}") + try: + record = json.loads((archive / "proxy.json").read_text()) + process = psutil.Process(record["pid"]) + if process.create_time() != record["created_at"]: + raise ValueError("stale process identity") + status = get(record["base_url"] + prefix + "status", token) + if status["service"] == service: + return record, status + except (OSError, ValueError, KeyError, psutil.Error): + pass + time.sleep(.1) + raise RuntimeError(f"{service} did not become ready: {log.read_text(errors='replace')}") + + +def alive(record): + try: + process = psutil.Process(record["pid"]) + return process.create_time() == record["created_at"] and process.status() != psutil.STATUS_ZOMBIE + except psutil.NoSuchProcess: + return False + + +def cleanup(launchers, records): + # Windows venv launchers can spawn the actual Python process. Stop verified + # published proxy identities and any descendants of our own live launchers. + owned = [] + for record in records: + if alive(record): + owned.append(psutil.Process(record["pid"])) + for launcher in launchers: + if launcher.poll() is None: + try: + process = psutil.Process(launcher.pid) + owned.extend(reversed(process.children(recursive=True))) + owned.append(process) + except psutil.NoSuchProcess: + pass + for process in owned: + try: + process.terminate() + except psutil.NoSuchProcess: + pass + _, remaining = psutil.wait_procs(owned, timeout=10) + for process in remaining: + try: + process.kill() # Only disposable acceptance processes we launched. + except psutil.NoSuchProcess: + pass + psutil.wait_procs(remaining, timeout=10) + for launcher in launchers: + launcher.wait(timeout=10) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("wheel", type=Path) + parser.add_argument("--legacy-wheel", type=Path) + args = parser.parse_args() + wheel = args.wheel.resolve() + if wheel.is_dir(): + wheel, = wheel.glob("kvpark-*-py3-none-any.whl") + with tempfile.TemporaryDirectory(prefix="kvpark-migration-test-") as tmp: + root = Path(tmp) + old = legacy_wheel(root, args.legacy_wheel) + venv.EnvBuilder(with_pip=True).create(root / "venv") + python = root / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-index", "--no-deps", str(old), str(wheel)], + check=True, stdout=subprocess.DEVNULL, timeout=120) + site = Path(subprocess.check_output([str(python), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + text=True, timeout=15).strip()) + dependencies = {str(metadata.distribution(name).locate_file("")) for name in ("psutil", "packaging")} + (site / "test-dependencies.pth").write_text("\n".join(sorted(dependencies)) + "\n") + env = {key: value for key, value in os.environ.items() if not key.startswith(("SLOTH_", "KVPARK_"))} + token = uuid.uuid4().hex + env["SLOTH_API_KEY"] = token + archive = root / "custom archive" + archive.mkdir() + key = "k-" + "a" * 64 + name = key + "." + "b" * 32 + ".bin" + preserved = {name: b"synthetic snapshot preservation marker", name + ".resume": b"synthetic companion"} + stamp = time.time() + preserved[key + ".meta"] = json.dumps(dict(format=2, filename=name, identity="acceptance-marker", + tokens=17, bytes=sum(map(len, preserved.values())), saved_at=stamp, last_used=stamp)).encode() + preserved["retention.json"] = b'{"ttl_days":7,"max_gib":32,"cleanup_enabled":true}' + for name, data in preserved.items(): + (archive / name).write_bytes(data) + backend = ThreadingHTTPServer(("127.0.0.1", 0), Backend) + backend.daemon_threads = True + worker = threading.Thread(target=backend.serve_forever, daemon=True) + worker.start() + upstream = f"http://127.0.0.1:{backend.server_port}" + launchers, records = [], [] + try: + def launch(module): + log = root / (module + ".log") + with log.open("ab") as output: + child = subprocess.Popen([str(python), "-I", "-m", module, "serve", "--archive-dir", str(archive), + "--port", "18081", "--backend", "ollama", "--cache-mode", "routing", "--upstream-url", upstream], + env=env, stdout=output, stderr=output, stdin=subprocess.DEVNULL) + launchers.append(child) + return child, log + + old_child, old_log = launch("sloth_memory") + original, status = wait_ready(archive, old_child, "sloth-memory", "/_sloth/", token, old_log) + records.append(original) + assert status["version"] == "0.2.0a2", status["version"] + assert status["entries"][0]["key"] == key + # Legacy startup normalizes retention JSON formatting. Compare the + # migration against that established on-disk baseline. + preserved["retention.json"] = (archive / "retention.json").read_bytes() + assert json.loads(preserved["retention.json"]) == dict(ttl_days=7, max_gib=32, cleanup_enabled=True) + command = [str(python), "-I", "-m", "kvpark", "migrate", "--archive-dir", str(archive)] + preview = subprocess.check_output(command, env=env, text=True, timeout=30) + assert "Migration preview" in preview, preview + assert alive(original), "Preview stopped the legacy proxy" + assert get(original["base_url"] + "/_sloth/status", token)["service"] == "sloth-memory" + subprocess.run([*command, "--confirm"], env=env, check=True, stdout=subprocess.DEVNULL, timeout=120) + old_child.wait(timeout=10) + assert not alive(original), "Confirmed migration left the legacy proxy alive" + assert get(upstream)["status"] == "ok", "Migration interrupted the existing backend" + for name, data in preserved.items(): + assert (archive / name).read_bytes() == data, f"Migration changed {name}" + child, log = launch("kvpark") + current, status = wait_ready(archive, child, "kvpark", "/_kvpark/", token, log) + records.append(current) + assert status["version"] == wheel.name.split("-")[1] + assert status["entries"][0]["key"] == key and status["entries"][0]["tokens"] == 17 + assert current["upstream_url"] == original["upstream_url"] + assert status["archive_dir"] == str(archive) + assert get(current["base_url"] + "/_kvpark/doctor", token)["ok"] + try: + get(current["base_url"] + "/_kvpark/status") + except HTTPError as exc: + assert exc.code == 401, exc.code + else: + raise AssertionError("Legacy authentication was not preserved") + for name, data in preserved.items(): + assert (archive / name).read_bytes() == data, f"New proxy changed {name}" + assert get(upstream)["status"] == "ok" + print("PASS: actual legacy wheel migration, read-only preview, old proxy stopped, backend and archive retained, legacy auth accepted") + finally: + try: + cleanup(launchers, records) + finally: + backend.shutdown() + backend.server_close() + worker.join(timeout=5) + + +if __name__ == "__main__": + main() diff --git a/scripts/test_update_release.py b/scripts/test_update_release.py index 2c8a4ad..2ae2511 100644 --- a/scripts/test_update_release.py +++ b/scripts/test_update_release.py @@ -1,6 +1,6 @@ """Exercise real pip upgrade/rollback in a disposable venv with a local HTTP backend. -Usage: python scripts/test_update_release.py dist/sloth_memory-0.2.0a1-py3-none-any.whl +Usage: python scripts/test_update_release.py dist/kvpark-0.2.0a1-py3-none-any.whl Requires the build environment to have psutil and packaging installed. No network. """ @@ -29,15 +29,15 @@ def variant(original, destination, version, *, broken=False): rows = [] with zipfile.ZipFile(original) as source, zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as wheel: old = next(n.split("/")[0] for n in source.namelist() if n.endswith(".dist-info/METADATA")) - old_version = old[len("sloth_memory-"):-len(".dist-info")] - new = f"sloth_memory-{version}.dist-info" + old_version = old[len("kvpark-"):-len(".dist-info")] + new = f"kvpark-{version}.dist-info" for name in source.namelist(): if name.endswith("/RECORD"): continue data = source.read(name) - if name.endswith("/METADATA") or name == "sloth_memory/__init__.py": + if name.endswith("/METADATA") or name == "kvpark/__init__.py": data = data.replace(old_version.encode(), version.encode()) - if broken and name == "sloth_memory/__main__.py": + if broken and name == "kvpark/__main__.py": data = b'import sys\nif "serve" in sys.argv: raise SystemExit(42)\n' + data name = name.replace(old, new) wheel.writestr(name, data) @@ -64,16 +64,16 @@ def do_GET(self): def main(): wheel = Path(sys.argv[1]).resolve() if wheel.is_dir(): - wheel, = wheel.glob("sloth_memory-*-py3-none-any.whl") + wheel, = wheel.glob("kvpark-*-py3-none-any.whl") current = wheel.name.split("-")[1] parsed = Version(current) future = f"{parsed.major}.{parsed.minor}.{parsed.micro + 1}a1" - with tempfile.TemporaryDirectory(prefix="sloth-update-test-") as tmp: + with tempfile.TemporaryDirectory(prefix="kvpark-update-test-") as tmp: root = Path(tmp) venv.EnvBuilder(with_pip=True).create(root / "venv") python = root / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python") - baseline = root / "sloth_memory-0.0.0-py3-none-any.whl" - broken = root / f"sloth_memory-{future}-py3-none-any.whl" + baseline = root / "kvpark-0.0.0-py3-none-any.whl" + broken = root / f"kvpark-{future}-py3-none-any.whl" variant(wheel, baseline, "0.0.0") variant(wheel, broken, future, broken=True) subprocess.run([str(python), "-m", "pip", "install", "--no-index", "--no-deps", str(baseline)], check=True, @@ -88,7 +88,7 @@ def main(): process = None try: with (root / "proxy.log").open("ab") as log: - process = subprocess.Popen([str(python), "-I", "-m", "sloth_memory", "serve", "--archive-dir", str(archive), + process = subprocess.Popen([str(python), "-I", "-m", "kvpark", "serve", "--archive-dir", str(archive), "--port", "18081", "--backend", "ollama", "--cache-mode", "routing", "--upstream-url", f"http://127.0.0.1:{backend.server_port}"], stdout=log, stderr=log) for _ in range(100): @@ -102,7 +102,7 @@ def main(): harness.write_text('''import hashlib, json, sys from pathlib import Path from unittest.mock import patch -from sloth_memory import releases, updates +from kvpark import releases, updates wheel, archive, version, expected = sys.argv[1:] wheel = Path(wheel) release = dict(version=version, url="unused", name=wheel.name, sha256=hashlib.sha256(wheel.read_bytes()).hexdigest()) @@ -117,12 +117,12 @@ def main(): ''') for candidate, version, expected in ((wheel, current, "complete"), (broken, future, "rolled_back")): subprocess.run([str(python), "-I", str(harness), str(candidate), str(archive), version, expected], check=True) - actual = subprocess.check_output([str(python), "-I", "-m", "sloth_memory", "--version"], text=True).strip() + actual = subprocess.check_output([str(python), "-I", "-m", "kvpark", "--version"], text=True).strip() assert actual == current, actual record = json.loads((archive / "proxy.json").read_text()) assert record["base_url"] == original["base_url"] assert record["upstream_url"] == original["upstream_url"] - subprocess.run([str(python), "-I", "-m", "sloth_memory", "doctor", "--archive-dir", str(archive)], + subprocess.run([str(python), "-I", "-m", "kvpark", "doctor", "--archive-dir", str(archive)], stdout=subprocess.DEVNULL, check=True) print("PASS: real package upgrade, failed-start rollback, stable proxy route, backend retained") finally: diff --git a/src/kvpark/__init__.py b/src/kvpark/__init__.py new file mode 100644 index 0000000..b93ca99 --- /dev/null +++ b/src/kvpark/__init__.py @@ -0,0 +1,11 @@ +"""Persistent inference state for local open-weight models.""" + +import os + +# Preserve existing profile credentials/settings during the distribution rename. +# Explicit new names always take precedence. +for _name, _value in list(os.environ.items()): + if _name.startswith("SLOTH_"): + os.environ.setdefault("KVPARK_" + _name[6:], _value) + +__version__ = "0.3.0a1" diff --git a/src/sloth_memory/__main__.py b/src/kvpark/__main__.py similarity index 100% rename from src/sloth_memory/__main__.py rename to src/kvpark/__main__.py diff --git a/src/sloth_memory/backends.py b/src/kvpark/backends.py similarity index 100% rename from src/sloth_memory/backends.py rename to src/kvpark/backends.py diff --git a/src/sloth_memory/cli.py b/src/kvpark/cli.py similarity index 76% rename from src/sloth_memory/cli.py rename to src/kvpark/cli.py index 1b5deeb..0f791e0 100644 --- a/src/sloth_memory/cli.py +++ b/src/kvpark/cli.py @@ -12,13 +12,16 @@ from .runtime import directory -def request(url, action, payload=None, *, timeout=900): +def request(url, action, payload=None, *, timeout=900, control_prefix="/_kvpark/"): headers = {"Content-Type": "application/json"} - if os.environ.get("SLOTH_API_KEY"): - headers["Authorization"] = "Bearer " + os.environ["SLOTH_API_KEY"] + key = os.environ.get("KVPARK_API_KEY") + if control_prefix == "/_sloth/": + key = os.environ.get("SLOTH_API_KEY", key) + if key: + headers["Authorization"] = "Bearer " + key data = None if payload is None else json.dumps(payload).encode() try: - with urlopen(Request(url.rstrip("/") + "/_sloth/" + action, data=data, headers=headers), timeout=timeout) as response: + with urlopen(Request(url.rstrip("/") + control_prefix + action, data=data, headers=headers), timeout=timeout) as response: return json.load(response) except HTTPError as exc: try: @@ -29,9 +32,13 @@ def request(url, action, payload=None, *, timeout=900): def main(): - parser = argparse.ArgumentParser(description="Let your local AI nap. Save its work for later.") + parser = argparse.ArgumentParser(description="Park your model's KV cache. Resume where you left off.") parser.add_argument("--version", action="version", version=__version__) sub = parser.add_subparsers(dest="command", required=True) + migrate = sub.add_parser("migrate", help="migrate sloth-memory without moving saved caches") + migrate.add_argument("--hermes", action="store_true", help="migrate the active Hermes profile") + migrate.add_argument("--archive-dir", help="standalone legacy archive directory") + migrate.add_argument("--confirm", action="store_true", help="drain the old proxy and apply migration") uninstall = sub.add_parser("uninstall", help="preview or disconnect services; keep packages and data until explicitly removed") uninstall.add_argument("--confirm", action="store_true", help="apply the uninstall after previewing") uninstall.add_argument("--hermes", action="store_true", help="restore routing and disable the plugin in the active Hermes profile") @@ -55,11 +62,11 @@ def main(): backend.add_argument("--archive-dir") backend.add_argument("--port", type=int, default=8090) backend.add_argument("server_args", nargs=argparse.REMAINDER, help="extra llama-server arguments after --") - for name in ("status", "park", "forget", "doctor", "settings", "cleanup"): - cmd = sub.add_parser(name, help={"status": "show archives and measured reuse", "park": "save the resident conversation", "forget": "delete a saved archive", "doctor": "check runtime, backend, and topology", "settings": "view or update saved cleanup preferences", "cleanup": "delete expired archives now"}[name]) - cmd.add_argument("--url", default=os.environ.get("SLOTH_URL")) + for name in ("status", "save", "forget", "doctor", "settings", "cleanup"): + cmd = sub.add_parser(name, aliases=["park"] if name == "save" else [], help={"status": "show archives and measured reuse", "save": "park the resident conversation", "forget": "delete a saved archive", "doctor": "check runtime, backend, and topology", "settings": "view or update saved cleanup preferences", "cleanup": "delete expired archives now"}[name]) + cmd.add_argument("--url", default=os.environ.get("KVPARK_URL")) cmd.add_argument("--archive-dir", help="discover the running proxy in this archive") - if name in ("park", "forget"): + if name in ("save", "forget"): group = cmd.add_mutually_exclusive_group(required=True) group.add_argument("--session", help="the exact slot_archive_key supplied during inference") group.add_argument("--key", help="the hashed k-… key returned by status") @@ -68,8 +75,13 @@ def main(): cmd.add_argument("--max-gib", type=float) cmd.add_argument("--cleanup", action=argparse.BooleanOptionalAction, default=None) args = parser.parse_args() + if args.command == "park": + args.command = "save" try: - if args.command == "uninstall": + if args.command == "migrate": + from .migration import run + print(run(hermes=args.hermes, archive=args.archive_dir, confirm=args.confirm)) + elif args.command == "uninstall": if args.hermes: if args.archive_dir: parser.error("--hermes uses its profile's archive; do not pass --archive-dir") @@ -104,9 +116,9 @@ def main(): args.cache_mode or ("native" if args.backend == "llama.cpp" else "routing")) overrides = validate({k: v for k, v in dict(ttl_days=args.ttl_days, max_gib=args.max_gib, cleanup_enabled=args.cleanup).items() if v is not None}) - os.environ.update(SLOTH_ARCHIVE_DIR=str(directory(args.archive_dir)), SLOTH_PORT=str(args.port), - SLOTH_UPSTREAM_PORT=str(args.upstream_port), SLOTH_POLICY_OVERRIDES=json.dumps(overrides), - SLOTH_UPSTREAM_URL=target.url, SLOTH_BACKEND=target.name, SLOTH_CACHE_MODE=target.cache_mode) + os.environ.update(KVPARK_ARCHIVE_DIR=str(directory(args.archive_dir)), KVPARK_PORT=str(args.port), + KVPARK_UPSTREAM_PORT=str(args.upstream_port), KVPARK_POLICY_OVERRIDES=json.dumps(overrides), + KVPARK_UPSTREAM_URL=target.url, KVPARK_BACKEND=target.name, KVPARK_CACHE_MODE=target.cache_mode) from .proxy import main as serve_proxy serve_proxy() elif args.command == "backend": @@ -117,7 +129,7 @@ def main(): launch(args.server, args.model, args.archive_dir, args.port, extra) else: payload = None - if args.command in ("park", "forget"): + if args.command in ("save", "forget"): key = args.key or "k-" + hashlib.sha256(args.session.encode()).hexdigest() payload = {"key": key} elif args.command == "cleanup": @@ -133,7 +145,7 @@ def main(): if args.command == "doctor" and not result["ok"]: raise SystemExit(1) except (OSError, ValueError, RuntimeError, URLError) as exc: - print(f"sloth-memory: {exc}", file=sys.stderr) + print(f"kvpark: {exc}", file=sys.stderr) raise SystemExit(1) from None except KeyboardInterrupt: raise SystemExit(130) from None diff --git a/src/sloth_memory/hermes.py b/src/kvpark/hermes.py similarity index 85% rename from src/sloth_memory/hermes.py rename to src/kvpark/hermes.py index fcc9f84..2ea2661 100644 --- a/src/sloth_memory/hermes.py +++ b/src/kvpark/hermes.py @@ -12,7 +12,7 @@ from .cli import request from .hermes_service import Service, defaults, validate_service, target -_command_context = ContextVar("sloth_memory_command_context", default=None) +_command_context = ContextVar("kvpark_command_context", default=None) def session_value(name): @@ -65,7 +65,7 @@ def key(self, session_id): return "k-" + hashlib.sha256((self.namespace + session_id).encode()).hexdigest() def capture_command(self, *, command="", session_key=None, **kwargs): - _command_context.set(session_key if command.replace("_", "-") in {"sloth", "sloth-memory"} else None) + _command_context.set(session_key if command == "kvpark" else None) def middleware(self, *, request, session_id="", base_url="", api_mode="", **kwargs): config = self.settings() @@ -106,11 +106,11 @@ def middleware(self, *, request, session_id="", base_url="", api_mode="", **kwar if thread: extra["slot_archive_thread"] = self.namespace + thread payload["extra_body"] = extra - if os.environ.get("SLOTH_API_KEY"): + if os.environ.get("KVPARK_API_KEY"): headers = dict(payload.get("extra_headers") or {}) - headers["Authorization"] = "Bearer " + os.environ["SLOTH_API_KEY"] + headers["Authorization"] = "Bearer " + os.environ["KVPARK_API_KEY"] payload["extra_headers"] = headers - return {"request": payload, "source": "sloth-memory", "reason": "verified conversation archive identity"} + return {"request": payload, "source": "kvpark", "reason": "verified conversation archive identity"} def call(self, action, payload=None): if self.settings()["autostart"]: @@ -119,7 +119,7 @@ def call(self, action, payload=None): def onboarding(self): config = self.settings() - lines = ["🦥 sloth-memory setup", "Saved disk snapshots expire after 7 days by default; cleanup checks hourly.", + lines = ["🅿️ kvpark setup", "Saved disk snapshots expire after 7 days by default; cleanup checks hourly.", "A 32 GiB budget also limits saved snapshots. Your transcript and live RAM state are kept.", f"Proxy: {config['base_url']}/v1", f"Archive: {config['archive_dir']}", "Starts with Hermes: " + ("on" if config["autostart"] else "off")] @@ -128,15 +128,15 @@ def onboarding(self): lines.append("Disk resume is unavailable for this adapter; backend-managed caches remain independent.") if config["backend"] == "llama.cpp" and not config["external"] and not config["upstream_url"] and not (config["server"] and config["model"]): lines += ["Next: configure your patched llama-server and GGUF:", - '/sloth-memory setup --server "/path/to/llama-server" --model "/path/to/model.gguf"'] + '/kvpark setup --server "/path/to/llama-server" --model "/path/to/model.gguf"'] elif not config["model"] and not config["external"]: - lines.append('Next: /sloth-memory setup --model "the-exact-model-ID-served-by-your-backend"') + lines.append('Next: /kvpark setup --model "the-exact-model-ID-served-by-your-backend"') elif config["connected"]: - lines.append("Configured. New Hermes sessions use this proxy; send a message, then /sloth-memory park to save it." + lines.append("Configured. New Hermes sessions use this proxy; send a message, then /kvpark save to save it." if config["cache_mode"] == "native" else "Configured. New Hermes sessions use this proxy in routing mode.") else: - lines += ["Next: /sloth-memory start, then /sloth-memory connect to select this route for future sessions."] - lines += ["Commands:", " status | park | delete [k-…] | slots", + lines += ["Next: /kvpark start, then /kvpark connect to select this route for future sessions."] + lines += ["Commands:", " save | status | forget [k-…] | slots", " update check | update | uninstall [confirm]", " retention 7 | budget 32 | cleanup on|off|now", " base-url http://127.0.0.1:8080 | autostart on|off", @@ -154,7 +154,7 @@ def configure(self, args): class Parser(argparse.ArgumentParser): def error(self, message): raise ValueError(message) - parser = Parser(prog="/sloth-memory setup", add_help=False) + parser = Parser(prog="/kvpark setup", add_help=False) for key in ("server", "model", "archive-dir", "base-url", "backend-args", "backend", "upstream-url", "cache-mode"): parser.add_argument("--" + key) parser.add_argument("--upstream-port", type=int) @@ -184,7 +184,7 @@ def error(self, message): def current_key(self, explicit=None): if explicit: if not re.fullmatch(r"k-[0-9a-f]{64}", explicit): - raise ValueError("use the exact k-… key from /sloth-memory slots") + raise ValueError("use the exact k-… key from /kvpark slots") return explicit session = session_value("HERMES_SESSION_ID") if session: @@ -199,18 +199,18 @@ def current_key(self, explicit=None): if len(matches) == 1: return matches[0] if not matches: - raise ValueError("this conversation has no saved or resident state in sloth-memory yet. " + raise ValueError("this conversation has no saved or resident state in kvpark yet. " "Send a normal message in this conversation, wait for the reply, then run " - "/sloth-memory park. Restarting the gateway alone does not load its model state.") - raise ValueError("this chat has multiple saved conversations; choose an exact key from /sloth-memory slots") - raise ValueError("Hermes did not provide this command's conversation identity; use an exact key from /sloth-memory slots") + "/kvpark save. Restarting the gateway alone does not load its model state.") + raise ValueError("this chat has multiple saved conversations; choose an exact key from /kvpark slots") + raise ValueError("Hermes did not provide this command's conversation identity; use an exact key from /kvpark slots") def connect(self): self.service.ensure() settings = self.settings() self.write_route(settings) self.ctx.set_config("service", {**settings, "connected": True}) - return "Hermes now defaults to sloth-memory for new sessions. Restart Hermes and start a new conversation; existing sessions keep their saved route." + return "Hermes now defaults to kvpark for new sessions. Restart Hermes and start a new conversation; existing sessions keep their saved route." def write_route(self, settings): # Explicit command selects the default for FUTURE sessions through Hermes' @@ -225,6 +225,7 @@ def write_route(self, settings): def handle(self, raw_args): args = shlex.split(raw_args) action = args[0] if args else "setup" + action = {"park": "save", "delete": "forget"}.get(action, action) rest = args[1:] if action == "uninstall" and rest in ([], ["confirm"]): from .hermes_uninstall import run @@ -233,7 +234,7 @@ def handle(self, raw_args): self.service.closed.set() return result if self.settings()["uninstalled"] and action not in {"setup", "onboarding", "help"}: - raise RuntimeError("Sloth is disconnected. Restart Hermes; see docs/uninstall.md to reinstall.") + raise RuntimeError("kvpark is disconnected. Restart Hermes; see docs/uninstall.md to reinstall.") if action == "update" and rest in ([], ["check"]): from . import updates config = self.settings() @@ -254,7 +255,7 @@ def handle(self, raw_args): if hermes_config.is_managed(): raise PermissionError("updates are managed by your administrator") result = updates.apply(config["archive_dir"], hermes_home=self.home, external=config["external"]) - return f"sloth-memory {result['version']}: {result['note']}" + return f"kvpark {result['version']}: {result['note']}" if action in {"setup", "onboarding", "help"}: return self.configure(rest) if rest and action == "setup" else self.onboarding() if action == "base-url" and len(rest) == 1: @@ -267,7 +268,7 @@ def handle(self, raw_args): return "Start with Hermes: " + rest[0] + ". Already running services are left running." if action == "start" and not rest: self.service.ensure() - return "sloth-memory is running. " + json.dumps(self.call("doctor")) + return "kvpark is running. " + json.dumps(self.call("doctor")) if action == "connect" and not rest: return self.connect() if action in {"retention", "budget"} and len(rest) == 1: @@ -278,12 +279,12 @@ def handle(self, raw_args): if action == "cleanup" and rest in (["on"], ["off"], ["now"]): result = self.call("cleanup", {}) if rest == ["now"] else self.call("settings", {"cleanup_enabled": rest == ["on"]}) return "Cleanup: " + json.dumps(result) + ". Snapshot files only; live RAM and transcripts are unchanged." - if action in {"park", "delete"} and len(rest) <= 1: - result = self.call("park" if action == "park" else "forget", {"key": self.current_key(rest[0] if rest else None)}) - return (f"Parked {result['tokens']:,} tokens. " if action == "park" else "Deleted saved snapshot. ") + result["note"] + if action in {"save", "forget"} and len(rest) <= 1: + result = self.call(action, {"key": self.current_key(rest[0] if rest else None)}) + return (f"Parked {result['tokens']:,} tokens. " if action == "save" else "Deleted saved snapshot. ") + result["note"] if action in {"status", "slots"} and not rest: status = self.call("status") - lines = [f"🦥 {status['archived']} saved slots · {status['total_gib']} / {status['max_gib']} GiB", + lines = [f"🅿️ {status['archived']} saved slots · {status['total_gib']} / {status['max_gib']} GiB", f"Cleanup {'on' if status['cleanup_enabled'] else 'off'} · expires {status['ttl_days']} days after saving · checks hourly", "Model: " + status["activity"]["phase"]] if status.get("runtime_error"): @@ -293,7 +294,7 @@ def handle(self, raw_args): for entry in status["entries"]: lines.append(f"{entry['key']} — {entry['tokens']:,} tokens, {entry['gib']} GiB, {entry['age_days']} days old") return "\n".join(lines) - raise ValueError("Unknown command or arguments. Use /sloth-memory setup for available commands.") + raise ValueError("Unknown command or arguments. Use /kvpark setup for available commands.") async def command(self, raw_args): try: @@ -301,7 +302,7 @@ async def command(self, raw_args): if shlex.split(raw_args) == ["update"]: from importlib.metadata import version from . import __version__ - if version("sloth-memory") != __version__ and self.gateway is not None: + if version("kvpark") != __version__ and self.gateway is not None: from gateway.restart import is_container_restart_context, is_gateway_supervisor_process supervised = is_gateway_supervisor_process() or is_container_restart_context() # Let the command response be sent before Hermes drains and @@ -311,17 +312,16 @@ async def command(self, raw_args): result += " Hermes will restart shortly to load the new adapter." return result except (OSError, ValueError, RuntimeError) as exc: - return "sloth-memory: " + str(exc) + return "kvpark: " + str(exc) finally: _command_context.set(None) def register(ctx): adapter = Adapter(ctx) - for name in ("sloth", "sloth-memory"): - ctx.register_command(name, adapter.command, - description="Set up conversation slots, park, delete, and configure cleanup", - args_hint="setup | status | park | delete | cleanup | retention | base-url | update | uninstall", argument_mode="text") + ctx.register_command("kvpark", adapter.command, + description="Park model state, resume conversations, and manage saved caches", + args_hint="setup | save | status | forget | cleanup | retention | base-url | update | uninstall", argument_mode="text") ctx.register_hook("pre_gateway_dispatch", adapter.capture_gateway) ctx.register_hook("pre_command", adapter.capture_command) ctx.register_middleware("llm_request", adapter.middleware) diff --git a/src/sloth_memory/hermes_service.py b/src/kvpark/hermes_service.py similarity index 94% rename from src/sloth_memory/hermes_service.py rename to src/kvpark/hermes_service.py index 8d9e9a7..d6b4fe4 100644 --- a/src/sloth_memory/hermes_service.py +++ b/src/kvpark/hermes_service.py @@ -1,4 +1,4 @@ -"""Start or attach to local sloth-memory services when Hermes loads its plugin.""" +"""Start or attach to local kvpark services when Hermes loads its plugin.""" import json import os @@ -84,7 +84,7 @@ def start_async(self): with self.lock: if self.closed.is_set() or self.worker and self.worker.is_alive(): return - self.worker = threading.Thread(target=self._start, name="sloth-memory-start", daemon=True) + self.worker = threading.Thread(target=self._start, name="kvpark-start", daemon=True) self.worker.start() def _start(self): @@ -99,7 +99,7 @@ def _existing(self, config): status = request(config["base_url"], "status", timeout=2) except (URLError, RuntimeError, ValueError, TimeoutError): return None - if not isinstance(status, dict) or status.get("service") != "sloth-memory" or status.get("control_version", 0) < 2: + if not isinstance(status, dict) or status.get("service") != "kvpark" or status.get("control_version", 0) < 2: return None if config["external"]: return status @@ -122,7 +122,7 @@ def _remember(self, config): def ensure(self): if self.settings().get("uninstalled", False): - raise RuntimeError("Sloth was uninstalled; follow docs/uninstall.md to reinstall") + raise RuntimeError("kvpark was uninstalled; follow docs/uninstall.md to reinstall") config = validate_service(self.settings()) if self.closed.is_set(): raise RuntimeError("Hermes adapter has been unloaded") @@ -135,7 +135,7 @@ def ensure(self): archive = Path(config["archive_dir"]) with file_lock(archive / ".hermes-start.lock"): if self.closed.is_set() or self.settings().get("uninstalled", False): - raise RuntimeError("Sloth startup was disabled while waiting for the archive") + raise RuntimeError("kvpark startup was disabled while waiting for the archive") # The process that won startup publishes the actual bound address. # Read it again under the interprocess lock, including after a reboot. record = proxy_record(archive) @@ -163,7 +163,7 @@ def ensure(self): raise RuntimeError("the archive's proxy is running but unavailable; inspect hermes-proxy.log") managed = config["backend"] == "llama.cpp" and not config["upstream_url"] if managed and (not config["server"] or not config["model"]): - raise ValueError("Run /sloth-memory setup --server /path/to/llama-server --model /path/to/model.gguf") + raise ValueError("Run /kvpark setup --server /path/to/llama-server --model /path/to/model.gguf") if not managed and not config["model"]: raise ValueError("Set --model to the model name served by your backend") if managed: @@ -231,15 +231,15 @@ def _spawn(argv, log): if log.exists() and log.stat().st_size > 1024**2: log.replace(log.with_suffix(".previous.log")) with log.open("ab") as output: - process = subprocess.Popen([sys.executable, "-m", "sloth_memory", *argv], stdin=subprocess.DEVNULL, + process = subprocess.Popen([sys.executable, "-m", "kvpark", *argv], stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, **detached_options()) - threading.Thread(target=process.wait, name="sloth-memory-reaper", daemon=True).start() + threading.Thread(target=process.wait, name="kvpark-reaper", daemon=True).start() return process @staticmethod def _probe(backend): headers = {} - key_file = os.environ.get("SLOTH_UPSTREAM_KEY_FILE") + key_file = os.environ.get("KVPARK_UPSTREAM_KEY_FILE") if key_file: headers["Authorization"] = "Bearer " + Path(key_file).read_text().strip() with urlopen(Request(backend.url + backend.health_path, headers=headers), timeout=5) as response: diff --git a/src/sloth_memory/hermes_uninstall.py b/src/kvpark/hermes_uninstall.py similarity index 89% rename from src/sloth_memory/hermes_uninstall.py rename to src/kvpark/hermes_uninstall.py index 6fe6d8d..257f6fe 100644 --- a/src/sloth_memory/hermes_uninstall.py +++ b/src/kvpark/hermes_uninstall.py @@ -11,7 +11,7 @@ def editable(): from hermes_cli import config, managed_scope paths = ["model." + field for field in FIELDS] - paths += ["plugins.enabled", "plugins.disabled", "plugins.entries.sloth-memory"] + paths += ["plugins.enabled", "plugins.disabled", "plugins.entries.kvpark"] managed = managed_scope.managed_config_keys() overlaps = any(key == path or key.startswith(path + ".") or path.startswith(key + ".") for key in managed for path in paths) @@ -25,7 +25,7 @@ def save_route(settings, model): editable() with _locked_plugin_state(config.get_config_path()), config._CONFIG_LOCK: raw = config.read_user_config_raw() - entry = raw.get("plugins", {}).get("entries", {}).get("sloth-memory", {}) + entry = raw.get("plugins", {}).get("entries", {}).get("kvpark", {}) backup = entry.get("settings", {}).get("route_backup") applied = entry.get("settings", {}).get("route_applied", {}) current = raw.get("model", {}) @@ -36,12 +36,12 @@ def save_route(settings, model): current_url = current.get("base_url", "").rstrip("/") # A refused preferred port can belong to the user's original backend. # Only an applied route (or an already-connected legacy install) proves - # that an address in previous_urls actually belonged to Sloth. + # that an address in previous_urls actually belonged to kvpark. owned_route = (bool(applied) and current_url == applied.get("base_url", "").rstrip("/")) legacy_route = not applied and settings["connected"] and current_url in urls if not owned_route and not legacy_route: backup = {field: copy.deepcopy(current[field]) for field in FIELDS if field in current} - saved = raw.setdefault("plugins", {}).setdefault("entries", {}).setdefault("sloth-memory", {}).setdefault("settings", {}) + saved = raw.setdefault("plugins", {}).setdefault("entries", {}).setdefault("kvpark", {}).setdefault("settings", {}) saved.update(route_backup=backup, route_applied=model) raw.setdefault("model", {}).update(model) config.save_config(raw) @@ -50,14 +50,14 @@ def save_route(settings, model): def restored_config(raw): result = copy.deepcopy(raw) plugins = result.setdefault("plugins", {}) - entry = plugins.setdefault("entries", {}).setdefault("sloth-memory", {}) + entry = plugins.setdefault("entries", {}).setdefault("kvpark", {}) settings = entry.setdefault("settings", {}) service = {**defaults(), **settings.get("service", entry.get("config", {}).get("service", {}))} model = result.get("model", {}) # Hermes also accepts the legacy shorthand model: "provider/model". route_model = {"default": model} if isinstance(model, str) else model applied = settings.get("route_applied", {}) - # Historical preferred ports may belong to upstream servers, not Sloth. + # Historical preferred ports may belong to upstream servers, not kvpark. urls = {applied["base_url"].rstrip("/")} if applied.get("base_url") else {service["base_url"].rstrip("/") + "/v1"} restore = route_model.get("base_url", "").rstrip("/") in urls if restore: @@ -74,8 +74,8 @@ def restored_config(raw): model[field] = copy.deepcopy(backup[field]) service.update(autostart=False, connected=False, uninstalled=True) settings["service"] = service - plugins["enabled"] = [name for name in plugins.get("enabled", []) if name != "sloth-memory"] - plugins["disabled"] = list(dict.fromkeys([*plugins.get("disabled", []), "sloth-memory"])) + plugins["enabled"] = [name for name in plugins.get("enabled", []) if name != "kvpark"] + plugins["disabled"] = list(dict.fromkeys([*plugins.get("disabled", []), "kvpark"])) return result, service, restore @@ -92,13 +92,13 @@ def run(*, confirm=False): "Disable the plugin and its automatic startup."] for field in ("proxy", "backend"): if processes[field]: - lines.append(f"Stop Sloth's {field} (PID {processes[field]['pid']}).") + lines.append(f"Stop kvpark's {field} (PID {processes[field]['pid']}).") if settings["external"]: lines.append("The externally managed proxy remains running.") lines += ["Keep saved snapshots, model weights, runtime builds, and transcripts.", "Archive: " + settings["archive_dir"]] if not confirm: - return "Uninstall preview (no changes made):\n" + "\n".join(lines) + "\nFinish other turns first, then run /sloth uninstall confirm." + return "Uninstall preview (no changes made):\n" + "\n".join(lines) + "\nFinish other turns first, then run /kvpark uninstall confirm." def disconnect(): # Re-read under the same locks as Hermes' native plugin config writer. @@ -111,9 +111,9 @@ def disconnect(): config.save_config(restored) removal.stop(settings["archive_dir"], disconnect=disconnect, **options) - return ("Sloth disconnected; owned services stopped and automatic startup disabled. " + return ("kvpark disconnected; owned services stopped and automatic startup disabled. " "Restart Hermes and start a new conversation to use your restored route. " "Existing conversations can retain the old proxy URL.\n" "Snapshots and runtime builds are kept. Archive: " + settings["archive_dir"] + "\n" "After closing every Hermes process using this Python environment, remove the package in a terminal:\n" - "python -m pip uninstall sloth-memory\nUse the same Python environment that runs Hermes.") + "python -m pip uninstall kvpark\nUse the same Python environment that runs Hermes.") diff --git a/src/kvpark/migration.py b/src/kvpark/migration.py new file mode 100644 index 0000000..53c2e35 --- /dev/null +++ b/src/kvpark/migration.py @@ -0,0 +1,137 @@ +"""Explicit one-time migration from the sloth-memory distribution.""" + +from contextlib import ExitStack +import copy +import json +import os +from pathlib import Path +import sys +import uuid + +from .cli import request +from .platforms import data_directory, lock_file, process_matches +from .removal import owned_process +from .updates import stop_proxy + +LEGACY = "sloth-memory" + + +def profile_plan(raw): + result = copy.deepcopy(raw) + plugins = result.setdefault("plugins", {}) + entries = plugins.setdefault("entries", {}) + if "kvpark" in entries: + if entries["kvpark"].get("settings", {}).get("migrated_from") == LEGACY: + return None + raise ValueError("This profile already has kvpark settings; refusing to overwrite them.") + if LEGACY not in entries: + raise ValueError("No sloth-memory settings in this Hermes profile; use /kvpark setup for a fresh install.") + entry = copy.deepcopy(entries[LEGACY]) + # Hermes falls back from settings to config per top-level setting. Mixed + # profiles can keep service in config and newer route backups in settings. + settings = {**copy.deepcopy(entry.get("config", {})), **entry.get("settings", {})} + entry["settings"] = settings + service = settings.setdefault("service", {}) + if service.get("external"): + raise ValueError("The legacy proxy is externally managed; migrate it through its service owner first.") + # Keep the absolute old directory: it participates in the native runtime's + # identity. Moving it would invalidate existing KV snapshots. + service["archive_dir"] = str(Path(service.get("archive_dir") or os.environ.get("KVPARK_ARCHIVE_DIR") + or data_directory() / LEGACY).expanduser().resolve()) + settings["migrated_from"] = LEGACY + entries["kvpark"] = entry + old_settings = {**copy.deepcopy(entries[LEGACY].get("config", {})), **entries[LEGACY].get("settings", {})} + entries[LEGACY]["settings"] = old_settings + old_settings.setdefault("service", {}).update(autostart=False, connected=False, uninstalled=True) + plugins["enabled"] = list(dict.fromkeys([name for name in plugins.get("enabled", []) if name != LEGACY] + ["kvpark"])) + plugins["disabled"] = list(dict.fromkeys([name for name in plugins.get("disabled", []) if name != "kvpark"] + [LEGACY])) + # A manually prioritized Telegram command should follow the rename too. + menu = result.get("platforms", {}).get("telegram", {}).get("extra", {}).get("command_menu", {}) + if isinstance(menu.get("priority"), list): + menu["priority"] = list(dict.fromkeys("kvpark" if name in {"sloth", LEGACY, "sloth_memory"} else name + for name in menu["priority"])) + return result + + +def editable(): + from hermes_cli import config, managed_scope + paths = ("plugins.enabled", "plugins.disabled", "plugins.entries.sloth-memory", "plugins.entries.kvpark", + "platforms.telegram.extra.command_menu.priority") + if config.is_managed() or any(key == path or key.startswith(path + ".") or path.startswith(key + ".") + for key in managed_scope.managed_config_keys() for path in paths): + raise PermissionError("Plugin migration is managed by your administrator.") + + +def run(*, hermes=False, archive=None, confirm=False): + raw = planned = None + if hermes: + if archive: + raise ValueError("--hermes reads the active profile's archive; omit --archive-dir") + from hermes_cli import config + from hermes_cli.plugins import _locked_plugin_state + editable() + # Terminal migration must see the same profile credentials as the + # stopped gateway. Import only this integration's environment settings. + for name, value in config.load_env().items(): + if name.startswith(("SLOTH_", "KVPARK_")): + os.environ.setdefault(name, value) + for name, value in list(os.environ.items()): + if name.startswith("SLOTH_"): + os.environ.setdefault("KVPARK_" + name[6:], value) + raw = config.read_user_config_raw() + planned = profile_plan(raw) + if planned is None: + return "This Hermes profile was already migrated. Restart Hermes and check /kvpark status." + archive = planned["plugins"]["entries"]["kvpark"]["settings"]["service"]["archive_dir"] + archive = Path(archive or os.environ.get("KVPARK_ARCHIVE_DIR") or data_directory() / LEGACY).expanduser().resolve() + record = owned_process(archive, "proxy.json", legacy=True) + preview = ((f"Hermes profile: {config.get_config_path()}\n" if hermes else "") + + f"Keep archive: {archive}\nKeep the backend process, runtime, weights, and saved snapshots.\n" + + (f"Drain and stop legacy proxy PID {record['pid']}.\n" if record else "Legacy proxy is already stopped.\n") + + ("Copy the active Hermes profile's settings; disable sloth-memory and enable kvpark.\n" if hermes else "Agent routes/configuration must be migrated separately.\n")) + if not confirm: + return "Migration preview (no changes made):\n" + preview + "Stop Hermes and other clients, then repeat with --confirm." + with ExitStack() as locks: + for path in (Path(sys.prefix) / ".kvpark-update.lock", Path(sys.prefix) / ".sloth-memory-update.lock", + archive / ".hermes-start.lock"): + fd = lock_file(path) + locks.callback(os.close, fd) + current = owned_process(archive, "proxy.json", legacy=True) + if current != record: + raise RuntimeError("Legacy proxy changed during migration; preview and retry.") + prepared = False + backup = None + written = None + try: + if record: + state = request(record["base_url"], "status", timeout=5, control_prefix="/_sloth/") + if (state.get("service") != LEGACY or state.get("control_version", 0) < 4 + or Path(state.get("archive_dir", "")).resolve() != archive): + raise RuntimeError("Legacy proxy cannot be drained; follow the manual migration guide.") + request(record["base_url"], "prepare-update", {}, timeout=90, control_prefix="/_sloth/") + prepared = True + if hermes: + with _locked_plugin_state(config.get_config_path()), config._CONFIG_LOCK: + editable() + if config.read_user_config_raw() != raw: + raise RuntimeError("Hermes configuration changed during migration; retry.") + backup = config.get_config_path().with_name("config.before-kvpark-" + uuid.uuid4().hex + ".json") + fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as out: + json.dump(raw, out, indent=2) + config.save_config(planned) + written = config.read_user_config_raw() + if record: + stop_proxy(record) + except BaseException: + # A failed stop or config save keeps the old installation usable. + if hermes and backup: + with _locked_plugin_state(config.get_config_path()), config._CONFIG_LOCK: + if written is not None and config.read_user_config_raw() == written: + config.save_config(raw) + if prepared and record and process_matches(record): + request(record["base_url"], "cancel-update", {}, timeout=5, control_prefix="/_sloth/") + raise + return ("Migration prepared. " + preview + (f"Private profile backup: {backup}\n" if backup else "") + + ("Start Hermes, then check /kvpark status. Keep the old package until the new proxy works." + if hermes else "Start kvpark serve with this same --archive-dir and your previous backend settings.")) diff --git a/src/sloth_memory/network.py b/src/kvpark/network.py similarity index 100% rename from src/sloth_memory/network.py rename to src/kvpark/network.py diff --git a/src/sloth_memory/platforms.py b/src/kvpark/platforms.py similarity index 100% rename from src/sloth_memory/platforms.py rename to src/kvpark/platforms.py diff --git a/src/sloth_memory/proxy.py b/src/kvpark/proxy.py similarity index 95% rename from src/sloth_memory/proxy.py rename to src/kvpark/proxy.py index 347ef2b..8b65203 100755 --- a/src/sloth_memory/proxy.py +++ b/src/kvpark/proxy.py @@ -23,31 +23,31 @@ from .runtime import directory from . import __version__ -LISTEN_HOST = os.environ.get("SLOTH_HOST", "127.0.0.1") -LISTEN_PORT = int(os.environ.get("SLOTH_PORT", "8080")) -UPSTREAM_HOST = os.environ.get("SLOTH_UPSTREAM_HOST", "127.0.0.1") -UPSTREAM_PORT = int(os.environ.get("SLOTH_UPSTREAM_PORT", "8090")) +LISTEN_HOST = os.environ.get("KVPARK_HOST", "127.0.0.1") +LISTEN_PORT = int(os.environ.get("KVPARK_PORT", "8080")) +UPSTREAM_HOST = os.environ.get("KVPARK_UPSTREAM_HOST", "127.0.0.1") +UPSTREAM_PORT = int(os.environ.get("KVPARK_UPSTREAM_PORT", "8090")) ARCHIVE = directory() -RUNTIME = Path(os.environ.get("SLOTH_RUNTIME", str(ARCHIVE / "runtime.json"))) -MIN_ARCHIVE_TOKENS = int(os.environ.get("SLOTH_MIN_TOKENS", "8192")) -RESAVE_GROWTH_TOKENS = int(os.environ.get("SLOTH_RESAVE_GROWTH", "4096")) -AUTO_SAVE = os.environ.get("SLOTH_AUTO_SAVE", "0") == "1" -TTL_DAYS = float(os.environ.get("SLOTH_TTL_DAYS", "7")) -MAX_ARCHIVE_GB = float(os.environ.get("SLOTH_MAX_GB", "32")) +RUNTIME = Path(os.environ.get("KVPARK_RUNTIME", str(ARCHIVE / "runtime.json"))) +MIN_ARCHIVE_TOKENS = int(os.environ.get("KVPARK_MIN_TOKENS", "8192")) +RESAVE_GROWTH_TOKENS = int(os.environ.get("KVPARK_RESAVE_GROWTH", "4096")) +AUTO_SAVE = os.environ.get("KVPARK_AUTO_SAVE", "0") == "1" +TTL_DAYS = float(os.environ.get("KVPARK_TTL_DAYS", "7")) +MAX_ARCHIVE_GB = float(os.environ.get("KVPARK_MAX_GB", "32")) CHAT_PATHS = {"/v1/chat/completions", "/chat/completions"} GENERATION_PATHS = CHAT_PATHS -CONTROL_PREFIX = "/_sloth/" +CONTROL_PREFIX = "/_kvpark/" HOP_BY_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "trailers", "transfer-encoding", "upgrade"} log = logging.getLogger("slot-proxy") -API_KEY = os.environ.get("SLOTH_API_KEY") +API_KEY = os.environ.get("KVPARK_API_KEY") MAX_REQUEST_BYTES = 64 * 1024**2 def backend(): - name = os.environ.get("SLOTH_BACKEND", "llama.cpp") - return Backend(name, os.environ.get("SLOTH_UPSTREAM_URL", f"http://{UPSTREAM_HOST}:{UPSTREAM_PORT}"), - os.environ.get("SLOTH_CACHE_MODE", "native" if name == "llama.cpp" else "routing")) + name = os.environ.get("KVPARK_BACKEND", "llama.cpp") + return Backend(name, os.environ.get("KVPARK_UPSTREAM_URL", f"http://{UPSTREAM_HOST}:{UPSTREAM_PORT}"), + os.environ.get("KVPARK_CACHE_MODE", "native" if name == "llama.cpp" else "routing")) class UnsafeRestoreError(RuntimeError): @@ -115,7 +115,7 @@ def __init__(self): self.current_prompt = None self.activity = {"phase": "idle", "key": None} self.runtime_error = None - self.maintenance_until = time.monotonic() + 300 if os.environ.get("SLOTH_UPDATE_START") == "1" else 0 + self.maintenance_until = time.monotonic() + 300 if os.environ.get("KVPARK_UPDATE_START") == "1" else 0 self.displaced = {} self._snapshot = {} self.entries = {} @@ -123,7 +123,7 @@ def __init__(self): from .retention import Retention self.retention = Retention(ARCHIVE / "retention.json", lambda: dict( ttl_days=TTL_DAYS, max_gib=MAX_ARCHIVE_GB, cleanup_enabled=True)) - overrides = os.environ.get("SLOTH_POLICY_OVERRIDES") + overrides = os.environ.get("KVPARK_POLICY_OVERRIDES") if overrides: self.retention.update(json.loads(overrides)) self.gc_wakeup = threading.Event() @@ -178,7 +178,7 @@ def request(self, method, path, body=None, timeout=600): try: payload = json.dumps(body).encode() if body is not None else None headers = {"Content-Type": "application/json", "Connection": "close"} - key_file = os.environ.get("SLOTH_UPSTREAM_KEY_FILE") + key_file = os.environ.get("KVPARK_UPSTREAM_KEY_FILE") if key_file: headers["Authorization"] = "Bearer " + Path(key_file).read_text().strip() conn.request(method, path, payload, headers) @@ -358,7 +358,7 @@ def status(self): upstream=backend().url.split("://", 1)[1], archive_dir=str(ARCHIVE), archived=len(entries), entries=entries, total_gib=round(sum(v["bytes"] for v in snapshot["entries"].values()) / 1024**3, 3), - service="sloth-memory", version=__version__, control_version=4, upstream_url=backend().url, + service="kvpark", version=__version__, control_version=4, upstream_url=backend().url, maintenance=self.maintenance_until > time.monotonic(), capabilities=backend().capabilities(), ttl_days=snapshot["retention"]["ttl_days"], max_gib=snapshot["retention"]["max_gib"], @@ -529,7 +529,7 @@ def control(self, method, path, body): try: if (method != "GET" and ARCHIVE_STATE.maintenance_until > time.monotonic() and path not in {CONTROL_PREFIX + "cancel-update", CONTROL_PREFIX + "prepare-update"}): - raise RuntimeError("sloth-memory is updating; retry shortly") + raise RuntimeError("kvpark is updating; retry shortly") if method == "GET" and path == CONTROL_PREFIX + "status": payload = ARCHIVE_STATE.status() elif method == "GET" and path == CONTROL_PREFIX + "doctor": @@ -551,7 +551,7 @@ def control(self, method, path, body): if not isinstance(req, dict): raise ValueError("control body must be a JSON object") payload = ARCHIVE_STATE.forget(req.get("key")) - elif method == "POST" and path in {CONTROL_PREFIX + "park", CONTROL_PREFIX + "simulate-gap"}: + elif method == "POST" and path in {CONTROL_PREFIX + "save", CONTROL_PREFIX + "park", CONTROL_PREFIX + "simulate-gap"}: if not backend().snapshots: raise ValueError(backend().capabilities()["note"]) req = json.loads(body or b"{}") @@ -633,7 +633,7 @@ def relay(self, method): started_at = time.monotonic() with lock: if generation and ARCHIVE_STATE.maintenance_until > time.monotonic(): - self.send_error(503, "sloth-memory is updating; retry shortly") + self.send_error(503, "kvpark is updating; retry shortly") return archive_ready = backend().snapshots if generation and archive_ready: @@ -669,7 +669,7 @@ def forward(self, method, body, started_at): headers["Content-Length"] = str(len(body)) headers["Connection"] = "close" # Proxy authentication and backend authentication are separate credentials. - key_file = os.environ.get("SLOTH_UPSTREAM_KEY_FILE") + key_file = os.environ.get("KVPARK_UPSTREAM_KEY_FILE") if key_file: headers["Authorization"] = "Bearer " + Path(key_file).read_text().strip() started = False @@ -728,7 +728,7 @@ def gc_loop(): def main(): - logging.basicConfig(level=os.environ.get("SLOTH_LOG", "INFO"), + logging.basicConfig(level=os.environ.get("KVPARK_LOG", "INFO"), format="%(asctime)s %(levelname)s %(message)s") if LISTEN_HOST != "127.0.0.1": raise SystemExit("the proxy listens on localhost only") @@ -749,7 +749,7 @@ def main(): atomic_json(ARCHIVE / "proxy.json", dict(**process_identity(os.getpid()), archive_dir=str(ARCHIVE), python_prefix=str(Path(sys.prefix).resolve()), - launch_token=os.environ.get("SLOTH_LAUNCH_TOKEN"), + launch_token=os.environ.get("KVPARK_LAUNCH_TOKEN"), base_url=f"http://{LISTEN_HOST}:{server.server_port}", upstream_url=backend().url, backend=backend().name, cache_mode=backend().cache_mode)) log.info("Proxy listening at http://%s:%s → %s (%s)", LISTEN_HOST, server.server_port, backend().url, backend().cache_mode) diff --git a/src/sloth_memory/releases.py b/src/kvpark/releases.py similarity index 85% rename from src/sloth_memory/releases.py rename to src/kvpark/releases.py index c1dea95..0247716 100644 --- a/src/sloth_memory/releases.py +++ b/src/kvpark/releases.py @@ -13,13 +13,13 @@ from packaging.specifiers import SpecifierSet from packaging.version import InvalidVersion, Version -REPOSITORY = "https://github.com/uncrayon/sloth-memory" -RELEASES_API = "https://api.github.com/repos/uncrayon/sloth-memory/releases?per_page=100" +REPOSITORY = "https://github.com/uncrayon/kvpark" +RELEASES_API = "https://api.github.com/repos/uncrayon/kvpark/releases?per_page=100" MAX_DOWNLOAD = 25 * 1024**2 def fetch(url, limit=MAX_DOWNLOAD): - req = Request(url, headers={"User-Agent": "sloth-memory-updater", "Accept": "application/vnd.github+json"}) + req = Request(url, headers={"User-Agent": "kvpark-updater", "Accept": "application/vnd.github+json"}) with urlopen(req, timeout=30) as response: data = response.read(limit + 1) if len(data) > limit: @@ -39,7 +39,7 @@ def latest(installed): continue if version.is_prerelease and not Version(installed).is_prerelease: continue - name = f"sloth_memory-{version}-py3-none-any.whl" + name = f"kvpark-{version}-py3-none-any.whl" for asset in release.get("assets", []): url = f"{REPOSITORY}/releases/download/{tag}/{name}" digest = asset.get("digest") or "" @@ -66,10 +66,10 @@ def download(release, destination): def validate_wheel(path, version): from email.parser import BytesParser with zipfile.ZipFile(path) as wheel: - info = BytesParser().parsebytes(wheel.read(f"sloth_memory-{version}.dist-info/METADATA")) - if info["Name"] != "sloth-memory" or Version(info["Version"]) != Version(version): + info = BytesParser().parsebytes(wheel.read(f"kvpark-{version}.dist-info/METADATA")) + if info["Name"] != "kvpark" or Version(info["Version"]) != Version(version): raise ValueError("release package identity mismatch") - compatibility = json.loads(wheel.read("sloth_memory/update_compat.json")) + compatibility = json.loads(wheel.read("kvpark/update_compat.json")) if compatibility != {"updater_protocol": 1, "snapshot_format": 2, "control_version": 4}: raise ValueError("this release requires a manual compatibility upgrade; see its release notes") current_python = ".".join(map(str, sys.version_info[:3])) diff --git a/src/sloth_memory/removal.py b/src/kvpark/removal.py similarity index 84% rename from src/sloth_memory/removal.py rename to src/kvpark/removal.py index 64c0bd8..62e2d4a 100644 --- a/src/sloth_memory/removal.py +++ b/src/kvpark/removal.py @@ -11,7 +11,7 @@ from .updates import stop_proxy -def owned_process(archive, filename): +def owned_process(archive, filename, *, legacy=False): path = archive / filename if not path.exists(): return None @@ -25,9 +25,10 @@ def owned_process(archive, filename): except psutil.Error as exc: raise RuntimeError("Cannot inspect the recorded service; stop it through its service owner.") from exc if filename == "proxy.json": - valid = (argv[1:4] == ["-m", "sloth_memory", "serve"] - or argv[1:5] == ["-I", "-m", "sloth_memory", "serve"] - or len(argv) > 2 and Path(argv[1]).name in {"sloth-memory", "sloth-memory.exe"} and argv[2] == "serve") + module, command = ("sloth_memory", "sloth-memory") if legacy else ("kvpark", "kvpark") + valid = (argv[1:4] == ["-m", module, "serve"] + or argv[1:5] == ["-I", "-m", module, "serve"] + or len(argv) > 2 and Path(argv[1]).name in {command, command + ".exe"} and argv[2] == "serve") flag = "--archive-dir" else: valid = argv == record.get("argv") @@ -60,7 +61,7 @@ def stop(archive, *, external=False, managed_backend=True, disconnect=None): record = result["proxy"] if record: status = request(record["base_url"], "status", timeout=5) - if (status.get("service") != "sloth-memory" or status.get("control_version", 0) < 4 + if (status.get("service") != "kvpark" or status.get("control_version", 0) < 4 or Path(status.get("archive_dir", "")).resolve() != archive): raise RuntimeError("Proxy cannot drain safely; stop clients and follow the manual uninstall guide.") request(record["base_url"], "prepare-update", {}, timeout=90) @@ -79,7 +80,7 @@ def stop(archive, *, external=False, managed_backend=True, disconnect=None): except psutil.NoSuchProcess: pass except (psutil.Error, RuntimeError) as exc: - raise RuntimeError(f"Could not stop Sloth's {field}; inspect its process before retrying: {exc}") from exc + raise RuntimeError(f"Could not stop kvpark's {field}; inspect its process before retrying: {exc}") from exc return result except BaseException: if prepared and record and process_matches(record): diff --git a/src/sloth_memory/retention.py b/src/kvpark/retention.py similarity index 100% rename from src/sloth_memory/retention.py rename to src/kvpark/retention.py diff --git a/src/sloth_memory/runtime.py b/src/kvpark/runtime.py similarity index 96% rename from src/sloth_memory/runtime.py rename to src/kvpark/runtime.py index 58af98a..980beab 100644 --- a/src/sloth_memory/runtime.py +++ b/src/kvpark/runtime.py @@ -17,7 +17,7 @@ def directory(value=None): root = data_directory() - return Path(value or os.environ.get("SLOTH_ARCHIVE_DIR", root / "sloth-memory")).expanduser().resolve() + return Path(value or os.environ.get("KVPARK_ARCHIVE_DIR", root / "kvpark")).expanduser().resolve() def lock_directory(path, name): @@ -83,7 +83,7 @@ def backend_command(server, model, archive, port, extra): "--alias", "-a", "--mmproj-url", "--lora", "--lora-scaled"} for arg in extra: if arg.split("=", 1)[0] in reserved: - raise ValueError(f"{arg} is managed by sloth-memory or unsupported in this alpha") + raise ValueError(f"{arg} is managed by kvpark or unsupported in this alpha") implicit = sorted(k for k in os.environ if k.startswith("LLAMA_ARG_")) if implicit: raise ValueError("unset LLAMA_ARG_* variables and pass backend settings explicitly: " + ", ".join(implicit)) diff --git a/src/sloth_memory/update_compat.json b/src/kvpark/update_compat.json similarity index 100% rename from src/sloth_memory/update_compat.json rename to src/kvpark/update_compat.json diff --git a/src/sloth_memory/updates.py b/src/kvpark/updates.py similarity index 92% rename from src/sloth_memory/updates.py rename to src/kvpark/updates.py index b053c23..511ba3c 100644 --- a/src/sloth_memory/updates.py +++ b/src/kvpark/updates.py @@ -1,4 +1,4 @@ -"""Replace only sloth-memory, retaining a local wheel for rollback and the model process.""" +"""Replace only kvpark, retaining a local wheel for rollback and the model process.""" import base64 import csv @@ -54,7 +54,7 @@ def write_json(path, value): def check(archive, *, url=None): - installed = metadata.version("sloth-memory") + installed = metadata.version("kvpark") record = proxy_record(Path(archive)) address = url or (record["base_url"] if record else None) try: @@ -81,17 +81,17 @@ def check(archive, *, url=None): def rollback_wheel(destination): """Repackage the installed distribution, including local patches, before pip replaces it.""" - dist = metadata.distribution("sloth-memory") + dist = metadata.distribution("kvpark") direct = json.loads(dist.read_text("direct_url.json") or "{}") if direct.get("dir_info", {}).get("editable"): raise ValueError("editable installations must be updated from their source checkout") - name = f"sloth_memory-{dist.version}" + name = f"kvpark-{dist.version}" path = destination / f"{name}-py3-none-any.whl" rows = [] with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as wheel: for file in dist.files or []: relative = file.as_posix() - if not relative.startswith(("sloth_memory/", name + ".dist-info/")): + if not relative.startswith(("kvpark/", name + ".dist-info/")): continue if "__pycache__" in relative or file.name in {"RECORD", "direct_url.json", "INSTALLER", "REQUESTED"}: continue @@ -99,7 +99,7 @@ def rollback_wheel(destination): wheel.writestr(relative, data) digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() rows.append((relative, "sha256=" + digest, str(len(data)))) - if not any(row[0] == "sloth_memory/__init__.py" for row in rows): + if not any(row[0] == "kvpark/__init__.py" for row in rows): raise ValueError("cannot back up this installation; use its original package manager") record = name + ".dist-info/RECORD" output = io.StringIO(newline="") @@ -136,11 +136,11 @@ def stop_proxy(record): def start_proxy(record, archive, env, version): launch_token = uuid.uuid4().hex - argv = [sys.executable, "-I", "-m", "sloth_memory", "serve", "--archive-dir", str(archive), + argv = [sys.executable, "-I", "-m", "kvpark", "serve", "--archive-dir", str(archive), "--port", record["base_url"].rsplit(":", 1)[1], "--backend", record["backend"], "--cache-mode", record["cache_mode"], "--upstream-url", record["upstream_url"]] with (archive / "hermes-proxy.log").open("ab") as log: - child = subprocess.Popen(argv, env={**env, "SLOTH_UPDATE_START": "1", "SLOTH_LAUNCH_TOKEN": launch_token}, stdin=subprocess.DEVNULL, stdout=log, + child = subprocess.Popen(argv, env={**env, "KVPARK_UPDATE_START": "1", "KVPARK_LAUNCH_TOKEN": launch_token}, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, **detached_options()) try: for _ in range(100): @@ -182,13 +182,13 @@ def start_proxy(record, archive, env, version): def apply(archive, *, hermes_home=None, external=False): if external: raise ValueError("this proxy is externally managed; update it through its service owner") - if os.name == "nt" and sys.argv[0].lower().endswith("sloth-memory.exe"): - raise ValueError("on Windows use python -m sloth_memory update so the console launcher can be replaced") + if os.name == "nt" and sys.argv[0].lower().endswith("kvpark.exe"): + raise ValueError("on Windows use python -m kvpark update so the console launcher can be replaced") archive = Path(archive) archive.mkdir(parents=True, exist_ok=True, mode=0o700) # One package environment can serve several profiles. Refuse concurrent # installs even when those profiles use different archive directories. - fd = lock_file(Path(sys.prefix) / ".sloth-memory-update.lock") + fd = lock_file(Path(sys.prefix) / ".kvpark-update.lock") try: return _apply(archive, hermes_home) finally: @@ -196,7 +196,7 @@ def apply(archive, *, hermes_home=None, external=False): def _apply(archive, hermes_home): - installed = metadata.version("sloth-memory") + installed = metadata.version("kvpark") release = releases.latest(installed) newer = release and Version(release["version"]) > Version(installed) existing = proxy_record(archive) @@ -226,7 +226,7 @@ def _apply(archive, hermes_home): raise RuntimeError("the running proxy predates coordinated updates; follow the one-time upgrade in docs/updates.md") process = psutil.Process(record["pid"]) argv = process.cmdline() - if not process_matches(record) or argv[1:4] != ["-m", "sloth_memory", "serve"] and argv[1:5] != ["-I", "-m", "sloth_memory", "serve"]: + if not process_matches(record) or argv[1:4] != ["-m", "kvpark", "serve"] and argv[1:5] != ["-I", "-m", "kvpark", "serve"]: raise RuntimeError("proxy ownership could not be verified") if not same_python_environment(argv[0], record.get("python_prefix")): raise RuntimeError("proxy uses a different Python environment; update it separately") @@ -240,7 +240,7 @@ def _apply(archive, hermes_home): if wheel: changed = True # A failed pip call can already have uninstalled files. install(wheel, stage / "install.log") - version = subprocess.check_output([sys.executable, "-I", "-m", "sloth_memory", "--version"], + version = subprocess.check_output([sys.executable, "-I", "-m", "kvpark", "--version"], text=True, timeout=15).strip() if version != target_version: raise RuntimeError("installed package failed its version check") diff --git a/src/sloth_memory/windows_job.py b/src/kvpark/windows_job.py similarity index 100% rename from src/sloth_memory/windows_job.py rename to src/kvpark/windows_job.py diff --git a/src/sloth_memory/__init__.py b/src/sloth_memory/__init__.py deleted file mode 100644 index 174cf50..0000000 --- a/src/sloth_memory/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Persistent inference state for local open-weight models.""" - -__version__ = "0.2.0a2" diff --git a/tests/hermes/test_integration.py b/tests/hermes/test_integration.py index bc13790..af50f7a 100644 --- a/tests/hermes/test_integration.py +++ b/tests/hermes/test_integration.py @@ -13,7 +13,7 @@ import unittest from unittest.mock import patch -from sloth_memory import proxy +from kvpark import proxy class HermesIntegrationTests(unittest.TestCase): @@ -37,20 +37,20 @@ def setUp(self): self.addCleanup(self.server.server_close) self.addCleanup(self.server.shutdown) self.url = f"http://127.0.0.1:{self.server.server_port}" - (self.home / "config.yaml").write_text(json.dumps({"plugins": {"enabled": ["sloth-memory"], - "entries": {"sloth-memory": {"settings": {"service": {"autostart": False, "external": True, "base_url": self.url}}}}}, + (self.home / "config.yaml").write_text(json.dumps({"plugins": {"enabled": ["kvpark"], + "entries": {"kvpark": {"settings": {"service": {"autostart": False, "external": True, "base_url": self.url}}}}}, "agent": {"max_turns": 12}, "model": {"provider": "custom", "default": "old", "base_url": self.url + "/v1"}})) from hermes_cli.plugins import get_plugin_manager, get_plugin_command_handler self.manager = get_plugin_manager() self.manager.discover_and_load() self.addCleanup(self.manager.unload) - self.command = get_plugin_command_handler("sloth-memory") + self.command = get_plugin_command_handler("kvpark") self.assertIsNotNone(self.command, "installed entry point did not register the slash command") def command_text(self, text): return asyncio.run(self.command(text)) - async def gateway_command(self, text, thread="discord:acceptance", *, platform="discord", command="sloth-memory"): + async def gateway_command(self, text, thread="discord:acceptance", *, platform="discord", command="kvpark"): from unittest.mock import AsyncMock from gateway.run_inbound import GatewayInboundMixin from gateway.session import SessionSource @@ -83,8 +83,8 @@ def test_telegram_short_command_preserves_chat_identity(self): self.archive.current_thread = adapter.namespace + "telegram:acceptance" self.archive.publish_status() with patch.object(self.archive, "park", return_value={"tokens": 456, "note": "Saved."}) as park: - result = asyncio.run(self.gateway_command("park", "telegram:acceptance", - platform="telegram", command="sloth")) + result = asyncio.run(self.gateway_command("save", "telegram:acceptance", + platform="telegram", command="kvpark")) self.assertIn("Parked 456 tokens", result) self.assertEqual(park.call_args.kwargs["key"], adapter.key("telegram-session")) @@ -92,47 +92,47 @@ def test_telegram_menu_priority_keeps_short_command_visible(self): from hermes_cli.config import save_config from hermes_cli.commands_platforms import telegram_menu_commands save_config({"platforms": {"telegram": {"extra": {"command_menu": { - "priority": ["sloth"], "priority_mode": "prepend"}}}}}, merge_existing=True) + "priority": ["kvpark"], "priority_mode": "prepend"}}}}}, merge_existing=True) menu, _ = telegram_menu_commands(max_commands=5) - self.assertIn("sloth", [name for name, _ in menu]) - self.assertEqual(sum(name == "sloth" for name, _ in menu), 1) + self.assertIn("kvpark", [name for name, _ in menu]) + self.assertEqual(sum(name == "kvpark" for name, _ in menu), 1) def test_update_check_dispatches_without_installing_or_restarting(self): - from sloth_memory import updates + from kvpark import updates result = dict(installed="0.2.0a1", loaded="0.2.0a1", proxy="0.2.0a1", latest="0.2.0a2", available=True) with patch.object(updates, "check", return_value=result), patch.object(updates, "apply") as install: - text = asyncio.run(self.gateway_command("update check", platform="telegram", command="sloth")) + text = asyncio.run(self.gateway_command("update check", platform="telegram", command="kvpark")) self.assertIn("Available: 0.2.0a2", text) install.assert_not_called() def test_uninstall_restores_route_disables_plugin_and_does_not_restart_it(self): from hermes_cli.config import read_user_config_raw, save_config adapter = self.command.__self__ - # The original server occupied Sloth's preferred port, forcing fallback. + # The original server occupied kvpark's preferred port, forcing fallback. original = dict(provider="custom", default="gemma", base_url="http://127.0.0.1:8080/v1", context_length=12345) adapter.ctx.set_config("service", {**adapter.settings(), "previous_urls": ["http://127.0.0.1:8080"]}) save_config({"model": original}, merge_existing=True) self.command_text("connect") self.command_text("connect") # Reconnect must not overwrite the original route. before = read_user_config_raw() - preview = asyncio.run(self.gateway_command("uninstall", command="sloth", platform="telegram")) + preview = asyncio.run(self.gateway_command("uninstall", command="kvpark", platform="telegram")) self.assertIn("no changes", preview) self.assertEqual(before, read_user_config_raw()) - result = asyncio.run(self.gateway_command("uninstall confirm", command="sloth", platform="telegram")) - self.assertIn("Sloth disconnected", result) + result = asyncio.run(self.gateway_command("uninstall confirm", command="kvpark", platform="telegram")) + self.assertIn("kvpark disconnected", result) current = read_user_config_raw() self.assertEqual(current["model"], original) self.assertEqual(current["agent"]["max_turns"], 12) - self.assertIn("sloth-memory", current["plugins"]["disabled"]) - self.assertNotIn("sloth-memory", current["plugins"]["enabled"]) + self.assertIn("kvpark", current["plugins"]["disabled"]) + self.assertNotIn("kvpark", current["plugins"]["enabled"]) self.assertTrue(adapter.service.closed.is_set()) self.assertIsNone(adapter.middleware(request={}, base_url=self.url + "/v1", api_mode="chat_completions")) - self.assertIn("Sloth is disconnected", self.command_text("status")) - self.assertIn("Sloth disconnected", self.command_text("uninstall confirm")) + self.assertIn("kvpark is disconnected", self.command_text("status")) + self.assertIn("kvpark disconnected", self.command_text("uninstall confirm")) self.manager.unload() self.manager.discover_and_load(force=True) from hermes_cli.plugins import get_plugin_command_handler - self.assertIsNone(get_plugin_command_handler("sloth")) + self.assertIsNone(get_plugin_command_handler("kvpark")) def test_uninstall_without_route_backup_does_not_change_profile(self): from hermes_cli.config import read_user_config_raw @@ -141,11 +141,58 @@ def test_uninstall_without_route_backup_does_not_change_profile(self): self.assertIn("no original model-route backup", result) self.assertEqual(before, read_user_config_raw()) + def test_legacy_profile_migration_keeps_model_route_and_archive(self): + from hermes_cli.config import read_user_config_raw, save_config + from kvpark.migration import run + raw = read_user_config_raw() + old = raw["plugins"]["entries"].pop("kvpark") + old["settings"]["service"].update(external=False, archive_dir=str(self.home / "legacy-archive")) + old["settings"]["route_backup"] = {"provider": "custom", "base_url": "http://127.0.0.1:9999/v1"} + raw["plugins"]["entries"]["sloth-memory"] = old + raw["plugins"]["enabled"] = ["sloth-memory"] + save_config(raw) + before = read_user_config_raw() + self.assertIn("no changes", run(hermes=True)) + self.assertEqual(read_user_config_raw(), before) + self.assertIn("Migration prepared", run(hermes=True, confirm=True)) + after = read_user_config_raw() + self.assertEqual(after["model"], before["model"]) + settings = after["plugins"]["entries"]["kvpark"]["settings"] + self.assertEqual(settings["service"]["archive_dir"], str(self.home / "legacy-archive")) + self.assertEqual(settings["route_backup"], old["settings"]["route_backup"]) + self.assertIn("already migrated", run(hermes=True, confirm=True)) + backup, = self.home.glob("config.before-kvpark-*.json") + self.assertEqual(json.loads(backup.read_text()), before) + if os.name != "nt": + self.assertEqual(backup.stat().st_mode & 0o777, 0o600) + + def test_failed_legacy_proxy_stop_restores_profile_and_reopens_gate(self): + from hermes_cli.config import read_user_config_raw, save_config + from kvpark import migration + raw = read_user_config_raw() + old = raw["plugins"]["entries"].pop("kvpark") + archive = str(self.home / "legacy-archive") + old["settings"]["service"].update(external=False, archive_dir=archive) + raw["plugins"]["entries"]["sloth-memory"] = old + raw["plugins"]["enabled"] = ["sloth-memory"] + save_config(raw) + before = read_user_config_raw() + record = dict(pid=123, base_url=self.url) + status = dict(service="sloth-memory", control_version=4, archive_dir=archive) + with patch.object(migration, "owned_process", return_value=record), \ + patch.object(migration, "request", side_effect=[status, {"ok": True}, {"ok": True}]) as request, \ + patch.object(migration, "stop_proxy", side_effect=RuntimeError("stop failed")), \ + patch.object(migration, "process_matches", return_value=True): + with self.assertRaisesRegex(RuntimeError, "stop failed"): + migration.run(hermes=True, confirm=True) + self.assertEqual(request.call_args.args[1], "cancel-update") + self.assertEqual(read_user_config_raw(), before) + def test_uninstall_respects_managed_plugin_leaf_settings(self): from hermes_cli.config import read_user_config_raw before = read_user_config_raw() - for key in ("plugins.entries.sloth-memory.settings.service.autostart", - "plugins.entries.sloth-memory.settings.route_backup.base_url"): + for key in ("plugins.entries.kvpark.settings.service.autostart", + "plugins.entries.kvpark.settings.route_backup.base_url"): with patch("hermes_cli.managed_scope.managed_config_keys", return_value={key}): result = self.command_text("uninstall confirm") self.assertIn("managed by your administrator", result) @@ -154,13 +201,13 @@ def test_uninstall_respects_managed_plugin_leaf_settings(self): def test_successful_update_requests_native_gateway_restart_after_reply(self): from unittest.mock import Mock from hermes_cli.lifecycle import invoke_hook - from sloth_memory import updates + from kvpark import updates gateway = Mock() invoke_hook("pre_gateway_dispatch", gateway=gateway) async def command(): loop = asyncio.get_running_loop() with patch.object(loop, "call_later", wraps=loop.call_later) as later: - result = await self.gateway_command("update", command="sloth") + result = await self.gateway_command("update", command="kvpark") self.assertIn("restart shortly", result) gateway.request_restart.assert_not_called() callback = next(call.args[1] for call in later.call_args_list if call.args[0] == 2) @@ -168,14 +215,14 @@ async def command(): gateway.request_restart.assert_called_once_with(detached=False, via_service=True) with patch.object(updates, "apply", return_value=dict(version="0.2.0a2", note="Updated.")), \ patch("importlib.metadata.version", return_value="0.2.0a2"), \ - patch("sloth_memory.__version__", "0.2.0a1"), \ + patch("kvpark.__version__", "0.2.0a1"), \ patch("gateway.restart.is_gateway_supervisor_process", return_value=True): asyncio.run(command()) def test_failed_update_never_requests_gateway_restart(self): from unittest.mock import Mock from hermes_cli.lifecycle import invoke_hook - from sloth_memory import updates + from kvpark import updates gateway = Mock() invoke_hook("pre_gateway_dispatch", gateway=gateway) with patch.object(updates, "apply", side_effect=RuntimeError("rolled_back")): @@ -185,7 +232,7 @@ def test_failed_update_never_requests_gateway_restart(self): def test_discord_park_before_first_turn_explains_how_to_load_state(self): with patch.object(self.archive, "park") as park: - result = asyncio.run(self.gateway_command("park")) + result = asyncio.run(self.gateway_command("save")) self.assertIn("Send a normal message", result) park.assert_not_called() @@ -196,7 +243,7 @@ def test_discord_park_uses_hook_thread_without_a_bound_session_id(self): self.archive.publish_status() with patch.dict(os.environ, {"HERMES_SESSION_ID": "unrelated-process-session"}): with patch.object(self.archive, "park", return_value={"tokens": 123, "note": "Saved."}) as park: - result = asyncio.run(self.gateway_command("park")) + result = asyncio.run(self.gateway_command("save")) self.assertIn("Parked 123 tokens", result) self.assertEqual(park.call_args.kwargs["key"], adapter.key("discord-session")) @@ -206,7 +253,7 @@ def test_discord_park_never_selects_another_threads_resident_state(self): self.archive.current_thread = adapter.namespace + "discord:someone-else" self.archive.publish_status() with patch.object(self.archive, "park") as park: - result = asyncio.run(self.gateway_command("park")) + result = asyncio.run(self.gateway_command("save")) self.assertIn("Send a normal message", result) park.assert_not_called() @@ -264,7 +311,7 @@ def test_delete_command_removes_exact_snapshot_without_model_turn(self): def test_autostart_setting_persists_and_discovery_invokes_startup(self): self.command_text("autostart off") - from sloth_memory.hermes_service import Service + from kvpark.hermes_service import Service with patch.object(Service, "start_async") as start: self.command_text("autostart on") start.assert_called_once() @@ -313,18 +360,18 @@ def test_changing_backend_clears_previous_model_and_endpoint(self): self.assertEqual(adapter.settings()["upstream_url"], "") -@unittest.skipUnless(os.environ.get("SLOTH_TEST_SERVER") and os.environ.get("SLOTH_TEST_MODEL"), "optional real-model startup test") +@unittest.skipUnless(os.environ.get("KVPARK_TEST_SERVER") and os.environ.get("KVPARK_TEST_MODEL"), "optional real-model startup test") class RealStartupTests(unittest.TestCase): def test_hermes_discovery_launches_services_and_native_park_delete_work(self): - from sloth_memory.hermes_service import Service - from sloth_memory.cli import request + from kvpark.hermes_service import Service + from kvpark.cli import request from hermes_cli.plugins import get_plugin_manager, get_plugin_command_handler from hermes_cli.middleware import apply_llm_request_middleware from agent.subagent_lifecycle import bind_subagent_parent from gateway.session_context import set_session_vars, clear_session_vars from openai import OpenAI - with tempfile.TemporaryDirectory(prefix="sloth-hermes-real-") as tmp: + with tempfile.TemporaryDirectory(prefix="kvpark-hermes-real-") as tmp: home = Path(tmp) occupied = [] for _ in range(2): @@ -336,12 +383,12 @@ def test_hermes_discovery_launches_services_and_native_park_delete_work(self): port, upstream = (sock.getsockname()[1] for sock in occupied) url = f"http://127.0.0.1:{port}" config = dict(autostart=True, base_url=url, upstream_port=upstream, archive_dir=str(home / "archive"), - server=os.environ["SLOTH_TEST_SERVER"], model=os.environ["SLOTH_TEST_MODEL"], + server=os.environ["KVPARK_TEST_SERVER"], model=os.environ["KVPARK_TEST_MODEL"], backend_args=["--device", "none", "--n-gpu-layers", "0", "--ctx-size", "2048", "--threads", "4", "--threads-batch", "4", "--cache-ram", "0", "--ctx-checkpoints", "8", "--checkpoint-min-step", "128", "--jinja"]) - (home / "config.yaml").write_text(json.dumps({"plugins": {"enabled": ["sloth-memory"], - "entries": {"sloth-memory": {"settings": {"service": config}}}}})) + (home / "config.yaml").write_text(json.dumps({"plugins": {"enabled": ["kvpark"], + "entries": {"kvpark": {"settings": {"service": config}}}}})) children = [] spawn = Service._spawn def tracked_spawn(*args): @@ -352,12 +399,12 @@ def tracked_spawn(*args): manager = get_plugin_manager() try: manager.discover_and_load() - command = get_plugin_command_handler("sloth-memory") + command = get_plugin_command_handler("kvpark") # No explicit start command: discovery itself must launch. deadline = time.monotonic() + 120 while time.monotonic() < deadline: try: - from sloth_memory.network import proxy_record + from kvpark.network import proxy_record record = proxy_record(home / "archive") if record: url = record["base_url"] @@ -385,7 +432,7 @@ def tracked_spawn(*args): with OpenAI(base_url=url + "/v1", api_key="local", timeout=120) as client: response = client.chat.completions.create(**payload) self.assertTrue(response.choices[0].message.content) - self.assertIn("Parked", asyncio.run(command("park"))) + self.assertIn("Parked", asyncio.run(command("save"))) self.assertEqual(request(url, "status")["archived"], 1) self.assertIn("Deleted saved snapshot", asyncio.run(command("delete"))) self.assertEqual(request(url, "status")["archived"], 0) @@ -394,7 +441,7 @@ def tracked_spawn(*args): manager.unload() self.assertTrue(all(child.poll() is None for child in children), "cleanup services must survive closing Hermes") manager.discover_and_load(force=True) - get_plugin_command_handler("sloth-memory").__self__.service.worker.join(10) + get_plugin_command_handler("kvpark").__self__.service.worker.join(10) self.assertEqual(len(children), 2, "reload started duplicate services") finally: manager.unload() diff --git a/tests/test_archive.py b/tests/test_archive.py index 9cde9cc..717b16b 100644 --- a/tests/test_archive.py +++ b/tests/test_archive.py @@ -11,7 +11,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import http.client -from sloth_memory import proxy as p +from kvpark import proxy as p class ArchiveTests(unittest.TestCase): @@ -334,7 +334,7 @@ def connect(test_id): self.assertIn(b"first", resp.read1(8192)) status_conn = http.client.HTTPConnection("127.0.0.1", proxy.server_port, timeout=1) self.addCleanup(status_conn.close) - status_conn.request("GET", "/_sloth/status") + status_conn.request("GET", "/_kvpark/status") status_resp = status_conn.getresponse() self.assertEqual(status_resp.status, 200) self.assertEqual(json.loads(status_resp.read())["activity"]["phase"], "generating") @@ -388,7 +388,7 @@ def test_manifest_detects_replaced_model_files_and_pid_reuse(self): model = Path(tmp) / "model.gguf" model.write_bytes(b"weights") st = model.stat() - from sloth_memory.platforms import process_identity + from kvpark.platforms import process_identity data = dict(**process_identity(os.getpid()), run_id="new", identity="id", files={str(model): [st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns]}) manifest = Path(tmp) / "runtime.json" diff --git a/tests/test_backends.py b/tests/test_backends.py index 3e08ba1..ef3c1b7 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -13,10 +13,10 @@ import time import unittest -from sloth_memory.backends import Backend -from sloth_memory.cli import request -from sloth_memory.hermes_service import Service, defaults -from sloth_memory.network import proxy_record +from kvpark.backends import Backend +from kvpark.cli import request +from kvpark.hermes_service import Service, defaults +from kvpark.network import proxy_record class Upstream(BaseHTTPRequestHandler): @@ -75,10 +75,10 @@ def stop(self): def start(self, backend): archive = self.root / backend - env = {key: value for key, value in os.environ.items() if not key.startswith("SLOTH_")} + env = {key: value for key, value in os.environ.items() if not key.startswith("KVPARK_")} log = self.root / (backend + ".log") with log.open("wb") as output: - process = subprocess.Popen([sys.executable, "-m", "sloth_memory", "serve", "--backend", backend, + process = subprocess.Popen([sys.executable, "-m", "kvpark", "serve", "--backend", backend, "--cache-mode", "routing", "--upstream-url", self.upstream_url, "--port", str(self.preferred), "--archive-dir", str(archive)], env=env, stdout=output, stderr=subprocess.STDOUT) self.children.append(process) @@ -91,7 +91,7 @@ def start(self, backend): self.fail("proxy did not publish its bound address: " + log.read_text(errors="replace")) def test_uninstall_stops_each_proxy_and_keeps_existing_backend_available(self): - from sloth_memory import removal + from kvpark import removal from urllib.request import urlopen for name in ("llama.cpp", "ollama", "vllm", "mlx"): with self.subTest(backend=name): @@ -137,7 +137,7 @@ def test_four_backends_forward_models_streaming_tools_and_report_capabilities(se self.assertEqual(headers["Authorization"], "Bearer backend-key") self.assertEqual(headers["Host"], self.upstream_url.removeprefix("http://")) conn.close() - result = subprocess.run([sys.executable, "-m", "sloth_memory", "status", "--archive-dir", str(archive)], capture_output=True, text=True) + result = subprocess.run([sys.executable, "-m", "kvpark", "status", "--archive-dir", str(archive)], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["capabilities"]["backend"], name) diff --git a/tests/test_cli_runtime.py b/tests/test_cli_runtime.py index 3234bba..652982e 100644 --- a/tests/test_cli_runtime.py +++ b/tests/test_cli_runtime.py @@ -7,8 +7,8 @@ import unittest from unittest.mock import patch -from sloth_memory import runtime -from sloth_memory import proxy +from kvpark import runtime +from kvpark import proxy class LauncherTests(unittest.TestCase): @@ -54,7 +54,7 @@ def test_directory_has_exclusive_process_lock(self): os.close(fd) def test_cli_requires_explicit_identity(self): - result = subprocess.run([sys.executable, "-m", "sloth_memory", "park"], capture_output=True, text=True) + result = subprocess.run([sys.executable, "-m", "kvpark", "park"], capture_output=True, text=True) self.assertEqual(result.returncode, 2) self.assertIn("--session", result.stderr) @@ -111,7 +111,7 @@ def setUp(self): self.addCleanup(self.server.server_close) self.addCleanup(self.server.shutdown) - def call(self, method="GET", path="/_sloth/status", body=None, headers=None): + def call(self, method="GET", path="/_kvpark/status", body=None, headers=None): import http.client conn = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2) try: @@ -124,7 +124,7 @@ def call(self, method="GET", path="/_sloth/status", body=None, headers=None): def test_auth_protects_status_and_mutations(self): with patch.object(proxy, "API_KEY", "test-secret"): self.assertEqual(self.call()[0], 401) - self.assertEqual(self.call("POST", "/_sloth/park", b"{}")[0], 401) + self.assertEqual(self.call("POST", "/_kvpark/park", b"{}")[0], 401) self.assertEqual(self.call(headers={"Authorization": "Bearer test-secret"})[0], 200) def test_browser_origins_cannot_control_local_service(self): diff --git a/tests/test_hermes_service.py b/tests/test_hermes_service.py index 396162c..6c3361d 100644 --- a/tests/test_hermes_service.py +++ b/tests/test_hermes_service.py @@ -5,14 +5,14 @@ from unittest.mock import patch from urllib.error import URLError -from sloth_memory.hermes_service import Service, defaults, validate_service +from kvpark.hermes_service import Service, defaults, validate_service class ServiceTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) - location = patch("sloth_memory.hermes_service.directory", side_effect=lambda value=None: Path(value or self.tmp.name)) + location = patch("kvpark.hermes_service.directory", side_effect=lambda value=None: Path(value or self.tmp.name)) location.start() self.addCleanup(location.stop) @@ -24,35 +24,35 @@ def test_base_url_normalization_and_local_only_boundary(self): def test_existing_service_is_attached_without_spawning(self): config = defaults() - state = {"service": "sloth-memory", "control_version": 2, "archive_dir": config["archive_dir"], "upstream": "127.0.0.1:8090"} + state = {"service": "kvpark", "control_version": 2, "archive_dir": config["archive_dir"], "upstream": "127.0.0.1:8090"} service = Service(lambda: config) - with patch("sloth_memory.hermes_service.request", return_value=state), patch.object(service, "_health", return_value=True), patch.object(service, "_spawn") as spawn: + with patch("kvpark.hermes_service.request", return_value=state), patch.object(service, "_health", return_value=True), patch.object(service, "_spawn") as spawn: self.assertEqual(service.ensure(), state) spawn.assert_not_called() def test_successful_retry_clears_previous_startup_error(self): config = defaults() service = Service(lambda: config) - with patch("sloth_memory.hermes_service.request", side_effect=URLError("offline")): + with patch("kvpark.hermes_service.request", side_effect=URLError("offline")): service._start() - self.assertIn("/sloth-memory setup", service.error) - state = {"service": "sloth-memory", "control_version": 2, + self.assertIn("/kvpark setup", service.error) + state = {"service": "kvpark", "control_version": 2, "archive_dir": config["archive_dir"], "upstream": "127.0.0.1:8090"} - with patch("sloth_memory.hermes_service.request", return_value=state): + with patch("kvpark.hermes_service.request", return_value=state): self.assertEqual(service.ensure(), state) self.assertIsNone(service.error) def test_unrelated_service_is_never_taken_over(self): service = Service(defaults) - with patch("sloth_memory.hermes_service.request", return_value={"service": "other"}), patch.object(service, "_spawn") as spawn: - with self.assertRaisesRegex(ValueError, "/sloth-memory setup"): + with patch("kvpark.hermes_service.request", return_value={"service": "other"}), patch.object(service, "_spawn") as spawn: + with self.assertRaisesRegex(ValueError, "/kvpark setup"): service.ensure() spawn.assert_not_called() def test_missing_configuration_guides_onboarding_without_spawning(self): service = Service(defaults) - with patch("sloth_memory.hermes_service.request", side_effect=URLError("offline")), patch.object(service, "_spawn") as spawn: - with self.assertRaisesRegex(ValueError, "/sloth-memory setup"): + with patch("kvpark.hermes_service.request", side_effect=URLError("offline")), patch.object(service, "_spawn") as spawn: + with self.assertRaisesRegex(ValueError, "/kvpark setup"): service.ensure() spawn.assert_not_called() @@ -62,7 +62,7 @@ def test_backend_args_cannot_override_archive_topology(self): model.write_bytes(b"model") config = {**defaults(), "server": sys.executable, "model": str(model), "backend_args": ["--parallel", "8"]} service = Service(lambda: config) - with patch("sloth_memory.hermes_service.request", side_effect=URLError("offline")), patch.object(service, "_spawn") as spawn: + with patch("kvpark.hermes_service.request", side_effect=URLError("offline")), patch.object(service, "_spawn") as spawn: with self.assertRaises(ValueError): service.ensure() spawn.assert_not_called() diff --git a/tests/test_migration.py b/tests/test_migration.py new file mode 100644 index 0000000..51b5406 --- /dev/null +++ b/tests/test_migration.py @@ -0,0 +1,77 @@ +import copy +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from kvpark.migration import profile_plan + + +class MigrationTests(unittest.TestCase): + def profile(self): + return {"model": {"base_url": "http://127.0.0.1:8080/v1", "default": "local"}, + "agent": {"max_turns": 20}, "plugins": {"enabled": ["other", "sloth-memory"], + "disabled": ["kvpark", "unrelated"], "entries": {"sloth-memory": {"settings": { + "service": {"archive_dir": str(Path('/old/archive').resolve()), "connected": True, "autostart": True, + "previous_urls": ["http://127.0.0.1:9090"], "backend": "llama.cpp"}, + "route_backup": {"provider": "old"}, "route_applied": {"default": "local"}}}}}, + "platforms": {"telegram": {"extra": {"command_menu": {"priority": ["status", "sloth", "kvpark"]}}}}} + + def test_preserves_cache_identity_route_and_original_backup(self): + source = self.profile() + before = copy.deepcopy(source) + result = profile_plan(source) + self.assertEqual(source, before) + settings = result["plugins"]["entries"]["kvpark"]["settings"] + old = source["plugins"]["entries"]["sloth-memory"]["settings"] + for key in old: + self.assertEqual(settings[key], old[key]) + self.assertEqual(result["model"], source["model"]) + self.assertEqual(result["agent"], source["agent"]) + self.assertEqual(result["plugins"]["enabled"], ["other", "kvpark"]) + self.assertIn("sloth-memory", result["plugins"]["disabled"]) + self.assertTrue(result["plugins"]["entries"]["sloth-memory"]["settings"]["service"]["uninstalled"]) + self.assertEqual(result["platforms"]["telegram"]["extra"]["command_menu"]["priority"], ["status", "kvpark"]) + self.assertIsNone(profile_plan(result)) + + def test_legacy_config_shape_migrates_and_existing_new_settings_are_protected(self): + source = self.profile() + old = source["plugins"]["entries"]["sloth-memory"] + old["config"] = old.pop("settings") + self.assertEqual(profile_plan(source)["plugins"]["entries"]["kvpark"]["settings"]["route_backup"], {"provider": "old"}) + source["plugins"]["entries"]["kvpark"] = {"settings": {"service": {"model": "new"}}} + with self.assertRaisesRegex(ValueError, "refusing to overwrite"): + profile_plan(source) + + def test_external_service_cannot_be_migrated_by_another_owner(self): + source = self.profile() + source["plugins"]["entries"]["sloth-memory"]["settings"]["service"]["external"] = True + with self.assertRaisesRegex(ValueError, "externally managed"): + profile_plan(source) + + def test_mixed_legacy_config_and_new_settings_keep_exact_service(self): + source = self.profile() + old = source["plugins"]["entries"]["sloth-memory"] + service = old["settings"].pop("service") + old["config"] = {"service": service} + result = profile_plan(source) + settings = result["plugins"]["entries"]["kvpark"]["settings"] + self.assertEqual(settings["service"], service) + self.assertEqual(settings["route_backup"], old["settings"]["route_backup"]) + # A complete settings.service overrides, rather than deep-merges, config.service. + old["settings"]["service"] = {"archive_dir": str(Path('/another/archive').resolve())} + result = profile_plan(source) + settings = result["plugins"]["entries"]["kvpark"]["settings"] + self.assertEqual(settings["service"], old["settings"]["service"]) + + def test_legacy_environment_fallback_and_new_name_precedence(self): + env = {key: value for key, value in os.environ.items() if not key.startswith(("SLOTH_", "KVPARK_"))} + env.update(SLOTH_API_KEY="old-test-key", SLOTH_ARCHIVE_DIR="old-dir", KVPARK_API_KEY="new-test-key") + command = [sys.executable, "-c", "import kvpark, os; assert os.environ['KVPARK_API_KEY']=='new-test-key'; assert os.environ['KVPARK_ARCHIVE_DIR']=='old-dir'"] + subprocess.run(command, env=env, check=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_platforms.py b/tests/test_platforms.py index 477f722..2e1f406 100644 --- a/tests/test_platforms.py +++ b/tests/test_platforms.py @@ -8,17 +8,17 @@ import unittest from unittest.mock import patch -from sloth_memory.platforms import available_port, process_identity, process_matches -from sloth_memory.network import bind_server -from sloth_memory.proxy import Handler, atomic_json -from sloth_memory.runtime import lock_directory +from kvpark.platforms import available_port, process_identity, process_matches +from kvpark.network import bind_server +from kvpark.proxy import Handler, atomic_json +from kvpark.runtime import lock_directory class PlatformTests(unittest.TestCase): def test_lock_excludes_other_process_and_releases_after_close(self): with tempfile.TemporaryDirectory() as tmp: fd = lock_directory(Path(tmp), "lock") - command = [sys.executable, "-c", "from sloth_memory.runtime import lock_directory; from pathlib import Path; import sys; lock_directory(Path(sys.argv[1]), 'lock')", tmp] + command = [sys.executable, "-c", "from kvpark.runtime import lock_directory; from pathlib import Path; import sys; lock_directory(Path(sys.argv[1]), 'lock')", tmp] try: self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0) finally: @@ -59,7 +59,7 @@ def test_atomic_metadata_replacement(self): @unittest.skipUnless(os.name == "nt", "Windows process lifetime") def test_job_stops_child_when_launcher_releases_handle(self): - from sloth_memory.windows_job import Job + from kvpark.windows_job import Job process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) try: job = Job(process.pid) diff --git a/tests/test_removal.py b/tests/test_removal.py index e386637..536fd82 100644 --- a/tests/test_removal.py +++ b/tests/test_removal.py @@ -10,16 +10,16 @@ import psutil -from sloth_memory import removal -from sloth_memory.hermes_uninstall import restored_config -from sloth_memory.platforms import process_identity +from kvpark import removal +from kvpark.hermes_uninstall import restored_config +from kvpark.platforms import process_identity class RestoreTests(unittest.TestCase): def profile(self): applied = dict(provider="custom", default="gemma", base_url="http://127.0.0.1:8080/v1", api_mode="chat_completions") return dict(model={**applied, "context_length": 12345}, agent={"max_turns": 8}, plugins=dict( - enabled=["other", "sloth-memory"], entries={"sloth-memory": {"settings": { + enabled=["other", "kvpark"], entries={"kvpark": {"settings": { "service": {"connected": True}, "route_applied": applied, "route_backup": {"provider": "custom", "default": "gemma", "base_url": "http://127.0.0.1:11434/v1"}}}})) @@ -32,7 +32,7 @@ def test_restore_removes_added_fields_and_preserves_other_settings(self): self.assertEqual(result["model"]["context_length"], 12345) self.assertEqual(result["agent"], original["agent"]) self.assertEqual(result["plugins"]["enabled"], ["other"]) - self.assertIn("sloth-memory", result["plugins"]["disabled"]) + self.assertIn("kvpark", result["plugins"]["disabled"]) self.assertFalse(settings["autostart"]) self.assertTrue(settings["uninstalled"]) self.assertEqual(original["model"]["base_url"], "http://127.0.0.1:8080/v1") @@ -42,7 +42,7 @@ def test_restore_removes_added_fields_and_preserves_other_settings(self): def test_changed_route_is_preserved_and_missing_backup_fails_closed(self): profile = self.profile() - profile["plugins"]["entries"]["sloth-memory"]["settings"].pop("route_backup") + profile["plugins"]["entries"]["kvpark"]["settings"].pop("route_backup") with self.assertRaisesRegex(ValueError, "no original"): restored_config(profile) profile["model"]["base_url"] = "http://127.0.0.1:9999/v1" @@ -123,7 +123,7 @@ def cleanup(): def test_failed_drain_never_disconnects_or_stops_processes(self): record = dict(pid=123, base_url="http://127.0.0.1:8080") result = dict(proxy=record, backend=None) - status = dict(service="sloth-memory", control_version=4, archive_dir=str(self.archive)) + status = dict(service="kvpark", control_version=4, archive_dir=str(self.archive)) with patch.object(removal, "plan", return_value=result), \ patch.object(removal, "request", side_effect=[status, RuntimeError("busy")]), \ patch.object(removal, "stop_proxy") as stop, \ @@ -137,7 +137,7 @@ def test_failed_drain_never_disconnects_or_stops_processes(self): def test_config_failure_reopens_proxy_without_stopping_it(self): record = dict(pid=123, base_url="http://127.0.0.1:8080") - status = dict(service="sloth-memory", control_version=4, archive_dir=str(self.archive)) + status = dict(service="kvpark", control_version=4, archive_dir=str(self.archive)) def disconnect(): raise RuntimeError("configuration changed") with patch.object(removal, "plan", return_value=dict(proxy=record, backend=None)), \ diff --git a/tests/test_retention.py b/tests/test_retention.py index 86e291b..1c8db1c 100644 --- a/tests/test_retention.py +++ b/tests/test_retention.py @@ -6,7 +6,7 @@ import unittest from unittest.mock import patch -from sloth_memory import proxy +from kvpark import proxy class RetentionTests(unittest.TestCase): @@ -71,7 +71,7 @@ def test_crash_orphans_expire_but_unrelated_files_and_symlinks_are_kept(self): path.write_bytes(b"orphan") os.utime(path, (time.time()-8*86400,)*2) keep = self.root / "notes.bin" - keep.write_text("not a sloth snapshot") + keep.write_text("not a kvpark snapshot") os.utime(keep, (time.time()-20*86400,)*2) link = self.root / (proxy.key_for("link") + "." + "c" * 32 + ".bin") link.symlink_to(keep) diff --git a/tests/test_updates.py b/tests/test_updates.py index ce98521..851894c 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -8,11 +8,11 @@ import zipfile from unittest.mock import MagicMock, patch -from sloth_memory import releases, updates +from kvpark import releases, updates def release(version, **overrides): - name = f"sloth_memory-{version}-py3-none-any.whl" + name = f"kvpark-{version}-py3-none-any.whl" return dict(tag_name="v" + version, draft=False, assets=[dict(name=name, browser_download_url=f"{releases.REPOSITORY}/releases/download/v{version}/{name}", digest="sha256:" + "a" * 64)], **overrides) @@ -23,8 +23,8 @@ def test_incompatible_snapshot_format_requires_manual_upgrade(self): with tempfile.TemporaryDirectory() as tmp: wheel = Path(tmp) / "package.whl" with zipfile.ZipFile(wheel, "w") as out: - out.writestr("sloth_memory-0.2.0a2.dist-info/METADATA", "Name: sloth-memory\nVersion: 0.2.0a2\n") - out.writestr("sloth_memory/update_compat.json", json.dumps(dict(updater_protocol=1, snapshot_format=3, control_version=4))) + out.writestr("kvpark-0.2.0a2.dist-info/METADATA", "Name: kvpark\nVersion: 0.2.0a2\n") + out.writestr("kvpark/update_compat.json", json.dumps(dict(updater_protocol=1, snapshot_format=3, control_version=4))) with self.assertRaisesRegex(ValueError, "manual compatibility"): releases.validate_wheel(wheel, "0.2.0a2") @@ -90,13 +90,13 @@ def setUp(self): "request": self.request, "install": self.install, "stop_proxy": self.stop, "start_proxy": self.start, "subprocess.check_output": lambda *a, **kw: "0.2.0a2\n"}) for name, value in values.items(): - mocked = patch("sloth_memory.updates." + name, side_effect=value).start() + mocked = patch("kvpark.updates." + name, side_effect=value).start() self.addCleanup(patch.stopall) self.mocks[name] = mocked process = MagicMock() - process.cmdline.return_value = [sys.executable, "-m", "sloth_memory", "serve"] + process.cmdline.return_value = [sys.executable, "-m", "kvpark", "serve"] process.environ.return_value = {} - self.process = patch("sloth_memory.updates.psutil.Process", return_value=process).start() + self.process = patch("kvpark.updates.psutil.Process", return_value=process).start() def request(self, url, action, *args, **kwargs): self.events.append(action) From f3f2d1ca136614c8c90119fdf0b394afc493fa59 Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 03:20:15 -0600 Subject: [PATCH 2/2] Compare canonical archive paths in migration acceptance tests --- scripts/test_migration_release.py | 4 +++- tests/hermes/test_integration.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/test_migration_release.py b/scripts/test_migration_release.py index 7cdeb42..9a848ba 100644 --- a/scripts/test_migration_release.py +++ b/scripts/test_migration_release.py @@ -129,7 +129,9 @@ def main(): if wheel.is_dir(): wheel, = wheel.glob("kvpark-*-py3-none-any.whl") with tempfile.TemporaryDirectory(prefix="kvpark-migration-test-") as tmp: - root = Path(tmp) + # Match the canonical paths published by both proxies on macOS (/private) + # and Windows (expanded short directory names). + root = Path(tmp).resolve() old = legacy_wheel(root, args.legacy_wheel) venv.EnvBuilder(with_pip=True).create(root / "venv") python = root / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python") diff --git a/tests/hermes/test_integration.py b/tests/hermes/test_integration.py index af50f7a..0f02fe0 100644 --- a/tests/hermes/test_integration.py +++ b/tests/hermes/test_integration.py @@ -158,7 +158,7 @@ def test_legacy_profile_migration_keeps_model_route_and_archive(self): after = read_user_config_raw() self.assertEqual(after["model"], before["model"]) settings = after["plugins"]["entries"]["kvpark"]["settings"] - self.assertEqual(settings["service"]["archive_dir"], str(self.home / "legacy-archive")) + self.assertEqual(settings["service"]["archive_dir"], str((self.home / "legacy-archive").resolve())) self.assertEqual(settings["route_backup"], old["settings"]["route_backup"]) self.assertIn("already migrated", run(hermes=True, confirm=True)) backup, = self.home.glob("config.before-kvpark-*.json")